OSDN Git Service

Merge UnkoTim220
authorStarg <starg@users.osdn.me>
Wed, 19 Sep 2018 14:26:58 +0000 (23:26 +0900)
committerStarg <starg@users.osdn.me>
Wed, 19 Sep 2018 14:26:58 +0000 (23:26 +0900)
809 files changed:
CMakeLists.txt [new file with mode: 0644]
FLAC/AUTHORS [new file with mode: 0644]
FLAC/CMakeLists.txt [new file with mode: 0644]
FLAC/COPYING.FDL [new file with mode: 0644]
FLAC/COPYING.GPL [new file with mode: 0644]
FLAC/COPYING.LGPL [new file with mode: 0644]
FLAC/COPYING.Xiph [new file with mode: 0644]
FLAC/README [new file with mode: 0644]
FLAC/file_decoder.h [deleted file]
FLAC/file_encoder.h [deleted file]
FLAC/include/FLAC/all.h [moved from FLAC/all.h with 99% similarity]
FLAC/include/FLAC/assert.h [moved from FLAC/assert.h with 97% similarity]
FLAC/include/FLAC/callback.h [moved from FLAC/callback.h with 99% similarity]
FLAC/include/FLAC/export.h [moved from FLAC/export.h with 96% similarity]
FLAC/include/FLAC/format.h [moved from FLAC/format.h with 99% similarity]
FLAC/include/FLAC/metadata.h [moved from FLAC/metadata.h with 99% similarity]
FLAC/include/FLAC/ordinals.h [moved from FLAC/ordinals.h with 98% similarity]
FLAC/include/FLAC/stream_decoder.h [moved from FLAC/stream_decoder.h with 99% similarity]
FLAC/include/FLAC/stream_encoder.h [moved from FLAC/stream_encoder.h with 95% similarity]
FLAC/seekable_stream_decoder.h [deleted file]
FLAC/seekable_stream_encoder.h [deleted file]
FLAC/src/bitmath.c [new file with mode: 0644]
FLAC/src/bitreader.c [new file with mode: 0644]
FLAC/src/bitwriter.c [new file with mode: 0644]
FLAC/src/cpu.c [new file with mode: 0644]
FLAC/src/crc.c [new file with mode: 0644]
FLAC/src/fixed.c [new file with mode: 0644]
FLAC/src/fixed_intrin_sse2.c [new file with mode: 0644]
FLAC/src/fixed_intrin_ssse3.c [new file with mode: 0644]
FLAC/src/float.c [new file with mode: 0644]
FLAC/src/format.c [new file with mode: 0644]
FLAC/src/lpc.c [new file with mode: 0644]
FLAC/src/lpc_intrin_avx2.c [new file with mode: 0644]
FLAC/src/lpc_intrin_sse.c [new file with mode: 0644]
FLAC/src/lpc_intrin_sse2.c [new file with mode: 0644]
FLAC/src/lpc_intrin_sse41.c [new file with mode: 0644]
FLAC/src/md5.c [new file with mode: 0644]
FLAC/src/memory.c [new file with mode: 0644]
FLAC/src/metadata_iterators.c [new file with mode: 0644]
FLAC/src/metadata_object.c [new file with mode: 0644]
FLAC/src/ogg_decoder_aspect.c [new file with mode: 0644]
FLAC/src/ogg_encoder_aspect.c [new file with mode: 0644]
FLAC/src/ogg_helper.c [new file with mode: 0644]
FLAC/src/ogg_mapping.c [new file with mode: 0644]
FLAC/src/private/all.h [new file with mode: 0644]
FLAC/src/private/bitmath.h [new file with mode: 0644]
FLAC/src/private/bitreader.h [new file with mode: 0644]
FLAC/src/private/bitwriter.h [new file with mode: 0644]
FLAC/src/private/cpu.h [new file with mode: 0644]
FLAC/src/private/crc.h [new file with mode: 0644]
FLAC/src/private/fixed.h [new file with mode: 0644]
FLAC/src/private/float.h [new file with mode: 0644]
FLAC/src/private/format.h [new file with mode: 0644]
FLAC/src/private/lpc.h [new file with mode: 0644]
FLAC/src/private/macros.h [new file with mode: 0644]
FLAC/src/private/md5.h [new file with mode: 0644]
FLAC/src/private/memory.h [new file with mode: 0644]
FLAC/src/private/metadata.h [new file with mode: 0644]
FLAC/src/private/ogg_decoder_aspect.h [new file with mode: 0644]
FLAC/src/private/ogg_encoder_aspect.h [new file with mode: 0644]
FLAC/src/private/ogg_helper.h [new file with mode: 0644]
FLAC/src/private/ogg_mapping.h [new file with mode: 0644]
FLAC/src/private/stream_encoder.h [new file with mode: 0644]
FLAC/src/private/stream_encoder_framing.h [new file with mode: 0644]
FLAC/src/private/window.h [new file with mode: 0644]
FLAC/src/protected/all.h [new file with mode: 0644]
FLAC/src/protected/stream_decoder.h [new file with mode: 0644]
FLAC/src/protected/stream_encoder.h [new file with mode: 0644]
FLAC/src/share/alloc.h [new file with mode: 0644]
FLAC/src/share/compat.h [new file with mode: 0644]
FLAC/src/share/endswap.h [new file with mode: 0644]
FLAC/src/share/getopt.h [new file with mode: 0644]
FLAC/src/share/grabbag.h [new file with mode: 0644]
FLAC/src/share/macros.h [new file with mode: 0644]
FLAC/src/share/private.h [new file with mode: 0644]
FLAC/src/share/replaygain_analysis.h [new file with mode: 0644]
FLAC/src/share/replaygain_synthesis.h [new file with mode: 0644]
FLAC/src/share/safe_str.h [new file with mode: 0644]
FLAC/src/share/utf8.h [new file with mode: 0644]
FLAC/src/share/win_utf8_io.h [new file with mode: 0644]
FLAC/src/share/windows_unicode_filenames.h [new file with mode: 0644]
FLAC/src/stream_decoder.c [new file with mode: 0644]
FLAC/src/stream_encoder.c [new file with mode: 0644]
FLAC/src/stream_encoder_framing.c [new file with mode: 0644]
FLAC/src/stream_encoder_intrin_avx2.c [new file with mode: 0644]
FLAC/src/stream_encoder_intrin_sse2.c [new file with mode: 0644]
FLAC/src/stream_encoder_intrin_ssse3.c [new file with mode: 0644]
FLAC/src/window.c [new file with mode: 0644]
FLAC/src/windows_unicode_filenames.c [new file with mode: 0644]
NEWS
WriteVersion.cmake [new file with mode: 0644]
calcnewton/calcnewton.vcproj [deleted file]
calcnewton/calcnewton.vcxproj [deleted file]
calcnewton/calcnewton.vcxproj.filters [deleted file]
calcnewton/calcnewton.vcxproj.user [deleted file]
cfgforsf/CMakeLists.txt
cfgforsf/cfgforsf.dsp [deleted file]
cfgforsf/cfgforsf.vcproj [deleted file]
cfgforsf/cfgforsf.vcxproj [deleted file]
cfgforsf/cfgforsf.vcxproj.filters [deleted file]
cfgforsf/cfgforsf.vcxproj.user [deleted file]
config.h [deleted file]
configure.in
dll/libFLAC.dll [deleted file]
dll/libOggFLAC.dll [deleted file]
dll/ogg.dll [deleted file]
dll/pdcurses.dll [deleted file]
gpl-2.0.txt [new file with mode: 0644]
interface.h [deleted file]
interface/CMakeLists.txt
interface/alsaseq_c.c
interface/interface.dsp [deleted file]
interface/interface.vcproj [deleted file]
interface/interface.vcxproj [deleted file]
interface/interface.vcxproj.filters [deleted file]
interface/interface.vcxproj.user [deleted file]
interface/ncurs_c.c
interface/rtsyn.h
interface/rtsyn_common.c
interface/rtsyn_npipe.c
interface/rtsyn_portmidi.c
interface/rtsyn_winmm.c
interface/version.h [deleted file]
interface/w32g_c.c
interface/w32g_i.c
interface/w32g_ini.c
interface/w32g_pref.c
interface/w32g_res.h
interface/w32g_res.rc
interface/w32g_subwin.c
interface/w32g_syn.c [changed mode: 0755->0644]
interface/w32g_utl.c
interface/w32g_visualstyle.manifest [deleted file]
interface/xaw_i.c
kbtim/kbtim_setting.cpp
lame/CMakeLists.txt [new file with mode: 0644]
lame/COPYING [new file with mode: 0644]
lame/Dll/BladeMP3EncDLL.c [new file with mode: 0644]
lame/Dll/BladeMP3EncDLL.def [new file with mode: 0644]
lame/Dll/BladeMP3EncDLL.h [moved from timidity/BladeMP3EncDLL.h with 100% similarity]
lame/Dll/README [new file with mode: 0644]
lame/LICENSE [new file with mode: 0644]
lame/README [new file with mode: 0644]
lame/config.h [new file with mode: 0644]
lame/include/lame.def [new file with mode: 0644]
lame/include/lame.h [new file with mode: 0644]
lame/libmp3lame/VbrTag.c [new file with mode: 0644]
lame/libmp3lame/VbrTag.h [new file with mode: 0644]
lame/libmp3lame/bitstream.c [new file with mode: 0644]
lame/libmp3lame/bitstream.h [new file with mode: 0644]
lame/libmp3lame/encoder.c [new file with mode: 0644]
lame/libmp3lame/encoder.h [new file with mode: 0644]
lame/libmp3lame/fft.c [new file with mode: 0644]
lame/libmp3lame/fft.h [new file with mode: 0644]
lame/libmp3lame/gain_analysis.c [new file with mode: 0644]
lame/libmp3lame/gain_analysis.h [new file with mode: 0644]
lame/libmp3lame/i386/choose_table.nas [new file with mode: 0644]
lame/libmp3lame/i386/cpu_feat.nas [new file with mode: 0644]
lame/libmp3lame/i386/fft.nas [new file with mode: 0644]
lame/libmp3lame/i386/fft3dn.nas [new file with mode: 0644]
lame/libmp3lame/i386/fftfpu.nas [new file with mode: 0644]
lame/libmp3lame/i386/fftsse.nas [new file with mode: 0644]
lame/libmp3lame/i386/ffttbl.nas [new file with mode: 0644]
lame/libmp3lame/i386/nasm.h [new file with mode: 0644]
lame/libmp3lame/i386/scalar.nas [new file with mode: 0644]
lame/libmp3lame/id3tag.c [new file with mode: 0644]
lame/libmp3lame/id3tag.h [new file with mode: 0644]
lame/libmp3lame/l3side.h [new file with mode: 0644]
lame/libmp3lame/lame-analysis.h [new file with mode: 0644]
lame/libmp3lame/lame.c [new file with mode: 0644]
lame/libmp3lame/lame.rc [new file with mode: 0644]
lame/libmp3lame/lame_global_flags.h [new file with mode: 0644]
lame/libmp3lame/lameerror.h [new file with mode: 0644]
lame/libmp3lame/logoe.ico [new file with mode: 0644]
lame/libmp3lame/machine.h [new file with mode: 0644]
lame/libmp3lame/mpglib_interface.c [new file with mode: 0644]
lame/libmp3lame/newmdct.c [new file with mode: 0644]
lame/libmp3lame/newmdct.h [new file with mode: 0644]
lame/libmp3lame/presets.c [new file with mode: 0644]
lame/libmp3lame/psymodel.c [new file with mode: 0644]
lame/libmp3lame/psymodel.h [new file with mode: 0644]
lame/libmp3lame/quantize.c [new file with mode: 0644]
lame/libmp3lame/quantize.h [new file with mode: 0644]
lame/libmp3lame/quantize_pvt.c [new file with mode: 0644]
lame/libmp3lame/quantize_pvt.h [new file with mode: 0644]
lame/libmp3lame/reservoir.c [new file with mode: 0644]
lame/libmp3lame/reservoir.h [new file with mode: 0644]
lame/libmp3lame/set_get.c [new file with mode: 0644]
lame/libmp3lame/set_get.h [new file with mode: 0644]
lame/libmp3lame/tables.c [new file with mode: 0644]
lame/libmp3lame/tables.h [new file with mode: 0644]
lame/libmp3lame/takehiro.c [new file with mode: 0644]
lame/libmp3lame/util.c [new file with mode: 0644]
lame/libmp3lame/util.h [new file with mode: 0644]
lame/libmp3lame/vbrquantize.c [new file with mode: 0644]
lame/libmp3lame/vbrquantize.h [new file with mode: 0644]
lame/libmp3lame/vector/lame_intrin.h [new file with mode: 0644]
lame/libmp3lame/vector/xmm_quantize_sub.c [new file with mode: 0644]
lame/libmp3lame/version.c [new file with mode: 0644]
lame/libmp3lame/version.h [new file with mode: 0644]
lgpl-2.0.txt [new file with mode: 0644]
lgpl-2.1.txt [new file with mode: 0644]
libarc/libarc.cbp [deleted file]
libarc/libarc.dsp [deleted file]
libarc/libarc.vcproj [deleted file]
libarc/libarc.vcxproj [deleted file]
libarc/libarc.vcxproj.filters [deleted file]
libarc/libarc.vcxproj.user [deleted file]
libmpg123/libmpg123.vcproj [deleted file]
libmpg123/libmpg123.vcxproj [deleted file]
libunimod/libunimod.dsp [deleted file]
libunimod/libunimod.vcproj [deleted file]
libunimod/libunimod.vcxproj [deleted file]
libunimod/libunimod.vcxproj.filters [deleted file]
libunimod/libunimod.vcxproj.user [deleted file]
nouse/nouse.dsp [deleted file]
nouse/nouse.vcproj [deleted file]
nouse/nouse.vcxproj [deleted file]
nouse/nouse.vcxproj.user [deleted file]
ogg/AUTHORS [new file with mode: 0644]
ogg/CMakeLists.txt [new file with mode: 0644]
ogg/COPYING [new file with mode: 0644]
ogg/README.md [new file with mode: 0644]
ogg/include/ogg/ogg.h [moved from ogg/ogg.h with 79% similarity]
ogg/include/ogg/os_types.h [new file with mode: 0644]
ogg/os_types.h [deleted file]
ogg/src/bitwise.c [new file with mode: 0644]
ogg/src/framing.c [new file with mode: 0644]
ogg/win32/ogg.def [new file with mode: 0644]
opus/AUTHORS [new file with mode: 0644]
opus/CMakeLists.txt [new file with mode: 0644]
opus/COPYING [new file with mode: 0644]
opus/README [new file with mode: 0644]
opus/celt/_kiss_fft_guts.h [new file with mode: 0644]
opus/celt/arch.h [new file with mode: 0644]
opus/celt/arm/arm2gnu.pl [new file with mode: 0644]
opus/celt/arm/arm_celt_map.c [new file with mode: 0644]
opus/celt/arm/armcpu.c [new file with mode: 0644]
opus/celt/arm/armcpu.h [new file with mode: 0644]
opus/celt/arm/armopts.s.in [new file with mode: 0644]
opus/celt/arm/celt_ne10_fft.c [new file with mode: 0644]
opus/celt/arm/celt_ne10_mdct.c [new file with mode: 0644]
opus/celt/arm/celt_neon_intr.c [new file with mode: 0644]
opus/celt/arm/celt_pitch_xcorr_arm-gnu.S [new file with mode: 0644]
opus/celt/arm/celt_pitch_xcorr_arm.s [new file with mode: 0644]
opus/celt/arm/fft_arm.h [new file with mode: 0644]
opus/celt/arm/fixed_arm64.h [new file with mode: 0644]
opus/celt/arm/fixed_armv4.h [new file with mode: 0644]
opus/celt/arm/fixed_armv5e.h [new file with mode: 0644]
opus/celt/arm/kiss_fft_armv4.h [new file with mode: 0644]
opus/celt/arm/kiss_fft_armv5e.h [new file with mode: 0644]
opus/celt/arm/mdct_arm.h [new file with mode: 0644]
opus/celt/arm/pitch_arm.h [new file with mode: 0644]
opus/celt/arm/pitch_neon_intr.c [new file with mode: 0644]
opus/celt/bands.c [new file with mode: 0644]
opus/celt/bands.h [new file with mode: 0644]
opus/celt/celt.c [new file with mode: 0644]
opus/celt/celt.h [new file with mode: 0644]
opus/celt/celt_decoder.c [new file with mode: 0644]
opus/celt/celt_encoder.c [new file with mode: 0644]
opus/celt/celt_lpc.c [new file with mode: 0644]
opus/celt/celt_lpc.h [new file with mode: 0644]
opus/celt/cpu_support.h [new file with mode: 0644]
opus/celt/cwrs.c [new file with mode: 0644]
opus/celt/cwrs.h [new file with mode: 0644]
opus/celt/ecintrin.h [new file with mode: 0644]
opus/celt/entcode.c [new file with mode: 0644]
opus/celt/entcode.h [new file with mode: 0644]
opus/celt/entdec.c [new file with mode: 0644]
opus/celt/entdec.h [new file with mode: 0644]
opus/celt/entenc.c [new file with mode: 0644]
opus/celt/entenc.h [new file with mode: 0644]
opus/celt/fixed_debug.h [new file with mode: 0644]
opus/celt/fixed_generic.h [new file with mode: 0644]
opus/celt/float_cast.h [new file with mode: 0644]
opus/celt/kiss_fft.c [new file with mode: 0644]
opus/celt/kiss_fft.h [new file with mode: 0644]
opus/celt/laplace.c [new file with mode: 0644]
opus/celt/laplace.h [new file with mode: 0644]
opus/celt/mathops.c [new file with mode: 0644]
opus/celt/mathops.h [new file with mode: 0644]
opus/celt/mdct.c [new file with mode: 0644]
opus/celt/mdct.h [new file with mode: 0644]
opus/celt/mfrngcod.h [new file with mode: 0644]
opus/celt/mips/celt_mipsr1.h [new file with mode: 0644]
opus/celt/mips/fixed_generic_mipsr1.h [new file with mode: 0644]
opus/celt/mips/kiss_fft_mipsr1.h [new file with mode: 0644]
opus/celt/mips/mdct_mipsr1.h [new file with mode: 0644]
opus/celt/mips/pitch_mipsr1.h [new file with mode: 0644]
opus/celt/mips/vq_mipsr1.h [new file with mode: 0644]
opus/celt/modes.c [new file with mode: 0644]
opus/celt/modes.h [new file with mode: 0644]
opus/celt/opus_custom_demo.c [new file with mode: 0644]
opus/celt/os_support.h [new file with mode: 0644]
opus/celt/pitch.c [new file with mode: 0644]
opus/celt/pitch.h [new file with mode: 0644]
opus/celt/quant_bands.c [new file with mode: 0644]
opus/celt/quant_bands.h [new file with mode: 0644]
opus/celt/rate.c [new file with mode: 0644]
opus/celt/rate.h [new file with mode: 0644]
opus/celt/stack_alloc.h [new file with mode: 0644]
opus/celt/static_modes_fixed.h [new file with mode: 0644]
opus/celt/static_modes_fixed_arm_ne10.h [new file with mode: 0644]
opus/celt/static_modes_float.h [new file with mode: 0644]
opus/celt/static_modes_float_arm_ne10.h [new file with mode: 0644]
opus/celt/tests/test_unit_cwrs32.c [new file with mode: 0644]
opus/celt/tests/test_unit_dft.c [new file with mode: 0644]
opus/celt/tests/test_unit_entropy.c [new file with mode: 0644]
opus/celt/tests/test_unit_laplace.c [new file with mode: 0644]
opus/celt/tests/test_unit_mathops.c [new file with mode: 0644]
opus/celt/tests/test_unit_mdct.c [new file with mode: 0644]
opus/celt/tests/test_unit_rotation.c [new file with mode: 0644]
opus/celt/tests/test_unit_types.c [new file with mode: 0644]
opus/celt/vq.c [new file with mode: 0644]
opus/celt/vq.h [new file with mode: 0644]
opus/celt/x86/celt_lpc_sse.c [new file with mode: 0644]
opus/celt/x86/celt_lpc_sse.h [new file with mode: 0644]
opus/celt/x86/pitch_sse.c [new file with mode: 0644]
opus/celt/x86/pitch_sse.h [new file with mode: 0644]
opus/celt/x86/pitch_sse2.c [new file with mode: 0644]
opus/celt/x86/pitch_sse4_1.c [new file with mode: 0644]
opus/celt/x86/vq_sse.h [new file with mode: 0644]
opus/celt/x86/vq_sse2.c [new file with mode: 0644]
opus/celt/x86/x86_celt_map.c [new file with mode: 0644]
opus/celt/x86/x86cpu.c [new file with mode: 0644]
opus/celt/x86/x86cpu.h [new file with mode: 0644]
opus/include/opus/opus.h [moved from opus/opus.h with 99% similarity]
opus/include/opus/opus_custom.h [moved from opus/opus_custom.h with 100% similarity]
opus/include/opus/opus_defines.h [moved from opus/opus_defines.h with 89% similarity]
opus/include/opus/opus_multistream.h [moved from opus/opus_multistream.h with 98% similarity]
opus/include/opus/opus_types.h [moved from opus/opus_types.h with 96% similarity]
opus/silk/A2NLSF.c [new file with mode: 0644]
opus/silk/API.h [new file with mode: 0644]
opus/silk/CNG.c [new file with mode: 0644]
opus/silk/HP_variable_cutoff.c [new file with mode: 0644]
opus/silk/Inlines.h [new file with mode: 0644]
opus/silk/LPC_analysis_filter.c [new file with mode: 0644]
opus/silk/LPC_fit.c [new file with mode: 0644]
opus/silk/LPC_inv_pred_gain.c [new file with mode: 0644]
opus/silk/LP_variable_cutoff.c [new file with mode: 0644]
opus/silk/MacroCount.h [new file with mode: 0644]
opus/silk/MacroDebug.h [new file with mode: 0644]
opus/silk/NLSF2A.c [new file with mode: 0644]
opus/silk/NLSF_VQ.c [new file with mode: 0644]
opus/silk/NLSF_VQ_weights_laroia.c [new file with mode: 0644]
opus/silk/NLSF_decode.c [new file with mode: 0644]
opus/silk/NLSF_del_dec_quant.c [new file with mode: 0644]
opus/silk/NLSF_encode.c [new file with mode: 0644]
opus/silk/NLSF_stabilize.c [new file with mode: 0644]
opus/silk/NLSF_unpack.c [new file with mode: 0644]
opus/silk/NSQ.c [new file with mode: 0644]
opus/silk/NSQ.h [new file with mode: 0644]
opus/silk/NSQ_del_dec.c [new file with mode: 0644]
opus/silk/PLC.c [new file with mode: 0644]
opus/silk/PLC.h [new file with mode: 0644]
opus/silk/SigProc_FIX.h [new file with mode: 0644]
opus/silk/VAD.c [new file with mode: 0644]
opus/silk/VQ_WMat_EC.c [new file with mode: 0644]
opus/silk/ana_filt_bank_1.c [new file with mode: 0644]
opus/silk/arm/LPC_inv_pred_gain_arm.h [new file with mode: 0644]
opus/silk/arm/LPC_inv_pred_gain_neon_intr.c [new file with mode: 0644]
opus/silk/arm/NSQ_del_dec_arm.h [new file with mode: 0644]
opus/silk/arm/NSQ_del_dec_neon_intr.c [new file with mode: 0644]
opus/silk/arm/NSQ_neon.c [new file with mode: 0644]
opus/silk/arm/NSQ_neon.h [new file with mode: 0644]
opus/silk/arm/SigProc_FIX_armv4.h [new file with mode: 0644]
opus/silk/arm/SigProc_FIX_armv5e.h [new file with mode: 0644]
opus/silk/arm/arm_silk_map.c [new file with mode: 0644]
opus/silk/arm/biquad_alt_arm.h [new file with mode: 0644]
opus/silk/arm/biquad_alt_neon_intr.c [new file with mode: 0644]
opus/silk/arm/macros_arm64.h [new file with mode: 0644]
opus/silk/arm/macros_armv4.h [new file with mode: 0644]
opus/silk/arm/macros_armv5e.h [new file with mode: 0644]
opus/silk/biquad_alt.c [new file with mode: 0644]
opus/silk/bwexpander.c [new file with mode: 0644]
opus/silk/bwexpander_32.c [new file with mode: 0644]
opus/silk/check_control_input.c [new file with mode: 0644]
opus/silk/code_signs.c [new file with mode: 0644]
opus/silk/control.h [new file with mode: 0644]
opus/silk/control_SNR.c [new file with mode: 0644]
opus/silk/control_audio_bandwidth.c [new file with mode: 0644]
opus/silk/control_codec.c [new file with mode: 0644]
opus/silk/debug.c [new file with mode: 0644]
opus/silk/debug.h [new file with mode: 0644]
opus/silk/dec_API.c [new file with mode: 0644]
opus/silk/decode_core.c [new file with mode: 0644]
opus/silk/decode_frame.c [new file with mode: 0644]
opus/silk/decode_indices.c [new file with mode: 0644]
opus/silk/decode_parameters.c [new file with mode: 0644]
opus/silk/decode_pitch.c [new file with mode: 0644]
opus/silk/decode_pulses.c [new file with mode: 0644]
opus/silk/decoder_set_fs.c [new file with mode: 0644]
opus/silk/define.h [new file with mode: 0644]
opus/silk/enc_API.c [new file with mode: 0644]
opus/silk/encode_indices.c [new file with mode: 0644]
opus/silk/encode_pulses.c [new file with mode: 0644]
opus/silk/errors.h [new file with mode: 0644]
opus/silk/fixed/LTP_analysis_filter_FIX.c [new file with mode: 0644]
opus/silk/fixed/LTP_scale_ctrl_FIX.c [new file with mode: 0644]
opus/silk/fixed/apply_sine_window_FIX.c [new file with mode: 0644]
opus/silk/fixed/arm/warped_autocorrelation_FIX_arm.h [new file with mode: 0644]
opus/silk/fixed/arm/warped_autocorrelation_FIX_neon_intr.c [new file with mode: 0644]
opus/silk/fixed/autocorr_FIX.c [new file with mode: 0644]
opus/silk/fixed/burg_modified_FIX.c [new file with mode: 0644]
opus/silk/fixed/corrMatrix_FIX.c [new file with mode: 0644]
opus/silk/fixed/encode_frame_FIX.c [new file with mode: 0644]
opus/silk/fixed/find_LPC_FIX.c [new file with mode: 0644]
opus/silk/fixed/find_LTP_FIX.c [new file with mode: 0644]
opus/silk/fixed/find_pitch_lags_FIX.c [new file with mode: 0644]
opus/silk/fixed/find_pred_coefs_FIX.c [new file with mode: 0644]
opus/silk/fixed/k2a_FIX.c [new file with mode: 0644]
opus/silk/fixed/k2a_Q16_FIX.c [new file with mode: 0644]
opus/silk/fixed/main_FIX.h [new file with mode: 0644]
opus/silk/fixed/mips/noise_shape_analysis_FIX_mipsr1.h [new file with mode: 0644]
opus/silk/fixed/mips/warped_autocorrelation_FIX_mipsr1.h [new file with mode: 0644]
opus/silk/fixed/noise_shape_analysis_FIX.c [new file with mode: 0644]
opus/silk/fixed/pitch_analysis_core_FIX.c [new file with mode: 0644]
opus/silk/fixed/process_gains_FIX.c [new file with mode: 0644]
opus/silk/fixed/regularize_correlations_FIX.c [new file with mode: 0644]
opus/silk/fixed/residual_energy16_FIX.c [new file with mode: 0644]
opus/silk/fixed/residual_energy_FIX.c [new file with mode: 0644]
opus/silk/fixed/schur64_FIX.c [new file with mode: 0644]
opus/silk/fixed/schur_FIX.c [new file with mode: 0644]
opus/silk/fixed/structs_FIX.h [new file with mode: 0644]
opus/silk/fixed/vector_ops_FIX.c [new file with mode: 0644]
opus/silk/fixed/warped_autocorrelation_FIX.c [new file with mode: 0644]
opus/silk/fixed/x86/burg_modified_FIX_sse.c [new file with mode: 0644]
opus/silk/fixed/x86/vector_ops_FIX_sse.c [new file with mode: 0644]
opus/silk/float/LPC_analysis_filter_FLP.c [new file with mode: 0644]
opus/silk/float/LPC_inv_pred_gain_FLP.c [new file with mode: 0644]
opus/silk/float/LTP_analysis_filter_FLP.c [new file with mode: 0644]
opus/silk/float/LTP_scale_ctrl_FLP.c [new file with mode: 0644]
opus/silk/float/SigProc_FLP.h [new file with mode: 0644]
opus/silk/float/apply_sine_window_FLP.c [new file with mode: 0644]
opus/silk/float/autocorrelation_FLP.c [new file with mode: 0644]
opus/silk/float/burg_modified_FLP.c [new file with mode: 0644]
opus/silk/float/bwexpander_FLP.c [new file with mode: 0644]
opus/silk/float/corrMatrix_FLP.c [new file with mode: 0644]
opus/silk/float/encode_frame_FLP.c [new file with mode: 0644]
opus/silk/float/energy_FLP.c [new file with mode: 0644]
opus/silk/float/find_LPC_FLP.c [new file with mode: 0644]
opus/silk/float/find_LTP_FLP.c [new file with mode: 0644]
opus/silk/float/find_pitch_lags_FLP.c [new file with mode: 0644]
opus/silk/float/find_pred_coefs_FLP.c [new file with mode: 0644]
opus/silk/float/inner_product_FLP.c [new file with mode: 0644]
opus/silk/float/k2a_FLP.c [new file with mode: 0644]
opus/silk/float/main_FLP.h [new file with mode: 0644]
opus/silk/float/noise_shape_analysis_FLP.c [new file with mode: 0644]
opus/silk/float/pitch_analysis_core_FLP.c [new file with mode: 0644]
opus/silk/float/process_gains_FLP.c [new file with mode: 0644]
opus/silk/float/regularize_correlations_FLP.c [new file with mode: 0644]
opus/silk/float/residual_energy_FLP.c [new file with mode: 0644]
opus/silk/float/scale_copy_vector_FLP.c [new file with mode: 0644]
opus/silk/float/scale_vector_FLP.c [new file with mode: 0644]
opus/silk/float/schur_FLP.c [new file with mode: 0644]
opus/silk/float/sort_FLP.c [new file with mode: 0644]
opus/silk/float/structs_FLP.h [new file with mode: 0644]
opus/silk/float/warped_autocorrelation_FLP.c [new file with mode: 0644]
opus/silk/float/wrappers_FLP.c [new file with mode: 0644]
opus/silk/gain_quant.c [new file with mode: 0644]
opus/silk/init_decoder.c [new file with mode: 0644]
opus/silk/init_encoder.c [new file with mode: 0644]
opus/silk/inner_prod_aligned.c [new file with mode: 0644]
opus/silk/interpolate.c [new file with mode: 0644]
opus/silk/lin2log.c [new file with mode: 0644]
opus/silk/log2lin.c [new file with mode: 0644]
opus/silk/macros.h [new file with mode: 0644]
opus/silk/main.h [new file with mode: 0644]
opus/silk/mips/NSQ_del_dec_mipsr1.h [new file with mode: 0644]
opus/silk/mips/macros_mipsr1.h [new file with mode: 0644]
opus/silk/mips/sigproc_fix_mipsr1.h [new file with mode: 0644]
opus/silk/pitch_est_defines.h [new file with mode: 0644]
opus/silk/pitch_est_tables.c [new file with mode: 0644]
opus/silk/process_NLSFs.c [new file with mode: 0644]
opus/silk/quant_LTP_gains.c [new file with mode: 0644]
opus/silk/resampler.c [new file with mode: 0644]
opus/silk/resampler_down2.c [new file with mode: 0644]
opus/silk/resampler_down2_3.c [new file with mode: 0644]
opus/silk/resampler_private.h [new file with mode: 0644]
opus/silk/resampler_private_AR2.c [new file with mode: 0644]
opus/silk/resampler_private_IIR_FIR.c [new file with mode: 0644]
opus/silk/resampler_private_down_FIR.c [new file with mode: 0644]
opus/silk/resampler_private_up2_HQ.c [new file with mode: 0644]
opus/silk/resampler_rom.c [new file with mode: 0644]
opus/silk/resampler_rom.h [new file with mode: 0644]
opus/silk/resampler_structs.h [new file with mode: 0644]
opus/silk/shell_coder.c [new file with mode: 0644]
opus/silk/sigm_Q15.c [new file with mode: 0644]
opus/silk/sort.c [new file with mode: 0644]
opus/silk/stereo_LR_to_MS.c [new file with mode: 0644]
opus/silk/stereo_MS_to_LR.c [new file with mode: 0644]
opus/silk/stereo_decode_pred.c [new file with mode: 0644]
opus/silk/stereo_encode_pred.c [new file with mode: 0644]
opus/silk/stereo_find_predictor.c [new file with mode: 0644]
opus/silk/stereo_quant_pred.c [new file with mode: 0644]
opus/silk/structs.h [new file with mode: 0644]
opus/silk/sum_sqr_shift.c [new file with mode: 0644]
opus/silk/table_LSF_cos.c [new file with mode: 0644]
opus/silk/tables.h [new file with mode: 0644]
opus/silk/tables_LTP.c [new file with mode: 0644]
opus/silk/tables_NLSF_CB_NB_MB.c [new file with mode: 0644]
opus/silk/tables_NLSF_CB_WB.c [new file with mode: 0644]
opus/silk/tables_gain.c [new file with mode: 0644]
opus/silk/tables_other.c [new file with mode: 0644]
opus/silk/tables_pitch_lag.c [new file with mode: 0644]
opus/silk/tables_pulses_per_block.c [new file with mode: 0644]
opus/silk/tests/test_unit_LPC_inv_pred_gain.c [new file with mode: 0644]
opus/silk/tuning_parameters.h [new file with mode: 0644]
opus/silk/typedef.h [new file with mode: 0644]
opus/silk/x86/NSQ_del_dec_sse.c [new file with mode: 0644]
opus/silk/x86/NSQ_sse.c [new file with mode: 0644]
opus/silk/x86/SigProc_FIX_sse.h [new file with mode: 0644]
opus/silk/x86/VAD_sse.c [new file with mode: 0644]
opus/silk/x86/VQ_WMat_EC_sse.c [new file with mode: 0644]
opus/silk/x86/main_sse.h [new file with mode: 0644]
opus/silk/x86/x86_silk_map.c [new file with mode: 0644]
opus/src/analysis.c [new file with mode: 0644]
opus/src/analysis.h [new file with mode: 0644]
opus/src/mlp.c [new file with mode: 0644]
opus/src/mlp.h [new file with mode: 0644]
opus/src/mlp_data.c [new file with mode: 0644]
opus/src/opus.c [new file with mode: 0644]
opus/src/opus_compare.c [new file with mode: 0644]
opus/src/opus_decoder.c [new file with mode: 0644]
opus/src/opus_demo.c [new file with mode: 0644]
opus/src/opus_encoder.c [new file with mode: 0644]
opus/src/opus_multistream.c [new file with mode: 0644]
opus/src/opus_multistream_decoder.c [new file with mode: 0644]
opus/src/opus_multistream_encoder.c [new file with mode: 0644]
opus/src/opus_private.h [new file with mode: 0644]
opus/src/repacketizer.c [new file with mode: 0644]
opus/src/tansig_table.h [new file with mode: 0644]
pdcurses/pdcurses.def [new file with mode: 0644]
pdcurses/pdcurses.vcproj [deleted file]
pdcurses/pdcurses.vcxproj [deleted file]
pdcurses/pdcurses.vcxproj.filters [deleted file]
pdcurses/pdcurses.vcxproj.user [deleted file]
pdcurses/win32/pdcurses.ico [new file with mode: 0644]
pdcurses/win32/pdcurses.rc [new file with mode: 0644]
portaudio/CMakeLists.txt [new file with mode: 0644]
portaudio/LICENSE.txt [new file with mode: 0644]
portaudio/README.txt [new file with mode: 0644]
portaudio/include/pa_asio.h [moved from portaudio/pa_common/pa_asio.h with 100% similarity]
portaudio/include/pa_jack.h [moved from portaudio/pa_common/pa_jack.h with 100% similarity]
portaudio/include/pa_linux_alsa.h [moved from portaudio/pa_common/pa_linux_alsa.h with 100% similarity]
portaudio/include/pa_mac_core.h [moved from portaudio/pa_common/pa_mac_core.h with 100% similarity]
portaudio/include/pa_win_ds.h [moved from portaudio/pa_common/pa_win_ds.h with 100% similarity]
portaudio/include/pa_win_wasapi.h [moved from portaudio/pa_common/pa_win_wasapi.h with 100% similarity]
portaudio/include/pa_win_waveformat.h [moved from portaudio/pa_common/pa_win_waveformat.h with 100% similarity]
portaudio/include/pa_win_wdmks.h [moved from portaudio/pa_common/pa_win_wdmks.h with 100% similarity]
portaudio/include/pa_win_wmme.h [moved from portaudio/pa_common/pa_win_wmme.h with 100% similarity]
portaudio/include/portaudio.h [moved from portaudio/pa_common/portaudio.h with 100% similarity]
portaudio/portaudio.def [new file with mode: 0644]
portaudio/src/common/pa_allocation.c [new file with mode: 0644]
portaudio/src/common/pa_allocation.h [new file with mode: 0644]
portaudio/src/common/pa_converters.c [new file with mode: 0644]
portaudio/src/common/pa_converters.h [new file with mode: 0644]
portaudio/src/common/pa_cpuload.c [new file with mode: 0644]
portaudio/src/common/pa_cpuload.h [new file with mode: 0644]
portaudio/src/common/pa_debugprint.c [new file with mode: 0644]
portaudio/src/common/pa_debugprint.h [new file with mode: 0644]
portaudio/src/common/pa_dither.c [new file with mode: 0644]
portaudio/src/common/pa_dither.h [new file with mode: 0644]
portaudio/src/common/pa_endianness.h [new file with mode: 0644]
portaudio/src/common/pa_front.c [new file with mode: 0644]
portaudio/src/common/pa_gitrevision.h [new file with mode: 0644]
portaudio/src/common/pa_hostapi.h [new file with mode: 0644]
portaudio/src/common/pa_memorybarrier.h [new file with mode: 0644]
portaudio/src/common/pa_process.c [new file with mode: 0644]
portaudio/src/common/pa_process.h [new file with mode: 0644]
portaudio/src/common/pa_ringbuffer.c [new file with mode: 0644]
portaudio/src/common/pa_ringbuffer.h [new file with mode: 0644]
portaudio/src/common/pa_stream.c [new file with mode: 0644]
portaudio/src/common/pa_stream.h [new file with mode: 0644]
portaudio/src/common/pa_trace.c [new file with mode: 0644]
portaudio/src/common/pa_trace.h [new file with mode: 0644]
portaudio/src/common/pa_types.h [new file with mode: 0644]
portaudio/src/common/pa_util.h [new file with mode: 0644]
portaudio/src/hostapi/alsa/pa_linux_alsa.c [new file with mode: 0644]
portaudio/src/hostapi/asihpi/pa_linux_asihpi.c [new file with mode: 0644]
portaudio/src/hostapi/asio/iasiothiscallresolver.cpp [new file with mode: 0644]
portaudio/src/hostapi/asio/iasiothiscallresolver.h [new file with mode: 0644]
portaudio/src/hostapi/asio/pa_asio.cpp [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core.c [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_old.c [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c [new file with mode: 0644]
portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h [new file with mode: 0644]
portaudio/src/hostapi/dsound/pa_win_ds.c [new file with mode: 0644]
portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c [new file with mode: 0644]
portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h [new file with mode: 0644]
portaudio/src/hostapi/jack/pa_jack.c [new file with mode: 0644]
portaudio/src/hostapi/oss/pa_unix_oss.c [new file with mode: 0644]
portaudio/src/hostapi/oss/recplay.c [new file with mode: 0644]
portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c [new file with mode: 0644]
portaudio/src/hostapi/wasapi/mingw-include/ks.h [new file with mode: 0644]
portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h [new file with mode: 0644]
portaudio/src/hostapi/wasapi/pa_win_wasapi.c [new file with mode: 0644]
portaudio/src/hostapi/wdmks/pa_win_wdmks.c [new file with mode: 0644]
portaudio/src/hostapi/wmme/pa_win_wmme.c [new file with mode: 0644]
portaudio/src/os/unix/pa_unix_hostapis.c [new file with mode: 0644]
portaudio/src/os/unix/pa_unix_util.c [new file with mode: 0644]
portaudio/src/os/unix/pa_unix_util.h [new file with mode: 0644]
portaudio/src/os/win/pa_win_coinitialize.c [new file with mode: 0644]
portaudio/src/os/win/pa_win_coinitialize.h [new file with mode: 0644]
portaudio/src/os/win/pa_win_hostapis.c [new file with mode: 0644]
portaudio/src/os/win/pa_win_util.c [new file with mode: 0644]
portaudio/src/os/win/pa_win_waveformat.c [new file with mode: 0644]
portaudio/src/os/win/pa_win_wdmks_utils.c [new file with mode: 0644]
portaudio/src/os/win/pa_win_wdmks_utils.h [new file with mode: 0644]
portaudio/src/os/win/pa_x86_plain_converters.c [new file with mode: 0644]
portaudio/src/os/win/pa_x86_plain_converters.h [new file with mode: 0644]
portmidi/CHANGELOG.txt [new file with mode: 0644]
portmidi/CMakeLists.txt [new file with mode: 0644]
portmidi/README.txt [new file with mode: 0644]
portmidi/license.txt [new file with mode: 0644]
portmidi/portmidi.vcproj [deleted file]
portmidi/portmidi.vcxproj [deleted file]
portmidi/portmidi.vcxproj.filters [deleted file]
portmidi/portmidi.vcxproj.user [deleted file]
portmidi/porttime/ptlinux.c [deleted file]
portmidi/porttime/ptmacosx_cf.c [deleted file]
portmidi/porttime/ptmacosx_mach.c [deleted file]
sf_view_gui/CMakeLists.txt
sf_view_gui/mysndfont.c
sf_view_gui/resource.h
sf_view_gui/sfview_dlg.rc
sf_view_gui/sfview_main.cpp
sfviewer/sfviewer.vcxproj [deleted file]
sfviewer/sfviewer.vcxproj.filters [deleted file]
sfviewer/sfviewer.vcxproj.user [deleted file]
speex/CMakeLists.txt [new file with mode: 0644]
speex/libspeex.def [new file with mode: 0644]
speex/libspeex.vcproj [deleted file]
speex/libspeex.vcxproj [deleted file]
speex/libspeex.vcxproj.filters [deleted file]
speex/libspeex.vcxproj.user [deleted file]
speex/os_support.h
speex/speex.vcproj [deleted file]
tim41-readme.txt [new file with mode: 0644]
tim_cui/tim_cui.vcproj [deleted file]
tim_cui/tim_cui.vcxproj [deleted file]
tim_cui/tim_cui.vcxproj.filters [deleted file]
tim_cui/tim_cui.vcxproj.user [deleted file]
timidity.dsp [deleted file]
timidity/CMakeLists.txt
timidity/aiff_a.c
timidity/controls.c
timidity/decode.c
timidity/filter.h
timidity/flac_a.c
timidity/gogo_a.c
timidity/int_synth.h
timidity/lame_a.c
timidity/mix.c
timidity/mod2midi.c
timidity/optcode.c [changed mode: 0755->0644]
timidity/optcode.h [changed mode: 0755->0644]
timidity/opus_a.c
timidity/output.c
timidity/playmidi.c
timidity/portaudio_a.h
timidity/readmidi.c
timidity/resample.c
timidity/smplfile.c [changed mode: 0755->0644]
timidity/sndfont.c
timidity/sndfontini.c
timidity/speex_a.c
timidity/sysdep.h [changed mode: 0755->0644]
timidity/thread.c
timidity/timidity.c
timidity/timidity.dsp [deleted file]
timidity/timidity.vcproj [deleted file]
timidity/timidity.vcxproj [deleted file]
timidity/timidity.vcxproj.filters [deleted file]
timidity/timidity.vcxproj.user [deleted file]
timidity/voice_effect.c
timidity/volumecalc_a.c
timidity/vorbis_a.c
timidity/w32_a.c
timidity/w32_a.h
timidity/w32_gogo.c
timidity/w32_libFLAC_dll.c
timidity/w32_libFLAC_dll_g.h
timidity/w32_libFLAC_dll_i.h
timidity/w32_libOggFLAC_dll.c
timidity/w32_libmpg123_dll.c
timidity/w32_portaudio_dll.c
timidity/w32_speex_dll.c [new file with mode: 0644]
timidity/w32g_ogg_dll.c
timidity/w32g_opus_dll.c
timidity/w32g_vorbis_dll.c
timidity/w32g_vorbisenc_dll.c
timidity/wasapi_a.c
timidity/wasapi_a.h
timidity/wdmks_a.c
timidity/wdmks_a.h
timidity/wrdt.c
timidity_vs2008.sln [deleted file]
timidity_vs2010.sln [deleted file]
timidity_vs6.dsw [deleted file]
timw32g/timw32g.dsp [deleted file]
timw32g/timw32g.vcproj [deleted file]
timw32g/timw32g.vcxproj [deleted file]
timw32g/timw32g.vcxproj.filters [deleted file]
timw32g/timw32g.vcxproj.user [deleted file]
timw32gd/timw32gd.dsp [deleted file]
timw32gd/timw32gd.vcproj [deleted file]
timw32gd/timw32gd.vcxproj [deleted file]
twsyn_bridge/CMakeLists.txt [new file with mode: 0644]
twsyn_bridge/twsyn_bridge.vcproj [deleted file]
twsyn_bridge/twsyn_bridge.vcxproj [deleted file]
twsyn_bridge/twsyn_bridge_host.c
twsyng/twsyng.dsp [deleted file]
twsyng/twsyng.vcproj [deleted file]
twsyng/twsyng.vcxproj [deleted file]
twsyng/twsyng.vcxproj.filters [deleted file]
twsyng/twsyng.vcxproj.user [deleted file]
twsynsrv/twsynsrv.vcproj [deleted file]
twsynsrv/twsynsrv.vcxproj [deleted file]
twsynsrv/twsynsrv.vcxproj.filters [deleted file]
twsynsrv/twsynsrv.vcxproj.user [deleted file]
utils/CMakeLists.txt [new file with mode: 0644]
utils/utils.dsp [deleted file]
utils/utils.vcproj [deleted file]
utils/utils.vcxproj [deleted file]
utils/utils.vcxproj.filters [deleted file]
utils/utils.vcxproj.user [deleted file]
version.h [deleted file]
version.h.in [new file with mode: 0644]
vorbis/AUTHORS [new file with mode: 0644]
vorbis/CMakeLists.txt [new file with mode: 0644]
vorbis/COPYING [new file with mode: 0644]
vorbis/README [new file with mode: 0644]
vorbis/include/vorbis/codec.h [moved from vorbis/codec.h with 86% similarity]
vorbis/include/vorbis/vorbisenc.h [new file with mode: 0644]
vorbis/include/vorbis/vorbisfile.h [moved from vorbis/vorbisfile.h with 59% similarity]
vorbis/lib/analysis.c [new file with mode: 0644]
vorbis/lib/backends.h [new file with mode: 0644]
vorbis/lib/barkmel.c [new file with mode: 0644]
vorbis/lib/bitrate.c [new file with mode: 0644]
vorbis/lib/bitrate.h [new file with mode: 0644]
vorbis/lib/block.c [new file with mode: 0644]
vorbis/lib/books/coupled/res_books_51.h [new file with mode: 0644]
vorbis/lib/books/coupled/res_books_stereo.h [new file with mode: 0644]
vorbis/lib/books/floor/floor_books.h [new file with mode: 0644]
vorbis/lib/books/uncoupled/res_books_uncoupled.h [new file with mode: 0644]
vorbis/lib/codebook.c [new file with mode: 0644]
vorbis/lib/codebook.h [new file with mode: 0644]
vorbis/lib/codec_internal.h [new file with mode: 0644]
vorbis/lib/envelope.c [new file with mode: 0644]
vorbis/lib/envelope.h [new file with mode: 0644]
vorbis/lib/floor0.c [new file with mode: 0644]
vorbis/lib/floor1.c [new file with mode: 0644]
vorbis/lib/highlevel.h [new file with mode: 0644]
vorbis/lib/info.c [new file with mode: 0644]
vorbis/lib/lookup.c [new file with mode: 0644]
vorbis/lib/lookup.h [new file with mode: 0644]
vorbis/lib/lookup_data.h [new file with mode: 0644]
vorbis/lib/lookups.pl [new file with mode: 0644]
vorbis/lib/lpc.c [new file with mode: 0644]
vorbis/lib/lpc.h [new file with mode: 0644]
vorbis/lib/lsp.c [new file with mode: 0644]
vorbis/lib/lsp.h [new file with mode: 0644]
vorbis/lib/mapping0.c [new file with mode: 0644]
vorbis/lib/masking.h [new file with mode: 0644]
vorbis/lib/mdct.c [new file with mode: 0644]
vorbis/lib/mdct.h [new file with mode: 0644]
vorbis/lib/misc.h [new file with mode: 0644]
vorbis/lib/modes/floor_all.h [new file with mode: 0644]
vorbis/lib/modes/psych_11.h [new file with mode: 0644]
vorbis/lib/modes/psych_16.h [new file with mode: 0644]
vorbis/lib/modes/psych_44.h [new file with mode: 0644]
vorbis/lib/modes/psych_8.h [new file with mode: 0644]
vorbis/lib/modes/residue_16.h [new file with mode: 0644]
vorbis/lib/modes/residue_44.h [new file with mode: 0644]
vorbis/lib/modes/residue_44p51.h [new file with mode: 0644]
vorbis/lib/modes/residue_44u.h [new file with mode: 0644]
vorbis/lib/modes/residue_8.h [new file with mode: 0644]
vorbis/lib/modes/setup_11.h [new file with mode: 0644]
vorbis/lib/modes/setup_16.h [new file with mode: 0644]
vorbis/lib/modes/setup_22.h [new file with mode: 0644]
vorbis/lib/modes/setup_32.h [new file with mode: 0644]
vorbis/lib/modes/setup_44.h [new file with mode: 0644]
vorbis/lib/modes/setup_44p51.h [new file with mode: 0644]
vorbis/lib/modes/setup_44u.h [new file with mode: 0644]
vorbis/lib/modes/setup_8.h [new file with mode: 0644]
vorbis/lib/modes/setup_X.h [new file with mode: 0644]
vorbis/lib/os.h [new file with mode: 0644]
vorbis/lib/psy.c [new file with mode: 0644]
vorbis/lib/psy.h [new file with mode: 0644]
vorbis/lib/registry.c [new file with mode: 0644]
vorbis/lib/registry.h [new file with mode: 0644]
vorbis/lib/res0.c [new file with mode: 0644]
vorbis/lib/scales.h [new file with mode: 0644]
vorbis/lib/sharedbook.c [new file with mode: 0644]
vorbis/lib/smallft.c [new file with mode: 0644]
vorbis/lib/smallft.h [new file with mode: 0644]
vorbis/lib/synthesis.c [new file with mode: 0644]
vorbis/lib/vorbisenc.c [new file with mode: 0644]
vorbis/lib/vorbisfile.c [new file with mode: 0644]
vorbis/lib/window.c [new file with mode: 0644]
vorbis/lib/window.h [new file with mode: 0644]
vorbis/vorbisenc.h [deleted file]
vorbis/win32/vorbis.def [new file with mode: 0644]
vorbis/win32/vorbisenc.def [new file with mode: 0644]
vorbis/win32/vorbisfile.def [new file with mode: 0644]

diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..d86e80f
--- /dev/null
@@ -0,0 +1,263 @@
+
+cmake_minimum_required(VERSION 3.9)
+
+project(timidity41)
+
+set(TIM41_USE_AVX2 FALSE CACHE BOOL "Enable use of Intel AVX2 enhanced instructions")
+set(TIM41_USE_CLANG_CL FALSE CACHE BOOL "Compile with clang-cl")
+
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/Debug/bin")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/Release/bin")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/RelWithDebInfo/bin")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/MinSizeRel/bin")
+
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/Debug/bin")
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/Release/bin")
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/RelWithDebInfo/bin")
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/MinSizeRel/bin")
+
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/Debug/bin")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/Release/bin")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/RelWithDebInfo/bin")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/MinSizeRel/bin")
+
+find_package(Git)
+
+if("${Git_FOUND}" AND EXISTS "${CMAKE_SOURCE_DIR}/.git")
+    add_custom_target(
+        UpdateTim41Version
+        COMMAND "${CMAKE_COMMAND}"
+            -DGIT_EXECUTABLE="${GIT_EXECUTABLE}"
+            -DINFILE="${CMAKE_CURRENT_SOURCE_DIR}/version.h.in"
+            -DOUTFILE="${CMAKE_CURRENT_BINARY_DIR}/version.h"
+            -P "${CMAKE_CURRENT_SOURCE_DIR}/WriteVersion.cmake"
+        BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/version.h"
+        WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
+        COMMENT "Updating version info..."
+    )
+else()
+    set(tim41VersionStr "current")
+    set(tim41Version4Comma "41,0,0,0")
+    configure_file(version.h.in version.h)
+
+    add_custom_target(
+        UpdateTim41Version
+        COMMAND "${CMAKE_COMMAND}" -E echo "automatic version detection is not available"
+    )
+endif()
+
+include_directories("${CMAKE_CURRENT_BINARY_DIR}")
+
+add_definitions(
+# TiMidity++ common
+    -DRETSIGTYPE=int
+    -DSTDC_HEADERS
+    -DHAVE_GETCWD
+    -DHAVE_POPEN
+    -DHAVE_SIGNAL
+    -DHAVE_SNPRINTF
+    -DHAVE_STRDUP
+    -DHAVE_STRERROR
+    -DHAVE_STRNCASECMP
+    -DHAVE_STRSTR
+    -DHAVE_VPRINTF
+    -DHAVE_VSNPRINTF
+    -DHAVE_ERRNO_H
+    -DHAVE_LIMITS_H
+    -DHAVE_MALLOC_H
+    -DHAVE_STDLIB_H
+       -DHAVE_SYS_STAT_H
+    -DHAVE_SYS_TYPES_H
+    -DHAVE_FCNTL_H
+    -DHAVE_LIBVORBIS
+    -DHAVE_LIBGOGO
+    -DHAVE_LIBMPG123
+    -DHAVE_MMSYSTEM_H
+    -DENABLE_SHERRY
+    -DENABLE_THREAD
+    -DSUPPORT_SOUNDSPEC
+    -DANOTHER_MAIN
+    -D__W32__
+    -D__W32READDIR__
+       -DUSE_TWSYN_BRIDGE
+    -DENABLE_SFZ
+       -DTIMW32G_USE_NEW_CONSOLE
+       -DENABLE_DLS
+
+# TiMidity++ audio
+    -DAU_W32
+    -DAU_WASAPI
+    -DAU_WDMKS
+    -DAU_OPUS
+    -DAU_OPUS_DLL
+    -DAU_SPEEX
+       -DAU_SPEEX_DLL
+    -DAU_LAME
+    -DAU_GOGO
+    -DAU_GOGO_DLL
+    -DAU_VORBIS
+    -DAU_VORBIS_DLL
+    -DVORBIS_DLL_INCLUDE_VORBISENC
+    -DVORBIS_DLL_INCLUDE_VORBISFILE
+    -DAU_FLAC
+    -DAU_FLAC_DLL
+    -DAU_OGGFLAC
+    -DAU_PORTAUDIO
+    -DAU_PORTAUDIO_DLL
+    -DPORTAUDIO_V19
+    -DPORTAUDIO_V19_6
+    -DVST_LOADER_ENABLE
+    -DVSTWRAP_EXT
+    -DAU_NPIPE
+    -DAU_LIST
+    -DAU_WRITE_MIDI
+    -DAU_MODMIDI
+    -DAU_VOLUME_CALC
+    -DAU_BENCHMARK
+
+# network
+    -DWINSOCK
+    -DHAVE_SOCKET
+    -DSUPPORT_SOCKET
+
+# pdcurses
+    -DPDC_DLL_BUILD
+
+# Windows
+    -DWIN32_LEAN_AND_MEAN
+    -DWINVER=0x0A00
+    -D_WIN32_WINNT=0x0A00
+
+# MSVCRT
+    -D_CRT_SECURE_NO_WARNINGS
+)
+
+if(TIM41_USE_AVX2)
+    add_definitions(-DUSE_AVX2)
+else()
+    add_definitions(-DUSE_SSE42)
+endif()
+
+if(MSVC)
+    if("${TIM41_USE_CLANG_CL}")
+        set(CMAKE_C_LINK_EXECUTABLE "lld-link <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> /out:<TARGET> <LINK_LIBRARIES>")
+        set(CMAKE_CXX_LINK_EXECUTABLE "lld-link <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> /out:<TARGET> <LINK_LIBRARIES>")
+        set(CMAKE_C_CREATE_SHARED_LIBRARY "lld-link /dll <CMAKE_SHARED_LIBRARY_C_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <SONAME_FLAG><TARGET_SONAME> /out:<TARGET> <OBJECTS> <LINK_LIBRARIES>")
+        set(CMAKE_CXX_CREATE_SHARED_LIBRARY "lld-link /dll <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <SONAME_FLAG><TARGET_SONAME> /out:<TARGET> <OBJECTS> <LINK_LIBRARIES>")
+    endif()
+
+    # remove existing /W3 options
+    string(REGEX REPLACE "/W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
+    string(REGEX REPLACE "/W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
+
+    add_compile_options(/W4 /Zi /GS /fp:fast)
+
+    if(NOT "${TIM41_USE_CLANG_CL}")
+        add_compile_options(/Qspectre)
+    endif()
+
+    add_compile_options(/we4013)    # '%s' undefined; assuming extern returning int
+    
+    if(TIM41_USE_AVX2)
+        add_compile_options(/arch:AVX2)
+    endif()
+    
+       set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /std:c++17")
+
+    if("${TIM41_USE_CLANG_CL}")
+        set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -flto=thin")
+        set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -flto=thin")
+    else()
+        set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /GL /guard:cf")
+        set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /GL /guard:cf")
+    endif()
+
+    if("${TIM41_USE_CLANG_CL}")
+        set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /DEBUG")
+        set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} /DEBUG")
+
+        set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /OPT:REF /OPT:ICF /DEBUG")
+        set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /OPT:REF /OPT:ICF /DEBUG")
+
+        set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /OPT:REF /DEBUG")
+        set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /OPT:REF /DEBUG")
+    else()
+        set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /DEBUG:FASTLINK")
+        set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} /DEBUG:FASTLINK")
+
+        set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /OPT:REF /OPT:ICF /LTCG:incremental /DEBUG:FULL /GUARD:CF")
+        set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /OPT:REF /OPT:ICF /LTCG:incremental /DEBUG:FULL /GUARD:CF")
+        set(CMAKE_STATIC_LINKER_FLAGS_RELEASE "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG:incremental")
+
+        set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /OPT:REF /DEBUG:FASTLINK")
+        set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /OPT:REF /DEBUG:FASTLINK")
+    endif()
+
+    add_definitions(
+        -DSTDOUT_FILENO=1
+    )
+else()
+    add_compile_options(-Wall -Wextra -Wno-missing-braces -ffast-math)
+
+    if(TIM41_USE_AVX2)
+        add_compile_options(-mavx2 -mfma)
+    else()
+        add_compile_options(-msse4.2)
+    endif()
+
+       set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")
+    set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -flto")
+    set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -flto")
+    set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -s")
+    set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -s")
+    set(CMAKE_RC_FLAGS "-O coff")
+endif()
+
+function(DisableMSManifest targetName)
+    if(MSVC)
+        get_property(linkFlags TARGET ${targetName} PROPERTY LINK_FLAGS)
+        set_target_properties(${targetName} PROPERTIES LINK_FLAGS "${linkFlags} /MANIFEST:NO")
+    endif()
+endfunction()
+
+include_directories(
+    "."
+    FLAC/include
+    interface
+    lame/DLL
+    lame/include
+    libarc
+    libmpg123/include
+    libunimod
+    ogg/include
+    opus/include
+    pdcurses
+    portaudio/include
+    portmidi/pm_common
+    portmidi/pm_win
+    portmidi/porttime
+    timidity
+       twsyn_bridge
+    utils
+    vorbis/include
+)
+
+add_subdirectory(FLAC)
+add_subdirectory(lame)
+add_subdirectory(libmpg123)
+add_subdirectory(ogg)
+add_subdirectory(opus)
+add_subdirectory(pdcurses)
+add_subdirectory(portaudio)
+add_subdirectory(portmidi)
+add_subdirectory(speex)
+add_subdirectory(vorbis)
+
+add_subdirectory(cfgforsf)
+add_subdirectory(interface)
+add_subdirectory(libarc)
+add_subdirectory(libunimod)
+add_subdirectory(sf_view_gui)
+add_subdirectory(timidity)
+add_subdirectory(twsyn_bridge)
+add_subdirectory(utils)
diff --git a/FLAC/AUTHORS b/FLAC/AUTHORS
new file mode 100644 (file)
index 0000000..8fe9092
--- /dev/null
@@ -0,0 +1,58 @@
+/* FLAC - Free Lossless Audio Codec
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * This file is part the FLAC project.  FLAC is comprised of several
+ * components distributed under different licenses.  The codec libraries
+ * are distributed under Xiph.Org's BSD-like license (see the file
+ * COPYING.Xiph in this distribution).  All other programs, libraries, and
+ * plugins are distributed under the GPL (see COPYING.GPL).  The documentation
+ * is distributed under the Gnu FDL (see COPYING.FDL).  Each file in the
+ * FLAC distribution contains at the top the terms under which it may be
+ * distributed.
+ *
+ * Since this particular file is relevant to all components of FLAC,
+ * it may be distributed under the Xiph.Org license, which is the least
+ * restrictive of those mentioned above.  See the file COPYING.Xiph in this
+ * distribution.
+ */
+
+Current FLAC maintainer: Erik de Castro Lopo <erikd@mega-nerd.com>
+
+Original author: Josh Coalson <jcoalson@users.sourceforge.net>
+
+Website : https://www.xiph.org/flac/
+
+FLAC is an Open Source lossless audio codec originally developed by Josh Coalson
+between 2001 and 2009. From 2009 to 2012 FLAC was basically unmaintained. In
+2012 the Erik de Castro Lopo became the chief maintainer as part of the
+Xiph.Org Foundation.
+
+Other major contributors and their contributions:
+
+"lvqcl" <lvqcl@users.sourceforge.net>
+* Visual Studio build system.
+* Optimisations in the encoder and decoder.
+
+"Janne Hyvärinen" <cse@sci.fi>
+* Visual Studio build system.
+* Unicode handling on Windows.
+
+"Andrey Astafiev" <andrei@tvcell.ru>
+* Russian translation of the HTML documentation
+
+"Miroslav Lichvar" <lichvarm@phoenix.inf.upol.cz>
+* IA-32 assembly versions of several libFLAC routines
+
+"Brady Patterson" <bpat@users.sourceforge.net>
+* AIFF file support, PPC assembly versions of libFLAC routines
+
+"Daisuke Shimamura" <Daisuke_Shimamura@nifty.com>
+* i18n support in the XMMS plugin
+
+"X-Fixer" <x-fixer@narod.ru>
+* Configuration system, tag editing, and file info in the Winamp2 plugin
+
+"Matt Zimmerman" <mdz@debian.org>
+* Libtool/autoconf/automake make system, flac man page
+
diff --git a/FLAC/CMakeLists.txt b/FLAC/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c9f4c87
--- /dev/null
@@ -0,0 +1,101 @@
+
+add_definitions(
+    -DFLAC_API_EXPORTS
+    -DFLAC__HAS_X86INTRIN
+    -DFLAC__HAS_OGG
+
+    -DPACKAGE_VERSION="1.3.2"
+)
+
+if(MINGW)
+    add_definitions(
+        -DHAVE_FSEEKO
+        -DHAVE_LROUND
+    )
+endif()
+
+include_directories(src)
+
+add_library(
+    FLAC SHARED
+
+    include/FLAC/all.h
+    include/FLAC/assert.h
+    include/FLAC/callback.h
+    include/FLAC/export.h
+    include/FLAC/format.h
+    include/FLAC/metadata.h
+    include/FLAC/ordinals.h
+    include/FLAC/stream_decoder.h
+    include/FLAC/stream_encoder.h
+
+    src/private/all.h
+    src/private/bitmath.h
+    src/private/bitreader.h
+    src/private/bitwriter.h
+    src/private/cpu.h
+    src/private/crc.h
+    src/private/fixed.h
+    src/private/float.h
+    src/private/format.h
+    src/private/lpc.h
+    src/private/macros.h
+    src/private/md5.h
+    src/private/memory.h
+    src/private/metadata.h
+    src/private/ogg_decoder_aspect.h
+    src/private/ogg_encoder_aspect.h
+    src/private/ogg_helper.h
+    src/private/ogg_mapping.h
+    src/private/stream_encoder.h
+    src/private/stream_encoder_framing.h
+    src/private/window.h
+
+    src/share/alloc.h
+    src/share/compat.h
+    src/share/endswap.h
+    src/share/getopt.h
+    src/share/grabbag.h
+    src/share/macros.h
+    src/share/private.h
+    src/share/replaygain_analysis.h
+    src/share/replaygain_synthesis.h
+    src/share/safe_str.h
+    src/share/utf8.h
+    src/share/windows_unicode_filenames.h
+    src/share/win_utf8_io.h
+
+    src/bitmath.c
+    src/bitreader.c
+    src/bitwriter.c
+    src/cpu.c
+    src/crc.c
+    src/fixed.c
+    src/fixed_intrin_sse2.c
+    src/fixed_intrin_ssse3.c
+    src/float.c
+    src/format.c
+    src/lpc.c
+    src/lpc_intrin_avx2.c
+    src/lpc_intrin_sse.c
+    src/lpc_intrin_sse2.c
+    src/lpc_intrin_sse41.c
+    src/md5.c
+    src/memory.c
+    src/metadata_iterators.c
+    src/metadata_object.c
+    src/ogg_decoder_aspect.c
+    src/ogg_encoder_aspect.c
+    src/ogg_helper.c
+    src/ogg_mapping.c
+    src/stream_decoder.c
+    src/stream_encoder.c
+    src/stream_encoder_framing.c
+    src/stream_encoder_intrin_avx2.c
+    src/stream_encoder_intrin_sse2.c
+    src/stream_encoder_intrin_ssse3.c
+    src/window.c
+    src/windows_unicode_filenames.c
+)
+
+target_link_libraries(FLAC ogg)
diff --git a/FLAC/COPYING.FDL b/FLAC/COPYING.FDL
new file mode 100644 (file)
index 0000000..4a0fe1c
--- /dev/null
@@ -0,0 +1,397 @@
+               GNU Free Documentation License
+                 Version 1.2, November 2002
+
+
+ Copyright (C) 2000,2001,2002  Free Software Foundation, Inc.
+     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+0. PREAMBLE
+
+The purpose of this License is to make a manual, textbook, or other
+functional and useful document "free" in the sense of freedom: to
+assure everyone the effective freedom to copy and redistribute it,
+with or without modifying it, either commercially or noncommercially.
+Secondarily, this License preserves for the author and publisher a way
+to get credit for their work, while not being considered responsible
+for modifications made by others.
+
+This License is a kind of "copyleft", which means that derivative
+works of the document must themselves be free in the same sense.  It
+complements the GNU General Public License, which is a copyleft
+license designed for free software.
+
+We have designed this License in order to use it for manuals for free
+software, because free software needs free documentation: a free
+program should come with manuals providing the same freedoms that the
+software does.  But this License is not limited to software manuals;
+it can be used for any textual work, regardless of subject matter or
+whether it is published as a printed book.  We recommend this License
+principally for works whose purpose is instruction or reference.
+
+
+1. APPLICABILITY AND DEFINITIONS
+
+This License applies to any manual or other work, in any medium, that
+contains a notice placed by the copyright holder saying it can be
+distributed under the terms of this License.  Such a notice grants a
+world-wide, royalty-free license, unlimited in duration, to use that
+work under the conditions stated herein.  The "Document", below,
+refers to any such manual or work.  Any member of the public is a
+licensee, and is addressed as "you".  You accept the license if you
+copy, modify or distribute the work in a way requiring permission
+under copyright law.
+
+A "Modified Version" of the Document means any work containing the
+Document or a portion of it, either copied verbatim, or with
+modifications and/or translated into another language.
+
+A "Secondary Section" is a named appendix or a front-matter section of
+the Document that deals exclusively with the relationship of the
+publishers or authors of the Document to the Document's overall subject
+(or to related matters) and contains nothing that could fall directly
+within that overall subject.  (Thus, if the Document is in part a
+textbook of mathematics, a Secondary Section may not explain any
+mathematics.)  The relationship could be a matter of historical
+connection with the subject or with related matters, or of legal,
+commercial, philosophical, ethical or political position regarding
+them.
+
+The "Invariant Sections" are certain Secondary Sections whose titles
+are designated, as being those of Invariant Sections, in the notice
+that says that the Document is released under this License.  If a
+section does not fit the above definition of Secondary then it is not
+allowed to be designated as Invariant.  The Document may contain zero
+Invariant Sections.  If the Document does not identify any Invariant
+Sections then there are none.
+
+The "Cover Texts" are certain short passages of text that are listed,
+as Front-Cover Texts or Back-Cover Texts, in the notice that says that
+the Document is released under this License.  A Front-Cover Text may
+be at most 5 words, and a Back-Cover Text may be at most 25 words.
+
+A "Transparent" copy of the Document means a machine-readable copy,
+represented in a format whose specification is available to the
+general public, that is suitable for revising the document
+straightforwardly with generic text editors or (for images composed of
+pixels) generic paint programs or (for drawings) some widely available
+drawing editor, and that is suitable for input to text formatters or
+for automatic translation to a variety of formats suitable for input
+to text formatters.  A copy made in an otherwise Transparent file
+format whose markup, or absence of markup, has been arranged to thwart
+or discourage subsequent modification by readers is not Transparent.
+An image format is not Transparent if used for any substantial amount
+of text.  A copy that is not "Transparent" is called "Opaque".
+
+Examples of suitable formats for Transparent copies include plain
+ASCII without markup, Texinfo input format, LaTeX input format, SGML
+or XML using a publicly available DTD, and standard-conforming simple
+HTML, PostScript or PDF designed for human modification.  Examples of
+transparent image formats include PNG, XCF and JPG.  Opaque formats
+include proprietary formats that can be read and edited only by
+proprietary word processors, SGML or XML for which the DTD and/or
+processing tools are not generally available, and the
+machine-generated HTML, PostScript or PDF produced by some word
+processors for output purposes only.
+
+The "Title Page" means, for a printed book, the title page itself,
+plus such following pages as are needed to hold, legibly, the material
+this License requires to appear in the title page.  For works in
+formats which do not have any title page as such, "Title Page" means
+the text near the most prominent appearance of the work's title,
+preceding the beginning of the body of the text.
+
+A section "Entitled XYZ" means a named subunit of the Document whose
+title either is precisely XYZ or contains XYZ in parentheses following
+text that translates XYZ in another language.  (Here XYZ stands for a
+specific section name mentioned below, such as "Acknowledgements",
+"Dedications", "Endorsements", or "History".)  To "Preserve the Title"
+of such a section when you modify the Document means that it remains a
+section "Entitled XYZ" according to this definition.
+
+The Document may include Warranty Disclaimers next to the notice which
+states that this License applies to the Document.  These Warranty
+Disclaimers are considered to be included by reference in this
+License, but only as regards disclaiming warranties: any other
+implication that these Warranty Disclaimers may have is void and has
+no effect on the meaning of this License.
+
+
+2. VERBATIM COPYING
+
+You may copy and distribute the Document in any medium, either
+commercially or noncommercially, provided that this License, the
+copyright notices, and the license notice saying this License applies
+to the Document are reproduced in all copies, and that you add no other
+conditions whatsoever to those of this License.  You may not use
+technical measures to obstruct or control the reading or further
+copying of the copies you make or distribute.  However, you may accept
+compensation in exchange for copies.  If you distribute a large enough
+number of copies you must also follow the conditions in section 3.
+
+You may also lend copies, under the same conditions stated above, and
+you may publicly display copies.
+
+
+3. COPYING IN QUANTITY
+
+If you publish printed copies (or copies in media that commonly have
+printed covers) of the Document, numbering more than 100, and the
+Document's license notice requires Cover Texts, you must enclose the
+copies in covers that carry, clearly and legibly, all these Cover
+Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
+the back cover.  Both covers must also clearly and legibly identify
+you as the publisher of these copies.  The front cover must present
+the full title with all words of the title equally prominent and
+visible.  You may add other material on the covers in addition.
+Copying with changes limited to the covers, as long as they preserve
+the title of the Document and satisfy these conditions, can be treated
+as verbatim copying in other respects.
+
+If the required texts for either cover are too voluminous to fit
+legibly, you should put the first ones listed (as many as fit
+reasonably) on the actual cover, and continue the rest onto adjacent
+pages.
+
+If you publish or distribute Opaque copies of the Document numbering
+more than 100, you must either include a machine-readable Transparent
+copy along with each Opaque copy, or state in or with each Opaque copy
+a computer-network location from which the general network-using
+public has access to download using public-standard network protocols
+a complete Transparent copy of the Document, free of added material.
+If you use the latter option, you must take reasonably prudent steps,
+when you begin distribution of Opaque copies in quantity, to ensure
+that this Transparent copy will remain thus accessible at the stated
+location until at least one year after the last time you distribute an
+Opaque copy (directly or through your agents or retailers) of that
+edition to the public.
+
+It is requested, but not required, that you contact the authors of the
+Document well before redistributing any large number of copies, to give
+them a chance to provide you with an updated version of the Document.
+
+
+4. MODIFICATIONS
+
+You may copy and distribute a Modified Version of the Document under
+the conditions of sections 2 and 3 above, provided that you release
+the Modified Version under precisely this License, with the Modified
+Version filling the role of the Document, thus licensing distribution
+and modification of the Modified Version to whoever possesses a copy
+of it.  In addition, you must do these things in the Modified Version:
+
+A. Use in the Title Page (and on the covers, if any) a title distinct
+   from that of the Document, and from those of previous versions
+   (which should, if there were any, be listed in the History section
+   of the Document).  You may use the same title as a previous version
+   if the original publisher of that version gives permission.
+B. List on the Title Page, as authors, one or more persons or entities
+   responsible for authorship of the modifications in the Modified
+   Version, together with at least five of the principal authors of the
+   Document (all of its principal authors, if it has fewer than five),
+   unless they release you from this requirement.
+C. State on the Title page the name of the publisher of the
+   Modified Version, as the publisher.
+D. Preserve all the copyright notices of the Document.
+E. Add an appropriate copyright notice for your modifications
+   adjacent to the other copyright notices.
+F. Include, immediately after the copyright notices, a license notice
+   giving the public permission to use the Modified Version under the
+   terms of this License, in the form shown in the Addendum below.
+G. Preserve in that license notice the full lists of Invariant Sections
+   and required Cover Texts given in the Document's license notice.
+H. Include an unaltered copy of this License.
+I. Preserve the section Entitled "History", Preserve its Title, and add
+   to it an item stating at least the title, year, new authors, and
+   publisher of the Modified Version as given on the Title Page.  If
+   there is no section Entitled "History" in the Document, create one
+   stating the title, year, authors, and publisher of the Document as
+   given on its Title Page, then add an item describing the Modified
+   Version as stated in the previous sentence.
+J. Preserve the network location, if any, given in the Document for
+   public access to a Transparent copy of the Document, and likewise
+   the network locations given in the Document for previous versions
+   it was based on.  These may be placed in the "History" section.
+   You may omit a network location for a work that was published at
+   least four years before the Document itself, or if the original
+   publisher of the version it refers to gives permission.
+K. For any section Entitled "Acknowledgements" or "Dedications",
+   Preserve the Title of the section, and preserve in the section all
+   the substance and tone of each of the contributor acknowledgements
+   and/or dedications given therein.
+L. Preserve all the Invariant Sections of the Document,
+   unaltered in their text and in their titles.  Section numbers
+   or the equivalent are not considered part of the section titles.
+M. Delete any section Entitled "Endorsements".  Such a section
+   may not be included in the Modified Version.
+N. Do not retitle any existing section to be Entitled "Endorsements"
+   or to conflict in title with any Invariant Section.
+O. Preserve any Warranty Disclaimers.
+
+If the Modified Version includes new front-matter sections or
+appendices that qualify as Secondary Sections and contain no material
+copied from the Document, you may at your option designate some or all
+of these sections as invariant.  To do this, add their titles to the
+list of Invariant Sections in the Modified Version's license notice.
+These titles must be distinct from any other section titles.
+
+You may add a section Entitled "Endorsements", provided it contains
+nothing but endorsements of your Modified Version by various
+parties--for example, statements of peer review or that the text has
+been approved by an organization as the authoritative definition of a
+standard.
+
+You may add a passage of up to five words as a Front-Cover Text, and a
+passage of up to 25 words as a Back-Cover Text, to the end of the list
+of Cover Texts in the Modified Version.  Only one passage of
+Front-Cover Text and one of Back-Cover Text may be added by (or
+through arrangements made by) any one entity.  If the Document already
+includes a cover text for the same cover, previously added by you or
+by arrangement made by the same entity you are acting on behalf of,
+you may not add another; but you may replace the old one, on explicit
+permission from the previous publisher that added the old one.
+
+The author(s) and publisher(s) of the Document do not by this License
+give permission to use their names for publicity for or to assert or
+imply endorsement of any Modified Version.
+
+
+5. COMBINING DOCUMENTS
+
+You may combine the Document with other documents released under this
+License, under the terms defined in section 4 above for modified
+versions, provided that you include in the combination all of the
+Invariant Sections of all of the original documents, unmodified, and
+list them all as Invariant Sections of your combined work in its
+license notice, and that you preserve all their Warranty Disclaimers.
+
+The combined work need only contain one copy of this License, and
+multiple identical Invariant Sections may be replaced with a single
+copy.  If there are multiple Invariant Sections with the same name but
+different contents, make the title of each such section unique by
+adding at the end of it, in parentheses, the name of the original
+author or publisher of that section if known, or else a unique number.
+Make the same adjustment to the section titles in the list of
+Invariant Sections in the license notice of the combined work.
+
+In the combination, you must combine any sections Entitled "History"
+in the various original documents, forming one section Entitled
+"History"; likewise combine any sections Entitled "Acknowledgements",
+and any sections Entitled "Dedications".  You must delete all sections
+Entitled "Endorsements".
+
+
+6. COLLECTIONS OF DOCUMENTS
+
+You may make a collection consisting of the Document and other documents
+released under this License, and replace the individual copies of this
+License in the various documents with a single copy that is included in
+the collection, provided that you follow the rules of this License for
+verbatim copying of each of the documents in all other respects.
+
+You may extract a single document from such a collection, and distribute
+it individually under this License, provided you insert a copy of this
+License into the extracted document, and follow this License in all
+other respects regarding verbatim copying of that document.
+
+
+7. AGGREGATION WITH INDEPENDENT WORKS
+
+A compilation of the Document or its derivatives with other separate
+and independent documents or works, in or on a volume of a storage or
+distribution medium, is called an "aggregate" if the copyright
+resulting from the compilation is not used to limit the legal rights
+of the compilation's users beyond what the individual works permit.
+When the Document is included in an aggregate, this License does not
+apply to the other works in the aggregate which are not themselves
+derivative works of the Document.
+
+If the Cover Text requirement of section 3 is applicable to these
+copies of the Document, then if the Document is less than one half of
+the entire aggregate, the Document's Cover Texts may be placed on
+covers that bracket the Document within the aggregate, or the
+electronic equivalent of covers if the Document is in electronic form.
+Otherwise they must appear on printed covers that bracket the whole
+aggregate.
+
+
+8. TRANSLATION
+
+Translation is considered a kind of modification, so you may
+distribute translations of the Document under the terms of section 4.
+Replacing Invariant Sections with translations requires special
+permission from their copyright holders, but you may include
+translations of some or all Invariant Sections in addition to the
+original versions of these Invariant Sections.  You may include a
+translation of this License, and all the license notices in the
+Document, and any Warranty Disclaimers, provided that you also include
+the original English version of this License and the original versions
+of those notices and disclaimers.  In case of a disagreement between
+the translation and the original version of this License or a notice
+or disclaimer, the original version will prevail.
+
+If a section in the Document is Entitled "Acknowledgements",
+"Dedications", or "History", the requirement (section 4) to Preserve
+its Title (section 1) will typically require changing the actual
+title.
+
+
+9. TERMINATION
+
+You may not copy, modify, sublicense, or distribute the Document except
+as expressly provided for under this License.  Any other attempt to
+copy, modify, sublicense or distribute the Document is void, and will
+automatically terminate your rights under this License.  However,
+parties who have received copies, or rights, from you under this
+License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+
+10. FUTURE REVISIONS OF THIS LICENSE
+
+The Free Software Foundation may publish new, revised versions
+of the GNU Free Documentation License from time to time.  Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.  See
+http://www.gnu.org/copyleft/.
+
+Each version of the License is given a distinguishing version number.
+If the Document specifies that a particular numbered version of this
+License "or any later version" applies to it, you have the option of
+following the terms and conditions either of that specified version or
+of any later version that has been published (not as a draft) by the
+Free Software Foundation.  If the Document does not specify a version
+number of this License, you may choose any version ever published (not
+as a draft) by the Free Software Foundation.
+
+
+ADDENDUM: How to use this License for your documents
+
+To use this License in a document you have written, include a copy of
+the License in the document and put the following copyright and
+license notices just after the title page:
+
+    Copyright (c)  YEAR  YOUR NAME.
+    Permission is granted to copy, distribute and/or modify this document
+    under the terms of the GNU Free Documentation License, Version 1.2
+    or any later version published by the Free Software Foundation;
+    with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
+    A copy of the license is included in the section entitled "GNU
+    Free Documentation License".
+
+If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
+replace the "with...Texts." line with this:
+
+    with the Invariant Sections being LIST THEIR TITLES, with the
+    Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
+
+If you have Invariant Sections without Cover Texts, or some other
+combination of the three, merge those two alternatives to suit the
+situation.
+
+If your document contains nontrivial examples of program code, we
+recommend releasing these examples in parallel under your choice of
+free software license, such as the GNU General Public License,
+to permit their use in free software.
diff --git a/FLAC/COPYING.GPL b/FLAC/COPYING.GPL
new file mode 100644 (file)
index 0000000..d159169
--- /dev/null
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/FLAC/COPYING.LGPL b/FLAC/COPYING.LGPL
new file mode 100644 (file)
index 0000000..5ab7695
--- /dev/null
@@ -0,0 +1,504 @@
+                 GNU LESSER GENERAL PUBLIC LICENSE
+                      Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+                 GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                           NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/FLAC/COPYING.Xiph b/FLAC/COPYING.Xiph
new file mode 100644 (file)
index 0000000..d8295f0
--- /dev/null
@@ -0,0 +1,29 @@
+Copyright (C) 2000-2009  Josh Coalson
+Copyright (C) 2011-2016  Xiph.Org Foundation
+
+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.
diff --git a/FLAC/README b/FLAC/README
new file mode 100644 (file)
index 0000000..dd5e6e7
--- /dev/null
@@ -0,0 +1,254 @@
+/* FLAC - Free Lossless Audio Codec
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * This file is part the FLAC project.  FLAC is comprised of several
+ * components distributed under different licenses.  The codec libraries
+ * are distributed under Xiph.Org's BSD-like license (see the file
+ * COPYING.Xiph in this distribution).  All other programs, libraries, and
+ * plugins are distributed under the LGPL or GPL (see COPYING.LGPL and
+ * COPYING.GPL).  The documentation is distributed under the Gnu FDL (see
+ * COPYING.FDL).  Each file in the FLAC distribution contains at the top the
+ * terms under which it may be distributed.
+ *
+ * Since this particular file is relevant to all components of FLAC,
+ * it may be distributed under the Xiph.Org license, which is the least
+ * restrictive of those mentioned above.  See the file COPYING.Xiph in this
+ * distribution.
+ */
+
+
+FLAC is an Open Source lossless audio codec developed by Josh Coalson from 2001
+to 2009.
+
+From January 2012 FLAC is being maintained by Erik de Castro Lopo under the
+auspices of the Xiph.org Foundation.
+
+FLAC is comprised of
+  * `libFLAC', a library which implements reference encoders and
+    decoders for native FLAC and Ogg FLAC, and a metadata interface
+  * `libFLAC++', a C++ object wrapper library around libFLAC
+  * `flac', a command-line program for encoding and decoding files
+  * `metaflac', a command-line program for viewing and editing FLAC
+    metadata
+  * player plugin for XMMS
+  * user and API documentation
+
+The libraries (libFLAC, libFLAC++) are
+licensed under Xiph.org's BSD-like license (see COPYING.Xiph).  All other
+programs and plugins are licensed under the GNU General Public License
+(see COPYING.GPL).  The documentation is licensed under the GNU Free
+Documentation License (see COPYING.FDL).
+
+
+===============================================================================
+FLAC - 1.3.2 - Contents
+===============================================================================
+
+- Introduction
+- Prerequisites
+- Note to embedded developers
+- Building in a GNU environment
+- Building with Makefile.lite
+- Building with MSVC
+- Building on Mac OS X
+
+
+===============================================================================
+Introduction
+===============================================================================
+
+This is the source release for the FLAC project.  See
+
+       doc/html/index.html
+
+for full documentation.
+
+A brief description of the directory tree:
+
+       doc/          the HTML documentation
+       examples/     example programs demonstrating the use of libFLAC and libFLAC++
+       include/      public include files for libFLAC and libFLAC++
+       man/          the man pages for `flac' and `metaflac'
+       src/          the source code and private headers
+       test/         the test scripts
+
+If you have questions about building FLAC that this document does not answer,
+please submit them at the following tracker so this document can be improved:
+
+       https://sourceforge.net/p/flac/support-requests/
+
+
+===============================================================================
+Prerequisites
+===============================================================================
+
+To build FLAC with support for Ogg FLAC you must have built and installed
+libogg according to the specific instructions below.  You must have
+libogg 1.1.2 or greater, or there will be seeking problems with Ogg FLAC.
+
+If you are building on x86 and want the assembly optimizations, you will
+need to have NASM >= 0.98.30 installed according to the specific instructions
+below.
+
+
+===============================================================================
+Note to embedded developers
+===============================================================================
+
+libFLAC has grown larger over time as more functionality has been
+included, but much of it may be unnecessary for a particular embedded
+implementation.  Unused parts may be pruned by some simple editing of
+configure.ac and src/libFLAC/Makefile.am; the following dependency
+graph shows which modules may be pruned without breaking things
+further down:
+
+metadata.h
+       stream_decoder.h
+       format.h
+
+stream_encoder.h
+       stream_decoder.h
+       format.h
+
+stream_decoder.h
+       format.h
+
+In other words, for pure decoding applications, both the stream encoder
+and metadata editing interfaces can be safely removed.
+
+There is a section dedicated to embedded use in the libFLAC API
+HTML documentation (see doc/html/api/index.html).
+
+Also, there are several places in the libFLAC code with comments marked
+with "OPT:" where a #define can be changed to enable code that might be
+faster on a specific platform.  Experimenting with these can yield faster
+binaries.
+
+
+===============================================================================
+Building in a GNU environment
+===============================================================================
+
+FLAC uses autoconf and libtool for configuring and building.
+Better documentation for these will be forthcoming, but in
+general, this should work:
+
+./configure && make && make check && make install
+
+The 'make check' step is optional; omit it to skip all the tests,
+which can take several hours and use around 70-80 megs of disk space.
+Even though it will stop with an explicit message on any failure, it
+does print out a lot of stuff so you might want to capture the output
+to a file if you're having a problem.  Also, don't run 'make check'
+as root because it confuses some of the tests.
+
+NOTE: Despite our best efforts it's entirely possible to have
+problems when using older versions of autoconf, automake, or
+libtool.  If you have the latest versions and still can't get it
+to work, see the next section on Makefile.lite.
+
+There are a few FLAC-specific arguments you can give to
+`configure':
+
+--enable-debug : Builds everything with debug symbols and some
+extra (and more verbose) error checking.
+
+--disable-asm-optimizations : Disables the compilation of the
+assembly routines.  Many routines have assembly versions for
+speed and `configure' is pretty good about knowing what is
+supported, but you can use this option to build only from the
+C sources.  May be necessary for building on OS X (Intel).
+
+--enable-sse : If you are building for an x86 CPU that supports
+SSE instructions, you can enable some of the faster routines
+if your operating system also supports SSE instructions.  flac
+can tell if the CPU supports the instructions but currently has
+no way to test if the OS does, so if it does, you must pass
+this argument to configure to use the SSE routines.  If flac
+crashes when built with this option you will have to go back and
+configure without --enable-sse.  Note that
+--disable-asm-optimizations implies --disable-sse.
+
+--enable-local-xmms-plugin : Installs the FLAC XMMS plugin in
+$HOME/.xmms/Plugins, instead of the global XMMS plugin area
+(usually /usr/lib/xmms/Input).
+
+--with-ogg=
+--with-xmms-prefix=
+--with-libiconv-prefix=
+Use these if you have these packages but configure can't find them.
+
+If you want to build completely from scratch (i.e. starting with just
+configure.ac and Makefile.am) you should be able to just run 'autogen.sh'
+but make sure and read the comments in that file first.
+
+
+===============================================================================
+Building with Makefile.lite
+===============================================================================
+
+There is a more lightweight build system for do-it-yourself-ers.
+It is also useful if configure isn't working, which may be the
+case since lately we've had some problems with different versions
+of automake and libtool.  The Makefile.lite system should work
+on GNU systems with few or no adjustments.
+
+From the top level just 'make -f Makefile.lite'.  You can
+specify zero or one optional target from 'release', 'debug',
+'test', or 'clean'.  The default is 'release'.  There is no
+'install' target but everything you need will end up in the
+obj/ directory.
+
+If you are not on an x86 system or you don't have nasm, you
+may have to change the DEFINES in src/libFLAC/Makefile.lite.  If
+you don't have nasm, remove -DFLAC__HAS_NASM.  If your target is
+not an x86, change -DFLAC__CPU_IA32 to -DFLAC__CPU_UNKNOWN.
+
+
+===============================================================================
+Building with MSVC
+===============================================================================
+
+There are .vcproj projects and a master FLAC.sln solution to build all
+the libraries and executables with MSVC 2005 or newer.
+
+Prerequisite: you must have the Ogg libraries installed as described
+later.
+
+Prerequisite: you must have nasm installed, and nasm.exe must be in
+your PATH, or the path to nasm.exe must be added to the list of
+directories for executable files in the MSVC global options.
+
+To build everything, run Visual Studio, do File|Open and open FLAC.sln.
+From the dropdown in the toolbar, select "Release" instead of "Debug",
+then do Build|Build Solution.
+
+This will build all libraries both statically (e.g.
+objs\release\lib\libFLAC_static.lib) and as DLLs (e.g.
+objs\release\lib\libFLAC.dll), and it will build all binaries, statically
+linked (e.g. objs\release\bin\flac.exe).
+
+Everything will end up in the "objs" directory.  DLLs and .exe files
+are all that are needed and can be copied to an installation area and
+added to the PATH.
+
+By default the code is configured with Ogg support. Before building FLAC
+you will need to get the Ogg source distribution
+(see http://xiph.org/downloads/), build libogg_static.lib (load
+win32\libogg_static.sln, change solution configuration to "Release" and
+code generation to "Multi-threaded (/MT)", then build), copy libogg_static.lib
+into FLAC's 'objs\release\lib' directory, and copy the entire include\ogg tree
+into FLAC's 'include' directory (so that there is an 'ogg' directory in FLAC's
+'include' directory with the files ogg.h, os_types.h and config_types.h).
+
+If you want to build without Ogg support, instead edit all .vcproj files
+and remove any "FLAC__HAS_OGG" definitions.
+
+
+===============================================================================
+Building on Mac OS X
+===============================================================================
+
+If you have Fink or a recent version of OS X with the proper autotools,
+the GNU flow above should work.
diff --git a/FLAC/file_decoder.h b/FLAC/file_decoder.h
deleted file mode 100644 (file)
index 3e5c721..0000000
+++ /dev/null
@@ -1,648 +0,0 @@
-/* libFLAC - Free Lossless Audio Codec library
- * Copyright (C) 2000,2001,2002,2003  Josh Coalson
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA  02111-1307, USA.
- */
-
-#ifndef FLAC__FILE_DECODER_H
-#define FLAC__FILE_DECODER_H
-
-#include "export.h"
-#include "seekable_stream_decoder.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/** \file include/FLAC/file_decoder.h
- *
- *  \brief
- *  This module contains the functions which implement the file
- *  decoder.
- *
- *  See the detailed documentation in the
- *  \link flac_file_decoder file decoder \endlink module.
- */
-
-/** \defgroup flac_file_decoder FLAC/file_decoder.h: file decoder interface
- *  \ingroup flac_decoder
- *
- *  \brief
- *  This module contains the functions which implement the file
- *  decoder.
- *
- * The basic usage of this decoder is as follows:
- * - The program creates an instance of a decoder using
- *   FLAC__file_decoder_new().
- * - The program overrides the default settings and sets callbacks for
- *   writing, error reporting, and metadata reporting using
- *   FLAC__file_decoder_set_*() functions.
- * - The program initializes the instance to validate the settings and
- *   prepare for decoding using FLAC__file_decoder_init().
- * - The program calls the FLAC__file_decoder_process_*() functions
- *   to decode data, which subsequently calls the callbacks.
- * - The program finishes the decoding with FLAC__file_decoder_finish(),
- *   which flushes the input and output and resets the decoder to the
- *   uninitialized state.
- * - The instance may be used again or deleted with
- *   FLAC__file_decoder_delete().
- *
- * The file decoder is a trivial wrapper around the
- * \link flac_seekable_stream_decoder seekable stream decoder \endlink
- * meant to simplfy the process of decoding from a standard file.  The
- * file decoder supplies all but the Write/Metadata/Error callbacks.
- * The user needs only to provide the path to the file and the file
- * decoder handles the rest.
- *
- * Like the seekable stream decoder, seeking is exposed through the
- * FLAC__file_decoder_seek_absolute() method.  At any point after the file
- * decoder has been initialized, the user can call this function to seek to
- * an exact sample within the file.  Subsequently, the first time the write
- * callback is called it will be passed a (possibly partial) block starting
- * at that sample.
- *
- * The file decoder also inherits MD5 signature checking from the seekable
- * stream decoder.  If this is turned on before initialization,
- * FLAC__file_decoder_finish() will report when the decoded MD5 signature
- * does not match the one stored in the STREAMINFO block.  MD5 checking is
- * automatically turned off if there is no signature in the STREAMINFO
- * block or when a seek is attempted.
- *
- * Make sure to read the detailed descriptions of the
- * \link flac_seekable_stream_decoder seekable stream decoder module \endlink
- * and \link flac_stream_decoder stream decoder module \endlink
- * since the file decoder inherits much of its behavior from them.
- *
- * \note
- * The "set" functions may only be called when the decoder is in the
- * state FLAC__FILE_DECODER_UNINITIALIZED, i.e. after
- * FLAC__file_decoder_new() or FLAC__file_decoder_finish(), but
- * before FLAC__file_decoder_init().  If this is the case they will
- * return \c true, otherwise \c false.
- *
- * \note
- * FLAC__file_decoder_finish() resets all settings to the constructor
- * defaults, including the callbacks.
- *
- * \{
- */
-
-
-/** State values for a FLAC__FileDecoder
- *
- *  The decoder's state can be obtained by calling FLAC__file_decoder_get_state().
- */
-typedef enum {
-
-       FLAC__FILE_DECODER_OK = 0,
-       /**< The decoder is in the normal OK state. */
-
-       FLAC__FILE_DECODER_END_OF_FILE,
-       /**< The decoder has reached the end of the file. */
-
-       FLAC__FILE_DECODER_ERROR_OPENING_FILE,
-       /**< An error occurred opening the input file. */
-
-       FLAC__FILE_DECODER_MEMORY_ALLOCATION_ERROR,
-       /**< An error occurred allocating memory. */
-
-       FLAC__FILE_DECODER_SEEK_ERROR,
-       /**< An error occurred while seeking. */
-
-       FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR,
-       /**< An error occurred in the underlying seekable stream decoder. */
-
-       FLAC__FILE_DECODER_ALREADY_INITIALIZED,
-       /**< FLAC__file_decoder_init() was called when the decoder was already
-        * initialized, usually because FLAC__file_decoder_finish() was not
-        * called.
-        */
-
-       FLAC__FILE_DECODER_INVALID_CALLBACK,
-       /**< FLAC__file_decoder_init() was called without all callbacks
-        * being set.
-        */
-
-       FLAC__FILE_DECODER_UNINITIALIZED
-       /**< The decoder is in the uninitialized state. */
-
-} FLAC__FileDecoderState;
-
-/** Maps a FLAC__FileDecoderState to a C string.
- *
- *  Using a FLAC__FileDecoderState as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__FileDecoderStateString[];
-
-
-/***********************************************************************
- *
- * class FLAC__FileDecoder : public FLAC__StreamDecoder
- *
- ***********************************************************************/
-
-struct FLAC__FileDecoderProtected;
-struct FLAC__FileDecoderPrivate;
-/** The opaque structure definition for the file decoder type.  See the
- *  \link flac_file_decoder file decoder module \endlink for a detailed
- *  description.
- */
-typedef struct {
-       struct FLAC__FileDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
-       struct FLAC__FileDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
-} FLAC__FileDecoder;
-
-/** Signature for the write callback.
- *  See FLAC__file_decoder_set_write_callback()
- *  and FLAC__SeekableStreamDecoderWriteCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  frame    The description of the decoded frame.
- * \param  buffer   An array of pointers to decoded channels of data.
- * \param  client_data  The callee's client data set through
- *                      FLAC__file_decoder_set_client_data().
- * \retval FLAC__StreamDecoderWriteStatus
- *    The callee's return status.
- */
-typedef FLAC__StreamDecoderWriteStatus (*FLAC__FileDecoderWriteCallback)(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
-
-/** Signature for the metadata callback.
- *  See FLAC__file_decoder_set_metadata_callback()
- *  and FLAC__SeekableStreamDecoderMetadataCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  metadata The decoded metadata block.
- * \param  client_data  The callee's client data set through
- *                      FLAC__file_decoder_set_client_data().
- */
-typedef void (*FLAC__FileDecoderMetadataCallback)(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
-
-/** Signature for the error callback.
- *  See FLAC__file_decoder_set_error_callback()
- *  and FLAC__SeekableStreamDecoderErrorCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  status   The error encountered by the decoder.
- * \param  client_data  The callee's client data set through
- *                      FLAC__file_decoder_set_client_data().
- */
-typedef void (*FLAC__FileDecoderErrorCallback)(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
-
-
-/***********************************************************************
- *
- * Class constructor/destructor
- *
- ***********************************************************************/
-
-/** Create a new file decoder instance.  The instance is created with
- *  default settings; see the individual FLAC__file_decoder_set_*()
- *  functions for each setting's default.
- *
- * \retval FLAC__FileDecoder*
- *    \c NULL if there was an error allocating memory, else the new instance.
- */
-FLAC_API FLAC__FileDecoder *FLAC__file_decoder_new();
-
-/** Free a decoder instance.  Deletes the object pointed to by \a decoder.
- *
- * \param decoder  A pointer to an existing decoder.
- * \assert
- *    \code decoder != NULL \endcode
- */
-FLAC_API void FLAC__file_decoder_delete(FLAC__FileDecoder *decoder);
-
-
-/***********************************************************************
- *
- * Public class method prototypes
- *
- ***********************************************************************/
-
-/** Set the "MD5 signature checking" flag.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_md5_checking().
- *
- * \default \c false
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_md5_checking(FLAC__FileDecoder *decoder, FLAC__bool value);
-
-/** Set the input file name to decode.
- *
- * \default \c "-"
- * \param  decoder  A decoder instance to set.
- * \param  value    The input file name, or "-" for \c stdin.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, or there was a memory
- *    allocation error, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_filename(FLAC__FileDecoder *decoder, const char *value);
-
-/** Set the write callback.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_write_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_write_callback(FLAC__FileDecoder *decoder, FLAC__FileDecoderWriteCallback value);
-
-/** Set the metadata callback.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_callback(FLAC__FileDecoder *decoder, FLAC__FileDecoderMetadataCallback value);
-
-/** Set the error callback.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_error_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_error_callback(FLAC__FileDecoder *decoder, FLAC__FileDecoderErrorCallback value);
-
-/** Set the client data to be passed back to callbacks.
- *  This value will be supplied to callbacks in their \a client_data
- *  argument.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_client_data(FLAC__FileDecoder *decoder, void *value);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_respond().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  type     See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \a type is valid
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_respond(FLAC__FileDecoder *decoder, FLAC__MetadataType type);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_respond_application().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  id       See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code id != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_respond_application(FLAC__FileDecoder *decoder, const FLAC__byte id[4]);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_respond_all().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_respond_all(FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_ignore().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  type     See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \a type is valid
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_ignore(FLAC__FileDecoder *decoder, FLAC__MetadataType type);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_ignore_application().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  id       See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code id != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_ignore_application(FLAC__FileDecoder *decoder, const FLAC__byte id[4]);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_set_metadata_ignore_all().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_set_metadata_ignore_all(FLAC__FileDecoder *decoder);
-
-/** Get the current decoder state.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__FileDecoderState
- *    The current decoder state.
- */
-FLAC_API FLAC__FileDecoderState FLAC__file_decoder_get_state(const FLAC__FileDecoder *decoder);
-
-/** Get the state of the underlying seekable stream decoder.
- *  Useful when the file decoder state is
- *  \c FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__SeekableStreamDecoderState
- *    The seekable stream decoder state.
- */
-FLAC_API FLAC__SeekableStreamDecoderState FLAC__file_decoder_get_seekable_stream_decoder_state(const FLAC__FileDecoder *decoder);
-
-/** Get the state of the underlying stream decoder.
- *  Useful when the file decoder state is
- *  \c FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR and the seekable stream
- *  decoder state is \c FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__StreamDecoderState
- *    The seekable stream decoder state.
- */
-FLAC_API FLAC__StreamDecoderState FLAC__file_decoder_get_stream_decoder_state(const FLAC__FileDecoder *decoder);
-
-/** Get the current decoder state as a C string.
- *  This version automatically resolves
- *  \c FLAC__FILE_DECODER_SEEKABLE_STREAM_DECODER_ERROR by getting the
- *  seekable stream decoder's state.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval const char *
- *    The decoder state as a C string.  Do not modify the contents.
- */
-FLAC_API const char *FLAC__file_decoder_get_resolved_state_string(const FLAC__FileDecoder *decoder);
-
-/** Get the "MD5 signature checking" flag.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_md5_checking().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_get_md5_checking(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_channels().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__file_decoder_get_channels(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_channel_assignment().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__ChannelAssignment
- *    See above.
- */
-FLAC_API FLAC__ChannelAssignment FLAC__file_decoder_get_channel_assignment(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_bits_per_sample().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__file_decoder_get_bits_per_sample(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_sample_rate().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__file_decoder_get_sample_rate(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_blocksize().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__file_decoder_get_blocksize(const FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_get_decode_position().
- *
- * \param  decoder   A decoder instance to query.
- * \param  position  Address at which to return the desired position.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code position != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, \c false if there was an error from
- *    the 'tell' callback.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_get_decode_position(const FLAC__FileDecoder *decoder, FLAC__uint64 *position);
-
-/** Initialize the decoder instance.
- *  Should be called after FLAC__file_decoder_new() and
- *  FLAC__file_decoder_set_*() but before any of the
- *  FLAC__file_decoder_process_*() functions.  Will set and return
- *  the decoder state, which will be FLAC__FILE_DECODER_OK if
- *  initialization succeeded.
- *
- * \param  decoder  An uninitialized decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__FileDecoderState
- *    \c FLAC__FILE_DECODER_OK if initialization was successful; see
- *    FLAC__FileDecoderState for the meanings of other return values.
- */
-FLAC_API FLAC__FileDecoderState FLAC__file_decoder_init(FLAC__FileDecoder *decoder);
-
-/** Finish the decoding process.
- *  Flushes the decoding buffer, releases resources, resets the decoder
- *  settings to their defaults, and returns the decoder state to
- *  FLAC__FILE_DECODER_UNINITIALIZED.
- *
- *  In the event of a prematurely-terminated decode, it is not strictly
- *  necessary to call this immediately before FLAC__file_decoder_delete()
- *  but it is good practice to match every FLAC__file_decoder_init() with
- *  a FLAC__file_decoder_finish().
- *
- * \param  decoder  An uninitialized decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if MD5 checking is on AND a STREAMINFO block was available
- *    AND the MD5 signature in the STREAMINFO block was non-zero AND the
- *    signature does not match the one computed by the decoder; else
- *    \c true.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_finish(FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_process_single().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_process_single(FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_process_until_end_of_metadata().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_process_until_end_of_metadata(FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_process_until_end_of_stream().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_process_until_end_of_file(FLAC__FileDecoder *decoder);
-
-/** This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_process_remaining_frames().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_process_remaining_frames(FLAC__FileDecoder *decoder);
-
-/** Flush the input and seek to an absolute sample.
- *  This is inherited from FLAC__SeekableStreamDecoder; see
- *  FLAC__seekable_stream_decoder_seek_absolute().
- *
- * \param  decoder  A decoder instance.
- * \param  sample   The target sample number to seek to.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false.
- */
-FLAC_API FLAC__bool FLAC__file_decoder_seek_absolute(FLAC__FileDecoder *decoder, FLAC__uint64 sample);
-
-/* \} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/FLAC/file_encoder.h b/FLAC/file_encoder.h
deleted file mode 100644 (file)
index ac222fe..0000000
+++ /dev/null
@@ -1,859 +0,0 @@
-/* libFLAC - Free Lossless Audio Codec library
- * Copyright (C) 2002,2003  Josh Coalson
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA  02111-1307, USA.
- */
-
-#ifndef FLAC__FILE_ENCODER_H
-#define FLAC__FILE_ENCODER_H
-
-#include "export.h"
-#include "seekable_stream_encoder.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/** \file include/FLAC/file_encoder.h
- *
- *  \brief
- *  This module contains the functions which implement the file
- *  encoder.
- *
- *  See the detailed documentation in the
- *  \link flac_file_encoder file encoder \endlink module.
- */
-
-/** \defgroup flac_file_encoder FLAC/file_encoder.h: file encoder interface
- *  \ingroup flac_encoder
- *
- *  \brief
- *  This module contains the functions which implement the file
- *  encoder.
- *
- * The basic usage of this encoder is as follows:
- * - The program creates an instance of an encoder using
- *   FLAC__file_encoder_new().
- * - The program overrides the default settings using
- *   FLAC__file_encoder_set_*() functions.
- * - The program initializes the instance to validate the settings and
- *   prepare for encoding using FLAC__file_encoder_init().
- * - The program calls FLAC__file_encoder_process() or
- *   FLAC__file_encoder_process_interleaved() to encode data, which
- *   subsequently writes data to the output file.
- * - The program finishes the encoding with FLAC__file_encoder_finish(),
- *   which causes the encoder to encode any data still in its input pipe,
- *   rewind and write the STREAMINFO metadata to file, and finally reset
- *   the encoder to the uninitialized state.
- * - The instance may be used again or deleted with
- *   FLAC__file_encoder_delete().
- *
- * The file encoder is a wrapper around the
- * \link flac_seekable_stream_encoder seekable stream encoder \endlink which supplies all
- * callbacks internally; the user need specify only the filename.
- *
- * Make sure to read the detailed description of the
- * \link flac_seekable_stream_encoder seekable stream encoder module \endlink since the
- * \link flac_stream_encoder stream encoder module \endlink since the
- * file encoder inherits much of its behavior from them.
- *
- * \note
- * The "set" functions may only be called when the encoder is in the
- * state FLAC__FILE_ENCODER_UNINITIALIZED, i.e. after
- * FLAC__file_encoder_new() or FLAC__file_encoder_finish(), but
- * before FLAC__file_encoder_init().  If this is the case they will
- * return \c true, otherwise \c false.
- *
- * \note
- * FLAC__file_encoder_finish() resets all settings to the constructor
- * defaults.
- *
- * \{
- */
-
-
-/** State values for a FLAC__FileEncoder
- *
- *  The encoder's state can be obtained by calling FLAC__file_encoder_get_state().
- */
-typedef enum {
-
-       FLAC__FILE_ENCODER_OK = 0,
-       /**< The encoder is in the normal OK state. */
-
-       FLAC__FILE_ENCODER_NO_FILENAME,
-       /**< FLAC__file_encoder_init() was called without first calling
-        * FLAC__file_encoder_set_filename().
-        */
-
-       FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR,
-       /**< An error occurred in the underlying seekable stream encoder;
-        * check FLAC__file_encoder_get_seekable_stream_encoder_state().
-        */
-
-       FLAC__FILE_ENCODER_FATAL_ERROR_WHILE_WRITING,
-       /**< A fatal error occurred while writing to the encoded file. */
-
-       FLAC__FILE_ENCODER_ERROR_OPENING_FILE,
-       /**< An error occurred opening the output file for writing. */
-
-       FLAC__FILE_ENCODER_MEMORY_ALLOCATION_ERROR,
-       /**< Memory allocation failed. */
-
-       FLAC__FILE_ENCODER_ALREADY_INITIALIZED,
-       /**< FLAC__file_encoder_init() was called when the encoder was
-        * already initialized, usually because
-        * FLAC__file_encoder_finish() was not called.
-        */
-
-       FLAC__FILE_ENCODER_UNINITIALIZED
-       /**< The encoder is in the uninitialized state. */
-
-} FLAC__FileEncoderState;
-
-/** Maps a FLAC__FileEncoderState to a C string.
- *
- *  Using a FLAC__FileEncoderState as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__FileEncoderStateString[];
-
-
-/***********************************************************************
- *
- * class FLAC__FileEncoder
- *
- ***********************************************************************/
-
-struct FLAC__FileEncoderProtected;
-struct FLAC__FileEncoderPrivate;
-/** The opaque structure definition for the file encoder type.
- *  See the \link flac_file_encoder file encoder module \endlink
- *  for a detailed description.
- */
-typedef struct {
-       struct FLAC__FileEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
-       struct FLAC__FileEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
-} FLAC__FileEncoder;
-
-/** Signature for the progress callback.
- *  See FLAC__file_encoder_set_progress_callback() for more info.
- *
- * \param  encoder          The encoder instance calling the callback.
- * \param  bytes_written    Bytes written so far.
- * \param  samples_written  Samples written so far.
- * \param  frames_written   Frames written so far.
- * \param  total_frames_estimate  The estimate of the total number of
- *                                frames to be written.
- * \param  client_data      The callee's client data set through
- *                          FLAC__file_encoder_set_client_data().
- */
-typedef void (*FLAC__FileEncoderProgressCallback)(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
-
-
-/***********************************************************************
- *
- * Class constructor/destructor
- *
- ***********************************************************************/
-
-/** Create a new file encoder instance.  The instance is created with
- *  default settings; see the individual FLAC__file_encoder_set_*()
- *  functions for each setting's default.
- *
- * \retval FLAC__FileEncoder*
- *    \c NULL if there was an error allocating memory, else the new instance.
- */
-FLAC_API FLAC__FileEncoder *FLAC__file_encoder_new();
-
-/** Free an encoder instance.  Deletes the object pointed to by \a encoder.
- *
- * \param encoder  A pointer to an existing encoder.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__file_encoder_delete(FLAC__FileEncoder *encoder);
-
-/***********************************************************************
- *
- * Public class method prototypes
- *
- ***********************************************************************/
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_verify().
- *
- * \default \c true
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_verify(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_streamable_subset().
- *
- * \default \c true
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_streamable_subset(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_do_mid_side_stereo().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_do_mid_side_stereo(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_loose_mid_side_stereo().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_loose_mid_side_stereo(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_channels().
- *
- * \default \c 2
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_channels(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_bits_per_sample().
- *
- * \warning
- * Do not feed the encoder data that is wider than the value you
- * set here or you will generate an invalid stream.
- *
- * \default \c 16
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_bits_per_sample(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_sample_rate().
- *
- * \default \c 44100
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_sample_rate(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_blocksize().
- *
- * \default \c 1152
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_blocksize(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_max_lpc_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_max_lpc_order(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_qlp_coeff_precision().
- *
- * \note
- * In the current implementation, qlp_coeff_precision + bits_per_sample must
- * be less than 32.
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_qlp_coeff_precision(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_do_qlp_coeff_prec_search().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_do_qlp_coeff_prec_search(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_do_escape_coding().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_do_escape_coding(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_do_exhaustive_model_search().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_do_exhaustive_model_search(FLAC__FileEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_min_residual_partition_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_min_residual_partition_order(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_max_residual_partition_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_max_residual_partition_order(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_rice_parameter_search_dist().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_rice_parameter_search_dist(FLAC__FileEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_total_samples_estimate().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_total_samples_estimate(FLAC__FileEncoder *encoder, FLAC__uint64 value);
-
-/** This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_set_metadata().
- *
- * \default \c NULL, 0
- * \param  encoder     An encoder instance to set.
- * \param  metadata    See above.
- * \param  num_blocks  See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_metadata(FLAC__FileEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
-
-/** Set the output file name encode to.
- *
- * \note
- * The filename is mandatory and must be set before initialization.
- *
- * \note
- * Unlike the FLAC__FileDecoder, the filename does not interpret "-" for
- * \c stdout; writing to \c stdout is not relevant in the file encoder.
- *
- * \default \c NULL
- * \param  encoder  A encoder instance to set.
- * \param  value    The output file name.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, or there was a memory
- *    allocation error, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_filename(FLAC__FileEncoder *encoder, const char *value);
-
-/** Set the progress callback.
- *  The supplied function will be called when the encoder has finished
- *  writing a frame.  The \c total_frames_estimate argument to the callback
- *  will be based on the value from
- *  FLAC__file_encoder_set_total_samples_estimate().
- *
- * \note
- * Unlike most other callbacks, the progress callback is \b not mandatory
- * and need not be set before initialization.
- *
- * \default \c NULL
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_progress_callback(FLAC__FileEncoder *encoder, FLAC__FileEncoderProgressCallback value);
-
-/** Set the client data to be passed back to callbacks.
- *  This value will be supplied to callbacks in their \a client_data
- *  argument.
- *
- * \default \c NULL
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_set_client_data(FLAC__FileEncoder *encoder, void *value);
-
-/** Get the current encoder state.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__FileEncoderState
- *    The current encoder state.
- */
-FLAC_API FLAC__FileEncoderState FLAC__file_encoder_get_state(const FLAC__FileEncoder *encoder);
-
-/** Get the state of the underlying seekable stream encoder.
- *  Useful when the file encoder state is
- *  \c FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__SeekableStreamEncoderState
- *    The seekable stream encoder state.
- */
-FLAC_API FLAC__SeekableStreamEncoderState FLAC__file_encoder_get_seekable_stream_encoder_state(const FLAC__FileEncoder *encoder);
-
-/** Get the state of the underlying stream encoder.
- *  Useful when the file encoder state is
- *  \c FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR and the seekable stream
- *  encoder state is \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__StreamEncoderState
- *    The seekable stream encoder state.
- */
-FLAC_API FLAC__StreamEncoderState FLAC__file_encoder_get_stream_encoder_state(const FLAC__FileEncoder *encoder);
-
-/** Get the state of the underlying stream encoder's verify decoder.
- *  Useful when the file encoder state is
- *  \c FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR and the seekable stream
- *  encoder state is \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR and
- *  the stream encoder state is \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__StreamDecoderState
- *    The stream encoder state.
- */
-FLAC_API FLAC__StreamDecoderState FLAC__file_encoder_get_verify_decoder_state(const FLAC__FileEncoder *encoder);
-
-/** Get the current encoder state as a C string.
- *  This version automatically resolves
- *  \c FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR by getting the
- *  seekable stream encoder's state.
- *
- * \param  encoder  A encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval const char *
- *    The encoder state as a C string.  Do not modify the contents.
- */
-FLAC_API const char *FLAC__file_encoder_get_resolved_state_string(const FLAC__FileEncoder *encoder);
-
-/** Get relevant values about the nature of a verify decoder error.
- *  Inherited from FLAC__seekable_stream_encoder_get_verify_decoder_error_stats().
- *  Useful when the file encoder state is
- *  \c FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR and the seekable stream
- *  encoder state is
- *  \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR and the
- *  stream encoder state is
- *  \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \param  absolute_sample  The absolute sample number of the mismatch.
- * \param  frame_number  The number of the frame in which the mismatch occurred.
- * \param  channel       The channel in which the mismatch occurred.
- * \param  sample        The number of the sample (relative to the frame) in
- *                       which the mismatch occurred.
- * \param  expected      The expected value for the sample in question.
- * \param  got           The actual value returned by the decoder.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__file_encoder_get_verify_decoder_error_stats(const FLAC__FileEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
-
-/** Get the "verify" flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_verify().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_verify().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_verify(const FLAC__FileEncoder *encoder);
-
-/** Get the "streamable subset" flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_streamable_subset().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_streamable_subset().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_streamable_subset(const FLAC__FileEncoder *encoder);
-
-/** Get the "mid/side stereo coding" flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_do_mid_side_stereo().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_get_do_mid_side_stereo().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_do_mid_side_stereo(const FLAC__FileEncoder *encoder);
-
-/** Get the "adaptive mid/side switching" flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_loose_mid_side_stereo().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_loose_mid_side_stereo().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_loose_mid_side_stereo(const FLAC__FileEncoder *encoder);
-
-/** Get the number of input channels being processed.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_channels().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_channels().
- */
-FLAC_API unsigned FLAC__file_encoder_get_channels(const FLAC__FileEncoder *encoder);
-
-/** Get the input sample resolution setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_bits_per_sample().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_bits_per_sample().
- */
-FLAC_API unsigned FLAC__file_encoder_get_bits_per_sample(const FLAC__FileEncoder *encoder);
-
-/** Get the input sample rate setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_sample_rate().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_sample_rate().
- */
-FLAC_API unsigned FLAC__file_encoder_get_sample_rate(const FLAC__FileEncoder *encoder);
-
-/** Get the blocksize setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_blocksize().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_blocksize().
- */
-FLAC_API unsigned FLAC__file_encoder_get_blocksize(const FLAC__FileEncoder *encoder);
-
-/** Get the maximum LPC order setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_max_lpc_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_max_lpc_order().
- */
-FLAC_API unsigned FLAC__file_encoder_get_max_lpc_order(const FLAC__FileEncoder *encoder);
-
-/** Get the quantized linear predictor coefficient precision setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_qlp_coeff_precision().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_qlp_coeff_precision().
- */
-FLAC_API unsigned FLAC__file_encoder_get_qlp_coeff_precision(const FLAC__FileEncoder *encoder);
-
-/** Get the qlp coefficient precision search flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_do_qlp_coeff_prec_search().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_do_qlp_coeff_prec_search().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_do_qlp_coeff_prec_search(const FLAC__FileEncoder *encoder);
-
-/** Get the "escape coding" flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_do_escape_coding().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_do_escape_coding().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_do_escape_coding(const FLAC__FileEncoder *encoder);
-
-/** Get the exhaustive model search flag.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_do_exhaustive_model_search().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__file_encoder_set_do_exhaustive_model_search().
- */
-FLAC_API FLAC__bool FLAC__file_encoder_get_do_exhaustive_model_search(const FLAC__FileEncoder *encoder);
-
-/** Get the minimum residual partition order setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_min_residual_partition_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_min_residual_partition_order().
- */
-FLAC_API unsigned FLAC__file_encoder_get_min_residual_partition_order(const FLAC__FileEncoder *encoder);
-
-/** Get maximum residual partition order setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_max_residual_partition_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_max_residual_partition_order().
- */
-FLAC_API unsigned FLAC__file_encoder_get_max_residual_partition_order(const FLAC__FileEncoder *encoder);
-
-/** Get the Rice parameter search distance setting.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_rice_parameter_search_dist().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__file_encoder_set_rice_parameter_search_dist().
- */
-FLAC_API unsigned FLAC__file_encoder_get_rice_parameter_search_dist(const FLAC__FileEncoder *encoder);
-
-/** Get the previously set estimate of the total samples to be encoded.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_get_total_samples_estimate().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__uint64
- *    See FLAC__file_encoder_set_total_samples_estimate().
- */
-FLAC_API FLAC__uint64 FLAC__file_encoder_get_total_samples_estimate(const FLAC__FileEncoder *encoder);
-
-/** Initialize the encoder instance.
- *  Should be called after FLAC__file_encoder_new() and
- *  FLAC__file_encoder_set_*() but before FLAC__file_encoder_process()
- *  or FLAC__file_encoder_process_interleaved().  Will set and return
- *  the encoder state, which will be FLAC__FILE_ENCODER_OK if
- *  initialization succeeded.
- *
- * \param  encoder  An uninitialized encoder instance.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__FileEncoderState
- *    \c FLAC__FILE_ENCODER_OK if initialization was successful; see
- *    FLAC__FileEncoderState for the meanings of other return values.
- */
-FLAC_API FLAC__FileEncoderState FLAC__file_encoder_init(FLAC__FileEncoder *encoder);
-
-/** Finish the encoding process.
- *  Flushes the encoding buffer, releases resources, resets the encoder
- *  settings to their defaults, and returns the encoder state to
- *  FLAC__FILE_ENCODER_UNINITIALIZED.
- *
- *  In the event of a prematurely-terminated encode, it is not strictly
- *  necessary to call this immediately before FLAC__file_encoder_delete()
- *  but it is good practice to match every FLAC__file_encoder_init()
- *  with a FLAC__file_encoder_finish().
- *
- * \param  encoder  An uninitialized encoder instance.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__file_encoder_finish(FLAC__FileEncoder *encoder);
-
-/** Submit data for encoding.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_process().
- *
- * \param  encoder  An initialized encoder instance in the OK state.
- * \param  buffer   An array of pointers to each channel's signal.
- * \param  samples  The number of samples in one channel.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code FLAC__file_encoder_get_state(encoder) == FLAC__FILE_ENCODER_OK \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false; in this case, check the
- *    encoder state with FLAC__file_encoder_get_state() to see what
- *    went wrong.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_process(FLAC__FileEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
-
-/** Submit data for encoding.
- *  This is inherited from FLAC__SeekableStreamEncoder; see
- *  FLAC__seekable_stream_encoder_process_interleaved().
- *
- * \param  encoder  An initialized encoder instance in the OK state.
- * \param  buffer   An array of channel-interleaved data (see above).
- * \param  samples  The number of samples in one channel, the same as for
- *                  FLAC__file_encoder_process().  For example, if
- *                  encoding two channels, \c 1000 \a samples corresponds
- *                  to a \a buffer of 2000 values.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code FLAC__file_encoder_get_state(encoder) == FLAC__FILE_ENCODER_OK \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false; in this case, check the
- *    encoder state with FLAC__file_encoder_get_state() to see what
- *    went wrong.
- */
-FLAC_API FLAC__bool FLAC__file_encoder_process_interleaved(FLAC__FileEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
-
-/* \} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
similarity index 99%
rename from FLAC/all.h
rename to FLAC/include/FLAC/all.h
index 9e28852..11d47d7 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * #endif
  * \endcode
  *
- * The the source will work for multiple versions and the legacy code can
+ * The source will work for multiple versions and the legacy code can
  * easily be removed when the transition is complete.
  *
  * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
similarity index 97%
rename from FLAC/assert.h
rename to FLAC/include/FLAC/assert.h
index 787cea9..b546fd0 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2001-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
similarity index 99%
rename from FLAC/callback.h
rename to FLAC/include/FLAC/callback.h
index 71bbaec..f942dd2 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2004-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
similarity index 96%
rename from FLAC/export.h
rename to FLAC/include/FLAC/export.h
index 2232b41..d52f0bb 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -61,9 +61,9 @@
 
 #elif defined(_MSC_VER)
 #ifdef FLAC_API_EXPORTS
-#define        FLAC_API        _declspec(dllexport)
+#define        FLAC_API __declspec(dllexport)
 #else
-#define FLAC_API       _declspec(dllimport)
+#define FLAC_API __declspec(dllimport)
 #endif
 
 #elif defined(FLAC__USE_VISIBILITY_ATTR)
similarity index 99%
rename from FLAC/format.h
rename to FLAC/include/FLAC/format.h
index e4c1c1a..c087d4a 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -509,9 +509,11 @@ typedef enum {
        FLAC__METADATA_TYPE_PICTURE = 6,
        /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
 
-       FLAC__METADATA_TYPE_UNDEFINED = 7
+       FLAC__METADATA_TYPE_UNDEFINED = 7,
        /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
 
+       FLAC__MAX_METADATA_TYPE = FLAC__MAX_METADATA_TYPE_CODE,
+       /**< No type will ever be greater than this. There is not enough room in the protocol block. */
 } FLAC__MetadataType;
 
 /** Maps a FLAC__MetadataType to a C string.
similarity index 99%
rename from FLAC/metadata.h
rename to FLAC/include/FLAC/metadata.h
index fcc8ed9..4e18cd6 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2001-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -500,7 +500,7 @@ FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const
  * \retval unsigned
  *    The length of the metadata block at the current iterator position.
  *    The is same length as that in the
- *    <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
+ *    <a href="http://xiph.org/flac/format.html#metadata_block_header">metadata block header</a>,
  *    i.e. the length of the metadata body that follows the header.
  */
 FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
@@ -667,7 +667,7 @@ FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_S
  *
  * - Create a new chain using FLAC__metadata_chain_new().  A chain is a
  *   linked list of FLAC metadata blocks.
- * - Read all metadata into the the chain from a FLAC file using
+ * - Read all metadata into the chain from a FLAC file using
  *   FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  *   check the status.
  * - Optionally, consolidate the padding using
@@ -764,7 +764,7 @@ typedef enum {
        FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
        /**< FLAC__metadata_chain_write() was called on a chain read by
         *   FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
-        *   or 
+        *   or
         *   FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
         *   was called on a chain read by
         *   FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
@@ -1692,7 +1692,7 @@ FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__Str
  *  For convenience, a trailing NUL is added to the entry if it doesn't have
  *  one already.
  *
- *  Depending on the the value of \a all, either all or just the first comment
+ *  Depending on the value of \a all, either all or just the first comment
  *  whose field name(s) match the given entry's name will be replaced by the
  *  given entry.  If no comments match, \a entry will simply be appended.
  *
similarity index 98%
rename from FLAC/ordinals.h
rename to FLAC/include/FLAC/ordinals.h
index a057299..ea52ea6 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
similarity index 99%
rename from FLAC/stream_decoder.h
rename to FLAC/include/FLAC/stream_decoder.h
index 152643f..39c958d 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -228,7 +228,7 @@ typedef enum {
         */
 
        FLAC__STREAM_DECODER_ABORTED,
-       /**< The decoder was aborted by the read callback. */
+       /**< The decoder was aborted by the read or write callback. */
 
        FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
        /**< An error occurred allocating memory.  The decoder is in an invalid
similarity index 95%
rename from FLAC/stream_encoder.h
rename to FLAC/include/FLAC/stream_encoder.h
index 6f7796b..40a2fd3 100644 (file)
@@ -1,6 +1,6 @@
 /* libFLAC - Free Lossless Audio Codec library
  * Copyright (C) 2000-2009  Josh Coalson
- * Copyright (C) 2011-2013  Xiph.Org Foundation
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -830,28 +830,28 @@ FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *en
  * The actual values set for each level are:
  * <table>
  * <tr>
- *  <td><b>level</b><td>
- *  <td>do mid-side stereo<td>
- *  <td>loose mid-side stereo<td>
- *  <td>apodization<td>
- *  <td>max lpc order<td>
- *  <td>qlp coeff precision<td>
- *  <td>qlp coeff prec search<td>
- *  <td>escape coding<td>
- *  <td>exhaustive model search<td>
- *  <td>min residual partition order<td>
- *  <td>max residual partition order<td>
- *  <td>rice parameter search dist<td>
+ *  <td><b>level</b></td>
+ *  <td>do mid-side stereo</td>
+ *  <td>loose mid-side stereo</td>
+ *  <td>apodization</td>
+ *  <td>max lpc order</td>
+ *  <td>qlp coeff precision</td>
+ *  <td>qlp coeff prec search</td>
+ *  <td>escape coding</td>
+ *  <td>exhaustive model search</td>
+ *  <td>min residual partition order</td>
+ *  <td>max residual partition order</td>
+ *  <td>rice parameter search dist</td>
  * </tr>
- * <tr>  <td><b>0</b><td>  <td>false<td>  <td>false<td>  <td>tukey(0.5)<td>  <td>0<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>3<td>  <td>0<td>  </tr>
- * <tr>  <td><b>1</b><td>  <td>true<td>   <td>true<td>   <td>tukey(0.5)<td>  <td>0<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>3<td>  <td>0<td>  </tr>
- * <tr>  <td><b>2</b><td>  <td>true<td>   <td>false<td>  <td>tukey(0.5)<td>  <td>0<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>3<td>  <td>0<td>  </tr>
- * <tr>  <td><b>3</b><td>  <td>false<td>  <td>false<td>  <td>tukey(0.5)<td>  <td>6<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>4<td>  <td>0<td>  </tr>
- * <tr>  <td><b>4</b><td>  <td>true<td>   <td>true<td>   <td>tukey(0.5)<td>  <td>8<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>4<td>  <td>0<td>  </tr>
- * <tr>  <td><b>5</b><td>  <td>true<td>   <td>false<td>  <td>tukey(0.5)<td>  <td>8<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>5<td>  <td>0<td>  </tr>
- * <tr>  <td><b>6</b><td>  <td>true<td>   <td>false<td>  <td>tukey(0.5)<td>  <td>8<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>false<td>  <td>0<td>  <td>6<td>  <td>0<td>  </tr>
- * <tr>  <td><b>7</b><td>  <td>true<td>   <td>false<td>  <td>tukey(0.5)<td>  <td>8<td>   <td>0<td>  <td>false<td>  <td>false<td>  <td>true<td>   <td>0<td>  <td>6<td>  <td>0<td>  </tr>
- * <tr>  <td><b>8</b><td>  <td>true<td>   <td>false<td>  <td>tukey(0.5)<td>  <td>12<td>  <td>0<td>  <td>false<td>  <td>false<td>  <td>true<td>   <td>0<td>  <td>6<td>  <td>0<td>  </tr>
+ * <tr>  <td><b>0</b></td> <td>false</td> <td>false</td> <td>tukey(0.5)<td>                                     <td>0</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>3</td> <td>0</td> </tr>
+ * <tr>  <td><b>1</b></td> <td>true</td>  <td>true</td>  <td>tukey(0.5)<td>                                     <td>0</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>3</td> <td>0</td> </tr>
+ * <tr>  <td><b>2</b></td> <td>true</td>  <td>false</td> <td>tukey(0.5)<td>                                     <td>0</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>3</td> <td>0</td> </tr>
+ * <tr>  <td><b>3</b></td> <td>false</td> <td>false</td> <td>tukey(0.5)<td>                                     <td>6</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>4</td> <td>0</td> </tr>
+ * <tr>  <td><b>4</b></td> <td>true</td>  <td>true</td>  <td>tukey(0.5)<td>                                     <td>8</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>4</td> <td>0</td> </tr>
+ * <tr>  <td><b>5</b></td> <td>true</td>  <td>false</td> <td>tukey(0.5)<td>                                     <td>8</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>5</td> <td>0</td> </tr>
+ * <tr>  <td><b>6</b></td> <td>true</td>  <td>false</td> <td>tukey(0.5);partial_tukey(2)<td>                    <td>8</td>  <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>6</td> <td>0</td> </tr>
+ * <tr>  <td><b>7</b></td> <td>true</td>  <td>false</td> <td>tukey(0.5);partial_tukey(2)<td>                    <td>12</td> <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>6</td> <td>0</td> </tr>
+ * <tr>  <td><b>8</b></td> <td>true</td>  <td>false</td> <td>tukey(0.5);partial_tukey(2);punchout_tukey(3)</td> <td>12</td> <td>0</td> <td>false</td> <td>false</td> <td>false</td> <td>0</td> <td>6</td> <td>0</td> </tr>
  * </table>
  *
  * \default \c 5
@@ -920,7 +920,8 @@ FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamE
  * The available functions are \c bartlett, \c bartlett_hann,
  * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
- * \c rectangle, \c triangle, \c tukey(P), \c welch.
+ * \c rectangle, \c triangle, \c tukey(P), \c partial_tukey(n[/ov[/P]]),
+ * \c punchout_tukey(n[/ov[/P]]), \c welch.
  *
  * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  * (0<STDDEV<=0.5).
@@ -929,6 +930,24 @@ FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamE
  * tapered (0<=P<=1).  P=0 corresponds to \c rectangle and P=1
  * corresponds to \c hann.
  *
+ * Specifying \c partial_tukey or \c punchout_tukey works a little
+ * different. These do not specify a single apodization function, but
+ * a series of them with some overlap. partial_tukey specifies a series
+ * of small windows (all treated separately) while punchout_tukey
+ * specifies a series of windows that have a hole in them. In this way,
+ * the predictor is constructed with only a part of the block, which
+ * helps in case a block consists of dissimilar parts.
+ *
+ * The three parameters that can be specified for the functions are
+ * n, ov and P. n is the number of functions to add, ov is the overlap
+ * of the windows in case of partial_tukey and the overlap in the gaps
+ * in case of punchout_tukey. P is the fraction of the window that is
+ * tapered, like with a regular tukey window. The function can be
+ * specified with only a number, a number and an overlap, or a number
+ * an overlap and a P, for example, partial_tukey(3), partial_tukey(3/0.3)
+ * and partial_tukey(3/0.3/0.5) are all valid. ov should be smaller than 1
+ * and can be negative.
+ *
  * Example specifications are \c "blackman" or
  * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  *
@@ -941,7 +960,9 @@ FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamE
  * results in the smallest compressed subframe.
  *
  * Note that each function specified causes the encoder to occupy a
- * floating point array in which to store the window.
+ * floating point array in which to store the window. Also note that the
+ * values of P, STDDEV and ov are locale-specific, so if the comma
+ * separator specified by the locale is a comma, a comma should be used.
  *
  * \default \c "tukey(0.5)"
  * \param  encoder        An encoder instance to set.
diff --git a/FLAC/seekable_stream_decoder.h b/FLAC/seekable_stream_decoder.h
deleted file mode 100644 (file)
index 864e9b6..0000000
+++ /dev/null
@@ -1,908 +0,0 @@
-/* libFLAC - Free Lossless Audio Codec library
- * Copyright (C) 2000,2001,2002,2003  Josh Coalson
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA  02111-1307, USA.
- */
-
-#ifndef FLAC__SEEKABLE_STREAM_DECODER_H
-#define FLAC__SEEKABLE_STREAM_DECODER_H
-
-#include "export.h"
-#include "stream_decoder.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/** \file include/FLAC/seekable_stream_decoder.h
- *
- *  \brief
- *  This module contains the functions which implement the seekable stream
- *  decoder.
- *
- *  See the detailed documentation in the
- *  \link flac_seekable_stream_decoder seekable stream decoder \endlink module.
- */
-
-/** \defgroup flac_seekable_stream_decoder FLAC/seekable_stream_decoder.h: seekable stream decoder interface
- *  \ingroup flac_decoder
- *
- *  \brief
- *  This module contains the functions which implement the seekable stream
- *  decoder.
- *
- * The basic usage of this decoder is as follows:
- * - The program creates an instance of a decoder using
- *   FLAC__seekable_stream_decoder_new().
- * - The program overrides the default settings and sets callbacks for
- *   reading, writing, seeking, error reporting, and metadata reporting
- *   using FLAC__seekable_stream_decoder_set_*() functions.
- * - The program initializes the instance to validate the settings and
- *   prepare for decoding using FLAC__seekable_stream_decoder_init().
- * - The program calls the FLAC__seekable_stream_decoder_process_*()
- *   functions to decode data, which subsequently calls the callbacks.
- * - The program finishes the decoding with
- *   FLAC__seekable_stream_decoder_finish(), which flushes the input and
- *   output and resets the decoder to the uninitialized state.
- * - The instance may be used again or deleted with
- *   FLAC__seekable_stream_decoder_delete().
- *
- * The seekable stream decoder is a wrapper around the
- * \link flac_stream_decoder stream decoder \endlink which also provides
- * seeking capability.  In addition to the Read/Write/Metadata/Error
- * callbacks of the stream decoder, the user must also provide the following:
- *
- * - Seek callback - This function will be called when the decoder wants to
- *   seek to an absolute position in the stream.
- * - Tell callback - This function will be called when the decoder wants to
- *   know the current absolute position of the stream.
- * - Length callback - This function will be called when the decoder wants
- *   to know length of the stream.  The seeking algorithm currently requires
- *   that the overall stream length be known.
- * - EOF callback - This function will be called when the decoder wants to
- *   know if it is at the end of the stream.  This could be synthesized from
- *   the tell and length callbacks but it may be more expensive that way, so
- *   there is a separate callback for it.
- *
- * Seeking is exposed through the
- * FLAC__seekable_stream_decoder_seek_absolute() method.  At any point after
- * the seekable stream decoder has been initialized, the user can call this
- * function to seek to an exact sample within the stream.  Subsequently, the
- * first time the write callback is called it will be passed a (possibly
- * partial) block starting at that sample.
- *
- * The seekable stream decoder also provides MD5 signature checking.  If
- * this is turned on before initialization,
- * FLAC__seekable_stream_decoder_finish() will report when the decoded MD5
- * signature does not match the one stored in the STREAMINFO block.  MD5
- * checking is automatically turned off (until the next
- * FLAC__seekable_stream_decoder_reset()) if there is no signature in the
- * STREAMINFO block or when a seek is attempted.
- *
- * Make sure to read the detailed description of the
- * \link flac_stream_decoder stream decoder module \endlink since the
- * seekable stream decoder inherits much of its behavior.
- *
- * \note
- * The "set" functions may only be called when the decoder is in the
- * state FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED, i.e. after
- * FLAC__seekable_stream_decoder_new() or
- * FLAC__seekable_stream_decoder_finish(), but before
- * FLAC__seekable_stream_decoder_init().  If this is the case they will
- * return \c true, otherwise \c false.
- *
- * \note
- * FLAC__stream_decoder_finish() resets all settings to the constructor
- * defaults, including the callbacks.
- *
- * \{
- */
-
-
-/** State values for a FLAC__SeekableStreamDecoder
- *
- *  The decoder's state can be obtained by calling FLAC__seekable_stream_decoder_get_state().
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_DECODER_OK = 0,
-       /**< The decoder is in the normal OK state. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_SEEKING,
-       /**< The decoder is in the process of seeking. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_END_OF_STREAM,
-       /**< The decoder has reached the end of the stream. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
-       /**< An error occurred allocating memory. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR,
-       /**< An error occurred in the underlying stream decoder. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_READ_ERROR,
-       /**< The read callback returned an error. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_SEEK_ERROR,
-       /**< An error occurred while seeking or the seek or tell
-        * callback returned an error.
-        */
-
-       FLAC__SEEKABLE_STREAM_DECODER_ALREADY_INITIALIZED,
-       /**< FLAC__seekable_stream_decoder_init() was called when the
-        * decoder was already initialized, usually because
-        * FLAC__seekable_stream_decoder_finish() was not called.
-        */
-
-       FLAC__SEEKABLE_STREAM_DECODER_INVALID_CALLBACK,
-       /**< FLAC__seekable_stream_decoder_init() was called without all
-        * callbacks being set.
-        */
-
-       FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED
-       /**< The decoder is in the uninitialized state. */
-
-} FLAC__SeekableStreamDecoderState;
-
-/** Maps a FLAC__SeekableStreamDecoderState to a C string.
- *
- *  Using a FLAC__SeekableStreamDecoderState as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamDecoderStateString[];
-
-
-/** Return values for the FLAC__SeekableStreamDecoder read callback.
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK,
-       /**< The read was OK and decoding can continue. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR
-       /**< An unrecoverable error occurred.  The decoder will return from the process call. */
-
-} FLAC__SeekableStreamDecoderReadStatus;
-
-/** Maps a FLAC__SeekableStreamDecoderReadStatus to a C string.
- *
- *  Using a FLAC__SeekableStreamDecoderReadStatus as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamDecoderReadStatusString[];
-
-
-/** Return values for the FLAC__SeekableStreamDecoder seek callback.
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK,
-       /**< The seek was OK and decoding can continue. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR
-       /**< An unrecoverable error occurred.  The decoder will return from the process call. */
-
-} FLAC__SeekableStreamDecoderSeekStatus;
-
-/** Maps a FLAC__SeekableStreamDecoderSeekStatus to a C string.
- *
- *  Using a FLAC__SeekableStreamDecoderSeekStatus as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamDecoderSeekStatusString[];
-
-
-/** Return values for the FLAC__SeekableStreamDecoder tell callback.
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK,
-       /**< The tell was OK and decoding can continue. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR
-       /**< An unrecoverable error occurred.  The decoder will return from the process call. */
-
-} FLAC__SeekableStreamDecoderTellStatus;
-
-/** Maps a FLAC__SeekableStreamDecoderTellStatus to a C string.
- *
- *  Using a FLAC__SeekableStreamDecoderTellStatus as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamDecoderTellStatusString[];
-
-
-/** Return values for the FLAC__SeekableStreamDecoder length callback.
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK,
-       /**< The length call was OK and decoding can continue. */
-
-       FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_ERROR
-       /**< An unrecoverable error occurred.  The decoder will return from the process call. */
-
-} FLAC__SeekableStreamDecoderLengthStatus;
-
-/** Maps a FLAC__SeekableStreamDecoderLengthStatus to a C string.
- *
- *  Using a FLAC__SeekableStreamDecoderLengthStatus as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamDecoderLengthStatusString[];
-
-
-/***********************************************************************
- *
- * class FLAC__SeekableStreamDecoder : public FLAC__StreamDecoder
- *
- ***********************************************************************/
-
-struct FLAC__SeekableStreamDecoderProtected;
-struct FLAC__SeekableStreamDecoderPrivate;
-/** The opaque structure definition for the seekable stream decoder type.
- *  See the
- *  \link flac_seekable_stream_decoder seekable stream decoder module \endlink
- *  for a detailed description.
- */
-typedef struct {
-       struct FLAC__SeekableStreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
-       struct FLAC__SeekableStreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
-} FLAC__SeekableStreamDecoder;
-
-/** Signature for the read callback.
- *  See FLAC__seekable_stream_decoder_set_read_callback()
- *  and FLAC__StreamDecoderReadCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  buffer   A pointer to a location for the callee to store
- *                  data to be decoded.
- * \param  bytes    A pointer to the size of the buffer.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__SeekableStreamDecoderReadStatus
- *    The callee's return status.
- */
-typedef FLAC__SeekableStreamDecoderReadStatus (*FLAC__SeekableStreamDecoderReadCallback)(const FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
-
-/** Signature for the seek callback.
- *  See FLAC__seekable_stream_decoder_set_seek_callback() for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  absolute_byte_offset  The offset from the beginning of the stream
- *                               to seek to.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__SeekableStreamDecoderSeekStatus
- *    The callee's return status.
- */
-typedef FLAC__SeekableStreamDecoderSeekStatus (*FLAC__SeekableStreamDecoderSeekCallback)(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
-
-/** Signature for the tell callback.
- *  See FLAC__seekable_stream_decoder_set_tell_callback() for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  absolute_byte_offset  A pointer to storage for the current offset
- *                               from the beginning of the stream.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__SeekableStreamDecoderTellStatus
- *    The callee's return status.
- */
-typedef FLAC__SeekableStreamDecoderTellStatus (*FLAC__SeekableStreamDecoderTellCallback)(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
-
-/** Signature for the length callback.
- *  See FLAC__seekable_stream_decoder_set_length_callback() for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  stream_length  A pointer to storage for the length of the stream
- *                        in bytes.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__SeekableStreamDecoderLengthStatus
- *    The callee's return status.
- */
-typedef FLAC__SeekableStreamDecoderLengthStatus (*FLAC__SeekableStreamDecoderLengthCallback)(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
-
-/** Signature for the EOF callback.
- *  See FLAC__seekable_stream_decoder_set_eof_callback() for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__bool
- *    \c true if the currently at the end of the stream, else \c false.
- */
-typedef FLAC__bool (*FLAC__SeekableStreamDecoderEofCallback)(const FLAC__SeekableStreamDecoder *decoder, void *client_data);
-
-/** Signature for the write callback.
- *  See FLAC__seekable_stream_decoder_set_write_callback()
- *  and FLAC__StreamDecoderWriteCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  frame    The description of the decoded frame.
- * \param  buffer   An array of pointers to decoded channels of data.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- * \retval FLAC__StreamDecoderWriteStatus
- *    The callee's return status.
- */
-typedef FLAC__StreamDecoderWriteStatus (*FLAC__SeekableStreamDecoderWriteCallback)(const FLAC__SeekableStreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
-
-/** Signature for the metadata callback.
- *  See FLAC__seekable_stream_decoder_set_metadata_callback()
- *  and FLAC__StreamDecoderMetadataCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  metadata The decoded metadata block.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- */
-typedef void (*FLAC__SeekableStreamDecoderMetadataCallback)(const FLAC__SeekableStreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
-
-/** Signature for the error callback.
- *  See FLAC__seekable_stream_decoder_set_error_callback()
- *  and FLAC__StreamDecoderErrorCallback for more info.
- *
- * \param  decoder  The decoder instance calling the callback.
- * \param  status   The error encountered by the decoder.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_decoder_set_client_data().
- */
-typedef void (*FLAC__SeekableStreamDecoderErrorCallback)(const FLAC__SeekableStreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
-
-
-/***********************************************************************
- *
- * Class constructor/destructor
- *
- ***********************************************************************/
-
-/** Create a new seekable stream decoder instance.  The instance is created
- *  with default settings; see the individual
- *  FLAC__seekable_stream_decoder_set_*() functions for each setting's
- *  default.
- *
- * \retval FLAC__SeekableStreamDecoder*
- *    \c NULL if there was an error allocating memory, else the new instance.
- */
-FLAC_API FLAC__SeekableStreamDecoder *FLAC__seekable_stream_decoder_new();
-
-/** Free a decoder instance.  Deletes the object pointed to by \a decoder.
- *
- * \param decoder  A pointer to an existing decoder.
- * \assert
- *    \code decoder != NULL \endcode
- */
-FLAC_API void FLAC__seekable_stream_decoder_delete(FLAC__SeekableStreamDecoder *decoder);
-
-
-/***********************************************************************
- *
- * Public class method prototypes
- *
- ***********************************************************************/
-
-/** Set the "MD5 signature checking" flag.  If \c true, the decoder will
- *  compute the MD5 signature of the unencoded audio data while decoding
- *  and compare it to the signature from the STREAMINFO block, if it
- *  exists, during FLAC__seekable_stream_decoder_finish().
- *
- *  MD5 signature checking will be turned off (until the next
- *  FLAC__seekable_stream_decoder_reset()) if there is no signature in
- *  the STREAMINFO block or when a seek is attempted.
- *
- * \default \c false
- * \param  decoder  A decoder instance to set.
- * \param  value    Flag value (see above).
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_md5_checking(FLAC__SeekableStreamDecoder *decoder, FLAC__bool value);
-
-/** Set the read callback.
- *  This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_read_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_read_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderReadCallback value);
-
-/** Set the seek callback.
- *  The supplied function will be called when the decoder needs to seek
- *  the input stream.  The decoder will pass the absolute byte offset
- *  to seek to, 0 meaning the beginning of the stream.
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_seek_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderSeekCallback value);
-
-/** Set the tell callback.
- *  The supplied function will be called when the decoder wants to know
- *  the current position of the stream.  The callback should return the
- *  byte offset from the beginning of the stream.
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_tell_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderTellCallback value);
-
-/** Set the length callback.
- *  The supplied function will be called when the decoder wants to know
- *  the total length of the stream in bytes.
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_length_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderLengthCallback value);
-
-/** Set the eof callback.
- *  The supplied function will be called when the decoder needs to know
- *  if the end of the stream has been reached.
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_eof_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderEofCallback value);
-
-/** Set the write callback.
- *  This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_write_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_write_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderWriteCallback value);
-
-/** Set the metadata callback.
- *  This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderMetadataCallback value);
-
-/** Set the error callback.
- *  This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_error_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_error_callback(FLAC__SeekableStreamDecoder *decoder, FLAC__SeekableStreamDecoderErrorCallback value);
-
-/** Set the client data to be passed back to callbacks.
- *  This value will be supplied to callbacks in their \a client_data
- *  argument.
- *
- * \default \c NULL
- * \param  decoder  A decoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_client_data(FLAC__SeekableStreamDecoder *decoder, void *value);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_respond().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  type     See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \a type is valid
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond(FLAC__SeekableStreamDecoder *decoder, FLAC__MetadataType type);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_respond_application().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  id       See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code id != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond_application(FLAC__SeekableStreamDecoder *decoder, const FLAC__byte id[4]);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_respond_all().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_respond_all(FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_ignore().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  type     See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \a type is valid
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore(FLAC__SeekableStreamDecoder *decoder, FLAC__MetadataType type);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_ignore_application().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \param  id       See above.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code id != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore_application(FLAC__SeekableStreamDecoder *decoder, const FLAC__byte id[4]);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_set_metadata_ignore_all().
- *
- * \default By default, only the \c STREAMINFO block is returned via the
- *          metadata callback.
- * \param  decoder  A decoder instance to set.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the decoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_set_metadata_ignore_all(FLAC__SeekableStreamDecoder *decoder);
-
-/** Get the current decoder state.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__SeekableStreamDecoderState
- *    The current decoder state.
- */
-FLAC_API FLAC__SeekableStreamDecoderState FLAC__seekable_stream_decoder_get_state(const FLAC__SeekableStreamDecoder *decoder);
-
-/** Get the state of the underlying stream decoder.
- *  Useful when the seekable stream decoder state is
- *  \c FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__StreamDecoderState
- *    The stream decoder state.
- */
-FLAC_API FLAC__StreamDecoderState FLAC__seekable_stream_decoder_get_stream_decoder_state(const FLAC__SeekableStreamDecoder *decoder);
-
-/** Get the current decoder state as a C string.
- *  This version automatically resolves
- *  \c FLAC__SEEKABLE_STREAM_DECODER_STREAM_DECODER_ERROR by getting the
- *  stream decoder's state.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval const char *
- *    The decoder state as a C string.  Do not modify the contents.
- */
-FLAC_API const char *FLAC__seekable_stream_decoder_get_resolved_state_string(const FLAC__SeekableStreamDecoder *decoder);
-
-/** Get the "MD5 signature checking" flag.
- *  This is the value of the setting, not whether or not the decoder is
- *  currently checking the MD5 (remember, it can be turned off automatically
- *  by a seek).  When the decoder is reset the flag will be restored to the
- *  value returned by this function.
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_get_md5_checking(const FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_get_channels().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__seekable_stream_decoder_get_channels(const FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_get_channel_assignment().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__ChannelAssignment
- *    See above.
- */
-FLAC_API FLAC__ChannelAssignment FLAC__seekable_stream_decoder_get_channel_assignment(const FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_get_bits_per_sample().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__seekable_stream_decoder_get_bits_per_sample(const FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_get_sample_rate().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__seekable_stream_decoder_get_sample_rate(const FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_get_blocksize().
- *
- * \param  decoder  A decoder instance to query.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval unsigned
- *    See above.
- */
-FLAC_API unsigned FLAC__seekable_stream_decoder_get_blocksize(const FLAC__SeekableStreamDecoder *decoder);
-
-/** Returns the decoder's current read position within the stream.
- *  The position is the byte offset from the start of the stream.
- *  Bytes before this position have been fully decoded.  Note that
- *  there may still be undecoded bytes in the decoder's read FIFO.
- *  The returned position is correct even after a seek.
- *
- * \param  decoder   A decoder instance to query.
- * \param  position  Address at which to return the desired position.
- * \assert
- *    \code decoder != NULL \endcode
- *    \code position != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, \c false if there was an error from
- *    the 'tell' callback.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_get_decode_position(const FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *position);
-
-/** Initialize the decoder instance.
- *  Should be called after FLAC__seekable_stream_decoder_new() and
- *  FLAC__seekable_stream_decoder_set_*() but before any of the
- *  FLAC__seekable_stream_decoder_process_*() functions.  Will set and return
- *  the decoder state, which will be FLAC__SEEKABLE_STREAM_DECODER_OK
- *  if initialization succeeded.
- *
- * \param  decoder  An uninitialized decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__SeekableStreamDecoderState
- *    \c FLAC__SEEKABLE_STREAM_DECODER_OK if initialization was
- *    successful; see FLAC__SeekableStreamDecoderState for the meanings
- *    of other return values.
- */
-FLAC_API FLAC__SeekableStreamDecoderState FLAC__seekable_stream_decoder_init(FLAC__SeekableStreamDecoder *decoder);
-
-/** Finish the decoding process.
- *  Flushes the decoding buffer, releases resources, resets the decoder
- *  settings to their defaults, and returns the decoder state to
- *  FLAC__SEEKABLE_STREAM_DECODER_UNINITIALIZED.
- *
- *  In the event of a prematurely-terminated decode, it is not strictly
- *  necessary to call this immediately before
- *  FLAC__seekable_stream_decoder_delete() but it is good practice to match
- *  every FLAC__seekable_stream_decoder_init() with a
- *  FLAC__seekable_stream_decoder_finish().
- *
- * \param  decoder  An uninitialized decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if MD5 checking is on AND a STREAMINFO block was available
- *    AND the MD5 signature in the STREAMINFO block was non-zero AND the
- *    signature does not match the one computed by the decoder; else
- *    \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_finish(FLAC__SeekableStreamDecoder *decoder);
-
-/** Flush the stream input.
- *  The decoder's input buffer will be cleared and the state set to
- *  \c FLAC__SEEKABLE_STREAM_DECODER_OK.  This will also turn off MD5
- *  checking.
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false if a memory allocation
- *    or stream decoder error occurs.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_flush(FLAC__SeekableStreamDecoder *decoder);
-
-/** Reset the decoding process.
- *  The decoder's input buffer will be cleared and the state set to
- *  \c FLAC__SEEKABLE_STREAM_DECODER_OK.  This is similar to
- *  FLAC__seekable_stream_decoder_finish() except that the settings are
- *  preserved; there is no need to call FLAC__seekable_stream_decoder_init()
- *  before decoding again.  MD5 checking will be restored to its original
- *  setting.
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false if a memory allocation
- *    or stream decoder error occurs.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_reset(FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_process_single().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_single(FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_process_until_end_of_metadata().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_until_end_of_metadata(FLAC__SeekableStreamDecoder *decoder);
-
-/** This is inherited from FLAC__StreamDecoder; see
- *  FLAC__stream_decoder_process_until_end_of_stream().
- *
- * \param  decoder  A decoder instance.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    See above.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_process_until_end_of_stream(FLAC__SeekableStreamDecoder *decoder);
-
-/** Flush the input and seek to an absolute sample.
- *  Decoding will resume at the given sample.  Note that because of
- *  this, the next write callback may contain a partial block.
- *
- * \param  decoder  A decoder instance.
- * \param  sample   The target sample number to seek to.
- * \assert
- *    \code decoder != NULL \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_decoder_seek_absolute(FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 sample);
-
-/* \} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/FLAC/seekable_stream_encoder.h b/FLAC/seekable_stream_encoder.h
deleted file mode 100644 (file)
index 2e77e00..0000000
+++ /dev/null
@@ -1,916 +0,0 @@
-/* libFLAC - Free Lossless Audio Codec library
- * Copyright (C) 2002,2003  Josh Coalson
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA  02111-1307, USA.
- */
-
-#ifndef FLAC__SEEKABLE_STREAM_ENCODER_H
-#define FLAC__SEEKABLE_STREAM_ENCODER_H
-
-#include "export.h"
-#include "stream_encoder.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/** \file include/FLAC/seekable_stream_encoder.h
- *
- *  \brief
- *  This module contains the functions which implement the seekable stream
- *  encoder.
- *
- *  See the detailed documentation in the
- *  \link flac_seekable_stream_encoder seekable stream encoder \endlink module.
- */
-
-/** \defgroup flac_seekable_stream_encoder FLAC/seekable_stream_encoder.h: seekable stream encoder interface
- *  \ingroup flac_encoder
- *
- *  \brief
- *  This module contains the functions which implement the seekable stream
- *  encoder.
- *
- * The basic usage of this encoder is as follows:
- * - The program creates an instance of an encoder using
- *   FLAC__seekable_stream_encoder_new().
- * - The program overrides the default settings and sets callbacks using
- *   FLAC__seekable_stream_encoder_set_*() functions.
- * - The program initializes the instance to validate the settings and
- *   prepare for encoding using FLAC__seekable_stream_encoder_init().
- * - The program calls FLAC__seekable_stream_encoder_process() or
- *   FLAC__seekable_stream_encoder_process_interleaved() to encode data, which
- *   subsequently calls the callbacks when there is encoder data ready
- *   to be written.
- * - The program finishes the encoding with FLAC__seekable_stream_encoder_finish(),
- *   which causes the encoder to encode any data still in its input pipe,
- *   rewrite the metadata with the final encoding statistics, and finally
- *   reset the encoder to the uninitialized state.
- * - The instance may be used again or deleted with
- *   FLAC__seekable_stream_encoder_delete().
- *
- * The seekable stream encoder is a wrapper around the
- * \link flac_stream_encoder stream encoder \endlink with callbacks for
- * seeking the output.  This allows the encoder to go back and rewrite
- * some of the metadata after encoding if necessary, and provides the
- * metadata callback of the stream encoder internally.  However, you
- * must provide a seek callback (see
- * FLAC__seekable_stream_encoder_set_seek_callback()).
- *
- * Make sure to read the detailed description of the
- * \link flac_stream_encoder stream encoder module \endlink since the
- * seekable stream encoder inherits much of its behavior.
- *
- * \note
- * If you are writing the FLAC data to a file, make sure it is open
- * for update (e.g. mode "w+" for stdio streams).  This is because after
- * the first encoding pass, the encoder will try to seek back to the
- * beginning of the stream, to the STREAMINFO block, to write some data
- * there.
- *
- * \note
- * The "set" functions may only be called when the encoder is in the
- * state FLAC__SEEKABLE_STREAM_ENCODER_UNINITIALIZED, i.e. after
- * FLAC__seekable_stream_encoder_new() or FLAC__seekable_stream_encoder_finish(), but
- * before FLAC__seekable_stream_encoder_init().  If this is the case they will
- * return \c true, otherwise \c false.
- *
- * \note
- * FLAC__seekable_stream_encoder_finish() resets all settings to the constructor
- * defaults, including the callbacks.
- *
- * \{
- */
-
-
-/** State values for a FLAC__SeekableStreamEncoder
- *
- *  The encoder's state can be obtained by calling FLAC__seekable_stream_encoder_get_state().
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_ENCODER_OK = 0,
-       /**< The encoder is in the normal OK state. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR,
-       /**< An error occurred in the underlying stream encoder;
-        * check FLAC__seekable_stream_encoder_get_stream_encoder_state().
-        */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_MEMORY_ALLOCATION_ERROR,
-       /**< Memory allocation failed. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_WRITE_ERROR,
-       /**< The write callback returned an error. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_READ_ERROR,
-       /**< The read callback returned an error. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_SEEK_ERROR,
-       /**< The seek callback returned an error. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_ALREADY_INITIALIZED,
-       /**< FLAC__seekable_stream_encoder_init() was called when the encoder was
-        * already initialized, usually because
-        * FLAC__seekable_stream_encoder_finish() was not called.
-        */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_INVALID_CALLBACK,
-       /**< FLAC__seekable_stream_encoder_init() was called without all
-        * callbacks being set.
-        */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_INVALID_SEEKTABLE,
-       /**< An invalid seek table was passed is the metadata to
-        * FLAC__seekable_stream_encoder_set_metadata().
-        */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_UNINITIALIZED
-       /**< The encoder is in the uninitialized state. */
-
-} FLAC__SeekableStreamEncoderState;
-
-/** Maps a FLAC__SeekableStreamEncoderState to a C string.
- *
- *  Using a FLAC__SeekableStreamEncoderState as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamEncoderStateString[];
-
-
-/** Return values for the FLAC__SeekableStreamEncoder seek callback.
- */
-typedef enum {
-
-       FLAC__SEEKABLE_STREAM_ENCODER_SEEK_STATUS_OK,
-       /**< The seek was OK and encoding can continue. */
-
-       FLAC__SEEKABLE_STREAM_ENCODER_SEEK_STATUS_ERROR
-       /**< An unrecoverable error occurred.  The encoder will return from the process call. */
-
-} FLAC__SeekableStreamEncoderSeekStatus;
-
-/** Maps a FLAC__SeekableStreamEncoderSeekStatus to a C string.
- *
- *  Using a FLAC__SeekableStreamEncoderSeekStatus as the index to this array
- *  will give the string equivalent.  The contents should not be modified.
- */
-extern FLAC_API const char * const FLAC__SeekableStreamEncoderSeekStatusString[];
-
-
-/***********************************************************************
- *
- * class FLAC__SeekableStreamEncoder
- *
- ***********************************************************************/
-
-struct FLAC__SeekableStreamEncoderProtected;
-struct FLAC__SeekableStreamEncoderPrivate;
-/** The opaque structure definition for the seekable stream encoder type.
- *  See the \link flac_seekable_stream_encoder seekable stream encoder module \endlink
- *  for a detailed description.
- */
-typedef struct {
-       struct FLAC__SeekableStreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
-       struct FLAC__SeekableStreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
-} FLAC__SeekableStreamEncoder;
-
-/** Signature for the seek callback.
- *  See FLAC__seekable_stream_encoder_set_seek_callback() for more info.
- *
- * \param  encoder  The encoder instance calling the callback.
- * \param  absolute_byte_offset  The offset from the beginning of the stream
- *                               to seek to.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_encoder_set_client_data().
- * \retval FLAC__SeekableStreamEncoderSeekStatus
- *    The callee's return status.
- */
-typedef FLAC__SeekableStreamEncoderSeekStatus (*FLAC__SeekableStreamEncoderSeekCallback)(const FLAC__SeekableStreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
-
-/** Signature for the write callback.
- *  See FLAC__seekable_stream_encoder_set_write_callback()
- *  and FLAC__StreamEncoderWriteCallback for more info.
- *
- * \param  encoder  The encoder instance calling the callback.
- * \param  buffer   An array of encoded data of length \a bytes.
- * \param  bytes    The byte length of \a buffer.
- * \param  samples  The number of samples encoded by \a buffer.
- *                  \c 0 has a special meaning; see
- *                  FLAC__stream_encoder_set_write_callback().
- * \param  current_frame  The number of current frame being encoded.
- * \param  client_data  The callee's client data set through
- *                      FLAC__seekable_stream_encoder_set_client_data().
- * \retval FLAC__StreamEncoderWriteStatus
- *    The callee's return status.
- */
-typedef FLAC__StreamEncoderWriteStatus (*FLAC__SeekableStreamEncoderWriteCallback)(const FLAC__SeekableStreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
-
-
-/***********************************************************************
- *
- * Class constructor/destructor
- *
- ***********************************************************************/
-
-/** Create a new seekable stream encoder instance.  The instance is created with
- *  default settings; see the individual FLAC__seekable_stream_encoder_set_*()
- *  functions for each setting's default.
- *
- * \retval FLAC__SeekableStreamEncoder*
- *    \c NULL if there was an error allocating memory, else the new instance.
- */
-FLAC_API FLAC__SeekableStreamEncoder *FLAC__seekable_stream_encoder_new();
-
-/** Free an encoder instance.  Deletes the object pointed to by \a encoder.
- *
- * \param encoder  A pointer to an existing encoder.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__seekable_stream_encoder_delete(FLAC__SeekableStreamEncoder *encoder);
-
-/***********************************************************************
- *
- * Public class method prototypes
- *
- ***********************************************************************/
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_verify().
- *
- * \default \c true
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_verify(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_streamable_subset().
- *
- * \default \c true
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_streamable_subset(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_do_mid_side_stereo().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_do_mid_side_stereo(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_loose_mid_side_stereo().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_loose_mid_side_stereo(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_channels().
- *
- * \default \c 2
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_channels(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_bits_per_sample().
- *
- * \warning
- * Do not feed the encoder data that is wider than the value you
- * set here or you will generate an invalid stream.
- *
- * \default \c 16
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_bits_per_sample(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_sample_rate().
- *
- * \default \c 44100
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_sample_rate(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_blocksize().
- *
- * \default \c 1152
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_blocksize(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_max_lpc_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_max_lpc_order(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_qlp_coeff_precision().
- *
- * \note
- * In the current implementation, qlp_coeff_precision + bits_per_sample must
- * be less than 32.
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_qlp_coeff_precision(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_do_qlp_coeff_prec_search(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_do_escape_coding().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_do_escape_coding(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_do_exhaustive_model_search().
- *
- * \default \c false
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_do_exhaustive_model_search(FLAC__SeekableStreamEncoder *encoder, FLAC__bool value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_min_residual_partition_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_min_residual_partition_order(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_max_residual_partition_order().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_max_residual_partition_order(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_rice_parameter_search_dist().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_rice_parameter_search_dist(FLAC__SeekableStreamEncoder *encoder, unsigned value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_total_samples_estimate().
- *
- * \default \c 0
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_total_samples_estimate(FLAC__SeekableStreamEncoder *encoder, FLAC__uint64 value);
-
-/** This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_metadata().
- *
- * \note
- * SEEKTABLE blocks are handled specially.  Since you will not know
- * the values for the seek point stream offsets, you should pass in
- * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
- * required sample numbers (or placeholder points), with \c 0 for the
- * \a frame_samples and \a stream_offset fields for each point.  While
- * encoding, the encoder will fill them in for you and when encoding
- * is finished, it will seek back and write the real values into the
- * SEEKTABLE block in the stream.  There are helper routines for
- * manipulating seektable template blocks; see metadata.h:
- * FLAC__metadata_object_seektable_template_*().
- *
- * \note
- * The encoder instance \b will modify the first \c SEEKTABLE block
- * as it transforms the template to a valid seektable while encoding,
- * but it is still up to the caller to free all metadata blocks after
- * encoding.
- *
- * \default \c NULL, 0
- * \param  encoder     An encoder instance to set.
- * \param  metadata    See above.
- * \param  num_blocks  See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_metadata(FLAC__SeekableStreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
-
-/** Set the seek callback.
- *  The supplied function will be called when the encoder needs to seek
- *  the output stream.  The encoder will pass the absolute byte offset
- *  to seek to, 0 meaning the beginning of the stream.
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_seek_callback(FLAC__SeekableStreamEncoder *encoder, FLAC__SeekableStreamEncoderSeekCallback value);
-
-/** Set the write callback.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_set_write_callback().
- *
- * \note
- * The callback is mandatory and must be set before initialization.
- *
- * \default \c NULL
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code value != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_write_callback(FLAC__SeekableStreamEncoder *encoder, FLAC__SeekableStreamEncoderWriteCallback value);
-
-/** Set the client data to be passed back to callbacks.
- *  This value will be supplied to callbacks in their \a client_data
- *  argument.
- *
- * \default \c NULL
- * \param  encoder  An encoder instance to set.
- * \param  value    See above.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    \c false if the encoder is already initialized, else \c true.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_set_client_data(FLAC__SeekableStreamEncoder *encoder, void *value);
-
-/** Get the current encoder state.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__SeekableStreamEncoderState
- *    The current encoder state.
- */
-FLAC_API FLAC__SeekableStreamEncoderState FLAC__seekable_stream_encoder_get_state(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the state of the underlying stream encoder.
- *  Useful when the seekable stream encoder state is
- *  \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__StreamEncoderState
- *    The stream encoder state.
- */
-FLAC_API FLAC__StreamEncoderState FLAC__seekable_stream_encoder_get_stream_encoder_state(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the state of the underlying stream encoder's verify decoder.
- *  Useful when the seekable stream encoder state is
- *  \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR and the
- *  stream encoder state is \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__StreamDecoderState
- *    The stream encoder state.
- */
-FLAC_API FLAC__StreamDecoderState FLAC__seekable_stream_encoder_get_verify_decoder_state(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the current encoder state as a C string.
- *  This version automatically resolves
- *  \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR by getting the
- *  stream encoder's state.
- *
- * \param  encoder  A encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval const char *
- *    The encoder state as a C string.  Do not modify the contents.
- */
-FLAC_API const char *FLAC__seekable_stream_encoder_get_resolved_state_string(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get relevant values about the nature of a verify decoder error.
- *  Inherited from FLAC__stream_encoder_get_verify_decoder_error_stats().
- *  Useful when the seekable stream encoder state is
- *  \c FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR and the
- *  stream encoder state is
- *  \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
- *
- * \param  encoder  An encoder instance to query.
- * \param  absolute_sample  The absolute sample number of the mismatch.
- * \param  frame_number  The number of the frame in which the mismatch occurred.
- * \param  channel       The channel in which the mismatch occurred.
- * \param  sample        The number of the sample (relative to the frame) in
- *                       which the mismatch occurred.
- * \param  expected      The expected value for the sample in question.
- * \param  got           The actual value returned by the decoder.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__seekable_stream_encoder_get_verify_decoder_error_stats(const FLAC__SeekableStreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
-
-/** Get the "verify" flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_verify().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_verify().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_verify(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the "streamable subset" flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_streamable_subset().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_streamable_subset().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_streamable_subset(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the "mid/side stereo coding" flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_do_mid_side_stereo().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_get_do_mid_side_stereo().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_do_mid_side_stereo(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the "adaptive mid/side switching" flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_loose_mid_side_stereo().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_loose_mid_side_stereo().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_loose_mid_side_stereo(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the number of input channels being processed.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_channels().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_channels().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_channels(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the input sample resolution setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_bits_per_sample().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_bits_per_sample().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_bits_per_sample(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the input sample rate setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_sample_rate().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_sample_rate().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_sample_rate(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the blocksize setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_blocksize().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_blocksize().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_blocksize(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the maximum LPC order setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_max_lpc_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_max_lpc_order().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_max_lpc_order(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the quantized linear predictor coefficient precision setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_qlp_coeff_precision().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_qlp_coeff_precision().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_qlp_coeff_precision(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the qlp coefficient precision search flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_do_qlp_coeff_prec_search().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_do_qlp_coeff_prec_search().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the "escape coding" flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_do_escape_coding().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_do_escape_coding().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_do_escape_coding(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the exhaustive model search flag.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_do_exhaustive_model_search().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__bool
- *    See FLAC__seekable_stream_encoder_set_do_exhaustive_model_search().
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_get_do_exhaustive_model_search(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the minimum residual partition order setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_min_residual_partition_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_min_residual_partition_order().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_min_residual_partition_order(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get maximum residual partition order setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_max_residual_partition_order().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_max_residual_partition_order().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_max_residual_partition_order(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the Rice parameter search distance setting.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_rice_parameter_search_dist().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval unsigned
- *    See FLAC__seekable_stream_encoder_set_rice_parameter_search_dist().
- */
-FLAC_API unsigned FLAC__seekable_stream_encoder_get_rice_parameter_search_dist(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Get the previously set estimate of the total samples to be encoded.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_get_total_samples_estimate().
- *
- * \param  encoder  An encoder instance to query.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__uint64
- *    See FLAC__seekable_stream_encoder_set_total_samples_estimate().
- */
-FLAC_API FLAC__uint64 FLAC__seekable_stream_encoder_get_total_samples_estimate(const FLAC__SeekableStreamEncoder *encoder);
-
-/** Initialize the encoder instance.
- *  Should be called after FLAC__seekable_stream_encoder_new() and
- *  FLAC__seekable_stream_encoder_set_*() but before FLAC__seekable_stream_encoder_process()
- *  or FLAC__seekable_stream_encoder_process_interleaved().  Will set and return
- *  the encoder state, which will be FLAC__SEEKABLE_STREAM_ENCODER_OK if
- *  initialization succeeded.
- *
- *  The call to FLAC__seekable_stream_encoder_init() currently will also immediately
- *  call the write callback with the \c fLaC signature and all the encoded
- *  metadata.
- *
- * \param  encoder  An uninitialized encoder instance.
- * \assert
- *    \code encoder != NULL \endcode
- * \retval FLAC__SeekableStreamEncoderState
- *    \c FLAC__SEEKABLE_STREAM_ENCODER_OK if initialization was successful; see
- *    FLAC__SeekableStreamEncoderState for the meanings of other return values.
- */
-FLAC_API FLAC__SeekableStreamEncoderState FLAC__seekable_stream_encoder_init(FLAC__SeekableStreamEncoder *encoder);
-
-/** Finish the encoding process.
- *  Flushes the encoding buffer, releases resources, resets the encoder
- *  settings to their defaults, and returns the encoder state to
- *  FLAC__SEEKABLE_STREAM_ENCODER_UNINITIALIZED.
- *
- *  In the event of a prematurely-terminated encode, it is not strictly
- *  necessary to call this immediately before FLAC__seekable_stream_encoder_delete()
- *  but it is good practice to match every FLAC__seekable_stream_encoder_init()
- *  with a FLAC__seekable_stream_encoder_finish().
- *
- * \param  encoder  An uninitialized encoder instance.
- * \assert
- *    \code encoder != NULL \endcode
- */
-FLAC_API void FLAC__seekable_stream_encoder_finish(FLAC__SeekableStreamEncoder *encoder);
-
-/** Submit data for encoding.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_process().
- *
- * \param  encoder  An initialized encoder instance in the OK state.
- * \param  buffer   An array of pointers to each channel's signal.
- * \param  samples  The number of samples in one channel.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code FLAC__seekable_stream_encoder_get_state(encoder) == FLAC__SEEKABLE_STREAM_ENCODER_OK \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false; in this case, check the
- *    encoder state with FLAC__seekable_stream_encoder_get_state() to see what
- *    went wrong.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_process(FLAC__SeekableStreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
-
-/** Submit data for encoding.
- *  This is inherited from FLAC__StreamEncoder; see
- *  FLAC__stream_encoder_process_interleaved().
- *
- * \param  encoder  An initialized encoder instance in the OK state.
- * \param  buffer   An array of channel-interleaved data (see above).
- * \param  samples  The number of samples in one channel, the same as for
- *                  FLAC__seekable_stream_encoder_process().  For example, if
- *                  encoding two channels, \c 1000 \a samples corresponds
- *                  to a \a buffer of 2000 values.
- * \assert
- *    \code encoder != NULL \endcode
- *    \code FLAC__seekable_stream_encoder_get_state(encoder) == FLAC__SEEKABLE_STREAM_ENCODER_OK \endcode
- * \retval FLAC__bool
- *    \c true if successful, else \c false; in this case, check the
- *    encoder state with FLAC__seekable_stream_encoder_get_state() to see what
- *    went wrong.
- */
-FLAC_API FLAC__bool FLAC__seekable_stream_encoder_process_interleaved(FLAC__SeekableStreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
-
-/* \} */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/FLAC/src/bitmath.c b/FLAC/src/bitmath.c
new file mode 100644 (file)
index 0000000..b3d797d
--- /dev/null
@@ -0,0 +1,73 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/bitmath.h"
+
+/* An example of what FLAC__bitmath_silog2() computes:
+ *
+ * silog2(-10) = 5
+ * silog2(- 9) = 5
+ * silog2(- 8) = 4
+ * silog2(- 7) = 4
+ * silog2(- 6) = 4
+ * silog2(- 5) = 4
+ * silog2(- 4) = 3
+ * silog2(- 3) = 3
+ * silog2(- 2) = 2
+ * silog2(- 1) = 2
+ * silog2(  0) = 0
+ * silog2(  1) = 2
+ * silog2(  2) = 3
+ * silog2(  3) = 3
+ * silog2(  4) = 4
+ * silog2(  5) = 4
+ * silog2(  6) = 4
+ * silog2(  7) = 4
+ * silog2(  8) = 5
+ * silog2(  9) = 5
+ * silog2( 10) = 5
+ */
+unsigned FLAC__bitmath_silog2(FLAC__int64 v)
+{
+       if(v == 0)
+               return 0;
+
+       if(v == -1)
+               return 2;
+
+       v = (v < 0) ? (-(v+1)) : v;
+       return FLAC__bitmath_ilog2_wide(v)+2;
+}
diff --git a/FLAC/src/bitreader.c b/FLAC/src/bitreader.c
new file mode 100644 (file)
index 0000000..ab62d41
--- /dev/null
@@ -0,0 +1,1087 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+#include "private/bitmath.h"
+#include "private/bitreader.h"
+#include "private/crc.h"
+#include "private/macros.h"
+#include "FLAC/assert.h"
+#include "share/compat.h"
+#include "share/endswap.h"
+
+/* Things should be fastest when this matches the machine word size */
+/* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS2 below to match */
+/* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
+/*           also, some sections currently only have fast versions for 4 or 8 bytes per word */
+
+#if (ENABLE_64_BIT_WORDS == 0)
+
+typedef FLAC__uint32 brword;
+#define FLAC__BYTES_PER_WORD 4         /* sizeof brword */
+#define FLAC__BITS_PER_WORD 32
+#define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
+/* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
+#if WORDS_BIGENDIAN
+#define SWAP_BE_WORD_TO_HOST(x) (x)
+#else
+#define SWAP_BE_WORD_TO_HOST(x) ENDSWAP_32(x)
+#endif
+/* counts the # of zero MSBs in a word */
+#define COUNT_ZERO_MSBS(word) FLAC__clz_uint32(word)
+#define COUNT_ZERO_MSBS2(word) FLAC__clz2_uint32(word)
+
+#else
+
+typedef FLAC__uint64 brword;
+#define FLAC__BYTES_PER_WORD 8         /* sizeof brword */
+#define FLAC__BITS_PER_WORD 64
+#define FLAC__WORD_ALL_ONES ((FLAC__uint64)FLAC__U64L(0xffffffffffffffff))
+/* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
+#if WORDS_BIGENDIAN
+#define SWAP_BE_WORD_TO_HOST(x) (x)
+#else
+#define SWAP_BE_WORD_TO_HOST(x) ENDSWAP_64(x)
+#endif
+/* counts the # of zero MSBs in a word */
+#define COUNT_ZERO_MSBS(word) FLAC__clz_uint64(word)
+#define COUNT_ZERO_MSBS2(word) FLAC__clz2_uint64(word)
+
+#endif
+
+/*
+ * This should be at least twice as large as the largest number of words
+ * required to represent any 'number' (in any encoding) you are going to
+ * read.  With FLAC this is on the order of maybe a few hundred bits.
+ * If the buffer is smaller than that, the decoder won't be able to read
+ * in a whole number that is in a variable length encoding (e.g. Rice).
+ * But to be practical it should be at least 1K bytes.
+ *
+ * Increase this number to decrease the number of read callbacks, at the
+ * expense of using more memory.  Or decrease for the reverse effect,
+ * keeping in mind the limit from the first paragraph.  The optimal size
+ * also depends on the CPU cache size and other factors; some twiddling
+ * may be necessary to squeeze out the best performance.
+ */
+static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
+
+struct FLAC__BitReader {
+       /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
+       /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
+       brword *buffer;
+       unsigned capacity; /* in words */
+       unsigned words; /* # of completed words in buffer */
+       unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
+       unsigned consumed_words; /* #words ... */
+       unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
+       unsigned read_crc16; /* the running frame CRC */
+       unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
+       FLAC__BitReaderReadCallback read_callback;
+       void *client_data;
+};
+
+static inline void crc16_update_word_(FLAC__BitReader *br, brword word)
+{
+       register unsigned crc = br->read_crc16;
+#if FLAC__BYTES_PER_WORD == 4
+       switch(br->crc16_align) {
+               case  0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
+               case  8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
+               case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
+               case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
+       }
+#elif FLAC__BYTES_PER_WORD == 8
+       switch(br->crc16_align) {
+               case  0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
+               case  8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
+               case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
+               case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
+               case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
+               case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
+               case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
+               case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
+       }
+#else
+       for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
+               crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
+       br->read_crc16 = crc;
+#endif
+       br->crc16_align = 0;
+}
+
+static FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
+{
+       unsigned start, end;
+       size_t bytes;
+       FLAC__byte *target;
+
+       /* first shift the unconsumed buffer data toward the front as much as possible */
+       if(br->consumed_words > 0) {
+               start = br->consumed_words;
+               end = br->words + (br->bytes? 1:0);
+               memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
+
+               br->words -= start;
+               br->consumed_words = 0;
+       }
+
+       /*
+        * set the target for reading, taking into account word alignment and endianness
+        */
+       bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
+       if(bytes == 0)
+               return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY  */
+       target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
+
+       /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
+        *   bitstream :  11 22 33 44 55            br->words=1 br->bytes=1 (partial tail word is left-justified)
+        *   buffer[BE]:  11 22 33 44 55 ?? ?? ??   (shown layed out as bytes sequentially in memory)
+        *   buffer[LE]:  44 33 22 11 ?? ?? ?? 55   (?? being don't-care)
+        *                               ^^-------target, bytes=3
+        * on LE machines, have to byteswap the odd tail word so nothing is
+        * overwritten:
+        */
+#if WORDS_BIGENDIAN
+#else
+       if(br->bytes)
+               br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
+#endif
+
+       /* now it looks like:
+        *   bitstream :  11 22 33 44 55            br->words=1 br->bytes=1
+        *   buffer[BE]:  11 22 33 44 55 ?? ?? ??
+        *   buffer[LE]:  44 33 22 11 55 ?? ?? ??
+        *                               ^^-------target, bytes=3
+        */
+
+       /* read in the data; note that the callback may return a smaller number of bytes */
+       if(!br->read_callback(target, &bytes, br->client_data))
+               return false;
+
+       /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
+        *   bitstream :  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
+        *   buffer[BE]:  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
+        *   buffer[LE]:  44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
+        * now have to byteswap on LE machines:
+        */
+#if WORDS_BIGENDIAN
+#else
+       end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + (unsigned)bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
+       for(start = br->words; start < end; start++)
+               br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
+#endif
+
+       /* now it looks like:
+        *   bitstream :  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
+        *   buffer[BE]:  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
+        *   buffer[LE]:  44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
+        * finally we'll update the reader values:
+        */
+       end = br->words*FLAC__BYTES_PER_WORD + br->bytes + (unsigned)bytes;
+       br->words = end / FLAC__BYTES_PER_WORD;
+       br->bytes = end % FLAC__BYTES_PER_WORD;
+
+       return true;
+}
+
+/***********************************************************************
+ *
+ * Class constructor/destructor
+ *
+ ***********************************************************************/
+
+FLAC__BitReader *FLAC__bitreader_new(void)
+{
+       FLAC__BitReader *br = calloc(1, sizeof(FLAC__BitReader));
+
+       /* calloc() implies:
+               memset(br, 0, sizeof(FLAC__BitReader));
+               br->buffer = 0;
+               br->capacity = 0;
+               br->words = br->bytes = 0;
+               br->consumed_words = br->consumed_bits = 0;
+               br->read_callback = 0;
+               br->client_data = 0;
+       */
+       return br;
+}
+
+void FLAC__bitreader_delete(FLAC__BitReader *br)
+{
+       FLAC__ASSERT(0 != br);
+
+       FLAC__bitreader_free(br);
+       free(br);
+}
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__BitReaderReadCallback rcb, void *cd)
+{
+       FLAC__ASSERT(0 != br);
+
+       br->words = br->bytes = 0;
+       br->consumed_words = br->consumed_bits = 0;
+       br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
+       br->buffer = malloc(sizeof(brword) * br->capacity);
+       if(br->buffer == 0)
+               return false;
+       br->read_callback = rcb;
+       br->client_data = cd;
+
+       return true;
+}
+
+void FLAC__bitreader_free(FLAC__BitReader *br)
+{
+       FLAC__ASSERT(0 != br);
+
+       if(0 != br->buffer)
+               free(br->buffer);
+       br->buffer = 0;
+       br->capacity = 0;
+       br->words = br->bytes = 0;
+       br->consumed_words = br->consumed_bits = 0;
+       br->read_callback = 0;
+       br->client_data = 0;
+}
+
+FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
+{
+       br->words = br->bytes = 0;
+       br->consumed_words = br->consumed_bits = 0;
+       return true;
+}
+
+void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
+{
+       unsigned i, j;
+       if(br == 0) {
+               fprintf(out, "bitreader is NULL\n");
+       }
+       else {
+               fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
+
+               for(i = 0; i < br->words; i++) {
+                       fprintf(out, "%08X: ", i);
+                       for(j = 0; j < FLAC__BITS_PER_WORD; j++)
+                               if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
+                                       fprintf(out, ".");
+                               else
+                                       fprintf(out, "%01u", br->buffer[i] & ((brword)1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
+                       fprintf(out, "\n");
+               }
+               if(br->bytes > 0) {
+                       fprintf(out, "%08X: ", i);
+                       for(j = 0; j < br->bytes*8; j++)
+                               if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
+                                       fprintf(out, ".");
+                               else
+                                       fprintf(out, "%01u", br->buffer[i] & ((brword)1 << (br->bytes*8-j-1)) ? 1:0);
+                       fprintf(out, "\n");
+               }
+       }
+}
+
+void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
+{
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       FLAC__ASSERT((br->consumed_bits & 7) == 0);
+
+       br->read_crc16 = (unsigned)seed;
+       br->crc16_align = br->consumed_bits;
+}
+
+FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
+{
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       FLAC__ASSERT((br->consumed_bits & 7) == 0);
+       FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
+
+       /* CRC any tail bytes in a partially-consumed word */
+       if(br->consumed_bits) {
+               const brword tail = br->buffer[br->consumed_words];
+               for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
+                       br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
+       }
+       return br->read_crc16;
+}
+
+inline FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
+{
+       return ((br->consumed_bits & 7) == 0);
+}
+
+inline unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
+{
+       return 8 - (br->consumed_bits & 7);
+}
+
+inline unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
+{
+       return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
+}
+
+FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
+{
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       FLAC__ASSERT(bits <= 32);
+       FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
+       FLAC__ASSERT(br->consumed_words <= br->words);
+
+       /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
+       FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
+
+       if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
+               *val = 0;
+               return true;
+       }
+
+       while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
+               if(!bitreader_read_from_client_(br))
+                       return false;
+       }
+       if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
+               /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
+               if(br->consumed_bits) {
+                       /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
+                       const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
+                       const brword word = br->buffer[br->consumed_words];
+                       if(bits < n) {
+                               *val = (FLAC__uint32)((word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits)); /* The result has <= 32 non-zero bits */
+                               br->consumed_bits += bits;
+                               return true;
+                       }
+                       /* (FLAC__BITS_PER_WORD - br->consumed_bits <= bits) ==> (FLAC__WORD_ALL_ONES >> br->consumed_bits) has no more than 'bits' non-zero bits */
+                       *val = (FLAC__uint32)(word & (FLAC__WORD_ALL_ONES >> br->consumed_bits));
+                       bits -= n;
+                       crc16_update_word_(br, word);
+                       br->consumed_words++;
+                       br->consumed_bits = 0;
+                       if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
+                               *val <<= bits;
+                               *val |= (FLAC__uint32)(br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
+                               br->consumed_bits = bits;
+                       }
+                       return true;
+               }
+               else { /* br->consumed_bits == 0 */
+                       const brword word = br->buffer[br->consumed_words];
+                       if(bits < FLAC__BITS_PER_WORD) {
+                               *val = (FLAC__uint32)(word >> (FLAC__BITS_PER_WORD-bits));
+                               br->consumed_bits = bits;
+                               return true;
+                       }
+                       /* at this point bits == FLAC__BITS_PER_WORD == 32; because of previous assertions, it can't be larger */
+                       *val = (FLAC__uint32)word;
+                       crc16_update_word_(br, word);
+                       br->consumed_words++;
+                       return true;
+               }
+       }
+       else {
+               /* in this case we're starting our read at a partial tail word;
+                * the reader has guaranteed that we have at least 'bits' bits
+                * available to read, which makes this case simpler.
+                */
+               /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
+               if(br->consumed_bits) {
+                       /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
+                       FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
+                       *val = (FLAC__uint32)((br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits));
+                       br->consumed_bits += bits;
+                       return true;
+               }
+               else {
+                       *val = (FLAC__uint32)(br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
+                       br->consumed_bits += bits;
+                       return true;
+               }
+       }
+}
+
+FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
+{
+       FLAC__uint32 uval, mask;
+       /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
+       if(!FLAC__bitreader_read_raw_uint32(br, &uval, bits))
+               return false;
+       /* sign-extend *val assuming it is currently bits wide. */
+       /* From: https://graphics.stanford.edu/~seander/bithacks.html#FixedSignExtend */
+       mask = 1u << (bits - 1);
+       *val = (uval ^ mask) - mask;
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
+{
+       FLAC__uint32 hi, lo;
+
+       if(bits > 32) {
+               if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
+                       return false;
+               if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
+                       return false;
+               *val = hi;
+               *val <<= 32;
+               *val |= lo;
+       }
+       else {
+               if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
+                       return false;
+               *val = lo;
+       }
+       return true;
+}
+
+inline FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
+{
+       FLAC__uint32 x8, x32 = 0;
+
+       /* this doesn't need to be that fast as currently it is only used for vorbis comments */
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
+               return false;
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
+               return false;
+       x32 |= (x8 << 8);
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
+               return false;
+       x32 |= (x8 << 16);
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
+               return false;
+       x32 |= (x8 << 24);
+
+       *val = x32;
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
+{
+       /*
+        * OPT: a faster implementation is possible but probably not that useful
+        * since this is only called a couple of times in the metadata readers.
+        */
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       if(bits > 0) {
+               const unsigned n = br->consumed_bits & 7;
+               unsigned m;
+               FLAC__uint32 x;
+
+               if(n != 0) {
+                       m = flac_min(8-n, bits);
+                       if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
+                               return false;
+                       bits -= m;
+               }
+               m = bits / 8;
+               if(m > 0) {
+                       if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
+                               return false;
+                       bits %= 8;
+               }
+               if(bits > 0) {
+                       if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
+                               return false;
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
+{
+       FLAC__uint32 x;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
+
+       /* step 1: skip over partial head word to get word aligned */
+       while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               nvals--;
+       }
+       if(0 == nvals)
+               return true;
+       /* step 2: skip whole words in chunks */
+       while(nvals >= FLAC__BYTES_PER_WORD) {
+               if(br->consumed_words < br->words) {
+                       br->consumed_words++;
+                       nvals -= FLAC__BYTES_PER_WORD;
+               }
+               else if(!bitreader_read_from_client_(br))
+                       return false;
+       }
+       /* step 3: skip any remainder from partial tail bytes */
+       while(nvals) {
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               nvals--;
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
+{
+       FLAC__uint32 x;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
+
+       /* step 1: read from partial head word to get word aligned */
+       while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               *val++ = (FLAC__byte)x;
+               nvals--;
+       }
+       if(0 == nvals)
+               return true;
+       /* step 2: read whole words in chunks */
+       while(nvals >= FLAC__BYTES_PER_WORD) {
+               if(br->consumed_words < br->words) {
+                       const brword word = br->buffer[br->consumed_words++];
+#if FLAC__BYTES_PER_WORD == 4
+                       val[0] = (FLAC__byte)(word >> 24);
+                       val[1] = (FLAC__byte)(word >> 16);
+                       val[2] = (FLAC__byte)(word >> 8);
+                       val[3] = (FLAC__byte)word;
+#elif FLAC__BYTES_PER_WORD == 8
+                       val[0] = (FLAC__byte)(word >> 56);
+                       val[1] = (FLAC__byte)(word >> 48);
+                       val[2] = (FLAC__byte)(word >> 40);
+                       val[3] = (FLAC__byte)(word >> 32);
+                       val[4] = (FLAC__byte)(word >> 24);
+                       val[5] = (FLAC__byte)(word >> 16);
+                       val[6] = (FLAC__byte)(word >> 8);
+                       val[7] = (FLAC__byte)word;
+#else
+                       for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
+                               val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
+#endif
+                       val += FLAC__BYTES_PER_WORD;
+                       nvals -= FLAC__BYTES_PER_WORD;
+               }
+               else if(!bitreader_read_from_client_(br))
+                       return false;
+       }
+       /* step 3: read any remainder from partial tail bytes */
+       while(nvals) {
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               *val++ = (FLAC__byte)x;
+               nvals--;
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
+#if 0 /* slow but readable version */
+{
+       unsigned bit;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       *val = 0;
+       while(1) {
+               if(!FLAC__bitreader_read_bit(br, &bit))
+                       return false;
+               if(bit)
+                       break;
+               else
+                       *val++;
+       }
+       return true;
+}
+#else
+{
+       unsigned i;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       *val = 0;
+       while(1) {
+               while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
+                       brword b = br->buffer[br->consumed_words] << br->consumed_bits;
+                       if(b) {
+                               i = COUNT_ZERO_MSBS(b);
+                               *val += i;
+                               i++;
+                               br->consumed_bits += i;
+                               if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
+                                       crc16_update_word_(br, br->buffer[br->consumed_words]);
+                                       br->consumed_words++;
+                                       br->consumed_bits = 0;
+                               }
+                               return true;
+                       }
+                       else {
+                               *val += FLAC__BITS_PER_WORD - br->consumed_bits;
+                               crc16_update_word_(br, br->buffer[br->consumed_words]);
+                               br->consumed_words++;
+                               br->consumed_bits = 0;
+                               /* didn't find stop bit yet, have to keep going... */
+                       }
+               }
+               /* at this point we've eaten up all the whole words; have to try
+                * reading through any tail bytes before calling the read callback.
+                * this is a repeat of the above logic adjusted for the fact we
+                * don't have a whole word.  note though if the client is feeding
+                * us data a byte at a time (unlikely), br->consumed_bits may not
+                * be zero.
+                */
+               if(br->bytes*8 > br->consumed_bits) {
+                       const unsigned end = br->bytes * 8;
+                       brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
+                       if(b) {
+                               i = COUNT_ZERO_MSBS(b);
+                               *val += i;
+                               i++;
+                               br->consumed_bits += i;
+                               FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
+                               return true;
+                       }
+                       else {
+                               *val += end - br->consumed_bits;
+                               br->consumed_bits = end;
+                               FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
+                               /* didn't find stop bit yet, have to keep going... */
+                       }
+               }
+               if(!bitreader_read_from_client_(br))
+                       return false;
+       }
+}
+#endif
+
+FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
+{
+       FLAC__uint32 lsbs = 0, msbs = 0;
+       unsigned uval;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       FLAC__ASSERT(parameter <= 31);
+
+       /* read the unary MSBs and end bit */
+       if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
+               return false;
+
+       /* read the binary LSBs */
+       if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
+               return false;
+
+       /* compose the value */
+       uval = (msbs << parameter) | lsbs;
+       if(uval & 1)
+               *val = -((int)(uval >> 1)) - 1;
+       else
+               *val = (int)(uval >> 1);
+
+       return true;
+}
+
+/* this is by far the most heavily used reader call.  it ain't pretty but it's fast */
+FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
+{
+       /* try and get br->consumed_words and br->consumed_bits into register;
+        * must remember to flush them back to *br before calling other
+        * bitreader functions that use them, and before returning */
+       unsigned cwords, words, lsbs, msbs, x, y;
+       unsigned ucbits; /* keep track of the number of unconsumed bits in word */
+       brword b;
+       int *val, *end;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+       /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
+       FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
+       FLAC__ASSERT(parameter < 32);
+       /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
+
+       val = vals;
+       end = vals + nvals;
+
+       if(parameter == 0) {
+               while(val < end) {
+                       /* read the unary MSBs and end bit */
+                       if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
+                               return false;
+
+                       *val++ = (int)(msbs >> 1) ^ -(int)(msbs & 1);
+               }
+
+               return true;
+       }
+
+       FLAC__ASSERT(parameter > 0);
+
+       cwords = br->consumed_words;
+       words = br->words;
+
+       /* if we've not consumed up to a partial tail word... */
+       if(cwords >= words) {
+               x = 0;
+               goto process_tail;
+       }
+
+       ucbits = FLAC__BITS_PER_WORD - br->consumed_bits;
+       b = br->buffer[cwords] << br->consumed_bits;  /* keep unconsumed bits aligned to left */
+
+       while(val < end) {
+               /* read the unary MSBs and end bit */
+               x = y = COUNT_ZERO_MSBS2(b);
+               if(x == FLAC__BITS_PER_WORD) {
+                       x = ucbits;
+                       do {
+                               /* didn't find stop bit yet, have to keep going... */
+                               crc16_update_word_(br, br->buffer[cwords++]);
+                               if (cwords >= words)
+                                       goto incomplete_msbs;
+                               b = br->buffer[cwords];
+                               y = COUNT_ZERO_MSBS2(b);
+                               x += y;
+                       } while(y == FLAC__BITS_PER_WORD);
+               }
+               b <<= y;
+               b <<= 1; /* account for stop bit */
+               ucbits = (ucbits - x - 1) % FLAC__BITS_PER_WORD;
+               msbs = x;
+
+               /* read the binary LSBs */
+               x = (FLAC__uint32)(b >> (FLAC__BITS_PER_WORD - parameter)); /* parameter < 32, so we can cast to 32-bit unsigned */
+               if(parameter <= ucbits) {
+                       ucbits -= parameter;
+                       b <<= parameter;
+               } else {
+                       /* there are still bits left to read, they will all be in the next word */
+                       crc16_update_word_(br, br->buffer[cwords++]);
+                       if (cwords >= words)
+                               goto incomplete_lsbs;
+                       b = br->buffer[cwords];
+                       ucbits += FLAC__BITS_PER_WORD - parameter;
+                       x |= (FLAC__uint32)(b >> ucbits);
+                       b <<= FLAC__BITS_PER_WORD - ucbits;
+               }
+               lsbs = x;
+
+               /* compose the value */
+               x = (msbs << parameter) | lsbs;
+               *val++ = (int)(x >> 1) ^ -(int)(x & 1);
+
+               continue;
+
+               /* at this point we've eaten up all the whole words */
+process_tail:
+               do {
+                       if(0) {
+incomplete_msbs:
+                               br->consumed_bits = 0;
+                               br->consumed_words = cwords;
+                       }
+
+                       /* read the unary MSBs and end bit */
+                       if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
+                               return false;
+                       msbs += x;
+                       x = ucbits = 0;
+
+                       if(0) {
+incomplete_lsbs:
+                               br->consumed_bits = 0;
+                               br->consumed_words = cwords;
+                       }
+
+                       /* read the binary LSBs */
+                       if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter - ucbits))
+                               return false;
+                       lsbs = x | lsbs;
+
+                       /* compose the value */
+                       x = (msbs << parameter) | lsbs;
+                       *val++ = (int)(x >> 1) ^ -(int)(x & 1);
+                       x = 0;
+
+                       cwords = br->consumed_words;
+                       words = br->words;
+                       ucbits = FLAC__BITS_PER_WORD - br->consumed_bits;
+                       b = br->buffer[cwords] << br->consumed_bits;
+               } while(cwords >= words && val < end);
+       }
+
+       if(ucbits == 0 && cwords < words) {
+               /* don't leave the head word with no unconsumed bits */
+               crc16_update_word_(br, br->buffer[cwords++]);
+               ucbits = FLAC__BITS_PER_WORD;
+       }
+
+       br->consumed_bits = FLAC__BITS_PER_WORD - ucbits;
+       br->consumed_words = cwords;
+
+       return true;
+}
+
+#if 0 /* UNUSED */
+FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
+{
+       FLAC__uint32 lsbs = 0, msbs = 0;
+       unsigned bit, uval, k;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       k = FLAC__bitmath_ilog2(parameter);
+
+       /* read the unary MSBs and end bit */
+       if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
+               return false;
+
+       /* read the binary LSBs */
+       if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
+               return false;
+
+       if(parameter == 1u<<k) {
+               /* compose the value */
+               uval = (msbs << k) | lsbs;
+       }
+       else {
+               unsigned d = (1 << (k+1)) - parameter;
+               if(lsbs >= d) {
+                       if(!FLAC__bitreader_read_bit(br, &bit))
+                               return false;
+                       lsbs <<= 1;
+                       lsbs |= bit;
+                       lsbs -= d;
+               }
+               /* compose the value */
+               uval = msbs * parameter + lsbs;
+       }
+
+       /* unfold unsigned to signed */
+       if(uval & 1)
+               *val = -((int)(uval >> 1)) - 1;
+       else
+               *val = (int)(uval >> 1);
+
+       return true;
+}
+
+FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
+{
+       FLAC__uint32 lsbs, msbs = 0;
+       unsigned bit, k;
+
+       FLAC__ASSERT(0 != br);
+       FLAC__ASSERT(0 != br->buffer);
+
+       k = FLAC__bitmath_ilog2(parameter);
+
+       /* read the unary MSBs and end bit */
+       if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
+               return false;
+
+       /* read the binary LSBs */
+       if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
+               return false;
+
+       if(parameter == 1u<<k) {
+               /* compose the value */
+               *val = (msbs << k) | lsbs;
+       }
+       else {
+               unsigned d = (1 << (k+1)) - parameter;
+               if(lsbs >= d) {
+                       if(!FLAC__bitreader_read_bit(br, &bit))
+                               return false;
+                       lsbs <<= 1;
+                       lsbs |= bit;
+                       lsbs -= d;
+               }
+               /* compose the value */
+               *val = msbs * parameter + lsbs;
+       }
+
+       return true;
+}
+#endif /* UNUSED */
+
+/* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
+FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
+{
+       FLAC__uint32 v = 0;
+       FLAC__uint32 x;
+       unsigned i;
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+               return false;
+       if(raw)
+               raw[(*rawlen)++] = (FLAC__byte)x;
+       if(!(x & 0x80)) { /* 0xxxxxxx */
+               v = x;
+               i = 0;
+       }
+       else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
+               v = x & 0x1F;
+               i = 1;
+       }
+       else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
+               v = x & 0x0F;
+               i = 2;
+       }
+       else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
+               v = x & 0x07;
+               i = 3;
+       }
+       else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
+               v = x & 0x03;
+               i = 4;
+       }
+       else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
+               v = x & 0x01;
+               i = 5;
+       }
+       else {
+               *val = 0xffffffff;
+               return true;
+       }
+       for( ; i; i--) {
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               if(raw)
+                       raw[(*rawlen)++] = (FLAC__byte)x;
+               if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
+                       *val = 0xffffffff;
+                       return true;
+               }
+               v <<= 6;
+               v |= (x & 0x3F);
+       }
+       *val = v;
+       return true;
+}
+
+/* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
+FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
+{
+       FLAC__uint64 v = 0;
+       FLAC__uint32 x;
+       unsigned i;
+
+       if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+               return false;
+       if(raw)
+               raw[(*rawlen)++] = (FLAC__byte)x;
+       if(!(x & 0x80)) { /* 0xxxxxxx */
+               v = x;
+               i = 0;
+       }
+       else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
+               v = x & 0x1F;
+               i = 1;
+       }
+       else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
+               v = x & 0x0F;
+               i = 2;
+       }
+       else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
+               v = x & 0x07;
+               i = 3;
+       }
+       else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
+               v = x & 0x03;
+               i = 4;
+       }
+       else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
+               v = x & 0x01;
+               i = 5;
+       }
+       else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
+               v = 0;
+               i = 6;
+       }
+       else {
+               *val = FLAC__U64L(0xffffffffffffffff);
+               return true;
+       }
+       for( ; i; i--) {
+               if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
+                       return false;
+               if(raw)
+                       raw[(*rawlen)++] = (FLAC__byte)x;
+               if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
+                       *val = FLAC__U64L(0xffffffffffffffff);
+                       return true;
+               }
+               v <<= 6;
+               v |= (x & 0x3F);
+       }
+       *val = v;
+       return true;
+}
+
+/* These functions are declared inline in this file but are also callable as
+ * externs from elsewhere.
+ * According to the C99 spec, section 6.7.4, simply providing a function
+ * prototype in a header file without 'inline' and making the function inline
+ * in this file should be sufficient.
+ * Unfortunately, the Microsoft VS compiler doesn't pick them up externally. To
+ * fix that we add extern declarations here.
+ */
+extern FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
+extern unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
+extern unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
+extern FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val);
diff --git a/FLAC/src/bitwriter.c b/FLAC/src/bitwriter.c
new file mode 100644 (file)
index 0000000..402b1c4
--- /dev/null
@@ -0,0 +1,881 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+#include "private/bitwriter.h"
+#include "private/crc.h"
+#include "private/macros.h"
+#include "FLAC/assert.h"
+#include "share/alloc.h"
+#include "share/compat.h"
+#include "share/endswap.h"
+
+/* Things should be fastest when this matches the machine word size */
+/* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
+/* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
+
+#if (ENABLE_64_BIT_WORDS == 0)
+
+typedef FLAC__uint32 bwword;
+#define FLAC__BYTES_PER_WORD 4         /* sizeof bwword */
+#define FLAC__BITS_PER_WORD 32
+/* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
+#if WORDS_BIGENDIAN
+#define SWAP_BE_WORD_TO_HOST(x) (x)
+#else
+#define SWAP_BE_WORD_TO_HOST(x) ENDSWAP_32(x)
+#endif
+
+#else
+
+typedef FLAC__uint64 bwword;
+#define FLAC__BYTES_PER_WORD 8         /* sizeof bwword */
+#define FLAC__BITS_PER_WORD 64
+/* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
+#if WORDS_BIGENDIAN
+#define SWAP_BE_WORD_TO_HOST(x) (x)
+#else
+#define SWAP_BE_WORD_TO_HOST(x) ENDSWAP_64(x)
+#endif
+
+#endif
+
+/*
+ * The default capacity here doesn't matter too much.  The buffer always grows
+ * to hold whatever is written to it.  Usually the encoder will stop adding at
+ * a frame or metadata block, then write that out and clear the buffer for the
+ * next one.
+ */
+static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
+/* When growing, increment 4K at a time */
+static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
+
+#define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
+#define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
+
+struct FLAC__BitWriter {
+       bwword *buffer;
+       bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
+       unsigned capacity; /* capacity of buffer in words */
+       unsigned words; /* # of complete words in buffer */
+       unsigned bits; /* # of used bits in accum */
+};
+
+/* * WATCHOUT: The current implementation only grows the buffer. */
+#ifndef __SUNPRO_C
+static
+#endif
+FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
+{
+       unsigned new_capacity;
+       bwword *new_buffer;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+
+       /* calculate total words needed to store 'bits_to_add' additional bits */
+       new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
+
+       /* it's possible (due to pessimism in the growth estimation that
+        * leads to this call) that we don't actually need to grow
+        */
+       if(bw->capacity >= new_capacity)
+               return true;
+
+       /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
+       if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
+               new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
+       /* make sure we got everything right */
+       FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
+       FLAC__ASSERT(new_capacity > bw->capacity);
+       FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
+
+       new_buffer = safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
+       if(new_buffer == 0)
+               return false;
+       bw->buffer = new_buffer;
+       bw->capacity = new_capacity;
+       return true;
+}
+
+
+/***********************************************************************
+ *
+ * Class constructor/destructor
+ *
+ ***********************************************************************/
+
+FLAC__BitWriter *FLAC__bitwriter_new(void)
+{
+       FLAC__BitWriter *bw = calloc(1, sizeof(FLAC__BitWriter));
+       /* note that calloc() sets all members to 0 for us */
+       return bw;
+}
+
+void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
+{
+       FLAC__ASSERT(0 != bw);
+
+       FLAC__bitwriter_free(bw);
+       free(bw);
+}
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
+{
+       FLAC__ASSERT(0 != bw);
+
+       bw->words = bw->bits = 0;
+       bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
+       bw->buffer = malloc(sizeof(bwword) * bw->capacity);
+       if(bw->buffer == 0)
+               return false;
+
+       return true;
+}
+
+void FLAC__bitwriter_free(FLAC__BitWriter *bw)
+{
+       FLAC__ASSERT(0 != bw);
+
+       if(0 != bw->buffer)
+               free(bw->buffer);
+       bw->buffer = 0;
+       bw->capacity = 0;
+       bw->words = bw->bits = 0;
+}
+
+void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
+{
+       bw->words = bw->bits = 0;
+}
+
+void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
+{
+       unsigned i, j;
+       if(bw == 0) {
+               fprintf(out, "bitwriter is NULL\n");
+       }
+       else {
+               fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
+
+               for(i = 0; i < bw->words; i++) {
+                       fprintf(out, "%08X: ", i);
+                       for(j = 0; j < FLAC__BITS_PER_WORD; j++)
+                               fprintf(out, "%01u", bw->buffer[i] & ((bwword)1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
+                       fprintf(out, "\n");
+               }
+               if(bw->bits > 0) {
+                       fprintf(out, "%08X: ", i);
+                       for(j = 0; j < bw->bits; j++)
+                               fprintf(out, "%01u", bw->accum & ((bwword)1 << (bw->bits-j-1)) ? 1:0);
+                       fprintf(out, "\n");
+               }
+       }
+}
+
+FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
+{
+       const FLAC__byte *buffer;
+       size_t bytes;
+
+       FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
+
+       if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
+               return false;
+
+       *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
+       FLAC__bitwriter_release_buffer(bw);
+       return true;
+}
+
+FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
+{
+       const FLAC__byte *buffer;
+       size_t bytes;
+
+       FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
+
+       if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
+               return false;
+
+       *crc = FLAC__crc8(buffer, bytes);
+       FLAC__bitwriter_release_buffer(bw);
+       return true;
+}
+
+FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
+{
+       return ((bw->bits & 7) == 0);
+}
+
+unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
+{
+       return FLAC__TOTAL_BITS(bw);
+}
+
+FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
+{
+       FLAC__ASSERT((bw->bits & 7) == 0);
+       /* double protection */
+       if(bw->bits & 7)
+               return false;
+       /* if we have bits in the accumulator we have to flush those to the buffer first */
+       if(bw->bits) {
+               FLAC__ASSERT(bw->words <= bw->capacity);
+               if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
+                       return false;
+               /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
+               bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
+       }
+       /* now we can just return what we have */
+       *buffer = (FLAC__byte*)bw->buffer;
+       *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
+       return true;
+}
+
+void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
+{
+       /* nothing to do.  in the future, strict checking of a 'writer-is-in-
+        * get-mode' flag could be added everywhere and then cleared here
+        */
+       (void)bw;
+}
+
+inline FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
+{
+       unsigned n;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+
+       if(bits == 0)
+               return true;
+       /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
+       if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
+               return false;
+       /* first part gets to word alignment */
+       if(bw->bits) {
+               n = flac_min(FLAC__BITS_PER_WORD - bw->bits, bits);
+               bw->accum <<= n;
+               bits -= n;
+               bw->bits += n;
+               if(bw->bits == FLAC__BITS_PER_WORD) {
+                       bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
+                       bw->bits = 0;
+               }
+               else
+                       return true;
+       }
+       /* do whole words */
+       while(bits >= FLAC__BITS_PER_WORD) {
+               bw->buffer[bw->words++] = 0;
+               bits -= FLAC__BITS_PER_WORD;
+       }
+       /* do any leftovers */
+       if(bits > 0) {
+               bw->accum = 0;
+               bw->bits = bits;
+       }
+       return true;
+}
+
+static inline FLAC__bool FLAC__bitwriter_write_raw_uint32_nocheck(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
+{
+       register unsigned left;
+
+       /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
+       FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
+
+       if(bw == 0 || bw->buffer == 0)
+               return false;
+
+       if (bits > 32)
+               return false;
+
+       if(bits == 0)
+               return true;
+
+       FLAC__ASSERT((bits == 32) || (val>>bits == 0));
+
+       /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
+       if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
+               return false;
+
+       left = FLAC__BITS_PER_WORD - bw->bits;
+       if(bits < left) {
+               bw->accum <<= bits;
+               bw->accum |= val;
+               bw->bits += bits;
+       }
+       else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
+               bw->accum <<= left;
+               bw->accum |= val >> (bw->bits = bits - left);
+               bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
+               bw->accum = val; /* unused top bits can contain garbage */
+       }
+       else { /* at this point bits == FLAC__BITS_PER_WORD == 32  and  bw->bits == 0 */
+               bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST((bwword)val);
+       }
+
+       return true;
+}
+
+inline FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
+{
+       /* check that unused bits are unset */
+       if((bits < 32) && (val>>bits != 0))
+               return false;
+
+       return FLAC__bitwriter_write_raw_uint32_nocheck(bw, val, bits);
+}
+
+inline FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
+{
+       /* zero-out unused bits */
+       if(bits < 32)
+               val &= (~(0xffffffff << bits));
+
+       return FLAC__bitwriter_write_raw_uint32_nocheck(bw, (FLAC__uint32)val, bits);
+}
+
+inline FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
+{
+       /* this could be a little faster but it's not used for much */
+       if(bits > 32) {
+               return
+                       FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
+                       FLAC__bitwriter_write_raw_uint32_nocheck(bw, (FLAC__uint32)val, 32);
+       }
+       else
+               return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
+}
+
+inline FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
+{
+       /* this doesn't need to be that fast as currently it is only used for vorbis comments */
+
+       if(!FLAC__bitwriter_write_raw_uint32_nocheck(bw, val & 0xff, 8))
+               return false;
+       if(!FLAC__bitwriter_write_raw_uint32_nocheck(bw, (val>>8) & 0xff, 8))
+               return false;
+       if(!FLAC__bitwriter_write_raw_uint32_nocheck(bw, (val>>16) & 0xff, 8))
+               return false;
+       if(!FLAC__bitwriter_write_raw_uint32_nocheck(bw, val>>24, 8))
+               return false;
+
+       return true;
+}
+
+inline FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
+{
+       unsigned i;
+
+       /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
+       for(i = 0; i < nvals; i++) {
+               if(!FLAC__bitwriter_write_raw_uint32_nocheck(bw, (FLAC__uint32)(vals[i]), 8))
+                       return false;
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
+{
+       if(val < 32)
+               return FLAC__bitwriter_write_raw_uint32_nocheck(bw, 1, ++val);
+       else
+               return
+                       FLAC__bitwriter_write_zeroes(bw, val) &&
+                       FLAC__bitwriter_write_raw_uint32_nocheck(bw, 1, 1);
+}
+
+unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
+{
+       FLAC__uint32 uval;
+
+       FLAC__ASSERT(parameter < 32);
+
+       /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
+       uval = val;
+       uval <<= 1;
+       uval ^= (val>>31);
+
+       return 1 + parameter + (uval >> parameter);
+}
+
+#if 0 /* UNUSED */
+unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
+{
+       unsigned bits, msbs, uval;
+       unsigned k;
+
+       FLAC__ASSERT(parameter > 0);
+
+       /* fold signed to unsigned */
+       if(val < 0)
+               uval = (unsigned)(((-(++val)) << 1) + 1);
+       else
+               uval = (unsigned)(val << 1);
+
+       k = FLAC__bitmath_ilog2(parameter);
+       if(parameter == 1u<<k) {
+               FLAC__ASSERT(k <= 30);
+
+               msbs = uval >> k;
+               bits = 1 + k + msbs;
+       }
+       else {
+               unsigned q, r, d;
+
+               d = (1 << (k+1)) - parameter;
+               q = uval / parameter;
+               r = uval - (q * parameter);
+
+               bits = 1 + q + k;
+               if(r >= d)
+                       bits++;
+       }
+       return bits;
+}
+
+unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
+{
+       unsigned bits, msbs;
+       unsigned k;
+
+       FLAC__ASSERT(parameter > 0);
+
+       k = FLAC__bitmath_ilog2(parameter);
+       if(parameter == 1u<<k) {
+               FLAC__ASSERT(k <= 30);
+
+               msbs = uval >> k;
+               bits = 1 + k + msbs;
+       }
+       else {
+               unsigned q, r, d;
+
+               d = (1 << (k+1)) - parameter;
+               q = uval / parameter;
+               r = uval - (q * parameter);
+
+               bits = 1 + q + k;
+               if(r >= d)
+                       bits++;
+       }
+       return bits;
+}
+#endif /* UNUSED */
+
+FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
+{
+       unsigned total_bits, interesting_bits, msbs;
+       FLAC__uint32 uval, pattern;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+       FLAC__ASSERT(parameter < 32);
+
+       /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
+       uval = val;
+       uval <<= 1;
+       uval ^= (val>>31);
+
+       msbs = uval >> parameter;
+       interesting_bits = 1 + parameter;
+       total_bits = interesting_bits + msbs;
+       pattern = 1 << parameter; /* the unary end bit */
+       pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
+
+       if(total_bits <= 32)
+               return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
+       else
+               return
+                       FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
+                       FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
+}
+
+FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
+{
+       const FLAC__uint32 mask1 = (FLAC__uint32)0xffffffff << parameter; /* we val|=mask1 to set the stop bit above it... */
+       const FLAC__uint32 mask2 = (FLAC__uint32)0xffffffff >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2 */
+       FLAC__uint32 uval;
+       unsigned left;
+       const unsigned lsbits = 1 + parameter;
+       unsigned msbits, total_bits;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+       FLAC__ASSERT(parameter < 31);
+       /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
+       FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
+
+       while(nvals) {
+               /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
+               uval = *vals;
+               uval <<= 1;
+               uval ^= (*vals>>31);
+
+               msbits = uval >> parameter;
+               total_bits = lsbits + msbits;
+
+               if(bw->bits && bw->bits + total_bits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
+                       /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
+                       bw->bits += total_bits;
+                       uval |= mask1; /* set stop bit */
+                       uval &= mask2; /* mask off unused top bits */
+                       bw->accum <<= total_bits;
+                       bw->accum |= uval;
+               }
+               else {
+                       /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
+                       /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
+                       if(bw->capacity <= bw->words + bw->bits + msbits + 1 /* lsbits always fit in 1 bwword */ && !bitwriter_grow_(bw, total_bits))
+                               return false;
+
+                       if(msbits) {
+                               /* first part gets to word alignment */
+                               if(bw->bits) {
+                                       left = FLAC__BITS_PER_WORD - bw->bits;
+                                       if(msbits < left) {
+                                               bw->accum <<= msbits;
+                                               bw->bits += msbits;
+                                               goto break1;
+                                       }
+                                       else {
+                                               bw->accum <<= left;
+                                               msbits -= left;
+                                               bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
+                                               bw->bits = 0;
+                                       }
+                               }
+                               /* do whole words */
+                               while(msbits >= FLAC__BITS_PER_WORD) {
+                                       bw->buffer[bw->words++] = 0;
+                                       msbits -= FLAC__BITS_PER_WORD;
+                               }
+                               /* do any leftovers */
+                               if(msbits > 0) {
+                                       bw->accum = 0;
+                                       bw->bits = msbits;
+                               }
+                       }
+break1:
+                       uval |= mask1; /* set stop bit */
+                       uval &= mask2; /* mask off unused top bits */
+
+                       left = FLAC__BITS_PER_WORD - bw->bits;
+                       if(lsbits < left) {
+                               bw->accum <<= lsbits;
+                               bw->accum |= uval;
+                               bw->bits += lsbits;
+                       }
+                       else {
+                               /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
+                                * be > lsbits (because of previous assertions) so it would have
+                                * triggered the (lsbits<left) case above.
+                                */
+                               FLAC__ASSERT(bw->bits);
+                               FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
+                               bw->accum <<= left;
+                               bw->accum |= uval >> (bw->bits = lsbits - left);
+                               bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
+                               bw->accum = uval; /* unused top bits can contain garbage */
+                       }
+               }
+               vals++;
+               nvals--;
+       }
+       return true;
+}
+
+#if 0 /* UNUSED */
+FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
+{
+       unsigned total_bits, msbs, uval;
+       unsigned k;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+       FLAC__ASSERT(parameter > 0);
+
+       /* fold signed to unsigned */
+       if(val < 0)
+               uval = (unsigned)(((-(++val)) << 1) + 1);
+       else
+               uval = (unsigned)(val << 1);
+
+       k = FLAC__bitmath_ilog2(parameter);
+       if(parameter == 1u<<k) {
+               unsigned pattern;
+
+               FLAC__ASSERT(k <= 30);
+
+               msbs = uval >> k;
+               total_bits = 1 + k + msbs;
+               pattern = 1 << k; /* the unary end bit */
+               pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
+
+               if(total_bits <= 32) {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
+                               return false;
+               }
+               else {
+                       /* write the unary MSBs */
+                       if(!FLAC__bitwriter_write_zeroes(bw, msbs))
+                               return false;
+                       /* write the unary end bit and binary LSBs */
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
+                               return false;
+               }
+       }
+       else {
+               unsigned q, r, d;
+
+               d = (1 << (k+1)) - parameter;
+               q = uval / parameter;
+               r = uval - (q * parameter);
+               /* write the unary MSBs */
+               if(!FLAC__bitwriter_write_zeroes(bw, q))
+                       return false;
+               /* write the unary end bit */
+               if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
+                       return false;
+               /* write the binary LSBs */
+               if(r >= d) {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
+                               return false;
+               }
+               else {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
+                               return false;
+               }
+       }
+       return true;
+}
+
+FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
+{
+       unsigned total_bits, msbs;
+       unsigned k;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+       FLAC__ASSERT(parameter > 0);
+
+       k = FLAC__bitmath_ilog2(parameter);
+       if(parameter == 1u<<k) {
+               unsigned pattern;
+
+               FLAC__ASSERT(k <= 30);
+
+               msbs = uval >> k;
+               total_bits = 1 + k + msbs;
+               pattern = 1 << k; /* the unary end bit */
+               pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
+
+               if(total_bits <= 32) {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
+                               return false;
+               }
+               else {
+                       /* write the unary MSBs */
+                       if(!FLAC__bitwriter_write_zeroes(bw, msbs))
+                               return false;
+                       /* write the unary end bit and binary LSBs */
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
+                               return false;
+               }
+       }
+       else {
+               unsigned q, r, d;
+
+               d = (1 << (k+1)) - parameter;
+               q = uval / parameter;
+               r = uval - (q * parameter);
+               /* write the unary MSBs */
+               if(!FLAC__bitwriter_write_zeroes(bw, q))
+                       return false;
+               /* write the unary end bit */
+               if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
+                       return false;
+               /* write the binary LSBs */
+               if(r >= d) {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
+                               return false;
+               }
+               else {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
+                               return false;
+               }
+       }
+       return true;
+}
+#endif /* UNUSED */
+
+FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
+{
+       FLAC__bool ok = 1;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+
+       if((val & 0x80000000) != 0) /* this version only handles 31 bits */
+               return false;
+
+       if(val < 0x80) {
+               return FLAC__bitwriter_write_raw_uint32_nocheck(bw, val, 8);
+       }
+       else if(val < 0x800) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xC0 | (val>>6), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (val&0x3F), 8);
+       }
+       else if(val < 0x10000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xE0 | (val>>12), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (val&0x3F), 8);
+       }
+       else if(val < 0x200000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xF0 | (val>>18), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (val&0x3F), 8);
+       }
+       else if(val < 0x4000000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xF8 | (val>>24), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>18)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (val&0x3F), 8);
+       }
+       else {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xFC | (val>>30), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>24)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>18)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | ((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (val&0x3F), 8);
+       }
+
+       return ok;
+}
+
+FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
+{
+       FLAC__bool ok = 1;
+
+       FLAC__ASSERT(0 != bw);
+       FLAC__ASSERT(0 != bw->buffer);
+
+       if((val & FLAC__U64L(0xFFFFFFF000000000)) != 0) /* this version only handles 36 bits */
+               return false;
+
+       if(val < 0x80) {
+               return FLAC__bitwriter_write_raw_uint32_nocheck(bw, (FLAC__uint32)val, 8);
+       }
+       else if(val < 0x800) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+       else if(val < 0x10000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+       else if(val < 0x200000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+       else if(val < 0x4000000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+       else if(val < 0x80000000) {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+       else {
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0xFE, 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
+               ok &= FLAC__bitwriter_write_raw_uint32_nocheck(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
+       }
+
+       return ok;
+}
+
+FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
+{
+       /* 0-pad to byte boundary */
+       if(bw->bits & 7u)
+               return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
+       else
+               return true;
+}
+
+/* These functions are declared inline in this file but are also callable as
+ * externs from elsewhere.
+ * According to the C99 spec, section 6.7.4, simply providing a function
+ * prototype in a header file without 'inline' and making the function inline
+ * in this file should be sufficient.
+ * Unfortunately, the Microsoft VS compiler doesn't pick them up externally. To
+ * fix that we add extern declarations here.
+ */
+extern FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
+extern FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
+extern FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
+extern FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
+extern FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val);
+extern FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
diff --git a/FLAC/src/cpu.c b/FLAC/src/cpu.c
new file mode 100644 (file)
index 0000000..ad3ebdd
--- /dev/null
@@ -0,0 +1,292 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+#include "share/compat.h"
+#include <stdlib.h>
+#include <memory.h>
+
+#if defined(_MSC_VER)
+#  include <intrin.h> /* for __cpuid() and _xgetbv() */
+#endif
+
+#if defined __GNUC__ && defined HAVE_CPUID_H
+#  include <cpuid.h> /* for __get_cpuid() and __get_cpuid_max() */
+#endif
+
+#ifdef DEBUG
+#include <stdio.h>
+
+#define dfprintf fprintf
+#else
+/* This is bad practice, it should be a static void empty function */
+#define dfprintf(file, format, ...)
+#endif
+
+
+#if defined FLAC__CPU_IA32
+/* these are flags in EDX of CPUID AX=00000001 */
+static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
+#endif
+
+#if FLAC__HAS_X86INTRIN || FLAC__AVX_SUPPORTED
+/* these are flags in ECX of CPUID AX=00000001 */
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE41 = 0x00080000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE42 = 0x00100000;
+
+/* these are flags in ECX of CPUID AX=00000001 */
+static const unsigned FLAC__CPUINFO_IA32_CPUID_OSXSAVE = 0x08000000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_AVX = 0x10000000;
+static const unsigned FLAC__CPUINFO_IA32_CPUID_FMA = 0x00001000;
+/* these are flags in EBX of CPUID AX=00000007 */
+static const unsigned FLAC__CPUINFO_IA32_CPUID_AVX2 = 0x00000020;
+#endif
+
+#if defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64
+static uint32_t
+cpu_xgetbv_x86(void)
+{
+#if (defined _MSC_VER || defined __INTEL_COMPILER) && FLAC__HAS_X86INTRIN && FLAC__AVX_SUPPORTED
+       return (uint32_t)_xgetbv(0);
+#elif defined __GNUC__
+       uint32_t lo, hi;
+       asm volatile (".byte 0x0f, 0x01, 0xd0" : "=a"(lo), "=d"(hi) : "c" (0));
+       return lo;
+#else
+       return 0;
+#endif
+}
+#endif
+
+static void
+ia32_cpu_info (FLAC__CPUInfo *info)
+{
+#if !defined FLAC__CPU_IA32
+       (void) info;
+#else
+       FLAC__bool ia32_osxsave = false;
+       FLAC__uint32 flags_eax, flags_ebx, flags_ecx, flags_edx;
+
+#if !defined FLAC__NO_ASM && (defined FLAC__HAS_NASM || FLAC__HAS_X86INTRIN)
+       info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
+#if defined FLAC__HAS_NASM
+       if(!FLAC__cpu_have_cpuid_asm_ia32())
+               return;
+#endif
+       /* http://www.sandpile.org/x86/cpuid.htm */
+#if FLAC__HAS_X86INTRIN
+               FLAC__cpu_info_x86(0, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+               info->ia32.intel = (flags_ebx == 0x756E6547 && flags_edx == 0x49656E69 && flags_ecx == 0x6C65746E) ? true : false; /* GenuineIntel */
+               FLAC__cpu_info_x86(1, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+#else
+               FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
+#endif
+
+       info->ia32.cmov  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV ) ? true : false;
+       info->ia32.mmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX  ) ? true : false;
+       info->ia32.sse   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE  ) ? true : false;
+       info->ia32.sse2  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 ) ? true : false;
+       info->ia32.sse3  = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 ) ? true : false;
+       info->ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3) ? true : false;
+       info->ia32.sse41 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE41) ? true : false;
+       info->ia32.sse42 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE42) ? true : false;
+
+       if (FLAC__HAS_X86INTRIN && FLAC__AVX_SUPPORTED) {
+               ia32_osxsave = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_OSXSAVE) ? true : false;
+               info->ia32.avx   = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_AVX    ) ? true : false;
+               info->ia32.fma   = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_FMA    ) ? true : false;
+               FLAC__cpu_info_x86(7, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+               info->ia32.avx2  = (flags_ebx & FLAC__CPUINFO_IA32_CPUID_AVX2   ) ? true : false;
+       }
+
+       dfprintf(stderr, "CPU info (IA-32):\n");
+       dfprintf(stderr, "  CMOV ....... %c\n", info->ia32.cmov    ? 'Y' : 'n');
+       dfprintf(stderr, "  MMX ........ %c\n", info->ia32.mmx     ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE ........ %c\n", info->ia32.sse     ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE2 ....... %c\n", info->ia32.sse2    ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE3 ....... %c\n", info->ia32.sse3    ? 'Y' : 'n');
+       dfprintf(stderr, "  SSSE3 ...... %c\n", info->ia32.ssse3   ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE41 ...... %c\n", info->ia32.sse41   ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE42 ...... %c\n", info->ia32.sse42   ? 'Y' : 'n');
+
+       if (FLAC__HAS_X86INTRIN && FLAC__AVX_SUPPORTED) {
+               dfprintf(stderr, "  AVX ........ %c\n", info->ia32.avx     ? 'Y' : 'n');
+               dfprintf(stderr, "  FMA ........ %c\n", info->ia32.fma     ? 'Y' : 'n');
+               dfprintf(stderr, "  AVX2 ....... %c\n", info->ia32.avx2    ? 'Y' : 'n');
+       }
+
+       /*
+        * now have to check for OS support of AVX instructions
+        */
+       if (!FLAC__HAS_X86INTRIN || !info->ia32.avx || !ia32_osxsave || (cpu_xgetbv_x86() & 0x6) != 0x6) {
+               /* no OS AVX support */
+               info->ia32.avx     = false;
+               info->ia32.avx2    = false;
+               info->ia32.fma     = false;
+       }
+
+       if (FLAC__HAS_X86INTRIN && FLAC__AVX_SUPPORTED) {
+               dfprintf(stderr, "  AVX OS sup . %c\n", info->ia32.avx ? 'Y' : 'n');
+       }
+#else
+       info->use_asm = false;
+#endif
+#endif
+}
+
+static void
+x86_64_cpu_info (FLAC__CPUInfo *info)
+{
+#if !defined FLAC__NO_ASM && FLAC__HAS_X86INTRIN
+       FLAC__bool x86_osxsave = false;
+       FLAC__uint32 flags_eax, flags_ebx, flags_ecx, flags_edx;
+
+       info->use_asm = true;
+
+       /* http://www.sandpile.org/x86/cpuid.htm */
+       FLAC__cpu_info_x86(0, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+       info->x86.intel = (flags_ebx == 0x756E6547 && flags_edx == 0x49656E69 && flags_ecx == 0x6C65746E) ? true : false; /* GenuineIntel */
+       FLAC__cpu_info_x86(1, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+       info->x86.sse3  = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 ) ? true : false;
+       info->x86.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3) ? true : false;
+       info->x86.sse41 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE41) ? true : false;
+       info->x86.sse42 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE42) ? true : false;
+
+       if (FLAC__AVX_SUPPORTED) {
+               x86_osxsave = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_OSXSAVE) ? true : false;
+               info->x86.avx   = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_AVX    ) ? true : false;
+               info->x86.fma   = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_FMA    ) ? true : false;
+               FLAC__cpu_info_x86(7, &flags_eax, &flags_ebx, &flags_ecx, &flags_edx);
+               info->x86.avx2  = (flags_ebx & FLAC__CPUINFO_IA32_CPUID_AVX2   ) ? true : false;
+       }
+
+       dfprintf(stderr, "CPU info (x86-64):\n");
+       dfprintf(stderr, "  SSE3 ....... %c\n", info->x86.sse3  ? 'Y' : 'n');
+       dfprintf(stderr, "  SSSE3 ...... %c\n", info->x86.ssse3 ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE41 ...... %c\n", info->x86.sse41 ? 'Y' : 'n');
+       dfprintf(stderr, "  SSE42 ...... %c\n", info->x86.sse42 ? 'Y' : 'n');
+
+       if (FLAC__AVX_SUPPORTED) {
+               dfprintf(stderr, "  AVX ........ %c\n", info->x86.avx   ? 'Y' : 'n');
+               dfprintf(stderr, "  FMA ........ %c\n", info->x86.fma   ? 'Y' : 'n');
+               dfprintf(stderr, "  AVX2 ....... %c\n", info->x86.avx2  ? 'Y' : 'n');
+       }
+
+       /*
+        * now have to check for OS support of AVX instructions
+        */
+       if (!info->x86.avx || !x86_osxsave || (cpu_xgetbv_x86() & 0x6) != 0x6) {
+               /* no OS AVX support */
+               info->x86.avx     = false;
+               info->x86.avx2    = false;
+               info->x86.fma     = false;
+       }
+
+       if (FLAC__AVX_SUPPORTED) {
+               dfprintf(stderr, "  AVX OS sup . %c\n", info->x86.avx ? 'Y' : 'n');
+       }
+#else
+       /* Silence compiler warnings. */
+       (void) info;
+#if defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64
+       if (0) cpu_xgetbv_x86 ();
+#endif
+#endif
+}
+
+void FLAC__cpu_info (FLAC__CPUInfo *info)
+{
+       memset(info, 0, sizeof(*info));
+
+#ifdef FLAC__CPU_IA32
+       info->type = FLAC__CPUINFO_TYPE_IA32;
+#elif defined FLAC__CPU_X86_64
+       info->type = FLAC__CPUINFO_TYPE_X86_64;
+#else
+       info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
+       info->use_asm = false;
+#endif
+
+       switch (info->type) {
+       case FLAC__CPUINFO_TYPE_IA32:
+               ia32_cpu_info (info);
+               break;
+       case FLAC__CPUINFO_TYPE_X86_64:
+               x86_64_cpu_info (info);
+               break;
+       default:
+               info->use_asm = false;
+               break;
+       }
+}
+
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+
+void FLAC__cpu_info_x86(FLAC__uint32 level, FLAC__uint32 *eax, FLAC__uint32 *ebx, FLAC__uint32 *ecx, FLAC__uint32 *edx)
+{
+#if defined _MSC_VER || defined __INTEL_COMPILER
+       int cpuinfo[4];
+       int ext = level & 0x80000000;
+       __cpuid(cpuinfo, ext);
+       if((unsigned)cpuinfo[0] >= level) {
+#if FLAC__AVX_SUPPORTED
+               __cpuidex(cpuinfo, ext, 0); /* for AVX2 detection */
+#else
+               __cpuid(cpuinfo, ext); /* some old compilers don't support __cpuidex */
+#endif
+
+               *eax = cpuinfo[0]; *ebx = cpuinfo[1]; *ecx = cpuinfo[2]; *edx = cpuinfo[3];
+
+               return;
+       }
+#elif defined __GNUC__ && defined HAVE_CPUID_H
+       FLAC__uint32 ext = level & 0x80000000;
+       __cpuid(ext, *eax, *ebx, *ecx, *edx);
+       if (*eax >= level) {
+               __cpuid_count(level, 0, *eax, *ebx, *ecx, *edx);
+
+               return;
+       }
+#endif
+       *eax = *ebx = *ecx = *edx = 0;
+}
+
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
diff --git a/FLAC/src/crc.c b/FLAC/src/crc.c
new file mode 100644 (file)
index 0000000..8123c3b
--- /dev/null
@@ -0,0 +1,143 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/crc.h"
+
+/* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
+
+FLAC__byte const FLAC__crc8_table[256] = {
+       0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
+       0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
+       0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
+       0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
+       0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
+       0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
+       0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
+       0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
+       0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
+       0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
+       0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
+       0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
+       0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
+       0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
+       0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
+       0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
+       0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
+       0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
+       0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
+       0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
+       0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
+       0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
+       0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
+       0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
+       0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
+       0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
+       0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
+       0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
+       0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
+       0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
+       0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
+       0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
+};
+
+/* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
+
+unsigned const FLAC__crc16_table[256] = {
+       0x0000,  0x8005,  0x800f,  0x000a,  0x801b,  0x001e,  0x0014,  0x8011,
+       0x8033,  0x0036,  0x003c,  0x8039,  0x0028,  0x802d,  0x8027,  0x0022,
+       0x8063,  0x0066,  0x006c,  0x8069,  0x0078,  0x807d,  0x8077,  0x0072,
+       0x0050,  0x8055,  0x805f,  0x005a,  0x804b,  0x004e,  0x0044,  0x8041,
+       0x80c3,  0x00c6,  0x00cc,  0x80c9,  0x00d8,  0x80dd,  0x80d7,  0x00d2,
+       0x00f0,  0x80f5,  0x80ff,  0x00fa,  0x80eb,  0x00ee,  0x00e4,  0x80e1,
+       0x00a0,  0x80a5,  0x80af,  0x00aa,  0x80bb,  0x00be,  0x00b4,  0x80b1,
+       0x8093,  0x0096,  0x009c,  0x8099,  0x0088,  0x808d,  0x8087,  0x0082,
+       0x8183,  0x0186,  0x018c,  0x8189,  0x0198,  0x819d,  0x8197,  0x0192,
+       0x01b0,  0x81b5,  0x81bf,  0x01ba,  0x81ab,  0x01ae,  0x01a4,  0x81a1,
+       0x01e0,  0x81e5,  0x81ef,  0x01ea,  0x81fb,  0x01fe,  0x01f4,  0x81f1,
+       0x81d3,  0x01d6,  0x01dc,  0x81d9,  0x01c8,  0x81cd,  0x81c7,  0x01c2,
+       0x0140,  0x8145,  0x814f,  0x014a,  0x815b,  0x015e,  0x0154,  0x8151,
+       0x8173,  0x0176,  0x017c,  0x8179,  0x0168,  0x816d,  0x8167,  0x0162,
+       0x8123,  0x0126,  0x012c,  0x8129,  0x0138,  0x813d,  0x8137,  0x0132,
+       0x0110,  0x8115,  0x811f,  0x011a,  0x810b,  0x010e,  0x0104,  0x8101,
+       0x8303,  0x0306,  0x030c,  0x8309,  0x0318,  0x831d,  0x8317,  0x0312,
+       0x0330,  0x8335,  0x833f,  0x033a,  0x832b,  0x032e,  0x0324,  0x8321,
+       0x0360,  0x8365,  0x836f,  0x036a,  0x837b,  0x037e,  0x0374,  0x8371,
+       0x8353,  0x0356,  0x035c,  0x8359,  0x0348,  0x834d,  0x8347,  0x0342,
+       0x03c0,  0x83c5,  0x83cf,  0x03ca,  0x83db,  0x03de,  0x03d4,  0x83d1,
+       0x83f3,  0x03f6,  0x03fc,  0x83f9,  0x03e8,  0x83ed,  0x83e7,  0x03e2,
+       0x83a3,  0x03a6,  0x03ac,  0x83a9,  0x03b8,  0x83bd,  0x83b7,  0x03b2,
+       0x0390,  0x8395,  0x839f,  0x039a,  0x838b,  0x038e,  0x0384,  0x8381,
+       0x0280,  0x8285,  0x828f,  0x028a,  0x829b,  0x029e,  0x0294,  0x8291,
+       0x82b3,  0x02b6,  0x02bc,  0x82b9,  0x02a8,  0x82ad,  0x82a7,  0x02a2,
+       0x82e3,  0x02e6,  0x02ec,  0x82e9,  0x02f8,  0x82fd,  0x82f7,  0x02f2,
+       0x02d0,  0x82d5,  0x82df,  0x02da,  0x82cb,  0x02ce,  0x02c4,  0x82c1,
+       0x8243,  0x0246,  0x024c,  0x8249,  0x0258,  0x825d,  0x8257,  0x0252,
+       0x0270,  0x8275,  0x827f,  0x027a,  0x826b,  0x026e,  0x0264,  0x8261,
+       0x0220,  0x8225,  0x822f,  0x022a,  0x823b,  0x023e,  0x0234,  0x8231,
+       0x8213,  0x0216,  0x021c,  0x8219,  0x0208,  0x820d,  0x8207,  0x0202
+};
+
+
+void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
+{
+       *crc = FLAC__crc8_table[*crc ^ data];
+}
+
+void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
+{
+       while(len--)
+               *crc = FLAC__crc8_table[*crc ^ *data++];
+}
+
+FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
+{
+       FLAC__uint8 crc = 0;
+
+       while(len--)
+               crc = FLAC__crc8_table[crc ^ *data++];
+
+       return crc;
+}
+
+unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
+{
+       unsigned crc = 0;
+
+       while(len--)
+               crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
+
+       return crc;
+}
diff --git a/FLAC/src/fixed.c b/FLAC/src/fixed.c
new file mode 100644 (file)
index 0000000..1e2d5b2
--- /dev/null
@@ -0,0 +1,395 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <string.h>
+#include "share/compat.h"
+#include "private/bitmath.h"
+#include "private/fixed.h"
+#include "private/macros.h"
+#include "FLAC/assert.h"
+
+#ifdef local_abs
+#undef local_abs
+#endif
+#define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
+
+#ifdef FLAC__INTEGER_ONLY_LIBRARY
+/* rbps stands for residual bits per sample
+ *
+ *             (ln(2) * err)
+ * rbps = log  (-----------)
+ *           2 (     n     )
+ */
+static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
+{
+       FLAC__uint32 rbps;
+       unsigned bits; /* the number of bits required to represent a number */
+       int fracbits; /* the number of bits of rbps that comprise the fractional part */
+
+       FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
+       FLAC__ASSERT(err > 0);
+       FLAC__ASSERT(n > 0);
+
+       FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
+       if(err <= n)
+               return 0;
+       /*
+        * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
+        * These allow us later to know we won't lose too much precision in the
+        * fixed-point division (err<<fracbits)/n.
+        */
+
+       fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
+
+       err <<= fracbits;
+       err /= n;
+       /* err now holds err/n with fracbits fractional bits */
+
+       /*
+        * Whittle err down to 16 bits max.  16 significant bits is enough for
+        * our purposes.
+        */
+       FLAC__ASSERT(err > 0);
+       bits = FLAC__bitmath_ilog2(err)+1;
+       if(bits > 16) {
+               err >>= (bits-16);
+               fracbits -= (bits-16);
+       }
+       rbps = (FLAC__uint32)err;
+
+       /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
+       rbps *= FLAC__FP_LN2;
+       fracbits += 16;
+       FLAC__ASSERT(fracbits >= 0);
+
+       /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
+       {
+               const int f = fracbits & 3;
+               if(f) {
+                       rbps >>= f;
+                       fracbits -= f;
+               }
+       }
+
+       rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
+
+       if(rbps == 0)
+               return 0;
+
+       /*
+        * The return value must have 16 fractional bits.  Since the whole part
+        * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
+        * must be >= -3, these assertion allows us to be able to shift rbps
+        * left if necessary to get 16 fracbits without losing any bits of the
+        * whole part of rbps.
+        *
+        * There is a slight chance due to accumulated error that the whole part
+        * will require 6 bits, so we use 6 in the assertion.  Really though as
+        * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
+        */
+       FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
+       FLAC__ASSERT(fracbits >= -3);
+
+       /* now shift the decimal point into place */
+       if(fracbits < 16)
+               return rbps << (16-fracbits);
+       else if(fracbits > 16)
+               return rbps >> (fracbits-16);
+       else
+               return rbps;
+}
+
+static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
+{
+       FLAC__uint32 rbps;
+       unsigned bits; /* the number of bits required to represent a number */
+       int fracbits; /* the number of bits of rbps that comprise the fractional part */
+
+       FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
+       FLAC__ASSERT(err > 0);
+       FLAC__ASSERT(n > 0);
+
+       FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
+       if(err <= n)
+               return 0;
+       /*
+        * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
+        * These allow us later to know we won't lose too much precision in the
+        * fixed-point division (err<<fracbits)/n.
+        */
+
+       fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
+
+       err <<= fracbits;
+       err /= n;
+       /* err now holds err/n with fracbits fractional bits */
+
+       /*
+        * Whittle err down to 16 bits max.  16 significant bits is enough for
+        * our purposes.
+        */
+       FLAC__ASSERT(err > 0);
+       bits = FLAC__bitmath_ilog2_wide(err)+1;
+       if(bits > 16) {
+               err >>= (bits-16);
+               fracbits -= (bits-16);
+       }
+       rbps = (FLAC__uint32)err;
+
+       /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
+       rbps *= FLAC__FP_LN2;
+       fracbits += 16;
+       FLAC__ASSERT(fracbits >= 0);
+
+       /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
+       {
+               const int f = fracbits & 3;
+               if(f) {
+                       rbps >>= f;
+                       fracbits -= f;
+               }
+       }
+
+       rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
+
+       if(rbps == 0)
+               return 0;
+
+       /*
+        * The return value must have 16 fractional bits.  Since the whole part
+        * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
+        * must be >= -3, these assertion allows us to be able to shift rbps
+        * left if necessary to get 16 fracbits without losing any bits of the
+        * whole part of rbps.
+        *
+        * There is a slight chance due to accumulated error that the whole part
+        * will require 6 bits, so we use 6 in the assertion.  Really though as
+        * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
+        */
+       FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
+       FLAC__ASSERT(fracbits >= -3);
+
+       /* now shift the decimal point into place */
+       if(fracbits < 16)
+               return rbps << (16-fracbits);
+       else if(fracbits > 16)
+               return rbps >> (fracbits-16);
+       else
+               return rbps;
+}
+#endif
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
+#else
+unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
+#endif
+{
+       FLAC__int32 last_error_0 = data[-1];
+       FLAC__int32 last_error_1 = data[-1] - data[-2];
+       FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
+       FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
+       FLAC__int32 error, save;
+       FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
+       unsigned i, order;
+
+       for(i = 0; i < data_len; i++) {
+               error  = data[i]     ; total_error_0 += local_abs(error);                      save = error;
+               error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
+               error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
+               error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
+               error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
+       }
+
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+#else
+       residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
+       residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
+       residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
+       residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
+       residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
+#endif
+
+       return order;
+}
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
+#else
+unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
+#endif
+{
+       FLAC__int32 last_error_0 = data[-1];
+       FLAC__int32 last_error_1 = data[-1] - data[-2];
+       FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
+       FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
+       FLAC__int32 error, save;
+       /* total_error_* are 64-bits to avoid overflow when encoding
+        * erratic signals when the bits-per-sample and blocksize are
+        * large.
+        */
+       FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
+       unsigned i, order;
+
+       for(i = 0; i < data_len; i++) {
+               error  = data[i]     ; total_error_0 += local_abs(error);                      save = error;
+               error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
+               error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
+               error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
+               error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
+       }
+
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+#else
+       residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
+       residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
+       residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
+       residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
+       residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
+#endif
+
+       return order;
+}
+
+void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
+{
+       const int idata_len = (int)data_len;
+       int i;
+
+       switch(order) {
+               case 0:
+                       FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
+                       memcpy(residual, data, sizeof(residual[0])*data_len);
+                       break;
+               case 1:
+                       for(i = 0; i < idata_len; i++)
+                               residual[i] = data[i] - data[i-1];
+                       break;
+               case 2:
+                       for(i = 0; i < idata_len; i++)
+                               residual[i] = data[i] - 2*data[i-1] + data[i-2];
+                       break;
+               case 3:
+                       for(i = 0; i < idata_len; i++)
+                               residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
+                       break;
+               case 4:
+                       for(i = 0; i < idata_len; i++)
+                               residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+}
+
+void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
+{
+       int i, idata_len = (int)data_len;
+
+       switch(order) {
+               case 0:
+                       FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
+                       memcpy(data, residual, sizeof(residual[0])*data_len);
+                       break;
+               case 1:
+                       for(i = 0; i < idata_len; i++)
+                               data[i] = residual[i] + data[i-1];
+                       break;
+               case 2:
+                       for(i = 0; i < idata_len; i++)
+                               data[i] = residual[i] + 2*data[i-1] - data[i-2];
+                       break;
+               case 3:
+                       for(i = 0; i < idata_len; i++)
+                               data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
+                       break;
+               case 4:
+                       for(i = 0; i < idata_len; i++)
+                               data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+}
diff --git a/FLAC/src/fixed_intrin_sse2.c b/FLAC/src/fixed_intrin_sse2.c
new file mode 100644 (file)
index 0000000..6a9b4dd
--- /dev/null
@@ -0,0 +1,255 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && defined FLAC__HAS_X86INTRIN
+#include "private/fixed.h"
+#ifdef FLAC__SSE2_SUPPORTED
+
+#include <emmintrin.h> /* SSE2 */
+#include <math.h>
+#include "private/macros.h"
+#include "share/compat.h"
+#include "FLAC/assert.h"
+
+#ifdef FLAC__CPU_IA32
+#define m128i_to_i64(dest, src) _mm_storel_epi64((__m128i*)&dest, src)
+#else
+#define m128i_to_i64(dest, src) dest = _mm_cvtsi128_si64(src)
+#endif
+
+FLAC__SSE_TARGET("sse2")
+unsigned FLAC__fixed_compute_best_predictor_intrin_sse2(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1])
+{
+       FLAC__uint32 total_error_0, total_error_1, total_error_2, total_error_3, total_error_4;
+       unsigned i, order;
+
+       __m128i total_err0, total_err1, total_err2;
+
+       {
+               FLAC__int32 itmp;
+               __m128i last_error;
+
+               last_error = _mm_cvtsi32_si128(data[-1]);                                                       // 0   0   0   le0
+               itmp = data[-2];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   0   le0 le1
+               itmp -= data[-3];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   le0 le1 le2
+               itmp -= data[-3] - data[-4];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // le0 le1 le2 le3
+
+               total_err0 = total_err1 = _mm_setzero_si128();
+               for(i = 0; i < data_len; i++) {
+                       __m128i err0, err1, tmp;
+                       err0 = _mm_cvtsi32_si128(data[i]);                                                              // 0   0   0   e0
+                       err1 = _mm_shuffle_epi32(err0, _MM_SHUFFLE(0,0,0,0));                   // e0  e0  e0  e0
+#if 1 /* OPT_SSE */
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   le0 le1 le2
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   le0 le1
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   0   le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#else
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 8));  // le0  le1  le2+le0  le3+le1
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 4));  // le0  le1+le0  le2+le0+le1  le3+le1+le2+le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#endif
+                       tmp = _mm_slli_si128(err0, 12);                                                                 // e0   0   0   0
+                       last_error = _mm_srli_si128(err1, 4);                                                   //  0  e1  e2  e3
+                       last_error = _mm_or_si128(last_error, tmp);                                             // e0  e1  e2  e3
+
+                       tmp = _mm_srai_epi32(err0, 31);
+                       err0 = _mm_xor_si128(err0, tmp);
+                       err0 = _mm_sub_epi32(err0, tmp);
+                       tmp = _mm_srai_epi32(err1, 31);
+                       err1 = _mm_xor_si128(err1, tmp);
+                       err1 = _mm_sub_epi32(err1, tmp);
+
+                       total_err0 = _mm_add_epi32(total_err0, err0);                                   // 0   0   0   te0
+                       total_err1 = _mm_add_epi32(total_err1, err1);                                   // te1 te2 te3 te4
+               }
+       }
+
+       total_error_0 = _mm_cvtsi128_si32(total_err0);
+       total_err2 = total_err1;                                                                                        // te1  te2  te3  te4
+       total_err1 = _mm_srli_si128(total_err1, 8);                                                     //  0    0   te1  te2
+       total_error_4 = _mm_cvtsi128_si32(total_err2);
+       total_error_2 = _mm_cvtsi128_si32(total_err1);
+       total_err2 = _mm_srli_si128(total_err2, 4);                                                     //  0   te1  te2  te3
+       total_err1 = _mm_srli_si128(total_err1, 4);                                                     //  0    0    0   te1
+       total_error_3 = _mm_cvtsi128_si32(total_err2);
+       total_error_1 = _mm_cvtsi128_si32(total_err1);
+
+       /* prefer higher order */
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+
+       return order;
+}
+
+FLAC__SSE_TARGET("sse2")
+unsigned FLAC__fixed_compute_best_predictor_wide_intrin_sse2(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1])
+{
+       FLAC__uint64 total_error_0, total_error_1, total_error_2, total_error_3, total_error_4;
+       unsigned i, order;
+
+       __m128i total_err0, total_err1, total_err3;
+
+       {
+               FLAC__int32 itmp;
+               __m128i last_error, zero = _mm_setzero_si128();
+
+               last_error = _mm_cvtsi32_si128(data[-1]);                                                       // 0   0   0   le0
+               itmp = data[-2];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   0   le0 le1
+               itmp -= data[-3];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   le0 le1 le2
+               itmp -= data[-3] - data[-4];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // le0 le1 le2 le3
+
+               total_err0 = total_err1 = total_err3 = _mm_setzero_si128();
+               for(i = 0; i < data_len; i++) {
+                       __m128i err0, err1, tmp;
+                       err0 = _mm_cvtsi32_si128(data[i]);                                                              // 0   0   0   e0
+                       err1 = _mm_shuffle_epi32(err0, _MM_SHUFFLE(0,0,0,0));                   // e0  e0  e0  e0
+#if 1 /* OPT_SSE */
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   le0 le1 le2
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   le0 le1
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   0   le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#else
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 8));  // le0  le1  le2+le0  le3+le1
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 4));  // le0  le1+le0  le2+le0+le1  le3+le1+le2+le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#endif
+                       tmp = _mm_slli_si128(err0, 12);                                                                 // e0   0   0   0
+                       last_error = _mm_srli_si128(err1, 4);                                                   //  0  e1  e2  e3
+                       last_error = _mm_or_si128(last_error, tmp);                                             // e0  e1  e2  e3
+
+                       tmp = _mm_srai_epi32(err0, 31);
+                       err0 = _mm_xor_si128(err0, tmp);
+                       err0 = _mm_sub_epi32(err0, tmp);
+                       tmp = _mm_srai_epi32(err1, 31);
+                       err1 = _mm_xor_si128(err1, tmp);
+                       err1 = _mm_sub_epi32(err1, tmp);
+
+                       total_err0 = _mm_add_epi64(total_err0, err0);                                   //        0       te0
+                       err0 = _mm_unpacklo_epi32(err1, zero);                                                  //   0  |e3|   0  |e4|
+                       err1 = _mm_unpackhi_epi32(err1, zero);                                                  //   0  |e1|   0  |e2|
+                       total_err3 = _mm_add_epi64(total_err3, err0);                                   //       te3      te4
+                       total_err1 = _mm_add_epi64(total_err1, err1);                                   //       te1      te2
+               }
+       }
+
+       m128i_to_i64(total_error_0, total_err0);
+       m128i_to_i64(total_error_4, total_err3);
+       m128i_to_i64(total_error_2, total_err1);
+       total_err3 = _mm_srli_si128(total_err3, 8);                                                     //         0      te3
+       total_err1 = _mm_srli_si128(total_err1, 8);                                                     //         0      te1
+       m128i_to_i64(total_error_3, total_err3);
+       m128i_to_i64(total_error_1, total_err1);
+
+       /* prefer higher order */
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+
+       return order;
+}
+
+#endif /* FLAC__SSE2_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/fixed_intrin_ssse3.c b/FLAC/src/fixed_intrin_ssse3.c
new file mode 100644 (file)
index 0000000..f4d93e8
--- /dev/null
@@ -0,0 +1,243 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/fixed.h"
+#ifdef FLAC__SSSE3_SUPPORTED
+
+#include <tmmintrin.h> /* SSSE3 */
+#include <math.h>
+#include "private/macros.h"
+#include "share/compat.h"
+#include "FLAC/assert.h"
+
+#ifdef FLAC__CPU_IA32
+#define m128i_to_i64(dest, src) _mm_storel_epi64((__m128i*)&dest, src)
+#else
+#define m128i_to_i64(dest, src) dest = _mm_cvtsi128_si64(src)
+#endif
+
+FLAC__SSE_TARGET("ssse3")
+unsigned FLAC__fixed_compute_best_predictor_intrin_ssse3(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1])
+{
+       FLAC__uint32 total_error_0, total_error_1, total_error_2, total_error_3, total_error_4;
+       unsigned i, order;
+
+       __m128i total_err0, total_err1, total_err2;
+
+       {
+               FLAC__int32 itmp;
+               __m128i last_error;
+
+               last_error = _mm_cvtsi32_si128(data[-1]);                                                       // 0   0   0   le0
+               itmp = data[-2];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   0   le0 le1
+               itmp -= data[-3];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   le0 le1 le2
+               itmp -= data[-3] - data[-4];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // le0 le1 le2 le3
+
+               total_err0 = total_err1 = _mm_setzero_si128();
+               for(i = 0; i < data_len; i++) {
+                       __m128i err0, err1;
+                       err0 = _mm_cvtsi32_si128(data[i]);                                                              // 0   0   0   e0
+                       err1 = _mm_shuffle_epi32(err0, _MM_SHUFFLE(0,0,0,0));                   // e0  e0  e0  e0
+#if 1 /* OPT_SSE */
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   le0 le1 le2
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   le0 le1
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   0   le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#else
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 8));  // le0  le1  le2+le0  le3+le1
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 4));  // le0  le1+le0  le2+le0+le1  le3+le1+le2+le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#endif
+                       last_error = _mm_alignr_epi8(err0, err1, 4);                                    // e0  e1  e2  e3
+
+                       err0 = _mm_abs_epi32(err0);
+                       err1 = _mm_abs_epi32(err1);
+
+                       total_err0 = _mm_add_epi32(total_err0, err0);                                   // 0   0   0   te0
+                       total_err1 = _mm_add_epi32(total_err1, err1);                                   // te1 te2 te3 te4
+               }
+       }
+
+       total_error_0 = _mm_cvtsi128_si32(total_err0);
+       total_err2 = total_err1;                                                                                        // te1  te2  te3  te4
+       total_err1 = _mm_srli_si128(total_err1, 8);                                                     //  0    0   te1  te2
+       total_error_4 = _mm_cvtsi128_si32(total_err2);
+       total_error_2 = _mm_cvtsi128_si32(total_err1);
+       total_err2 = _mm_srli_si128(total_err2, 4);                                                     //  0   te1  te2  te3
+       total_err1 = _mm_srli_si128(total_err1, 4);                                                     //  0    0    0   te1
+       total_error_3 = _mm_cvtsi128_si32(total_err2);
+       total_error_1 = _mm_cvtsi128_si32(total_err1);
+
+       /* prefer higher order */
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+
+       return order;
+}
+
+FLAC__SSE_TARGET("ssse3")
+unsigned FLAC__fixed_compute_best_predictor_wide_intrin_ssse3(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1])
+{
+       FLAC__uint64 total_error_0, total_error_1, total_error_2, total_error_3, total_error_4;
+       unsigned i, order;
+
+       __m128i total_err0, total_err1, total_err3;
+
+       {
+               FLAC__int32 itmp;
+               __m128i last_error, zero = _mm_setzero_si128();
+
+               last_error = _mm_cvtsi32_si128(data[-1]);                                                       // 0   0   0   le0
+               itmp = data[-2];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   0   le0 le1
+               itmp -= data[-3];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // 0   le0 le1 le2
+               itmp -= data[-3] - data[-4];
+               last_error = _mm_shuffle_epi32(last_error, _MM_SHUFFLE(2,1,0,0));
+               last_error = _mm_sub_epi32(last_error, _mm_cvtsi32_si128(itmp));        // le0 le1 le2 le3
+
+               total_err0 = total_err1 = total_err3 = _mm_setzero_si128();
+               for(i = 0; i < data_len; i++) {
+                       __m128i err0, err1;
+                       err0 = _mm_cvtsi32_si128(data[i]);                                                              // 0   0   0   e0
+                       err1 = _mm_shuffle_epi32(err0, _MM_SHUFFLE(0,0,0,0));                   // e0  e0  e0  e0
+#if 1 /* OPT_SSE */
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   le0 le1 le2
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   le0 le1
+                       err1 = _mm_sub_epi32(err1, last_error);
+                       last_error = _mm_srli_si128(last_error, 4);                                             // 0   0   0   le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#else
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 8));  // le0  le1  le2+le0  le3+le1
+                       last_error = _mm_add_epi32(last_error, _mm_srli_si128(last_error, 4));  // le0  le1+le0  le2+le0+le1  le3+le1+le2+le0
+                       err1 = _mm_sub_epi32(err1, last_error);                                                 // e1  e2  e3  e4
+#endif
+                       last_error = _mm_alignr_epi8(err0, err1, 4);                                    // e0  e1  e2  e3
+
+                       err0 = _mm_abs_epi32(err0);
+                       err1 = _mm_abs_epi32(err1);                                                                             // |e1| |e2| |e3| |e4|
+
+                       total_err0 = _mm_add_epi64(total_err0, err0);                                   //        0       te0
+                       err0 = _mm_unpacklo_epi32(err1, zero);                                                  //   0  |e3|   0  |e4|
+                       err1 = _mm_unpackhi_epi32(err1, zero);                                                  //   0  |e1|   0  |e2|
+                       total_err3 = _mm_add_epi64(total_err3, err0);                                   //       te3      te4
+                       total_err1 = _mm_add_epi64(total_err1, err1);                                   //       te1      te2
+               }
+       }
+
+       m128i_to_i64(total_error_0, total_err0);
+       m128i_to_i64(total_error_4, total_err3);
+       m128i_to_i64(total_error_2, total_err1);
+       total_err3 = _mm_srli_si128(total_err3, 8);                                                     //         0      te3
+       total_err1 = _mm_srli_si128(total_err1, 8);                                                     //         0      te1
+       m128i_to_i64(total_error_3, total_err3);
+       m128i_to_i64(total_error_1, total_err1);
+
+       /* prefer higher order */
+       if(total_error_0 < flac_min(flac_min(flac_min(total_error_1, total_error_2), total_error_3), total_error_4))
+               order = 0;
+       else if(total_error_1 < flac_min(flac_min(total_error_2, total_error_3), total_error_4))
+               order = 1;
+       else if(total_error_2 < flac_min(total_error_3, total_error_4))
+               order = 2;
+       else if(total_error_3 < total_error_4)
+               order = 3;
+       else
+               order = 4;
+
+       /* Estimate the expected number of bits per residual signal sample. */
+       /* 'total_error*' is linearly related to the variance of the residual */
+       /* signal, so we use it directly to compute E(|x|) */
+       FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
+       FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
+
+       residual_bits_per_sample[0] = (float)((total_error_0 > 0) ? log(M_LN2 * (double)total_error_0 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[1] = (float)((total_error_1 > 0) ? log(M_LN2 * (double)total_error_1 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[2] = (float)((total_error_2 > 0) ? log(M_LN2 * (double)total_error_2 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[3] = (float)((total_error_3 > 0) ? log(M_LN2 * (double)total_error_3 / (double)data_len) / M_LN2 : 0.0);
+       residual_bits_per_sample[4] = (float)((total_error_4 > 0) ? log(M_LN2 * (double)total_error_4 / (double)data_len) / M_LN2 : 0.0);
+
+       return order;
+}
+
+#endif /* FLAC__SSSE3_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/float.c b/FLAC/src/float.c
new file mode 100644 (file)
index 0000000..25d1a78
--- /dev/null
@@ -0,0 +1,302 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "FLAC/assert.h"
+#include "share/compat.h"
+#include "private/float.h"
+
+#ifdef FLAC__INTEGER_ONLY_LIBRARY
+
+const FLAC__fixedpoint FLAC__FP_ZERO = 0;
+const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
+const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
+const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
+const FLAC__fixedpoint FLAC__FP_E = 178145;
+
+/* Lookup tables for Knuth's logarithm algorithm */
+#define LOG2_LOOKUP_PRECISION 16
+static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
+       {
+               /*
+                * 0 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00000001,
+               /* lg(4/3) = */ 0x00000000,
+               /* lg(8/7) = */ 0x00000000,
+               /* lg(16/15) = */ 0x00000000,
+               /* lg(32/31) = */ 0x00000000,
+               /* lg(64/63) = */ 0x00000000,
+               /* lg(128/127) = */ 0x00000000,
+               /* lg(256/255) = */ 0x00000000,
+               /* lg(512/511) = */ 0x00000000,
+               /* lg(1024/1023) = */ 0x00000000,
+               /* lg(2048/2047) = */ 0x00000000,
+               /* lg(4096/4095) = */ 0x00000000,
+               /* lg(8192/8191) = */ 0x00000000,
+               /* lg(16384/16383) = */ 0x00000000,
+               /* lg(32768/32767) = */ 0x00000000
+       },
+       {
+               /*
+                * 4 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00000010,
+               /* lg(4/3) = */ 0x00000007,
+               /* lg(8/7) = */ 0x00000003,
+               /* lg(16/15) = */ 0x00000001,
+               /* lg(32/31) = */ 0x00000001,
+               /* lg(64/63) = */ 0x00000000,
+               /* lg(128/127) = */ 0x00000000,
+               /* lg(256/255) = */ 0x00000000,
+               /* lg(512/511) = */ 0x00000000,
+               /* lg(1024/1023) = */ 0x00000000,
+               /* lg(2048/2047) = */ 0x00000000,
+               /* lg(4096/4095) = */ 0x00000000,
+               /* lg(8192/8191) = */ 0x00000000,
+               /* lg(16384/16383) = */ 0x00000000,
+               /* lg(32768/32767) = */ 0x00000000
+       },
+       {
+               /*
+                * 8 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00000100,
+               /* lg(4/3) = */ 0x0000006a,
+               /* lg(8/7) = */ 0x00000031,
+               /* lg(16/15) = */ 0x00000018,
+               /* lg(32/31) = */ 0x0000000c,
+               /* lg(64/63) = */ 0x00000006,
+               /* lg(128/127) = */ 0x00000003,
+               /* lg(256/255) = */ 0x00000001,
+               /* lg(512/511) = */ 0x00000001,
+               /* lg(1024/1023) = */ 0x00000000,
+               /* lg(2048/2047) = */ 0x00000000,
+               /* lg(4096/4095) = */ 0x00000000,
+               /* lg(8192/8191) = */ 0x00000000,
+               /* lg(16384/16383) = */ 0x00000000,
+               /* lg(32768/32767) = */ 0x00000000
+       },
+       {
+               /*
+                * 12 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00001000,
+               /* lg(4/3) = */ 0x000006a4,
+               /* lg(8/7) = */ 0x00000315,
+               /* lg(16/15) = */ 0x0000017d,
+               /* lg(32/31) = */ 0x000000bc,
+               /* lg(64/63) = */ 0x0000005d,
+               /* lg(128/127) = */ 0x0000002e,
+               /* lg(256/255) = */ 0x00000017,
+               /* lg(512/511) = */ 0x0000000c,
+               /* lg(1024/1023) = */ 0x00000006,
+               /* lg(2048/2047) = */ 0x00000003,
+               /* lg(4096/4095) = */ 0x00000001,
+               /* lg(8192/8191) = */ 0x00000001,
+               /* lg(16384/16383) = */ 0x00000000,
+               /* lg(32768/32767) = */ 0x00000000
+       },
+       {
+               /*
+                * 16 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00010000,
+               /* lg(4/3) = */ 0x00006a40,
+               /* lg(8/7) = */ 0x00003151,
+               /* lg(16/15) = */ 0x000017d6,
+               /* lg(32/31) = */ 0x00000bba,
+               /* lg(64/63) = */ 0x000005d1,
+               /* lg(128/127) = */ 0x000002e6,
+               /* lg(256/255) = */ 0x00000172,
+               /* lg(512/511) = */ 0x000000b9,
+               /* lg(1024/1023) = */ 0x0000005c,
+               /* lg(2048/2047) = */ 0x0000002e,
+               /* lg(4096/4095) = */ 0x00000017,
+               /* lg(8192/8191) = */ 0x0000000c,
+               /* lg(16384/16383) = */ 0x00000006,
+               /* lg(32768/32767) = */ 0x00000003
+       },
+       {
+               /*
+                * 20 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x00100000,
+               /* lg(4/3) = */ 0x0006a3fe,
+               /* lg(8/7) = */ 0x00031513,
+               /* lg(16/15) = */ 0x00017d60,
+               /* lg(32/31) = */ 0x0000bb9d,
+               /* lg(64/63) = */ 0x00005d10,
+               /* lg(128/127) = */ 0x00002e59,
+               /* lg(256/255) = */ 0x00001721,
+               /* lg(512/511) = */ 0x00000b8e,
+               /* lg(1024/1023) = */ 0x000005c6,
+               /* lg(2048/2047) = */ 0x000002e3,
+               /* lg(4096/4095) = */ 0x00000171,
+               /* lg(8192/8191) = */ 0x000000b9,
+               /* lg(16384/16383) = */ 0x0000005c,
+               /* lg(32768/32767) = */ 0x0000002e
+       },
+       {
+               /*
+                * 24 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x01000000,
+               /* lg(4/3) = */ 0x006a3fe6,
+               /* lg(8/7) = */ 0x00315130,
+               /* lg(16/15) = */ 0x0017d605,
+               /* lg(32/31) = */ 0x000bb9ca,
+               /* lg(64/63) = */ 0x0005d0fc,
+               /* lg(128/127) = */ 0x0002e58f,
+               /* lg(256/255) = */ 0x0001720e,
+               /* lg(512/511) = */ 0x0000b8d8,
+               /* lg(1024/1023) = */ 0x00005c61,
+               /* lg(2048/2047) = */ 0x00002e2d,
+               /* lg(4096/4095) = */ 0x00001716,
+               /* lg(8192/8191) = */ 0x00000b8b,
+               /* lg(16384/16383) = */ 0x000005c5,
+               /* lg(32768/32767) = */ 0x000002e3
+       },
+       {
+               /*
+                * 28 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ 0x10000000,
+               /* lg(4/3) = */ 0x06a3fe5c,
+               /* lg(8/7) = */ 0x03151301,
+               /* lg(16/15) = */ 0x017d6049,
+               /* lg(32/31) = */ 0x00bb9ca6,
+               /* lg(64/63) = */ 0x005d0fba,
+               /* lg(128/127) = */ 0x002e58f7,
+               /* lg(256/255) = */ 0x001720da,
+               /* lg(512/511) = */ 0x000b8d87,
+               /* lg(1024/1023) = */ 0x0005c60b,
+               /* lg(2048/2047) = */ 0x0002e2d7,
+               /* lg(4096/4095) = */ 0x00017160,
+               /* lg(8192/8191) = */ 0x0000b8ad,
+               /* lg(16384/16383) = */ 0x00005c56,
+               /* lg(32768/32767) = */ 0x00002e2b
+       }
+};
+
+#if 0
+static const FLAC__uint64 log2_lookup_wide[] = {
+       {
+               /*
+                * 32 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ FLAC__U64L(0x100000000),
+               /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
+               /* lg(8/7) = */ FLAC__U64L(0x31513015),
+               /* lg(16/15) = */ FLAC__U64L(0x17d60497),
+               /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
+               /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
+               /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
+               /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
+               /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
+               /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
+               /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
+               /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
+               /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
+               /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
+               /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
+       },
+       {
+               /*
+                * 48 fraction bits
+                */
+               /* undefined */ 0x00000000,
+               /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
+               /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
+               /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
+               /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
+               /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
+               /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
+               /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
+               /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
+               /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
+               /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
+               /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
+               /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
+               /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
+               /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
+               /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
+       }
+};
+#endif
+
+FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
+{
+       const FLAC__uint32 ONE = (1u << fracbits);
+       const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
+
+       FLAC__ASSERT(fracbits < 32);
+       FLAC__ASSERT((fracbits & 0x3) == 0);
+
+       if(x < ONE)
+               return 0;
+
+       if(precision > LOG2_LOOKUP_PRECISION)
+               precision = LOG2_LOOKUP_PRECISION;
+
+       /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
+       {
+               FLAC__uint32 y = 0;
+               FLAC__uint32 z = x >> 1, k = 1;
+               while (x > ONE && k < precision) {
+                       if (x - z >= ONE) {
+                               x -= z;
+                               z = x >> k;
+                               y += table[k];
+                       }
+                       else {
+                               z >>= 1;
+                               k++;
+                       }
+               }
+               return y;
+       }
+}
+
+#endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/format.c b/FLAC/src/format.c
new file mode 100644 (file)
index 0000000..214bd09
--- /dev/null
@@ -0,0 +1,589 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdio.h>
+#include <stdlib.h> /* for qsort() */
+#include <string.h> /* for memset() */
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+#include "share/alloc.h"
+#include "share/compat.h"
+#include "private/format.h"
+#include "private/macros.h"
+
+/* PACKAGE_VERSION should come from configure */
+FLAC_API const char *FLAC__VERSION_STRING = PACKAGE_VERSION;
+
+FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " PACKAGE_VERSION " 20170101";
+
+FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
+FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
+FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
+
+FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
+
+FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
+FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
+
+FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
+FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
+FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
+
+FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
+
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
+
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
+FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
+
+FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
+       "PARTITIONED_RICE",
+       "PARTITIONED_RICE2"
+};
+
+FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
+FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
+
+FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
+FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
+FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
+
+FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
+FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
+FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
+FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
+
+FLAC_API const char * const FLAC__SubframeTypeString[] = {
+       "CONSTANT",
+       "VERBATIM",
+       "FIXED",
+       "LPC"
+};
+
+FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
+       "INDEPENDENT",
+       "LEFT_SIDE",
+       "RIGHT_SIDE",
+       "MID_SIDE"
+};
+
+FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
+       "FRAME_NUMBER_TYPE_FRAME_NUMBER",
+       "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
+};
+
+FLAC_API const char * const FLAC__MetadataTypeString[] = {
+       "STREAMINFO",
+       "PADDING",
+       "APPLICATION",
+       "SEEKTABLE",
+       "VORBIS_COMMENT",
+       "CUESHEET",
+       "PICTURE"
+};
+
+FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
+       "Other",
+       "32x32 pixels 'file icon' (PNG only)",
+       "Other file icon",
+       "Cover (front)",
+       "Cover (back)",
+       "Leaflet page",
+       "Media (e.g. label side of CD)",
+       "Lead artist/lead performer/soloist",
+       "Artist/performer",
+       "Conductor",
+       "Band/Orchestra",
+       "Composer",
+       "Lyricist/text writer",
+       "Recording Location",
+       "During recording",
+       "During performance",
+       "Movie/video screen capture",
+       "A bright coloured fish",
+       "Illustration",
+       "Band/artist logotype",
+       "Publisher/Studio logotype"
+};
+
+FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
+{
+       if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
+               return false;
+       }
+       else
+               return true;
+}
+
+FLAC_API FLAC__bool FLAC__format_blocksize_is_subset(unsigned blocksize, unsigned sample_rate)
+{
+       if(blocksize > 16384)
+               return false;
+       else if(sample_rate <= 48000 && blocksize > 4608)
+               return false;
+       else
+               return true;
+}
+
+FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
+{
+       if(
+               !FLAC__format_sample_rate_is_valid(sample_rate) ||
+               (
+                       sample_rate >= (1u << 16) &&
+                       !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
+               )
+       ) {
+               return false;
+       }
+       else
+               return true;
+}
+
+/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
+FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
+{
+       unsigned i;
+       FLAC__uint64 prev_sample_number = 0;
+       FLAC__bool got_prev = false;
+
+       FLAC__ASSERT(0 != seek_table);
+
+       for(i = 0; i < seek_table->num_points; i++) {
+               if(got_prev) {
+                       if(
+                               seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
+                               seek_table->points[i].sample_number <= prev_sample_number
+                       )
+                               return false;
+               }
+               prev_sample_number = seek_table->points[i].sample_number;
+               got_prev = true;
+       }
+
+       return true;
+}
+
+/* used as the sort predicate for qsort() */
+static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
+{
+       /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
+       if(l->sample_number == r->sample_number)
+               return 0;
+       else if(l->sample_number < r->sample_number)
+               return -1;
+       else
+               return 1;
+}
+
+/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
+FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
+{
+       unsigned i, j;
+       FLAC__bool first;
+
+       FLAC__ASSERT(0 != seek_table);
+
+       if (seek_table->num_points == 0)
+               return 0;
+
+       /* sort the seekpoints */
+       qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
+
+       /* uniquify the seekpoints */
+       first = true;
+       for(i = j = 0; i < seek_table->num_points; i++) {
+               if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
+                       if(!first) {
+                               if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
+                                       continue;
+                       }
+               }
+               first = false;
+               seek_table->points[j++] = seek_table->points[i];
+       }
+
+       for(i = j; i < seek_table->num_points; i++) {
+               seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
+               seek_table->points[i].stream_offset = 0;
+               seek_table->points[i].frame_samples = 0;
+       }
+
+       return j;
+}
+
+/*
+ * also disallows non-shortest-form encodings, c.f.
+ *   http://www.unicode.org/versions/corrigendum1.html
+ * and a more clear explanation at the end of this section:
+ *   http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
+ */
+static unsigned utf8len_(const FLAC__byte *utf8)
+{
+       FLAC__ASSERT(0 != utf8);
+       if ((utf8[0] & 0x80) == 0) {
+               return 1;
+       }
+       else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
+               if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
+                       return 0;
+               return 2;
+       }
+       else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
+               if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
+                       return 0;
+               /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
+               if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
+                       return 0;
+               if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
+                       return 0;
+               return 3;
+       }
+       else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
+               if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
+                       return 0;
+               return 4;
+       }
+       else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
+               if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
+                       return 0;
+               return 5;
+       }
+       else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
+               if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
+                       return 0;
+               return 6;
+       }
+       else {
+               return 0;
+       }
+}
+
+FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
+{
+       char c;
+       for(c = *name; c; c = *(++name))
+               if(c < 0x20 || c == 0x3d || c > 0x7d)
+                       return false;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
+{
+       if(length == (unsigned)(-1)) {
+               while(*value) {
+                       unsigned n = utf8len_(value);
+                       if(n == 0)
+                               return false;
+                       value += n;
+               }
+       }
+       else {
+               const FLAC__byte *end = value + length;
+               while(value < end) {
+                       unsigned n = utf8len_(value);
+                       if(n == 0)
+                               return false;
+                       value += n;
+               }
+               if(value != end)
+                       return false;
+       }
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
+{
+       const FLAC__byte *s, *end;
+
+       for(s = entry, end = s + length; s < end && *s != '='; s++) {
+               if(*s < 0x20 || *s > 0x7D)
+                       return false;
+       }
+       if(s == end)
+               return false;
+
+       s++; /* skip '=' */
+
+       while(s < end) {
+               unsigned n = utf8len_(s);
+               if(n == 0)
+                       return false;
+               s += n;
+       }
+       if(s != end)
+               return false;
+
+       return true;
+}
+
+/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
+FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
+{
+       unsigned i, j;
+
+       if(check_cd_da_subset) {
+               if(cue_sheet->lead_in < 2 * 44100) {
+                       if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
+                       return false;
+               }
+               if(cue_sheet->lead_in % 588 != 0) {
+                       if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
+                       return false;
+               }
+       }
+
+       if(cue_sheet->num_tracks == 0) {
+               if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
+               return false;
+       }
+
+       if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
+               if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
+               return false;
+       }
+
+       for(i = 0; i < cue_sheet->num_tracks; i++) {
+               if(cue_sheet->tracks[i].number == 0) {
+                       if(violation) *violation = "cue sheet may not have a track number 0";
+                       return false;
+               }
+
+               if(check_cd_da_subset) {
+                       if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
+                               if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
+                               return false;
+                       }
+               }
+
+               if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
+                       if(violation) {
+                               if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
+                                       *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
+                               else
+                                       *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
+                       }
+                       return false;
+               }
+
+               if(i < cue_sheet->num_tracks - 1) {
+                       if(cue_sheet->tracks[i].num_indices == 0) {
+                               if(violation) *violation = "cue sheet track must have at least one index point";
+                               return false;
+                       }
+
+                       if(cue_sheet->tracks[i].indices[0].number > 1) {
+                               if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
+                               return false;
+                       }
+               }
+
+               for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
+                       if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
+                               if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
+                               return false;
+                       }
+
+                       if(j > 0) {
+                               if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
+                                       if(violation) *violation = "cue sheet track index numbers must increase by 1";
+                                       return false;
+                               }
+                       }
+               }
+       }
+
+       return true;
+}
+
+/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
+FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
+{
+       char *p;
+       FLAC__byte *b;
+
+       for(p = picture->mime_type; *p; p++) {
+               if(*p < 0x20 || *p > 0x7e) {
+                       if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
+                       return false;
+               }
+       }
+
+       for(b = picture->description; *b; ) {
+               unsigned n = utf8len_(b);
+               if(n == 0) {
+                       if(violation) *violation = "description string must be valid UTF-8";
+                       return false;
+               }
+               b += n;
+       }
+
+       return true;
+}
+
+/*
+ * These routines are private to libFLAC
+ */
+unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
+{
+       return
+               FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
+                       FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
+                       blocksize,
+                       predictor_order
+               );
+}
+
+unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
+{
+       unsigned max_rice_partition_order = 0;
+       while(!(blocksize & 1)) {
+               max_rice_partition_order++;
+               blocksize >>= 1;
+       }
+       return flac_min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
+}
+
+unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
+{
+       unsigned max_rice_partition_order = limit;
+
+       while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
+               max_rice_partition_order--;
+
+       FLAC__ASSERT(
+               (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
+               (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
+       );
+
+       return max_rice_partition_order;
+}
+
+void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
+{
+       FLAC__ASSERT(0 != object);
+
+       object->parameters = 0;
+       object->raw_bits = 0;
+       object->capacity_by_order = 0;
+}
+
+void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
+{
+       FLAC__ASSERT(0 != object);
+
+       if(0 != object->parameters)
+               free(object->parameters);
+       if(0 != object->raw_bits)
+               free(object->raw_bits);
+       FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
+}
+
+FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
+{
+       FLAC__ASSERT(0 != object);
+
+       FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
+
+       if(object->capacity_by_order < max_partition_order) {
+               if(0 == (object->parameters = safe_realloc_(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
+                       return false;
+               if(0 == (object->raw_bits = safe_realloc_(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
+                       return false;
+               memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
+               object->capacity_by_order = max_partition_order;
+       }
+
+       return true;
+}
diff --git a/FLAC/src/lpc.c b/FLAC/src/lpc.c
new file mode 100644 (file)
index 0000000..531247b
--- /dev/null
@@ -0,0 +1,1357 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "FLAC/assert.h"
+#include "FLAC/format.h"
+#include "share/compat.h"
+#include "private/bitmath.h"
+#include "private/lpc.h"
+#include "private/macros.h"
+#if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
+#include <stdio.h>
+#endif
+
+/* OPT: #undef'ing this may improve the speed on some architectures */
+#define FLAC__LPC_UNROLLED_FILTER_LOOPS
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+#if defined(_MSC_VER) && (_MSC_VER < 1800)
+#include <float.h>
+static inline long int lround(double x) {
+       return (long)(x + _copysign(0.5, x));
+}
+#elif !defined(HAVE_LROUND) && defined(__GNUC__)
+static inline long int lround(double x) {
+       return (long)(x + __builtin_copysign(0.5, x));
+}
+/* If this fails, we are in the presence of a mid 90's compiler, move along... */
+#endif
+
+void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
+{
+       unsigned i;
+       for(i = 0; i < data_len; i++)
+               out[i] = in[i] * window[i];
+}
+
+void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       /* a readable, but slower, version */
+#if 0
+       FLAC__real d;
+       unsigned i;
+
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= data_len);
+
+       /*
+        * Technically we should subtract the mean first like so:
+        *   for(i = 0; i < data_len; i++)
+        *     data[i] -= mean;
+        * but it appears not to make enough of a difference to matter, and
+        * most signals are already closely centered around zero
+        */
+       while(lag--) {
+               for(i = lag, d = 0.0; i < data_len; i++)
+                       d += data[i] * data[i - lag];
+               autoc[lag] = d;
+       }
+#endif
+
+       /*
+        * this version tends to run faster because of better data locality
+        * ('data_len' is usually much larger than 'lag')
+        */
+       FLAC__real d;
+       unsigned sample, coeff;
+       const unsigned limit = data_len - lag;
+
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= data_len);
+
+       for(coeff = 0; coeff < lag; coeff++)
+               autoc[coeff] = 0.0;
+       for(sample = 0; sample <= limit; sample++) {
+               d = data[sample];
+               for(coeff = 0; coeff < lag; coeff++)
+                       autoc[coeff] += d * data[sample+coeff];
+       }
+       for(; sample < data_len; sample++) {
+               d = data[sample];
+               for(coeff = 0; coeff < data_len - sample; coeff++)
+                       autoc[coeff] += d * data[sample+coeff];
+       }
+}
+
+void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], double error[])
+{
+       unsigned i, j;
+       double r, err, lpc[FLAC__MAX_LPC_ORDER];
+
+       FLAC__ASSERT(0 != max_order);
+       FLAC__ASSERT(0 < *max_order);
+       FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
+       FLAC__ASSERT(autoc[0] != 0.0);
+
+       err = autoc[0];
+
+       for(i = 0; i < *max_order; i++) {
+               /* Sum up this iteration's reflection coefficient. */
+               r = -autoc[i+1];
+               for(j = 0; j < i; j++)
+                       r -= lpc[j] * autoc[i-j];
+               r /= err;
+
+               /* Update LPC coefficients and total error. */
+               lpc[i]=r;
+               for(j = 0; j < (i>>1); j++) {
+                       double tmp = lpc[j];
+                       lpc[j] += r * lpc[i-1-j];
+                       lpc[i-1-j] += r * tmp;
+               }
+               if(i & 1)
+                       lpc[j] += lpc[j] * r;
+
+               err *= (1.0 - r * r);
+
+               /* save this order */
+               for(j = 0; j <= i; j++)
+                       lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
+               error[i] = err;
+
+               /* see SF bug https://sourceforge.net/p/flac/bugs/234/ */
+               if(err == 0.0) {
+                       *max_order = i+1;
+                       return;
+               }
+       }
+}
+
+int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
+{
+       unsigned i;
+       double cmax;
+       FLAC__int32 qmax, qmin;
+
+       FLAC__ASSERT(precision > 0);
+       FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
+
+       /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
+       precision--;
+       qmax = 1 << precision;
+       qmin = -qmax;
+       qmax--;
+
+       /* calc cmax = max( |lp_coeff[i]| ) */
+       cmax = 0.0;
+       for(i = 0; i < order; i++) {
+               const double d = fabs(lp_coeff[i]);
+               if(d > cmax)
+                       cmax = d;
+       }
+
+       if(cmax <= 0.0) {
+               /* => coefficients are all 0, which means our constant-detect didn't work */
+               return 2;
+       }
+       else {
+               const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
+               const int min_shiftlimit = -max_shiftlimit - 1;
+               int log2cmax;
+
+               (void)frexp(cmax, &log2cmax);
+               log2cmax--;
+               *shift = (int)precision - log2cmax - 1;
+
+               if(*shift > max_shiftlimit)
+                       *shift = max_shiftlimit;
+               else if(*shift < min_shiftlimit)
+                       return 1;
+       }
+
+       if(*shift >= 0) {
+               double error = 0.0;
+               FLAC__int32 q;
+               for(i = 0; i < order; i++) {
+                       error += lp_coeff[i] * (1 << *shift);
+                       q = lround(error);
+
+#ifdef FLAC__OVERFLOW_DETECT
+                       if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
+                               fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
+                       else if(q < qmin)
+                               fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
+#endif
+                       if(q > qmax)
+                               q = qmax;
+                       else if(q < qmin)
+                               q = qmin;
+                       error -= q;
+                       qlp_coeff[i] = q;
+               }
+       }
+       /* negative shift is very rare but due to design flaw, negative shift is
+        * not allowed in the decoder, so it must be handled specially by scaling
+        * down coeffs
+        */
+       else {
+               const int nshift = -(*shift);
+               double error = 0.0;
+               FLAC__int32 q;
+#ifdef DEBUG
+               fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
+#endif
+               for(i = 0; i < order; i++) {
+                       error += lp_coeff[i] / (1 << nshift);
+                       q = lround(error);
+#ifdef FLAC__OVERFLOW_DETECT
+                       if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
+                               fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
+                       else if(q < qmin)
+                               fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
+#endif
+                       if(q > qmax)
+                               q = qmax;
+                       else if(q < qmin)
+                               q = qmin;
+                       error -= q;
+                       qlp_coeff[i] = q;
+               }
+               *shift = 0;
+       }
+
+       return 0;
+}
+
+#if defined(_MSC_VER)
+// silence MSVC warnings about __restrict modifier
+#pragma warning ( disable : 4028 )
+#endif
+
+void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 * flac_restrict data, unsigned data_len, const FLAC__int32 * flac_restrict qlp_coeff, unsigned order, int lp_quantization, FLAC__int32 * flac_restrict residual)
+#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
+{
+       FLAC__int64 sumo;
+       unsigned i, j;
+       FLAC__int32 sum;
+       const FLAC__int32 *history;
+
+#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
+       fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
+       for(i=0;i<order;i++)
+               fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
+       fprintf(stderr,"\n");
+#endif
+       FLAC__ASSERT(order > 0);
+
+       for(i = 0; i < data_len; i++) {
+               sumo = 0;
+               sum = 0;
+               history = data;
+               for(j = 0; j < order; j++) {
+                       sum += qlp_coeff[j] * (*(--history));
+                       sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
+                       if(sumo > 2147483647ll || sumo < -2147483648ll)
+                               fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%" PRId64 "\n",i,j,qlp_coeff[j],*history,sumo);
+               }
+               *(residual++) = *(data++) - (sum >> lp_quantization);
+       }
+
+       /* Here's a slower but clearer version:
+       for(i = 0; i < data_len; i++) {
+               sum = 0;
+               for(j = 0; j < order; j++)
+                       sum += qlp_coeff[j] * data[i-j-1];
+               residual[i] = data[i] - (sum >> lp_quantization);
+       }
+       */
+}
+#else /* fully unrolled version for normal use */
+{
+       int i;
+       FLAC__int32 sum;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       /*
+        * We do unique versions up to 12th order since that's the subset limit.
+        * Also they are roughly ordered to match frequency of occurrence to
+        * minimize branching.
+        */
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[11] * data[i-12];
+                                               sum += qlp_coeff[10] * data[i-11];
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[10] * data[i-11];
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               residual[i] = data[i] - (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       for(i = 0; i < (int)data_len; i++)
+                                               residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+}
+#endif
+
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 * flac_restrict data, unsigned data_len, const FLAC__int32 * flac_restrict qlp_coeff, unsigned order, int lp_quantization, FLAC__int32 * flac_restrict residual)
+#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
+{
+       unsigned i, j;
+       FLAC__int64 sum;
+       const FLAC__int32 *history;
+
+#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
+       fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
+       for(i=0;i<order;i++)
+               fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
+       fprintf(stderr,"\n");
+#endif
+       FLAC__ASSERT(order > 0);
+
+       for(i = 0; i < data_len; i++) {
+               sum = 0;
+               history = data;
+               for(j = 0; j < order; j++)
+                       sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
+               if(FLAC__bitmath_silog2(sum >> lp_quantization) > 32) {
+                       fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%" PRId64 "\n", i, (sum >> lp_quantization));
+                       break;
+               }
+               if(FLAC__bitmath_silog2((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
+                       fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%" PRId64 ", residual=%" PRId64 "\n", i, *data, (int64_t)(sum >> lp_quantization), ((FLAC__int64)(*data) - (sum >> lp_quantization)));
+                       break;
+               }
+               *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
+       }
+}
+#else /* fully unrolled version for normal use */
+{
+       int i;
+       FLAC__int64 sum;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       /*
+        * We do unique versions up to 12th order since that's the subset limit.
+        * Also they are roughly ordered to match frequency of occurrence to
+        * minimize branching.
+        */
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                               sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       for(i = 0; i < (int)data_len; i++)
+                                               residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
+                               case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
+                               case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
+                               case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
+                               case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
+                               case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
+                               case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
+                               case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
+                               case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
+                               case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
+                               case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
+                               case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
+                               case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
+                               case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
+                               case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
+                               case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
+                               case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
+                               case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
+                               case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
+                               case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
+                                        sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                        sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                        sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                                        sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                                        sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                                        sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                                        sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                                        sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                                        sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                                        sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                                        sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                                        sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+}
+#endif
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
+
+void FLAC__lpc_restore_signal(const FLAC__int32 * flac_restrict residual, unsigned data_len, const FLAC__int32 * flac_restrict qlp_coeff, unsigned order, int lp_quantization, FLAC__int32 * flac_restrict data)
+#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
+{
+       FLAC__int64 sumo;
+       unsigned i, j;
+       FLAC__int32 sum;
+       const FLAC__int32 *r = residual, *history;
+
+#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
+       fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
+       for(i=0;i<order;i++)
+               fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
+       fprintf(stderr,"\n");
+#endif
+       FLAC__ASSERT(order > 0);
+
+       for(i = 0; i < data_len; i++) {
+               sumo = 0;
+               sum = 0;
+               history = data;
+               for(j = 0; j < order; j++) {
+                       sum += qlp_coeff[j] * (*(--history));
+                       sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
+                       if(sumo > 2147483647ll || sumo < -2147483648ll)
+                               fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%" PRId64 "\n",i,j,qlp_coeff[j],*history,sumo);
+               }
+               *(data++) = *(r++) + (sum >> lp_quantization);
+       }
+
+       /* Here's a slower but clearer version:
+       for(i = 0; i < data_len; i++) {
+               sum = 0;
+               for(j = 0; j < order; j++)
+                       sum += qlp_coeff[j] * data[i-j-1];
+               data[i] = residual[i] + (sum >> lp_quantization);
+       }
+       */
+}
+#else /* fully unrolled version for normal use */
+{
+       int i;
+       FLAC__int32 sum;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       /*
+        * We do unique versions up to 12th order since that's the subset limit.
+        * Also they are roughly ordered to match frequency of occurrence to
+        * minimize branching.
+        */
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[11] * data[i-12];
+                                               sum += qlp_coeff[10] * data[i-11];
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[10] * data[i-11];
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[9] * data[i-10];
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[8] * data[i-9];
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[7] * data[i-8];
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[6] * data[i-7];
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[5] * data[i-6];
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[4] * data[i-5];
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[3] * data[i-4];
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[2] * data[i-3];
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[1] * data[i-2];
+                                               sum += qlp_coeff[0] * data[i-1];
+                                               data[i] = residual[i] + (sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       for(i = 0; i < (int)data_len; i++)
+                                               data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       data[i] = residual[i] + (sum >> lp_quantization);
+               }
+       }
+}
+#endif
+
+void FLAC__lpc_restore_signal_wide(const FLAC__int32 * flac_restrict residual, unsigned data_len, const FLAC__int32 * flac_restrict qlp_coeff, unsigned order, int lp_quantization, FLAC__int32 * flac_restrict data)
+#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
+{
+       unsigned i, j;
+       FLAC__int64 sum;
+       const FLAC__int32 *r = residual, *history;
+
+#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
+       fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
+       for(i=0;i<order;i++)
+               fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
+       fprintf(stderr,"\n");
+#endif
+       FLAC__ASSERT(order > 0);
+
+       for(i = 0; i < data_len; i++) {
+               sum = 0;
+               history = data;
+               for(j = 0; j < order; j++)
+                       sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
+               if(FLAC__bitmath_silog2(sum >> lp_quantization) > 32) {
+                       fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%" PRId64 "\n", i, (sum >> lp_quantization));
+                       break;
+               }
+               if(FLAC__bitmath_silog2((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
+                       fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%" PRId64 ", data=%" PRId64 "\n", i, *r, (sum >> lp_quantization), ((FLAC__int64)(*r) + (sum >> lp_quantization)));
+                       break;
+               }
+               *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
+       }
+}
+#else /* fully unrolled version for normal use */
+{
+       int i;
+       FLAC__int64 sum;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       /*
+        * We do unique versions up to 12th order since that's the subset limit.
+        * Also they are roughly ordered to match frequency of occurrence to
+        * minimize branching.
+        */
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                               sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               sum = 0;
+                                               sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       for(i = 0; i < (int)data_len; i++)
+                                               data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
+                               case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
+                               case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
+                               case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
+                               case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
+                               case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
+                               case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
+                               case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
+                               case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
+                               case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
+                               case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
+                               case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
+                               case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
+                               case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
+                               case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
+                               case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
+                               case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
+                               case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
+                               case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
+                               case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
+                                        sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                        sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                        sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                                        sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                                        sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                                        sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                                        sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                                        sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                                        sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                                        sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                                        sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                                        sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+}
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning ( default : 4028 )
+#endif
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+double FLAC__lpc_compute_expected_bits_per_residual_sample(double lpc_error, unsigned total_samples)
+{
+       double error_scale;
+
+       FLAC__ASSERT(total_samples > 0);
+
+       error_scale = 0.5 / (double)total_samples;
+
+       return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
+}
+
+double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(double lpc_error, double error_scale)
+{
+       if(lpc_error > 0.0) {
+               double bps = (double)0.5 * log(error_scale * lpc_error) / M_LN2;
+               if(bps >= 0.0)
+                       return bps;
+               else
+                       return 0.0;
+       }
+       else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
+               return 1e32;
+       }
+       else {
+               return 0.0;
+       }
+}
+
+unsigned FLAC__lpc_compute_best_order(const double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
+{
+       unsigned order, indx, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
+       double bits, best_bits, error_scale;
+
+       FLAC__ASSERT(max_order > 0);
+       FLAC__ASSERT(total_samples > 0);
+
+       error_scale = 0.5 / (double)total_samples;
+
+       best_index = 0;
+       best_bits = (unsigned)(-1);
+
+       for(indx = 0, order = 1; indx < max_order; indx++, order++) {
+               bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[indx], error_scale) * (double)(total_samples - order) + (double)(order * overhead_bits_per_order);
+               if(bits < best_bits) {
+                       best_index = indx;
+                       best_bits = bits;
+               }
+       }
+
+       return best_index+1; /* +1 since indx of lpc_error[] is order-1 */
+}
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/lpc_intrin_avx2.c b/FLAC/src/lpc_intrin_avx2.c
new file mode 100644 (file)
index 0000000..f9f5ccd
--- /dev/null
@@ -0,0 +1,1122 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/lpc.h"
+#ifdef FLAC__AVX2_SUPPORTED
+
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+
+#include <immintrin.h> /* AVX2 */
+
+FLAC__SSE_TARGET("avx2")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       FLAC__int32 sum;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(0xffff & qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(0xffff & qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(0xffff & qlp_coeff[9 ]);
+                                       q10 = _mm256_set1_epi32(0xffff & qlp_coeff[10]);
+                                       q11 = _mm256_set1_epi32(0xffff & qlp_coeff[11]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q11, _mm256_loadu_si256((const __m256i*)(data+i-12)));
+                                               mull = _mm256_madd_epi16(q10, _mm256_loadu_si256((const __m256i*)(data+i-11))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(0xffff & qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(0xffff & qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(0xffff & qlp_coeff[9 ]);
+                                       q10 = _mm256_set1_epi32(0xffff & qlp_coeff[10]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q10, _mm256_loadu_si256((const __m256i*)(data+i-11)));
+                                               mull = _mm256_madd_epi16(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(0xffff & qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(0xffff & qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(0xffff & qlp_coeff[9 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10)));
+                                               mull = _mm256_madd_epi16(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(0xffff & qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(0xffff & qlp_coeff[8 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9 )));
+                                               mull = _mm256_madd_epi16(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(0xffff & qlp_coeff[7 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8 )));
+                                               mull = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(0xffff & qlp_coeff[6 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7 )));
+                                               mull = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       __m256i q0, q1, q2, q3, q4, q5;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(0xffff & qlp_coeff[5 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6 )));
+                                               mull = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m256i q0, q1, q2, q3, q4;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(0xffff & qlp_coeff[4 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5 )));
+                                               mull = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       __m256i q0, q1, q2, q3;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(0xffff & qlp_coeff[3 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4 )));
+                                               mull = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m256i q0, q1, q2;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(0xffff & qlp_coeff[2 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3 )));
+                                               mull = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 ))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       __m256i q0, q1;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(0xffff & qlp_coeff[1 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_madd_epi16(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2 )));
+                                               mull = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 ))); summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m256i q0;
+                                       q0  = _mm256_set1_epi32(0xffff & qlp_coeff[0 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ;
+                                               summ = _mm256_madd_epi16(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1 )));
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               for(; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 12: sum += qlp_coeff[11] * data[i-12];
+                               case 11: sum += qlp_coeff[10] * data[i-11];
+                               case 10: sum += qlp_coeff[ 9] * data[i-10];
+                               case 9:  sum += qlp_coeff[ 8] * data[i- 9];
+                               case 8:  sum += qlp_coeff[ 7] * data[i- 8];
+                               case 7:  sum += qlp_coeff[ 6] * data[i- 7];
+                               case 6:  sum += qlp_coeff[ 5] * data[i- 6];
+                               case 5:  sum += qlp_coeff[ 4] * data[i- 5];
+                               case 4:  sum += qlp_coeff[ 3] * data[i- 4];
+                               case 3:  sum += qlp_coeff[ 2] * data[i- 3];
+                               case 2:  sum += qlp_coeff[ 1] * data[i- 2];
+                               case 1:  sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       _mm256_zeroupper();
+}
+
+FLAC__SSE_TARGET("avx2")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       FLAC__int32 sum;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(qlp_coeff[9 ]);
+                                       q10 = _mm256_set1_epi32(qlp_coeff[10]);
+                                       q11 = _mm256_set1_epi32(qlp_coeff[11]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q11, _mm256_loadu_si256((const __m256i*)(data+i-12)));
+                                               mull = _mm256_mullo_epi32(q10, _mm256_loadu_si256((const __m256i*)(data+i-11))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(qlp_coeff[9 ]);
+                                       q10 = _mm256_set1_epi32(qlp_coeff[10]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q10, _mm256_loadu_si256((const __m256i*)(data+i-11)));
+                                               mull = _mm256_mullo_epi32(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10))); summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(qlp_coeff[8 ]);
+                                       q9  = _mm256_set1_epi32(qlp_coeff[9 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q9,  _mm256_loadu_si256((const __m256i*)(data+i-10)));
+                                               mull = _mm256_mullo_epi32(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(qlp_coeff[7 ]);
+                                       q8  = _mm256_set1_epi32(qlp_coeff[8 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q8,  _mm256_loadu_si256((const __m256i*)(data+i-9)));
+                                               mull = _mm256_mullo_epi32(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+                                       q7  = _mm256_set1_epi32(qlp_coeff[7 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q7,  _mm256_loadu_si256((const __m256i*)(data+i-8)));
+                                               mull = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+                                       q6  = _mm256_set1_epi32(qlp_coeff[6 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q6,  _mm256_loadu_si256((const __m256i*)(data+i-7)));
+                                               mull = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       __m256i q0, q1, q2, q3, q4, q5;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+                                       q5  = _mm256_set1_epi32(qlp_coeff[5 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q5,  _mm256_loadu_si256((const __m256i*)(data+i-6)));
+                                               mull = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m256i q0, q1, q2, q3, q4;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+                                       q4  = _mm256_set1_epi32(qlp_coeff[4 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q4,  _mm256_loadu_si256((const __m256i*)(data+i-5)));
+                                               mull = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       __m256i q0, q1, q2, q3;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+                                       q3  = _mm256_set1_epi32(qlp_coeff[3 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q3,  _mm256_loadu_si256((const __m256i*)(data+i-4)));
+                                               mull = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m256i q0, q1, q2;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+                                       q2  = _mm256_set1_epi32(qlp_coeff[2 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q2,  _mm256_loadu_si256((const __m256i*)(data+i-3)));
+                                               mull = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));  summ = _mm256_add_epi32(summ, mull);
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       __m256i q0, q1;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+                                       q1  = _mm256_set1_epi32(qlp_coeff[1 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mullo_epi32(q1,  _mm256_loadu_si256((const __m256i*)(data+i-2)));
+                                               mull = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));  summ = _mm256_add_epi32(summ, mull);
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m256i q0;
+                                       q0  = _mm256_set1_epi32(qlp_coeff[0 ]);
+
+                                       for(i = 0; i < (int)data_len-7; i+=8) {
+                                               __m256i summ;
+                                               summ = _mm256_mullo_epi32(q0,  _mm256_loadu_si256((const __m256i*)(data+i-1)));
+                                               summ = _mm256_sra_epi32(summ, cnt);
+                                               _mm256_storeu_si256((__m256i*)(residual+i), _mm256_sub_epi32(_mm256_loadu_si256((const __m256i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               for(; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 12: sum += qlp_coeff[11] * data[i-12];
+                               case 11: sum += qlp_coeff[10] * data[i-11];
+                               case 10: sum += qlp_coeff[ 9] * data[i-10];
+                               case 9:  sum += qlp_coeff[ 8] * data[i- 9];
+                               case 8:  sum += qlp_coeff[ 7] * data[i- 8];
+                               case 7:  sum += qlp_coeff[ 6] * data[i- 7];
+                               case 6:  sum += qlp_coeff[ 5] * data[i- 6];
+                               case 5:  sum += qlp_coeff[ 4] * data[i- 5];
+                               case 4:  sum += qlp_coeff[ 3] * data[i- 4];
+                               case 3:  sum += qlp_coeff[ 2] * data[i- 3];
+                               case 2:  sum += qlp_coeff[ 1] * data[i- 2];
+                               case 1:  sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       _mm256_zeroupper();
+}
+
+static FLAC__int32 pack_arr[8] = { 0, 2, 4, 6, 1, 3, 5, 7 };
+
+FLAC__SSE_TARGET("avx2")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       FLAC__int64 sum;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+       __m256i pack = _mm256_loadu_si256((const __m256i *)pack_arr);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+       FLAC__ASSERT(lp_quantization <= 32); /* there's no _mm256_sra_epi64() so we have to use _mm256_srl_epi64() */
+
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+                                       q7  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[7 ]));
+                                       q8  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[8 ]));
+                                       q9  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[9 ]));
+                                       q10 = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[10]));
+                                       q11 = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[11]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q11, _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-12))));
+                                               mull = _mm256_mul_epi32(q10, _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-11)))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q9,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-10)))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q8,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-9 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q7,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-8 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+                                       q7  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[7 ]));
+                                       q8  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[8 ]));
+                                       q9  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[9 ]));
+                                       q10 = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[10]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q10, _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-11))));
+                                               mull = _mm256_mul_epi32(q9,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-10)))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q8,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-9 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q7,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-8 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+                                       q7  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[7 ]));
+                                       q8  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[8 ]));
+                                       q9  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[9 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q9,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-10))));
+                                               mull = _mm256_mul_epi32(q8,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-9 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q7,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-8 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7, q8;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+                                       q7  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[7 ]));
+                                       q8  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[8 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q8,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-9 ))));
+                                               mull = _mm256_mul_epi32(q7,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-8 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       __m256i q0, q1, q2, q3, q4, q5, q6, q7;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+                                       q7  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[7 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q7,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-8 ))));
+                                               mull = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m256i q0, q1, q2, q3, q4, q5, q6;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+                                       q6  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[6 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q6,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-7 ))));
+                                               mull = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       __m256i q0, q1, q2, q3, q4, q5;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+                                       q5  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[5 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q5,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-6 ))));
+                                               mull = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m256i q0, q1, q2, q3, q4;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+                                       q4  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[4 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q4,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-5 ))));
+                                               mull = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       __m256i q0, q1, q2, q3;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+                                       q3  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[3 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q3,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-4 ))));
+                                               mull = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m256i q0, q1, q2;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+                                       q2  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[2 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q2,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-3 ))));
+                                               mull = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 )))); summ = _mm256_add_epi64(summ, mull);
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       __m256i q0, q1;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+                                       q1  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[1 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ, mull;
+                                               summ = _mm256_mul_epi32(q1,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-2 ))));
+                                               mull = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 )))); summ = _mm256_add_epi64(summ, mull);
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m256i q0;
+                                       q0  = _mm256_cvtepu32_epi64(_mm_set1_epi32(qlp_coeff[0 ]));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m256i summ;
+                                               summ = _mm256_mul_epi32(q0,  _mm256_cvtepu32_epi64(_mm_loadu_si128((const __m128i*)(data+i-1 ))));
+                                               summ = _mm256_permutevar8x32_epi32(_mm256_srl_epi64(summ, cnt), pack);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), _mm256_castsi256_si128(summ)));
+                                       }
+                               }
+                       }
+               }
+               for(; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 12: sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                               case 11: sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                               case 10: sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                               case 9:  sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                               case 8:  sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                               case 7:  sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                               case 6:  sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                               case 5:  sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                               case 4:  sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                               case 3:  sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                               case 2:  sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                               case 1:  sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
+                               case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
+                               case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
+                               case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
+                               case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
+                               case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
+                               case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
+                               case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
+                               case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
+                               case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
+                               case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
+                               case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
+                               case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
+                               case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
+                               case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
+                               case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
+                               case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
+                               case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
+                               case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
+                               case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
+                                        sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                        sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                        sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                                        sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                                        sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                                        sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                                        sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                                        sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                                        sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                                        sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                                        sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                                        sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+       _mm256_zeroupper();
+}
+
+#endif /* FLAC__AVX2_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/lpc_intrin_sse.c b/FLAC/src/lpc_intrin_sse.c
new file mode 100644 (file)
index 0000000..430e73f
--- /dev/null
@@ -0,0 +1,454 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/lpc.h"
+#ifdef FLAC__SSE_SUPPORTED
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+
+#include <xmmintrin.h> /* SSE */
+
+/*   new routines: more unaligned loads, less shuffle
+ *   old routines: less unaligned loads, more shuffle
+ *   these *_old routines are equivalent to the ASM routines in ia32/lpc_asm.nasm
+ */
+
+/* new routines: faster on current Intel (starting from Core i aka Nehalem) and all AMD CPUs */
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       int i;
+       int limit = data_len - 4;
+       __m128 sum0;
+
+       (void) lag;
+       FLAC__ASSERT(lag <= 4);
+       FLAC__ASSERT(lag <= data_len);
+
+       sum0 = _mm_setzero_ps();
+
+       for(i = 0; i <= limit; i++) {
+               __m128 d, d0;
+               d0 = _mm_loadu_ps(data+i);
+               d = d0; d = _mm_shuffle_ps(d, d, 0);
+               sum0 = _mm_add_ps(sum0, _mm_mul_ps(d0, d));
+       }
+
+       {
+               __m128 d0 = _mm_setzero_ps();
+               limit++; if(limit < 0) limit = 0;
+
+               for(i = data_len-1; i >= limit; i--) {
+                       __m128 d;
+                       d = _mm_load_ss(data+i); d = _mm_shuffle_ps(d, d, 0);
+                       d0 = _mm_shuffle_ps(d0, d0, _MM_SHUFFLE(2,1,0,3));
+                       d0 = _mm_move_ss(d0, d);
+                       sum0 = _mm_add_ps(sum0, _mm_mul_ps(d, d0));
+               }
+       }
+
+       _mm_storeu_ps(autoc,   sum0);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       int i;
+       int limit = data_len - 8;
+       __m128 sum0, sum1;
+
+       (void) lag;
+       FLAC__ASSERT(lag <= 8);
+       FLAC__ASSERT(lag <= data_len);
+
+       sum0 = _mm_setzero_ps();
+       sum1 = _mm_setzero_ps();
+
+       for(i = 0; i <= limit; i++) {
+               __m128 d, d0, d1;
+               d0 = _mm_loadu_ps(data+i);
+               d1 = _mm_loadu_ps(data+i+4);
+               d = d0; d = _mm_shuffle_ps(d, d, 0);
+               sum0 = _mm_add_ps(sum0, _mm_mul_ps(d0, d));
+               sum1 = _mm_add_ps(sum1, _mm_mul_ps(d1, d));
+       }
+
+       {
+               __m128 d0 = _mm_setzero_ps();
+               __m128 d1 = _mm_setzero_ps();
+               limit++; if(limit < 0) limit = 0;
+
+               for(i = data_len-1; i >= limit; i--) {
+                       __m128 d;
+                       d = _mm_load_ss(data+i); d = _mm_shuffle_ps(d, d, 0);
+                       d1 = _mm_shuffle_ps(d1, d1, _MM_SHUFFLE(2,1,0,3));
+                       d0 = _mm_shuffle_ps(d0, d0, _MM_SHUFFLE(2,1,0,3));
+                       d1 = _mm_move_ss(d1, d0);
+                       d0 = _mm_move_ss(d0, d);
+                       sum1 = _mm_add_ps(sum1, _mm_mul_ps(d, d1));
+                       sum0 = _mm_add_ps(sum0, _mm_mul_ps(d, d0));
+               }
+       }
+
+       _mm_storeu_ps(autoc,   sum0);
+       _mm_storeu_ps(autoc+4, sum1);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       int i;
+       int limit = data_len - 12;
+       __m128 sum0, sum1, sum2;
+
+       (void) lag;
+       FLAC__ASSERT(lag <= 12);
+       FLAC__ASSERT(lag <= data_len);
+
+       sum0 = _mm_setzero_ps();
+       sum1 = _mm_setzero_ps();
+       sum2 = _mm_setzero_ps();
+
+       for(i = 0; i <= limit; i++) {
+               __m128 d, d0, d1, d2;
+               d0 = _mm_loadu_ps(data+i);
+               d1 = _mm_loadu_ps(data+i+4);
+               d2 = _mm_loadu_ps(data+i+8);
+               d = d0; d = _mm_shuffle_ps(d, d, 0);
+               sum0 = _mm_add_ps(sum0, _mm_mul_ps(d0, d));
+               sum1 = _mm_add_ps(sum1, _mm_mul_ps(d1, d));
+               sum2 = _mm_add_ps(sum2, _mm_mul_ps(d2, d));
+       }
+
+       {
+               __m128 d0 = _mm_setzero_ps();
+               __m128 d1 = _mm_setzero_ps();
+               __m128 d2 = _mm_setzero_ps();
+               limit++; if(limit < 0) limit = 0;
+
+               for(i = data_len-1; i >= limit; i--) {
+                       __m128 d;
+                       d = _mm_load_ss(data+i); d = _mm_shuffle_ps(d, d, 0);
+                       d2 = _mm_shuffle_ps(d2, d2, _MM_SHUFFLE(2,1,0,3));
+                       d1 = _mm_shuffle_ps(d1, d1, _MM_SHUFFLE(2,1,0,3));
+                       d0 = _mm_shuffle_ps(d0, d0, _MM_SHUFFLE(2,1,0,3));
+                       d2 = _mm_move_ss(d2, d1);
+                       d1 = _mm_move_ss(d1, d0);
+                       d0 = _mm_move_ss(d0, d);
+                       sum2 = _mm_add_ps(sum2, _mm_mul_ps(d, d2));
+                       sum1 = _mm_add_ps(sum1, _mm_mul_ps(d, d1));
+                       sum0 = _mm_add_ps(sum0, _mm_mul_ps(d, d0));
+               }
+       }
+
+       _mm_storeu_ps(autoc,   sum0);
+       _mm_storeu_ps(autoc+4, sum1);
+       _mm_storeu_ps(autoc+8, sum2);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       int i;
+       int limit = data_len - 16;
+       __m128 sum0, sum1, sum2, sum3;
+
+       (void) lag;
+       FLAC__ASSERT(lag <= 16);
+       FLAC__ASSERT(lag <= data_len);
+
+       sum0 = _mm_setzero_ps();
+       sum1 = _mm_setzero_ps();
+       sum2 = _mm_setzero_ps();
+       sum3 = _mm_setzero_ps();
+
+       for(i = 0; i <= limit; i++) {
+               __m128 d, d0, d1, d2, d3;
+               d0 = _mm_loadu_ps(data+i);
+               d1 = _mm_loadu_ps(data+i+4);
+               d2 = _mm_loadu_ps(data+i+8);
+               d3 = _mm_loadu_ps(data+i+12);
+               d = d0; d = _mm_shuffle_ps(d, d, 0);
+               sum0 = _mm_add_ps(sum0, _mm_mul_ps(d0, d));
+               sum1 = _mm_add_ps(sum1, _mm_mul_ps(d1, d));
+               sum2 = _mm_add_ps(sum2, _mm_mul_ps(d2, d));
+               sum3 = _mm_add_ps(sum3, _mm_mul_ps(d3, d));
+       }
+
+       {
+               __m128 d0 = _mm_setzero_ps();
+               __m128 d1 = _mm_setzero_ps();
+               __m128 d2 = _mm_setzero_ps();
+               __m128 d3 = _mm_setzero_ps();
+               limit++; if(limit < 0) limit = 0;
+
+               for(i = data_len-1; i >= limit; i--) {
+                       __m128 d;
+                       d = _mm_load_ss(data+i); d = _mm_shuffle_ps(d, d, 0);
+                       d3 = _mm_shuffle_ps(d3, d3, _MM_SHUFFLE(2,1,0,3));
+                       d2 = _mm_shuffle_ps(d2, d2, _MM_SHUFFLE(2,1,0,3));
+                       d1 = _mm_shuffle_ps(d1, d1, _MM_SHUFFLE(2,1,0,3));
+                       d0 = _mm_shuffle_ps(d0, d0, _MM_SHUFFLE(2,1,0,3));
+                       d3 = _mm_move_ss(d3, d2);
+                       d2 = _mm_move_ss(d2, d1);
+                       d1 = _mm_move_ss(d1, d0);
+                       d0 = _mm_move_ss(d0, d);
+                       sum3 = _mm_add_ps(sum3, _mm_mul_ps(d, d3));
+                       sum2 = _mm_add_ps(sum2, _mm_mul_ps(d, d2));
+                       sum1 = _mm_add_ps(sum1, _mm_mul_ps(d, d1));
+                       sum0 = _mm_add_ps(sum0, _mm_mul_ps(d, d0));
+               }
+       }
+
+       _mm_storeu_ps(autoc,   sum0);
+       _mm_storeu_ps(autoc+4, sum1);
+       _mm_storeu_ps(autoc+8, sum2);
+       _mm_storeu_ps(autoc+12,sum3);
+}
+
+/* old routines: faster on older Intel CPUs (up to Core 2) */
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       __m128 xmm0, xmm2, xmm5;
+
+       (void) lag;
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= 4);
+       FLAC__ASSERT(lag <= data_len);
+       FLAC__ASSERT(data_len > 0);
+
+       xmm5 = _mm_setzero_ps();
+
+       xmm0 = _mm_load_ss(data++);
+       xmm2 = xmm0;
+       xmm0 = _mm_shuffle_ps(xmm0, xmm0, 0);
+
+       xmm0 = _mm_mul_ps(xmm0, xmm2);
+       xmm5 = _mm_add_ps(xmm5, xmm0);
+
+       data_len--;
+
+       while(data_len)
+       {
+               xmm0 = _mm_load1_ps(data++);
+
+               xmm2 = _mm_shuffle_ps(xmm2, xmm2, _MM_SHUFFLE(2,1,0,3));
+               xmm2 = _mm_move_ss(xmm2, xmm0);
+               xmm0 = _mm_mul_ps(xmm0, xmm2);
+               xmm5 = _mm_add_ps(xmm5, xmm0);
+
+               data_len--;
+       }
+
+       _mm_storeu_ps(autoc, xmm5);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       __m128 xmm0, xmm1, xmm2, xmm3, xmm5, xmm6;
+
+       (void) lag;
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= 8);
+       FLAC__ASSERT(lag <= data_len);
+       FLAC__ASSERT(data_len > 0);
+
+       xmm5 = _mm_setzero_ps();
+       xmm6 = _mm_setzero_ps();
+
+       xmm0 = _mm_load_ss(data++);
+       xmm2 = xmm0;
+       xmm0 = _mm_shuffle_ps(xmm0, xmm0, 0);
+       xmm3 = _mm_setzero_ps();
+
+       xmm0 = _mm_mul_ps(xmm0, xmm2);
+       xmm5 = _mm_add_ps(xmm5, xmm0);
+
+       data_len--;
+
+       while(data_len)
+       {
+               xmm0 = _mm_load1_ps(data++);
+
+               xmm2 = _mm_shuffle_ps(xmm2, xmm2, _MM_SHUFFLE(2,1,0,3));
+               xmm3 = _mm_shuffle_ps(xmm3, xmm3, _MM_SHUFFLE(2,1,0,3));
+               xmm3 = _mm_move_ss(xmm3, xmm2);
+               xmm2 = _mm_move_ss(xmm2, xmm0);
+
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm3);
+               xmm0 = _mm_mul_ps(xmm0, xmm2);
+               xmm6 = _mm_add_ps(xmm6, xmm1);
+               xmm5 = _mm_add_ps(xmm5, xmm0);
+
+               data_len--;
+       }
+
+       _mm_storeu_ps(autoc,   xmm5);
+       _mm_storeu_ps(autoc+4, xmm6);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       __m128 xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+
+       (void) lag;
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= 12);
+       FLAC__ASSERT(lag <= data_len);
+       FLAC__ASSERT(data_len > 0);
+
+       xmm5 = _mm_setzero_ps();
+       xmm6 = _mm_setzero_ps();
+       xmm7 = _mm_setzero_ps();
+
+       xmm0 = _mm_load_ss(data++);
+       xmm2 = xmm0;
+       xmm0 = _mm_shuffle_ps(xmm0, xmm0, 0);
+       xmm3 = _mm_setzero_ps();
+       xmm4 = _mm_setzero_ps();
+
+       xmm0 = _mm_mul_ps(xmm0, xmm2);
+       xmm5 = _mm_add_ps(xmm5, xmm0);
+
+       data_len--;
+
+       while(data_len)
+       {
+               xmm0 = _mm_load1_ps(data++);
+
+               xmm2 = _mm_shuffle_ps(xmm2, xmm2, _MM_SHUFFLE(2,1,0,3));
+               xmm3 = _mm_shuffle_ps(xmm3, xmm3, _MM_SHUFFLE(2,1,0,3));
+               xmm4 = _mm_shuffle_ps(xmm4, xmm4, _MM_SHUFFLE(2,1,0,3));
+               xmm4 = _mm_move_ss(xmm4, xmm3);
+               xmm3 = _mm_move_ss(xmm3, xmm2);
+               xmm2 = _mm_move_ss(xmm2, xmm0);
+
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm2);
+               xmm5 = _mm_add_ps(xmm5, xmm1);
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm3);
+               xmm6 = _mm_add_ps(xmm6, xmm1);
+               xmm0 = _mm_mul_ps(xmm0, xmm4);
+               xmm7 = _mm_add_ps(xmm7, xmm0);
+
+               data_len--;
+       }
+
+       _mm_storeu_ps(autoc,   xmm5);
+       _mm_storeu_ps(autoc+4, xmm6);
+       _mm_storeu_ps(autoc+8, xmm7);
+}
+
+FLAC__SSE_TARGET("sse")
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
+{
+       __m128 xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9;
+
+       (void) lag;
+       FLAC__ASSERT(lag > 0);
+       FLAC__ASSERT(lag <= 16);
+       FLAC__ASSERT(lag <= data_len);
+       FLAC__ASSERT(data_len > 0);
+
+       xmm6 = _mm_setzero_ps();
+       xmm7 = _mm_setzero_ps();
+       xmm8 = _mm_setzero_ps();
+       xmm9 = _mm_setzero_ps();
+
+       xmm0 = _mm_load_ss(data++);
+       xmm2 = xmm0;
+       xmm0 = _mm_shuffle_ps(xmm0, xmm0, 0);
+       xmm3 = _mm_setzero_ps();
+       xmm4 = _mm_setzero_ps();
+       xmm5 = _mm_setzero_ps();
+
+       xmm0 = _mm_mul_ps(xmm0, xmm2);
+       xmm6 = _mm_add_ps(xmm6, xmm0);
+
+       data_len--;
+
+       while(data_len)
+       {
+               xmm0 = _mm_load1_ps(data++);
+
+               /* shift xmm5:xmm4:xmm3:xmm2 left by one float */
+               xmm5 = _mm_shuffle_ps(xmm5, xmm5, _MM_SHUFFLE(2,1,0,3));
+               xmm4 = _mm_shuffle_ps(xmm4, xmm4, _MM_SHUFFLE(2,1,0,3));
+               xmm3 = _mm_shuffle_ps(xmm3, xmm3, _MM_SHUFFLE(2,1,0,3));
+               xmm2 = _mm_shuffle_ps(xmm2, xmm2, _MM_SHUFFLE(2,1,0,3));
+               xmm5 = _mm_move_ss(xmm5, xmm4);
+               xmm4 = _mm_move_ss(xmm4, xmm3);
+               xmm3 = _mm_move_ss(xmm3, xmm2);
+               xmm2 = _mm_move_ss(xmm2, xmm0);
+
+               /* xmm9|xmm8|xmm7|xmm6 += xmm0|xmm0|xmm0|xmm0 * xmm5|xmm4|xmm3|xmm2 */
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm5);
+               xmm9 = _mm_add_ps(xmm9, xmm1);
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm4);
+               xmm8 = _mm_add_ps(xmm8, xmm1);
+               xmm1 = xmm0;
+               xmm1 = _mm_mul_ps(xmm1, xmm3);
+               xmm7 = _mm_add_ps(xmm7, xmm1);
+               xmm0 = _mm_mul_ps(xmm0, xmm2);
+               xmm6 = _mm_add_ps(xmm6, xmm0);
+
+               data_len--;
+       }
+
+       _mm_storeu_ps(autoc,   xmm6);
+       _mm_storeu_ps(autoc+4, xmm7);
+       _mm_storeu_ps(autoc+8, xmm8);
+       _mm_storeu_ps(autoc+12,xmm9);
+}
+
+#endif /* FLAC__SSE_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/lpc_intrin_sse2.c b/FLAC/src/lpc_intrin_sse2.c
new file mode 100644 (file)
index 0000000..1383394
--- /dev/null
@@ -0,0 +1,1090 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/lpc.h"
+#ifdef FLAC__SSE2_SUPPORTED
+
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+
+#include <emmintrin.h> /* SSE2 */
+
+#define RESIDUAL16_RESULT(xmmN) curr = *data++; *residual++ = curr - (_mm_cvtsi128_si32(xmmN) >> lp_quantization);
+#define     DATA16_RESULT(xmmN) curr = *residual++ + (_mm_cvtsi128_si32(xmmN) >> lp_quantization); *data++ = curr;
+
+#define RESIDUAL32_RESULT(xmmN) residual[i] = data[i] - (_mm_cvtsi128_si32(xmmN) >> lp_quantization);
+#define     DATA32_RESULT(xmmN) data[i] = residual[i] + (_mm_cvtsi128_si32(xmmN) >> lp_quantization);
+
+FLAC__SSE_TARGET("sse2")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       FLAC__int32 sum;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(0xffff & qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(0xffff & qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(0xffff & qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+                                       q10 = _mm_cvtsi32_si128(0xffff & qlp_coeff[10]); q10 = _mm_shuffle_epi32(q10, _MM_SHUFFLE(0,0,0,0));
+                                       q11 = _mm_cvtsi32_si128(0xffff & qlp_coeff[11]); q11 = _mm_shuffle_epi32(q11, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q11, _mm_loadu_si128((const __m128i*)(data+i-12)));
+                                               mull = _mm_madd_epi16(q10, _mm_loadu_si128((const __m128i*)(data+i-11))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q9, _mm_loadu_si128((const __m128i*)(data+i-10))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(0xffff & qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(0xffff & qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(0xffff & qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+                                       q10 = _mm_cvtsi32_si128(0xffff & qlp_coeff[10]); q10 = _mm_shuffle_epi32(q10, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q10, _mm_loadu_si128((const __m128i*)(data+i-11)));
+                                               mull = _mm_madd_epi16(q9, _mm_loadu_si128((const __m128i*)(data+i-10))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(0xffff & qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(0xffff & qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(0xffff & qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q9, _mm_loadu_si128((const __m128i*)(data+i-10)));
+                                               mull = _mm_madd_epi16(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(0xffff & qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(0xffff & qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q8, _mm_loadu_si128((const __m128i*)(data+i-9)));
+                                               mull = _mm_madd_epi16(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(0xffff & qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q7, _mm_loadu_si128((const __m128i*)(data+i-8)));
+                                               mull = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(0xffff & qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q6, _mm_loadu_si128((const __m128i*)(data+i-7)));
+                                               mull = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       __m128i q0, q1, q2, q3, q4, q5;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(0xffff & qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q5, _mm_loadu_si128((const __m128i*)(data+i-6)));
+                                               mull = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m128i q0, q1, q2, q3, q4;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(0xffff & qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q4, _mm_loadu_si128((const __m128i*)(data+i-5)));
+                                               mull = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       __m128i q0, q1, q2, q3;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(0xffff & qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q3, _mm_loadu_si128((const __m128i*)(data+i-4)));
+                                               mull = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m128i q0, q1, q2;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(0xffff & qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q2, _mm_loadu_si128((const __m128i*)(data+i-3)));
+                                               mull = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       __m128i q0, q1;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(0xffff & qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_madd_epi16(q1, _mm_loadu_si128((const __m128i*)(data+i-2)));
+                                               mull = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m128i q0;
+                                       q0 = _mm_cvtsi32_si128(0xffff & qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ;
+                                               summ = _mm_madd_epi16(q0, _mm_loadu_si128((const __m128i*)(data+i-1)));
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               for(; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 12: sum += qlp_coeff[11] * data[i-12];
+                               case 11: sum += qlp_coeff[10] * data[i-11];
+                               case 10: sum += qlp_coeff[ 9] * data[i-10];
+                               case 9:  sum += qlp_coeff[ 8] * data[i- 9];
+                               case 8:  sum += qlp_coeff[ 7] * data[i- 8];
+                               case 7:  sum += qlp_coeff[ 6] * data[i- 7];
+                               case 6:  sum += qlp_coeff[ 5] * data[i- 6];
+                               case 5:  sum += qlp_coeff[ 4] * data[i- 5];
+                               case 4:  sum += qlp_coeff[ 3] * data[i- 4];
+                               case 3:  sum += qlp_coeff[ 2] * data[i- 3];
+                               case 2:  sum += qlp_coeff[ 1] * data[i- 2];
+                               case 1:  sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+}
+
+FLAC__SSE_TARGET("sse2")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       if(order <= 12) {
+               if(order > 8) { /* order == 9, 10, 11, 12 */
+                       if(order > 10) { /* order == 11, 12 */
+                               if(order == 12) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));  // 0  0  q[1]  q[0]
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));  // 0  0  q[3]  q[2]
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));  // 0  0  q[5]  q[4]
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));  // 0  0  q[7]  q[6]
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));  // 0  0  q[9]  q[8]
+                                       xmm5 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+10)); // 0  0  q[11] q[10]
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0)); // 0  q[1]  0  q[0]
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0)); // 0  q[3]  0  q[2]
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0)); // 0  q[5]  0  q[4]
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0)); // 0  q[7]  0  q[6]
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0)); // 0  q[9]  0  q[8]
+                                       xmm5 = _mm_shuffle_epi32(xmm5, _MM_SHUFFLE(3,1,2,0)); // 0  q[11] 0  q[10]
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[11] * data[i-12];
+                                               //sum += qlp_coeff[10] * data[i-11];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-12));  // 0   0        d[i-11]  d[i-12]
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1)); // 0  d[i-12]   0        d[i-11]
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm5); /* we use _unsigned_ multiplication and discard high dword of the result values */
+
+                                               //sum += qlp_coeff[9] * data[i-10];
+                                               //sum += qlp_coeff[8] * data[i-9];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm4);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[7] * data[i-8];
+                                               //sum += qlp_coeff[6] * data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));
+                                       xmm5 = _mm_cvtsi32_si128(qlp_coeff[10]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[10] * data[i-11];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-11]);
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm5);
+
+                                               //sum += qlp_coeff[9] * data[i-10];
+                                               //sum += qlp_coeff[8] * data[i-9];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm4);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[7] * data[i-8];
+                                               //sum += qlp_coeff[6] * data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 9, 10 */
+                               if(order == 10) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[9] * data[i-10];
+                                               //sum += qlp_coeff[8] * data[i-9];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm4);
+
+                                               //sum += qlp_coeff[7] * data[i-8];
+                                               //sum += qlp_coeff[6] * data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_cvtsi32_si128(qlp_coeff[8]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[8] * data[i-9];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-9]);
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm4);
+
+                                               //sum += qlp_coeff[7] * data[i-8];
+                                               //sum += qlp_coeff[6] * data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) { /* order == 5, 6, 7, 8 */
+                       if(order > 6) { /* order == 7, 8 */
+                               if(order == 8) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[7] * data[i-8];
+                                               //sum += qlp_coeff[6] * data[i-7];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm3);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_cvtsi32_si128(qlp_coeff[6]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[6] * data[i-7];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-7]);
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm3);
+
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 5, 6 */
+                               if(order == 6) {
+                                       __m128i xmm0, xmm1, xmm2, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[5] * data[i-6];
+                                               //sum += qlp_coeff[4] * data[i-5];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm2);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m128i xmm0, xmm1, xmm2, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_cvtsi32_si128(qlp_coeff[4]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[4] * data[i-5];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-5]);
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm2);
+
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                       }
+               }
+               else { /* order == 1, 2, 3, 4 */
+                       if(order > 2) { /* order == 3, 4 */
+                               if(order == 4) {
+                                       __m128i xmm0, xmm1, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[3] * data[i-4];
+                                               //sum += qlp_coeff[2] * data[i-3];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm1);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m128i xmm0, xmm1, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_cvtsi32_si128(qlp_coeff[2]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[2] * data[i-3];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-3]);
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm1);
+
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epu32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi32(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 1, 2 */
+                               if(order == 2) {
+                                       __m128i xmm0, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[1] * data[i-2];
+                                               //sum += qlp_coeff[0] * data[i-1];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epu32(xmm7, xmm0);
+
+                                               xmm7 = _mm_add_epi32(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL32_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       for(i = 0; i < (int)data_len; i++)
+                                               residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               FLAC__int32 sum;
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+}
+
+#if defined FLAC__CPU_IA32 && !defined FLAC__HAS_NASM /* unused for x64; not better than MMX asm */
+
+FLAC__SSE_TARGET("sse2")
+void FLAC__lpc_restore_signal_16_intrin_sse2(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
+{
+       if (order < 8 || order > 12) {
+               FLAC__lpc_restore_signal(residual, data_len, qlp_coeff, order, lp_quantization, data);
+               return;
+       }
+       if (data_len == 0)
+               return;
+
+       FLAC__ASSERT(order >= 8);
+       FLAC__ASSERT(order <= 12);
+
+       if(order > 8) { /* order == 9, 10, 11, 12 */
+               FLAC__int32 curr;
+               __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+               xmm0 = _mm_loadu_si128((const __m128i*)(qlp_coeff+0));
+               xmm6 = _mm_loadu_si128((const __m128i*)(qlp_coeff+4));
+               xmm1 = _mm_loadu_si128((const __m128i*)(qlp_coeff+8)); /* read 0 to 3 uninitialized coeffs... */
+               switch(order)                                          /* ...and zero them out */
+               {
+               case 9:
+                       xmm1 = _mm_slli_si128(xmm1, 12); xmm1 = _mm_srli_si128(xmm1, 12); break;
+               case 10:
+                       xmm1 = _mm_slli_si128(xmm1, 8); xmm1 = _mm_srli_si128(xmm1, 8); break;
+               case 11:
+                       xmm1 = _mm_slli_si128(xmm1, 4); xmm1 = _mm_srli_si128(xmm1, 4); break;
+               }
+               xmm2 = _mm_setzero_si128();
+               xmm0 = _mm_packs_epi32(xmm0, xmm6);
+               xmm1 = _mm_packs_epi32(xmm1, xmm2);
+
+               xmm4 = _mm_loadu_si128((const __m128i*)(data-12));
+               xmm5 = _mm_loadu_si128((const __m128i*)(data-8));
+               xmm3 = _mm_loadu_si128((const __m128i*)(data-4));
+               xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(0,1,2,3));
+               xmm5 = _mm_shuffle_epi32(xmm5, _MM_SHUFFLE(0,1,2,3));
+               xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(0,1,2,3));
+               xmm4 = _mm_packs_epi32(xmm4, xmm2);
+               xmm3 = _mm_packs_epi32(xmm3, xmm5);
+
+               xmm7 = _mm_slli_si128(xmm1, 2);
+               xmm7 = _mm_or_si128(xmm7, _mm_srli_si128(xmm0, 14));
+               xmm2 = _mm_slli_si128(xmm0, 2);
+
+               /* xmm0, xmm1: qlp_coeff
+                       xmm2, xmm7: qlp_coeff << 16 bit
+                       xmm3, xmm4: data */
+
+               xmm5 = _mm_madd_epi16(xmm4, xmm1);
+               xmm6 = _mm_madd_epi16(xmm3, xmm0);
+               xmm6 = _mm_add_epi32(xmm6, xmm5);
+               xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+               xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+               DATA16_RESULT(xmm6);
+
+               data_len--;
+
+               if(data_len % 2) {
+                       xmm6 = _mm_srli_si128(xmm3, 14);
+                       xmm4 = _mm_slli_si128(xmm4, 2);
+                       xmm3 = _mm_slli_si128(xmm3, 2);
+                       xmm4 = _mm_or_si128(xmm4, xmm6);
+                       xmm3 = _mm_insert_epi16(xmm3, curr, 0);
+
+                       xmm5 = _mm_madd_epi16(xmm4, xmm1);
+                       xmm6 = _mm_madd_epi16(xmm3, xmm0);
+                       xmm6 = _mm_add_epi32(xmm6, xmm5);
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+                       DATA16_RESULT(xmm6);
+
+                       data_len--;
+               }
+
+               while(data_len) { /* data_len is a multiple of 2 */
+                       /* 1 _mm_slli_si128 per data element less but we need shifted qlp_coeff in xmm2:xmm7 */
+                       xmm6 = _mm_srli_si128(xmm3, 12);
+                       xmm4 = _mm_slli_si128(xmm4, 4);
+                       xmm3 = _mm_slli_si128(xmm3, 4);
+                       xmm4 = _mm_or_si128(xmm4, xmm6);
+                       xmm3 = _mm_insert_epi16(xmm3, curr, 1);
+
+                       xmm5 = _mm_madd_epi16(xmm4, xmm7);
+                       xmm6 = _mm_madd_epi16(xmm3, xmm2);
+                       xmm6 = _mm_add_epi32(xmm6, xmm5);
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+                       DATA16_RESULT(xmm6);
+
+                       xmm3 = _mm_insert_epi16(xmm3, curr, 0);
+
+                       xmm5 = _mm_madd_epi16(xmm4, xmm1);
+                       xmm6 = _mm_madd_epi16(xmm3, xmm0);
+                       xmm6 = _mm_add_epi32(xmm6, xmm5);
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+                       DATA16_RESULT(xmm6);
+
+                       data_len-=2;
+               }
+       } /* endif(order > 8) */
+       else
+       {
+               FLAC__int32 curr;
+               __m128i xmm0, xmm1, xmm3, xmm6;
+               xmm0 = _mm_loadu_si128((const __m128i*)(qlp_coeff+0));
+               xmm1 = _mm_loadu_si128((const __m128i*)(qlp_coeff+4));
+               xmm0 = _mm_packs_epi32(xmm0, xmm1);
+
+               xmm1 = _mm_loadu_si128((const __m128i*)(data-8));
+               xmm3 = _mm_loadu_si128((const __m128i*)(data-4));
+               xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(0,1,2,3));
+               xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(0,1,2,3));
+               xmm3 = _mm_packs_epi32(xmm3, xmm1);
+
+               /* xmm0: qlp_coeff
+                       xmm3: data */
+
+               xmm6 = _mm_madd_epi16(xmm3, xmm0);
+               xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+               xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+               DATA16_RESULT(xmm6);
+
+               data_len--;
+
+               while(data_len) {
+                       xmm3 = _mm_slli_si128(xmm3, 2);
+                       xmm3 = _mm_insert_epi16(xmm3, curr, 0);
+
+                       xmm6 = _mm_madd_epi16(xmm3, xmm0);
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 8));
+                       xmm6 = _mm_add_epi32(xmm6, _mm_srli_si128(xmm6, 4));
+
+                       DATA16_RESULT(xmm6);
+
+                       data_len--;
+               }
+       }
+}
+
+#endif /* defined FLAC__CPU_IA32 && !defined FLAC__HAS_NASM */
+
+#endif /* FLAC__SSE2_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/lpc_intrin_sse41.c b/FLAC/src/lpc_intrin_sse41.c
new file mode 100644 (file)
index 0000000..bef73f4
--- /dev/null
@@ -0,0 +1,1314 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/lpc.h"
+#ifdef FLAC__SSE4_1_SUPPORTED
+
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+
+#include <smmintrin.h> /* SSE4.1 */
+
+#if defined FLAC__CPU_IA32 /* unused for x64 */
+
+#define RESIDUAL64_RESULT(xmmN)  residual[i] = data[i] - _mm_cvtsi128_si32(_mm_srl_epi64(xmmN, cnt))
+#define RESIDUAL64_RESULT1(xmmN) residual[i] = data[i] - _mm_cvtsi128_si32(_mm_srli_epi64(xmmN, lp_quantization))
+
+FLAC__SSE_TARGET("sse4.1")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+       FLAC__ASSERT(lp_quantization <= 32); /* there's no _mm_sra_epi64() so we have to use _mm_srl_epi64() */
+
+       if(order <= 12) {
+               if(order > 8) { /* order == 9, 10, 11, 12 */
+                       if(order > 10) { /* order == 11, 12 */
+                               if(order == 12) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));  // 0  0  q[1]  q[0]
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));  // 0  0  q[3]  q[2]
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));  // 0  0  q[5]  q[4]
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));  // 0  0  q[7]  q[6]
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));  // 0  0  q[9]  q[8]
+                                       xmm5 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+10)); // 0  0  q[11] q[10]
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0)); // 0  q[1]  0  q[0]
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0)); // 0  q[3]  0  q[2]
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0)); // 0  q[5]  0  q[4]
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0)); // 0  q[7]  0  q[6]
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0)); // 0  q[9]  0  q[8]
+                                       xmm5 = _mm_shuffle_epi32(xmm5, _MM_SHUFFLE(3,1,2,0)); // 0  q[11] 0  q[10]
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                               //sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-12));  // 0   0        d[i-11]  d[i-12]
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1)); // 0  d[i-12]   0        d[i-11]
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm5);
+
+                                               //sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               //sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm4);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               //sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT1(xmm7);
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));
+                                       xmm5 = _mm_cvtsi32_si128(qlp_coeff[10]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-11]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm5);
+
+                                               //sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               //sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm4);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               //sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT1(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 9, 10 */
+                               if(order == 10) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+                                       xmm4 = _mm_shuffle_epi32(xmm4, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
+                                               //sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-10));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm4);
+
+                                               //sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               //sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                                       xmm4 = _mm_cvtsi32_si128(qlp_coeff[8]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[8] * (FLAC__int64)data[i-9];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-9]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm4);
+
+                                               //sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               //sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm3);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) { /* order == 5, 6, 7, 8 */
+                       if(order > 6) { /* order == 7, 8 */
+                               if(order == 8) {
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+                                       xmm3 = _mm_shuffle_epi32(xmm3, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
+                                               //sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-8));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm3);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m128i xmm0, xmm1, xmm2, xmm3, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                                       xmm3 = _mm_cvtsi32_si128(qlp_coeff[6]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[6] * (FLAC__int64)data[i-7];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-7]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm3);
+
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm2);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 5, 6 */
+                               if(order == 6) {
+                                       __m128i xmm0, xmm1, xmm2, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+                                       xmm2 = _mm_shuffle_epi32(xmm2, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
+                                               //sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-6));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm2);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m128i xmm0, xmm1, xmm2, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                                       xmm2 = _mm_cvtsi32_si128(qlp_coeff[4]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[4] * (FLAC__int64)data[i-5];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-5]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm2);
+
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm1);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                       }
+               }
+               else { /* order == 1, 2, 3, 4 */
+                       if(order > 2) { /* order == 3, 4 */
+                               if(order == 4) {
+                                       __m128i xmm0, xmm1, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+                                       xmm1 = _mm_shuffle_epi32(xmm1, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
+                                               //sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-4));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm1);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m128i xmm0, xmm1, xmm6, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm1 = _mm_cvtsi32_si128(qlp_coeff[2]);
+
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum  = qlp_coeff[2] * (FLAC__int64)data[i-3];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-3]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm1);
+
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm6 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm6 = _mm_shuffle_epi32(xmm6, _MM_SHUFFLE(2,0,3,1));
+                                               xmm6 = _mm_mul_epi32(xmm6, xmm0);
+                                               xmm7 = _mm_add_epi64(xmm7, xmm6);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                       }
+                       else { /* order == 1, 2 */
+                               if(order == 2) {
+                                       __m128i xmm0, xmm7;
+                                       xmm0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                                       xmm0 = _mm_shuffle_epi32(xmm0, _MM_SHUFFLE(3,1,2,0));
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = 0;
+                                               //sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
+                                               //sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm7 = _mm_loadl_epi64((const __m128i*)(data+i-2));
+                                               xmm7 = _mm_shuffle_epi32(xmm7, _MM_SHUFFLE(2,0,3,1));
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm0);
+
+                                               xmm7 = _mm_add_epi64(xmm7, _mm_srli_si128(xmm7, 8));
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m128i xmm0, xmm7;
+                                       xmm0 = _mm_cvtsi32_si128(qlp_coeff[0]);
+
+                                       for(i = 0; i < (int)data_len; i++) {
+                                               //sum = qlp_coeff[0] * (FLAC__int64)data[i-1];
+                                               xmm7 = _mm_cvtsi32_si128(data[i-1]);
+                                               xmm7 = _mm_mul_epi32(xmm7, xmm0);
+                                               RESIDUAL64_RESULT(xmm7);
+                                       }
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               FLAC__int64 sum;
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
+                               case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
+                               case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
+                               case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
+                               case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
+                               case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
+                               case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
+                               case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
+                               case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
+                               case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
+                               case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
+                               case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
+                               case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
+                               case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
+                               case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
+                               case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
+                               case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
+                               case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
+                               case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
+                               case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
+                                        sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                        sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                        sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                                        sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                                        sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                                        sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                                        sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                                        sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                                        sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                                        sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                                        sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                                        sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+}
+
+FLAC__SSE_TARGET("sse4.1")
+void FLAC__lpc_restore_signal_wide_intrin_sse41(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
+{
+       int i;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       if (!data_len)
+               return;
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+       FLAC__ASSERT(lp_quantization <= 32); /* there's no _mm_sra_epi64() so we have to use _mm_srl_epi64() */
+
+       if(order <= 12) {
+               if(order > 8) { /* order == 9, 10, 11, 12 */
+                       if(order > 10) { /* order == 11, 12 */
+                               __m128i qlp[6], dat[6];
+                               __m128i summ, temp;
+                               qlp[0] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));        // 0  0  q[1]  q[0]
+                               qlp[1] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));        // 0  0  q[3]  q[2]
+                               qlp[2] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));        // 0  0  q[5]  q[4]
+                               qlp[3] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));        // 0  0  q[7]  q[6]
+                               qlp[4] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));        // 0  0  q[9]  q[8]
+                               if (order == 12)
+                                       qlp[5] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+10));       // 0  0  q[11] q[10]
+                               else
+                                       qlp[5] = _mm_cvtsi32_si128(qlp_coeff[10]);                                      // 0  0  0     q[10]
+
+                               qlp[0] = _mm_shuffle_epi32(qlp[0], _MM_SHUFFLE(2,0,3,1));       // 0  q[0]  0  q[1]
+                               qlp[1] = _mm_shuffle_epi32(qlp[1], _MM_SHUFFLE(2,0,3,1));       // 0  q[2]  0  q[3]
+                               qlp[2] = _mm_shuffle_epi32(qlp[2], _MM_SHUFFLE(2,0,3,1));       // 0  q[4]  0  q[5]
+                               qlp[3] = _mm_shuffle_epi32(qlp[3], _MM_SHUFFLE(2,0,3,1));       // 0  q[5]  0  q[7]
+                               qlp[4] = _mm_shuffle_epi32(qlp[4], _MM_SHUFFLE(2,0,3,1));       // 0  q[8]  0  q[9]
+                               qlp[5] = _mm_shuffle_epi32(qlp[5], _MM_SHUFFLE(2,0,3,1));       // 0  q[10] 0  q[11]
+
+                               dat[5] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-12)));        // ?  d[i-11]  ?  d[i-12]
+                               dat[4] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-10)));        // ?  d[i-9]   ?  d[i-10]
+                               dat[3] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-8 )));        // ?  d[i-7]   ?  d[i-8]
+                               dat[2] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-6 )));        // ?  d[i-5]   ?  d[i-6]
+                               dat[1] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-4 )));        // ?  d[i-3]   ?  d[i-4]
+                               dat[0] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));        // ?  d[i-1]   ?  d[i-2]
+
+                               summ =                     _mm_mul_epi32(dat[5], qlp[5]) ;
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[4], qlp[4]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[3], qlp[3]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));    // ?_64  sum_64
+                               summ = _mm_srl_epi64(summ, cnt);                                                // ?_64  (sum >> lp_quantization)_64  ==  ?_32  ?_32  ?_32  (sum >> lp_quantization)_32
+                               temp = _mm_cvtsi32_si128(residual[0]);                                  // 0  0  0  r[i]
+                               temp = _mm_add_epi32(temp, summ);                                               // ?  ?  ?  d[i]
+                               data[0] = _mm_cvtsi128_si32(temp);
+
+                               for(i = 1; i < (int)data_len; i++) {
+                                       dat[5] = _mm_alignr_epi8(dat[4], dat[5], 8);    //  ?  d[i-10] ?  d[i-11]
+                                       dat[4] = _mm_alignr_epi8(dat[3], dat[4], 8);    //  ?  d[i-8]  ?  d[i-9]
+                                       dat[3] = _mm_alignr_epi8(dat[2], dat[3], 8);    //  ?  d[i-6]  ?  d[i-7]
+                                       dat[2] = _mm_alignr_epi8(dat[1], dat[2], 8);    //  ?  d[i-4]  ?  d[i-5]
+                                       dat[1] = _mm_alignr_epi8(dat[0], dat[1], 8);    //  ?  d[i-2]  ?  d[i-3]
+                                       dat[0] = _mm_alignr_epi8(temp,   dat[0], 8);    //  ?  d[i  ]  ?  d[i-1]
+
+                                       summ =                     _mm_mul_epi32(dat[5], qlp[5]) ;
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[4], qlp[4]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[3], qlp[3]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));    // ?_64  sum_64
+                                       summ = _mm_srl_epi64(summ, cnt);                                                // ?_64  (sum >> lp_quantization)_64  ==  ?_32  ?_32  ?_32  (sum >> lp_quantization)_32
+                                       temp = _mm_cvtsi32_si128(residual[i]);                                  // 0  0  0  r[i]
+                                       temp = _mm_add_epi32(temp, summ);                                               // ?  ?  ?  d[i]
+                                       data[i] = _mm_cvtsi128_si32(temp);
+                               }
+                       }
+                       else { /* order == 9, 10 */
+                               __m128i qlp[5], dat[5];
+                               __m128i summ, temp;
+                               qlp[0] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                               qlp[1] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                               qlp[2] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                               qlp[3] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                               if (order == 10)
+                                       qlp[4] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+8));
+                               else
+                                       qlp[4] = _mm_cvtsi32_si128(qlp_coeff[8]);
+
+                               qlp[0] = _mm_shuffle_epi32(qlp[0], _MM_SHUFFLE(2,0,3,1));
+                               qlp[1] = _mm_shuffle_epi32(qlp[1], _MM_SHUFFLE(2,0,3,1));
+                               qlp[2] = _mm_shuffle_epi32(qlp[2], _MM_SHUFFLE(2,0,3,1));
+                               qlp[3] = _mm_shuffle_epi32(qlp[3], _MM_SHUFFLE(2,0,3,1));
+                               qlp[4] = _mm_shuffle_epi32(qlp[4], _MM_SHUFFLE(2,0,3,1));
+
+                               dat[4] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-10)));
+                               dat[3] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-8 )));
+                               dat[2] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-6 )));
+                               dat[1] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-4 )));
+                               dat[0] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));
+
+                               summ =                     _mm_mul_epi32(dat[4], qlp[4]) ;
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[3], qlp[3]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                               summ = _mm_srl_epi64(summ, cnt);
+                               temp = _mm_cvtsi32_si128(residual[0]);
+                               temp = _mm_add_epi32(temp, summ);
+                               data[0] = _mm_cvtsi128_si32(temp);
+
+                               for(i = 1; i < (int)data_len; i++) {
+                                       dat[4] = _mm_alignr_epi8(dat[3], dat[4], 8);
+                                       dat[3] = _mm_alignr_epi8(dat[2], dat[3], 8);
+                                       dat[2] = _mm_alignr_epi8(dat[1], dat[2], 8);
+                                       dat[1] = _mm_alignr_epi8(dat[0], dat[1], 8);
+                                       dat[0] = _mm_alignr_epi8(temp,   dat[0], 8);
+
+                                       summ =                     _mm_mul_epi32(dat[4], qlp[4]) ;
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[3], qlp[3]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[i]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[i] = _mm_cvtsi128_si32(temp);
+                               }
+                       }
+               }
+               else if(order > 4) { /* order == 5, 6, 7, 8 */
+                       if(order > 6) { /* order == 7, 8 */
+                               __m128i qlp[4], dat[4];
+                               __m128i summ, temp;
+                               qlp[0] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                               qlp[1] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                               qlp[2] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                               if (order == 8)
+                                       qlp[3] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+6));
+                               else
+                                       qlp[3] = _mm_cvtsi32_si128(qlp_coeff[6]);
+
+                               qlp[0] = _mm_shuffle_epi32(qlp[0], _MM_SHUFFLE(2,0,3,1));
+                               qlp[1] = _mm_shuffle_epi32(qlp[1], _MM_SHUFFLE(2,0,3,1));
+                               qlp[2] = _mm_shuffle_epi32(qlp[2], _MM_SHUFFLE(2,0,3,1));
+                               qlp[3] = _mm_shuffle_epi32(qlp[3], _MM_SHUFFLE(2,0,3,1));
+
+                               dat[3] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-8 )));
+                               dat[2] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-6 )));
+                               dat[1] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-4 )));
+                               dat[0] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));
+
+                               summ =                     _mm_mul_epi32(dat[3], qlp[3]) ;
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                               summ = _mm_srl_epi64(summ, cnt);
+                               temp = _mm_cvtsi32_si128(residual[0]);
+                               temp = _mm_add_epi32(temp, summ);
+                               data[0] = _mm_cvtsi128_si32(temp);
+
+                               for(i = 1; i < (int)data_len; i++) {
+                                       dat[3] = _mm_alignr_epi8(dat[2], dat[3], 8);
+                                       dat[2] = _mm_alignr_epi8(dat[1], dat[2], 8);
+                                       dat[1] = _mm_alignr_epi8(dat[0], dat[1], 8);
+                                       dat[0] = _mm_alignr_epi8(temp,   dat[0], 8);
+
+                                       summ =                     _mm_mul_epi32(dat[3], qlp[3]) ;
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[2], qlp[2]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[i]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[i] = _mm_cvtsi128_si32(temp);
+                               }
+                       }
+                       else { /* order == 5, 6 */
+                               __m128i qlp[3], dat[3];
+                               __m128i summ, temp;
+                               qlp[0] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                               qlp[1] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                               if (order == 6)
+                                       qlp[2] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+4));
+                               else
+                                       qlp[2] = _mm_cvtsi32_si128(qlp_coeff[4]);
+
+                               qlp[0] = _mm_shuffle_epi32(qlp[0], _MM_SHUFFLE(2,0,3,1));
+                               qlp[1] = _mm_shuffle_epi32(qlp[1], _MM_SHUFFLE(2,0,3,1));
+                               qlp[2] = _mm_shuffle_epi32(qlp[2], _MM_SHUFFLE(2,0,3,1));
+
+                               dat[2] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-6 )));
+                               dat[1] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-4 )));
+                               dat[0] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));
+
+                               summ =                     _mm_mul_epi32(dat[2], qlp[2]) ;
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                               summ = _mm_srl_epi64(summ, cnt);
+                               temp = _mm_cvtsi32_si128(residual[0]);
+                               temp = _mm_add_epi32(temp, summ);
+                               data[0] = _mm_cvtsi128_si32(temp);
+
+                               for(i = 1; i < (int)data_len; i++) {
+                                       dat[2] = _mm_alignr_epi8(dat[1], dat[2], 8);
+                                       dat[1] = _mm_alignr_epi8(dat[0], dat[1], 8);
+                                       dat[0] = _mm_alignr_epi8(temp,   dat[0], 8);
+
+                                       summ =                     _mm_mul_epi32(dat[2], qlp[2]) ;
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[1], qlp[1]));
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[i]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[i] = _mm_cvtsi128_si32(temp);
+                               }
+                       }
+               }
+               else { /* order == 1, 2, 3, 4 */
+                       if(order > 2) { /* order == 3, 4 */
+                               __m128i qlp[2], dat[2];
+                               __m128i summ, temp;
+                               qlp[0] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+0));
+                               if (order == 4)
+                                       qlp[1] = _mm_loadl_epi64((const __m128i*)(qlp_coeff+2));
+                               else
+                                       qlp[1] = _mm_cvtsi32_si128(qlp_coeff[2]);
+
+                               qlp[0] = _mm_shuffle_epi32(qlp[0], _MM_SHUFFLE(2,0,3,1));
+                               qlp[1] = _mm_shuffle_epi32(qlp[1], _MM_SHUFFLE(2,0,3,1));
+
+                               dat[1] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-4 )));
+                               dat[0] = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));
+
+                               summ =                     _mm_mul_epi32(dat[1], qlp[1]) ;
+                               summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                               summ = _mm_srl_epi64(summ, cnt);
+                               temp = _mm_cvtsi32_si128(residual[0]);
+                               temp = _mm_add_epi32(temp, summ);
+                               data[0] = _mm_cvtsi128_si32(temp);
+
+                               for(i = 1; i < (int)data_len; i++) {
+                                       dat[1] = _mm_alignr_epi8(dat[0], dat[1], 8);
+                                       dat[0] = _mm_alignr_epi8(temp,   dat[0], 8);
+
+                                       summ =                     _mm_mul_epi32(dat[1], qlp[1]) ;
+                                       summ = _mm_add_epi64(summ, _mm_mul_epi32(dat[0], qlp[0]));
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[i]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[i] = _mm_cvtsi128_si32(temp);
+                               }
+                       }
+                       else { /* order == 1, 2 */
+                               if(order == 2) {
+                                       __m128i qlp0, dat0;
+                                       __m128i summ, temp;
+                                       qlp0 = _mm_loadl_epi64((const __m128i*)(qlp_coeff));
+                                       qlp0 = _mm_shuffle_epi32(qlp0, _MM_SHUFFLE(2,0,3,1));
+
+                                       dat0 = _mm_cvtepu32_epi64(_mm_loadl_epi64((const __m128i*)(data-2 )));
+
+                                       summ = _mm_mul_epi32(dat0, qlp0) ;
+
+                                       summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[0]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[0] = _mm_cvtsi128_si32(temp);
+
+                                       for(i = 1; i < (int)data_len; i++) {
+                                               dat0 = _mm_alignr_epi8(temp, dat0, 8);
+
+                                               summ = _mm_mul_epi32(dat0, qlp0) ;
+
+                                               summ = _mm_add_epi64(summ, _mm_srli_si128(summ, 8));
+                                               summ = _mm_srl_epi64(summ, cnt);
+                                               temp = _mm_cvtsi32_si128(residual[i]);
+                                               temp = _mm_add_epi32(temp, summ);
+                                               data[i] = _mm_cvtsi128_si32(temp);
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m128i qlp0;
+                                       __m128i summ, temp;
+                                       qlp0 = _mm_cvtsi32_si128(qlp_coeff[0]);
+                                       temp = _mm_cvtsi32_si128(data[-1]);
+
+                                       summ = _mm_mul_epi32(temp, qlp0);
+                                       summ = _mm_srl_epi64(summ, cnt);
+                                       temp = _mm_cvtsi32_si128(residual[0]);
+                                       temp = _mm_add_epi32(temp, summ);
+                                       data[0] = _mm_cvtsi128_si32(temp);
+
+                                       for(i = 1; i < (int)data_len; i++) {
+                                               summ = _mm_mul_epi32(temp, qlp0) ;
+                                               summ = _mm_srl_epi64(summ, cnt);
+                                               temp = _mm_cvtsi32_si128(residual[i]);
+                                               temp = _mm_add_epi32(temp, summ);
+                                               data[i] = _mm_cvtsi128_si32(temp);
+                                       }
+                               }
+                       }
+               }
+       }
+       else { /* order > 12 */
+               FLAC__int64 sum;
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
+                               case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
+                               case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
+                               case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
+                               case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
+                               case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
+                               case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
+                               case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
+                               case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
+                               case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
+                               case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
+                               case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
+                               case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
+                               case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
+                               case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
+                               case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
+                               case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
+                               case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
+                               case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
+                               case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
+                                        sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
+                                        sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
+                                        sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
+                                        sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
+                                        sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
+                                        sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
+                                        sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
+                                        sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
+                                        sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
+                                        sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
+                                        sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
+                                        sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
+                       }
+                       data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
+               }
+       }
+}
+
+#endif /* defined FLAC__CPU_IA32 */
+
+FLAC__SSE_TARGET("sse4.1")
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
+{
+       int i;
+       FLAC__int32 sum;
+       __m128i cnt = _mm_cvtsi32_si128(lp_quantization);
+
+       FLAC__ASSERT(order > 0);
+       FLAC__ASSERT(order <= 32);
+
+       if(order <= 12) {
+               if(order > 8) {
+                       if(order > 10) {
+                               if(order == 12) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+                                       q10 = _mm_cvtsi32_si128(qlp_coeff[10]); q10 = _mm_shuffle_epi32(q10, _MM_SHUFFLE(0,0,0,0));
+                                       q11 = _mm_cvtsi32_si128(qlp_coeff[11]); q11 = _mm_shuffle_epi32(q11, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q11, _mm_loadu_si128((const __m128i*)(data+i-12)));
+                                               mull = _mm_mullo_epi32(q10, _mm_loadu_si128((const __m128i*)(data+i-11))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q9, _mm_loadu_si128((const __m128i*)(data+i-10))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 11 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+                                       q10 = _mm_cvtsi32_si128(qlp_coeff[10]); q10 = _mm_shuffle_epi32(q10, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q10, _mm_loadu_si128((const __m128i*)(data+i-11)));
+                                               mull = _mm_mullo_epi32(q9, _mm_loadu_si128((const __m128i*)(data+i-10))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 10) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+                                       q9 = _mm_cvtsi32_si128(qlp_coeff[9]); q9 = _mm_shuffle_epi32(q9, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q9, _mm_loadu_si128((const __m128i*)(data+i-10)));
+                                               mull = _mm_mullo_epi32(q8, _mm_loadu_si128((const __m128i*)(data+i-9))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 9 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7, q8;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+                                       q8 = _mm_cvtsi32_si128(qlp_coeff[8]); q8 = _mm_shuffle_epi32(q8, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q8, _mm_loadu_si128((const __m128i*)(data+i-9)));
+                                               mull = _mm_mullo_epi32(q7, _mm_loadu_si128((const __m128i*)(data+i-8))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else if(order > 4) {
+                       if(order > 6) {
+                               if(order == 8) {
+                                       __m128i q0, q1, q2, q3, q4, q5, q6, q7;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+                                       q7 = _mm_cvtsi32_si128(qlp_coeff[7]); q7 = _mm_shuffle_epi32(q7, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q7, _mm_loadu_si128((const __m128i*)(data+i-8)));
+                                               mull = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 7 */
+                                       __m128i q0, q1, q2, q3, q4, q5, q6;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+                                       q6 = _mm_cvtsi32_si128(qlp_coeff[6]); q6 = _mm_shuffle_epi32(q6, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q6, _mm_loadu_si128((const __m128i*)(data+i-7)));
+                                               mull = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 6) {
+                                       __m128i q0, q1, q2, q3, q4, q5;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+                                       q5 = _mm_cvtsi32_si128(qlp_coeff[5]); q5 = _mm_shuffle_epi32(q5, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q5, _mm_loadu_si128((const __m128i*)(data+i-6)));
+                                               mull = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 5 */
+                                       __m128i q0, q1, q2, q3, q4;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+                                       q4 = _mm_cvtsi32_si128(qlp_coeff[4]); q4 = _mm_shuffle_epi32(q4, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q4, _mm_loadu_si128((const __m128i*)(data+i-5)));
+                                               mull = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               else {
+                       if(order > 2) {
+                               if(order == 4) {
+                                       __m128i q0, q1, q2, q3;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+                                       q3 = _mm_cvtsi32_si128(qlp_coeff[3]); q3 = _mm_shuffle_epi32(q3, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q3, _mm_loadu_si128((const __m128i*)(data+i-4)));
+                                               mull = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 3 */
+                                       __m128i q0, q1, q2;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+                                       q2 = _mm_cvtsi32_si128(qlp_coeff[2]); q2 = _mm_shuffle_epi32(q2, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q2, _mm_loadu_si128((const __m128i*)(data+i-3)));
+                                               mull = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2))); summ = _mm_add_epi32(summ, mull);
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+                       else {
+                               if(order == 2) {
+                                       __m128i q0, q1;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+                                       q1 = _mm_cvtsi32_si128(qlp_coeff[1]); q1 = _mm_shuffle_epi32(q1, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ, mull;
+                                               summ = _mm_mullo_epi32(q1, _mm_loadu_si128((const __m128i*)(data+i-2)));
+                                               mull = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1))); summ = _mm_add_epi32(summ, mull);
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                               else { /* order == 1 */
+                                       __m128i q0;
+                                       q0 = _mm_cvtsi32_si128(qlp_coeff[0]); q0 = _mm_shuffle_epi32(q0, _MM_SHUFFLE(0,0,0,0));
+
+                                       for(i = 0; i < (int)data_len-3; i+=4) {
+                                               __m128i summ;
+                                               summ = _mm_mullo_epi32(q0, _mm_loadu_si128((const __m128i*)(data+i-1)));
+                                               summ = _mm_sra_epi32(summ, cnt);
+                                               _mm_storeu_si128((__m128i*)(residual+i), _mm_sub_epi32(_mm_loadu_si128((const __m128i*)(data+i)), summ));
+                                       }
+                               }
+                       }
+               }
+               for(; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 12: sum += qlp_coeff[11] * data[i-12];
+                               case 11: sum += qlp_coeff[10] * data[i-11];
+                               case 10: sum += qlp_coeff[ 9] * data[i-10];
+                               case 9:  sum += qlp_coeff[ 8] * data[i- 9];
+                               case 8:  sum += qlp_coeff[ 7] * data[i- 8];
+                               case 7:  sum += qlp_coeff[ 6] * data[i- 7];
+                               case 6:  sum += qlp_coeff[ 5] * data[i- 6];
+                               case 5:  sum += qlp_coeff[ 4] * data[i- 5];
+                               case 4:  sum += qlp_coeff[ 3] * data[i- 4];
+                               case 3:  sum += qlp_coeff[ 2] * data[i- 3];
+                               case 2:  sum += qlp_coeff[ 1] * data[i- 2];
+                               case 1:  sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+       else { /* order > 12 */
+               for(i = 0; i < (int)data_len; i++) {
+                       sum = 0;
+                       switch(order) {
+                               case 32: sum += qlp_coeff[31] * data[i-32];
+                               case 31: sum += qlp_coeff[30] * data[i-31];
+                               case 30: sum += qlp_coeff[29] * data[i-30];
+                               case 29: sum += qlp_coeff[28] * data[i-29];
+                               case 28: sum += qlp_coeff[27] * data[i-28];
+                               case 27: sum += qlp_coeff[26] * data[i-27];
+                               case 26: sum += qlp_coeff[25] * data[i-26];
+                               case 25: sum += qlp_coeff[24] * data[i-25];
+                               case 24: sum += qlp_coeff[23] * data[i-24];
+                               case 23: sum += qlp_coeff[22] * data[i-23];
+                               case 22: sum += qlp_coeff[21] * data[i-22];
+                               case 21: sum += qlp_coeff[20] * data[i-21];
+                               case 20: sum += qlp_coeff[19] * data[i-20];
+                               case 19: sum += qlp_coeff[18] * data[i-19];
+                               case 18: sum += qlp_coeff[17] * data[i-18];
+                               case 17: sum += qlp_coeff[16] * data[i-17];
+                               case 16: sum += qlp_coeff[15] * data[i-16];
+                               case 15: sum += qlp_coeff[14] * data[i-15];
+                               case 14: sum += qlp_coeff[13] * data[i-14];
+                               case 13: sum += qlp_coeff[12] * data[i-13];
+                                        sum += qlp_coeff[11] * data[i-12];
+                                        sum += qlp_coeff[10] * data[i-11];
+                                        sum += qlp_coeff[ 9] * data[i-10];
+                                        sum += qlp_coeff[ 8] * data[i- 9];
+                                        sum += qlp_coeff[ 7] * data[i- 8];
+                                        sum += qlp_coeff[ 6] * data[i- 7];
+                                        sum += qlp_coeff[ 5] * data[i- 6];
+                                        sum += qlp_coeff[ 4] * data[i- 5];
+                                        sum += qlp_coeff[ 3] * data[i- 4];
+                                        sum += qlp_coeff[ 2] * data[i- 3];
+                                        sum += qlp_coeff[ 1] * data[i- 2];
+                                        sum += qlp_coeff[ 0] * data[i- 1];
+                       }
+                       residual[i] = data[i] - (sum >> lp_quantization);
+               }
+       }
+}
+
+#endif /* FLAC__SSE4_1_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
+#endif /* FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/md5.c b/FLAC/src/md5.c
new file mode 100644 (file)
index 0000000..e9013a9
--- /dev/null
@@ -0,0 +1,516 @@
+#ifdef HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
+#include <stdlib.h>            /* for malloc() */
+#include <string.h>            /* for memcpy() */
+
+#include "private/md5.h"
+#include "share/alloc.h"
+#include "share/endswap.h"
+
+/*
+ * This code implements the MD5 message-digest algorithm.
+ * The algorithm is due to Ron Rivest.  This code was
+ * written by Colin Plumb in 1993, no copyright is claimed.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is equivalent,
+ * except that you don't need to include two pages of legalese
+ * with every copy.
+ *
+ * To compute the message digest of a chunk of bytes, declare an
+ * MD5Context structure, pass it to MD5Init, call MD5Update as
+ * needed on buffers full of bytes, and then call MD5Final, which
+ * will fill a supplied 16-byte array with the digest.
+ *
+ * Changed so as no longer to depend on Colin Plumb's `usual.h' header
+ * definitions; now uses stuff from dpkg's config.h.
+ *  - Ian Jackson <ijackson@nyx.cs.du.edu>.
+ * Still in the public domain.
+ *
+ * Josh Coalson: made some changes to integrate with libFLAC.
+ * Still in the public domain.
+ */
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f,w,x,y,z,in,s) \
+        (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
+{
+       register FLAC__uint32 a, b, c, d;
+
+       a = buf[0];
+       b = buf[1];
+       c = buf[2];
+       d = buf[3];
+
+       MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+       MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+       MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+       MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+       MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+       MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+       MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+       MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+       MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+       MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+       MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+       MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+       MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+       MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+       MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+       MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+       MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+       MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+       MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+       MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+       MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+       MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+       MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+       MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+       MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+       MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+       MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+       MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+       MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+       MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+       MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+       MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+       MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+       MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+       MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+       MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+       MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+       MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+       MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+       MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+       MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+       MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+       MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+       MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+       MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+       MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+       MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+       MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+       MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+       MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+       MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+       MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+       MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+       MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+       MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+       MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+       MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+       MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+       MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+       MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+       MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+       MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+       MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+       MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+       buf[0] += a;
+       buf[1] += b;
+       buf[2] += c;
+       buf[3] += d;
+}
+
+#if WORDS_BIGENDIAN
+//@@@@@@ OPT: use bswap/intrinsics
+static void byteSwap(FLAC__uint32 *buf, unsigned words)
+{
+       register FLAC__uint32 x;
+       do {
+               x = *buf;
+               x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
+               *buf++ = (x >> 16) | (x << 16);
+       } while (--words);
+}
+static void byteSwapX16(FLAC__uint32 *buf)
+{
+       register FLAC__uint32 x;
+
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
+       x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf   = (x >> 16) | (x << 16);
+}
+#else
+#define byteSwap(buf, words)
+#define byteSwapX16(buf)
+#endif
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
+{
+       FLAC__uint32 t;
+
+       /* Update byte count */
+
+       t = ctx->bytes[0];
+       if ((ctx->bytes[0] = t + len) < t)
+               ctx->bytes[1]++;        /* Carry from low to high */
+
+       t = 64 - (t & 0x3f);    /* Space available in ctx->in (at least 1) */
+       if (t > len) {
+               memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
+               return;
+       }
+       /* First chunk is an odd size */
+       memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
+       byteSwapX16(ctx->in);
+       FLAC__MD5Transform(ctx->buf, ctx->in);
+       buf += t;
+       len -= t;
+
+       /* Process data in 64-byte chunks */
+       while (len >= 64) {
+               memcpy(ctx->in, buf, 64);
+               byteSwapX16(ctx->in);
+               FLAC__MD5Transform(ctx->buf, ctx->in);
+               buf += 64;
+               len -= 64;
+       }
+
+       /* Handle any remaining bytes of data. */
+       memcpy(ctx->in, buf, len);
+}
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void FLAC__MD5Init(FLAC__MD5Context *ctx)
+{
+       ctx->buf[0] = 0x67452301;
+       ctx->buf[1] = 0xefcdab89;
+       ctx->buf[2] = 0x98badcfe;
+       ctx->buf[3] = 0x10325476;
+
+       ctx->bytes[0] = 0;
+       ctx->bytes[1] = 0;
+
+       ctx->internal_buf.p8 = 0;
+       ctx->capacity = 0;
+}
+
+/*
+ * Final wrapup - pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
+{
+       int count = ctx->bytes[0] & 0x3f;       /* Number of bytes in ctx->in */
+       FLAC__byte *p = (FLAC__byte *)ctx->in + count;
+
+       /* Set the first char of padding to 0x80.  There is always room. */
+       *p++ = 0x80;
+
+       /* Bytes of padding needed to make 56 bytes (-8..55) */
+       count = 56 - 1 - count;
+
+       if (count < 0) {        /* Padding forces an extra block */
+               memset(p, 0, count + 8);
+               byteSwapX16(ctx->in);
+               FLAC__MD5Transform(ctx->buf, ctx->in);
+               p = (FLAC__byte *)ctx->in;
+               count = 56;
+       }
+       memset(p, 0, count);
+       byteSwap(ctx->in, 14);
+
+       /* Append length in bits and transform */
+       ctx->in[14] = ctx->bytes[0] << 3;
+       ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
+       FLAC__MD5Transform(ctx->buf, ctx->in);
+
+       byteSwap(ctx->buf, 4);
+       memcpy(digest, ctx->buf, 16);
+       if (0 != ctx->internal_buf.p8) {
+               free(ctx->internal_buf.p8);
+               ctx->internal_buf.p8 = 0;
+               ctx->capacity = 0;
+       }
+       memset(ctx, 0, sizeof(*ctx));   /* In case it's sensitive */
+}
+
+/*
+ * Convert the incoming audio signal to a byte stream
+ */
+static void format_input_(FLAC__multibyte *mbuf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
+{
+       FLAC__byte *buf_ = mbuf->p8;
+       FLAC__int16 *buf16 = mbuf->p16;
+       FLAC__int32 *buf32 = mbuf->p32;
+       FLAC__int32 a_word;
+       unsigned channel, sample;
+
+       /* Storage in the output buffer, buf, is little endian. */
+
+#define BYTES_CHANNEL_SELECTOR(bytes, channels)   (bytes * 100 + channels)
+
+       /* First do the most commonly used combinations. */
+       switch (BYTES_CHANNEL_SELECTOR (bytes_per_sample, channels)) {
+               /* One byte per sample. */
+               case (BYTES_CHANNEL_SELECTOR (1, 1)):
+                       for (sample = 0; sample < samples; sample++)
+                               *buf_++ = signal[0][sample];
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (1, 2)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf_++ = signal[0][sample];
+                               *buf_++ = signal[1][sample];
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (1, 4)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf_++ = signal[0][sample];
+                               *buf_++ = signal[1][sample];
+                               *buf_++ = signal[2][sample];
+                               *buf_++ = signal[3][sample];
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (1, 6)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf_++ = signal[0][sample];
+                               *buf_++ = signal[1][sample];
+                               *buf_++ = signal[2][sample];
+                               *buf_++ = signal[3][sample];
+                               *buf_++ = signal[4][sample];
+                               *buf_++ = signal[5][sample];
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (1, 8)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf_++ = signal[0][sample];
+                               *buf_++ = signal[1][sample];
+                               *buf_++ = signal[2][sample];
+                               *buf_++ = signal[3][sample];
+                               *buf_++ = signal[4][sample];
+                               *buf_++ = signal[5][sample];
+                               *buf_++ = signal[6][sample];
+                               *buf_++ = signal[7][sample];
+                       }
+                       return;
+
+               /* Two bytes per sample. */
+               case (BYTES_CHANNEL_SELECTOR (2, 1)):
+                       for (sample = 0; sample < samples; sample++)
+                               *buf16++ = H2LE_16(signal[0][sample]);
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (2, 2)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf16++ = H2LE_16(signal[0][sample]);
+                               *buf16++ = H2LE_16(signal[1][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (2, 4)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf16++ = H2LE_16(signal[0][sample]);
+                               *buf16++ = H2LE_16(signal[1][sample]);
+                               *buf16++ = H2LE_16(signal[2][sample]);
+                               *buf16++ = H2LE_16(signal[3][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (2, 6)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf16++ = H2LE_16(signal[0][sample]);
+                               *buf16++ = H2LE_16(signal[1][sample]);
+                               *buf16++ = H2LE_16(signal[2][sample]);
+                               *buf16++ = H2LE_16(signal[3][sample]);
+                               *buf16++ = H2LE_16(signal[4][sample]);
+                               *buf16++ = H2LE_16(signal[5][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (2, 8)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf16++ = H2LE_16(signal[0][sample]);
+                               *buf16++ = H2LE_16(signal[1][sample]);
+                               *buf16++ = H2LE_16(signal[2][sample]);
+                               *buf16++ = H2LE_16(signal[3][sample]);
+                               *buf16++ = H2LE_16(signal[4][sample]);
+                               *buf16++ = H2LE_16(signal[5][sample]);
+                               *buf16++ = H2LE_16(signal[6][sample]);
+                               *buf16++ = H2LE_16(signal[7][sample]);
+                       }
+                       return;
+
+               /* Three bytes per sample. */
+               case (BYTES_CHANNEL_SELECTOR (3, 1)):
+                       for (sample = 0; sample < samples; sample++) {
+                               a_word = signal[0][sample];
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word;
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (3, 2)):
+                       for (sample = 0; sample < samples; sample++) {
+                               a_word = signal[0][sample];
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word;
+                               a_word = signal[1][sample];
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                               *buf_++ = (FLAC__byte)a_word;
+                       }
+                       return;
+
+               /* Four bytes per sample. */
+               case (BYTES_CHANNEL_SELECTOR (4, 1)):
+                       for (sample = 0; sample < samples; sample++)
+                               *buf32++ = H2LE_32(signal[0][sample]);
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (4, 2)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf32++ = H2LE_32(signal[0][sample]);
+                               *buf32++ = H2LE_32(signal[1][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (4, 4)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf32++ = H2LE_32(signal[0][sample]);
+                               *buf32++ = H2LE_32(signal[1][sample]);
+                               *buf32++ = H2LE_32(signal[2][sample]);
+                               *buf32++ = H2LE_32(signal[3][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (4, 6)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf32++ = H2LE_32(signal[0][sample]);
+                               *buf32++ = H2LE_32(signal[1][sample]);
+                               *buf32++ = H2LE_32(signal[2][sample]);
+                               *buf32++ = H2LE_32(signal[3][sample]);
+                               *buf32++ = H2LE_32(signal[4][sample]);
+                               *buf32++ = H2LE_32(signal[5][sample]);
+                       }
+                       return;
+
+               case (BYTES_CHANNEL_SELECTOR (4, 8)):
+                       for (sample = 0; sample < samples; sample++) {
+                               *buf32++ = H2LE_32(signal[0][sample]);
+                               *buf32++ = H2LE_32(signal[1][sample]);
+                               *buf32++ = H2LE_32(signal[2][sample]);
+                               *buf32++ = H2LE_32(signal[3][sample]);
+                               *buf32++ = H2LE_32(signal[4][sample]);
+                               *buf32++ = H2LE_32(signal[5][sample]);
+                               *buf32++ = H2LE_32(signal[6][sample]);
+                               *buf32++ = H2LE_32(signal[7][sample]);
+                       }
+                       return;
+
+               default:
+                       break;
+       }
+
+       /* General version. */
+       switch (bytes_per_sample) {
+               case 1:
+                       for (sample = 0; sample < samples; sample++)
+                               for (channel = 0; channel < channels; channel++)
+                                       *buf_++ = signal[channel][sample];
+                       return;
+
+               case 2:
+                       for (sample = 0; sample < samples; sample++)
+                               for (channel = 0; channel < channels; channel++)
+                                       *buf16++ = H2LE_16(signal[channel][sample]);
+                       return;
+
+               case 3:
+                       for (sample = 0; sample < samples; sample++)
+                               for (channel = 0; channel < channels; channel++) {
+                                       a_word = signal[channel][sample];
+                                       *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                                       *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
+                                       *buf_++ = (FLAC__byte)a_word;
+                               }
+                       return;
+
+               case 4:
+                       for (sample = 0; sample < samples; sample++)
+                               for (channel = 0; channel < channels; channel++)
+                                       *buf32++ = H2LE_32(signal[channel][sample]);
+                       return;
+
+               default:
+                       break;
+       }
+}
+
+/*
+ * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
+ */
+FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
+{
+       const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
+
+       /* overflow check */
+       if ((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
+               return false;
+       if ((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
+               return false;
+
+       if (ctx->capacity < bytes_needed) {
+               if (0 == (ctx->internal_buf.p8 = safe_realloc_(ctx->internal_buf.p8, bytes_needed))) {
+                       if (0 == (ctx->internal_buf.p8 = safe_malloc_(bytes_needed))) {
+                               ctx->capacity = 0;
+                               return false;
+                       }
+               }
+               ctx->capacity = bytes_needed;
+       }
+
+       format_input_(&ctx->internal_buf, signal, channels, samples, bytes_per_sample);
+
+       FLAC__MD5Update(ctx, ctx->internal_buf.p8, bytes_needed);
+
+       return true;
+}
diff --git a/FLAC/src/memory.c b/FLAC/src/memory.c
new file mode 100644 (file)
index 0000000..a8ebd10
--- /dev/null
@@ -0,0 +1,218 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 HAVE_STDINT_H
+#include <stdint.h>
+#endif
+
+#include "private/memory.h"
+#include "FLAC/assert.h"
+#include "share/alloc.h"
+
+void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
+{
+       void *x;
+
+       FLAC__ASSERT(0 != aligned_address);
+
+#ifdef FLAC__ALIGN_MALLOC_DATA
+       /* align on 32-byte (256-bit) boundary */
+       x = safe_malloc_add_2op_(bytes, /*+*/31L);
+       *aligned_address = (void*)(((uintptr_t)x + 31L) & -32L);
+#else
+       x = safe_malloc_(bytes);
+       *aligned_address = x;
+#endif
+       return x;
+}
+
+FLAC__bool FLAC__memory_alloc_aligned_int32_array(size_t elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
+{
+       FLAC__int32 *pu; /* unaligned pointer */
+       union { /* union needed to comply with C99 pointer aliasing rules */
+               FLAC__int32 *pa; /* aligned pointer */
+               void        *pv; /* aligned pointer alias */
+       } u;
+
+       FLAC__ASSERT(elements > 0);
+       FLAC__ASSERT(0 != unaligned_pointer);
+       FLAC__ASSERT(0 != aligned_pointer);
+       FLAC__ASSERT(unaligned_pointer != aligned_pointer);
+
+       if(elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
+               return false;
+
+       pu = FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
+       if(0 == pu) {
+               return false;
+       }
+       else {
+               if(*unaligned_pointer != 0)
+                       free(*unaligned_pointer);
+               *unaligned_pointer = pu;
+               *aligned_pointer = u.pa;
+               return true;
+       }
+}
+
+FLAC__bool FLAC__memory_alloc_aligned_uint32_array(size_t elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
+{
+       FLAC__uint32 *pu; /* unaligned pointer */
+       union { /* union needed to comply with C99 pointer aliasing rules */
+               FLAC__uint32 *pa; /* aligned pointer */
+               void         *pv; /* aligned pointer alias */
+       } u;
+
+       FLAC__ASSERT(elements > 0);
+       FLAC__ASSERT(0 != unaligned_pointer);
+       FLAC__ASSERT(0 != aligned_pointer);
+       FLAC__ASSERT(unaligned_pointer != aligned_pointer);
+
+       if(elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
+               return false;
+
+       pu = FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
+       if(0 == pu) {
+               return false;
+       }
+       else {
+               if(*unaligned_pointer != 0)
+                       free(*unaligned_pointer);
+               *unaligned_pointer = pu;
+               *aligned_pointer = u.pa;
+               return true;
+       }
+}
+
+FLAC__bool FLAC__memory_alloc_aligned_uint64_array(size_t elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
+{
+       FLAC__uint64 *pu; /* unaligned pointer */
+       union { /* union needed to comply with C99 pointer aliasing rules */
+               FLAC__uint64 *pa; /* aligned pointer */
+               void         *pv; /* aligned pointer alias */
+       } u;
+
+       FLAC__ASSERT(elements > 0);
+       FLAC__ASSERT(0 != unaligned_pointer);
+       FLAC__ASSERT(0 != aligned_pointer);
+       FLAC__ASSERT(unaligned_pointer != aligned_pointer);
+
+       if(elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
+               return false;
+
+       pu = FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
+       if(0 == pu) {
+               return false;
+       }
+       else {
+               if(*unaligned_pointer != 0)
+                       free(*unaligned_pointer);
+               *unaligned_pointer = pu;
+               *aligned_pointer = u.pa;
+               return true;
+       }
+}
+
+FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(size_t elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
+{
+       unsigned *pu; /* unaligned pointer */
+       union { /* union needed to comply with C99 pointer aliasing rules */
+               unsigned *pa; /* aligned pointer */
+               void     *pv; /* aligned pointer alias */
+       } u;
+
+       FLAC__ASSERT(elements > 0);
+       FLAC__ASSERT(0 != unaligned_pointer);
+       FLAC__ASSERT(0 != aligned_pointer);
+       FLAC__ASSERT(unaligned_pointer != aligned_pointer);
+
+       if(elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
+               return false;
+
+       pu = FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
+       if(0 == pu) {
+               return false;
+       }
+       else {
+               if(*unaligned_pointer != 0)
+                       free(*unaligned_pointer);
+               *unaligned_pointer = pu;
+               *aligned_pointer = u.pa;
+               return true;
+       }
+}
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+FLAC__bool FLAC__memory_alloc_aligned_real_array(size_t elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
+{
+       FLAC__real *pu; /* unaligned pointer */
+       union { /* union needed to comply with C99 pointer aliasing rules */
+               FLAC__real *pa; /* aligned pointer */
+               void       *pv; /* aligned pointer alias */
+       } u;
+
+       FLAC__ASSERT(elements > 0);
+       FLAC__ASSERT(0 != unaligned_pointer);
+       FLAC__ASSERT(0 != aligned_pointer);
+       FLAC__ASSERT(unaligned_pointer != aligned_pointer);
+
+       if(elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
+               return false;
+
+       pu = FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
+       if(0 == pu) {
+               return false;
+       }
+       else {
+               if(*unaligned_pointer != 0)
+                       free(*unaligned_pointer);
+               *unaligned_pointer = pu;
+               *aligned_pointer = u.pa;
+               return true;
+       }
+}
+
+#endif
+
+void *safe_malloc_mul_2op_p(size_t size1, size_t size2)
+{
+       if(!size1 || !size2)
+               return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
+       if(size1 > SIZE_MAX / size2)
+               return 0;
+       return malloc(size1*size2);
+}
diff --git a/FLAC/src/metadata_iterators.c b/FLAC/src/metadata_iterators.c
new file mode 100644 (file)
index 0000000..0a84d03
--- /dev/null
@@ -0,0 +1,3481 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include <sys/stat.h> /* for stat(), maybe chmod() */
+
+#include "private/metadata.h"
+
+#include "FLAC/assert.h"
+#include "FLAC/stream_decoder.h"
+#include "share/alloc.h"
+#include "share/compat.h"
+#include "share/macros.h"
+#include "share/safe_str.h"
+#include "private/macros.h"
+#include "private/memory.h"
+
+/* Alias the first (in share/alloc.h) to the second (in src/libFLAC/memory.c). */
+#define safe_malloc_mul_2op_ safe_malloc_mul_2op_p
+
+/****************************************************************************
+ *
+ * Local function declarations
+ *
+ ***************************************************************************/
+
+static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
+static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
+static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes);
+static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes);
+static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes);
+static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes);
+
+static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator);
+static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block);
+static FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry, unsigned max_length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_VorbisComment *block, unsigned block_length);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block);
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length);
+
+static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
+static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
+static FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
+static FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
+static FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block);
+static FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length);
+static FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length);
+static FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block);
+static FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block);
+static FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block);
+static FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block);
+static FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length);
+
+static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block);
+static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last);
+static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append);
+
+static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator);
+static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator);
+
+static unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb);
+static unsigned seek_to_first_metadata_block_(FILE *f);
+
+static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append);
+static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, FLAC__off_t fixup_is_last_flag_offset, FLAC__bool backup);
+
+static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
+static FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
+static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status);
+static FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status);
+
+static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
+static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
+static void cleanup_tempfile_(FILE **tempfile, char **tempfilename);
+
+static FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats);
+static void set_file_stats_(const char *filename, struct flac_stat_s *stats);
+
+static int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence);
+static FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle);
+
+static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status);
+
+
+#ifdef FLAC__VALGRIND_TESTING
+static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
+{
+       size_t ret = fwrite(ptr, size, nmemb, stream);
+       if(!ferror(stream))
+               fflush(stream);
+       return ret;
+}
+#else
+#define local__fwrite fwrite
+#endif
+
+/****************************************************************************
+ *
+ * Level 0 implementation
+ *
+ ***************************************************************************/
+
+static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
+static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
+static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
+
+typedef struct {
+       FLAC__bool got_error;
+       FLAC__StreamMetadata *object;
+} level0_client_data;
+
+static FLAC__StreamMetadata *get_one_metadata_block_(const char *filename, FLAC__MetadataType type)
+{
+       level0_client_data cd;
+       FLAC__StreamDecoder *decoder;
+
+       FLAC__ASSERT(0 != filename);
+
+       cd.got_error = false;
+       cd.object = 0;
+
+       decoder = FLAC__stream_decoder_new();
+
+       if(0 == decoder)
+               return 0;
+
+       FLAC__stream_decoder_set_md5_checking(decoder, false);
+       FLAC__stream_decoder_set_metadata_ignore_all(decoder);
+       FLAC__stream_decoder_set_metadata_respond(decoder, type);
+
+       if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &cd) != FLAC__STREAM_DECODER_INIT_STATUS_OK || cd.got_error) {
+               (void)FLAC__stream_decoder_finish(decoder);
+               FLAC__stream_decoder_delete(decoder);
+               return 0;
+       }
+
+       if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || cd.got_error) {
+               (void)FLAC__stream_decoder_finish(decoder);
+               FLAC__stream_decoder_delete(decoder);
+               if(0 != cd.object)
+                       FLAC__metadata_object_delete(cd.object);
+               return 0;
+       }
+
+       (void)FLAC__stream_decoder_finish(decoder);
+       FLAC__stream_decoder_delete(decoder);
+
+       return cd.object;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo)
+{
+       FLAC__StreamMetadata *object;
+
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != streaminfo);
+
+       object = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_STREAMINFO);
+
+       if (object) {
+               /* can just copy the contents since STREAMINFO has no internal structure */
+               *streaminfo = *object;
+               FLAC__metadata_object_delete(object);
+               return true;
+       }
+       else {
+               return false;
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags)
+{
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != tags);
+
+       *tags = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+       return 0 != *tags;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet)
+{
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != cuesheet);
+
+       *cuesheet = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_CUESHEET);
+
+       return 0 != *cuesheet;
+}
+
+FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
+{
+       (void)decoder, (void)frame, (void)buffer, (void)client_data;
+
+       return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
+}
+
+void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
+{
+       level0_client_data *cd = (level0_client_data *)client_data;
+       (void)decoder;
+
+       /*
+        * we assume we only get here when the one metadata block we were
+        * looking for was passed to us
+        */
+       if(!cd->got_error && 0 == cd->object) {
+               if(0 == (cd->object = FLAC__metadata_object_clone(metadata)))
+                       cd->got_error = true;
+       }
+}
+
+void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
+{
+       level0_client_data *cd = (level0_client_data *)client_data;
+       (void)decoder;
+
+       if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
+               cd->got_error = true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors)
+{
+       FLAC__Metadata_SimpleIterator *it;
+       FLAC__uint64 max_area_seen = 0;
+       FLAC__uint64 max_depth_seen = 0;
+
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != picture);
+
+       *picture = 0;
+
+       it = FLAC__metadata_simple_iterator_new();
+       if(0 == it)
+               return false;
+       if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) {
+               FLAC__metadata_simple_iterator_delete(it);
+               return false;
+       }
+       do {
+               if(FLAC__metadata_simple_iterator_get_block_type(it) == FLAC__METADATA_TYPE_PICTURE) {
+                       FLAC__StreamMetadata *obj = FLAC__metadata_simple_iterator_get_block(it);
+                       FLAC__uint64 area = (FLAC__uint64)obj->data.picture.width * (FLAC__uint64)obj->data.picture.height;
+                       /* check constraints */
+                       if(
+                               (type == (FLAC__StreamMetadata_Picture_Type)(-1) || type == obj->data.picture.type) &&
+                               (mime_type == 0 || !strcmp(mime_type, obj->data.picture.mime_type)) &&
+                               (description == 0 || !strcmp((const char *)description, (const char *)obj->data.picture.description)) &&
+                               obj->data.picture.width <= max_width &&
+                               obj->data.picture.height <= max_height &&
+                               obj->data.picture.depth <= max_depth &&
+                               obj->data.picture.colors <= max_colors &&
+                               (area > max_area_seen || (area == max_area_seen && obj->data.picture.depth > max_depth_seen))
+                       ) {
+                               if(*picture)
+                                       FLAC__metadata_object_delete(*picture);
+                               *picture = obj;
+                               max_area_seen = area;
+                               max_depth_seen = obj->data.picture.depth;
+                       }
+                       else {
+                               FLAC__metadata_object_delete(obj);
+                       }
+               }
+       } while(FLAC__metadata_simple_iterator_next(it));
+
+       FLAC__metadata_simple_iterator_delete(it);
+
+       return (0 != *picture);
+}
+
+
+/****************************************************************************
+ *
+ * Level 1 implementation
+ *
+ ***************************************************************************/
+
+#define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4)
+/* 1 for initial offset, +4 for our own personal use */
+
+struct FLAC__Metadata_SimpleIterator {
+       FILE *file;
+       char *filename, *tempfile_path_prefix;
+       struct flac_stat_s stats;
+       FLAC__bool has_stats;
+       FLAC__bool is_writable;
+       FLAC__Metadata_SimpleIteratorStatus status;
+       FLAC__off_t offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH];
+       FLAC__off_t first_offset; /* this is the offset to the STREAMINFO block */
+       unsigned depth;
+       /* this is the metadata block header of the current block we are pointing to: */
+       FLAC__bool is_last;
+       FLAC__MetadataType type;
+       unsigned length;
+};
+
+FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = {
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR",
+       "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR"
+};
+
+
+FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void)
+{
+       FLAC__Metadata_SimpleIterator *iterator = calloc(1, sizeof(FLAC__Metadata_SimpleIterator));
+
+       if(0 != iterator) {
+               iterator->file = 0;
+               iterator->filename = 0;
+               iterator->tempfile_path_prefix = 0;
+               iterator->has_stats = false;
+               iterator->is_writable = false;
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+               iterator->first_offset = iterator->offset[0] = -1;
+               iterator->depth = 0;
+       }
+
+       return iterator;
+}
+
+static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+
+       if(0 != iterator->file) {
+               fclose(iterator->file);
+               iterator->file = 0;
+               if(iterator->has_stats)
+                       set_file_stats_(iterator->filename, &iterator->stats);
+       }
+       if(0 != iterator->filename) {
+               free(iterator->filename);
+               iterator->filename = 0;
+       }
+       if(0 != iterator->tempfile_path_prefix) {
+               free(iterator->tempfile_path_prefix);
+               iterator->tempfile_path_prefix = 0;
+       }
+}
+
+FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+
+       simple_iterator_free_guts_(iterator);
+       free(iterator);
+}
+
+FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__Metadata_SimpleIteratorStatus status;
+
+       FLAC__ASSERT(0 != iterator);
+
+       status = iterator->status;
+       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+       return status;
+}
+
+static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only)
+{
+       unsigned ret;
+
+       FLAC__ASSERT(0 != iterator);
+
+       if(read_only || 0 == (iterator->file = flac_fopen(iterator->filename, "r+b"))) {
+               iterator->is_writable = false;
+               if(read_only || errno == EACCES) {
+                       if(0 == (iterator->file = flac_fopen(iterator->filename, "rb"))) {
+                               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
+                               return false;
+                       }
+               }
+               else {
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
+                       return false;
+               }
+       }
+       else {
+               iterator->is_writable = true;
+       }
+
+       ret = seek_to_first_metadata_block_(iterator->file);
+       switch(ret) {
+               case 0:
+                       iterator->depth = 0;
+                       iterator->first_offset = iterator->offset[iterator->depth] = ftello(iterator->file);
+                       return read_metadata_block_header_(iterator);
+               case 1:
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               case 2:
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+                       return false;
+               case 3:
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE;
+                       return false;
+               default:
+                       FLAC__ASSERT(0);
+                       return false;
+       }
+}
+
+#if 0
+@@@ If we decide to finish implementing this, put this comment back in metadata.h
+/*
+ * The 'tempfile_path_prefix' allows you to specify a directory where
+ * tempfiles should go.  Remember that if your metadata edits cause the
+ * FLAC file to grow, the entire file will have to be rewritten.  If
+ * 'tempfile_path_prefix' is NULL, the temp file will be written in the
+ * same directory as the original FLAC file.  This makes replacing the
+ * original with the tempfile fast but requires extra space in the same
+ * partition for the tempfile.  If space is a problem, you can pass a
+ * directory name belonging to a different partition in
+ * 'tempfile_path_prefix'.  Note that you should use the forward slash
+ * '/' as the directory separator.  A trailing slash is not needed; it
+ * will be added automatically.
+ */
+FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool preserve_file_stats, const char *tempfile_path_prefix);
+#endif
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats)
+{
+       const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'flac_rename(...)' for what it will take to finish implementing this */
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != filename);
+
+       simple_iterator_free_guts_(iterator);
+
+       if(!read_only && preserve_file_stats)
+               iterator->has_stats = get_file_stats_(filename, &iterator->stats);
+
+       if(0 == (iterator->filename = strdup(filename))) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       return simple_iterator_prime_input_(iterator, read_only);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       return iterator->is_writable;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       if(iterator->is_last)
+               return false;
+
+       if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       iterator->offset[iterator->depth] = ftello(iterator->file);
+
+       return read_metadata_block_header_(iterator);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__off_t this_offset;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       if(iterator->offset[iterator->depth] == iterator->first_offset)
+               return false;
+
+       if(0 != fseeko(iterator->file, iterator->first_offset, SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+       this_offset = iterator->first_offset;
+       if(!read_metadata_block_header_(iterator))
+               return false;
+
+       /* we ignore any error from ftello() and catch it in fseeko() */
+       while(ftello(iterator->file) + (FLAC__off_t)iterator->length < iterator->offset[iterator->depth]) {
+               if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+                       return false;
+               }
+               this_offset = ftello(iterator->file);
+               if(!read_metadata_block_header_(iterator))
+                       return false;
+       }
+
+       iterator->offset[iterator->depth] = this_offset;
+
+       return true;
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       return iterator->is_last;
+}
+
+/*@@@@add to tests*/
+FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       return iterator->offset[iterator->depth];
+}
+
+FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       return iterator->type;
+}
+
+/*@@@@add to tests*/
+FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       return iterator->length;
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id)
+{
+       const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+       FLAC__ASSERT(0 != id);
+
+       if(iterator->type != FLAC__METADATA_TYPE_APPLICATION) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
+               return false;
+       }
+
+       if(fread(id, 1, id_bytes, iterator->file) != id_bytes) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+               return false;
+       }
+
+       /* back up */
+       if(0 != fseeko(iterator->file, -((int)id_bytes), SEEK_CUR)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type);
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       if(0 != block) {
+               block->is_last = iterator->is_last;
+               block->length = iterator->length;
+
+               if(!read_metadata_block_data_(iterator, block)) {
+                       FLAC__metadata_object_delete(block);
+                       return 0;
+               }
+
+               /* back up to the beginning of the block data to stay consistent */
+               if(0 != fseeko(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) {
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+                       FLAC__metadata_object_delete(block);
+                       return 0;
+               }
+       }
+       else
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       return block;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
+{
+       FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth];)
+       FLAC__bool ret;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+       FLAC__ASSERT(0 != block);
+
+       if(!iterator->is_writable) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
+               return false;
+       }
+
+       if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) {
+               if(iterator->type != block->type) {
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
+                       return false;
+               }
+       }
+
+       block->is_last = iterator->is_last;
+
+       if(iterator->length == block->length)
+               return write_metadata_block_stationary_(iterator, block);
+       else if(iterator->length > block->length) {
+               if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) {
+                       ret = write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last);
+                       FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
+                       FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       return ret;
+               }
+               else {
+                       ret = rewrite_whole_file_(iterator, block, /*append=*/false);
+                       FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
+                       FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       return ret;
+               }
+       }
+       else /* iterator->length < block->length */ {
+               unsigned padding_leftover = 0;
+               FLAC__bool padding_is_last = false;
+               if(use_padding) {
+                       /* first see if we can even use padding */
+                       if(iterator->is_last) {
+                               use_padding = false;
+                       }
+                       else {
+                               const unsigned extra_padding_bytes_required = block->length - iterator->length;
+                               simple_iterator_push_(iterator);
+                               if(!FLAC__metadata_simple_iterator_next(iterator)) {
+                                       (void)simple_iterator_pop_(iterator);
+                                       return false;
+                               }
+                               if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
+                                       use_padding = false;
+                               }
+                               else {
+                                       if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) {
+                                               padding_leftover = 0;
+                                               block->is_last = iterator->is_last;
+                                       }
+                                       else if(iterator->length < extra_padding_bytes_required)
+                                               use_padding = false;
+                                       else {
+                                               padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required;
+                                               padding_is_last = iterator->is_last;
+                                               block->is_last = false;
+                                       }
+                               }
+                               if(!simple_iterator_pop_(iterator))
+                                       return false;
+                       }
+               }
+               if(use_padding) {
+                       if(padding_leftover == 0) {
+                               ret = write_metadata_block_stationary_(iterator, block);
+                               FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
+                               FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                               return ret;
+                       }
+                       else {
+                               FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
+                               ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
+                               FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
+                               FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                               return ret;
+                       }
+               }
+               else {
+                       ret = rewrite_whole_file_(iterator, block, /*append=*/false);
+                       FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
+                       FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       return ret;
+               }
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
+{
+       unsigned padding_leftover = 0;
+       FLAC__bool padding_is_last = false;
+
+       FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;)
+       FLAC__bool ret;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+       FLAC__ASSERT(0 != block);
+
+       if(!iterator->is_writable) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
+               return false;
+       }
+
+       if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
+               return false;
+       }
+
+       block->is_last = iterator->is_last;
+
+       if(use_padding) {
+               /* first see if we can even use padding */
+               if(iterator->is_last) {
+                       use_padding = false;
+               }
+               else {
+                       simple_iterator_push_(iterator);
+                       if(!FLAC__metadata_simple_iterator_next(iterator)) {
+                               (void)simple_iterator_pop_(iterator);
+                               return false;
+                       }
+                       if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
+                               use_padding = false;
+                       }
+                       else {
+                               if(iterator->length == block->length) {
+                                       padding_leftover = 0;
+                                       block->is_last = iterator->is_last;
+                               }
+                               else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length)
+                                       use_padding = false;
+                               else {
+                                       padding_leftover = iterator->length - block->length;
+                                       padding_is_last = iterator->is_last;
+                                       block->is_last = false;
+                               }
+                       }
+                       if(!simple_iterator_pop_(iterator))
+                               return false;
+               }
+       }
+       if(use_padding) {
+               /* move to the next block, which is suitable padding */
+               if(!FLAC__metadata_simple_iterator_next(iterator))
+                       return false;
+               if(padding_leftover == 0) {
+                       ret = write_metadata_block_stationary_(iterator, block);
+                       FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
+                       FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       return ret;
+               }
+               else {
+                       FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
+                       FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
+                       FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+                       return ret;
+               }
+       }
+       else {
+               ret = rewrite_whole_file_(iterator, block, /*append=*/true);
+               FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
+               FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+               return ret;
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding)
+{
+       FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth];)
+       FLAC__bool ret;
+
+       if(!iterator->is_writable) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
+               return false;
+       }
+
+       if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
+               return false;
+       }
+
+       if(use_padding) {
+               FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
+               if(0 == padding) {
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               padding->length = iterator->length;
+               if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) {
+                       FLAC__metadata_object_delete(padding);
+                       return false;
+               }
+               FLAC__metadata_object_delete(padding);
+               if(!FLAC__metadata_simple_iterator_prev(iterator))
+                       return false;
+               FLAC__ASSERT(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length == debug_target_offset);
+               FLAC__ASSERT(ftello(iterator->file) + (FLAC__off_t)iterator->length == debug_target_offset);
+               return true;
+       }
+       else {
+               ret = rewrite_whole_file_(iterator, 0, /*append=*/false);
+               FLAC__ASSERT(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length == debug_target_offset);
+               FLAC__ASSERT(ftello(iterator->file) + (FLAC__off_t)iterator->length == debug_target_offset);
+               return ret;
+       }
+}
+
+
+
+/****************************************************************************
+ *
+ * Level 2 implementation
+ *
+ ***************************************************************************/
+
+
+typedef struct FLAC__Metadata_Node {
+       FLAC__StreamMetadata *data;
+       struct FLAC__Metadata_Node *prev, *next;
+} FLAC__Metadata_Node;
+
+struct FLAC__Metadata_Chain {
+       char *filename; /* will be NULL if using callbacks */
+       FLAC__bool is_ogg;
+       FLAC__Metadata_Node *head;
+       FLAC__Metadata_Node *tail;
+       unsigned nodes;
+       FLAC__Metadata_ChainStatus status;
+       FLAC__off_t first_offset, last_offset;
+       /*
+        * This is the length of the chain initially read from the FLAC file.
+        * it is used to compare against the current length to decide whether
+        * or not the whole file has to be rewritten.
+        */
+       FLAC__off_t initial_length;
+       /* @@@ hacky, these are currently only needed by ogg reader */
+       FLAC__IOHandle handle;
+       FLAC__IOCallback_Read read_cb;
+};
+
+struct FLAC__Metadata_Iterator {
+       FLAC__Metadata_Chain *chain;
+       FLAC__Metadata_Node *current;
+};
+
+FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = {
+       "FLAC__METADATA_CHAIN_STATUS_OK",
+       "FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT",
+       "FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE",
+       "FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE",
+       "FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE",
+       "FLAC__METADATA_CHAIN_STATUS_BAD_METADATA",
+       "FLAC__METADATA_CHAIN_STATUS_READ_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR",
+       "FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS",
+       "FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH",
+       "FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL"
+};
+
+
+static FLAC__Metadata_Node *node_new_(void)
+{
+       return calloc(1, sizeof(FLAC__Metadata_Node));
+}
+
+static void node_delete_(FLAC__Metadata_Node *node)
+{
+       FLAC__ASSERT(0 != node);
+       if(0 != node->data)
+               FLAC__metadata_object_delete(node->data);
+       free(node);
+}
+
+static void chain_init_(FLAC__Metadata_Chain *chain)
+{
+       FLAC__ASSERT(0 != chain);
+
+       chain->filename = 0;
+       chain->is_ogg = false;
+       chain->head = chain->tail = 0;
+       chain->nodes = 0;
+       chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
+       chain->initial_length = 0;
+       chain->read_cb = 0;
+}
+
+static void chain_clear_(FLAC__Metadata_Chain *chain)
+{
+       FLAC__Metadata_Node *node, *next;
+
+       FLAC__ASSERT(0 != chain);
+
+       for(node = chain->head; node; ) {
+               next = node->next;
+               node_delete_(node);
+               node = next;
+       }
+
+       if(0 != chain->filename)
+               free(chain->filename);
+
+       chain_init_(chain);
+}
+
+static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
+{
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != node);
+       FLAC__ASSERT(0 != node->data);
+
+       node->next = node->prev = 0;
+       node->data->is_last = true;
+       if(0 != chain->tail)
+               chain->tail->data->is_last = false;
+
+       if(0 == chain->head)
+               chain->head = node;
+       else {
+               FLAC__ASSERT(0 != chain->tail);
+               chain->tail->next = node;
+               node->prev = chain->tail;
+       }
+       chain->tail = node;
+       chain->nodes++;
+}
+
+static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
+{
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != node);
+
+       if(node == chain->head)
+               chain->head = node->next;
+       else
+               node->prev->next = node->next;
+
+       if(node == chain->tail)
+               chain->tail = node->prev;
+       else
+               node->next->prev = node->prev;
+
+       if(0 != chain->tail)
+               chain->tail->data->is_last = true;
+
+       chain->nodes--;
+}
+
+static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
+{
+       chain_remove_node_(chain, node);
+       node_delete_(node);
+}
+
+static FLAC__off_t chain_calculate_length_(FLAC__Metadata_Chain *chain)
+{
+       const FLAC__Metadata_Node *node;
+       FLAC__off_t length = 0;
+       for(node = chain->head; node; node = node->next)
+               length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
+       return length;
+}
+
+static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
+{
+       FLAC__ASSERT(0 != node);
+       FLAC__ASSERT(0 != node->data);
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+       FLAC__ASSERT(0 != iterator->chain);
+       FLAC__ASSERT(0 != iterator->chain->head);
+       FLAC__ASSERT(0 != iterator->chain->tail);
+
+       node->data->is_last = false;
+
+       node->prev = iterator->current->prev;
+       node->next = iterator->current;
+
+       if(0 == node->prev)
+               iterator->chain->head = node;
+       else
+               node->prev->next = node;
+
+       iterator->current->prev = node;
+
+       iterator->chain->nodes++;
+}
+
+static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
+{
+       FLAC__ASSERT(0 != node);
+       FLAC__ASSERT(0 != node->data);
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+       FLAC__ASSERT(0 != iterator->chain);
+       FLAC__ASSERT(0 != iterator->chain->head);
+       FLAC__ASSERT(0 != iterator->chain->tail);
+
+       iterator->current->data->is_last = false;
+
+       node->prev = iterator->current;
+       node->next = iterator->current->next;
+
+       if(0 == node->next)
+               iterator->chain->tail = node;
+       else
+               node->next->prev = node;
+
+       node->prev->next = node;
+
+       iterator->chain->tail->data->is_last = true;
+
+       iterator->chain->nodes++;
+}
+
+/* return true iff node and node->next are both padding */
+static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
+{
+       if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
+               const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
+               node->data->length += growth; /* new block size can be greater than max metadata block size, but it'll be fixed later in chain_prepare_for_write_() */
+
+               chain_delete_node_(chain, node->next);
+               return true;
+       }
+       else
+               return false;
+}
+
+/* Returns the new length of the chain, or 0 if there was an error. */
+/* WATCHOUT: This can get called multiple times before a write, so
+ * it should still work when this happens.
+ */
+/* WATCHOUT: Make sure to also update the logic in
+ * FLAC__metadata_chain_check_if_tempfile_needed() if the logic here changes.
+ */
+static FLAC__off_t chain_prepare_for_write_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
+{
+       FLAC__off_t current_length = chain_calculate_length_(chain);
+
+       if(use_padding) {
+               /* if the metadata shrank and the last block is padding, we just extend the last padding block */
+               if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
+                       const FLAC__off_t delta = chain->initial_length - current_length;
+                       chain->tail->data->length += delta;
+                       current_length += delta;
+                       FLAC__ASSERT(current_length == chain->initial_length);
+               }
+               /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
+               else if(current_length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
+                       FLAC__StreamMetadata *padding;
+                       FLAC__Metadata_Node *node;
+                       if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
+                               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+                               return 0;
+                       }
+                       padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
+                       if(0 == (node = node_new_())) {
+                               FLAC__metadata_object_delete(padding);
+                               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+                               return 0;
+                       }
+                       node->data = padding;
+                       chain_append_node_(chain, node);
+                       current_length = chain_calculate_length_(chain);
+                       FLAC__ASSERT(current_length == chain->initial_length);
+               }
+               /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
+               else if(current_length > chain->initial_length) {
+                       const FLAC__off_t delta = current_length - chain->initial_length;
+                       if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
+                               /* if the delta is exactly the size of the last padding block, remove the padding block */
+                               if((FLAC__off_t)chain->tail->data->length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
+                                       chain_delete_node_(chain, chain->tail);
+                                       current_length = chain_calculate_length_(chain);
+                                       FLAC__ASSERT(current_length == chain->initial_length);
+                               }
+                               /* if there is at least 'delta' bytes of padding, trim the padding down */
+                               else if((FLAC__off_t)chain->tail->data->length >= delta) {
+                                       chain->tail->data->length -= delta;
+                                       current_length -= delta;
+                                       FLAC__ASSERT(current_length == chain->initial_length);
+                               }
+                       }
+               }
+       }
+
+       /* check sizes of all metadata blocks; reduce padding size if necessary */
+       {
+               FLAC__Metadata_Node *node;
+               for (node = chain->head; node; node = node->next) {
+                       if(node->data->length >= (1u << FLAC__STREAM_METADATA_LENGTH_LEN)) {
+                               if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
+                                       node->data->length = (1u << FLAC__STREAM_METADATA_LENGTH_LEN) - 1;
+                                       current_length = chain_calculate_length_(chain);
+                               } else {
+                                       chain->status = FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
+                                       return 0;
+                               }
+                       }
+               }
+       }
+
+       return current_length;
+}
+
+static FLAC__bool chain_read_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Tell tell_cb)
+{
+       FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != chain);
+
+       /* we assume we're already at the beginning of the file */
+
+       switch(seek_to_first_metadata_block_cb_(handle, read_cb, seek_cb)) {
+               case 0:
+                       break;
+               case 1:
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
+                       return false;
+               case 2:
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+                       return false;
+               case 3:
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
+                       return false;
+               default:
+                       FLAC__ASSERT(0);
+                       return false;
+       }
+
+       {
+               FLAC__int64 pos = tell_cb(handle);
+               if(pos < 0) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
+                       return false;
+               }
+               chain->first_offset = (FLAC__off_t)pos;
+       }
+
+       {
+               FLAC__bool is_last;
+               FLAC__MetadataType type;
+               unsigned length;
+
+               do {
+                       node = node_new_();
+                       if(0 == node) {
+                               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+                               return false;
+                       }
+
+                       if(!read_metadata_block_header_cb_(handle, read_cb, &is_last, &type, &length)) {
+                               node_delete_(node);
+                               chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
+                               return false;
+                       }
+
+                       node->data = FLAC__metadata_object_new(type);
+                       if(0 == node->data) {
+                               node_delete_(node);
+                               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+                               return false;
+                       }
+
+                       node->data->is_last = is_last;
+                       node->data->length = length;
+
+                       chain->status = get_equivalent_status_(read_metadata_block_data_cb_(handle, read_cb, seek_cb, node->data));
+                       if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
+                               node_delete_(node);
+                               return false;
+                       }
+                       chain_append_node_(chain, node);
+               } while(!is_last);
+       }
+
+       {
+               FLAC__int64 pos = tell_cb(handle);
+               if(pos < 0) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
+                       return false;
+               }
+               chain->last_offset = (FLAC__off_t)pos;
+       }
+
+       chain->initial_length = chain_calculate_length_(chain);
+
+       return true;
+}
+
+static FLAC__StreamDecoderReadStatus chain_read_ogg_read_cb_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
+       (void)decoder;
+       if(*bytes > 0 && chain->status == FLAC__METADATA_CHAIN_STATUS_OK) {
+               *bytes = chain->read_cb(buffer, sizeof(FLAC__byte), *bytes, chain->handle);
+               if(*bytes == 0)
+                       return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
+               else
+                       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+       }
+       else
+               return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+}
+
+static FLAC__StreamDecoderWriteStatus chain_read_ogg_write_cb_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
+{
+       (void)decoder, (void)frame, (void)buffer, (void)client_data;
+       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+}
+
+static void chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
+{
+       FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
+       FLAC__Metadata_Node *node;
+
+       (void)decoder;
+
+       node = node_new_();
+       if(0 == node) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+               return;
+       }
+
+       node->data = FLAC__metadata_object_clone(metadata);
+       if(0 == node->data) {
+               node_delete_(node);
+               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+               return;
+       }
+
+       chain_append_node_(chain, node);
+}
+
+static void chain_read_ogg_error_cb_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
+{
+       FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
+       (void)decoder, (void)status;
+       chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
+}
+
+static FLAC__bool chain_read_ogg_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb)
+{
+       FLAC__StreamDecoder *decoder;
+
+       FLAC__ASSERT(0 != chain);
+
+       /* we assume we're already at the beginning of the file */
+
+       chain->handle = handle;
+       chain->read_cb = read_cb;
+       if(0 == (decoder = FLAC__stream_decoder_new())) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       FLAC__stream_decoder_set_metadata_respond_all(decoder);
+       if(FLAC__stream_decoder_init_ogg_stream(decoder, chain_read_ogg_read_cb_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, chain_read_ogg_write_cb_, chain_read_ogg_metadata_cb_, chain_read_ogg_error_cb_, chain) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+               FLAC__stream_decoder_delete(decoder);
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
+               return false;
+       }
+
+       chain->first_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
+
+       if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
+       if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
+               FLAC__stream_decoder_delete(decoder);
+               return false;
+       }
+
+       FLAC__stream_decoder_delete(decoder);
+
+       chain->last_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
+
+       chain->initial_length = chain_calculate_length_(chain);
+
+       return true;
+}
+
+static FLAC__bool chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, FLAC__IOCallback_Seek seek_cb)
+{
+       FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != chain->head);
+
+       if(0 != seek_cb(handle, chain->first_offset, SEEK_SET)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       for(node = chain->head; node; node = node->next) {
+               if(!write_metadata_block_header_cb_(handle, write_cb, node->data)) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
+                       return false;
+               }
+               if(!write_metadata_block_data_cb_(handle, write_cb, node->data)) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
+                       return false;
+               }
+       }
+
+       /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
+
+       chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
+       return true;
+}
+
+static FLAC__bool chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain *chain)
+{
+       FILE *file;
+       FLAC__bool ret;
+
+       FLAC__ASSERT(0 != chain->filename);
+
+       if(0 == (file = flac_fopen(chain->filename, "r+b"))) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
+               return false;
+       }
+
+       /* chain_rewrite_metadata_in_place_cb_() sets chain->status for us */
+       ret = chain_rewrite_metadata_in_place_cb_(chain, (FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, fseek_wrapper_);
+
+       fclose(file);
+
+       return ret;
+}
+
+static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
+{
+       FILE *f, *tempfile = NULL;
+       char *tempfilename;
+       FLAC__Metadata_SimpleIteratorStatus status;
+       const FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != chain->filename);
+       FLAC__ASSERT(0 != chain->head);
+
+       /* copy the file prefix (data up to first metadata block */
+       if(0 == (f = flac_fopen(chain->filename, "rb"))) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
+               return false;
+       }
+       if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
+               chain->status = get_equivalent_status_(status);
+               goto err;
+       }
+       if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
+               chain->status = get_equivalent_status_(status);
+               goto err;
+       }
+
+       /* write the metadata */
+       for(node = chain->head; node; node = node->next) {
+               if(!write_metadata_block_header_(tempfile, &status, node->data)) {
+                       chain->status = get_equivalent_status_(status);
+                       goto err;
+               }
+               if(!write_metadata_block_data_(tempfile, &status, node->data)) {
+                       chain->status = get_equivalent_status_(status);
+                       goto err;
+               }
+       }
+       /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
+
+       /* copy the file postfix (everything after the metadata) */
+       if(0 != fseeko(f, chain->last_offset, SEEK_SET)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               goto err;
+       }
+       if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
+               chain->status = get_equivalent_status_(status);
+               goto err;
+       }
+
+       /* move the tempfile on top of the original */
+       (void)fclose(f);
+       if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
+               return false;
+
+       return true;
+
+err:
+       (void)fclose(f);
+       cleanup_tempfile_(&tempfile, &tempfilename);
+       return false;
+}
+
+/* assumes 'handle' is already at beginning of file */
+static FLAC__bool chain_rewrite_file_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb)
+{
+       FLAC__Metadata_SimpleIteratorStatus status;
+       const FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 == chain->filename);
+       FLAC__ASSERT(0 != chain->head);
+
+       /* copy the file prefix (data up to first metadata block */
+       if(!copy_n_bytes_from_file_cb_(handle, read_cb, temp_handle, temp_write_cb, chain->first_offset, &status)) {
+               chain->status = get_equivalent_status_(status);
+               return false;
+       }
+
+       /* write the metadata */
+       for(node = chain->head; node; node = node->next) {
+               if(!write_metadata_block_header_cb_(temp_handle, temp_write_cb, node->data)) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
+                       return false;
+               }
+               if(!write_metadata_block_data_cb_(temp_handle, temp_write_cb, node->data)) {
+                       chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
+                       return false;
+               }
+       }
+       /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
+
+       /* copy the file postfix (everything after the metadata) */
+       if(0 != seek_cb(handle, chain->last_offset, SEEK_SET)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               return false;
+       }
+       if(!copy_remaining_bytes_from_file_cb_(handle, read_cb, eof_cb, temp_handle, temp_write_cb, &status)) {
+               chain->status = get_equivalent_status_(status);
+               return false;
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void)
+{
+       FLAC__Metadata_Chain *chain = calloc(1, sizeof(FLAC__Metadata_Chain));
+
+       if(0 != chain)
+               chain_init_(chain);
+
+       return chain;
+}
+
+FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
+{
+       FLAC__ASSERT(0 != chain);
+
+       chain_clear_(chain);
+
+       free(chain);
+}
+
+FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
+{
+       FLAC__Metadata_ChainStatus status;
+
+       FLAC__ASSERT(0 != chain);
+
+       status = chain->status;
+       chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
+       return status;
+}
+
+static FLAC__bool chain_read_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool is_ogg)
+{
+       FILE *file;
+       FLAC__bool ret;
+
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != filename);
+
+       chain_clear_(chain);
+
+       if(0 == (chain->filename = strdup(filename))) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       chain->is_ogg = is_ogg;
+
+       if(0 == (file = flac_fopen(filename, "rb"))) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
+               return false;
+       }
+
+       /* the function also sets chain->status for us */
+       ret = is_ogg?
+               chain_read_ogg_cb_(chain, file, (FLAC__IOCallback_Read)fread) :
+               chain_read_cb_(chain, file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, ftell_wrapper_)
+       ;
+
+       fclose(file);
+
+       return ret;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
+{
+       return chain_read_(chain, filename, /*is_ogg=*/false);
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename)
+{
+       return chain_read_(chain, filename, /*is_ogg=*/true);
+}
+
+static FLAC__bool chain_read_with_callbacks_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__bool is_ogg)
+{
+       FLAC__bool ret;
+
+       FLAC__ASSERT(0 != chain);
+
+       chain_clear_(chain);
+
+       if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.tell) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
+               return false;
+       }
+
+       chain->is_ogg = is_ogg;
+
+       /* rewind */
+       if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       /* the function also sets chain->status for us */
+       ret = is_ogg?
+               chain_read_ogg_cb_(chain, handle, callbacks.read) :
+               chain_read_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.tell)
+       ;
+
+       return ret;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
+{
+       return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/false);
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
+{
+       return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/true);
+}
+
+typedef enum {
+       LBS_NONE = 0,
+       LBS_SIZE_CHANGED,
+       LBS_BLOCK_ADDED,
+       LBS_BLOCK_REMOVED
+} LastBlockState;
+
+FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
+{
+       /* This does all the same checks that are in chain_prepare_for_write_()
+        * but doesn't actually alter the chain.  Make sure to update the logic
+        * here if chain_prepare_for_write_() changes.
+        */
+       FLAC__off_t current_length;
+       LastBlockState lbs_state = LBS_NONE;
+       unsigned lbs_size = 0;
+
+       FLAC__ASSERT(0 != chain);
+
+       current_length = chain_calculate_length_(chain);
+
+       if(use_padding) {
+               const FLAC__Metadata_Node * const node = chain->tail;
+               /* if the metadata shrank and the last block is padding, we just extend the last padding block */
+               if(current_length < chain->initial_length && node->data->type == FLAC__METADATA_TYPE_PADDING) {
+                       lbs_state = LBS_SIZE_CHANGED;
+                       lbs_size = node->data->length + (chain->initial_length - current_length);
+               }
+               /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
+               else if(current_length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
+                       lbs_state = LBS_BLOCK_ADDED;
+                       lbs_size = chain->initial_length - (current_length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
+               }
+               /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
+               else if(current_length > chain->initial_length) {
+                       const FLAC__off_t delta = current_length - chain->initial_length;
+                       if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
+                               /* if the delta is exactly the size of the last padding block, remove the padding block */
+                               if((FLAC__off_t)node->data->length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
+                                       lbs_state = LBS_BLOCK_REMOVED;
+                                       lbs_size = 0;
+                               }
+                               /* if there is at least 'delta' bytes of padding, trim the padding down */
+                               else if((FLAC__off_t)node->data->length >= delta) {
+                                       lbs_state = LBS_SIZE_CHANGED;
+                                       lbs_size = node->data->length - delta;
+                               }
+                       }
+               }
+       }
+
+       current_length = 0;
+       /* check sizes of all metadata blocks; reduce padding size if necessary */
+       {
+               const FLAC__Metadata_Node *node;
+               for(node = chain->head; node; node = node->next) {
+                       unsigned block_len = node->data->length;
+                       if(node == chain->tail) {
+                               if(lbs_state == LBS_BLOCK_REMOVED)
+                                       continue;
+                               else if(lbs_state == LBS_SIZE_CHANGED)
+                                       block_len = lbs_size;
+                       }
+                       if(block_len >= (1u << FLAC__STREAM_METADATA_LENGTH_LEN)) {
+                               if(node->data->type == FLAC__METADATA_TYPE_PADDING)
+                                       block_len = (1u << FLAC__STREAM_METADATA_LENGTH_LEN) - 1;
+                               else
+                                       return false /* the return value doesn't matter */;
+                       }
+                       current_length += (FLAC__STREAM_METADATA_HEADER_LENGTH + block_len);
+               }
+
+               if(lbs_state == LBS_BLOCK_ADDED) {
+                       /* test added padding block */
+                       unsigned block_len = lbs_size;
+                       if(block_len >= (1u << FLAC__STREAM_METADATA_LENGTH_LEN))
+                               block_len = (1u << FLAC__STREAM_METADATA_LENGTH_LEN) - 1;
+                       current_length += (FLAC__STREAM_METADATA_HEADER_LENGTH + block_len);
+               }
+       }
+
+       return (current_length != chain->initial_length);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
+{
+       struct flac_stat_s stats;
+       const char *tempfile_path_prefix = 0;
+       FLAC__off_t current_length;
+
+       FLAC__ASSERT(0 != chain);
+
+       if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
+               return false;
+       }
+
+       if (0 == chain->filename) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
+               return false;
+       }
+
+       current_length = chain_prepare_for_write_(chain, use_padding);
+
+       /* a return value of 0 means there was an error; chain->status is already set */
+       if (0 == current_length)
+               return false;
+
+       if(preserve_file_stats)
+               get_file_stats_(chain->filename, &stats);
+
+       if(current_length == chain->initial_length) {
+               if(!chain_rewrite_metadata_in_place_(chain))
+                       return false;
+       }
+       else {
+               if(!chain_rewrite_file_(chain, tempfile_path_prefix))
+                       return false;
+
+               /* recompute lengths and offsets */
+               {
+                       const FLAC__Metadata_Node *node;
+                       chain->initial_length = current_length;
+                       chain->last_offset = chain->first_offset;
+                       for(node = chain->head; node; node = node->next)
+                               chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
+               }
+       }
+
+       if(preserve_file_stats)
+               set_file_stats_(chain->filename, &stats);
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
+{
+       FLAC__off_t current_length;
+
+       FLAC__ASSERT(0 != chain);
+
+       if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
+               return false;
+       }
+
+       if (0 != chain->filename) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
+               return false;
+       }
+
+       if (0 == callbacks.write || 0 == callbacks.seek) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
+               return false;
+       }
+
+       if (FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
+               return false;
+       }
+
+       current_length = chain_prepare_for_write_(chain, use_padding);
+
+       /* a return value of 0 means there was an error; chain->status is already set */
+       if (0 == current_length)
+               return false;
+
+       FLAC__ASSERT(current_length == chain->initial_length);
+
+       return chain_rewrite_metadata_in_place_cb_(chain, handle, callbacks.write, callbacks.seek);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks)
+{
+       FLAC__off_t current_length;
+
+       FLAC__ASSERT(0 != chain);
+
+       if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
+               return false;
+       }
+
+       if (0 != chain->filename) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
+               return false;
+       }
+
+       if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.eof) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
+               return false;
+       }
+       if (0 == temp_callbacks.write) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
+               return false;
+       }
+
+       if (!FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
+               return false;
+       }
+
+       current_length = chain_prepare_for_write_(chain, use_padding);
+
+       /* a return value of 0 means there was an error; chain->status is already set */
+       if (0 == current_length)
+               return false;
+
+       FLAC__ASSERT(current_length != chain->initial_length);
+
+       /* rewind */
+       if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
+               chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       if(!chain_rewrite_file_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.eof, temp_handle, temp_callbacks.write))
+               return false;
+
+       /* recompute lengths and offsets */
+       {
+               const FLAC__Metadata_Node *node;
+               chain->initial_length = current_length;
+               chain->last_offset = chain->first_offset;
+               for(node = chain->head; node; node = node->next)
+                       chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
+       }
+
+       return true;
+}
+
+FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
+{
+       FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != chain);
+
+       for(node = chain->head; node; ) {
+               if(!chain_merge_adjacent_padding_(chain, node))
+                       node = node->next;
+       }
+}
+
+FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
+{
+       FLAC__Metadata_Node *node, *save;
+       unsigned i;
+
+       FLAC__ASSERT(0 != chain);
+
+       /*
+        * Don't try and be too smart... this simple algo is good enough for
+        * the small number of nodes that we deal with.
+        */
+       for(i = 0, node = chain->head; i < chain->nodes; i++) {
+               if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
+                       save = node->next;
+                       chain_remove_node_(chain, node);
+                       chain_append_node_(chain, node);
+                       node = save;
+               }
+               else {
+                       node = node->next;
+               }
+       }
+
+       FLAC__metadata_chain_merge_padding(chain);
+}
+
+
+FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void)
+{
+       FLAC__Metadata_Iterator *iterator = calloc(1, sizeof(FLAC__Metadata_Iterator));
+
+       /* calloc() implies:
+               iterator->current = 0;
+               iterator->chain = 0;
+       */
+
+       return iterator;
+}
+
+FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+
+       free(iterator);
+}
+
+FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != chain);
+       FLAC__ASSERT(0 != chain->head);
+
+       iterator->chain = chain;
+       iterator->current = chain->head;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+
+       if(0 == iterator->current || 0 == iterator->current->next)
+               return false;
+
+       iterator->current = iterator->current->next;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+
+       if(0 == iterator->current || 0 == iterator->current->prev)
+               return false;
+
+       iterator->current = iterator->current->prev;
+       return true;
+}
+
+FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+       FLAC__ASSERT(0 != iterator->current->data);
+
+       return iterator->current->data->type;
+}
+
+FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+
+       return iterator->current->data;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != block);
+       return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
+{
+       FLAC__Metadata_Node *save;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+
+       if(0 == iterator->current->prev) {
+               FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
+               return false;
+       }
+
+       save = iterator->current->prev;
+
+       if(replace_with_padding) {
+               FLAC__metadata_object_delete_data(iterator->current->data);
+               iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
+       }
+       else {
+               chain_delete_node_(iterator->chain, iterator->current);
+       }
+
+       iterator->current = save;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
+{
+       FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+       FLAC__ASSERT(0 != block);
+
+       if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
+               return false;
+
+       if(0 == iterator->current->prev) {
+               FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
+               return false;
+       }
+
+       if(0 == (node = node_new_()))
+               return false;
+
+       node->data = block;
+       iterator_insert_node_(iterator, node);
+       iterator->current = node;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
+{
+       FLAC__Metadata_Node *node;
+
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->current);
+       FLAC__ASSERT(0 != block);
+
+       if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
+               return false;
+
+       if(0 == (node = node_new_()))
+               return false;
+
+       node->data = block;
+       iterator_insert_node_after_(iterator, node);
+       iterator->current = node;
+       return true;
+}
+
+
+/****************************************************************************
+ *
+ * Local function definitions
+ *
+ ***************************************************************************/
+
+void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
+{
+       unsigned i;
+
+       b += bytes;
+
+       for(i = 0; i < bytes; i++) {
+               *(--b) = (FLAC__byte)(val & 0xff);
+               val >>= 8;
+       }
+}
+
+void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
+{
+       unsigned i;
+
+       for(i = 0; i < bytes; i++) {
+               *(b++) = (FLAC__byte)(val & 0xff);
+               val >>= 8;
+       }
+}
+
+void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
+{
+       unsigned i;
+
+       b += bytes;
+
+       for(i = 0; i < bytes; i++) {
+               *(--b) = (FLAC__byte)(val & 0xff);
+               val >>= 8;
+       }
+}
+
+FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
+{
+       FLAC__uint32 ret = 0;
+       unsigned i;
+
+       for(i = 0; i < bytes; i++)
+               ret = (ret << 8) | (FLAC__uint32)(*b++);
+
+       return ret;
+}
+
+FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
+{
+       FLAC__uint32 ret = 0;
+       unsigned i;
+
+       b += bytes;
+
+       for(i = 0; i < bytes; i++)
+               ret = (ret << 8) | (FLAC__uint32)(*--b);
+
+       return ret;
+}
+
+FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
+{
+       FLAC__uint64 ret = 0;
+       unsigned i;
+
+       for(i = 0; i < bytes; i++)
+               ret = (ret << 8) | (FLAC__uint64)(*b++);
+
+       return ret;
+}
+
+FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       if(!read_metadata_block_header_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, &iterator->is_last, &iterator->type, &iterator->length)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+               return false;
+       }
+
+       return true;
+}
+
+FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
+{
+       FLAC__ASSERT(0 != iterator);
+       FLAC__ASSERT(0 != iterator->file);
+
+       iterator->status = read_metadata_block_data_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, block);
+
+       return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
+}
+
+FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length)
+{
+       FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
+
+       if(read_cb(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
+               return false;
+
+       *is_last = raw_header[0] & 0x80? true : false;
+       *type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
+       *length = unpack_uint32_(raw_header + 1, 3);
+
+       /* Note that we don't check:
+        *    if(iterator->type >= FLAC__METADATA_TYPE_UNDEFINED)
+        * we just will read in an opaque block
+        */
+
+       return true;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block)
+{
+       switch(block->type) {
+               case FLAC__METADATA_TYPE_STREAMINFO:
+                       return read_metadata_block_data_streaminfo_cb_(handle, read_cb, &block->data.stream_info);
+               case FLAC__METADATA_TYPE_PADDING:
+                       return read_metadata_block_data_padding_cb_(handle, seek_cb, &block->data.padding, block->length);
+               case FLAC__METADATA_TYPE_APPLICATION:
+                       return read_metadata_block_data_application_cb_(handle, read_cb, &block->data.application, block->length);
+               case FLAC__METADATA_TYPE_SEEKTABLE:
+                       return read_metadata_block_data_seektable_cb_(handle, read_cb, &block->data.seek_table, block->length);
+               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                       return read_metadata_block_data_vorbis_comment_cb_(handle, read_cb, seek_cb, &block->data.vorbis_comment, block->length);
+               case FLAC__METADATA_TYPE_CUESHEET:
+                       return read_metadata_block_data_cuesheet_cb_(handle, read_cb, &block->data.cue_sheet);
+               case FLAC__METADATA_TYPE_PICTURE:
+                       return read_metadata_block_data_picture_cb_(handle, read_cb, &block->data.picture);
+               default:
+                       return read_metadata_block_data_unknown_cb_(handle, read_cb, &block->data.unknown, block->length);
+       }
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block)
+{
+       FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
+
+       if(read_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+       b = buffer;
+
+       /* we are using hardcoded numbers for simplicity but we should
+        * probably eventually write a bit-level unpacker and use the
+        * _STREAMINFO_ constants.
+        */
+       block->min_blocksize = unpack_uint32_(b, 2); b += 2;
+       block->max_blocksize = unpack_uint32_(b, 2); b += 2;
+       block->min_framesize = unpack_uint32_(b, 3); b += 3;
+       block->max_framesize = unpack_uint32_(b, 3); b += 3;
+       block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
+       block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
+       block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
+       block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
+       memcpy(block->md5sum, b+8, 16);
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length)
+{
+       (void)block; /* nothing to do; we don't care about reading the padding bytes */
+
+       if(0 != seek_cb(handle, block_length, SEEK_CUR))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length)
+{
+       const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
+
+       if(read_cb(block->id, 1, id_bytes, handle) != id_bytes)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+       if(block_length < id_bytes)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+       block_length -= id_bytes;
+
+       if(block_length == 0) {
+               block->data = 0;
+       }
+       else {
+               if(0 == (block->data = malloc(block_length)))
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+               if(read_cb(block->data, 1, block_length, handle) != block_length)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
+{
+       unsigned i;
+       FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
+
+       FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
+
+       block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
+
+       if(block->num_points == 0)
+               block->points = 0;
+       else if(0 == (block->points = safe_malloc_mul_2op_p(block->num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint))))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       for(i = 0; i < block->num_points; i++) {
+               if(read_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+               /* some MAGIC NUMBERs here */
+               block->points[i].sample_number = unpack_uint64_(buffer, 8);
+               block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
+               block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry, unsigned max_length)
+{
+       const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
+       FLAC__byte buffer[4]; /* magic number is asserted below */
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == sizeof(buffer));
+
+       if(max_length < entry_length_len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA;
+
+       max_length -= entry_length_len;
+       if(read_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
+       if(max_length < entry->length) {
+               entry->length = 0;
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA;
+       } else max_length -= entry->length;
+
+       if(0 != entry->entry)
+               free(entry->entry);
+
+       if(entry->length == 0) {
+               entry->entry = 0;
+       }
+       else {
+               if(0 == (entry->entry = safe_malloc_add_2op_(entry->length, /*+*/1)))
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+               if(read_cb(entry->entry, 1, entry->length, handle) != entry->length)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+               entry->entry[entry->length] = '\0';
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_VorbisComment *block, unsigned block_length)
+{
+       unsigned i;
+       FLAC__Metadata_SimpleIteratorStatus status;
+       const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
+       FLAC__byte buffer[4]; /* magic number is asserted below */
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == sizeof(buffer));
+
+       status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, &(block->vendor_string), block_length);
+       if(block_length >= 4)
+               block_length -= 4;
+       if(status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA)
+               goto skip;
+       else if(status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
+               return status;
+       block_length -= block->vendor_string.length;
+
+       if(block_length < num_comments_len) goto skip; else block_length -= num_comments_len;
+       if(read_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
+
+       if(block->num_comments == 0) {
+               block->comments = 0;
+       }
+       else if(0 == (block->comments = calloc(block->num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
+               block->num_comments = 0;
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+       }
+
+       for(i = 0; i < block->num_comments; i++) {
+               status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, block->comments + i, block_length);
+               if(block_length >= 4) block_length -= 4;
+               if(status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA) {
+                       block->num_comments = i;
+                       goto skip;
+               }
+               else if(status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) return status;
+               block_length -= block->comments[i].length;
+       }
+
+  skip:
+       if(block_length > 0) {
+               /* bad metadata */
+               if(0 != seek_cb(handle, block_length, SEEK_CUR))
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track)
+{
+       unsigned i, len;
+       FLAC__byte buffer[32]; /* asserted below that this is big enough */
+
+       FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       track->offset = unpack_uint64_(buffer, len);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       track->number = (FLAC__byte)unpack_uint32_(buffer, len);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
+       if(read_cb(track->isrc, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+       FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
+       len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN == 1);
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN == 1);
+       track->type = buffer[0] >> 7;
+       track->pre_emphasis = (buffer[0] >> 6) & 1;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       track->num_indices = (FLAC__byte)unpack_uint32_(buffer, len);
+
+       if(track->num_indices == 0) {
+               track->indices = 0;
+       }
+       else if(0 == (track->indices = calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index))))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       for(i = 0; i < track->num_indices; i++) {
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
+               if(read_cb(buffer, 1, len, handle) != len)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+               track->indices[i].offset = unpack_uint64_(buffer, len);
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
+               if(read_cb(buffer, 1, len, handle) != len)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+               track->indices[i].number = (FLAC__byte)unpack_uint32_(buffer, len);
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
+               if(read_cb(buffer, 1, len, handle) != len)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block)
+{
+       unsigned i, len;
+       FLAC__Metadata_SimpleIteratorStatus status;
+       FLAC__byte buffer[1024]; /* MSVC needs a constant expression so we put a magic number and assert */
+
+       FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)/8 <= sizeof(buffer));
+       FLAC__ASSERT(sizeof(FLAC__uint64) <= sizeof(buffer));
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
+       if(read_cb(block->media_catalog_number, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->lead_in = unpack_uint64_(buffer, len);
+
+       FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
+       len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->is_cd = buffer[0]&0x80? true : false;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->num_tracks = unpack_uint32_(buffer, len);
+
+       if(block->num_tracks == 0) {
+               block->tracks = 0;
+       }
+       else if(0 == (block->tracks = calloc(block->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track))))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       for(i = 0; i < block->num_tracks; i++) {
+               if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_cuesheet_track_cb_(handle, read_cb, block->tracks + i)))
+                       return status;
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__byte **data, FLAC__uint32 *length, FLAC__uint32 length_len)
+{
+       FLAC__byte buffer[sizeof(FLAC__uint32)];
+
+       FLAC__ASSERT(0 != data);
+       FLAC__ASSERT(length_len%8 == 0);
+
+       length_len /= 8; /* convert to bytes */
+
+       FLAC__ASSERT(sizeof(buffer) >= length_len);
+
+       if(read_cb(buffer, 1, length_len, handle) != length_len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       *length = unpack_uint32_(buffer, length_len);
+
+       if(0 != *data)
+               free(*data);
+
+       if(0 == (*data = safe_malloc_add_2op_(*length, /*+*/1)))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       if(*length > 0) {
+               if(read_cb(*data, 1, *length, handle) != *length)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       }
+
+       (*data)[*length] = '\0';
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block)
+{
+       FLAC__Metadata_SimpleIteratorStatus status;
+       FLAC__byte buffer[4]; /* asserted below that this is big enough */
+       FLAC__uint32 len;
+
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_TYPE_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->type = (FLAC__StreamMetadata_Picture_Type)unpack_uint32_(buffer, len);
+
+       if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, (FLAC__byte**)(&(block->mime_type)), &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
+               return status;
+
+       if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->description), &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
+               return status;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->width = unpack_uint32_(buffer, len);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->height = unpack_uint32_(buffer, len);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->depth = unpack_uint32_(buffer, len);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_COLORS_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN / 8;
+       if(read_cb(buffer, 1, len, handle) != len)
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       block->colors = unpack_uint32_(buffer, len);
+
+       /* for convenience we use read_metadata_block_data_picture_cstring_cb_() even though it adds an extra terminating NUL we don't use */
+       if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->data), &(block->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
+               return status;
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length)
+{
+       if(block_length == 0) {
+               block->data = 0;
+       }
+       else {
+               if(0 == (block->data = malloc(block_length)))
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+               if(read_cb(block->data, 1, block_length, handle) != block_length)
+                       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+       }
+
+       return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+}
+
+FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
+{
+       FLAC__ASSERT(0 != file);
+       FLAC__ASSERT(0 != status);
+
+       if(!write_metadata_block_header_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+               return false;
+       }
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
+{
+       FLAC__ASSERT(0 != file);
+       FLAC__ASSERT(0 != status);
+
+       if (write_metadata_block_data_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
+               return true;
+       }
+       else {
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+               return false;
+       }
+}
+
+FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
+{
+       FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
+
+       FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
+       /* double protection */
+       if(block->length >= (1u << FLAC__STREAM_METADATA_LENGTH_LEN))
+               return false;
+
+       buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
+       pack_uint32_(block->length, buffer + 1, 3);
+
+       if(write_cb(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
+{
+       FLAC__ASSERT(0 != block);
+
+       switch(block->type) {
+               case FLAC__METADATA_TYPE_STREAMINFO:
+                       return write_metadata_block_data_streaminfo_cb_(handle, write_cb, &block->data.stream_info);
+               case FLAC__METADATA_TYPE_PADDING:
+                       return write_metadata_block_data_padding_cb_(handle, write_cb, &block->data.padding, block->length);
+               case FLAC__METADATA_TYPE_APPLICATION:
+                       return write_metadata_block_data_application_cb_(handle, write_cb, &block->data.application, block->length);
+               case FLAC__METADATA_TYPE_SEEKTABLE:
+                       return write_metadata_block_data_seektable_cb_(handle, write_cb, &block->data.seek_table);
+               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                       return write_metadata_block_data_vorbis_comment_cb_(handle, write_cb, &block->data.vorbis_comment);
+               case FLAC__METADATA_TYPE_CUESHEET:
+                       return write_metadata_block_data_cuesheet_cb_(handle, write_cb, &block->data.cue_sheet);
+               case FLAC__METADATA_TYPE_PICTURE:
+                       return write_metadata_block_data_picture_cb_(handle, write_cb, &block->data.picture);
+               default:
+                       return write_metadata_block_data_unknown_cb_(handle, write_cb, &block->data.unknown, block->length);
+       }
+}
+
+FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block)
+{
+       FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
+       const unsigned channels1 = block->channels - 1;
+       const unsigned bps1 = block->bits_per_sample - 1;
+
+       /* we are using hardcoded numbers for simplicity but we should
+        * probably eventually write a bit-level packer and use the
+        * _STREAMINFO_ constants.
+        */
+       pack_uint32_(block->min_blocksize, buffer, 2);
+       pack_uint32_(block->max_blocksize, buffer+2, 2);
+       pack_uint32_(block->min_framesize, buffer+4, 3);
+       pack_uint32_(block->max_framesize, buffer+7, 3);
+       buffer[10] = (block->sample_rate >> 12) & 0xff;
+       buffer[11] = (block->sample_rate >> 4) & 0xff;
+       buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
+       buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
+       pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
+       memcpy(buffer+18, block->md5sum, 16);
+
+       if(write_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
+{
+       unsigned i, n = block_length;
+       FLAC__byte buffer[1024];
+
+       (void)block;
+
+       memset(buffer, 0, 1024);
+
+       for(i = 0; i < n/1024; i++)
+               if(write_cb(buffer, 1, 1024, handle) != 1024)
+                       return false;
+
+       n %= 1024;
+
+       if(write_cb(buffer, 1, n, handle) != n)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length)
+{
+       const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
+
+       if(write_cb(block->id, 1, id_bytes, handle) != id_bytes)
+               return false;
+
+       block_length -= id_bytes;
+
+       if(write_cb(block->data, 1, block_length, handle) != block_length)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block)
+{
+       unsigned i;
+       FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
+
+       for(i = 0; i < block->num_points; i++) {
+               /* some MAGIC NUMBERs here */
+               pack_uint64_(block->points[i].sample_number, buffer, 8);
+               pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
+               pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
+               if(write_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
+                       return false;
+       }
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block)
+{
+       unsigned i;
+       const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
+       const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
+       FLAC__byte buffer[4]; /* magic number is asserted below */
+
+       FLAC__ASSERT(flac_max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == sizeof(buffer));
+
+       pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
+       if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
+               return false;
+       if(write_cb(block->vendor_string.entry, 1, block->vendor_string.length, handle) != block->vendor_string.length)
+               return false;
+
+       pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
+       if(write_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
+               return false;
+
+       for(i = 0; i < block->num_comments; i++) {
+               pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
+               if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
+                       return false;
+               if(write_cb(block->comments[i].entry, 1, block->comments[i].length, handle) != block->comments[i].length)
+                       return false;
+       }
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block)
+{
+       unsigned i, j, len;
+       FLAC__byte buffer[1024]; /* asserted below that this is big enough */
+
+       FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
+       if(write_cb(block->media_catalog_number, 1, len, handle) != len)
+               return false;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
+       pack_uint64_(block->lead_in, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
+       len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
+       memset(buffer, 0, len);
+       if(block->is_cd)
+               buffer[0] |= 0x80;
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
+       len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
+       pack_uint32_(block->num_tracks, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       for(i = 0; i < block->num_tracks; i++) {
+               FLAC__StreamMetadata_CueSheet_Track *track = block->tracks + i;
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
+               pack_uint64_(track->offset, buffer, len);
+               if(write_cb(buffer, 1, len, handle) != len)
+                       return false;
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
+               pack_uint32_(track->number, buffer, len);
+               if(write_cb(buffer, 1, len, handle) != len)
+                       return false;
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
+               if(write_cb(track->isrc, 1, len, handle) != len)
+                       return false;
+
+               FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
+               len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
+               memset(buffer, 0, len);
+               buffer[0] = (track->type << 7) | (track->pre_emphasis << 6);
+               if(write_cb(buffer, 1, len, handle) != len)
+                       return false;
+
+               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
+               len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
+               pack_uint32_(track->num_indices, buffer, len);
+               if(write_cb(buffer, 1, len, handle) != len)
+                       return false;
+
+               for(j = 0; j < track->num_indices; j++) {
+                       FLAC__StreamMetadata_CueSheet_Index *indx = track->indices + j;
+
+                       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
+                       len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
+                       pack_uint64_(indx->offset, buffer, len);
+                       if(write_cb(buffer, 1, len, handle) != len)
+                               return false;
+
+                       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
+                       len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
+                       pack_uint32_(indx->number, buffer, len);
+                       if(write_cb(buffer, 1, len, handle) != len)
+                               return false;
+
+                       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
+                       len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
+                       memset(buffer, 0, len);
+                       if(write_cb(buffer, 1, len, handle) != len)
+                               return false;
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block)
+{
+       unsigned len;
+       size_t slen;
+       FLAC__byte buffer[4]; /* magic number is asserted below */
+
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_TYPE_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_COLORS_LEN%8);
+       FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN%8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
+       FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8);
+
+       len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8;
+       pack_uint32_(block->type, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8;
+       slen = strlen(block->mime_type);
+       pack_uint32_(slen, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+       if(write_cb(block->mime_type, 1, slen, handle) != slen)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8;
+       slen = strlen((const char *)block->description);
+       pack_uint32_(slen, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+       if(write_cb(block->description, 1, slen, handle) != slen)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8;
+       pack_uint32_(block->width, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8;
+       pack_uint32_(block->height, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8;
+       pack_uint32_(block->depth, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8;
+       pack_uint32_(block->colors, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+
+       len = FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8;
+       pack_uint32_(block->data_length, buffer, len);
+       if(write_cb(buffer, 1, len, handle) != len)
+               return false;
+       if(write_cb(block->data, 1, block->data_length, handle) != block->data_length)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length)
+{
+       if(write_cb(block->data, 1, block_length, handle) != block_length)
+               return false;
+
+       return true;
+}
+
+FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
+{
+       if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
+               return false;
+
+       if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
+               return false;
+
+       if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       return read_metadata_block_header_(iterator);
+}
+
+FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
+{
+       FLAC__StreamMetadata *padding;
+
+       if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       block->is_last = false;
+
+       if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
+               return false;
+
+       if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
+               return false;
+
+       if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
+               return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+
+       padding->is_last = padding_is_last;
+       padding->length = padding_length;
+
+       if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
+               FLAC__metadata_object_delete(padding);
+               return false;
+       }
+
+       if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
+               FLAC__metadata_object_delete(padding);
+               return false;
+       }
+
+       FLAC__metadata_object_delete(padding);
+
+       if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       return read_metadata_block_header_(iterator);
+}
+
+FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
+{
+       FILE *tempfile = NULL;
+       char *tempfilename = NULL;
+       int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
+       FLAC__off_t fixup_is_last_flag_offset = -1;
+
+       FLAC__ASSERT(0 != block || append == false);
+
+       if(iterator->is_last) {
+               if(append) {
+                       fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
+                       fixup_is_last_flag_offset = iterator->offset[iterator->depth];
+               }
+               else if(0 == block) {
+                       simple_iterator_push_(iterator);
+                       if(!FLAC__metadata_simple_iterator_prev(iterator)) {
+                               (void)simple_iterator_pop_(iterator);
+                               return false;
+                       }
+                       fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
+                       fixup_is_last_flag_offset = iterator->offset[iterator->depth];
+                       if(!simple_iterator_pop_(iterator))
+                               return false;
+               }
+       }
+
+       if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
+               return false;
+
+       if(0 != block) {
+               if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
+                       cleanup_tempfile_(&tempfile, &tempfilename);
+                       return false;
+               }
+
+               if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
+                       cleanup_tempfile_(&tempfile, &tempfilename);
+                       return false;
+               }
+       }
+
+       if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
+               return false;
+
+       if(append)
+               return FLAC__metadata_simple_iterator_next(iterator);
+
+       return true;
+}
+
+void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
+       iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
+       iterator->depth++;
+}
+
+FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
+{
+       FLAC__ASSERT(iterator->depth > 0);
+       iterator->depth--;
+       if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+
+       return read_metadata_block_header_(iterator);
+}
+
+/* return meanings:
+ * 0: ok
+ * 1: read error
+ * 2: seek error
+ * 3: not a FLAC file
+ */
+unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb)
+{
+       FLAC__byte buffer[4];
+       size_t n;
+       unsigned i;
+
+       FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == sizeof(buffer));
+
+       /* skip any id3v2 tag */
+       errno = 0;
+       n = read_cb(buffer, 1, 4, handle);
+       if(errno)
+               return 1;
+       else if(n != 4)
+               return 3;
+       else if(0 == memcmp(buffer, "ID3", 3)) {
+               unsigned tag_length = 0;
+
+               /* skip to the tag length */
+               if(seek_cb(handle, 2, SEEK_CUR) < 0)
+                       return 2;
+
+               /* read the length */
+               for(i = 0; i < 4; i++) {
+                       if(read_cb(buffer, 1, 1, handle) < 1 || buffer[0] & 0x80)
+                               return 1;
+                       tag_length <<= 7;
+                       tag_length |= (buffer[0] & 0x7f);
+               }
+
+               /* skip the rest of the tag */
+               if(seek_cb(handle, tag_length, SEEK_CUR) < 0)
+                       return 2;
+
+               /* read the stream sync code */
+               errno = 0;
+               n = read_cb(buffer, 1, 4, handle);
+               if(errno)
+                       return 1;
+               else if(n != 4)
+                       return 3;
+       }
+
+       /* check for the fLaC signature */
+       if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
+               return 0;
+       else
+               return 3;
+}
+
+unsigned seek_to_first_metadata_block_(FILE *f)
+{
+       return seek_to_first_metadata_block_cb_((FLAC__IOHandle)f, (FLAC__IOCallback_Read)fread, fseek_wrapper_);
+}
+
+FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
+{
+       const FLAC__off_t offset_end = append? iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length : iterator->offset[iterator->depth];
+
+       if(0 != fseeko(iterator->file, 0, SEEK_SET)) {
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+       if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               return false;
+       }
+       if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               return false;
+       }
+
+       return true;
+}
+
+FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, FLAC__off_t fixup_is_last_flag_offset, FLAC__bool backup)
+{
+       FLAC__off_t save_offset = iterator->offset[iterator->depth];
+       FLAC__ASSERT(0 != *tempfile);
+
+       if(0 != fseeko(iterator->file, save_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length, SEEK_SET)) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+               return false;
+       }
+       if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               return false;
+       }
+
+       if(fixup_is_last_code != 0) {
+               /*
+                * if code == 1, it means a block was appended to the end so
+                *   we have to clear the is_last flag of the previous block
+                * if code == -1, it means the last block was deleted so
+                *   we have to set the is_last flag of the previous block
+                */
+               /* MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
+               FLAC__byte x;
+               if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
+                       cleanup_tempfile_(tempfile, tempfilename);
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+                       return false;
+               }
+               if(fread(&x, 1, 1, *tempfile) != 1) {
+                       cleanup_tempfile_(tempfile, tempfilename);
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               }
+               if(fixup_is_last_code > 0) {
+                       FLAC__ASSERT(x & 0x80);
+                       x &= 0x7f;
+               }
+               else {
+                       FLAC__ASSERT(!(x & 0x80));
+                       x |= 0x80;
+               }
+               if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
+                       cleanup_tempfile_(tempfile, tempfilename);
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
+                       return false;
+               }
+               if(local__fwrite(&x, 1, 1, *tempfile) != 1) {
+                       cleanup_tempfile_(tempfile, tempfilename);
+                       iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+                       return false;
+               }
+       }
+
+       (void)fclose(iterator->file);
+
+       if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
+               return false;
+
+       if(iterator->has_stats)
+               set_file_stats_(iterator->filename, &iterator->stats);
+
+       if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
+               return false;
+       if(backup) {
+               while(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length < save_offset)
+                       if(!FLAC__metadata_simple_iterator_next(iterator))
+                               return false;
+               return true;
+       }
+       else {
+               /* move the iterator to it's original block faster by faking a push, then doing a pop_ */
+               FLAC__ASSERT(iterator->depth == 0);
+               iterator->offset[0] = save_offset;
+               iterator->depth++;
+               return simple_iterator_pop_(iterator);
+       }
+}
+
+FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       FLAC__byte buffer[8192];
+       size_t n;
+
+       FLAC__ASSERT(bytes >= 0);
+       while(bytes > 0) {
+               n = flac_min(sizeof(buffer), (size_t)bytes);
+               if(fread(buffer, 1, n, file) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               }
+               if(local__fwrite(buffer, 1, n, tempfile) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+                       return false;
+               }
+               bytes -= n;
+       }
+
+       return true;
+}
+
+FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       FLAC__byte buffer[8192];
+       size_t n;
+
+       FLAC__ASSERT(bytes >= 0);
+       while(bytes > 0) {
+               n = flac_min(sizeof(buffer), (size_t)bytes);
+               if(read_cb(buffer, 1, n, handle) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               }
+               if(temp_write_cb(buffer, 1, n, temp_handle) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+                       return false;
+               }
+               bytes -= n;
+       }
+
+       return true;
+}
+
+FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       FLAC__byte buffer[8192];
+       size_t n;
+
+       while(!feof(file)) {
+               n = fread(buffer, 1, sizeof(buffer), file);
+               if(n == 0 && !feof(file)) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               }
+               if(n > 0 && local__fwrite(buffer, 1, n, tempfile) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       FLAC__byte buffer[8192];
+       size_t n;
+
+       while(!eof_cb(handle)) {
+               n = read_cb(buffer, 1, sizeof(buffer), handle);
+               if(n == 0 && !eof_cb(handle)) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
+                       return false;
+               }
+               if(n > 0 && temp_write_cb(buffer, 1, n, temp_handle) != n) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+static int
+local_snprintf(char *str, size_t size, const char *fmt, ...)
+{
+       va_list va;
+       int rc;
+
+#if defined _MSC_VER
+       if (size == 0)
+               return 1024;
+#endif
+
+       va_start (va, fmt);
+
+#if defined _MSC_VER
+       rc = vsnprintf_s (str, size, _TRUNCATE, fmt, va);
+       if (rc < 0)
+               rc = size - 1;
+#elif defined __MINGW32__
+       rc = __mingw_vsnprintf (str, size, fmt, va);
+#else
+       rc = vsnprintf (str, size, fmt, va);
+#endif
+       va_end (va);
+
+       return rc;
+}
+
+FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       static const char *tempfile_suffix = ".metadata_edit";
+       if(0 == tempfile_path_prefix) {
+               size_t dest_len = strlen(filename) + strlen(tempfile_suffix) + 1;
+               if(0 == (*tempfilename = safe_malloc_(dest_len))) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               local_snprintf(*tempfilename, dest_len, "%s%s", filename, tempfile_suffix);
+       }
+       else {
+               const char *p = strrchr(filename, '/');
+               size_t dest_len;
+               if(0 == p)
+                       p = filename;
+               else
+                       p++;
+
+               dest_len = strlen(tempfile_path_prefix) + strlen(p) + strlen(tempfile_suffix) + 2;
+
+               if(0 == (*tempfilename = safe_malloc_(dest_len))) {
+                       *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               local_snprintf(*tempfilename, dest_len, "%s/%s%s", tempfile_path_prefix, p, tempfile_suffix);
+       }
+
+       if(0 == (*tempfile = flac_fopen(*tempfilename, "w+b"))) {
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
+               return false;
+       }
+
+       return true;
+}
+
+FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
+{
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != tempfile);
+       FLAC__ASSERT(0 != *tempfile);
+       FLAC__ASSERT(0 != tempfilename);
+       FLAC__ASSERT(0 != *tempfilename);
+       FLAC__ASSERT(0 != status);
+
+       (void)fclose(*tempfile);
+       *tempfile = 0;
+
+#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__
+       /* on some flavors of windows, flac_rename() will fail if the destination already exists */
+       if(flac_unlink(filename) < 0) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
+               return false;
+       }
+#endif
+
+       /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just flac_rename(): */
+       if(0 != flac_rename(*tempfilename, filename)) {
+               cleanup_tempfile_(tempfile, tempfilename);
+               *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
+               return false;
+       }
+
+       cleanup_tempfile_(tempfile, tempfilename);
+
+       return true;
+}
+
+void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
+{
+       if(0 != *tempfile) {
+               (void)fclose(*tempfile);
+               *tempfile = 0;
+       }
+
+       if(0 != *tempfilename) {
+               (void)flac_unlink(*tempfilename);
+               free(*tempfilename);
+               *tempfilename = 0;
+       }
+}
+
+FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats)
+{
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != stats);
+       return (0 == flac_stat(filename, stats));
+}
+
+void set_file_stats_(const char *filename, struct flac_stat_s *stats)
+{
+       struct utimbuf srctime;
+
+       FLAC__ASSERT(0 != filename);
+       FLAC__ASSERT(0 != stats);
+
+       srctime.actime = stats->st_atime;
+       srctime.modtime = stats->st_mtime;
+       (void)flac_chmod(filename, stats->st_mode);
+       (void)flac_utime(filename, &srctime);
+#if !defined _MSC_VER && !defined __BORLANDC__ && !defined __MINGW32__
+       FLAC_CHECK_RETURN(chown(filename, stats->st_uid, -1));
+       FLAC_CHECK_RETURN(chown(filename, -1, stats->st_gid));
+#endif
+}
+
+int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence)
+{
+       return fseeko((FILE*)handle, (FLAC__off_t)offset, whence);
+}
+
+FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle)
+{
+       return ftello((FILE*)handle);
+}
+
+FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
+{
+       switch(status) {
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
+                       return FLAC__METADATA_CHAIN_STATUS_OK;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
+                       return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
+                       return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
+                       return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
+                       return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
+                       return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
+                       return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
+               case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
+               default:
+                       return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
+       }
+}
diff --git a/FLAC/src/metadata_object.c b/FLAC/src/metadata_object.c
new file mode 100644 (file)
index 0000000..9cb9501
--- /dev/null
@@ -0,0 +1,1821 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+
+#include "private/metadata.h"
+#include "private/memory.h"
+
+#include "FLAC/assert.h"
+#include "share/alloc.h"
+#include "share/compat.h"
+
+/* Alias the first (in share/alloc.h) to the second (in src/libFLAC/memory.c). */
+#define safe_malloc_mul_2op_ safe_malloc_mul_2op_p
+
+
+/****************************************************************************
+ *
+ * Local routines
+ *
+ ***************************************************************************/
+
+/* copy bytes:
+ *  from = NULL  && bytes = 0
+ *       to <- NULL
+ *  from != NULL && bytes > 0
+ *       to <- copy of from
+ *  else ASSERT
+ * malloc error leaves 'to' unchanged
+ */
+static FLAC__bool copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes)
+{
+       FLAC__ASSERT(to != NULL);
+       if (bytes > 0 && from != NULL) {
+               FLAC__byte *x;
+               if ((x = safe_malloc_(bytes)) == NULL)
+                       return false;
+               memcpy(x, from, bytes);
+               *to = x;
+       }
+       else {
+               *to = 0;
+       }
+       return true;
+}
+
+#if 0 /* UNUSED */
+/* like copy_bytes_(), but free()s the original '*to' if the copy succeeds and the original '*to' is non-NULL */
+static FLAC__bool free_copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes)
+{
+       FLAC__byte *copy;
+       FLAC__ASSERT(to != NULL);
+       if (copy_bytes_(&copy, from, bytes)) {
+               free(*to);
+               *to = copy;
+               return true;
+       }
+       else
+               return false;
+}
+#endif
+
+/* reallocate entry to 1 byte larger and add a terminating NUL */
+/* realloc() failure leaves entry unchanged */
+static FLAC__bool ensure_null_terminated_(FLAC__byte **entry, unsigned length)
+{
+       FLAC__byte *x = safe_realloc_add_2op_(*entry, length, /*+*/1);
+       if (x != NULL) {
+               x[length] = '\0';
+               *entry = x;
+               return true;
+       }
+       else
+               return false;
+}
+
+/* copies the NUL-terminated C-string 'from' to '*to', leaving '*to'
+ * unchanged if malloc fails, free()ing the original '*to' if it
+ * succeeds and the original '*to' was not NULL
+ */
+static FLAC__bool copy_cstring_(char **to, const char *from)
+{
+       char *copy = strdup(from);
+       FLAC__ASSERT(to != NULL);
+       if (copy) {
+               free(*to);
+               *to = copy;
+               return true;
+       }
+       else
+               return false;
+}
+
+static FLAC__bool copy_vcentry_(FLAC__StreamMetadata_VorbisComment_Entry *to, const FLAC__StreamMetadata_VorbisComment_Entry *from)
+{
+       to->length = from->length;
+       if (from->entry == 0) {
+               FLAC__ASSERT(from->length == 0);
+               to->entry = 0;
+       }
+       else {
+               FLAC__byte *x;
+               FLAC__ASSERT(from->length > 0);
+               if ((x = safe_malloc_add_2op_(from->length, /*+*/1)) == NULL)
+                       return false;
+               memcpy(x, from->entry, from->length);
+               x[from->length] = '\0';
+               to->entry = x;
+       }
+       return true;
+}
+
+static FLAC__bool copy_track_(FLAC__StreamMetadata_CueSheet_Track *to, const FLAC__StreamMetadata_CueSheet_Track *from)
+{
+       memcpy(to, from, sizeof(FLAC__StreamMetadata_CueSheet_Track));
+       if (from->indices == 0) {
+               FLAC__ASSERT(from->num_indices == 0);
+       }
+       else {
+               FLAC__StreamMetadata_CueSheet_Index *x;
+               FLAC__ASSERT(from->num_indices > 0);
+               if ((x = safe_malloc_mul_2op_p(from->num_indices, /*times*/sizeof(FLAC__StreamMetadata_CueSheet_Index))) == NULL)
+                       return false;
+               memcpy(x, from->indices, from->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index));
+               to->indices = x;
+       }
+       return true;
+}
+
+static void seektable_calculate_length_(FLAC__StreamMetadata *object)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       object->length = object->data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
+}
+
+static FLAC__StreamMetadata_SeekPoint *seekpoint_array_new_(unsigned num_points)
+{
+       FLAC__StreamMetadata_SeekPoint *object_array;
+
+       FLAC__ASSERT(num_points > 0);
+
+       object_array = safe_malloc_mul_2op_p(num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint));
+
+       if (object_array != NULL) {
+               unsigned i;
+               for (i = 0; i < num_points; i++) {
+                       object_array[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
+                       object_array[i].stream_offset = 0;
+                       object_array[i].frame_samples = 0;
+               }
+       }
+
+       return object_array;
+}
+
+static void vorbiscomment_calculate_length_(FLAC__StreamMetadata *object)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+       object->length = (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN) / 8;
+       object->length += object->data.vorbis_comment.vendor_string.length;
+       object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8;
+       for (i = 0; i < object->data.vorbis_comment.num_comments; i++) {
+               object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8);
+               object->length += object->data.vorbis_comment.comments[i].length;
+       }
+}
+
+static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_new_(unsigned num_comments)
+{
+       FLAC__ASSERT(num_comments > 0);
+
+       return safe_calloc_(num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry));
+}
+
+static void vorbiscomment_entry_array_delete_(FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object_array != NULL && num_comments > 0);
+
+       for (i = 0; i < num_comments; i++)
+               free(object_array[i].entry);
+
+       free(object_array);
+}
+
+static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_copy_(const FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments)
+{
+       FLAC__StreamMetadata_VorbisComment_Entry *return_array;
+
+       FLAC__ASSERT(object_array != NULL);
+       FLAC__ASSERT(num_comments > 0);
+
+       return_array = vorbiscomment_entry_array_new_(num_comments);
+
+       if (return_array != NULL) {
+               unsigned i;
+
+               for (i = 0; i < num_comments; i++) {
+                       if (!copy_vcentry_(return_array+i, object_array+i)) {
+                               vorbiscomment_entry_array_delete_(return_array, num_comments);
+                               return 0;
+                       }
+               }
+       }
+
+       return return_array;
+}
+
+static FLAC__bool vorbiscomment_set_entry_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry *dest, const FLAC__StreamMetadata_VorbisComment_Entry *src, FLAC__bool copy)
+{
+       FLAC__byte *save;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(dest != NULL);
+       FLAC__ASSERT(src != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+       FLAC__ASSERT((src->entry != NULL && src->length > 0) || (src->entry == NULL && src->length == 0));
+
+       save = dest->entry;
+
+       if (src->entry != NULL) {
+               if (copy) {
+                       /* do the copy first so that if we fail we leave the dest object untouched */
+                       if (!copy_vcentry_(dest, src))
+                               return false;
+               }
+               else {
+                       /* we have to make sure that the string we're taking over is null-terminated */
+
+                       /*
+                        * Stripping the const from src->entry is OK since we're taking
+                        * ownership of the pointer.  This is a hack around a deficiency
+                        * in the API where the same function is used for 'copy' and
+                        * 'own', but the source entry is a const pointer.  If we were
+                        * precise, the 'own' flavor would be a separate function with a
+                        * non-const source pointer.  But it's not, so we hack away.
+                        */
+                       if (!ensure_null_terminated_((FLAC__byte**)(&src->entry), src->length))
+                               return false;
+                       *dest = *src;
+               }
+       }
+       else {
+               /* the src is null */
+               *dest = *src;
+       }
+
+       free(save);
+
+       vorbiscomment_calculate_length_(object);
+       return true;
+}
+
+static int vorbiscomment_find_entry_from_(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name, unsigned field_name_length)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+       FLAC__ASSERT(field_name != NULL);
+
+       for (i = offset; i < object->data.vorbis_comment.num_comments; i++) {
+               if (FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length))
+                       return (int)i;
+       }
+
+       return -1;
+}
+
+static void cuesheet_calculate_length_(FLAC__StreamMetadata *object)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+
+       object->length = (
+               FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN
+       ) / 8;
+
+       object->length += object->data.cue_sheet.num_tracks * (
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN +
+               FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN
+       ) / 8;
+
+       for (i = 0; i < object->data.cue_sheet.num_tracks; i++) {
+               object->length += object->data.cue_sheet.tracks[i].num_indices * (
+                       FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN +
+                       FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN +
+                       FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN
+               ) / 8;
+       }
+}
+
+static FLAC__StreamMetadata_CueSheet_Index *cuesheet_track_index_array_new_(unsigned num_indices)
+{
+       FLAC__ASSERT(num_indices > 0);
+
+       return safe_calloc_(num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index));
+}
+
+static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_new_(unsigned num_tracks)
+{
+       FLAC__ASSERT(num_tracks > 0);
+
+       return safe_calloc_(num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track));
+}
+
+static void cuesheet_track_array_delete_(FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object_array != NULL && num_tracks > 0);
+
+       for (i = 0; i < num_tracks; i++) {
+               if (object_array[i].indices != 0) {
+                       FLAC__ASSERT(object_array[i].num_indices > 0);
+                       free(object_array[i].indices);
+               }
+       }
+
+       free(object_array);
+}
+
+static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_copy_(const FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks)
+{
+       FLAC__StreamMetadata_CueSheet_Track *return_array;
+
+       FLAC__ASSERT(object_array != NULL);
+       FLAC__ASSERT(num_tracks > 0);
+
+       return_array = cuesheet_track_array_new_(num_tracks);
+
+       if (return_array != NULL) {
+               unsigned i;
+
+               for (i = 0; i < num_tracks; i++) {
+                       if (!copy_track_(return_array+i, object_array+i)) {
+                               cuesheet_track_array_delete_(return_array, num_tracks);
+                               return 0;
+                       }
+               }
+       }
+
+       return return_array;
+}
+
+static FLAC__bool cuesheet_set_track_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_CueSheet_Track *dest, const FLAC__StreamMetadata_CueSheet_Track *src, FLAC__bool copy)
+{
+       FLAC__StreamMetadata_CueSheet_Index *save;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(dest != NULL);
+       FLAC__ASSERT(src != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT((src->indices != NULL && src->num_indices > 0) || (src->indices == NULL && src->num_indices == 0));
+
+       save = dest->indices;
+
+       /* do the copy first so that if we fail we leave the object untouched */
+       if (copy) {
+               if (!copy_track_(dest, src))
+                       return false;
+       }
+       else {
+               *dest = *src;
+       }
+
+       free(save);
+
+       cuesheet_calculate_length_(object);
+       return true;
+}
+
+
+/****************************************************************************
+ *
+ * Metadata object routines
+ *
+ ***************************************************************************/
+
+FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type)
+{
+       FLAC__StreamMetadata *object;
+
+       if (type > FLAC__MAX_METADATA_TYPE)
+               return 0;
+
+       object = calloc(1, sizeof(FLAC__StreamMetadata));
+       if (object != NULL) {
+               object->is_last = false;
+               object->type = type;
+               switch(type) {
+                       case FLAC__METADATA_TYPE_STREAMINFO:
+                               object->length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
+                               break;
+                       case FLAC__METADATA_TYPE_PADDING:
+                               /* calloc() took care of this for us:
+                               object->length = 0;
+                               */
+                               break;
+                       case FLAC__METADATA_TYPE_APPLICATION:
+                               object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
+                               /* calloc() took care of this for us:
+                               object->data.application.data = 0;
+                               */
+                               break;
+                       case FLAC__METADATA_TYPE_SEEKTABLE:
+                               /* calloc() took care of this for us:
+                               object->length = 0;
+                               object->data.seek_table.num_points = 0;
+                               object->data.seek_table.points = 0;
+                               */
+                               break;
+                       case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                               object->data.vorbis_comment.vendor_string.length = (unsigned)strlen(FLAC__VENDOR_STRING);
+                               if (!copy_bytes_(&object->data.vorbis_comment.vendor_string.entry, (const FLAC__byte*)FLAC__VENDOR_STRING, object->data.vorbis_comment.vendor_string.length+1)) {
+                                       free(object);
+                                       return 0;
+                               }
+                               vorbiscomment_calculate_length_(object);
+                               break;
+                       case FLAC__METADATA_TYPE_CUESHEET:
+                               cuesheet_calculate_length_(object);
+                               break;
+                       case FLAC__METADATA_TYPE_PICTURE:
+                               object->length = (
+                                       FLAC__STREAM_METADATA_PICTURE_TYPE_LEN +
+                                       FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* empty mime_type string */
+                                       FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* empty description string */
+                                       FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN +
+                                       FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN +
+                                       FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN +
+                                       FLAC__STREAM_METADATA_PICTURE_COLORS_LEN +
+                                       FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN +
+                                       0 /* no data */
+                               ) / 8;
+                               object->data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER;
+                               object->data.picture.mime_type = 0;
+                               object->data.picture.description = 0;
+                               /* calloc() took care of this for us:
+                               object->data.picture.width = 0;
+                               object->data.picture.height = 0;
+                               object->data.picture.depth = 0;
+                               object->data.picture.colors = 0;
+                               object->data.picture.data_length = 0;
+                               object->data.picture.data = 0;
+                               */
+                               /* now initialize mime_type and description with empty strings to make things easier on the client */
+                               if (!copy_cstring_(&object->data.picture.mime_type, "")) {
+                                       free(object);
+                                       return 0;
+                               }
+                               if (!copy_cstring_((char**)(&object->data.picture.description), "")) {
+                                       free(object->data.picture.mime_type);
+                                       free(object);
+                                       return 0;
+                               }
+                               break;
+                       default:
+                               /* calloc() took care of this for us:
+                               object->length = 0;
+                               object->data.unknown.data = 0;
+                               */
+                               break;
+               }
+       }
+
+       return object;
+}
+
+FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object)
+{
+       FLAC__StreamMetadata *to;
+
+       FLAC__ASSERT(object != NULL);
+
+       if ((to = FLAC__metadata_object_new(object->type)) != NULL) {
+               to->is_last = object->is_last;
+               to->type = object->type;
+               to->length = object->length;
+               switch(to->type) {
+                       case FLAC__METADATA_TYPE_STREAMINFO:
+                               memcpy(&to->data.stream_info, &object->data.stream_info, sizeof(FLAC__StreamMetadata_StreamInfo));
+                               break;
+                       case FLAC__METADATA_TYPE_PADDING:
+                               break;
+                       case FLAC__METADATA_TYPE_APPLICATION:
+                               if (to->length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8) { /* underflow check */
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               memcpy(&to->data.application.id, &object->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8);
+                               if (!copy_bytes_(&to->data.application.data, object->data.application.data, object->length - FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               break;
+                       case FLAC__METADATA_TYPE_SEEKTABLE:
+                               to->data.seek_table.num_points = object->data.seek_table.num_points;
+                               if (to->data.seek_table.num_points > UINT32_MAX / sizeof(FLAC__StreamMetadata_SeekPoint)) { /* overflow check */
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               if (!copy_bytes_((FLAC__byte**)&to->data.seek_table.points, (FLAC__byte*)object->data.seek_table.points, object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint))) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               break;
+                       case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                               if (to->data.vorbis_comment.vendor_string.entry != NULL) {
+                                       free(to->data.vorbis_comment.vendor_string.entry);
+                                       to->data.vorbis_comment.vendor_string.entry = 0;
+                               }
+                               if (!copy_vcentry_(&to->data.vorbis_comment.vendor_string, &object->data.vorbis_comment.vendor_string)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               if (object->data.vorbis_comment.num_comments == 0) {
+                                       to->data.vorbis_comment.comments = 0;
+                               }
+                               else {
+                                       to->data.vorbis_comment.comments = vorbiscomment_entry_array_copy_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments);
+                                       if (to->data.vorbis_comment.comments == NULL) {
+                                               to->data.vorbis_comment.num_comments = 0;
+                                               FLAC__metadata_object_delete(to);
+                                               return 0;
+                                       }
+                               }
+                               to->data.vorbis_comment.num_comments = object->data.vorbis_comment.num_comments;
+                               break;
+                       case FLAC__METADATA_TYPE_CUESHEET:
+                               memcpy(&to->data.cue_sheet, &object->data.cue_sheet, sizeof(FLAC__StreamMetadata_CueSheet));
+                               if (object->data.cue_sheet.num_tracks == 0) {
+                                       FLAC__ASSERT(object->data.cue_sheet.tracks == NULL);
+                               }
+                               else {
+                                       FLAC__ASSERT(object->data.cue_sheet.tracks != 0);
+                                       to->data.cue_sheet.tracks = cuesheet_track_array_copy_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks);
+                                       if (to->data.cue_sheet.tracks == NULL) {
+                                               FLAC__metadata_object_delete(to);
+                                               return 0;
+                                       }
+                               }
+                               break;
+                       case FLAC__METADATA_TYPE_PICTURE:
+                               to->data.picture.type = object->data.picture.type;
+                               if (!copy_cstring_(&to->data.picture.mime_type, object->data.picture.mime_type)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               if (!copy_cstring_((char**)(&to->data.picture.description), (const char*)object->data.picture.description)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               to->data.picture.width = object->data.picture.width;
+                               to->data.picture.height = object->data.picture.height;
+                               to->data.picture.depth = object->data.picture.depth;
+                               to->data.picture.colors = object->data.picture.colors;
+                               to->data.picture.data_length = object->data.picture.data_length;
+                               if (!copy_bytes_((&to->data.picture.data), object->data.picture.data, object->data.picture.data_length)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               break;
+                       default:
+                               if (!copy_bytes_(&to->data.unknown.data, object->data.unknown.data, object->length)) {
+                                       FLAC__metadata_object_delete(to);
+                                       return 0;
+                               }
+                               break;
+               }
+       }
+
+       return to;
+}
+
+void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object)
+{
+       FLAC__ASSERT(object != NULL);
+
+       switch(object->type) {
+               case FLAC__METADATA_TYPE_STREAMINFO:
+               case FLAC__METADATA_TYPE_PADDING:
+                       break;
+               case FLAC__METADATA_TYPE_APPLICATION:
+                       if (object->data.application.data != NULL) {
+                               free(object->data.application.data);
+                               object->data.application.data = NULL;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_SEEKTABLE:
+                       if (object->data.seek_table.points != NULL) {
+                               free(object->data.seek_table.points);
+                               object->data.seek_table.points = NULL;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                       if (object->data.vorbis_comment.vendor_string.entry != NULL) {
+                               free(object->data.vorbis_comment.vendor_string.entry);
+                               object->data.vorbis_comment.vendor_string.entry = 0;
+                       }
+                       if (object->data.vorbis_comment.comments != NULL) {
+                               FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0);
+                               vorbiscomment_entry_array_delete_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments);
+                               object->data.vorbis_comment.comments = NULL;
+                               object->data.vorbis_comment.num_comments = 0;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_CUESHEET:
+                       if (object->data.cue_sheet.tracks != NULL) {
+                               FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0);
+                               cuesheet_track_array_delete_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks);
+                               object->data.cue_sheet.tracks = NULL;
+                               object->data.cue_sheet.num_tracks = 0;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_PICTURE:
+                       if (object->data.picture.mime_type != NULL) {
+                               free(object->data.picture.mime_type);
+                               object->data.picture.mime_type = NULL;
+                       }
+                       if (object->data.picture.description != NULL) {
+                               free(object->data.picture.description);
+                               object->data.picture.description = NULL;
+                       }
+                       if (object->data.picture.data != NULL) {
+                               free(object->data.picture.data);
+                               object->data.picture.data = NULL;
+                       }
+                       break;
+               default:
+                       if (object->data.unknown.data != NULL) {
+                               free(object->data.unknown.data);
+                               object->data.unknown.data = NULL;
+                       }
+                       break;
+       }
+}
+
+FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object)
+{
+       FLAC__metadata_object_delete_data(object);
+       free(object);
+}
+
+static FLAC__bool compare_block_data_streaminfo_(const FLAC__StreamMetadata_StreamInfo *block1, const FLAC__StreamMetadata_StreamInfo *block2)
+{
+       if (block1->min_blocksize != block2->min_blocksize)
+               return false;
+       if (block1->max_blocksize != block2->max_blocksize)
+               return false;
+       if (block1->min_framesize != block2->min_framesize)
+               return false;
+       if (block1->max_framesize != block2->max_framesize)
+               return false;
+       if (block1->sample_rate != block2->sample_rate)
+               return false;
+       if (block1->channels != block2->channels)
+               return false;
+       if (block1->bits_per_sample != block2->bits_per_sample)
+               return false;
+       if (block1->total_samples != block2->total_samples)
+               return false;
+       if (memcmp(block1->md5sum, block2->md5sum, 16) != 0)
+               return false;
+       return true;
+}
+
+static FLAC__bool compare_block_data_application_(const FLAC__StreamMetadata_Application *block1, const FLAC__StreamMetadata_Application *block2, unsigned block_length)
+{
+       FLAC__ASSERT(block1 != NULL);
+       FLAC__ASSERT(block2 != NULL);
+       FLAC__ASSERT(block_length >= sizeof(block1->id));
+
+       if (memcmp(block1->id, block2->id, sizeof(block1->id)) != 0)
+               return false;
+       if (block1->data != NULL && block2->data != NULL)
+               return memcmp(block1->data, block2->data, block_length - sizeof(block1->id)) == 0;
+       else
+               return block1->data == block2->data;
+}
+
+static FLAC__bool compare_block_data_seektable_(const FLAC__StreamMetadata_SeekTable *block1, const FLAC__StreamMetadata_SeekTable *block2)
+{
+       unsigned i;
+
+       FLAC__ASSERT(block1 != NULL);
+       FLAC__ASSERT(block2 != NULL);
+
+       if (block1->num_points != block2->num_points)
+               return false;
+
+       if (block1->points != NULL && block2->points != NULL) {
+               for (i = 0; i < block1->num_points; i++) {
+                       if (block1->points[i].sample_number != block2->points[i].sample_number)
+                               return false;
+                       if (block1->points[i].stream_offset != block2->points[i].stream_offset)
+                               return false;
+                       if (block1->points[i].frame_samples != block2->points[i].frame_samples)
+                               return false;
+               }
+               return true;
+       }
+       else
+               return block1->points == block2->points;
+}
+
+static FLAC__bool compare_block_data_vorbiscomment_(const FLAC__StreamMetadata_VorbisComment *block1, const FLAC__StreamMetadata_VorbisComment *block2)
+{
+       unsigned i;
+
+       if (block1->vendor_string.length != block2->vendor_string.length)
+               return false;
+
+       if (block1->vendor_string.entry != NULL && block2->vendor_string.entry != NULL) {
+               if (memcmp(block1->vendor_string.entry, block2->vendor_string.entry, block1->vendor_string.length) != 0)
+                       return false;
+       }
+       else if (block1->vendor_string.entry != block2->vendor_string.entry)
+               return false;
+
+       if (block1->num_comments != block2->num_comments)
+               return false;
+
+       for (i = 0; i < block1->num_comments; i++) {
+               if (block1->comments[i].entry != NULL && block2->comments[i].entry != NULL) {
+                       if (memcmp(block1->comments[i].entry, block2->comments[i].entry, block1->comments[i].length) != 0)
+                               return false;
+               }
+               else if (block1->comments[i].entry != block2->comments[i].entry)
+                       return false;
+       }
+       return true;
+}
+
+static FLAC__bool compare_block_data_cuesheet_(const FLAC__StreamMetadata_CueSheet *block1, const FLAC__StreamMetadata_CueSheet *block2)
+{
+       unsigned i, j;
+
+       if (strcmp(block1->media_catalog_number, block2->media_catalog_number) != 0)
+               return false;
+
+       if (block1->lead_in != block2->lead_in)
+               return false;
+
+       if (block1->is_cd != block2->is_cd)
+               return false;
+
+       if (block1->num_tracks != block2->num_tracks)
+               return false;
+
+       if (block1->tracks != NULL && block2->tracks != NULL) {
+               FLAC__ASSERT(block1->num_tracks > 0);
+               for (i = 0; i < block1->num_tracks; i++) {
+                       if (block1->tracks[i].offset != block2->tracks[i].offset)
+                               return false;
+                       if (block1->tracks[i].number != block2->tracks[i].number)
+                               return false;
+                       if (memcmp(block1->tracks[i].isrc, block2->tracks[i].isrc, sizeof(block1->tracks[i].isrc)) != 0)
+                               return false;
+                       if (block1->tracks[i].type != block2->tracks[i].type)
+                               return false;
+                       if (block1->tracks[i].pre_emphasis != block2->tracks[i].pre_emphasis)
+                               return false;
+                       if (block1->tracks[i].num_indices != block2->tracks[i].num_indices)
+                               return false;
+                       if (block1->tracks[i].indices != NULL && block2->tracks[i].indices != NULL) {
+                               FLAC__ASSERT(block1->tracks[i].num_indices > 0);
+                               for (j = 0; j < block1->tracks[i].num_indices; j++) {
+                                       if (block1->tracks[i].indices[j].offset != block2->tracks[i].indices[j].offset)
+                                               return false;
+                                       if (block1->tracks[i].indices[j].number != block2->tracks[i].indices[j].number)
+                                               return false;
+                               }
+                       }
+                       else if (block1->tracks[i].indices != block2->tracks[i].indices)
+                               return false;
+               }
+       }
+       else if (block1->tracks != block2->tracks)
+               return false;
+       return true;
+}
+
+static FLAC__bool compare_block_data_picture_(const FLAC__StreamMetadata_Picture *block1, const FLAC__StreamMetadata_Picture *block2)
+{
+       if (block1->type != block2->type)
+               return false;
+       if (block1->mime_type != block2->mime_type && (block1->mime_type == 0 || block2->mime_type == 0 || strcmp(block1->mime_type, block2->mime_type)))
+               return false;
+       if (block1->description != block2->description && (block1->description == 0 || block2->description == 0 || strcmp((const char *)block1->description, (const char *)block2->description)))
+               return false;
+       if (block1->width != block2->width)
+               return false;
+       if (block1->height != block2->height)
+               return false;
+       if (block1->depth != block2->depth)
+               return false;
+       if (block1->colors != block2->colors)
+               return false;
+       if (block1->data_length != block2->data_length)
+               return false;
+       if (block1->data != block2->data && (block1->data == NULL || block2->data == NULL || memcmp(block1->data, block2->data, block1->data_length)))
+               return false;
+       return true;
+}
+
+static FLAC__bool compare_block_data_unknown_(const FLAC__StreamMetadata_Unknown *block1, const FLAC__StreamMetadata_Unknown *block2, unsigned block_length)
+{
+       FLAC__ASSERT(block1 != NULL);
+       FLAC__ASSERT(block2 != NULL);
+
+       if (block1->data != NULL && block2->data != NULL)
+               return memcmp(block1->data, block2->data, block_length) == 0;
+       else
+               return block1->data == block2->data;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2)
+{
+       FLAC__ASSERT(block1 != NULL);
+       FLAC__ASSERT(block2 != NULL);
+
+       if (block1->type != block2->type) {
+               return false;
+       }
+       if (block1->is_last != block2->is_last) {
+               return false;
+       }
+       if (block1->length != block2->length) {
+               return false;
+       }
+       switch(block1->type) {
+               case FLAC__METADATA_TYPE_STREAMINFO:
+                       return compare_block_data_streaminfo_(&block1->data.stream_info, &block2->data.stream_info);
+               case FLAC__METADATA_TYPE_PADDING:
+                       return true; /* we don't compare the padding guts */
+               case FLAC__METADATA_TYPE_APPLICATION:
+                       return compare_block_data_application_(&block1->data.application, &block2->data.application, block1->length);
+               case FLAC__METADATA_TYPE_SEEKTABLE:
+                       return compare_block_data_seektable_(&block1->data.seek_table, &block2->data.seek_table);
+               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                       return compare_block_data_vorbiscomment_(&block1->data.vorbis_comment, &block2->data.vorbis_comment);
+               case FLAC__METADATA_TYPE_CUESHEET:
+                       return compare_block_data_cuesheet_(&block1->data.cue_sheet, &block2->data.cue_sheet);
+               case FLAC__METADATA_TYPE_PICTURE:
+                       return compare_block_data_picture_(&block1->data.picture, &block2->data.picture);
+               default:
+                       return compare_block_data_unknown_(&block1->data.unknown, &block2->data.unknown, block1->length);
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy)
+{
+       FLAC__byte *save;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_APPLICATION);
+       FLAC__ASSERT((data != NULL && length > 0) || (data == NULL && length == 0 && copy == false));
+
+       save = object->data.application.data;
+
+       /* do the copy first so that if we fail we leave the object untouched */
+       if (copy) {
+               if (!copy_bytes_(&object->data.application.data, data, length))
+                       return false;
+       }
+       else {
+               object->data.application.data = data;
+       }
+
+       free(save);
+
+       object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8 + length;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       if (object->data.seek_table.points == 0) {
+               FLAC__ASSERT(object->data.seek_table.num_points == 0);
+               if (new_num_points == 0)
+                       return true;
+               else if ((object->data.seek_table.points = seekpoint_array_new_(new_num_points)) == 0)
+                       return false;
+       }
+       else {
+               const size_t old_size = object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint);
+               const size_t new_size = new_num_points * sizeof(FLAC__StreamMetadata_SeekPoint);
+
+               /* overflow check */
+               if (new_num_points > UINT32_MAX / sizeof(FLAC__StreamMetadata_SeekPoint))
+                       return false;
+
+               FLAC__ASSERT(object->data.seek_table.num_points > 0);
+
+               if (new_size == 0) {
+                       free(object->data.seek_table.points);
+                       object->data.seek_table.points = 0;
+               }
+               else if ((object->data.seek_table.points = safe_realloc_(object->data.seek_table.points, new_size)) == NULL)
+                       return false;
+
+               /* if growing, set new elements to placeholders */
+               if (new_size > old_size) {
+                       unsigned i;
+                       for (i = object->data.seek_table.num_points; i < new_num_points; i++) {
+                               object->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
+                               object->data.seek_table.points[i].stream_offset = 0;
+                               object->data.seek_table.points[i].frame_samples = 0;
+                       }
+               }
+       }
+
+       object->data.seek_table.num_points = new_num_points;
+
+       seektable_calculate_length_(object);
+       return true;
+}
+
+FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(point_num < object->data.seek_table.num_points);
+
+       object->data.seek_table.points[point_num] = point;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point)
+{
+       int i;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(point_num <= object->data.seek_table.num_points);
+
+       if (!FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points+1))
+               return false;
+
+       /* move all points >= point_num forward one space */
+       for (i = (int)object->data.seek_table.num_points-1; i > (int)point_num; i--)
+               object->data.seek_table.points[i] = object->data.seek_table.points[i-1];
+
+       FLAC__metadata_object_seektable_set_point(object, point_num, point);
+       seektable_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num)
+{
+       unsigned i;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(point_num < object->data.seek_table.num_points);
+
+       /* move all points > point_num backward one space */
+       for (i = point_num; i < object->data.seek_table.num_points-1; i++)
+               object->data.seek_table.points[i] = object->data.seek_table.points[i+1];
+
+       return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points-1);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       return FLAC__format_seektable_is_legal(&object->data.seek_table);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       if (num > 0)
+               /* WATCHOUT: we rely on the fact that growing the array adds PLACEHOLDERS at the end */
+               return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points + num);
+       else
+               return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number)
+{
+       FLAC__StreamMetadata_SeekTable *seek_table;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       seek_table = &object->data.seek_table;
+
+       if (!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + 1))
+               return false;
+
+       seek_table->points[seek_table->num_points - 1].sample_number = sample_number;
+       seek_table->points[seek_table->num_points - 1].stream_offset = 0;
+       seek_table->points[seek_table->num_points - 1].frame_samples = 0;
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(sample_numbers != 0 || num == 0);
+
+       if (num > 0) {
+               FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
+               unsigned i, j;
+
+               i = seek_table->num_points;
+
+               if (!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num))
+                       return false;
+
+               for (j = 0; j < num; i++, j++) {
+                       seek_table->points[i].sample_number = sample_numbers[j];
+                       seek_table->points[i].stream_offset = 0;
+                       seek_table->points[i].frame_samples = 0;
+               }
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(total_samples > 0);
+
+       if (num > 0 && total_samples > 0) {
+               FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
+               unsigned i, j;
+
+               i = seek_table->num_points;
+
+               if (!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num))
+                       return false;
+
+               for (j = 0; j < num; i++, j++) {
+                       seek_table->points[i].sample_number = total_samples * (FLAC__uint64)j / (FLAC__uint64)num;
+                       seek_table->points[i].stream_offset = 0;
+                       seek_table->points[i].frame_samples = 0;
+               }
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+       FLAC__ASSERT(samples > 0);
+       FLAC__ASSERT(total_samples > 0);
+
+       if (samples > 0 && total_samples > 0) {
+               FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
+               unsigned i, j;
+               FLAC__uint64 num, sample;
+
+               num = 1 + total_samples / samples; /* 1+ for the first sample at 0 */
+               /* now account for the fact that we don't place a seekpoint at "total_samples" since samples are number from 0: */
+               if (total_samples % samples == 0)
+                       num--;
+
+               /* Put a strict upper bound on the number of allowed seek points. */
+               if (num > 32768) {
+                       /* Set the bound and recalculate samples accordingly. */
+                       num = 32768;
+                       samples = total_samples / num;
+               }
+
+               i = seek_table->num_points;
+
+               if (!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + (unsigned)num))
+                       return false;
+
+               sample = 0;
+               for (j = 0; j < num; i++, j++, sample += samples) {
+                       seek_table->points[i].sample_number = sample;
+                       seek_table->points[i].stream_offset = 0;
+                       seek_table->points[i].frame_samples = 0;
+               }
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact)
+{
+       unsigned unique;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
+
+       unique = FLAC__format_seektable_sort(&object->data.seek_table);
+
+       return !compact || FLAC__metadata_object_seektable_resize_points(object, unique);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
+{
+       if (!FLAC__format_vorbiscomment_entry_value_is_legal(entry.entry, entry.length))
+               return false;
+       return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.vendor_string, &entry, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+       if (object->data.vorbis_comment.comments == NULL) {
+               FLAC__ASSERT(object->data.vorbis_comment.num_comments == 0);
+               if (new_num_comments == 0)
+                       return true;
+               else if ((object->data.vorbis_comment.comments = vorbiscomment_entry_array_new_(new_num_comments)) == NULL)
+                       return false;
+       }
+       else {
+               const size_t old_size = object->data.vorbis_comment.num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry);
+               const size_t new_size = new_num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry);
+
+               /* overflow check */
+               if (new_num_comments > UINT32_MAX / sizeof(FLAC__StreamMetadata_VorbisComment_Entry))
+                       return false;
+
+               FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0);
+
+               /* if shrinking, free the truncated entries */
+               if (new_num_comments < object->data.vorbis_comment.num_comments) {
+                       unsigned i;
+                       for (i = new_num_comments; i < object->data.vorbis_comment.num_comments; i++)
+                               if (object->data.vorbis_comment.comments[i].entry != NULL)
+                                       free(object->data.vorbis_comment.comments[i].entry);
+               }
+
+               if (new_size == 0) {
+                       free(object->data.vorbis_comment.comments);
+                       object->data.vorbis_comment.comments = 0;
+               }
+               else {
+                       FLAC__StreamMetadata_VorbisComment_Entry *oldptr = object->data.vorbis_comment.comments;
+                       if ((object->data.vorbis_comment.comments = realloc(object->data.vorbis_comment.comments, new_size)) == NULL) {
+                               vorbiscomment_entry_array_delete_(oldptr, object->data.vorbis_comment.num_comments);
+                               object->data.vorbis_comment.num_comments = 0;
+                               return false;
+                       }
+               }
+
+               /* if growing, zero all the length/pointers of new elements */
+               if (new_size > old_size)
+                       memset(object->data.vorbis_comment.comments + object->data.vorbis_comment.num_comments, 0, new_size - old_size);
+       }
+
+       object->data.vorbis_comment.num_comments = new_num_comments;
+
+       vorbiscomment_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments);
+
+       if (!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
+               return false;
+       return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.comments[comment_num], &entry, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
+{
+       FLAC__StreamMetadata_VorbisComment *vc;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+       FLAC__ASSERT(comment_num <= object->data.vorbis_comment.num_comments);
+
+       if (!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
+               return false;
+
+       vc = &object->data.vorbis_comment;
+
+       if (!FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments+1))
+               return false;
+
+       /* move all comments >= comment_num forward one space */
+       memmove(&vc->comments[comment_num+1], &vc->comments[comment_num], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-1-comment_num));
+       vc->comments[comment_num].length = 0;
+       vc->comments[comment_num].entry = 0;
+
+       return FLAC__metadata_object_vorbiscomment_set_comment(object, comment_num, entry, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+       return FLAC__metadata_object_vorbiscomment_insert_comment(object, object->data.vorbis_comment.num_comments, entry, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy)
+{
+       FLAC__ASSERT(entry.entry != NULL && entry.length > 0);
+
+       if (!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
+               return false;
+
+       {
+               int i;
+               size_t field_name_length;
+               const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
+
+               if (eq == NULL)
+                       return false; /* double protection */
+
+               field_name_length = eq-entry.entry;
+
+               i = vorbiscomment_find_entry_from_(object, 0, (const char *)entry.entry, field_name_length);
+               if (i >= 0) {
+                       unsigned indx = (unsigned)i;
+                       if (!FLAC__metadata_object_vorbiscomment_set_comment(object, indx, entry, copy))
+                               return false;
+                       entry = object->data.vorbis_comment.comments[indx];
+                       indx++; /* skip over replaced comment */
+                       if (all && indx < object->data.vorbis_comment.num_comments) {
+                               i = vorbiscomment_find_entry_from_(object, indx, (const char *)entry.entry, field_name_length);
+                               while (i >= 0) {
+                                       indx = (unsigned)i;
+                                       if (!FLAC__metadata_object_vorbiscomment_delete_comment(object, indx))
+                                               return false;
+                                       if (indx < object->data.vorbis_comment.num_comments)
+                                               i = vorbiscomment_find_entry_from_(object, indx, (const char *)entry.entry, field_name_length);
+                                       else
+                                               i = -1;
+                               }
+                       }
+                       return true;
+               }
+               else
+                       return FLAC__metadata_object_vorbiscomment_append_comment(object, entry, copy);
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num)
+{
+       FLAC__StreamMetadata_VorbisComment *vc;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+       FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments);
+
+       vc = &object->data.vorbis_comment;
+
+       /* free the comment at comment_num */
+       free(vc->comments[comment_num].entry);
+
+       /* move all comments > comment_num backward one space */
+       memmove(&vc->comments[comment_num], &vc->comments[comment_num+1], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-comment_num-1));
+       vc->comments[vc->num_comments-1].length = 0;
+       vc->comments[vc->num_comments-1].entry = 0;
+
+       return FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments-1);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value)
+{
+       FLAC__ASSERT(entry != NULL);
+       FLAC__ASSERT(field_name != NULL);
+       FLAC__ASSERT(field_value != NULL);
+
+       if (!FLAC__format_vorbiscomment_entry_name_is_legal(field_name))
+               return false;
+       if (!FLAC__format_vorbiscomment_entry_value_is_legal((const FLAC__byte *)field_value, (unsigned)(-1)))
+               return false;
+
+       {
+               const size_t nn = strlen(field_name);
+               const size_t nv = strlen(field_value);
+               entry->length = nn + 1 /*=*/ + nv;
+               if ((entry->entry = safe_malloc_add_4op_(nn, /*+*/1, /*+*/nv, /*+*/1)) == NULL)
+                       return false;
+               memcpy(entry->entry, field_name, nn);
+               entry->entry[nn] = '=';
+               memcpy(entry->entry+nn+1, field_value, nv);
+               entry->entry[entry->length] = '\0';
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value)
+{
+       FLAC__ASSERT(entry.entry != NULL && entry.length > 0);
+       FLAC__ASSERT(field_name != NULL);
+       FLAC__ASSERT(field_value != NULL);
+
+       if (!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
+               return false;
+
+       {
+               const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
+               const size_t nn = eq-entry.entry;
+               const size_t nv = entry.length-nn-1; /* -1 for the '=' */
+
+               if (eq == NULL)
+                       return false; /* double protection */
+               if ((*field_name = safe_malloc_add_2op_(nn, /*+*/1)) == NULL)
+                       return false;
+               if ((*field_value = safe_malloc_add_2op_(nv, /*+*/1)) == NULL) {
+                       free(*field_name);
+                       return false;
+               }
+               memcpy(*field_name, entry.entry, nn);
+               memcpy(*field_value, entry.entry+nn+1, nv);
+               (*field_name)[nn] = '\0';
+               (*field_value)[nv] = '\0';
+       }
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length)
+{
+       FLAC__ASSERT(entry.entry != NULL && entry.length > 0);
+       {
+               const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
+               return (eq != NULL && (unsigned)(eq-entry.entry) == field_name_length && FLAC__STRNCASECMP(field_name, (const char *)entry.entry, field_name_length) == 0);
+       }
+}
+
+FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name)
+{
+       FLAC__ASSERT(field_name != NULL);
+
+       return vorbiscomment_find_entry_from_(object, offset, field_name, strlen(field_name));
+}
+
+FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name)
+{
+       const unsigned field_name_length = strlen(field_name);
+       unsigned i;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+       for (i = 0; i < object->data.vorbis_comment.num_comments; i++) {
+               if (FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) {
+                       if (!FLAC__metadata_object_vorbiscomment_delete_comment(object, i))
+                               return -1;
+                       else
+                               return 1;
+               }
+       }
+
+       return 0;
+}
+
+FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name)
+{
+       FLAC__bool ok = true;
+       unsigned matching = 0;
+       const unsigned field_name_length = strlen(field_name);
+       int i;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
+
+       /* must delete from end to start otherwise it will interfere with our iteration */
+       for (i = (int)object->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) {
+               if (FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) {
+                       matching++;
+                       ok &= FLAC__metadata_object_vorbiscomment_delete_comment(object, (unsigned)i);
+               }
+       }
+
+       return ok? (int)matching : -1;
+}
+
+FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void)
+{
+       return calloc(1, sizeof(FLAC__StreamMetadata_CueSheet_Track));
+}
+
+FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object)
+{
+       FLAC__StreamMetadata_CueSheet_Track *to;
+
+       FLAC__ASSERT(object != NULL);
+
+       if ((to = FLAC__metadata_object_cuesheet_track_new()) != NULL) {
+               if (!copy_track_(to, object)) {
+                       FLAC__metadata_object_cuesheet_track_delete(to);
+                       return 0;
+               }
+       }
+
+       return to;
+}
+
+void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object)
+{
+       FLAC__ASSERT(object != NULL);
+
+       if (object->indices != NULL) {
+               FLAC__ASSERT(object->num_indices > 0);
+               free(object->indices);
+       }
+}
+
+FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object)
+{
+       FLAC__metadata_object_cuesheet_track_delete_data(object);
+       free(object);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices)
+{
+       FLAC__StreamMetadata_CueSheet_Track *track;
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
+
+       track = &object->data.cue_sheet.tracks[track_num];
+
+       if (track->indices == NULL) {
+               FLAC__ASSERT(track->num_indices == 0);
+               if (new_num_indices == 0)
+                       return true;
+               else if ((track->indices = cuesheet_track_index_array_new_(new_num_indices)) == NULL)
+                       return false;
+       }
+       else {
+               const size_t old_size = track->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index);
+               const size_t new_size = new_num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index);
+
+               /* overflow check */
+               if (new_num_indices > UINT32_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Index))
+                       return false;
+
+               FLAC__ASSERT(track->num_indices > 0);
+
+               if (new_size == 0) {
+                       free(track->indices);
+                       track->indices = 0;
+               }
+               else if ((track->indices = safe_realloc_(track->indices, new_size)) == NULL)
+                       return false;
+
+               /* if growing, zero all the lengths/pointers of new elements */
+               if (new_size > old_size)
+                       memset(track->indices + track->num_indices, 0, new_size - old_size);
+       }
+
+       track->num_indices = new_num_indices;
+
+       cuesheet_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index indx)
+{
+       FLAC__StreamMetadata_CueSheet_Track *track;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
+       FLAC__ASSERT(index_num <= object->data.cue_sheet.tracks[track_num].num_indices);
+
+       track = &object->data.cue_sheet.tracks[track_num];
+
+       if (!FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices+1))
+               return false;
+
+       /* move all indices >= index_num forward one space */
+       memmove(&track->indices[index_num+1], &track->indices[index_num], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-1-index_num));
+
+       track->indices[index_num] = indx;
+       cuesheet_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num)
+{
+       FLAC__StreamMetadata_CueSheet_Index indx;
+       memset(&indx, 0, sizeof(indx));
+       return FLAC__metadata_object_cuesheet_track_insert_index(object, track_num, index_num, indx);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num)
+{
+       FLAC__StreamMetadata_CueSheet_Track *track;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
+       FLAC__ASSERT(index_num < object->data.cue_sheet.tracks[track_num].num_indices);
+
+       track = &object->data.cue_sheet.tracks[track_num];
+
+       /* move all indices > index_num backward one space */
+       memmove(&track->indices[index_num], &track->indices[index_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-index_num-1));
+
+       FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices-1);
+       cuesheet_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+
+       if (object->data.cue_sheet.tracks == NULL) {
+               FLAC__ASSERT(object->data.cue_sheet.num_tracks == 0);
+               if (new_num_tracks == 0)
+                       return true;
+               else if ((object->data.cue_sheet.tracks = cuesheet_track_array_new_(new_num_tracks)) == NULL)
+                       return false;
+       }
+       else {
+               const size_t old_size = object->data.cue_sheet.num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track);
+               const size_t new_size = new_num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track);
+
+               /* overflow check */
+               if (new_num_tracks > UINT32_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Track))
+                       return false;
+
+               FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0);
+
+               /* if shrinking, free the truncated entries */
+               if (new_num_tracks < object->data.cue_sheet.num_tracks) {
+                       unsigned i;
+                       for (i = new_num_tracks; i < object->data.cue_sheet.num_tracks; i++)
+                               free(object->data.cue_sheet.tracks[i].indices);
+               }
+
+               if (new_size == 0) {
+                       free(object->data.cue_sheet.tracks);
+                       object->data.cue_sheet.tracks = 0;
+               }
+               else if ((object->data.cue_sheet.tracks = safe_realloc_(object->data.cue_sheet.tracks, new_size)) == NULL)
+                       return false;
+
+               /* if growing, zero all the lengths/pointers of new elements */
+               if (new_size > old_size)
+                       memset(object->data.cue_sheet.tracks + object->data.cue_sheet.num_tracks, 0, new_size - old_size);
+       }
+
+       object->data.cue_sheet.num_tracks = new_num_tracks;
+
+       cuesheet_calculate_length_(object);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
+
+       return cuesheet_set_track_(object, object->data.cue_sheet.tracks + track_num, track, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy)
+{
+       FLAC__StreamMetadata_CueSheet *cs;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT(track_num <= object->data.cue_sheet.num_tracks);
+
+       cs = &object->data.cue_sheet;
+
+       if (!FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks+1))
+               return false;
+
+       /* move all tracks >= track_num forward one space */
+       memmove(&cs->tracks[track_num+1], &cs->tracks[track_num], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-1-track_num));
+       cs->tracks[track_num].num_indices = 0;
+       cs->tracks[track_num].indices = 0;
+
+       return FLAC__metadata_object_cuesheet_set_track(object, track_num, track, copy);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num)
+{
+       FLAC__StreamMetadata_CueSheet_Track track;
+       memset(&track, 0, sizeof(track));
+       return FLAC__metadata_object_cuesheet_insert_track(object, track_num, &track, /*copy=*/false);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num)
+{
+       FLAC__StreamMetadata_CueSheet *cs;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+       FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
+
+       cs = &object->data.cue_sheet;
+
+       /* free the track at track_num */
+       free(cs->tracks[track_num].indices);
+
+       /* move all tracks > track_num backward one space */
+       memmove(&cs->tracks[track_num], &cs->tracks[track_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-track_num-1));
+       cs->tracks[cs->num_tracks-1].num_indices = 0;
+       cs->tracks[cs->num_tracks-1].indices = 0;
+
+       return FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks-1);
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+
+       return FLAC__format_cuesheet_is_legal(&object->data.cue_sheet, check_cd_da_subset, violation);
+}
+
+static FLAC__uint64 get_index_01_offset_(const FLAC__StreamMetadata_CueSheet *cs, unsigned track)
+{
+       if (track >= (cs->num_tracks-1) || cs->tracks[track].num_indices < 1)
+               return 0;
+       else if (cs->tracks[track].indices[0].number == 1)
+               return cs->tracks[track].indices[0].offset + cs->tracks[track].offset + cs->lead_in;
+       else if (cs->tracks[track].num_indices < 2)
+               return 0;
+       else if (cs->tracks[track].indices[1].number == 1)
+               return cs->tracks[track].indices[1].offset + cs->tracks[track].offset + cs->lead_in;
+       else
+               return 0;
+}
+
+static FLAC__uint32 cddb_add_digits_(FLAC__uint32 x)
+{
+       FLAC__uint32 n = 0;
+       while (x) {
+               n += (x%10);
+               x /= 10;
+       }
+       return n;
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object)
+{
+       const FLAC__StreamMetadata_CueSheet *cs;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
+
+       cs = &object->data.cue_sheet;
+
+       if (cs->num_tracks < 2) /* need at least one real track and the lead-out track */
+               return 0;
+
+       {
+               FLAC__uint32 i, length, sum = 0;
+               for (i = 0; i < (cs->num_tracks-1); i++) /* -1 to avoid counting the lead-out */
+                       sum += cddb_add_digits_((FLAC__uint32)(get_index_01_offset_(cs, i) / 44100));
+               length = (FLAC__uint32)((cs->tracks[cs->num_tracks-1].offset+cs->lead_in) / 44100) - (FLAC__uint32)(get_index_01_offset_(cs, 0) / 44100);
+
+               return (sum % 0xFF) << 24 | length << 8 | (FLAC__uint32)(cs->num_tracks-1);
+       }
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy)
+{
+       char *old;
+       size_t old_length, new_length;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
+       FLAC__ASSERT(mime_type != NULL);
+
+       old = object->data.picture.mime_type;
+       old_length = old? strlen(old) : 0;
+       new_length = strlen(mime_type);
+
+       /* do the copy first so that if we fail we leave the object untouched */
+       if (copy) {
+               if (new_length >= SIZE_MAX) /* overflow check */
+                       return false;
+               if (!copy_bytes_((FLAC__byte**)(&object->data.picture.mime_type), (FLAC__byte*)mime_type, new_length+1))
+                       return false;
+       }
+       else {
+               object->data.picture.mime_type = mime_type;
+       }
+
+       free(old);
+
+       object->length -= old_length;
+       object->length += new_length;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy)
+{
+       FLAC__byte *old;
+       size_t old_length, new_length;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
+       FLAC__ASSERT(description != NULL);
+
+       old = object->data.picture.description;
+       old_length = old? strlen((const char *)old) : 0;
+       new_length = strlen((const char *)description);
+
+       /* do the copy first so that if we fail we leave the object untouched */
+       if (copy) {
+               if (new_length >= SIZE_MAX) /* overflow check */
+                       return false;
+               if (!copy_bytes_(&object->data.picture.description, description, new_length+1))
+                       return false;
+       }
+       else {
+               object->data.picture.description = description;
+       }
+
+       free(old);
+
+       object->length -= old_length;
+       object->length += new_length;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy)
+{
+       FLAC__byte *old;
+
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
+       FLAC__ASSERT((data != NULL && length > 0) || (data == NULL && length == 0 && copy == false));
+
+       old = object->data.picture.data;
+
+       /* do the copy first so that if we fail we leave the object untouched */
+       if (copy) {
+               if (!copy_bytes_(&object->data.picture.data, data, length))
+                       return false;
+       }
+       else {
+               object->data.picture.data = data;
+       }
+
+       free(old);
+
+       object->length -= object->data.picture.data_length;
+       object->data.picture.data_length = length;
+       object->length += length;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation)
+{
+       FLAC__ASSERT(object != NULL);
+       FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
+
+       return FLAC__format_picture_is_legal(&object->data.picture, violation);
+}
diff --git a/FLAC/src/ogg_decoder_aspect.c b/FLAC/src/ogg_decoder_aspect.c
new file mode 100644 (file)
index 0000000..40cee19
--- /dev/null
@@ -0,0 +1,251 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <string.h> /* for memcpy() */
+#include "FLAC/assert.h"
+#include "private/ogg_decoder_aspect.h"
+#include "private/ogg_mapping.h"
+#include "private/macros.h"
+
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+FLAC__bool FLAC__ogg_decoder_aspect_init(FLAC__OggDecoderAspect *aspect)
+{
+       /* we will determine the serial number later if necessary */
+       if(ogg_stream_init(&aspect->stream_state, aspect->serial_number) != 0)
+               return false;
+
+       if(ogg_sync_init(&aspect->sync_state) != 0)
+               return false;
+
+       aspect->version_major = ~(0u);
+       aspect->version_minor = ~(0u);
+
+       aspect->need_serial_number = aspect->use_first_serial_number;
+
+       aspect->end_of_stream = false;
+       aspect->have_working_page = false;
+
+       return true;
+}
+
+void FLAC__ogg_decoder_aspect_finish(FLAC__OggDecoderAspect *aspect)
+{
+       (void)ogg_sync_clear(&aspect->sync_state);
+       (void)ogg_stream_clear(&aspect->stream_state);
+}
+
+void FLAC__ogg_decoder_aspect_set_serial_number(FLAC__OggDecoderAspect *aspect, long value)
+{
+       aspect->use_first_serial_number = false;
+       aspect->serial_number = value;
+}
+
+void FLAC__ogg_decoder_aspect_set_defaults(FLAC__OggDecoderAspect *aspect)
+{
+       aspect->use_first_serial_number = true;
+}
+
+void FLAC__ogg_decoder_aspect_flush(FLAC__OggDecoderAspect *aspect)
+{
+       (void)ogg_stream_reset(&aspect->stream_state);
+       (void)ogg_sync_reset(&aspect->sync_state);
+       aspect->end_of_stream = false;
+       aspect->have_working_page = false;
+}
+
+void FLAC__ogg_decoder_aspect_reset(FLAC__OggDecoderAspect *aspect)
+{
+       FLAC__ogg_decoder_aspect_flush(aspect);
+
+       if(aspect->use_first_serial_number)
+               aspect->need_serial_number = true;
+}
+
+FLAC__OggDecoderAspectReadStatus FLAC__ogg_decoder_aspect_read_callback_wrapper(FLAC__OggDecoderAspect *aspect, FLAC__byte buffer[], size_t *bytes, FLAC__OggDecoderAspectReadCallbackProxy read_callback, const FLAC__StreamDecoder *decoder, void *client_data)
+{
+       static const size_t OGG_BYTES_CHUNK = 8192;
+       const size_t bytes_requested = *bytes;
+
+       /*
+        * The FLAC decoding API uses pull-based reads, whereas Ogg decoding
+        * is push-based.  In libFLAC, when you ask to decode a frame, the
+        * decoder will eventually call the read callback to supply some data,
+        * but how much it asks for depends on how much free space it has in
+        * its internal buffer.  It does not try to grow its internal buffer
+        * to accomodate a whole frame because then the internal buffer size
+        * could not be limited, which is necessary in embedded applications.
+        *
+        * Ogg however grows its internal buffer until a whole page is present;
+        * only then can you get decoded data out.  So we can't just ask for
+        * the same number of bytes from Ogg, then pass what's decoded down to
+        * libFLAC.  If what libFLAC is asking for will not contain a whole
+        * page, then we will get no data from ogg_sync_pageout(), and at the
+        * same time cannot just read more data from the client for the purpose
+        * of getting a whole decoded page because the decoded size might be
+        * larger than libFLAC's internal buffer.
+        *
+        * Instead, whenever this read callback wrapper is called, we will
+        * continually request data from the client until we have at least one
+        * page, and manage pages internally so that we can send pieces of
+        * pages down to libFLAC in such a way that we obey its size
+        * requirement.  To limit the amount of callbacks, we will always try
+        * to read in enough pages to return the full number of bytes
+        * requested.
+        */
+       *bytes = 0;
+       while (*bytes < bytes_requested && !aspect->end_of_stream) {
+               if (aspect->have_working_page) {
+                       if (aspect->have_working_packet) {
+                               size_t n = bytes_requested - *bytes;
+                               if ((size_t)aspect->working_packet.bytes <= n) {
+                                       /* the rest of the packet will fit in the buffer */
+                                       n = aspect->working_packet.bytes;
+                                       memcpy(buffer, aspect->working_packet.packet, n);
+                                       *bytes += n;
+                                       buffer += n;
+                                       aspect->have_working_packet = false;
+                               }
+                               else {
+                                       /* only n bytes of the packet will fit in the buffer */
+                                       memcpy(buffer, aspect->working_packet.packet, n);
+                                       *bytes += n;
+                                       buffer += n;
+                                       aspect->working_packet.packet += n;
+                                       aspect->working_packet.bytes -= n;
+                               }
+                       }
+                       else {
+                               /* try and get another packet */
+                               const int ret = ogg_stream_packetout(&aspect->stream_state, &aspect->working_packet);
+                               if (ret > 0) {
+                                       aspect->have_working_packet = true;
+                                       /* if it is the first header packet, check for magic and a supported Ogg FLAC mapping version */
+                                       if (aspect->working_packet.bytes > 0 && aspect->working_packet.packet[0] == FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE) {
+                                               const FLAC__byte *b = aspect->working_packet.packet;
+                                               const unsigned header_length =
+                                                       FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
+                                                       FLAC__OGG_MAPPING_MAGIC_LENGTH +
+                                                       FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
+                                                       FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
+                                                       FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH;
+                                               if (aspect->working_packet.bytes < (long)header_length)
+                                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC;
+                                               b += FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH;
+                                               if (memcmp(b, FLAC__OGG_MAPPING_MAGIC, FLAC__OGG_MAPPING_MAGIC_LENGTH))
+                                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC;
+                                               b += FLAC__OGG_MAPPING_MAGIC_LENGTH;
+                                               aspect->version_major = (unsigned)(*b);
+                                               b += FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH;
+                                               aspect->version_minor = (unsigned)(*b);
+                                               if (aspect->version_major != 1)
+                                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION;
+                                               aspect->working_packet.packet += header_length;
+                                               aspect->working_packet.bytes -= header_length;
+                                       }
+                               }
+                               else if (ret == 0) {
+                                       aspect->have_working_page = false;
+                               }
+                               else { /* ret < 0 */
+                                       /* lost sync, we'll leave the working page for the next call */
+                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC;
+                               }
+                       }
+               }
+               else {
+                       /* try and get another page */
+                       const int ret = ogg_sync_pageout(&aspect->sync_state, &aspect->working_page);
+                       if (ret > 0) {
+                               /* got a page, grab the serial number if necessary */
+                               if(aspect->need_serial_number) {
+                                       aspect->stream_state.serialno = aspect->serial_number = ogg_page_serialno(&aspect->working_page);
+                                       aspect->need_serial_number = false;
+                               }
+                               if(ogg_stream_pagein(&aspect->stream_state, &aspect->working_page) == 0) {
+                                       aspect->have_working_page = true;
+                                       aspect->have_working_packet = false;
+                               }
+                               /* else do nothing, could be a page from another stream */
+                       }
+                       else if (ret == 0) {
+                               /* need more data */
+                               const size_t ogg_bytes_to_read = flac_max(bytes_requested - *bytes, OGG_BYTES_CHUNK);
+                               char *oggbuf = ogg_sync_buffer(&aspect->sync_state, ogg_bytes_to_read);
+
+                               if(0 == oggbuf) {
+                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR;
+                               }
+                               else {
+                                       size_t ogg_bytes_read = ogg_bytes_to_read;
+
+                                       switch(read_callback(decoder, (FLAC__byte*)oggbuf, &ogg_bytes_read, client_data)) {
+                                               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
+                                                       break;
+                                               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
+                                                       aspect->end_of_stream = true;
+                                                       break;
+                                               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
+                                                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
+                                               default:
+                                                       FLAC__ASSERT(0);
+                                       }
+
+                                       if(ogg_sync_wrote(&aspect->sync_state, ogg_bytes_read) < 0) {
+                                               /* double protection; this will happen if the read callback returns more bytes than the max requested, which would overflow Ogg's internal buffer */
+                                               FLAC__ASSERT(0);
+                                               return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR;
+                                       }
+                               }
+                       }
+                       else { /* ret < 0 */
+                               /* lost sync, bail out */
+                               return FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC;
+                       }
+               }
+       }
+
+       if (aspect->end_of_stream && *bytes == 0) {
+               return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
+       }
+
+       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
+}
diff --git a/FLAC/src/ogg_encoder_aspect.c b/FLAC/src/ogg_encoder_aspect.c
new file mode 100644 (file)
index 0000000..ebd4614
--- /dev/null
@@ -0,0 +1,228 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <string.h> /* for memset() */
+#include "FLAC/assert.h"
+#include "private/ogg_encoder_aspect.h"
+#include "private/ogg_mapping.h"
+
+static const FLAC__byte FLAC__OGG_MAPPING_VERSION_MAJOR = 1;
+static const FLAC__byte FLAC__OGG_MAPPING_VERSION_MINOR = 0;
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+FLAC__bool FLAC__ogg_encoder_aspect_init(FLAC__OggEncoderAspect *aspect)
+{
+       /* we will determine the serial number later if necessary */
+       if(ogg_stream_init(&aspect->stream_state, aspect->serial_number) != 0)
+               return false;
+
+       aspect->seen_magic = false;
+       aspect->is_first_packet = true;
+       aspect->samples_written = 0;
+
+       return true;
+}
+
+void FLAC__ogg_encoder_aspect_finish(FLAC__OggEncoderAspect *aspect)
+{
+       (void)ogg_stream_clear(&aspect->stream_state);
+       /*@@@ what about the page? */
+}
+
+void FLAC__ogg_encoder_aspect_set_serial_number(FLAC__OggEncoderAspect *aspect, long value)
+{
+       aspect->serial_number = value;
+}
+
+FLAC__bool FLAC__ogg_encoder_aspect_set_num_metadata(FLAC__OggEncoderAspect *aspect, unsigned value)
+{
+       if(value < (1u << FLAC__OGG_MAPPING_NUM_HEADERS_LEN)) {
+               aspect->num_metadata = value;
+               return true;
+       }
+       else
+               return false;
+}
+
+void FLAC__ogg_encoder_aspect_set_defaults(FLAC__OggEncoderAspect *aspect)
+{
+       aspect->serial_number = 0;
+       aspect->num_metadata = 0;
+}
+
+/*
+ * The basic FLAC -> Ogg mapping goes like this:
+ *
+ * - 'fLaC' magic and STREAMINFO block get combined into the first
+ *   packet.  The packet is prefixed with
+ *   + the one-byte packet type 0x7F
+ *   + 'FLAC' magic
+ *   + the 2 byte Ogg FLAC mapping version number
+ *   + tne 2 byte big-endian # of header packets
+ * - The first packet is flushed to the first page.
+ * - Each subsequent metadata block goes into its own packet.
+ * - Each metadata packet is flushed to page (this is not required,
+ *   the mapping only requires that a flush must occur after all
+ *   metadata is written).
+ * - Each subsequent FLAC audio frame goes into its own packet.
+ *
+ * WATCHOUT:
+ * This depends on the behavior of FLAC__StreamEncoder that we get a
+ * separate write callback for the fLaC magic, and then separate write
+ * callbacks for each metadata block and audio frame.
+ */
+FLAC__StreamEncoderWriteStatus FLAC__ogg_encoder_aspect_write_callback_wrapper(FLAC__OggEncoderAspect *aspect, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, FLAC__bool is_last_block, FLAC__OggEncoderAspectWriteCallbackProxy write_callback, void *encoder, void *client_data)
+{
+       /* WATCHOUT:
+        * This depends on the behavior of FLAC__StreamEncoder that 'samples'
+        * will be 0 for metadata writes.
+        */
+       const FLAC__bool is_metadata = (samples == 0);
+
+       /*
+        * Treat fLaC magic packet specially.  We will note when we see it, then
+        * wait until we get the STREAMINFO and prepend it in that packet
+        */
+       if(aspect->seen_magic) {
+               ogg_packet packet;
+               FLAC__byte synthetic_first_packet_body[
+                       FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
+                       FLAC__OGG_MAPPING_MAGIC_LENGTH +
+                       FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
+                       FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
+                       FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
+                       FLAC__STREAM_SYNC_LENGTH +
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       FLAC__STREAM_METADATA_STREAMINFO_LENGTH
+               ];
+
+               memset(&packet, 0, sizeof(packet));
+               packet.granulepos = aspect->samples_written + samples;
+
+               if(aspect->is_first_packet) {
+                       FLAC__byte *b = synthetic_first_packet_body;
+                       if(bytes != FLAC__STREAM_METADATA_HEADER_LENGTH + FLAC__STREAM_METADATA_STREAMINFO_LENGTH) {
+                               /*
+                                * If we get here, our assumption about the way write callbacks happen
+                                * (explained above) is wrong
+                                */
+                               FLAC__ASSERT(0);
+                               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+                       }
+                       /* add first header packet type */
+                       *b = FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE;
+                       b += FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH;
+                       /* add 'FLAC' mapping magic */
+                       memcpy(b, FLAC__OGG_MAPPING_MAGIC, FLAC__OGG_MAPPING_MAGIC_LENGTH);
+                       b += FLAC__OGG_MAPPING_MAGIC_LENGTH;
+                       /* add Ogg FLAC mapping major version number */
+                       memcpy(b, &FLAC__OGG_MAPPING_VERSION_MAJOR, FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH);
+                       b += FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH;
+                       /* add Ogg FLAC mapping minor version number */
+                       memcpy(b, &FLAC__OGG_MAPPING_VERSION_MINOR, FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH);
+                       b += FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH;
+                       /* add number of header packets */
+                       *b = (FLAC__byte)(aspect->num_metadata >> 8);
+                       b++;
+                       *b = (FLAC__byte)(aspect->num_metadata);
+                       b++;
+                       /* add native FLAC 'fLaC' magic */
+                       memcpy(b, FLAC__STREAM_SYNC_STRING, FLAC__STREAM_SYNC_LENGTH);
+                       b += FLAC__STREAM_SYNC_LENGTH;
+                       /* add STREAMINFO */
+                       memcpy(b, buffer, bytes);
+                       FLAC__ASSERT(b + bytes - synthetic_first_packet_body == sizeof(synthetic_first_packet_body));
+                       packet.packet = (unsigned char *)synthetic_first_packet_body;
+                       packet.bytes = sizeof(synthetic_first_packet_body);
+
+                       packet.b_o_s = 1;
+                       aspect->is_first_packet = false;
+               }
+               else {
+                       packet.packet = (unsigned char *)buffer;
+                       packet.bytes = bytes;
+               }
+
+               if(is_last_block) {
+                       /* we used to check:
+                        * FLAC__ASSERT(total_samples_estimate == 0 || total_samples_estimate == aspect->samples_written + samples);
+                        * but it's really not useful since total_samples_estimate is an estimate and can be inexact
+                        */
+                       packet.e_o_s = 1;
+               }
+
+               if(ogg_stream_packetin(&aspect->stream_state, &packet) != 0)
+                       return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+
+               /*@@@ can't figure out a way to pass a useful number for 'samples' to the write_callback, so we'll just pass 0 */
+               if(is_metadata) {
+                       while(ogg_stream_flush(&aspect->stream_state, &aspect->page) != 0) {
+                               if(write_callback(encoder, aspect->page.header, aspect->page.header_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK)
+                                       return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+                               if(write_callback(encoder, aspect->page.body, aspect->page.body_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK)
+                                       return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+                       }
+               }
+               else {
+                       while(ogg_stream_pageout(&aspect->stream_state, &aspect->page) != 0) {
+                               if(write_callback(encoder, aspect->page.header, aspect->page.header_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK)
+                                       return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+                               if(write_callback(encoder, aspect->page.body, aspect->page.body_len, 0, current_frame, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK)
+                                       return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+                       }
+               }
+       }
+       else if(is_metadata && current_frame == 0 && samples == 0 && bytes == 4 && 0 == memcmp(buffer, FLAC__STREAM_SYNC_STRING, sizeof(FLAC__STREAM_SYNC_STRING))) {
+               aspect->seen_magic = true;
+       }
+       else {
+               /*
+                * If we get here, our assumption about the way write callbacks happen
+                * explained above is wrong
+                */
+               FLAC__ASSERT(0);
+               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+       }
+
+       aspect->samples_written += samples;
+
+       return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+}
diff --git a/FLAC/src/ogg_helper.c b/FLAC/src/ogg_helper.c
new file mode 100644 (file)
index 0000000..7ca9160
--- /dev/null
@@ -0,0 +1,210 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdlib.h> /* for malloc() */
+#include <string.h> /* for memcmp(), memcpy() */
+#include "FLAC/assert.h"
+#include "share/alloc.h"
+#include "private/ogg_helper.h"
+#include "protected/stream_encoder.h"
+
+
+static FLAC__bool full_read_(FLAC__StreamEncoder *encoder, FLAC__byte *buffer, size_t bytes, FLAC__StreamEncoderReadCallback read_callback, void *client_data)
+{
+       while(bytes > 0) {
+               size_t bytes_read = bytes;
+               switch(read_callback(encoder, buffer, &bytes_read, client_data)) {
+                       case FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE:
+                               bytes -= bytes_read;
+                               buffer += bytes_read;
+                               break;
+                       case FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM:
+                               if(bytes_read == 0) {
+                                       encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                                       return false;
+                               }
+                               bytes -= bytes_read;
+                               buffer += bytes_read;
+                               break;
+                       case FLAC__STREAM_ENCODER_READ_STATUS_ABORT:
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                               return false;
+                       case FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED:
+                               return false;
+                       default:
+                               /* double protection: */
+                               FLAC__ASSERT(0);
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                               return false;
+               }
+       }
+
+       return true;
+}
+
+void simple_ogg_page__init(ogg_page *page)
+{
+       page->header = 0;
+       page->header_len = 0;
+       page->body = 0;
+       page->body_len = 0;
+}
+
+void simple_ogg_page__clear(ogg_page *page)
+{
+       if(page->header)
+               free(page->header);
+       if(page->body)
+               free(page->body);
+       simple_ogg_page__init(page);
+}
+
+FLAC__bool simple_ogg_page__get_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderReadCallback read_callback, void *client_data)
+{
+       static const unsigned OGG_HEADER_FIXED_PORTION_LEN = 27;
+       static const unsigned OGG_MAX_HEADER_LEN = 27/*OGG_HEADER_FIXED_PORTION_LEN*/ + 255;
+       FLAC__byte crc[4];
+       FLAC__StreamEncoderSeekStatus seek_status;
+
+       FLAC__ASSERT(page->header == 0);
+       FLAC__ASSERT(page->header_len == 0);
+       FLAC__ASSERT(page->body == 0);
+       FLAC__ASSERT(page->body_len == 0);
+
+       /* move the stream pointer to the supposed beginning of the page */
+       if(0 == seek_callback)
+               return false;
+       if((seek_status = seek_callback((FLAC__StreamEncoder*)encoder, position, client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+               if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return false;
+       }
+
+       /* allocate space for the page header */
+       if(0 == (page->header = safe_malloc_(OGG_MAX_HEADER_LEN))) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       /* read in the fixed part of the page header (up to but not including
+        * the segment table */
+       if(!full_read_(encoder, page->header, OGG_HEADER_FIXED_PORTION_LEN, read_callback, client_data))
+               return false;
+
+       page->header_len = OGG_HEADER_FIXED_PORTION_LEN + page->header[26];
+
+       /* check to see if it's a correct, "simple" page (one packet only) */
+       if(
+               memcmp(page->header, "OggS", 4) ||               /* doesn't start with OggS */
+               (page->header[5] & 0x01) ||                      /* continued packet */
+               memcmp(page->header+6, "\0\0\0\0\0\0\0\0", 8) || /* granulepos is non-zero */
+               page->header[26] == 0                            /* packet is 0-size */
+       ) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+               return false;
+       }
+
+       /* read in the segment table */
+       if(!full_read_(encoder, page->header + OGG_HEADER_FIXED_PORTION_LEN, page->header[26], read_callback, client_data))
+               return false;
+
+       {
+               unsigned i;
+
+               /* check to see that it specifies a single packet */
+               for(i = 0; i < (unsigned)page->header[26] - 1; i++) {
+                       if(page->header[i + OGG_HEADER_FIXED_PORTION_LEN] != 255) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                               return false;
+                       }
+               }
+
+               page->body_len = 255 * i + page->header[i + OGG_HEADER_FIXED_PORTION_LEN];
+       }
+
+       /* allocate space for the page body */
+       if(0 == (page->body = safe_malloc_(page->body_len))) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       /* read in the page body */
+       if(!full_read_(encoder, page->body, page->body_len, read_callback, client_data))
+               return false;
+
+       /* check the CRC */
+       memcpy(crc, page->header+22, 4);
+       ogg_page_checksum_set(page);
+       if(memcmp(crc, page->header+22, 4)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+               return false;
+       }
+
+       return true;
+}
+
+FLAC__bool simple_ogg_page__set_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderWriteCallback write_callback, void *client_data)
+{
+       FLAC__StreamEncoderSeekStatus seek_status;
+
+       FLAC__ASSERT(page->header != 0);
+       FLAC__ASSERT(page->header_len != 0);
+       FLAC__ASSERT(page->body != 0);
+       FLAC__ASSERT(page->body_len != 0);
+
+       /* move the stream pointer to the supposed beginning of the page */
+       if(0 == seek_callback)
+               return false;
+       if((seek_status = seek_callback((FLAC__StreamEncoder*)encoder, position, client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+               if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return false;
+       }
+
+       ogg_page_checksum_set(page);
+
+       /* re-write the page */
+       if(write_callback((FLAC__StreamEncoder*)encoder, page->header, page->header_len, 0, 0, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return false;
+       }
+       if(write_callback((FLAC__StreamEncoder*)encoder, page->body, page->body_len, 0, 0, client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return false;
+       }
+
+       return true;
+}
diff --git a/FLAC/src/ogg_mapping.c b/FLAC/src/ogg_mapping.c
new file mode 100644 (file)
index 0000000..08fa514
--- /dev/null
@@ -0,0 +1,48 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/ogg_mapping.h"
+
+const unsigned FLAC__OGG_MAPPING_PACKET_TYPE_LEN = 8; /* bits */
+
+const FLAC__byte FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE = 0x7f;
+
+const FLAC__byte * const FLAC__OGG_MAPPING_MAGIC = (const FLAC__byte * const)"FLAC";
+
+const unsigned FLAC__OGG_MAPPING_VERSION_MAJOR_LEN = 8; /* bits */
+const unsigned FLAC__OGG_MAPPING_VERSION_MINOR_LEN = 8; /* bits */
+
+const unsigned FLAC__OGG_MAPPING_NUM_HEADERS_LEN = 16; /* bits */
diff --git a/FLAC/src/private/all.h b/FLAC/src/private/all.h
new file mode 100644 (file)
index 0000000..7715962
--- /dev/null
@@ -0,0 +1,50 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__ALL_H
+#define FLAC__PRIVATE__ALL_H
+
+#include "bitmath.h"
+#include "bitreader.h"
+#include "bitwriter.h"
+#include "cpu.h"
+#include "crc.h"
+#include "fixed.h"
+#include "float.h"
+#include "format.h"
+#include "lpc.h"
+#include "md5.h"
+#include "memory.h"
+#include "metadata.h"
+#include "stream_encoder_framing.h"
+
+#endif
diff --git a/FLAC/src/private/bitmath.h b/FLAC/src/private/bitmath.h
new file mode 100644 (file)
index 0000000..9c75f85
--- /dev/null
@@ -0,0 +1,210 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__BITMATH_H
+#define FLAC__PRIVATE__BITMATH_H
+
+#include "FLAC/ordinals.h"
+#include "FLAC/assert.h"
+
+#include "share/compat.h"
+
+#if defined(_MSC_VER)
+#include <intrin.h> /* for _BitScanReverse* */
+#endif
+
+/* Will never be emitted for MSVC, GCC, Intel compilers */
+static inline unsigned int FLAC__clz_soft_uint32(FLAC__uint32 word)
+{
+       static const unsigned char byte_to_unary_table[] = {
+       8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
+       3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+       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, 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, 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, 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, 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, 0, 0, 0,
+       };
+
+       return word > 0xffffff ? byte_to_unary_table[word >> 24] :
+               word > 0xffff ? byte_to_unary_table[word >> 16] + 8 :
+               word > 0xff ? byte_to_unary_table[word >> 8] + 16 :
+               byte_to_unary_table[word] + 24;
+}
+
+static inline unsigned int FLAC__clz_uint32(FLAC__uint32 v)
+{
+/* Never used with input 0 */
+       FLAC__ASSERT(v > 0);
+#if defined(__INTEL_COMPILER)
+       return _bit_scan_reverse(v) ^ 31U;
+#elif defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+/* This will translate either to (bsr ^ 31U), clz , ctlz, cntlz, lzcnt depending on
+ * -march= setting or to a software routine in exotic machines. */
+       return __builtin_clz(v);
+#elif defined(_MSC_VER)
+       {
+               unsigned long idx;
+               _BitScanReverse(&idx, v);
+               return idx ^ 31U;
+       }
+#else
+       return FLAC__clz_soft_uint32(v);
+#endif
+}
+
+/* Used when 64-bit bsr/clz is unavailable; can use 32-bit bsr/clz when possible */
+static inline unsigned int FLAC__clz_soft_uint64(FLAC__uint64 word)
+{
+       return (FLAC__uint32)(word>>32) ? FLAC__clz_uint32((FLAC__uint32)(word>>32)) :
+               FLAC__clz_uint32((FLAC__uint32)word) + 32;
+}
+
+static inline unsigned int FLAC__clz_uint64(FLAC__uint64 v)
+{
+       /* Never used with input 0 */
+       FLAC__ASSERT(v > 0);
+#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+       return __builtin_clzll(v);
+#elif (defined(__INTEL_COMPILER) || defined(_MSC_VER)) && (defined(_M_IA64) || defined(_M_X64))
+       {
+               unsigned long idx;
+               _BitScanReverse64(&idx, v);
+               return idx ^ 63U;
+       }
+#else
+       return FLAC__clz_soft_uint64(v);
+#endif
+}
+
+/* These two functions work with input 0 */
+static inline unsigned int FLAC__clz2_uint32(FLAC__uint32 v)
+{
+       if (!v)
+               return 32;
+       return FLAC__clz_uint32(v);
+}
+
+static inline unsigned int FLAC__clz2_uint64(FLAC__uint64 v)
+{
+       if (!v)
+               return 64;
+       return FLAC__clz_uint64(v);
+}
+
+/* An example of what FLAC__bitmath_ilog2() computes:
+ *
+ * ilog2( 0) = assertion failure
+ * ilog2( 1) = 0
+ * ilog2( 2) = 1
+ * ilog2( 3) = 1
+ * ilog2( 4) = 2
+ * ilog2( 5) = 2
+ * ilog2( 6) = 2
+ * ilog2( 7) = 2
+ * ilog2( 8) = 3
+ * ilog2( 9) = 3
+ * ilog2(10) = 3
+ * ilog2(11) = 3
+ * ilog2(12) = 3
+ * ilog2(13) = 3
+ * ilog2(14) = 3
+ * ilog2(15) = 3
+ * ilog2(16) = 4
+ * ilog2(17) = 4
+ * ilog2(18) = 4
+ */
+
+static inline unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
+{
+       FLAC__ASSERT(v > 0);
+#if defined(__INTEL_COMPILER)
+       return _bit_scan_reverse(v);
+#elif defined(_MSC_VER)
+       {
+               unsigned long idx;
+               _BitScanReverse(&idx, v);
+               return idx;
+       }
+#else
+       return FLAC__clz_uint32(v) ^ 31U;
+#endif
+}
+
+static inline unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
+{
+       FLAC__ASSERT(v > 0);
+#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+       return __builtin_clzll(v) ^ 63U;
+/* Sorry, only supported in x64/Itanium.. and both have fast FPU which makes integer-only encoder pointless */
+#elif (defined(__INTEL_COMPILER) || defined(_MSC_VER)) && (defined(_M_IA64) || defined(_M_X64))
+       {
+               unsigned long idx;
+               _BitScanReverse64(&idx, v);
+               return idx;
+       }
+#else
+/*  Brain-damaged compilers will use the fastest possible way that is,
+       de Bruijn sequences (http://supertech.csail.mit.edu/papers/debruijn.pdf)
+       (C) Timothy B. Terriberry (tterribe@xiph.org) 2001-2009 CC0 (Public domain).
+*/
+       {
+               static const unsigned char DEBRUIJN_IDX64[64]={
+                       0, 1, 2, 7, 3,13, 8,19, 4,25,14,28, 9,34,20,40,
+                       5,17,26,38,15,46,29,48,10,31,35,54,21,50,41,57,
+                       63, 6,12,18,24,27,33,39,16,37,45,47,30,53,49,56,
+                       62,11,23,32,36,44,52,55,61,22,43,51,60,42,59,58
+               };
+               v|= v>>1;
+               v|= v>>2;
+               v|= v>>4;
+               v|= v>>8;
+               v|= v>>16;
+               v|= v>>32;
+               v= (v>>1)+1;
+               return DEBRUIJN_IDX64[v*FLAC__U64L(0x218A392CD3D5DBF)>>58&0x3F];
+       }
+#endif
+}
+
+unsigned FLAC__bitmath_silog2(FLAC__int64 v);
+
+#endif
diff --git a/FLAC/src/private/bitreader.h b/FLAC/src/private/bitreader.h
new file mode 100644 (file)
index 0000000..7c73165
--- /dev/null
@@ -0,0 +1,91 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__BITREADER_H
+#define FLAC__PRIVATE__BITREADER_H
+
+#include <stdio.h> /* for FILE */
+#include "FLAC/ordinals.h"
+#include "cpu.h"
+
+/*
+ * opaque structure definition
+ */
+struct FLAC__BitReader;
+typedef struct FLAC__BitReader FLAC__BitReader;
+
+typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
+
+/*
+ * construction, deletion, initialization, etc functions
+ */
+FLAC__BitReader *FLAC__bitreader_new(void);
+void FLAC__bitreader_delete(FLAC__BitReader *br);
+FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__BitReaderReadCallback rcb, void *cd);
+void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
+FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
+void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
+
+/*
+ * CRC functions
+ */
+void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
+FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
+
+/*
+ * info functions
+ */
+FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
+unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
+unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
+
+/*
+ * read functions
+ */
+
+FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
+FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
+FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
+FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
+FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
+FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
+FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
+FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
+FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
+FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
+#if 0 /* UNUSED */
+FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
+FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
+#endif
+FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
+FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
+#endif
diff --git a/FLAC/src/private/bitwriter.h b/FLAC/src/private/bitwriter.h
new file mode 100644 (file)
index 0000000..ef3ad1b
--- /dev/null
@@ -0,0 +1,104 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__BITWRITER_H
+#define FLAC__PRIVATE__BITWRITER_H
+
+#include <stdio.h> /* for FILE */
+#include "FLAC/ordinals.h"
+
+/*
+ * opaque structure definition
+ */
+struct FLAC__BitWriter;
+typedef struct FLAC__BitWriter FLAC__BitWriter;
+
+/*
+ * construction, deletion, initialization, etc functions
+ */
+FLAC__BitWriter *FLAC__bitwriter_new(void);
+void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
+FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
+void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
+void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
+void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
+
+/*
+ * CRC functions
+ *
+ * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
+ */
+FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
+FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
+
+/*
+ * info functions
+ */
+FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
+unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
+
+/*
+ * direct buffer access
+ *
+ * there may be no calls on the bitwriter between get and release.
+ * the bitwriter continues to own the returned buffer.
+ * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
+ */
+FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
+void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
+
+/*
+ * write functions
+ */
+FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
+FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
+FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
+FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
+FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
+FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
+FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
+unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
+#if 0 /* UNUSED */
+unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
+unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
+#endif
+FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
+FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
+#if 0 /* UNUSED */
+FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
+FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
+#endif
+FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
+FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
+FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
+
+#endif
diff --git a/FLAC/src/private/cpu.h b/FLAC/src/private/cpu.h
new file mode 100644 (file)
index 0000000..7c65180
--- /dev/null
@@ -0,0 +1,186 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__CPU_H
+#define FLAC__PRIVATE__CPU_H
+
+#include "FLAC/ordinals.h"
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifndef FLAC__CPU_X86_64
+
+#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
+#define FLAC__CPU_X86_64
+#endif
+
+#endif
+
+#ifndef FLAC__CPU_IA32
+
+#if defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) ||defined( __i386) || defined(_M_IX86)
+#define FLAC__CPU_IA32
+#endif
+
+#endif
+
+
+#if FLAC__HAS_X86INTRIN
+/* SSE intrinsics support by ICC/MSVC/GCC */
+#if defined __INTEL_COMPILER
+  #define FLAC__SSE_TARGET(x)
+  #define FLAC__SSE_SUPPORTED 1
+  #define FLAC__SSE2_SUPPORTED 1
+  #if (__INTEL_COMPILER >= 1000) /* Intel C++ Compiler 10.0 */
+    #define FLAC__SSSE3_SUPPORTED 1
+    #define FLAC__SSE4_1_SUPPORTED 1
+  #endif
+  #if (__INTEL_COMPILER >= 1110) /* Intel C++ Compiler 11.1 */
+    #define FLAC__AVX_SUPPORTED 1
+  #endif
+  #if (__INTEL_COMPILER >= 1300) /* Intel C++ Compiler 13.0 */
+    #define FLAC__AVX2_SUPPORTED 1
+    #define FLAC__FMA_SUPPORTED 1
+  #endif
+#elif defined _MSC_VER
+  #define FLAC__SSE_TARGET(x)
+  #define FLAC__SSE_SUPPORTED 1
+  #define FLAC__SSE2_SUPPORTED 1
+  #if (_MSC_VER >= 1500) /* MS Visual Studio 2008 */
+    #define FLAC__SSSE3_SUPPORTED 1
+    #define FLAC__SSE4_1_SUPPORTED 1
+  #endif
+  #if (_MSC_FULL_VER >= 160040219) /* MS Visual Studio 2010 SP1 */
+    #define FLAC__AVX_SUPPORTED 1
+  #endif
+  #if (_MSC_VER >= 1700) /* MS Visual Studio 2012 */
+    #define FLAC__AVX2_SUPPORTED 1
+    #define FLAC__FMA_SUPPORTED 1
+  #endif
+#elif defined __GNUC__
+  #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) /* since GCC 4.9 -msse.. compiler options aren't necessary */
+    #define FLAC__SSE_TARGET(x) __attribute__ ((__target__ (x)))
+    #define FLAC__SSE_SUPPORTED 1
+    #define FLAC__SSE2_SUPPORTED 1
+    #define FLAC__SSSE3_SUPPORTED 1
+    #define FLAC__SSE4_1_SUPPORTED 1
+#ifdef FLAC__USE_AVX
+    #define FLAC__AVX_SUPPORTED 1
+    #define FLAC__AVX2_SUPPORTED 1
+    #define FLAC__FMA_SUPPORTED 1
+#endif
+  #else /* for GCC older than 4.9 */
+    #define FLAC__SSE_TARGET(x)
+    #ifdef __SSE__
+      #define FLAC__SSE_SUPPORTED 1
+    #endif
+    #ifdef __SSE2__
+      #define FLAC__SSE2_SUPPORTED 1
+    #endif
+    #ifdef __SSSE3__
+      #define FLAC__SSSE3_SUPPORTED 1
+    #endif
+    #ifdef __SSE4_1__
+      #define FLAC__SSE4_1_SUPPORTED 1
+    #endif
+    #ifdef __AVX__
+      #define FLAC__AVX_SUPPORTED 1
+    #endif
+    #ifdef __AVX2__
+      #define FLAC__AVX2_SUPPORTED 1
+    #endif
+    #ifdef __FMA__
+      #define FLAC__FMA_SUPPORTED 1
+    #endif
+  #endif /* GCC version */
+#endif /* compiler version */
+#endif /* intrinsics support */
+
+
+#ifndef FLAC__AVX_SUPPORTED
+#define FLAC__AVX_SUPPORTED 0
+#endif
+
+typedef enum {
+       FLAC__CPUINFO_TYPE_IA32,
+       FLAC__CPUINFO_TYPE_X86_64,
+       FLAC__CPUINFO_TYPE_UNKNOWN
+} FLAC__CPUInfo_Type;
+
+typedef struct {
+       FLAC__bool intel;
+
+       FLAC__bool cmov;
+       FLAC__bool mmx;
+       FLAC__bool sse;
+       FLAC__bool sse2;
+
+       FLAC__bool sse3;
+       FLAC__bool ssse3;
+       FLAC__bool sse41;
+       FLAC__bool sse42;
+       FLAC__bool avx;
+       FLAC__bool avx2;
+       FLAC__bool fma;
+} FLAC__CPUInfo_IA32;
+
+typedef struct {
+       FLAC__bool intel;
+
+       FLAC__bool sse3;
+       FLAC__bool ssse3;
+       FLAC__bool sse41;
+       FLAC__bool sse42;
+       FLAC__bool avx;
+       FLAC__bool avx2;
+       FLAC__bool fma;
+} FLAC__CPUInfo_x86;
+
+
+typedef struct {
+       FLAC__bool use_asm;
+       FLAC__CPUInfo_Type type;
+       FLAC__CPUInfo_IA32 ia32;
+       FLAC__CPUInfo_x86 x86;
+} FLAC__CPUInfo;
+
+void FLAC__cpu_info(FLAC__CPUInfo *info);
+
+FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
+
+void         FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
+
+void         FLAC__cpu_info_x86(FLAC__uint32 level, FLAC__uint32 *eax, FLAC__uint32 *ebx, FLAC__uint32 *ecx, FLAC__uint32 *edx);
+
+#endif
diff --git a/FLAC/src/private/crc.h b/FLAC/src/private/crc.h
new file mode 100644 (file)
index 0000000..294f60e
--- /dev/null
@@ -0,0 +1,62 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__CRC_H
+#define FLAC__PRIVATE__CRC_H
+
+#include "FLAC/ordinals.h"
+
+/* 8 bit CRC generator, MSB shifted first
+** polynomial = x^8 + x^2 + x^1 + x^0
+** init = 0
+*/
+extern FLAC__byte const FLAC__crc8_table[256];
+#define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
+void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
+void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
+FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
+
+/* 16 bit CRC generator, MSB shifted first
+** polynomial = x^16 + x^15 + x^2 + x^0
+** init = 0
+*/
+extern unsigned const FLAC__crc16_table[256];
+
+#define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)])
+/* this alternate may be faster on some systems/compilers */
+#if 0
+#define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
+#endif
+
+unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
+
+#endif
diff --git a/FLAC/src/private/fixed.h b/FLAC/src/private/fixed.h
new file mode 100644 (file)
index 0000000..68cdfce
--- /dev/null
@@ -0,0 +1,107 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__FIXED_H
+#define FLAC__PRIVATE__FIXED_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "private/cpu.h"
+#include "private/float.h"
+#include "FLAC/format.h"
+
+/*
+ *     FLAC__fixed_compute_best_predictor()
+ *     --------------------------------------------------------------------
+ *     Compute the best fixed predictor and the expected bits-per-sample
+ *  of the residual signal for each order.  The _wide() version uses
+ *  64-bit integers which is statistically necessary when bits-per-
+ *  sample + log2(blocksize) > 30
+ *
+ *     IN data[0,data_len-1]
+ *     IN data_len
+ *     OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
+ */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+# ifndef FLAC__NO_ASM
+#  if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#   ifdef FLAC__SSE2_SUPPORTED
+unsigned FLAC__fixed_compute_best_predictor_intrin_sse2(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1]);
+unsigned FLAC__fixed_compute_best_predictor_wide_intrin_sse2(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1]);
+#   endif
+#   ifdef FLAC__SSSE3_SUPPORTED
+unsigned FLAC__fixed_compute_best_predictor_intrin_ssse3(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+unsigned FLAC__fixed_compute_best_predictor_wide_intrin_ssse3(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER + 1]);
+#   endif
+#  endif
+#  if defined FLAC__CPU_IA32 && defined FLAC__HAS_NASM
+unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+#  endif
+# endif
+#else
+unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+#endif
+
+/*
+ *     FLAC__fixed_compute_residual()
+ *     --------------------------------------------------------------------
+ *     Compute the residual signal obtained from sutracting the predicted
+ *     signal from the original.
+ *
+ *     IN data[-order,data_len-1]        original signal (NOTE THE INDICES!)
+ *     IN data_len                       length of original signal
+ *     IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
+ *     OUT residual[0,data_len-1]        residual signal
+ */
+void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
+
+/*
+ *     FLAC__fixed_restore_signal()
+ *     --------------------------------------------------------------------
+ *     Restore the original signal by summing the residual and the
+ *     predictor.
+ *
+ *     IN residual[0,data_len-1]         residual signal
+ *     IN data_len                       length of original signal
+ *     IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
+ *     *** IMPORTANT: the caller must pass in the historical samples:
+ *     IN  data[-order,-1]               previously-reconstructed historical samples
+ *     OUT data[0,data_len-1]            original signal
+ */
+void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
+
+#endif
diff --git a/FLAC/src/private/float.h b/FLAC/src/private/float.h
new file mode 100644 (file)
index 0000000..12ece60
--- /dev/null
@@ -0,0 +1,95 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__FLOAT_H
+#define FLAC__PRIVATE__FLOAT_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "FLAC/ordinals.h"
+
+/*
+ * All the code in libFLAC that uses float and double
+ * should be protected by checks of the macro
+ * FLAC__INTEGER_ONLY_LIBRARY.
+ *
+ */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+/*
+ * FLAC__real is the basic floating point type used in LPC analysis.
+ *
+ * WATCHOUT: changing FLAC__real will change the signatures of many
+ * functions that have assembly language equivalents and break them.
+ */
+typedef float FLAC__real;
+#else
+/*
+ * The convention for FLAC__fixedpoint is to use the upper 16 bits
+ * for the integer part and lower 16 bits for the fractional part.
+ */
+typedef FLAC__int32 FLAC__fixedpoint;
+extern const FLAC__fixedpoint FLAC__FP_ZERO;
+extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
+extern const FLAC__fixedpoint FLAC__FP_ONE;
+extern const FLAC__fixedpoint FLAC__FP_LN2;
+extern const FLAC__fixedpoint FLAC__FP_E;
+
+#define FLAC__fixedpoint_trunc(x) ((x)>>16)
+
+#define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
+
+#define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
+
+/*
+ *     FLAC__fixedpoint_log2()
+ *     --------------------------------------------------------------------
+ *     Returns the base-2 logarithm of the fixed-point number 'x' using an
+ *     algorithm by Knuth for x >= 1.0
+ *
+ *     'fracbits' is the number of fractional bits of 'x'.  'fracbits' must
+ *     be < 32 and evenly divisible by 4 (0 is OK but not very precise).
+ *
+ *     'precision' roughly limits the number of iterations that are done;
+ *     use (unsigned)(-1) for maximum precision.
+ *
+ *     If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
+ *     function will punt and return 0.
+ *
+ *     The return value will also have 'fracbits' fractional bits.
+ */
+FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
+
+#endif
+
+#endif
diff --git a/FLAC/src/private/format.h b/FLAC/src/private/format.h
new file mode 100644 (file)
index 0000000..5b9cfbd
--- /dev/null
@@ -0,0 +1,45 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__FORMAT_H
+#define FLAC__PRIVATE__FORMAT_H
+
+#include "FLAC/format.h"
+
+unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
+unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
+unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
+void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
+void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
+FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
+
+#endif
diff --git a/FLAC/src/private/lpc.h b/FLAC/src/private/lpc.h
new file mode 100644 (file)
index 0000000..6eb02be
--- /dev/null
@@ -0,0 +1,250 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__LPC_H
+#define FLAC__PRIVATE__LPC_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "private/cpu.h"
+#include "private/float.h"
+#include "FLAC/format.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+/*
+ *     FLAC__lpc_window_data()
+ *     --------------------------------------------------------------------
+ *     Applies the given window to the data.
+ *  OPT: asm implementation
+ *
+ *     IN in[0,data_len-1]
+ *     IN window[0,data_len-1]
+ *     OUT out[0,lag-1]
+ *     IN data_len
+ */
+void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
+
+/*
+ *     FLAC__lpc_compute_autocorrelation()
+ *     --------------------------------------------------------------------
+ *     Compute the autocorrelation for lags between 0 and lag-1.
+ *     Assumes data[] outside of [0,data_len-1] == 0.
+ *     Asserts that lag > 0.
+ *
+ *     IN data[0,data_len-1]
+ *     IN data_len
+ *     IN 0 < lag <= data_len
+ *     OUT autoc[0,lag-1]
+ */
+void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+#ifndef FLAC__NO_ASM
+#  ifdef FLAC__CPU_IA32
+#    ifdef FLAC__HAS_NASM
+void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+#    endif
+#  endif
+#  if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#    ifdef FLAC__SSE_SUPPORTED
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+void FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+#    endif
+#  endif
+#endif
+
+/*
+ *     FLAC__lpc_compute_lp_coefficients()
+ *     --------------------------------------------------------------------
+ *     Computes LP coefficients for orders 1..max_order.
+ *     Do not call if autoc[0] == 0.0.  This means the signal is zero
+ *     and there is no point in calculating a predictor.
+ *
+ *     IN autoc[0,max_order]                      autocorrelation values
+ *     IN 0 < max_order <= FLAC__MAX_LPC_ORDER    max LP order to compute
+ *     OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
+ *     *** IMPORTANT:
+ *     *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
+ *     OUT error[0,max_order-1]                   error for each order (more
+ *                                                specifically, the variance of
+ *                                                the error signal times # of
+ *                                                samples in the signal)
+ *
+ *     Example: if max_order is 9, the LP coefficients for order 9 will be
+ *              in lp_coeff[8][0,8], the LP coefficients for order 8 will be
+ *                      in lp_coeff[7][0,7], etc.
+ */
+void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], double error[]);
+
+/*
+ *     FLAC__lpc_quantize_coefficients()
+ *     --------------------------------------------------------------------
+ *     Quantizes the LP coefficients.  NOTE: precision + bits_per_sample
+ *     must be less than 32 (sizeof(FLAC__int32)*8).
+ *
+ *     IN lp_coeff[0,order-1]    LP coefficients
+ *     IN order                  LP order
+ *     IN FLAC__MIN_QLP_COEFF_PRECISION < precision
+ *                               desired precision (in bits, including sign
+ *                               bit) of largest coefficient
+ *     OUT qlp_coeff[0,order-1]  quantized coefficients
+ *     OUT shift                 # of bits to shift right to get approximated
+ *                               LP coefficients.  NOTE: could be negative.
+ *     RETURN 0 => quantization OK
+ *            1 => coefficients require too much shifting for *shift to
+ *              fit in the LPC subframe header.  'shift' is unset.
+ *         2 => coefficients are all zero, which is bad.  'shift' is
+ *              unset.
+ */
+int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
+
+/*
+ *     FLAC__lpc_compute_residual_from_qlp_coefficients()
+ *     --------------------------------------------------------------------
+ *     Compute the residual signal obtained from sutracting the predicted
+ *     signal from the original.
+ *
+ *     IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
+ *     IN data_len                length of original signal
+ *     IN qlp_coeff[0,order-1]    quantized LP coefficients
+ *     IN order > 0               LP order
+ *     IN lp_quantization         quantization of LP coefficients in bits
+ *     OUT residual[0,data_len-1] residual signal
+ */
+void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#ifndef FLAC__NO_ASM
+#  ifdef FLAC__CPU_IA32
+#    ifdef FLAC__HAS_NASM
+void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#    endif
+#  endif
+#  if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#    ifdef FLAC__SSE2_SUPPORTED
+void FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#    endif
+#    ifdef FLAC__SSE4_1_SUPPORTED
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#    endif
+#    ifdef FLAC__AVX2_SUPPORTED
+void FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+void FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#    endif
+#  endif
+#endif
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
+
+/*
+ *     FLAC__lpc_restore_signal()
+ *     --------------------------------------------------------------------
+ *     Restore the original signal by summing the residual and the
+ *     predictor.
+ *
+ *     IN residual[0,data_len-1]  residual signal
+ *     IN data_len                length of original signal
+ *     IN qlp_coeff[0,order-1]    quantized LP coefficients
+ *     IN order > 0               LP order
+ *     IN lp_quantization         quantization of LP coefficients in bits
+ *     *** IMPORTANT: the caller must pass in the historical samples:
+ *     IN  data[-order,-1]        previously-reconstructed historical samples
+ *     OUT data[0,data_len-1]     original signal
+ */
+void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+#ifndef FLAC__NO_ASM
+#  ifdef FLAC__CPU_IA32
+#    ifdef FLAC__HAS_NASM
+void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+void FLAC__lpc_restore_signal_wide_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+#    endif /* FLAC__HAS_NASM */
+#  endif /* FLAC__CPU_IA32 */
+#  if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#    ifdef FLAC__SSE2_SUPPORTED
+void FLAC__lpc_restore_signal_16_intrin_sse2(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+#    endif
+#    ifdef FLAC__SSE4_1_SUPPORTED
+void FLAC__lpc_restore_signal_wide_intrin_sse41(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+#    endif
+#  endif
+#endif /* FLAC__NO_ASM */
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+/*
+ *     FLAC__lpc_compute_expected_bits_per_residual_sample()
+ *     --------------------------------------------------------------------
+ *     Compute the expected number of bits per residual signal sample
+ *     based on the LP error (which is related to the residual variance).
+ *
+ *     IN lpc_error >= 0.0   error returned from calculating LP coefficients
+ *     IN total_samples > 0  # of samples in residual signal
+ *     RETURN                expected bits per sample
+ */
+double FLAC__lpc_compute_expected_bits_per_residual_sample(double lpc_error, unsigned total_samples);
+double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(double lpc_error, double error_scale);
+
+/*
+ *     FLAC__lpc_compute_best_order()
+ *     --------------------------------------------------------------------
+ *     Compute the best order from the array of signal errors returned
+ *     during coefficient computation.
+ *
+ *     IN lpc_error[0,max_order-1] >= 0.0  error returned from calculating LP coefficients
+ *     IN max_order > 0                    max LP order
+ *     IN total_samples > 0                # of samples in residual signal
+ *     IN overhead_bits_per_order          # of bits overhead for each increased LP order
+ *                                         (includes warmup sample size and quantized LP coefficient)
+ *     RETURN [1,max_order]                best order
+ */
+unsigned FLAC__lpc_compute_best_order(const double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
+
+#endif
diff --git a/FLAC/src/private/macros.h b/FLAC/src/private/macros.h
new file mode 100644 (file)
index 0000000..becc59f
--- /dev/null
@@ -0,0 +1,72 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2012-2016  Xiph.org Foundation
+ *
+ * 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 FLAC__PRIVATE__MACROS_H
+#define FLAC__PRIVATE__MACROS_H
+
+#if defined(__GNUC__) && (__GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 3))
+
+#define flac_max(a,b) \
+       ({ __typeof__ (a) _a = (a); \
+       __typeof__ (b) _b = (b); \
+       _a > _b ? _a : _b; })
+
+#define MIN_PASTE(A,B) A##B
+#define MIN_IMPL(A,B,L) ({ \
+       __typeof__(A) MIN_PASTE(__a,L) = (A); \
+       __typeof__(B) MIN_PASTE(__b,L) = (B); \
+       MIN_PASTE(__a,L) < MIN_PASTE(__b,L) ? MIN_PASTE(__a,L) : MIN_PASTE(__b,L); \
+       })
+
+#define flac_min(A,B) MIN_IMPL(A,B,__COUNTER__)
+
+/* Whatever other unix that has sys/param.h */
+#elif defined(HAVE_SYS_PARAM_H)
+#include <sys/param.h>
+#define flac_max(a,b) MAX(a,b)
+#define flac_min(a,b) MIN(a,b)
+
+/* Windows VS has them in stdlib.h.. XXX:Untested */
+#elif defined(_MSC_VER)
+#include <stdlib.h>
+#define flac_max(a,b) __max(a,b)
+#define flac_min(a,b) __min(a,b)
+#endif
+
+#ifndef MIN
+#define MIN(x,y)       ((x) <= (y) ? (x) : (y))
+#endif
+
+#ifndef MAX
+#define MAX(x,y)       ((x) >= (y) ? (x) : (y))
+#endif
+
+#endif
diff --git a/FLAC/src/private/md5.h b/FLAC/src/private/md5.h
new file mode 100644 (file)
index 0000000..c665ab3
--- /dev/null
@@ -0,0 +1,50 @@
+#ifndef FLAC__PRIVATE__MD5_H
+#define FLAC__PRIVATE__MD5_H
+
+/*
+ * This is the header file for the MD5 message-digest algorithm.
+ * The algorithm is due to Ron Rivest.  This code was
+ * written by Colin Plumb in 1993, no copyright is claimed.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is equivalent,
+ * except that you don't need to include two pages of legalese
+ * with every copy.
+ *
+ * To compute the message digest of a chunk of bytes, declare an
+ * MD5Context structure, pass it to MD5Init, call MD5Update as
+ * needed on buffers full of bytes, and then call MD5Final, which
+ * will fill a supplied 16-byte array with the digest.
+ *
+ * Changed so as no longer to depend on Colin Plumb's `usual.h'
+ * header definitions; now uses stuff from dpkg's config.h
+ *  - Ian Jackson <ijackson@nyx.cs.du.edu>.
+ * Still in the public domain.
+ *
+ * Josh Coalson: made some changes to integrate with libFLAC.
+ * Still in the public domain, with no warranty.
+ */
+
+#include "FLAC/ordinals.h"
+
+typedef union {
+       FLAC__byte *p8;
+       FLAC__int16 *p16;
+       FLAC__int32 *p32;
+} FLAC__multibyte;
+
+typedef struct {
+       FLAC__uint32 in[16];
+       FLAC__uint32 buf[4];
+       FLAC__uint32 bytes[2];
+       FLAC__multibyte internal_buf;
+       size_t capacity;
+} FLAC__MD5Context;
+
+void FLAC__MD5Init(FLAC__MD5Context *context);
+void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
+
+FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
+
+#endif
diff --git a/FLAC/src/private/memory.h b/FLAC/src/private/memory.h
new file mode 100644 (file)
index 0000000..f103c53
--- /dev/null
@@ -0,0 +1,58 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__MEMORY_H
+#define FLAC__PRIVATE__MEMORY_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h> /* for size_t */
+
+#include "private/float.h"
+#include "FLAC/ordinals.h" /* for FLAC__bool */
+
+/* Returns the unaligned address returned by malloc.
+ * Use free() on this address to deallocate.
+ */
+void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
+FLAC__bool FLAC__memory_alloc_aligned_int32_array(size_t elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
+FLAC__bool FLAC__memory_alloc_aligned_uint32_array(size_t elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
+FLAC__bool FLAC__memory_alloc_aligned_uint64_array(size_t elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
+FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(size_t elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+FLAC__bool FLAC__memory_alloc_aligned_real_array(size_t elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
+#endif
+void *safe_malloc_mul_2op_p(size_t size1, size_t size2);
+
+#endif
diff --git a/FLAC/src/private/metadata.h b/FLAC/src/private/metadata.h
new file mode 100644 (file)
index 0000000..161947f
--- /dev/null
@@ -0,0 +1,46 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__METADATA_H
+#define FLAC__PRIVATE__METADATA_H
+
+#include "FLAC/metadata.h"
+
+/* WATCHOUT: all malloc()ed data in the block is free()ed; this may not
+ * be a consistent state (e.g. PICTURE) or equivalent to the initial
+ * state after FLAC__metadata_object_new()
+ */
+void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object);
+
+void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object);
+
+#endif
diff --git a/FLAC/src/private/ogg_decoder_aspect.h b/FLAC/src/private/ogg_decoder_aspect.h
new file mode 100644 (file)
index 0000000..218f44e
--- /dev/null
@@ -0,0 +1,80 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__OGG_DECODER_ASPECT_H
+#define FLAC__PRIVATE__OGG_DECODER_ASPECT_H
+
+#include <ogg/ogg.h>
+
+#include "FLAC/ordinals.h"
+#include "FLAC/stream_decoder.h" /* for FLAC__StreamDecoderReadStatus */
+
+typedef struct FLAC__OggDecoderAspect {
+       /* these are storage for values that can be set through the API */
+       FLAC__bool use_first_serial_number;
+       long serial_number;
+
+       /* these are for internal state related to Ogg decoding */
+       ogg_stream_state stream_state;
+       ogg_sync_state sync_state;
+       unsigned version_major, version_minor;
+       FLAC__bool need_serial_number;
+       FLAC__bool end_of_stream;
+       FLAC__bool have_working_page; /* only if true will the following vars be valid */
+       ogg_page working_page;
+       FLAC__bool have_working_packet; /* only if true will the following vars be valid */
+       ogg_packet working_packet; /* as we work through the packet we will move working_packet.packet forward and working_packet.bytes down */
+} FLAC__OggDecoderAspect;
+
+void FLAC__ogg_decoder_aspect_set_serial_number(FLAC__OggDecoderAspect *aspect, long value);
+void FLAC__ogg_decoder_aspect_set_defaults(FLAC__OggDecoderAspect *aspect);
+FLAC__bool FLAC__ogg_decoder_aspect_init(FLAC__OggDecoderAspect *aspect);
+void FLAC__ogg_decoder_aspect_finish(FLAC__OggDecoderAspect *aspect);
+void FLAC__ogg_decoder_aspect_flush(FLAC__OggDecoderAspect *aspect);
+void FLAC__ogg_decoder_aspect_reset(FLAC__OggDecoderAspect *aspect);
+
+typedef enum {
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK = 0,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR,
+       FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR
+} FLAC__OggDecoderAspectReadStatus;
+
+typedef FLAC__OggDecoderAspectReadStatus (*FLAC__OggDecoderAspectReadCallbackProxy)(const void *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+
+FLAC__OggDecoderAspectReadStatus FLAC__ogg_decoder_aspect_read_callback_wrapper(FLAC__OggDecoderAspect *aspect, FLAC__byte buffer[], size_t *bytes, FLAC__OggDecoderAspectReadCallbackProxy read_callback, const FLAC__StreamDecoder *decoder, void *client_data);
+
+#endif
diff --git a/FLAC/src/private/ogg_encoder_aspect.h b/FLAC/src/private/ogg_encoder_aspect.h
new file mode 100644 (file)
index 0000000..f55ef32
--- /dev/null
@@ -0,0 +1,63 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__OGG_ENCODER_ASPECT_H
+#define FLAC__PRIVATE__OGG_ENCODER_ASPECT_H
+
+#include <ogg/ogg.h>
+
+#include "FLAC/ordinals.h"
+#include "FLAC/stream_encoder.h" /* for FLAC__StreamEncoderWriteStatus */
+
+typedef struct FLAC__OggEncoderAspect {
+       /* these are storage for values that can be set through the API */
+       long serial_number;
+       unsigned num_metadata;
+
+       /* these are for internal state related to Ogg encoding */
+       ogg_stream_state stream_state;
+       ogg_page page;
+       FLAC__bool seen_magic; /* true if we've seen the fLaC magic in the write callback yet */
+       FLAC__bool is_first_packet;
+       FLAC__uint64 samples_written;
+} FLAC__OggEncoderAspect;
+
+void FLAC__ogg_encoder_aspect_set_serial_number(FLAC__OggEncoderAspect *aspect, long value);
+FLAC__bool FLAC__ogg_encoder_aspect_set_num_metadata(FLAC__OggEncoderAspect *aspect, unsigned value);
+void FLAC__ogg_encoder_aspect_set_defaults(FLAC__OggEncoderAspect *aspect);
+FLAC__bool FLAC__ogg_encoder_aspect_init(FLAC__OggEncoderAspect *aspect);
+void FLAC__ogg_encoder_aspect_finish(FLAC__OggEncoderAspect *aspect);
+
+typedef FLAC__StreamEncoderWriteStatus (*FLAC__OggEncoderAspectWriteCallbackProxy)(const void *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
+
+FLAC__StreamEncoderWriteStatus FLAC__ogg_encoder_aspect_write_callback_wrapper(FLAC__OggEncoderAspect *aspect, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, FLAC__bool is_last_block, FLAC__OggEncoderAspectWriteCallbackProxy write_callback, void *encoder, void *client_data);
+#endif
diff --git a/FLAC/src/private/ogg_helper.h b/FLAC/src/private/ogg_helper.h
new file mode 100644 (file)
index 0000000..4c1000c
--- /dev/null
@@ -0,0 +1,44 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__OGG_HELPER_H
+#define FLAC__PRIVATE__OGG_HELPER_H
+
+#include <ogg/ogg.h>
+#include "FLAC/stream_encoder.h" /* for FLAC__StreamEncoder */
+
+void simple_ogg_page__init(ogg_page *page);
+void simple_ogg_page__clear(ogg_page *page);
+FLAC__bool simple_ogg_page__get_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderReadCallback read_callback, void *client_data);
+FLAC__bool simple_ogg_page__set_at(FLAC__StreamEncoder *encoder, FLAC__uint64 position, ogg_page *page, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderWriteCallback write_callback, void *client_data);
+
+#endif
diff --git a/FLAC/src/private/ogg_mapping.h b/FLAC/src/private/ogg_mapping.h
new file mode 100644 (file)
index 0000000..1fa022d
--- /dev/null
@@ -0,0 +1,64 @@
+/* libFLAC - Free Lossless Audio Codec
+ * Copyright (C) 2004-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__OGG_MAPPING_H
+#define FLAC__PRIVATE__OGG_MAPPING_H
+
+#include "FLAC/ordinals.h"
+
+/** The length of the packet type field in bytes. */
+#define FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH (1u)
+
+extern const unsigned FLAC__OGG_MAPPING_PACKET_TYPE_LEN; /* = 8 bits */
+
+extern const FLAC__byte FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE; /* = 0x7f */
+
+/** The length of the 'FLAC' magic in bytes. */
+#define FLAC__OGG_MAPPING_MAGIC_LENGTH (4u)
+
+extern const FLAC__byte * const FLAC__OGG_MAPPING_MAGIC; /* = "FLAC" */
+
+extern const unsigned FLAC__OGG_MAPPING_VERSION_MAJOR_LEN; /* = 8 bits */
+extern const unsigned FLAC__OGG_MAPPING_VERSION_MINOR_LEN; /* = 8 bits */
+
+/** The length of the Ogg FLAC mapping major version number in bytes. */
+#define FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH (1u)
+
+/** The length of the Ogg FLAC mapping minor version number in bytes. */
+#define FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH (1u)
+
+extern const unsigned FLAC__OGG_MAPPING_NUM_HEADERS_LEN; /* = 16 bits */
+
+/** The length of the #-of-header-packets number bytes. */
+#define FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH (2u)
+
+#endif
diff --git a/FLAC/src/private/stream_encoder.h b/FLAC/src/private/stream_encoder.h
new file mode 100644 (file)
index 0000000..ab1721f
--- /dev/null
@@ -0,0 +1,67 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__STREAM_ENCODER_H
+#define FLAC__PRIVATE__STREAM_ENCODER_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+/*
+ * This is used to avoid overflow with unusual signals in 32-bit
+ * accumulator in the *precompute_partition_info_sums_* functions.
+ */
+#define FLAC__MAX_EXTRA_RESIDUAL_BPS 4
+
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && defined FLAC__HAS_X86INTRIN
+#include "private/cpu.h"
+#include "FLAC/format.h"
+
+#ifdef FLAC__SSE2_SUPPORTED
+extern void FLAC__precompute_partition_info_sums_intrin_sse2(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+                       unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
+#endif
+
+#ifdef FLAC__SSSE3_SUPPORTED
+extern void FLAC__precompute_partition_info_sums_intrin_ssse3(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+                       unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
+#endif
+
+#ifdef FLAC__AVX2_SUPPORTED
+extern void FLAC__precompute_partition_info_sums_intrin_avx2(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+                       unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
+#endif
+
+#endif
+
+#endif
diff --git a/FLAC/src/private/stream_encoder_framing.h b/FLAC/src/private/stream_encoder_framing.h
new file mode 100644 (file)
index 0000000..f633a9d
--- /dev/null
@@ -0,0 +1,46 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
+#define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
+
+#include "FLAC/format.h"
+#include "bitwriter.h"
+
+FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
+FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
+FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
+FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
+FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
+FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
+
+#endif
diff --git a/FLAC/src/private/window.h b/FLAC/src/private/window.h
new file mode 100644 (file)
index 0000000..bfed774
--- /dev/null
@@ -0,0 +1,74 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2006-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PRIVATE__WINDOW_H
+#define FLAC__PRIVATE__WINDOW_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "private/float.h"
+#include "FLAC/format.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+/*
+ *     FLAC__window_*()
+ *     --------------------------------------------------------------------
+ *     Calculates window coefficients according to different apodization
+ *     functions.
+ *
+ *     OUT window[0,L-1]
+ *     IN L (number of points in window)
+ */
+void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
+void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
+void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
+void FLAC__window_partial_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p, const FLAC__real start, const FLAC__real end);
+void FLAC__window_punchout_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p, const FLAC__real start, const FLAC__real end);
+void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
+
+#endif
diff --git a/FLAC/src/protected/all.h b/FLAC/src/protected/all.h
new file mode 100644 (file)
index 0000000..9468bd3
--- /dev/null
@@ -0,0 +1,39 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PROTECTED__ALL_H
+#define FLAC__PROTECTED__ALL_H
+
+#include "stream_decoder.h"
+#include "stream_encoder.h"
+
+#endif
diff --git a/FLAC/src/protected/stream_decoder.h b/FLAC/src/protected/stream_decoder.h
new file mode 100644 (file)
index 0000000..5c31c16
--- /dev/null
@@ -0,0 +1,60 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PROTECTED__STREAM_DECODER_H
+#define FLAC__PROTECTED__STREAM_DECODER_H
+
+#include "FLAC/stream_decoder.h"
+#if FLAC__HAS_OGG
+#include "private/ogg_decoder_aspect.h"
+#endif
+
+typedef struct FLAC__StreamDecoderProtected {
+       FLAC__StreamDecoderState state;
+       FLAC__StreamDecoderInitStatus initstate;
+       unsigned channels;
+       FLAC__ChannelAssignment channel_assignment;
+       unsigned bits_per_sample;
+       unsigned sample_rate; /* in Hz */
+       unsigned blocksize; /* in samples (per channel) */
+       FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
+#if FLAC__HAS_OGG
+       FLAC__OggDecoderAspect ogg_decoder_aspect;
+#endif
+} FLAC__StreamDecoderProtected;
+
+/*
+ * return the number of input bytes consumed
+ */
+unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
+
+#endif
diff --git a/FLAC/src/protected/stream_encoder.h b/FLAC/src/protected/stream_encoder.h
new file mode 100644 (file)
index 0000000..8850c6b
--- /dev/null
@@ -0,0 +1,118 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2001-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__PROTECTED__STREAM_ENCODER_H
+#define FLAC__PROTECTED__STREAM_ENCODER_H
+
+#include "FLAC/stream_encoder.h"
+#if FLAC__HAS_OGG
+#include "private/ogg_encoder_aspect.h"
+#endif
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+#include "private/float.h"
+
+#define FLAC__MAX_APODIZATION_FUNCTIONS 32
+
+typedef enum {
+       FLAC__APODIZATION_BARTLETT,
+       FLAC__APODIZATION_BARTLETT_HANN,
+       FLAC__APODIZATION_BLACKMAN,
+       FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
+       FLAC__APODIZATION_CONNES,
+       FLAC__APODIZATION_FLATTOP,
+       FLAC__APODIZATION_GAUSS,
+       FLAC__APODIZATION_HAMMING,
+       FLAC__APODIZATION_HANN,
+       FLAC__APODIZATION_KAISER_BESSEL,
+       FLAC__APODIZATION_NUTTALL,
+       FLAC__APODIZATION_RECTANGLE,
+       FLAC__APODIZATION_TRIANGLE,
+       FLAC__APODIZATION_TUKEY,
+       FLAC__APODIZATION_PARTIAL_TUKEY,
+       FLAC__APODIZATION_PUNCHOUT_TUKEY,
+       FLAC__APODIZATION_WELCH
+} FLAC__ApodizationFunction;
+
+typedef struct {
+       FLAC__ApodizationFunction type;
+       union {
+               struct {
+                       FLAC__real stddev;
+               } gauss;
+               struct {
+                       FLAC__real p;
+               } tukey;
+               struct {
+                       FLAC__real p;
+                       FLAC__real start;
+                       FLAC__real end;
+               } multiple_tukey;
+       } parameters;
+} FLAC__ApodizationSpecification;
+
+#endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+typedef struct FLAC__StreamEncoderProtected {
+       FLAC__StreamEncoderState state;
+       FLAC__bool verify;
+       FLAC__bool streamable_subset;
+       FLAC__bool do_md5;
+       FLAC__bool do_mid_side_stereo;
+       FLAC__bool loose_mid_side_stereo;
+       unsigned channels;
+       unsigned bits_per_sample;
+       unsigned sample_rate;
+       unsigned blocksize;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       unsigned num_apodizations;
+       FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
+#endif
+       unsigned max_lpc_order;
+       unsigned qlp_coeff_precision;
+       FLAC__bool do_qlp_coeff_prec_search;
+       FLAC__bool do_exhaustive_model_search;
+       FLAC__bool do_escape_coding;
+       unsigned min_residual_partition_order;
+       unsigned max_residual_partition_order;
+       unsigned rice_parameter_search_dist;
+       FLAC__uint64 total_samples_estimate;
+       FLAC__StreamMetadata **metadata;
+       unsigned num_metadata_blocks;
+       FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
+#if FLAC__HAS_OGG
+       FLAC__OggEncoderAspect ogg_encoder_aspect;
+#endif
+} FLAC__StreamEncoderProtected;
+
+#endif
diff --git a/FLAC/src/share/alloc.h b/FLAC/src/share/alloc.h
new file mode 100644 (file)
index 0000000..914de9b
--- /dev/null
@@ -0,0 +1,219 @@
+/* alloc - Convenience routines for safely allocating memory
+ * Copyright (C) 2007-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 FLAC__SHARE__ALLOC_H
+#define FLAC__SHARE__ALLOC_H
+
+#ifdef HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
+/* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
+ * before #including this file,  otherwise SIZE_MAX might not be defined
+ */
+
+#include <limits.h> /* for SIZE_MAX */
+#if HAVE_STDINT_H
+#include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
+#endif
+#include <stdlib.h> /* for size_t, malloc(), etc */
+#include "share/compat.h"
+
+#ifndef SIZE_MAX
+# ifndef SIZE_T_MAX
+#  ifdef _MSC_VER
+#   ifdef _WIN64
+#    define SIZE_T_MAX FLAC__U64L(0xffffffffffffffff)
+#   else
+#    define SIZE_T_MAX 0xffffffff
+#   endif
+#  else
+#   error
+#  endif
+# endif
+# define SIZE_MAX SIZE_T_MAX
+#endif
+
+/* avoid malloc()ing 0 bytes, see:
+ * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
+*/
+static inline void *safe_malloc_(size_t size)
+{
+       /* malloc(0) is undefined; FLAC src convention is to always allocate */
+       if(!size)
+               size++;
+       return malloc(size);
+}
+
+static inline void *safe_calloc_(size_t nmemb, size_t size)
+{
+       if(!nmemb || !size)
+               return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
+       return calloc(nmemb, size);
+}
+
+/*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
+
+static inline void *safe_malloc_add_2op_(size_t size1, size_t size2)
+{
+       size2 += size1;
+       if(size2 < size1)
+               return 0;
+       return safe_malloc_(size2);
+}
+
+static inline void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
+{
+       size2 += size1;
+       if(size2 < size1)
+               return 0;
+       size3 += size2;
+       if(size3 < size2)
+               return 0;
+       return safe_malloc_(size3);
+}
+
+static inline void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
+{
+       size2 += size1;
+       if(size2 < size1)
+               return 0;
+       size3 += size2;
+       if(size3 < size2)
+               return 0;
+       size4 += size3;
+       if(size4 < size3)
+               return 0;
+       return safe_malloc_(size4);
+}
+
+void *safe_malloc_mul_2op_(size_t size1, size_t size2) ;
+
+static inline void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
+{
+       if(!size1 || !size2 || !size3)
+               return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
+       if(size1 > SIZE_MAX / size2)
+               return 0;
+       size1 *= size2;
+       if(size1 > SIZE_MAX / size3)
+               return 0;
+       return malloc(size1*size3);
+}
+
+/* size1*size2 + size3 */
+static inline void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
+{
+       if(!size1 || !size2)
+               return safe_malloc_(size3);
+       if(size1 > SIZE_MAX / size2)
+               return 0;
+       return safe_malloc_add_2op_(size1*size2, size3);
+}
+
+/* size1 * (size2 + size3) */
+static inline void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
+{
+       if(!size1 || (!size2 && !size3))
+               return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
+       size2 += size3;
+       if(size2 < size3)
+               return 0;
+       if(size1 > SIZE_MAX / size2)
+               return 0;
+       return malloc(size1*size2);
+}
+
+static inline void *safe_realloc_(void *ptr, size_t size)
+{
+       void *oldptr = ptr;
+       void *newptr = realloc(ptr, size);
+       if(size > 0 && newptr == 0)
+               free(oldptr);
+       return newptr;
+}
+static inline void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
+{
+       size2 += size1;
+       if(size2 < size1) {
+               free(ptr);
+               return 0;
+       }
+       return realloc(ptr, size2);
+}
+
+static inline void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
+{
+       size2 += size1;
+       if(size2 < size1)
+               return 0;
+       size3 += size2;
+       if(size3 < size2)
+               return 0;
+       return realloc(ptr, size3);
+}
+
+static inline void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
+{
+       size2 += size1;
+       if(size2 < size1)
+               return 0;
+       size3 += size2;
+       if(size3 < size2)
+               return 0;
+       size4 += size3;
+       if(size4 < size3)
+               return 0;
+       return realloc(ptr, size4);
+}
+
+static inline void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
+{
+       if(!size1 || !size2)
+               return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
+       if(size1 > SIZE_MAX / size2)
+               return 0;
+       return safe_realloc_(ptr, size1*size2);
+}
+
+/* size1 * (size2 + size3) */
+static inline void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
+{
+       if(!size1 || (!size2 && !size3))
+               return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
+       size2 += size3;
+       if(size2 < size3)
+               return 0;
+       return safe_realloc_mul_2op_(ptr, size1, size2);
+}
+
+#endif
diff --git a/FLAC/src/share/compat.h b/FLAC/src/share/compat.h
new file mode 100644 (file)
index 0000000..2083f3a
--- /dev/null
@@ -0,0 +1,209 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2012-2016  Xiph.org Foundation
+ *
+ * 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 the prefered location of all CPP hackery to make $random_compiler
+ * work like something approaching a C99 (or maybe more accurately GNU99)
+ * compiler.
+ *
+ * It is assumed that this header will be included after "config.h".
+ */
+
+#ifndef FLAC__SHARE__COMPAT_H
+#define FLAC__SHARE__COMPAT_H
+
+#if defined _WIN32 && !defined __CYGWIN__
+/* where MSVC puts unlink() */
+# include <io.h>
+#else
+# include <unistd.h>
+#endif
+
+#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
+#include <sys/types.h> /* for off_t */
+#define FLAC__off_t __int64 /* use this instead of off_t to fix the 2 GB limit */
+#if !defined __MINGW32__
+#define fseeko _fseeki64
+#define ftello _ftelli64
+#else /* MinGW */
+#if !defined(HAVE_FSEEKO)
+#define fseeko fseeko64
+#define ftello ftello64
+#endif
+#endif
+#else
+#define FLAC__off_t off_t
+#endif
+
+#if HAVE_INTTYPES_H
+#define __STDC_FORMAT_MACROS
+#include <inttypes.h>
+#endif
+
+#if defined(_MSC_VER)
+#define strtoll _strtoi64
+#define strtoull _strtoui64
+#endif
+
+#if defined(_MSC_VER)
+#define inline __inline
+#endif
+
+#if defined __INTEL_COMPILER || (defined _MSC_VER && defined _WIN64)
+/* MSVS generates VERY slow 32-bit code with __restrict */
+#define flac_restrict __restrict
+#elif defined __GNUC__
+#define flac_restrict __restrict__
+#else
+#define flac_restrict
+#endif
+
+#define FLAC__U64L(x) x##ULL
+
+#if defined _MSC_VER || defined __MINGW32__
+#define FLAC__STRCASECMP _stricmp
+#define FLAC__STRNCASECMP _strnicmp
+#elif defined __BORLANDC__
+#define FLAC__STRCASECMP stricmp
+#define FLAC__STRNCASECMP strnicmp
+#else
+#define FLAC__STRCASECMP strcasecmp
+#define FLAC__STRNCASECMP strncasecmp
+#endif
+
+#if defined _MSC_VER || defined __MINGW32__ || defined __CYGWIN__ || defined __EMX__
+#include <io.h> /* for _setmode(), chmod() */
+#include <fcntl.h> /* for _O_BINARY */
+#else
+#include <unistd.h> /* for chown(), unlink() */
+#endif
+
+#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
+#if defined __BORLANDC__
+#include <utime.h> /* for utime() */
+#else
+#include <sys/utime.h> /* for utime() */
+#endif
+#else
+#include <sys/types.h> /* some flavors of BSD (like OS X) require this to get time_t */
+#include <utime.h> /* for utime() */
+#endif
+
+#if defined _MSC_VER
+#  if _MSC_VER >= 1800
+#    include <inttypes.h>
+#  elif _MSC_VER >= 1600
+/* Visual Studio 2010 has decent C99 support */
+#    include <stdint.h>
+#    define PRIu64 "llu"
+#    define PRId64 "lld"
+#    define PRIx64 "llx"
+#  else
+#    include <limits.h>
+#    ifndef UINT32_MAX
+#      define UINT32_MAX _UI32_MAX
+#    endif
+     typedef unsigned __int64 uint64_t;
+     typedef unsigned __int32 uint32_t;
+     typedef unsigned __int16 uint16_t;
+     typedef unsigned __int8 uint8_t;
+     typedef __int64 int64_t;
+     typedef __int32 int32_t;
+     typedef __int16 int16_t;
+     typedef __int8  int8_t;
+#    define PRIu64 "I64u"
+#    define PRId64 "I64d"
+#    define PRIx64 "I64x"
+#  endif
+#endif /* defined _MSC_VER */
+
+#ifdef _WIN32
+/* All char* strings are in UTF-8 format. Added to support Unicode files on Windows */
+
+#include "share/win_utf8_io.h"
+#define flac_printf printf_utf8
+#define flac_fprintf fprintf_utf8
+#define flac_vfprintf vfprintf_utf8
+
+#include "share/windows_unicode_filenames.h"
+#define flac_fopen flac_internal_fopen_utf8
+#define flac_chmod flac_internal_chmod_utf8
+#define flac_utime flac_internal_utime_utf8
+#define flac_unlink flac_internal_unlink_utf8
+#define flac_rename flac_internal_rename_utf8
+#define flac_stat flac_internal_stat64_utf8
+
+#else
+
+#define flac_printf printf
+#define flac_fprintf fprintf
+#define flac_vfprintf vfprintf
+
+#define flac_fopen fopen
+#define flac_chmod chmod
+#define flac_utime utime
+#define flac_unlink unlink
+#define flac_rename rename
+#define flac_stat stat
+
+#endif
+
+#ifdef _WIN32
+#define flac_stat_s __stat64 /* stat struct */
+#define flac_fstat _fstat64
+#else
+#define flac_stat_s stat /* stat struct */
+#define flac_fstat fstat
+#endif
+
+#ifndef M_LN2
+#define M_LN2 0.69314718055994530942
+#endif
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+/* FLAC needs to compile and work correctly on systems with a normal ISO C99
+ * snprintf as well as Microsoft Visual Studio which has an non-standards
+ * conformant snprint_s function.
+ *
+ * This function wraps the MS version to behave more like the ISO version.
+ */
+#include <stdarg.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+int flac_snprintf(char *str, size_t size, const char *fmt, ...);
+int flac_vsnprintf(char *str, size_t size, const char *fmt, va_list va);
+#ifdef __cplusplus
+};
+#endif
+
+#endif /* FLAC__SHARE__COMPAT_H */
diff --git a/FLAC/src/share/endswap.h b/FLAC/src/share/endswap.h
new file mode 100644 (file)
index 0000000..9088a74
--- /dev/null
@@ -0,0 +1,84 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2012-2016  Xiph.org Foundation
+ *
+ * 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.
+ */
+
+/* It is assumed that this header will be included after "config.h". */
+
+#if HAVE_BSWAP32                       /* GCC and Clang */
+
+/* GCC prior to 4.8 didn't provide bswap16 on x86_64 */
+#if ! HAVE_BSWAP16
+static inline unsigned short __builtin_bswap16(unsigned short a)
+{
+       return (a<<8)|(a>>8);
+}
+#endif
+
+#define        ENDSWAP_16(x)           (__builtin_bswap16 (x))
+#define        ENDSWAP_32(x)           (__builtin_bswap32 (x))
+#define        ENDSWAP_64(x)           (__builtin_bswap64 (x))
+
+#elif defined _MSC_VER         /* Windows */
+
+#include <stdlib.h>
+
+#define        ENDSWAP_16(x)           (_byteswap_ushort (x))
+#define        ENDSWAP_32(x)           (_byteswap_ulong (x))
+#define        ENDSWAP_64(x)           (_byteswap_uint64 (x))
+
+#elif defined HAVE_BYTESWAP_H          /* Linux */
+
+#include <byteswap.h>
+
+#define        ENDSWAP_16(x)           (bswap_16 (x))
+#define        ENDSWAP_32(x)           (bswap_32 (x))
+#define        ENDSWAP_64(x)           (bswap_64 (x))
+
+#else
+
+#define        ENDSWAP_16(x)           ((((x) >> 8) & 0xFF) | (((x) & 0xFF) << 8))
+#define        ENDSWAP_32(x)           ((((x) >> 24) & 0xFF) | (((x) >> 8) & 0xFF00) | (((x) & 0xFF00) << 8) | (((x) & 0xFF) << 24))
+#define        ENDSWAP_64(x)           ((ENDSWAP_32(((x) >> 32) & 0xFFFFFFFF)) | (ENDSWAP_32((x) & 0xFFFFFFFF) << 32))
+
+#endif
+
+
+/* Host to little-endian byte swapping (for MD5 calculation) */
+#if CPU_IS_BIG_ENDIAN
+
+#define H2LE_16(x)             ENDSWAP_16 (x)
+#define H2LE_32(x)             ENDSWAP_32 (x)
+
+#else
+
+#define H2LE_16(x)             (x)
+#define H2LE_32(x)             (x)
+
+#endif
diff --git a/FLAC/src/share/getopt.h b/FLAC/src/share/getopt.h
new file mode 100644 (file)
index 0000000..66aced0
--- /dev/null
@@ -0,0 +1,184 @@
+/*
+       NOTE:
+       I cannot get the vanilla getopt code to work (i.e. compile only what
+       is needed and not duplicate symbols found in the standard library)
+       on all the platforms that FLAC supports.  In particular the gating
+       of code with the ELIDE_CODE #define is not accurate enough on systems
+       that are POSIX but not glibc.  If someone has a patch that works on
+       GNU/Linux, Darwin, AND Solaris please submit it on the project page:
+               https://sourceforge.net/p/flac/patches/
+
+       In the meantime I have munged the global symbols and removed gates
+       around code, while at the same time trying to touch the original as
+       little as possible.
+*/
+/* Declarations for getopt.
+   Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Library General Public License as
+   published by the Free Software Foundation; either version 2 of the
+   License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Library General Public License for more details.
+
+   You should have received a copy of the GNU Library General Public
+   License along with the GNU C Library; see the file COPYING.LIB.  If not,
+   write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
+
+#ifndef SHARE__GETOPT_H
+#define SHARE__GETOPT_H
+
+/*[JEC] was:#ifndef __need_getopt*/
+/*[JEC] was:# define _GETOPT_H 1*/
+/*[JEC] was:#endif*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* For communication from `share__getopt' to the caller.
+   When `share__getopt' finds an option that takes an argument,
+   the argument value is returned here.
+   Also, when `ordering' is RETURN_IN_ORDER,
+   each non-option ARGV-element is returned here.  */
+
+extern char *share__optarg;
+
+/* Index in ARGV of the next element to be scanned.
+   This is used for communication to and from the caller
+   and for communication between successive calls to `share__getopt'.
+
+   On entry to `share__getopt', zero means this is the first call; initialize.
+
+   When `share__getopt' returns -1, this is the index of the first of the
+   non-option elements that the caller should itself scan.
+
+   Otherwise, `share__optind' communicates from one call to the next
+   how much of ARGV has been scanned so far.  */
+
+extern int share__optind;
+
+/* Callers store zero here to inhibit the error message `share__getopt' prints
+   for unrecognized options.  */
+
+extern int share__opterr;
+
+/* Set to an option character which was unrecognized.  */
+
+extern int share__optopt;
+
+/*[JEC] was:#ifndef __need_getopt */
+/* Describe the long-named options requested by the application.
+   The LONG_OPTIONS argument to share__getopt_long or share__getopt_long_only is a vector
+   of `struct share__option' terminated by an element containing a name which is
+   zero.
+
+   The field `has_arg' is:
+   share__no_argument          (or 0) if the option does not take an argument,
+   share__required_argument    (or 1) if the option requires an argument,
+   share__optional_argument    (or 2) if the option takes an optional argument.
+
+   If the field `flag' is not NULL, it points to a variable that is set
+   to the value given in the field `val' when the option is found, but
+   left unchanged if the option is not found.
+
+   To have a long-named option do something other than set an `int' to
+   a compiled-in constant, such as set a value from `share__optarg', set the
+   option's `flag' field to zero and its `val' field to a nonzero
+   value (the equivalent single-letter option character, if there is
+   one).  For long options that have a zero `flag' field, `share__getopt'
+   returns the contents of the `val' field.  */
+
+struct share__option
+{
+# if defined __STDC__ && __STDC__
+  const char *name;
+# else
+  char *name;
+# endif
+  /* has_arg can't be an enum because some compilers complain about
+     type mismatches in all the code that assumes it is an int.  */
+  int has_arg;
+  int *flag;
+  int val;
+};
+
+/* Names for the values of the `has_arg' field of `struct share__option'.  */
+
+# define share__no_argument            0
+# define share__required_argument      1
+# define share__optional_argument      2
+/*[JEC] was:#endif*/   /* need getopt */
+
+
+/* Get definitions and prototypes for functions to process the
+   arguments in ARGV (ARGC of them, minus the program name) for
+   options given in OPTS.
+
+   Return the option character from OPTS just read.  Return -1 when
+   there are no more options.  For unrecognized options, or options
+   missing arguments, `share__optopt' is set to the option letter, and '?' is
+   returned.
+
+   The OPTS string is a list of characters which are recognized option
+   letters, optionally followed by colons, specifying that that letter
+   takes an argument, to be placed in `share__optarg'.
+
+   If a letter in OPTS is followed by two colons, its argument is
+   optional.  This behavior is specific to the GNU `share__getopt'.
+
+   The argument `--' causes premature termination of argument
+   scanning, explicitly telling `share__getopt' that there are no more
+   options.
+
+   If OPTS begins with `--', then non-option arguments are treated as
+   arguments to the option '\0'.  This behavior is specific to the GNU
+   `share__getopt'.  */
+
+/*[JEC] was:#if defined __STDC__ && __STDC__*/
+/*[JEC] was:# ifdef __GNU_LIBRARY__*/
+/* Many other libraries have conflicting prototypes for getopt, with
+   differences in the consts, in stdlib.h.  To avoid compilation
+   errors, only prototype getopt for the GNU C library.  */
+extern int share__getopt (int argc, char *const *argv, const char *shortopts);
+/*[JEC] was:# else*/ /* not __GNU_LIBRARY__ */
+/*[JEC] was:extern int getopt ();*/
+/*[JEC] was:# endif*/ /* __GNU_LIBRARY__ */
+
+/*[JEC] was:# ifndef __need_getopt*/
+extern int share__getopt_long (int argc, char *const *argv, const char *shortopts,
+                       const struct share__option *longopts, int *longind);
+extern int share__getopt_long_only (int argc, char *const *argv,
+                            const char *shortopts,
+                            const struct share__option *longopts, int *longind);
+
+/* Internal only.  Users should not call this directly.  */
+extern int share___getopt_internal (int argc, char *const *argv,
+                            const char *shortopts,
+                            const struct share__option *longopts, int *longind,
+                            int long_only);
+/*[JEC] was:# endif*/
+/*[JEC] was:#else*/ /* not __STDC__ */
+/*[JEC] was:extern int getopt ();*/
+/*[JEC] was:# ifndef __need_getopt*/
+/*[JEC] was:extern int getopt_long ();*/
+/*[JEC] was:extern int getopt_long_only ();*/
+
+/*[JEC] was:extern int _getopt_internal ();*/
+/*[JEC] was:# endif*/
+/*[JEC] was:#endif*/ /* __STDC__ */
+
+#ifdef __cplusplus
+}
+#endif
+
+/* Make sure we later can get all the definitions and declarations.  */
+/*[JEC] was:#undef __need_getopt*/
+
+#endif /* getopt.h */
diff --git a/FLAC/src/share/grabbag.h b/FLAC/src/share/grabbag.h
new file mode 100644 (file)
index 0000000..92ec998
--- /dev/null
@@ -0,0 +1,30 @@
+/* grabbag - Convenience lib for various routines common to several tools
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef SHARE__GRABBAG_H
+#define SHARE__GRABBAG_H
+
+/* These can't be included by themselves, only from within grabbag.h */
+#include "grabbag/cuesheet.h"
+#include "grabbag/file.h"
+#include "grabbag/picture.h"
+#include "grabbag/replaygain.h"
+#include "grabbag/seektable.h"
+
+#endif
diff --git a/FLAC/src/share/macros.h b/FLAC/src/share/macros.h
new file mode 100644 (file)
index 0000000..20b3ea5
--- /dev/null
@@ -0,0 +1,45 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.org Foundation
+ *
+ * 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 <errno.h>
+
+/* FLAC_CHECK_RETURN : Check the return value of the provided function and
+ * print an error message if it fails (ie returns a value < 0).
+ *
+ * Ideally, a library should not print anything, but this macro is only used
+ * for things that extremely unlikely to fail, like `chown` to a previoulsy
+ * saved `uid`.
+ */
+
+#define FLAC_CHECK_RETURN(x) \
+                       {       if ((x) < 0) \
+                                       fprintf (stderr, "%s : %s\n", #x, strerror (errno)) ; \
+                       }
diff --git a/FLAC/src/share/private.h b/FLAC/src/share/private.h
new file mode 100644 (file)
index 0000000..f7e3b85
--- /dev/null
@@ -0,0 +1,45 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.org Foundation
+ *
+ * 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 FLAC__SHARE__PRIVATE_H
+#define FLAC__SHARE__PRIVATE_H
+
+/*
+ * Unpublished debug routines from libFLAC> This should not be used from any
+ * client code other than code shipped with the FLAC sources.
+ */
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value);
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder);
+
+#endif /* FLAC__SHARE__PRIVATE_H */
diff --git a/FLAC/src/share/replaygain_analysis.h b/FLAC/src/share/replaygain_analysis.h
new file mode 100644 (file)
index 0000000..f06a9b2
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ *  ReplayGainAnalysis - analyzes input samples and give the recommended dB change
+ *  Copyright (C) 2001 David Robinson and Glen Sawyer
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  concept and filter values by David Robinson (David@Robinson.org)
+ *    -- blame him if you think the idea is flawed
+ *  coding by Glen Sawyer (glensawyer@hotmail.com) 442 N 700 E, Provo, UT 84606 USA
+ *    -- blame him if you think this runs too slowly, or the coding is otherwise flawed
+ *  minor cosmetic tweaks to integrate with FLAC by Josh Coalson
+ *
+ *  For an explanation of the concepts and the basic algorithms involved, go to:
+ *    http://www.replaygain.org/
+ */
+
+#ifndef GAIN_ANALYSIS_H
+#define GAIN_ANALYSIS_H
+
+#include <stddef.h>
+
+#define GAIN_NOT_ENOUGH_SAMPLES  -24601
+#define GAIN_ANALYSIS_ERROR           0
+#define GAIN_ANALYSIS_OK              1
+
+#define INIT_GAIN_ANALYSIS_ERROR      0
+#define INIT_GAIN_ANALYSIS_OK         1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef float   flac_float_t;         /* Type used for filtering */
+
+extern flac_float_t ReplayGainReferenceLoudness; /* in dB SPL, currently == 89.0 */
+
+int     InitGainAnalysis ( long samplefreq );
+int     ValidGainFrequency ( long samplefreq );
+int     AnalyzeSamples   ( const flac_float_t* left_samples, const flac_float_t* right_samples, size_t num_samples, int num_channels );
+flac_float_t GetTitleGain     ( void );
+flac_float_t GetAlbumGain     ( void );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GAIN_ANALYSIS_H */
diff --git a/FLAC/src/share/replaygain_synthesis.h b/FLAC/src/share/replaygain_synthesis.h
new file mode 100644 (file)
index 0000000..5f4c3ff
--- /dev/null
@@ -0,0 +1,52 @@
+/* replaygain_synthesis - Routines for applying ReplayGain to a signal
+ * Copyright (C) 2002-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#ifndef FLAC__SHARE__REPLAYGAIN_SYNTHESIS_H
+#define FLAC__SHARE__REPLAYGAIN_SYNTHESIS_H
+
+#include <stdlib.h> /* for size_t */
+#include "FLAC/format.h"
+
+#define FLAC_SHARE__MAX_SUPPORTED_CHANNELS FLAC__MAX_CHANNELS
+
+typedef enum {
+       NOISE_SHAPING_NONE = 0,
+       NOISE_SHAPING_LOW = 1,
+       NOISE_SHAPING_MEDIUM = 2,
+       NOISE_SHAPING_HIGH = 3
+} NoiseShaping;
+
+typedef struct {
+       const float*  FilterCoeff;
+       FLAC__uint64  Mask;
+       double        Add;
+       float         Dither;
+       float         ErrorHistory     [FLAC_SHARE__MAX_SUPPORTED_CHANNELS] [16];  /* 16th order Noise shaping */
+       float         DitherHistory    [FLAC_SHARE__MAX_SUPPORTED_CHANNELS] [16];
+       int           LastRandomNumber [FLAC_SHARE__MAX_SUPPORTED_CHANNELS];
+       unsigned      LastHistoryIndex;
+       NoiseShaping  ShapingType;
+} DitherContext;
+
+void FLAC__replaygain_synthesis__init_dither_context(DitherContext *dither, int bits, int shapingtype);
+
+/* scale = (float) pow(10., (double)replaygain * 0.05); */
+size_t FLAC__replaygain_synthesis__apply_gain(FLAC__byte *data_out, FLAC__bool little_endian_data_out, FLAC__bool unsigned_data_out, const FLAC__int32 * const input[], unsigned wide_samples, unsigned channels, const unsigned source_bps, const unsigned target_bps, const double scale, const FLAC__bool hard_limit, FLAC__bool do_dithering, DitherContext *dither_context);
+
+#endif
diff --git a/FLAC/src/share/safe_str.h b/FLAC/src/share/safe_str.h
new file mode 100644 (file)
index 0000000..eb974c5
--- /dev/null
@@ -0,0 +1,69 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.org Foundation
+ *
+ * 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.
+ */
+
+/* Safe string handling functions to replace things like strcpy, strncpy,
+ * strcat, strncat etc.
+ * All of these functions guarantee a correctly NUL terminated string but
+ * the string may be truncated if the destination buffer was too short.
+ */
+
+#ifndef FLAC__SHARE_SAFE_STR_H
+#define FLAC__SHARE_SAFE_STR_H
+
+static inline char *
+safe_strncat(char *dest, const char *src, size_t dest_size)
+{
+       char * ret;
+
+       if (dest_size < 1)
+               return dest;
+
+       ret = strncat(dest, src, dest_size - strlen (dest));
+       dest [dest_size - 1] = 0;
+
+       return ret;
+}
+
+static inline char *
+safe_strncpy(char *dest, const char *src, size_t dest_size)
+{
+       char * ret;
+
+       if (dest_size < 1)
+               return dest;
+
+       ret = strncpy(dest, src, dest_size);
+       dest [dest_size - 1] = 0;
+
+       return ret;
+}
+
+#endif /* FLAC__SHARE_SAFE_STR_H */
diff --git a/FLAC/src/share/utf8.h b/FLAC/src/share/utf8.h
new file mode 100644 (file)
index 0000000..7d6650d
--- /dev/null
@@ -0,0 +1,25 @@
+#ifndef SHARE__UTF8_H
+#define SHARE__UTF8_H
+
+/*
+ * Convert a string between UTF-8 and the locale's charset.
+ * Invalid bytes are replaced by '#', and characters that are
+ * not available in the target encoding are replaced by '?'.
+ *
+ * If the locale's charset is not set explicitly then it is
+ * obtained using nl_langinfo(CODESET), where available, the
+ * environment variable CHARSET, or assumed to be US-ASCII.
+ *
+ * Return value of conversion functions:
+ *
+ *  -1 : memory allocation failed
+ *   0 : data was converted exactly
+ *   1 : valid data was converted approximately (using '?')
+ *   2 : input was invalid (but still converted, using '#')
+ *   3 : unknown encoding (but still converted, using '?')
+ */
+
+int utf8_encode(const char *from, char **to);
+int utf8_decode(const char *from, char **to);
+
+#endif
diff --git a/FLAC/src/share/win_utf8_io.h b/FLAC/src/share/win_utf8_io.h
new file mode 100644 (file)
index 0000000..13fd118
--- /dev/null
@@ -0,0 +1,58 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.Org Foundation
+ *
+ * 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 _WIN32
+
+#ifndef flac__win_utf8_io_h
+#define flac__win_utf8_io_h
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+size_t strlen_utf8(const char *str);
+int win_get_console_width(void);
+
+int get_utf8_argv(int *argc, char ***argv);
+
+int printf_utf8(const char *format, ...);
+int fprintf_utf8(FILE *stream, const char *format, ...);
+int vfprintf_utf8(FILE *stream, const char *format, va_list argptr);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
+#endif
diff --git a/FLAC/src/share/windows_unicode_filenames.h b/FLAC/src/share/windows_unicode_filenames.h
new file mode 100644 (file)
index 0000000..86820ca
--- /dev/null
@@ -0,0 +1,67 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.Org Foundation
+ *
+ * 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 _WIN32
+
+#ifndef flac__windows_unicode_filenames_h
+#define flac__windows_unicode_filenames_h
+
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/utime.h>
+#include "FLAC/ordinals.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void flac_internal_set_utf8_filenames(FLAC__bool flag);
+FLAC__bool flac_internal_get_utf8_filenames(void);
+#define flac_set_utf8_filenames flac_internal_set_utf8_filenames
+#define flac_get_utf8_filenames flac_internal_get_utf8_filenames
+
+FILE* flac_internal_fopen_utf8(const char *filename, const char *mode);
+int flac_internal_stat64_utf8(const char *path, struct __stat64 *buffer);
+int flac_internal_chmod_utf8(const char *filename, int pmode);
+int flac_internal_utime_utf8(const char *filename, struct utimbuf *times);
+int flac_internal_unlink_utf8(const char *filename);
+int flac_internal_rename_utf8(const char *oldname, const char *newname);
+
+#include <windows.h>
+HANDLE WINAPI flac_internal_CreateFile_utf8(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);
+#define CreateFile_utf8 flac_internal_CreateFile_utf8
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
+#endif
diff --git a/FLAC/src/stream_decoder.c b/FLAC/src/stream_decoder.c
new file mode 100644 (file)
index 0000000..d364b0c
--- /dev/null
@@ -0,0 +1,3400 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdio.h>
+#include <stdlib.h> /* for malloc() */
+#include <string.h> /* for memset/memcpy() */
+#include <sys/stat.h> /* for stat() */
+#include <sys/types.h> /* for off_t */
+#include "share/compat.h"
+#include "FLAC/assert.h"
+#include "share/alloc.h"
+#include "protected/stream_decoder.h"
+#include "private/bitreader.h"
+#include "private/bitmath.h"
+#include "private/cpu.h"
+#include "private/crc.h"
+#include "private/fixed.h"
+#include "private/format.h"
+#include "private/lpc.h"
+#include "private/md5.h"
+#include "private/memory.h"
+#include "private/macros.h"
+
+
+/* technically this should be in an "export.c" but this is convenient enough */
+FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC = FLAC__HAS_OGG;
+
+
+/***********************************************************************
+ *
+ * Private static data
+ *
+ ***********************************************************************/
+
+static const FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
+
+/***********************************************************************
+ *
+ * Private class method prototypes
+ *
+ ***********************************************************************/
+
+static void set_defaults_(FLAC__StreamDecoder *decoder);
+static FILE *get_binary_stdin_(void);
+static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
+static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
+static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
+static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
+static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
+static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
+static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length);
+static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
+static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
+static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
+static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
+static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
+static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
+static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
+static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
+static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
+static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
+static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
+static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
+static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
+static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
+#if FLAC__HAS_OGG
+static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
+static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+#endif
+static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
+static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
+static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
+#if FLAC__HAS_OGG
+static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
+#endif
+static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
+static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
+static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
+static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
+
+/***********************************************************************
+ *
+ * Private class data
+ *
+ ***********************************************************************/
+
+typedef struct FLAC__StreamDecoderPrivate {
+       FLAC__bool is_ogg;
+       FLAC__StreamDecoderReadCallback read_callback;
+       FLAC__StreamDecoderSeekCallback seek_callback;
+       FLAC__StreamDecoderTellCallback tell_callback;
+       FLAC__StreamDecoderLengthCallback length_callback;
+       FLAC__StreamDecoderEofCallback eof_callback;
+       FLAC__StreamDecoderWriteCallback write_callback;
+       FLAC__StreamDecoderMetadataCallback metadata_callback;
+       FLAC__StreamDecoderErrorCallback error_callback;
+       /* generic 32-bit datapath: */
+       void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+       /* generic 64-bit datapath: */
+       void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+       /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
+       void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
+       void *client_data;
+       FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
+       FLAC__BitReader *input;
+       FLAC__int32 *output[FLAC__MAX_CHANNELS];
+       FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
+       FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
+       unsigned output_capacity, output_channels;
+       FLAC__uint32 fixed_block_size, next_fixed_block_size;
+       FLAC__uint64 samples_decoded;
+       FLAC__bool has_stream_info, has_seek_table;
+       FLAC__StreamMetadata stream_info;
+       FLAC__StreamMetadata seek_table;
+       FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
+       FLAC__byte *metadata_filter_ids;
+       size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
+       FLAC__Frame frame;
+       FLAC__bool cached; /* true if there is a byte in lookahead */
+       FLAC__CPUInfo cpuinfo;
+       FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
+       FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
+       /* unaligned (original) pointers to allocated data */
+       FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
+       FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
+       FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
+       FLAC__bool is_seeking;
+       FLAC__MD5Context md5context;
+       FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
+       /* (the rest of these are only used for seeking) */
+       FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
+       FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
+       FLAC__uint64 target_sample;
+       unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
+       FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
+} FLAC__StreamDecoderPrivate;
+
+/***********************************************************************
+ *
+ * Public static class data
+ *
+ ***********************************************************************/
+
+FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
+       "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
+       "FLAC__STREAM_DECODER_READ_METADATA",
+       "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
+       "FLAC__STREAM_DECODER_READ_FRAME",
+       "FLAC__STREAM_DECODER_END_OF_STREAM",
+       "FLAC__STREAM_DECODER_OGG_ERROR",
+       "FLAC__STREAM_DECODER_SEEK_ERROR",
+       "FLAC__STREAM_DECODER_ABORTED",
+       "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
+       "FLAC__STREAM_DECODER_UNINITIALIZED"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
+       "FLAC__STREAM_DECODER_INIT_STATUS_OK",
+       "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
+       "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
+       "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
+       "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
+       "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
+       "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
+       "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
+       "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
+       "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
+       "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
+       "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
+       "FLAC__STREAM_DECODER_TELL_STATUS_OK",
+       "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
+       "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
+       "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
+       "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
+       "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
+       "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
+       "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
+};
+
+FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
+       "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
+       "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
+       "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
+       "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
+};
+
+/***********************************************************************
+ *
+ * Class constructor/destructor
+ *
+ ***********************************************************************/
+FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
+{
+       FLAC__StreamDecoder *decoder;
+       unsigned i;
+
+       FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
+
+       decoder = calloc(1, sizeof(FLAC__StreamDecoder));
+       if(decoder == 0) {
+               return 0;
+       }
+
+       decoder->protected_ = calloc(1, sizeof(FLAC__StreamDecoderProtected));
+       if(decoder->protected_ == 0) {
+               free(decoder);
+               return 0;
+       }
+
+       decoder->private_ = calloc(1, sizeof(FLAC__StreamDecoderPrivate));
+       if(decoder->private_ == 0) {
+               free(decoder->protected_);
+               free(decoder);
+               return 0;
+       }
+
+       decoder->private_->input = FLAC__bitreader_new();
+       if(decoder->private_->input == 0) {
+               free(decoder->private_);
+               free(decoder->protected_);
+               free(decoder);
+               return 0;
+       }
+
+       decoder->private_->metadata_filter_ids_capacity = 16;
+       if(0 == (decoder->private_->metadata_filter_ids = malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
+               FLAC__bitreader_delete(decoder->private_->input);
+               free(decoder->private_);
+               free(decoder->protected_);
+               free(decoder);
+               return 0;
+       }
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               decoder->private_->output[i] = 0;
+               decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
+       }
+
+       decoder->private_->output_capacity = 0;
+       decoder->private_->output_channels = 0;
+       decoder->private_->has_seek_table = false;
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++)
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
+
+       decoder->private_->file = 0;
+
+       set_defaults_(decoder);
+
+       decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
+
+       return decoder;
+}
+
+FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
+{
+       unsigned i;
+
+       if (decoder == NULL)
+               return ;
+
+       FLAC__ASSERT(0 != decoder->protected_);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->private_->input);
+
+       (void)FLAC__stream_decoder_finish(decoder);
+
+       if(0 != decoder->private_->metadata_filter_ids)
+               free(decoder->private_->metadata_filter_ids);
+
+       FLAC__bitreader_delete(decoder->private_->input);
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++)
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
+
+       free(decoder->private_);
+       free(decoder->protected_);
+       free(decoder);
+}
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+static FLAC__StreamDecoderInitStatus init_stream_internal_(
+       FLAC__StreamDecoder *decoder,
+       FLAC__StreamDecoderReadCallback read_callback,
+       FLAC__StreamDecoderSeekCallback seek_callback,
+       FLAC__StreamDecoderTellCallback tell_callback,
+       FLAC__StreamDecoderLengthCallback length_callback,
+       FLAC__StreamDecoderEofCallback eof_callback,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       FLAC__ASSERT(0 != decoder);
+
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       if(FLAC__HAS_OGG == 0 && is_ogg)
+               return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
+
+       if(
+               0 == read_callback ||
+               0 == write_callback ||
+               0 == error_callback ||
+               (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
+       )
+               return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
+
+#if FLAC__HAS_OGG
+       decoder->private_->is_ogg = is_ogg;
+       if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
+               return decoder->protected_->initstate = FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
+#endif
+
+       /*
+        * get the CPU info and set the function pointers
+        */
+       FLAC__cpu_info(&decoder->private_->cpuinfo);
+       /* first default to the non-asm routines */
+       decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
+       decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
+       decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
+       /* now override with asm where appropriate */
+#ifndef FLAC__NO_ASM
+       if(decoder->private_->cpuinfo.use_asm) {
+#ifdef FLAC__CPU_IA32
+               FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
+#ifdef FLAC__HAS_NASM
+               decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide_asm_ia32; /* OPT_IA32: was really necessary for GCC < 4.9 */
+               if(decoder->private_->cpuinfo.ia32.mmx) {
+                       decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
+                       decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
+               }
+               else {
+                       decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
+                       decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
+               }
+#endif
+#if FLAC__HAS_X86INTRIN && ! defined FLAC__INTEGER_ONLY_LIBRARY
+# if defined FLAC__SSE2_SUPPORTED && !defined FLAC__HAS_NASM /* OPT_SSE: not better than MMX asm */
+               if(decoder->private_->cpuinfo.ia32.sse2) {
+                       decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_16_intrin_sse2;
+               }
+# endif
+# if defined FLAC__SSE4_1_SUPPORTED
+               if(decoder->private_->cpuinfo.ia32.sse41) {
+                       decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide_intrin_sse41;
+               }
+# endif
+#endif
+#elif defined FLAC__CPU_X86_64
+               FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
+               /* No useful SSE optimizations yet */
+#endif
+       }
+#endif
+
+       /* from here on, errors are fatal */
+
+       if(!FLAC__bitreader_init(decoder->private_->input, read_callback_, decoder)) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
+       }
+
+       decoder->private_->read_callback = read_callback;
+       decoder->private_->seek_callback = seek_callback;
+       decoder->private_->tell_callback = tell_callback;
+       decoder->private_->length_callback = length_callback;
+       decoder->private_->eof_callback = eof_callback;
+       decoder->private_->write_callback = write_callback;
+       decoder->private_->metadata_callback = metadata_callback;
+       decoder->private_->error_callback = error_callback;
+       decoder->private_->client_data = client_data;
+       decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
+       decoder->private_->samples_decoded = 0;
+       decoder->private_->has_stream_info = false;
+       decoder->private_->cached = false;
+
+       decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
+       decoder->private_->is_seeking = false;
+
+       decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
+       if(!FLAC__stream_decoder_reset(decoder)) {
+               /* above call sets the state for us */
+               return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
+       }
+
+       return FLAC__STREAM_DECODER_INIT_STATUS_OK;
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
+       FLAC__StreamDecoder *decoder,
+       FLAC__StreamDecoderReadCallback read_callback,
+       FLAC__StreamDecoderSeekCallback seek_callback,
+       FLAC__StreamDecoderTellCallback tell_callback,
+       FLAC__StreamDecoderLengthCallback length_callback,
+       FLAC__StreamDecoderEofCallback eof_callback,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_stream_internal_(
+               decoder,
+               read_callback,
+               seek_callback,
+               tell_callback,
+               length_callback,
+               eof_callback,
+               write_callback,
+               metadata_callback,
+               error_callback,
+               client_data,
+               /*is_ogg=*/false
+       );
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
+       FLAC__StreamDecoder *decoder,
+       FLAC__StreamDecoderReadCallback read_callback,
+       FLAC__StreamDecoderSeekCallback seek_callback,
+       FLAC__StreamDecoderTellCallback tell_callback,
+       FLAC__StreamDecoderLengthCallback length_callback,
+       FLAC__StreamDecoderEofCallback eof_callback,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_stream_internal_(
+               decoder,
+               read_callback,
+               seek_callback,
+               tell_callback,
+               length_callback,
+               eof_callback,
+               write_callback,
+               metadata_callback,
+               error_callback,
+               client_data,
+               /*is_ogg=*/true
+       );
+}
+
+static FLAC__StreamDecoderInitStatus init_FILE_internal_(
+       FLAC__StreamDecoder *decoder,
+       FILE *file,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != file);
+
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return decoder->protected_->initstate = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       if(0 == write_callback || 0 == error_callback)
+               return decoder->protected_->initstate = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
+
+       /*
+        * To make sure that our file does not go unclosed after an error, we
+        * must assign the FILE pointer before any further error can occur in
+        * this routine.
+        */
+       if(file == stdin)
+               file = get_binary_stdin_(); /* just to be safe */
+
+       decoder->private_->file = file;
+
+       return init_stream_internal_(
+               decoder,
+               file_read_callback_,
+               decoder->private_->file == stdin? 0: file_seek_callback_,
+               decoder->private_->file == stdin? 0: file_tell_callback_,
+               decoder->private_->file == stdin? 0: file_length_callback_,
+               file_eof_callback_,
+               write_callback,
+               metadata_callback,
+               error_callback,
+               client_data,
+               is_ogg
+       );
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
+       FLAC__StreamDecoder *decoder,
+       FILE *file,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
+       FLAC__StreamDecoder *decoder,
+       FILE *file,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
+}
+
+static FLAC__StreamDecoderInitStatus init_file_internal_(
+       FLAC__StreamDecoder *decoder,
+       const char *filename,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       FILE *file;
+
+       FLAC__ASSERT(0 != decoder);
+
+       /*
+        * To make sure that our file does not go unclosed after an error, we
+        * have to do the same entrance checks here that are later performed
+        * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
+        */
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return decoder->protected_->initstate = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       if(0 == write_callback || 0 == error_callback)
+               return decoder->protected_->initstate = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
+
+       file = filename? flac_fopen(filename, "rb") : stdin;
+
+       if(0 == file)
+               return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
+
+       return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
+       FLAC__StreamDecoder *decoder,
+       const char *filename,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
+}
+
+FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
+       FLAC__StreamDecoder *decoder,
+       const char *filename,
+       FLAC__StreamDecoderWriteCallback write_callback,
+       FLAC__StreamDecoderMetadataCallback metadata_callback,
+       FLAC__StreamDecoderErrorCallback error_callback,
+       void *client_data
+)
+{
+       return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
+{
+       FLAC__bool md5_failed = false;
+       unsigned i;
+
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
+               return true;
+
+       /* see the comment in FLAC__stream_decoder_reset() as to why we
+        * always call FLAC__MD5Final()
+        */
+       FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
+
+       free(decoder->private_->seek_table.data.seek_table.points);
+       decoder->private_->seek_table.data.seek_table.points = 0;
+       decoder->private_->has_seek_table = false;
+
+       FLAC__bitreader_free(decoder->private_->input);
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               /* WATCHOUT:
+                * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
+                * output arrays have a buffer of up to 3 zeroes in front
+                * (at negative indices) for alignment purposes; we use 4
+                * to keep the data well-aligned.
+                */
+               if(0 != decoder->private_->output[i]) {
+                       free(decoder->private_->output[i]-4);
+                       decoder->private_->output[i] = 0;
+               }
+               if(0 != decoder->private_->residual_unaligned[i]) {
+                       free(decoder->private_->residual_unaligned[i]);
+                       decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
+               }
+       }
+       decoder->private_->output_capacity = 0;
+       decoder->private_->output_channels = 0;
+
+#if FLAC__HAS_OGG
+       if(decoder->private_->is_ogg)
+               FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
+#endif
+
+       if(0 != decoder->private_->file) {
+               if(decoder->private_->file != stdin)
+                       fclose(decoder->private_->file);
+               decoder->private_->file = 0;
+       }
+
+       if(decoder->private_->do_md5_checking) {
+               if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
+                       md5_failed = true;
+       }
+       decoder->private_->is_seeking = false;
+
+       set_defaults_(decoder);
+
+       decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
+
+       return !md5_failed;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+#if FLAC__HAS_OGG
+       /* can't check decoder->private_->is_ogg since that's not set until init time */
+       FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
+       return true;
+#else
+       (void)value;
+       return false;
+#endif
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+       decoder->protected_->md5_checking = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
+       /* double protection */
+       if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
+               return false;
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+       decoder->private_->metadata_filter[type] = true;
+       if(type == FLAC__METADATA_TYPE_APPLICATION)
+               decoder->private_->metadata_filter_ids_count = 0;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       FLAC__ASSERT(0 != id);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+
+       if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
+               return true;
+
+       FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
+
+       if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
+               if(0 == (decoder->private_->metadata_filter_ids = safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               decoder->private_->metadata_filter_ids_capacity *= 2;
+       }
+
+       memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
+       decoder->private_->metadata_filter_ids_count++;
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
+{
+       unsigned i;
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+       for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
+               decoder->private_->metadata_filter[i] = true;
+       decoder->private_->metadata_filter_ids_count = 0;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
+       /* double protection */
+       if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
+               return false;
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+       decoder->private_->metadata_filter[type] = false;
+       if(type == FLAC__METADATA_TYPE_APPLICATION)
+               decoder->private_->metadata_filter_ids_count = 0;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       FLAC__ASSERT(0 != id);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+
+       if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
+               return true;
+
+       FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
+
+       if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
+               if(0 == (decoder->private_->metadata_filter_ids = safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               decoder->private_->metadata_filter_ids_capacity *= 2;
+       }
+
+       memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
+       decoder->private_->metadata_filter_ids_count++;
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+       if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+       memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
+       decoder->private_->metadata_filter_ids_count = 0;
+       return true;
+}
+
+FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->state;
+}
+
+FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
+{
+       return FLAC__StreamDecoderStateString[decoder->protected_->state];
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->md5_checking;
+}
+
+FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
+}
+
+FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->channels;
+}
+
+FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->channel_assignment;
+}
+
+FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->bits_per_sample;
+}
+
+FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->sample_rate;
+}
+
+FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+       return decoder->protected_->blocksize;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != position);
+
+       if(FLAC__HAS_OGG && decoder->private_->is_ogg)
+               return false;
+
+       if(0 == decoder->private_->tell_callback)
+               return false;
+       if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
+               return false;
+       /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
+       if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
+               return false;
+       FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
+       *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       if(!decoder->private_->internal_reset_hack && decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
+               return false;
+
+       decoder->private_->samples_decoded = 0;
+       decoder->private_->do_md5_checking = false;
+
+#if FLAC__HAS_OGG
+       if(decoder->private_->is_ogg)
+               FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
+#endif
+
+       if(!FLAC__bitreader_clear(decoder->private_->input)) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       if(!FLAC__stream_decoder_flush(decoder)) {
+               /* above call sets the state for us */
+               return false;
+       }
+
+#if FLAC__HAS_OGG
+       /*@@@ could go in !internal_reset_hack block below */
+       if(decoder->private_->is_ogg)
+               FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
+#endif
+
+       /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
+        * (internal_reset_hack) don't try to rewind since we are already at
+        * the beginning of the stream and don't want to fail if the input is
+        * not seekable.
+        */
+       if(!decoder->private_->internal_reset_hack) {
+               if(decoder->private_->file == stdin)
+                       return false; /* can't rewind stdin, reset fails */
+               if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
+                       return false; /* seekable and seek fails, reset fails */
+       }
+       else
+               decoder->private_->internal_reset_hack = false;
+
+       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
+
+       decoder->private_->has_stream_info = false;
+
+       free(decoder->private_->seek_table.data.seek_table.points);
+       decoder->private_->seek_table.data.seek_table.points = 0;
+       decoder->private_->has_seek_table = false;
+
+       decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
+       /*
+        * This goes in reset() and not flush() because according to the spec, a
+        * fixed-blocksize stream must stay that way through the whole stream.
+        */
+       decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
+
+       /* We initialize the FLAC__MD5Context even though we may never use it.  This
+        * is because md5 checking may be turned on to start and then turned off if
+        * a seek occurs.  So we init the context here and finalize it in
+        * FLAC__stream_decoder_finish() to make sure things are always cleaned up
+        * properly.
+        */
+       FLAC__MD5Init(&decoder->private_->md5context);
+
+       decoder->private_->first_frame_offset = 0;
+       decoder->private_->unparseable_frame_count = 0;
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
+{
+       FLAC__bool got_a_frame;
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       while(1) {
+               switch(decoder->protected_->state) {
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
+                               if(!find_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_METADATA:
+                               if(!read_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               else
+                                       return true;
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
+                               if(!frame_sync_(decoder))
+                                       return true; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_FRAME:
+                               if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
+                                       return false; /* above function sets the status for us */
+                               if(got_a_frame)
+                                       return true; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_END_OF_STREAM:
+                       case FLAC__STREAM_DECODER_ABORTED:
+                               return true;
+                       default:
+                               FLAC__ASSERT(0);
+                               return false;
+               }
+       }
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       while(1) {
+               switch(decoder->protected_->state) {
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
+                               if(!find_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_METADATA:
+                               if(!read_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
+                       case FLAC__STREAM_DECODER_READ_FRAME:
+                       case FLAC__STREAM_DECODER_END_OF_STREAM:
+                       case FLAC__STREAM_DECODER_ABORTED:
+                               return true;
+                       default:
+                               FLAC__ASSERT(0);
+                               return false;
+               }
+       }
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
+{
+       FLAC__bool dummy;
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       while(1) {
+               switch(decoder->protected_->state) {
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
+                               if(!find_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_METADATA:
+                               if(!read_metadata_(decoder))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
+                               if(!frame_sync_(decoder))
+                                       return true; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_FRAME:
+                               if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
+                                       return false; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_END_OF_STREAM:
+                       case FLAC__STREAM_DECODER_ABORTED:
+                               return true;
+                       default:
+                               FLAC__ASSERT(0);
+                               return false;
+               }
+       }
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
+{
+       FLAC__bool got_a_frame;
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->protected_);
+
+       while(1) {
+               switch(decoder->protected_->state) {
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
+                       case FLAC__STREAM_DECODER_READ_METADATA:
+                               return false; /* above function sets the status for us */
+                       case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
+                               if(!frame_sync_(decoder))
+                                       return true; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_READ_FRAME:
+                               if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
+                                       return false; /* above function sets the status for us */
+                               if(got_a_frame)
+                                       return true; /* above function sets the status for us */
+                               break;
+                       case FLAC__STREAM_DECODER_END_OF_STREAM:
+                       case FLAC__STREAM_DECODER_ABORTED:
+                               return true;
+                       default:
+                               FLAC__ASSERT(0);
+                               return false;
+               }
+       }
+}
+
+FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
+{
+       FLAC__uint64 length;
+
+       FLAC__ASSERT(0 != decoder);
+
+       if(
+               decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
+               decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
+               decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
+               decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
+               decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
+       )
+               return false;
+
+       if(0 == decoder->private_->seek_callback)
+               return false;
+
+       FLAC__ASSERT(decoder->private_->seek_callback);
+       FLAC__ASSERT(decoder->private_->tell_callback);
+       FLAC__ASSERT(decoder->private_->length_callback);
+       FLAC__ASSERT(decoder->private_->eof_callback);
+
+       if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
+               return false;
+
+       decoder->private_->is_seeking = true;
+
+       /* turn off md5 checking if a seek is attempted */
+       decoder->private_->do_md5_checking = false;
+
+       /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
+       if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
+               decoder->private_->is_seeking = false;
+               return false;
+       }
+
+       /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
+       if(
+               decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
+               decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
+       ) {
+               if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
+                       /* above call sets the state for us */
+                       decoder->private_->is_seeking = false;
+                       return false;
+               }
+               /* check this again in case we didn't know total_samples the first time */
+               if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
+                       decoder->private_->is_seeking = false;
+                       return false;
+               }
+       }
+
+       {
+               const FLAC__bool ok =
+#if FLAC__HAS_OGG
+                       decoder->private_->is_ogg?
+                       seek_to_absolute_sample_ogg_(decoder, length, sample) :
+#endif
+                       seek_to_absolute_sample_(decoder, length, sample)
+               ;
+               decoder->private_->is_seeking = false;
+               return ok;
+       }
+}
+
+/***********************************************************************
+ *
+ * Protected class methods
+ *
+ ***********************************************************************/
+
+unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
+{
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+       FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
+       return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
+}
+
+/***********************************************************************
+ *
+ * Private class methods
+ *
+ ***********************************************************************/
+
+void set_defaults_(FLAC__StreamDecoder *decoder)
+{
+       decoder->private_->is_ogg = false;
+       decoder->private_->read_callback = 0;
+       decoder->private_->seek_callback = 0;
+       decoder->private_->tell_callback = 0;
+       decoder->private_->length_callback = 0;
+       decoder->private_->eof_callback = 0;
+       decoder->private_->write_callback = 0;
+       decoder->private_->metadata_callback = 0;
+       decoder->private_->error_callback = 0;
+       decoder->private_->client_data = 0;
+
+       memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
+       decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
+       decoder->private_->metadata_filter_ids_count = 0;
+
+       decoder->protected_->md5_checking = false;
+
+#if FLAC__HAS_OGG
+       FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
+#endif
+}
+
+/*
+ * This will forcibly set stdin to binary mode (for OSes that require it)
+ */
+FILE *get_binary_stdin_(void)
+{
+       /* if something breaks here it is probably due to the presence or
+        * absence of an underscore before the identifiers 'setmode',
+        * 'fileno', and/or 'O_BINARY'; check your system header files.
+        */
+#if defined _MSC_VER || defined __MINGW32__
+       _setmode(_fileno(stdin), _O_BINARY);
+#elif defined __CYGWIN__
+       /* almost certainly not needed for any modern Cygwin, but let's be safe... */
+       setmode(_fileno(stdin), _O_BINARY);
+#elif defined __EMX__
+       setmode(fileno(stdin), O_BINARY);
+#endif
+
+       return stdin;
+}
+
+FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
+{
+       unsigned i;
+       FLAC__int32 *tmp;
+
+       if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
+               return true;
+
+       /* simply using realloc() is not practical because the number of channels may change mid-stream */
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               if(0 != decoder->private_->output[i]) {
+                       free(decoder->private_->output[i]-4);
+                       decoder->private_->output[i] = 0;
+               }
+               if(0 != decoder->private_->residual_unaligned[i]) {
+                       free(decoder->private_->residual_unaligned[i]);
+                       decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
+               }
+       }
+
+       for(i = 0; i < channels; i++) {
+               /* WATCHOUT:
+                * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
+                * output arrays have a buffer of up to 3 zeroes in front
+                * (at negative indices) for alignment purposes; we use 4
+                * to keep the data well-aligned.
+                */
+               tmp = safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
+               if(tmp == 0) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               memset(tmp, 0, sizeof(FLAC__int32)*4);
+               decoder->private_->output[i] = tmp + 4;
+
+               if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+       }
+
+       decoder->private_->output_capacity = size;
+       decoder->private_->output_channels = channels;
+
+       return true;
+}
+
+FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
+{
+       size_t i;
+
+       FLAC__ASSERT(0 != decoder);
+       FLAC__ASSERT(0 != decoder->private_);
+
+       for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
+               if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
+                       return true;
+
+       return false;
+}
+
+FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
+{
+       FLAC__uint32 x;
+       unsigned i, id;
+       FLAC__bool first = true;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       for(i = id = 0; i < 4; ) {
+               if(decoder->private_->cached) {
+                       x = (FLAC__uint32)decoder->private_->lookahead;
+                       decoder->private_->cached = false;
+               }
+               else {
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                               return false; /* read_callback_ sets the state for us */
+               }
+               if(x == FLAC__STREAM_SYNC_STRING[i]) {
+                       first = true;
+                       i++;
+                       id = 0;
+                       continue;
+               }
+
+               if(id >= 3)
+                       return false;
+
+               if(x == ID3V2_TAG_[id]) {
+                       id++;
+                       i = 0;
+                       if(id == 3) {
+                               if(!skip_id3v2_tag_(decoder))
+                                       return false; /* skip_id3v2_tag_ sets the state for us */
+                       }
+                       continue;
+               }
+               id = 0;
+               if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
+                       decoder->private_->header_warmup[0] = (FLAC__byte)x;
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                               return false; /* read_callback_ sets the state for us */
+
+                       /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
+                       /* else we have to check if the second byte is the end of a sync code */
+                       if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
+                               decoder->private_->lookahead = (FLAC__byte)x;
+                               decoder->private_->cached = true;
+                       }
+                       else if(x >> 1 == 0x7c) { /* MAGIC NUMBER for the last 6 sync bits and reserved 7th bit */
+                               decoder->private_->header_warmup[1] = (FLAC__byte)x;
+                               decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
+                               return true;
+                       }
+               }
+               i = 0;
+               if(first) {
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+                       first = false;
+               }
+       }
+
+       decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
+       return true;
+}
+
+FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
+{
+       FLAC__bool is_last;
+       FLAC__uint32 i, x, type, length;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
+               return false; /* read_callback_ sets the state for us */
+       is_last = x? true : false;
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       if(type == FLAC__METADATA_TYPE_STREAMINFO) {
+               if(!read_metadata_streaminfo_(decoder, is_last, length))
+                       return false;
+
+               decoder->private_->has_stream_info = true;
+               if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
+                       decoder->private_->do_md5_checking = false;
+               if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
+                       decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
+       }
+       else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
+               /* just in case we already have a seek table, and reading the next one fails: */
+               decoder->private_->has_seek_table = false;
+
+               if(!read_metadata_seektable_(decoder, is_last, length))
+                       return false;
+
+               decoder->private_->has_seek_table = true;
+               if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
+                       decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
+       }
+       else {
+               FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
+               unsigned real_length = length;
+               FLAC__StreamMetadata block;
+
+               memset(&block, 0, sizeof(block));
+               block.is_last = is_last;
+               block.type = (FLAC__MetadataType)type;
+               block.length = length;
+
+               if(type == FLAC__METADATA_TYPE_APPLICATION) {
+                       if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
+                               return false; /* read_callback_ sets the state for us */
+
+                       if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
+                               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
+                               return false;
+                       }
+
+                       real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
+
+                       if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
+                               skip_it = !skip_it;
+               }
+
+               if(skip_it) {
+                       if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
+                               return false; /* read_callback_ sets the state for us */
+               }
+               else {
+                       FLAC__bool ok = true;
+                       switch(type) {
+                               case FLAC__METADATA_TYPE_PADDING:
+                                       /* skip the padding bytes */
+                                       if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
+                                               ok = false; /* read_callback_ sets the state for us */
+                                       break;
+                               case FLAC__METADATA_TYPE_APPLICATION:
+                                       /* remember, we read the ID already */
+                                       if(real_length > 0) {
+                                               if(0 == (block.data.application.data = malloc(real_length))) {
+                                                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                                                       ok = false;
+                                               }
+                                               else if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
+                                                       ok = false; /* read_callback_ sets the state for us */
+                                       }
+                                       else
+                                               block.data.application.data = 0;
+                                       break;
+                               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                                       if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment, real_length))
+                                               ok = false;
+                                       break;
+                               case FLAC__METADATA_TYPE_CUESHEET:
+                                       if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
+                                               ok = false;
+                                       break;
+                               case FLAC__METADATA_TYPE_PICTURE:
+                                       if(!read_metadata_picture_(decoder, &block.data.picture))
+                                               ok = false;
+                                       break;
+                               case FLAC__METADATA_TYPE_STREAMINFO:
+                               case FLAC__METADATA_TYPE_SEEKTABLE:
+                                       FLAC__ASSERT(0);
+                                       break;
+                               default:
+                                       if(real_length > 0) {
+                                               if(0 == (block.data.unknown.data = malloc(real_length))) {
+                                                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                                                       ok = false;
+                                               }
+                                               else if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
+                                                       ok = false; /* read_callback_ sets the state for us */
+                                       }
+                                       else
+                                               block.data.unknown.data = 0;
+                                       break;
+                       }
+                       if(ok && !decoder->private_->is_seeking && decoder->private_->metadata_callback)
+                               decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
+
+                       /* now we have to free any malloc()ed data in the block */
+                       switch(type) {
+                               case FLAC__METADATA_TYPE_PADDING:
+                                       break;
+                               case FLAC__METADATA_TYPE_APPLICATION:
+                                       if(0 != block.data.application.data)
+                                               free(block.data.application.data);
+                                       break;
+                               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                                       if(0 != block.data.vorbis_comment.vendor_string.entry)
+                                               free(block.data.vorbis_comment.vendor_string.entry);
+                                       if(block.data.vorbis_comment.num_comments > 0)
+                                               for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
+                                                       if(0 != block.data.vorbis_comment.comments[i].entry)
+                                                               free(block.data.vorbis_comment.comments[i].entry);
+                                       if(0 != block.data.vorbis_comment.comments)
+                                               free(block.data.vorbis_comment.comments);
+                                       break;
+                               case FLAC__METADATA_TYPE_CUESHEET:
+                                       if(block.data.cue_sheet.num_tracks > 0)
+                                               for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
+                                                       if(0 != block.data.cue_sheet.tracks[i].indices)
+                                                               free(block.data.cue_sheet.tracks[i].indices);
+                                       if(0 != block.data.cue_sheet.tracks)
+                                               free(block.data.cue_sheet.tracks);
+                                       break;
+                               case FLAC__METADATA_TYPE_PICTURE:
+                                       if(0 != block.data.picture.mime_type)
+                                               free(block.data.picture.mime_type);
+                                       if(0 != block.data.picture.description)
+                                               free(block.data.picture.description);
+                                       if(0 != block.data.picture.data)
+                                               free(block.data.picture.data);
+                                       break;
+                               case FLAC__METADATA_TYPE_STREAMINFO:
+                               case FLAC__METADATA_TYPE_SEEKTABLE:
+                                       FLAC__ASSERT(0);
+                               default:
+                                       if(0 != block.data.unknown.data)
+                                               free(block.data.unknown.data);
+                                       break;
+                       }
+
+                       if(!ok) /* anything that unsets "ok" should also make sure decoder->protected_->state is updated */
+                               return false;
+               }
+       }
+
+       if(is_last) {
+               /* if this fails, it's OK, it's just a hint for the seek routine */
+               if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
+                       decoder->private_->first_frame_offset = 0;
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+       }
+
+       return true;
+}
+
+FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
+{
+       FLAC__uint32 x;
+       unsigned bits, used_bits = 0;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
+       decoder->private_->stream_info.is_last = is_last;
+       decoder->private_->stream_info.length = length;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.min_blocksize = x;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.max_blocksize = x;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.min_framesize = x;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.max_framesize = x;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.sample_rate = x;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.channels = x+1;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
+       used_bits += bits;
+
+       bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
+       if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
+               return false; /* read_callback_ sets the state for us */
+       used_bits += bits;
+
+       if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
+               return false; /* read_callback_ sets the state for us */
+       used_bits += 16*8;
+
+       /* skip the rest of the block */
+       FLAC__ASSERT(used_bits % 8 == 0);
+       length -= (used_bits / 8);
+       if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
+               return false; /* read_callback_ sets the state for us */
+
+       return true;
+}
+
+FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
+{
+       FLAC__uint32 i, x;
+       FLAC__uint64 xx;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
+       decoder->private_->seek_table.is_last = is_last;
+       decoder->private_->seek_table.length = length;
+
+       decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
+
+       /* use realloc since we may pass through here several times (e.g. after seeking) */
+       if(0 == (decoder->private_->seek_table.data.seek_table.points = safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
+               if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
+                       return false; /* read_callback_ sets the state for us */
+               decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
+
+               if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
+                       return false; /* read_callback_ sets the state for us */
+               decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
+
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
+                       return false; /* read_callback_ sets the state for us */
+               decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
+       }
+       length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
+       /* if there is a partial point left, skip over it */
+       if(length > 0) {
+               /*@@@ do a send_error_to_client_() here?  there's an argument for either way */
+               if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
+                       return false; /* read_callback_ sets the state for us */
+       }
+
+       return true;
+}
+
+FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length)
+{
+       FLAC__uint32 i;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       /* read vendor string */
+       if (length >= 8) {
+               length -= 8; /* vendor string length + num comments entries alone take 8 bytes */
+               FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
+               if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
+                       return false; /* read_callback_ sets the state for us */
+               if (obj->vendor_string.length > 0) {
+                       if (length < obj->vendor_string.length) {
+                               obj->vendor_string.length = 0;
+                               obj->vendor_string.entry = 0;
+                               goto skip;
+                       }
+                       else
+                               length -= obj->vendor_string.length;
+                       if (0 == (obj->vendor_string.entry = safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
+                               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                               return false;
+                       }
+                       if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
+                               return false; /* read_callback_ sets the state for us */
+                       obj->vendor_string.entry[obj->vendor_string.length] = '\0';
+               }
+               else
+                       obj->vendor_string.entry = 0;
+
+               /* read num comments */
+               FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
+               if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
+                       return false; /* read_callback_ sets the state for us */
+
+               /* read comments */
+               if (obj->num_comments > 100000) {
+                       /* Possibly malicious file. */
+                       obj->num_comments = 0;
+                       return false;
+               }
+               if (obj->num_comments > 0) {
+                       if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
+                               obj->num_comments = 0;
+                               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                               return false;
+                       }
+                       for (i = 0; i < obj->num_comments; i++) {
+                               /* Initialize here just to make sure. */
+                               obj->comments[i].length = 0;
+                               obj->comments[i].entry = 0;
+
+                               FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
+                               if (length < 4) {
+                                       obj->num_comments = i;
+                                       goto skip;
+                               }
+                               else
+                                       length -= 4;
+                               if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length)) {
+                                       obj->num_comments = i;
+                                       return false; /* read_callback_ sets the state for us */
+                               }
+                               if (obj->comments[i].length > 0) {
+                                       if (length < obj->comments[i].length) {
+                                               obj->num_comments = i;
+                                               goto skip;
+                                       }
+                                       else
+                                               length -= obj->comments[i].length;
+                                       if (0 == (obj->comments[i].entry = safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
+                                               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                                               obj->num_comments = i;
+                                               return false;
+                                       }
+                                       memset (obj->comments[i].entry, 0, obj->comments[i].length) ;
+                                       if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) {
+                                               obj->num_comments = i;
+                                               goto skip;
+                                       }
+                                       obj->comments[i].entry[obj->comments[i].length] = '\0';
+                               }
+                               else
+                                       obj->comments[i].entry = 0;
+                       }
+               }
+       }
+
+  skip:
+       if (length > 0) {
+               /* length > 0 can only happen on files with invalid data in comments */
+               if(obj->num_comments < 1) {
+                       free(obj->comments);
+                       obj->comments = NULL;
+               }
+               if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
+                       return false; /* read_callback_ sets the state for us */
+       }
+
+       return true;
+}
+
+FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
+{
+       FLAC__uint32 i, j, x;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
+
+       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
+       if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
+               return false; /* read_callback_ sets the state for us */
+
+       if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
+               return false; /* read_callback_ sets the state for us */
+       obj->is_cd = x? true : false;
+
+       if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
+               return false; /* read_callback_ sets the state for us */
+       obj->num_tracks = x;
+
+       if(obj->num_tracks > 0) {
+               if(0 == (obj->tracks = safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                       return false;
+               }
+               for(i = 0; i < obj->num_tracks; i++) {
+                       FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
+                       if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
+                               return false; /* read_callback_ sets the state for us */
+
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       track->number = (FLAC__byte)x;
+
+                       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
+                       if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
+                               return false; /* read_callback_ sets the state for us */
+
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       track->type = x;
+
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       track->pre_emphasis = x;
+
+                       if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
+                               return false; /* read_callback_ sets the state for us */
+
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       track->num_indices = (FLAC__byte)x;
+
+                       if(track->num_indices > 0) {
+                               if(0 == (track->indices = safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
+                                       decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+                                       return false;
+                               }
+                               for(j = 0; j < track->num_indices; j++) {
+                                       FLAC__StreamMetadata_CueSheet_Index *indx = &track->indices[j];
+                                       if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &indx->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
+                                               return false; /* read_callback_ sets the state for us */
+
+                                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
+                                               return false; /* read_callback_ sets the state for us */
+                                       indx->number = (FLAC__byte)x;
+
+                                       if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
+                                               return false; /* read_callback_ sets the state for us */
+                               }
+                       }
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
+{
+       FLAC__uint32 x;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       /* read type */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       obj->type = x;
+
+       /* read MIME type */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(0 == (obj->mime_type = safe_malloc_add_2op_(x, /*+*/1))) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       if(x > 0) {
+               if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
+                       return false; /* read_callback_ sets the state for us */
+       }
+       obj->mime_type[x] = '\0';
+
+       /* read description */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(0 == (obj->description = safe_malloc_add_2op_(x, /*+*/1))) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       if(x > 0) {
+               if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
+                       return false; /* read_callback_ sets the state for us */
+       }
+       obj->description[x] = '\0';
+
+       /* read width */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       /* read height */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       /* read depth */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       /* read colors */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
+               return false; /* read_callback_ sets the state for us */
+
+       /* read data */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(0 == (obj->data = safe_malloc_(obj->data_length))) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+       if(obj->data_length > 0) {
+               if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
+                       return false; /* read_callback_ sets the state for us */
+       }
+
+       return true;
+}
+
+FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
+{
+       FLAC__uint32 x;
+       unsigned i, skip;
+
+       /* skip the version and flags bytes */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
+               return false; /* read_callback_ sets the state for us */
+       /* get the size (in bytes) to skip */
+       skip = 0;
+       for(i = 0; i < 4; i++) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                       return false; /* read_callback_ sets the state for us */
+               skip <<= 7;
+               skip |= (x & 0x7f);
+       }
+       /* skip the rest of the tag */
+       if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
+               return false; /* read_callback_ sets the state for us */
+       return true;
+}
+
+FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
+{
+       FLAC__uint32 x;
+       FLAC__bool first = true;
+
+       /* If we know the total number of samples in the stream, stop if we've read that many. */
+       /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
+       if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
+               if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
+                       return true;
+               }
+       }
+
+       /* make sure we're byte aligned */
+       if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
+                       return false; /* read_callback_ sets the state for us */
+       }
+
+       while(1) {
+               if(decoder->private_->cached) {
+                       x = (FLAC__uint32)decoder->private_->lookahead;
+                       decoder->private_->cached = false;
+               }
+               else {
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                               return false; /* read_callback_ sets the state for us */
+               }
+               if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
+                       decoder->private_->header_warmup[0] = (FLAC__byte)x;
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                               return false; /* read_callback_ sets the state for us */
+
+                       /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
+                       /* else we have to check if the second byte is the end of a sync code */
+                       if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
+                               decoder->private_->lookahead = (FLAC__byte)x;
+                               decoder->private_->cached = true;
+                       }
+                       else if(x >> 1 == 0x7c) { /* MAGIC NUMBER for the last 6 sync bits and reserved 7th bit */
+                               decoder->private_->header_warmup[1] = (FLAC__byte)x;
+                               decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
+                               return true;
+                       }
+               }
+               if(first) {
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+                       first = false;
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
+{
+       unsigned channel;
+       unsigned i;
+       FLAC__int32 mid, side;
+       unsigned frame_crc; /* the one we calculate from the input stream */
+       FLAC__uint32 x;
+
+       *got_a_frame = false;
+
+       /* init the CRC */
+       frame_crc = 0;
+       frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
+       frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
+       FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
+
+       if(!read_frame_header_(decoder))
+               return false;
+       if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
+               return true;
+       if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
+               return false;
+       for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
+               /*
+                * first figure the correct bits-per-sample of the subframe
+                */
+               unsigned bps = decoder->private_->frame.header.bits_per_sample;
+               switch(decoder->private_->frame.header.channel_assignment) {
+                       case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
+                               /* no adjustment needed */
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
+                               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                               if(channel == 1)
+                                       bps++;
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
+                               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                               if(channel == 0)
+                                       bps++;
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
+                               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                               if(channel == 1)
+                                       bps++;
+                               break;
+                       default:
+                               FLAC__ASSERT(0);
+               }
+               /*
+                * now read it
+                */
+               if(!read_subframe_(decoder, channel, bps, do_full_decode))
+                       return false;
+               if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
+                       return true;
+       }
+       if(!read_zero_padding_(decoder))
+               return false;
+       if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
+               return true;
+
+       /*
+        * Read the frame CRC-16 from the footer and check
+        */
+       frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(frame_crc == x) {
+               if(do_full_decode) {
+                       /* Undo any special channel coding */
+                       switch(decoder->private_->frame.header.channel_assignment) {
+                               case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
+                                       /* do nothing */
+                                       break;
+                               case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
+                                       FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                                       for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
+                                               decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
+                                       break;
+                               case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
+                                       FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                                       for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
+                                               decoder->private_->output[0][i] += decoder->private_->output[1][i];
+                                       break;
+                               case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
+                                       FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
+                                       for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
+#if 1
+                                               mid = decoder->private_->output[0][i];
+                                               side = decoder->private_->output[1][i];
+                                               mid = ((uint32_t) mid) << 1;
+                                               mid |= (side & 1); /* i.e. if 'side' is odd... */
+                                               decoder->private_->output[0][i] = (mid + side) >> 1;
+                                               decoder->private_->output[1][i] = (mid - side) >> 1;
+#else
+                                               /* OPT: without 'side' temp variable */
+                                               mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
+                                               decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
+                                               decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
+#endif
+                                       }
+                                       break;
+                               default:
+                                       FLAC__ASSERT(0);
+                                       break;
+                       }
+               }
+       }
+       else {
+               /* Bad frame, emit error and zero the output signal */
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
+               if(do_full_decode) {
+                       for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
+                               memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
+                       }
+               }
+       }
+
+       *got_a_frame = true;
+
+       /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
+       if(decoder->private_->next_fixed_block_size)
+               decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
+
+       /* put the latest values into the public section of the decoder instance */
+       decoder->protected_->channels = decoder->private_->frame.header.channels;
+       decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
+       decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
+       decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
+       decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
+
+       FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
+       decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
+
+       /* write it */
+       if(do_full_decode) {
+               if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
+                       return false;
+               }
+       }
+
+       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+       return true;
+}
+
+FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
+{
+       FLAC__uint32 x;
+       FLAC__uint64 xx;
+       unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
+       FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
+       unsigned raw_header_len;
+       FLAC__bool is_unparseable = false;
+
+       FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
+
+       /* init the raw header with the saved bits from synchronization */
+       raw_header[0] = decoder->private_->header_warmup[0];
+       raw_header[1] = decoder->private_->header_warmup[1];
+       raw_header_len = 2;
+
+       /* check to make sure that reserved bit is 0 */
+       if(raw_header[1] & 0x02) /* MAGIC NUMBER */
+               is_unparseable = true;
+
+       /*
+        * Note that along the way as we read the header, we look for a sync
+        * code inside.  If we find one it would indicate that our original
+        * sync was bad since there cannot be a sync code in a valid header.
+        *
+        * Three kinds of things can go wrong when reading the frame header:
+        *  1) We may have sync'ed incorrectly and not landed on a frame header.
+        *     If we don't find a sync code, it can end up looking like we read
+        *     a valid but unparseable header, until getting to the frame header
+        *     CRC.  Even then we could get a false positive on the CRC.
+        *  2) We may have sync'ed correctly but on an unparseable frame (from a
+        *     future encoder).
+        *  3) We may be on a damaged frame which appears valid but unparseable.
+        *
+        * For all these reasons, we try and read a complete frame header as
+        * long as it seems valid, even if unparseable, up until the frame
+        * header CRC.
+        */
+
+       /*
+        * read in the raw header as bytes so we can CRC it, and parse it on the way
+        */
+       for(i = 0; i < 2; i++) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                       return false; /* read_callback_ sets the state for us */
+               if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
+                       /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
+                       decoder->private_->lookahead = (FLAC__byte)x;
+                       decoder->private_->cached = true;
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+               }
+               raw_header[raw_header_len++] = (FLAC__byte)x;
+       }
+
+       switch(x = raw_header[2] >> 4) {
+               case 0:
+                       is_unparseable = true;
+                       break;
+               case 1:
+                       decoder->private_->frame.header.blocksize = 192;
+                       break;
+               case 2:
+               case 3:
+               case 4:
+               case 5:
+                       decoder->private_->frame.header.blocksize = 576 << (x-2);
+                       break;
+               case 6:
+               case 7:
+                       blocksize_hint = x;
+                       break;
+               case 8:
+               case 9:
+               case 10:
+               case 11:
+               case 12:
+               case 13:
+               case 14:
+               case 15:
+                       decoder->private_->frame.header.blocksize = 256 << (x-8);
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+                       break;
+       }
+
+       switch(x = raw_header[2] & 0x0f) {
+               case 0:
+                       if(decoder->private_->has_stream_info)
+                               decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
+                       else
+                               is_unparseable = true;
+                       break;
+               case 1:
+                       decoder->private_->frame.header.sample_rate = 88200;
+                       break;
+               case 2:
+                       decoder->private_->frame.header.sample_rate = 176400;
+                       break;
+               case 3:
+                       decoder->private_->frame.header.sample_rate = 192000;
+                       break;
+               case 4:
+                       decoder->private_->frame.header.sample_rate = 8000;
+                       break;
+               case 5:
+                       decoder->private_->frame.header.sample_rate = 16000;
+                       break;
+               case 6:
+                       decoder->private_->frame.header.sample_rate = 22050;
+                       break;
+               case 7:
+                       decoder->private_->frame.header.sample_rate = 24000;
+                       break;
+               case 8:
+                       decoder->private_->frame.header.sample_rate = 32000;
+                       break;
+               case 9:
+                       decoder->private_->frame.header.sample_rate = 44100;
+                       break;
+               case 10:
+                       decoder->private_->frame.header.sample_rate = 48000;
+                       break;
+               case 11:
+                       decoder->private_->frame.header.sample_rate = 96000;
+                       break;
+               case 12:
+               case 13:
+               case 14:
+                       sample_rate_hint = x;
+                       break;
+               case 15:
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       x = (unsigned)(raw_header[3] >> 4);
+       if(x & 8) {
+               decoder->private_->frame.header.channels = 2;
+               switch(x & 7) {
+                       case 0:
+                               decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
+                               break;
+                       case 1:
+                               decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
+                               break;
+                       case 2:
+                               decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
+                               break;
+                       default:
+                               is_unparseable = true;
+                               break;
+               }
+       }
+       else {
+               decoder->private_->frame.header.channels = (unsigned)x + 1;
+               decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
+       }
+
+       switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
+               case 0:
+                       if(decoder->private_->has_stream_info)
+                               decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
+                       else
+                               is_unparseable = true;
+                       break;
+               case 1:
+                       decoder->private_->frame.header.bits_per_sample = 8;
+                       break;
+               case 2:
+                       decoder->private_->frame.header.bits_per_sample = 12;
+                       break;
+               case 4:
+                       decoder->private_->frame.header.bits_per_sample = 16;
+                       break;
+               case 5:
+                       decoder->private_->frame.header.bits_per_sample = 20;
+                       break;
+               case 6:
+                       decoder->private_->frame.header.bits_per_sample = 24;
+                       break;
+               case 3:
+               case 7:
+                       is_unparseable = true;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+                       break;
+       }
+
+       /* check to make sure that reserved bit is 0 */
+       if(raw_header[3] & 0x01) /* MAGIC NUMBER */
+               is_unparseable = true;
+
+       /* read the frame's starting sample number (or frame number as the case may be) */
+       if(
+               raw_header[1] & 0x01 ||
+               /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
+               (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
+       ) { /* variable blocksize */
+               if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
+                       return false; /* read_callback_ sets the state for us */
+               if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
+                       decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
+                       decoder->private_->cached = true;
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+               }
+               decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
+               decoder->private_->frame.header.number.sample_number = xx;
+       }
+       else { /* fixed blocksize */
+               if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
+                       return false; /* read_callback_ sets the state for us */
+               if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
+                       decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
+                       decoder->private_->cached = true;
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+               }
+               decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
+               decoder->private_->frame.header.number.frame_number = x;
+       }
+
+       if(blocksize_hint) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                       return false; /* read_callback_ sets the state for us */
+               raw_header[raw_header_len++] = (FLAC__byte)x;
+               if(blocksize_hint == 7) {
+                       FLAC__uint32 _x;
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
+                               return false; /* read_callback_ sets the state for us */
+                       raw_header[raw_header_len++] = (FLAC__byte)_x;
+                       x = (x << 8) | _x;
+               }
+               decoder->private_->frame.header.blocksize = x+1;
+       }
+
+       if(sample_rate_hint) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+                       return false; /* read_callback_ sets the state for us */
+               raw_header[raw_header_len++] = (FLAC__byte)x;
+               if(sample_rate_hint != 12) {
+                       FLAC__uint32 _x;
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
+                               return false; /* read_callback_ sets the state for us */
+                       raw_header[raw_header_len++] = (FLAC__byte)_x;
+                       x = (x << 8) | _x;
+               }
+               if(sample_rate_hint == 12)
+                       decoder->private_->frame.header.sample_rate = x*1000;
+               else if(sample_rate_hint == 13)
+                       decoder->private_->frame.header.sample_rate = x;
+               else
+                       decoder->private_->frame.header.sample_rate = x*10;
+       }
+
+       /* read the CRC-8 byte */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
+               return false; /* read_callback_ sets the state for us */
+       crc8 = (FLAC__byte)x;
+
+       if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+
+       /* calculate the sample number from the frame number if needed */
+       decoder->private_->next_fixed_block_size = 0;
+       if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
+               x = decoder->private_->frame.header.number.frame_number;
+               decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
+               if(decoder->private_->fixed_block_size)
+                       decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
+               else if(decoder->private_->has_stream_info) {
+                       if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
+                               decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
+                               decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
+                       }
+                       else
+                               is_unparseable = true;
+               }
+               else if(x == 0) {
+                       decoder->private_->frame.header.number.sample_number = 0;
+                       decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
+               }
+               else {
+                       /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
+                       decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
+               }
+       }
+
+       if(is_unparseable) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+
+       return true;
+}
+
+FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
+{
+       FLAC__uint32 x;
+       FLAC__bool wasted_bits;
+       unsigned i;
+
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
+               return false; /* read_callback_ sets the state for us */
+
+       wasted_bits = (x & 1);
+       x &= 0xfe;
+
+       if(wasted_bits) {
+               unsigned u;
+               if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
+                       return false; /* read_callback_ sets the state for us */
+               decoder->private_->frame.subframes[channel].wasted_bits = u+1;
+               if (decoder->private_->frame.subframes[channel].wasted_bits >= bps)
+                       return false;
+               bps -= decoder->private_->frame.subframes[channel].wasted_bits;
+       }
+       else
+               decoder->private_->frame.subframes[channel].wasted_bits = 0;
+
+       /*
+        * Lots of magic numbers here
+        */
+       if(x & 0x80) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+       else if(x == 0) {
+               if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
+                       return false;
+       }
+       else if(x == 2) {
+               if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
+                       return false;
+       }
+       else if(x < 16) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+       else if(x <= 24) {
+               if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
+                       return false;
+               if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
+                       return true;
+       }
+       else if(x < 64) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+       else {
+               if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
+                       return false;
+               if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
+                       return true;
+       }
+
+       if(wasted_bits && do_full_decode) {
+               x = decoder->private_->frame.subframes[channel].wasted_bits;
+               for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
+                       uint32_t val = decoder->private_->output[channel][i];
+                       decoder->private_->output[channel][i] = (val << x);
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
+{
+       FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
+       FLAC__int32 x;
+       unsigned i;
+       FLAC__int32 *output = decoder->private_->output[channel];
+
+       decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
+
+       if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
+               return false; /* read_callback_ sets the state for us */
+
+       subframe->value = x;
+
+       /* decode the subframe */
+       if(do_full_decode) {
+               for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
+                       output[i] = x;
+       }
+
+       return true;
+}
+
+FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
+{
+       FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
+       FLAC__int32 i32;
+       FLAC__uint32 u32;
+       unsigned u;
+
+       decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
+
+       subframe->residual = decoder->private_->residual[channel];
+       subframe->order = order;
+
+       /* read warm-up samples */
+       for(u = 0; u < order; u++) {
+               if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
+                       return false; /* read_callback_ sets the state for us */
+               subframe->warmup[u] = i32;
+       }
+
+       /* read entropy coding method info */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       if(decoder->private_->frame.header.blocksize >> u32 < order) {
+                               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                               return true;
+                       }
+                       subframe->entropy_coding_method.data.partitioned_rice.order = u32;
+                       subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
+                       break;
+               default:
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+       }
+
+       /* read residual */
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
+                               return false;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       /* decode the subframe */
+       if(do_full_decode) {
+               memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
+               FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
+       }
+
+       return true;
+}
+
+FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
+{
+       FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
+       FLAC__int32 i32;
+       FLAC__uint32 u32;
+       unsigned u;
+
+       decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
+
+       subframe->residual = decoder->private_->residual[channel];
+       subframe->order = order;
+
+       /* read warm-up samples */
+       for(u = 0; u < order; u++) {
+               if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
+                       return false; /* read_callback_ sets the state for us */
+               subframe->warmup[u] = i32;
+       }
+
+       /* read qlp coeff precision */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+       subframe->qlp_coeff_precision = u32+1;
+
+       /* read qlp shift */
+       if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
+               return false; /* read_callback_ sets the state for us */
+       if(i32 < 0) {
+               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               return true;
+       }
+       subframe->quantization_level = i32;
+
+       /* read quantized lp coefficiencts */
+       for(u = 0; u < order; u++) {
+               if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
+                       return false; /* read_callback_ sets the state for us */
+               subframe->qlp_coeff[u] = i32;
+       }
+
+       /* read entropy coding method info */
+       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
+               return false; /* read_callback_ sets the state for us */
+       subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       if(decoder->private_->frame.header.blocksize >> u32 < order) {
+                               send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                               return true;
+                       }
+                       subframe->entropy_coding_method.data.partitioned_rice.order = u32;
+                       subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
+                       break;
+               default:
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+                       return true;
+       }
+
+       /* read residual */
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
+                               return false;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       /* decode the subframe */
+       if(do_full_decode) {
+               memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
+               if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
+                       if(bps <= 16 && subframe->qlp_coeff_precision <= 16)
+                               decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
+                       else
+                               decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
+               else
+                       decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
+       }
+
+       return true;
+}
+
+FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
+{
+       FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
+       FLAC__int32 x, *residual = decoder->private_->residual[channel];
+       unsigned i;
+
+       decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
+
+       subframe->data = residual;
+
+       for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
+               if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
+                       return false; /* read_callback_ sets the state for us */
+               residual[i] = x;
+       }
+
+       /* decode the subframe */
+       if(do_full_decode)
+               memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
+
+       return true;
+}
+
+FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
+{
+       FLAC__uint32 rice_parameter;
+       int i;
+       unsigned partition, sample, u;
+       const unsigned partitions = 1u << partition_order;
+       const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
+       const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
+       const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
+
+       /* invalid predictor and partition orders mush be handled in the callers */
+       FLAC__ASSERT(partition_order > 0? partition_samples >= predictor_order : decoder->private_->frame.header.blocksize >= predictor_order);
+
+       if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order))) {
+               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       sample = 0;
+       for(partition = 0; partition < partitions; partition++) {
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
+                       return false; /* read_callback_ sets the state for us */
+               partitioned_rice_contents->parameters[partition] = rice_parameter;
+               if(rice_parameter < pesc) {
+                       partitioned_rice_contents->raw_bits[partition] = 0;
+                       u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
+                       if(!FLAC__bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
+                               return false; /* read_callback_ sets the state for us */
+                       sample += u;
+               }
+               else {
+                       if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
+                               return false; /* read_callback_ sets the state for us */
+                       partitioned_rice_contents->raw_bits[partition] = rice_parameter;
+                       for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
+                               if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
+                                       return false; /* read_callback_ sets the state for us */
+                               residual[sample] = i;
+                       }
+               }
+       }
+
+       return true;
+}
+
+FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
+{
+       if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
+               FLAC__uint32 zero = 0;
+               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
+                       return false; /* read_callback_ sets the state for us */
+               if(zero != 0) {
+                       send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
+               }
+       }
+       return true;
+}
+
+FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
+
+       if(
+#if FLAC__HAS_OGG
+               /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
+               !decoder->private_->is_ogg &&
+#endif
+               decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
+       ) {
+               *bytes = 0;
+               decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
+               return false;
+       }
+       else if(*bytes > 0) {
+               /* While seeking, it is possible for our seek to land in the
+                * middle of audio data that looks exactly like a frame header
+                * from a future version of an encoder.  When that happens, our
+                * error callback will get an
+                * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
+                * unparseable_frame_count.  But there is a remote possibility
+                * that it is properly synced at such a "future-codec frame",
+                * so to make sure, we wait to see many "unparseable" errors in
+                * a row before bailing out.
+                */
+               if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
+                       return false;
+               }
+               else {
+                       const FLAC__StreamDecoderReadStatus status =
+#if FLAC__HAS_OGG
+                               decoder->private_->is_ogg?
+                               read_callback_ogg_aspect_(decoder, buffer, bytes) :
+#endif
+                               decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
+                       ;
+                       if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
+                               decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
+                               return false;
+                       }
+                       else if(*bytes == 0) {
+                               if(
+                                       status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
+                                       (
+#if FLAC__HAS_OGG
+                                               /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
+                                               !decoder->private_->is_ogg &&
+#endif
+                                               decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
+                                       )
+                               ) {
+                                       decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
+                                       return false;
+                               }
+                               else
+                                       return true;
+                       }
+                       else
+                               return true;
+               }
+       }
+       else {
+               /* abort to avoid a deadlock */
+               decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
+               return false;
+       }
+       /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
+        * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
+        * and at the same time hit the end of the stream (for example, seeking
+        * to a point that is after the beginning of the last Ogg page).  There
+        * is no way to report an Ogg sync loss through the callbacks (see note
+        * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
+        * So to keep the decoder from stopping at this point we gate the call
+        * to the eof_callback and let the Ogg decoder aspect set the
+        * end-of-stream state when it is needed.
+        */
+}
+
+#if FLAC__HAS_OGG
+FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
+{
+       switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
+                       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+               /* we don't really have a way to handle lost sync via read
+                * callback so we'll let it pass and let the underlying
+                * FLAC decoder catch the error
+                */
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
+                       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
+                       return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
+               case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
+                       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+               default:
+                       FLAC__ASSERT(0);
+                       /* double protection */
+                       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+       }
+}
+
+FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
+
+       switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
+               case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
+                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
+               case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
+                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
+               case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
+                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
+               default:
+                       /* double protection: */
+                       FLAC__ASSERT(0);
+                       return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
+       }
+}
+#endif
+
+FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
+{
+       if(decoder->private_->is_seeking) {
+               FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
+               FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
+               FLAC__uint64 target_sample = decoder->private_->target_sample;
+
+               FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
+
+#if FLAC__HAS_OGG
+               decoder->private_->got_a_frame = true;
+#endif
+               decoder->private_->last_frame = *frame; /* save the frame */
+               if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
+                       unsigned delta = (unsigned)(target_sample - this_frame_sample);
+                       /* kick out of seek mode */
+                       decoder->private_->is_seeking = false;
+                       /* shift out the samples before target_sample */
+                       if(delta > 0) {
+                               unsigned channel;
+                               const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
+                               for(channel = 0; channel < frame->header.channels; channel++)
+                                       newbuffer[channel] = buffer[channel] + delta;
+                               decoder->private_->last_frame.header.blocksize -= delta;
+                               decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
+                               /* write the relevant samples */
+                               return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
+                       }
+                       else {
+                               /* write the relevant samples */
+                               return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
+                       }
+               }
+               else {
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
+               }
+       }
+       else {
+               /*
+                * If we never got STREAMINFO, turn off MD5 checking to save
+                * cycles since we don't have a sum to compare to anyway
+                */
+               if(!decoder->private_->has_stream_info)
+                       decoder->private_->do_md5_checking = false;
+               if(decoder->private_->do_md5_checking) {
+                       if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
+                               return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+               return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
+       }
+}
+
+void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
+{
+       if(!decoder->private_->is_seeking)
+               decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
+       else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
+               decoder->private_->unparseable_frame_count++;
+}
+
+FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
+{
+       FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
+       FLAC__int64 pos = -1;
+       int i;
+       unsigned approx_bytes_per_frame;
+       FLAC__bool first_seek = true;
+       const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
+       const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
+       const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
+       const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
+       const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
+       /* take these from the current frame in case they've changed mid-stream */
+       unsigned channels = FLAC__stream_decoder_get_channels(decoder);
+       unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
+       const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
+
+       /* use values from stream info if we didn't decode a frame */
+       if(channels == 0)
+               channels = decoder->private_->stream_info.data.stream_info.channels;
+       if(bps == 0)
+               bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
+
+       /* we are just guessing here */
+       if(max_framesize > 0)
+               approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
+       /*
+        * Check if it's a known fixed-blocksize stream.  Note that though
+        * the spec doesn't allow zeroes in the STREAMINFO block, we may
+        * never get a STREAMINFO block when decoding so the value of
+        * min_blocksize might be zero.
+        */
+       else if(min_blocksize == max_blocksize && min_blocksize > 0) {
+               /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
+               approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
+       }
+       else
+               approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
+
+       /*
+        * First, we set an upper and lower bound on where in the
+        * stream we will search.  For now we assume the worst case
+        * scenario, which is our best guess at the beginning of
+        * the first frame and end of the stream.
+        */
+       lower_bound = first_frame_offset;
+       lower_bound_sample = 0;
+       upper_bound = stream_length;
+       upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
+
+       /*
+        * Now we refine the bounds if we have a seektable with
+        * suitable points.  Note that according to the spec they
+        * must be ordered by ascending sample number.
+        *
+        * Note: to protect against invalid seek tables we will ignore points
+        * that have frame_samples==0 or sample_number>=total_samples
+        */
+       if(seek_table) {
+               FLAC__uint64 new_lower_bound = lower_bound;
+               FLAC__uint64 new_upper_bound = upper_bound;
+               FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
+               FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
+
+               /* find the closest seek point <= target_sample, if it exists */
+               for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
+                       if(
+                               seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
+                               seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
+                               (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
+                               seek_table->points[i].sample_number <= target_sample
+                       )
+                               break;
+               }
+               if(i >= 0) { /* i.e. we found a suitable seek point... */
+                       new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
+                       new_lower_bound_sample = seek_table->points[i].sample_number;
+               }
+
+               /* find the closest seek point > target_sample, if it exists */
+               for(i = 0; i < (int)seek_table->num_points; i++) {
+                       if(
+                               seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
+                               seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
+                               (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
+                               seek_table->points[i].sample_number > target_sample
+                       )
+                               break;
+               }
+               if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
+                       new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
+                       new_upper_bound_sample = seek_table->points[i].sample_number;
+               }
+               /* final protection against unsorted seek tables; keep original values if bogus */
+               if(new_upper_bound >= new_lower_bound) {
+                       lower_bound = new_lower_bound;
+                       upper_bound = new_upper_bound;
+                       lower_bound_sample = new_lower_bound_sample;
+                       upper_bound_sample = new_upper_bound_sample;
+               }
+       }
+
+       FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
+       /* there are 2 insidious ways that the following equality occurs, which
+        * we need to fix:
+        *  1) total_samples is 0 (unknown) and target_sample is 0
+        *  2) total_samples is 0 (unknown) and target_sample happens to be
+        *     exactly equal to the last seek point in the seek table; this
+        *     means there is no seek point above it, and upper_bound_samples
+        *     remains equal to the estimate (of target_samples) we made above
+        * in either case it does not hurt to move upper_bound_sample up by 1
+        */
+       if(upper_bound_sample == lower_bound_sample)
+               upper_bound_sample++;
+
+       decoder->private_->target_sample = target_sample;
+       while(1) {
+               /* check if the bounds are still ok */
+               if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                       return false;
+               }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+               pos = (FLAC__int64)lower_bound + (FLAC__int64)((double)(target_sample - lower_bound_sample) / (double)(upper_bound_sample - lower_bound_sample) * (double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
+#else
+               /* a little less accurate: */
+               if(upper_bound - lower_bound < 0xffffffff)
+                       pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
+               else /* @@@ WATCHOUT, ~2TB limit */
+                       pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
+#endif
+               if(pos >= (FLAC__int64)upper_bound)
+                       pos = (FLAC__int64)upper_bound - 1;
+               if(pos < (FLAC__int64)lower_bound)
+                       pos = (FLAC__int64)lower_bound;
+               if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                       return false;
+               }
+               if(!FLAC__stream_decoder_flush(decoder)) {
+                       /* above call sets the state for us */
+                       return false;
+               }
+               /* Now we need to get a frame.  First we need to reset our
+                * unparseable_frame_count; if we get too many unparseable
+                * frames in a row, the read callback will return
+                * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
+                * FLAC__stream_decoder_process_single() to return false.
+                */
+               decoder->private_->unparseable_frame_count = 0;
+               if(!FLAC__stream_decoder_process_single(decoder) ||
+                  decoder->protected_->state == FLAC__STREAM_DECODER_ABORTED) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                       return false;
+               }
+               /* our write callback will change the state when it gets to the target frame */
+               /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
+#if 0
+               /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
+               if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
+                       break;
+#endif
+               if(!decoder->private_->is_seeking)
+                       break;
+
+               FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
+               this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
+
+               if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
+                       if (pos == (FLAC__int64)lower_bound) {
+                               /* can't move back any more than the first frame, something is fatally wrong */
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                               return false;
+                       }
+                       /* our last move backwards wasn't big enough, try again */
+                       approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
+                       continue;
+               }
+               /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
+               first_seek = false;
+
+               /* make sure we are not seeking in corrupted stream */
+               if (this_frame_sample < lower_bound_sample) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                       return false;
+               }
+
+               /* we need to narrow the search */
+               if(target_sample < this_frame_sample) {
+                       upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
+/*@@@@@@ what will decode position be if at end of stream? */
+                       if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                               return false;
+                       }
+                       approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
+               }
+               else { /* target_sample >= this_frame_sample + this frame's blocksize */
+                       lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
+                       if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                               return false;
+                       }
+                       approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
+               }
+       }
+
+       return true;
+}
+
+#if FLAC__HAS_OGG
+FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
+{
+       FLAC__uint64 left_pos = 0, right_pos = stream_length;
+       FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
+       FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
+       FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
+       FLAC__bool did_a_seek;
+       unsigned iteration = 0;
+
+       /* In the first iterations, we will calculate the target byte position
+        * by the distance from the target sample to left_sample and
+        * right_sample (let's call it "proportional search").  After that, we
+        * will switch to binary search.
+        */
+       unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
+
+       /* We will switch to a linear search once our current sample is less
+        * than this number of samples ahead of the target sample
+        */
+       static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
+
+       /* If the total number of samples is unknown, use a large value, and
+        * force binary search immediately.
+        */
+       if(right_sample == 0) {
+               right_sample = (FLAC__uint64)(-1);
+               BINARY_SEARCH_AFTER_ITERATION = 0;
+       }
+
+       decoder->private_->target_sample = target_sample;
+       for( ; ; iteration++) {
+               if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
+                       if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
+                               pos = (right_pos + left_pos) / 2;
+                       }
+                       else {
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+                               pos = (FLAC__uint64)((double)(target_sample - left_sample) / (double)(right_sample - left_sample) * (double)(right_pos - left_pos));
+#else
+                               /* a little less accurate: */
+                               if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
+                                       pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
+                               else /* @@@ WATCHOUT, ~2TB limit */
+                                       pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
+#endif
+                               /* @@@ TODO: might want to limit pos to some distance
+                                * before EOF, to make sure we land before the last frame,
+                                * thereby getting a this_frame_sample and so having a better
+                                * estimate.
+                                */
+                       }
+
+                       /* physical seek */
+                       if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                               return false;
+                       }
+                       if(!FLAC__stream_decoder_flush(decoder)) {
+                               /* above call sets the state for us */
+                               return false;
+                       }
+                       did_a_seek = true;
+               }
+               else
+                       did_a_seek = false;
+
+               decoder->private_->got_a_frame = false;
+               if(!FLAC__stream_decoder_process_single(decoder) ||
+                  decoder->protected_->state == FLAC__STREAM_DECODER_ABORTED) {
+                       decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                       return false;
+               }
+               if(!decoder->private_->got_a_frame) {
+                       if(did_a_seek) {
+                               /* this can happen if we seek to a point after the last frame; we drop
+                                * to binary search right away in this case to avoid any wasted
+                                * iterations of proportional search.
+                                */
+                               right_pos = pos;
+                               BINARY_SEARCH_AFTER_ITERATION = 0;
+                       }
+                       else {
+                               /* this can probably only happen if total_samples is unknown and the
+                                * target_sample is past the end of the stream
+                                */
+                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                               return false;
+                       }
+               }
+               /* our write callback will change the state when it gets to the target frame */
+               else if(!decoder->private_->is_seeking) {
+                       break;
+               }
+               else {
+                       this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
+                       FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
+
+                       if (did_a_seek) {
+                               if (this_frame_sample <= target_sample) {
+                                       /* The 'equal' case should not happen, since
+                                        * FLAC__stream_decoder_process_single()
+                                        * should recognize that it has hit the
+                                        * target sample and we would exit through
+                                        * the 'break' above.
+                                        */
+                                       FLAC__ASSERT(this_frame_sample != target_sample);
+
+                                       left_sample = this_frame_sample;
+                                       /* sanity check to avoid infinite loop */
+                                       if (left_pos == pos) {
+                                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                                               return false;
+                                       }
+                                       left_pos = pos;
+                               }
+                               else if(this_frame_sample > target_sample) {
+                                       right_sample = this_frame_sample;
+                                       /* sanity check to avoid infinite loop */
+                                       if (right_pos == pos) {
+                                               decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
+                                               return false;
+                                       }
+                                       right_pos = pos;
+                               }
+                       }
+               }
+       }
+
+       return true;
+}
+#endif
+
+FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       (void)client_data;
+
+       if(*bytes > 0) {
+               *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
+               if(ferror(decoder->private_->file))
+                       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+               else if(*bytes == 0)
+                       return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
+               else
+                       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+       }
+       else
+               return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
+}
+
+FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
+{
+       (void)client_data;
+
+       if(decoder->private_->file == stdin)
+               return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
+       else if(fseeko(decoder->private_->file, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
+               return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
+       else
+               return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
+}
+
+FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
+{
+       FLAC__off_t pos;
+       (void)client_data;
+
+       if(decoder->private_->file == stdin)
+               return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
+       else if((pos = ftello(decoder->private_->file)) < 0)
+               return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
+       else {
+               *absolute_byte_offset = (FLAC__uint64)pos;
+               return FLAC__STREAM_DECODER_TELL_STATUS_OK;
+       }
+}
+
+FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
+{
+       struct flac_stat_s filestats;
+       (void)client_data;
+
+       if(decoder->private_->file == stdin)
+               return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
+       else if(flac_fstat(fileno(decoder->private_->file), &filestats) != 0)
+               return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
+       else {
+               *stream_length = (FLAC__uint64)filestats.st_size;
+               return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
+       }
+}
+
+FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
+{
+       (void)client_data;
+
+       return feof(decoder->private_->file)? true : false;
+}
diff --git a/FLAC/src/stream_encoder.c b/FLAC/src/stream_encoder.c
new file mode 100644 (file)
index 0000000..037b8cb
--- /dev/null
@@ -0,0 +1,4549 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <limits.h>
+#include <stdio.h>
+#include <stdlib.h> /* for malloc() */
+#include <string.h> /* for memcpy() */
+#include <sys/types.h> /* for off_t */
+#ifdef _WIN32
+#include <windows.h> /* for GetFileType() */
+#include <io.h> /* for _get_osfhandle() */
+#endif
+#include "share/compat.h"
+#include "FLAC/assert.h"
+#include "FLAC/stream_decoder.h"
+#include "protected/stream_encoder.h"
+#include "private/bitwriter.h"
+#include "private/bitmath.h"
+#include "private/crc.h"
+#include "private/cpu.h"
+#include "private/fixed.h"
+#include "private/format.h"
+#include "private/lpc.h"
+#include "private/md5.h"
+#include "private/memory.h"
+#include "private/macros.h"
+#if FLAC__HAS_OGG
+#include "private/ogg_helper.h"
+#include "private/ogg_mapping.h"
+#endif
+#include "private/stream_encoder.h"
+#include "private/stream_encoder_framing.h"
+#include "private/window.h"
+#include "share/alloc.h"
+#include "share/private.h"
+
+
+/* Exact Rice codeword length calculation is off by default.  The simple
+ * (and fast) estimation (of how many bits a residual value will be
+ * encoded with) in this encoder is very good, almost always yielding
+ * compression within 0.1% of exact calculation.
+ */
+#undef EXACT_RICE_BITS_CALCULATION
+/* Rice parameter searching is off by default.  The simple (and fast)
+ * parameter estimation in this encoder is very good, almost always
+ * yielding compression within 0.1% of the optimal parameters.
+ */
+#undef ENABLE_RICE_PARAMETER_SEARCH
+
+
+typedef struct {
+       FLAC__int32 *data[FLAC__MAX_CHANNELS];
+       unsigned size; /* of each data[] in samples */
+       unsigned tail;
+} verify_input_fifo;
+
+typedef struct {
+       const FLAC__byte *data;
+       unsigned capacity;
+       unsigned bytes;
+} verify_output;
+
+typedef enum {
+       ENCODER_IN_MAGIC = 0,
+       ENCODER_IN_METADATA = 1,
+       ENCODER_IN_AUDIO = 2
+} EncoderStateHint;
+
+static struct CompressionLevels {
+       FLAC__bool do_mid_side_stereo;
+       FLAC__bool loose_mid_side_stereo;
+       unsigned max_lpc_order;
+       unsigned qlp_coeff_precision;
+       FLAC__bool do_qlp_coeff_prec_search;
+       FLAC__bool do_escape_coding;
+       FLAC__bool do_exhaustive_model_search;
+       unsigned min_residual_partition_order;
+       unsigned max_residual_partition_order;
+       unsigned rice_parameter_search_dist;
+       const char *apodization;
+} compression_levels_[] = {
+       { false, false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
+       { true , true ,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
+       { true , false,  0, 0, false, false, false, 0, 3, 0, "tukey(5e-1)" },
+       { false, false,  6, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
+       { true , true ,  8, 0, false, false, false, 0, 4, 0, "tukey(5e-1)" },
+       { true , false,  8, 0, false, false, false, 0, 5, 0, "tukey(5e-1)" },
+       { true , false,  8, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
+       { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2)" },
+       { true , false, 12, 0, false, false, false, 0, 6, 0, "tukey(5e-1);partial_tukey(2);punchout_tukey(3)" }
+       /* here we use locale-independent 5e-1 instead of 0.5 or 0,5 */
+};
+
+
+/***********************************************************************
+ *
+ * Private class method prototypes
+ *
+ ***********************************************************************/
+
+static void set_defaults_(FLAC__StreamEncoder *encoder);
+static void free_(FLAC__StreamEncoder *encoder);
+static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
+static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
+static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
+static void update_metadata_(const FLAC__StreamEncoder *encoder);
+#if FLAC__HAS_OGG
+static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
+#endif
+static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
+static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
+
+static FLAC__bool process_subframe_(
+       FLAC__StreamEncoder *encoder,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       const FLAC__FrameHeader *frame_header,
+       unsigned subframe_bps,
+       const FLAC__int32 integer_signal[],
+       FLAC__Subframe *subframe[2],
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
+       FLAC__int32 *residual[2],
+       unsigned *best_subframe,
+       unsigned *best_bits
+);
+
+static FLAC__bool add_subframe_(
+       FLAC__StreamEncoder *encoder,
+       unsigned blocksize,
+       unsigned subframe_bps,
+       const FLAC__Subframe *subframe,
+       FLAC__BitWriter *frame
+);
+
+static unsigned evaluate_constant_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal,
+       unsigned blocksize,
+       unsigned subframe_bps,
+       FLAC__Subframe *subframe
+);
+
+static unsigned evaluate_fixed_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       unsigned order,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__Subframe *subframe,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
+);
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+static unsigned evaluate_lpc_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       const FLAC__real lp_coeff[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       unsigned order,
+       unsigned qlp_coeff_precision,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__Subframe *subframe,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
+);
+#endif
+
+static unsigned evaluate_verbatim_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       FLAC__Subframe *subframe
+);
+
+static unsigned find_best_partition_order_(
+       struct FLAC__StreamEncoderPrivate *private_,
+       const FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       unsigned bps,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__EntropyCodingMethod *best_ecm
+);
+
+static void precompute_partition_info_sums_(
+       const FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       unsigned bps
+);
+
+static void precompute_partition_info_escapes_(
+       const FLAC__int32 residual[],
+       unsigned raw_bits_per_partition[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned min_partition_order,
+       unsigned max_partition_order
+);
+
+static FLAC__bool set_partitioned_rice_(
+#ifdef EXACT_RICE_BITS_CALCULATION
+       const FLAC__int32 residual[],
+#endif
+       const FLAC__uint64 abs_residual_partition_sums[],
+       const unsigned raw_bits_per_partition[],
+       const unsigned residual_samples,
+       const unsigned predictor_order,
+       const unsigned suggested_rice_parameter,
+       const unsigned rice_parameter_limit,
+       const unsigned rice_parameter_search_dist,
+       const unsigned partition_order,
+       const FLAC__bool search_for_escapes,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
+       unsigned *bits
+);
+
+static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
+
+/* verify-related routines: */
+static void append_to_verify_fifo_(
+       verify_input_fifo *fifo,
+       const FLAC__int32 * const input[],
+       unsigned input_offset,
+       unsigned channels,
+       unsigned wide_samples
+);
+
+static void append_to_verify_fifo_interleaved_(
+       verify_input_fifo *fifo,
+       const FLAC__int32 input[],
+       unsigned input_offset,
+       unsigned channels,
+       unsigned wide_samples
+);
+
+static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
+static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
+static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
+
+static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
+static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
+static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
+static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
+static FILE *get_binary_stdout_(void);
+
+
+/***********************************************************************
+ *
+ * Private class data
+ *
+ ***********************************************************************/
+
+typedef struct FLAC__StreamEncoderPrivate {
+       unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
+       FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
+       FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
+       FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
+       FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
+       FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
+#endif
+       unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
+       unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
+       FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
+       FLAC__int32 *residual_workspace_mid_side[2][2];
+       FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
+       FLAC__Subframe subframe_workspace_mid_side[2][2];
+       FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
+       FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
+       FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
+       FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
+       unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
+       unsigned best_subframe_mid_side[2];
+       unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
+       unsigned best_subframe_bits_mid_side[2];
+       FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
+       unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
+       FLAC__BitWriter *frame;                           /* the current frame being worked on */
+       unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
+       unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
+       FLAC__ChannelAssignment last_channel_assignment;
+       FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
+       FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
+       unsigned current_sample_number;
+       unsigned current_frame_number;
+       FLAC__MD5Context md5context;
+       FLAC__CPUInfo cpuinfo;
+       void (*local_precompute_partition_info_sums)(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[], unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps);
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+       unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+#else
+       unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+       unsigned (*local_fixed_compute_best_predictor_wide)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
+#endif
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
+       void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+       void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+       void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
+#endif
+       FLAC__bool disable_constant_subframes;
+       FLAC__bool disable_fixed_subframes;
+       FLAC__bool disable_verbatim_subframes;
+       FLAC__bool is_ogg;
+       FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
+       FLAC__StreamEncoderSeekCallback seek_callback;
+       FLAC__StreamEncoderTellCallback tell_callback;
+       FLAC__StreamEncoderWriteCallback write_callback;
+       FLAC__StreamEncoderMetadataCallback metadata_callback;
+       FLAC__StreamEncoderProgressCallback progress_callback;
+       void *client_data;
+       unsigned first_seekpoint_to_check;
+       FILE *file;                            /* only used when encoding to a file */
+       FLAC__uint64 bytes_written;
+       FLAC__uint64 samples_written;
+       unsigned frames_written;
+       unsigned total_frames_estimate;
+       /* unaligned (original) pointers to allocated data */
+       FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
+       FLAC__int32 *integer_signal_mid_side_unaligned[2];
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
+       FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
+       FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
+       FLAC__real *windowed_signal_unaligned;
+#endif
+       FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
+       FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
+       FLAC__uint64 *abs_residual_partition_sums_unaligned;
+       unsigned *raw_bits_per_partition_unaligned;
+       /*
+        * These fields have been moved here from private function local
+        * declarations merely to save stack space during encoding.
+        */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
+#endif
+       FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
+       /*
+        * The data for the verify section
+        */
+       struct {
+               FLAC__StreamDecoder *decoder;
+               EncoderStateHint state_hint;
+               FLAC__bool needs_magic_hack;
+               verify_input_fifo input_fifo;
+               verify_output output;
+               struct {
+                       FLAC__uint64 absolute_sample;
+                       unsigned frame_number;
+                       unsigned channel;
+                       unsigned sample;
+                       FLAC__int32 expected;
+                       FLAC__int32 got;
+               } error_stats;
+       } verify;
+       FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
+} FLAC__StreamEncoderPrivate;
+
+/***********************************************************************
+ *
+ * Public static class data
+ *
+ ***********************************************************************/
+
+FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
+       "FLAC__STREAM_ENCODER_OK",
+       "FLAC__STREAM_ENCODER_UNINITIALIZED",
+       "FLAC__STREAM_ENCODER_OGG_ERROR",
+       "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
+       "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
+       "FLAC__STREAM_ENCODER_CLIENT_ERROR",
+       "FLAC__STREAM_ENCODER_IO_ERROR",
+       "FLAC__STREAM_ENCODER_FRAMING_ERROR",
+       "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
+};
+
+FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
+       "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
+       "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
+};
+
+FLAC_API const char * const FLAC__StreamEncoderReadStatusString[] = {
+       "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
+       "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
+       "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
+       "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
+};
+
+FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
+       "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
+       "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
+};
+
+FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
+       "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
+       "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
+       "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
+};
+
+FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
+       "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
+       "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
+       "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
+};
+
+/* Number of samples that will be overread to watch for end of stream.  By
+ * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
+ * always try to read blocksize+1 samples before encoding a block, so that
+ * even if the stream has a total sample count that is an integral multiple
+ * of the blocksize, we will still notice when we are encoding the last
+ * block.  This is needed, for example, to correctly set the end-of-stream
+ * marker in Ogg FLAC.
+ *
+ * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
+ * not really any reason to change it.
+ */
+static const unsigned OVERREAD_ = 1;
+
+/***********************************************************************
+ *
+ * Class constructor/destructor
+ *
+ */
+FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
+{
+       FLAC__StreamEncoder *encoder;
+       unsigned i;
+
+       FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
+
+       encoder = calloc(1, sizeof(FLAC__StreamEncoder));
+       if(encoder == 0) {
+               return 0;
+       }
+
+       encoder->protected_ = calloc(1, sizeof(FLAC__StreamEncoderProtected));
+       if(encoder->protected_ == 0) {
+               free(encoder);
+               return 0;
+       }
+
+       encoder->private_ = calloc(1, sizeof(FLAC__StreamEncoderPrivate));
+       if(encoder->private_ == 0) {
+               free(encoder->protected_);
+               free(encoder);
+               return 0;
+       }
+
+       encoder->private_->frame = FLAC__bitwriter_new();
+       if(encoder->private_->frame == 0) {
+               free(encoder->private_);
+               free(encoder->protected_);
+               free(encoder);
+               return 0;
+       }
+
+       encoder->private_->file = 0;
+
+       set_defaults_(encoder);
+
+       encoder->private_->is_being_deleted = false;
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
+               encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
+       }
+       for(i = 0; i < 2; i++) {
+               encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
+               encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
+       }
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
+               encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
+       }
+       for(i = 0; i < 2; i++) {
+               encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
+               encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
+       }
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
+       }
+       for(i = 0; i < 2; i++) {
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
+       }
+       for(i = 0; i < 2; i++)
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
+
+       encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
+
+       return encoder;
+}
+
+FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
+{
+       unsigned i;
+
+       if (encoder == NULL)
+               return ;
+
+       FLAC__ASSERT(0 != encoder->protected_);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->private_->frame);
+
+       encoder->private_->is_being_deleted = true;
+
+       (void)FLAC__stream_encoder_finish(encoder);
+
+       if(0 != encoder->private_->verify.decoder)
+               FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
+
+       for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
+       }
+       for(i = 0; i < 2; i++) {
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
+       }
+       for(i = 0; i < 2; i++)
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
+
+       FLAC__bitwriter_delete(encoder->private_->frame);
+       free(encoder->private_);
+       free(encoder->protected_);
+       free(encoder);
+}
+
+/***********************************************************************
+ *
+ * Public class methods
+ *
+ ***********************************************************************/
+
+static FLAC__StreamEncoderInitStatus init_stream_internal_(
+       FLAC__StreamEncoder *encoder,
+       FLAC__StreamEncoderReadCallback read_callback,
+       FLAC__StreamEncoderWriteCallback write_callback,
+       FLAC__StreamEncoderSeekCallback seek_callback,
+       FLAC__StreamEncoderTellCallback tell_callback,
+       FLAC__StreamEncoderMetadataCallback metadata_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       unsigned i;
+       FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
+
+       FLAC__ASSERT(0 != encoder);
+
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       if(FLAC__HAS_OGG == 0 && is_ogg)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
+
+       if(0 == write_callback || (seek_callback && 0 == tell_callback))
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
+
+       if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
+
+       if(encoder->protected_->channels != 2) {
+               encoder->protected_->do_mid_side_stereo = false;
+               encoder->protected_->loose_mid_side_stereo = false;
+       }
+       else if(!encoder->protected_->do_mid_side_stereo)
+               encoder->protected_->loose_mid_side_stereo = false;
+
+       if(encoder->protected_->bits_per_sample >= 32)
+               encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
+
+       if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
+
+       if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
+
+       if(encoder->protected_->blocksize == 0) {
+               if(encoder->protected_->max_lpc_order == 0)
+                       encoder->protected_->blocksize = 1152;
+               else
+                       encoder->protected_->blocksize = 4096;
+       }
+
+       if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
+
+       if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
+
+       if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
+
+       if(encoder->protected_->qlp_coeff_precision == 0) {
+               if(encoder->protected_->bits_per_sample < 16) {
+                       /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
+                       /* @@@ until then we'll make a guess */
+                       encoder->protected_->qlp_coeff_precision = flac_max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
+               }
+               else if(encoder->protected_->bits_per_sample == 16) {
+                       if(encoder->protected_->blocksize <= 192)
+                               encoder->protected_->qlp_coeff_precision = 7;
+                       else if(encoder->protected_->blocksize <= 384)
+                               encoder->protected_->qlp_coeff_precision = 8;
+                       else if(encoder->protected_->blocksize <= 576)
+                               encoder->protected_->qlp_coeff_precision = 9;
+                       else if(encoder->protected_->blocksize <= 1152)
+                               encoder->protected_->qlp_coeff_precision = 10;
+                       else if(encoder->protected_->blocksize <= 2304)
+                               encoder->protected_->qlp_coeff_precision = 11;
+                       else if(encoder->protected_->blocksize <= 4608)
+                               encoder->protected_->qlp_coeff_precision = 12;
+                       else
+                               encoder->protected_->qlp_coeff_precision = 13;
+               }
+               else {
+                       if(encoder->protected_->blocksize <= 384)
+                               encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
+                       else if(encoder->protected_->blocksize <= 1152)
+                               encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
+                       else
+                               encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
+               }
+               FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
+       }
+       else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
+
+       if(encoder->protected_->streamable_subset) {
+               if(!FLAC__format_blocksize_is_subset(encoder->protected_->blocksize, encoder->protected_->sample_rate))
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
+               if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
+               if(
+                       encoder->protected_->bits_per_sample != 8 &&
+                       encoder->protected_->bits_per_sample != 12 &&
+                       encoder->protected_->bits_per_sample != 16 &&
+                       encoder->protected_->bits_per_sample != 20 &&
+                       encoder->protected_->bits_per_sample != 24
+               )
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
+               if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
+               if(
+                       encoder->protected_->sample_rate <= 48000 &&
+                       (
+                               encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
+                               encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
+                       )
+               ) {
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
+               }
+       }
+
+       if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
+               encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
+       if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
+               encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
+
+#if FLAC__HAS_OGG
+       /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
+       if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
+               unsigned i1;
+               for(i1 = 1; i1 < encoder->protected_->num_metadata_blocks; i1++) {
+                       if(0 != encoder->protected_->metadata[i1] && encoder->protected_->metadata[i1]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
+                               FLAC__StreamMetadata *vc = encoder->protected_->metadata[i1];
+                               for( ; i1 > 0; i1--)
+                                       encoder->protected_->metadata[i1] = encoder->protected_->metadata[i1-1];
+                               encoder->protected_->metadata[0] = vc;
+                               break;
+                       }
+               }
+       }
+#endif
+       /* keep track of any SEEKTABLE block */
+       if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
+               unsigned i2;
+               for(i2 = 0; i2 < encoder->protected_->num_metadata_blocks; i2++) {
+                       if(0 != encoder->protected_->metadata[i2] && encoder->protected_->metadata[i2]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
+                               encoder->private_->seek_table = &encoder->protected_->metadata[i2]->data.seek_table;
+                               break; /* take only the first one */
+                       }
+               }
+       }
+
+       /* validate metadata */
+       if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+       metadata_has_seektable = false;
+       metadata_has_vorbis_comment = false;
+       metadata_picture_has_type1 = false;
+       metadata_picture_has_type2 = false;
+       for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
+               const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
+               if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+               else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
+                       if(metadata_has_seektable) /* only one is allowed */
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                       metadata_has_seektable = true;
+                       if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+               }
+               else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
+                       if(metadata_has_vorbis_comment) /* only one is allowed */
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                       metadata_has_vorbis_comment = true;
+               }
+               else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
+                       if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+               }
+               else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
+                       if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                       if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
+                               if(metadata_picture_has_type1) /* there should only be 1 per stream */
+                                       return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                               metadata_picture_has_type1 = true;
+                               /* standard icon must be 32x32 pixel PNG */
+                               if(
+                                       m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
+                                       (
+                                               (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
+                                               m->data.picture.width != 32 ||
+                                               m->data.picture.height != 32
+                                       )
+                               )
+                                       return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                       }
+                       else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
+                               if(metadata_picture_has_type2) /* there should only be 1 per stream */
+                                       return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
+                               metadata_picture_has_type2 = true;
+                       }
+               }
+       }
+
+       encoder->private_->input_capacity = 0;
+       for(i = 0; i < encoder->protected_->channels; i++) {
+               encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+               encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
+#endif
+       }
+       for(i = 0; i < 2; i++) {
+               encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+               encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
+#endif
+       }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       for(i = 0; i < encoder->protected_->num_apodizations; i++)
+               encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
+       encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
+#endif
+       for(i = 0; i < encoder->protected_->channels; i++) {
+               encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
+               encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
+               encoder->private_->best_subframe[i] = 0;
+       }
+       for(i = 0; i < 2; i++) {
+               encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
+               encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
+               encoder->private_->best_subframe_mid_side[i] = 0;
+       }
+       encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
+       encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       encoder->private_->loose_mid_side_stereo_frames = (unsigned)((double)encoder->protected_->sample_rate * 0.4 / (double)encoder->protected_->blocksize + 0.5);
+#else
+       /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
+       /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
+       FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
+       FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
+       FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
+       FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
+       encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
+#endif
+       if(encoder->private_->loose_mid_side_stereo_frames == 0)
+               encoder->private_->loose_mid_side_stereo_frames = 1;
+       encoder->private_->loose_mid_side_stereo_frame_count = 0;
+       encoder->private_->current_sample_number = 0;
+       encoder->private_->current_frame_number = 0;
+
+       /*
+        * get the CPU info and set the function pointers
+        */
+       FLAC__cpu_info(&encoder->private_->cpuinfo);
+       /* first default to the non-asm routines */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
+#endif
+       encoder->private_->local_precompute_partition_info_sums = precompute_partition_info_sums_;
+       encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
+       encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
+       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
+       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
+#endif
+       /* now override with asm where appropriate */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+# ifndef FLAC__NO_ASM
+       if(encoder->private_->cpuinfo.use_asm) {
+#  ifdef FLAC__CPU_IA32
+               FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
+#   ifdef FLAC__HAS_NASM
+               if(encoder->private_->cpuinfo.ia32.sse) {
+                       if(encoder->protected_->max_lpc_order < 4)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4_old;
+                       else if(encoder->protected_->max_lpc_order < 8)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8_old;
+                       else if(encoder->protected_->max_lpc_order < 12)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12_old;
+                       else if(encoder->protected_->max_lpc_order < 16)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_16_old;
+                       else
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
+               }
+               else
+                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
+
+               encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_asm_ia32; /* OPT_IA32: was really necessary for GCC < 4.9 */
+               if(encoder->private_->cpuinfo.ia32.mmx) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
+               }
+               else {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
+               }
+
+               if(encoder->private_->cpuinfo.ia32.mmx && encoder->private_->cpuinfo.ia32.cmov)
+                       encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
+#   endif /* FLAC__HAS_NASM */
+#   if FLAC__HAS_X86INTRIN
+#    if defined FLAC__SSE_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.sse) {
+                       if(encoder->private_->cpuinfo.ia32.sse42 || !encoder->private_->cpuinfo.ia32.intel) { /* use new autocorrelation functions */
+                               if(encoder->protected_->max_lpc_order < 4)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
+                               else if(encoder->protected_->max_lpc_order < 8)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
+                               else if(encoder->protected_->max_lpc_order < 12)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
+                               else if(encoder->protected_->max_lpc_order < 16)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
+                               else
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
+                       }
+                       else { /* use old autocorrelation functions */
+                               if(encoder->protected_->max_lpc_order < 4)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
+                               else if(encoder->protected_->max_lpc_order < 8)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
+                               else if(encoder->protected_->max_lpc_order < 12)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
+                               else if(encoder->protected_->max_lpc_order < 16)
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
+                               else
+                                       encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
+                       }
+               }
+#    endif
+
+#    ifdef FLAC__SSE2_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.sse2) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse2;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
+               }
+#    endif
+#    ifdef FLAC__SSE4_1_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.sse41) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_sse41;
+               }
+#    endif
+#    ifdef FLAC__AVX2_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.avx2) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
+               }
+#    endif
+
+#    ifdef FLAC__SSE2_SUPPORTED
+               if (encoder->private_->cpuinfo.ia32.sse2) {
+                       encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
+                       encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
+               }
+#    endif
+#    ifdef FLAC__SSSE3_SUPPORTED
+               if (encoder->private_->cpuinfo.ia32.ssse3) {
+                       encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
+                       encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
+               }
+#    endif
+#   endif /* FLAC__HAS_X86INTRIN */
+#  elif defined FLAC__CPU_X86_64
+               FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_X86_64);
+#   if FLAC__HAS_X86INTRIN
+#    ifdef FLAC__SSE_SUPPORTED
+               if(encoder->private_->cpuinfo.x86.sse42 || !encoder->private_->cpuinfo.x86.intel) { /* use new autocorrelation functions */
+                       if(encoder->protected_->max_lpc_order < 4)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_new;
+                       else if(encoder->protected_->max_lpc_order < 8)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_new;
+                       else if(encoder->protected_->max_lpc_order < 12)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_new;
+                       else if(encoder->protected_->max_lpc_order < 16)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_new;
+               }
+               else {
+                       if(encoder->protected_->max_lpc_order < 4)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_4_old;
+                       else if(encoder->protected_->max_lpc_order < 8)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_8_old;
+                       else if(encoder->protected_->max_lpc_order < 12)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_12_old;
+                       else if(encoder->protected_->max_lpc_order < 16)
+                               encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_intrin_sse_lag_16_old;
+               }
+#    endif
+
+#    ifdef FLAC__SSE2_SUPPORTED
+               encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_sse2;
+#    endif
+#    ifdef FLAC__SSE4_1_SUPPORTED
+               if(encoder->private_->cpuinfo.x86.sse41) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_sse41;
+               }
+#    endif
+#    ifdef FLAC__AVX2_SUPPORTED
+               if(encoder->private_->cpuinfo.x86.avx2) {
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_16_intrin_avx2;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients       = FLAC__lpc_compute_residual_from_qlp_coefficients_intrin_avx2;
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide_intrin_avx2;
+               }
+#    endif
+
+#    ifdef FLAC__SSE2_SUPPORTED
+               encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_sse2;
+               encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_sse2;
+#    endif
+#    ifdef FLAC__SSSE3_SUPPORTED
+               if (encoder->private_->cpuinfo.x86.ssse3) {
+                       encoder->private_->local_fixed_compute_best_predictor      = FLAC__fixed_compute_best_predictor_intrin_ssse3;
+                       encoder->private_->local_fixed_compute_best_predictor_wide = FLAC__fixed_compute_best_predictor_wide_intrin_ssse3;
+               }
+#    endif
+#   endif /* FLAC__HAS_X86INTRIN */
+#  endif /* FLAC__CPU_... */
+       }
+# endif /* !FLAC__NO_ASM */
+#endif /* !FLAC__INTEGER_ONLY_LIBRARY */
+#if !defined FLAC__NO_ASM && FLAC__HAS_X86INTRIN
+       if(encoder->private_->cpuinfo.use_asm) {
+# if defined FLAC__CPU_IA32
+#  ifdef FLAC__SSE2_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.sse2)
+                       encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
+#  endif
+#  ifdef FLAC__SSSE3_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.ssse3)
+                       encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
+#  endif
+#  ifdef FLAC__AVX2_SUPPORTED
+               if(encoder->private_->cpuinfo.ia32.avx2)
+                       encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
+#  endif
+# elif defined FLAC__CPU_X86_64
+#  ifdef FLAC__SSE2_SUPPORTED
+               encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_sse2;
+#  endif
+#  ifdef FLAC__SSSE3_SUPPORTED
+               if(encoder->private_->cpuinfo.x86.ssse3)
+                       encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_ssse3;
+#  endif
+#  ifdef FLAC__AVX2_SUPPORTED
+               if(encoder->private_->cpuinfo.x86.avx2)
+                       encoder->private_->local_precompute_partition_info_sums = FLAC__precompute_partition_info_sums_intrin_avx2;
+#  endif
+# endif /* FLAC__CPU_... */
+       }
+#endif /* !FLAC__NO_ASM && FLAC__HAS_X86INTRIN */
+
+       /* set state to OK; from here on, errors are fatal and we'll override the state then */
+       encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
+
+#if FLAC__HAS_OGG
+       encoder->private_->is_ogg = is_ogg;
+       if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+#endif
+
+       encoder->private_->read_callback = read_callback;
+       encoder->private_->write_callback = write_callback;
+       encoder->private_->seek_callback = seek_callback;
+       encoder->private_->tell_callback = tell_callback;
+       encoder->private_->metadata_callback = metadata_callback;
+       encoder->private_->client_data = client_data;
+
+       if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
+               /* the above function sets the state for us in case of an error */
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       if(!FLAC__bitwriter_init(encoder->private_->frame)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       /*
+        * Set up the verify stuff if necessary
+        */
+       if(encoder->protected_->verify) {
+               /*
+                * First, set up the fifo which will hold the
+                * original signal to compare against
+                */
+               encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
+               for(i = 0; i < encoder->protected_->channels; i++) {
+                       if(0 == (encoder->private_->verify.input_fifo.data[i] = safe_malloc_mul_2op_p(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+                       }
+               }
+               encoder->private_->verify.input_fifo.tail = 0;
+
+               /*
+                * Now set up a stream decoder for verification
+                */
+               if(0 == encoder->private_->verify.decoder) {
+                       encoder->private_->verify.decoder = FLAC__stream_decoder_new();
+                       if(0 == encoder->private_->verify.decoder) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
+                               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+                       }
+               }
+
+               if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+               }
+       }
+       encoder->private_->verify.error_stats.absolute_sample = 0;
+       encoder->private_->verify.error_stats.frame_number = 0;
+       encoder->private_->verify.error_stats.channel = 0;
+       encoder->private_->verify.error_stats.sample = 0;
+       encoder->private_->verify.error_stats.expected = 0;
+       encoder->private_->verify.error_stats.got = 0;
+
+       /*
+        * These must be done before we write any metadata, because that
+        * calls the write_callback, which uses these values.
+        */
+       encoder->private_->first_seekpoint_to_check = 0;
+       encoder->private_->samples_written = 0;
+       encoder->protected_->streaminfo_offset = 0;
+       encoder->protected_->seektable_offset = 0;
+       encoder->protected_->audio_offset = 0;
+
+       /*
+        * write the stream header
+        */
+       if(encoder->protected_->verify)
+               encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
+       if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+       if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
+               /* the above function sets the state for us in case of an error */
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       /*
+        * write the STREAMINFO metadata block
+        */
+       if(encoder->protected_->verify)
+               encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
+       encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
+       encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
+       encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
+       encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
+       encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
+       encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
+       encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
+       encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
+       encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
+       encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
+       encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
+       memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
+       if(encoder->protected_->do_md5)
+               FLAC__MD5Init(&encoder->private_->md5context);
+       if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+       if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
+               /* the above function sets the state for us in case of an error */
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       /*
+        * Now that the STREAMINFO block is written, we can init this to an
+        * absurdly-high value...
+        */
+       encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
+       /* ... and clear this to 0 */
+       encoder->private_->streaminfo.data.stream_info.total_samples = 0;
+
+       /*
+        * Check to see if the supplied metadata contains a VORBIS_COMMENT;
+        * if not, we will write an empty one (FLAC__add_metadata_block()
+        * automatically supplies the vendor string).
+        *
+        * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
+        * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
+        * true it will have already insured that the metadata list is properly
+        * ordered.)
+        */
+       if(!metadata_has_vorbis_comment) {
+               FLAC__StreamMetadata vorbis_comment;
+               vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
+               vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
+               vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
+               vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
+               vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
+               vorbis_comment.data.vorbis_comment.num_comments = 0;
+               vorbis_comment.data.vorbis_comment.comments = 0;
+               if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+               }
+               if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
+                       /* the above function sets the state for us in case of an error */
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+               }
+       }
+
+       /*
+        * write the user's metadata blocks
+        */
+       for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
+               encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
+               if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+               }
+               if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
+                       /* the above function sets the state for us in case of an error */
+                       return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+               }
+       }
+
+       /* now that all the metadata is written, we save the stream offset */
+       if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       if(encoder->protected_->verify)
+               encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
+
+       return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
+       FLAC__StreamEncoder *encoder,
+       FLAC__StreamEncoderWriteCallback write_callback,
+       FLAC__StreamEncoderSeekCallback seek_callback,
+       FLAC__StreamEncoderTellCallback tell_callback,
+       FLAC__StreamEncoderMetadataCallback metadata_callback,
+       void *client_data
+)
+{
+       return init_stream_internal_(
+               encoder,
+               /*read_callback=*/0,
+               write_callback,
+               seek_callback,
+               tell_callback,
+               metadata_callback,
+               client_data,
+               /*is_ogg=*/false
+       );
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
+       FLAC__StreamEncoder *encoder,
+       FLAC__StreamEncoderReadCallback read_callback,
+       FLAC__StreamEncoderWriteCallback write_callback,
+       FLAC__StreamEncoderSeekCallback seek_callback,
+       FLAC__StreamEncoderTellCallback tell_callback,
+       FLAC__StreamEncoderMetadataCallback metadata_callback,
+       void *client_data
+)
+{
+       return init_stream_internal_(
+               encoder,
+               read_callback,
+               write_callback,
+               seek_callback,
+               tell_callback,
+               metadata_callback,
+               client_data,
+               /*is_ogg=*/true
+       );
+}
+
+static FLAC__StreamEncoderInitStatus init_FILE_internal_(
+       FLAC__StreamEncoder *encoder,
+       FILE *file,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       FLAC__StreamEncoderInitStatus init_status;
+
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != file);
+
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       /* double protection */
+       if(file == 0) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       /*
+        * To make sure that our file does not go unclosed after an error, we
+        * must assign the FILE pointer before any further error can occur in
+        * this routine.
+        */
+       if(file == stdout)
+               file = get_binary_stdout_(); /* just to be safe */
+
+#ifdef _WIN32
+       /*
+        * Windows can suffer quite badly from disk fragmentation. This can be
+        * reduced significantly by setting the output buffer size to be 10MB.
+        */
+       if(GetFileType((HANDLE)_get_osfhandle(_fileno(file))) == FILE_TYPE_DISK)
+               setvbuf(file, NULL, _IOFBF, 10*1024*1024);
+#endif
+       encoder->private_->file = file;
+
+       encoder->private_->progress_callback = progress_callback;
+       encoder->private_->bytes_written = 0;
+       encoder->private_->samples_written = 0;
+       encoder->private_->frames_written = 0;
+
+       init_status = init_stream_internal_(
+               encoder,
+               encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
+               file_write_callback_,
+               encoder->private_->file == stdout? 0 : file_seek_callback_,
+               encoder->private_->file == stdout? 0 : file_tell_callback_,
+               /*metadata_callback=*/0,
+               client_data,
+               is_ogg
+       );
+       if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
+               /* the above function sets the state for us in case of an error */
+               return init_status;
+       }
+
+       {
+               unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
+
+               FLAC__ASSERT(blocksize != 0);
+               encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
+       }
+
+       return init_status;
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
+       FLAC__StreamEncoder *encoder,
+       FILE *file,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data
+)
+{
+       return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
+       FLAC__StreamEncoder *encoder,
+       FILE *file,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data
+)
+{
+       return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
+}
+
+static FLAC__StreamEncoderInitStatus init_file_internal_(
+       FLAC__StreamEncoder *encoder,
+       const char *filename,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data,
+       FLAC__bool is_ogg
+)
+{
+       FILE *file;
+
+       FLAC__ASSERT(0 != encoder);
+
+       /*
+        * To make sure that our file does not go unclosed after an error, we
+        * have to do the same entrance checks here that are later performed
+        * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
+        */
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
+
+       file = filename? flac_fopen(filename, "w+b") : stdout;
+
+       if(file == 0) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
+               return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
+       }
+
+       return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
+       FLAC__StreamEncoder *encoder,
+       const char *filename,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data
+)
+{
+       return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
+}
+
+FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
+       FLAC__StreamEncoder *encoder,
+       const char *filename,
+       FLAC__StreamEncoderProgressCallback progress_callback,
+       void *client_data
+)
+{
+       return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
+{
+       FLAC__bool error = false;
+
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+
+       if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return true;
+
+       if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
+               if(encoder->private_->current_sample_number != 0) {
+                       const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
+                       encoder->protected_->blocksize = encoder->private_->current_sample_number;
+                       if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
+                               error = true;
+               }
+       }
+
+       if(encoder->protected_->do_md5)
+               FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
+
+       if(!encoder->private_->is_being_deleted) {
+               if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
+                       if(encoder->private_->seek_callback) {
+#if FLAC__HAS_OGG
+                               if(encoder->private_->is_ogg)
+                                       update_ogg_metadata_(encoder);
+                               else
+#endif
+                               update_metadata_(encoder);
+
+                               /* check if an error occurred while updating metadata */
+                               if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
+                                       error = true;
+                       }
+                       if(encoder->private_->metadata_callback)
+                               encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
+               }
+
+               if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
+                       if(!error)
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
+                       error = true;
+               }
+       }
+
+       if(0 != encoder->private_->file) {
+               if(encoder->private_->file != stdout)
+                       fclose(encoder->private_->file);
+               encoder->private_->file = 0;
+       }
+
+#if FLAC__HAS_OGG
+       if(encoder->private_->is_ogg)
+               FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
+#endif
+
+       free_(encoder);
+       set_defaults_(encoder);
+
+       if(!error)
+               encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
+
+       return !error;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+#if FLAC__HAS_OGG
+       /* can't check encoder->private_->is_ogg since that's not set until init time */
+       FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
+       return true;
+#else
+       (void)value;
+       return false;
+#endif
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+#ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
+       encoder->protected_->verify = value;
+#endif
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->streamable_subset = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->do_md5 = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->channels = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->bits_per_sample = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->sample_rate = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__bool ok = true;
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
+               value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
+       ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
+       ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#if 1
+       ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
+#else
+       /* equivalent to -A tukey(0.5) */
+       encoder->protected_->num_apodizations = 1;
+       encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
+       encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
+#endif
+#endif
+       ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
+       ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
+       ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
+       ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
+       ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
+       ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
+       ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
+       ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
+       return ok;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->blocksize = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->do_mid_side_stereo = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->loose_mid_side_stereo = value;
+       return true;
+}
+
+/*@@@@add to tests*/
+FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       FLAC__ASSERT(0 != specification);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+#ifdef FLAC__INTEGER_ONLY_LIBRARY
+       (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
+#else
+       encoder->protected_->num_apodizations = 0;
+       while(1) {
+               const char *s = strchr(specification, ';');
+               const size_t n = s? (size_t)(s - specification) : strlen(specification);
+               if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
+               else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
+               else if(n==8  && 0 == strncmp("blackman"     , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
+               else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
+               else if(n==6  && 0 == strncmp("connes"       , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
+               else if(n==7  && 0 == strncmp("flattop"      , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
+               else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
+                       FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
+                       if (stddev > 0.0 && stddev <= 0.5) {
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
+                       }
+               }
+               else if(n==7  && 0 == strncmp("hamming"      , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
+               else if(n==4  && 0 == strncmp("hann"         , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
+               else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
+               else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
+               else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
+               else if(n==8  && 0 == strncmp("triangle"     , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
+               else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
+                       FLAC__real p = (FLAC__real)strtod(specification+6, 0);
+                       if (p >= 0.0 && p <= 1.0) {
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
+                       }
+               }
+               else if(n>15   && 0 == strncmp("partial_tukey("       , specification, 14)) {
+                       FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+14, 0);
+                       const char *si_1 = strchr(specification, '/');
+                       FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.1f;
+                       FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
+                       const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
+                       FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
+
+                       if (tukey_parts <= 1) {
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
+                       }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
+                               FLAC__int32 m;
+                               for(m = 0; m < tukey_parts; m++){
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PARTIAL_TUKEY;
+                               }
+                       }
+               }
+               else if(n>16   && 0 == strncmp("punchout_tukey("       , specification, 15)) {
+                       FLAC__int32 tukey_parts = (FLAC__int32)strtod(specification+15, 0);
+                       const char *si_1 = strchr(specification, '/');
+                       FLAC__real overlap = si_1?flac_min((FLAC__real)strtod(si_1+1, 0),0.99f):0.2f;
+                       FLAC__real overlap_units = 1.0f/(1.0f - overlap) - 1.0f;
+                       const char *si_2 = strchr((si_1?(si_1+1):specification), '/');
+                       FLAC__real tukey_p = si_2?(FLAC__real)strtod(si_2+1, 0):0.2f;
+
+                       if (tukey_parts <= 1) {
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = tukey_p;
+                               encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
+                       }else if (encoder->protected_->num_apodizations + tukey_parts < 32){
+                               FLAC__int32 m;
+                               for(m = 0; m < tukey_parts; m++){
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.p = tukey_p;
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.start = m/(tukey_parts+overlap_units);
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.multiple_tukey.end = (m+1+overlap_units)/(tukey_parts+overlap_units);
+                                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_PUNCHOUT_TUKEY;
+                               }
+                       }
+               }
+               else if(n==5  && 0 == strncmp("welch"        , specification, n))
+                       encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
+               if (encoder->protected_->num_apodizations == 32)
+                       break;
+               if (s)
+                       specification = s+1;
+               else
+                       break;
+       }
+       if(encoder->protected_->num_apodizations == 0) {
+               encoder->protected_->num_apodizations = 1;
+               encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
+               encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
+       }
+#endif
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->max_lpc_order = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->qlp_coeff_precision = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->do_qlp_coeff_prec_search = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+#if 0
+       /*@@@ deprecated: */
+       encoder->protected_->do_escape_coding = value;
+#else
+       (void)value;
+#endif
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->do_exhaustive_model_search = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->min_residual_partition_order = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->protected_->max_residual_partition_order = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+#if 0
+       /*@@@ deprecated: */
+       encoder->protected_->rice_parameter_search_dist = value;
+#else
+       (void)value;
+#endif
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       value = flac_min(value, (FLAC__U64L(1) << FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN) - 1);
+       encoder->protected_->total_samples_estimate = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       if(0 == metadata)
+               num_blocks = 0;
+       if(0 == num_blocks)
+               metadata = 0;
+       /* realloc() does not do exactly what we want so... */
+       if(encoder->protected_->metadata) {
+               free(encoder->protected_->metadata);
+               encoder->protected_->metadata = 0;
+               encoder->protected_->num_metadata_blocks = 0;
+       }
+       if(num_blocks) {
+               FLAC__StreamMetadata **m;
+               if(0 == (m = safe_malloc_mul_2op_p(sizeof(m[0]), /*times*/num_blocks)))
+                       return false;
+               memcpy(m, metadata, sizeof(m[0]) * num_blocks);
+               encoder->protected_->metadata = m;
+               encoder->protected_->num_metadata_blocks = num_blocks;
+       }
+#if FLAC__HAS_OGG
+       if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
+               return false;
+#endif
+       return true;
+}
+
+/*
+ * These three functions are not static, but not publically exposed in
+ * include/FLAC/ either.  They are used by the test suite.
+ */
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->private_->disable_constant_subframes = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->private_->disable_fixed_subframes = value;
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
+               return false;
+       encoder->private_->disable_verbatim_subframes = value;
+       return true;
+}
+
+FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->state;
+}
+
+FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->verify)
+               return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
+       else
+               return FLAC__STREAM_DECODER_UNINITIALIZED;
+}
+
+FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
+               return FLAC__StreamEncoderStateString[encoder->protected_->state];
+       else
+               return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
+}
+
+FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       if(0 != absolute_sample)
+               *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
+       if(0 != frame_number)
+               *frame_number = encoder->private_->verify.error_stats.frame_number;
+       if(0 != channel)
+               *channel = encoder->private_->verify.error_stats.channel;
+       if(0 != sample)
+               *sample = encoder->private_->verify.error_stats.sample;
+       if(0 != expected)
+               *expected = encoder->private_->verify.error_stats.expected;
+       if(0 != got)
+               *got = encoder->private_->verify.error_stats.got;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->verify;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->streamable_subset;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->do_md5;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->channels;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->bits_per_sample;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->sample_rate;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->blocksize;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->do_mid_side_stereo;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->loose_mid_side_stereo;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->max_lpc_order;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->qlp_coeff_precision;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->do_qlp_coeff_prec_search;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->do_escape_coding;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->do_exhaustive_model_search;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->min_residual_partition_order;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->max_residual_partition_order;
+}
+
+FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->rice_parameter_search_dist;
+}
+
+FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       return encoder->protected_->total_samples_estimate;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
+{
+       unsigned i, j = 0, channel;
+       const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
+
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
+
+       do {
+               const unsigned n = flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
+
+               if(encoder->protected_->verify)
+                       append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
+
+               for(channel = 0; channel < channels; channel++) {
+                       if (buffer[channel] == NULL) {
+                               return false;
+                       }
+                       memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
+               }
+
+               if(encoder->protected_->do_mid_side_stereo) {
+                       FLAC__ASSERT(channels == 2);
+                       /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
+                       for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
+                               encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
+                               encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
+                       }
+               }
+               else
+                       j += n;
+
+               encoder->private_->current_sample_number += n;
+
+               /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
+               if(encoder->private_->current_sample_number > blocksize) {
+                       FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
+                       FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
+                       if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
+                               return false;
+                       /* move unprocessed overread samples to beginnings of arrays */
+                       for(channel = 0; channel < channels; channel++)
+                               encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
+                       if(encoder->protected_->do_mid_side_stereo) {
+                               encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
+                               encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
+                       }
+                       encoder->private_->current_sample_number = 1;
+               }
+       } while(j < samples);
+
+       return true;
+}
+
+FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
+{
+       unsigned i, j, k, channel;
+       FLAC__int32 x, mid, side;
+       const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
+
+       FLAC__ASSERT(0 != encoder);
+       FLAC__ASSERT(0 != encoder->private_);
+       FLAC__ASSERT(0 != encoder->protected_);
+       FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
+
+       j = k = 0;
+       /*
+        * we have several flavors of the same basic loop, optimized for
+        * different conditions:
+        */
+       if(encoder->protected_->do_mid_side_stereo && channels == 2) {
+               /*
+                * stereo coding: unroll channel loop
+                */
+               do {
+                       if(encoder->protected_->verify)
+                               append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
+
+                       /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
+                       for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
+                               encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
+                               x = buffer[k++];
+                               encoder->private_->integer_signal[1][i] = x;
+                               mid += x;
+                               side -= x;
+                               mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
+                               encoder->private_->integer_signal_mid_side[1][i] = side;
+                               encoder->private_->integer_signal_mid_side[0][i] = mid;
+                       }
+                       encoder->private_->current_sample_number = i;
+                       /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
+                       if(i > blocksize) {
+                               if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
+                                       return false;
+                               /* move unprocessed overread samples to beginnings of arrays */
+                               FLAC__ASSERT(i == blocksize+OVERREAD_);
+                               FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
+                               encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
+                               encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
+                               encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
+                               encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
+                               encoder->private_->current_sample_number = 1;
+                       }
+               } while(j < samples);
+       }
+       else {
+               /*
+                * independent channel coding: buffer each channel in inner loop
+                */
+               do {
+                       if(encoder->protected_->verify)
+                               append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, flac_min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
+
+                       /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
+                       for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
+                               for(channel = 0; channel < channels; channel++)
+                                       encoder->private_->integer_signal[channel][i] = buffer[k++];
+                       }
+                       encoder->private_->current_sample_number = i;
+                       /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
+                       if(i > blocksize) {
+                               if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
+                                       return false;
+                               /* move unprocessed overread samples to beginnings of arrays */
+                               FLAC__ASSERT(i == blocksize+OVERREAD_);
+                               FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
+                               for(channel = 0; channel < channels; channel++)
+                                       encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
+                               encoder->private_->current_sample_number = 1;
+                       }
+               } while(j < samples);
+       }
+
+       return true;
+}
+
+/***********************************************************************
+ *
+ * Private class methods
+ *
+ ***********************************************************************/
+
+void set_defaults_(FLAC__StreamEncoder *encoder)
+{
+       FLAC__ASSERT(0 != encoder);
+
+#ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
+       encoder->protected_->verify = true;
+#else
+       encoder->protected_->verify = false;
+#endif
+       encoder->protected_->streamable_subset = true;
+       encoder->protected_->do_md5 = true;
+       encoder->protected_->do_mid_side_stereo = false;
+       encoder->protected_->loose_mid_side_stereo = false;
+       encoder->protected_->channels = 2;
+       encoder->protected_->bits_per_sample = 16;
+       encoder->protected_->sample_rate = 44100;
+       encoder->protected_->blocksize = 0;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       encoder->protected_->num_apodizations = 1;
+       encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
+       encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
+#endif
+       encoder->protected_->max_lpc_order = 0;
+       encoder->protected_->qlp_coeff_precision = 0;
+       encoder->protected_->do_qlp_coeff_prec_search = false;
+       encoder->protected_->do_exhaustive_model_search = false;
+       encoder->protected_->do_escape_coding = false;
+       encoder->protected_->min_residual_partition_order = 0;
+       encoder->protected_->max_residual_partition_order = 0;
+       encoder->protected_->rice_parameter_search_dist = 0;
+       encoder->protected_->total_samples_estimate = 0;
+       encoder->protected_->metadata = 0;
+       encoder->protected_->num_metadata_blocks = 0;
+
+       encoder->private_->seek_table = 0;
+       encoder->private_->disable_constant_subframes = false;
+       encoder->private_->disable_fixed_subframes = false;
+       encoder->private_->disable_verbatim_subframes = false;
+       encoder->private_->is_ogg = false;
+       encoder->private_->read_callback = 0;
+       encoder->private_->write_callback = 0;
+       encoder->private_->seek_callback = 0;
+       encoder->private_->tell_callback = 0;
+       encoder->private_->metadata_callback = 0;
+       encoder->private_->progress_callback = 0;
+       encoder->private_->client_data = 0;
+
+#if FLAC__HAS_OGG
+       FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
+#endif
+
+       FLAC__stream_encoder_set_compression_level(encoder, 5);
+}
+
+void free_(FLAC__StreamEncoder *encoder)
+{
+       unsigned i, channel;
+
+       FLAC__ASSERT(0 != encoder);
+       if(encoder->protected_->metadata) {
+               free(encoder->protected_->metadata);
+               encoder->protected_->metadata = 0;
+               encoder->protected_->num_metadata_blocks = 0;
+       }
+       for(i = 0; i < encoder->protected_->channels; i++) {
+               if(0 != encoder->private_->integer_signal_unaligned[i]) {
+                       free(encoder->private_->integer_signal_unaligned[i]);
+                       encoder->private_->integer_signal_unaligned[i] = 0;
+               }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+               if(0 != encoder->private_->real_signal_unaligned[i]) {
+                       free(encoder->private_->real_signal_unaligned[i]);
+                       encoder->private_->real_signal_unaligned[i] = 0;
+               }
+#endif
+       }
+       for(i = 0; i < 2; i++) {
+               if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
+                       free(encoder->private_->integer_signal_mid_side_unaligned[i]);
+                       encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
+               }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+               if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
+                       free(encoder->private_->real_signal_mid_side_unaligned[i]);
+                       encoder->private_->real_signal_mid_side_unaligned[i] = 0;
+               }
+#endif
+       }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       for(i = 0; i < encoder->protected_->num_apodizations; i++) {
+               if(0 != encoder->private_->window_unaligned[i]) {
+                       free(encoder->private_->window_unaligned[i]);
+                       encoder->private_->window_unaligned[i] = 0;
+               }
+       }
+       if(0 != encoder->private_->windowed_signal_unaligned) {
+               free(encoder->private_->windowed_signal_unaligned);
+               encoder->private_->windowed_signal_unaligned = 0;
+       }
+#endif
+       for(channel = 0; channel < encoder->protected_->channels; channel++) {
+               for(i = 0; i < 2; i++) {
+                       if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
+                               free(encoder->private_->residual_workspace_unaligned[channel][i]);
+                               encoder->private_->residual_workspace_unaligned[channel][i] = 0;
+                       }
+               }
+       }
+       for(channel = 0; channel < 2; channel++) {
+               for(i = 0; i < 2; i++) {
+                       if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
+                               free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
+                               encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
+                       }
+               }
+       }
+       if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
+               free(encoder->private_->abs_residual_partition_sums_unaligned);
+               encoder->private_->abs_residual_partition_sums_unaligned = 0;
+       }
+       if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
+               free(encoder->private_->raw_bits_per_partition_unaligned);
+               encoder->private_->raw_bits_per_partition_unaligned = 0;
+       }
+       if(encoder->protected_->verify) {
+               for(i = 0; i < encoder->protected_->channels; i++) {
+                       if(0 != encoder->private_->verify.input_fifo.data[i]) {
+                               free(encoder->private_->verify.input_fifo.data[i]);
+                               encoder->private_->verify.input_fifo.data[i] = 0;
+                       }
+               }
+       }
+       FLAC__bitwriter_free(encoder->private_->frame);
+}
+
+FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
+{
+       FLAC__bool ok;
+       unsigned i, channel;
+
+       FLAC__ASSERT(new_blocksize > 0);
+       FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
+       FLAC__ASSERT(encoder->private_->current_sample_number == 0);
+
+       /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
+       if(new_blocksize <= encoder->private_->input_capacity)
+               return true;
+
+       ok = true;
+
+       /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx() and ..._intrin_sse2()
+        * require that the input arrays (in our case the integer signals)
+        * have a buffer of up to 3 zeroes in front (at negative indices) for
+        * alignment purposes; we use 4 in front to keep the data well-aligned.
+        */
+
+       for(i = 0; ok && i < encoder->protected_->channels; i++) {
+               ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
+               memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
+               encoder->private_->integer_signal[i] += 4;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#if 0 /* @@@ currently unused */
+               if(encoder->protected_->max_lpc_order > 0)
+                       ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
+#endif
+#endif
+       }
+       for(i = 0; ok && i < 2; i++) {
+               ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
+               memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
+               encoder->private_->integer_signal_mid_side[i] += 4;
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+#if 0 /* @@@ currently unused */
+               if(encoder->protected_->max_lpc_order > 0)
+                       ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
+#endif
+#endif
+       }
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       if(ok && encoder->protected_->max_lpc_order > 0) {
+               for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
+                       ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
+               ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
+       }
+#endif
+       for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
+               for(i = 0; ok && i < 2; i++) {
+                       ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
+               }
+       }
+       for(channel = 0; ok && channel < 2; channel++) {
+               for(i = 0; ok && i < 2; i++) {
+                       ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
+               }
+       }
+       /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
+       /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
+       ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
+       if(encoder->protected_->do_escape_coding)
+               ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
+
+       /* now adjust the windows if the blocksize has changed */
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
+               for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
+                       switch(encoder->protected_->apodizations[i].type) {
+                               case FLAC__APODIZATION_BARTLETT:
+                                       FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_BARTLETT_HANN:
+                                       FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_BLACKMAN:
+                                       FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
+                                       FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_CONNES:
+                                       FLAC__window_connes(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_FLATTOP:
+                                       FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_GAUSS:
+                                       FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
+                                       break;
+                               case FLAC__APODIZATION_HAMMING:
+                                       FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_HANN:
+                                       FLAC__window_hann(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_KAISER_BESSEL:
+                                       FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_NUTTALL:
+                                       FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_RECTANGLE:
+                                       FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_TRIANGLE:
+                                       FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               case FLAC__APODIZATION_TUKEY:
+                                       FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
+                                       break;
+                               case FLAC__APODIZATION_PARTIAL_TUKEY:
+                                       FLAC__window_partial_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.multiple_tukey.p, encoder->protected_->apodizations[i].parameters.multiple_tukey.start, encoder->protected_->apodizations[i].parameters.multiple_tukey.end);
+                                       break;
+                               case FLAC__APODIZATION_PUNCHOUT_TUKEY:
+                                       FLAC__window_punchout_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.multiple_tukey.p, encoder->protected_->apodizations[i].parameters.multiple_tukey.start, encoder->protected_->apodizations[i].parameters.multiple_tukey.end);
+                                       break;
+                               case FLAC__APODIZATION_WELCH:
+                                       FLAC__window_welch(encoder->private_->window[i], new_blocksize);
+                                       break;
+                               default:
+                                       FLAC__ASSERT(0);
+                                       /* double protection */
+                                       FLAC__window_hann(encoder->private_->window[i], new_blocksize);
+                                       break;
+                       }
+               }
+       }
+#endif
+
+       if(ok)
+               encoder->private_->input_capacity = new_blocksize;
+       else
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+
+       return ok;
+}
+
+FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
+{
+       const FLAC__byte *buffer;
+       size_t bytes;
+
+       FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
+
+       if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       if(encoder->protected_->verify) {
+               encoder->private_->verify.output.data = buffer;
+               encoder->private_->verify.output.bytes = bytes;
+               if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
+                       encoder->private_->verify.needs_magic_hack = true;
+               }
+               else {
+                       if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
+                               FLAC__bitwriter_release_buffer(encoder->private_->frame);
+                               FLAC__bitwriter_clear(encoder->private_->frame);
+                               if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
+                                       encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
+                               return false;
+                       }
+               }
+       }
+
+       if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+               FLAC__bitwriter_release_buffer(encoder->private_->frame);
+               FLAC__bitwriter_clear(encoder->private_->frame);
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return false;
+       }
+
+       FLAC__bitwriter_release_buffer(encoder->private_->frame);
+       FLAC__bitwriter_clear(encoder->private_->frame);
+
+       if(samples > 0) {
+               encoder->private_->streaminfo.data.stream_info.min_framesize = flac_min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
+               encoder->private_->streaminfo.data.stream_info.max_framesize = flac_max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
+       }
+
+       return true;
+}
+
+FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
+{
+       FLAC__StreamEncoderWriteStatus status;
+       FLAC__uint64 output_position = 0;
+
+#if FLAC__HAS_OGG == 0
+       (void)is_last_block;
+#endif
+
+       /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
+       if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+       }
+
+       /*
+        * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
+        */
+       if(samples == 0) {
+               FLAC__MetadataType type = (buffer[0] & 0x7f);
+               if(type == FLAC__METADATA_TYPE_STREAMINFO)
+                       encoder->protected_->streaminfo_offset = output_position;
+               else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
+                       encoder->protected_->seektable_offset = output_position;
+       }
+
+       /*
+        * Mark the current seek point if hit (if audio_offset == 0 that
+        * means we're still writing metadata and haven't hit the first
+        * frame yet)
+        */
+       if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
+               const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
+               const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
+               const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
+               FLAC__uint64 test_sample;
+               unsigned i;
+               for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
+                       test_sample = encoder->private_->seek_table->points[i].sample_number;
+                       if(test_sample > frame_last_sample) {
+                               break;
+                       }
+                       else if(test_sample >= frame_first_sample) {
+                               encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
+                               encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
+                               encoder->private_->seek_table->points[i].frame_samples = blocksize;
+                               encoder->private_->first_seekpoint_to_check++;
+                               /* DO NOT: "break;" and here's why:
+                                * The seektable template may contain more than one target
+                                * sample for any given frame; we will keep looping, generating
+                                * duplicate seekpoints for them, and we'll clean it up later,
+                                * just before writing the seektable back to the metadata.
+                                */
+                       }
+                       else {
+                               encoder->private_->first_seekpoint_to_check++;
+                       }
+               }
+       }
+
+#if FLAC__HAS_OGG
+       if(encoder->private_->is_ogg) {
+               status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
+                       &encoder->protected_->ogg_encoder_aspect,
+                       buffer,
+                       bytes,
+                       samples,
+                       encoder->private_->current_frame_number,
+                       is_last_block,
+                       (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
+                       encoder,
+                       encoder->private_->client_data
+               );
+       }
+       else
+#endif
+       status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
+
+       if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+               encoder->private_->bytes_written += bytes;
+               encoder->private_->samples_written += samples;
+               /* we keep a high watermark on the number of frames written because
+                * when the encoder goes back to write metadata, 'current_frame'
+                * will drop back to 0.
+                */
+               encoder->private_->frames_written = flac_max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
+       }
+       else
+               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+
+       return status;
+}
+
+/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
+void update_metadata_(const FLAC__StreamEncoder *encoder)
+{
+       FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
+       const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
+       const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
+       const unsigned min_framesize = metadata->data.stream_info.min_framesize;
+       const unsigned max_framesize = metadata->data.stream_info.max_framesize;
+       const unsigned bps = metadata->data.stream_info.bits_per_sample;
+       FLAC__StreamEncoderSeekStatus seek_status;
+
+       FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
+
+       /* All this is based on intimate knowledge of the stream header
+        * layout, but a change to the header format that would break this
+        * would also break all streams encoded in the previous format.
+        */
+
+       /*
+        * Write MD5 signature
+        */
+       {
+               const unsigned md5_offset =
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
+                       ) / 8;
+
+               if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+                       if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+               if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+       }
+
+       /*
+        * Write total samples
+        */
+       {
+               const unsigned total_samples_byte_offset =
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
+                               - 4
+                       ) / 8;
+
+               b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
+               b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
+               b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
+               b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
+               b[4] = (FLAC__byte)(samples & 0xFF);
+               if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+                       if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+               if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+       }
+
+       /*
+        * Write min/max framesize
+        */
+       {
+               const unsigned min_framesize_offset =
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
+                       ) / 8;
+
+               b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
+               b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
+               b[2] = (FLAC__byte)(min_framesize & 0xFF);
+               b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
+               b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
+               b[5] = (FLAC__byte)(max_framesize & 0xFF);
+               if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+                       if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+               if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+       }
+
+       /*
+        * Write seektable
+        */
+       if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
+               unsigned i;
+
+               FLAC__format_seektable_sort(encoder->private_->seek_table);
+
+               FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
+
+               if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
+                       if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                       return;
+               }
+
+               for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
+                       FLAC__uint64 xx;
+                       unsigned x;
+                       xx = encoder->private_->seek_table->points[i].sample_number;
+                       b[7] = (FLAC__byte)xx; xx >>= 8;
+                       b[6] = (FLAC__byte)xx; xx >>= 8;
+                       b[5] = (FLAC__byte)xx; xx >>= 8;
+                       b[4] = (FLAC__byte)xx; xx >>= 8;
+                       b[3] = (FLAC__byte)xx; xx >>= 8;
+                       b[2] = (FLAC__byte)xx; xx >>= 8;
+                       b[1] = (FLAC__byte)xx; xx >>= 8;
+                       b[0] = (FLAC__byte)xx; xx >>= 8;
+                       xx = encoder->private_->seek_table->points[i].stream_offset;
+                       b[15] = (FLAC__byte)xx; xx >>= 8;
+                       b[14] = (FLAC__byte)xx; xx >>= 8;
+                       b[13] = (FLAC__byte)xx; xx >>= 8;
+                       b[12] = (FLAC__byte)xx; xx >>= 8;
+                       b[11] = (FLAC__byte)xx; xx >>= 8;
+                       b[10] = (FLAC__byte)xx; xx >>= 8;
+                       b[9] = (FLAC__byte)xx; xx >>= 8;
+                       b[8] = (FLAC__byte)xx; xx >>= 8;
+                       x = encoder->private_->seek_table->points[i].frame_samples;
+                       b[17] = (FLAC__byte)x; x >>= 8;
+                       b[16] = (FLAC__byte)x; x >>= 8;
+                       if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
+                               return;
+                       }
+               }
+       }
+}
+
+#if FLAC__HAS_OGG
+/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
+void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
+{
+       /* the # of bytes in the 1st packet that precede the STREAMINFO */
+       static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
+               FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
+               FLAC__OGG_MAPPING_MAGIC_LENGTH +
+               FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
+               FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
+               FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
+               FLAC__STREAM_SYNC_LENGTH
+       ;
+       FLAC__byte b[flac_max(6u, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
+       const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
+       const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
+       const unsigned min_framesize = metadata->data.stream_info.min_framesize;
+       const unsigned max_framesize = metadata->data.stream_info.max_framesize;
+       ogg_page page;
+
+       FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
+       FLAC__ASSERT(0 != encoder->private_->seek_callback);
+
+       /* Pre-check that client supports seeking, since we don't want the
+        * ogg_helper code to ever have to deal with this condition.
+        */
+       if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
+               return;
+
+       /* All this is based on intimate knowledge of the stream header
+        * layout, but a change to the header format that would break this
+        * would also break all streams encoded in the previous format.
+        */
+
+       /**
+        ** Write STREAMINFO stats
+        **/
+       simple_ogg_page__init(&page);
+       if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
+               simple_ogg_page__clear(&page);
+               return; /* state already set */
+       }
+
+       /*
+        * Write MD5 signature
+        */
+       {
+               const unsigned md5_offset =
+                       FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
+                       ) / 8;
+
+               if(md5_offset + 16 > (unsigned)page.body_len) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                       simple_ogg_page__clear(&page);
+                       return;
+               }
+               memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
+       }
+
+       /*
+        * Write total samples
+        */
+       {
+               const unsigned total_samples_byte_offset =
+                       FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
+                               - 4
+                       ) / 8;
+
+               if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                       simple_ogg_page__clear(&page);
+                       return;
+               }
+               b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
+               b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
+               b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
+               b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
+               b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
+               b[4] = (FLAC__byte)(samples & 0xFF);
+               memcpy(page.body + total_samples_byte_offset, b, 5);
+       }
+
+       /*
+        * Write min/max framesize
+        */
+       {
+               const unsigned min_framesize_offset =
+                       FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
+                       FLAC__STREAM_METADATA_HEADER_LENGTH +
+                       (
+                               FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
+                               FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
+                       ) / 8;
+
+               if(min_framesize_offset + 6 > (unsigned)page.body_len) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                       simple_ogg_page__clear(&page);
+                       return;
+               }
+               b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
+               b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
+               b[2] = (FLAC__byte)(min_framesize & 0xFF);
+               b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
+               b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
+               b[5] = (FLAC__byte)(max_framesize & 0xFF);
+               memcpy(page.body + min_framesize_offset, b, 6);
+       }
+       if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
+               simple_ogg_page__clear(&page);
+               return; /* state already set */
+       }
+       simple_ogg_page__clear(&page);
+
+       /*
+        * Write seektable
+        */
+       if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
+               unsigned i;
+               FLAC__byte *p;
+
+               FLAC__format_seektable_sort(encoder->private_->seek_table);
+
+               FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
+
+               simple_ogg_page__init(&page);
+               if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
+                       simple_ogg_page__clear(&page);
+                       return; /* state already set */
+               }
+
+               if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
+                       simple_ogg_page__clear(&page);
+                       return;
+               }
+
+               for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
+                       FLAC__uint64 xx;
+                       unsigned x;
+                       xx = encoder->private_->seek_table->points[i].sample_number;
+                       b[7] = (FLAC__byte)xx; xx >>= 8;
+                       b[6] = (FLAC__byte)xx; xx >>= 8;
+                       b[5] = (FLAC__byte)xx; xx >>= 8;
+                       b[4] = (FLAC__byte)xx; xx >>= 8;
+                       b[3] = (FLAC__byte)xx; xx >>= 8;
+                       b[2] = (FLAC__byte)xx; xx >>= 8;
+                       b[1] = (FLAC__byte)xx; xx >>= 8;
+                       b[0] = (FLAC__byte)xx; xx >>= 8;
+                       xx = encoder->private_->seek_table->points[i].stream_offset;
+                       b[15] = (FLAC__byte)xx; xx >>= 8;
+                       b[14] = (FLAC__byte)xx; xx >>= 8;
+                       b[13] = (FLAC__byte)xx; xx >>= 8;
+                       b[12] = (FLAC__byte)xx; xx >>= 8;
+                       b[11] = (FLAC__byte)xx; xx >>= 8;
+                       b[10] = (FLAC__byte)xx; xx >>= 8;
+                       b[9] = (FLAC__byte)xx; xx >>= 8;
+                       b[8] = (FLAC__byte)xx; xx >>= 8;
+                       x = encoder->private_->seek_table->points[i].frame_samples;
+                       b[17] = (FLAC__byte)x; x >>= 8;
+                       b[16] = (FLAC__byte)x; x >>= 8;
+                       memcpy(p, b, 18);
+               }
+
+               if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
+                       simple_ogg_page__clear(&page);
+                       return; /* state already set */
+               }
+               simple_ogg_page__clear(&page);
+       }
+}
+#endif
+
+FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
+{
+       FLAC__uint16 crc;
+       FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
+
+       /*
+        * Accumulate raw signal to the MD5 signature
+        */
+       if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       /*
+        * Process the frame header and subframes into the frame bitbuffer
+        */
+       if(!process_subframes_(encoder, is_fractional_block)) {
+               /* the above function sets the state for us in case of an error */
+               return false;
+       }
+
+       /*
+        * Zero-pad the frame to a byte_boundary
+        */
+       if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       /*
+        * CRC-16 the whole thing
+        */
+       FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
+       if(
+               !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
+               !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
+       ) {
+               encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
+               return false;
+       }
+
+       /*
+        * Write it
+        */
+       if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
+               /* the above function sets the state for us in case of an error */
+               return false;
+       }
+
+       /*
+        * Get ready for the next frame
+        */
+       encoder->private_->current_sample_number = 0;
+       encoder->private_->current_frame_number++;
+       encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
+
+       return true;
+}
+
+FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
+{
+       FLAC__FrameHeader frame_header;
+       unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
+       FLAC__bool do_independent, do_mid_side;
+
+       /*
+        * Calculate the min,max Rice partition orders
+        */
+       if(is_fractional_block) {
+               max_partition_order = 0;
+       }
+       else {
+               max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
+               max_partition_order = flac_min(max_partition_order, encoder->protected_->max_residual_partition_order);
+       }
+       min_partition_order = flac_min(min_partition_order, max_partition_order);
+
+       /*
+        * Setup the frame
+        */
+       frame_header.blocksize = encoder->protected_->blocksize;
+       frame_header.sample_rate = encoder->protected_->sample_rate;
+       frame_header.channels = encoder->protected_->channels;
+       frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
+       frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
+       frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
+       frame_header.number.frame_number = encoder->private_->current_frame_number;
+
+       /*
+        * Figure out what channel assignments to try
+        */
+       if(encoder->protected_->do_mid_side_stereo) {
+               if(encoder->protected_->loose_mid_side_stereo) {
+                       if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
+                               do_independent = true;
+                               do_mid_side = true;
+                       }
+                       else {
+                               do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
+                               do_mid_side = !do_independent;
+                       }
+               }
+               else {
+                       do_independent = true;
+                       do_mid_side = true;
+               }
+       }
+       else {
+               do_independent = true;
+               do_mid_side = false;
+       }
+
+       FLAC__ASSERT(do_independent || do_mid_side);
+
+       /*
+        * Check for wasted bits; set effective bps for each subframe
+        */
+       if(do_independent) {
+               for(channel = 0; channel < encoder->protected_->channels; channel++) {
+                       unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
+                       if (w > encoder->protected_->bits_per_sample) {
+                               w = encoder->protected_->bits_per_sample;
+                       }
+                       encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
+                       encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
+               }
+       }
+       if(do_mid_side) {
+               FLAC__ASSERT(encoder->protected_->channels == 2);
+               for(channel = 0; channel < 2; channel++) {
+                       unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
+                       if (w > encoder->protected_->bits_per_sample) {
+                               w = encoder->protected_->bits_per_sample;
+                       }
+                       encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
+                       encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
+               }
+       }
+
+       /*
+        * First do a normal encoding pass of each independent channel
+        */
+       if(do_independent) {
+               for(channel = 0; channel < encoder->protected_->channels; channel++) {
+                       if(!
+                               process_subframe_(
+                                       encoder,
+                                       min_partition_order,
+                                       max_partition_order,
+                                       &frame_header,
+                                       encoder->private_->subframe_bps[channel],
+                                       encoder->private_->integer_signal[channel],
+                                       encoder->private_->subframe_workspace_ptr[channel],
+                                       encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
+                                       encoder->private_->residual_workspace[channel],
+                                       encoder->private_->best_subframe+channel,
+                                       encoder->private_->best_subframe_bits+channel
+                               )
+                       )
+                               return false;
+               }
+       }
+
+       /*
+        * Now do mid and side channels if requested
+        */
+       if(do_mid_side) {
+               FLAC__ASSERT(encoder->protected_->channels == 2);
+
+               for(channel = 0; channel < 2; channel++) {
+                       if(!
+                               process_subframe_(
+                                       encoder,
+                                       min_partition_order,
+                                       max_partition_order,
+                                       &frame_header,
+                                       encoder->private_->subframe_bps_mid_side[channel],
+                                       encoder->private_->integer_signal_mid_side[channel],
+                                       encoder->private_->subframe_workspace_ptr_mid_side[channel],
+                                       encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
+                                       encoder->private_->residual_workspace_mid_side[channel],
+                                       encoder->private_->best_subframe_mid_side+channel,
+                                       encoder->private_->best_subframe_bits_mid_side+channel
+                               )
+                       )
+                               return false;
+               }
+       }
+
+       /*
+        * Compose the frame bitbuffer
+        */
+       if(do_mid_side) {
+               unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
+               FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
+               FLAC__ChannelAssignment channel_assignment;
+
+               FLAC__ASSERT(encoder->protected_->channels == 2);
+
+               if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
+                       channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
+               }
+               else {
+                       unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
+                       unsigned min_bits;
+                       int ca;
+
+                       FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
+                       FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
+                       FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
+                       FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
+                       FLAC__ASSERT(do_independent && do_mid_side);
+
+                       /* We have to figure out which channel assignent results in the smallest frame */
+                       bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
+                       bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
+                       bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
+                       bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
+
+                       channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
+                       min_bits = bits[channel_assignment];
+                       for(ca = 1; ca <= 3; ca++) {
+                               if(bits[ca] < min_bits) {
+                                       min_bits = bits[ca];
+                                       channel_assignment = (FLAC__ChannelAssignment)ca;
+                               }
+                       }
+               }
+
+               frame_header.channel_assignment = channel_assignment;
+
+               if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                       return false;
+               }
+
+               switch(channel_assignment) {
+                       case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
+                               left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
+                               right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
+                               left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
+                               right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
+                               left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
+                               right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
+                               left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
+                               right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
+                               break;
+                       default:
+                               FLAC__ASSERT(0);
+               }
+
+               switch(channel_assignment) {
+                       case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
+                               left_bps  = encoder->private_->subframe_bps         [0];
+                               right_bps = encoder->private_->subframe_bps         [1];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
+                               left_bps  = encoder->private_->subframe_bps         [0];
+                               right_bps = encoder->private_->subframe_bps_mid_side[1];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
+                               left_bps  = encoder->private_->subframe_bps_mid_side[1];
+                               right_bps = encoder->private_->subframe_bps         [1];
+                               break;
+                       case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
+                               left_bps  = encoder->private_->subframe_bps_mid_side[0];
+                               right_bps = encoder->private_->subframe_bps_mid_side[1];
+                               break;
+                       default:
+                               FLAC__ASSERT(0);
+               }
+
+               /* note that encoder_add_subframe_ sets the state for us in case of an error */
+               if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
+                       return false;
+               if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
+                       return false;
+       }
+       else {
+               if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                       return false;
+               }
+
+               for(channel = 0; channel < encoder->protected_->channels; channel++) {
+                       if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
+                               /* the above function sets the state for us in case of an error */
+                               return false;
+                       }
+               }
+       }
+
+       if(encoder->protected_->loose_mid_side_stereo) {
+               encoder->private_->loose_mid_side_stereo_frame_count++;
+               if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
+                       encoder->private_->loose_mid_side_stereo_frame_count = 0;
+       }
+
+       encoder->private_->last_channel_assignment = frame_header.channel_assignment;
+
+       return true;
+}
+
+FLAC__bool process_subframe_(
+       FLAC__StreamEncoder *encoder,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       const FLAC__FrameHeader *frame_header,
+       unsigned subframe_bps,
+       const FLAC__int32 integer_signal[],
+       FLAC__Subframe *subframe[2],
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
+       FLAC__int32 *residual[2],
+       unsigned *best_subframe,
+       unsigned *best_bits
+)
+{
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
+#else
+       FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
+#endif
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+       double lpc_residual_bits_per_sample;
+       FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm and x86 intrinsic routines need all the space */
+       double lpc_error[FLAC__MAX_LPC_ORDER];
+       unsigned min_lpc_order, max_lpc_order, lpc_order;
+       unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
+#endif
+       unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
+       unsigned rice_parameter;
+       unsigned _candidate_bits, _best_bits;
+       unsigned _best_subframe;
+       /* only use RICE2 partitions if stream bps > 16 */
+       const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
+
+       FLAC__ASSERT(frame_header->blocksize > 0);
+
+       /* verbatim subframe is the baseline against which we measure other compressed subframes */
+       _best_subframe = 0;
+       if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
+               _best_bits = UINT_MAX;
+       else
+               _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
+
+       if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
+               unsigned signal_is_constant = false;
+               if(subframe_bps + 4 + FLAC__bitmath_ilog2((frame_header->blocksize-FLAC__MAX_FIXED_ORDER)|1) <= 32)
+                       guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
+               else
+                       guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor_wide(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
+               /* check for constant subframe */
+               if(
+                       !encoder->private_->disable_constant_subframes &&
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+                       fixed_residual_bits_per_sample[1] == 0.0
+#else
+                       fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
+#endif
+               ) {
+                       /* the above means it's possible all samples are the same value; now double-check it: */
+                       unsigned i;
+                       signal_is_constant = true;
+                       for(i = 1; i < frame_header->blocksize; i++) {
+                               if(integer_signal[0] != integer_signal[i]) {
+                                       signal_is_constant = false;
+                                       break;
+                               }
+                       }
+               }
+               if(signal_is_constant) {
+                       _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
+                       if(_candidate_bits < _best_bits) {
+                               _best_subframe = !_best_subframe;
+                               _best_bits = _candidate_bits;
+                       }
+               }
+               else {
+                       if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
+                               /* encode fixed */
+                               if(encoder->protected_->do_exhaustive_model_search) {
+                                       min_fixed_order = 0;
+                                       max_fixed_order = FLAC__MAX_FIXED_ORDER;
+                               }
+                               else {
+                                       min_fixed_order = max_fixed_order = guess_fixed_order;
+                               }
+                               if(max_fixed_order >= frame_header->blocksize)
+                                       max_fixed_order = frame_header->blocksize - 1;
+                               for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+                                       if(fixed_residual_bits_per_sample[fixed_order] >= (float)subframe_bps)
+                                               continue; /* don't even try */
+                                       rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
+#else
+                                       if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
+                                               continue; /* don't even try */
+                                       rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
+#endif
+                                       rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
+                                       if(rice_parameter >= rice_parameter_limit) {
+#ifdef DEBUG_VERBOSE
+                                               fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
+#endif
+                                               rice_parameter = rice_parameter_limit - 1;
+                                       }
+                                       _candidate_bits =
+                                               evaluate_fixed_subframe_(
+                                                       encoder,
+                                                       integer_signal,
+                                                       residual[!_best_subframe],
+                                                       encoder->private_->abs_residual_partition_sums,
+                                                       encoder->private_->raw_bits_per_partition,
+                                                       frame_header->blocksize,
+                                                       subframe_bps,
+                                                       fixed_order,
+                                                       rice_parameter,
+                                                       rice_parameter_limit,
+                                                       min_partition_order,
+                                                       max_partition_order,
+                                                       encoder->protected_->do_escape_coding,
+                                                       encoder->protected_->rice_parameter_search_dist,
+                                                       subframe[!_best_subframe],
+                                                       partitioned_rice_contents[!_best_subframe]
+                                               );
+                                       if(_candidate_bits < _best_bits) {
+                                               _best_subframe = !_best_subframe;
+                                               _best_bits = _candidate_bits;
+                                       }
+                               }
+                       }
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+                       /* encode lpc */
+                       if(encoder->protected_->max_lpc_order > 0) {
+                               if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
+                                       max_lpc_order = frame_header->blocksize-1;
+                               else
+                                       max_lpc_order = encoder->protected_->max_lpc_order;
+                               if(max_lpc_order > 0) {
+                                       unsigned a;
+                                       for (a = 0; a < encoder->protected_->num_apodizations; a++) {
+                                               FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
+                                               encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
+                                               /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
+                                               if(autoc[0] != 0.0) {
+                                                       FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
+                                                       if(encoder->protected_->do_exhaustive_model_search) {
+                                                               min_lpc_order = 1;
+                                                       }
+                                                       else {
+                                                               const unsigned guess_lpc_order =
+                                                                       FLAC__lpc_compute_best_order(
+                                                                               lpc_error,
+                                                                               max_lpc_order,
+                                                                               frame_header->blocksize,
+                                                                               subframe_bps + (
+                                                                                       encoder->protected_->do_qlp_coeff_prec_search?
+                                                                                               FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
+                                                                                               encoder->protected_->qlp_coeff_precision
+                                                                               )
+                                                                       );
+                                                               min_lpc_order = max_lpc_order = guess_lpc_order;
+                                                       }
+                                                       if(max_lpc_order >= frame_header->blocksize)
+                                                               max_lpc_order = frame_header->blocksize - 1;
+                                                       for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
+                                                               lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
+                                                               if(lpc_residual_bits_per_sample >= (double)subframe_bps)
+                                                                       continue; /* don't even try */
+                                                               rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
+                                                               rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
+                                                               if(rice_parameter >= rice_parameter_limit) {
+#ifdef DEBUG_VERBOSE
+                                                                       fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
+#endif
+                                                                       rice_parameter = rice_parameter_limit - 1;
+                                                               }
+                                                               if(encoder->protected_->do_qlp_coeff_prec_search) {
+                                                                       min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
+                                                                       /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps(+1bps for side channel) streams */
+                                                                       if(subframe_bps <= 17) {
+                                                                               max_qlp_coeff_precision = flac_min(32 - subframe_bps - FLAC__bitmath_ilog2(lpc_order), FLAC__MAX_QLP_COEFF_PRECISION);
+                                                                               max_qlp_coeff_precision = flac_max(max_qlp_coeff_precision, min_qlp_coeff_precision);
+                                                                       }
+                                                                       else
+                                                                               max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
+                                                               }
+                                                               else {
+                                                                       min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
+                                                               }
+                                                               for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
+                                                                       _candidate_bits =
+                                                                               evaluate_lpc_subframe_(
+                                                                                       encoder,
+                                                                                       integer_signal,
+                                                                                       residual[!_best_subframe],
+                                                                                       encoder->private_->abs_residual_partition_sums,
+                                                                                       encoder->private_->raw_bits_per_partition,
+                                                                                       encoder->private_->lp_coeff[lpc_order-1],
+                                                                                       frame_header->blocksize,
+                                                                                       subframe_bps,
+                                                                                       lpc_order,
+                                                                                       qlp_coeff_precision,
+                                                                                       rice_parameter,
+                                                                                       rice_parameter_limit,
+                                                                                       min_partition_order,
+                                                                                       max_partition_order,
+                                                                                       encoder->protected_->do_escape_coding,
+                                                                                       encoder->protected_->rice_parameter_search_dist,
+                                                                                       subframe[!_best_subframe],
+                                                                                       partitioned_rice_contents[!_best_subframe]
+                                                                               );
+                                                                       if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
+                                                                               if(_candidate_bits < _best_bits) {
+                                                                                       _best_subframe = !_best_subframe;
+                                                                                       _best_bits = _candidate_bits;
+                                                                               }
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
+               }
+       }
+
+       /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
+       if(_best_bits == UINT_MAX) {
+               FLAC__ASSERT(_best_subframe == 0);
+               _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
+       }
+
+       *best_subframe = _best_subframe;
+       *best_bits = _best_bits;
+
+       return true;
+}
+
+FLAC__bool add_subframe_(
+       FLAC__StreamEncoder *encoder,
+       unsigned blocksize,
+       unsigned subframe_bps,
+       const FLAC__Subframe *subframe,
+       FLAC__BitWriter *frame
+)
+{
+       switch(subframe->type) {
+               case FLAC__SUBFRAME_TYPE_CONSTANT:
+                       if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                               return false;
+                       }
+                       break;
+               case FLAC__SUBFRAME_TYPE_FIXED:
+                       if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                               return false;
+                       }
+                       break;
+               case FLAC__SUBFRAME_TYPE_LPC:
+                       if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                               return false;
+                       }
+                       break;
+               case FLAC__SUBFRAME_TYPE_VERBATIM:
+                       if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
+                               encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
+                               return false;
+                       }
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       return true;
+}
+
+#define SPOTCHECK_ESTIMATE 0
+#if SPOTCHECK_ESTIMATE
+static void spotcheck_subframe_estimate_(
+       FLAC__StreamEncoder *encoder,
+       unsigned blocksize,
+       unsigned subframe_bps,
+       const FLAC__Subframe *subframe,
+       unsigned estimate
+)
+{
+       FLAC__bool ret;
+       FLAC__BitWriter *frame = FLAC__bitwriter_new();
+       if(frame == 0) {
+               fprintf(stderr, "EST: can't allocate frame\n");
+               return;
+       }
+       if(!FLAC__bitwriter_init(frame)) {
+               fprintf(stderr, "EST: can't init frame\n");
+               return;
+       }
+       ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
+       FLAC__ASSERT(ret);
+       {
+               const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
+               if(estimate != actual)
+                       fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
+       }
+       FLAC__bitwriter_delete(frame);
+}
+#endif
+
+unsigned evaluate_constant_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal,
+       unsigned blocksize,
+       unsigned subframe_bps,
+       FLAC__Subframe *subframe
+)
+{
+       unsigned estimate;
+       subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
+       subframe->data.constant.value = signal;
+
+       estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
+
+#if SPOTCHECK_ESTIMATE
+       spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
+#else
+       (void)encoder, (void)blocksize;
+#endif
+
+       return estimate;
+}
+
+unsigned evaluate_fixed_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       unsigned order,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__Subframe *subframe,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
+)
+{
+       unsigned i, residual_bits, estimate;
+       const unsigned residual_samples = blocksize - order;
+
+       FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
+
+       subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
+
+       subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
+       subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
+       subframe->data.fixed.residual = residual;
+
+       residual_bits =
+               find_best_partition_order_(
+                       encoder->private_,
+                       residual,
+                       abs_residual_partition_sums,
+                       raw_bits_per_partition,
+                       residual_samples,
+                       order,
+                       rice_parameter,
+                       rice_parameter_limit,
+                       min_partition_order,
+                       max_partition_order,
+                       subframe_bps,
+                       do_escape_coding,
+                       rice_parameter_search_dist,
+                       &subframe->data.fixed.entropy_coding_method
+               );
+
+       subframe->data.fixed.order = order;
+       for(i = 0; i < order; i++)
+               subframe->data.fixed.warmup[i] = signal[i];
+
+       estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
+
+#if SPOTCHECK_ESTIMATE
+       spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
+#endif
+
+       return estimate;
+}
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+unsigned evaluate_lpc_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       const FLAC__real lp_coeff[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       unsigned order,
+       unsigned qlp_coeff_precision,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__Subframe *subframe,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
+)
+{
+       FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; /* WATCHOUT: the size is important; some x86 intrinsic routines need more than lpc order elements */
+       unsigned i, residual_bits, estimate;
+       int quantization, ret;
+       const unsigned residual_samples = blocksize - order;
+
+       /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps(+1bps for side channel) streams */
+       if(subframe_bps <= 17) {
+               FLAC__ASSERT(order > 0);
+               FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
+               qlp_coeff_precision = flac_min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
+       }
+
+       ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
+       if(ret != 0)
+               return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
+
+       if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
+               if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
+               else
+                       encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
+       else
+               encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
+
+       subframe->type = FLAC__SUBFRAME_TYPE_LPC;
+
+       subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
+       subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
+       subframe->data.lpc.residual = residual;
+
+       residual_bits =
+               find_best_partition_order_(
+                       encoder->private_,
+                       residual,
+                       abs_residual_partition_sums,
+                       raw_bits_per_partition,
+                       residual_samples,
+                       order,
+                       rice_parameter,
+                       rice_parameter_limit,
+                       min_partition_order,
+                       max_partition_order,
+                       subframe_bps,
+                       do_escape_coding,
+                       rice_parameter_search_dist,
+                       &subframe->data.lpc.entropy_coding_method
+               );
+
+       subframe->data.lpc.order = order;
+       subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
+       subframe->data.lpc.quantization_level = quantization;
+       memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
+       for(i = 0; i < order; i++)
+               subframe->data.lpc.warmup[i] = signal[i];
+
+       estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
+
+#if SPOTCHECK_ESTIMATE
+       spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
+#endif
+
+       return estimate;
+}
+#endif
+
+unsigned evaluate_verbatim_subframe_(
+       FLAC__StreamEncoder *encoder,
+       const FLAC__int32 signal[],
+       unsigned blocksize,
+       unsigned subframe_bps,
+       FLAC__Subframe *subframe
+)
+{
+       unsigned estimate;
+
+       subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
+
+       subframe->data.verbatim.data = signal;
+
+       estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
+
+#if SPOTCHECK_ESTIMATE
+       spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
+#else
+       (void)encoder;
+#endif
+
+       return estimate;
+}
+
+unsigned find_best_partition_order_(
+       FLAC__StreamEncoderPrivate *private_,
+       const FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned raw_bits_per_partition[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned rice_parameter,
+       unsigned rice_parameter_limit,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       unsigned bps,
+       FLAC__bool do_escape_coding,
+       unsigned rice_parameter_search_dist,
+       FLAC__EntropyCodingMethod *best_ecm
+)
+{
+       unsigned residual_bits, best_residual_bits = 0;
+       unsigned best_parameters_index = 0;
+       unsigned best_partition_order = 0;
+       const unsigned blocksize = residual_samples + predictor_order;
+
+       max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
+       min_partition_order = flac_min(min_partition_order, max_partition_order);
+
+       private_->local_precompute_partition_info_sums(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
+
+       if(do_escape_coding)
+               precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
+
+       {
+               int partition_order;
+               unsigned sum;
+
+               for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
+                       if(!
+                               set_partitioned_rice_(
+#ifdef EXACT_RICE_BITS_CALCULATION
+                                       residual,
+#endif
+                                       abs_residual_partition_sums+sum,
+                                       raw_bits_per_partition+sum,
+                                       residual_samples,
+                                       predictor_order,
+                                       rice_parameter,
+                                       rice_parameter_limit,
+                                       rice_parameter_search_dist,
+                                       (unsigned)partition_order,
+                                       do_escape_coding,
+                                       &private_->partitioned_rice_contents_extra[!best_parameters_index],
+                                       &residual_bits
+                               )
+                       )
+                       {
+                               FLAC__ASSERT(best_residual_bits != 0);
+                               break;
+                       }
+                       sum += 1u << partition_order;
+                       if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
+                               best_residual_bits = residual_bits;
+                               best_parameters_index = !best_parameters_index;
+                               best_partition_order = partition_order;
+                       }
+               }
+       }
+
+       best_ecm->data.partitioned_rice.order = best_partition_order;
+
+       {
+               /*
+                * We are allowed to de-const the pointer based on our special
+                * knowledge; it is const to the outside world.
+                */
+               FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
+               unsigned partition;
+
+               /* save best parameters and raw_bits */
+               FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, flac_max(6u, best_partition_order));
+               memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
+               if(do_escape_coding)
+                       memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
+               /*
+                * Now need to check if the type should be changed to
+                * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
+                * size of the rice parameters.
+                */
+               for(partition = 0; partition < (1u<<best_partition_order); partition++) {
+                       if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
+                               best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
+                               break;
+                       }
+               }
+       }
+
+       return best_residual_bits;
+}
+
+void precompute_partition_info_sums_(
+       const FLAC__int32 residual[],
+       FLAC__uint64 abs_residual_partition_sums[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned min_partition_order,
+       unsigned max_partition_order,
+       unsigned bps
+)
+{
+       const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
+       unsigned partitions = 1u << max_partition_order;
+
+       FLAC__ASSERT(default_partition_samples > predictor_order);
+
+       /* first do max_partition_order */
+       {
+               const unsigned threshold = 32 - FLAC__bitmath_ilog2(default_partition_samples);
+               unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
+               /* WATCHOUT: "bps + FLAC__MAX_EXTRA_RESIDUAL_BPS" is the maximum assumed size of the average residual magnitude */
+               if(bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < threshold) {
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               FLAC__uint32 abs_residual_partition_sum = 0;
+                               end += default_partition_samples;
+                               for( ; residual_sample < end; residual_sample++)
+                                       abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
+                               abs_residual_partition_sums[partition] = abs_residual_partition_sum;
+                       }
+               }
+               else { /* have to pessimistically use 64 bits for accumulator */
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               FLAC__uint64 abs_residual_partition_sum64 = 0;
+                               end += default_partition_samples;
+                               for( ; residual_sample < end; residual_sample++)
+                                       abs_residual_partition_sum64 += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
+                               abs_residual_partition_sums[partition] = abs_residual_partition_sum64;
+                       }
+               }
+       }
+
+       /* now merge partitions for lower orders */
+       {
+               unsigned from_partition = 0, to_partition = partitions;
+               int partition_order;
+               for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
+                       unsigned i;
+                       partitions >>= 1;
+                       for(i = 0; i < partitions; i++) {
+                               abs_residual_partition_sums[to_partition++] =
+                                       abs_residual_partition_sums[from_partition  ] +
+                                       abs_residual_partition_sums[from_partition+1];
+                               from_partition += 2;
+                       }
+               }
+       }
+}
+
+void precompute_partition_info_escapes_(
+       const FLAC__int32 residual[],
+       unsigned raw_bits_per_partition[],
+       unsigned residual_samples,
+       unsigned predictor_order,
+       unsigned min_partition_order,
+       unsigned max_partition_order
+)
+{
+       int partition_order;
+       unsigned from_partition, to_partition = 0;
+       const unsigned blocksize = residual_samples + predictor_order;
+
+       /* first do max_partition_order */
+       for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
+               FLAC__int32 r;
+               FLAC__uint32 rmax;
+               unsigned partition, partition_sample, partition_samples, residual_sample;
+               const unsigned partitions = 1u << partition_order;
+               const unsigned default_partition_samples = blocksize >> partition_order;
+
+               FLAC__ASSERT(default_partition_samples > predictor_order);
+
+               for(partition = residual_sample = 0; partition < partitions; partition++) {
+                       partition_samples = default_partition_samples;
+                       if(partition == 0)
+                               partition_samples -= predictor_order;
+                       rmax = 0;
+                       for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
+                               r = residual[residual_sample++];
+                               /* OPT: maybe faster: rmax |= r ^ (r>>31) */
+                               if(r < 0)
+                                       rmax |= ~r;
+                               else
+                                       rmax |= r;
+                       }
+                       /* now we know all residual values are in the range [-rmax-1,rmax] */
+                       raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
+               }
+               to_partition = partitions;
+               break; /*@@@ yuck, should remove the 'for' loop instead */
+       }
+
+       /* now merge partitions for lower orders */
+       for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
+               unsigned m;
+               unsigned i;
+               const unsigned partitions = 1u << partition_order;
+               for(i = 0; i < partitions; i++) {
+                       m = raw_bits_per_partition[from_partition];
+                       from_partition++;
+                       raw_bits_per_partition[to_partition] = flac_max(m, raw_bits_per_partition[from_partition]);
+                       from_partition++;
+                       to_partition++;
+               }
+       }
+}
+
+#ifdef EXACT_RICE_BITS_CALCULATION
+static inline unsigned count_rice_bits_in_partition_(
+       const unsigned rice_parameter,
+       const unsigned partition_samples,
+       const FLAC__int32 *residual
+)
+{
+       unsigned i, partition_bits =
+               FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
+               (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
+       ;
+       for(i = 0; i < partition_samples; i++)
+               partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
+       return partition_bits;
+}
+#else
+static inline unsigned count_rice_bits_in_partition_(
+       const unsigned rice_parameter,
+       const unsigned partition_samples,
+       const FLAC__uint64 abs_residual_partition_sum
+)
+{
+       return
+               FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
+               (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
+               (
+                       rice_parameter?
+                               (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
+                               : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
+               )
+               - (partition_samples >> 1)
+               /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
+                * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
+                * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
+                * So the subtraction term tries to guess how many extra bits were contributed.
+                * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
+                */
+       ;
+}
+#endif
+
+FLAC__bool set_partitioned_rice_(
+#ifdef EXACT_RICE_BITS_CALCULATION
+       const FLAC__int32 residual[],
+#endif
+       const FLAC__uint64 abs_residual_partition_sums[],
+       const unsigned raw_bits_per_partition[],
+       const unsigned residual_samples,
+       const unsigned predictor_order,
+       const unsigned suggested_rice_parameter,
+       const unsigned rice_parameter_limit,
+       const unsigned rice_parameter_search_dist,
+       const unsigned partition_order,
+       const FLAC__bool search_for_escapes,
+       FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
+       unsigned *bits
+)
+{
+       unsigned rice_parameter, partition_bits;
+       unsigned best_partition_bits, best_rice_parameter = 0;
+       unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
+       unsigned *parameters, *raw_bits;
+#ifdef ENABLE_RICE_PARAMETER_SEARCH
+       unsigned min_rice_parameter, max_rice_parameter;
+#else
+       (void)rice_parameter_search_dist;
+#endif
+
+       FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
+       FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
+
+       FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, flac_max(6u, partition_order));
+       parameters = partitioned_rice_contents->parameters;
+       raw_bits = partitioned_rice_contents->raw_bits;
+
+       if(partition_order == 0) {
+               best_partition_bits = (unsigned)(-1);
+#ifdef ENABLE_RICE_PARAMETER_SEARCH
+               if(rice_parameter_search_dist) {
+                       if(suggested_rice_parameter < rice_parameter_search_dist)
+                               min_rice_parameter = 0;
+                       else
+                               min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
+                       max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
+                       if(max_rice_parameter >= rice_parameter_limit) {
+#ifdef DEBUG_VERBOSE
+                               fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
+#endif
+                               max_rice_parameter = rice_parameter_limit - 1;
+                       }
+               }
+               else
+                       min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
+
+               for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
+#else
+                       rice_parameter = suggested_rice_parameter;
+#endif
+#ifdef EXACT_RICE_BITS_CALCULATION
+                       partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
+#else
+                       partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
+#endif
+                       if(partition_bits < best_partition_bits) {
+                               best_rice_parameter = rice_parameter;
+                               best_partition_bits = partition_bits;
+                       }
+#ifdef ENABLE_RICE_PARAMETER_SEARCH
+               }
+#endif
+               if(search_for_escapes) {
+                       partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
+                       if(partition_bits <= best_partition_bits) {
+                               raw_bits[0] = raw_bits_per_partition[0];
+                               best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
+                               best_partition_bits = partition_bits;
+                       }
+                       else
+                               raw_bits[0] = 0;
+               }
+               parameters[0] = best_rice_parameter;
+               bits_ += best_partition_bits;
+       }
+       else {
+               unsigned partition, residual_sample;
+               unsigned partition_samples;
+               FLAC__uint64 mean, k;
+               const unsigned partitions = 1u << partition_order;
+               for(partition = residual_sample = 0; partition < partitions; partition++) {
+                       partition_samples = (residual_samples+predictor_order) >> partition_order;
+                       if(partition == 0) {
+                               if(partition_samples <= predictor_order)
+                                       return false;
+                               else
+                                       partition_samples -= predictor_order;
+                       }
+                       mean = abs_residual_partition_sums[partition];
+                       /* we are basically calculating the size in bits of the
+                        * average residual magnitude in the partition:
+                        *   rice_parameter = floor(log2(mean/partition_samples))
+                        * 'mean' is not a good name for the variable, it is
+                        * actually the sum of magnitudes of all residual values
+                        * in the partition, so the actual mean is
+                        * mean/partition_samples
+                        */
+#if 0 /* old simple code */
+                       for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
+                               ;
+#else
+#if defined FLAC__CPU_X86_64 /* and other 64-bit arch, too */
+                       if(mean <= 0x80000000/512) { /* 512: more or less optimal for both 16- and 24-bit input */
+#else
+                       if(mean <= 0x80000000/8) { /* 32-bit arch: use 32-bit math if possible */
+#endif
+                               FLAC__uint32 k2, mean2 = (FLAC__uint32) mean;
+                               rice_parameter = 0; k2 = partition_samples;
+                               while(k2*8 < mean2) { /* requires: mean <= (2^31)/8 */
+                                       rice_parameter += 4; k2 <<= 4; /* tuned for 16-bit input */
+                               }
+                               while(k2 < mean2) { /* requires: mean <= 2^31 */
+                                       rice_parameter++; k2 <<= 1;
+                               }
+                       }
+                       else {
+                               rice_parameter = 0; k = partition_samples;
+                               if(mean <= FLAC__U64L(0x8000000000000000)/128) /* usually mean is _much_ smaller than this value */
+                                       while(k*128 < mean) { /* requires: mean <= (2^63)/128 */
+                                               rice_parameter += 8; k <<= 8; /* tuned for 24-bit input */
+                                       }
+                               while(k < mean) { /* requires: mean <= 2^63 */
+                                       rice_parameter++; k <<= 1;
+                               }
+                       }
+#endif
+                       if(rice_parameter >= rice_parameter_limit) {
+#ifdef DEBUG_VERBOSE
+                               fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
+#endif
+                               rice_parameter = rice_parameter_limit - 1;
+                       }
+
+                       best_partition_bits = (unsigned)(-1);
+#ifdef ENABLE_RICE_PARAMETER_SEARCH
+                       if(rice_parameter_search_dist) {
+                               if(rice_parameter < rice_parameter_search_dist)
+                                       min_rice_parameter = 0;
+                               else
+                                       min_rice_parameter = rice_parameter - rice_parameter_search_dist;
+                               max_rice_parameter = rice_parameter + rice_parameter_search_dist;
+                               if(max_rice_parameter >= rice_parameter_limit) {
+#ifdef DEBUG_VERBOSE
+                                       fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
+#endif
+                                       max_rice_parameter = rice_parameter_limit - 1;
+                               }
+                       }
+                       else
+                               min_rice_parameter = max_rice_parameter = rice_parameter;
+
+                       for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
+#endif
+#ifdef EXACT_RICE_BITS_CALCULATION
+                               partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
+#else
+                               partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
+#endif
+                               if(partition_bits < best_partition_bits) {
+                                       best_rice_parameter = rice_parameter;
+                                       best_partition_bits = partition_bits;
+                               }
+#ifdef ENABLE_RICE_PARAMETER_SEARCH
+                       }
+#endif
+                       if(search_for_escapes) {
+                               partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
+                               if(partition_bits <= best_partition_bits) {
+                                       raw_bits[partition] = raw_bits_per_partition[partition];
+                                       best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
+                                       best_partition_bits = partition_bits;
+                               }
+                               else
+                                       raw_bits[partition] = 0;
+                       }
+                       parameters[partition] = best_rice_parameter;
+                       bits_ += best_partition_bits;
+                       residual_sample += partition_samples;
+               }
+       }
+
+       *bits = bits_;
+       return true;
+}
+
+unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
+{
+       unsigned i, shift;
+       FLAC__int32 x = 0;
+
+       for(i = 0; i < samples && !(x&1); i++)
+               x |= signal[i];
+
+       if(x == 0) {
+               shift = 0;
+       }
+       else {
+               for(shift = 0; !(x&1); shift++)
+                       x >>= 1;
+       }
+
+       if(shift > 0) {
+               for(i = 0; i < samples; i++)
+                        signal[i] >>= shift;
+       }
+
+       return shift;
+}
+
+void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
+{
+       unsigned channel;
+
+       for(channel = 0; channel < channels; channel++)
+               memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
+
+       fifo->tail += wide_samples;
+
+       FLAC__ASSERT(fifo->tail <= fifo->size);
+}
+
+void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
+{
+       unsigned channel;
+       unsigned sample, wide_sample;
+       unsigned tail = fifo->tail;
+
+       sample = input_offset * channels;
+       for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
+               for(channel = 0; channel < channels; channel++)
+                       fifo->data[channel][tail] = input[sample++];
+               tail++;
+       }
+       fifo->tail = tail;
+
+       FLAC__ASSERT(fifo->tail <= fifo->size);
+}
+
+FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
+       const size_t encoded_bytes = encoder->private_->verify.output.bytes;
+       (void)decoder;
+
+       if(encoder->private_->verify.needs_magic_hack) {
+               FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
+               *bytes = FLAC__STREAM_SYNC_LENGTH;
+               memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
+               encoder->private_->verify.needs_magic_hack = false;
+       }
+       else {
+               if(encoded_bytes == 0) {
+                       /*
+                        * If we get here, a FIFO underflow has occurred,
+                        * which means there is a bug somewhere.
+                        */
+                       FLAC__ASSERT(0);
+                       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
+               }
+               else if(encoded_bytes < *bytes)
+                       *bytes = encoded_bytes;
+               memcpy(buffer, encoder->private_->verify.output.data, *bytes);
+               encoder->private_->verify.output.data += *bytes;
+               encoder->private_->verify.output.bytes -= *bytes;
+       }
+
+       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
+}
+
+FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
+{
+       FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
+       unsigned channel;
+       const unsigned channels = frame->header.channels;
+       const unsigned blocksize = frame->header.blocksize;
+       const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
+
+       (void)decoder;
+
+       for(channel = 0; channel < channels; channel++) {
+               if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
+                       unsigned i, sample = 0;
+                       FLAC__int32 expect = 0, got = 0;
+
+                       for(i = 0; i < blocksize; i++) {
+                               if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
+                                       sample = i;
+                                       expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
+                                       got = (FLAC__int32)buffer[channel][i];
+                                       break;
+                               }
+                       }
+                       FLAC__ASSERT(i < blocksize);
+                       FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
+                       encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
+                       encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
+                       encoder->private_->verify.error_stats.channel = channel;
+                       encoder->private_->verify.error_stats.sample = sample;
+                       encoder->private_->verify.error_stats.expected = expect;
+                       encoder->private_->verify.error_stats.got = got;
+                       encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
+                       return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
+               }
+       }
+       /* dequeue the frame from the fifo */
+       encoder->private_->verify.input_fifo.tail -= blocksize;
+       FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
+       for(channel = 0; channel < channels; channel++)
+               memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
+       return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
+}
+
+void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
+{
+       (void)decoder, (void)metadata, (void)client_data;
+}
+
+void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
+{
+       FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
+       (void)decoder, (void)status;
+       encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
+}
+
+FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
+{
+       (void)client_data;
+
+       *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
+       if (*bytes == 0) {
+               if (feof(encoder->private_->file))
+                       return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
+               else if (ferror(encoder->private_->file))
+                       return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
+       }
+       return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
+}
+
+FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
+{
+       (void)client_data;
+
+       if(fseeko(encoder->private_->file, (FLAC__off_t)absolute_byte_offset, SEEK_SET) < 0)
+               return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
+       else
+               return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
+}
+
+FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
+{
+       FLAC__off_t offset;
+
+       (void)client_data;
+
+       offset = ftello(encoder->private_->file);
+
+       if(offset < 0) {
+               return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
+       }
+       else {
+               *absolute_byte_offset = (FLAC__uint64)offset;
+               return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
+       }
+}
+
+#ifdef FLAC__VALGRIND_TESTING
+static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
+{
+       size_t ret = fwrite(ptr, size, nmemb, stream);
+       if(!ferror(stream))
+               fflush(stream);
+       return ret;
+}
+#else
+#define local__fwrite fwrite
+#endif
+
+FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
+{
+       (void)client_data, (void)current_frame;
+
+       if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
+               FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
+#if FLAC__HAS_OGG
+                       /* We would like to be able to use 'samples > 0' in the
+                        * clause here but currently because of the nature of our
+                        * Ogg writing implementation, 'samples' is always 0 (see
+                        * ogg_encoder_aspect.c).  The downside is extra progress
+                        * callbacks.
+                        */
+                       encoder->private_->is_ogg? true :
+#endif
+                       samples > 0
+               );
+               if(call_it) {
+                       /* NOTE: We have to add +bytes, +samples, and +1 to the stats
+                        * because at this point in the callback chain, the stats
+                        * have not been updated.  Only after we return and control
+                        * gets back to write_frame_() are the stats updated
+                        */
+                       encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
+               }
+               return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+       }
+       else
+               return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
+}
+
+/*
+ * This will forcibly set stdout to binary mode (for OSes that require it)
+ */
+FILE *get_binary_stdout_(void)
+{
+       /* if something breaks here it is probably due to the presence or
+        * absence of an underscore before the identifiers 'setmode',
+        * 'fileno', and/or 'O_BINARY'; check your system header files.
+        */
+#if defined _MSC_VER || defined __MINGW32__
+       _setmode(_fileno(stdout), _O_BINARY);
+#elif defined __CYGWIN__
+       /* almost certainly not needed for any modern Cygwin, but let's be safe... */
+       setmode(_fileno(stdout), _O_BINARY);
+#elif defined __EMX__
+       setmode(fileno(stdout), O_BINARY);
+#endif
+
+       return stdout;
+}
diff --git a/FLAC/src/stream_encoder_framing.c b/FLAC/src/stream_encoder_framing.c
new file mode 100644 (file)
index 0000000..0929cd7
--- /dev/null
@@ -0,0 +1,554 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 <stdio.h>
+#include <string.h> /* for strlen() */
+#include "private/stream_encoder_framing.h"
+#include "private/crc.h"
+#include "FLAC/assert.h"
+#include "share/compat.h"
+
+static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
+static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
+
+FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
+{
+       unsigned i, j;
+       const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
+               return false;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
+               return false;
+
+       /*
+        * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
+        */
+       i = metadata->length;
+       if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
+               FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
+               i -= metadata->data.vorbis_comment.vendor_string.length;
+               i += vendor_string_length;
+       }
+       FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
+       /* double protection */
+       if(i >= (1u << FLAC__STREAM_METADATA_LENGTH_LEN))
+               return false;
+       if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
+               return false;
+
+       switch(metadata->type) {
+               case FLAC__METADATA_TYPE_STREAMINFO:
+                       FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
+                               return false;
+                       FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.channels > 0);
+                       FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
+                       FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
+                               return false;
+                       FLAC__ASSERT(metadata->data.stream_info.total_samples < (FLAC__U64L(1) << FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN));
+                       if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
+                               return false;
+                       if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
+                               return false;
+                       break;
+               case FLAC__METADATA_TYPE_PADDING:
+                       if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
+                               return false;
+                       break;
+               case FLAC__METADATA_TYPE_APPLICATION:
+                       if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
+                               return false;
+                       if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
+                               return false;
+                       break;
+               case FLAC__METADATA_TYPE_SEEKTABLE:
+                       for(i = 0; i < metadata->data.seek_table.num_points; i++) {
+                               if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
+                                       return false;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
+                       if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
+                               return false;
+                       if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
+                               return false;
+                       if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
+                               return false;
+                       for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
+                               if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
+                                       return false;
+                               if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
+                                       return false;
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_CUESHEET:
+                       FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
+                       if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
+                               return false;
+                       if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
+                               return false;
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
+                               return false;
+                       if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
+                               return false;
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
+                               return false;
+                       for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
+                               const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
+
+                               if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
+                                       return false;
+                               FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
+                               if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
+                                       return false;
+                               for(j = 0; j < track->num_indices; j++) {
+                                       const FLAC__StreamMetadata_CueSheet_Index *indx = track->indices + j;
+
+                                       if(!FLAC__bitwriter_write_raw_uint64(bw, indx->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
+                                               return false;
+                                       if(!FLAC__bitwriter_write_raw_uint32(bw, indx->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
+                                               return false;
+                                       if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
+                                               return false;
+                               }
+                       }
+                       break;
+               case FLAC__METADATA_TYPE_PICTURE:
+                       {
+                               size_t len;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
+                                       return false;
+                               len = strlen(metadata->data.picture.mime_type);
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
+                                       return false;
+                               len = strlen((const char *)metadata->data.picture.description);
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
+                                       return false;
+                               if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
+                                       return false;
+                       }
+                       break;
+               default:
+                       if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
+                               return false;
+                       break;
+       }
+
+       FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
+       return true;
+}
+
+FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
+{
+       unsigned u, blocksize_hint, sample_rate_hint;
+       FLAC__byte crc;
+
+       FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
+               return false;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
+               return false;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
+               return false;
+
+       FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
+       /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
+       FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
+       blocksize_hint = 0;
+       switch(header->blocksize) {
+               case   192: u = 1; break;
+               case   576: u = 2; break;
+               case  1152: u = 3; break;
+               case  2304: u = 4; break;
+               case  4608: u = 5; break;
+               case   256: u = 8; break;
+               case   512: u = 9; break;
+               case  1024: u = 10; break;
+               case  2048: u = 11; break;
+               case  4096: u = 12; break;
+               case  8192: u = 13; break;
+               case 16384: u = 14; break;
+               case 32768: u = 15; break;
+               default:
+                       if(header->blocksize <= 0x100)
+                               blocksize_hint = u = 6;
+                       else
+                               blocksize_hint = u = 7;
+                       break;
+       }
+       if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
+               return false;
+
+       FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
+       sample_rate_hint = 0;
+       switch(header->sample_rate) {
+               case  88200: u = 1; break;
+               case 176400: u = 2; break;
+               case 192000: u = 3; break;
+               case   8000: u = 4; break;
+               case  16000: u = 5; break;
+               case  22050: u = 6; break;
+               case  24000: u = 7; break;
+               case  32000: u = 8; break;
+               case  44100: u = 9; break;
+               case  48000: u = 10; break;
+               case  96000: u = 11; break;
+               default:
+                       if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
+                               sample_rate_hint = u = 12;
+                       else if(header->sample_rate % 10 == 0)
+                               sample_rate_hint = u = 14;
+                       else if(header->sample_rate <= 0xffff)
+                               sample_rate_hint = u = 13;
+                       else
+                               u = 0;
+                       break;
+       }
+       if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
+               return false;
+
+       FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
+       switch(header->channel_assignment) {
+               case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
+                       u = header->channels - 1;
+                       break;
+               case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
+                       FLAC__ASSERT(header->channels == 2);
+                       u = 8;
+                       break;
+               case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
+                       FLAC__ASSERT(header->channels == 2);
+                       u = 9;
+                       break;
+               case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
+                       FLAC__ASSERT(header->channels == 2);
+                       u = 10;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+       if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
+               return false;
+
+       FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
+       switch(header->bits_per_sample) {
+               case 8 : u = 1; break;
+               case 12: u = 2; break;
+               case 16: u = 4; break;
+               case 20: u = 5; break;
+               case 24: u = 6; break;
+               default: u = 0; break;
+       }
+       if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
+               return false;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
+               return false;
+
+       if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
+               if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
+                       return false;
+       }
+       else {
+               if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
+                       return false;
+       }
+
+       if(blocksize_hint)
+               if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
+                       return false;
+
+       switch(sample_rate_hint) {
+               case 12:
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
+                               return false;
+                       break;
+               case 13:
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
+                               return false;
+                       break;
+               case 14:
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
+                               return false;
+                       break;
+       }
+
+       /* write the CRC */
+       if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
+               return false;
+       if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
+               return false;
+
+       return true;
+}
+
+FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
+{
+       FLAC__bool ok;
+
+       ok =
+               FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
+               (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
+               FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
+       ;
+
+       return ok;
+}
+
+FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
+{
+       unsigned i;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
+               return false;
+       if(wasted_bits)
+               if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
+                       return false;
+
+       for(i = 0; i < subframe->order; i++)
+               if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
+                       return false;
+
+       if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
+               return false;
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!add_residual_partitioned_rice_(
+                               bw,
+                               subframe->residual,
+                               residual_samples,
+                               subframe->order,
+                               subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
+                               subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
+                               subframe->entropy_coding_method.data.partitioned_rice.order,
+                               /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
+                       ))
+                               return false;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
+{
+       unsigned i;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
+               return false;
+       if(wasted_bits)
+               if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
+                       return false;
+
+       for(i = 0; i < subframe->order; i++)
+               if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
+                       return false;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
+               return false;
+       if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
+               return false;
+       for(i = 0; i < subframe->order; i++)
+               if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
+                       return false;
+
+       if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
+               return false;
+       switch(subframe->entropy_coding_method.type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!add_residual_partitioned_rice_(
+                               bw,
+                               subframe->residual,
+                               residual_samples,
+                               subframe->order,
+                               subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
+                               subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
+                               subframe->entropy_coding_method.data.partitioned_rice.order,
+                               /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
+                       ))
+                               return false;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+
+       return true;
+}
+
+FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
+{
+       unsigned i;
+       const FLAC__int32 *signal = subframe->data;
+
+       if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
+               return false;
+       if(wasted_bits)
+               if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
+                       return false;
+
+       for(i = 0; i < samples; i++)
+               if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
+                       return false;
+
+       return true;
+}
+
+FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
+{
+       if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
+               return false;
+       switch(method->type) {
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
+               case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
+                               return false;
+                       break;
+               default:
+                       FLAC__ASSERT(0);
+       }
+       return true;
+}
+
+FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
+{
+       const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
+       const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
+
+       if(partition_order == 0) {
+               unsigned i;
+
+               if(raw_bits[0] == 0) {
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
+                               return false;
+                       if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
+                               return false;
+               }
+               else {
+                       FLAC__ASSERT(rice_parameters[0] == 0);
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
+                               return false;
+                       if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
+                               return false;
+                       for(i = 0; i < residual_samples; i++) {
+                               if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
+                                       return false;
+                       }
+               }
+               return true;
+       }
+       else {
+               unsigned i, j, k = 0, k_last = 0;
+               unsigned partition_samples;
+               const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
+               for(i = 0; i < (1u<<partition_order); i++) {
+                       partition_samples = default_partition_samples;
+                       if(i == 0)
+                               partition_samples -= predictor_order;
+                       k += partition_samples;
+                       if(raw_bits[i] == 0) {
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
+                                       return false;
+                               if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
+                                       return false;
+                       }
+                       else {
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
+                                       return false;
+                               if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
+                                       return false;
+                               for(j = k_last; j < k; j++) {
+                                       if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
+                                               return false;
+                               }
+                       }
+                       k_last = k;
+               }
+               return true;
+       }
+}
diff --git a/FLAC/src/stream_encoder_intrin_avx2.c b/FLAC/src/stream_encoder_intrin_avx2.c
new file mode 100644 (file)
index 0000000..a94a02b
--- /dev/null
@@ -0,0 +1,146 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/stream_encoder.h"
+#include "private/bitmath.h"
+#ifdef FLAC__AVX2_SUPPORTED
+
+#include <stdlib.h>    /* for abs() */
+#include <immintrin.h> /* AVX2 */
+#include "FLAC/assert.h"
+
+FLAC__SSE_TARGET("avx2")
+void FLAC__precompute_partition_info_sums_intrin_avx2(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+               unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps)
+{
+       const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
+       unsigned partitions = 1u << max_partition_order;
+
+       FLAC__ASSERT(default_partition_samples > predictor_order);
+
+       /* first do max_partition_order */
+       {
+               const unsigned threshold = 32 - FLAC__bitmath_ilog2(default_partition_samples);
+               unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
+
+               if(bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < threshold) {
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m256i sum256 = _mm256_setzero_si256();
+                               __m128i sum128;
+                               end += default_partition_samples;
+
+                               for( ; (int)residual_sample < (int)end-7; residual_sample+=8) {
+                                       __m256i res256 = _mm256_abs_epi32(_mm256_loadu_si256((const __m256i*)(residual+residual_sample)));
+                                       sum256 = _mm256_add_epi32(sum256, res256);
+                               }
+
+                               sum128 = _mm_add_epi32(_mm256_extracti128_si256(sum256, 1), _mm256_castsi256_si128(sum256));
+
+                               for( ; (int)residual_sample < (int)end-3; residual_sample+=4) {
+                                       __m128i res128 = _mm_abs_epi32(_mm_loadu_si128((const __m128i*)(residual+residual_sample)));
+                                       sum128 = _mm_add_epi32(sum128, res128);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i res128 = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       sum128 = _mm_add_epi32(sum128, res128);
+                               }
+
+                               sum128 = _mm_hadd_epi32(sum128, sum128);
+                               sum128 = _mm_hadd_epi32(sum128, sum128);
+                               abs_residual_partition_sums[partition] = (FLAC__uint32)_mm_cvtsi128_si32(sum128);
+/* workaround for a bug in MSVC2015U2 - see https://connect.microsoft.com/VisualStudio/feedback/details/2659191/incorrect-code-generation-for-x86-64 */
+#if (defined _MSC_VER) && (_MSC_FULL_VER == 190023918) && (defined FLAC__CPU_X86_64)
+                               abs_residual_partition_sums[partition] &= 0xFFFFFFFF; /**/
+#endif
+                       }
+               }
+               else { /* have to pessimistically use 64 bits for accumulator */
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m256i sum256 = _mm256_setzero_si256();
+                               __m128i sum128;
+                               end += default_partition_samples;
+
+                               for( ; (int)residual_sample < (int)end-3; residual_sample+=4) {
+                                       __m128i res128 = _mm_abs_epi32(_mm_loadu_si128((const __m128i*)(residual+residual_sample)));
+                                       __m256i res256 = _mm256_cvtepu32_epi64(res128);
+                                       sum256 = _mm256_add_epi64(sum256, res256);
+                               }
+
+                               sum128 = _mm_add_epi64(_mm256_extracti128_si256(sum256, 1), _mm256_castsi256_si128(sum256));
+
+                               for( ; (int)residual_sample < (int)end-1; residual_sample+=2) {
+                                       __m128i res128 = _mm_abs_epi32(_mm_loadl_epi64((const __m128i*)(residual+residual_sample)));
+                                       res128 = _mm_cvtepu32_epi64(res128);
+                                       sum128 = _mm_add_epi64(sum128, res128);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i res128 = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       sum128 = _mm_add_epi64(sum128, res128);
+                               }
+
+                               sum128 = _mm_add_epi64(sum128, _mm_srli_si128(sum128, 8));
+                               _mm_storel_epi64((__m128i*)(abs_residual_partition_sums+partition), sum128);
+                       }
+               }
+       }
+
+       /* now merge partitions for lower orders */
+       {
+               unsigned from_partition = 0, to_partition = partitions;
+               int partition_order;
+               for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
+                       unsigned i;
+                       partitions >>= 1;
+                       for(i = 0; i < partitions; i++) {
+                               abs_residual_partition_sums[to_partition++] =
+                                       abs_residual_partition_sums[from_partition  ] +
+                                       abs_residual_partition_sums[from_partition+1];
+                               from_partition += 2;
+                       }
+               }
+       }
+       _mm256_zeroupper();
+}
+
+#endif /* FLAC__AVX2_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
diff --git a/FLAC/src/stream_encoder_intrin_sse2.c b/FLAC/src/stream_encoder_intrin_sse2.c
new file mode 100644 (file)
index 0000000..0f1d7aa
--- /dev/null
@@ -0,0 +1,159 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/stream_encoder.h"
+#include "private/bitmath.h"
+#ifdef FLAC__SSE2_SUPPORTED
+
+#include <stdlib.h>    /* for abs() */
+#include <emmintrin.h> /* SSE2 */
+#include "FLAC/assert.h"
+#include "share/compat.h"
+
+FLAC__SSE_TARGET("sse2")
+static inline __m128i local_abs_epi32(__m128i val)
+{
+       __m128i mask = _mm_srai_epi32(val, 31);
+       val = _mm_xor_si128(val, mask);
+       val = _mm_sub_epi32(val, mask);
+       return val;
+}
+
+
+FLAC__SSE_TARGET("sse2")
+void FLAC__precompute_partition_info_sums_intrin_sse2(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+               unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps)
+{
+       const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
+       unsigned partitions = 1u << max_partition_order;
+
+       FLAC__ASSERT(default_partition_samples > predictor_order);
+
+       /* first do max_partition_order */
+       {
+               const unsigned threshold = 32 - FLAC__bitmath_ilog2(default_partition_samples);
+               unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
+
+               if(bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < threshold) {
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m128i mm_sum = _mm_setzero_si128();
+                               unsigned e1, e3;
+                               end += default_partition_samples;
+
+                               e1 = (residual_sample + 3) & ~3; e3 = end & ~3;
+                               if(e1 > end)
+                                       e1 = end; /* try flac -l 1 -b 16 and you'll be here */
+
+                               /* assumption: residual[] is properly aligned so (residual + e1) is properly aligned too and _mm_loadu_si128() is fast */
+                               for( ; residual_sample < e1; residual_sample++) {
+                                       __m128i mm_res = local_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < e3; residual_sample+=4) {
+                                       __m128i mm_res = local_abs_epi32(_mm_loadu_si128((const __m128i*)(residual+residual_sample)));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i mm_res = local_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               mm_sum = _mm_add_epi32(mm_sum, _mm_srli_si128(mm_sum, 8));
+                               mm_sum = _mm_add_epi32(mm_sum, _mm_srli_si128(mm_sum, 4));
+                               abs_residual_partition_sums[partition] = (FLAC__uint32)_mm_cvtsi128_si32(mm_sum);
+/* workaround for a bug in MSVC2015U2 - see https://connect.microsoft.com/VisualStudio/feedback/details/2659191/incorrect-code-generation-for-x86-64 */
+#if (defined _MSC_VER) && (_MSC_FULL_VER == 190023918) && (defined FLAC__CPU_X86_64)
+                               abs_residual_partition_sums[partition] &= 0xFFFFFFFF;
+#endif
+                       }
+               }
+               else { /* have to pessimistically use 64 bits for accumulator */
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m128i mm_sum = _mm_setzero_si128();
+                               unsigned e1, e3;
+                               end += default_partition_samples;
+
+                               e1 = (residual_sample + 1) & ~1; e3 = end & ~1;
+                               FLAC__ASSERT(e1 <= end);
+
+                               for( ; residual_sample < e1; residual_sample++) {
+                                       __m128i mm_res = local_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample])); /*  0   0   0  |r0|  ==   00   |r0_64| */
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < e3; residual_sample+=2) {
+                                       __m128i mm_res = local_abs_epi32(_mm_loadl_epi64((const __m128i*)(residual+residual_sample))); /*  0   0  |r1|   |r0| */
+                                       mm_res = _mm_shuffle_epi32(mm_res, _MM_SHUFFLE(3,1,2,0)); /* 0  |r1|  0  |r0|  ==  |r1_64|  |r0_64|  */
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i mm_res = local_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               mm_sum = _mm_add_epi64(mm_sum, _mm_srli_si128(mm_sum, 8));
+                               _mm_storel_epi64((__m128i*)(abs_residual_partition_sums+partition), mm_sum);
+                       }
+               }
+       }
+
+       /* now merge partitions for lower orders */
+       {
+               unsigned from_partition = 0, to_partition = partitions;
+               int partition_order;
+               for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
+                       unsigned i;
+                       partitions >>= 1;
+                       for(i = 0; i < partitions; i++) {
+                               abs_residual_partition_sums[to_partition++] =
+                                       abs_residual_partition_sums[from_partition  ] +
+                                       abs_residual_partition_sums[from_partition+1];
+                               from_partition += 2;
+                       }
+               }
+       }
+}
+
+#endif /* FLAC__SSE2_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
diff --git a/FLAC/src/stream_encoder_intrin_ssse3.c b/FLAC/src/stream_encoder_intrin_ssse3.c
new file mode 100644 (file)
index 0000000..21a08fc
--- /dev/null
@@ -0,0 +1,148 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2000-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "private/cpu.h"
+
+#ifndef FLAC__NO_ASM
+#if (defined FLAC__CPU_IA32 || defined FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN
+#include "private/stream_encoder.h"
+#include "private/bitmath.h"
+#ifdef FLAC__SSSE3_SUPPORTED
+
+#include <stdlib.h>    /* for abs() */
+#include <tmmintrin.h> /* SSSE3 */
+#include "FLAC/assert.h"
+
+FLAC__SSE_TARGET("ssse3")
+void FLAC__precompute_partition_info_sums_intrin_ssse3(const FLAC__int32 residual[], FLAC__uint64 abs_residual_partition_sums[],
+               unsigned residual_samples, unsigned predictor_order, unsigned min_partition_order, unsigned max_partition_order, unsigned bps)
+{
+       const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
+       unsigned partitions = 1u << max_partition_order;
+
+       FLAC__ASSERT(default_partition_samples > predictor_order);
+
+       /* first do max_partition_order */
+       {
+               const unsigned threshold = 32 - FLAC__bitmath_ilog2(default_partition_samples);
+               unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
+
+               if(bps + FLAC__MAX_EXTRA_RESIDUAL_BPS < threshold) {
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m128i mm_sum = _mm_setzero_si128();
+                               unsigned e1, e3;
+                               end += default_partition_samples;
+
+                               e1 = (residual_sample + 3) & ~3; e3 = end & ~3;
+                               if(e1 > end)
+                                       e1 = end; /* try flac -l 1 -b 16 and you'll be here */
+
+                               /* assumption: residual[] is properly aligned so (residual + e1) is properly aligned too and _mm_loadu_si128() is fast */
+                               for( ; residual_sample < e1; residual_sample++) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < e3; residual_sample+=4) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_loadu_si128((const __m128i*)(residual+residual_sample)));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi32(mm_sum, mm_res);
+                               }
+
+                               mm_sum = _mm_hadd_epi32(mm_sum, mm_sum);
+                               mm_sum = _mm_hadd_epi32(mm_sum, mm_sum);
+                               abs_residual_partition_sums[partition] = (FLAC__uint32)_mm_cvtsi128_si32(mm_sum);
+/* workaround for a bug in MSVC2015U2 - see https://connect.microsoft.com/VisualStudio/feedback/details/2659191/incorrect-code-generation-for-x86-64 */
+#if (defined _MSC_VER) && (_MSC_FULL_VER == 190023918) && (defined FLAC__CPU_X86_64)
+                               abs_residual_partition_sums[partition] &= 0xFFFFFFFF;
+#endif
+                       }
+               }
+               else { /* have to pessimistically use 64 bits for accumulator */
+                       for(partition = residual_sample = 0; partition < partitions; partition++) {
+                               __m128i mm_sum = _mm_setzero_si128();
+                               unsigned e1, e3;
+                               end += default_partition_samples;
+
+                               e1 = (residual_sample + 1) & ~1; e3 = end & ~1;
+                               FLAC__ASSERT(e1 <= end);
+
+                               for( ; residual_sample < e1; residual_sample++) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample])); /*  0   0   0  |r0|  ==   00   |r0_64| */
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < e3; residual_sample+=2) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_loadl_epi64((const __m128i*)(residual+residual_sample))); /*  0   0  |r1|   |r0| */
+                                       mm_res = _mm_shuffle_epi32(mm_res, _MM_SHUFFLE(3,1,2,0)); /* 0  |r1|  0  |r0|  ==  |r1_64|  |r0_64|  */
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               for( ; residual_sample < end; residual_sample++) {
+                                       __m128i mm_res = _mm_abs_epi32(_mm_cvtsi32_si128(residual[residual_sample]));
+                                       mm_sum = _mm_add_epi64(mm_sum, mm_res);
+                               }
+
+                               mm_sum = _mm_add_epi64(mm_sum, _mm_srli_si128(mm_sum, 8));
+                               _mm_storel_epi64((__m128i*)(abs_residual_partition_sums+partition), mm_sum);
+                       }
+               }
+       }
+
+       /* now merge partitions for lower orders */
+       {
+               unsigned from_partition = 0, to_partition = partitions;
+               int partition_order;
+               for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
+                       unsigned i;
+                       partitions >>= 1;
+                       for(i = 0; i < partitions; i++) {
+                               abs_residual_partition_sums[to_partition++] =
+                                       abs_residual_partition_sums[from_partition  ] +
+                                       abs_residual_partition_sums[from_partition+1];
+                               from_partition += 2;
+                       }
+               }
+       }
+}
+
+#endif /* FLAC__SSSE3_SUPPORTED */
+#endif /* (FLAC__CPU_IA32 || FLAC__CPU_X86_64) && FLAC__HAS_X86INTRIN */
+#endif /* FLAC__NO_ASM */
diff --git a/FLAC/src/window.c b/FLAC/src/window.c
new file mode 100644 (file)
index 0000000..e977fd8
--- /dev/null
@@ -0,0 +1,282 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2006-2009  Josh Coalson
+ * Copyright (C) 2011-2016  Xiph.Org Foundation
+ *
+ * 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 "share/compat.h"
+#include "FLAC/assert.h"
+#include "FLAC/format.h"
+#include "private/window.h"
+
+#ifndef FLAC__INTEGER_ONLY_LIBRARY
+
+
+void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       if (L & 1) {
+               for (n = 0; n <= N/2; n++)
+                       window[n] = 2.0f * n / (float)N;
+               for (; n <= N; n++)
+                       window[n] = 2.0f - 2.0f * n / (float)N;
+       }
+       else {
+               for (n = 0; n <= L/2-1; n++)
+                       window[n] = 2.0f * n / (float)N;
+               for (; n <= N; n++)
+                       window[n] = 2.0f - 2.0f * n / (float)N;
+       }
+}
+
+void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N-0.5f) - 0.38f * cos(2.0f * M_PI * ((float)n/(float)N)));
+}
+
+void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
+}
+
+/* 4-term -92dB side-lobe */
+void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n <= N; n++)
+               window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
+}
+
+void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       const double N2 = (double)N / 2.;
+       FLAC__int32 n;
+
+       for (n = 0; n <= N; n++) {
+               double k = ((double)n - N2) / N2;
+               k = 1.0f - k * k;
+               window[n] = (FLAC__real)(k * k);
+       }
+}
+
+void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
+}
+
+void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
+{
+       const FLAC__int32 N = L - 1;
+       const double N2 = (double)N / 2.;
+       FLAC__int32 n;
+
+       for (n = 0; n <= N; n++) {
+               const double k = ((double)n - N2) / (stddev * N2);
+               window[n] = (FLAC__real)exp(-0.5f * k * k);
+       }
+}
+
+void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
+}
+
+void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
+}
+
+void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
+}
+
+void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
+}
+
+void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
+{
+       FLAC__int32 n;
+
+       for (n = 0; n < L; n++)
+               window[n] = 1.0f;
+}
+
+void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
+{
+       FLAC__int32 n;
+
+       if (L & 1) {
+               for (n = 1; n <= (L+1)/2; n++)
+                       window[n-1] = 2.0f * n / ((float)L + 1.0f);
+               for (; n <= L; n++)
+                       window[n-1] = (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
+       }
+       else {
+               for (n = 1; n <= L/2; n++)
+                       window[n-1] = 2.0f * n / ((float)L + 1.0f);
+               for (; n <= L; n++)
+                       window[n-1] = (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
+       }
+}
+
+void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
+{
+       if (p <= 0.0)
+               FLAC__window_rectangle(window, L);
+       else if (p >= 1.0)
+               FLAC__window_hann(window, L);
+       else {
+               const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
+               FLAC__int32 n;
+               /* start with rectangle... */
+               FLAC__window_rectangle(window, L);
+               /* ...replace ends with hann */
+               if (Np > 0) {
+                       for (n = 0; n <= Np; n++) {
+                               window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
+                               window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
+                       }
+               }
+       }
+}
+
+void FLAC__window_partial_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p, const FLAC__real start, const FLAC__real end)
+{
+       const FLAC__int32 start_n = (FLAC__int32)(start * L);
+       const FLAC__int32 end_n = (FLAC__int32)(end * L);
+       const FLAC__int32 N = end_n - start_n;
+       FLAC__int32 Np, n, i;
+
+       if (p <= 0.0f)
+               FLAC__window_partial_tukey(window, L, 0.05f, start, end);
+       else if (p >= 1.0f)
+               FLAC__window_partial_tukey(window, L, 0.95f, start, end);
+       else {
+
+               Np = (FLAC__int32)(p / 2.0f * N);
+
+               for (n = 0; n < start_n && n < L; n++)
+                       window[n] = 0.0f;
+               for (i = 1; n < (start_n+Np) && n < L; n++, i++)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Np));
+               for (; n < (end_n-Np) && n < L; n++)
+                       window[n] = 1.0f;
+               for (i = Np; n < end_n && n < L; n++, i--)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Np));
+               for (; n < L; n++)
+                       window[n] = 0.0f;
+       }
+}
+
+void FLAC__window_punchout_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p, const FLAC__real start, const FLAC__real end)
+{
+       const FLAC__int32 start_n = (FLAC__int32)(start * L);
+       const FLAC__int32 end_n = (FLAC__int32)(end * L);
+       FLAC__int32 Ns, Ne, n, i;
+
+       if (p <= 0.0f)
+               FLAC__window_punchout_tukey(window, L, 0.05f, start, end);
+       else if (p >= 1.0f)
+               FLAC__window_punchout_tukey(window, L, 0.95f, start, end);
+       else {
+
+               Ns = (FLAC__int32)(p / 2.0f * start_n);
+               Ne = (FLAC__int32)(p / 2.0f * (L - end_n));
+
+               for (n = 0, i = 1; n < Ns && n < L; n++, i++)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Ns));
+               for (; n < start_n-Ns && n < L; n++)
+                       window[n] = 1.0f;
+               for (i = Ns; n < start_n && n < L; n++, i--)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Ns));
+               for (; n < end_n && n < L; n++)
+                       window[n] = 0.0f;
+               for (i = 1; n < end_n+Ne && n < L; n++, i++)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Ne));
+               for (; n < L - (Ne) && n < L; n++)
+                       window[n] = 1.0f;
+               for (i = Ne; n < L; n++, i--)
+                       window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * i / Ne));
+       }
+}
+
+void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
+{
+       const FLAC__int32 N = L - 1;
+       const double N2 = (double)N / 2.;
+       FLAC__int32 n;
+
+       for (n = 0; n <= N; n++) {
+               const double k = ((double)n - N2) / N2;
+               window[n] = (FLAC__real)(1.0f - k * k);
+       }
+}
+
+#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
diff --git a/FLAC/src/windows_unicode_filenames.c b/FLAC/src/windows_unicode_filenames.c
new file mode 100644 (file)
index 0000000..b7b6b6b
--- /dev/null
@@ -0,0 +1,202 @@
+/* libFLAC - Free Lossless Audio Codec library
+ * Copyright (C) 2013-2016  Xiph.Org Foundation
+ *
+ * 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 <io.h>
+#include <stdlib.h>
+#include "share/windows_unicode_filenames.h"
+
+/* convert UTF-8 back to WCHAR. Caller is responsible for freeing memory */
+static wchar_t *wchar_from_utf8(const char *str)
+{
+       wchar_t *widestr;
+       int len;
+
+       if (!str)
+               return NULL;
+       if ((len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) == 0)
+               return NULL;
+       if ((widestr = (wchar_t *)malloc(len*sizeof(wchar_t))) == NULL)
+               return NULL;
+       if (MultiByteToWideChar(CP_UTF8, 0, str, -1, widestr, len) == 0) {
+               free(widestr);
+               widestr = NULL;
+       }
+
+       return widestr;
+}
+
+
+static FLAC__bool utf8_filenames = false;
+
+
+void flac_internal_set_utf8_filenames(FLAC__bool flag)
+{
+       utf8_filenames = flag ? true : false;
+}
+
+FLAC__bool flac_internal_get_utf8_filenames(void)
+{
+       return utf8_filenames;
+}
+
+/* file functions */
+
+FILE* flac_internal_fopen_utf8(const char *filename, const char *mode)
+{
+       if (!utf8_filenames) {
+               return fopen(filename, mode);
+       } else {
+               wchar_t *wname = NULL;
+               wchar_t *wmode = NULL;
+               FILE *f = NULL;
+
+               do {
+                       if (!(wname = wchar_from_utf8(filename))) break;
+                       if (!(wmode = wchar_from_utf8(mode))) break;
+                       f = _wfopen(wname, wmode);
+               } while(0);
+
+               free(wname);
+               free(wmode);
+
+               return f;
+       }
+}
+
+int flac_internal_stat64_utf8(const char *path, struct __stat64 *buffer)
+{
+       if (!utf8_filenames) {
+               return _stat64(path, buffer);
+       } else {
+               wchar_t *wpath;
+               int ret;
+
+               if (!(wpath = wchar_from_utf8(path))) return -1;
+               ret = _wstat64(wpath, buffer);
+               free(wpath);
+
+               return ret;
+       }
+}
+
+int flac_internal_chmod_utf8(const char *filename, int pmode)
+{
+       if (!utf8_filenames) {
+               return _chmod(filename, pmode);
+       } else {
+               wchar_t *wname;
+               int ret;
+
+               if (!(wname = wchar_from_utf8(filename))) return -1;
+               ret = _wchmod(wname, pmode);
+               free(wname);
+
+               return ret;
+       }
+}
+
+int flac_internal_utime_utf8(const char *filename, struct utimbuf *times)
+{
+       if (!utf8_filenames) {
+               return utime(filename, times);
+       } else {
+               wchar_t *wname;
+               struct __utimbuf64 ut;
+               int ret;
+
+               if (!(wname = wchar_from_utf8(filename))) return -1;
+               ut.actime = times->actime;
+               ut.modtime = times->modtime;
+               ret = _wutime64(wname, &ut);
+               free(wname);
+
+               return ret;
+       }
+}
+
+int flac_internal_unlink_utf8(const char *filename)
+{
+       if (!utf8_filenames) {
+               return _unlink(filename);
+       } else {
+               wchar_t *wname;
+               int ret;
+
+               if (!(wname = wchar_from_utf8(filename))) return -1;
+               ret = _wunlink(wname);
+               free(wname);
+
+               return ret;
+       }
+}
+
+int flac_internal_rename_utf8(const char *oldname, const char *newname)
+{
+       if (!utf8_filenames) {
+               return rename(oldname, newname);
+       } else {
+               wchar_t *wold = NULL;
+               wchar_t *wnew = NULL;
+               int ret = -1;
+
+               do {
+                       if (!(wold = wchar_from_utf8(oldname))) break;
+                       if (!(wnew = wchar_from_utf8(newname))) break;
+                       ret = _wrename(wold, wnew);
+               } while(0);
+
+               free(wold);
+               free(wnew);
+
+               return ret;
+       }
+}
+
+HANDLE WINAPI flac_internal_CreateFile_utf8(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
+{
+       if (!utf8_filenames) {
+               return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
+       } else {
+               wchar_t *wname;
+               HANDLE handle = INVALID_HANDLE_VALUE;
+
+               if ((wname = wchar_from_utf8(lpFileName)) != NULL) {
+                       handle = CreateFileW(wname, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
+                       free(wname);
+               }
+
+               return handle;
+       }
+}
diff --git a/NEWS b/NEWS
index a665838..1555033 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,17 @@
+08/29, 2018
+    * Version 2.15.0 released.
+    * Add support for segment play option (-G, --segment) with a great
+      contribution by Yotam Medini <yotam.medini@gmail.com>.
+    * Add metronome indicator in dumb interface trace mode.
+    * Let libao backend set ao options via TIMIDITY_AO_OPTIONS
+      environment variable.
+    * Fix for CVE-2009-0179, CVE-2009-3996, CVE-2010-2546 and
+      CVE-2010-2971.
+    * Fix for CVE-2017-11546.
+    * Support for Tcl/Tk 8.6.
+    * Improve Windows MIDI driver.
+    * ...and many other bug fixes.
+
 06/29, 2012
     * Version 2.14.0 released.
     * Add --reverb option for Freeverb parameter.
@@ -7,7 +21,7 @@
       specified file is missing.
     * Support for GM2 Master Fine/Coarse Tuning, GS Master Tune and XG
       Master Tuning (4C not 27) SysEx.
-    * Allow Device Numbers other than 0x10 for XG SYSTEM ON SYSEX 
+    * Allow Device Numbers other than 0x10 for XG SYSTEM ON SYSEX
       events.
     * Fix multiple vulnerabilities found in GNU gzip also apply to lha,
       namely: CVE-2006-4335, CVE-2006-4337 and CVE-2006-4338.
diff --git a/WriteVersion.cmake b/WriteVersion.cmake
new file mode 100644 (file)
index 0000000..c796aa0
--- /dev/null
@@ -0,0 +1,18 @@
+
+execute_process(
+    COMMAND "${GIT_EXECUTABLE}" describe
+    OUTPUT_VARIABLE gitDescribeResult
+    OUTPUT_STRIP_TRAILING_WHITESPACE
+)
+
+string(REPLACE "tim" "" tim41VersionStr "${gitDescribeResult}")
+
+if("${gitDescribeResult}" MATCHES "[0-9.]+\\.[0-9.]+\\.[0-9.]+-[0-9]+")
+    string(REGEX MATCH "[0-9.]+\\.[0-9.]+\\.[0-9.]+-[0-9]+" tim41Version4 "${gitDescribeResult}")
+else()
+    string(REGEX MATCH "[0-9.]+\\.[0-9.]+\\.[0-9.]+" tim41Version4 "${gitDescribeResult}")
+    string(APPEND tim41Version4 ".0")
+endif()
+
+string(REGEX REPLACE "[\\.\\-]" "," tim41Version4Comma "${tim41Version4}")
+configure_file(${INFILE} ${OUTFILE})
diff --git a/calcnewton/calcnewton.vcproj b/calcnewton/calcnewton.vcproj
deleted file mode 100644 (file)
index 8b4ea74..0000000
+++ /dev/null
@@ -1,214 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="calcnewton"
-       ProjectGUID="{4F65093E-E5C5-46C1-819D-0987086BF312}"
-       Keyword="Win32Proj"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="Debug"
-                       IntermediateDirectory="Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               WarningLevel="3"
-                               Detect64BitPortabilityProblems="true"
-                               DebugInformationFormat="4"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               OutputFile="$(OutDir)/calcnewton.exe"
-                               LinkIncremental="2"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile="$(OutDir)/calcnewton.pdb"
-                               SubSystem="1"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                               CommandLine="$(TargetPath) ..\timidity\newton_table.c"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="Release"
-                       IntermediateDirectory="Release"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="2"
-                               InlineFunctionExpansion="1"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               WarningLevel="3"
-                               Detect64BitPortabilityProblems="true"
-                               DebugInformationFormat="3"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               OutputFile="$(OutDir)/calcnewton.exe"
-                               LinkIncremental="1"
-                               GenerateDebugInformation="true"
-                               SubSystem="1"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                               CommandLine="$(TargetPath) ..\timidity\newton_table.c"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="\83\\81[\83\83t\83@\83C\83\8b"
-                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"
-                       >
-                       <File
-                               RelativePath="..\timidity\calcnewt.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="\83w\83b\83_\81\83t\83@\83C\83\8b"
-                       Filter="h;hpp;hxx;hm;inl;inc"
-                       >
-               </Filter>
-               <Filter
-                       Name="\83\8a\83\\81[\83\83t\83@\83C\83\8b"
-                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/calcnewton/calcnewton.vcxproj b/calcnewton/calcnewton.vcxproj
deleted file mode 100644 (file)
index 3376d5e..0000000
+++ /dev/null
@@ -1,216 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{4F65093E-E5C5-46C1-819D-0987086BF312}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-    </ClCompile>
-    <Link>
-      <OutputFile>$(OutDir)calcnewton.exe</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>$(OutDir)calcnewton.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-    <PostBuildEvent>
-      <Command>$(TargetPath) ..\timidity\newton_table.c</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-    </ClCompile>
-    <Link>
-      <OutputFile>$(OutDir)calcnewton.exe</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>$(OutDir)calcnewton.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-    <PostBuildEvent>
-      <Command>$(TargetPath) ..\timidity\newton_table.c</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>MaxSpeed</Optimization>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-    </ClCompile>
-    <Link>
-      <OutputFile>$(OutDir)calcnewton.exe</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <SubSystem>Console</SubSystem>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-    <PostBuildEvent>
-      <Command>$(TargetPath) ..\timidity\newton_table.c</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <Optimization>MaxSpeed</Optimization>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-    </ClCompile>
-    <Link>
-      <OutputFile>$(OutDir)calcnewton.exe</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <SubSystem>Console</SubSystem>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-    <PostBuildEvent>
-      <Command>$(TargetPath) ..\timidity\newton_table.c</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\calcnewt.c" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/calcnewton/calcnewton.vcxproj.filters b/calcnewton/calcnewton.vcxproj.filters
deleted file mode 100644 (file)
index 7684219..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{add7af49-ec9d-4826-a507-2c95a50e2e9c}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{553110f2-05ef-4365-ba1c-d732de0430c8}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>
-    </Filter>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{41cc0fa2-20ca-4b54-abdf-c6ecea4ae669}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\calcnewt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/calcnewton/calcnewton.vcxproj.user b/calcnewton/calcnewton.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
index b194a39..dd1949c 100644 (file)
@@ -7,6 +7,8 @@ add_executable(
     ../interface/dumb_c.c
     ../timidity/common.c
     ../timidity/controls.c
+    ../timidity/decode.c
+    ../timidity/dls.cpp
     ../timidity/envelope.c
     ../timidity/filter.c
     ../timidity/freq.c
@@ -19,13 +21,20 @@ add_executable(
     ../timidity/sbkconv.c
     ../timidity/sffile.c
     ../timidity/sfitem.c
+    ../timidity/sfz.cpp
     ../timidity/smplfile.c
     ../timidity/sndfont.c
     ../timidity/tables.c
     ../timidity/version.c
+    ../timidity/w32_libFLAC_dll.c
+    ../timidity/w32_libmpg123_dll.c
+    ../timidity/w32g_vorbis_dll.c
+    ../timidity/w32g_vorbisfile_dll.c
 
     ../timidity/common.h
     ../timidity/controls.h
+    ../timidity/decode.h
+    ../timidity/dls.h
     ../timidity/envelope.h
     ../timidity/filter.h
     ../timidity/freq.h
@@ -41,6 +50,7 @@ add_executable(
     ../timidity/sffile.h
     ../timidity/sfitem.h
     ../timidity/sflayer.h
+    ../timidity/sfz.h
     ../timidity/tables.h
     ../timidity/timidity.h
     ../timidity/wrd.h
diff --git a/cfgforsf/cfgforsf.dsp b/cfgforsf/cfgforsf.dsp
deleted file mode 100644 (file)
index 169a34e..0000000
+++ /dev/null
@@ -1,258 +0,0 @@
-# Microsoft Developer Studio Project File - Name="cfgforsf" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Console Application" 0x0103
-
-CFG=cfgforsf - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "cfgforsf.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "cfgforsf.mak" CFG="cfgforsf - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "cfgforsf - Win32 Release" ("Win32 (x86) Console Application" \97p)
-!MESSAGE "cfgforsf - Win32 Debug" ("Win32 (x86) Console Application" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "cfgforsf - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I "..\..\include" /D "NDEBUG" /D "_MT" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D "HAVE_CONFIG_H" /D "CFG_FOR_SF" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
-# ADD LINK32 wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
-
-!ELSEIF  "$(CFG)" == "cfgforsf - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I "..\..\include" /D "_DEBUG" /D "_MT" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "_WINDOWS" /D "HAVE_CONFIG_H" /D "CFG_FOR_SF" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /nodefaultlib:"LIBCD LIBCMT" /pdbtype:sept
-
-!ENDIF 
-
-# Begin Target
-
-# Name "cfgforsf - Win32 Release"
-# Name "cfgforsf - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\timidity\common.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\controls.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\dumb_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\instrum.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\quantity.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\reverb.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sbkconv.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sffile.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sfitem.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\smplfile.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sndfont.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\tables.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\version.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\libarc\arc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\common.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\config.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\config_w32vc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\controls.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\instrum.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface_w32vc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mblock.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\nkflib.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\output.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\playmidi.h"
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\quantity.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\readmidi.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\resample.h"
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\reverb.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sffile.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sfitem.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sflayer.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\strtab.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\support.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\tables.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\timidity.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\wrd.h"
-# End Source File
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# End Group
-# Begin Source File
-
-SOURCE=..\Release\utils.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\libarc.lib
-# End Source File
-# End Target
-# End Project
diff --git a/cfgforsf/cfgforsf.vcproj b/cfgforsf/cfgforsf.vcproj
deleted file mode 100644 (file)
index c38a3c9..0000000
+++ /dev/null
@@ -1,384 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="cfgforsf"
-       ProjectGUID="{936F8415-4094-44C5-8640-8D710ECCABB6}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory=".\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               TypeLibraryName=".\Debug/cfgforsf.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include"
-                               PreprocessorDefinitions="_DEBUG,_MT,WIN32,_CONSOLE,_WINDOWS,HAVE_CONFIG_H,CFG_FOR_SF"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/cfgforsf.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib odbc32.lib odbccp32.lib"
-                               OutputFile=".\Debug/cfgforsf.exe"
-                               LinkIncremental="2"
-                               SuppressStartupBanner="true"
-                               IgnoreDefaultLibraryNames="LIBCD LIBCMT"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile=".\Debug/cfgforsf.pdb"
-                               SubSystem="1"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory=".\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               TypeLibraryName=".\Release/cfgforsf.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               InlineFunctionExpansion="1"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include"
-                               PreprocessorDefinitions="NDEBUG,_MT,WIN32,_CONSOLE,_WINDOWS,HAVE_CONFIG_H,CFG_FOR_SF"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/cfgforsf.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib odbc32.lib odbccp32.lib"
-                               OutputFile=".\Release/cfgforsf.exe"
-                               LinkIncremental="1"
-                               SuppressStartupBanner="true"
-                               ProgramDatabaseFile=".\Release/cfgforsf.pdb"
-                               SubSystem="1"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath="..\timidity\common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\controls.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\dumb_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\instrum.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\quantity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\reverb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sbkconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sffile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sfitem.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\smplfile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfont.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\version.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath="..\libarc\arc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\common.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\config_w32vc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\controls.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\instrum.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface_w32vc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\utils\mblock.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\utils\nkflib.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\output.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\playmidi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\quantity.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\readmidi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\resample.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\reverb.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sffile.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sfitem.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sflayer.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\utils\strtab.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\utils\support.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\tables.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timidity.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\libarc\url.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wrd.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Resource Files"
-                       Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/cfgforsf/cfgforsf.vcxproj b/cfgforsf/cfgforsf.vcxproj
deleted file mode 100644 (file)
index 8250536..0000000
+++ /dev/null
@@ -1,314 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{936F8415-4094-44C5-8640-8D710ECCABB6}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\Debug\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\Debug\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\Release\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\Release\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Midl>
-      <TypeLibraryName>.\Debug/cfgforsf.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>C:\Program Files\Microsoft Visual C++ Toolkit 2003\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;CFG_FOR_SF;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/cfgforsf.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>wsock32.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>.\Debug/cfgforsf.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>LIBCD LIBCMT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/cfgforsf.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <TypeLibraryName>.\Debug/cfgforsf.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>C:\Program Files\Microsoft Visual C++ Toolkit 2003\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;CFG_FOR_SF;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/cfgforsf.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>wsock32.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>.\Debug/cfgforsf.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>LIBCD LIBCMT;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/cfgforsf.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Midl>
-      <TypeLibraryName>.\Release/cfgforsf.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>C:\Program Files\Microsoft Visual C++ Toolkit 2003\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;CFG_FOR_SF;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/cfgforsf.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>wsock32.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>.\Release/cfgforsf.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <ProgramDatabaseFile>.\Release/cfgforsf.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <Midl>
-      <TypeLibraryName>.\Release/cfgforsf.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>C:\Program Files\Microsoft Visual C++ Toolkit 2003\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;CFG_FOR_SF;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/cfgforsf.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>wsock32.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>.\Release/cfgforsf.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <ProgramDatabaseFile>.\Release/cfgforsf.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\common.c" />
-    <ClCompile Include="..\timidity\controls.c" />
-    <ClCompile Include="..\interface\dumb_c.c" />
-    <ClCompile Include="..\timidity\instrum.c" />
-    <ClCompile Include="..\timidity\quantity.c" />
-    <ClCompile Include="..\timidity\reverb.c" />
-    <ClCompile Include="..\timidity\sbkconv.c" />
-    <ClCompile Include="..\timidity\sffile.c" />
-    <ClCompile Include="..\timidity\sfitem.c" />
-    <ClCompile Include="..\timidity\smplfile.c" />
-    <ClCompile Include="..\timidity\sndfont.c" />
-    <ClCompile Include="..\timidity\tables.c" />
-    <ClCompile Include="..\timidity\version.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\libarc\arc.h" />
-    <ClInclude Include="..\timidity\common.h" />
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\config_w32vc.h" />
-    <ClInclude Include="..\timidity\controls.h" />
-    <ClInclude Include="..\timidity\instrum.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\interface_w32vc.h" />
-    <ClInclude Include="..\utils\mblock.h" />
-    <ClInclude Include="..\utils\nkflib.h" />
-    <ClInclude Include="..\timidity\output.h" />
-    <ClInclude Include="..\timidity\playmidi.h" />
-    <ClInclude Include="..\timidity\quantity.h" />
-    <ClInclude Include="..\timidity\readmidi.h" />
-    <ClInclude Include="..\timidity\resample.h" />
-    <ClInclude Include="..\timidity\reverb.h" />
-    <ClInclude Include="..\timidity\sffile.h" />
-    <ClInclude Include="..\timidity\sfitem.h" />
-    <ClInclude Include="..\timidity\sflayer.h" />
-    <ClInclude Include="..\utils\strtab.h" />
-    <ClInclude Include="..\utils\support.h" />
-    <ClInclude Include="..\timidity\tables.h" />
-    <ClInclude Include="..\timidity\timidity.h" />
-    <ClInclude Include="..\libarc\url.h" />
-    <ClInclude Include="..\timidity\wrd.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\utils\utils.vcxproj">
-      <Project>{b05f8aa0-6140-4335-ad39-e276d17002cb}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/cfgforsf/cfgforsf.vcxproj.filters b/cfgforsf/cfgforsf.vcxproj.filters
deleted file mode 100644 (file)
index c4c883a..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{dec36c27-f82f-4c09-bc34-fb7e5eb10623}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{a5c5f0d2-de08-46b3-8538-a4423d4980c9}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{00bd62ea-1793-4545-ab28-4e99cbd41b1d}</UniqueIdentifier>
-      <Extensions>ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\controls.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\dumb_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\instrum.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\quantity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\reverb.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sbkconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sffile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sfitem.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smplfile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfont.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\tables.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\version.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\libarc\arc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\common.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\config_w32vc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\controls.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\instrum.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface_w32vc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\mblock.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\nkflib.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\output.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\playmidi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\quantity.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\readmidi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\resample.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\reverb.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sffile.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sfitem.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sflayer.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\strtab.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\support.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\tables.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\timidity.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\libarc\url.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\wrd.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/cfgforsf/cfgforsf.vcxproj.user b/cfgforsf/cfgforsf.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/config.h b/config.h
deleted file mode 100644 (file)
index e3b3d76..0000000
--- a/config.h
+++ /dev/null
@@ -1,822 +0,0 @@
-/* config.h.in.  Generated automatically from configure.in by autoheader.  */
-
-/* Define if type char is unsigned and you are not using gcc.  */
-// #ifndef __CHAR_UNSIGNED__
-// #undef __CHAR_UNSIGNED__
-// #endif
-
-#pragma inline_recursion(on) // \83C\83\93\83\89\83C\83\93\93W\8aJ\97L\8cø
-#pragma inline_depth(256)
-
-#pragma warning(disable:4996) // \88À\91S\82Å\82Í\82È\82¢\8aÖ\90\94\82Ì\8eg\97p
-#pragma warning(disable:4101) // \88ê\93x\82à\8eg\97p\82µ\82Ä\82¢\82È\82¢\95Ï\90\94
-#pragma warning(disable:4018) // signed unsigned \82Ì\94ä\8ar
-#pragma warning(disable:4013) // int\8c^\82Ì\8aO\95\94\8aÖ\90\94\82Æ\82Ý\82È\82·
-
-//#pragma warning(disable:4133) // \8cÝ\8a·\90«\82ª\82È\82¢\8cÄ\82Ñ\8fo\82µ
-
-#pragma warning(disable:4554) // \83V\83t\83g\89\89\8eZ\8eq\82Ì\97D\90æ\8f\87\88Ê
-#pragma warning(disable:4005) // \8dÄ\92è\8b`
-
-#ifndef _DEBUG
-#pragma warning(disable:4244) // \8c^\95Ï\8a·
-#pragma warning(disable:4068) // \95s\96¾\82È\83v\83\89\83O\83}
-#endif
-
-/* Define to empty if the keyword does not work.  */
-// #undef const
-
-/* Define if you don't have vprintf but do have _doprnt.  */
-#undef HAVE_DOPRNT
-
-/* Define if you have a working `mmap' system call.  */
-#undef HAVE_MMAP
-
-/* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
-#undef HAVE_SYS_WAIT_H
-
-/* Define if you have the vprintf function.  */
-// #undef HAVE_VPRINTF
-#define HAVE_VPRINTF
-
-/* Define as __inline if that's what the C compiler calls it.  */
-// #undef inline
-#define inline __inline
-
-/* Define to `long' if <sys/types.h> doesn't define.  */
-// #undef off_t
-
-/* Define to `int' if <sys/types.h> doesn't define.  */
-// #undef pid_t
-
-/* Define as the return type of signal handlers (int or void).  */
-// #undef RETSIGTYPE
-#define RETSIGTYPE int
-
-/* Define if the setvbuf function takes the buffering type as its second
-   argument and the buffer pointer as the third, as on System V
-   before release 3.  */
-// #undef SETVBUF_REVERSED
-
-/* Define to `unsigned' if <sys/types.h> doesn't define.  */
-// #undef size_t
-
-/* Define if you have the ANSI C header files.  */
-#undef STDC_HEADERS
-
-/* Define if you can safely include both <sys/time.h> and <time.h>.  */
-// #undef TIME_WITH_SYS_TIME
-
-/* Define if your processor stores words with the most significant
-   byte first (like Motorola and SPARC, unlike Intel and VAX).  */
-#undef WORDS_BIGENDIAN
-
-/* Define if the X Window System is missing or not being used.  */
-#undef X_DISPLAY_MISSING
-
-/* Get 64-bit file size support */
-/* #undef _FILE_OFFSET_BITS */
-
-/* Define for ftello and fseeko extension. */
-/* #undef _LARGEFILE_SOURCE */
-
-/* Define if you have the XShmCreatePixmap function.  */
-#undef HAVE_XSHMCREATEPIXMAP
-
-/* Define if you have the XmuRegisterExternalAgent function.  */
-#undef HAVE_XMUREGISTEREXTERNALAGENT
-
-/* Define if you have the getcwd function.  */
-// #undef HAVE_GETCWD
-#define HAVE_GETCWD
-
-/* Define if you have the gethostbyname function.  */
-// #undef HAVE_GETHOSTBYNAME
-#define HAVE_GETHOSTBYNAME
-
-/* Define if you have the getopt function.  */
-#undef HAVE_GETOPT
-
-/* Define if you have the getpagesize function.  */
-#undef HAVE_GETPAGESIZE
-
-/* Define if you have the gettimeofday function.  */
-#undef HAVE_GETTIMEOFDAY
-
-/* Define if you have the isatty function.  */
-// #undef HAVE_ISATTY
-#define HAVE_ISATTY
-
-/* Define if you have the popen function.  */
-// #undef HAVE_POPEN
-#ifdef _MSC_VER
-#define HAVE_POPEN
-#define popen _popen
-#define pclose _pclose
-#endif
-
-/* Define if you have the select function.  */
-// #undef HAVE_SELECT
-#define HAVE_SELECT
-
-/* Define if you have the signal function.  */
-// #undef HAVE_SIGNAL
-#define HAVE_SIGNAL
-
-/* Define if you have the sleep function.  */
-#undef HAVE_SLEEP
-
-/* Define if you have the snprintf function.  */
-// #undef HAVE_SNPRINTF
-#ifdef _MSC_VER
-#define HAVE_SNPRINTF
-#define snprintf _snprintf
-#endif
-
-/* Define if you have the socket function.  */
-// #undef HAVE_SOCKET
-#define HAVE_SOCKET
-
-/* Define if you have the strdup function.  */
-// #undef HAVE_STRDUP
-#define HAVE_STRDUP
-
-/* Define if you have the strerror function.  */
-// #undef HAVE_STRERROR
-#define HAVE_STRERROR
-
-/* Define if you have the strncasecmp function.  */
-// #undef HAVE_STRNCASECMP
-#define HAVE_STRNCASECMP
-
-/* Define if you have the strstr function.  */
-// #undef HAVE_STRSTR
-#define HAVE_STRSTR
-
-/* Define if you have the usleep function.  */
-#undef HAVE_USLEEP
-
-/* Define if you have the vsnprintf function.  */
-// #undef HAVE_VSNPRINTF
-#ifdef _MSC_VER
-#define HAVE_VSNPRINTF
-//#define vsnprintf _vsnprintf
-#endif
-
-/* Define if you have the <X11/Xmu/ExtAgent.h> header file.  */
-#undef HAVE_X11_XMU_EXTAGENT_H
-
-/* Define if you have the <X11/extensions/XShm.h> header file.  */
-#undef HAVE_X11_EXTENSIONS_XSHM_H
-
-/* Define to 1 if you enable Sherry WRD */
-#define ENABLE_SHERRY 1
-
-/* Define to 1 if you need thread support */
-#define ENABLE_THREAD 1
-
-/* Define if you have the <curses.h> header file.  */
-#undef HAVE_CURSES_H
-
-/* Define if you have the <dirent.h> header file.  */
-// #undef HAVE_DIRENT_H
-#ifdef _MSC_VER
-#undef HAVE_DIRENT_H
-#else
-#define HAVE_DIRENT_H
-#endif
-
-/* Define if you have the <dlfcn.h> header file.  */
-#undef HAVE_DLFCN_H
-
-/* Define if you have the <errno.h> header file.  */
-// #undef HAVE_ERRNO_H
-#define HAVE_ERRNO_H
-
-/* Define if you have the <fcntl.h> header file.  */
-// #undef HAVE_FCNTL_H
-#define HAVE_FCNTL_H
-
-/* Define if you have the <getopt.h> header file.  */
-#undef HAVE_GETOPT_H
-
-/* Define if you have the <glob.h> header file.  */
-#undef HAVE_GLOB_H
-
-/* Define if you have the <limits.h> header file.  */
-// #undef HAVE_LIMITS_H
-#define HAVE_LIMITS_H
-
-/* Define if you have the <machine/endian.h> header file.  */
-#undef HAVE_MACHINE_ENDIAN_H
-
-/* Define if you have the <malloc.h> header file.  */
-#define HAVE_MALLOC_H
-
-/* Define if you have the <ncurses.h> header file.  */
-#undef HAVE_NCURSES_H
-
-/* Define if you have the <ncurses/curses.h> header file.  */
-#undef HAVE_NCURSES_CURSES_H
-
-/* Define if you have the <ndir.h> header file.  */
-#undef HAVE_NDIR_H
-
-/* Define if you have the <slang.h> header file.  */
-#undef HAVE_SLANG_H
-
-/* Define if you have the <slang/slang.h> header file.  */
-#undef HAVE_SLANG_SLANG_H
-
-/* Define if you have the <strings.h> header file.  */
-#undef HAVE_STRINGS_H
-
-/* Define if you have the <stropts.h> header file.  */
-#undef HAVE_STROPTS_H
-
-/* Define if you have the <sun/audioio.h> header file.  */
-#undef HAVE_SUN_AUDIOIO_H
-
-/* Define if you have the <sys/audioio.h> header file.  */
-#undef HAVE_SYS_AUDIOIO_H
-
-/* Define if you have the <sys/dir.h> header file.  */
-#undef HAVE_SYS_DIR_H
-
-/* Define if you have the <sys/ioctl.h> header file.  */
-#undef HAVE_SYS_IOCTL_H
-
-/* Define if you have the <sys/ipc.h> header file.  */
-#undef HAVE_SYS_IPC_H
-
-/* Define if you have the <sys/ndir.h> header file.  */
-#undef HAVE_SYS_NDIR_H
-
-/* Define if you have the <sys/param.h> header file.  */
-#undef HAVE_SYS_PARAM_H
-
-/* Define if you have the <sys/shm.h> header file.  */
-#undef HAVE_SYS_SHM_H
-
-/* Define if you have the <sys/soundcard.h> header file.  */
-#undef HAVE_SYS_SOUNDCARD_H
-
-/* Define if you have the <sys/time.h> header file.  */
-#undef HAVE_SYS_TIME_H
-
-/* Define if you have the <sys/types.h> header file.  */
-// #undef HAVE_SYS_TYPES_H
-#define HAVE_SYS_TYPES_H
-
-/* Define if you have the <unistd.h> header file.  */
-#undef HAVE_UNISTD_H
-
-/* Define if you have the ICE library (-lICE).  */
-#undef HAVE_LIBICE
-
-/* Define if you have the X11 library (-lX11).  */
-#undef HAVE_LIBX11
-
-/* Define if you have the asound library (-lasound).  */
-#undef HAVE_LIBASOUND
-
-/* Define if you have the m library (-lm).  */
-#define HAVE_LIBM
-
-/* Define if you have the socket library (-lsocket).  */
-#define HAVE_LIBSOCKET
-
-/* Define if you have the vorbis library (-lvorbis).  */
-#define HAVE_LIBVORBIS
-
-/* Define if you have the gogo library (-lgogo).  */
-#define HAVE_LIBGOGO
-
-/* Define if you have the mpg123 library .  */
-#define HAVE_LIBMPG123
-
-/* Define if you have the <mmsystem.h> header file for Win32. */
-#define HAVE_MMSYSTEM_H
-
-/* Define to 1 if you need spectrogram vewer. */
-#define SUPPORT_SOUNDSPEC 1
-
-/* place to install modules */
-#define PKGLIBDIR "."
-
-/* In VDS Macro AAA=BBB is not available. */
-#define __W32__
-#define TIMID_VERSION  "current"
-#define DEFAULT_PATH   ".\\"
-#define AU_W32 1
-#define AU_WASAPI 1
-#define AU_WDMKS 1
-#define AU_VORBIS 1
-#define AU_VORBIS_DLL 1
-#define VORBIS_DLL_INCLUDE_VORBISENC 1 /* ver 1.3.3 */
-//#define VORBIS_DLL_INCLUDE_VORBISFILE 1 /* ver 1.3.3 */
-#define AU_GOGO 1
-#define AU_GOGO_DLL 1
-#define AU_LAME 1
-#define AU_FLAC 1
-#define AU_FLAC_DLL 1
-#define AU_OGGFLAC 1
-//#define AU_OGGFLAC_DLL
-#define AU_OPUS 1
-#define AU_OPUS_DLL 1
-#define AU_SPEEX 1
-//#define AU_AO 1
-//#define AU_ASIO 1
-#define AU_PORTAUDIO 1
-#define AU_PORTAUDIO_DLL 1
-#define PORTAUDIO_V19 1
-#define PORTAUDIO_V19_6 1  /* ver 19.6 */
-#define VST_LOADER_ENABLE 1
-#define VSTWRAP_EXT 1
-#define AU_NPIPE 1
-#define AU_WRITE_MIDI 1
-#define AU_LIST 1
-#define AU_MODMIDI 1
-#define AU_VOLUME_CALC 1
-#define AU_BENCHMARK 1
-#define FLAC__NO_DLL 1
-#define SMFCONV 1
-//#undef AU_WRITE_MIDI
-//#undef AU_LIST
-//#undef AU_MODMIDI
-//#undef AU_VOLUME_CALC
-
-#define WINSOCK 1 
-#define __W32READDIR__ 1
-#define URL_DIR_CACHE_ENABLE
-#define ANOTHER_MAIN 1
-#define __W32G__       /* for Win32 GUI */
-#define SUPPORT_SOCKET
-
-#undef WINVER
-#define WINVER 0x0410
-
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT WINVER
-#endif
-
-/* Windows 2000 or later */
-#if WINVER >= 0x0500
-#define HAVE_GETADDRINFO 1
-#endif
-
-#ifndef NDEBUG
-#define TIMIDITY_LEAK_CHECK 1
-#endif
-
-#ifndef KBTIM
-#include <winsock2.h>
-#endif
-//#include <Ws2tcpip.h>
-//#include <Wspiapi.h>
-#include <windows.h>
-#include <string.h>
-#include <time.h>
-#include <io.h>
-#include <direct.h>
-
-#ifdef TIMIDITY_LEAK_CHECK
-#define _CRTDBG_MAP_ALLOC 1
-#include <crtdbg.h>
-#ifdef __cplusplus
-#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
-#endif
-#define CRTDEBUGFLAGS (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF)
-#else
-#define CRTDEBUGFLAGS (0)
-#endif
-
-#define STDIN_FILENO 0
-#define STDOUT_FILENO 1
-#define STDERR_FILENO 2
-
-
-/*
-  for Visual Studio Project Option 
-  LIB: mmsystem.lib comdlg32.lib
-  MACRO: _MT, _WINDOWS
-  Multithread library
-  */
-#define NAME_MAX (MAX_PATH)
-#define NLS "\r\n"
-
-#ifdef TWSYNG32
-#define DEFAULT_VOICES               64 /* 64 voices */
-#define DEFAULT_AUDIO_BUFFER_BITS     9 /* 512sample 11ms (44.1kHz) */
-#define DEFAULT_AUDIO_BUFFER_NUM     32 /* 370ms over */
-#define DEFAULT_COMPUTE_BUFFER_BITS   6 /* ratio 1.45ms (44.1kHz) */
-#define TWSYNG32INI 1 // use twsyng32.ini or timpp32g.ini ??
-#define USE_TWSYN_BRIDGE 1
-#undef ANOTHER_MAIN
-//#undef __W32G__      /* for Win32 GUI */
-#undef IA_W32GUI       /* for Win32 GUI */
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-//#undef AU_FLAC
-//#undef AU_FLAC_DLL
-//#undef AU_OGGFLAC
-//#undef AU_OGGFLAC_DLL
-/* #undef AU_OPUS */
-/* #undef AU_OPUS_DLL */
-#undef AU_SPEEX
-/* #undef AU_AO */
-//#undef AU_PORTAUDIO
-//#undef AU_PORTAUDIO_DLL
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-//#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef SMFCONV
-/* Define if you have the vorbis library (-lvorbis).  */
-//#undef HAVE_LIBVORBIS
-/* Define if you have the vorbis library (-lgogo).  */
-#undef HAVE_LIBGOGOL
-#endif
-
-/* Win32 Synthesizer Service */
-#ifdef TWSYNSRV
-#define DEFAULT_VOICES               64 /* 64 voices */
-#define DEFAULT_AUDIO_BUFFER_BITS     9 /* 512sample 11ms (44.1kHz) */
-#define DEFAULT_AUDIO_BUFFER_NUM     32 /* 370ms over */
-#define DEFAULT_COMPUTE_BUFFER_BITS   6 /* ratio 1.45ms (44.1kHz) */
-#undef USE_TWSYN_BRIDGE
-/* #undef AU_NPIPE */
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-/* #undef AU_PORTAUDIO */
-/* #undef AU_PORTAUDIO_DLL */
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-/* #undef AU_AO */
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-/* #undef VST_LOADER_ENABLE */
-#undef SMFCONV
-#undef SUPPORT_SOCKET
-#undef SUPPORT_SOUNDSPEC
-#undef __W32G__        /* for Win32 GUI */
-#endif
-
-
-#ifdef WINDRV
-#define DEFAULT_VOICES               64 /* 64 voices */
-#define DEFAULT_AUDIO_BUFFER_BITS     9 /* 512sample 11ms (44.1kHz) */
-#define DEFAULT_AUDIO_BUFFER_NUM     32 /* 370ms over */
-#define DEFAULT_COMPUTE_BUFFER_BITS   6 /* ratio 1.45ms (44.1kHz) */
-#define TIMDRVINI 1 // use timdrv.ini or twsyng32.ini or timpp32g.ini ??
-#define IA_WINSYN
-#undef USE_TWSYN_BRIDGE
-//#undef AU_WASAPI
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#define AU_PORTAUDIO 1
-#define AU_PORTAUDIO_DLL 1
-//#undef AU_PORTAUDIO
-//#undef AU_PORTAUDIO_DLL
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef SMFCONV
-
-/* Define if you have the vorbis library (-lvorbis).  */
-//#undef HAVE_LIBVORBIS
-
-/* Define if you have the vorbis library (-lgogo).  */
-//#undef HAVE_LIBGOGOL
-
-#undef __W32G__        /* for Win32 GUI */
-#undef SUPPORT_SOUNDSPEC
-#endif
-
-
-/* Win32GUI Standalone */
-#if defined(__W32G__) && !TWSYNG32 && !KBTIM
-#define FORCE_TIME_PERIOD 1
-#endif
-
-
-/* Win32 Console */
-#ifdef TIM_CUI
-#undef ANOTHER_MAIN
-#undef __W32G__        /* for Win32 GUI */
-#undef IA_W32G_SYN     /* for Win32 GUI */
-//#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-//#undef AU_GOGO
-//#undef AU_GOGO_DLL
-//#undef AU_LAME
-//#undef AU_FLAC
-//#undef AU_FLAC_DLL
-//#undef AU_OGGFLAC
-//#undef AU_OGGFLAC_DLL
-//#undef AU_SPEEX
-//#undef AU_AO
-//#undef AU_PORTAUDIO
-//#undef AU_PORTAUDIO_DLL
-//#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#define AU_LIST 1
-#define AU_MODMIDI 1
-#define AU_VOLUME_CALC 1
-//#undef AU_VOLUME_CALC
-//#undef AU_BENCHMARK
-//#undef SMFCONV
-#undef SUPPORT_SOCKET
-//#undef SUPPORT_SOUNDSPEC
-#define FORCE_TIME_PERIOD 1
-#endif
-
-
-/* x64 */
-#ifdef _WIN64
-#define _AMD64_ 1
-//#undef SUPPORT_SOUNDSPEC
-//#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-//#undef AU_GOGO
-//#undef AU_GOGO_DLL
-//#undef AU_LAME
-//#undef AU_FLAC
-//#undef AU_FLAC_DLL
-//#undef AU_OGGFLAC
-//#undef AU_OGGFLAC_DLL
-//#undef AU_OPUS
-//#undef AU_OPUS_DLL
-//#undef AU_SPEEX
-//#undef AU_AO
-//#undef AU_PORTAUDIO
-//#undef AU_PORTAUDIO_DLL
-//#undef AU_NPIPE
-//#undef AU_WRITE_MIDI
-//#undef AU_LIST
-//#undef AU_MODMIDI
-//#undef AU_VOLUME_CALC
-#undef SMFCONV
-
-#define DWL_MSGRESULT (DWLP_MSGRESULT)
-#define DWL_DLGPROC (DWLP_DLGPROC)
-#define DWL_USER (DWLP_USER)
-#endif
-
-#ifdef CFG_FOR_SF
-#undef AU_WASAPI
-#undef AU_VORBIS
-#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_PORTAUDIO
-#undef AU_PORTAUDIO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef VST_LOADER_ENABLE
-#undef SMFCONV
-#undef SUPPORT_SOCKET
-#undef SUPPORT_SOUNDSPEC
-#undef __W32G__
-#undef HAVE_POPEN
-#endif
-
-
-#ifdef WINDRV_SETUP
-#define DEFAULT_VOICES               64 /* 64 voices */
-#define DEFAULT_AUDIO_BUFFER_BITS     9 /* 512sample 11ms (44.1kHz) */
-#define DEFAULT_AUDIO_BUFFER_NUM     32 /* 370ms over */
-#define DEFAULT_COMPUTE_BUFFER_BITS   6 /* ratio 1.45ms (44.1kHz) */
-#define TIMDRVINI 1 // use timdrv.ini or twsyng32.ini or timpp32g.ini ??
-#define IA_WINSYN
-#undef USE_TWSYN_BRIDGE
-#define WINDRV 1
-#define AU_W32 1
-#define AU_WDMKS 1
-#define AU_WASAPI 1
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#define AU_PORTAUDIO 1
-#define AU_PORTAUDIO_DLL 1
-//#undef AU_PORTAUDIO
-//#undef AU_PORTAUDIO_DLL
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef SMFCONV
-#undef HAVE_LIBVORBIS
-#undef HAVE_LIBMPG123
-#endif
-
-
-
-#ifdef KBTIM /*added by Kobarin*/
-#define IN_TIMIDITY // in_timidity(WINAMP Plugin) \82Å\8eg\97p\82·\82é\8b@\94\\92Ç\89Á // SMF\88È\8aO\91Î\89\9e
-#undef TIM_CUI
-#undef IA_W32G_SYN     /* for Win32 GUI */
-#define __W32G__
-#define cmsg(X) cmsg  //50KB \82Ù\82Ç\8f¬\82³\82­\82È\82é
-//#define DEFAULT_RESAMPLATION_NUM 1 // linear
-#define NO_MIDI_CACHE
-#define HAVE_MKSTEMP
-#undef HAVE_POPEN
-#undef REDUCE_VOICE_TIME_TUNING //playmidi.c \82Ì\90é\8c¾\95\94\82Ì #define \95\94\82ð\8dí\8f\9c\82µ\82È\82¢\82Æ\8b@\94\\82µ\82È\82¢
-#undef AU_W32
-#undef AU_WASAPI
-#undef AU_WDMKS
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#undef AU_PORTAUDIO
-#undef AU_PORTAUDIO_DLL
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef URL_DIR_CACHE_ENABLE
-#ifndef IN_TIMIDITY
-#undef SMFCONV // for in_timidity
-#endif
-#undef SUPPORT_SOCKET
-#define HAVE_SYS_STAT_H
-#define S_ISDIR(mode)   (((mode)&0xF000) == 0x4000)
-#define HAVE_VSNPRINTF
-#define HAVE_SNPRINTF
-typedef __int64 int64;
-#undef HAVE_SIGNAL
-#undef SUPPORT_SOUNDSPEC
-#endif
-
-#ifdef KBTIM_SETUP
-#define IN_TIMIDITY // in_timidity(WINAMP Plugin) \82Å\8eg\97p\82·\82é\8b@\94\\92Ç\89Á // SMF\88È\8aO\91Î\89\9e
-#undef TIM_CUI
-#undef IA_W32G_SYN     /* for Win32 GUI */
-#define __W32G__
-//#define cmsg(X) cmsg  //50KB \82Ù\82Ç\8f¬\82³\82­\82È\82é
-//#define DEFAULT_RESAMPLATION_NUM 1 // linear
-#define NO_MIDI_CACHE
-#define HAVE_MKSTEMP
-#undef HAVE_POPEN
-#undef REDUCE_VOICE_TIME_TUNING //playmidi.c \82Ì\90é\8c¾\95\94\82Ì #define \95\94\82ð\8dí\8f\9c\82µ\82È\82¢\82Æ\8b@\94\\82µ\82È\82¢
-#undef AU_W32
-#undef AU_WASAPI
-#undef AU_WDMKS
-#undef AU_VORBIS
-//#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#define AU_PORTAUDIO 1
-#define AU_PORTAUDIO_DLL 1
-#undef AU_PORTAUDIO
-#undef AU_PORTAUDIO_DLL
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef SUPPORT_SOUNDSPEC
-#undef URL_DIR_CACHE_ENABLE
-#ifndef IN_TIMIDITY
-#undef SMFCONV // for in_timidity
-#endif
-#undef SUPPORT_SOCKET
-#define HAVE_SYS_STAT_H
-#define S_ISDIR(mode)   (((mode)&0xF000) == 0x4000)
-#define HAVE_VSNPRINTF
-#define HAVE_SNPRINTF
-typedef __int64 int64;
-#undef HAVE_SIGNAL
-//#undef SUPPORT_SOUNDSPEC
-#undef HAVE_LIBVORBIS
-#undef HAVE_LIBMPG123
-#endif
-
-
-
-#ifdef TIMVSTI
-#ifdef WIN32
-#define WINVSTI 1
-#endif
-#endif
-
-#ifdef WINVSTI
-#define DEFAULT_VOICES               64 /* 64 voices */
-#define DEFAULT_AUDIO_BUFFER_BITS     9 /* 512sample 11ms (44.1kHz) */
-#define DEFAULT_AUDIO_BUFFER_NUM     32 /* 370ms over */
-#define DEFAULT_COMPUTE_BUFFER_BITS   6 /* ratio 1.45ms (44.1kHz) */
-#undef TIM_CUI
-#undef IA_WINSYN
-#undef HAVE_POPEN
-#undef REDUCE_VOICE_TIME_TUNING //playmidi.c \82Ì\90é\8c¾\95\94\82Ì #define \95\94\82ð\8dí\8f\9c\82µ\82È\82¢\82Æ\8b@\94\\82µ\82È\82¢
-#undef AU_BUFFER 1
-#undef AU_W32
-#undef AU_WASAPI
-#undef AU_WDMKS
-#undef AU_VORBIS
-#undef AU_VORBIS_DLL
-#undef AU_GOGO
-#undef AU_GOGO_DLL
-#undef AU_LAME
-#undef AU_FLAC
-#undef AU_FLAC_DLL
-#undef AU_OGGFLAC
-#undef AU_OGGFLAC_DLL
-#undef AU_OPUS
-#undef AU_OPUS_DLL
-#undef AU_SPEEX
-#undef AU_AO
-#undef AU_PORTAUDIO 1
-#undef AU_PORTAUDIO_DLL 1
-#undef AU_NPIPE
-#undef AU_WRITE_MIDI
-#undef AU_LIST
-#undef AU_MODMIDI
-#undef AU_VOLUME_CALC
-#undef AU_BENCHMARK
-#undef SMFCONV
-/* Define if you have the vorbis library (-lvorbis).  */
-#undef HAVE_LIBVORBIS
-/* Define if you have the vorbis library (-lgogo).  */
-#undef HAVE_LIBGOGOL
-#undef __W32G__        /* for Win32 GUI */
-#undef SUPPORT_SOUNDSPEC
-#endif
index 75690b3..9cfa390 100644 (file)
@@ -49,7 +49,7 @@ dnl               (such as -fPIC)
 # AC_PREREQ(2.56)
 
 # "AC_INIT(timidity/timidity.c)" is obsolate yet.
-AC_INIT([TiMidity++],[2.14.0],[timidity-talk@lists.sourceforge.net],[TiMidity++])
+AC_INIT([TiMidity++],[2.15.0],[timidity-talk@lists.sourceforge.net],[TiMidity++])
 AC_CONFIG_AUX_DIR([autoconf])
 AC_CANONICAL_TARGET
 AM_INIT_AUTOMAKE([gnu dist-bzip2])
@@ -1931,11 +1931,11 @@ CONFIG_INTERFACE(tcltk,TCLTK,k,
 
     tcl_lib=
     tk_lib=
-    for l in tcl tcl8.5 tcl8.4 tcl84 tcl8.3 tcl8.0jp tcl7.6jp tcl80jp tcl76jp tcl8.0 tcl7.6 tcl80 tcl76; do
+    for l in tcl tck8.6 tcl8.5 tcl8.4 tcl84 tcl8.3 tcl8.0jp tcl7.6jp tcl80jp tcl76jp tcl8.0 tcl7.6 tcl80 tcl76; do
       case "x$tcl_lib" in x) AC_CHECK_LIB($l,Tcl_Init,tcl_lib=-l$l);; esac
     done
     LIBS="$LIBS $tcl_lib"
-    for l in tk tk8.5 tk8.4 tcl84 tk8.3 tk8.0jp tk4.2jp tk80jp tk42jp tk8.0 tk4.2 tk80 tk42; do
+    for l in tk tk8.6 tk8.5 tk8.4 tcl84 tk8.3 tk8.0jp tk4.2jp tk80jp tk42jp tk8.0 tk4.2 tk80 tk42; do
       case "x$tk_lib" in x) AC_CHECK_LIB($l,Tk_Init,tk_lib=-l$l);; esac
     done
 
diff --git a/dll/libFLAC.dll b/dll/libFLAC.dll
deleted file mode 100644 (file)
index a6d3fae..0000000
Binary files a/dll/libFLAC.dll and /dev/null differ
diff --git a/dll/libOggFLAC.dll b/dll/libOggFLAC.dll
deleted file mode 100644 (file)
index 1b417f2..0000000
Binary files a/dll/libOggFLAC.dll and /dev/null differ
diff --git a/dll/ogg.dll b/dll/ogg.dll
deleted file mode 100644 (file)
index 84c5bb3..0000000
Binary files a/dll/ogg.dll and /dev/null differ
diff --git a/dll/pdcurses.dll b/dll/pdcurses.dll
deleted file mode 100644 (file)
index 7507a15..0000000
Binary files a/dll/pdcurses.dll and /dev/null differ
diff --git a/gpl-2.0.txt b/gpl-2.0.txt
new file mode 100644 (file)
index 0000000..d159169
--- /dev/null
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/interface.h b/interface.h
deleted file mode 100644 (file)
index b59f87d..0000000
+++ /dev/null
@@ -1,190 +0,0 @@
-
-
-#ifndef INTERFACE_H_INCLUDED
-#define INTERFACE_H_INCLUDED 1
-
-/* interface.h.  Generated from interface.h.in by configure.  */
-/* Define if you have EMACS interface. */
-/* #undef IA_EMACS */
-
-/* Define if you have GTK interface. */
-/* #undef IA_GTK */
-
-/* Define if you have KMIDI interface. */
-/* #undef IA_KMIDI */
-
-/* Define if you have MOTIF interface. */
-/* #undef IA_MOTIF */
-
-/* Define if you have NCURSES interface. */
-#define IA_NCURSES 1
-
-/* Define if you have PDCURSES library. */
-#define USE_PDCURSES 1
-
-/* Define if you have PLUGIN interface. */
-/* #undef IA_PLUGIN */
-
-/* Define if you have SLANG interface. */
-/* #undef IA_SLANG */
-
-/* Define if you have TCLTK interface. */
-/* #undef IA_TCLTK */
-
-/* Define if you have VT100 interface. */
-#define IA_VT100 1
-
-/* Define if you have XAW interface. */
-/* #undef IA_XAW */
-
-/* Define if you have XSKIN interface. */
-/* #undef IA_XSKIN */
-
-/* Define if you have DYNAMIC interface. */
-#define IA_DYNAMIC 1
-
-/* Define if you have Windows32 GUI interface. */
-/* #undef IA_W32GUI */
-
-/* Define if you have Windows GUI synthesizer mode interface. */
-/* #undef IA_W32G_SYN */
-
-/* Define if you have Remote MIDI interface. */
-/* #undef IA_SERVER */
-
-/* Define if you have Remote MIDI interface. */
-/* #undef IA_ALSASEQ */
-
-/* Define if you have Windows synthesizer mode interface. */
-#define IA_WINSYN 1
-
-/* Define if you have PortMIDI synthesizer mode interface. */
-#define IA_PORTMIDISYN 1
-
-/* Define if you have Windows named pipe synthesizer mode interface. */
-#define IA_NPSYN 1
-
-/* Define if you have Windows32 GUI synthesizer mode interface. */
-#ifdef TWSYNG32
-#define IA_W32G_SYN 1
-#endif
-
-
-/* Define if you have Windows32 GUI interface. */
-#ifdef TWSYNG32
-#undef IA_W32GUI
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-//#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#elif defined(__W32G__)
-#define IA_W32GUI 1
-#endif
-
-#if defined(IA_W32GUI) || defined(IA_W32G_SYN)
-#ifndef __W32READDIR__
-#define __W32READDIR__
-#endif
-#ifndef URL_DIR_CACHE_ENABLE
-#define URL_DIR_CACHE_ENABLE
-#endif
-#define __W32G__        /* for Win32 GUI */
-//#define IA_XSKIN
-#endif
-
-/* Define if you have Windows32 CUI interface. */
-#ifdef TIM_CUI
-#undef __W32G__        /* for Win32 GUI */
-#undef IA_W32G_SYN     /* for Win32 GUI */
-#undef IA_W32GUI
-#undef IA_DYNAMIC // need GNU DLD ?
-//#undef IA_NCURSES
-//#undef IA_VT100
-//#undef IA_WINSYN
-//#undef IA_PORTMIDISYN
-//#undef IA_NPSYN
-#endif
-
-/* Define if you have Windows32 Service mode interface. */
-#ifdef TWSYNSRV
-#define IA_W32G_SYN 1
-#undef __W32G__        /* for Win32 GUI */
-#undef IA_W32GUI
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-//#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif
-
-/* Define if you have Windows32 Driver mode interface. */
-#ifdef WINDRV
-#undef __W32G__        /* for Win32 GUI */
-#undef IA_W32GUI
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-//#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif
-
-/* Define if you have Windows32 GUI interface. */
-#if defined(__W32G__) && !defined(TWSYNG32) && !defined(KBTIM)
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif
-
-/* Define if you have cfgforsf interface. */
-#ifdef CFG_FOR_SF
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif
-
-
-///r
-#ifdef KBTIM /*added by Kobarin*/
-#undef IA_W32GUI
-#undef IA_W32G_SYN
-#undef TIM_CUI
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif /*KBTIM*/
-
-#ifdef KBTIM_SETUP
-#define IA_W32GUI 1
-#undef IA_W32G_SYN
-
-#endif /*KBTIM_SETUP*/
-
-
-#ifdef WINVSTI
-#undef IA_W32GUI
-#undef IA_W32G_SYN
-#undef TIM_CUI
-#undef IA_NCURSES
-#undef IA_VT100
-#undef IA_DYNAMIC
-#undef IA_WINSYN
-#undef IA_PORTMIDISYN
-#undef IA_NPSYN
-#endif /*KBTIM*/
-
-
-
-#endif /* INTERFACE_H_INCLUDED */
index 99f1be4..e899b19 100644 (file)
@@ -2,10 +2,7 @@
 set(
     INTERFACE_COMMON_SOURCES
 
-    ncurs_c.c
     rtsyn_common.c
-    vt100.c
-    vt100_c.c
     VTPrsTbl.c
     w32g_soundspec.c
     wrdt_dumb.c
@@ -19,7 +16,6 @@ set(
     rtsyn.h
     server_defs.h
     soundspec.h
-    vt100.h
     VTparse.h
     w32g_utl.h
     xaw.h
@@ -30,6 +26,17 @@ set(
 )
 
 set(
+    INTERFACE_CON_SOURCES
+
+    dumb_c.c
+    ncurs_c.c
+    wrdt_wcon.c
+    vt100.c
+    vt100_c.c
+    vt100.h
+)
+
+set(
     INTERFACE_W32G_COMMON_SOURCES
 
     w32g_c.c
@@ -38,6 +45,7 @@ set(
     w32g_ini.c
     w32g_int_synth_editor.c
     w32g_mag.c
+       w32g_new_console.cpp
     w32g_playlist.c
     w32g_pref.c
     w32g_subwin.c
@@ -53,6 +61,7 @@ set(
     w32g_dib.h
     w32g_int_synth_editor.h
     w32g_mag.h
+       w32g_new_console.h
     w32g_pref.h
     w32g_rec.h
     w32g_res.h
@@ -61,25 +70,38 @@ set(
     w32g_ut2.h
     w32g_utl.h
     w32g_wrd.h
+
+    w32g_res.rc
+)
+
+set(
+    INTERFACE_SYN_SOURCES
+
+    npsyn_c.c
+    portmidisyn_c.c
+    rtsyn_npipe.c
+    rtsyn_winmm.c
+    winsyn_c.c
+
+       ../twsyn_bridge/twsyn_bridge_host.c
+       ../twsyn_bridge/twsyn_bridge_host.h
 )
 
-if(MSVC)
-    set_source_files_properties(
-        w32g_res.rc
-
-        PROPERTIES
-            OBJECT_DEPENDS
-                w32g_btn.bmp
-                w32g_icon.ico
-                w32g_icon_gray.ico
-                w32g_icon_normal.ico
-                w32g_icon_silver.ico
-                w32g_playlist_play.ico
-                w32g_sleep.bmp
-                w32g_subbtn.bmp
-                w32g_tracer.bmp
-    )
-endif()
+set_source_files_properties(
+    w32g_res.rc
+
+    PROPERTIES
+        OBJECT_DEPENDS
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_btn.bmp"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_icon.ico"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_icon_gray.ico"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_icon_normal.ico"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_icon_silver.ico"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_playlist_play.ico"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_sleep.bmp"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_subbtn.bmp"
+            "${CMAKE_CURRENT_SOURCE_DIR}/w32g_tracer.bmp"
+)
 
 # for timidity
 
@@ -87,11 +109,10 @@ add_library(
     interface OBJECT
 
     ${INTERFACE_COMMON_SOURCES}
-    dumb_c.c
-    wrdt_wcon.c
+    ${INTERFACE_CON_SOURCES}
 )
 
-target_compile_definitions(interface PRIVATE -DIA_NCURSES)
+target_compile_definitions(interface PRIVATE -DIA_NCURSES -DIA_VT100)
 
 # for twsynsrv
 
@@ -99,17 +120,12 @@ add_library(
     interface_synsrv OBJECT
 
     ${INTERFACE_COMMON_SOURCES}
-    dumb_c.c
-    rtsyn_winmm.c
-    winsyn_c.c
-    wrdt_wcon.c
-
-       ../twsyn_bridge/twsyn_bridge_host.c
-       ../twsyn_bridge/twsyn_bridge_host.h
+    ${INTERFACE_CON_SOURCES}
+    ${INTERFACE_SYN_SOURCES}
 )
 
 add_dependencies(interface_synsrv twsyn_bridge)
-target_compile_definitions(interface_synsrv PRIVATE -DIA_WINSYN -DTWSYNSRV)
+target_compile_definitions(interface_synsrv PRIVATE -DIA_NPSYN -DIA_PORTMIDISYN -DIA_WINSYN -DTWSYNSRV)
 
 # for timw32g
 
@@ -117,7 +133,6 @@ add_library(
     interface_w32g OBJECT
 
     ${INTERFACE_W32G_COMMON_SOURCES}
-    w32g_res.rc
 )
 
 add_dependencies(interface_w32g UpdateTim41Version)
@@ -130,14 +145,9 @@ add_library(
 
     ${INTERFACE_COMMON_SOURCES}
     ${INTERFACE_W32G_COMMON_SOURCES}
-    rtsyn_winmm.c
+    ${INTERFACE_SYN_SOURCES}
     w32g_syn.c
-    winsyn_c.c
-    w32g_res.rc
-
-       ../twsyn_bridge/twsyn_bridge_host.c
-       ../twsyn_bridge/twsyn_bridge_host.h
 )
 
 add_dependencies(interface_w32gsyn UpdateTim41Version twsyn_bridge)
-target_compile_definitions(interface_w32gsyn PRIVATE -DIA_W32G_SYN -D__W32G__ -DTWSYNG32)
+target_compile_definitions(interface_w32gsyn PRIVATE -DIA_NPSYN -DIA_PORTMIDISYN -DIA_W32G_SYN -D__W32G__ -DTWSYNG32)
index b52d1af..abe71b1 100644 (file)
@@ -66,8 +66,6 @@
 #include "timer.h"
 
 
-void readmidi_read_init(void);
-
 #define MAX_PORTS      16
 
 #define TICKTIME_HZ    100
diff --git a/interface/interface.dsp b/interface/interface.dsp
deleted file mode 100644 (file)
index d825d8a..0000000
+++ /dev/null
@@ -1,176 +0,0 @@
-# Microsoft Developer Studio Project File - Name="interface" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Static Library" 0x0104
-
-CFG=interface - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "interface.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "interface.mak" CFG="interface - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "interface - Win32 Release" ("Win32 (x86) Static Library" \97p)
-!MESSAGE "interface - Win32 Debug" ("Win32 (x86) Static Library" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "interface - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "NDEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Release\interface.lib"
-
-!ELSEIF  "$(CFG)" == "interface - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\" /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "_DEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Debug\interface.lib"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "interface - Win32 Release"
-# Name "interface - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\interface\dumb_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\vt100.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\vt100_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\VTPrsTbl.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_dumb.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_tty.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\interface\gtk_h.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_c.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_mag.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_wrdwindow.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\motif.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\server_defs.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\soundspec.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\vt100.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\VTparse.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_mag.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_sherry.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_wrdwindow.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xaw.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xskin.h"
-# End Source File
-# End Group
-# End Target
-# End Project
diff --git a/interface/interface.vcproj b/interface/interface.vcproj
deleted file mode 100644 (file)
index 484d197..0000000
+++ /dev/null
@@ -1,292 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="interface"
-       ProjectGUID="{248B20A6-9609-4A5B-AFAE-09C7572FCE54}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\"
-                               PreprocessorDefinitions="_DEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/interface.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\interface.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="NDEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/interface.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\interface.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\dumb_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vt100.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vt100_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\VTPrsTbl.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wrdt_dumb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wrdt_tty.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\gtk_h.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_c.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_mag.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_wrdwindow.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\motif.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\configs\msc-config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\server_defs.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\soundspec.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vt100.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\VTparse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32g_utl.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\x_mag.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\x_sherry.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\x_wrdwindow.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\xaw.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\xskin.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/interface/interface.vcxproj b/interface/interface.vcxproj
deleted file mode 100644 (file)
index 12d21ed..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{248B20A6-9609-4A5B-AFAE-09C7572FCE54}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/interface.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\interface.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/interface.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\interface.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/interface.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\interface.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/interface.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\interface.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="dumb_c.c" />
-    <ClCompile Include="vt100.c" />
-    <ClCompile Include="vt100_c.c" />
-    <ClCompile Include="VTPrsTbl.c" />
-    <ClCompile Include="wrdt_dumb.c" />
-    <ClCompile Include="wrdt_tty.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="gtk_h.h" />
-    <ClInclude Include="mac_c.h" />
-    <ClInclude Include="mac_mag.h" />
-    <ClInclude Include="mac_wrdwindow.h" />
-    <ClInclude Include="motif.h" />
-    <ClInclude Include="..\configs\msc-config.h" />
-    <ClInclude Include="server_defs.h" />
-    <ClInclude Include="soundspec.h" />
-    <ClInclude Include="vt100.h" />
-    <ClInclude Include="VTparse.h" />
-    <ClInclude Include="w32g_utl.h" />
-    <ClInclude Include="x_mag.h" />
-    <ClInclude Include="x_sherry.h" />
-    <ClInclude Include="x_wrdwindow.h" />
-    <ClInclude Include="xaw.h" />
-    <ClInclude Include="xskin.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/interface/interface.vcxproj.filters b/interface/interface.vcxproj.filters
deleted file mode 100644 (file)
index 592bc92..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{1673b1d8-e95d-418b-ad13-1c5d8a4c2821}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{bf104e0a-54fc-4e98-bdef-c5be00c10e4f}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="dumb_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="vt100.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="vt100_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="VTPrsTbl.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="wrdt_dumb.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="wrdt_tty.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="gtk_h.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_c.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_mag.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_wrdwindow.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="motif.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\configs\msc-config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="server_defs.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="soundspec.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="vt100.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="VTparse.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="w32g_utl.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="x_mag.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="x_sherry.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="x_wrdwindow.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="xaw.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="xskin.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/interface/interface.vcxproj.user b/interface/interface.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
index 1371097..4cb9c8f 100644 (file)
@@ -1,6 +1,6 @@
 /*
     TiMidity++ -- MIDI to WAVE converter and player
-    Copyright (C) 1999-2004 Masanao Izumo <iz@onicos.co.jp>
+    Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>
     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
 
     This program is free software; you can redistribute it and/or modify
@@ -460,7 +460,7 @@ static void N_ctl_scrinit(void)
        waddch(dftwin, 'v');
     waddstr(dftwin, timidity_version);
     wmove(dftwin, VERSION_LINE,COLS-51);
-    waddstr(dftwin, "(C) 1995,1999-2004 Tuukka Toivonen, Masanao Izumo");
+    waddstr(dftwin, "(C) 1995,1999-2018 Tuukka Toivonen, Masanao Izumo");
     wmove(dftwin, FILE_LINE,0);
     waddstr(dftwin, "File:");
 #ifdef MIDI_TITLE
index a212951..825ad8e 100644 (file)
@@ -26,7 +26,7 @@
             Copyright (c) 2000  Takashi Iwai <tiwai@suse.de>
         readmidi.c
 */
-#include "interface.h"
+
 
 #include <stdio.h>
 
 #endif
 
 
-#ifndef __W32__
 #ifdef HAVE_STDLIB_H
 #include <stdlib.h>
 #endif
-#endif
 
 
 
index ea503f0..876fcb3 100644 (file)
@@ -29,7 +29,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef __POCC__
 #include <sys/types.h>
index d415792..66e0af6 100755 (executable)
@@ -31,7 +31,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef __POCC__
 #include <sys/types.h>
index 1bde704..698446b 100644 (file)
@@ -31,7 +31,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #include <stdio.h>
 
index 8776510..66c94be 100644 (file)
@@ -31,7 +31,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef __POCC__
 #include <sys/types.h>
diff --git a/interface/version.h b/interface/version.h
deleted file mode 100644 (file)
index 348365a..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
-    TiMidity++ -- MIDI to WAVE converter and player
-    Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
-    Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-*/
-
-// for ResEdit
-#include "..\version.h"
index fcacd29..266cb36 100644 (file)
@@ -262,6 +262,10 @@ static void ctl_close(void)
        ClearNewConsoleBuffer();
 #endif
 
+#ifdef TIMW32G_USE_NEW_CONSOLE
+       ClearNewConsoleBuffer();
+#endif
+
 //#ifdef FORCE_TIME_PERIOD
 //     timeEndPeriod(tcaps.wPeriodMin);
 //#endif
index 1aa189b..450e72b 100644 (file)
@@ -1,6 +1,6 @@
 /*
     TiMidity++ -- MIDI to WAVE converter and player
-    Copyright (C) 1999-2004 Masanao Izumo <iz@onicos.co.jp>
+    Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>
     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
 
     This program is free software; you can redistribute it and/or modify
@@ -45,7 +45,7 @@
                         * Edit_* and ListBox_* are defined in
                         * <windowsx.h>
                         */
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 #include "instrum.h"
@@ -4574,8 +4574,8 @@ static void TiMidityWnd(HWND hParentWnd)
 {
        char TiMidityText[2024];
   sprintf(TiMidityText,
-" TiMidity++ %s%s %s -- MIDI to WAVE converter and player" NLS
-" Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>" NLS
+" TiMidity++ %s%s -- MIDI to WAVE converter and player" NLS
+" Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>" NLS
 " Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>" NLS
 NLS
 " Win32 version by Davide Moretti <dmoretti@iper.net>" NLS
index de981b8..c4cf297 100644 (file)
@@ -29,7 +29,7 @@
 #include <stdlib.h>
 #endif /* HAVE_STDLIB_H */
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 #include "output.h"
index ee913fb..5e2ff4a 100644 (file)
@@ -23,7 +23,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include <stdio.h>
 #ifdef HAVE_STDLIB_H
 #include <stdlib.h>
@@ -660,7 +660,6 @@ LRESULT APIENTRY CALLBACK PrefWndDialogProc(HWND hwnd, UINT uMess, WPARAM wParam
 
 extern void TracerWndApplyQuietChannel( ChannelBitMask quietchannels_ );
 
-#if !defined(IA_W32G_SYN)
 /* st_temp, sp_temp \82ð\93K\97p\82·\82é
  * \92\8d\88Ó: MainThread \82©\82ç\82Ì\8cÄ\82Ñ\8fo\82µ\8bÖ\8e~\81A\8aë\8c¯\81I
  */
@@ -744,7 +743,6 @@ void PrefSettingApplyReally(void)
 //             PrefWndDoing = 0;
        }
 }
-#endif
 
 #if defined(IA_W32G_SYN)
 extern int w32g_syn_do_before_pref_apply ( void );
@@ -6139,19 +6137,11 @@ int wave_ConfigDialogInfoSaveINI(void)
        const char *inifile = timidity_output_inifile;
        char buffer[1024];
 
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMSAVE(name) \
                sprintf(buffer, "%d", wave_ConfigDialogInfo.name); \
                WritePrivateProfileStringA(section, #name, buffer, inifile);
 #define STRSAVE(name, len) \
                WritePrivateProfileStringA(section, (char*)#name, (char*)wave_ConfigDialogInfo.name, inifile);
-#else
-#define NUMSAVE(name) \
-               sprintf(buffer, "%d", wave_ConfigDialogInfo.##name); \
-               WritePrivateProfileStringA(section, #name, buffer, inifile);
-#define STRSAVE(name, len) \
-               WritePrivateProfileStringA(section, (char*)#name, (char*)wave_ConfigDialogInfo.##name, inifile);
-#endif
        STRSAVE(optIDC_EDIT_RIFFWAVE_UPDATE_STEP, 1024)
        NUMSAVE(optIDC_CHECKBOX_RIFFWAVE_EXTENSIBLE)
        WritePrivateProfileStringA(NULL, NULL, NULL, inifile);          // Write Flush
@@ -6165,7 +6155,6 @@ int wave_ConfigDialogInfoLoadINI(void)
        const char *inifile = timidity_output_inifile;
        int num;
        char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMLOAD(name) \
                num = GetPrivateProfileIntA(section, #name, -1, inifile); \
                if (num != -1) wave_ConfigDialogInfo.name = num;
@@ -6174,16 +6163,6 @@ int wave_ConfigDialogInfoLoadINI(void)
                buffer[len - 1] = '\0'; \
                if (buffer[0] != 0) \
                        strcpy((char*)wave_ConfigDialogInfo.name, buffer);
-#else
-#define NUMLOAD(name) \
-               num = GetPrivateProfileIntA(section, #name, -1, inifile); \
-               if (num != -1) wave_ConfigDialogInfo.##name = num;
-#define STRLOAD(name, len) \
-               GetPrivateProfileStringA(section, (char*)#name, "", buffer, len, inifile); \
-               buffer[len - 1] = '\0'; \
-               if (buffer[0] != 0) \
-                       strcpy((char*)wave_ConfigDialogInfo.##name, buffer);
-#endif
        wave_ConfigDialogInfoLock();
        STRLOAD(optIDC_EDIT_RIFFWAVE_UPDATE_STEP, 1024)
        NUMLOAD(optIDC_CHECKBOX_RIFFWAVE_EXTENSIBLE)
@@ -7013,19 +6992,11 @@ int gogo_ConfigDialogInfoSaveINI(void)
        char *section = SEC_GOGO;
        char *inifile = timidity_output_inifile;
        char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMSAVE(name) \
                sprintf(buffer,"%d",gogo_ConfigDialogInfo.name ); \
                WritePrivateProfileString(section, #name ,buffer,inifile);
 #define STRSAVE(name) \
                WritePrivateProfileString(section,(char *) #name ,(char *)gogo_ConfigDialogInfo.name ,inifile);
-#else
-#define NUMSAVE(name) \
-               sprintf(buffer,"%d",gogo_ConfigDialogInfo. ## name ); \
-               WritePrivateProfileString(section, #name ,buffer,inifile);
-#define STRSAVE(name) \
-               WritePrivateProfileString(section,(char *) #name ,(char *)gogo_ConfigDialogInfo. ## name ,inifile);
-#endif
        NUMSAVE(optIDC_CHECK_DEFAULT)
        NUMSAVE(optIDC_CHECK_COMMANDLINE_OPTS)
        STRSAVE(optIDC_EDIT_COMMANDLINE_OPTION)
@@ -7074,7 +7045,6 @@ int gogo_ConfigDialogInfoLoadINI(void)
        char *inifile = timidity_output_inifile;
        int num;
        char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMLOAD(name) \
                num = GetPrivateProfileInt(section, #name ,-1,inifile); \
                if(num!=-1) gogo_ConfigDialogInfo.name = num;
@@ -7083,16 +7053,6 @@ int gogo_ConfigDialogInfoLoadINI(void)
                buffer[len-1] = '\0'; \
                if(buffer[0]!=0) \
                        strcpy((char *)gogo_ConfigDialogInfo.name ,buffer);
-#else
-#define NUMLOAD(name) \
-               num = GetPrivateProfileInt(section, #name ,-1,inifile); \
-               if(num!=-1) gogo_ConfigDialogInfo. ## name = num;
-#define STRLOAD(name,len) \
-               GetPrivateProfileString(section,(char *) #name ,"",buffer,len,inifile); \
-               buffer[len-1] = '\0'; \
-               if(buffer[0]!=0) \
-                       strcpy((char *)gogo_ConfigDialogInfo. ## name ,buffer);
-#endif
        gogo_ConfigDialogInfoLock();
        NUMLOAD(optIDC_CHECK_DEFAULT)
        NUMLOAD(optIDC_CHECK_COMMANDLINE_OPTS)
@@ -7484,19 +7444,11 @@ int vorbis_ConfigDialogInfoSaveINI(void)
        char *inifile = timidity_output_inifile;
        char buffer[1024];
 //     int len;
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMSAVE(name) \
                sprintf(buffer,"%d",vorbis_ConfigDialogInfo.name ); \
                WritePrivateProfileString(section, #name ,buffer,inifile);
 #define STRSAVE(name,len) \
                WritePrivateProfileString(section,(char *) #name ,(char *)vorbis_ConfigDialogInfo.name ,inifile);
-#else
-#define NUMSAVE(name) \
-               sprintf(buffer,"%d",vorbis_ConfigDialogInfo. ## name ); \
-               WritePrivateProfileString(section, #name ,buffer,inifile);
-#define STRSAVE(name,len) \
-               WritePrivateProfileString(section,(char *) #name ,(char *)vorbis_ConfigDialogInfo. ## name ,inifile);
-#endif
        NUMSAVE(optIDC_CHECK_DEFAULT)
        NUMSAVE(optIDC_COMBO_MODE)
        NUMSAVE(optIDC_CHECK_USE_TAG)
@@ -7514,7 +7466,6 @@ int vorbis_ConfigDialogInfoLoadINI(void)
        char *inifile = timidity_output_inifile;
        int num;
        char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMLOAD(name) \
                num = GetPrivateProfileInt(section, #name ,-1,inifile); \
                if(num!=-1) vorbis_ConfigDialogInfo.name = num;
@@ -7523,16 +7474,6 @@ int vorbis_ConfigDialogInfoLoadINI(void)
                buffer[len-1] = '\0'; \
                if(buffer[0]!=0) \
                        strcpy((char *)vorbis_ConfigDialogInfo.name ,buffer);
-#else
-#define NUMLOAD(name) \
-               num = GetPrivateProfileInt(section, #name ,-1,inifile); \
-               if(num!=-1) vorbis_ConfigDialogInfo. ## name = num;
-#define STRLOAD(name,len) \
-               GetPrivateProfileString(section,(char *) #name ,"",buffer,len,inifile); \
-               buffer[len-1] = '\0'; \
-               if(buffer[0]!=0) \
-                       strcpy((char *)vorbis_ConfigDialogInfo. ## name ,buffer);
-#endif
        vorbis_ConfigDialogInfoLock();
        NUMLOAD(optIDC_CHECK_DEFAULT)
        NUMLOAD(optIDC_COMBO_MODE)
@@ -7737,19 +7678,11 @@ int lame_ConfigDialogInfoSaveINI(void)
        char *inifile = timidity_output_inifile;
        char buffer[1024];
 //     int len;
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMSAVE(name) \
                sprintf(buffer,"%d",lame_ConfigDialogInfo.name ); \
                WritePrivateProfileString(section, #name ,buffer,inifile);
 //#define STRSAVE(name,len) \
 //             WritePrivateProfileString(section,(char *) #name ,(char *)lame_ConfigDialogInfo.name ,inifile);
-#else
-#define NUMSAVE(name) \
-               sprintf(buffer,"%d",lame_ConfigDialogInfo. ## name ); \
-               WritePrivateProfileString(section, #name ,buffer,inifile);
-//#define STRSAVE(name,len) \
-//             WritePrivateProfileString(section,(char *) #name ,(char *)lame_ConfigDialogInfo. ## name ,inifile);
-#endif
        NUMSAVE(optIDC_LAME_CBPRESET)
        WritePrivateProfileString(NULL,NULL,NULL,inifile);              // Write Flush
 #undef NUMSAVE
@@ -7762,7 +7695,6 @@ int lame_ConfigDialogInfoLoadINI(void)
        char *inifile = timidity_output_inifile;
        int num;
 //     char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMLOAD(name) \
                num = GetPrivateProfileInt(section, #name ,-1,inifile); \
                if(num!=-1) lame_ConfigDialogInfo.name = num;
@@ -7771,16 +7703,6 @@ int lame_ConfigDialogInfoLoadINI(void)
 //             buffer[len-1] = '\0'; \
 //             if(buffer[0]!=0) \
 //                     strcpy((char *)lame_ConfigDialogInfo.name ,buffer);
-#else
-#define NUMLOAD(name) \
-               num = GetPrivateProfileInt(section, #name ,-1,inifile); \
-               if(num!=-1) lame_ConfigDialogInfo. ## name = num;
-//#define STRLOAD(name,len) \
-//             GetPrivateProfileString(section,(char *) #name ,"",buffer,len,inifile); \
-//             buffer[len-1] = '\0'; \
-//             if(buffer[0]!=0) \
-//                     strcpy((char *)lame_ConfigDialogInfo. ## name ,buffer);
-#endif
        lame_ConfigDialogInfoLock();
        NUMLOAD(optIDC_LAME_CBPRESET)
 #undef NUMLOAD
@@ -8035,19 +7957,11 @@ int flac_ConfigDialogInfoSaveINI(void)
        char *inifile = timidity_output_inifile;
        char buffer[1024];
 //     int len;
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMSAVE(name) \
                sprintf(buffer,"%d",flac_ConfigDialogInfo.name ); \
                WritePrivateProfileString(section, #name ,buffer,inifile);
 //#define STRSAVE(name,len) \
 //             WritePrivateProfileString(section,(char *) #name ,(char *)flac_ConfigDialogInfo.name ,inifile);
-#else
-#define NUMSAVE(name) \
-               sprintf(buffer,"%d",flac_ConfigDialogInfo. ## name ); \
-               WritePrivateProfileString(section, #name ,buffer,inifile);
-//#define STRSAVE(name,len) \
-//             WritePrivateProfileString(section,(char *) #name ,(char *)flac_ConfigDialogInfo. ## name ,inifile);
-#endif
        NUMSAVE(optIDC_COMBO_ENCODE_MODE)
        NUMSAVE(optIDC_CHECKBOX_OGGFLAC_CONTAINER)
        WritePrivateProfileString(NULL,NULL,NULL,inifile);              // Write Flush
@@ -8061,7 +7975,6 @@ int flac_ConfigDialogInfoLoadINI(void)
        char *inifile = timidity_output_inifile;
        int num;
 //     char buffer[1024];
-#if defined(__MINGW32__) || defined(__CYGWIN__)
 #define NUMLOAD(name) \
                num = GetPrivateProfileInt(section, #name ,-1,inifile); \
                if(num!=-1) flac_ConfigDialogInfo.name = num;
@@ -8070,16 +7983,6 @@ int flac_ConfigDialogInfoLoadINI(void)
 //             buffer[len-1] = '\0'; \
 //             if(buffer[0]!=0) \
 //                     strcpy((char *)flac_ConfigDialogInfo.name ,buffer);
-#else
-#define NUMLOAD(name) \
-               num = GetPrivateProfileInt(section, #name ,-1,inifile); \
-               if(num!=-1) flac_ConfigDialogInfo. ## name = num;
-//#define STRLOAD(name,len) \
-//             GetPrivateProfileString(section,(char *) #name ,"",buffer,len,inifile); \
-//             buffer[len-1] = '\0'; \
-//             if(buffer[0]!=0) \
-//                     strcpy((char *)flac_ConfigDialogInfo. ## name ,buffer);
-#endif
        flac_ConfigDialogInfoLock();
        NUMLOAD(optIDC_COMBO_ENCODE_MODE)
        NUMLOAD(optIDC_CHECKBOX_OGGFLAC_CONTAINER)
index 7956f5e..24ebbcc 100644 (file)
 #define IDD_DIALOG_SIMPLE_LIST          110
 #define IDD_DIALOG_WRD                  111
 #define IDD_DIALOG_SOUNDSPEC_EN         112
-#define IDD_DIALOG_SOUNDSPEC            112
-#define IDD_DIALOG_WAVEFORM             113
-#define IDD_DIALOG_PLAYLIST_EN          114
-#define IDD_DIALOG_PLAYLIST             115
-#define IDD_DIALOG_SEARCHBOX            116
+#define IDD_DIALOG_SOUNDSPEC            113
+#define IDD_DIALOG_WAVEFORM             114
+#define IDD_DIALOG_PLAYLIST_EN          115
+#define IDD_DIALOG_PLAYLIST             116
+#define IDD_DIALOG_SEARCHBOX            117
 #define IDD_DIALOG_ONE_LINE_EN          118
 #define IDD_DIALOG_ONE_LINE             119
 #define IDD_DIALOG_PREF_EN              120
index 2fb1ac2..e72a586 100644 (file)
@@ -9,25 +9,71 @@
 #include "afxres.h"\r
 #include "version.h"\r
 \r
-\r
+1 RT_MANIFEST\r
+BEGIN\r
+    "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>\n"\r
+    "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">\n"\r
+    "<compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1"">\n"\r
+    "    <application>\n"\r
+    "        <!--This Id value indicates the application supports Windows Vista functionality-->\n"\r
+    "        <supportedOS Id=""{e2011457-1546-43c5-a5fe-008deee3d3f0}""/>\n"\r
+    "        <!--This Id value indicates the application supports Windows 7 functionality-->\n"\r
+    "        <supportedOS Id=""{35138b9a-5d96-4fbd-8e2d-a2440225f93a}""/>\n"\r
+    "        <!--This Id value indicates the application supports Windows 8 functionality-->\n"\r
+    "        <supportedOS Id=""{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}""/>\n"\r
+    "        <!--This Id value indicates the application supports Windows 8.1 functionality-->\n"\r
+    "        <supportedOS Id=""{1f676c76-80e1-4239-95bb-83d0f6d0da78}""/>\n"\r
+    "        <!--This Id value indicates the application supports Windows Threshold functionality-->\n"\r
+    "        <supportedOS Id=""{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}""/>\n"\r
+    "    </application>\n"\r
+    "</compatibility>\n"\r
+    "<dependency>\n"\r
+    "    <dependentAssembly>\n"\r
+    "        <assemblyIdentity\n"\r
+    "            type=""win32""\n"\r
+    "            name=""Microsoft.Windows.Common-Controls""\n"\r
+    "            version=""6.0.0.0""\n"\r
+    "            processorArchitecture=""*""\n"\r
+    "            publicKeyToken=""6595b64144ccf1df""\n"\r
+    "            language=""*""\n"\r
+    "        />\n"\r
+    "    </dependentAssembly>\n"\r
+    "</dependency>\n"\r
+    "<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v3"">\n"\r
+    "    <security>\n"\r
+    "        <requestedPrivileges>\n"\r
+    "            <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>\n"\r
+    "        </requestedPrivileges>\n"\r
+    "    </security>\n"\r
+    "</trustInfo>\n"\r
+    "</assembly>\n"\r
+END\r
 \r
 \r
 //\r
 // Bitmap resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDB_BITMAP_MAIN_BUTTON BITMAP         "w32g_btn.bmp"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDB_BITMAP_SLEEP   BITMAP         "w32g_sleep.bmp"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDB_BITMAP_SUBWND_BUTTON BITMAP         "w32g_subbtn.bmp"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDB_BITMAP_TRACER  BITMAP         "w32g_tracer.bmp"\r
 \r
 \r
@@ -35,7 +81,9 @@ IDB_BITMAP_TRACER  BITMAP         "w32g_tracer.bmp"
 //\r
 // Menu resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDM_MENU_MAIN MENU\r
 {\r
     POPUP "\83t\83@\83C\83\8b(&F)"\r
@@ -85,7 +133,9 @@ IDM_MENU_MAIN MENU
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDM_MENU_MAIN_EN MENU\r
 {\r
     POPUP "File(&F)"\r
@@ -137,13 +187,20 @@ IDM_MENU_MAIN_EN MENU
 //\r
 // Dialog resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_CONSOLE DIALOGEX 0, 0, 250, 200\r
 STYLE DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
+EXSTYLE WS_EX_ACCEPTFILES\r
 CAPTION "\83R\83\93\83\\81[\83\8b (TiMidity++ Win32GUI)"\r
 FONT 9, "MS UI Gothic", 400, 0, 128\r
 {\r
+#ifdef TIMW32G_USE_NEW_CONSOLE\r
+       CONTROL         "", IDC_EDIT, "TimW32gNewConsole", 0, 0, 250, 175, WS_HSCROLL | WS_VSCROLL\r
+#else\r
     EDITTEXT        IDC_EDIT, 0, 0, 250, 175, WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_NOHIDESEL | ES_READONLY | ES_WANTRETURN, WS_EX_STATICEDGE\r
+#endif\r
     PUSHBUTTON      "\83\8c\83x\83\8b", IDC_BUTTON_VERBOSITY, 4, 180, 50, 16, BS_CENTER, WS_EX_CLIENTEDGE\r
     EDITTEXT        IDC_EDIT_VERBOSITY, 55, 180, 20, 16, ES_OEMCONVERT\r
     PUSHBUTTON      "<<", IDC_BUTTON_DEC, 80, 180, 12, 16, BS_CENTER\r
@@ -154,13 +211,20 @@ FONT 9, "MS UI Gothic", 400, 0, 128
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_CONSOLE_EN DIALOGEX 0, 0, 250, 200\r
 STYLE DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
+EXSTYLE WS_EX_ACCEPTFILES\r
 CAPTION "Console Window (TiMidity++ Win32GUI)"\r
 FONT 8, "Tahoma", 400, 0, 0\r
 {\r
+#ifdef TIMW32G_USE_NEW_CONSOLE\r
+       CONTROL         "", IDC_EDIT, "TimW32gNewConsole", 0, 0, 250, 175, WS_HSCROLL | WS_VSCROLL\r
+#else\r
     EDITTEXT        IDC_EDIT, 0, 0, 250, 175, WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_NOHIDESEL | ES_READONLY | ES_WANTRETURN, WS_EX_STATICEDGE\r
+#endif\r
     PUSHBUTTON      "VERBOSITY", IDC_BUTTON_VERBOSITY, 4, 180, 50, 16, BS_CENTER, WS_EX_CLIENTEDGE\r
     EDITTEXT        IDC_EDIT_VERBOSITY, 55, 180, 21, 16, ES_OEMCONVERT\r
     PUSHBUTTON      "<<", IDC_BUTTON_DEC, 80, 180, 15, 16, BS_CENTER\r
@@ -171,7 +235,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_DEBUG DIALOG 0, 0, 309, 239\r
 STYLE DS_SETFONT | WS_CAPTION | WS_SYSMENU\r
 CAPTION "Debug Window (TiMidity++ Win32GUI)"\r
@@ -201,7 +267,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_DOC DIALOGEX 0, 0, 300, 251\r
 STYLE DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES\r
@@ -217,7 +285,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_DOC_EN DIALOGEX 0, 0, 350, 232\r
 STYLE DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES\r
@@ -233,7 +303,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_FLAC DIALOG 0, 0, 125, 94\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "FLAC \90Ý\92è\83_\83C\83A\83\8d\83O"\r
@@ -250,7 +322,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_FLAC_EN DIALOG 0, 0, 125, 94\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "FLAC Setting"\r
@@ -267,7 +341,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_GOGO DIALOG 0, 0, 320, 204\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "MP3(\8cß\8cã\82Ì\82±\81`\82¾) \90Ý\92è\83_\83C\83A\83\8d\83O"\r
@@ -323,7 +399,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_GOGO_EN DIALOG 0, 0, 346, 199\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "MP3 (gogo) Configuration"\r
@@ -379,7 +457,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_ISEDITOR DIALOG 0, 0, 750, 550\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "\93à\91 \83V\83\93\83Z\83G\83f\83B\83^"\r
@@ -393,7 +473,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_ISEDITOR_EN DIALOG 0, 0, 750, 550\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Internal Synth Editor"\r
@@ -407,7 +489,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_LAME DIALOGEX 0, 0, 120, 44\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Lame Setting"\r
@@ -420,7 +504,9 @@ FONT 8, "Tahoma", 400, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_MAIN DIALOGEX 0, 0, 305, 60\r
 STYLE DS_SETFONT | WS_CAPTION | WS_VISIBLE | WS_CLIPCHILDREN | WS_GROUP | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW\r
@@ -438,7 +524,9 @@ FONT 8, "MS Sans Serif", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_MAIN_EN DIALOGEX 0, 0, 305, 60\r
 STYLE DS_SETFONT | WS_CAPTION | WS_VISIBLE | WS_CLIPCHILDREN | WS_GROUP | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES | WS_EX_APPWINDOW\r
@@ -456,7 +544,9 @@ FONT 8, "MS Sans Serif", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_ONE_LINE DIALOGEX 0, 0, 187, 74\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -471,7 +561,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_ONE_LINE_EN DIALOGEX 0, 0, 187, 67\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 FONT 8, "Tahoma", 400, 0, 0\r
@@ -486,7 +578,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_PLAYLIST DIALOGEX 0, 0, 200, 150\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES | WS_EX_CONTROLPARENT\r
@@ -504,7 +598,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_PLAYLIST_EN DIALOGEX 0, 0, 200, 150\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES | WS_EX_CONTROLPARENT\r
@@ -522,7 +618,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_PORTAUDIO DIALOGEX 0, 0, 271, 230\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "PortAudio Config"\r
@@ -556,7 +654,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_PREF DIALOG 0, 0, 364, 350\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "TiMidity++ Win32GUI \8fÚ\8d×\90Ý\92è"\r
@@ -574,7 +674,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_PREF_EN DIALOG 0, 0, 364, 350\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "TiMidity++ Win32GUI Preference"\r
@@ -592,7 +694,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_RIFFWAVE DIALOG 0, 0, 165, 65\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "RIFF WAVE \90Ý\92è\83_\83C\83A\83\8d\83O"\r
@@ -607,7 +711,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_RIFFWAVE_EN DIALOG 0, 0, 165, 65\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "RIFF WAVE Setting"\r
@@ -622,7 +728,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_SEARCHBOX DIALOG 0, 0, 183, 54\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Seach"\r
@@ -635,7 +743,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_SIMPLE_LIST DIALOGEX 0, 0, 200, 150\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES | WS_EX_CONTROLPARENT\r
@@ -653,7 +763,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_SIMPLE_LIST_EN DIALOGEX 0, 0, 200, 150\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES | WS_EX_CONTROLPARENT\r
@@ -671,7 +783,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_SOUNDSPEC DIALOG 0, 0, 192, 144\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES\r
@@ -682,7 +796,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_SOUNDSPEC_EN DIALOG 0, 0, 192, 144\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES\r
@@ -693,7 +809,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_TRACER DIALOGEX 0, 0, 335, 221\r
 STYLE DS_CONTEXTHELP | DS_SETFONT | WS_CAPTION | WS_THICKFRAME | WS_SYSMENU\r
 EXSTYLE WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES\r
@@ -716,7 +834,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_VORBIS DIALOG 0, 0, 195, 104\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Ogg Vorbis \90Ý\92è\83_\83C\83A\83\8d\83O"\r
@@ -739,7 +859,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_VORBIS_EN DIALOG 0, 0, 225, 102\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Ogg Vorbis Configurations"\r
@@ -761,8 +883,9 @@ FONT 8, "Tahoma"
 }\r
 \r
 \r
-\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_WASAPI DIALOGEX 0, 0, 215, 220\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "WASAPI Config"\r
@@ -799,8 +922,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 }\r
 \r
 \r
-\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_WAVEFORM DIALOGEX 0, 0, 240, 120\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_VISIBLE\r
 FONT 9, "Times New Roman", 400, 0, 1\r
@@ -809,7 +933,9 @@ FONT 9, "Times New Roman", 400, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_WDMKS DIALOGEX 0, 0, 215, 255\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "WDM Kernel Streaming Config"\r
@@ -857,8 +983,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 }\r
 \r
 \r
-\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_DIALOG_WMME DIALOGEX 0, 0, 235, 85\r
 STYLE DS_MODALFRAME | DS_SETFONT | WS_CAPTION | WS_POPUP | WS_SYSMENU\r
 CAPTION "Windows Audio Driver Config"\r
@@ -880,7 +1007,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_DIALOG_WRD DIALOGEX 0, 0, 366, 215\r
 STYLE DS_SETFONT | WS_CAPTION | WS_SYSMENU\r
 EXSTYLE WS_EX_ACCEPTFILES\r
@@ -891,7 +1020,9 @@ FONT 9, "Times New Roman", 400, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_ISEDITOR_MMS DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -1394,7 +1525,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_ISEDITOR_MMS_EN DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -1897,7 +2030,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_ISEDITOR_SCC DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2036,7 +2171,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_ISEDITOR_SCC_DATA DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2153,7 +2290,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_ISEDITOR_SCC_DATA_EN DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -2270,7 +2409,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_ISEDITOR_SCC_EN DIALOGEX 0, 0, 730, 500\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -2409,7 +2550,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_CUSTOM1 DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2499,7 +2642,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_CUSTOM1_EN DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -2589,7 +2734,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_CUSTOM2 DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2669,7 +2816,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_CUSTOM2_EN DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -2749,7 +2898,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_INT_SYNTH DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2765,7 +2916,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_INT_SYNTH_EN DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -2781,7 +2934,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_PLAYER DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2843,7 +2998,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_PLAYER_EN DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 400, 0, 0\r
@@ -2905,7 +3062,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_SFINI1 DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -2990,7 +3149,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_SFINI1_EN DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -3075,7 +3236,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_SFINI2 DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -3147,7 +3310,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_SFINI2_EN DIALOGEX 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 0, 0, 1\r
@@ -3219,7 +3384,9 @@ FONT 8, "Tahoma", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_SYN1 DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic", 0, 0, 1\r
@@ -3268,7 +3435,9 @@ FONT 9, "MS UI Gothic", 0, 0, 1
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_SYN1_EN DIALOGEX 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma", 400, 0, 0\r
@@ -3317,7 +3486,9 @@ FONT 8, "Tahoma", 400, 0, 0
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_TIMIDITY1 DIALOG 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic"\r
@@ -3405,7 +3576,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_TIMIDITY1_EN DIALOG 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma"\r
@@ -3493,7 +3666,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_TIMIDITY2 DIALOG 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic"\r
@@ -3599,7 +3774,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_TIMIDITY2_EN DIALOG 0, 0, 350, 290\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma"\r
@@ -3705,7 +3882,9 @@ FONT 8, "Tahoma"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDD_PREF_TIMIDITY3 DIALOG 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 9, "MS UI Gothic"\r
@@ -3771,7 +3950,9 @@ FONT 9, "MS UI Gothic"
 \r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\r
+#endif\r
 IDD_PREF_TIMIDITY3_EN DIALOG 0, 0, 350, 280\r
 STYLE DS_CONTROL | DS_SETFONT | WS_CHILDWINDOW\r
 FONT 8, "Tahoma"\r
@@ -3840,7 +4021,9 @@ FONT 8, "Tahoma"
 //\r
 // String Table resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 STRINGTABLE\r
 {\r
     IDM_MHVERSION                 "Version information of TiMidity++."\r
@@ -3870,19 +4053,27 @@ STRINGTABLE
 //\r
 // Icon resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDI_ICON_PLAYLIST_PLAY ICON           "w32g_playlist_play.ico"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDI_ICON_SERVER_PAUSE ICON           "w32g_icon_gray.ico"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDI_ICON_SERVER_START ICON           "w32g_icon_normal.ico"\r
 \r
 \r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 IDI_ICON_TIMIDITY  ICON           "w32g_icon.ico"\r
 \r
 \r
@@ -3890,10 +4081,12 @@ IDI_ICON_TIMIDITY  ICON           "w32g_icon.ico"
 //\r
 // Version Information resources\r
 //\r
+#ifdef _MSC_VER\r
 LANGUAGE LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN\r
+#endif\r
 VS_VERSION_INFO VERSIONINFO\r
-    FILEVERSION     2,13,0,0\r
-    PRODUCTVERSION  2,13,0,0\r
+    FILEVERSION     TIMID_VERSION4_COMMA\r
+    PRODUCTVERSION  TIMID_VERSION4_COMMA\r
     FILEOS          VOS__WINDOWS32\r
     FILETYPE        VFT_APP\r
     FILESUBTYPE     VFT2_UNKNOWN\r
@@ -3906,15 +4099,22 @@ VS_VERSION_INFO VERSIONINFO
         {\r
             VALUE "Comments", "\0"\r
             VALUE "CompanyName", "\0"\r
-            VALUE "FileDescription", "timw32g\0"\r
-            VALUE "FileVersion", "2, 13, 0, 0\0"\r
+            VALUE "FileVersion", TIMID_VERSION_RESSTR\r
+#ifdef TWSYNG32\r
+            VALUE "FileDescription", "TiMidity++ Win32GUI Synthesizer\0"\r
+            VALUE "InternalName", "twsyng\0"\r
+            VALUE "OriginalFilename", "twsyng.exe\0"\r
+            VALUE "ProductName", "TiMidity++ Win32GUI Synthesizer Version\0"\r
+#else\r
+            VALUE "FileDescription", "TiMidity++ Win32GUI\0"\r
             VALUE "InternalName", "timw32g\0"\r
-            VALUE "LegalCopyright", "Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>\r\nCopyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>\0"\r
-            VALUE "LegalTrademarks", "\0"\r
             VALUE "OriginalFilename", "timw32g.exe\0"\r
-            VALUE "PrivateBuild", "\0"\r
             VALUE "ProductName", "TiMidity++ Win32GUI Version\0"\r
-            VALUE "ProductVersion", "2, 13, 0, 0\0"\r
+#endif\r
+            VALUE "LegalCopyright", "Copyright (C) 1999-2018 Masanao Izumo <mo@goice.co.jp>\r\nCopyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>\0"\r
+            VALUE "LegalTrademarks", "\0"\r
+            VALUE "PrivateBuild", "\0"\r
+            VALUE "ProductVersion", TIMID_VERSION\r
             VALUE "SpecialBuild", "\0"\r
         }\r
     }\r
index 9200a83..01f09f4 100644 (file)
@@ -145,6 +145,10 @@ void InitConsoleWnd(HWND hParentWnd)
        InitializeNewConsole();
 #endif
 
+#ifdef TIMW32G_USE_NEW_CONSOLE
+       InitializeNewConsole();
+#endif
+
        switch(PlayerLanguage){
        case LANGUAGE_ENGLISH:
                hConsoleWnd = CreateDialog
old mode 100755 (executable)
new mode 100644 (file)
index c6138d0..fd51359
@@ -23,7 +23,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #include <stdio.h>
 #ifdef HAVE_STDLIB_H
@@ -105,59 +105,7 @@ static w32g_syn_t w32g_syn;
 
 // \8ae\8eí\95Ï\90\94 (^^;;;
 HINSTANCE hInst = NULL;
-int PlayerLanguage = LANGUAGE_ENGLISH;
-int IniFileAutoSave = 1;
-char *IniFile;
-char *ConfigFile;
-char *PlaylistFile;
-char *PlaylistHistoryFile;
-char *MidiFileOpenDir;
-char *ConfigFileOpenDir;
-char *PlaylistFileOpenDir;
-int SecondMode = 0;
-BOOL PosSizeSave = TRUE;
-int DocMaxSize;
-char *DocFileExt;
-int AutoloadPlaylist = 0;
-int AutosavePlaylist = 0;
-int SeachDirRecursive = 0;
-int DocWndIndependent = 0;
-int DocWndAutoPopup = 0;
-int TraceGraphicFlag;
-int PlayerThreadPriority;
-int MidiPlayerThreadPriority;
-int MainThreadPriority;
-int GUIThreadPriority;
-int TracerThreadPriority;
-int WrdThreadPriority;
-int SubWindowMax = 6;
-int InitMinimizeFlag = 0;
-int main_panel_update_time = 10;
-int DebugWndStartFlag = 1;
-int ConsoleWndStartFlag = 0;
-int ListWndStartFlag = 0;
-int TracerWndStartFlag = 0;
-int DocWndStartFlag = 0;
-int WrdWndStartFlag = 0;
-int SoundSpecWndStartFlag = 0;
-int DebugWndFlag = 1;
-int ConsoleWndFlag = 1;
-int ListWndFlag = 1;
-int TracerWndFlag = 0;
-int DocWndFlag = 1;
-int WrdWndFlag = 0;
-int SoundSpecWndFlag = 0;
-int WrdGraphicFlag;
-int TraceGraphicFlag;
-///r
-int RestartTimidity = 0;
-int w32g_auto_output_mode = 0;
-char *w32g_output_dir = NULL;
-int playlist_max = 1;
-int playlist_max_ini = 1;
-int ConsoleClearFlag = 0;
-int opt_use_twsyn_bridge = 0;
-int w32g_lock_open_file = 0;
+extern int RestartTimidity;
 
 extern void CmdLineToArgv(LPSTR lpCmdLine, int *argc, CHAR ***argv);
 
@@ -1620,95 +1568,6 @@ int w32g_syn_do_after_pref_save_restart(void)
 // ****************************************************************************
 // Edit Ctl.
 
-void VprintfEditCtlWnd(HWND hwnd, const char *fmt, va_list argList)
-{
-        char buffer[BUFSIZ], out[BUFSIZ];
-        char *in;
-        int i;
-
-        if (!IsWindow(hwnd))
-                 return;
-
-        vsnprintf(buffer, sizeof(buffer), fmt, argList);
-        in = buffer;
-        i = 0;
-        for (;;) {
-                 if (*in == '\0' || i > sizeof(out) - 3) {
-                               out[i] = '\0';
-                               break;
-                 }
-                 if (*in == '\n') {
-                               out[i] = 13;
-                               out[i + 1] = 10;
-                               in++;
-                               i += 2;
-                               continue;
-                 }
-                 out[i] = *in;
-                 in++;
-                 i++;
-        }
-        Edit_SetSel(hwnd, -1, -1);
-        Edit_ReplaceSel(hwnd, out);
-}
-
-void PrintfEditCtlWnd(HWND hwnd, const char *fmt, ...)
-{
-    va_list ap;
-    va_start(ap, fmt);
-    VprintfEditCtlWnd(hwnd, fmt, ap);
-    va_end(ap);
-}
-
-#if 1
-void PutsEditCtlWnd(HWND hwnd, char *str)
-{
-       char *in = str;
-       int i;
-       char out[BUFSIZ];
-       i = 0;
-       for (;;) {
-               if (*in == '\0' || i > sizeof(out) - 3) {
-                       out[i] = '\0';
-                       break;
-               }
-               if (*in == '\n') {
-                       out[i] = 13;
-                       out[i + 1] = 10;
-                       in++;
-                       i += 2;
-                       continue;
-               }
-               out[i] = *in;
-               in++;
-               i++;
-       }
-       if (IsWindow(hwnd)) {
-               Edit_SetSel(hwnd, -1, -1);
-               Edit_ReplaceSel(hwnd, out);
-       }
-}
-#else
-void PutsEditCtlWnd(HWND hwnd, char *str)
-{
-       if (!IsWindow(hwnd))
-               return;
-       PrintfEditCtlWnd(hwnd, "%s", str);
-}
-#endif
-
-void ClearEditCtlWnd(HWND hwnd)
-{
-       char pszVoid[] = "";
-       if (!IsWindow(hwnd))
-               return;
-       if (IsWindow(hwnd)) {
-//             Edit_SetSel(hwnd, 0, -1);
-               Edit_SetSel(hwnd, -1, -1);
-       }
-       Edit_SetText(hwnd, pszVoid);
-}
-
 static void VersionWnd(HWND hParentWnd)
 {
        char VersionText[2024];
@@ -1776,7 +1635,7 @@ static void ConsoleWndVerbosityUpdate(void);
 static void ConsoleWndVerbosityApply(void);
 static void ConsoleWndValidUpdate(void);
 static void ConsoleWndValidApply(void);
-static void ConsoleWndVerbosityApplyIncDec(int num);
+static void ConsoleWndVerbosityApplySet(int num);
 static int ConsoleWndInfoReset(HWND hwnd);
 static int ConsoleWndInfoApply(void);
 
@@ -1785,36 +1644,6 @@ void ClearConsoleWnd(void);
 // ---------------------------------------------------------------------------
 // Global Functions
 
-// Initialization
-void InitConsoleWnd(HWND hParentWnd)
-{
-       HICON hIcon;
-       if (hConsoleWnd) {
-               DestroyWindow(hConsoleWnd);
-               hConsoleWnd = NULL;
-       }
-       switch (PlayerLanguage) {
-       case LANGUAGE_ENGLISH:
-               hConsoleWnd = CreateDialog
-                       (hInst, MAKEINTRESOURCE(IDD_DIALOG_CONSOLE_EN), hParentWnd, ConsoleWndProc);
-               break;
-       default:
-       case LANGUAGE_JAPANESE:
-               hConsoleWnd = CreateDialog
-                       (hInst, MAKEINTRESOURCE(IDD_DIALOG_CONSOLE), hParentWnd, ConsoleWndProc);
-       break;
-       }
-       hIcon = LoadImage(hInst, MAKEINTRESOURCE(IDI_ICON_TIMIDITY), IMAGE_ICON, 16, 16, 0);
-       if (hIcon)
-               SendMessage(hConsoleWnd, WM_SETICON, FALSE, (LPARAM)hIcon);
-       ShowWindow(hConsoleWnd, ConsoleWndStartFlag ? SW_SHOW : SW_HIDE);
-       UpdateWindow(hConsoleWnd);
-
-       ConsoleWndVerbosityApplyIncDec(0);
-       CheckDlgButton(hConsoleWnd, IDC_CHECKBOX_VALID, ConsoleWndFlag);
-       Edit_LimitText(GetDlgItem(hConsoleWnd, IDC_EDIT), ConsoleWndMaxSize);
-}
-
 // Window Procedure
 static LRESULT CALLBACK
 ConsoleWndProc(HWND hwnd, UINT uMess, WPARAM wParam, LPARAM lParam)
@@ -1839,10 +1668,18 @@ ConsoleWndProc(HWND hwnd, UINT uMess, WPARAM wParam, LPARAM lParam)
                        ConsoleWndVerbosityApply();
                        break;
                case IDC_BUTTON_INC:
-                       ConsoleWndVerbosityApplyIncDec(1);
+                       {
+                               int n = (int)GetDlgItemInt(hwnd, IDC_EDIT_VERBOSITY, NULL, TRUE);
+                               n++;
+                               ConsoleWndVerbosityApplySet(n);
+                       }
                        break;
                case IDC_BUTTON_DEC:
-                       ConsoleWndVerbosityApplyIncDec(-1);
+                       {
+                               int n = (int)GetDlgItemInt(hwnd, IDC_EDIT_VERBOSITY, NULL, TRUE);
+                               n--;
+                               ConsoleWndVerbosityApplySet(n);
+                       }
                        break;
                default:
                        break;
@@ -1977,39 +1814,6 @@ ConsoleWndProc(HWND hwnd, UINT uMess, WPARAM wParam, LPARAM lParam)
        return FALSE;
 }
 
-// puts()
-void PutsConsoleWnd(char *str)
-{
-       HWND hwnd;
-       if (!IsWindow(hConsoleWnd) || !ConsoleWndFlag)
-               return;
-       hwnd = GetDlgItem(hConsoleWnd, IDC_EDIT);
-       PutsEditCtlWnd(hwnd, str);
-}
-
-// printf()
-void PrintfConsoleWnd(const char *fmt, ...)
-{
-       HWND hwnd;
-       va_list ap;
-       if (!IsWindow(hConsoleWnd) || !ConsoleWndFlag)
-               return;
-       hwnd = GetDlgItem(hConsoleWnd, IDC_EDIT);
-       va_start(ap, fmt);
-       VprintfEditCtlWnd(hwnd, fmt, ap);
-       va_end(ap);
-}
-
-// Clear
-void ClearConsoleWnd(void)
-{
-       HWND hwnd;
-       if (!IsWindow(hConsoleWnd))
-               return;
-       hwnd = GetDlgItem(hConsoleWnd, IDC_EDIT);
-       ClearEditCtlWnd(hwnd);
-}
-
 // ---------------------------------------------------------------------------
 // Static Functions
 
@@ -2053,10 +1857,10 @@ static void ConsoleWndVerbosityApply(void)
        ConsoleWndVerbosityUpdate();
 }
 
-static void ConsoleWndVerbosityApplyIncDec(int num)
+static void ConsoleWndVerbosityApplySet(int num)
 {
        if (!IsWindow(hConsoleWnd)) return;
-       ctl->verbosity += num;
+       ctl->verbosity = num;
        RANGE(ctl->verbosity, -1, 4);
        ConsoleWndVerbosityUpdate();
 }
@@ -2124,105 +1928,6 @@ extern void UpdateSpectrogramCanvas(void);
 // ---------------------------------------------------------------------------
 // Global Functions
 
-// Initialization
-// Global Functions
-void InitSoundSpecWnd(HWND hParentWnd)
-{
-       HICON hIcon;
-       if (hSoundSpecWnd) {
-               DestroyWindow(hSoundSpecWnd);
-               hSoundSpecWnd = NULL;
-       }
-       switch (PlayerLanguage) {
-       case LANGUAGE_JAPANESE:
-               hSoundSpecWnd = CreateDialog
-                       (hInst, MAKEINTRESOURCE(IDD_DIALOG_SOUNDSPEC), hParentWnd, SoundSpecWndProc);
-               break;
-       case LANGUAGE_ENGLISH:
-       default:
-               hSoundSpecWnd = CreateDialog
-                       (hInst, MAKEINTRESOURCE(IDD_DIALOG_SOUNDSPEC_EN), hParentWnd, SoundSpecWndProc);
-               break;
-       }
-       hIcon = LoadImage(hInst, MAKEINTRESOURCE(IDI_ICON_TIMIDITY), IMAGE_ICON, 16, 16, 0);
-       if (hIcon)
-               SendMessage(hSoundSpecWnd, WM_SETICON, FALSE, (LPARAM)hIcon);
-       ShowWindow(hSoundSpecWnd, SoundSpecWndStartFlag ? SW_SHOW : SW_HIDE);
-       UpdateWindow(hSoundSpecWnd);
-}
-
-LRESULT CALLBACK
-SoundSpecWndProc(HWND hwnd, UINT uMess, WPARAM wParam, LPARAM lParam)
-{
-       switch (uMess) {
-       case WM_INITDIALOG:
-#ifdef SUPPORT_SOUNDSPEC
-               open_soundspec();
-               TargetSpectrogramCanvas(hwnd);
-               soundspec_update_wave(NULL, 0);
-#endif /* SUPPORT_SOUNDSPEC */
-               return FALSE;
-       case WM_COMMAND:
-               switch (LOWORD(wParam)) {
-               case IDCLOSE:
-                       ShowWindow(hwnd, SW_HIDE);
-                       break;
-               default:
-                       return FALSE;
-               }
-               break;
-       case WM_ERASEBKGND:
-               return 0;
-       case WM_PAINT:
-#ifdef SUPPORT_SOUNDSPEC
-               UpdateSpectrogramCanvas();
-#endif /* SUPPORT_SOUNDSPEC */
-               break;
-       case WM_SIZE:
-               InvalidateRect(hwnd, NULL, FALSE);
-               return FALSE;
-       case WM_MOVE:
-               return FALSE;
-       case WM_DESTROY:
-#ifdef SUPPORT_SOUNDSPEC
-               close_soundspec();
-#endif /* SUPPORT_SOUNDSPEC */
-               break;
-       case WM_CLOSE:
-               ShowWindow(hSoundSpecWnd, SW_HIDE);
-               break;
-       case WM_CHAR:
-               break;
-       case WM_SYSKEYDOWN:
-       case WM_KEYDOWN:
-       {
-               int nVirtKey = (int)wParam;
-               short nModifiers = (int)lParam & 0xFFFF;
-               switch (nVirtKey) {
-                       case VK_ESCAPE:
-                               SendMessage(hwnd, WM_CLOSE, 0, 0);
-                               break;
-                       default:
-#ifdef SUPPORT_SOUNDSPEC
-                               HandleSpecKeydownEvent(nVirtKey, nModifiers);
-#endif /* SUPPORT_SOUNDSPEC */
-                               break;
-               }
-       }
-               break;
-       case WM_GETMINMAXINFO:
-       {
-               LPMINMAXINFO lpmmi = (LPMINMAXINFO) lParam;
-               lpmmi->ptMinTrackSize.x = max(192, lpmmi->ptMinTrackSize.x);
-               lpmmi->ptMinTrackSize.y = max(100, lpmmi->ptMinTrackSize.y);
-       }
-               return 0;
-       default:
-               return FALSE;
-       }
-       return FALSE;
-}
-
 // ---------------------------------------------------------------------------
 // Static Functions
 
index 654cb0e..0b6a179 100644 (file)
@@ -25,7 +25,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef HAVE_STDLIB_H
 #include <stdlib.h>
@@ -78,6 +78,7 @@
 #include "thread.h"
 #include "miditrace.h"
 #include "rtsyn.h"
+
 ///r
 extern int opt_default_mid;
 extern int effect_lr_mode;
@@ -1860,7 +1861,6 @@ char **FilesExpandDir(int *p_nfiles, char **files)
 
 }
 
-#ifndef IA_W32G_SYN
 int w32gLoadDefaultPlaylist(void)
 {
        int i;
@@ -1904,7 +1904,6 @@ int w32gSaveDefaultPlaylist(void)
        }
        return 0;
 }
-#endif
 
 static char *get_filename(char *src, char *dest)
 {
diff --git a/interface/w32g_visualstyle.manifest b/interface/w32g_visualstyle.manifest
deleted file mode 100644 (file)
index 635b789..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
-  <dependency>
-    <dependentAssembly>
-      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity>
-    </dependentAssembly>
-  </dependency>
-</assembly>
index fb74f55..1dbb82e 100644 (file)
@@ -4590,7 +4590,7 @@ get_user_home_dir(void) {
   return p;
 }
 
-#include "interface.h"
+
 #if defined(IA_MOTIF)
 /*
  * Switch -lXm's vendorShellWidgetClass to -lXaw's vendorShellWidgetClass
index 9d73005..5b8cf10 100644 (file)
@@ -3,7 +3,7 @@
 extern "C"{
 ///r
 #include "config.h"
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 #include "instrum.h"
diff --git a/lame/CMakeLists.txt b/lame/CMakeLists.txt
new file mode 100644 (file)
index 0000000..2285376
--- /dev/null
@@ -0,0 +1,77 @@
+
+add_definitions(
+    -DHAVE_CONFIG_H
+    -DLAME_LIBRARY_BUILD
+    -DHAVE_XMMINTRIN_H
+    -DSTDC_HEADERS
+    -DHAVE_ERRNO_H
+    -DHAVE_FCNTL_H
+    -DHAVE_LIMITS_H
+    -DPACKAGE="lame"
+    -DPROTOTYPES
+    -DUSE_FAST_LOG
+    -DHAVE_STRCHR
+    -DHAVE_MEMCPY
+)
+
+include_directories(.)
+
+add_library(
+    lame_enc SHARED
+
+    config.h
+
+    Dll/BladeMP3EncDLL.c
+    Dll/BladeMP3EncDLL.h
+
+    include/lame.h
+
+    libmp3lame/bitstream.c
+    libmp3lame/bitstream.h
+    libmp3lame/encoder.c
+    libmp3lame/encoder.h
+    libmp3lame/fft.c
+    libmp3lame/fft.h
+    libmp3lame/gain_analysis.c
+    libmp3lame/gain_analysis.h
+    libmp3lame/id3tag.c
+    libmp3lame/id3tag.h
+    libmp3lame/l3side.h
+    libmp3lame/lame-analysis.h
+    libmp3lame/lame.c
+    libmp3lame/lameerror.h
+    libmp3lame/lame_global_flags.h
+    libmp3lame/machine.h
+    libmp3lame/mpglib_interface.c
+    libmp3lame/newmdct.c
+    libmp3lame/newmdct.h
+    libmp3lame/presets.c
+    libmp3lame/psymodel.c
+    libmp3lame/psymodel.h
+    libmp3lame/quantize.c
+    libmp3lame/quantize.h
+    libmp3lame/quantize_pvt.c
+    libmp3lame/quantize_pvt.h
+    libmp3lame/reservoir.c
+    libmp3lame/reservoir.h
+    libmp3lame/set_get.c
+    libmp3lame/set_get.h
+    libmp3lame/tables.c
+    libmp3lame/tables.h
+    libmp3lame/takehiro.c
+    libmp3lame/util.c
+    libmp3lame/util.h
+    libmp3lame/vbrquantize.c
+    libmp3lame/vbrquantize.h
+    libmp3lame/VbrTag.c
+    libmp3lame/VbrTag.h
+    libmp3lame/version.c
+    libmp3lame/version.h
+    libmp3lame/vector/lame_intrin.h
+    libmp3lame/vector/xmm_quantize_sub.c
+
+    Dll/BladeMP3EncDLL.def
+    libmp3lame/lame.rc
+)
+
+set_target_properties(lame_enc PROPERTIES PREFIX "")
diff --git a/lame/COPYING b/lame/COPYING
new file mode 100644 (file)
index 0000000..f503049
--- /dev/null
@@ -0,0 +1,481 @@
+                 GNU LIBRARY GENERAL PUBLIC LICENSE
+                      Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+                   59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL.  It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it.  You can use it for
+your libraries, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library.  If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+\f
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software.  To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+  Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs.  This
+license, the GNU Library General Public License, applies to certain
+designated libraries.  This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+  The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it.  Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program.  However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+  Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries.  We
+concluded that weaker conditions might promote sharing better.
+
+  However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves.  This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them.  (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.)  The hope is that this
+will lead to faster development of free libraries.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+  Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+\f
+                 GNU LIBRARY GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License").  Each licensee is
+addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    c) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    d) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                           NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/lame/Dll/BladeMP3EncDLL.c b/lame/Dll/BladeMP3EncDLL.c
new file mode 100644 (file)
index 0000000..5889a8f
--- /dev/null
@@ -0,0 +1,1029 @@
+/*
+*      Blade DLL Interface for LAME.
+*
+*      Copyright (c) 1999 - 2002 A.L. Faber
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU Library General Public
+* License as published by the Free Software Foundation; either
+* version 2 of the License, or (at your option) any later version.
+* 
+* This library is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+* Library General Public License for more details.
+* 
+* You should have received a copy of the GNU Library General Public
+* License along with this library; if not, write to the
+* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+* Boston, MA  02111-1307, USA.
+*/
+
+#include <windows.h>
+#include <Windef.h>
+#include "BladeMP3EncDLL.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <lame.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define         Min(A, B)       ((A) < (B) ? (A) : (B))
+#define         Max(A, B)       ((A) > (B) ? (A) : (B))
+
+#define _RELEASEDEBUG 0
+
+// lame_enc DLL version number
+const BYTE MAJORVERSION = 1;
+const BYTE MINORVERSION = 32;
+
+
+// Local variables
+static DWORD                           dwSampleBufferSize=0;
+static HMODULE                         gs_hModule=NULL;
+static BOOL                                    gs_bLogFile=FALSE;
+static lame_global_flags*      gfp_save = NULL;
+
+// Local function prototypes
+static void dump_config(       lame_global_flags*      gfp );
+static void DebugPrintf( const char* pzFormat, ... );
+static void DispErr( char const* strErr );
+static void PresetOptions( lame_global_flags *gfp, LONG myPreset );
+
+
+static void DebugPrintf(const char* pzFormat, ...)
+{
+    char       szBuffer[1024]={'\0',};
+    char       szFileName[MAX_PATH+1]={'\0',};
+    va_list ap;
+
+    // Get the full module (DLL) file name
+    GetModuleFileNameA(        gs_hModule, 
+        szFileName,
+        sizeof( szFileName ) );
+
+    // change file name extention
+    szFileName[ strlen(szFileName) - 3 ] = 't';
+    szFileName[ strlen(szFileName) - 2 ] = 'x';
+    szFileName[ strlen(szFileName) - 1 ] = 't';
+
+    // start at beginning of the list
+    va_start(ap, pzFormat);
+
+    // copy it to the string buffer
+    _vsnprintf(szBuffer, sizeof(szBuffer), pzFormat, ap);
+
+    // log it to the file?
+    if ( gs_bLogFile ) 
+    {  
+        FILE* fp = NULL;
+
+        // try to open the log file
+        fp=fopen( szFileName, "a+" );
+
+        // check file open result
+        if (fp)
+        {
+            // write string to the file
+            fputs(szBuffer,fp);
+
+            // close the file
+            fclose(fp);
+        }
+    }
+
+#if defined _DEBUG || defined _RELEASEDEBUG
+    OutputDebugStringA( szBuffer );
+#endif
+
+    va_end(ap);
+}
+
+
+static void PresetOptions( lame_global_flags *gfp, LONG myPreset )
+{
+    switch (myPreset)
+    {
+        /*-1*/case LQP_NOPRESET:
+            break;
+
+        /*0*/case LQP_NORMAL_QUALITY:
+            /* lame_set_quality( gfp, 5 );*/
+            break;
+
+        /*1*/case LQP_LOW_QUALITY:
+             lame_set_quality( gfp, 9 );
+             break;
+
+        /*2*/case LQP_HIGH_QUALITY:
+             lame_set_quality( gfp, 2 );
+             break;
+
+        /*3*/case LQP_VOICE_QUALITY:                           // --voice flag for experimental voice mode
+             lame_set_mode( gfp, MONO );
+             lame_set_preset( gfp, 56);
+             break;
+
+        /*4*/case LQP_R3MIX:                                   // --R3MIX
+             lame_set_preset( gfp, R3MIX);
+             break;
+
+        /*5*/case LQP_VERYHIGH_QUALITY:
+             lame_set_quality( gfp, 0 );
+             break;
+
+        /*6*/case LQP_STANDARD:                                // --PRESET STANDARD
+            lame_set_preset( gfp, STANDARD);
+            break;
+
+        /*7*/case LQP_FAST_STANDARD:                           // --PRESET FAST STANDARD
+            lame_set_preset( gfp, STANDARD_FAST);
+            break;
+
+        /*8*/case LQP_EXTREME:                         // --PRESET EXTREME
+            lame_set_preset( gfp, EXTREME);
+            break;
+
+        /*9*/case LQP_FAST_EXTREME:                            // --PRESET FAST EXTREME:
+            lame_set_preset( gfp, EXTREME_FAST);
+            break;
+
+        /*10*/case LQP_INSANE:                         // --PRESET INSANE
+            lame_set_preset( gfp, INSANE);
+            break;
+
+        /*11*/case LQP_ABR:                                    // --PRESET ABR
+            // handled in beInitStream
+            break;
+
+        /*12*/case LQP_CBR:                                    // --PRESET CBR
+            // handled in beInitStream
+            break;
+
+        /*13*/case LQP_MEDIUM:                                 // --PRESET MEDIUM
+            lame_set_preset( gfp, MEDIUM);
+            break;
+
+        /*14*/case LQP_FAST_MEDIUM:                                    // --PRESET FAST MEDIUM
+            lame_set_preset( gfp, MEDIUM_FAST);
+            break;
+
+        /*1000*/case LQP_PHONE:
+            lame_set_mode( gfp, MONO );
+            lame_set_preset( gfp, 16);
+            break;
+
+        /*2000*/case LQP_SW:
+            lame_set_mode( gfp, MONO );
+            lame_set_preset( gfp, 24);
+            break;
+
+        /*3000*/case LQP_AM:
+            lame_set_mode( gfp, MONO );
+            lame_set_preset( gfp, 40);
+            break;
+
+        /*4000*/case LQP_FM:
+            lame_set_preset( gfp, 112);
+            break;
+
+        /*5000*/case LQP_VOICE:
+            lame_set_mode( gfp, MONO );
+            lame_set_preset( gfp, 56);
+            break;
+
+        /*6000*/case LQP_RADIO:
+            lame_set_preset( gfp, 112);
+            break;
+
+        /*7000*/case LQP_TAPE:
+            lame_set_preset( gfp, 112);
+            break;
+
+        /*8000*/case LQP_HIFI:
+            lame_set_preset( gfp, 160);
+            break;
+
+        /*9000*/case LQP_CD:
+            lame_set_preset( gfp, 192);
+            break;
+
+        /*10000*/case LQP_STUDIO:
+            lame_set_preset( gfp, 256);
+            break;
+
+    }
+}
+
+
+__declspec(dllexport) BE_ERR   beInitStream(PBE_CONFIG pbeConfig, PDWORD dwSamples, PDWORD dwBufferSize, PHBE_STREAM phbeStream)
+{
+    int actual_bitrate;
+    //2001-12-18
+    BE_CONFIG                  lameConfig = { 0, };
+    int                                        nInitReturn = 0;
+    lame_global_flags* gfp = NULL;
+
+    // Init the global flags structure
+    gfp = lame_init();
+    *phbeStream = (HBE_STREAM)gfp;
+
+    // clear out structure
+    memset(&lameConfig,0x00,CURRENT_STRUCT_SIZE);
+
+    // Check if this is a regular BLADE_ENCODER header
+    if (pbeConfig->dwConfig!=BE_CONFIG_LAME)
+    {
+        int nCRC=pbeConfig->format.mp3.bCRC;
+        int nVBR=(nCRC>>12)&0x0F;
+
+        // Copy parameter from old Blade structure
+        lameConfig.format.LHV1.dwSampleRate    =pbeConfig->format.mp3.dwSampleRate;
+        //for low bitrates, LAME will automatically downsample for better
+        //sound quality.  Forcing output samplerate = input samplerate is not a good idea 
+        //unless the user specifically requests it:
+        //lameConfig.format.LHV1.dwReSampleRate=pbeConfig->format.mp3.dwSampleRate;
+        lameConfig.format.LHV1.nMode           =(pbeConfig->format.mp3.byMode&0x0F);
+        lameConfig.format.LHV1.dwBitrate       =pbeConfig->format.mp3.wBitrate;
+        lameConfig.format.LHV1.bPrivate                =pbeConfig->format.mp3.bPrivate;
+        lameConfig.format.LHV1.bOriginal       =pbeConfig->format.mp3.bOriginal;
+        lameConfig.format.LHV1.bCRC            =nCRC&0x01;
+        lameConfig.format.LHV1.bCopyright      =pbeConfig->format.mp3.bCopyright;
+
+        // Fill out the unknowns
+        lameConfig.format.LHV1.dwStructSize=CURRENT_STRUCT_SIZE;
+        lameConfig.format.LHV1.dwStructVersion=CURRENT_STRUCT_VERSION;
+
+        // Get VBR setting from fourth nibble
+        if ( nVBR>0 )
+        {
+            lameConfig.format.LHV1.bWriteVBRHeader = TRUE;
+            lameConfig.format.LHV1.bEnableVBR = TRUE;
+            lameConfig.format.LHV1.nVBRQuality = nVBR-1;
+        }
+
+        // Get Quality from third nibble
+        lameConfig.format.LHV1.nPreset=((nCRC>>8)&0x0F);
+
+    }
+    else
+    {
+        // Copy the parameters
+        memcpy(&lameConfig,pbeConfig,pbeConfig->format.LHV1.dwStructSize);
+    }
+
+    // --------------- Set arguments to LAME encoder -------------------------
+
+    // Set input sample frequency
+    lame_set_in_samplerate( gfp, lameConfig.format.LHV1.dwSampleRate );
+
+    // disable INFO/VBR tag by default.  
+    // if this tag is used, the calling program must call beWriteVBRTag()
+    // after encoding.  But the original DLL documentation does not 
+    // require the 
+    // app to call beWriteVBRTag() unless they have specifically
+    // set LHV1.bWriteVBRHeader=TRUE.  Thus the default setting should
+    // be disabled.  
+    lame_set_bWriteVbrTag( gfp, 0 );
+
+    //2001-12-18 Dibrom's ABR preset stuff
+
+    if(lameConfig.format.LHV1.nPreset == LQP_ABR)              // --ALT-PRESET ABR
+    {
+        actual_bitrate = lameConfig.format.LHV1.dwVbrAbr_bps / 1000;
+
+        // limit range
+        if( actual_bitrate > 320)
+        {
+            actual_bitrate = 320;
+        }
+
+        if( actual_bitrate < 8 )
+        {
+            actual_bitrate = 8;
+        }
+
+        lame_set_preset( gfp, actual_bitrate );
+    }    
+
+    // end Dibrom's ABR preset 2001-12-18 ****** START OF CBR
+
+    if(lameConfig.format.LHV1.nPreset == LQP_CBR)              // --ALT-PRESET CBR
+    {
+        actual_bitrate = lameConfig.format.LHV1.dwBitrate;
+        lame_set_preset(gfp, actual_bitrate);
+        lame_set_VBR(gfp, vbr_off);
+    }
+
+    // end Dibrom's CBR preset 2001-12-18
+
+    // The following settings only used when preset is not one of the LAME QUALITY Presets
+    if ( (int)lameConfig.format.LHV1.nPreset < (int) LQP_STANDARD )
+    {
+        switch ( lameConfig.format.LHV1.nMode )
+        {
+        case BE_MP3_MODE_STEREO:
+            lame_set_mode( gfp, STEREO );
+            lame_set_num_channels( gfp, 2 );
+            break;
+        case BE_MP3_MODE_JSTEREO:
+            lame_set_mode( gfp, JOINT_STEREO );
+            //lame_set_force_ms( gfp, bForceMS ); // no check box to force this?
+            lame_set_num_channels( gfp, 2 );
+            break;
+        case BE_MP3_MODE_MONO:
+            lame_set_mode( gfp, MONO );
+            lame_set_num_channels( gfp, 1 );
+            break;
+        case BE_MP3_MODE_DUALCHANNEL:
+            lame_set_mode( gfp, DUAL_CHANNEL );
+            lame_set_num_channels( gfp, 2 );
+            break;
+        default:
+            {
+                DebugPrintf("Invalid lameConfig.format.LHV1.nMode, value is %d\n",lameConfig.format.LHV1.nMode);
+                return BE_ERR_INVALID_FORMAT_PARAMETERS;
+            }
+        }
+
+        if ( lameConfig.format.LHV1.bEnableVBR )
+        {
+            /* set VBR quality */
+            lame_set_VBR_q( gfp, lameConfig.format.LHV1.nVBRQuality );
+
+            /* select proper VBR method */
+            switch ( lameConfig.format.LHV1.nVbrMethod)
+            {
+            case VBR_METHOD_NONE:
+                lame_set_VBR( gfp, vbr_off );
+                break;
+
+            case VBR_METHOD_DEFAULT:
+                lame_set_VBR( gfp, vbr_default ); 
+                break;
+
+            case VBR_METHOD_OLD:
+                lame_set_VBR( gfp, vbr_rh ); 
+                break;
+
+            case VBR_METHOD_MTRH:
+            case VBR_METHOD_NEW:
+                /*                                
+                * the --vbr-mtrh commandline switch is obsolete. 
+                * now --vbr-mtrh is known as --vbr-new
+                */
+                lame_set_VBR( gfp, vbr_mtrh ); 
+                break;
+
+            case VBR_METHOD_ABR:
+                lame_set_VBR( gfp, vbr_abr ); 
+                break;
+
+            default:
+                /* unsupported VBR method */
+                assert( FALSE );
+            }
+        }
+        else
+        {
+            /* use CBR encoding method, so turn off VBR */
+            lame_set_VBR( gfp, vbr_off );
+        }
+
+        /* Set bitrate.  (CDex users always specify bitrate=Min bitrate when using VBR) */
+        lame_set_brate( gfp, lameConfig.format.LHV1.dwBitrate );
+
+        /* check if we have to use ABR, in order to backwards compatible, this
+        * condition should still be checked indepedent of the nVbrMethod method
+        */
+        if (lameConfig.format.LHV1.dwVbrAbr_bps > 0 )
+        {
+            /* set VBR method to ABR */
+            lame_set_VBR( gfp, vbr_abr );
+
+            /* calculate to kbps, round to nearest kbps */
+            lame_set_VBR_mean_bitrate_kbps( gfp, ( lameConfig.format.LHV1.dwVbrAbr_bps + 500 ) / 1000 );
+
+            /* limit range */
+            if( lame_get_VBR_mean_bitrate_kbps( gfp ) > 320)
+            {
+                lame_set_VBR_mean_bitrate_kbps( gfp, 320 );
+            }
+
+            if( lame_get_VBR_mean_bitrate_kbps( gfp ) < 8 )
+            {
+                lame_set_VBR_mean_bitrate_kbps( gfp, 8 );
+            }
+        }
+
+    }
+
+    // First set all the preset options
+    if ( LQP_NOPRESET !=  lameConfig.format.LHV1.nPreset )
+    {
+        PresetOptions( gfp, lameConfig.format.LHV1.nPreset );
+    }
+
+
+    // Set frequency resampling rate, if specified
+    if ( lameConfig.format.LHV1.dwReSampleRate > 0 )
+    {
+        lame_set_out_samplerate( gfp, lameConfig.format.LHV1.dwReSampleRate );
+    }
+
+
+    switch ( lameConfig.format.LHV1.nMode )
+    {
+    case BE_MP3_MODE_MONO:
+        lame_set_mode( gfp, MONO );
+        lame_set_num_channels( gfp, 1 );
+        break;
+
+    default:
+        break;
+    }
+
+
+    // Use strict ISO encoding?
+    lame_set_strict_ISO( gfp, ( lameConfig.format.LHV1.bStrictIso ) ? 1 : 0 );
+
+    // Set copyright flag?
+    if ( lameConfig.format.LHV1.bCopyright )
+    {
+        lame_set_copyright( gfp, 1 );
+    }
+
+    // Do we have to tag  it as non original 
+    if ( !lameConfig.format.LHV1.bOriginal )
+    {
+        lame_set_original( gfp, 0 );
+    }
+    else
+    {
+        lame_set_original( gfp, 1 );
+    }
+
+    // Add CRC?
+    if ( lameConfig.format.LHV1.bCRC )
+    {
+        lame_set_error_protection( gfp, 1 );
+    }
+    else
+    {
+        lame_set_error_protection( gfp, 0 );
+    }
+
+    // Set private bit?
+    if ( lameConfig.format.LHV1.bPrivate )
+    {
+        lame_set_extension( gfp, 1 );
+    }
+    else
+    {
+        lame_set_extension( gfp, 0 );
+    }
+
+
+    // Set VBR min bitrate, if specified
+    if ( lameConfig.format.LHV1.dwBitrate > 0 )
+    {
+        lame_set_VBR_min_bitrate_kbps( gfp, lameConfig.format.LHV1.dwBitrate );
+    }
+
+    // Set Maxbitrate, if specified
+    if ( lameConfig.format.LHV1.dwMaxBitrate > 0 )
+    {
+        lame_set_VBR_max_bitrate_kbps( gfp, lameConfig.format.LHV1.dwMaxBitrate );
+    }
+    // Set bit resovoir option
+    if ( lameConfig.format.LHV1.bNoRes )
+    {
+        lame_set_disable_reservoir( gfp,1 );
+    }
+
+    // check if the VBR tag is required
+    if ( lameConfig.format.LHV1.bWriteVBRHeader ) 
+    {
+        lame_set_bWriteVbrTag( gfp, 1 );
+    }
+    else
+    {
+        lame_set_bWriteVbrTag( gfp, 0 );
+    }
+
+    // Override Quality setting, use HIGHBYTE = NOT LOWBYTE to be backwards compatible
+    if (       ( lameConfig.format.LHV1.nQuality & 0xFF ) ==
+        ((~( lameConfig.format.LHV1.nQuality >> 8 )) & 0xFF) )
+    {
+        lame_set_quality( gfp, lameConfig.format.LHV1.nQuality & 0xFF );
+    }
+
+    if ( 0 != ( nInitReturn = lame_init_params( gfp ) ) )
+    {
+        return nInitReturn;
+    }
+
+    //LAME encoding call will accept any number of samples.  
+    if ( 0 == lame_get_version( gfp ) )
+    {
+        // For MPEG-II, only 576 samples per frame per channel
+        *dwSamples= 576 * lame_get_num_channels( gfp );
+    }
+    else
+    {
+        // For MPEG-I, 1152 samples per frame per channel
+        *dwSamples= 1152 * lame_get_num_channels( gfp );
+    }
+
+    // Set the input sample buffer size, so we know what we can expect
+    dwSampleBufferSize = *dwSamples;
+
+    // Set MP3 buffer size, conservative estimate
+    *dwBufferSize=(DWORD)( 1.25 * ( *dwSamples / lame_get_num_channels( gfp ) ) + 7200 );
+
+    // For debugging purposes
+    dump_config( gfp );
+
+    // Everything went OK, thus return SUCCESSFUL
+    return BE_ERR_SUCCESSFUL;
+}
+
+
+
+__declspec(dllexport) BE_ERR   beFlushNoGap(HBE_STREAM hbeStream, PBYTE pOutput, PDWORD pdwOutput)
+{
+    int nOutputSamples = 0;
+
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    // Init the global flags structure
+    nOutputSamples = lame_encode_flush_nogap( gfp, pOutput, LAME_MAXMP3BUFFER );
+
+    if ( nOutputSamples < 0 )
+    {
+        *pdwOutput = 0;
+        return BE_ERR_BUFFER_TOO_SMALL;
+    }
+    else
+    {
+        *pdwOutput = nOutputSamples;
+    }
+
+    return BE_ERR_SUCCESSFUL;
+}
+
+__declspec(dllexport) BE_ERR   beDeinitStream(HBE_STREAM hbeStream, PBYTE pOutput, PDWORD pdwOutput)
+{
+    int nOutputSamples = 0;
+
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    nOutputSamples = lame_encode_flush( gfp, pOutput, 0 );
+
+    if ( nOutputSamples < 0 )
+    {
+        *pdwOutput = 0;
+        return BE_ERR_BUFFER_TOO_SMALL;
+    }
+    else
+    {
+        *pdwOutput = nOutputSamples;
+    }
+
+    return BE_ERR_SUCCESSFUL;
+}
+
+
+__declspec(dllexport) BE_ERR   beCloseStream(HBE_STREAM hbeStream)
+{
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    // lame will be close in VbrWriteTag function
+    if ( !lame_get_bWriteVbrTag( gfp ) )
+    {
+        // clean up of allocated memory
+        lame_close( gfp );
+
+        gfp_save = NULL;
+    }
+    else
+    {
+        gfp_save = (lame_global_flags*)hbeStream;
+    }
+
+    // DeInit encoder
+    return BE_ERR_SUCCESSFUL;
+}
+
+
+
+__declspec(dllexport) VOID             beVersion(PBE_VERSION pbeVersion)
+{
+    // DLL Release date
+    char lpszDate[20]  = { '\0', };
+    char lpszTemp[5]   = { '\0', };
+    lame_version_t lv   = { 0, };
+
+
+    // Set DLL interface version
+    pbeVersion->byDLLMajorVersion=MAJORVERSION;
+    pbeVersion->byDLLMinorVersion=MINORVERSION;
+
+    get_lame_version_numerical ( &lv );
+
+    // Set Engine version number (Same as Lame version)
+    pbeVersion->byMajorVersion = (BYTE)lv.major;
+    pbeVersion->byMinorVersion = (BYTE)lv.minor;
+    pbeVersion->byAlphaLevel   = (BYTE)lv.alpha;
+    pbeVersion->byBetaLevel    = (BYTE)lv.beta;
+
+#ifdef MMX_choose_table
+    pbeVersion->byMMXEnabled=1;
+#else
+    pbeVersion->byMMXEnabled=0;
+#endif
+
+    memset( pbeVersion->btReserved, 0, sizeof( pbeVersion->btReserved ) );
+
+    // Get compilation date
+    strcpy(lpszDate,__DATE__);
+
+    // Get the first three character, which is the month
+    strncpy(lpszTemp,lpszDate,3);
+    lpszTemp[3] = '\0';
+    pbeVersion->byMonth=1;
+
+    // Set month
+    if (strcmp(lpszTemp,"Jan")==0)     pbeVersion->byMonth = 1;
+    if (strcmp(lpszTemp,"Feb")==0)     pbeVersion->byMonth = 2;
+    if (strcmp(lpszTemp,"Mar")==0)     pbeVersion->byMonth = 3;
+    if (strcmp(lpszTemp,"Apr")==0)     pbeVersion->byMonth = 4;
+    if (strcmp(lpszTemp,"May")==0)     pbeVersion->byMonth = 5;
+    if (strcmp(lpszTemp,"Jun")==0)     pbeVersion->byMonth = 6;
+    if (strcmp(lpszTemp,"Jul")==0)     pbeVersion->byMonth = 7;
+    if (strcmp(lpszTemp,"Aug")==0)     pbeVersion->byMonth = 8;
+    if (strcmp(lpszTemp,"Sep")==0)     pbeVersion->byMonth = 9;
+    if (strcmp(lpszTemp,"Oct")==0)     pbeVersion->byMonth = 10;
+    if (strcmp(lpszTemp,"Nov")==0)     pbeVersion->byMonth = 11;
+    if (strcmp(lpszTemp,"Dec")==0)     pbeVersion->byMonth = 12;
+
+    // Get day of month string (char [4..5])
+    pbeVersion->byDay = (BYTE) atoi( lpszDate + 4 );
+
+    // Get year of compilation date (char [7..10])
+    pbeVersion->wYear = (WORD) atoi( lpszDate + 7 );
+
+    memset( pbeVersion->zHomepage, 0x00, BE_MAX_HOMEPAGE );
+
+    strcpy( pbeVersion->zHomepage, "http://www.mp3dev.org/" );
+}
+
+__declspec(dllexport) BE_ERR   beEncodeChunk(HBE_STREAM hbeStream, DWORD nSamples, 
+                                              PSHORT pSamples, PBYTE pOutput, PDWORD pdwOutput)
+{
+    // Encode it
+    int dwSamples;
+    int        nOutputSamples = 0;
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    dwSamples = nSamples / lame_get_num_channels( gfp );
+
+    // old versions of lame_enc.dll required exactly 1152 samples
+    // and worked even if nSamples accidently set to 2304 
+    // simulate this behavoir:
+    if ( 1 == lame_get_num_channels( gfp ) && nSamples == 2304)
+    {
+        dwSamples/= 2;
+    }
+
+
+    if ( 1 == lame_get_num_channels( gfp ) )
+    {
+        nOutputSamples = lame_encode_buffer(gfp,pSamples,pSamples,dwSamples,pOutput,0);
+    }
+    else
+    {
+        nOutputSamples = lame_encode_buffer_interleaved(gfp,pSamples,dwSamples,pOutput,0);
+    }
+
+
+    if ( nOutputSamples < 0 )
+    {
+        *pdwOutput=0;
+        return BE_ERR_BUFFER_TOO_SMALL;
+    }
+    else
+    {
+        *pdwOutput = (DWORD)nOutputSamples;
+    }
+
+    return BE_ERR_SUCCESSFUL;
+}
+
+
+// accept floating point audio samples, scaled to the range of a signed 16-bit
+//  integer (within +/- 32768), in non-interleaved channels  -- DSPguru, jd
+__declspec(dllexport) BE_ERR   beEncodeChunkFloatS16NI(HBE_STREAM hbeStream, DWORD nSamples, 
+                                                        PFLOAT buffer_l, PFLOAT buffer_r, PBYTE pOutput, PDWORD pdwOutput)
+{
+    int nOutputSamples;
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    nOutputSamples = lame_encode_buffer_float(gfp,buffer_l,buffer_r,nSamples,pOutput,0);
+
+    if ( nOutputSamples >= 0 )
+    {
+        *pdwOutput = (DWORD) nOutputSamples;
+    }
+    else
+    {
+        *pdwOutput=0;
+        return BE_ERR_BUFFER_TOO_SMALL;
+    }
+
+    return BE_ERR_SUCCESSFUL;
+}
+
+static int
+maybeSyncWord(FILE* fpStream)
+{
+    unsigned char mp3_frame_header[4];
+    size_t nbytes = fread(mp3_frame_header, 1, sizeof(mp3_frame_header), fpStream);
+    if ( nbytes != sizeof(mp3_frame_header) ) {
+        return -1;
+    }
+    if ( mp3_frame_header[0] != 0xffu ) {
+        return -1; /* doesn't look like a sync word */
+    }
+    if ( (mp3_frame_header[1] & 0xE0u) != 0xE0u ) {
+        return -1; /* doesn't look like a sync word */
+    }
+    return 0;
+}
+
+static int
+skipId3v2(FILE * fpStream, size_t lametag_frame_size)
+{
+    size_t  nbytes;
+    size_t  id3v2TagSize = 0;
+    unsigned char id3v2Header[10];
+
+    /* seek to the beginning of the stream */
+    if (fseek(fpStream, 0, SEEK_SET) != 0) {
+        return -2;  /* not seekable, abort */
+    }
+    /* read 10 bytes in case there's an ID3 version 2 header here */
+    nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
+    if (nbytes != sizeof(id3v2Header)) {
+        return -3;  /* not readable, maybe opened Write-Only */
+    }
+    /* does the stream begin with the ID3 version 2 file identifier? */
+    if (!strncmp((char *) id3v2Header, "ID3", 3)) {
+        /* the tag size (minus the 10-byte header) is encoded into four
+        * bytes where the most significant bit is clear in each byte
+        */
+        id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
+            | ((id3v2Header[7] & 0x7f) << 14)
+            | ((id3v2Header[8] & 0x7f) << 7)
+            | (id3v2Header[9] & 0x7f))
+            + sizeof id3v2Header;
+    }
+    /* Seek to the beginning of the audio stream */
+    if ( fseek(fpStream, id3v2TagSize, SEEK_SET) != 0 ) {
+        return -2;
+    }
+    if ( maybeSyncWord(fpStream) != 0) {
+        return -1;
+    }
+    if ( fseek(fpStream, id3v2TagSize+lametag_frame_size, SEEK_SET) != 0 ) {
+        return -2;
+    }
+    if ( maybeSyncWord(fpStream) != 0) {
+        return -1;
+    }
+    /* OK, it seems we found our LAME-Tag/Xing frame again */
+    /* Seek to the beginning of the audio stream */
+    if ( fseek(fpStream, id3v2TagSize, SEEK_SET) != 0 ) {
+        return -2;
+    }
+    return 0;
+}
+
+static BE_ERR
+updateLameTagFrame(lame_global_flags* gfp, FILE* fpStream)
+{
+    size_t n = lame_get_lametag_frame( gfp, 0, 0 ); /* ask for bufer size */
+
+    if ( n > 0 )
+    {
+        unsigned char* buffer = 0;
+        size_t m = 1;
+
+        if ( 0 != skipId3v2(fpStream, n) ) 
+        {
+            DispErr( "Error updating LAME-tag frame:\n\n"
+                     "can't locate old frame\n" );
+            return BE_ERR_INVALID_FORMAT_PARAMETERS;
+        }
+
+        buffer = (unsigned char*)malloc( n );
+
+        if ( buffer == 0 ) 
+        {
+            DispErr( "Error updating LAME-tag frame:\n\n"
+                     "can't allocate frame buffer\n" );
+            return BE_ERR_INVALID_FORMAT_PARAMETERS;
+        }
+
+        /* Put it all to disk again */
+        n = lame_get_lametag_frame( gfp, buffer, n );
+        if ( n > 0 ) 
+        {
+            m = fwrite( buffer, n, 1, fpStream );        
+        }
+        free( buffer );
+
+        if ( m != 1 ) 
+        {
+            DispErr( "Error updating LAME-tag frame:\n\n"
+                     "couldn't write frame into file\n" );
+            return BE_ERR_INVALID_FORMAT_PARAMETERS;
+        }
+    }
+    return BE_ERR_SUCCESSFUL;
+}
+
+__declspec(dllexport) BE_ERR beWriteInfoTag( HBE_STREAM hbeStream,
+                                            LPCSTR lpszFileName )
+{
+    FILE* fpStream     = NULL;
+    BE_ERR beResult    = BE_ERR_SUCCESSFUL;
+
+    lame_global_flags* gfp = (lame_global_flags*)hbeStream;
+
+    if ( NULL != gfp )
+    {
+        // Do we have to write the VBR tag?
+        if ( lame_get_bWriteVbrTag( gfp ) )
+        {
+            // Try to open the file
+            fpStream=fopen( lpszFileName, "rb+" );
+
+            // Check file open result
+            if ( NULL == fpStream )
+            {
+                beResult = BE_ERR_INVALID_FORMAT_PARAMETERS;
+                DispErr( "Error updating LAME-tag frame:\n\n"
+                         "can't open file for reading and writing\n" );
+            }
+            else
+            {
+                beResult = updateLameTagFrame( gfp, fpStream );
+
+                // Close the file stream
+                fclose( fpStream );
+            }
+        }
+
+        // clean up of allocated memory
+        lame_close( gfp );
+    }
+    else
+    {
+        beResult = BE_ERR_INVALID_FORMAT_PARAMETERS;
+    }
+
+    // return result
+    return beResult;
+}
+
+// for backwards compatiblity
+__declspec(dllexport) BE_ERR beWriteVBRHeader(LPCSTR lpszFileName)
+{
+    return beWriteInfoTag( (HBE_STREAM)gfp_save, lpszFileName );
+}
+
+
+BOOL APIENTRY DllMain(HANDLE hModule, 
+                      DWORD  ul_reason_for_call, 
+                      LPVOID lpReserved)
+{
+    (void) lpReserved;
+    gs_hModule = (HMODULE) hModule;
+
+    switch( ul_reason_for_call )
+    {
+    case DLL_PROCESS_ATTACH:
+        // Enable debug/logging?
+        gs_bLogFile = GetPrivateProfileIntA("Debug","WriteLogFile",gs_bLogFile,"lame_enc.ini");
+        break;
+    case DLL_THREAD_ATTACH:
+        break;
+    case DLL_THREAD_DETACH:
+        break;
+    case DLL_PROCESS_DETACH:
+        break;
+    }
+    return TRUE;
+}
+
+
+static void dump_config( lame_global_flags* gfp )
+{
+    DebugPrintf("\n\nLame_enc configuration options:\n");
+    DebugPrintf("==========================================================\n");
+
+    DebugPrintf("version                =%d\n",lame_get_version( gfp ) );
+    DebugPrintf("Layer                  =3\n");
+    DebugPrintf("mode                   =");
+    switch ( lame_get_mode( gfp ) )
+    {
+    case STEREO:       DebugPrintf( "Stereo\n" ); break;
+    case JOINT_STEREO: DebugPrintf( "Joint-Stereo\n" ); break;
+    case DUAL_CHANNEL: DebugPrintf( "Forced Stereo\n" ); break;
+    case MONO:         DebugPrintf( "Mono\n" ); break;
+    case NOT_SET:      /* FALLTROUGH */
+    default:           DebugPrintf( "Error (unknown)\n" ); break;
+    }
+
+    DebugPrintf("Input sample rate      =%.1f kHz\n", lame_get_in_samplerate( gfp ) /1000.0 );
+    DebugPrintf("Output sample rate     =%.1f kHz\n", lame_get_out_samplerate( gfp ) /1000.0 );
+
+    DebugPrintf("bitrate                =%d kbps\n", lame_get_brate( gfp ) );
+    DebugPrintf("Quality Setting        =%d\n", lame_get_quality( gfp ) );
+
+    DebugPrintf("Low pass frequency     =%d\n", lame_get_lowpassfreq( gfp ) );
+    DebugPrintf("Low pass width         =%d\n", lame_get_lowpasswidth( gfp ) );
+
+    DebugPrintf("High pass frequency    =%d\n", lame_get_highpassfreq( gfp ) );
+    DebugPrintf("High pass width        =%d\n", lame_get_highpasswidth( gfp ) );
+
+    DebugPrintf("No short blocks        =%d\n", lame_get_no_short_blocks( gfp ) );
+    DebugPrintf("Force short blocks     =%d\n", lame_get_force_short_blocks( gfp ) );
+
+    DebugPrintf("de-emphasis            =%d\n", lame_get_emphasis( gfp ) );
+    DebugPrintf("private flag           =%d\n", lame_get_extension( gfp ) );
+
+    DebugPrintf("copyright flag         =%d\n", lame_get_copyright( gfp ) );
+    DebugPrintf("original flag          =%d\n",        lame_get_original( gfp ) );
+    DebugPrintf("CRC                    =%s\n", lame_get_error_protection( gfp ) ? "on" : "off" );
+    DebugPrintf("Fast mode              =%s\n", ( lame_get_quality( gfp ) )? "enabled" : "disabled" );
+    DebugPrintf("Force mid/side stereo  =%s\n", ( lame_get_force_ms( gfp ) )?"enabled":"disabled" );
+    DebugPrintf("Disable Reservoir      =%d\n", lame_get_disable_reservoir( gfp ) );
+    DebugPrintf("Allow diff-short       =%d\n", lame_get_allow_diff_short( gfp ) );
+    DebugPrintf("Interchannel masking   =%f\n", lame_get_interChRatio( gfp ) );
+    DebugPrintf("Strict ISO Encoding    =%s\n", ( lame_get_strict_ISO( gfp ) ) ?"Yes":"No");
+    DebugPrintf("Scale                  =%5.2f\n", lame_get_scale( gfp ) );
+
+    DebugPrintf("VBR                    =%s, VBR_q =%d, VBR method =",
+        ( lame_get_VBR( gfp ) !=vbr_off ) ? "enabled": "disabled",
+        lame_get_VBR_q( gfp ) );
+
+    switch ( lame_get_VBR( gfp ) )
+    {
+    case vbr_off:      DebugPrintf( "vbr_off\n" );     break;
+    case vbr_mt :      DebugPrintf( "vbr_mt \n" );     break;
+    case vbr_rh :      DebugPrintf( "vbr_rh \n" );     break;
+    case vbr_mtrh:     DebugPrintf( "vbr_mtrh \n" );   break;
+    case vbr_abr: 
+        DebugPrintf( "vbr_abr (average bitrate %d kbps)\n", lame_get_VBR_mean_bitrate_kbps( gfp ) );
+        break;
+    default:
+        DebugPrintf("error, unknown VBR setting\n");
+        break;
+    }
+
+    DebugPrintf("Vbr Min bitrate        =%d kbps\n", lame_get_VBR_min_bitrate_kbps( gfp ) );
+    DebugPrintf("Vbr Max bitrate        =%d kbps\n", lame_get_VBR_max_bitrate_kbps( gfp ) );
+
+    DebugPrintf("Write VBR Header       =%s\n", ( lame_get_bWriteVbrTag( gfp ) ) ?"Yes":"No");
+    DebugPrintf("VBR Hard min           =%d\n", lame_get_VBR_hard_min( gfp ) );
+
+    DebugPrintf("ATH Only               =%d\n", lame_get_ATHonly( gfp ) );
+    DebugPrintf("ATH short              =%d\n", lame_get_ATHshort( gfp ) );
+    DebugPrintf("ATH no                 =%d\n", lame_get_noATH( gfp ) );
+    DebugPrintf("ATH type               =%d\n", lame_get_ATHtype( gfp ) );
+    DebugPrintf("ATH lower              =%f\n", lame_get_ATHlower( gfp ) );
+    DebugPrintf("ATH aa                 =%d\n", lame_get_athaa_type( gfp ) );
+    //DebugPrintf("ATH aa  loudapprox     =%d\n", lame_get_athaa_loudapprox( gfp ) );
+    DebugPrintf("ATH aa  sensitivity    =%f\n", lame_get_athaa_sensitivity( gfp ) );
+
+    DebugPrintf("Experimental nspsytune =%d\n", lame_get_exp_nspsytune( gfp ) );
+    DebugPrintf("Experimental X         =%d\n", lame_get_experimentalX( gfp ) );
+    DebugPrintf("Experimental Y         =%d\n", lame_get_experimentalY( gfp ) );
+    DebugPrintf("Experimental Z         =%d\n", lame_get_experimentalZ( gfp ) );
+}
+
+
+static void DispErr(char const* strErr)
+{
+    MessageBoxA(NULL,strErr,"LAME_ENC.DLL",MB_OK|MB_ICONHAND);
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/lame/Dll/BladeMP3EncDLL.def b/lame/Dll/BladeMP3EncDLL.def
new file mode 100644 (file)
index 0000000..4ae1a43
--- /dev/null
@@ -0,0 +1,35 @@
+EXPORTS
+
+beInitStream                   @1
+beEncodeChunk                  @2
+beDeinitStream                 @3
+beCloseStream                  @4
+beVersion                              @5
+beWriteVBRHeader               @6
+beEncodeChunkFloatS16NI        @7
+beFlushNoGap                   @8
+beWriteInfoTag                 @9
+
+lame_init                                              @100
+lame_close                                             @101
+lame_init_params                               @102
+lame_encode_buffer_interleaved @110
+lame_encode_flush                              @120
+lame_mp3_tags_fid                              @130
+
+
+lame_set_num_samples                   @1000
+lame_get_num_samples                   @1001
+lame_set_in_samplerate                 @1002
+lame_get_in_samplerate                 @1003
+lame_set_num_channels                  @1004
+lame_get_num_channels                  @1005
+lame_set_scale                                 @1006
+lame_get_scale                                 @1007
+lame_set_scale_left                            @1008
+lame_get_scale_left                            @1009
+lame_set_scale_right                   @1010
+lame_get_scale_right                   @1011
+lame_set_out_samplerate                        @1012
+lame_get_out_samplerate                        @1013
+
diff --git a/lame/Dll/README b/lame/Dll/README
new file mode 100644 (file)
index 0000000..ed8467a
--- /dev/null
@@ -0,0 +1,21 @@
+
+This directory contains a Windows DLL interface to the LAME
+encoding engine.
+
+This DLL is compatible with the BladeEnc.dll.  
+See BladeMP3EncDLL.c for details of the calling
+sequence, and BladeMP3EncDLL.h for details of the
+data that must be passed to the DLL.  
+
+As of yet, there is no other documentation. 
+
+To use this DLL as a replacement for BladeEnc.dll, you
+need to populate the 'mp3' struct.  
+
+To use more advanced features of LAME, you need to 
+populate the LHV1 struct instead.
+
+Delphi 4 Users:  Gabriel Gélin <ggelin@alapage.com> has
+contributed a .PAS file, do you can access the DLL from
+Delphi.   See MP3export.pas.
+
diff --git a/lame/LICENSE b/lame/LICENSE
new file mode 100644 (file)
index 0000000..430a6a0
--- /dev/null
@@ -0,0 +1,13 @@
+Can I use LAME in my commercial program?  
+
+Yes, you can, under the restrictions of the LGPL (see COPYING
+in this folder). The easiest way to do this is to:
+
+1. Link to LAME as separate library (libmp3lame.a on unix or 
+   lame_enc.dll or libmp3lame.dll on windows)
+
+2. Fully acknowledge that you are using LAME, and give a link
+   to our web site, www.mp3dev.org
+
+3. If you make modifications to LAME, you *must* release these
+   modifications back to the LAME project, under the LGPL.
diff --git a/lame/README b/lame/README
new file mode 100644 (file)
index 0000000..77c6c47
--- /dev/null
@@ -0,0 +1,44 @@
+                      LAME 3.xx
+               LAME Ain't an MP3 Encoder
+                  http://lame.sf.net
+                         May 2011
+
+Originally developed by Mike Cheng (www.uq.net.au/~zzmcheng) and was
+latter developed by Mark Taylor (www.mp3dev.org). Currently maintained
+by The LAME Project.
+
+This code is distributed under the GNU LIBRARY GENERAL PUBLIC LICENSE
+(LGPL, see www.gnu.org), version 2.
+
+As LAME may contain software for which some companies may claim software
+patents, if you are in a location where software patents are recognized, it is
+suggested that you seek legal advice before deploying and/or redistributing
+LAME.
+
+In particular, it is suggested to visit
+
+    http://www.mp3licensing.com/
+
+if it applies to your jurisdiction.
+
+============================================================================
+
+see the file "INSTALL" for installation (compiling) instructions.
+see the file "USAGE" for the most up-to-date guide to the command line options.
+see the file "LICENSE" for details on how to use LAME in non-GPL programs.
+see the file "HACKING" if you are interested in working on LAME
+see the file "API" for details of the LAME encoding library API
+
+There is HTML documentation and a man page in the doc directory.
+
+============================================================================
+
+LAME uses the MPGLIB decoding engine, from the mpg123 package, written
+by: Michael Hipp (www.mpg123.de) MPGLIB is released under the GPL.
+
+Copyrights (c) 1999-2011 by The LAME Project
+Copyrights (c) 1999,2000,2001 by Mark Taylor
+Copyrights (c) 1998 by Michael Cheng
+Copyrights (c) 1995,1996,1997 by Michael Hipp: mpglib
+
+As well as additional copyrights as documented in the source code.
diff --git a/lame/config.h b/lame/config.h
new file mode 100644 (file)
index 0000000..4a175ab
--- /dev/null
@@ -0,0 +1,11 @@
+
+#pragma once
+
+#include <stdint.h>
+
+typedef float  float32_t;
+typedef double float64_t;
+
+typedef long double ieee854_float80_t;
+typedef double      ieee754_float64_t;
+typedef float       ieee754_float32_t;
diff --git a/lame/include/lame.def b/lame/include/lame.def
new file mode 100644 (file)
index 0000000..def5287
--- /dev/null
@@ -0,0 +1,301 @@
+LIBRARY  libmp3lame.DLL
+EXPORTS
+
+lame_init              @1
+
+lame_set_num_samples   @2
+lame_get_num_samples   @3
+
+lame_set_in_samplerate @4
+lame_get_in_samplerate @5
+
+lame_set_num_channels  @6
+lame_get_num_channels  @7
+
+lame_set_scale         @8
+lame_get_scale         @9
+
+lame_set_scale_left    @10
+lame_get_scale_left    @11
+
+lame_set_scale_right   @12
+lame_get_scale_right   @13
+
+lame_set_out_samplerate        @14
+lame_get_out_samplerate        @15
+
+lame_set_analysis      @16
+lame_get_analysis      @17
+
+lame_set_bWriteVbrTag  @18
+lame_get_bWriteVbrTag  @19
+
+lame_set_decode_only   @20
+lame_get_decode_only   @21
+
+lame_set_quality       @22
+lame_get_quality       @23
+
+lame_set_mode          @24
+lame_get_mode          @25
+
+lame_set_force_ms      @26
+lame_get_force_ms      @27
+
+lame_set_free_format   @28
+lame_get_free_format   @29
+
+
+lame_set_findReplayGain        @30
+lame_get_findReplayGain        @31
+
+lame_set_decode_on_the_fly     @32
+lame_get_decode_on_the_fly     @33
+
+lame_set_nogap_total   @34
+lame_get_nogap_total   @35
+
+lame_set_nogap_currentindex    @36
+lame_get_nogap_currentindex    @37
+
+
+lame_set_errorf                @38
+lame_set_debugf                @39
+lame_set_msgf          @40
+
+lame_set_brate         @41
+lame_get_brate         @42
+lame_set_compression_ratio     @43
+lame_get_compression_ratio     @44
+
+lame_set_preset                @45
+
+lame_set_asm_optimizations     @46
+
+
+lame_set_copyright     @47
+lame_get_copyright     @48
+
+lame_set_original      @49
+lame_get_original      @50
+
+lame_set_error_protection      @51
+lame_get_error_protection      @52
+
+lame_set_padding_type  @53
+lame_get_padding_type  @54
+
+lame_set_extension     @55
+lame_get_extension     @56
+
+lame_set_strict_ISO    @57
+lame_get_strict_ISO    @58
+
+lame_set_disable_reservoir     @59
+lame_get_disable_reservoir     @60
+
+lame_set_quant_comp    @61
+lame_get_quant_comp    @62
+lame_set_quant_comp_short      @63
+lame_get_quant_comp_short      @64
+
+lame_set_experimentalX @65
+lame_get_experimentalX @66
+
+lame_set_experimentalY @67
+lame_get_experimentalY @68
+
+lame_set_experimentalZ @69
+lame_get_experimentalZ @70
+
+lame_set_exp_nspsytune @71
+lame_get_exp_nspsytune @72
+
+lame_set_msfix         @73
+lame_get_msfix         @74
+
+lame_set_VBR           @75
+lame_get_VBR           @76
+
+lame_set_VBR_q         @77
+lame_get_VBR_q         @78
+
+lame_set_VBR_mean_bitrate_kbps @79
+lame_get_VBR_mean_bitrate_kbps @80
+
+lame_set_VBR_min_bitrate_kbps  @81
+lame_get_VBR_min_bitrate_kbps  @82
+
+lame_set_VBR_max_bitrate_kbps  @83
+lame_get_VBR_max_bitrate_kbps  @84
+
+lame_set_VBR_hard_min  @85
+lame_get_VBR_hard_min  @86
+
+lame_set_preset_expopts        @87
+
+lame_set_lowpassfreq   @88
+lame_get_lowpassfreq   @89
+
+lame_set_lowpasswidth  @90
+lame_get_lowpasswidth  @91
+
+lame_set_highpassfreq  @92
+lame_get_highpassfreq  @93
+
+lame_set_highpasswidth @94
+lame_get_highpasswidth @95
+
+lame_set_ATHonly       @96
+lame_get_ATHonly       @97
+
+lame_set_ATHshort      @98
+lame_get_ATHshort      @99
+
+lame_set_noATH         @100
+lame_get_noATH         @101
+
+lame_set_ATHtype       @102
+lame_get_ATHtype       @103
+
+lame_set_ATHlower      @104
+lame_get_ATHlower      @105
+
+lame_set_athaa_type    @106
+lame_get_athaa_type    @107
+
+lame_set_athaa_loudapprox      @108
+lame_get_athaa_loudapprox      @109
+
+lame_set_athaa_sensitivity     @110
+lame_get_athaa_sensitivity     @111
+
+lame_set_cwlimit       @112
+lame_get_cwlimit       @113
+
+lame_set_useTemporal   @114
+lame_get_useTemporal   @115
+
+lame_set_interChRatio  @116
+lame_get_interChRatio  @117
+
+lame_set_no_short_blocks       @118
+lame_get_no_short_blocks       @119
+lame_set_force_short_blocks    @120
+lame_get_force_short_blocks    @121
+lame_set_allow_diff_short      @122
+lame_get_allow_diff_short      @123
+
+lame_set_emphasis      @124
+lame_get_emphasis      @125
+
+lame_get_version       @126
+lame_get_encoder_delay @127
+lame_get_encoder_padding       @128
+lame_get_framesize     @129
+
+lame_get_mf_samples_to_encode  @130
+lame_get_size_mp3buffer        @131
+lame_get_frameNum      @132
+lame_get_totalframes   @133
+
+lame_get_RadioGain     @134
+lame_get_AudiophileGain        @135
+lame_get_PeakSample    @136
+lame_get_noclipGainChange      @137
+lame_get_noclipScale   @138
+
+lame_init_params       @139
+
+get_lame_version       @140
+get_lame_short_version @141
+get_lame_very_short_version    @142
+get_psy_version                @143        
+get_lame_url           @144           
+
+get_lame_version_numerical     @145
+
+lame_print_config      @146
+lame_print_internals   @147
+
+lame_encode_buffer     @148
+lame_encode_buffer_interleaved @149
+lame_encode_buffer_float       @150
+lame_encode_buffer_long        @151
+lame_encode_buffer_long2       @152
+lame_encode_buffer_int @153
+lame_encode_flush      @154
+lame_encode_flush_nogap        @155
+
+lame_init_bitstream    @156
+
+lame_bitrate_hist      @157
+lame_bitrate_kbps      @158
+lame_stereo_mode_hist  @159
+lame_bitrate_stereo_mode_hist  @160
+lame_block_type_hist   @161
+lame_bitrate_block_type_hist   @162
+lame_mp3_tags_fid      @163
+lame_close             @164
+lame_get_lametag_frame @165
+get_lame_os_bitness    @166
+lame_set_VBR_quality   @167
+lame_get_VBR_quality   @168
+
+lame_encode_buffer_ieee_float  @169
+lame_encode_buffer_interleaved_ieee_float      @170
+lame_encode_buffer_ieee_double @171
+lame_encode_buffer_interleaved_ieee_double     @172
+lame_encode_buffer_interleaved_int     @173
+
+lame_get_bitrate       @502
+lame_get_samplerate    @503
+lame_get_maximum_number_of_samples     @504
+
+lame_decode_init       @1000
+lame_decode            @1001
+lame_decode_headers    @1002
+lame_decode1           @1003
+lame_decode1_headers   @1004
+lame_decode1_headersB  @1005
+lame_decode_exit       @1006
+
+hip_decode_init        @1100
+hip_decode_exit        @1101
+hip_decode             @1102
+hip_decode_headers     @1103
+hip_decode1            @1104
+hip_decode1_headers    @1105
+hip_decode1_headersB   @1106
+hip_set_debugf @1107
+hip_set_errorf @1108
+hip_set_msgf   @1109
+
+id3tag_genre_list      @2000
+id3tag_init            @2001
+id3tag_add_v2          @2002
+id3tag_v1_only         @2003
+id3tag_v2_only         @2004
+id3tag_space_v1        @2005
+id3tag_pad_v2          @2006
+id3tag_set_title       @2007
+id3tag_set_artist      @2008
+id3tag_set_album       @2009
+id3tag_set_year                @2010
+id3tag_set_comment     @2011
+id3tag_set_track       @2012
+id3tag_set_genre       @2013
+id3tag_set_fieldvalue  @2014
+id3tag_set_albumart    @2015
+lame_get_id3v1_tag     @2016
+lame_get_id3v2_tag     @2017
+lame_set_write_id3tag_automatic        @2018
+lame_get_write_id3tag_automatic        @2019
+id3tag_set_pad @2020
+id3tag_set_comment_ucs2        @2021
+id3tag_set_textinfo_ucs2 @2022
+id3tag_set_fieldvalue_ucs2     @2023
+id3tag_set_comment_utf16       @2024
+id3tag_set_textinfo_utf16 @2025
+id3tag_set_fieldvalue_utf16    @2026
diff --git a/lame/include/lame.h b/lame/include/lame.h
new file mode 100644 (file)
index 0000000..5196690
--- /dev/null
@@ -0,0 +1,1342 @@
+/*
+ *     Interface to MP3 LAME encoding engine
+ *
+ *     Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: lame.h,v 1.192 2017/08/31 14:14:46 robert Exp $ */
+
+#ifndef LAME_LAME_H
+#define LAME_LAME_H
+
+/* for size_t typedef */
+#include <stddef.h>
+/* for va_list typedef */
+#include <stdarg.h>
+/* for FILE typedef, TODO: remove when removing lame_mp3_tags_fid */
+#include <stdio.h>
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+typedef void (*lame_report_function)(const char *format, va_list ap);
+
+#if defined(WIN32) || defined(_WIN32)
+#undef CDECL
+#define CDECL __cdecl
+#else
+#define CDECL
+#endif
+
+#define DEPRECATED_OR_OBSOLETE_CODE_REMOVED 1
+
+typedef enum vbr_mode_e {
+  vbr_off=0,
+  vbr_mt,               /* obsolete, same as vbr_mtrh */
+  vbr_rh,
+  vbr_abr,
+  vbr_mtrh,
+  vbr_max_indicator,    /* Don't use this! It's used for sanity checks.       */
+  vbr_default=vbr_mtrh    /* change this to change the default VBR mode of LAME */
+} vbr_mode;
+
+
+/* MPEG modes */
+typedef enum MPEG_mode_e {
+  STEREO = 0,
+  JOINT_STEREO,
+  DUAL_CHANNEL,   /* LAME doesn't supports this! */
+  MONO,
+  NOT_SET,
+  MAX_INDICATOR   /* Don't use this! It's used for sanity checks. */
+} MPEG_mode;
+
+/* Padding types */
+typedef enum Padding_type_e {
+  PAD_NO = 0,
+  PAD_ALL,
+  PAD_ADJUST,
+  PAD_MAX_INDICATOR   /* Don't use this! It's used for sanity checks. */
+} Padding_type;
+
+
+
+/*presets*/
+typedef enum preset_mode_e {
+    /*values from 8 to 320 should be reserved for abr bitrates*/
+    /*for abr I'd suggest to directly use the targeted bitrate as a value*/
+    ABR_8 = 8,
+    ABR_320 = 320,
+
+    V9 = 410, /*Vx to match Lame and VBR_xx to match FhG*/
+    VBR_10 = 410,
+    V8 = 420,
+    VBR_20 = 420,
+    V7 = 430,
+    VBR_30 = 430,
+    V6 = 440,
+    VBR_40 = 440,
+    V5 = 450,
+    VBR_50 = 450,
+    V4 = 460,
+    VBR_60 = 460,
+    V3 = 470,
+    VBR_70 = 470,
+    V2 = 480,
+    VBR_80 = 480,
+    V1 = 490,
+    VBR_90 = 490,
+    V0 = 500,
+    VBR_100 = 500,
+
+
+
+    /*still there for compatibility*/
+    R3MIX = 1000,
+    STANDARD = 1001,
+    EXTREME = 1002,
+    INSANE = 1003,
+    STANDARD_FAST = 1004,
+    EXTREME_FAST = 1005,
+    MEDIUM = 1006,
+    MEDIUM_FAST = 1007
+} preset_mode;
+
+
+/*asm optimizations*/
+typedef enum asm_optimizations_e {
+    MMX = 1,
+    AMD_3DNOW = 2,
+    SSE = 3
+} asm_optimizations;
+
+
+/* psychoacoustic model */
+typedef enum Psy_model_e {
+    PSY_GPSYCHO = 1,
+    PSY_NSPSYTUNE = 2
+} Psy_model;
+
+
+/* buffer considerations */
+typedef enum buffer_constraint_e {
+    MDB_DEFAULT=0,
+    MDB_STRICT_ISO=1,
+    MDB_MAXIMUM=2
+} buffer_constraint;
+
+
+struct lame_global_struct;
+typedef struct lame_global_struct lame_global_flags;
+typedef lame_global_flags *lame_t;
+
+
+
+
+/***********************************************************************
+ *
+ *  The LAME API
+ *  These functions should be called, in this order, for each
+ *  MP3 file to be encoded.  See the file "API" for more documentation
+ *
+ ***********************************************************************/
+
+
+/*
+ * REQUIRED:
+ * initialize the encoder.  sets default for all encoder parameters,
+ * returns NULL if some malloc()'s failed
+ * otherwise returns pointer to structure needed for all future
+ * API calls.
+ */
+lame_global_flags * CDECL lame_init(void);
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* obsolete version */
+int CDECL lame_init_old(lame_global_flags *);
+#endif
+
+/*
+ * OPTIONAL:
+ * set as needed to override defaults
+ */
+
+/********************************************************************
+ *  input stream description
+ ***********************************************************************/
+/* number of samples.  default = 2^32-1   */
+int CDECL lame_set_num_samples(lame_global_flags *, unsigned long);
+unsigned long CDECL lame_get_num_samples(const lame_global_flags *);
+
+/* input sample rate in Hz.  default = 44100hz */
+int CDECL lame_set_in_samplerate(lame_global_flags *, int);
+int CDECL lame_get_in_samplerate(const lame_global_flags *);
+
+/* number of channels in input stream. default=2  */
+int CDECL lame_set_num_channels(lame_global_flags *, int);
+int CDECL lame_get_num_channels(const lame_global_flags *);
+
+/*
+  scale the input by this amount before encoding.  default=1
+  (not used by decoding routines)
+*/
+int CDECL lame_set_scale(lame_global_flags *, float);
+float CDECL lame_get_scale(const lame_global_flags *);
+
+/*
+  scale the channel 0 (left) input by this amount before encoding.  default=1
+  (not used by decoding routines)
+*/
+int CDECL lame_set_scale_left(lame_global_flags *, float);
+float CDECL lame_get_scale_left(const lame_global_flags *);
+
+/*
+  scale the channel 1 (right) input by this amount before encoding.  default=1
+  (not used by decoding routines)
+*/
+int CDECL lame_set_scale_right(lame_global_flags *, float);
+float CDECL lame_get_scale_right(const lame_global_flags *);
+
+/*
+  output sample rate in Hz.  default = 0, which means LAME picks best value
+  based on the amount of compression.  MPEG only allows:
+  MPEG1    32, 44.1,   48khz
+  MPEG2    16, 22.05,  24
+  MPEG2.5   8, 11.025, 12
+  (not used by decoding routines)
+*/
+int CDECL lame_set_out_samplerate(lame_global_flags *, int);
+int CDECL lame_get_out_samplerate(const lame_global_flags *);
+
+
+/********************************************************************
+ *  general control parameters
+ ***********************************************************************/
+/* 1=cause LAME to collect data for an MP3 frame analyzer. default=0 */
+int CDECL lame_set_analysis(lame_global_flags *, int);
+int CDECL lame_get_analysis(const lame_global_flags *);
+
+/*
+  1 = write a Xing VBR header frame.
+  default = 1
+  this variable must have been added by a Hungarian notation Windows programmer :-)
+*/
+int CDECL lame_set_bWriteVbrTag(lame_global_flags *, int);
+int CDECL lame_get_bWriteVbrTag(const lame_global_flags *);
+
+/* 1=decode only.  use lame/mpglib to convert mp3/ogg to wav.  default=0 */
+int CDECL lame_set_decode_only(lame_global_flags *, int);
+int CDECL lame_get_decode_only(const lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* 1=encode a Vorbis .ogg file.  default=0 */
+/* DEPRECATED */
+int CDECL lame_set_ogg(lame_global_flags *, int);
+int CDECL lame_get_ogg(const lame_global_flags *);
+#endif
+
+/*
+  internal algorithm selection.  True quality is determined by the bitrate
+  but this variable will effect quality by selecting expensive or cheap algorithms.
+  quality=0..9.  0=best (very slow).  9=worst.
+  recommended:  2     near-best quality, not too slow
+                5     good quality, fast
+                7     ok quality, really fast
+*/
+int CDECL lame_set_quality(lame_global_flags *, int);
+int CDECL lame_get_quality(const lame_global_flags *);
+
+/*
+  mode = 0,1,2,3 = stereo, jstereo, dual channel (not supported), mono
+  default: lame picks based on compression ration and input channels
+*/
+int CDECL lame_set_mode(lame_global_flags *, MPEG_mode);
+MPEG_mode CDECL lame_get_mode(const lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/*
+  mode_automs.  Use a M/S mode with a switching threshold based on
+  compression ratio
+  DEPRECATED
+*/
+int CDECL lame_set_mode_automs(lame_global_flags *, int);
+int CDECL lame_get_mode_automs(const lame_global_flags *);
+#endif
+
+/*
+  force_ms.  Force M/S for all frames.  For testing only.
+  default = 0 (disabled)
+*/
+int CDECL lame_set_force_ms(lame_global_flags *, int);
+int CDECL lame_get_force_ms(const lame_global_flags *);
+
+/* use free_format?  default = 0 (disabled) */
+int CDECL lame_set_free_format(lame_global_flags *, int);
+int CDECL lame_get_free_format(const lame_global_flags *);
+
+/* perform ReplayGain analysis?  default = 0 (disabled) */
+int CDECL lame_set_findReplayGain(lame_global_flags *, int);
+int CDECL lame_get_findReplayGain(const lame_global_flags *);
+
+/* decode on the fly. Search for the peak sample. If the ReplayGain
+ * analysis is enabled then perform the analysis on the decoded data
+ * stream. default = 0 (disabled)
+ * NOTE: if this option is set the build-in decoder should not be used */
+int CDECL lame_set_decode_on_the_fly(lame_global_flags *, int);
+int CDECL lame_get_decode_on_the_fly(const lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* DEPRECATED: now does the same as lame_set_findReplayGain()
+   default = 0 (disabled) */
+int CDECL lame_set_ReplayGain_input(lame_global_flags *, int);
+int CDECL lame_get_ReplayGain_input(const lame_global_flags *);
+
+/* DEPRECATED: now does the same as
+   lame_set_decode_on_the_fly() && lame_set_findReplayGain()
+   default = 0 (disabled) */
+int CDECL lame_set_ReplayGain_decode(lame_global_flags *, int);
+int CDECL lame_get_ReplayGain_decode(const lame_global_flags *);
+
+/* DEPRECATED: now does the same as lame_set_decode_on_the_fly()
+   default = 0 (disabled) */
+int CDECL lame_set_findPeakSample(lame_global_flags *, int);
+int CDECL lame_get_findPeakSample(const lame_global_flags *);
+#endif
+
+/* counters for gapless encoding */
+int CDECL lame_set_nogap_total(lame_global_flags*, int);
+int CDECL lame_get_nogap_total(const lame_global_flags*);
+
+int CDECL lame_set_nogap_currentindex(lame_global_flags* , int);
+int CDECL lame_get_nogap_currentindex(const lame_global_flags*);
+
+
+/*
+ * OPTIONAL:
+ * Set printf like error/debug/message reporting functions.
+ * The second argument has to be a pointer to a function which looks like
+ *   void my_debugf(const char *format, va_list ap)
+ *   {
+ *       (void) vfprintf(stdout, format, ap);
+ *   }
+ * If you use NULL as the value of the pointer in the set function, the
+ * lame buildin function will be used (prints to stderr).
+ * To quiet any output you have to replace the body of the example function
+ * with just "return;" and use it in the set function.
+ */
+int CDECL lame_set_errorf(lame_global_flags *, lame_report_function);
+int CDECL lame_set_debugf(lame_global_flags *, lame_report_function);
+int CDECL lame_set_msgf  (lame_global_flags *, lame_report_function);
+
+
+
+/* set one of brate compression ratio.  default is compression ratio of 11.  */
+int CDECL lame_set_brate(lame_global_flags *, int);
+int CDECL lame_get_brate(const lame_global_flags *);
+int CDECL lame_set_compression_ratio(lame_global_flags *, float);
+float CDECL lame_get_compression_ratio(const lame_global_flags *);
+
+
+int CDECL lame_set_preset( lame_global_flags*  gfp, int );
+int CDECL lame_set_asm_optimizations( lame_global_flags*  gfp, int, int );
+
+
+
+/********************************************************************
+ *  frame params
+ ***********************************************************************/
+/* mark as copyright.  default=0 */
+int CDECL lame_set_copyright(lame_global_flags *, int);
+int CDECL lame_get_copyright(const lame_global_flags *);
+
+/* mark as original.  default=1 */
+int CDECL lame_set_original(lame_global_flags *, int);
+int CDECL lame_get_original(const lame_global_flags *);
+
+/* error_protection.  Use 2 bytes from each frame for CRC checksum. default=0 */
+int CDECL lame_set_error_protection(lame_global_flags *, int);
+int CDECL lame_get_error_protection(const lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* padding_type. 0=pad no frames  1=pad all frames 2=adjust padding(default) */
+int CDECL lame_set_padding_type(lame_global_flags *, Padding_type);
+Padding_type CDECL lame_get_padding_type(const lame_global_flags *);
+#endif
+
+/* MP3 'private extension' bit  Meaningless.  default=0 */
+int CDECL lame_set_extension(lame_global_flags *, int);
+int CDECL lame_get_extension(const lame_global_flags *);
+
+/* enforce strict ISO compliance.  default=0 */
+int CDECL lame_set_strict_ISO(lame_global_flags *, int);
+int CDECL lame_get_strict_ISO(const lame_global_flags *);
+
+
+/********************************************************************
+ * quantization/noise shaping
+ ***********************************************************************/
+
+/* disable the bit reservoir. For testing only. default=0 */
+int CDECL lame_set_disable_reservoir(lame_global_flags *, int);
+int CDECL lame_get_disable_reservoir(const lame_global_flags *);
+
+/* select a different "best quantization" function. default=0  */
+int CDECL lame_set_quant_comp(lame_global_flags *, int);
+int CDECL lame_get_quant_comp(const lame_global_flags *);
+int CDECL lame_set_quant_comp_short(lame_global_flags *, int);
+int CDECL lame_get_quant_comp_short(const lame_global_flags *);
+
+int CDECL lame_set_experimentalX(lame_global_flags *, int); /* compatibility*/
+int CDECL lame_get_experimentalX(const lame_global_flags *);
+
+/* another experimental option.  for testing only */
+int CDECL lame_set_experimentalY(lame_global_flags *, int);
+int CDECL lame_get_experimentalY(const lame_global_flags *);
+
+/* another experimental option.  for testing only */
+int CDECL lame_set_experimentalZ(lame_global_flags *, int);
+int CDECL lame_get_experimentalZ(const lame_global_flags *);
+
+/* Naoki's psycho acoustic model.  default=0 */
+int CDECL lame_set_exp_nspsytune(lame_global_flags *, int);
+int CDECL lame_get_exp_nspsytune(const lame_global_flags *);
+
+void CDECL lame_set_msfix(lame_global_flags *, double);
+float CDECL lame_get_msfix(const lame_global_flags *);
+
+
+/********************************************************************
+ * VBR control
+ ***********************************************************************/
+/* Types of VBR.  default = vbr_off = CBR */
+int CDECL lame_set_VBR(lame_global_flags *, vbr_mode);
+vbr_mode CDECL lame_get_VBR(const lame_global_flags *);
+
+/* VBR quality level.  0=highest  9=lowest  */
+int CDECL lame_set_VBR_q(lame_global_flags *, int);
+int CDECL lame_get_VBR_q(const lame_global_flags *);
+
+/* VBR quality level.  0=highest  9=lowest, Range [0,...,10[  */
+int CDECL lame_set_VBR_quality(lame_global_flags *, float);
+float CDECL lame_get_VBR_quality(const lame_global_flags *);
+
+/* Ignored except for VBR=vbr_abr (ABR mode) */
+int CDECL lame_set_VBR_mean_bitrate_kbps(lame_global_flags *, int);
+int CDECL lame_get_VBR_mean_bitrate_kbps(const lame_global_flags *);
+
+int CDECL lame_set_VBR_min_bitrate_kbps(lame_global_flags *, int);
+int CDECL lame_get_VBR_min_bitrate_kbps(const lame_global_flags *);
+
+int CDECL lame_set_VBR_max_bitrate_kbps(lame_global_flags *, int);
+int CDECL lame_get_VBR_max_bitrate_kbps(const lame_global_flags *);
+
+/*
+  1=strictly enforce VBR_min_bitrate.  Normally it will be violated for
+  analog silence
+*/
+int CDECL lame_set_VBR_hard_min(lame_global_flags *, int);
+int CDECL lame_get_VBR_hard_min(const lame_global_flags *);
+
+/* for preset */
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+int CDECL lame_set_preset_expopts(lame_global_flags *, int);
+#endif
+
+/********************************************************************
+ * Filtering control
+ ***********************************************************************/
+/* freq in Hz to apply lowpass. Default = 0 = lame chooses.  -1 = disabled */
+int CDECL lame_set_lowpassfreq(lame_global_flags *, int);
+int CDECL lame_get_lowpassfreq(const lame_global_flags *);
+/* width of transition band, in Hz.  Default = one polyphase filter band */
+int CDECL lame_set_lowpasswidth(lame_global_flags *, int);
+int CDECL lame_get_lowpasswidth(const lame_global_flags *);
+
+/* freq in Hz to apply highpass. Default = 0 = lame chooses.  -1 = disabled */
+int CDECL lame_set_highpassfreq(lame_global_flags *, int);
+int CDECL lame_get_highpassfreq(const lame_global_flags *);
+/* width of transition band, in Hz.  Default = one polyphase filter band */
+int CDECL lame_set_highpasswidth(lame_global_flags *, int);
+int CDECL lame_get_highpasswidth(const lame_global_flags *);
+
+
+/********************************************************************
+ * psycho acoustics and other arguments which you should not change
+ * unless you know what you are doing
+ ***********************************************************************/
+
+/* only use ATH for masking */
+int CDECL lame_set_ATHonly(lame_global_flags *, int);
+int CDECL lame_get_ATHonly(const lame_global_flags *);
+
+/* only use ATH for short blocks */
+int CDECL lame_set_ATHshort(lame_global_flags *, int);
+int CDECL lame_get_ATHshort(const lame_global_flags *);
+
+/* disable ATH */
+int CDECL lame_set_noATH(lame_global_flags *, int);
+int CDECL lame_get_noATH(const lame_global_flags *);
+
+/* select ATH formula */
+int CDECL lame_set_ATHtype(lame_global_flags *, int);
+int CDECL lame_get_ATHtype(const lame_global_flags *);
+
+/* lower ATH by this many db */
+int CDECL lame_set_ATHlower(lame_global_flags *, float);
+float CDECL lame_get_ATHlower(const lame_global_flags *);
+
+/* select ATH adaptive adjustment type */
+int CDECL lame_set_athaa_type( lame_global_flags *, int);
+int CDECL lame_get_athaa_type( const lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* select the loudness approximation used by the ATH adaptive auto-leveling  */
+int CDECL lame_set_athaa_loudapprox( lame_global_flags *, int);
+int CDECL lame_get_athaa_loudapprox( const lame_global_flags *);
+#endif
+
+/* adjust (in dB) the point below which adaptive ATH level adjustment occurs */
+int CDECL lame_set_athaa_sensitivity( lame_global_flags *, float);
+float CDECL lame_get_athaa_sensitivity( const lame_global_flags* );
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* OBSOLETE: predictability limit (ISO tonality formula) */
+int CDECL lame_set_cwlimit(lame_global_flags *, int);
+int CDECL lame_get_cwlimit(const lame_global_flags *);
+#endif
+
+/*
+  allow blocktypes to differ between channels?
+  default: 0 for jstereo, 1 for stereo
+*/
+int CDECL lame_set_allow_diff_short(lame_global_flags *, int);
+int CDECL lame_get_allow_diff_short(const lame_global_flags *);
+
+/* use temporal masking effect (default = 1) */
+int CDECL lame_set_useTemporal(lame_global_flags *, int);
+int CDECL lame_get_useTemporal(const lame_global_flags *);
+
+/* use temporal masking effect (default = 1) */
+int CDECL lame_set_interChRatio(lame_global_flags *, float);
+float CDECL lame_get_interChRatio(const lame_global_flags *);
+
+/* disable short blocks */
+int CDECL lame_set_no_short_blocks(lame_global_flags *, int);
+int CDECL lame_get_no_short_blocks(const lame_global_flags *);
+
+/* force short blocks */
+int CDECL lame_set_force_short_blocks(lame_global_flags *, int);
+int CDECL lame_get_force_short_blocks(const lame_global_flags *);
+
+/* Input PCM is emphased PCM (for instance from one of the rarely
+   emphased CDs), it is STRONGLY not recommended to use this, because
+   psycho does not take it into account, and last but not least many decoders
+   ignore these bits */
+int CDECL lame_set_emphasis(lame_global_flags *, int);
+int CDECL lame_get_emphasis(const lame_global_flags *);
+
+
+
+/************************************************************************/
+/* internal variables, cannot be set...                                 */
+/* provided because they may be of use to calling application           */
+/************************************************************************/
+/* version  0=MPEG-2  1=MPEG-1  (2=MPEG-2.5)     */
+int CDECL lame_get_version(const lame_global_flags *);
+
+/* encoder delay   */
+int CDECL lame_get_encoder_delay(const lame_global_flags *);
+
+/*
+  padding appended to the input to make sure decoder can fully decode
+  all input.  Note that this value can only be calculated during the
+  call to lame_encoder_flush().  Before lame_encoder_flush() has
+  been called, the value of encoder_padding = 0.
+*/
+int CDECL lame_get_encoder_padding(const lame_global_flags *);
+
+/* size of MPEG frame */
+int CDECL lame_get_framesize(const lame_global_flags *);
+
+/* number of PCM samples buffered, but not yet encoded to mp3 data. */
+int CDECL lame_get_mf_samples_to_encode( const lame_global_flags*  gfp );
+
+/*
+  size (bytes) of mp3 data buffered, but not yet encoded.
+  this is the number of bytes which would be output by a call to
+  lame_encode_flush_nogap.  NOTE: lame_encode_flush() will return
+  more bytes than this because it will encode the reamining buffered
+  PCM samples before flushing the mp3 buffers.
+*/
+int CDECL lame_get_size_mp3buffer( const lame_global_flags*  gfp );
+
+/* number of frames encoded so far */
+int CDECL lame_get_frameNum(const lame_global_flags *);
+
+/*
+  lame's estimate of the total number of frames to be encoded
+   only valid if calling program set num_samples
+*/
+int CDECL lame_get_totalframes(const lame_global_flags *);
+
+/* RadioGain value. Multiplied by 10 and rounded to the nearest. */
+int CDECL lame_get_RadioGain(const lame_global_flags *);
+
+/* AudiophileGain value. Multipled by 10 and rounded to the nearest. */
+int CDECL lame_get_AudiophileGain(const lame_global_flags *);
+
+/* the peak sample */
+float CDECL lame_get_PeakSample(const lame_global_flags *);
+
+/* Gain change required for preventing clipping. The value is correct only if
+   peak sample searching was enabled. If negative then the waveform
+   already does not clip. The value is multiplied by 10 and rounded up. */
+int CDECL lame_get_noclipGainChange(const lame_global_flags *);
+
+/* user-specified scale factor required for preventing clipping. Value is
+   correct only if peak sample searching was enabled and no user-specified
+   scaling was performed. If negative then either the waveform already does
+   not clip or the value cannot be determined */
+float CDECL lame_get_noclipScale(const lame_global_flags *);
+
+/* returns the limit of PCM samples, which one can pass in an encode call
+   under the constrain of a provided buffer of size buffer_size */
+int CDECL lame_get_maximum_number_of_samples(lame_t gfp, size_t buffer_size);
+
+
+
+
+/*
+ * REQUIRED:
+ * sets more internal configuration based on data provided above.
+ * returns -1 if something failed.
+ */
+int CDECL lame_init_params(lame_global_flags *);
+
+
+/*
+ * OPTIONAL:
+ * get the version number, in a string. of the form:
+ * "3.63 (beta)" or just "3.63".
+ */
+const char*  CDECL get_lame_version       ( void );
+const char*  CDECL get_lame_short_version ( void );
+const char*  CDECL get_lame_very_short_version ( void );
+const char*  CDECL get_psy_version        ( void );
+const char*  CDECL get_lame_url           ( void );
+const char*  CDECL get_lame_os_bitness    ( void );
+
+/*
+ * OPTIONAL:
+ * get the version numbers in numerical form.
+ */
+typedef struct {
+    /* generic LAME version */
+    int major;
+    int minor;
+    int alpha;               /* 0 if not an alpha version                  */
+    int beta;                /* 0 if not a beta version                    */
+
+    /* version of the psy model */
+    int psy_major;
+    int psy_minor;
+    int psy_alpha;           /* 0 if not an alpha version                  */
+    int psy_beta;            /* 0 if not a beta version                    */
+
+    /* compile time features */
+    const char *features;    /* Don't make assumptions about the contents! */
+} lame_version_t;
+void CDECL get_lame_version_numerical(lame_version_t *);
+
+
+/*
+ * OPTIONAL:
+ * print internal lame configuration to message handler
+ */
+void CDECL lame_print_config(const lame_global_flags*  gfp);
+
+void CDECL lame_print_internals( const lame_global_flags *gfp);
+
+
+/*
+ * input pcm data, output (maybe) mp3 frames.
+ * This routine handles all buffering, resampling and filtering for you.
+ *
+ * return code     number of bytes output in mp3buf. Can be 0
+ *                 -1:  mp3buf was too small
+ *                 -2:  malloc() problem
+ *                 -3:  lame_init_params() not called
+ *                 -4:  psycho acoustic problems
+ *
+ * The required mp3buf_size can be computed from num_samples,
+ * samplerate and encoding rate, but here is a worst case estimate:
+ *
+ * mp3buf_size in bytes = 1.25*num_samples + 7200
+ *
+ * I think a tighter bound could be:  (mt, March 2000)
+ * MPEG1:
+ *    num_samples*(bitrate/8)/samplerate + 4*1152*(bitrate/8)/samplerate + 512
+ * MPEG2:
+ *    num_samples*(bitrate/8)/samplerate + 4*576*(bitrate/8)/samplerate + 256
+ *
+ * but test first if you use that!
+ *
+ * set mp3buf_size = 0 and LAME will not check if mp3buf_size is
+ * large enough.
+ *
+ * NOTE:
+ * if gfp->num_channels=2, but gfp->mode = 3 (mono), the L & R channels
+ * will be averaged into the L channel before encoding only the L channel
+ * This will overwrite the data in buffer_l[] and buffer_r[].
+ *
+*/
+int CDECL lame_encode_buffer (
+        lame_global_flags*  gfp,           /* global context handle         */
+        const short int     buffer_l [],   /* PCM data for left channel     */
+        const short int     buffer_r [],   /* PCM data for right channel    */
+        const int           nsamples,      /* number of samples per channel */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        const int           mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+/*
+ * as above, but input has L & R channel data interleaved.
+ * NOTE:
+ * num_samples = number of samples in the L (or R)
+ * channel, not the total number of samples in pcm[]
+ */
+int CDECL lame_encode_buffer_interleaved(
+        lame_global_flags*  gfp,           /* global context handlei        */
+        short int           pcm[],         /* PCM data for left and right
+                                              channel, interleaved          */
+        int                 num_samples,   /* number of samples per channel,
+                                              _not_ number of samples in
+                                              pcm[]                         */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        int                 mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+
+/* as lame_encode_buffer, but for 'float's.
+ * !! NOTE: !! data must still be scaled to be in the same range as
+ * short int, +/- 32768
+ */
+int CDECL lame_encode_buffer_float(
+        lame_global_flags*  gfp,           /* global context handle         */
+        const float         pcm_l [],      /* PCM data for left channel     */
+        const float         pcm_r [],      /* PCM data for right channel    */
+        const int           nsamples,      /* number of samples per channel */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        const int           mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+/* as lame_encode_buffer, but for 'float's.
+ * !! NOTE: !! data must be scaled to +/- 1 full scale
+ */
+int CDECL lame_encode_buffer_ieee_float(
+        lame_t          gfp,
+        const float     pcm_l [],          /* PCM data for left channel     */
+        const float     pcm_r [],          /* PCM data for right channel    */
+        const int       nsamples,
+        unsigned char * mp3buf,
+        const int       mp3buf_size);
+int CDECL lame_encode_buffer_interleaved_ieee_float(
+        lame_t          gfp,
+        const float     pcm[],             /* PCM data for left and right
+                                              channel, interleaved          */
+        const int       nsamples,
+        unsigned char * mp3buf,
+        const int       mp3buf_size);
+
+/* as lame_encode_buffer, but for 'double's.
+ * !! NOTE: !! data must be scaled to +/- 1 full scale
+ */
+int CDECL lame_encode_buffer_ieee_double(
+        lame_t          gfp,
+        const double    pcm_l [],          /* PCM data for left channel     */
+        const double    pcm_r [],          /* PCM data for right channel    */
+        const int       nsamples,
+        unsigned char * mp3buf,
+        const int       mp3buf_size);
+int CDECL lame_encode_buffer_interleaved_ieee_double(
+        lame_t          gfp,
+        const double    pcm[],             /* PCM data for left and right
+                                              channel, interleaved          */
+        const int       nsamples,
+        unsigned char * mp3buf,
+        const int       mp3buf_size);
+
+/* as lame_encode_buffer, but for long's
+ * !! NOTE: !! data must still be scaled to be in the same range as
+ * short int, +/- 32768
+ *
+ * This scaling was a mistake (doesn't allow one to exploit full
+ * precision of type 'long'.  Use lame_encode_buffer_long2() instead.
+ *
+ */
+int CDECL lame_encode_buffer_long(
+        lame_global_flags*  gfp,           /* global context handle         */
+        const long     buffer_l [],       /* PCM data for left channel     */
+        const long     buffer_r [],       /* PCM data for right channel    */
+        const int           nsamples,      /* number of samples per channel */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        const int           mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+/* Same as lame_encode_buffer_long(), but with correct scaling.
+ * !! NOTE: !! data must still be scaled to be in the same range as
+ * type 'long'.   Data should be in the range:  +/- 2^(8*size(long)-1)
+ *
+ */
+int CDECL lame_encode_buffer_long2(
+        lame_global_flags*  gfp,           /* global context handle         */
+        const long     buffer_l [],       /* PCM data for left channel     */
+        const long     buffer_r [],       /* PCM data for right channel    */
+        const int           nsamples,      /* number of samples per channel */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        const int           mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+/* as lame_encode_buffer, but for int's
+ * !! NOTE: !! input should be scaled to the maximum range of 'int'
+ * If int is 4 bytes, then the values should range from
+ * +/- 2147483648.
+ *
+ * This routine does not (and cannot, without loosing precision) use
+ * the same scaling as the rest of the lame_encode_buffer() routines.
+ *
+ */
+int CDECL lame_encode_buffer_int(
+        lame_global_flags*  gfp,           /* global context handle         */
+        const int      buffer_l [],       /* PCM data for left channel     */
+        const int      buffer_r [],       /* PCM data for right channel    */
+        const int           nsamples,      /* number of samples per channel */
+        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */
+        const int           mp3buf_size ); /* number of valid octets in this
+                                              stream                        */
+
+/*
+ * as above, but for interleaved data.
+ * !! NOTE: !! data must still be scaled to be in the same range as
+ * type 'int32_t'.   Data should be in the range:  +/- 2^(8*size(int32_t)-1)
+ * NOTE:
+ * num_samples = number of samples in the L (or R)
+ * channel, not the total number of samples in pcm[]
+ */
+int
+lame_encode_buffer_interleaved_int(
+        lame_t          gfp,
+        const int       pcm [],            /* PCM data for left and right
+                                              channel, interleaved          */
+        const int       nsamples,          /* number of samples per channel,
+                                              _not_ number of samples in
+                                              pcm[]                         */
+        unsigned char*  mp3buf,            /* pointer to encoded MP3 stream */
+        const int       mp3buf_size );     /* number of valid octets in this
+                                              stream                        */
+
+
+
+/*
+ * REQUIRED:
+ * lame_encode_flush will flush the intenal PCM buffers, padding with
+ * 0's to make sure the final frame is complete, and then flush
+ * the internal MP3 buffers, and thus may return a
+ * final few mp3 frames.  'mp3buf' should be at least 7200 bytes long
+ * to hold all possible emitted data.
+ *
+ * will also write id3v1 tags (if any) into the bitstream
+ *
+ * return code = number of bytes output to mp3buf. Can be 0
+ */
+int CDECL lame_encode_flush(
+        lame_global_flags *  gfp,    /* global context handle                 */
+        unsigned char*       mp3buf, /* pointer to encoded MP3 stream         */
+        int                  size);  /* number of valid octets in this stream */
+
+/*
+ * OPTIONAL:
+ * lame_encode_flush_nogap will flush the internal mp3 buffers and pad
+ * the last frame with ancillary data so it is a complete mp3 frame.
+ *
+ * 'mp3buf' should be at least 7200 bytes long
+ * to hold all possible emitted data.
+ *
+ * After a call to this routine, the outputed mp3 data is complete, but
+ * you may continue to encode new PCM samples and write future mp3 data
+ * to a different file.  The two mp3 files will play back with no gaps
+ * if they are concatenated together.
+ *
+ * This routine will NOT write id3v1 tags into the bitstream.
+ *
+ * return code = number of bytes output to mp3buf. Can be 0
+ */
+int CDECL lame_encode_flush_nogap(
+        lame_global_flags *  gfp,    /* global context handle                 */
+        unsigned char*       mp3buf, /* pointer to encoded MP3 stream         */
+        int                  size);  /* number of valid octets in this stream */
+
+/*
+ * OPTIONAL:
+ * Normally, this is called by lame_init_params().  It writes id3v2 and
+ * Xing headers into the front of the bitstream, and sets frame counters
+ * and bitrate histogram data to 0.  You can also call this after
+ * lame_encode_flush_nogap().
+ */
+int CDECL lame_init_bitstream(
+        lame_global_flags *  gfp);    /* global context handle                 */
+
+
+
+/*
+ * OPTIONAL:    some simple statistics
+ * a bitrate histogram to visualize the distribution of used frame sizes
+ * a stereo mode histogram to visualize the distribution of used stereo
+ *   modes, useful in joint-stereo mode only
+ *   0: LR    left-right encoded
+ *   1: LR-I  left-right and intensity encoded (currently not supported)
+ *   2: MS    mid-side encoded
+ *   3: MS-I  mid-side and intensity encoded (currently not supported)
+ *
+ * attention: don't call them after lame_encode_finish
+ * suggested: lame_encode_flush -> lame_*_hist -> lame_close
+ */
+
+void CDECL lame_bitrate_hist(
+        const lame_global_flags * gfp,
+        int bitrate_count[14] );
+void CDECL lame_bitrate_kbps(
+        const lame_global_flags * gfp,
+        int bitrate_kbps [14] );
+void CDECL lame_stereo_mode_hist(
+        const lame_global_flags * gfp,
+        int stereo_mode_count[4] );
+
+void CDECL lame_bitrate_stereo_mode_hist (
+        const lame_global_flags * gfp,
+        int bitrate_stmode_count[14][4] );
+
+void CDECL lame_block_type_hist (
+        const lame_global_flags * gfp,
+        int btype_count[6] );
+
+void CDECL lame_bitrate_block_type_hist (
+        const lame_global_flags * gfp,
+        int bitrate_btype_count[14][6] );
+
+#if (DEPRECATED_OR_OBSOLETE_CODE_REMOVED && 0)
+#else
+/*
+ * OPTIONAL:
+ * lame_mp3_tags_fid will rewrite a Xing VBR tag to the mp3 file with file
+ * pointer fid.  These calls perform forward and backwards seeks, so make
+ * sure fid is a real file.  Make sure lame_encode_flush has been called,
+ * and all mp3 data has been written to the file before calling this
+ * function.
+ * NOTE:
+ * if VBR  tags are turned off by the user, or turned off by LAME because
+ * the output is not a regular file, this call does nothing
+ * NOTE:
+ * LAME wants to read from the file to skip an optional ID3v2 tag, so
+ * make sure you opened the file for writing and reading.
+ * NOTE:
+ * You can call lame_get_lametag_frame instead, if you want to insert
+ * the lametag yourself.
+*/
+void CDECL lame_mp3_tags_fid(lame_global_flags *, FILE* fid);
+#endif
+
+/*
+ * OPTIONAL:
+ * lame_get_lametag_frame copies the final LAME-tag into 'buffer'.
+ * The function returns the number of bytes copied into buffer, or
+ * the required buffer size, if the provided buffer is too small.
+ * Function failed, if the return value is larger than 'size'!
+ * Make sure lame_encode flush has been called before calling this function.
+ * NOTE:
+ * if VBR  tags are turned off by the user, or turned off by LAME,
+ * this call does nothing and returns 0.
+ * NOTE:
+ * LAME inserted an empty frame in the beginning of mp3 audio data,
+ * which you have to replace by the final LAME-tag frame after encoding.
+ * In case there is no ID3v2 tag, usually this frame will be the very first
+ * data in your mp3 file. If you put some other leading data into your
+ * file, you'll have to do some bookkeeping about where to write this buffer.
+ */
+size_t CDECL lame_get_lametag_frame(
+        const lame_global_flags *, unsigned char* buffer, size_t size);
+
+/*
+ * REQUIRED:
+ * final call to free all remaining buffers
+ */
+int  CDECL lame_close (lame_global_flags *);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/*
+ * OBSOLETE:
+ * lame_encode_finish combines lame_encode_flush() and lame_close() in
+ * one call.  However, once this call is made, the statistics routines
+ * will no longer work because the data will have been cleared, and
+ * lame_mp3_tags_fid() cannot be called to add data to the VBR header
+ */
+int CDECL lame_encode_finish(
+        lame_global_flags*  gfp,
+        unsigned char*      mp3buf,
+        int                 size );
+#endif
+
+
+
+
+
+
+/*********************************************************************
+ *
+ * decoding
+ *
+ * a simple interface to mpglib, part of mpg123, is also included if
+ * libmp3lame is compiled with HAVE_MPGLIB
+ *
+ *********************************************************************/
+
+struct hip_global_struct;
+typedef struct hip_global_struct hip_global_flags;
+typedef hip_global_flags *hip_t;
+
+
+typedef struct {
+  int header_parsed;   /* 1 if header was parsed and following data was
+                          computed                                       */
+  int stereo;          /* number of channels                             */
+  int samplerate;      /* sample rate                                    */
+  int bitrate;         /* bitrate                                        */
+  int mode;            /* mp3 frame type                                 */
+  int mode_ext;        /* mp3 frame type                                 */
+  int framesize;       /* number of samples per mp3 frame                */
+
+  /* this data is only computed if mpglib detects a Xing VBR header */
+  unsigned long nsamp; /* number of samples in mp3 file.                 */
+  int totalframes;     /* total number of frames in mp3 file             */
+
+  /* this data is not currently computed by the mpglib routines */
+  int framenum;        /* frames decoded counter                         */
+} mp3data_struct;
+
+/* required call to initialize decoder */
+hip_t CDECL hip_decode_init(void);
+
+/* cleanup call to exit decoder  */
+int CDECL hip_decode_exit(hip_t gfp);
+
+/* HIP reporting functions */
+void CDECL hip_set_errorf(hip_t gfp, lame_report_function f);
+void CDECL hip_set_debugf(hip_t gfp, lame_report_function f);
+void CDECL hip_set_msgf  (hip_t gfp, lame_report_function f);
+
+/*********************************************************************
+ * input 1 mp3 frame, output (maybe) pcm data.
+ *
+ *  nout = hip_decode(hip, mp3buf,len,pcm_l,pcm_r);
+ *
+ * input:
+ *    len          :  number of bytes of mp3 data in mp3buf
+ *    mp3buf[len]  :  mp3 data to be decoded
+ *
+ * output:
+ *    nout:  -1    : decoding error
+ *            0    : need more data before we can complete the decode
+ *           >0    : returned 'nout' samples worth of data in pcm_l,pcm_r
+ *    pcm_l[nout]  : left channel data
+ *    pcm_r[nout]  : right channel data
+ *
+ *********************************************************************/
+int CDECL hip_decode( hip_t           gfp
+                    , unsigned char * mp3buf
+                    , size_t          len
+                    , short           pcm_l[]
+                    , short           pcm_r[]
+                    );
+
+/* same as hip_decode, and also returns mp3 header data */
+int CDECL hip_decode_headers( hip_t           gfp
+                            , unsigned char*  mp3buf
+                            , size_t          len
+                            , short           pcm_l[]
+                            , short           pcm_r[]
+                            , mp3data_struct* mp3data
+                            );
+
+/* same as hip_decode, but returns at most one frame */
+int CDECL hip_decode1( hip_t          gfp
+                     , unsigned char* mp3buf
+                     , size_t         len
+                     , short          pcm_l[]
+                     , short          pcm_r[]
+                     );
+
+/* same as hip_decode1, but returns at most one frame and mp3 header data */
+int CDECL hip_decode1_headers( hip_t           gfp
+                             , unsigned char*  mp3buf
+                             , size_t          len
+                             , short           pcm_l[]
+                             , short           pcm_r[]
+                             , mp3data_struct* mp3data
+                             );
+
+/* same as hip_decode1_headers, but also returns enc_delay and enc_padding
+   from VBR Info tag, (-1 if no info tag was found) */
+int CDECL hip_decode1_headersB( hip_t gfp
+                              , unsigned char*   mp3buf
+                              , size_t           len
+                              , short            pcm_l[]
+                              , short            pcm_r[]
+                              , mp3data_struct*  mp3data
+                              , int             *enc_delay
+                              , int             *enc_padding
+                              );
+
+
+
+/* OBSOLETE:
+ * lame_decode... functions are there to keep old code working
+ * but it is strongly recommended to replace calls by hip_decode...
+ * function calls, see above.
+ */
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+int CDECL lame_decode_init(void);
+int CDECL lame_decode(
+        unsigned char *  mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[] );
+int CDECL lame_decode_headers(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data );
+int CDECL lame_decode1(
+        unsigned char*  mp3buf,
+        int             len,
+        short           pcm_l[],
+        short           pcm_r[] );
+int CDECL lame_decode1_headers(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data );
+int CDECL lame_decode1_headersB(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data,
+        int              *enc_delay,
+        int              *enc_padding );
+int CDECL lame_decode_exit(void);
+
+#endif /* obsolete lame_decode API calls */
+
+
+/*********************************************************************
+ *
+ * id3tag stuff
+ *
+ *********************************************************************/
+
+/*
+ * id3tag.h -- Interface to write ID3 version 1 and 2 tags.
+ *
+ * Copyright (C) 2000 Don Melton.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+/* utility to obtain alphabetically sorted list of genre names with numbers */
+void CDECL id3tag_genre_list(
+        void (*handler)(int, const char *, void *),
+        void*  cookie);
+
+void CDECL id3tag_init     (lame_t gfp);
+
+/* force addition of version 2 tag */
+void CDECL id3tag_add_v2   (lame_t gfp);
+
+/* add only a version 1 tag */
+void CDECL id3tag_v1_only  (lame_t gfp);
+
+/* add only a version 2 tag */
+void CDECL id3tag_v2_only  (lame_t gfp);
+
+/* pad version 1 tag with spaces instead of nulls */
+void CDECL id3tag_space_v1 (lame_t gfp);
+
+/* pad version 2 tag with extra 128 bytes */
+void CDECL id3tag_pad_v2   (lame_t gfp);
+
+/* pad version 2 tag with extra n bytes */
+void CDECL id3tag_set_pad  (lame_t gfp, size_t n);
+
+void CDECL id3tag_set_title(lame_t gfp, const char* title);
+void CDECL id3tag_set_artist(lame_t gfp, const char* artist);
+void CDECL id3tag_set_album(lame_t gfp, const char* album);
+void CDECL id3tag_set_year(lame_t gfp, const char* year);
+void CDECL id3tag_set_comment(lame_t gfp, const char* comment);
+            
+/* return -1 result if track number is out of ID3v1 range
+                    and ignored for ID3v1 */
+int CDECL id3tag_set_track(lame_t gfp, const char* track);
+
+/* return non-zero result if genre name or number is invalid
+  result 0: OK
+  result -1: genre number out of range
+  result -2: no valid ID3v1 genre name, mapped to ID3v1 'Other'
+             but taken as-is for ID3v2 genre tag */
+int CDECL id3tag_set_genre(lame_t gfp, const char* genre);
+
+/* return non-zero result if field name is invalid */
+int CDECL id3tag_set_fieldvalue(lame_t gfp, const char* fieldvalue);
+
+/* return non-zero result if image type is invalid */
+int CDECL id3tag_set_albumart(lame_t gfp, const char* image, size_t size);
+
+/* lame_get_id3v1_tag copies ID3v1 tag into buffer.
+ * Function returns number of bytes copied into buffer, or number
+ * of bytes rquired if buffer 'size' is too small.
+ * Function fails, if returned value is larger than 'size'.
+ * NOTE:
+ * This functions does nothing, if user/LAME disabled ID3v1 tag.
+ */
+size_t CDECL lame_get_id3v1_tag(lame_t gfp, unsigned char* buffer, size_t size);
+
+/* lame_get_id3v2_tag copies ID3v2 tag into buffer.
+ * Function returns number of bytes copied into buffer, or number
+ * of bytes rquired if buffer 'size' is too small.
+ * Function fails, if returned value is larger than 'size'.
+ * NOTE:
+ * This functions does nothing, if user/LAME disabled ID3v2 tag.
+ */
+size_t CDECL lame_get_id3v2_tag(lame_t gfp, unsigned char* buffer, size_t size);
+
+/* normaly lame_init_param writes ID3v2 tags into the audio stream
+ * Call lame_set_write_id3tag_automatic(gfp, 0) before lame_init_param
+ * to turn off this behaviour and get ID3v2 tag with above function
+ * write it yourself into your file.
+ */
+void CDECL lame_set_write_id3tag_automatic(lame_global_flags * gfp, int);
+int CDECL lame_get_write_id3tag_automatic(lame_global_flags const* gfp);
+
+/* experimental */
+int CDECL id3tag_set_textinfo_latin1(lame_t gfp, char const *id, char const *text);
+
+/* experimental */
+int CDECL id3tag_set_comment_latin1(lame_t gfp, char const *lang, char const *desc, char const *text);
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+#else
+/* experimental */
+int CDECL id3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text);
+
+/* experimental */
+int CDECL id3tag_set_comment_ucs2(lame_t gfp, char const *lang,
+                                  unsigned short const *desc, unsigned short const *text);
+
+/* experimental */
+int CDECL id3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue);
+#endif
+
+/* experimental */
+int CDECL id3tag_set_fieldvalue_utf16(lame_t gfp, const unsigned short *fieldvalue);
+
+/* experimental */
+int CDECL id3tag_set_textinfo_utf16(lame_t gfp, char const *id, unsigned short const *text);
+
+/* experimental */
+int CDECL id3tag_set_comment_utf16(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text);
+
+
+/***********************************************************************
+*
+*  list of valid bitrates [kbps] & sample frequencies [Hz].
+*  first index: 0: MPEG-2   values  (sample frequencies 16...24 kHz)
+*               1: MPEG-1   values  (sample frequencies 32...48 kHz)
+*               2: MPEG-2.5 values  (sample frequencies  8...12 kHz)
+***********************************************************************/
+
+extern const int     bitrate_table    [3][16];
+extern const int     samplerate_table [3][ 4];
+
+/* access functions for use in DLL, global vars are not exported */
+int CDECL lame_get_bitrate(int mpeg_version, int table_index);
+int CDECL lame_get_samplerate(int mpeg_version, int table_index);
+
+
+/* maximum size of albumart image (128KB), which affects LAME_MAXMP3BUFFER
+   as well since lame_encode_buffer() also returns ID3v2 tag data */
+#define LAME_MAXALBUMART    (128 * 1024)
+
+/* maximum size of mp3buffer needed if you encode at most 1152 samples for
+   each call to lame_encode_buffer.  see lame_encode_buffer() below  
+   (LAME_MAXMP3BUFFER is now obsolete)  */
+#define LAME_MAXMP3BUFFER   (16384 + LAME_MAXALBUMART)
+
+
+typedef enum {
+    LAME_OKAY             =   0,
+    LAME_NOERROR          =   0,
+    LAME_GENERICERROR     =  -1,
+    LAME_NOMEM            = -10,
+    LAME_BADBITRATE       = -11,
+    LAME_BADSAMPFREQ      = -12,
+    LAME_INTERNALERROR    = -13,
+
+    FRONTEND_READERROR    = -80,
+    FRONTEND_WRITEERROR   = -81,
+    FRONTEND_FILETOOLARGE = -82
+
+} lame_errorcodes_t;
+
+#if defined(__cplusplus)
+}
+#endif
+#endif /* LAME_LAME_H */
+
diff --git a/lame/libmp3lame/VbrTag.c b/lame/libmp3lame/VbrTag.c
new file mode 100644 (file)
index 0000000..5800a44
--- /dev/null
@@ -0,0 +1,1082 @@
+/*
+ *      Xing VBR tagging for LAME.
+ *
+ *      Copyright (c) 1999 A.L. Faber
+ *      Copyright (c) 2001 Jonathan Dee
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: VbrTag.c,v 1.106 2017/08/06 18:15:47 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "bitstream.h"
+#include "VbrTag.h"
+#include "lame_global_flags.h"
+#include "tables.h"
+
+#ifdef __sun__
+/* woraround for SunOS 4.x, it has SEEK_* defined here */
+#include <unistd.h>
+#endif
+
+
+#ifdef _DEBUG
+/*  #define DEBUG_VBRTAG */
+#endif
+
+/*
+ *    4 bytes for Header Tag
+ *    4 bytes for Header Flags
+ *  100 bytes for entry (NUMTOCENTRIES)
+ *    4 bytes for FRAME SIZE
+ *    4 bytes for STREAM_SIZE
+ *    4 bytes for VBR SCALE. a VBR quality indicator: 0=best 100=worst
+ *   20 bytes for LAME tag.  for example, "LAME3.12 (beta 6)"
+ * ___________
+ *  140 bytes
+*/
+#define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)
+
+#define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)
+
+/* the size of the Xing header (MPEG1 and MPEG2) in kbps */
+#define XING_BITRATE1 128
+#define XING_BITRATE2  64
+#define XING_BITRATE25 32
+
+extern const char* get_lame_tag_encoder_short_version(void);
+
+static const char VBRTag0[] = { "Xing" };
+static const char VBRTag1[] = { "Info" };
+
+
+
+
+/* Lookup table for fast CRC computation
+ * See 'CRC_update_lookup'
+ * Uses the polynomial x^16+x^15+x^2+1 */
+
+static const unsigned int crc16_lookup[256] = {
+    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
+    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
+    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
+    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
+    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
+    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
+    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
+    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
+    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
+    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
+    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
+    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
+    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
+    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
+    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
+    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
+    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
+    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
+    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
+    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
+    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
+    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
+    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
+    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
+    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
+    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
+    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
+    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
+    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
+    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
+    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
+    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
+};
+
+
+
+
+
+/***********************************************************************
+ *  Robert Hegemann 2001-01-17
+ ***********************************************************************/
+
+static void
+addVbr(VBR_seek_info_t * v, int bitrate)
+{
+    int     i;
+
+    v->nVbrNumFrames++;
+    v->sum += bitrate;
+    v->seen++;
+
+    if (v->seen < v->want) {
+        return;
+    }
+
+    if (v->pos < v->size) {
+        v->bag[v->pos] = v->sum;
+        v->pos++;
+        v->seen = 0;
+    }
+    if (v->pos == v->size) {
+        for (i = 1; i < v->size; i += 2) {
+            v->bag[i / 2] = v->bag[i];
+        }
+        v->want *= 2;
+        v->pos /= 2;
+    }
+}
+
+static void
+Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
+{
+    int     i, indx;
+    int     seek_point;
+
+    if (v->pos <= 0)
+        return;
+
+    for (i = 1; i < NUMTOCENTRIES; ++i) {
+        float   j = i / (float) NUMTOCENTRIES, act, sum;
+        indx = (int) (floor(j * v->pos));
+        if (indx > v->pos - 1)
+            indx = v->pos - 1;
+        act = v->bag[indx];
+        sum = v->sum;
+        seek_point = (int) (256. * act / sum);
+        if (seek_point > 255)
+            seek_point = 255;
+        t[i] = seek_point;
+    }
+}
+
+#ifdef DEBUG_VBR_SEEKING_TABLE
+static void
+print_seeking(unsigned char *t)
+{
+    int     i;
+
+    printf("seeking table ");
+    for (i = 0; i < NUMTOCENTRIES; ++i) {
+        printf(" %d ", t[i]);
+    }
+    printf("\n");
+}
+#endif
+
+
+/****************************************************************************
+ * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
+ * Paramters:
+ *      nStreamPos: how many bytes did we write to the bitstream so far
+ *                              (in Bytes NOT Bits)
+ ****************************************************************************
+*/
+void
+AddVbrFrame(lame_internal_flags * gfc)
+{
+    int     kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];
+    assert(gfc->VBR_seek_table.bag);
+    addVbr(&gfc->VBR_seek_table, kbps);
+}
+
+
+/*-------------------------------------------------------------*/
+static int
+ExtractI4(const unsigned char *buf)
+{
+    int     x;
+    /* big endian extract */
+    x = buf[0];
+    x <<= 8;
+    x |= buf[1];
+    x <<= 8;
+    x |= buf[2];
+    x <<= 8;
+    x |= buf[3];
+    return x;
+}
+
+static void
+CreateI4(unsigned char *buf, uint32_t nValue)
+{
+    /* big endian create */
+    buf[0] = (nValue >> 24) & 0xff;
+    buf[1] = (nValue >> 16) & 0xff;
+    buf[2] = (nValue >> 8) & 0xff;
+    buf[3] = (nValue) & 0xff;
+}
+
+
+
+static void
+CreateI2(unsigned char *buf, int nValue)
+{
+    /* big endian create */
+    buf[0] = (nValue >> 8) & 0xff;
+    buf[1] = (nValue) & 0xff;
+}
+
+/* check for magic strings*/
+static int
+IsVbrTag(const unsigned char *buf)
+{
+    int     isTag0, isTag1;
+
+    isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])
+              && (buf[3] == VBRTag0[3]));
+    isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])
+              && (buf[3] == VBRTag1[3]));
+
+    return (isTag0 || isTag1);
+}
+
+#define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
+
+static void
+setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t const *const eov = &gfc->ov_enc;
+    char    abyte, bbyte;
+
+    SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
+
+    SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);
+    SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);
+    SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);
+    SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);
+    SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);
+
+    SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);
+    SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);
+    SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);
+    SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);
+
+    SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);
+    SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);
+    SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);
+    SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);
+    SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);
+
+    /* the default VBR header. 48 kbps layer III, no padding, no crc */
+    /* but sampling freq, mode andy copyright/copy protection taken */
+    /* from first valid frame */
+    buffer[0] = (uint8_t) 0xff;
+    abyte = (buffer[1] & (unsigned char) 0xf1);
+    {
+        int     bitrate;
+        if (1 == cfg->version) {
+            bitrate = XING_BITRATE1;
+        }
+        else {
+            if (cfg->samplerate_out < 16000)
+                bitrate = XING_BITRATE25;
+            else
+                bitrate = XING_BITRATE2;
+        }
+
+        if (cfg->vbr == vbr_off)
+            bitrate = cfg->avg_bitrate;
+
+        if (cfg->free_format)
+            bbyte = 0x00;
+        else
+            bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
+    }
+
+    /* Use as much of the info from the real frames in the
+     * Xing header:  samplerate, channels, crc, etc...
+     */
+    if (cfg->version == 1) {
+        /* MPEG1 */
+        buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */
+        abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
+        buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */
+    }
+    else {
+        /* MPEG2 */
+        buffer[1] = abyte | (char) 0x02; /* was 0x03; */
+        abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
+        buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */
+    }
+}
+
+#if 0
+static int CheckVbrTag(unsigned char *buf);
+
+/*-------------------------------------------------------------*/
+/* Same as GetVbrTag below, but only checks for the Xing tag.
+   requires buf to contain only 40 bytes */
+/*-------------------------------------------------------------*/
+int
+CheckVbrTag(unsigned char *buf)
+{
+    int     h_id, h_mode;
+
+    /* get selected MPEG header data */
+    h_id = (buf[1] >> 3) & 1;
+    h_mode = (buf[3] >> 6) & 3;
+
+    /*  determine offset of header */
+    if (h_id) {
+        /* mpeg1 */
+        if (h_mode != 3)
+            buf += (32 + 4);
+        else
+            buf += (17 + 4);
+    }
+    else {
+        /* mpeg2 */
+        if (h_mode != 3)
+            buf += (17 + 4);
+        else
+            buf += (9 + 4);
+    }
+
+    return IsVbrTag(buf);
+}
+#endif
+
+int
+GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
+{
+    int     i, head_flags;
+    int     h_bitrate, h_id, h_mode, h_sr_index, h_layer;
+    int     enc_delay, enc_padding;
+
+    /* get Vbr header data */
+    pTagData->flags = 0;
+
+    /* get selected MPEG header data */
+    h_layer = (buf[1] >> 1) & 3;
+    if ( h_layer != 0x01 ) {
+        /* the following code assumes Layer-3, so give up here */
+        return 0;
+    }
+    h_id = (buf[1] >> 3) & 1;
+    h_sr_index = (buf[2] >> 2) & 3;
+    h_mode = (buf[3] >> 6) & 3;
+    h_bitrate = ((buf[2] >> 4) & 0xf);
+    h_bitrate = bitrate_table[h_id][h_bitrate];
+
+    /* check for FFE syncword */
+    if ((buf[1] >> 4) == 0xE)
+        pTagData->samprate = samplerate_table[2][h_sr_index];
+    else
+        pTagData->samprate = samplerate_table[h_id][h_sr_index];
+    /* if( h_id == 0 ) */
+    /*  pTagData->samprate >>= 1; */
+
+
+
+    /*  determine offset of header */
+    if (h_id) {
+        /* mpeg1 */
+        if (h_mode != 3)
+            buf += (32 + 4);
+        else
+            buf += (17 + 4);
+    }
+    else {
+        /* mpeg2 */
+        if (h_mode != 3)
+            buf += (17 + 4);
+        else
+            buf += (9 + 4);
+    }
+
+    if (!IsVbrTag(buf))
+        return 0;
+
+    buf += 4;
+
+    pTagData->h_id = h_id;
+
+    head_flags = pTagData->flags = ExtractI4(buf);
+    buf += 4;           /* get flags */
+
+    if (head_flags & FRAMES_FLAG) {
+        pTagData->frames = ExtractI4(buf);
+        buf += 4;
+    }
+
+    if (head_flags & BYTES_FLAG) {
+        pTagData->bytes = ExtractI4(buf);
+        buf += 4;
+    }
+
+    if (head_flags & TOC_FLAG) {
+        if (pTagData->toc != NULL) {
+            for (i = 0; i < NUMTOCENTRIES; i++)
+                pTagData->toc[i] = buf[i];
+        }
+        buf += NUMTOCENTRIES;
+    }
+
+    pTagData->vbr_scale = -1;
+
+    if (head_flags & VBR_SCALE_FLAG) {
+        pTagData->vbr_scale = ExtractI4(buf);
+        buf += 4;
+    }
+
+    pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
+
+    buf += 21;
+    enc_delay = buf[0] << 4;
+    enc_delay += buf[1] >> 4;
+    enc_padding = (buf[1] & 0x0F) << 8;
+    enc_padding += buf[2];
+    /* check for reasonable values (this may be an old Xing header, */
+    /* not a INFO tag) */
+    if (enc_delay < 0 || enc_delay > 3000)
+        enc_delay = -1;
+    if (enc_padding < 0 || enc_padding > 3000)
+        enc_padding = -1;
+
+    pTagData->enc_delay = enc_delay;
+    pTagData->enc_padding = enc_padding;
+
+#ifdef DEBUG_VBRTAG
+    fprintf(stderr, "\n\n********************* VBR TAG INFO *****************\n");
+    fprintf(stderr, "tag         :%s\n", VBRTag);
+    fprintf(stderr, "head_flags  :%d\n", head_flags);
+    fprintf(stderr, "bytes       :%d\n", pTagData->bytes);
+    fprintf(stderr, "frames      :%d\n", pTagData->frames);
+    fprintf(stderr, "VBR Scale   :%d\n", pTagData->vbr_scale);
+    fprintf(stderr, "enc_delay  = %i \n", enc_delay);
+    fprintf(stderr, "enc_padding= %i \n", enc_padding);
+    fprintf(stderr, "toc:\n");
+    if (pTagData->toc != NULL) {
+        for (i = 0; i < NUMTOCENTRIES; i++) {
+            if ((i % 10) == 0)
+                fprintf(stderr, "\n");
+            fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
+        }
+    }
+    fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
+#endif
+    return 1;           /* success */
+}
+
+
+/****************************************************************************
+ * InitVbrTag: Initializes the header, and write empty frame to stream
+ * Paramters:
+ *                              fpStream: pointer to output file stream
+ *                              nMode   : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
+ ****************************************************************************
+*/
+int
+InitVbrTag(lame_global_flags * gfp)
+{
+    lame_internal_flags *gfc = gfp->internal_flags;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     kbps_header;
+
+#define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
+
+    /*
+     * Xing VBR pretends to be a 48kbs layer III frame.  (at 44.1kHz).
+     * (at 48kHz they use 56kbs since 48kbs frame not big enough for
+     * table of contents)
+     * let's always embed Xing header inside a 64kbs layer III frame.
+     * this gives us enough room for a LAME version string too.
+     * size determined by sampling frequency (MPEG1)
+     * 32kHz:    216 bytes@48kbs    288bytes@ 64kbs
+     * 44.1kHz:  156 bytes          208bytes@64kbs     (+1 if padding = 1)
+     * 48kHz:    144 bytes          192
+     *
+     * MPEG 2 values are the same since the framesize and samplerate
+     * are each reduced by a factor of 2.
+     */
+
+
+    if (1 == cfg->version) {
+        kbps_header = XING_BITRATE1;
+    }
+    else {
+        if (cfg->samplerate_out < 16000)
+            kbps_header = XING_BITRATE25;
+        else
+            kbps_header = XING_BITRATE2;
+    }
+
+    if (cfg->vbr == vbr_off)
+        kbps_header = cfg->avg_bitrate;
+
+    /** make sure LAME Header fits into Frame
+     */
+    {
+        int     total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;
+        int     header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);
+        gfc->VBR_seek_table.TotalFrameSize = total_frame_size;
+        if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {
+            /* disable tag, it wont fit */
+            gfc->cfg.write_lame_tag = 0;
+            return 0;
+        }
+    }
+
+    gfc->VBR_seek_table.nVbrNumFrames = 0;
+    gfc->VBR_seek_table.nBytesWritten = 0;
+    gfc->VBR_seek_table.sum = 0;
+
+    gfc->VBR_seek_table.seen = 0;
+    gfc->VBR_seek_table.want = 1;
+    gfc->VBR_seek_table.pos = 0;
+
+    if (gfc->VBR_seek_table.bag == NULL) {
+        gfc->VBR_seek_table.bag = lame_calloc(int, 400);
+        if (gfc->VBR_seek_table.bag != NULL) {
+            gfc->VBR_seek_table.size = 400;
+        }
+        else {
+            gfc->VBR_seek_table.size = 0;
+            ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
+            gfc->cfg.write_lame_tag = 0;
+            return -1;
+        }
+    }
+
+    /* write dummy VBR tag of all 0's into bitstream */
+    {
+        uint8_t buffer[MAXFRAMESIZE];
+        size_t  i, n;
+
+        memset(buffer, 0, sizeof(buffer));
+        setLameTagFrameHeader(gfc, buffer);
+        n = gfc->VBR_seek_table.TotalFrameSize;
+        for (i = 0; i < n; ++i) {
+            add_dummy_byte(gfc, buffer[i], 1);
+        }
+    }
+    /* Success */
+    return 0;
+}
+
+
+
+/* fast CRC-16 computation - uses table crc16_lookup 8*/
+static uint16_t
+CRC_update_lookup(uint16_t value, uint16_t crc)
+{
+    uint16_t tmp;
+    tmp = crc ^ value;
+    crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];
+    return crc;
+}
+
+void
+UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
+{
+    int     i;
+    for (i = 0; i < size; ++i)
+        *crc = CRC_update_lookup(buffer[i], *crc);
+}
+
+
+
+
+
+/****************************************************************************
+ * Jonathan Dee 2001/08/31
+ *
+ * PutLameVBR: Write LAME info: mini version + info on various switches used
+ * Paramters:
+ *                              pbtStreamBuffer : pointer to output buffer
+ *                              id3v2size               : size of id3v2 tag in bytes
+ *                              crc                             : computation of crc-16 of Lame Tag so far (starting at frame sync)
+ *
+ ****************************************************************************
+*/
+static int
+PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
+{
+    lame_internal_flags const *gfc = gfp->internal_flags;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+
+    int     nBytesWritten = 0;
+    int     i;
+
+    int     enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
+    int     enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding  */
+
+    /*recall: cfg->vbr_q is for example set by the switch -V  */
+    /*   gfp->quality by -q, -h, -f, etc */
+
+    int     nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
+
+
+    /*
+    NOTE:
+            Even though the specification for the LAME VBR tag
+            did explicitly mention other encoders than LAME,
+            many SW/HW decoder seem to be able to make use of
+            this tag only, if the encoder version starts with LAME.
+            To be compatible with such decoders, ANY encoder will
+            be forced to write a fake LAME version string!
+            As a result, the encoder version info becomes worthless.
+    */
+    const char *szVersion = get_lame_tag_encoder_short_version();
+    uint8_t nVBR;
+    uint8_t nRevision = 0x00;
+    uint8_t nRevMethod;
+    uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
+
+    uint8_t nLowpass =
+        (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
+
+    uint32_t nPeakSignalAmplitude = 0;
+
+    uint16_t nRadioReplayGain = 0;
+    uint16_t nAudiophileReplayGain = 0;
+
+    uint8_t nNoiseShaping = cfg->noise_shaping;
+    uint8_t nStereoMode = 0;
+    int     bNonOptimal = 0;
+    uint8_t nSourceFreq = 0;
+    uint8_t nMisc = 0;
+    uint16_t nMusicCRC = 0;
+
+    /*psy model type: Gpsycho or NsPsytune */
+    unsigned char bExpNPsyTune = 1; /* only NsPsytune */
+    unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
+
+    unsigned char bNoGapMore = 0;
+    unsigned char bNoGapPrevious = 0;
+
+    int     nNoGapCount = gfp->nogap_total;
+    int     nNoGapCurr = gfp->nogap_current;
+
+
+    uint8_t nAthType = cfg->ATHtype; /*4 bits. */
+
+    uint8_t nFlags = 0;
+
+    /* if ABR, {store bitrate <=255} else { store "-b"} */
+    int     nABRBitrate;
+    switch (cfg->vbr) {
+    case vbr_abr:{
+            nABRBitrate = cfg->vbr_avg_bitrate_kbps;
+            break;
+        }
+    case vbr_off:{
+            nABRBitrate = cfg->avg_bitrate;
+            break;
+        }
+    default:{          /*vbr modes */
+            nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
+        }
+    }
+
+
+    /*revision and vbr method */
+    if (cfg->vbr < sizeof(vbr_type_translator))
+        nVBR = vbr_type_translator[cfg->vbr];
+    else
+        nVBR = 0x00;    /*unknown. */
+
+    nRevMethod = 0x10 * nRevision + nVBR;
+
+
+    /* ReplayGain */
+    if (cfg->findReplayGain) {
+        int     RadioGain = gfc->ov_rpg.RadioGain;
+        if (RadioGain > 0x1FE)
+            RadioGain = 0x1FE;
+        if (RadioGain < -0x1FE)
+            RadioGain = -0x1FE;
+
+        nRadioReplayGain = 0x2000; /* set name code */
+        nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
+
+        if (RadioGain >= 0)
+            nRadioReplayGain |= RadioGain; /* set gain adjustment */
+        else {
+            nRadioReplayGain |= 0x200; /* set the sign bit */
+            nRadioReplayGain |= -RadioGain; /* set gain adjustment */
+        }
+    }
+
+    /* peak sample */
+    if (cfg->findPeakSample)
+        nPeakSignalAmplitude =
+            abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
+
+    /*nogap */
+    if (nNoGapCount != -1) {
+        if (nNoGapCurr > 0)
+            bNoGapPrevious = 1;
+
+        if (nNoGapCurr < nNoGapCount - 1)
+            bNoGapMore = 1;
+    }
+
+    /*flags */
+
+    nFlags = nAthType + (bExpNPsyTune << 4)
+        + (bSafeJoint << 5)
+        + (bNoGapMore << 6)
+        + (bNoGapPrevious << 7);
+
+
+    if (nQuality < 0)
+        nQuality = 0;
+
+    /*stereo mode field... a bit ugly. */
+
+    switch (cfg->mode) {
+    case MONO:
+        nStereoMode = 0;
+        break;
+    case STEREO:
+        nStereoMode = 1;
+        break;
+    case DUAL_CHANNEL:
+        nStereoMode = 2;
+        break;
+    case JOINT_STEREO:
+        if (cfg->force_ms)
+            nStereoMode = 4;
+        else
+            nStereoMode = 3;
+        break;
+    case NOT_SET:
+        /* FALLTHROUGH */
+    default:
+        nStereoMode = 7;
+        break;
+    }
+
+    /*Intensity stereo : nStereoMode = 6. IS is not implemented */
+
+    if (cfg->samplerate_in <= 32000)
+        nSourceFreq = 0x00;
+    else if (cfg->samplerate_in == 48000)
+        nSourceFreq = 0x02;
+    else if (cfg->samplerate_in > 48000)
+        nSourceFreq = 0x03;
+    else
+        nSourceFreq = 0x01; /*default is 44100Hz. */
+
+
+    /*Check if the user overrided the default LAME behaviour with some nasty options */
+
+    if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* "-k" */
+        (cfg->disable_reservoir && cfg->avg_bitrate < 320) ||
+        cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)
+        bNonOptimal = 1;
+
+    nMisc = nNoiseShaping + (nStereoMode << 2)
+        + (bNonOptimal << 5)
+        + (nSourceFreq << 6);
+
+
+    nMusicCRC = gfc->nMusicCRC;
+
+
+    /*Write all this information into the stream */
+    CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
+    nBytesWritten += 4;
+
+    strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
+    nBytesWritten += 9;
+
+    pbtStreamBuffer[nBytesWritten] = nRevMethod;
+    nBytesWritten++;
+
+    pbtStreamBuffer[nBytesWritten] = nLowpass;
+    nBytesWritten++;
+
+    CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
+    nBytesWritten += 4;
+
+    CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
+    nBytesWritten += 2;
+
+    CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
+    nBytesWritten += 2;
+
+    pbtStreamBuffer[nBytesWritten] = nFlags;
+    nBytesWritten++;
+
+    if (nABRBitrate >= 255)
+        pbtStreamBuffer[nBytesWritten] = 0xFF;
+    else
+        pbtStreamBuffer[nBytesWritten] = nABRBitrate;
+    nBytesWritten++;
+
+    pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */
+    pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);
+    pbtStreamBuffer[nBytesWritten + 2] = enc_padding;
+
+    nBytesWritten += 3;
+
+    pbtStreamBuffer[nBytesWritten] = nMisc;
+    nBytesWritten++;
+
+
+    pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
+
+    CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
+    nBytesWritten += 2;
+
+    CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
+    nBytesWritten += 4;
+
+    CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
+    nBytesWritten += 2;
+
+    /*Calculate tag CRC.... must be done here, since it includes
+     *previous information*/
+
+    for (i = 0; i < nBytesWritten; i++)
+        crc = CRC_update_lookup(pbtStreamBuffer[i], crc);
+
+    CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
+    nBytesWritten += 2;
+
+    return nBytesWritten;
+}
+
+static long
+skipId3v2(FILE * fpStream)
+{
+    size_t  nbytes;
+    long    id3v2TagSize;
+    unsigned char id3v2Header[10];
+
+    /* seek to the beginning of the stream */
+    if (fseek(fpStream, 0, SEEK_SET) != 0) {
+        return -2;      /* not seekable, abort */
+    }
+    /* read 10 bytes in case there's an ID3 version 2 header here */
+    nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
+    if (nbytes != sizeof(id3v2Header)) {
+        return -3;      /* not readable, maybe opened Write-Only */
+    }
+    /* does the stream begin with the ID3 version 2 file identifier? */
+    if (!strncmp((char *) id3v2Header, "ID3", 3)) {
+        /* the tag size (minus the 10-byte header) is encoded into four
+         * bytes where the most significant bit is clear in each byte */
+        id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
+                        | ((id3v2Header[7] & 0x7f) << 14)
+                        | ((id3v2Header[8] & 0x7f) << 7)
+                        | (id3v2Header[9] & 0x7f))
+            + sizeof id3v2Header;
+    }
+    else {
+        /* no ID3 version 2 tag in this stream */
+        id3v2TagSize = 0;
+    }
+    return id3v2TagSize;
+}
+
+
+
+size_t
+lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
+{
+    lame_internal_flags *gfc;
+    SessionConfig_t const *cfg;
+    unsigned long stream_size;
+    unsigned int  nStreamIndex;
+    uint8_t btToc[NUMTOCENTRIES];
+
+    if (gfp == 0) {
+        return 0;
+    }
+    gfc = gfp->internal_flags;
+    if (gfc == 0) {
+        return 0;
+    }
+    if (!is_lame_internal_flags_valid(gfc)) {
+        return 0;
+    }
+    cfg = &gfc->cfg;
+    if (cfg->write_lame_tag == 0) {
+        return 0;
+    }
+    if (gfc->VBR_seek_table.pos <= 0) {
+        return 0;
+    }
+    if (size < gfc->VBR_seek_table.TotalFrameSize) {
+        return gfc->VBR_seek_table.TotalFrameSize;
+    }
+    if (buffer == 0) {
+        return 0;
+    }
+
+    memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
+
+    /* 4 bytes frame header */
+
+    setLameTagFrameHeader(gfc, buffer);
+
+    /* Clear all TOC entries */
+    memset(btToc, 0, sizeof(btToc));
+
+    if (cfg->free_format) {
+        int     i;
+        for (i = 1; i < NUMTOCENTRIES; ++i)
+            btToc[i] = 255 * i / 100;
+    }
+    else {
+        Xing_seek_table(&gfc->VBR_seek_table, btToc);
+    }
+#ifdef DEBUG_VBR_SEEKING_TABLE
+    print_seeking(btToc);
+#endif
+
+    /* Start writing the tag after the zero frame */
+    nStreamIndex = cfg->sideinfo_len;
+    /* note! Xing header specifies that Xing data goes in the
+     * ancillary data with NO ERROR PROTECTION.  If error protecton
+     * in enabled, the Xing data still starts at the same offset,
+     * and now it is in sideinfo data block, and thus will not
+     * decode correctly by non-Xing tag aware players */
+    if (cfg->error_protection)
+        nStreamIndex -= 2;
+
+    /* Put Vbr tag */
+    if (cfg->vbr == vbr_off) {
+        buffer[nStreamIndex++] = VBRTag1[0];
+        buffer[nStreamIndex++] = VBRTag1[1];
+        buffer[nStreamIndex++] = VBRTag1[2];
+        buffer[nStreamIndex++] = VBRTag1[3];
+
+    }
+    else {
+        buffer[nStreamIndex++] = VBRTag0[0];
+        buffer[nStreamIndex++] = VBRTag0[1];
+        buffer[nStreamIndex++] = VBRTag0[2];
+        buffer[nStreamIndex++] = VBRTag0[3];
+    }
+
+    /* Put header flags */
+    CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
+    nStreamIndex += 4;
+
+    /* Put Total Number of frames */
+    CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
+    nStreamIndex += 4;
+
+    /* Put total audio stream size, including Xing/LAME Header */
+    stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;
+    CreateI4(&buffer[nStreamIndex], stream_size);
+    nStreamIndex += 4;
+
+    /* Put TOC */
+    memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
+    nStreamIndex += sizeof(btToc);
+
+
+    if (cfg->error_protection) {
+        /* (jo) error_protection: add crc16 information to header */
+        CRC_writeheader(gfc, (char *) buffer);
+    }
+    {
+        /*work out CRC so far: initially crc = 0 */
+        uint16_t crc = 0x00;
+        unsigned int i;
+        for (i = 0; i < nStreamIndex; i++)
+            crc = CRC_update_lookup(buffer[i], crc);
+        /*Put LAME VBR info */
+        nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);
+    }
+
+#ifdef DEBUG_VBRTAG
+    {
+        VBRTAGDATA TestHeader;
+        GetVbrTag(&TestHeader, buffer);
+    }
+#endif
+
+    return gfc->VBR_seek_table.TotalFrameSize;
+}
+
+/***********************************************************************
+ *
+ * PutVbrTag: Write final VBR tag to the file
+ * Paramters:
+ *                              lpszFileName: filename of MP3 bit stream
+ *                              nVbrScale       : encoder quality indicator (0..100)
+ ****************************************************************************
+ */
+
+int
+PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
+{
+    lame_internal_flags *gfc = gfp->internal_flags;
+
+    long    lFileSize;
+    long    id3v2TagSize;
+    size_t  nbytes;
+    uint8_t buffer[MAXFRAMESIZE];
+
+    if (gfc->VBR_seek_table.pos <= 0)
+        return -1;
+
+    /* Seek to end of file */
+    fseek(fpStream, 0, SEEK_END);
+
+    /* Get file size */
+    lFileSize = ftell(fpStream);
+
+    /* Abort if file has zero length. Yes, it can happen :) */
+    if (lFileSize == 0)
+        return -1;
+
+    /*
+     * The VBR tag may NOT be located at the beginning of the stream.
+     * If an ID3 version 2 tag was added, then it must be skipped to write
+     * the VBR tag data.
+     */
+
+    id3v2TagSize = skipId3v2(fpStream);
+
+    if (id3v2TagSize < 0) {
+        return id3v2TagSize;
+    }
+
+    /*Seek to the beginning of the stream */
+    fseek(fpStream, id3v2TagSize, SEEK_SET);
+
+    nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
+    if (nbytes > sizeof(buffer)) {
+        return -1;
+    }
+
+    if (nbytes < 1) {
+        return 0;
+    }
+
+    /* Put it all to disk again */
+    if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
+        return -1;
+    }
+
+    return 0;           /* success */
+}
diff --git a/lame/libmp3lame/VbrTag.h b/lame/libmp3lame/VbrTag.h
new file mode 100644 (file)
index 0000000..406af36
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *      Xing VBR tagging for LAME.
+ *
+ *      Copyright (c) 1999 A.L. Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_VRBTAG_H
+#define LAME_VRBTAG_H
+
+
+/* -----------------------------------------------------------
+ * A Vbr header may be present in the ancillary
+ * data field of the first frame of an mp3 bitstream
+ * The Vbr header (optionally) contains
+ *      frames      total number of audio frames in the bitstream
+ *      bytes       total number of bytes in the bitstream
+ *      toc         table of contents
+
+ * toc (table of contents) gives seek points
+ * for random access
+ * the ith entry determines the seek point for
+ * i-percent duration
+ * seek point in bytes = (toc[i]/256.0) * total_bitstream_bytes
+ * e.g. half duration seek point = (toc[50]/256.0) * total_bitstream_bytes
+ */
+
+
+#define FRAMES_FLAG     0x0001
+#define BYTES_FLAG      0x0002
+#define TOC_FLAG        0x0004
+#define VBR_SCALE_FLAG  0x0008
+
+#define NUMTOCENTRIES 100
+
+#ifndef lame_internal_flags_defined
+#define lame_internal_flags_defined
+struct lame_internal_flags;
+typedef struct lame_internal_flags lame_internal_flags;
+#endif
+
+
+/*structure to receive extracted header */
+/* toc may be NULL*/
+typedef struct {
+    int     h_id;            /* from MPEG header, 0=MPEG2, 1=MPEG1 */
+    int     samprate;        /* determined from MPEG header */
+    int     flags;           /* from Vbr header data */
+    int     frames;          /* total bit stream frames from Vbr header data */
+    int     bytes;           /* total bit stream bytes from Vbr header data */
+    int     vbr_scale;       /* encoded vbr scale from Vbr header data */
+    unsigned char toc[NUMTOCENTRIES]; /* may be NULL if toc not desired */
+    int     headersize;      /* size of VBR header, in bytes */
+    int     enc_delay;       /* encoder delay */
+    int     enc_padding;     /* encoder paddign added at end of stream */
+} VBRTAGDATA;
+
+int     GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf);
+
+int     InitVbrTag(lame_global_flags * gfp);
+int     PutVbrTag(lame_global_flags const *gfp, FILE * fid);
+void    AddVbrFrame(lame_internal_flags * gfc);
+void    UpdateMusicCRC(uint16_t * crc, const unsigned char *buffer, int size);
+
+#endif
diff --git a/lame/libmp3lame/bitstream.c b/lame/libmp3lame/bitstream.c
new file mode 100644 (file)
index 0000000..aa35915
--- /dev/null
@@ -0,0 +1,1111 @@
+/*
+ *      MP3 bitstream Output interface for LAME
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *      Copyright (c) 1999-2002 Takehiro Tominaga
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ *
+ * $Id: bitstream.c,v 1.99 2017/08/31 14:14:46 robert Exp $
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "tables.h"
+#include "quantize_pvt.h"
+#include "lame_global_flags.h"
+#include "gain_analysis.h"
+#include "VbrTag.h"
+#include "bitstream.h"
+#include "tables.h"
+
+
+
+/* unsigned int is at least this large:  */
+/* we work with ints, so when doing bit manipulation, we limit
+ * ourselves to MAX_LENGTH-2 just to be on the safe side */
+#define MAX_LENGTH      32
+
+
+
+#ifdef DEBUG
+static int hogege;
+#endif
+
+
+
+static int
+calcFrameLength(SessionConfig_t const *const cfg, int kbps, int pad)
+{
+  return 8 * ((cfg->version + 1) * 72000 * kbps / cfg->samplerate_out + pad);
+}
+
+
+/***********************************************************************
+ * compute bitsperframe and mean_bits for a layer III frame
+ **********************************************************************/
+int
+getframebits(const lame_internal_flags * gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t const *const eov = &gfc->ov_enc;
+    int     bit_rate;
+
+    /* get bitrate in kbps [?] */
+    if (eov->bitrate_index)
+        bit_rate = bitrate_table[cfg->version][eov->bitrate_index];
+    else
+        bit_rate = cfg->avg_bitrate;
+    /*assert(bit_rate <= 550); */
+    assert(8 <= bit_rate && bit_rate <= 640);
+
+    /* main encoding routine toggles padding on and off */
+    /* one Layer3 Slot consists of 8 bits */
+    return calcFrameLength(cfg, bit_rate, eov->padding);
+}
+
+int
+get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint)
+{
+    int     maxmp3buf = 0;
+    if (cfg->avg_bitrate > 320) {
+        /* in freeformat the buffer is constant */
+        if (constraint == MDB_STRICT_ISO) {
+            maxmp3buf = calcFrameLength(cfg, cfg->avg_bitrate, 0);
+        }
+        else {
+            /* maximum allowed bits per granule are 7680 */
+            maxmp3buf = 7680 * (cfg->version + 1);
+        }
+    }
+    else {
+        int     max_kbps;
+        if (cfg->samplerate_out < 16000) {
+            max_kbps = bitrate_table[cfg->version][8]; /* default: allow 64 kbps (MPEG-2.5) */
+        }
+        else {
+            max_kbps = bitrate_table[cfg->version][14];
+        }
+        switch (constraint) 
+        {
+        default:
+        case MDB_DEFAULT:
+            /* Bouvigne suggests this more lax interpretation of the ISO doc instead of using 8*960. */
+            /* All mp3 decoders should have enough buffer to handle this value: size of a 320kbps 32kHz frame */
+            maxmp3buf = 8 * 1440;
+            break;
+        case MDB_STRICT_ISO:
+            maxmp3buf = calcFrameLength(cfg, max_kbps, 0);
+            break;
+        case MDB_MAXIMUM:
+            maxmp3buf = 7680 * (cfg->version + 1);
+            break;
+        }
+    }
+    return maxmp3buf;
+}
+
+
+static void
+putheader_bits(lame_internal_flags * gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    Bit_stream_struc *bs = &gfc->bs;
+#ifdef DEBUG
+    hogege += cfg->sideinfo_len * 8;
+#endif
+    memcpy(&bs->buf[bs->buf_byte_idx], esv->header[esv->w_ptr].buf, cfg->sideinfo_len);
+    bs->buf_byte_idx += cfg->sideinfo_len;
+    bs->totbit += cfg->sideinfo_len * 8;
+    esv->w_ptr = (esv->w_ptr + 1) & (MAX_HEADER_BUF - 1);
+}
+
+
+
+
+/*write j bits into the bit stream */
+inline static void
+putbits2(lame_internal_flags * gfc, int val, int j)
+{
+    EncStateVar_t const *const esv = &gfc->sv_enc;
+    Bit_stream_struc *bs;
+    bs = &gfc->bs;
+
+    assert(j < MAX_LENGTH - 2);
+
+    while (j > 0) {
+        int     k;
+        if (bs->buf_bit_idx == 0) {
+            bs->buf_bit_idx = 8;
+            bs->buf_byte_idx++;
+            assert(bs->buf_byte_idx < BUFFER_SIZE);
+            assert(esv->header[esv->w_ptr].write_timing >= bs->totbit);
+            if (esv->header[esv->w_ptr].write_timing == bs->totbit) {
+                putheader_bits(gfc);
+            }
+            bs->buf[bs->buf_byte_idx] = 0;
+        }
+
+        k = Min(j, bs->buf_bit_idx);
+        j -= k;
+
+        bs->buf_bit_idx -= k;
+
+        assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
+        assert(bs->buf_bit_idx < MAX_LENGTH);
+
+        bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
+        bs->totbit += k;
+    }
+}
+
+/*write j bits into the bit stream, ignoring frame headers */
+inline static void
+putbits_noheaders(lame_internal_flags * gfc, int val, int j)
+{
+    Bit_stream_struc *bs;
+    bs = &gfc->bs;
+
+    assert(j < MAX_LENGTH - 2);
+
+    while (j > 0) {
+        int     k;
+        if (bs->buf_bit_idx == 0) {
+            bs->buf_bit_idx = 8;
+            bs->buf_byte_idx++;
+            assert(bs->buf_byte_idx < BUFFER_SIZE);
+            bs->buf[bs->buf_byte_idx] = 0;
+        }
+
+        k = Min(j, bs->buf_bit_idx);
+        j -= k;
+
+        bs->buf_bit_idx -= k;
+
+        assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */
+        assert(bs->buf_bit_idx < MAX_LENGTH);
+
+        bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);
+        bs->totbit += k;
+    }
+}
+
+
+/*
+  Some combinations of bitrate, Fs, and stereo make it impossible to stuff
+  out a frame using just main_data, due to the limited number of bits to
+  indicate main_data_length. In these situations, we put stuffing bits into
+  the ancillary data...
+*/
+
+inline static void
+drain_into_ancillary(lame_internal_flags * gfc, int remainingBits)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     i;
+    assert(remainingBits >= 0);
+
+    if (remainingBits >= 8) {
+        putbits2(gfc, 0x4c, 8);
+        remainingBits -= 8;
+    }
+    if (remainingBits >= 8) {
+        putbits2(gfc, 0x41, 8);
+        remainingBits -= 8;
+    }
+    if (remainingBits >= 8) {
+        putbits2(gfc, 0x4d, 8);
+        remainingBits -= 8;
+    }
+    if (remainingBits >= 8) {
+        putbits2(gfc, 0x45, 8);
+        remainingBits -= 8;
+    }
+
+    if (remainingBits >= 32) {
+        const char *const version = get_lame_short_version();
+        if (remainingBits >= 32)
+            for (i = 0; i < (int) strlen(version) && remainingBits >= 8; ++i) {
+                remainingBits -= 8;
+                putbits2(gfc, version[i], 8);
+            }
+    }
+
+    for (; remainingBits >= 1; remainingBits -= 1) {
+        putbits2(gfc, esv->ancillary_flag, 1);
+        esv->ancillary_flag ^= !cfg->disable_reservoir;
+    }
+
+    assert(remainingBits == 0);
+
+}
+
+/*write N bits into the header */
+inline static void
+writeheader(lame_internal_flags * gfc, int val, int j)
+{
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     ptr = esv->header[esv->h_ptr].ptr;
+
+    while (j > 0) {
+        int const k = Min(j, 8 - (ptr & 7));
+        j -= k;
+        assert(j < MAX_LENGTH); /* >> 32  too large for 32 bit machines */
+        esv->header[esv->h_ptr].buf[ptr >> 3]
+            |= ((val >> j)) << (8 - (ptr & 7) - k);
+        ptr += k;
+    }
+    esv->header[esv->h_ptr].ptr = ptr;
+}
+
+
+static int
+CRC_update(int value, int crc)
+{
+    int     i;
+    value <<= 8;
+    for (i = 0; i < 8; i++) {
+        value <<= 1;
+        crc <<= 1;
+
+        if (((crc ^ value) & 0x10000))
+            crc ^= CRC16_POLYNOMIAL;
+    }
+    return crc;
+}
+
+
+void
+CRC_writeheader(lame_internal_flags const *gfc, char *header)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     crc = 0xffff;    /* (jo) init crc16 for error_protection */
+    int     i;
+
+    crc = CRC_update(((unsigned char *) header)[2], crc);
+    crc = CRC_update(((unsigned char *) header)[3], crc);
+    for (i = 6; i < cfg->sideinfo_len; i++) {
+        crc = CRC_update(((unsigned char *) header)[i], crc);
+    }
+
+    header[4] = crc >> 8;
+    header[5] = crc & 255;
+}
+
+inline static void
+encodeSideInfo2(lame_internal_flags * gfc, int bitsPerFrame)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t const *const eov = &gfc->ov_enc;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    III_side_info_t *l3_side;
+    int     gr, ch;
+
+    l3_side = &gfc->l3_side;
+    esv->header[esv->h_ptr].ptr = 0;
+    memset(esv->header[esv->h_ptr].buf, 0, cfg->sideinfo_len);
+    if (cfg->samplerate_out < 16000)
+        writeheader(gfc, 0xffe, 12);
+    else
+        writeheader(gfc, 0xfff, 12);
+    writeheader(gfc, (cfg->version), 1);
+    writeheader(gfc, 4 - 3, 2);
+    writeheader(gfc, (!cfg->error_protection), 1);
+    writeheader(gfc, (eov->bitrate_index), 4);
+    writeheader(gfc, (cfg->samplerate_index), 2);
+    writeheader(gfc, (eov->padding), 1);
+    writeheader(gfc, (cfg->extension), 1);
+    writeheader(gfc, (cfg->mode), 2);
+    writeheader(gfc, (eov->mode_ext), 2);
+    writeheader(gfc, (cfg->copyright), 1);
+    writeheader(gfc, (cfg->original), 1);
+    writeheader(gfc, (cfg->emphasis), 2);
+    if (cfg->error_protection) {
+        writeheader(gfc, 0, 16); /* dummy */
+    }
+
+    if (cfg->version == 1) {
+        /* MPEG1 */
+        assert(l3_side->main_data_begin >= 0);
+        writeheader(gfc, (l3_side->main_data_begin), 9);
+
+        if (cfg->channels_out == 2)
+            writeheader(gfc, l3_side->private_bits, 3);
+        else
+            writeheader(gfc, l3_side->private_bits, 5);
+
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            int     band;
+            for (band = 0; band < 4; band++) {
+                writeheader(gfc, l3_side->scfsi[ch][band], 1);
+            }
+        }
+
+        for (gr = 0; gr < 2; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gr_info *const gi = &l3_side->tt[gr][ch];
+                writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
+                writeheader(gfc, gi->big_values / 2, 9);
+                writeheader(gfc, gi->global_gain, 8);
+                writeheader(gfc, gi->scalefac_compress, 4);
+
+                if (gi->block_type != NORM_TYPE) {
+                    writeheader(gfc, 1, 1); /* window_switching_flag */
+                    writeheader(gfc, gi->block_type, 2);
+                    writeheader(gfc, gi->mixed_block_flag, 1);
+
+                    if (gi->table_select[0] == 14)
+                        gi->table_select[0] = 16;
+                    writeheader(gfc, gi->table_select[0], 5);
+                    if (gi->table_select[1] == 14)
+                        gi->table_select[1] = 16;
+                    writeheader(gfc, gi->table_select[1], 5);
+
+                    writeheader(gfc, gi->subblock_gain[0], 3);
+                    writeheader(gfc, gi->subblock_gain[1], 3);
+                    writeheader(gfc, gi->subblock_gain[2], 3);
+                }
+                else {
+                    writeheader(gfc, 0, 1); /* window_switching_flag */
+                    if (gi->table_select[0] == 14)
+                        gi->table_select[0] = 16;
+                    writeheader(gfc, gi->table_select[0], 5);
+                    if (gi->table_select[1] == 14)
+                        gi->table_select[1] = 16;
+                    writeheader(gfc, gi->table_select[1], 5);
+                    if (gi->table_select[2] == 14)
+                        gi->table_select[2] = 16;
+                    writeheader(gfc, gi->table_select[2], 5);
+
+                    assert(0 <= gi->region0_count && gi->region0_count < 16);
+                    assert(0 <= gi->region1_count && gi->region1_count < 8);
+                    writeheader(gfc, gi->region0_count, 4);
+                    writeheader(gfc, gi->region1_count, 3);
+                }
+                writeheader(gfc, gi->preflag, 1);
+                writeheader(gfc, gi->scalefac_scale, 1);
+                writeheader(gfc, gi->count1table_select, 1);
+            }
+        }
+    }
+    else {
+        /* MPEG2 */
+        assert(l3_side->main_data_begin >= 0);
+        writeheader(gfc, (l3_side->main_data_begin), 8);
+        writeheader(gfc, l3_side->private_bits, cfg->channels_out);
+
+        gr = 0;
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            gr_info *const gi = &l3_side->tt[gr][ch];
+            writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);
+            writeheader(gfc, gi->big_values / 2, 9);
+            writeheader(gfc, gi->global_gain, 8);
+            writeheader(gfc, gi->scalefac_compress, 9);
+
+            if (gi->block_type != NORM_TYPE) {
+                writeheader(gfc, 1, 1); /* window_switching_flag */
+                writeheader(gfc, gi->block_type, 2);
+                writeheader(gfc, gi->mixed_block_flag, 1);
+
+                if (gi->table_select[0] == 14)
+                    gi->table_select[0] = 16;
+                writeheader(gfc, gi->table_select[0], 5);
+                if (gi->table_select[1] == 14)
+                    gi->table_select[1] = 16;
+                writeheader(gfc, gi->table_select[1], 5);
+
+                writeheader(gfc, gi->subblock_gain[0], 3);
+                writeheader(gfc, gi->subblock_gain[1], 3);
+                writeheader(gfc, gi->subblock_gain[2], 3);
+            }
+            else {
+                writeheader(gfc, 0, 1); /* window_switching_flag */
+                if (gi->table_select[0] == 14)
+                    gi->table_select[0] = 16;
+                writeheader(gfc, gi->table_select[0], 5);
+                if (gi->table_select[1] == 14)
+                    gi->table_select[1] = 16;
+                writeheader(gfc, gi->table_select[1], 5);
+                if (gi->table_select[2] == 14)
+                    gi->table_select[2] = 16;
+                writeheader(gfc, gi->table_select[2], 5);
+
+                assert(0 <= gi->region0_count && gi->region0_count < 16);
+                assert(0 <= gi->region1_count && gi->region1_count < 8);
+                writeheader(gfc, gi->region0_count, 4);
+                writeheader(gfc, gi->region1_count, 3);
+            }
+
+            writeheader(gfc, gi->scalefac_scale, 1);
+            writeheader(gfc, gi->count1table_select, 1);
+        }
+    }
+
+    if (cfg->error_protection) {
+        /* (jo) error_protection: add crc16 information to header */
+        CRC_writeheader(gfc, esv->header[esv->h_ptr].buf);
+    }
+
+    {
+        int const old = esv->h_ptr;
+        assert(esv->header[old].ptr == cfg->sideinfo_len * 8);
+
+        esv->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);
+        esv->header[esv->h_ptr].write_timing = esv->header[old].write_timing + bitsPerFrame;
+
+        if (esv->h_ptr == esv->w_ptr) {
+            /* yikes! we are out of header buffer space */
+            ERRORF(gfc, "Error: MAX_HEADER_BUF too small in bitstream.c \n");
+        }
+
+    }
+}
+
+
+inline static int
+huffman_coder_count1(lame_internal_flags * gfc, gr_info const *gi)
+{
+    /* Write count1 area */
+    struct huffcodetab const *const h = &ht[gi->count1table_select + 32];
+    int     i, bits = 0;
+#ifdef DEBUG
+    int     gegebo = gfc->bs.totbit;
+#endif
+
+    int const *ix = &gi->l3_enc[gi->big_values];
+    FLOAT const *xr = &gi->xr[gi->big_values];
+    assert(gi->count1table_select < 2);
+
+    for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {
+        int     huffbits = 0;
+        int     p = 0, v;
+
+        v = ix[0];
+        if (v) {
+            p += 8;
+            if (xr[0] < 0.0f)
+                huffbits++;
+            assert(v <= 1);
+        }
+
+        v = ix[1];
+        if (v) {
+            p += 4;
+            huffbits *= 2;
+            if (xr[1] < 0.0f)
+                huffbits++;
+            assert(v <= 1);
+        }
+
+        v = ix[2];
+        if (v) {
+            p += 2;
+            huffbits *= 2;
+            if (xr[2] < 0.0f)
+                huffbits++;
+            assert(v <= 1);
+        }
+
+        v = ix[3];
+        if (v) {
+            p++;
+            huffbits *= 2;
+            if (xr[3] < 0.0f)
+                huffbits++;
+            assert(v <= 1);
+        }
+
+        ix += 4;
+        xr += 4;
+        putbits2(gfc, huffbits + h->table[p], h->hlen[p]);
+        bits += h->hlen[p];
+    }
+#ifdef DEBUG
+    DEBUGF(gfc, "count1: real: %ld counted:%d (bigv %d count1len %d)\n",
+           gfc->bs.totbit - gegebo, gi->count1bits, gi->big_values, gi->count1);
+#endif
+    return bits;
+}
+
+
+
+/*
+  Implements the pseudocode of page 98 of the IS
+  */
+inline static int
+Huffmancode(lame_internal_flags * const gfc, const unsigned int tableindex,
+            int start, int end, gr_info const *gi)
+{
+    struct huffcodetab const *const h = &ht[tableindex];
+    unsigned int const linbits = h->xlen;
+    int     i, bits = 0;
+
+    assert(tableindex < 32u);
+    if (!tableindex)
+        return bits;
+
+    for (i = start; i < end; i += 2) {
+        int16_t  cbits = 0;
+        uint16_t xbits = 0;
+        unsigned int xlen = h->xlen;
+        unsigned int ext = 0;
+        unsigned int x1 = gi->l3_enc[i];
+        unsigned int x2 = gi->l3_enc[i + 1];
+
+        assert(gi->l3_enc[i] >= 0);
+        assert(gi->l3_enc[i+1] >= 0);
+
+        if (x1 != 0u) {
+            if (gi->xr[i] < 0.0f)
+                ext++;
+            cbits--;
+        }
+
+        if (tableindex > 15u) {
+            /* use ESC-words */
+            if (x1 >= 15u) {
+                uint16_t const linbits_x1 = x1 - 15u;
+                assert(linbits_x1 <= h->linmax);
+                ext |= linbits_x1 << 1u;
+                xbits = linbits;
+                x1 = 15u;
+            }
+
+            if (x2 >= 15u) {
+                uint16_t const linbits_x2 = x2 - 15u;
+                assert(linbits_x2 <= h->linmax);
+                ext <<= linbits;
+                ext |= linbits_x2;
+                xbits += linbits;
+                x2 = 15u;
+            }
+            xlen = 16;
+        }
+
+        if (x2 != 0u) {
+            ext <<= 1;
+            if (gi->xr[i + 1] < 0.0f)
+                ext++;
+            cbits--;
+        }
+
+        assert((x1 | x2) < 16u);
+
+        x1 = x1 * xlen + x2;
+        xbits -= cbits;
+        cbits += h->hlen[x1];
+
+        assert(cbits <= MAX_LENGTH);
+        assert(xbits <= MAX_LENGTH);
+
+        putbits2(gfc, h->table[x1], cbits);
+        putbits2(gfc, (int)ext, xbits);
+        bits += cbits + xbits;
+    }
+    return bits;
+}
+
+/*
+  Note the discussion of huffmancodebits() on pages 28
+  and 29 of the IS, as well as the definitions of the side
+  information on pages 26 and 27.
+  */
+static int
+ShortHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
+{
+    int     bits;
+    int     region1Start;
+
+    region1Start = 3 * gfc->scalefac_band.s[3];
+    if (region1Start > gi->big_values)
+        region1Start = gi->big_values;
+
+    /* short blocks do not have a region2 */
+    bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
+    bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);
+    return bits;
+}
+
+static int
+LongHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)
+{
+    unsigned int i;
+    int     bigvalues, bits;
+    int     region1Start, region2Start;
+
+    bigvalues = gi->big_values;
+    assert(0 <= bigvalues && bigvalues <= 576);
+
+    assert(gi->region0_count >= -1);
+    assert(gi->region1_count >= -1);
+    i = gi->region0_count + 1;
+    assert((size_t) i < dimension_of(gfc->scalefac_band.l));
+    region1Start = gfc->scalefac_band.l[i];
+    i += gi->region1_count + 1;
+    assert((size_t) i < dimension_of(gfc->scalefac_band.l));
+    region2Start = gfc->scalefac_band.l[i];
+
+    if (region1Start > bigvalues)
+        region1Start = bigvalues;
+
+    if (region2Start > bigvalues)
+        region2Start = bigvalues;
+
+    bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);
+    bits += Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);
+    bits += Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);
+    return bits;
+}
+
+inline static int
+writeMainData(lame_internal_flags * const gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    III_side_info_t const *const l3_side = &gfc->l3_side;
+    int     gr, ch, sfb, data_bits, tot_bits = 0;
+
+    if (cfg->version == 1) {
+        /* MPEG 1 */
+        for (gr = 0; gr < 2; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gr_info const *const gi = &l3_side->tt[gr][ch];
+                int const slen1 = slen1_tab[gi->scalefac_compress];
+                int const slen2 = slen2_tab[gi->scalefac_compress];
+                data_bits = 0;
+#ifdef DEBUG
+                hogege = gfc->bs.totbit;
+#endif
+                for (sfb = 0; sfb < gi->sfbdivide; sfb++) {
+                    if (gi->scalefac[sfb] == -1)
+                        continue; /* scfsi is used */
+                    putbits2(gfc, gi->scalefac[sfb], slen1);
+                    data_bits += slen1;
+                }
+                for (; sfb < gi->sfbmax; sfb++) {
+                    if (gi->scalefac[sfb] == -1)
+                        continue; /* scfsi is used */
+                    putbits2(gfc, gi->scalefac[sfb], slen2);
+                    data_bits += slen2;
+                }
+                assert(data_bits == gi->part2_length);
+
+                if (gi->block_type == SHORT_TYPE) {
+                    data_bits += ShortHuffmancodebits(gfc, gi);
+                }
+                else {
+                    data_bits += LongHuffmancodebits(gfc, gi);
+                }
+                data_bits += huffman_coder_count1(gfc, gi);
+#ifdef DEBUG
+                DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
+#endif
+                /* does bitcount in quantize.c agree with actual bit count? */
+                assert(data_bits == gi->part2_3_length + gi->part2_length);
+                tot_bits += data_bits;
+            }           /* for ch */
+        }               /* for gr */
+    }
+    else {
+        /* MPEG 2 */
+        gr = 0;
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            gr_info const *const gi = &l3_side->tt[gr][ch];
+            int     i, sfb_partition, scale_bits = 0;
+            assert(gi->sfb_partition_table);
+            data_bits = 0;
+#ifdef DEBUG
+            hogege = gfc->bs.totbit;
+#endif
+            sfb = 0;
+            sfb_partition = 0;
+
+            if (gi->block_type == SHORT_TYPE) {
+                for (; sfb_partition < 4; sfb_partition++) {
+                    int const sfbs = gi->sfb_partition_table[sfb_partition] / 3;
+                    int const slen = gi->slen[sfb_partition];
+                    for (i = 0; i < sfbs; i++, sfb++) {
+                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 0], 0), slen);
+                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 1], 0), slen);
+                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 2], 0), slen);
+                        scale_bits += 3 * slen;
+                    }
+                }
+                data_bits += ShortHuffmancodebits(gfc, gi);
+            }
+            else {
+                for (; sfb_partition < 4; sfb_partition++) {
+                    int const sfbs = gi->sfb_partition_table[sfb_partition];
+                    int const slen = gi->slen[sfb_partition];
+                    for (i = 0; i < sfbs; i++, sfb++) {
+                        putbits2(gfc, Max(gi->scalefac[sfb], 0), slen);
+                        scale_bits += slen;
+                    }
+                }
+                data_bits += LongHuffmancodebits(gfc, gi);
+            }
+            data_bits += huffman_coder_count1(gfc, gi);
+#ifdef DEBUG
+            DEBUGF(gfc, "<%ld> ", gfc->bs.totbit - hogege);
+#endif
+            /* does bitcount in quantize.c agree with actual bit count? */
+            assert(data_bits == gi->part2_3_length);
+            assert(scale_bits == gi->part2_length);
+            tot_bits += scale_bits + data_bits;
+        }               /* for ch */
+    }                   /* for gf */
+    return tot_bits;
+}                       /* main_data */
+
+
+
+/* compute the number of bits required to flush all mp3 frames
+   currently in the buffer.  This should be the same as the
+   reservoir size.  Only call this routine between frames - i.e.
+   only after all headers and data have been added to the buffer
+   by format_bitstream().
+
+   Also compute total_bits_output =
+       size of mp3 buffer (including frame headers which may not
+       have yet been send to the mp3 buffer) +
+       number of bits needed to flush all mp3 frames.
+
+   total_bytes_output is the size of the mp3 output buffer if
+   lame_encode_flush_nogap() was called right now.
+
+ */
+int
+compute_flushbits(const lame_internal_flags * gfc, int *total_bytes_output)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t const *const esv = &gfc->sv_enc;
+    int     flushbits, remaining_headers;
+    int     bitsPerFrame;
+    int     last_ptr, first_ptr;
+    first_ptr = esv->w_ptr; /* first header to add to bitstream */
+    last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
+    if (last_ptr == -1)
+        last_ptr = MAX_HEADER_BUF - 1;
+
+    /* add this many bits to bitstream so we can flush all headers */
+    flushbits = esv->header[last_ptr].write_timing - gfc->bs.totbit;
+    *total_bytes_output = flushbits;
+
+    if (flushbits >= 0) {
+        /* if flushbits >= 0, some headers have not yet been written */
+        /* reduce flushbits by the size of the headers */
+        remaining_headers = 1 + last_ptr - first_ptr;
+        if (last_ptr < first_ptr)
+            remaining_headers = 1 + last_ptr - first_ptr + MAX_HEADER_BUF;
+        flushbits -= remaining_headers * 8 * cfg->sideinfo_len;
+    }
+
+
+    /* finally, add some bits so that the last frame is complete
+     * these bits are not necessary to decode the last frame, but
+     * some decoders will ignore last frame if these bits are missing
+     */
+    bitsPerFrame = getframebits(gfc);
+    flushbits += bitsPerFrame;
+    *total_bytes_output += bitsPerFrame;
+    /* round up:   */
+    if (*total_bytes_output % 8)
+        *total_bytes_output = 1 + (*total_bytes_output / 8);
+    else
+        *total_bytes_output = (*total_bytes_output / 8);
+    *total_bytes_output += gfc->bs.buf_byte_idx + 1;
+
+
+    if (flushbits < 0) {
+#if 0
+        /* if flushbits < 0, this would mean that the buffer looks like:
+         * (data...)  last_header  (data...)  (extra data that should not be here...)
+         */
+        DEBUGF(gfc, "last header write_timing = %i \n", esv->header[last_ptr].write_timing);
+        DEBUGF(gfc, "first header write_timing = %i \n", esv->header[first_ptr].write_timing);
+        DEBUGF(gfc, "bs.totbit:                 %i \n", gfc->bs.totbit);
+        DEBUGF(gfc, "first_ptr, last_ptr        %i %i \n", first_ptr, last_ptr);
+        DEBUGF(gfc, "remaining_headers =        %i \n", remaining_headers);
+        DEBUGF(gfc, "bitsperframe:              %i \n", bitsPerFrame);
+        DEBUGF(gfc, "sidelen:                   %i \n", cfg->sideinfo_len);
+#endif
+        ERRORF(gfc, "strange error flushing buffer ... \n");
+    }
+    return flushbits;
+}
+
+
+void
+flush_bitstream(lame_internal_flags * gfc)
+{
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    III_side_info_t *l3_side;
+    int     nbytes;
+    int     flushbits;
+    int     last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */
+    if (last_ptr == -1)
+        last_ptr = MAX_HEADER_BUF - 1;
+    l3_side = &gfc->l3_side;
+
+
+    if ((flushbits = compute_flushbits(gfc, &nbytes)) < 0)
+        return;
+    drain_into_ancillary(gfc, flushbits);
+
+    /* check that the 100% of the last frame has been written to bitstream */
+    assert(esv->header[last_ptr].write_timing + getframebits(gfc)
+           == gfc->bs.totbit);
+
+    /* we have padded out all frames with ancillary data, which is the
+       same as filling the bitreservoir with ancillary data, so : */
+    esv->ResvSize = 0;
+    l3_side->main_data_begin = 0;
+}
+
+
+
+
+void
+add_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n)
+{
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     i;
+
+    while (n-- > 0u) {
+        putbits_noheaders(gfc, val, 8);
+
+        for (i = 0; i < MAX_HEADER_BUF; ++i)
+            esv->header[i].write_timing += 8;
+    }
+}
+
+
+/*
+  format_bitstream()
+
+  This is called after a frame of audio has been quantized and coded.
+  It will write the encoded audio to the bitstream. Note that
+  from a layer3 encoder's perspective the bit stream is primarily
+  a series of main_data() blocks, with header and side information
+  inserted at the proper locations to maintain framing. (See Figure A.7
+  in the IS).
+  */
+int
+format_bitstream(lame_internal_flags * gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     bits, nbytes;
+    III_side_info_t *l3_side;
+    int     bitsPerFrame;
+    l3_side = &gfc->l3_side;
+
+    bitsPerFrame = getframebits(gfc);
+    drain_into_ancillary(gfc, l3_side->resvDrain_pre);
+
+    encodeSideInfo2(gfc, bitsPerFrame);
+    bits = 8 * cfg->sideinfo_len;
+    bits += writeMainData(gfc);
+    drain_into_ancillary(gfc, l3_side->resvDrain_post);
+    bits += l3_side->resvDrain_post;
+
+    l3_side->main_data_begin += (bitsPerFrame - bits) / 8;
+
+    /* compare number of bits needed to clear all buffered mp3 frames
+     * with what we think the resvsize is: */
+    if (compute_flushbits(gfc, &nbytes) != esv->ResvSize) {
+        ERRORF(gfc, "Internal buffer inconsistency. flushbits <> ResvSize");
+    }
+
+
+    /* compare main_data_begin for the next frame with what we
+     * think the resvsize is: */
+    if ((l3_side->main_data_begin * 8) != esv->ResvSize) {
+        ERRORF(gfc, "bit reservoir error: \n"
+               "l3_side->main_data_begin: %i \n"
+               "Resvoir size:             %i \n"
+               "resv drain (post)         %i \n"
+               "resv drain (pre)          %i \n"
+               "header and sideinfo:      %i \n"
+               "data bits:                %i \n"
+               "total bits:               %i (remainder: %i) \n"
+               "bitsperframe:             %i \n",
+               8 * l3_side->main_data_begin,
+               esv->ResvSize,
+               l3_side->resvDrain_post,
+               l3_side->resvDrain_pre,
+               8 * cfg->sideinfo_len,
+               bits - l3_side->resvDrain_post - 8 * cfg->sideinfo_len,
+               bits, bits % 8, bitsPerFrame);
+
+        ERRORF(gfc, "This is a fatal error.  It has several possible causes:");
+        ERRORF(gfc, "90%%  LAME compiled with buggy version of gcc using advanced optimizations");
+        ERRORF(gfc, " 9%%  Your system is overclocked");
+        ERRORF(gfc, " 1%%  bug in LAME encoding library");
+
+        esv->ResvSize = l3_side->main_data_begin * 8;
+    };
+    assert(gfc->bs.totbit % 8 == 0);
+
+    if (gfc->bs.totbit > 1000000000) {
+        /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter */
+        int     i;
+        for (i = 0; i < MAX_HEADER_BUF; ++i)
+            esv->header[i].write_timing -= gfc->bs.totbit;
+        gfc->bs.totbit = 0;
+    }
+
+
+    return 0;
+}
+
+
+static int
+do_gain_analysis(lame_internal_flags * gfc, unsigned char* buffer, int minimum)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    RpgStateVar_t const *const rsv = &gfc->sv_rpg;
+    RpgResult_t *const rov = &gfc->ov_rpg;
+#ifdef DECODE_ON_THE_FLY
+    if (cfg->decode_on_the_fly) { /* decode the frame */
+        sample_t pcm_buf[2][1152];
+        int     mp3_in = minimum;
+        int     samples_out = -1;
+
+        /* re-synthesis to pcm.  Repeat until we get a samples_out=0 */
+        while (samples_out != 0) {
+
+            samples_out = hip_decode1_unclipped(gfc->hip, buffer, mp3_in, pcm_buf[0], pcm_buf[1]);
+            /* samples_out = 0:  need more data to decode
+             * samples_out = -1:  error.  Lets assume 0 pcm output
+             * samples_out = number of samples output */
+
+            /* set the lenght of the mp3 input buffer to zero, so that in the
+             * next iteration of the loop we will be querying mpglib about
+             * buffered data */
+            mp3_in = 0;
+
+            if (samples_out == -1) {
+                /* error decoding. Not fatal, but might screw up
+                 * the ReplayGain tag. What should we do? Ignore for now */
+                samples_out = 0;
+            }
+            if (samples_out > 0) {
+                /* process the PCM data */
+
+                /* this should not be possible, and indicates we have
+                 * overflown the pcm_buf buffer */
+                assert(samples_out <= 1152);
+
+                if (cfg->findPeakSample) {
+                    int     i;
+                    /* FIXME: is this correct? maybe Max(fabs(pcm),PeakSample) */
+                    for (i = 0; i < samples_out; i++) {
+                        if (pcm_buf[0][i] > rov->PeakSample)
+                            rov->PeakSample = pcm_buf[0][i];
+                        else if (-pcm_buf[0][i] > rov->PeakSample)
+                            rov->PeakSample = -pcm_buf[0][i];
+                    }
+                    if (cfg->channels_out > 1)
+                        for (i = 0; i < samples_out; i++) {
+                            if (pcm_buf[1][i] > rov->PeakSample)
+                                rov->PeakSample = pcm_buf[1][i];
+                            else if (-pcm_buf[1][i] > rov->PeakSample)
+                                rov->PeakSample = -pcm_buf[1][i];
+                        }
+                }
+
+                if (cfg->findReplayGain)
+                    if (AnalyzeSamples
+                        (rsv->rgdata, pcm_buf[0], pcm_buf[1], samples_out,
+                         cfg->channels_out) == GAIN_ANALYSIS_ERROR)
+                        return -6;
+
+            }       /* if (samples_out>0) */
+        }           /* while (samples_out!=0) */
+    }               /* if (gfc->decode_on_the_fly) */
+#endif
+    return minimum;
+}
+
+static int
+do_copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size)
+{
+    Bit_stream_struc *const bs = &gfc->bs;
+    int const minimum = bs->buf_byte_idx + 1;
+    if (minimum <= 0)
+        return 0;
+    if (minimum > size)
+        return -1;      /* buffer is too small */
+    memcpy(buffer, bs->buf, minimum);
+    bs->buf_byte_idx = -1;
+    bs->buf_bit_idx = 0;
+    return minimum;
+}
+
+/* copy data out of the internal MP3 bit buffer into a user supplied
+   unsigned char buffer.
+
+   mp3data=0      indicates data in buffer is an id3tags and VBR tags
+   mp3data=1      data is real mp3 frame data.
+
+
+*/
+int
+copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size, int mp3data)
+{
+    int const minimum = do_copy_buffer(gfc, buffer, size);
+    if (minimum > 0 && mp3data) {
+        UpdateMusicCRC(&gfc->nMusicCRC, buffer, minimum);
+
+        /** sum number of bytes belonging to the mp3 stream
+         *  this info will be written into the Xing/LAME header for seeking
+         */
+        gfc->VBR_seek_table.nBytesWritten += minimum;
+
+        return do_gain_analysis(gfc, buffer, minimum);
+    }                   /* if (mp3data) */
+    return minimum;
+}
+
+
+void
+init_bit_stream_w(lame_internal_flags * gfc)
+{
+    EncStateVar_t *const esv = &gfc->sv_enc;
+
+    esv->h_ptr = esv->w_ptr = 0;
+    esv->header[esv->h_ptr].write_timing = 0;
+
+    gfc->bs.buf = lame_calloc(unsigned char, BUFFER_SIZE);
+    gfc->bs.buf_size = BUFFER_SIZE;
+    gfc->bs.buf_byte_idx = -1;
+    gfc->bs.buf_bit_idx = 0;
+    gfc->bs.totbit = 0;
+}
+
+/* end of bitstream.c */
diff --git a/lame/libmp3lame/bitstream.h b/lame/libmp3lame/bitstream.h
new file mode 100644 (file)
index 0000000..3ae48d0
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ *     MP3 bitstream Output interface for LAME
+ *
+ *     Copyright (c) 1999 Takehiro TOMINAGA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_BITSTREAM_H
+#define LAME_BITSTREAM_H
+
+int     getframebits(const lame_internal_flags * gfc);
+
+int     format_bitstream(lame_internal_flags * gfc);
+
+void    flush_bitstream(lame_internal_flags * gfc);
+void    add_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n);
+
+int     copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int buffer_size,
+                    int update_crc);
+void    init_bit_stream_w(lame_internal_flags * gfc);
+void    CRC_writeheader(lame_internal_flags const *gfc, char *buffer);
+int     compute_flushbits(const lame_internal_flags * gfp, int *nbytes);
+
+int     get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint);
+
+#endif
diff --git a/lame/libmp3lame/encoder.c b/lame/libmp3lame/encoder.c
new file mode 100644 (file)
index 0000000..48f46c7
--- /dev/null
@@ -0,0 +1,574 @@
+/*
+ *      LAME MP3 encoding engine
+ *
+ *      Copyright (c) 1999 Mark Taylor
+ *      Copyright (c) 2000-2002 Takehiro Tominaga
+ *      Copyright (c) 2000-2011 Robert Hegemann
+ *      Copyright (c) 2001 Gabriel Bouvigne
+ *      Copyright (c) 2001 John Dahlstrom
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: encoder.c,v 1.114 2017/08/26 10:54:57 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "lame_global_flags.h"
+#include "newmdct.h"
+#include "psymodel.h"
+#include "lame-analysis.h"
+#include "bitstream.h"
+#include "VbrTag.h"
+#include "quantize.h"
+#include "quantize_pvt.h"
+
+
+
+/*
+ * auto-adjust of ATH, useful for low volume
+ * Gabriel Bouvigne 3 feb 2001
+ *
+ * modifies some values in
+ *   gfp->internal_flags->ATH
+ *   (gfc->ATH)
+ */
+static void
+adjust_ATH(lame_internal_flags const *const gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    FLOAT   gr2_max, max_pow;
+
+    if (gfc->ATH->use_adjust == 0) {
+        gfc->ATH->adjust_factor = 1.0; /* no adjustment */
+        return;
+    }
+
+    /* jd - 2001 mar 12, 27, jun 30 */
+    /* loudness based on equal loudness curve; */
+    /* use granule with maximum combined loudness */
+    max_pow = gfc->ov_psy.loudness_sq[0][0];
+    gr2_max = gfc->ov_psy.loudness_sq[1][0];
+    if (cfg->channels_out == 2) {
+        max_pow += gfc->ov_psy.loudness_sq[0][1];
+        gr2_max += gfc->ov_psy.loudness_sq[1][1];
+    }
+    else {
+        max_pow += max_pow;
+        gr2_max += gr2_max;
+    }
+    if (cfg->mode_gr == 2) {
+        max_pow = Max(max_pow, gr2_max);
+    }
+    max_pow *= 0.5;     /* max_pow approaches 1.0 for full band noise */
+
+    /* jd - 2001 mar 31, jun 30 */
+    /* user tuning of ATH adjustment region */
+    max_pow *= gfc->ATH->aa_sensitivity_p;
+
+    /*  adjust ATH depending on range of maximum value
+     */
+
+    /* jd - 2001 feb27, mar12,20, jun30, jul22 */
+    /* continuous curves based on approximation */
+    /* to GB's original values. */
+    /* For an increase in approximate loudness, */
+    /* set ATH adjust to adjust_limit immediately */
+    /* after a delay of one frame. */
+    /* For a loudness decrease, reduce ATH adjust */
+    /* towards adjust_limit gradually. */
+    /* max_pow is a loudness squared or a power. */
+    if (max_pow > 0.03125) { /* ((1 - 0.000625)/ 31.98) from curve below */
+        if (gfc->ATH->adjust_factor >= 1.0) {
+            gfc->ATH->adjust_factor = 1.0;
+        }
+        else {
+            /* preceding frame has lower ATH adjust; */
+            /* ascend only to the preceding adjust_limit */
+            /* in case there is leading low volume */
+            if (gfc->ATH->adjust_factor < gfc->ATH->adjust_limit) {
+                gfc->ATH->adjust_factor = gfc->ATH->adjust_limit;
+            }
+        }
+        gfc->ATH->adjust_limit = 1.0;
+    }
+    else {              /* adjustment curve */
+        /* about 32 dB maximum adjust (0.000625) */
+        FLOAT const adj_lim_new = 31.98 * max_pow + 0.000625;
+        if (gfc->ATH->adjust_factor >= adj_lim_new) { /* descend gradually */
+            gfc->ATH->adjust_factor *= adj_lim_new * 0.075 + 0.925;
+            if (gfc->ATH->adjust_factor < adj_lim_new) { /* stop descent */
+                gfc->ATH->adjust_factor = adj_lim_new;
+            }
+        }
+        else {          /* ascend */
+            if (gfc->ATH->adjust_limit >= adj_lim_new) {
+                gfc->ATH->adjust_factor = adj_lim_new;
+            }
+            else {      /* preceding frame has lower ATH adjust; */
+                /* ascend only to the preceding adjust_limit */
+                if (gfc->ATH->adjust_factor < gfc->ATH->adjust_limit) {
+                    gfc->ATH->adjust_factor = gfc->ATH->adjust_limit;
+                }
+            }
+        }
+        gfc->ATH->adjust_limit = adj_lim_new;
+    }
+}
+
+/***********************************************************************
+ *
+ *  some simple statistics
+ *
+ *  bitrate index 0: free bitrate -> not allowed in VBR mode
+ *  : bitrates, kbps depending on MPEG version
+ *  bitrate index 15: forbidden
+ *
+ *  mode_ext:
+ *  0:  LR
+ *  1:  LR-i
+ *  2:  MS
+ *  3:  MS-i
+ *
+ ***********************************************************************/
+
+static void
+updateStats(lame_internal_flags * const gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *eov = &gfc->ov_enc;
+    int     gr, ch;
+    assert(0 <= eov->bitrate_index && eov->bitrate_index < 16);
+    assert(0 <= eov->mode_ext && eov->mode_ext < 4);
+
+    /* count bitrate indices */
+    eov->bitrate_channelmode_hist[eov->bitrate_index][4]++;
+    eov->bitrate_channelmode_hist[15][4]++;
+
+    /* count 'em for every mode extension in case of 2 channel encoding */
+    if (cfg->channels_out == 2) {
+        eov->bitrate_channelmode_hist[eov->bitrate_index][eov->mode_ext]++;
+        eov->bitrate_channelmode_hist[15][eov->mode_ext]++;
+    }
+    for (gr = 0; gr < cfg->mode_gr; ++gr) {
+        for (ch = 0; ch < cfg->channels_out; ++ch) {
+            int     bt = gfc->l3_side.tt[gr][ch].block_type;
+            if (gfc->l3_side.tt[gr][ch].mixed_block_flag)
+                bt = 4;
+            eov->bitrate_blocktype_hist[eov->bitrate_index][bt]++;
+            eov->bitrate_blocktype_hist[eov->bitrate_index][5]++;
+            eov->bitrate_blocktype_hist[15][bt]++;
+            eov->bitrate_blocktype_hist[15][5]++;
+        }
+    }
+}
+
+
+
+
+static void
+lame_encode_frame_init(lame_internal_flags * gfc, const sample_t *const inbuf[2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+
+    int     ch, gr;
+
+    if (gfc->lame_encode_frame_init == 0) {
+        sample_t primebuff0[286 + 1152 + 576];
+        sample_t primebuff1[286 + 1152 + 576];
+        int const framesize = 576 * cfg->mode_gr;
+        /* prime the MDCT/polyphase filterbank with a short block */
+        int     i, j;
+        gfc->lame_encode_frame_init = 1;
+        memset(primebuff0, 0, sizeof(primebuff0));
+        memset(primebuff1, 0, sizeof(primebuff1));
+        for (i = 0, j = 0; i < 286 + 576 * (1 + cfg->mode_gr); ++i) {
+            if (i < framesize) {
+                primebuff0[i] = 0;
+                if (cfg->channels_out == 2)
+                    primebuff1[i] = 0;
+            }
+            else {
+                primebuff0[i] = inbuf[0][j];
+                if (cfg->channels_out == 2)
+                    primebuff1[i] = inbuf[1][j];
+                ++j;
+            }
+        }
+        /* polyphase filtering / mdct */
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gfc->l3_side.tt[gr][ch].block_type = SHORT_TYPE;
+            }
+        }
+        mdct_sub48(gfc, primebuff0, primebuff1);
+
+        /* check FFT will not use a negative starting offset */
+#if 576 < FFTOFFSET
+# error FFTOFFSET greater than 576: FFT uses a negative offset
+#endif
+        /* check if we have enough data for FFT */
+        assert(gfc->sv_enc.mf_size >= (BLKSIZE + framesize - FFTOFFSET));
+        /* check if we have enough data for polyphase filterbank */
+        assert(gfc->sv_enc.mf_size >= (512 + framesize - 32));
+    }
+
+}
+
+
+
+
+
+
+
+/************************************************************************
+*
+* encodeframe()           Layer 3
+*
+* encode a single frame
+*
+************************************************************************
+lame_encode_frame()
+
+
+                       gr 0            gr 1
+inbuf:           |--------------|--------------|--------------|
+
+
+Polyphase (18 windows, each shifted 32)
+gr 0:
+window1          <----512---->
+window18                 <----512---->
+
+gr 1:
+window1                         <----512---->
+window18                                <----512---->
+
+
+
+MDCT output:  |--------------|--------------|--------------|
+
+FFT's                    <---------1024---------->
+                                         <---------1024-------->
+
+
+
+    inbuf = buffer of PCM data size=MP3 framesize
+    encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
+    so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
+
+    psy-model FFT has a 1 granule delay, so we feed it data for the 
+    next granule.
+    FFT is centered over granule:  224+576+224
+    So FFT starts at:   576-224-MDCTDELAY
+
+    MPEG2:  FFT ends at:  BLKSIZE+576-224-MDCTDELAY      (1328)
+    MPEG1:  FFT ends at:  BLKSIZE+2*576-224-MDCTDELAY    (1904)
+
+    MPEG2:  polyphase first window:  [0..511]
+                      18th window:   [544..1055]          (1056)
+    MPEG1:            36th window:   [1120..1631]         (1632)
+            data needed:  512+framesize-32
+
+    A close look newmdct.c shows that the polyphase filterbank
+    only uses data from [0..510] for each window.  Perhaps because the window
+    used by the filterbank is zero for the last point, so Takehiro's
+    code doesn't bother to compute with it.
+
+    FFT starts at 576-224-MDCTDELAY (304)  = 576-FFTOFFSET
+
+*/
+
+typedef FLOAT chgrdata[2][2];
+
+
+int
+lame_encode_mp3_frame(       /* Output */
+                         lame_internal_flags * gfc, /* Context */
+                         sample_t const *inbuf_l, /* Input */
+                         sample_t const *inbuf_r, /* Input */
+                         unsigned char *mp3buf, /* Output */
+                         int mp3buf_size)
+{                       /* Output */
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     mp3count;
+    III_psy_ratio masking_LR[2][2]; /*LR masking & energy */
+    III_psy_ratio masking_MS[2][2]; /*MS masking & energy */
+    const III_psy_ratio (*masking)[2]; /*pointer to selected maskings */
+    const sample_t *inbuf[2];
+
+    FLOAT   tot_ener[2][4];
+    FLOAT   ms_ener_ratio[2] = { .5, .5 };
+    FLOAT   pe[2][2] = { {0., 0.}, {0., 0.} }, pe_MS[2][2] = { {
+    0., 0.}, {
+    0., 0.}};
+    FLOAT (*pe_use)[2];
+
+    int     ch, gr;
+
+    inbuf[0] = inbuf_l;
+    inbuf[1] = inbuf_r;
+
+    if (gfc->lame_encode_frame_init == 0) {
+        /*first run? */
+        lame_encode_frame_init(gfc, inbuf);
+
+    }
+
+
+    /********************** padding *****************************/
+    /* padding method as described in 
+     * "MPEG-Layer3 / Bitstream Syntax and Decoding"
+     * by Martin Sieler, Ralph Sperschneider
+     *
+     * note: there is no padding for the very first frame
+     *
+     * Robert Hegemann 2000-06-22
+     */
+    gfc->ov_enc.padding = FALSE;
+    if ((gfc->sv_enc.slot_lag -= gfc->sv_enc.frac_SpF) < 0) {
+        gfc->sv_enc.slot_lag += cfg->samplerate_out;
+        gfc->ov_enc.padding = TRUE;
+    }
+
+
+
+    /****************************************
+    *   Stage 1: psychoacoustic model       *
+    ****************************************/
+
+    {
+        /* psychoacoustic model
+         * psy model has a 1 granule (576) delay that we must compensate for
+         * (mt 6/99).
+         */
+        int     ret;
+        const sample_t *bufp[2] = {0, 0}; /* address of beginning of left & right granule */
+        int     blocktype[2];
+
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                bufp[ch] = &inbuf[ch][576 + gr * 576 - FFTOFFSET];
+            }
+            ret = L3psycho_anal_vbr(gfc, bufp, gr,
+                                    masking_LR, masking_MS,
+                                    pe[gr], pe_MS[gr], tot_ener[gr], blocktype);
+            if (ret != 0)
+                return -4;
+
+            if (cfg->mode == JOINT_STEREO) {
+                ms_ener_ratio[gr] = tot_ener[gr][2] + tot_ener[gr][3];
+                if (ms_ener_ratio[gr] > 0)
+                    ms_ener_ratio[gr] = tot_ener[gr][3] / ms_ener_ratio[gr];
+            }
+
+            /* block type flags */
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
+                cod_info->block_type = blocktype[ch];
+                cod_info->mixed_block_flag = 0;
+            }
+        }
+    }
+
+
+    /* auto-adjust of ATH, useful for low volume */
+    adjust_ATH(gfc);
+
+
+    /****************************************
+    *   Stage 2: MDCT                       *
+    ****************************************/
+
+    /* polyphase filtering / mdct */
+    mdct_sub48(gfc, inbuf[0], inbuf[1]);
+
+
+    /****************************************
+    *   Stage 3: MS/LR decision             *
+    ****************************************/
+
+    /* Here will be selected MS or LR coding of the 2 stereo channels */
+    gfc->ov_enc.mode_ext = MPG_MD_LR_LR;
+
+    if (cfg->force_ms) {
+        gfc->ov_enc.mode_ext = MPG_MD_MS_LR;
+    }
+    else if (cfg->mode == JOINT_STEREO) {
+        /* ms_ratio = is scaled, for historical reasons, to look like
+           a ratio of side_channel / total.
+           0 = signal is 100% mono
+           .5 = L & R uncorrelated
+         */
+
+        /* [0] and [1] are the results for the two granules in MPEG-1,
+         * in MPEG-2 it's only a faked averaging of the same value
+         * _prev is the value of the last granule of the previous frame
+         * _next is the value of the first granule of the next frame
+         */
+
+        FLOAT   sum_pe_MS = 0;
+        FLOAT   sum_pe_LR = 0;
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                sum_pe_MS += pe_MS[gr][ch];
+                sum_pe_LR += pe[gr][ch];
+            }
+        }
+
+        /* based on PE: M/S coding would not use much more bits than L/R */
+        if (sum_pe_MS <= 1.00 * sum_pe_LR) {
+
+            gr_info const *const gi0 = &gfc->l3_side.tt[0][0];
+            gr_info const *const gi1 = &gfc->l3_side.tt[cfg->mode_gr - 1][0];
+
+            if (gi0[0].block_type == gi0[1].block_type && gi1[0].block_type == gi1[1].block_type) {
+
+                gfc->ov_enc.mode_ext = MPG_MD_MS_LR;
+            }
+        }
+    }
+
+    /* bit and noise allocation */
+    if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+        masking = (const III_psy_ratio (*)[2])masking_MS; /* use MS masking */
+        pe_use = pe_MS;
+    }
+    else {
+        masking = (const III_psy_ratio (*)[2])masking_LR; /* use LR masking */
+        pe_use = pe;
+    }
+
+
+    /* copy data for MP3 frame analyzer */
+    if (cfg->analysis && gfc->pinfo != NULL) {
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gfc->pinfo->ms_ratio[gr] = 0;
+                gfc->pinfo->ms_ener_ratio[gr] = ms_ener_ratio[gr];
+                gfc->pinfo->blocktype[gr][ch] = gfc->l3_side.tt[gr][ch].block_type;
+                gfc->pinfo->pe[gr][ch] = pe_use[gr][ch];
+                memcpy(gfc->pinfo->xr[gr][ch], &gfc->l3_side.tt[gr][ch].xr[0], sizeof(FLOAT) * 576);
+                /* in psymodel, LR and MS data was stored in pinfo.  
+                   switch to MS data: */
+                if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+                    gfc->pinfo->ers[gr][ch] = gfc->pinfo->ers[gr][ch + 2];
+                    memcpy(gfc->pinfo->energy[gr][ch], gfc->pinfo->energy[gr][ch + 2],
+                           sizeof(gfc->pinfo->energy[gr][ch]));
+                }
+            }
+        }
+    }
+
+
+    /****************************************
+    *   Stage 4: quantization loop          *
+    ****************************************/
+
+    if (cfg->vbr == vbr_off || cfg->vbr == vbr_abr) {
+        static FLOAT const fircoef[9] = {
+            -0.0207887 * 5, -0.0378413 * 5, -0.0432472 * 5, -0.031183 * 5,
+            7.79609e-18 * 5, 0.0467745 * 5, 0.10091 * 5, 0.151365 * 5,
+            0.187098 * 5
+        };
+
+        int     i;
+        FLOAT   f;
+
+        for (i = 0; i < 18; i++)
+            gfc->sv_enc.pefirbuf[i] = gfc->sv_enc.pefirbuf[i + 1];
+
+        f = 0.0;
+        for (gr = 0; gr < cfg->mode_gr; gr++)
+            for (ch = 0; ch < cfg->channels_out; ch++)
+                f += pe_use[gr][ch];
+        gfc->sv_enc.pefirbuf[18] = f;
+
+        f = gfc->sv_enc.pefirbuf[9];
+        for (i = 0; i < 9; i++)
+            f += (gfc->sv_enc.pefirbuf[i] + gfc->sv_enc.pefirbuf[18 - i]) * fircoef[i];
+
+        f = (670 * 5 * cfg->mode_gr * cfg->channels_out) / f;
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                pe_use[gr][ch] *= f;
+            }
+        }
+    }
+    switch (cfg->vbr)
+    {
+    default:
+    case vbr_off:
+        CBR_iteration_loop(gfc, (const FLOAT (*)[2])pe_use, ms_ener_ratio, masking);
+        break;
+    case vbr_abr:
+        ABR_iteration_loop(gfc, (const FLOAT (*)[2])pe_use, ms_ener_ratio, masking);
+        break;
+    case vbr_rh:
+        VBR_old_iteration_loop(gfc, (const FLOAT (*)[2])pe_use, ms_ener_ratio, masking);
+        break;
+    case vbr_mt:
+    case vbr_mtrh:
+        VBR_new_iteration_loop(gfc, (const FLOAT (*)[2])pe_use, ms_ener_ratio, masking);
+        break;
+    }
+
+
+    /****************************************
+    *   Stage 5: bitstream formatting       *
+    ****************************************/
+
+
+    /*  write the frame to the bitstream  */
+    (void) format_bitstream(gfc);
+
+    /* copy mp3 bit buffer into array */
+    mp3count = copy_buffer(gfc, mp3buf, mp3buf_size, 1);
+
+
+    if (cfg->write_lame_tag) {
+        AddVbrFrame(gfc);
+    }
+
+    if (cfg->analysis && gfc->pinfo != NULL) {
+        int     framesize = 576 * cfg->mode_gr;
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            int     j;
+            for (j = 0; j < FFTOFFSET; j++)
+                gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j + framesize];
+            for (j = FFTOFFSET; j < 1600; j++) {
+                gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j - FFTOFFSET];
+            }
+        }
+        gfc->sv_qnt.masking_lower = 1.0;
+
+        set_frame_pinfo(gfc, masking);
+    }
+
+    ++gfc->ov_enc.frame_number;
+
+    updateStats(gfc);
+
+    return mp3count;
+}
diff --git a/lame/libmp3lame/encoder.h b/lame/libmp3lame/encoder.h
new file mode 100644 (file)
index 0000000..b06a7c6
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ *      encoder.h include file
+ *
+ *      Copyright (c) 2000 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+
+#ifndef LAME_ENCODER_H
+#define LAME_ENCODER_H
+
+/***********************************************************************
+*
+*  encoder and decoder delays
+*
+***********************************************************************/
+
+/* 
+ * layer III enc->dec delay:  1056 (1057?)   (observed)
+ * layer  II enc->dec delay:   480  (481?)   (observed)
+ *
+ * polyphase 256-16             (dec or enc)        = 240
+ * mdct      256+32  (9*32)     (dec or enc)        = 288
+ * total:    512+16
+ *
+ * My guess is that delay of polyphase filterbank is actualy 240.5
+ * (there are technical reasons for this, see postings in mp3encoder).
+ * So total Encode+Decode delay = ENCDELAY + 528 + 1
+ */
+
+/* 
+ * ENCDELAY  The encoder delay.  
+ *
+ * Minimum allowed is MDCTDELAY (see below)
+ *  
+ * The first 96 samples will be attenuated, so using a value less than 96
+ * will result in corrupt data for the first 96-ENCDELAY samples.
+ *
+ * suggested: 576
+ * set to 1160 to sync with FhG.
+ */
+
+#define ENCDELAY      576
+
+
+
+/*
+ * make sure there is at least one complete frame after the
+ * last frame containing real data
+ *
+ * Using a value of 288 would be sufficient for a 
+ * a very sophisticated decoder that can decode granule-by-granule instead
+ * of frame by frame.  But lets not assume this, and assume the decoder  
+ * will not decode frame N unless it also has data for frame N+1
+ *
+ */
+/*#define POSTDELAY   288*/
+#define POSTDELAY   1152
+
+
+
+/* 
+ * delay of the MDCT used in mdct.c
+ * original ISO routines had a delay of 528!  
+ * Takehiro's routines: 
+ */
+
+#define MDCTDELAY     48
+#define FFTOFFSET     (224+MDCTDELAY)
+
+/*
+ * Most decoders, including the one we use, have a delay of 528 samples.  
+ */
+
+#define DECDELAY      528
+
+
+/* number of subbands */
+#define SBLIMIT       32
+
+/* parition bands bands */
+#define CBANDS        64
+
+/* number of critical bands/scale factor bands where masking is computed*/
+#define SBPSY_l       21
+#define SBPSY_s       12
+
+/* total number of scalefactor bands encoded */
+#define SBMAX_l       22
+#define SBMAX_s       13
+#define PSFB21         6
+#define PSFB12         6
+
+
+
+/* FFT sizes */
+#define BLKSIZE       1024
+#define HBLKSIZE      (BLKSIZE/2 + 1)
+#define BLKSIZE_s     256
+#define HBLKSIZE_s    (BLKSIZE_s/2 + 1)
+
+
+/* #define switch_pe        1800 */
+#define NORM_TYPE     0
+#define START_TYPE    1
+#define SHORT_TYPE    2
+#define STOP_TYPE     3
+
+/* 
+ * Mode Extention:
+ * When we are in stereo mode, there are 4 possible methods to store these
+ * two channels. The stereo modes -m? are using a subset of them.
+ *
+ *  -ms: MPG_MD_LR_LR
+ *  -mj: MPG_MD_LR_LR and MPG_MD_MS_LR
+ *  -mf: MPG_MD_MS_LR
+ *  -mi: all
+ */
+#if 0
+#define MPG_MD_LR_LR  0
+#define MPG_MD_LR_I   1
+#define MPG_MD_MS_LR  2
+#define MPG_MD_MS_I   3
+#endif
+enum MPEGChannelMode
+{   MPG_MD_LR_LR = 0
+,   MPG_MD_LR_I  = 1
+,   MPG_MD_MS_LR = 2
+,   MPG_MD_MS_I  = 3
+};
+
+#ifndef lame_internal_flags_defined
+#define lame_internal_flags_defined
+struct lame_internal_flags;
+typedef struct lame_internal_flags lame_internal_flags;
+#endif
+
+int     lame_encode_mp3_frame(lame_internal_flags * gfc,
+                              sample_t const *inbuf_l,
+                              sample_t const *inbuf_r, unsigned char *mp3buf, int mp3buf_size);
+
+#endif /* LAME_ENCODER_H */
diff --git a/lame/libmp3lame/fft.c b/lame/libmp3lame/fft.c
new file mode 100644 (file)
index 0000000..4eea1ad
--- /dev/null
@@ -0,0 +1,339 @@
+/*
+** FFT and FHT routines
+**  Copyright 1988, 1993; Ron Mayer
+**      Copyright (c) 1999-2000 Takehiro Tominaga
+**
+**  fht(fz,n);
+**      Does a hartley transform of "n" points in the array "fz".
+**
+** NOTE: This routine uses at least 2 patented algorithms, and may be
+**       under the restrictions of a bunch of different organizations.
+**       Although I wrote it completely myself; it is kind of a derivative
+**       of a routine I once authored and released under the GPL, so it
+**       may fall under the free software foundation's restrictions;
+**       it was worked on as a Stanford Univ project, so they claim
+**       some rights to it; it was further optimized at work here, so
+**       I think this company claims parts of it.  The patents are
+**       held by R. Bracewell (the FHT algorithm) and O. Buneman (the
+**       trig generator), both at Stanford Univ.
+**       If it were up to me, I'd say go do whatever you want with it;
+**       but it would be polite to give credit to the following people
+**       if you use this anywhere:
+**           Euler     - probable inventor of the fourier transform.
+**           Gauss     - probable inventor of the FFT.
+**           Hartley   - probable inventor of the hartley transform.
+**           Buneman   - for a really cool trig generator
+**           Mayer(me) - for authoring this particular version and
+**                       including all the optimizations in one package.
+**       Thanks,
+**       Ron Mayer; mayer@acuson.com
+** and added some optimization by
+**           Mather    - idea of using lookup table
+**           Takehiro  - some dirty hack for speed up
+*/
+
+/* $Id: fft.c,v 1.39 2017/09/06 15:07:29 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "fft.h"
+
+#include "vector/lame_intrin.h"
+
+
+
+#define TRI_SIZE (5-1)  /* 1024 =  4**5 */
+
+/* fft.c    */
+
+static const FLOAT costab[TRI_SIZE * 2] = {
+    9.238795325112867e-01, 3.826834323650898e-01,
+    9.951847266721969e-01, 9.801714032956060e-02,
+    9.996988186962042e-01, 2.454122852291229e-02,
+    9.999811752826011e-01, 6.135884649154475e-03
+};
+
+static void
+fht(FLOAT * fz, int n)
+{
+    const FLOAT *tri = costab;
+    int     k4;
+    FLOAT  *fi, *gi;
+    FLOAT const *fn;
+
+    n <<= 1;            /* to get BLKSIZE, because of 3DNow! ASM routine */
+    fn = fz + n;
+    k4 = 4;
+    do {
+        FLOAT   s1, c1;
+        int     i, k1, k2, k3, kx;
+        kx = k4 >> 1;
+        k1 = k4;
+        k2 = k4 << 1;
+        k3 = k2 + k1;
+        k4 = k2 << 1;
+        fi = fz;
+        gi = fi + kx;
+        do {
+            FLOAT   f0, f1, f2, f3;
+            f1 = fi[0] - fi[k1];
+            f0 = fi[0] + fi[k1];
+            f3 = fi[k2] - fi[k3];
+            f2 = fi[k2] + fi[k3];
+            fi[k2] = f0 - f2;
+            fi[0] = f0 + f2;
+            fi[k3] = f1 - f3;
+            fi[k1] = f1 + f3;
+            f1 = gi[0] - gi[k1];
+            f0 = gi[0] + gi[k1];
+            f3 = SQRT2 * gi[k3];
+            f2 = SQRT2 * gi[k2];
+            gi[k2] = f0 - f2;
+            gi[0] = f0 + f2;
+            gi[k3] = f1 - f3;
+            gi[k1] = f1 + f3;
+            gi += k4;
+            fi += k4;
+        } while (fi < fn);
+        c1 = tri[0];
+        s1 = tri[1];
+        for (i = 1; i < kx; i++) {
+            FLOAT   c2, s2;
+            c2 = 1 - (2 * s1) * s1;
+            s2 = (2 * s1) * c1;
+            fi = fz + i;
+            gi = fz + k1 - i;
+            do {
+                FLOAT   a, b, g0, f0, f1, g1, f2, g2, f3, g3;
+                b = s2 * fi[k1] - c2 * gi[k1];
+                a = c2 * fi[k1] + s2 * gi[k1];
+                f1 = fi[0] - a;
+                f0 = fi[0] + a;
+                g1 = gi[0] - b;
+                g0 = gi[0] + b;
+                b = s2 * fi[k3] - c2 * gi[k3];
+                a = c2 * fi[k3] + s2 * gi[k3];
+                f3 = fi[k2] - a;
+                f2 = fi[k2] + a;
+                g3 = gi[k2] - b;
+                g2 = gi[k2] + b;
+                b = s1 * f2 - c1 * g3;
+                a = c1 * f2 + s1 * g3;
+                fi[k2] = f0 - a;
+                fi[0] = f0 + a;
+                gi[k3] = g1 - b;
+                gi[k1] = g1 + b;
+                b = c1 * g2 - s1 * f3;
+                a = s1 * g2 + c1 * f3;
+                gi[k2] = g0 - a;
+                gi[0] = g0 + a;
+                fi[k3] = f1 - b;
+                fi[k1] = f1 + b;
+                gi += k4;
+                fi += k4;
+            } while (fi < fn);
+            c2 = c1;
+            c1 = c2 * tri[0] - s1 * tri[1];
+            s1 = c2 * tri[1] + s1 * tri[0];
+        }
+        tri += 2;
+    } while (k4 < n);
+}
+
+
+static const unsigned char rv_tbl[] = {
+    0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
+    0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
+    0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
+    0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
+    0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
+    0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
+    0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
+    0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
+    0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
+    0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
+    0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
+    0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
+    0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
+    0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
+    0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
+    0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe
+};
+
+#define ch01(index)  (buffer[chn][index])
+
+#define ml00(f) (window[i        ] * f(i))
+#define ml10(f) (window[i + 0x200] * f(i + 0x200))
+#define ml20(f) (window[i + 0x100] * f(i + 0x100))
+#define ml30(f) (window[i + 0x300] * f(i + 0x300))
+
+#define ml01(f) (window[i + 0x001] * f(i + 0x001))
+#define ml11(f) (window[i + 0x201] * f(i + 0x201))
+#define ml21(f) (window[i + 0x101] * f(i + 0x101))
+#define ml31(f) (window[i + 0x301] * f(i + 0x301))
+
+#define ms00(f) (window_s[i       ] * f(i + k))
+#define ms10(f) (window_s[0x7f - i] * f(i + k + 0x80))
+#define ms20(f) (window_s[i + 0x40] * f(i + k + 0x40))
+#define ms30(f) (window_s[0x3f - i] * f(i + k + 0xc0))
+
+#define ms01(f) (window_s[i + 0x01] * f(i + k + 0x01))
+#define ms11(f) (window_s[0x7e - i] * f(i + k + 0x81))
+#define ms21(f) (window_s[i + 0x41] * f(i + k + 0x41))
+#define ms31(f) (window_s[0x3e - i] * f(i + k + 0xc1))
+
+void
+fft_short(lame_internal_flags const *const gfc,
+          FLOAT x_real[3][BLKSIZE_s], int chn, const sample_t *const buffer[2])
+{
+    int     i;
+    int     j;
+    int     b;
+
+#define window_s gfc->cd_psy->window_s
+#define window gfc->cd_psy->window
+
+    for (b = 0; b < 3; b++) {
+        FLOAT  *x = &x_real[b][BLKSIZE_s / 2];
+        short const k = (576 / 3) * (b + 1);
+        j = BLKSIZE_s / 8 - 1;
+        do {
+            FLOAT   f0, f1, f2, f3, w;
+
+            i = rv_tbl[j << 2];
+
+            f0 = ms00(ch01);
+            w = ms10(ch01);
+            f1 = f0 - w;
+            f0 = f0 + w;
+            f2 = ms20(ch01);
+            w = ms30(ch01);
+            f3 = f2 - w;
+            f2 = f2 + w;
+
+            x -= 4;
+            x[0] = f0 + f2;
+            x[2] = f0 - f2;
+            x[1] = f1 + f3;
+            x[3] = f1 - f3;
+
+            f0 = ms01(ch01);
+            w = ms11(ch01);
+            f1 = f0 - w;
+            f0 = f0 + w;
+            f2 = ms21(ch01);
+            w = ms31(ch01);
+            f3 = f2 - w;
+            f2 = f2 + w;
+
+            x[BLKSIZE_s / 2 + 0] = f0 + f2;
+            x[BLKSIZE_s / 2 + 2] = f0 - f2;
+            x[BLKSIZE_s / 2 + 1] = f1 + f3;
+            x[BLKSIZE_s / 2 + 3] = f1 - f3;
+        } while (--j >= 0);
+
+#undef window
+#undef window_s
+
+        gfc->fft_fht(x, BLKSIZE_s / 2);
+        /* BLKSIZE_s/2 because of 3DNow! ASM routine */
+    }
+}
+
+void
+fft_long(lame_internal_flags const *const gfc,
+         FLOAT x[BLKSIZE], int chn, const sample_t *const buffer[2])
+{
+    int     i;
+    int     jj = BLKSIZE / 8 - 1;
+    x += BLKSIZE / 2;
+
+#define window_s gfc->cd_psy->window_s
+#define window gfc->cd_psy->window
+
+    do {
+        FLOAT   f0, f1, f2, f3, w;
+
+        i = rv_tbl[jj];
+        f0 = ml00(ch01);
+        w = ml10(ch01);
+        f1 = f0 - w;
+        f0 = f0 + w;
+        f2 = ml20(ch01);
+        w = ml30(ch01);
+        f3 = f2 - w;
+        f2 = f2 + w;
+
+        x -= 4;
+        x[0] = f0 + f2;
+        x[2] = f0 - f2;
+        x[1] = f1 + f3;
+        x[3] = f1 - f3;
+
+        f0 = ml01(ch01);
+        w = ml11(ch01);
+        f1 = f0 - w;
+        f0 = f0 + w;
+        f2 = ml21(ch01);
+        w = ml31(ch01);
+        f3 = f2 - w;
+        f2 = f2 + w;
+
+        x[BLKSIZE / 2 + 0] = f0 + f2;
+        x[BLKSIZE / 2 + 2] = f0 - f2;
+        x[BLKSIZE / 2 + 1] = f1 + f3;
+        x[BLKSIZE / 2 + 3] = f1 - f3;
+    } while (--jj >= 0);
+
+#undef window
+#undef window_s
+
+    gfc->fft_fht(x, BLKSIZE / 2);
+    /* BLKSIZE/2 because of 3DNow! ASM routine */
+}
+
+#ifdef HAVE_NASM
+extern void fht_3DN(FLOAT * fz, int n);
+extern void fht_SSE(FLOAT * fz, int n);
+#endif
+
+void
+init_fft(lame_internal_flags * const gfc)
+{
+    int     i;
+
+    /* The type of window used here will make no real difference, but */
+    /* in the interest of merging nspsytune stuff - switch to blackman window */
+    for (i = 0; i < BLKSIZE; i++)
+        /* blackman window */
+        gfc->cd_psy->window[i] = 0.42 - 0.5 * cos(2 * PI * (i + .5) / BLKSIZE) +
+            0.08 * cos(4 * PI * (i + .5) / BLKSIZE);
+
+    for (i = 0; i < BLKSIZE_s / 2; i++)
+        gfc->cd_psy->window_s[i] = 0.5 * (1.0 - cos(2.0 * PI * (i + 0.5) / BLKSIZE_s));
+
+    gfc->fft_fht = fht;
+#ifdef HAVE_NASM
+    if (gfc->CPU_features.AMD_3DNow) {
+        gfc->fft_fht = fht_3DN;
+    }
+    else if (gfc->CPU_features.SSE) {
+        gfc->fft_fht = fht_SSE;
+    }
+    else {
+        gfc->fft_fht = fht;
+    }
+#else
+#ifdef HAVE_XMMINTRIN_H
+#ifdef MIN_ARCH_SSE
+    gfc->fft_fht = fht_SSE2;
+#endif
+#endif
+#endif
+}
diff --git a/lame/libmp3lame/fft.h b/lame/libmp3lame/fft.h
new file mode 100644 (file)
index 0000000..258df88
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ *     Fast Fourier Transform include file
+ *
+ *     Copyright (c) 2000 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_FFT_H
+#define LAME_FFT_H
+
+void    fft_long(lame_internal_flags const *const gfc, FLOAT x_real[BLKSIZE],
+                 int chn, const sample_t *const data[2]);
+
+void    fft_short(lame_internal_flags const *const gfc, FLOAT x_real[3][BLKSIZE_s],
+                  int chn, const sample_t *const data[2]);
+
+void    init_fft(lame_internal_flags * const gfc);
+
+#endif
+
+/* End of fft.h */
diff --git a/lame/libmp3lame/gain_analysis.c b/lame/libmp3lame/gain_analysis.c
new file mode 100644 (file)
index 0000000..c94db78
--- /dev/null
@@ -0,0 +1,476 @@
+/*
+ *  ReplayGainAnalysis - analyzes input samples and give the recommended dB change
+ *  Copyright (C) 2001 David Robinson and Glen Sawyer
+ *  Improvements and optimizations added by Frank Klemm, and by Marcel Muller 
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ *  concept and filter values by David Robinson (David@Robinson.org)
+ *    -- blame him if you think the idea is flawed
+ *  original coding by Glen Sawyer (mp3gain@hotmail.com)
+ *    -- blame him if you think this runs too slowly, or the coding is otherwise flawed
+ *
+ *  lots of code improvements by Frank Klemm ( http://www.uni-jena.de/~pfk/mpp/ )
+ *    -- credit him for all the _good_ programming ;)
+ *
+ *
+ *  For an explanation of the concepts and the basic algorithms involved, go to:
+ *    http://www.replaygain.org/
+ */
+
+/*
+ *  Here's the deal. Call
+ *
+ *    InitGainAnalysis ( long samplefreq );
+ *
+ *  to initialize everything. Call
+ *
+ *    AnalyzeSamples ( const Float_t*  left_samples,
+ *                     const Float_t*  right_samples,
+ *                     size_t          num_samples,
+ *                     int             num_channels );
+ *
+ *  as many times as you want, with as many or as few samples as you want.
+ *  If mono, pass the sample buffer in through left_samples, leave
+ *  right_samples NULL, and make sure num_channels = 1.
+ *
+ *    GetTitleGain()
+ *
+ *  will return the recommended dB level change for all samples analyzed
+ *  SINCE THE LAST TIME you called GetTitleGain() OR InitGainAnalysis().
+ *
+ *    GetAlbumGain()
+ *
+ *  will return the recommended dB level change for all samples analyzed
+ *  since InitGainAnalysis() was called and finalized with GetTitleGain().
+ *
+ *  Pseudo-code to process an album:
+ *
+ *    Float_t       l_samples [4096];
+ *    Float_t       r_samples [4096];
+ *    size_t        num_samples;
+ *    unsigned int  num_songs;
+ *    unsigned int  i;
+ *
+ *    InitGainAnalysis ( 44100 );
+ *    for ( i = 1; i <= num_songs; i++ ) {
+ *        while ( ( num_samples = getSongSamples ( song[i], left_samples, right_samples ) ) > 0 )
+ *            AnalyzeSamples ( left_samples, right_samples, num_samples, 2 );
+ *        fprintf ("Recommended dB change for song %2d: %+6.2f dB\n", i, GetTitleGain() );
+ *    }
+ *    fprintf ("Recommended dB change for whole album: %+6.2f dB\n", GetAlbumGain() );
+ */
+
+/*
+ *  So here's the main source of potential code confusion:
+ *
+ *  The filters applied to the incoming samples are IIR filters,
+ *  meaning they rely on up to <filter order> number of previous samples
+ *  AND up to <filter order> number of previous filtered samples.
+ *
+ *  I set up the AnalyzeSamples routine to minimize memory usage and interface
+ *  complexity. The speed isn't compromised too much (I don't think), but the
+ *  internal complexity is higher than it should be for such a relatively
+ *  simple routine.
+ *
+ *  Optimization/clarity suggestions are welcome.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "lame.h"
+#include "machine.h"
+#include "gain_analysis.h"
+
+/* for each filter: */
+/* [0] 48 kHz, [1] 44.1 kHz, [2] 32 kHz, [3] 24 kHz, [4] 22050 Hz, [5] 16 kHz, [6] 12 kHz, [7] is 11025 Hz, [8] 8 kHz */
+
+#ifdef WIN32
+#pragma warning ( disable : 4305 )
+#endif
+
+
+/*lint -save -e736 loss of precision */
+static const Float_t ABYule[9][multiple_of(4, 2 * YULE_ORDER + 1)] = {
+    /* 20                 18                 16                 14                 12                 10                 8                  6                  4                  2                 0                 19                 17                 15                 13                 11                 9                  7                  5                  3                  1              */
+    { 0.00288463683916,  0.00012025322027,  0.00306428023191,  0.00594298065125, -0.02074045215285,  0.02161526843274, -0.01655260341619, -0.00009291677959, -0.00123395316851, -0.02160367184185, 0.03857599435200, 0.13919314567432, -0.86984376593551,  2.75465861874613, -5.87257861775999,  9.48293806319790,-12.28759895145294, 13.05504219327545,-11.34170355132042,  7.81501653005538, -3.84664617118067},
+    {-0.00187763777362,  0.00674613682247, -0.00240879051584,  0.01624864962975, -0.02596338512915,  0.02245293253339, -0.00834990904936, -0.00851165645469, -0.00848709379851, -0.02911007808948, 0.05418656406430, 0.13149317958808, -0.75104302451432,  2.19611684890774, -4.39470996079559,  6.85401540936998, -8.81498681370155,  9.47693607801280, -8.54751527471874,  6.36317777566148, -3.47845948550071},
+    {-0.00881362733839,  0.00651420667831, -0.01390589421898,  0.03174092540049,  0.00222312597743,  0.04781476674921, -0.05588393329856,  0.02163541888798, -0.06247880153653, -0.09331049056315, 0.15457299681924, 0.02347897407020, -0.05032077717131,  0.16378164858596, -0.45953458054983,  1.00595954808547, -1.67148153367602,  2.23697657451713, -2.64577170229825,  2.84868151156327, -2.37898834973084},
+    {-0.02950134983287,  0.00205861885564, -0.00000828086748,  0.06276101321749, -0.00584456039913, -0.02364141202522, -0.00915702933434,  0.03282930172664, -0.08587323730772, -0.22613988682123, 0.30296907319327, 0.00302439095741,  0.02005851806501,  0.04500235387352, -0.22138138954925,  0.39120800788284, -0.22638893773906, -0.16276719120440, -0.25656257754070,  1.07977492259970, -1.61273165137247},
+    {-0.01760176568150, -0.01635381384540,  0.00832043980773,  0.05724228140351, -0.00589500224440, -0.00469977914380, -0.07834489609479,  0.11921148675203, -0.11828570177555, -0.25572241425570, 0.33642304856132, 0.02977207319925, -0.04237348025746,  0.08333755284107, -0.04067510197014, -0.12453458140019,  0.47854794562326, -0.80774944671438,  0.12205022308084,  0.87350271418188, -1.49858979367799},
+    { 0.00541907748707, -0.03193428438915, -0.01863887810927,  0.10478503600251,  0.04097565135648, -0.12398163381748,  0.04078262797139, -0.01419140100551, -0.22784394429749, -0.14351757464547, 0.44915256608450, 0.03222754072173,  0.05784820375801,  0.06747620744683,  0.00613424350682,  0.22199650564824, -0.42029820170918,  0.00213767857124, -0.37256372942400,  0.29661783706366, -0.62820619233671},
+    {-0.00588215443421, -0.03788984554840,  0.08647503780351,  0.00647310677246, -0.27562961986224,  0.30931782841830, -0.18901604199609,  0.16744243493672,  0.16242137742230, -0.75464456939302, 0.56619470757641, 0.01807364323573,  0.01639907836189, -0.04784254229033,  0.06739368333110, -0.33032403314006,  0.45054734505008,  0.00819999645858, -0.26806001042947,  0.29156311971249, -1.04800335126349},
+    {-0.00749618797172, -0.03721611395801,  0.06920467763959,  0.01628462406333, -0.25344790059353,  0.15558449135573,  0.02377945217615,  0.17520704835522, -0.14289799034253, -0.53174909058578, 0.58100494960553, 0.01818801111503,  0.02442357316099, -0.02505961724053, -0.05246019024463, -0.23313271880868,  0.38952639978999,  0.14728154134330, -0.20256413484477, -0.31863563325245, -0.51035327095184},
+    {-0.02217936801134,  0.04788665548180, -0.04060034127000, -0.11202315195388, -0.02459864859345,  0.14590772289388, -0.10214864179676,  0.04267842219415, -0.00275953611929, -0.42163034350696, 0.53648789255105, 0.04704409688120,  0.05477720428674, -0.18823009262115, -0.17556493366449,  0.15113130533216,  0.26408300200955, -0.04678328784242, -0.03424681017675, -0.43193942311114, -0.25049871956020}
+};
+
+static const Float_t ABButter[9][multiple_of(4, 2 * BUTTER_ORDER + 1)] = {
+    /* 5                4                  3                  2                 1              */
+    {0.98621192462708, 0.97261396931306, -1.97242384925416, -1.97223372919527, 0.98621192462708},
+    {0.98500175787242, 0.97022847566350, -1.97000351574484, -1.96977855582618, 0.98500175787242},
+    {0.97938932735214, 0.95920349965459, -1.95877865470428, -1.95835380975398, 0.97938932735214},
+    {0.97531843204928, 0.95124613669835, -1.95063686409857, -1.95002759149878, 0.97531843204928},
+    {0.97316523498161, 0.94705070426118, -1.94633046996323, -1.94561023566527, 0.97316523498161},
+    {0.96454515552826, 0.93034775234268, -1.92909031105652, -1.92783286977036, 0.96454515552826},
+    {0.96009142950541, 0.92177618768381, -1.92018285901082, -1.91858953033784, 0.96009142950541},
+    {0.95856916599601, 0.91885558323625, -1.91713833199203, -1.91542108074780, 0.95856916599601},
+    {0.94597685600279, 0.89487434461664, -1.89195371200558, -1.88903307939452, 0.94597685600279}
+};
+
+/*lint -restore */
+
+#ifdef WIN32
+#pragma warning ( default : 4305 )
+#endif
+
+/* When calling this procedure, make sure that ip[-order] and op[-order] point to real data! */
+
+static void
+filterYule(const Float_t * input, Float_t * output, size_t nSamples, const Float_t * const kernel)
+{
+    while (nSamples--) {
+        Float_t y0 =  input[-10] * kernel[ 0];
+        Float_t y2 =  input[ -9] * kernel[ 1];
+        Float_t y4 =  input[ -8] * kernel[ 2];
+        Float_t y6 =  input[ -7] * kernel[ 3];
+        Float_t s00 = y0 + y2 + y4 + y6;
+        Float_t y8 =  input[ -6] * kernel[ 4];
+        Float_t yA =  input[ -5] * kernel[ 5];
+        Float_t yC =  input[ -4] * kernel[ 6];
+        Float_t yE =  input[ -3] * kernel[ 7];
+        Float_t s01 = y8 + yA + yC + yE;
+        Float_t yG =  input[ -2] * kernel[ 8] + input[ -1] * kernel[ 9];
+        Float_t yK =  input[  0] * kernel[10];
+
+        Float_t s1 = s00 + s01 + yG + yK;
+
+        Float_t x1 = output[-10] * kernel[11] + output[ -9] * kernel[12];
+        Float_t x5 = output[ -8] * kernel[13] + output[ -7] * kernel[14];
+        Float_t x9 = output[ -6] * kernel[15] + output[ -5] * kernel[16];
+        Float_t xD = output[ -4] * kernel[17] + output[ -3] * kernel[18];
+        Float_t xH = output[ -2] * kernel[19] + output[ -1] * kernel[20];
+
+        Float_t s2 = x1 + x5 + x9 + xD + xH;
+
+        output[0] = (Float_t)(s1 - s2);
+
+        ++output;
+        ++input;
+    }
+}
+
+static void
+filterButter(const Float_t * input, Float_t * output, size_t nSamples, const Float_t * const kernel)
+{
+    while (nSamples--) {
+        Float_t s1 =  input[-2] * kernel[0] +  input[-1] * kernel[2] +  input[ 0] * kernel[4];
+        Float_t s2 = output[-2] * kernel[1] + output[-1] * kernel[3];
+        output[0] = (Float_t)(s1 - s2);
+        ++output;
+        ++input;
+    }
+}
+
+
+
+static int ResetSampleFrequency(replaygain_t * rgData, long samplefreq);
+
+/* returns a INIT_GAIN_ANALYSIS_OK if successful, INIT_GAIN_ANALYSIS_ERROR if not */
+
+int
+ResetSampleFrequency(replaygain_t * rgData, long samplefreq)
+{
+    /* zero out initial values, only first MAX_ORDER values */
+    memset(rgData->linprebuf, 0, MAX_ORDER * sizeof(*rgData->linprebuf));
+    memset(rgData->rinprebuf, 0, MAX_ORDER * sizeof(*rgData->rinprebuf));
+    memset(rgData->lstepbuf,  0, MAX_ORDER * sizeof(*rgData->lstepbuf));
+    memset(rgData->rstepbuf,  0, MAX_ORDER * sizeof(*rgData->rstepbuf));
+    memset(rgData->loutbuf,   0, MAX_ORDER * sizeof(*rgData->loutbuf));
+    memset(rgData->routbuf,   0, MAX_ORDER * sizeof(*rgData->routbuf));
+
+    switch ((int) (samplefreq)) {
+    case 48000:
+        rgData->freqindex = 0;
+        break;
+    case 44100:
+        rgData->freqindex = 1;
+        break;
+    case 32000:
+        rgData->freqindex = 2;
+        break;
+    case 24000:
+        rgData->freqindex = 3;
+        break;
+    case 22050:
+        rgData->freqindex = 4;
+        break;
+    case 16000:
+        rgData->freqindex = 5;
+        break;
+    case 12000:
+        rgData->freqindex = 6;
+        break;
+    case 11025:
+        rgData->freqindex = 7;
+        break;
+    case 8000:
+        rgData->freqindex = 8;
+        break;
+    default:
+        return INIT_GAIN_ANALYSIS_ERROR;
+    }
+
+    rgData->sampleWindow =
+        (samplefreq * RMS_WINDOW_TIME_NUMERATOR + RMS_WINDOW_TIME_DENOMINATOR -
+         1) / RMS_WINDOW_TIME_DENOMINATOR;
+
+    rgData->lsum = 0.;
+    rgData->rsum = 0.;
+    rgData->totsamp = 0;
+
+    memset(rgData->A, 0, sizeof(rgData->A));
+
+    return INIT_GAIN_ANALYSIS_OK;
+}
+
+int
+InitGainAnalysis(replaygain_t * rgData, long samplefreq)
+{
+    if (ResetSampleFrequency(rgData, samplefreq) != INIT_GAIN_ANALYSIS_OK) {
+        return INIT_GAIN_ANALYSIS_ERROR;
+    }
+
+    rgData->linpre = rgData->linprebuf + MAX_ORDER;
+    rgData->rinpre = rgData->rinprebuf + MAX_ORDER;
+    rgData->lstep = rgData->lstepbuf + MAX_ORDER;
+    rgData->rstep = rgData->rstepbuf + MAX_ORDER;
+    rgData->lout = rgData->loutbuf + MAX_ORDER;
+    rgData->rout = rgData->routbuf + MAX_ORDER;
+
+    memset(rgData->B, 0, sizeof(rgData->B));
+
+    return INIT_GAIN_ANALYSIS_OK;
+}
+
+/* returns GAIN_ANALYSIS_OK if successful, GAIN_ANALYSIS_ERROR if not */
+
+int
+AnalyzeSamples(replaygain_t * rgData, const Float_t * left_samples, const Float_t * right_samples,
+               size_t num_samples, int num_channels)
+{
+    const Float_t *curleft;
+    const Float_t *curright;
+    long    batchsamples;
+    long    cursamples;
+    long    cursamplepos;
+    int     i;
+    Float_t sum_l, sum_r;
+
+    if (num_samples == 0)
+        return GAIN_ANALYSIS_OK;
+
+    cursamplepos = 0;
+    batchsamples = (long) num_samples;
+
+    switch (num_channels) {
+    case 1:
+        right_samples = left_samples;
+        break;
+    case 2:
+        break;
+    default:
+        return GAIN_ANALYSIS_ERROR;
+    }
+
+    if (num_samples < MAX_ORDER) {
+        memcpy(rgData->linprebuf + MAX_ORDER, left_samples, num_samples * sizeof(Float_t));
+        memcpy(rgData->rinprebuf + MAX_ORDER, right_samples, num_samples * sizeof(Float_t));
+    }
+    else {
+        memcpy(rgData->linprebuf + MAX_ORDER, left_samples, MAX_ORDER * sizeof(Float_t));
+        memcpy(rgData->rinprebuf + MAX_ORDER, right_samples, MAX_ORDER * sizeof(Float_t));
+    }
+
+    while (batchsamples > 0) {
+        cursamples = batchsamples > rgData->sampleWindow - rgData->totsamp ?
+            rgData->sampleWindow - rgData->totsamp : batchsamples;
+        if (cursamplepos < MAX_ORDER) {
+            curleft = rgData->linpre + cursamplepos;
+            curright = rgData->rinpre + cursamplepos;
+            if (cursamples > MAX_ORDER - cursamplepos)
+                cursamples = MAX_ORDER - cursamplepos;
+        }
+        else {
+            curleft = left_samples + cursamplepos;
+            curright = right_samples + cursamplepos;
+        }
+
+        YULE_FILTER(curleft, rgData->lstep + rgData->totsamp, cursamples,
+                    ABYule[rgData->freqindex]);
+        YULE_FILTER(curright, rgData->rstep + rgData->totsamp, cursamples,
+                    ABYule[rgData->freqindex]);
+
+        BUTTER_FILTER(rgData->lstep + rgData->totsamp, rgData->lout + rgData->totsamp, cursamples,
+                      ABButter[rgData->freqindex]);
+        BUTTER_FILTER(rgData->rstep + rgData->totsamp, rgData->rout + rgData->totsamp, cursamples,
+                      ABButter[rgData->freqindex]);
+
+        curleft = rgData->lout + rgData->totsamp; /* Get the squared values */
+        curright = rgData->rout + rgData->totsamp;
+
+        sum_l = 0;
+        sum_r = 0;
+        i = cursamples & 0x03;
+        while (i--) {
+            Float_t const l = *curleft++;
+            Float_t const r = *curright++;
+            sum_l += l * l;
+            sum_r += r * r;
+        }
+        i = cursamples / 4;
+        while (i--) {
+            Float_t l0 = curleft[0] * curleft[0];
+            Float_t l1 = curleft[1] * curleft[1];
+            Float_t l2 = curleft[2] * curleft[2];
+            Float_t l3 = curleft[3] * curleft[3];
+            Float_t sl = l0 + l1 + l2 + l3;
+            Float_t r0 = curright[0] * curright[0];
+            Float_t r1 = curright[1] * curright[1];
+            Float_t r2 = curright[2] * curright[2];
+            Float_t r3 = curright[3] * curright[3];
+            Float_t sr = r0 + r1 + r2 + r3;
+            sum_l += sl;
+            curleft += 4;
+            sum_r += sr;
+            curright += 4;
+        }
+        rgData->lsum += sum_l;
+        rgData->rsum += sum_r;
+
+        batchsamples -= cursamples;
+        cursamplepos += cursamples;
+        rgData->totsamp += cursamples;
+        if (rgData->totsamp == rgData->sampleWindow) { /* Get the Root Mean Square (RMS) for this set of samples */
+            double const val =
+                STEPS_per_dB * 10. * log10((rgData->lsum + rgData->rsum) / rgData->totsamp * 0.5 +
+                                           1.e-37);
+            size_t  ival = (val <= 0) ? 0 : (size_t) val;
+            if (ival >= sizeof(rgData->A) / sizeof(*(rgData->A)))
+                ival = sizeof(rgData->A) / sizeof(*(rgData->A)) - 1;
+            rgData->A[ival]++;
+            rgData->lsum = rgData->rsum = 0.;
+            memmove(rgData->loutbuf, rgData->loutbuf + rgData->totsamp,
+                    MAX_ORDER * sizeof(Float_t));
+            memmove(rgData->routbuf, rgData->routbuf + rgData->totsamp,
+                    MAX_ORDER * sizeof(Float_t));
+            memmove(rgData->lstepbuf, rgData->lstepbuf + rgData->totsamp,
+                    MAX_ORDER * sizeof(Float_t));
+            memmove(rgData->rstepbuf, rgData->rstepbuf + rgData->totsamp,
+                    MAX_ORDER * sizeof(Float_t));
+            rgData->totsamp = 0;
+        }
+        if (rgData->totsamp > rgData->sampleWindow) /* somehow I really screwed up: Error in programming! Contact author about totsamp > sampleWindow */
+            return GAIN_ANALYSIS_ERROR;
+    }
+    if (num_samples < MAX_ORDER) {
+        memmove(rgData->linprebuf, rgData->linprebuf + num_samples,
+                (MAX_ORDER - num_samples) * sizeof(Float_t));
+        memmove(rgData->rinprebuf, rgData->rinprebuf + num_samples,
+                (MAX_ORDER - num_samples) * sizeof(Float_t));
+        memcpy(rgData->linprebuf + MAX_ORDER - num_samples, left_samples,
+               num_samples * sizeof(Float_t));
+        memcpy(rgData->rinprebuf + MAX_ORDER - num_samples, right_samples,
+               num_samples * sizeof(Float_t));
+    }
+    else {
+        memcpy(rgData->linprebuf, left_samples + num_samples - MAX_ORDER,
+               MAX_ORDER * sizeof(Float_t));
+        memcpy(rgData->rinprebuf, right_samples + num_samples - MAX_ORDER,
+               MAX_ORDER * sizeof(Float_t));
+    }
+
+    return GAIN_ANALYSIS_OK;
+}
+
+
+static  Float_t
+analyzeResult(uint32_t const *Array, size_t len)
+{
+    uint32_t elems;
+    uint32_t upper;
+    uint32_t sum;
+    size_t  i;
+
+    elems = 0;
+    for (i = 0; i < len; i++)
+        elems += Array[i];
+    if (elems == 0)
+        return GAIN_NOT_ENOUGH_SAMPLES;
+
+    upper = (uint32_t) ceil(elems * (1. - RMS_PERCENTILE));
+    sum = 0;
+    for (i = len; i-- > 0;) {
+        sum += Array[i];
+        if (sum >= upper) {
+            break;
+        }
+    }
+
+    return (Float_t) ((Float_t) PINK_REF - (Float_t) i / (Float_t) STEPS_per_dB);
+}
+
+
+Float_t
+GetTitleGain(replaygain_t * rgData)
+{
+    Float_t retval;
+    unsigned int i;
+
+    retval = analyzeResult(rgData->A, sizeof(rgData->A) / sizeof(*(rgData->A)));
+
+    for (i = 0; i < sizeof(rgData->A) / sizeof(*(rgData->A)); i++) {
+        rgData->B[i] += rgData->A[i];
+        rgData->A[i] = 0;
+    }
+
+    for (i = 0; i < MAX_ORDER; i++)
+        rgData->linprebuf[i] = rgData->lstepbuf[i]
+            = rgData->loutbuf[i]
+            = rgData->rinprebuf[i]
+            = rgData->rstepbuf[i]
+            = rgData->routbuf[i] = 0.f;
+
+    rgData->totsamp = 0;
+    rgData->lsum = rgData->rsum = 0.;
+    return retval;
+}
+
+#if 0
+static Float_t GetAlbumGain(replaygain_t const* rgData);
+
+Float_t
+GetAlbumGain(replaygain_t const* rgData)
+{
+    return analyzeResult(rgData->B, sizeof(rgData->B) / sizeof(*(rgData->B)));
+}
+#endif
+
+/* end of gain_analysis.c */
diff --git a/lame/libmp3lame/gain_analysis.h b/lame/libmp3lame/gain_analysis.h
new file mode 100644 (file)
index 0000000..a6b56ab
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ *  ReplayGainAnalysis - analyzes input samples and give the recommended dB change
+ *  Copyright (C) 2001 David Robinson and Glen Sawyer
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ *  concept and filter values by David Robinson (David@Robinson.org)
+ *    -- blame him if you think the idea is flawed
+ *  coding by Glen Sawyer (mp3gain@hotmail.com) 735 W 255 N, Orem, UT 84057-4505 USA
+ *    -- blame him if you think this runs too slowly, or the coding is otherwise flawed
+ *
+ *  For an explanation of the concepts and the basic algorithms involved, go to:
+ *    http://www.replaygain.org/
+ */
+
+#ifndef GAIN_ANALYSIS_H
+#define GAIN_ANALYSIS_H
+
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#else
+# ifdef HAVE_STDINT_H
+#  include <stdint.h>
+# endif
+#endif
+
+#ifdef __cplusplus
+extern  "C" {
+#endif
+
+
+    typedef sample_t Float_t; /* Type used for filtering */
+
+
+#define PINK_REF                64.82       /* 298640883795 */ /* calibration value for 89dB */
+
+
+#define YULE_ORDER         10
+#define BUTTER_ORDER        2
+#define YULE_FILTER     filterYule
+#define BUTTER_FILTER   filterButter
+#define RMS_PERCENTILE      0.95 /* percentile which is louder than the proposed level */
+#define MAX_SAMP_FREQ   48000L /* maximum allowed sample frequency [Hz] */
+#define RMS_WINDOW_TIME_NUMERATOR    1L
+#define RMS_WINDOW_TIME_DENOMINATOR 20L /* numerator / denominator = time slice size [s] */
+#define STEPS_per_dB      100 /* Table entries per dB */
+#define MAX_dB            120 /* Table entries for 0...MAX_dB (normal max. values are 70...80 dB) */
+
+    enum { GAIN_NOT_ENOUGH_SAMPLES = -24601, GAIN_ANALYSIS_ERROR = 0, GAIN_ANALYSIS_OK =
+            1, INIT_GAIN_ANALYSIS_ERROR = 0, INIT_GAIN_ANALYSIS_OK = 1
+    };
+
+    enum { MAX_ORDER = (BUTTER_ORDER > YULE_ORDER ? BUTTER_ORDER : YULE_ORDER)
+            , MAX_SAMPLES_PER_WINDOW = ((MAX_SAMP_FREQ * RMS_WINDOW_TIME_NUMERATOR) / RMS_WINDOW_TIME_DENOMINATOR + 1) /* max. Samples per Time slice */
+    };
+
+    struct replaygain_data {
+        Float_t linprebuf[MAX_ORDER * 2];
+        Float_t *linpre;     /* left input samples, with pre-buffer */
+        Float_t lstepbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];
+        Float_t *lstep;      /* left "first step" (i.e. post first filter) samples */
+        Float_t loutbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];
+        Float_t *lout;       /* left "out" (i.e. post second filter) samples */
+        Float_t rinprebuf[MAX_ORDER * 2];
+        Float_t *rinpre;     /* right input samples ... */
+        Float_t rstepbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];
+        Float_t *rstep;
+        Float_t routbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];
+        Float_t *rout;
+        long    sampleWindow; /* number of samples required to reach number of milliseconds required for RMS window */
+        long    totsamp;
+        double  lsum;
+        double  rsum;
+        int     freqindex;
+        int     first;
+        uint32_t A[STEPS_per_dB * MAX_dB];
+        uint32_t B[STEPS_per_dB * MAX_dB];
+
+    };
+#ifndef replaygain_data_defined
+#define replaygain_data_defined
+    typedef struct replaygain_data replaygain_t;
+#endif
+
+
+
+
+    int     InitGainAnalysis(replaygain_t * rgData, long samplefreq);
+    int     AnalyzeSamples(replaygain_t * rgData, const Float_t * left_samples,
+                           const Float_t * right_samples, size_t num_samples, int num_channels);
+    Float_t GetTitleGain(replaygain_t * rgData);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif                       /* GAIN_ANALYSIS_H */
diff --git a/lame/libmp3lame/i386/choose_table.nas b/lame/libmp3lame/i386/choose_table.nas
new file mode 100644 (file)
index 0000000..9217c8e
--- /dev/null
@@ -0,0 +1,447 @@
+; new count bit routine
+;      part of this code is origined from
+;      new GOGO-no-coda (1999, 2000)
+;      Copyright (C) 1999 shigeo
+;      modified by Keiichi SAKAI
+
+%include "nasm.h"
+
+       globaldef       choose_table_MMX
+       globaldef       MMX_masking
+
+       externdef       largetbl
+       externdef       t1l
+       externdef       table23
+       externdef       table56
+
+       segment_data
+       align   16
+D14_14_14_14   dd      0x000E000E, 0x000E000E
+D15_15_15_15   dd      0xfff0fff0, 0xfff0fff0
+mul_add                dd      0x00010010, 0x00010010
+mul_add23      dd      0x00010003, 0x00010003
+mul_add56      dd      0x00010004, 0x00010004
+tableDEF
+       dd      0x00010003,0x01,0x00050005,0x05,0x00070006,0x07,0x00090008,0x08,0x000a0008, 0x09
+       dd      0x000a0009,0x0a,0x000b000a,0x0a,0x000b000a,0x0b,0x000c000a,0x0a,0x000c000b, 0x0b
+       dd      0x000c000b,0x0c,0x000d000c,0x0c,0x000d000c,0x0d,0x000d000c,0x0d,0x000e000d, 0x0e
+       dd      0x000b000e,0x0e,0x00040005,0x04,0x00060005,0x06,0x00080007,0x08,0x00090008, 0x09
+       dd      0x000a0009,0x0a,0x000b0009,0x0a,0x000b000a,0x0b,0x000b000a,0x0b,0x000c000a, 0x0b
+       dd      0x000c000b,0x0b,0x000c000b,0x0c,0x000d000c,0x0c,0x000e000c,0x0d,0x000d000c, 0x0e
+       dd      0x000e000d,0x0e,0x000b000d,0x0e,0x00070006,0x07,0x00080007,0x08,0x00090007, 0x09
+       dd      0x000a0008,0x0a,0x000b0009,0x0b,0x000b0009,0x0b,0x000c000a,0x0c,0x000c000a, 0x0c
+       dd      0x000d000a,0x0b,0x000c000b,0x0c,0x000d000b,0x0c,0x000d000c,0x0d,0x000d000c, 0x0d
+       dd      0x000e000d,0x0e,0x000e000d,0x0f,0x000c000d,0x0f,0x00090007,0x08,0x00090008, 0x09
+       dd      0x000a0008,0x0a,0x000b0009,0x0b,0x000b0009,0x0b,0x000c000a,0x0c,0x000c000a, 0x0c
+       dd      0x000c000b,0x0c,0x000d000b,0x0c,0x000d000b,0x0d,0x000e000c,0x0d,0x000e000c, 0x0d
+       dd      0x000e000c,0x0d,0x000f000d,0x0e,0x000f000d,0x0f,0x000d000d,0x0f,0x000a0008, 0x09
+       dd      0x000a0008,0x09,0x000b0009,0x0b,0x000b0009,0x0b,0x000c000a,0x0c,0x000c000a, 0x0c
+       dd      0x000d000b,0x0d,0x000d000b,0x0d,0x000d000b,0x0c,0x000e000b,0x0d,0x000e000c, 0x0d
+       dd      0x000e000c,0x0e,0x000f000c,0x0e,0x000f000d,0x0f,0x000f000d,0x0f,0x000c000d, 0x10
+       dd      0x000a0009,0x0a,0x000a0009,0x0a,0x000b0009,0x0b,0x000b000a,0x0c,0x000c000a, 0x0c
+       dd      0x000d000a,0x0c,0x000d000b,0x0d,0x000e000b,0x0d,0x000d000b,0x0d,0x000e000b, 0x0d
+       dd      0x000e000c,0x0e,0x000f000c,0x0d,0x000f000d,0x0f,0x000f000d,0x0f,0x0010000d, 0x10
+       dd      0x000d000e,0x10,0x000b000a,0x0a,0x000b0009,0x0b,0x000b000a,0x0c,0x000c000a, 0x0c
+       dd      0x000d000a,0x0d,0x000d000b,0x0d,0x000d000b,0x0d,0x000d000b,0x0d,0x000e000b, 0x0d
+       dd      0x000e000c,0x0e,0x000e000c,0x0e,0x000e000c,0x0e,0x000f000d,0x0f,0x000f000d, 0x0f
+       dd      0x0010000e,0x10,0x000d000e,0x10,0x000b000a,0x0b,0x000b000a,0x0b,0x000c000a, 0x0c
+       dd      0x000c000b,0x0d,0x000d000b,0x0d,0x000d000b,0x0d,0x000d000b,0x0e,0x000e000c, 0x0e
+       dd      0x000e000c,0x0e,0x000f000c,0x0e,0x000f000c,0x0f,0x000f000c,0x0f,0x000f000d, 0x0f
+       dd      0x0011000d,0x10,0x0011000d,0x12,0x000d000e,0x12,0x000b000a,0x0a,0x000c000a, 0x0a
+       dd      0x000c000a,0x0b,0x000d000b,0x0c,0x000d000b,0x0c,0x000d000b,0x0d,0x000e000b, 0x0d
+       dd      0x000e000c,0x0e,0x000f000c,0x0e,0x000f000c,0x0e,0x000f000c,0x0e,0x000f000d, 0x0f
+       dd      0x0010000d,0x0f,0x0010000e,0x10,0x0010000e,0x11,0x000d000e,0x11,0x000c000a, 0x0b
+       dd      0x000c000a,0x0b,0x000c000b,0x0c,0x000d000b,0x0c,0x000d000b,0x0d,0x000e000b, 0x0d
+       dd      0x000e000c,0x0d,0x000f000c,0x0f,0x000f000c,0x0e,0x000f000d,0x0f,0x000f000d, 0x0f
+       dd      0x0010000d,0x10,0x000f000d,0x10,0x0010000e,0x10,0x000f000e,0x12,0x000e000e, 0x11
+       dd      0x000c000b,0x0b,0x000d000b,0x0c,0x000c000b,0x0c,0x000d000b,0x0d,0x000e000c, 0x0d
+       dd      0x000e000c,0x0e,0x000e000c,0x0e,0x000e000c,0x0f,0x000f000c,0x0e,0x0010000d, 0x0f
+       dd      0x0010000d,0x10,0x0010000d,0x0f,0x0011000d,0x10,0x0011000e,0x11,0x0010000f, 0x12
+       dd      0x000d000e,0x13,0x000d000b,0x0c,0x000d000b,0x0c,0x000d000b,0x0c,0x000d000b, 0x0d
+       dd      0x000e000c,0x0e,0x000e000c,0x0e,0x000f000c,0x0e,0x0010000c,0x0e,0x0010000d, 0x0f
+       dd      0x0010000d,0x0f,0x0010000d,0x0f,0x0010000d,0x10,0x0010000e,0x11,0x000f000e, 0x11
+       dd      0x0010000e,0x11,0x000e000f,0x12,0x000d000c,0x0c,0x000e000c,0x0d,0x000e000b, 0x0d
+       dd      0x000e000c,0x0e,0x000e000c,0x0e,0x000f000c,0x0f,0x000f000d,0x0e,0x000f000d, 0x0f
+       dd      0x000f000d,0x10,0x0011000d,0x10,0x0010000d,0x11,0x0010000d,0x11,0x0010000e, 0x11
+       dd      0x0010000e,0x12,0x0012000f,0x12,0x000e000f,0x12,0x000f000c,0x0d,0x000e000c, 0x0d
+       dd      0x000e000c,0x0e,0x000e000c,0x0f,0x000f000c,0x0f,0x000f000d,0x0f,0x0010000d, 0x10
+       dd      0x0010000d,0x10,0x0010000d,0x10,0x0012000e,0x10,0x0011000e,0x10,0x0011000e, 0x11
+       dd      0x0011000e,0x12,0x0013000e,0x11,0x0011000f,0x12,0x000e000f,0x12,0x000e000d, 0x0e
+       dd      0x000f000d,0x0e,0x000d000d,0x0e,0x000e000d,0x0f,0x0010000d,0x0f,0x0010000d, 0x0f
+       dd      0x000f000d,0x11,0x0010000d,0x10,0x0010000e,0x10,0x0011000e,0x13,0x0012000e, 0x11
+       dd      0x0011000e,0x11,0x0013000f,0x11,0x0011000f,0x13,0x0010000e,0x12,0x000e000f, 0x12
+       dd      0x000b000d,0x0d,0x000b000d,0x0e,0x000b000d,0x0f,0x000c000d,0x10,0x000c000d, 0x10
+       dd      0x000d000d,0x10,0x000d000d,0x11,0x000d000e,0x10,0x000e000e,0x11,0x000e000e, 0x11
+       dd      0x000e000e,0x12,0x000e000e,0x12,0x000e000f,0x15,0x000e000f,0x14,0x000e000f, 0x15
+       dd      0x000c000f,0x12
+
+tableABC
+       dd      0x00020004,0x1,0x00040004,0x4,0x00060006,0x7,0x00080008,0x9,0x00090009,0xa,0x000a000a,0xa
+       dd      0x0009000a,0xa,0x000a000a,0xb,0x00000000,0x0,0x00020003,0x1,0x00040004,0x4,0x00070006,0x7
+       dd      0x00090007,0x9,0x00090009,0x9,0x000a000a,0xa,0x00000000,0x0,0x00040004,0x4,0x00050005,0x6
+       dd      0x00060006,0x8,0x00080007,0x9,0x000a0009,0xa,0x000a0009,0xb,0x0009000a,0xa,0x000a000a,0xa
+       dd      0x00000000,0x0,0x00040004,0x4,0x00040005,0x6,0x00060006,0x8,0x000a0007,0x9,0x000a0008,0x9
+       dd      0x000a000a,0xa,0x00000000,0x0,0x00060006,0x7,0x00070006,0x8,0x00080007,0x9,0x00090008,0xa
+       dd      0x000a0009,0xb,0x000b000a,0xc,0x000a0009,0xb,0x000a000a,0xb,0x00000000,0x0,0x00070005,0x7
+       dd      0x00060006,0x7,0x00080007,0x9,0x000a0008,0xa,0x000a0009,0xa,0x000b000a,0xb,0x00000000,0x0
+       dd      0x00080007,0x8,0x00080007,0x9,0x00090008,0xa,0x000b0008,0xb,0x000a0009,0xc,0x000c000a,0xc
+       dd      0x000a000a,0xb,0x000b000a,0xc,0x00000000,0x0,0x00090007,0x8,0x000a0007,0x9,0x000a0008,0xa
+       dd      0x000b0009,0xb,0x000b0009,0xb,0x000c000a,0xb,0x00000000,0x0,0x00090008,0x9,0x000a0008,0xa
+       dd      0x000a0009,0xb,0x000b0009,0xc,0x000b000a,0xc,0x000c000a,0xc,0x000b000a,0xc,0x000c000b,0xc
+       dd      0x00000000,0x0,0x00090008,0x8,0x00090008,0x9,0x000a0009,0xa,0x000b0009,0xb,0x000c000a,0xb
+       dd      0x000c000b,0xc,0x00000000,0x0,0x00090009,0xa,0x000a0009,0xb,0x000b000a,0xc,0x000c000a,0xc
+       dd      0x000c000a,0xd,0x000d000b,0xd,0x000c000a,0xc,0x000d000b,0xd,0x00000000,0x0,0x000a0009,0x9
+       dd      0x000a0009,0xa,0x000b000a,0xb,0x000b000a,0xc,0x000d000b,0xc,0x000d000b,0xc,0x00000000,0x0
+       dd      0x00090009,0x9,0x00090009,0xa,0x00090009,0xb,0x000a000a,0xc,0x000b000a,0xc,0x000c000b,0xc
+       dd      0x000c000b,0xd,0x000c000c,0xd,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0
+       dd      0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x0009000a,0xa,0x0009000a,0xa
+       dd      0x000a000a,0xb,0x000b000b,0xc,0x000c000b,0xc,0x000c000b,0xd,0x000c000b,0xd,0x000c000c,0xd
+       dd      0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0,0x00000000,0x0
+       dd      0x0,0x00000000, 0x0,0x00000000
+
+linbits32
+       dd      0x00040004,0x10001,0x00040004,0x20002,0x00040004,0x30003,0x00040004,0x40004
+       dd      0x00050005,0x60006,0x00060006,0x60006,0x00070007,0x80008,0x00080008,0x80008
+       dd      0x00090009,0xa000a,0x000b000b,0xa000a,0x000b000b,0xd000d,0x000d000d,0xd000d
+       dd      0x000d000d,0xd000d
+
+
+choose_table_H
+       dw      0x1810, 0x1811, 0x1812, 0x1813, 0x1914, 0x1a14, 0x1b15, 0x1c15
+       dw      0x1d16, 0x1e16, 0x1e17, 0x1f17, 0x1f17
+
+choose_jump_table_L:
+       dd      table_MMX.L_case_0    - choose_table_MMX
+       dd      table_MMX.L_case_1    - choose_table_MMX
+       dd      table_MMX.L_case_2    - choose_table_MMX
+       dd      table_MMX.L_case_3    - choose_table_MMX
+       dd      table_MMX.L_case_45   - choose_table_MMX
+       dd      table_MMX.L_case_45   - choose_table_MMX
+       dd      table_MMX.L_case_67   - choose_table_MMX
+       dd      table_MMX.L_case_67   - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+       dd      table_MMX.L_case_8_15 - choose_table_MMX
+
+       segment_code
+;
+; use MMX
+;
+
+PIC_OFFSETTABLE
+
+       align   16
+; int choose_table(int *ix, int *end, int *s)
+choose_table_MMX:
+       push    ebp
+       call    get_pc.bp
+       add     ebp, PIC_BASE()
+
+       mov     ecx,[esp+8]     ;ecx = begin
+       mov     edx,[esp+12]    ;edx = end
+       sub     ecx,edx         ;ecx = begin-end(should be minus)
+       test    ecx,8
+       pxor    mm0,mm0         ;mm0=[0:0]
+       movq    mm1,[edx+ecx]
+       jz      .lp
+
+       add     ecx,8
+       jz      .exit
+
+       align   4
+.lp:
+       movq    mm4,[edx+ecx]
+       movq    mm5,[edx+ecx+8]
+       add     ecx,16
+       psubusw mm4,mm0 ; \e$BK\Ev$O\e(B dword \e$B$G$J$$$H$$$1$J$$$N$@$,\e(B
+       psubusw mm5,mm1 ; \e$B$=$s$J%3%^%s%I$O$J$$\e(B :-p
+       paddw   mm0,mm4 ; \e$B$,\e(B, \e$B$3$3$G07$&CM$NHO0O$O\e(B 8191+15 \e$B0J2<$J$N$GLdBj$J$$\e(B
+       paddw   mm1,mm5
+       jnz     .lp
+.exit:
+       psubusw mm1,mm0 ; \e$B$3$l$bK\Ev$O\e(B dword \e$B$G$J$$$H$$$1$J$$\e(B
+       paddw   mm0,mm1
+
+       movq    mm4,mm0
+       punpckhdq       mm4,mm4
+       psubusw mm4,mm0 ; \e$B$3$l$bK\Ev$O\e(B dword \e$B$G$J$$$H$$$1$J$$\e(B
+       paddw   mm0,mm4
+       movd    eax,mm0
+
+       cmp     eax,15
+       ja      .with_ESC
+       lea     ecx,[PIC_EBP_REL(choose_table_MMX)]
+       add     ecx,[PIC_EBP_REL(choose_jump_table_L+eax*4)]
+       jmp     ecx
+
+.with_ESC1:
+       emms
+       mov     ecx, [esp+16]   ; *s
+       mov     [ecx], eax
+       or      eax,-1
+       pop     ebp
+       ret
+
+.with_ESC:
+       cmp     eax, 8191+15
+       ja      .with_ESC1
+
+       sub     eax,15
+       push    ebx
+       push    esi
+       bsr     eax, eax
+%assign _P 4*2
+       movq    mm5, [PIC_EBP_REL(D15_15_15_15)]
+       movq    mm6, [PIC_EBP_REL(D14_14_14_14)]
+       movq    mm3, [PIC_EBP_REL(mul_add)]
+
+       mov     ecx, [esp+_P+8]         ; = ix
+;      mov     edx, [esp+_P+12]        ; = end
+       sub     ecx, edx
+
+       xor     esi, esi        ; sum = 0
+       test    ecx, 8
+       pxor    mm7, mm7        ; linbits_sum, 14\e$B$r1[$($?$b$N$N?t\e(B
+       jz      .H_dual_lp1
+
+       movq    mm0, [edx+ecx]
+       add     ecx,8
+       packssdw        mm0,mm7
+       movq    mm2, mm0
+       paddusw mm0, mm5        ; mm0 = min(ix, 15)+0xfff0
+       pcmpgtw mm2, mm6        ; 14\e$B$h$jBg$-$$$+!)\e(B
+       psubw   mm7, mm2        ; 14\e$B$h$jBg$-$$$H$-\e(B linbits_sum++;
+       pmaddwd mm0, mm3        ; {0, 0, y, x}*{1, 16, 1, 16}
+       movd    ebx, mm0
+       mov     esi, [PIC_EBP_REL(largetbl+ebx*4+(16*16+16)*4)]
+
+       jz      .H_dual_exit
+
+       align   4
+.H_dual_lp1:
+       movq    mm0, [edx+ecx]
+       movq    mm1, [edx+ecx+8]
+       packssdw        mm0,mm1
+       movq    mm2, mm0
+       paddusw mm0, mm5        ; mm0 = min(ix, 15)+0xfff0
+       pcmpgtw mm2, mm6        ; 14\e$B$h$jBg$-$$$+!)\e(B
+       pmaddwd mm0, mm3        ; {y, x, y, x}*{1, 16, 1, 16}
+       movd    ebx, mm0
+       punpckhdq       mm0,mm0
+       add     esi, [PIC_EBP_REL(largetbl+ebx*4+(16*16+16)*4)]
+       movd    ebx, mm0
+       add     esi, [PIC_EBP_REL(largetbl+ebx*4+(16*16+16)*4)]
+       add     ecx, 16
+       psubw   mm7, mm2        ; 14\e$B$h$jBg$-$$$H$-\e(B linbits_sum++;
+       jnz     .H_dual_lp1
+
+.H_dual_exit:
+       pmov    mm1,mm7
+       punpckhdq       mm7,mm7
+       paddd   mm7,mm1
+       punpckldq       mm7,mm7
+
+       pmaddwd mm7, [PIC_EBP_REL(linbits32+eax*8)]     ; linbits
+       mov     ax, [PIC_EBP_REL(choose_table_H+eax*2)]
+
+       movd    ecx, mm7
+       punpckhdq       mm7,mm7
+       movd    edx,mm7
+       emms
+       shl     edx, 16
+       add     ecx, edx
+
+       add     ecx, esi
+
+       pop     esi
+       pop     ebx
+
+       mov     edx, ecx
+       and     ecx, 0xffff     ; ecx = sum2
+       shr     edx, 16 ; edx = sum
+
+       cmp     edx, ecx
+       jle     .chooseE_s1
+       mov     edx, ecx
+       shr     eax, 8
+.chooseE_s1:
+       mov     ecx, [esp+16] ; *s
+       and     eax, 0xff
+       add     [ecx], edx
+       pop     ebp
+       ret
+
+table_MMX.L_case_0:
+       emms
+       pop     ebp
+       ret
+
+table_MMX.L_case_1:
+       emms
+       mov     eax, [esp+16] ; *s
+       mov     ecx, [esp+8] ; *ix
+       sub     ecx, edx
+       push    ebx
+.lp:
+       mov     ebx, [edx+ecx]
+       add     ebx, ebx
+       add     ebx, [edx+ecx+4]
+       movzx   ebx, byte [PIC_EBP_REL(ebx+t1l)]
+       add     [eax], ebx
+       add     ecx, 8
+       jnz     .lp
+       pop     ebx
+       mov     eax, 1
+       pop     ebp
+       ret
+
+table_MMX.L_case_45:
+       push    dword 7
+       lea     ecx, [PIC_EBP_REL(tableABC+9*8)]
+       jmp     from3
+
+table_MMX.L_case_67:
+       push    dword 10
+       lea     ecx, [PIC_EBP_REL(tableABC)]
+       jmp     from3
+
+table_MMX.L_case_8_15:
+       push    dword 13
+       lea     ecx, [PIC_EBP_REL(tableDEF)]
+from3:
+       mov     eax,[esp+12]    ;eax = *begin
+;      mov     edx,[esp+16]    ;edx = *end
+
+       push    ebx
+       sub     eax, edx
+
+       movq    mm5,[PIC_EBP_REL(mul_add)]
+       pxor    mm2,mm2 ;mm2 = sum
+
+       test    eax, 8
+       jz      .choose3_lp1
+; odd length
+       movq    mm0,[edx+eax]   ;mm0 = ix[0] | ix[1]
+       add     eax,8
+       packssdw        mm0,mm2
+
+       pmaddwd mm0,mm5
+       movd    ebx,mm0
+
+       movq    mm2,  [ecx+ebx*8]
+
+       jz      .choose3_exit
+
+       align   4
+.choose3_lp1
+       movq    mm0,[edx+eax]
+       movq    mm1,[edx+eax+8]
+       add     eax,16
+       packssdw        mm0,mm1 ;mm0 = ix[0]|ix[1]|ix[2]|ix[3]
+       pmaddwd mm0,mm5
+       movd    ebx,mm0
+       punpckhdq       mm0,mm0
+       paddd   mm2, [ecx+ebx*8]
+       movd    ebx,mm0
+       paddd   mm2, [ecx+ebx*8]
+       jnz     .choose3_lp1
+.choose3_exit
+;      xor     eax,eax
+       movd    ebx, mm2
+       punpckhdq       mm2,mm2
+       mov     ecx, ebx
+       and     ecx, 0xffff     ; ecx = sum2
+       shr     ebx, 16 ; ebx = sum1
+       movd    edx, mm2        ; edx = sum
+
+       cmp     edx, ebx
+       jle     .choose3_s1
+       mov     edx, ebx
+       inc     eax
+.choose3_s1:
+       emms
+       pop     ebx
+       cmp     edx, ecx
+       jle     .choose3_s2
+       mov     edx, ecx
+       mov     eax, 2
+.choose3_s2:
+       pop     ecx
+       add     eax, ecx
+       mov     ecx, [esp+16] ; *s
+       add     [ecx], edx
+       pop     ebp
+       ret
+
+table_MMX.L_case_2:
+       push    dword 2
+       lea     ecx,[PIC_EBP_REL(table23)]
+       pmov    mm5,[PIC_EBP_REL(mul_add23)]
+       jmp     from2
+table_MMX.L_case_3:
+       push    dword 5
+       lea     ecx,[PIC_EBP_REL(table56)]
+       pmov    mm5,[PIC_EBP_REL(mul_add56)]
+from2:
+       mov     eax,[esp+12]    ;eax = *begin
+;      mov     edx,[esp+16]    ;edx = *end
+       push    ebx
+       push    edi
+
+       sub     eax, edx
+       xor     edi, edi
+       test    eax, 8
+       jz      .choose2_lp1
+; odd length
+       movq    mm0,[edx+eax]   ;mm0 = ix[0] | ix[1]
+       pxor    mm2,mm2         ;mm2 = sum
+       packssdw        mm0,mm2
+
+       pmaddwd mm0,mm5
+       movd    ebx,mm0
+
+       mov     edi,  [ecx+ebx*4]
+
+       add     eax,8
+       jz      .choose2_exit
+
+       align   4
+.choose2_lp1
+       movq    mm0,[edx+eax]
+       movq    mm1,[edx+eax+8]
+       packssdw        mm0,mm1 ;mm0 = ix[0]|ix[1]|ix[2]|ix[3]
+       pmaddwd mm0,mm5
+       movd    ebx,mm0
+       punpckhdq       mm0,mm0
+       add     edi, [ecx+ebx*4]
+       movd    ebx, mm0
+       add     edi, [ecx+ebx*4]
+       add     eax,16
+       jnc     .choose2_lp1
+.choose2_exit
+       mov     ecx, edi
+       pop     edi
+       pop     ebx
+       pop     eax ; table num.
+       emms
+
+       mov     edx, ecx
+       and     ecx, 0xffff     ; ecx = sum2
+       shr     edx, 16 ; edx = sum1
+
+       cmp     edx, ecx
+       jle     .choose2_s1
+       mov     edx, ecx
+       inc     eax
+.choose2_s1:
+       mov     ecx, [esp+16] ; *s
+       add     [ecx], edx
+       pop     ebp
+       ret
+
+       end
diff --git a/lame/libmp3lame/i386/cpu_feat.nas b/lame/libmp3lame/i386/cpu_feat.nas
new file mode 100644 (file)
index 0000000..b5b09c1
--- /dev/null
@@ -0,0 +1,107 @@
+;
+;
+;      assembler routines to detect CPU-features
+;
+;      MMX / 3DNow! / SSE / SSE2
+;
+;      for the LAME project
+;      Frank Klemm, Robert Hegemann 2000-10-12
+;
+
+%include "nasm.h"
+
+       globaldef       has_MMX_nasm
+       globaldef       has_3DNow_nasm
+       globaldef       has_SSE_nasm
+       globaldef       has_SSE2_nasm
+
+        segment_code
+
+testCPUID:
+       pushfd                          
+       pop     eax
+       mov     ecx,eax
+       xor     eax,0x200000
+       push    eax
+       popfd
+       pushfd
+       pop     eax
+       cmp     eax,ecx
+       ret
+
+;---------------------------------------
+;      int  has_MMX_nasm (void)
+;---------------------------------------
+
+has_MMX_nasm:
+        pushad
+       call    testCPUID
+       jz      return0         ; no CPUID command, so no MMX
+
+       mov     eax,0x1
+       CPUID
+       test    edx,0x800000
+       jz      return0         ; no MMX support
+       jmp     return1         ; MMX support
+        
+;---------------------------------------
+;      int  has_SSE_nasm (void)
+;---------------------------------------
+
+has_SSE_nasm:
+        pushad
+       call    testCPUID
+       jz      return0         ; no CPUID command, so no SSE
+        
+       mov     eax,0x1
+       CPUID
+       test    edx,0x02000000
+       jz      return0         ; no SSE support
+       jmp     return1         ; SSE support
+        
+;---------------------------------------
+;      int  has_SSE2_nasm (void)
+;---------------------------------------
+
+has_SSE2_nasm:
+        pushad
+       call    testCPUID
+       jz      return0         ; no CPUID command, so no SSE2
+        
+       mov     eax,0x1
+       CPUID
+       test    edx,0x04000000
+       jz      return0         ; no SSE2 support
+       jmp     return1         ; SSE2 support
+        
+;---------------------------------------
+;      int  has_3DNow_nasm (void)
+;---------------------------------------
+
+has_3DNow_nasm:
+        pushad
+       call    testCPUID
+       jz      return0         ; no CPUID command, so no 3DNow!
+
+       mov     eax,0x80000000
+       CPUID
+       cmp     eax,0x80000000
+       jbe     return0         ; no extended MSR(1), so no 3DNow!
+
+       mov     eax,0x80000001
+       CPUID
+       test    edx,0x80000000
+       jz      return0         ; no 3DNow! support
+                               ; 3DNow! support
+return1:
+       popad
+       xor     eax,eax
+       inc     eax
+       ret
+
+return0:
+       popad
+       xor     eax,eax
+       ret
+        
+        end
diff --git a/lame/libmp3lame/i386/fft.nas b/lame/libmp3lame/i386/fft.nas
new file mode 100644 (file)
index 0000000..7928b33
--- /dev/null
@@ -0,0 +1,267 @@
+
+;      for new GOGO-no-coda (1999/09)
+;      Copyright (C) 1999 shigeo
+;      special thanks to Keiichi SAKAI, URURI
+%include "nasm.h"
+
+       globaldef fht_3DN
+       globaldef fht
+       externdef costab_fft
+       externdef sintab_fft
+       externdef gray_index
+
+       segment_data
+       align 16
+D_MSB1_0       dd      0         ,0x80000000
+D_SQRT2        dd      1.414213562,1.414213562
+t_s0   dd      0       ;[ t_c:t_s]
+t_c0   dd      0
+t_c1   dd      0       ;[-t_s:t_c]
+t_s1   dd      0
+D_s1c1 dd      0, 0
+D_Mc1s1        dd      0, 0
+D_s2c2 dd      0, 0
+D_Mc2s2        dd      0, 0
+D_0_1  dd      1.0, 0.0
+S_05   DD      0.5
+S_00005        DD      0.0005
+fht            dd      0       ;´Ø¿ô¥Ý¥¤¥ó¥¿
+
+       segment_code
+
+;************************************************************************
+
+;      by shigeo
+;      99/08/16
+;      23000clk ¿É¤«¤Ã¤¿¡Á
+;      18500clk bit reversal from gogo1 by URURI
+
+;void fht(float *fz, int n);
+       align 16
+fht_3DN:
+       push    ebx
+       push    esi
+       push    edi
+       push    ebp
+%assign _P 4*4
+       ;¤Þ¤ººÇ½é¤Î¥ë¡¼¥×... ¤Ïfht()¤Î³°¤Ø°ÜÆ°
+
+       mov     esi,[esp+_P+4]  ;esi=fz
+       mov     ecx,[esp+_P+8]  ;ecx=n
+
+       ;¥á¥¤¥ó¥ë¡¼¥×
+       movq    mm7,[D_MSB1_0]  ;mm7=[1<<31:0]
+
+%assign LOCAL_STACK    16
+       sub     esp,LOCAL_STACK
+%assign _P (_P+LOCAL_STACK)
+       xor     eax,eax
+       mov     [esp],eax       ;k=0
+%define k dword [esp]
+%define kx     dword [esp+4]
+%define fn dword [esp+8]
+
+.lp30: ;k=0; do{
+       mov     ecx,k
+       add     ecx,2
+       mov     k,ecx
+       mov     eax,1
+       shl     eax,cl          ;eax=k1 = 1<<k
+       lea     ebx,[eax+eax]   ;ebx=k2 = k1*2
+       lea     ecx,[eax+eax*2] ;ecx=k3 = k2 + k1 = k1*3
+       lea     edx,[ebx+ebx]   ;edx=k4 = k1*4
+       mov     esi,eax
+       shr     esi,1           ;esi=kx=k1>>1
+       mov     kx,esi          ;Êݸ(¸å¤Ç»È¤¦)
+       mov     edi,[esp+_P+4]  ;edi=fi=fz
+       lea     ebp,[edi+esi*4] ;ebp=gi=fz+kx
+       mov     esi,[esp+_P+8]  ;esi=n
+       lea     esi,[edi+esi*4] ;esi=fn=fz+n
+       movq    mm6,[D_SQRT2]   ;mm6=[¢å2:¢å2]
+
+.lp31: ;fn=fz+n; do{ FLOAT g0,f0,f1,...
+       movd    mm0,[edi]       ;mm0=[0:fi[ 0]]
+       movd    mm1,[edi+eax*4] ;mm1=[0:fi[k1]]
+       punpckldq       mm0,mm0 ;mm0=[fi_0 :fi_0 ]
+       punpckldq       mm1,mm1 ;mm1=[fi_k1:fi_k1]
+       movd    mm2,[edi+ebx*4]
+       movd    mm3,[edi+ecx*4]
+       punpckldq       mm2,mm2 ;mm2=[fi_k2:fi_k2]
+       punpckldq       mm3,mm3 ;mm3=[fi_k3:fi_k3]
+       pxor    mm1,mm7         ;mm1=[-fi_k1:fi_k1]
+       pxor    mm3,mm7         ;mm3=[-fi_k3:fi_k3]
+       pfadd   mm0,mm1         ;mm0=[f1:f0]=[fi_0 -fi_k1 : fi_0 +fi_k1]
+       pfadd   mm2,mm3         ;mm2=[f3:f2]=[fi_k2-fi_k3 : fi_k2+fi_k3]
+       movq    mm3,mm0         ;mm3=[f1:f0]
+       pfadd   mm0,mm2         ;mm0=[f1+f3:f0+f2]
+       movd    [edi],mm0       ;fi[0]=f0+f2
+       psrlq   mm0,32          ;mm0=[0:f1+f3]
+       pfsub   mm3,mm2         ;mm3=[f1-f3:f0-f2]
+       movd    [edi+eax*4],mm0 ;fi[k1]=f1+f3
+       movd    [edi+ebx*4],mm3 ;fi[k2]=f0-f2
+       psrlq   mm3,32          ;mm3=[0:f1-f3]
+       movd    [edi+ecx*4],mm3 ;fi[k3]=f1-f3
+
+       movd    mm0,[ebp]       ;mm0=[0:gi_0]
+       movd    mm1,[ebp+eax*4] ;mm1=[0:gi_k1]
+       punpckldq       mm0,mm0 ;mm0=[gi_0 :gi_0 ]
+       punpckldq       mm1,mm1 ;mm1=[gi_k1:gi_k1]
+       movd    mm2,[ebp+ebx*4] ;mm2=[0:gi_k2]
+       pxor    mm1,mm7         ;mm1=[-gi_k1:gi_k1]
+       punpckldq       mm2,[ebp+ecx*4] ;mm2=[gi_k3:gi_k2]
+       pfadd   mm0,mm1         ;mm0=[g1:g0]=[gi_0 -gi_k1:gi_0 +gi_k1]
+       pfmul   mm2,mm6         ;mm2=[g3:g2]=sqrt2 * [gi_k3:gi_k2]
+       movq    mm1,mm0         ;mm1=[g1:g0]
+       pfadd   mm0,mm2         ;mm0=[g1+g3:g0+g2]
+       movd    [ebp],mm0       ;gi[0]=g0+g2
+       psrlq   mm0,32          ;mm0=[0:g1+g3]
+       pfsub   mm1,mm2         ;mm1=[g1-g3:g0-g2]
+       movd    [ebp+eax*4],mm0 ;gi[k1]=g1+g3
+       movd    [ebp+ebx*4],mm1 ;gi[k2]=g0-g2
+       psrlq   mm1,32          ;mm1=[0:g1-g3]
+       movd    [ebp+ecx*4],mm1 ;gi[k3]=g1-g3
+       lea     edi,[edi+edx*4] ;fi += k4
+       lea     ebp,[ebp+edx*4] ;gi += k4
+       cmp     edi,esi
+       jc      near .lp31      ;}while(fi<fn);
+
+;      ¤³¤³¤Þ¤Ç¤Ï¿ʬO.K.
+
+       mov     fn,esi          ;fn=fz+n
+       ;¼¡¤ÎÃͤϰú¤­Â³¤­»È¤¦
+       ;eax=k1,ebx=k2,ecx=k3,edx=k4
+
+       mov     edi,k
+       lea     ebp,[costab_fft+edi*4]
+       mov     ebp,[ebp]       ;ebp=t_c
+       mov     [t_c0],ebp
+       mov     [t_c1],ebp      ;t_c
+       lea     ebp,[sintab_fft+edi*4]
+       mov     ebp,[ebp]       ;ebx=t_s
+       mov     [t_s0],ebp
+       xor     ebp,0x80000000
+       mov     [t_s1],ebp      ;-t_s
+
+       movq    mm1,[D_0_1]     ;mm1=[0:1]
+       movq    [D_s1c1],mm1    ;mm1=[s1:c1]
+       mov     esi,1           ;esi=i=1
+
+.lp32: ;       for(i=1;i<kx;i++){
+       movq    mm0,[D_s1c1]    ;mm1=[s1:t]=[s1:c1]
+       movq    mm2,mm0
+       pfmul   mm0,[t_c1]      ;mm0=[-s1*t_s: t*t_c]
+       pfmul   mm2,[t_s0]      ;mm2=[ s1*t_c: t*t_s]
+       pfacc   mm0,mm2         ;mm0=[s1:c1]=[ s1*t_c+t*t_s:-s1*t_s+t*t_c]
+       movq    mm2,mm0         ;mm2=[s1:c1]
+       movq    [D_s1c1],mm0    ;Êݸ
+       movq    mm6,mm2
+       punpckldq       mm5,mm6
+       punpckhdq       mm6,mm5 ;mm6=[ c1:s1]
+       pxor    mm6,mm7         ;mm6=[-c1:s1]
+       movq    [D_Mc1s1],mm6   ;Êݸ
+       pfmul   mm2,mm2         ;mm2=[s1*s1:c1*c1]
+       movq    mm3,mm0         ;mm3=[s1:c1]
+       pxor    mm2,mm7         ;mm2=[-s1*s1:c1*c1]
+       psrlq   mm3,32          ;mm3=[ 0:s1]
+       pfacc   mm2,mm2         ;mm2=[c2:c2]=[c1*c1-s1*s1:<]
+       pfmul   mm0,mm3         ;mm0=[ 0:c1*s1]
+       pfadd   mm0,mm0         ;mm0=[0:s2]=[ 0:2*c1*s1]
+       punpckldq       mm2,mm0 ;mm2=[s2:c2]
+       movq    [D_s2c2],mm2    ;Êݸ
+
+       punpckldq       mm0,mm2
+       punpckhdq       mm2,mm0 ;mm2=[c2:s2]
+       pxor    mm2,mm7         ;mm2=[-c2:s2]
+       movq    [D_Mc2s2],mm2   ;Êݸ
+
+       mov     edi,[esp+_P+4]  ;edi=fz
+       lea     edi,[edi+esi*4] ;edi=fz+i
+
+       mov     ebp,[esp+_P+4]  ;ebp=fz
+       neg     esi             ;esi=-i
+       lea     ebp,[ebp+eax*4] ;ebp=fz+k1
+       lea     ebp,[ebp+esi*4] ;ebp=gi=fz+k1-i
+       neg     esi             ;esi=i
+
+.lp33: ;       do{ FLOAT a,b,g0,f0,f1,g1,f2,g2,f3,g3;
+
+       movd    mm0,[edi+eax*4] ;mm0=[0:fi_k1]
+       punpckldq       mm0,[ebp+eax*4] ;mm0=[gi_k1:fi_k1]
+       movq    mm1,mm0
+       pfmul   mm0,[D_s2c2]    ;mm0=[ s2*gi_k1:c2*fi_k1]
+       pfmul   mm1,[D_Mc2s2]   ;mm1=[-c2*gi_k1:s2*fi_k1]
+       pfacc   mm0,mm1         ;mm0=[b:a]
+       movd    mm4,[edi]       ;mm4=[0:fi_0]
+       movq    mm3,mm0         ;mm3=[b:a]
+       punpckldq       mm4,[ebp]       ;mm4=[gi_0:fi_0]
+       pfadd   mm3,mm4         ;mm3=[g0:f0]=[gi_0+b:fi_0+a]
+       pfsub   mm4,mm0         ;mm4=[g1:f1]=[gi_0-b:fi_0-a]
+
+       movd    mm0,[edi+ecx*4] ;mm0=[0:fi_k3]
+       punpckldq       mm0,[ebp+ecx*4] ;mm0=[gi_k3:fi_k3]
+       movq    mm1,mm0
+       pfmul   mm0,[D_s2c2]    ;mm0=[ s2*gi_k3:c2*fi_k3]
+       pfmul   mm1,[D_Mc2s2]   ;mm1=[-c2*gi_k3:s2*fi_k3]
+       pfacc   mm0,mm1         ;mm0=[b:a]
+       movd    mm5,[edi+ebx*4] ;mm5=[0:fi_k2]
+       movq    mm6,mm0         ;mm6=[b:a]
+       punpckldq       mm5,[ebp+ebx*4] ;mm5=[gi_k2:fi_k2]
+       pfadd   mm6,mm5         ;mm6=[g2:f2]=[gi_k2+b:fi_k2+a]
+       pfsub   mm5,mm0         ;mm5=[g3:f3]=[gi_k2-b:fi_k2-a]
+
+       punpckldq       mm1,mm6 ;mm1=[f2:*]
+       movq    mm0,[D_s1c1]    ;mm0=[s1:c1]
+       punpckhdq       mm1,mm5 ;mm1=[g3:f2]
+       pfmul   mm0,mm1         ;mm0=[ s1*g3:c1*f2]
+       movq    mm2,[D_Mc1s1]   ;mm2=[-c1:s1]
+       pfmul   mm2,mm1         ;mm2=[-c1*g3:s1*f2]
+       pfacc   mm0,mm2         ;mm0=[b:a]
+
+       punpckldq       mm1,mm3 ;mm1=[f0:*]
+       punpckhdq       mm1,mm4 ;mm1=[g1:f0]
+       movq    mm2,mm0         ;mm2=[b:a]
+       pfadd   mm0,mm1         ;mm0=[g1+b:f0+a]
+       pfsubr  mm2,mm1         ;mm2=[g1-b:f0-a]
+       movd    [edi],mm0       ;fi[0]=f0+a
+       psrlq   mm0,32          ;mm0=[0:g1+b]
+       movd    [edi+ebx*4],mm2 ;fi[k2]=f0-a
+       psrlq   mm2,32          ;mm2=[0:g1-b]
+       movd    [ebp+eax*4],mm0 ;gi[k1]=g1+b
+       movd    [ebp+ecx*4],mm2 ;gi[k3]=g1-b
+       psrlq   mm6,32          ;mm6=[0:g2]
+       movq    mm0,[D_s1c1]    ;mm0=[s1:c1]
+       punpckldq       mm5,mm6 ;mm5=[g2:f3]
+       pfmul   mm0,mm5         ;mm0=[g2* s1:f3*c1]
+       pfmul   mm5,[D_Mc1s1]   ;mm5=[g2*-c1:f3*s1]
+       pfacc   mm0,mm5         ;mm0=[-b:a]
+       psrlq   mm3,32          ;mm3=[0:g0]
+       movq    mm1,mm0         ;mm1=[-b:a]
+       punpckldq       mm3,mm4 ;mm3=[f1:g0]
+       pfadd   mm0,mm3         ;mm0=[f1-b:g0+a]
+       pfsubr  mm1,mm3         ;mm1=[f1+b:g0-a]
+       movd    [ebp],mm0       ;gi[0]=g0+a
+       psrlq   mm0,32          ;mm0=[0:f1-b]
+       movd    [ebp+ebx*4],mm1 ;gi[k2]=g0-a
+       psrlq   mm1,32          ;mm1=[0:f1+b]
+       movd    [edi+ecx*4],mm0 ;fi[k3]=f1-b
+       movd    [edi+eax*4],mm1 ;fi[k1]=f1+b
+
+       lea     edi,[edi+edx*4] ;fi += k4
+       lea     ebp,[ebp+edx*4] ;gi += k4
+       cmp     edi,fn
+       jc      near .lp33      ;}while(fi<fn)
+       inc     esi
+       cmp     esi,kx
+       jnz     near .lp32      ;}
+       cmp     edx,[esp+_P+8]
+       jnz     near .lp30      ;}while(k4<n)
+
+
+.exit:
+       add     esp,LOCAL_STACK
+       femms
+       pop     ebp
+       pop     edi
+       pop     esi
+       pop     ebx
+       ret
diff --git a/lame/libmp3lame/i386/fft3dn.nas b/lame/libmp3lame/i386/fft3dn.nas
new file mode 100644 (file)
index 0000000..71db7db
--- /dev/null
@@ -0,0 +1,488 @@
+; from a new GOGO-no-coda (1999/09)
+;      Copyright (C) 1999 shigeo
+;      special thanks to Keiichi SAKAI, URURI
+; hacked and back-ported to LAME
+;       by Takehiro TOMINAGA Nov 2000
+
+%include "nasm.h"
+
+       globaldef fht_3DN
+
+       segment_data
+       align   16
+costab dd      0x80000000, 0
+       dd      1.414213562,1.414213562
+       dd      9.238795283293805e-01, 9.238795283293805e-01
+       dd      3.826834424611044e-01, 3.826834424611044e-01
+       dd      9.951847264044178e-01, 9.951847264044178e-01
+       dd      9.801714304836734e-02, 9.801714304836734e-02
+       dd      9.996988186794428e-01, 9.996988186794428e-01
+       dd      2.454122920569705e-02, 2.454122920569705e-02
+       dd      9.999811752815535e-01, 9.999811752815535e-01
+       dd      6.135884819898878e-03, 6.135884819898878e-03
+D_1_0_0_0      dd      0.0             , 1.0
+
+       segment_code
+
+PIC_OFFSETTABLE
+
+
+;void fht_3DN(float *fz, int nn);
+
+proc   fht_3DN
+
+       pushd   ebp, ebx, esi, edi
+
+       sub     esp, 20
+
+       call    get_pc.bp
+       add     ebp, PIC_BASE()
+
+       mov     r0, [esp+40]            ;fi
+       mov     r1, [esp+44]            ;r1 = nn
+       lea     r3, [PIC_EBP_REL(costab)]               ;tri = costab
+       lea     r4, [r0+r1*8]           ;r4 = fn = &fz[n]
+       mov     [esp+16], r4
+       mov     r4, 8                   ;kx = k1/2
+
+       pmov    mm7, [r3]
+
+       loopalign 16
+.do1
+       lea     r3, [r3+16]     ;tri += 2;
+       pmov    mm6, [PIC_EBP_REL(costab+8)]
+       lea     r2, [r4+r4*2]           ;k3*fsize/2
+       mov     r5, 4           ;i = 1*fsize
+
+       loopalign 16
+.do2:
+       lea     r1, [r0+r4]             ;gi = fi + kx
+       ;f
+       pmov    mm0, [r0]       ;fi0
+       pmov    mm1, [r0+r4*2]  ;fi1
+       pmov    mm2, [r0+r2*2]  ;fi3
+       pmov    mm3, [r0+r4*4]  ;fi2
+
+       pupldq  mm0, mm0        ;fi0 | fi0
+       pupldq  mm1, mm1        ;fi1 | fi1
+       pupldq  mm2, mm2        ;fi2 | fi2
+       pupldq  mm3, mm3        ;fi3 | fi3
+
+       pxor    mm1, mm7        ;fi1 | -fi1
+       pxor    mm3, mm7        ;fi3 | -fi3
+
+       pfsub   mm0, mm1        ;f1 | f0
+       pfsub   mm2, mm3        ;f3 | f2
+
+       pmov    mm4, mm0
+       pfadd   mm0, mm2        ;f1+f3|f0+f2 = fi1 | fi0
+       pfsub   mm4, mm2        ;f1-f3|f0-f2 = fi3 | fi2
+
+       pmovd   [r0], mm0       ;fi[0]
+       puphdq  mm0, mm0
+       pmovd   [r0+r4*4], mm4  ;fi[k2]
+       puphdq  mm4, mm4
+
+       pmovd   [r0+r4*2], mm4  ;fi[k1]
+       pmovd   [r0+r2*2], mm0  ;fi[k3]
+       lea     r0, [r0+r4*8]
+
+       ;g
+       pmov    mm0, [r1]       ;gi0
+       pmov    mm1, [r1+r4*2]  ;gi1
+       pmov    mm2, [r1+r4*4]  ;gi2
+       pmov    mm3, [r1+r2*2]  ;gi3
+
+       pupldq  mm1, mm1
+       pupldq  mm0, mm0        ;gi0 | gi0
+       pupldq  mm2, mm3        ;gi3 | gi2
+
+       pxor    mm1, mm7        ;gi1 | -gi1
+
+       pfsub   mm0, mm1        ;gi0-gi1|gi0+gi1 = g1 | g0
+       pfmul   mm2, mm6        ;gi3*SQRT2|gi2*SQRT2 = g3 | g2
+
+       pmov    mm4, mm0
+       pfadd   mm0, mm2        ;g1+g3|g0+g2 = gi1 | gi0
+       pfsub   mm4, mm2        ;g1-g3|g0-g2 = gi3 | gi2
+
+       pmovd   [r1], mm0       ;gi[0]
+       puphdq  mm0, mm0
+       pmovd   [r1+r4*4], mm4  ;gi[k2]
+       puphdq  mm4, mm4
+
+       cmp     r0, [esp + 16]
+       pmovd   [r1+r4*2], mm0  ;gi[k1]
+       pmovd   [r1+r2*2], mm4  ;gi[k3]
+
+       jb near .do2
+
+       pmov    mm6, [r3+r5]    ; this is not aligned address!!
+
+       loopalign 16
+.for:
+;
+; mm6 = c1 | s1
+; mm7 = 0x800000000 | 0
+;
+       pmov    mm1, mm6
+       mov     r0, [esp+40]    ; fz
+       puphdq  mm1, mm1        ; c1 | c1
+       lea     r1, [r0+r4*2]
+       pfadd   mm1, mm1        ; c1+c1 | c1+c1
+       pfmul   mm1, mm6        ; 2*c1*c1 | 2*c1*s1
+       pfsub   mm1, [PIC_EBP_REL(D_1_0_0_0)] ; 2*c1*c1-1.0 | 2*c1*s1 = -c2 | s2
+
+       pmov    mm0, mm1
+       pxor    mm7, mm6        ; c1 | -s1
+
+       pupldq  mm2, mm0
+       pupldq  mm3, mm6        ; ** | c1
+       puphdq  mm0, mm2        ; s2 | c2
+       puphdq  mm6, mm3        ;-s1 | c1
+
+       pxor    mm0, [PIC_EBP_REL(costab)]      ; c2 | -s2
+
+; mm0 =  s2| c2
+; mm1 = -c2| s2
+; mm6 =  c1| s1
+; mm7 =  s1|-c1 (we use the opposite sign. from GOGO here)
+
+       pmov    [esp], mm0
+       pmov    [esp+8], mm1
+
+       sub     r1, r5          ;r1 = gi
+       add     r0, r5          ;r0 = fi
+
+       loopalign 16
+.do3:
+       pmov    mm2, [r0+r4*2] ; fi[k1]
+       pmov    mm4, [r1+r4*2] ; gi[k1]
+       pmov    mm3, [r0+r2*2] ; fi[k3]
+       pmov    mm5, [r1+r2*2] ; gi[k3]
+
+       pupldq  mm2, mm2        ; fi1 | fi1
+       pupldq  mm4, mm4        ; gi1 | gi1
+       pupldq  mm3, mm3        ; fi3 | fi3
+       pupldq  mm5, mm5        ; gi3 | gi3
+
+       pfmul   mm2, mm0        ; s2 * fi1 | c2 * fi1
+       pfmul   mm4, mm1        ;-c2 * gi1 | s2 * gi1
+       pfmul   mm3, mm0        ; s2 * fi3 | c2 * fi3
+       pfmul   mm5, mm1        ;-c2 * gi3 | s2 * gi3
+
+       pfadd   mm2, mm4                ;b | a
+       pfadd   mm3, mm5                ;d | c
+
+       pmov    mm0, [r0]
+       pmov    mm4, [r1]
+       pmov    mm1, [r0+r4*4]
+       pmov    mm5, [r1+r4*4]
+
+       pupldq  mm0, mm4                ;gi0 | fi0
+       pupldq  mm1, mm5                ;gi2 | fi2
+
+       pmov    mm4, mm2
+       pmov    mm5, mm3
+
+       pfadd   mm2, mm0                ;g0 | f0
+       pfadd   mm3, mm1                ;g2 | f2
+
+       pfsub   mm0, mm4                ;g1 | f1
+       pfsub   mm1, mm5                ;g3 | f3
+
+       pmov    mm4, mm3
+       pmov    mm5, mm1
+
+       pupldq  mm4, mm4                ;f2 | f2
+       puphdq  mm5, mm5                ;g3 | g3
+       puphdq  mm3, mm3                ;g2 | g2
+       pupldq  mm1, mm1                ;f3 | f3
+
+       pfmul   mm4, mm6                ;f2 * c1 | f2 * s1
+       pfmul   mm5, mm7                ;g3 * s1 | g3 *-c1
+       pfmul   mm3, mm6                ;g2 * c1 | g2 * s1
+       pfmul   mm1, mm7                ;f3 * s1 | f3 *-c1
+
+       pfadd   mm4, mm5                ;a | b
+       pfsub   mm3, mm1                ;d | c
+
+       pmov    mm5, mm2
+       pmov    mm1, mm0
+
+       pupldq  mm2, mm2                ;f0 | f0
+       pupldq  mm0, mm0                ;f1 | f1
+
+       puphdq  mm1, mm2                ;f0 | g1
+       puphdq  mm5, mm0                ;f1 | g0
+
+       pmov    mm2, mm4
+       pmov    mm0, mm3
+
+       pfadd   mm4, mm1                ;fi0 | gi1
+       pfadd   mm3, mm5                ;fi1 | gi0
+       pfsub   mm1, mm2                ;fi2 | gi3
+       pfsub   mm5, mm0                ;fi3 | gi2
+
+       pmovd   [r1+r4*2], mm4  ;gi[k1]
+       puphdq  mm4, mm4
+       pmovd   [r1], mm3               ;gi[0]
+       puphdq  mm3, mm3
+       pmovd   [r1+r2*2], mm1  ;gi[k3]
+       puphdq  mm1, mm1
+       pmovd   [r1+r4*4], mm5  ;gi[k2]
+       puphdq  mm5, mm5
+
+       pmovd   [r0], mm4       ;fi[0]
+       pmovd   [r0+r4*2], mm3  ;fi[k1]
+       pmovd   [r0+r4*4], mm1  ;fi[k2]
+       pmovd   [r0+r2*2], mm5  ;fi[k3]
+
+       lea     r0, [r0+r4*8]
+       lea     r1, [r1+r4*8]
+       cmp     r0, [esp + 16]
+       pmov    mm0, [esp]
+       pmov    mm1, [esp+8]
+
+       jb near .do3
+
+       add     r5, 4
+; mm6 =  c1| s1
+; mm7 =  s1|-c1 (we use the opposite sign. from GOGO here)
+       pfmul   mm6, [r3]       ; c1*a | s1*a
+       pfmul   mm7, [r3+8]     ; s1*b |-c1*b
+       cmp     r5, r4
+
+       pfsub   mm6, mm7        ; c1*a-s1*b | s1*a+c1*b
+       pupldq  mm7,mm6
+       puphdq  mm6,mm7
+       pmov    mm7, [PIC_EBP_REL(costab)]
+       jb near .for
+
+       mov     r0, [esp+40]    ;fi
+       cmp     r4, [esp+40+4]
+       lea     r4, [r4*4]      ;kx *= 4
+
+       jb near .do1
+.exitttt
+       femms
+       add     esp,20
+       popd    ebp, ebx, esi, edi
+endproc
+
+
+;void fht_E3DN(float *fz, int nn);
+
+proc   fht_E3DN
+
+       pushd   ebp, ebx, esi, edi
+
+       sub     esp, 20
+
+       call    get_pc.bp
+       add     ebp, PIC_BASE()
+
+       mov     r0, [esp+40]            ;fi
+       mov     r1, [esp+44]            ;r1 = nn
+       lea     r3, [PIC_EBP_REL(costab)]               ;tri = costab
+       lea     r4, [r0+r1*8]           ;r4 = fn = &fz[n]
+       mov     [esp+16], r4
+       mov     r4, 8                   ;kx = k1/2
+
+       pmov    mm7, [r3]
+
+       loopalign 16
+.do1
+       lea     r3, [r3+16]     ;tri += 2;
+       pmov    mm6, [PIC_EBP_REL(costab+8)]
+       lea     r2, [r4+r4*2]           ;k3*fsize/2
+       mov     r5, 4           ;i = 1*fsize
+
+       loopalign 16
+.do2:
+       lea     r1, [r0+r4]             ;gi = fi + kx
+;f
+       pmov    mm0, [r0]       ; X  | fi0
+       pmov    mm1, [r0+r4*4]  ; X  | fi2
+       pupldq  mm0, [r0+r4*2]  ;fi1 | fi0
+       pupldq  mm1, [r0+r2*2]  ;fi3 | fi2
+       pfpnacc mm0, mm0        ;fi0+fi1 | fi0-fi1 = f0|f1
+       pfpnacc mm1, mm1        ;fi2+fi3 | fi2-fi3 = f2|f3
+
+       pmov    mm2, mm0
+       pfadd   mm0, mm1        ;f0+f2|f1+f3 = fi0 | fi1
+       pfsub   mm2, mm1        ;f0-f2|f1-f3 = fi2 | fi3
+
+       pmovd   [r0+r4*2], mm0  ;fi[k1]
+       pmovd   [r0+r2*2], mm2  ;fi[k3]
+
+       puphdq  mm0, mm0
+       puphdq  mm2, mm2
+       pmovd   [r0], mm0       ;fi[0]
+       pmovd   [r0+r4*4], mm2  ;fi[k2]
+
+       lea     r0, [r0+r4*8]
+;g
+       pmov    mm3, [r1]       ;    gi0
+       pmov    mm4, [r1+r2*2]  ;    gi3
+       pupldq  mm3, [r1+r4*2]  ;gi1|gi0
+       pupldq  mm4, [r1+r4*4]  ;gi2|gi3
+
+       pfpnacc mm3, mm3        ;gi0+gi1  |gi0-gi1   = f0|f1
+       pfmul   mm4, mm6        ;gi2*SQRT2|gi3*SQRT2 = f2|f3
+
+       pmov    mm5, mm3
+       pfadd   mm3, mm4        ;f0+f2|f1+f3
+       pfsub   mm5, mm4        ;f0-f2|f1-f3
+
+       cmp     r0, [esp + 16]
+       pmovd   [r1+r4*2], mm3  ;gi[k1]
+       pmovd   [r1+r2*2], mm5  ;gi[k3]
+       puphdq  mm3, mm3
+       puphdq  mm5, mm5
+       pmovd   [r1], mm3       ;gi[0]
+       pmovd   [r1+r4*4], mm5  ;gi[k2]
+
+       jb near .do2
+
+       pmov    mm6, [r3+r5]    ; this is not aligned address!!
+
+       loopalign 16
+.for:
+;
+; mm6 = c1 | s1
+; mm7 = 0x800000000 | 0
+;
+       pmov    mm5, mm6
+       mov     r0, [esp+40]    ; fz
+       puphdq  mm5, mm5        ; c1 | c1
+       lea     r1, [r0+r4*2]
+       pfadd   mm5, mm5        ; c1+c1 | c1+c1
+       pfmul   mm5, mm6        ; 2*c1*c1 | 2*c1*s1
+       pfsub   mm5, [PIC_EBP_REL(D_1_0_0_0)] ; 2*c1*c1-1.0 | 2*c1*s1 = -c2 | s2
+
+       pswapd  mm4, mm5        ; s2 |-c2
+       pxor    mm4, mm7        ; s2 | c2
+       pxor    mm7, mm6        ; c1 |-s1
+       pswapd  mm6, mm6        ; s1 | c1
+
+; mm4 =  s2| c2
+; mm5 = -c2| s2
+; mm6 =  c1| s1
+; mm7 =  s1|-c1 (we use the opposite sign. from GOGO here)
+
+       pmov    [esp], mm4
+       pmov    [esp+8], mm5
+
+       sub     r1, r5          ;r1 = gi
+       add     r0, r5          ;r0 = fi
+
+       loopalign 16
+.do3:
+       pmov    mm0, [r0+r2*2] ; fi[k1]
+       pmov    mm2, [r1+r2*2] ; gi[k1]
+       pmov    mm1, [r0+r4*2] ; fi[k3]
+       pmov    mm3, [r1+r4*2] ; gi[k3]
+
+       pupldq  mm0, mm0
+       pupldq  mm2, mm2
+       pupldq  mm1, mm1
+       pupldq  mm3, mm3
+
+       pfmul   mm0, mm4
+       pfmul   mm2, mm5
+       pfmul   mm1, mm4
+       pfmul   mm3, mm5
+
+       pfadd   mm0, mm2                ;d | c
+       pfadd   mm1, mm3                ;b | a
+
+       pmov    mm2, [r0+r4*4]          ;fi2
+       pupldq  mm3, [r1+r4*4]          ;gi2 | -
+       pmov    mm4, [r0]               ;fi0
+       pupldq  mm5, [r1]               ;gi0 | -
+
+       pupldq  mm2, mm0                ;c | fi2
+       puphdq  mm3, mm0                ;d | gi2
+       pupldq  mm4, mm1                ;a | fi0
+       puphdq  mm5, mm1                ;b | gi0
+
+       pfpnacc mm2, mm2                ;f2 | f3
+       pfpnacc mm3, mm3                ;g2 | g3
+       pfpnacc mm4, mm4                ;f0 | f1
+       pfpnacc mm5, mm5                ;g0 | g1
+
+       pmov    mm0, mm2
+       pmov    mm1, mm3
+       pupldq  mm2, mm2                ;f3 | f3
+       pupldq  mm3, mm3                ;g3 | g3
+       puphdq  mm0, mm0                ;f2 | f2
+       puphdq  mm1, mm1                ;g2 | g2
+
+       pswapd  mm4, mm4                ;f1 | f0
+       pswapd  mm5, mm5                ;g1 | g0
+
+       pfmul   mm0, mm7                ;f2 * s1 | f2 *-c1
+       pfmul   mm3, mm6                ;g3 * c1 | g3 * s1
+       pfmul   mm1, mm6                ;g2 * c1 | g2 * s1
+       pfmul   mm2, mm7                ;f3 * s1 | f3 *-c1
+
+       pfsub   mm0, mm3                ; b |-a
+       pfsub   mm1, mm2                ; d | c
+
+       pmov    mm2, mm5
+       pmov    mm3, mm4
+       pupldq  mm4, mm0                ;-a | f0
+       pupldq  mm5, mm1                ; c | g0
+       puphdq  mm2, mm0                ; b | g1
+       puphdq  mm3, mm1                ; d | f1
+
+       pfpnacc mm4, mm4                ;fi2 | fi0
+       pfpnacc mm5, mm5                ;gi0 | gi2
+       pfpnacc mm2, mm2                ;gi1 | gi3
+       pfpnacc mm3, mm3                ;fi1 | fi3
+
+       pmovd   [r0], mm4               ;fi[0]
+       pmovd   [r1+r4*4], mm5          ;gi[k2]
+       pmovd   [r1+r2*2], mm2          ;gi[k3]
+       pmovd   [r0+r2*2], mm3          ;fi[k3]
+
+       puphdq  mm4, mm4
+       puphdq  mm5, mm5
+       puphdq  mm2, mm2
+       puphdq  mm3, mm3
+       pmovd   [r0+r4*4], mm4          ;fi[k2]
+       pmovd   [r1], mm5               ;gi[0]
+       pmovd   [r1+r4*2], mm2          ;gi[k1]
+       pmovd   [r0+r4*2], mm3          ;fi[k1]
+
+       lea     r0, [r0+r4*8]
+       lea     r1, [r1+r4*8]
+       cmp     r0, [esp + 16]
+       pmov    mm4, [esp]
+       pmov    mm5, [esp+8]
+
+       jb near .do3
+
+       add     r5, 4
+; mm6 =  c1| s1
+; mm7 =  s1|-c1 (we use the opposite sign. from GOGO here)
+       pfmul   mm6, [r3]       ; c1*a | s1*a
+       pfmul   mm7, [r3+8]     ; s1*b |-c1*b
+       cmp     r5, r4
+
+       pfsub   mm6, mm7        ; c1*a-s1*b | s1*a+c1*b
+       pswapd  mm6, mm6 ; ???  ; s1*a+c1*b | c1*a-s1*b
+       pmov    mm7, [PIC_EBP_REL(costab)]
+       jb near .for
+
+       mov     r0, [esp+40]    ;fi
+       cmp     r4, [esp+40+4]
+       lea     r4, [r4*4]      ;kx *= 4
+
+       jb near .do1
+.exitttt
+       femms
+       add     esp,20
+       popd    ebp, ebx, esi, edi
+endproc
diff --git a/lame/libmp3lame/i386/fftfpu.nas b/lame/libmp3lame/i386/fftfpu.nas
new file mode 100644 (file)
index 0000000..2ae89bd
--- /dev/null
@@ -0,0 +1,619 @@
+; back port from GOGO-no coda 2.24b by Takehiro TOMINAGA
+
+; GOGO-no-coda
+;      Copyright (C) 1999 shigeo
+;      special thanks to URURI
+
+%include "nasm.h"
+
+       externdef costab_fft
+       externdef sintab_fft
+
+       segment_data
+       align 32
+D_1_41421      dd      1.41421356
+D_1_0  dd      1.0
+D_0_5  dd      0.5
+D_0_25 dd      0.25
+D_0_0005       dd      0.0005
+D_0_0  dd      0.0
+
+       segment_code
+
+;void fht(float *fz, int n);
+proc   fht_FPU
+
+%$fz   arg     4
+%$n    arg     4
+
+%$k    local   4
+
+%$f0   local   4
+%$f1   local   4
+%$f2   local   4
+%$f3   local   4
+
+%$g0   local   4
+%$g1   local   4
+%$g2   local   4
+%$g3   local   4
+
+%$s1   local   4
+%$c1   local   4
+%$s2   local   4
+%$c2   local   4
+
+%$t_s  local   4
+%$t_c  local   4
+       alloc
+
+       pushd   ebp, ebx, esi, edi
+
+fht_FPU_1st_part:
+
+fht_FPU_2nd_part:
+
+fht_FPU_3rd_part:
+
+.do_init:
+       mov     r3, 16          ;k1*fsize = 4*fsize = k4
+       mov     r4, 8           ;kx = k1/2
+       mov     r2, 48          ;k3*fsize
+       mov     dword [sp(%$k)], 2      ;k = 2
+       mov     r0, [sp(%$fz)]  ;fi
+       lea     r1, [r0+8]              ;gi = fi + kx
+
+.do:
+.do2:
+       ;f
+       fld     dword [r0]
+       fsub    dword [r0+r3]
+
+       fld     dword [r0]
+       fadd    dword [r0+r3]
+
+       fld     dword [r0+r3*2]
+       fsub    dword [r0+r2]
+
+       fld     dword [r0+r3*2]
+       fadd    dword [r0+r2]           ;f2 f3 f0 f1
+
+       fld     st2                     ;f0 f2 f3 f0 f1
+       fadd    st0, st1
+       fstp    dword [r0]              ;fi[0]
+
+       fld     st3                     ;f1 f2 f3 f0 f1
+       fadd    st0, st2
+       fstp    dword [r0+r3]           ;fi[k1]
+
+       fsubr   st0, st2                ;f0-f2 f3 f0 f1
+       fstp    dword [r0+r3*2]         ;fi[k2]
+
+       fsubr   st0, st2                ;f1-f3 f0 f1
+       fstp    dword [r0+r2]           ;fi[k3]
+       fcompp
+
+       ;g
+       fld     dword [r1]
+       fsub    dword [r1+r3]
+
+       fld     dword [r1]
+       fadd    dword [r1+r3]
+
+       fld     dword [D_1_41421]
+       fmul    dword [r1+r2]
+
+       fld     dword [D_1_41421]
+       fmul    dword [r1+r3*2]         ;g2 g3 g0 g1
+
+       fld     st2                     ;g0 g2 g3 g0 g1
+       fadd    st0, st1
+       fstp    dword [r1]              ;gi[0]
+
+       fld     st3                     ;g1 g2 g3 g0 g1
+       fadd    st0, st2
+       fstp    dword [r1+r3]           ;gi[k1]
+
+       fsubr   st0, st2                ;g0-g2 g3 g0 g1
+       fstp    dword [r1+r3*2]         ;gi[k2]
+
+       fsubr   st0, st2                ;g1-g3 g0 g1
+       fstp    dword [r1+r2]           ;gi[k3]
+       fcompp
+
+       lea     r0, [r0+r3*4]
+       lea     r1, [r1+r3*4]
+       cmp     r0, r6
+       jb      .do2
+
+
+       mov     r0, [sp(%$k)]
+       fld     dword [costab_fft +r0*4]
+       fstp    dword [sp(%$t_c)]
+       fld     dword [sintab_fft +r0*4]
+       fstp    dword [sp(%$t_s)]
+       fld     dword [D_1_0]
+       fstp    dword [sp(%$c1)]
+       fld     dword [D_0_0]
+       fstp    dword [sp(%$s1)]
+
+.for_init:
+       mov     r5, 4           ;i = 1*fsize
+
+.for:
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$t_c)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$t_s)]
+       fsubp   st1, st0                ;c1
+
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$t_s)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$t_c)]
+       faddp   st1, st0                ;s1 c1
+       
+       fld     st1
+       fmul    st0, st0                ;c1c1 s1 c1
+       fld     st1
+       fmul    st0, st0                ;s1s1 c1c1 s1 c1
+       fsubp   st1, st0                ;c2 s1 c1
+       fstp    dword [sp(%$c2)]        ;s1 c1
+
+       fld     st1                     ;c1 s1 c1
+       fmul    st0, st1                ;c1s1 s1 c1
+       fadd    st0, st0                ;s2 s1 c1
+       fstp    dword [sp(%$s2)]        ;s1 c1
+
+       fstp    dword [sp(%$s1)]        ;c1
+       fstp    dword [sp(%$c1)]        ;
+       
+       mov     r0, [sp(%$fz)]
+       add     r0, r5          ;r0 = fi
+       mov     r1, [sp(%$fz)]
+       add     r1, r3
+       sub     r1, r5          ;r1 = gi
+
+.do3:
+       fld     dword [sp(%$s2)]
+       fmul    dword [r0+r3]
+       fld     dword [sp(%$c2)]
+       fmul    dword [r1+r3]
+       fsubp   st1, st0                ;b = s2*fi[k1] - c2*gi[k1]
+
+       fld     dword [sp(%$c2)]
+       fmul    dword [r0+r3]
+       fld     dword [sp(%$s2)]
+       fmul    dword [r1+r3]
+       faddp   st1, st0                ;a = c2*fi[k1] + s2*gi[k1]  b
+
+       fld     dword [r0]
+       fsub    st0, st1                ;f1 a b
+       fstp    dword [sp(%$f1)]        ;a b
+
+       fadd    dword [r0]              ;f0 b
+       fstp    dword [sp(%$f0)]        ;b
+
+       fld     dword [r1]
+       fsub    st0, st1                ;g1 b
+       fstp    dword [sp(%$g1)]        ;b
+
+       fadd    dword [r1]              ;g0
+       fstp    dword [sp(%$g0)]        ;
+
+
+       fld     dword [sp(%$s2)]
+       fmul    dword [r0+r2]
+       fld     dword [sp(%$c2)]
+       fmul    dword [r1+r2]
+       fsubp   st1, st0                ;b = s2*fi[k3] - c2*gi[k3]
+
+       fld     dword [sp(%$c2)]
+       fmul    dword [r0+r2]
+       fld     dword [sp(%$s2)]
+       fmul    dword [r1+r2]
+       faddp   st1, st0                ;a = c2*fi[k3] + s2*gi[k3]  b
+
+       fld     dword [r0+r3*2]
+       fsub    st0, st1                ;f3 a b
+       fstp    dword [sp(%$f3)]        ;a b
+
+       fadd    dword [r0+r3*2] ;f2 b
+       fstp    dword [sp(%$f2)]        ;b
+
+       fld     dword [r1+r3*2]
+       fsub    st0, st1                ;g3 b
+       fstp    dword [sp(%$g3)]        ;b
+
+       fadd    dword [r1+r3*2] ;g2
+       fstp    dword [sp(%$g2)]        ;
+
+
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$f2)]
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$g3)]
+       fsubp   st1, st0                ;b = s1*f2 - c1*g3
+       
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$f2)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$g3)]
+       faddp   st1, st0                ;a = c1*f2 + s1*g3  b
+
+       fld     dword [sp(%$f0)]
+       fsub    st0, st1                ;fi[k2] a b
+       fstp    dword [r0+r3*2]
+
+       fadd    dword [sp(%$f0)]        ;fi[0] b
+       fstp    dword [r0]
+
+       fld     dword [sp(%$g1)]
+       fsub    st0, st1                ;gi[k3] b
+       fstp    dword [r1+r2]
+
+       fadd    dword [sp(%$g1)]        ;gi[k1]
+       fstp    dword [r1+r3]
+
+
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$g2)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$f3)]
+       fsubp   st1, st0                ;b = c1*g2 - s1*f3
+       
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$g2)]
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$f3)]
+       faddp   st1, st0                ;a = s1*g2 + c1*f3  b
+
+       fld     dword [sp(%$g0)]
+       fsub    st0, st1                ;gi[k2] a b
+       fstp    dword [r1+r3*2]
+
+       fadd    dword [sp(%$g0)]        ;gi[0] b
+       fstp    dword [r1]
+
+       fld     dword [sp(%$f1)]
+       fsub    st0, st1                ;fi[k3] b
+       fstp    dword [r0+r2]
+
+       fadd    dword [sp(%$f1)]        ;fi[k1]
+       fstp    dword [r0+r3]
+
+
+       lea     r0, [r0+r3*4]
+       lea     r1, [r1+r3*4]
+       cmp     r0, r6
+       jb near .do3
+
+       add     r5, 4
+       cmp     r5, r4
+       jb near .for
+
+       cmp     r3, [sp(%$n)]
+       jae     .exit
+
+       add     dword [sp(%$k)], 2      ;k  += 2;
+       lea     r3, [r3*4]              ;k1 *= 4
+       lea     r2, [r2*4]              ;k3 *= 4
+       lea     r4, [r4*4]              ;kx *= 4
+       mov     r0, [sp(%$fz)]  ;fi
+       lea     r1, [r0+r4]             ;gi = fi + kx
+       jmp     .do
+
+.exit:
+       popd    ebp, ebx, esi, edi
+endproc
+
+;*************************************************************
+
+;void fht_FPU_FXCH(float *fz, int n);
+proc   fht_FPU_FXCH
+
+%$fz   arg     4
+%$n    arg     4
+
+%$k    local   4
+
+%$f0   local   4
+%$f1   local   4
+%$f2   local   4
+%$f3   local   4
+
+%$g0   local   4
+%$g1   local   4
+%$g2   local   4
+%$g3   local   4
+
+%$s1   local   4
+%$c1   local   4
+%$s2   local   4
+%$c2   local   4
+
+%$t_s  local   4
+%$t_c  local   4
+       alloc
+
+       pushd   ebp, ebx, esi, edi
+
+fht_FPU_FXCH_1st_part:
+
+fht_FPU_FXCH_2nd_part:
+
+fht_FPU_FXCH_3rd_part:
+
+.do_init:
+       mov     r3, 16          ;k1*fsize = 4*fsize = k4
+       mov     r4, 8           ;kx = k1/2
+       mov     r2, 48          ;k3*fsize
+       mov     dword [sp(%$k)], 2      ;k = 2
+       mov     r0, [sp(%$fz)]  ;fi
+       lea     r1, [r0+8]              ;gi = fi + kx
+
+.do:
+.do2:
+       ;f
+       fld     dword [r0]
+       fsub    dword [r0+r3]
+       fld     dword [r0]
+       fadd    dword [r0+r3]
+
+       fld     dword [r0+r3*2]
+       fsub    dword [r0+r2]
+       fld     dword [r0+r3*2]
+       fadd    dword [r0+r2]           ;f2 f3 f0 f1
+
+       fld     st3
+       fld     st3
+       fxch    st5
+       fadd    st0, st3
+       fxch    st4
+       fadd    st0, st2
+       fxch    st3
+       fsubp   st1, st0
+       fxch    st1
+       fsubp   st4, st0
+       fxch    st2
+
+       fstp    dword [r0+r3]           ;fi[k1]
+       fstp    dword [r0]              ;fi[0]
+       fstp    dword [r0+r2]           ;fi[k3]
+       fstp    dword [r0+r3*2]         ;fi[k2]
+
+       ;g
+       fld     dword [r1]
+       fsub    dword [r1+r3]
+       fld     dword [r1]
+       fadd    dword [r1+r3]
+
+       fld     dword [D_1_41421]
+       fmul    dword [r1+r2]
+       fld     dword [D_1_41421]
+       fmul    dword [r1+r3*2]         ;g2 g3 g0 g1
+
+       fld     st3
+       fld     st3
+       fxch    st5
+       fadd    st0, st3
+       fxch    st4
+       fadd    st0, st2
+       fxch    st3
+       fsubp   st1, st0
+       fxch    st1
+       fsubp   st4, st0
+       fxch    st2
+
+       fstp    dword [r1+r3]           ;gi[k1]
+       fstp    dword [r1]              ;gi[0]
+       fstp    dword [r1+r2]           ;gi[k3]
+       fstp    dword [r1+r3*2]         ;gi[k2]
+
+       lea     r0, [r0+r3*4]
+       lea     r1, [r1+r3*4]
+       cmp     r0, r6
+       jb      .do2
+
+
+       mov     r0, [sp(%$k)]
+       fld     dword [costab_fft +r0*4]
+       fld     dword [sintab_fft +r0*4]
+       fld     dword [D_1_0]
+       fld     dword [D_0_0]
+       fxch    st3
+       fstp    dword [sp(%$t_c)]
+       fxch    st1
+       fstp    dword [sp(%$t_s)]
+       fstp    dword [sp(%$c1)]
+       fstp    dword [sp(%$s1)]
+
+.for_init:
+       mov     r5, 4           ;i = 1*fsize
+
+.for:
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$t_c)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$t_s)]
+
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$t_s)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$t_c)]
+       fxch    st2
+       fsubp   st3, st0                ;c1
+       faddp   st1, st0                ;s1 c1
+       
+       fld     st1
+       fxch    st2
+       fmul    st0, st0                ;c1c1 s1 c1
+       fld     st1
+       fxch    st2
+       fmul    st0, st0                ;s1s1 c1c1 s1 c1
+
+       fxch    st3
+       fst     dword [sp(%$c1)]        ;c1
+       fxch    st2
+       fst     dword [sp(%$s1)]        ;s1 c1c1 c1 s1s1
+
+       fmulp   st2, st0
+       fsubrp  st2, st0
+       fadd    st0, st0                ;s2 c2
+       fxch    st1
+       fstp    dword [sp(%$c2)]
+       fstp    dword [sp(%$s2)]
+
+       mov     r0, [sp(%$fz)]
+       mov     r1, [sp(%$fz)]
+       add     r0, r5          ;r0 = fi
+       add     r1, r3
+       sub     r1, r5          ;r1 = gi
+
+.do3:
+       fld     dword [sp(%$s2)]
+       fmul    dword [r0+r3]
+       fld     dword [sp(%$c2)]
+       fmul    dword [r1+r3]
+
+       fld     dword [sp(%$c2)]
+       fmul    dword [r0+r3]
+       fld     dword [sp(%$s2)]
+       fmul    dword [r1+r3]
+       fxch    st2
+       fsubp   st3, st0                ;b = s2*fi[k1] - c2*gi[k1]
+       faddp   st1, st0                ;a = c2*fi[k1] + s2*gi[k1]  b
+
+       fld     dword [r1]
+       fsub    st0, st2                ;g1 a b
+       fxch    st2
+       fadd    dword [r1]              ;g0 a g1
+
+       fld     dword [r0]
+       fsub    st0, st2                ;f1 g0 a g1
+       fxch    st2
+       fadd    dword [r0]              ;f0 g0 f1 g1
+
+       fxch    st3
+       fstp    dword [sp(%$g1)]
+       fstp    dword [sp(%$g0)]
+       fstp    dword [sp(%$f1)]
+       fstp    dword [sp(%$f0)]
+
+
+       fld     dword [sp(%$s2)]
+       fmul    dword [r0+r2]
+       fld     dword [sp(%$c2)]
+       fmul    dword [r1+r2]
+
+       fld     dword [sp(%$c2)]
+       fmul    dword [r0+r2]
+       fld     dword [sp(%$s2)]
+       fmul    dword [r1+r2]
+       fxch    st2
+       fsubp   st3, st0                ;b = s2*fi[k3] - c2*gi[k3]
+       faddp   st1, st0                ;a = c2*fi[k3] + s2*gi[k3]  b
+
+
+       fld     dword [r1+r3*2]
+       fsub    st0, st2                ;g3 a b
+       fxch    st2
+       fadd    dword [r1+r3*2] ;g2 a g3
+
+       fld     dword [r0+r3*2]
+       fsub    st0, st2                ;f3 g2 a g3
+       fxch    st2
+       fadd    dword [r0+r3*2] ;f2 g2 f3 g3
+
+       fxch    st3
+       fstp    dword [sp(%$g3)]
+       fstp    dword [sp(%$g2)]
+       fstp    dword [sp(%$f3)]
+       fstp    dword [sp(%$f2)]
+
+
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$f2)]
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$g3)]
+       
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$f2)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$g3)]
+       fxch    st2
+       fsubp   st3, st0                ;b = s1*f2 - c1*g3
+       faddp   st1, st0                ;a = c1*f2 + s1*g3  b
+
+       fld     dword [sp(%$g1)]
+       fsub    st0, st2                ;gi[k3] a b
+       fxch    st2
+       fadd    dword [sp(%$g1)]        ;gi[k1] a gi[k3]
+
+       fld     dword [sp(%$f0)]
+       fsub    st0, st2                ;fi[k2] gi[k1] a gi[k3]
+       fxch    st2
+       fadd    dword [sp(%$f0)]        ;fi[0] gi[k1] fi[k2] gi[k3]
+
+       fxch    st3
+       fstp    dword [r1+r2]
+       fstp    dword [r1+r3]
+       fstp    dword [r0+r3*2]
+       fstp    dword [r0]
+
+
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$g2)]
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$f3)]
+       
+       fld     dword [sp(%$s1)]
+       fmul    dword [sp(%$g2)]
+       fld     dword [sp(%$c1)]
+       fmul    dword [sp(%$f3)]
+       fxch    st2
+       fsubp   st3, st0                ;b = c1*g2 - s1*f3
+       faddp   st1, st0                ;a = s1*g2 + c1*f3  b
+
+       fld     dword [sp(%$f1)]
+       fsub    st0, st2                ;fi[k3] a b
+       fxch    st2
+       fadd    dword [sp(%$f1)]        ;fi[k1] a fi[k3]
+
+       fld     dword [sp(%$g0)]
+       fsub    st0, st2                ;gi[k2] fi[k1] a fi[k3]
+       fxch    st2
+       fadd    dword [sp(%$g0)]        ;gi[0] fi[k1] gi[k2] fi[k3]
+
+       fxch    st3
+       fstp    dword [r0+r2]
+       fstp    dword [r0+r3]
+       fstp    dword [r1+r3*2]
+       fstp    dword [r1]
+
+
+       lea     r0, [r0+r3*4]
+       lea     r1, [r1+r3*4]
+       cmp     r0, r6
+       jb near .do3
+
+       add     r5, 4
+       cmp     r5, r4
+       jb near .for
+
+       cmp     r3, [sp(%$n)]
+       jae     .exit
+
+       add     dword [sp(%$k)], 2      ;k  += 2;
+       lea     r3, [r3*4]              ;k1 *= 4
+       lea     r2, [r2*4]              ;k3 *= 4
+       lea     r4, [r4*4]              ;kx *= 4
+       mov     r0, [sp(%$fz)]  ;fi
+       lea     r1, [r0+r4]             ;gi = fi + kx
+       jmp     .do
+
+.exit:
+       popd    ebp, ebx, esi, edi
+endproc
+
+       end
diff --git a/lame/libmp3lame/i386/fftsse.nas b/lame/libmp3lame/i386/fftsse.nas
new file mode 100644 (file)
index 0000000..616fcc2
--- /dev/null
@@ -0,0 +1,422 @@
+; back port from GOGO-no coda 2.24b by Takehiro TOMINAGA
+
+; GOGO-no-coda
+;      Copyright (C) 1999 shigeo
+;      special thanks to Keiichi SAKAI
+%include "nasm.h"
+
+       globaldef fht_SSE
+
+       segment_data
+       align 16
+Q_MMPP dd      0x0,0x0,0x80000000,0x80000000
+Q_MPMP dd      0x0,0x80000000,0x0,0x80000000
+D_1100 dd 0.0, 0.0, 1.0, 1.0
+costab_fft:
+       dd 9.238795325112867e-01
+       dd 3.826834323650898e-01
+       dd 9.951847266721969e-01
+       dd 9.801714032956060e-02
+       dd 9.996988186962042e-01
+       dd 2.454122852291229e-02
+       dd 9.999811752836011e-01
+       dd 6.135884649154475e-03
+S_SQRT2        dd      1.414213562
+
+       segment_code
+
+PIC_OFFSETTABLE
+
+;------------------------------------------------------------------------
+;      by K. SAKAI
+;      99/08/18        PIII 23k[clk]
+;      99/08/19        Ì¿Îá½ç½øÆþ¤ì´¹¤¨ PIII 22k[clk]
+;      99/08/20        bit reversal ¤òµì¸á¸å¤«¤é°Ü¿¢¤·¤¿ PIII 17k[clk]
+;      99/08/23        °ìÉô unroll PIII 14k[clk]
+;      99/11/12        clean up
+;
+;void fht_SSE(float *fz, int n);
+       align 16
+fht_SSE:
+       push    ebx
+       push    esi
+       push    edi
+       push    ebp
+
+%assign _P 4*5
+
+       ;2¤ÄÌܤΥ롼¥×
+       mov     eax,[esp+_P+0]  ;eax=fz
+       mov     ebp,[esp+_P+4]  ;=n
+       shl     ebp,3
+       add     ebp,eax         ; fn  = fz + n, ¤³¤Î´Ø¿ô½ªÎ»¤Þ¤ÇÉÔÊÑ
+       push    ebp
+
+       call    get_pc.bp
+       add     ebp, PIC_BASE()
+
+       lea     ecx,[PIC_EBP_REL(costab_fft)]
+       xor     eax,eax
+       mov     al,8            ; =k1=1*(sizeof float)  // 4, 16, 64, 256,...
+.lp2:                          ; do{
+       mov     esi,[esp+_P+4]  ; esi=fi=fz
+       lea     edx,[eax+eax*2]
+       mov     ebx, esi
+
+; ¤¿¤«¤À¤«2ÊÂÎó¤·¤«´üÂԤǤ­¤Ê¤¤Éôʬ¤ÏFPU¤Î¤Û¤¦¤¬Â®¤¤¡£
+       loopalign       16
+.lp20:                         ; do{
+;                       f0     = fi[0 ] + fi[k1];
+;                       f2     = fi[k2] + fi[k3];
+;                       f1     = fi[0 ] - fi[k1];
+;                       f3     = fi[k2] - fi[k3];
+;                       fi[0 ] = f0     + f2;
+;                       fi[k1] = f1     + f3;
+;                       fi[k2] = f0     - f2;
+;                       fi[k3] = f1     - f3;
+       lea     edi,[ebx+eax]   ; edi=gi=fi+ki/2
+       fld     dword [ebx]
+       fadd    dword [ebx+eax*2]
+       fld     dword [ebx+eax*4]
+       fadd    dword [ebx+edx*2]
+
+       fld     dword [ebx]
+       fsub    dword [ebx+eax*2]
+       fld     dword [ebx+eax*4]
+       fsub    dword [ebx+edx*2]
+
+       fld     st1
+       fadd    st0,st1
+       fstp    dword [ebx+eax*2]
+       fsubp   st1,st0
+       fstp    dword [ebx+edx*2]
+
+       fld     st1
+       fadd    st0,st1
+       fstp    dword [ebx]
+       fsubp   st1,st0
+       fstp    dword [ebx+eax*4]
+
+       lea     ebx,[ebx + eax*8]       ; = fi += (k1 * 4);
+;                       g0     = gi[0 ] + gi[k1];
+;                       g2     = SQRT2  * gi[k2];
+;                       g1     = gi[0 ] - gi[k1];
+;                       g3     = SQRT2  * gi[k3];
+;                       gi[0 ] = g0     + g2;
+;                       gi[k2] = g0     - g2;
+;                       gi[k1] = g1     + g3;
+;                       gi[k3] = g1     - g3;
+       fld     dword [edi]
+       fadd    dword [edi+eax*2]
+       fld     dword [PIC_EBP_REL(S_SQRT2)]
+       fmul    dword [edi+eax*4]
+
+       fld     dword [edi]
+       fsub    dword [edi+eax*2]
+       fld     dword [PIC_EBP_REL(S_SQRT2)]
+       fmul    dword [edi+edx*2]
+
+       fld     st1
+       fadd    st0,st1
+       fstp    dword [edi+eax*2]
+       fsubp   st1,st0
+       fstp    dword [edi+edx*2]
+
+       fld     st1
+       fadd    st0,st1
+       fstp    dword [edi]
+       fsubp   st1,st0
+       fstp    dword [edi+eax*4]
+
+       cmp     ebx,[esp]
+       jl      near .lp20              ; while (fi<fn);
+
+
+;               i = 1; //for (i=1;i<kx;i++){
+;                       c1 = 1.0*t_c - 0.0*t_s;
+;                       s1 = 0.0*t_c + 1.0*t_s;
+       movlps  xmm6,[ecx] ; = { --,  --,  s1, c1}
+       movaps  xmm7,xmm6
+
+       shufps  xmm6,xmm6,R4(0,1,1,0)   ; = {+c1, +s1, +s1, +c1} -> É¬Í×
+;                       c2 = c1*c1 - s1*s1 = 1 - (2*s1)*s1;
+;                       s2 = c1*s1 + s1*c1 = 2*s1*c1;
+       shufps  xmm7,xmm7,R4(1,0,0,1)
+       movss   xmm5,xmm7               ; = { --,  --,  --, s1}
+       xorps   xmm7,[PIC_EBP_REL(Q_MMPP)]      ; = {-s1, -c1, +c1, +s1} -> É¬Í×
+
+       addss   xmm5,xmm5               ; = (--, --,  --, 2*s1)
+       add     esi,4           ; esi = fi = fz + i
+       shufps  xmm5,xmm5,R4(0,0,0,0)   ; = (2*s1, 2*s1, 2*s1, 2*s1)
+       mulps   xmm5,xmm6               ; = (2*s1*c1, 2*s1*s1, 2*s1*s1, 2*s1*c1)
+       subps   xmm5,[PIC_EBP_REL(D_1100)]              ; = (--, 2*s1*s1-1, --, 2*s1*c1) = {-- -c2 -- s2}
+       movaps  xmm4,xmm5
+       shufps  xmm5,xmm5,R4(2,0,2,0)   ; = {-c2, s2, -c2, s2} -> É¬Í×
+
+       xorps   xmm4,[PIC_EBP_REL(Q_MMPP)]              ; = {--, c2, --, s2}
+       shufps  xmm4,xmm4,R4(0,2,0,2)   ; = {s2, c2, s2, c2} -> É¬Í×
+
+       loopalign       16
+.lp21:                         ; do{
+;                               a       = c2*fi[k1] + s2*gi[k1];
+;                               b       = s2*fi[k1] - c2*gi[k1];
+;                               c       = c2*fi[k3] + s2*gi[k3];
+;                               d       = s2*fi[k3] - c2*gi[k3];
+;                               f0      = fi[0 ]        + a;
+;                               g0      = gi[0 ]        + b;
+;                               f2      = fi[k1 * 2]    + c;
+;                               g2      = gi[k1 * 2]    + d;
+;                               f1      = fi[0 ]        - a;
+;                               g1      = gi[0 ]        - b;
+;                               f3      = fi[k1 * 2]    - c;
+;                               g3      = gi[k1 * 2]    - d;
+       lea     edi,[esi + eax*2 - 8]   ; edi = gi = fz +k1-i
+
+       movss   xmm0,[esi + eax*2]      ; = fi[k1]
+       movss   xmm2,[esi + edx*2]      ; = fi[k3]
+       shufps  xmm0,xmm2,0x00  ; = {fi[k3], fi[k3], fi[k1], fi[k1]}
+       movss   xmm1,[edi + eax*2]      ; = fi[k1]
+       movss   xmm3,[edi + edx*2]      ; = fi[k3]
+       shufps  xmm1,xmm3,0x00  ; = {gi[k3], gi[k3], gi[k1], gi[k1]}
+       movss   xmm2,[esi]              ; = fi[0]
+       mulps   xmm0,xmm4               ; *= {+s2, +c2, +s2, +c2}
+       movss   xmm3,[esi + eax*4]      ; = fi[k2]
+       unpcklps        xmm2,xmm3       ; = {--, --, fi[k2], fi[0]}
+       mulps   xmm1,xmm5               ; *= {-c2, +s2, -c2, +s2}
+       movss   xmm3,[edi + eax*4]      ; = gi[k2]
+       addps   xmm0,xmm1               ; = {d, c, b, a}
+       movss   xmm1,[edi]              ; = gi[0]
+       unpcklps        xmm1,xmm3       ; = {--,  --, gi[k2], gi[0]}
+       unpcklps        xmm2,xmm1       ; = {gi[k2], fi[k2], gi[0], fi[0]}
+       movaps  xmm1,xmm2
+       addps   xmm1,xmm0       ; = {g2, f2, g0, f0}
+       subps   xmm2,xmm0       ; = {g3, f3, g1, f1}
+
+;                               a       = c1*f2     + s1*g3;
+;                               c       = s1*g2     + c1*f3;
+;                               b       = s1*f2     - c1*g3;
+;                               d       = c1*g2     - s1*f3;
+;                               fi[0 ]  = f0        + a;
+;                               gi[0 ]  = g0        + c;
+;                               gi[k1]  = g1        + b;
+;                               fi[k1]  = f1        + d;
+;                               fi[k1 * 2]  = f0    - a;
+;                               gi[k1 * 2]  = g0    - c;
+;                               gi[k3]      = g1    - b;
+;                               fi[k3]      = f1    - d;
+       movaps  xmm3,xmm1
+       movhlps xmm1,xmm1       ; = {g2, f2, g2, f2}
+       shufps  xmm3,xmm2,0x14  ; = {f1, g1, g0, f0}
+       mulps   xmm1,xmm6       ; *= {+c1, +s1, +s1, +c1}
+       shufps  xmm2,xmm2,0xBB  ; = {f3, g3, f3, g3}
+       mulps   xmm2,xmm7       ; *= {-s1, -c1, +c1, +s1}
+       addps   xmm1,xmm2       ; = {d, b, c, a}
+       movaps  xmm2,xmm3
+       addps   xmm3,xmm1       ; = {fi[k1], gi[k1], gi[0], fi[0]}
+       subps   xmm2,xmm1       ; = {fi[k3], gi[k3], gi[k1*2], fi[k1*2]}
+       movhlps xmm0,xmm3
+       movss   [esi],xmm3
+       shufps  xmm3,xmm3,0x55
+       movss   [edi+eax*2],xmm0
+       shufps  xmm0,xmm0,0x55
+       movss   [edi],xmm3
+       movss   [esi+eax*2],xmm0
+       movhlps xmm0,xmm2
+       movss   [esi+eax*4],xmm2
+       shufps  xmm2,xmm2,0x55
+       movss   [edi+edx*2],xmm0
+       shufps  xmm0,xmm0,0x55
+       movss   [edi+eax*4],xmm2
+       movss   [esi+edx*2],xmm0
+       lea     esi,[esi + eax*8] ; fi += (k1 * 4);
+       cmp     esi,[esp]
+       jl      near .lp21              ; while (fi<fn);
+
+
+; unrollÁ°¤Îdo loop¤Ï43+4Ì¿Îá
+
+; ºÇÆâ¼þ¤Ç¤Ï¤Ê¤¤for¥ë¡¼¥×¤Îi=2¤«¤éÀè¤òunrolling¤·¤¿
+; kx=   2,   8,  32,  128
+; k4=  16,  64, 256, 1024
+;       0, 6/2,30/2,126/2
+
+       xor     ebx,ebx
+       mov     bl, 4*2         ; = i = 4
+       cmp     ebx,eax         ; i < k1
+       jnl     near .F22
+;               for (i=2;i<kx;i+=2){
+       loopalign       16
+.lp22:
+; at here, xmm6 is {c3, s3, s3, c3}
+;                       c1 = c3*t_c - s3*t_s;
+;                       s1 = c3*t_s + s3*t_c;
+       movlps  xmm0,[ecx]
+       shufps  xmm0,xmm0,R4(1,1,0,0)   ; = {t_s, t_s, t_c, t_c}
+       mulps   xmm6,xmm0       ; = {c3*ts, s3*ts, s3*tc, c3*tc}
+       movhlps xmm4,xmm6       ; = {--,    --,    c3*ts, s3*ts}
+       xorps   xmm4,[PIC_EBP_REL(Q_MPMP)]      ; = {--,    --,   -c3*ts, s3*ts}
+       subps   xmm6,xmm4       ; = {-,-, c3*ts+s3*tc, c3*tc-s3*ts}={-,-,s1,c1}
+
+;                       c3 = c1*t_c - s1*t_s;
+;                       s3 = s1*t_c + c1*t_s;
+       shufps  xmm6,xmm6,0x14  ; = {c1, s1, s1, c1}
+       mulps   xmm0,xmm6       ; = {ts*c1 ts*s1 tc*s1 tc*c1}
+       movhlps xmm3,xmm0
+       xorps   xmm3,[PIC_EBP_REL(Q_MPMP)]
+       subps   xmm0,xmm3       ; = {--, --, s3, c3}
+
+; {s2 s4 c4 c2} = {2*s1*c1 2*s3*c3 1-2*s3*s3 1-2*s1*s1}
+       unpcklps        xmm6,xmm0       ; xmm6 = {s3, s1, c3, c1}
+       movaps  xmm7, xmm6
+       shufps  xmm6,xmm6,R4(2,3,1,0)   ; xmm6 = {s1, s3, c3, c1}
+       addps   xmm7, xmm7              ; {s3*2, s1*2,   --,   --}
+       mov     edi,[esp+_P+4]          ; = fz
+       shufps  xmm7, xmm7, R4(2,3,3,2) ; {s1*2, s3*2, s3*2, s1*2}
+       sub     edi,ebx                 ; edi = fz - i/2
+       mulps   xmm7, xmm6              ; {s1*s1*2, s3*s3*2, s3*c3*2, s1*c1*2}
+       lea     esi,[edi + ebx*2]       ; esi = fi = fz +i/2
+       subps   xmm7, [PIC_EBP_REL(D_1100)]             ; {-c2, -c4, s4, s2}
+       lea     edi,[edi + eax*2-4]     ; edi = gi = fz +k1-i/2
+
+;                       fi = fz +i;
+;                       gi = fz +k1-i;
+;                       do{
+.lp220:
+; unroll¸å¤Îdo loop¤Ï51+4Ì¿Îá
+;                               a       = c2*fi[k1  ] + s2*gi[k1  ];
+;                               e       = c4*fi[k1+1] + s4*gi[k1-1];
+;                               f       = s4*fi[k1+1] - c4*gi[k1-1];
+;                               b       = s2*fi[k1  ] - c2*gi[k1  ];
+;                               c       = c2*fi[k3  ] + s2*gi[k3  ];
+;                               g       = c4*fi[k3+1] + s4*gi[k3-1];
+;                               h       = s4*fi[k3+1] - c4*gi[k3-1];
+;                               d       = s2*fi[k3  ] - c2*gi[k3  ];
+
+       movaps  xmm4,xmm7       ; = {-c2 -c4  s4  s2}
+       xorps   xmm4,[PIC_EBP_REL(Q_MMPP)]      ; = { c2  c4  s4  s2}
+       shufps  xmm4,xmm4,0x1B  ; = { s2  s4  c4  c2}
+       movlps  xmm0,[esi+eax*2]
+       movlps  xmm1,[edi+eax*2]
+       movlps  xmm2,[esi+edx*2]
+       movlps  xmm3,[edi+edx*2]
+       shufps  xmm0,xmm0,0x14
+       shufps  xmm1,xmm1,0x41
+       shufps  xmm2,xmm2,0x14
+       shufps  xmm3,xmm3,0x41
+       mulps   xmm0,xmm4
+       mulps   xmm1,xmm7
+       mulps   xmm2,xmm4
+       mulps   xmm3,xmm7
+       addps   xmm0,xmm1       ; xmm0 = {b, f, e, a}
+       addps   xmm2,xmm3       ; xmm2 = {d, h, g, c}
+;17
+
+;                               f0      = fi[0   ]    + a;
+;                               f4      = fi[0 +1]    + e;
+;                               g4      = gi[0 -1]    + f;
+;                               g0      = gi[0   ]    + b;
+;                               f1      = fi[0   ]    - a;
+;                               f5      = fi[0 +1]    - e;
+;                               g5      = gi[0 -1]    - f;
+;                               g1      = gi[0   ]    - b;
+;                               f2      = fi[k2  ]    + c;
+;                               f6      = fi[k2+1]    + g;
+;                               g6      = gi[k2-1]    + h;
+;                               g2      = gi[k2  ]    + d;
+;                               f3      = fi[k2  ]    - c;
+;                               f7      = fi[k2+1]    - g;
+;                               g7      = gi[k2-1]    - h;
+;                               g3      = gi[k2  ]    - d;
+       movlps  xmm1,[esi      ]
+       movhps  xmm1,[edi      ]
+       movaps  xmm4,xmm1
+       subps   xmm1,xmm0       ; xmm1 = {g1, g5, f5, f1}
+       movlps  xmm3,[esi+eax*4]
+       movhps  xmm3,[edi+eax*4]
+       movaps  xmm5,xmm3
+       subps   xmm3,xmm2       ; xmm3 = {g3, g7, f7, f3}
+       addps   xmm0,xmm4       ; xmm0 = {g0, g4, f4, f0}
+       addps   xmm2,xmm5       ; xmm2 = {g2, g6, f6, f2}
+;10
+
+;                               a       = c1*f2     + s1*g3;   ½ç*½ç + µÕ*µÕ
+;                               e       = c3*f6     + s3*g7;
+;                               g       = s3*g6     + c3*f7;
+;                               c       = s1*g2     + c1*f3;
+;                               d       = c1*g2     - s1*f3;   ½ç*µÕ - µÕ*½ç
+;                               h       = c3*g6     - s3*f7;
+;                               f       = s3*f6     - c3*g7;
+;                               b       = s1*f2     - c1*g3;
+
+       movaps  xmm5,xmm6       ; xmm6 = {s1, s3, c3, c1}
+       shufps  xmm5,xmm5,0x1B  ; = {c1, c3, s3, s1}
+       movaps  xmm4,xmm2
+       mulps   xmm4,xmm6
+       shufps  xmm2,xmm2,0x1B  ; xmm2 = {f2, f6, g6, g2}
+       mulps   xmm2,xmm6
+       mulps   xmm5,xmm3
+       mulps   xmm3,xmm6
+       shufps  xmm3,xmm3,0x1B
+       addps   xmm4,xmm3       ; = {c, g, e, a}
+       subps   xmm2,xmm5       ; = {b, f, h, d}
+;10
+
+;                               fi[0   ]  = f0        + a;
+;                               fi[0 +1]  = f4        + e;
+;                               gi[0 -1]  = g4        + g;
+;                               gi[0   ]  = g0        + c;
+;                               fi[k2  ]  = f0        - a;
+;                               fi[k2+1]  = f4        - e;
+;                               gi[k2-1]  = g4        - g;
+;                               gi[k2  ]  = g0        - c;
+;                               fi[k1  ]  = f1        + d;
+;                               fi[k1+1]  = f5        + h;
+;                               gi[k1-1]  = g5        + f;
+;                               gi[k1  ]  = g1        + b;
+;                               fi[k3  ]  = f1        - d;
+;                               fi[k3+1]  = f5        - h;
+;                               gi[k3-1]  = g5        - f;
+;                               gi[k3  ]  = g1        - b;
+       movaps  xmm3,xmm0
+       subps   xmm0,xmm4
+       movlps  [esi+eax*4],xmm0
+       movhps  [edi+eax*4],xmm0
+       addps   xmm4,xmm3
+       movlps  [esi      ],xmm4
+       movhps  [edi      ],xmm4
+
+       movaps  xmm5,xmm1
+       subps   xmm1,xmm2
+       movlps  [esi+edx*2],xmm1
+       movhps  [edi+edx*2],xmm1
+       addps   xmm2,xmm5
+       movlps  [esi+eax*2],xmm2
+       movhps  [edi+eax*2],xmm2
+; 14
+;                               gi     += k4;
+;                               fi     += k4;
+       lea     edi,[edi + eax*8] ; gi += (k1 * 4);
+       lea     esi,[esi + eax*8] ; fi += (k1 * 4);
+       cmp     esi,[esp]
+       jl      near .lp220             ; while (fi<fn);
+;                       } while (fi<fn);
+
+       add     ebx,byte 2*4    ; i+= 4
+       cmp     ebx,eax         ; i < k1
+       shufps  xmm6,xmm6,R4(1,2,2,1)   ; (--,s3,c3,--) => {c3, s3, s3, c3}
+       jl      near .lp22
+;               }
+.F22:
+       shl     eax,2
+       add     ecx, byte 8
+       cmp     eax,[esp+_P+8]  ; while ((k1 * 4)<n);
+       jle     near .lp2
+       pop     ebp
+       pop     ebp
+       pop     edi
+       pop     esi
+       pop     ebx
+       ret
+
+       end
diff --git a/lame/libmp3lame/i386/ffttbl.nas b/lame/libmp3lame/i386/ffttbl.nas
new file mode 100644 (file)
index 0000000..14dd9ae
--- /dev/null
@@ -0,0 +1,78 @@
+
+;      for new GOGO-no-coda (1999/09)
+;      Copyright (C) 1999 shigeo
+;      special thanks to URURI, Keiichi SAKAI
+
+
+;      fft sin,cos,gray¥Æ¡¼¥Ö¥ë
+;      99/08/21
+;      99/09/01(¤¦¤ë¤ê)¡¡¥Ó¥Ã¥Èȿž¥Æ¡¼¥Ö¥ëºï½ü
+;      99/09/14 ¥°¥ì¥¤¥³¡¼¥É¥¤¥ó¥Ç¥Ã¥¯¥¹É½¥°¥í¡¼¥Ð¥ë²½
+
+%include "nasm.h"
+
+       globaldef       costab_fft
+       globaldef       sintab_fft
+       globaldef       gray_index
+
+       segment_data
+       align 16
+
+costab_fft:
+       dd 0.000000000000
+       dd 0.707106781187
+       dd 0.923879532511
+       dd 0.980785280403
+       dd 0.995184726672
+       dd 0.998795456205
+       dd 0.999698818696
+       dd 0.999924701839
+       dd 0.999981175283
+       dd 0.999995293810
+       dd 0.999998823452
+       dd 0.999999705863
+       dd 0.999999926466
+       dd 0.999999981616
+       dd 0.999999995404
+       dd 0.999999998851
+
+sintab_fft:
+       dd 1.000000000000
+       dd 0.707106781187
+       dd 0.382683432365
+       dd 0.195090322016
+       dd 0.098017140330
+       dd 0.049067674327
+       dd 0.024541228523
+       dd 0.012271538286
+       dd 0.006135884649
+       dd 0.003067956763
+       dd 0.001533980186
+       dd 0.000766990319
+       dd 0.000383495188
+       dd 0.000191747597
+       dd 0.000095873799
+       dd 0.000047936900
+
+               align 16
+gray_index:
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 8
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 9
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 8
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6
+               db      2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 10
+
+       segment_code
+
+       end
diff --git a/lame/libmp3lame/i386/nasm.h b/lame/libmp3lame/i386/nasm.h
new file mode 100644 (file)
index 0000000..720f666
--- /dev/null
@@ -0,0 +1,268 @@
+
+;      Copyright (C) 1999 URURI
+
+;      nasm�ѥޥ���
+;      1999/08/21 ���
+;      1999/10/10 ���Ĥ��ɲ�
+;      1999/10/27 aout�б�
+;      1999/11/07 pushf, popf ��NASM�ΥХ��б�
+;      1999/12/02 for BCC ( Thanks to Miquel )
+
+; for Windows Visual C++        -> define WIN32
+;             Borland or cygwin ->        WIN32 and COFF
+; for FreeBSD 2.x               ->        AOUT
+; for TownsOS                   ->        __tos__
+; otherwise                     ->   none
+
+;̾����դ���
+
+BITS 32
+
+section .note.GNU-stack noalloc noexec nowrite progbits
+
+%ifdef YASM
+       %define segment_code segment .text align=16 use32
+       %define segment_data segment .data align=16 use32
+       %define segment_bss  segment .bss align=16 use32
+%elifdef WIN32
+       %define segment_code segment .text align=16 class=CODE use32
+       %define segment_data segment .data align=16 class=DATA use32
+%ifdef __BORLANDC__
+       %define segment_bss  segment .data align=16 class=DATA use32
+%else
+       %define segment_bss  segment .bss align=16 class=DATA use32
+%endif
+%elifdef AOUT
+       %define _NAMING
+       %define segment_code segment .text
+       %define segment_data segment .data
+       %define segment_bss  segment .bss
+%else
+%ifidn __OUTPUT_FORMAT__,elf
+       section .note.GNU-stack progbits noalloc noexec nowrite align=1
+%endif
+       %define segment_code segment .text align=16 class=CODE use32
+       %define segment_data segment .data align=16 class=DATA use32
+       %define segment_bss  segment .bss align=16 class=DATA use32
+%endif
+
+%ifdef WIN32
+       %define _NAMING
+%endif
+
+%ifdef __tos__
+group CGROUP text
+group DGROUP data
+%endif
+
+;ñ�����ư��������
+
+%idefine float dword
+%idefine fsize 4
+%idefine fsizen(a) (fsize*(a))
+
+;��ɷ��
+
+%idefine wsize 2
+%idefine wsizen(a) (wsize*(a))
+%idefine dwsize 4
+%idefine dwsizen(a) (dwsize*(a))
+
+;REG
+
+%define r0 eax
+%define r1 ebx
+%define r2 ecx
+%define r3 edx
+%define r4 esi
+%define r5 edi
+%define r6 ebp
+%define r7 esp
+
+;MMX,3DNow!,SSE
+
+%define pmov   movq
+%define pmovd  movd
+
+%define pupldq punpckldq
+%define puphdq punpckhdq
+%define puplwd punpcklwd
+%define puphwd punpckhwd
+
+%define xm0 xmm0
+%define xm1 xmm1
+%define xm2 xmm2
+%define xm3 xmm3
+%define xm4 xmm4
+%define xm5 xmm5
+%define xm6 xmm6
+%define xm7 xmm7
+
+;�����åե��Ѥ�4�ʥޥ���
+
+%define R4(a,b,c,d) (a*64+b*16+c*4+d)
+
+;C�饤���ʴʰץޥ���
+
+%imacro globaldef 1
+       %ifdef _NAMING
+               %define %1 _%1
+       %endif
+       global %1
+%endmacro
+
+%imacro externdef 1
+       %ifdef _NAMING
+               %define %1 _%1
+       %endif
+       extern %1
+%endmacro
+
+%imacro proc 1
+       %push   proc
+       %ifdef _NAMING
+               global _%1
+       %else
+               global %1
+       %endif
+
+       align 32
+%1:
+_%1:
+
+       %assign %$STACK 0
+       %assign %$STACKN 0
+       %assign %$ARG 4
+%endmacro
+
+%imacro endproc 0
+       %ifnctx proc
+               %error expected 'proc' before 'endproc'.
+       %else
+               %if %$STACK > 0
+                       add esp, %$STACK
+               %endif
+
+               %if %$STACK <> (-%$STACKN)
+                       %error STACKLEVEL mismatch check 'local', 'alloc', 'pushd', 'popd'
+               %endif
+
+               ret
+               %pop
+       %endif
+%endmacro
+
+%idefine sp(a) esp+%$STACK+a
+
+%imacro arg 1
+       %00     equ %$ARG
+       %assign %$ARG %$ARG+%1
+%endmacro
+
+%imacro local 1
+       %assign %$STACKN %$STACKN-%1
+       %00 equ %$STACKN
+%endmacro
+
+%imacro alloc 0
+       sub esp, (-%$STACKN)-%$STACK
+       %assign %$STACK (-%$STACKN)
+%endmacro
+
+%imacro pushd 1-*
+       %rep %0
+               push %1
+               %assign %$STACK %$STACK+4
+       %rotate 1
+       %endrep
+%endmacro
+
+%imacro popd 1-*
+       %rep %0
+       %rotate -1
+               pop %1
+               %assign %$STACK %$STACK-4
+       %endrep
+%endmacro
+
+; bug of NASM-0.98
+%define pushf db 0x66, 0x9C
+%define popf  db 0x66, 0x9D
+
+%define        ge16(n)         ((((n) / 16)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge15(n)         ((((n) / 15)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge14(n)         ((((n) / 14)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge13(n)         ((((n) / 13)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge12(n)         ((((n) / 12)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge11(n)         ((((n) / 11)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge10(n)         ((((n) / 10)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge9(n)          ((((n) /  9)*0xFFFFFFFF) & 0xFFFFFFFF)
+%define        ge8(n)          (ge9(n) | ((((n) /  8)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge7(n)          (ge9(n) | ((((n) /  7)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge6(n)          (ge9(n) | ((((n) /  6)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge5(n)          (ge9(n) | ((((n) /  5)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge4(n)          (ge5(n) | ((((n) /  4)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge3(n)          (ge5(n) | ((((n) /  3)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge2(n)          (ge3(n) | ((((n) /  2)*0xFFFFFFFF) & 0xFFFFFFFF))
+%define        ge1(n)          (ge2(n) | ((((n) /  1)*0xFFFFFFFF) & 0xFFFFFFFF))
+
+; macro to align for begining of loop
+; %1   does not align if it LE bytes to next alignment 
+;      4..16 
+;      default is 12
+
+%imacro        loopalignK6     0-1 12 
+%%here:
+       times (($$-%%here) & 15 & ge1(($$-%%here) & 15) & ~ge4(($$-%%here) & 15)) nop
+       times (1                & ge4(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) jmp short %%skip
+       times (((($$-%%here) & 15)-2) & ge4(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) nop
+%%skip:
+%endmacro
+
+%imacro        loopalignK7     0-1 12 
+%%here:
+       times (1 & ge1(($$-%%here) & 15)  & ~ge2(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) nop
+       times (1 & ge2(($$-%%here) & 15)  & ~ge3(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Bh,0C0h
+       times (1 & ge3(($$-%%here) & 15)  & ~ge4(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,004h,020h
+       times (1 & ge4(($$-%%here) & 15)  & ~ge5(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,044h,020h,000h
+       times (1 & ge5(($$-%%here) & 15)  & ~ge6(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,044h,020h,000h,090h
+       times (1 & ge6(($$-%%here) & 15)  & ~ge7(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,080h,0,0,0,0
+       times (1 & ge7(($$-%%here) & 15)  & ~ge8(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,004h,005h,0,0,0,0
+       times (1 & ge8(($$-%%here) & 15)  & ~ge9(($$-%%here) & 15)  & ~ge%1(($$-%%here) & 15)) DB 08Dh,004h,005h,0,0,0,0,90h
+       times (1 & ge9(($$-%%here) & 15)  & ~ge10(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,007h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge10(($$-%%here) & 15) & ~ge11(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,008h,90h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge11(($$-%%here) & 15) & ~ge12(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,009h,90h,90h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge12(($$-%%here) & 15) & ~ge13(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,00Ah,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge13(($$-%%here) & 15) & ~ge14(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,00Bh,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge14(($$-%%here) & 15) & ~ge15(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,00Ch,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h
+       times (1 & ge15(($$-%%here) & 15) & ~ge16(($$-%%here) & 15) & ~ge%1(($$-%%here) & 15)) DB 0EBh,00Dh,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h,90h
+%%skip:
+%endmacro
+
+%imacro        loopalign       0-1 12 
+       loopalignK7 %1
+%endmacro
+%define PACK(x,y,z,w)  (x*64+y*16+z*4+w)
+
+%ifidn __OUTPUT_FORMAT__,elf
+
+%idefine PIC_BASE(A) _GLOBAL_OFFSET_TABLE_ + $$ - $ wrt ..gotpc
+%idefine PIC_EBP_REL(A) ebp + A wrt ..gotoff
+%macro PIC_OFFSETTABLE 0
+extern  _GLOBAL_OFFSET_TABLE_
+get_pc.bp:
+       mov ebp, [esp]
+       retn
+%endmacro
+
+%else
+
+%define PIC_BASE(A) (0)
+%define PIC_EBP_REL(A) (A)
+%macro PIC_OFFSETTABLE 0
+get_pc.bp:
+       mov ebp, [esp]
+       retn
+%endmacro
+
+%endif
diff --git a/lame/libmp3lame/i386/scalar.nas b/lame/libmp3lame/i386/scalar.nas
new file mode 100644 (file)
index 0000000..6d69f42
--- /dev/null
@@ -0,0 +1,1022 @@
+;
+;    (C) Frank Klemm 1995,99,2000
+;    Dedicated to the LAME project
+;
+;
+        %include "nasm.h"
+
+        segment_code
+        
+; float_t  scalar04_float32_i387 ( 
+;         const float32_t* const  p, 
+;         const float32_t* const  q );
+
+proc    scalar04_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar08_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar12_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+        fld     dword [eax + 32]
+        fmul    dword [edx + 32]
+        faddp   st1,st0    
+        fld     dword [eax + 36]
+        fmul    dword [edx + 36]
+        faddp   st1,st0    
+        fld     dword [eax + 40]
+        fmul    dword [edx + 40]
+        faddp   st1,st0    
+        fld     dword [eax + 44]
+        fmul    dword [edx + 44]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar16_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+        fld     dword [eax + 32]
+        fmul    dword [edx + 32]
+        faddp   st1,st0    
+        fld     dword [eax + 36]
+        fmul    dword [edx + 36]
+        faddp   st1,st0    
+        fld     dword [eax + 40]
+        fmul    dword [edx + 40]
+        faddp   st1,st0    
+        fld     dword [eax + 44]
+        fmul    dword [edx + 44]
+        faddp   st1,st0    
+        fld     dword [eax + 48]
+        fmul    dword [edx + 48]
+        faddp   st1,st0    
+        fld     dword [eax + 52]
+        fmul    dword [edx + 52]
+        faddp   st1,st0    
+        fld     dword [eax + 56]
+        fmul    dword [edx + 56]
+        faddp   st1,st0    
+        fld     dword [eax + 60]
+        fmul    dword [edx + 60]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar20_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+        fld     dword [eax + 32]
+        fmul    dword [edx + 32]
+        faddp   st1,st0    
+        fld     dword [eax + 36]
+        fmul    dword [edx + 36]
+        faddp   st1,st0    
+        fld     dword [eax + 40]
+        fmul    dword [edx + 40]
+        faddp   st1,st0    
+        fld     dword [eax + 44]
+        fmul    dword [edx + 44]
+        faddp   st1,st0    
+        fld     dword [eax + 48]
+        fmul    dword [edx + 48]
+        faddp   st1,st0    
+        fld     dword [eax + 52]
+        fmul    dword [edx + 52]
+        faddp   st1,st0    
+        fld     dword [eax + 56]
+        fmul    dword [edx + 56]
+        faddp   st1,st0    
+        fld     dword [eax + 60]
+        fmul    dword [edx + 60]
+        faddp   st1,st0    
+        fld     dword [eax + 64]
+        fmul    dword [edx + 64]
+        faddp   st1,st0    
+        fld     dword [eax + 68]
+        fmul    dword [edx + 68]
+        faddp   st1,st0    
+        fld     dword [eax + 72]
+        fmul    dword [edx + 72]
+        faddp   st1,st0    
+        fld     dword [eax + 76]
+        fmul    dword [edx + 76]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar24_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+        fld     dword [eax + 32]
+        fmul    dword [edx + 32]
+        faddp   st1,st0    
+        fld     dword [eax + 36]
+        fmul    dword [edx + 36]
+        faddp   st1,st0    
+        fld     dword [eax + 40]
+        fmul    dword [edx + 40]
+        faddp   st1,st0    
+        fld     dword [eax + 44]
+        fmul    dword [edx + 44]
+        faddp   st1,st0    
+        fld     dword [eax + 48]
+        fmul    dword [edx + 48]
+        faddp   st1,st0    
+        fld     dword [eax + 52]
+        fmul    dword [edx + 52]
+        faddp   st1,st0    
+        fld     dword [eax + 56]
+        fmul    dword [edx + 56]
+        faddp   st1,st0    
+        fld     dword [eax + 60]
+        fmul    dword [edx + 60]
+        faddp   st1,st0    
+        fld     dword [eax + 64]
+        fmul    dword [edx + 64]
+        faddp   st1,st0    
+        fld     dword [eax + 68]
+        fmul    dword [edx + 68]
+        faddp   st1,st0    
+        fld     dword [eax + 72]
+        fmul    dword [edx + 72]
+        faddp   st1,st0    
+        fld     dword [eax + 76]
+        fmul    dword [edx + 76]
+        faddp   st1,st0    
+        fld     dword [eax + 80]
+        fmul    dword [edx + 80]
+        faddp   st1,st0    
+        fld     dword [eax + 84]
+        fmul    dword [edx + 84]
+        faddp   st1,st0    
+        fld     dword [eax + 88]
+        fmul    dword [edx + 88]
+        faddp   st1,st0    
+        fld     dword [eax + 92]
+        fmul    dword [edx + 92]
+        faddp   st1,st0    
+endproc
+
+
+proc    scalar32_float32_i387
+%$p     arg     4
+%$q     arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0    
+        fld     dword [eax + 16]
+        fmul    dword [edx + 16]
+        faddp   st1,st0    
+        fld     dword [eax + 20]
+        fmul    dword [edx + 20]
+        faddp   st1,st0    
+        fld     dword [eax + 24]
+        fmul    dword [edx + 24]
+        faddp   st1,st0    
+        fld     dword [eax + 28]
+        fmul    dword [edx + 28]
+        faddp   st1,st0    
+        fld     dword [eax + 32]
+        fmul    dword [edx + 32]
+        faddp   st1,st0    
+        fld     dword [eax + 36]
+        fmul    dword [edx + 36]
+        faddp   st1,st0    
+        fld     dword [eax + 40]
+        fmul    dword [edx + 40]
+        faddp   st1,st0    
+        fld     dword [eax + 44]
+        fmul    dword [edx + 44]
+        faddp   st1,st0    
+        fld     dword [eax + 48]
+        fmul    dword [edx + 48]
+        faddp   st1,st0    
+        fld     dword [eax + 52]
+        fmul    dword [edx + 52]
+        faddp   st1,st0    
+        fld     dword [eax + 56]
+        fmul    dword [edx + 56]
+        faddp   st1,st0    
+        fld     dword [eax + 60]
+        fmul    dword [edx + 60]
+        faddp   st1,st0    
+        fld     dword [eax + 64]
+        fmul    dword [edx + 64]
+        faddp   st1,st0    
+        fld     dword [eax + 68]
+        fmul    dword [edx + 68]
+        faddp   st1,st0    
+        fld     dword [eax + 72]
+        fmul    dword [edx + 72]
+        faddp   st1,st0    
+        fld     dword [eax + 76]
+        fmul    dword [edx + 76]
+        faddp   st1,st0    
+        fld     dword [eax + 80]
+        fmul    dword [edx + 80]
+        faddp   st1,st0    
+        fld     dword [eax + 84]
+        fmul    dword [edx + 84]
+        faddp   st1,st0    
+        fld     dword [eax + 88]
+        fmul    dword [edx + 88]
+        faddp   st1,st0    
+        fld     dword [eax + 92]
+        fmul    dword [edx + 92]
+        faddp   st1,st0    
+        fld     dword [eax + 96]
+        fmul    dword [edx + 96]
+        faddp   st1,st0    
+        fld     dword [eax +100]
+        fmul    dword [edx +100]
+        faddp   st1,st0    
+        fld     dword [eax +104]
+        fmul    dword [edx +104]
+        faddp   st1,st0    
+        fld     dword [eax +108]
+        fmul    dword [edx +108]
+        faddp   st1,st0    
+        fld     dword [eax +112]
+        fmul    dword [edx +112]
+        faddp   st1,st0    
+        fld     dword [eax +116]
+        fmul    dword [edx +116]
+        faddp   st1,st0    
+        fld     dword [eax +120]
+        fmul    dword [edx +120]
+        faddp   st1,st0    
+        fld     dword [eax +124]
+        fmul    dword [edx +124]
+        faddp   st1,st0    
+endproc
+
+
+; float_t  scalar4n_float32_i387 ( 
+;         const float32_t* const  p, 
+;         const float32_t* const  q,
+;         const size_t            len );
+
+proc    scalar4n_float32_i387
+%$p     arg     4
+%$q     arg     4
+%$len   arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        mov     ecx,[sp(%$len)]
+        fld     dword [eax]
+        fmul    dword [edx]
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0
+        dec     ecx
+        jz      .ret1
+        add     eax,byte 16
+        add     edx,byte 16
+.lbl1
+        fld     dword [eax]
+        fmul    dword [edx]
+        faddp   st1,st0
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0
+        add     eax,byte 16
+        add     edx,byte 16
+        dec     ecx
+        jnz     .lbl1
+.ret1   
+endproc
+
+
+; float_t  scalar1n_float32_i387 ( 
+;         const float32_t* const  p, 
+;         const float32_t* const  q,
+;         const size_t            len );
+
+proc    scalar1n_float32_i387
+%$p     arg     4
+%$q     arg     4
+%$len   arg     4
+;;;     alloc
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        mov     ecx,[sp(%$len)]
+        fld0
+        shr     ecx,1
+        jnc     .lbl2
+        fld     dword [eax]
+        fmul    dword [edx]
+        faddp   st1,st0
+        add     eax,byte 4
+        add     edx,byte 4
+.lbl2
+        shr     ecx,1
+        jnc     .lbl3
+        fld     dword [eax]
+        fmul    dword [edx]
+        faddp   st1,st0
+        fld     dword [eax + 4]
+        fmul    dword [edx + 4]
+        faddp   st1,st0
+        add     eax,byte 8
+        add     edx,byte 8
+        and     ecx,ecx
+.lbl3
+        jz      .ret2
+.lbl4
+        fld     dword [eax]
+        fmul    dword [edx]
+        faddp   st1,st0
+        fld     dword [eax +  4]
+        fmul    dword [edx +  4]
+        faddp   st1,st0
+        fld     dword [eax +  8]
+        fmul    dword [edx +  8]
+        faddp   st1,st0
+        fld     dword [eax + 12]
+        fmul    dword [edx + 12]
+        faddp   st1,st0
+        add     eax,byte 16
+        add     edx,byte 16
+        dec     ecx
+        jnz     .lbl4
+.ret2
+endproc
+
+
+proc    scalar04_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar08_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar12_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+32]
+        pmov    mm3,qword [eax+40]
+        pfmul   mm2,qword [edx+32]
+        pfmul   mm3,qword [edx+40]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar16_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+32]
+        pmov    mm3,qword [eax+40]
+        pfmul   mm2,qword [edx+32]
+        pfmul   mm3,qword [edx+40]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+48]
+        pmov    mm3,qword [eax+56]
+        pfmul   mm2,qword [edx+48]
+        pfmul   mm3,qword [edx+56]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar20_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+32]
+        pmov    mm3,qword [eax+40]
+        pfmul   mm2,qword [edx+32]
+        pfmul   mm3,qword [edx+40]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+48]
+        pmov    mm3,qword [eax+56]
+        pfmul   mm2,qword [edx+48]
+        pfmul   mm3,qword [edx+56]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+64]
+        pmov    mm3,qword [eax+72]
+        pfmul   mm2,qword [edx+64]
+        pfmul   mm3,qword [edx+72]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar24_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+32]
+        pmov    mm3,qword [eax+40]
+        pfmul   mm2,qword [edx+32]
+        pfmul   mm3,qword [edx+40]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+48]
+        pmov    mm3,qword [eax+56]
+        pfmul   mm2,qword [edx+48]
+        pfmul   mm3,qword [edx+56]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+64]
+        pmov    mm3,qword [eax+72]
+        pfmul   mm2,qword [edx+64]
+        pfmul   mm3,qword [edx+72]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+80]
+        pmov    mm3,qword [eax+88]
+        pfmul   mm2,qword [edx+80]
+        pfmul   mm3,qword [edx+88]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+proc    scalar32_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+
+        pmov    mm2,qword [eax+16]
+        pmov    mm3,qword [eax+24]
+        pfmul   mm2,qword [edx+16]
+        pfmul   mm3,qword [edx+24]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+32]
+        pmov    mm3,qword [eax+40]
+        pfmul   mm2,qword [edx+32]
+        pfmul   mm3,qword [edx+40]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+48]
+        pmov    mm3,qword [eax+56]
+        pfmul   mm2,qword [edx+48]
+        pfmul   mm3,qword [edx+56]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+64]
+        pmov    mm3,qword [eax+72]
+        pfmul   mm2,qword [edx+64]
+        pfmul   mm3,qword [edx+72]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+80]
+        pmov    mm3,qword [eax+88]
+        pfmul   mm2,qword [edx+80]
+        pfmul   mm3,qword [edx+88]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+96]
+        pmov    mm3,qword [eax+104]
+        pfmul   mm2,qword [edx+96]
+        pfmul   mm3,qword [edx+104]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pmov    mm2,qword [eax+112]
+        pmov    mm3,qword [eax+120]
+        pfmul   mm2,qword [edx+112]
+        pfmul   mm3,qword [edx+120]
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+
+        pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar4n_float32_3DNow
+%$p     arg     4
+%$q     arg     4
+%$len   arg     4
+
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+        mov     ecx,[sp(%$len)]
+
+        pmov    mm0,qword [eax]
+        pmov    mm1,qword [eax+8]
+        pfmul   mm0,qword [edx]
+        pfmul   mm1,qword [edx+8]
+        dec     ecx
+        jz      .ret4
+        
+        add     eax,byte 16
+        add     edx,byte 16
+.lbl4:  
+        pmov    mm2,qword [eax]
+        pmov    mm3,qword [eax+8]
+        pfmul   mm2,qword [edx]
+        pfmul   mm3,qword [edx+8]
+        add     eax,byte 16
+        add     edx,byte 16
+        pfadd   mm0,mm2
+        pfadd   mm1,mm3
+        dec     ecx
+        jnz     .lbl4
+
+.ret4:  pfadd   mm0,mm1
+        pmov    qword [sp(%$p)],mm0
+        femms
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar1n_float32_3DNow
+        jmp     scalar24_float32_i387
+endproc
+
+
+proc    scalar04_float32_SIMD
+        jmp     scalar04_float32_i387
+endproc
+
+
+proc    scalar08_float32_SIMD
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        movups  xmm0, [eax]
+        movups  xmm1, [eax+16]
+        mulps   xmm0, [edx]
+        mulps   xmm1, [edx+16]
+
+        addps   xmm0,xmm1
+        sub     esp,16
+        movups  [esp],xmm0
+        fld     dword [esp+ 0]
+        fadd    dword [esp+ 4]
+        fadd    dword [esp+ 8]
+        fadd    dword [esp+12]
+        add     esp,16
+endproc
+
+
+proc    scalar12_float32_SIMD
+        jmp     scalar12_float32_i387
+endproc
+
+
+proc    scalar16_float32_SIMD
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        movups  xmm0, [eax]
+        movups  xmm1, [eax+16]
+        mulps   xmm0, [edx]
+        mulps   xmm1, [edx+16]
+
+        movups  xmm2, [eax+32]
+        movups  xmm3, [eax+48]
+        mulps   xmm2, [edx+32]
+        mulps   xmm3, [edx+48]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        addps   xmm0,xmm1
+        sub     esp,16
+        movups  [esp],xmm0
+        fld     dword [esp+ 0]
+        fadd    dword [esp+ 4]
+        fadd    dword [esp+ 8]
+        fadd    dword [esp+12]
+        add     esp,16
+endproc
+
+
+proc    scalar20_float32_SIMD
+        jmp     scalar20_float32_i387
+endproc
+
+
+proc    scalar24_float32_SIMD
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        movups  xmm0, [eax]
+        movups  xmm1, [eax+16]
+        mulps   xmm0, [edx]
+        mulps   xmm1, [edx+16]
+
+        movups  xmm2, [eax+32]
+        movups  xmm3, [eax+48]
+        mulps   xmm2, [edx+32]
+        mulps   xmm3, [edx+48]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        movups  xmm2, [eax+64]
+        movups  xmm3, [eax+80]
+        mulps   xmm2, [edx+64]
+        mulps   xmm3, [edx+80]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        addps   xmm0,xmm1
+        sub     esp,16
+        movups  [esp],xmm0
+        fld     dword [esp+ 0]
+        fadd    dword [esp+ 4]
+        fadd    dword [esp+ 8]
+        fadd    dword [esp+12]
+        add     esp,16
+endproc
+
+
+proc    scalar32_float32_SIMD
+%$p     arg     4
+%$q     arg     4
+        mov     eax,[sp(%$p)]
+        mov     edx,[sp(%$q)]
+
+        movups  xmm0, [eax]
+        movups  xmm1, [eax+16]
+        mulps   xmm0, [edx]
+        mulps   xmm1, [edx+16]
+
+        movups  xmm2, [eax+32]
+        movups  xmm3, [eax+48]
+        mulps   xmm2, [edx+32]
+        mulps   xmm3, [edx+48]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        movups  xmm2, [eax+64]
+        movups  xmm3, [eax+80]
+        mulps   xmm2, [edx+64]
+        mulps   xmm3, [edx+80]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        movups  xmm2, [eax+96]
+        movups  xmm3, [eax+112]
+        mulps   xmm2, [edx+96]
+        mulps   xmm3, [edx+112]
+        addps   xmm0,xmm2
+        addps   xmm1,xmm3
+
+        addps   xmm0,xmm1
+
+        ;sub     esp,16
+        ;movups  [esp],xmm0
+        ;fld     dword [esp+ 0]
+        ;fadd    dword [esp+ 4]
+        ;fadd    dword [esp+ 8]
+        ;fadd    dword [esp+12]
+        ;add     esp,16
+         
+         movhlps xmm1,xmm0
+         addps   xmm0,xmm1
+         movlps  [sp(%$p)],xmm0
+        fld     dword [sp(%$p)]
+        fadd    dword [sp(%$p)+4]
+endproc
+
+
+proc    scalar4n_float32_SIMD
+        jmp     scalar4n_float32_i387
+endproc
+
+
+proc    scalar1n_float32_SIMD
+        jmp     scalar1n_float32_i387
+endproc
+
+; end of scalar.nas
diff --git a/lame/libmp3lame/id3tag.c b/lame/libmp3lame/id3tag.c
new file mode 100644 (file)
index 0000000..ac48510
--- /dev/null
@@ -0,0 +1,1926 @@
+/*
+ * id3tag.c -- Write ID3 version 1 and 2 tags.
+ *
+ * Copyright (C) 2000 Don Melton
+ * Copyright (C) 2011-2017 Robert Hegemann
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+/*
+ * HISTORY: This source file is part of LAME (see http://www.mp3dev.org)
+ * and was originally adapted by Conrad Sanderson <c.sanderson@me.gu.edu.au>
+ * from mp3info by Ricardo Cerqueira <rmc@rccn.net> to write only ID3 version 1
+ * tags.  Don Melton <don@blivet.com> COMPLETELY rewrote it to support version
+ * 2 tags and be more conformant to other standards while remaining flexible.
+ *
+ * NOTE: See http://id3.org/ for more information about ID3 tag formats.
+ */
+
+/* $Id: id3tag.c,v 1.80 2017/08/28 15:39:51 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef STDC_HEADERS
+# include <stddef.h>
+# include <stdlib.h>
+# include <string.h>
+# include <ctype.h>
+#else
+# ifndef HAVE_STRCHR
+#  define strchr index
+#  define strrchr rindex
+# endif
+char   *strchr(), *strrchr();
+# ifndef HAVE_MEMCPY
+#  define memcpy(d, s, n) bcopy ((s), (d), (n))
+# endif
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "id3tag.h"
+#include "lame_global_flags.h"
+#include "util.h"
+#include "bitstream.h"
+
+
+static const char *const genre_names[] = {
+    /*
+     * NOTE: The spelling of these genre names is identical to those found in
+     * Winamp and mp3info.
+     */
+    "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge",
+    "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B",
+    "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
+    "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop",
+    "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental",
+    "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "Alternative Rock",
+    "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop",
+    "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial",
+    "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy",
+    "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle",
+    "Native US", "Cabaret", "New Wave", "Psychedelic", "Rave",
+    "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz",
+    "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk",
+    "Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebob", "Latin",
+    "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock",
+    "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock",
+    "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech",
+    "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass",
+    "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba",
+    "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet",
+    "Punk Rock", "Drum Solo", "A Cappella", "Euro-House", "Dance Hall",
+    "Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie",
+    "BritPop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta",
+    "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian",
+    "Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop",
+    "SynthPop"
+};
+
+#define GENRE_NAME_COUNT \
+    ((int)(sizeof genre_names / sizeof (const char *const)))
+
+static const int genre_alpha_map[] = {
+    123, 34, 74, 73, 99, 20, 40, 26, 145, 90, 116, 41, 135, 85, 96, 138, 89, 0,
+    107, 132, 65, 88, 104, 102, 97, 136, 61, 141, 32, 1, 112, 128, 57, 140, 2,
+    139, 58, 3, 125, 50, 22, 4, 55, 127, 122, 120, 98, 52, 48, 54, 124, 25, 84,
+    80, 115, 81, 119, 5, 30, 36, 59, 126, 38, 49, 91, 6, 129, 79, 137, 7, 35,
+    100, 131, 19, 33, 46, 47, 8, 29, 146, 63, 86, 71, 45, 142, 9, 77, 82, 64,
+    133, 10, 66, 39, 11, 103, 12, 75, 134, 13, 53, 62, 109, 117, 23, 108, 92,
+    67, 93, 43, 121, 15, 68, 14, 16, 76, 87, 118, 17, 78, 143, 114, 110, 69, 21,
+    111, 95, 105, 42, 37, 24, 56, 44, 101, 83, 94, 106, 147, 113, 18, 51, 130,
+    144, 60, 70, 31, 72, 27, 28
+};
+
+#define GENRE_ALPHA_COUNT ((int)(sizeof genre_alpha_map / sizeof (int)))
+
+#define GENRE_INDEX_OTHER 12
+
+
+#define FRAME_ID(a, b, c, d) \
+    ( ((unsigned long)(a) << 24) \
+    | ((unsigned long)(b) << 16) \
+    | ((unsigned long)(c) <<  8) \
+    | ((unsigned long)(d) <<  0) )
+
+typedef enum UsualStringIDs { ID_TITLE = FRAME_ID('T', 'I', 'T', '2')
+        , ID_ARTIST = FRAME_ID('T', 'P', 'E', '1')
+        , ID_ALBUM = FRAME_ID('T', 'A', 'L', 'B')
+        , ID_GENRE = FRAME_ID('T', 'C', 'O', 'N')
+        , ID_ENCODER = FRAME_ID('T', 'S', 'S', 'E')
+        , ID_PLAYLENGTH = FRAME_ID('T', 'L', 'E', 'N')
+        , ID_COMMENT = FRAME_ID('C', 'O', 'M', 'M') /* full text string */
+} UsualStringIDs;
+
+typedef enum NumericStringIDs { ID_DATE = FRAME_ID('T', 'D', 'A', 'T') /* "ddMM" */
+        , ID_TIME = FRAME_ID('T', 'I', 'M', 'E') /* "hhmm" */
+        , ID_TPOS = FRAME_ID('T', 'P', 'O', 'S') /* '0'-'9' and '/' allowed */
+        , ID_TRACK = FRAME_ID('T', 'R', 'C', 'K') /* '0'-'9' and '/' allowed */
+        , ID_YEAR = FRAME_ID('T', 'Y', 'E', 'R') /* "yyyy" */
+} NumericStringIDs;
+
+typedef enum MiscIDs { ID_TXXX = FRAME_ID('T', 'X', 'X', 'X')
+        , ID_WXXX = FRAME_ID('W', 'X', 'X', 'X')
+        , ID_SYLT = FRAME_ID('S', 'Y', 'L', 'T')
+        , ID_APIC = FRAME_ID('A', 'P', 'I', 'C')
+        , ID_GEOB = FRAME_ID('G', 'E', 'O', 'B')
+        , ID_PCNT = FRAME_ID('P', 'C', 'N', 'T')
+        , ID_AENC = FRAME_ID('A', 'E', 'N', 'C')
+        , ID_LINK = FRAME_ID('L', 'I', 'N', 'K')
+        , ID_ENCR = FRAME_ID('E', 'N', 'C', 'R')
+        , ID_GRID = FRAME_ID('G', 'R', 'I', 'D')
+        , ID_PRIV = FRAME_ID('P', 'R', 'I', 'V')
+        , ID_USLT = FRAME_ID('U', 'S', 'L', 'T') /* full text string */
+        , ID_USER = FRAME_ID('U', 'S', 'E', 'R') /* full text string */
+        , ID_PCST = FRAME_ID('P', 'C', 'S', 'T') /* iTunes Podcast indicator, only presence important */
+        , ID_WFED = FRAME_ID('W', 'F', 'E', 'D') /* iTunes Podcast URL as TEXT FRAME !!! violates standard */
+} MiscIDs;
+
+
+static int
+frame_id_matches(int id, int mask)
+{
+    int     result = 0, i, window = 0xff;
+    for (i = 0; i < 4; ++i, window <<= 8) {
+        int const mw = (mask & window);
+        int const iw = (id & window);
+        if (mw != 0 && mw != iw) {
+            result |= iw;
+        }
+    }
+    return result;
+}
+
+static int
+isFrameIdMatching(int id, int mask)
+{
+    return frame_id_matches(id, mask) == 0 ? 1 : 0;
+}
+
+static int
+test_tag_spec_flags(lame_internal_flags const *gfc, unsigned int tst)
+{
+    return (gfc->tag_spec.flags & tst) != 0u ? 1 : 0;
+}
+
+#if 0
+static void
+debug_tag_spec_flags(lame_internal_flags * gfc, const char* info)
+{
+    MSGF(gfc, "%s\n", info);
+    MSGF(gfc, "CHANGED_FLAG  : %d\n", test_tag_spec_flags(gfc, CHANGED_FLAG )); 
+    MSGF(gfc, "ADD_V2_FLAG   : %d\n", test_tag_spec_flags(gfc, ADD_V2_FLAG  )); 
+    MSGF(gfc, "V1_ONLY_FLAG  : %d\n", test_tag_spec_flags(gfc, V1_ONLY_FLAG )); 
+    MSGF(gfc, "V2_ONLY_FLAG  : %d\n", test_tag_spec_flags(gfc, V2_ONLY_FLAG )); 
+    MSGF(gfc, "SPACE_V1_FLAG : %d\n", test_tag_spec_flags(gfc, SPACE_V1_FLAG)); 
+    MSGF(gfc, "PAD_V2_FLAG   : %d\n", test_tag_spec_flags(gfc, PAD_V2_FLAG  )); 
+}
+#endif
+
+static int
+is_lame_internal_flags_null(lame_t gfp)
+{
+    return (gfp && gfp->internal_flags) ? 0 : 1;
+}
+
+static int
+id3v2_add_ucs2_lng(lame_t gfp, uint32_t frame_id, unsigned short const *desc, unsigned short const *text);
+static int
+id3v2_add_latin1_lng(lame_t gfp, uint32_t frame_id, char const *desc, char const *text);
+
+
+static void
+copyV1ToV2(lame_t gfp, int frame_id, char const *s)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc != 0) {
+        unsigned int flags = gfc->tag_spec.flags;
+        id3v2_add_latin1_lng(gfp, frame_id, 0, s);
+        gfc->tag_spec.flags = flags;
+#if 0
+        debug_tag_spec_flags(gfc, "copyV1ToV2");
+#endif
+    }
+}
+
+
+static void
+id3v2AddLameVersion(lame_t gfp)
+{
+    char    buffer[1024];
+    const char *b = get_lame_os_bitness();
+    const char *v = get_lame_version();
+    const char *u = get_lame_url();
+    const size_t lenb = strlen(b);
+
+    if (lenb > 0) {
+        sprintf(buffer, "LAME %s version %s (%s)", b, v, u);
+    }
+    else {
+        sprintf(buffer, "LAME version %s (%s)", v, u);
+    }
+    copyV1ToV2(gfp, ID_ENCODER, buffer);
+}
+
+static void
+id3v2AddAudioDuration(lame_t gfp, double ms)
+{
+    SessionConfig_t const *const cfg = &gfp->internal_flags->cfg; /* caller checked pointers */
+    char    buffer[1024];
+    double const max_ulong = MAX_U_32_NUM;
+    unsigned long playlength_ms;
+
+    ms *= 1000;
+    ms /= cfg->samplerate_in;
+    if (ms > max_ulong) {
+        playlength_ms = max_ulong;
+    }
+    else if (ms < 0) {
+        playlength_ms = 0;
+    }
+    else {
+        playlength_ms = ms;
+    }
+    sprintf(buffer, "%lu", playlength_ms);
+    copyV1ToV2(gfp, ID_PLAYLENGTH, buffer);
+}
+
+void
+id3tag_genre_list(void (*handler) (int, const char *, void *), void *cookie)
+{
+    if (handler) {
+        int     i;
+        for (i = 0; i < GENRE_NAME_COUNT; ++i) {
+            if (i < GENRE_ALPHA_COUNT) {
+                int     j = genre_alpha_map[i];
+                handler(j, genre_names[j], cookie);
+            }
+        }
+    }
+}
+
+#define GENRE_NUM_UNKNOWN 255
+
+
+
+void
+id3tag_init(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    free_id3tag(gfc);
+    memset(&gfc->tag_spec, 0, sizeof gfc->tag_spec);
+    gfc->tag_spec.genre_id3v1 = GENRE_NUM_UNKNOWN;
+    gfc->tag_spec.padding_size = 128;
+    id3v2AddLameVersion(gfp);
+}
+
+
+
+void
+id3tag_add_v2(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;
+    gfc->tag_spec.flags |= ADD_V2_FLAG;
+}
+
+void
+id3tag_v1_only(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    gfc->tag_spec.flags &= ~(ADD_V2_FLAG | V2_ONLY_FLAG);
+    gfc->tag_spec.flags |= V1_ONLY_FLAG;
+}
+
+void
+id3tag_v2_only(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;
+    gfc->tag_spec.flags |= V2_ONLY_FLAG;
+}
+
+void
+id3tag_space_v1(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    gfc->tag_spec.flags &= ~V2_ONLY_FLAG;
+    gfc->tag_spec.flags |= SPACE_V1_FLAG;
+}
+
+void
+id3tag_pad_v2(lame_t gfp)
+{
+    id3tag_set_pad(gfp, 128);
+}
+
+void
+id3tag_set_pad(lame_t gfp, size_t n)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;
+    gfc->tag_spec.flags |= PAD_V2_FLAG;
+    gfc->tag_spec.flags |= ADD_V2_FLAG;
+    gfc->tag_spec.padding_size = (unsigned int)n;
+}
+
+static int
+hasUcs2ByteOrderMarker(unsigned short bom)
+{
+    if (bom == 0xFFFEu || bom == 0xFEFFu) {
+        return 1;
+    }
+    return 0;
+}
+
+
+static unsigned short
+swap_bytes(unsigned short w)
+{
+    return (0xff00u & (w << 8)) | (0x00ffu & (w >> 8));
+}
+
+
+static unsigned short
+toLittleEndian(unsigned short bom, unsigned short c)
+{
+    if (bom == 0xFFFEu) {
+        return swap_bytes(c);
+    }
+    return c;
+}
+
+static unsigned short
+fromLatin1Char(const unsigned short* s, unsigned short c)
+{
+    if (s[0] == 0xFFFEu) {
+        return swap_bytes(c);
+    }
+    return c;
+}
+
+
+static  size_t
+local_strdup(char **dst, const char *src)
+{
+    if (dst == 0) {
+        return 0;
+    }
+    free(*dst);
+    *dst = 0;
+    if (src != 0) {
+        size_t  n;
+        for (n = 0; src[n] != 0; ++n) { /* calc src string length */
+        }
+        if (n > 0) {    /* string length without zero termination */
+            assert(sizeof(*src) == sizeof(**dst));
+            *dst = lame_calloc(char, n + 1);
+            if (*dst != 0) {
+                memcpy(*dst, src, n * sizeof(**dst));
+                (*dst)[n] = 0;
+                return n;
+            }
+        }
+    }
+    return 0;
+}
+
+static  size_t
+local_ucs2_strdup(unsigned short **dst, unsigned short const *src)
+{
+    if (dst == 0) {
+        return 0;
+    }
+    free(*dst);         /* free old string pointer */
+    *dst = 0;
+    if (src != 0) {
+        size_t  n;
+        for (n = 0; src[n] != 0; ++n) { /* calc src string length */
+        }
+        if (n > 0) {    /* string length without zero termination */
+            assert(sizeof(*src) >= 2);
+            assert(sizeof(*src) == sizeof(**dst));
+            *dst = lame_calloc(unsigned short, n + 1);
+            if (*dst != 0) {
+                memcpy(*dst, src, n * sizeof(**dst));
+                (*dst)[n] = 0;
+                return n;
+            }
+        }
+    }
+    return 0;
+}
+
+
+static  size_t
+local_ucs2_strlen(unsigned short const *s)
+{
+    size_t  n = 0;
+    if (s != 0) {
+        while (*s++) {
+            ++n;
+        }
+    }
+    return n;
+}
+
+
+static size_t
+local_ucs2_substr(unsigned short** dst, unsigned short const* src, size_t start, size_t end)
+{
+    size_t const len = 1 + 1 + ((start < end) ? (end - start) : 0);
+    size_t n = 0;
+    unsigned short *ptr = lame_calloc(unsigned short, len);
+    *dst = ptr;
+    if (ptr == 0 || src == 0) {
+        return 0;
+    }
+    if (hasUcs2ByteOrderMarker(src[0])) {
+        ptr[n++] = src[0];
+        if (start == 0) {
+            ++start;
+        }
+    }
+    while (start < end) {
+        ptr[n++] = src[start++];
+    }
+    ptr[n] = 0;
+    return n;
+}
+
+static int
+local_ucs2_pos(unsigned short const* str, unsigned short c)
+{
+    int     i;
+    for (i = 0; str != 0 && str[i] != 0; ++i) {
+        if (str[i] == c) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+static int
+local_char_pos(char const* str, char c)
+{
+    int     i;
+    for (i = 0; str != 0 && str[i] != 0; ++i) {
+        if (str[i] == c) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+static int
+maybeLatin1(unsigned short const* text)
+{
+    if (text) {
+        unsigned short bom = *text++;
+        while (*text) {
+            unsigned short c = toLittleEndian(bom, *text++);
+            if (c > 0x00fe) return 0;
+        }
+    }
+    return 1;
+}
+
+static int searchGenre(char const* genre);
+static int sloppySearchGenre(char const* genre);
+
+static int
+lookupGenre(char const* genre)
+{
+    char   *str;
+    int     num = strtol(genre, &str, 10);
+    /* is the input a string or a valid number? */
+    if (*str) {
+        num = searchGenre(genre);
+        if (num == GENRE_NAME_COUNT) {
+            num = sloppySearchGenre(genre);
+        }
+        if (num == GENRE_NAME_COUNT) {
+            return -2; /* no common genre text found */
+        }
+    }
+    else {
+        if ((num < 0) || (num >= GENRE_NAME_COUNT)) {
+            return -1; /* number unknown */
+        }
+    }
+    return num;
+}
+
+static unsigned char *
+writeLoBytes(unsigned char *frame, unsigned short const *str, size_t n);
+
+static char*
+local_strdup_utf16_to_latin1(unsigned short const* utf16)
+{
+    size_t  len = local_ucs2_strlen(utf16);
+    unsigned char* latin1 = lame_calloc(unsigned char, len+1);
+    writeLoBytes(latin1, utf16, len);
+    return (char*)latin1;
+}
+
+
+static int
+id3tag_set_genre_utf16(lame_t gfp, unsigned short const* text)
+{
+    lame_internal_flags* gfc = gfp->internal_flags;
+    int   ret;
+    if (text == 0) {
+        return -3;
+    }
+    if (!hasUcs2ByteOrderMarker(text[0])) {
+        return -3;
+    }
+    if (maybeLatin1(text)) {
+        char*   latin1 = local_strdup_utf16_to_latin1(text);
+        int     num = lookupGenre(latin1);
+        free(latin1);
+        if (num == -1) return -1; /* number out of range */
+        if (num >= 0) {           /* common genre found  */
+            gfc->tag_spec.flags |= CHANGED_FLAG;
+            gfc->tag_spec.genre_id3v1 = num;
+            copyV1ToV2(gfp, ID_GENRE, genre_names[num]);
+            return 0;
+        }
+    }
+    ret = id3v2_add_ucs2_lng(gfp, ID_GENRE, 0, text);
+    if (ret == 0) {
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        gfc->tag_spec.genre_id3v1 = GENRE_INDEX_OTHER;
+    }
+    return ret;
+}
+
+/*
+Some existing options for ID3 tag can be specified by --tv option
+as follows.
+--tt <value>, --tv TIT2=value
+--ta <value>, --tv TPE1=value
+--tl <value>, --tv TALB=value
+--ty <value>, --tv TYER=value
+--tn <value>, --tv TRCK=value
+--tg <value>, --tv TCON=value
+(although some are not exactly same)*/
+
+int
+id3tag_set_albumart(lame_t gfp, const char *image, size_t size)
+{
+    int     mimetype = MIMETYPE_NONE;
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    gfc = gfp->internal_flags;
+
+    if (image != 0) {
+        unsigned char const *data = (unsigned char const *) image;
+        /* determine MIME type from the actual image data */
+        if (2 < size && data[0] == 0xFF && data[1] == 0xD8) {
+            mimetype = MIMETYPE_JPEG;
+        }
+        else if (4 < size && data[0] == 0x89 && strncmp((const char *) &data[1], "PNG", 3) == 0) {
+            mimetype = MIMETYPE_PNG;
+        }
+        else if (4 < size && strncmp((const char *) data, "GIF8", 4) == 0) {
+            mimetype = MIMETYPE_GIF;
+        }
+        else {
+            return -1;
+        }
+    }
+    if (gfc->tag_spec.albumart != 0) {
+        free(gfc->tag_spec.albumart);
+        gfc->tag_spec.albumart = 0;
+        gfc->tag_spec.albumart_size = 0;
+        gfc->tag_spec.albumart_mimetype = MIMETYPE_NONE;
+    }
+    if (size < 1 || mimetype == MIMETYPE_NONE) {
+        return 0;
+    }
+    gfc->tag_spec.albumart = lame_calloc(unsigned char, size);
+    if (gfc->tag_spec.albumart != 0) {
+        memcpy(gfc->tag_spec.albumart, image, size);
+        gfc->tag_spec.albumart_size = (unsigned int)size;
+        gfc->tag_spec.albumart_mimetype = mimetype;
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        id3tag_add_v2(gfp);
+    }
+    return 0;
+}
+
+static unsigned char *
+set_4_byte_value(unsigned char *bytes, uint32_t value)
+{
+    int     i;
+    for (i = 3; i >= 0; --i) {
+        bytes[i] = value & 0xffUL;
+        value >>= 8;
+    }
+    return bytes + 4;
+}
+
+static uint32_t
+toID3v2TagId(char const *s)
+{
+    unsigned int i, x = 0;
+    if (s == 0) {
+        return 0;
+    }
+    for (i = 0; i < 4 && s[i] != 0; ++i) {
+        char const c = s[i];
+        unsigned int const u = 0x0ff & c;
+        x <<= 8;
+        x |= u;
+        if (c < 'A' || 'Z' < c) {
+            if (c < '0' || '9' < c) {
+                return 0;
+            }
+        }
+    }
+    return x;
+}
+
+static uint32_t
+toID3v2TagId_ucs2(unsigned short const *s)
+{
+    unsigned int i, x = 0;
+    unsigned short bom = 0;
+    if (s == 0) {
+        return 0;
+    }
+    bom = s[0];
+    if (hasUcs2ByteOrderMarker(bom)) {
+        ++s;
+    }
+    for (i = 0; i < 4 && s[i] != 0; ++i) {
+        unsigned short const c = toLittleEndian(bom, s[i]);
+        if (c < 'A' || 'Z' < c) {
+            if (c < '0' || '9' < c) {
+                return 0;
+            }
+        }
+        x <<= 8;
+        x |= c;
+    }
+    return x;
+}
+
+#if 0
+static int
+isNumericString(uint32_t frame_id)
+{
+    switch (frame_id) {
+    case ID_DATE:
+    case ID_TIME:
+    case ID_TPOS:
+    case ID_TRACK:
+    case ID_YEAR:
+        return 1;
+    }
+    return 0;
+}
+#endif
+
+static int
+isMultiFrame(uint32_t frame_id)
+{
+    switch (frame_id) {
+    case ID_TXXX:
+    case ID_WXXX:
+    case ID_COMMENT:
+    case ID_SYLT:
+    case ID_APIC:
+    case ID_GEOB:
+    case ID_PCNT:
+    case ID_AENC:
+    case ID_LINK:
+    case ID_ENCR:
+    case ID_GRID:
+    case ID_PRIV:
+        return 1;
+    }
+    return 0;
+}
+
+#if 0
+static int
+isFullTextString(int frame_id)
+{
+    switch (frame_id) {
+    case ID_VSLT:
+    case ID_COMMENT:
+        return 1;
+    }
+    return 0;
+}
+#endif
+
+static FrameDataNode *
+findNode(id3tag_spec const *tag, uint32_t frame_id, FrameDataNode const *last)
+{
+    FrameDataNode *node = last ? last->nxt : tag->v2_head;
+    while (node != 0) {
+        if (node->fid == frame_id) {
+            return node;
+        }
+        node = node->nxt;
+    }
+    return 0;
+}
+
+static void
+appendNode(id3tag_spec * tag, FrameDataNode * node)
+{
+    if (tag->v2_tail == 0 || tag->v2_head == 0) {
+        tag->v2_head = node;
+        tag->v2_tail = node;
+    }
+    else {
+        tag->v2_tail->nxt = node;
+        tag->v2_tail = node;
+    }
+}
+
+static void
+setLang(char *dst, char const *src)
+{
+    int     i;
+    if (src == 0 || src[0] == 0) {
+        dst[0] = 'e';
+        dst[1] = 'n';
+        dst[2] = 'g';
+    }
+    else {
+        for (i = 0; i < 3 && src && *src; ++i) {
+            dst[i] = src[i];
+        }
+        for (; i < 3; ++i) {
+            dst[i] = ' ';
+        }
+    }
+}
+
+static int
+isSameLang(char const *l1, char const *l2)
+{
+    char    d[3];
+    int     i;
+    setLang(d, l2);
+    for (i = 0; i < 3; ++i) {
+        char    a = tolower(l1[i]);
+        char    b = tolower(d[i]);
+        if (a < ' ')
+            a = ' ';
+        if (b < ' ')
+            b = ' ';
+        if (a != b) {
+            return 0;
+        }
+    }
+    return 1;
+}
+
+static int
+isSameDescriptor(FrameDataNode const *node, char const *dsc)
+{
+    size_t  i;
+    if (node->dsc.enc == 1 && node->dsc.dim > 0) {
+        return 0;
+    }
+    for (i = 0; i < node->dsc.dim; ++i) {
+        if (!dsc || node->dsc.ptr.l[i] != dsc[i]) {
+            return 0;
+        }
+    }
+    return 1;
+}
+
+static int
+isSameDescriptorUcs2(FrameDataNode const *node, unsigned short const *dsc)
+{
+    size_t  i;
+    if (node->dsc.enc != 1 && node->dsc.dim > 0) {
+        return 0;
+    }
+    for (i = 0; i < node->dsc.dim; ++i) {
+        if (!dsc || node->dsc.ptr.u[i] != dsc[i]) {
+            return 0;
+        }
+    }
+    return 1;
+}
+
+static int
+id3v2_add_ucs2(lame_t gfp, uint32_t frame_id, char const *lng, unsigned short const *desc, unsigned short const *text)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc != 0) {
+        FrameDataNode *node = findNode(&gfc->tag_spec, frame_id, 0);
+        char lang[4];
+        setLang(lang, lng);
+        if (isMultiFrame(frame_id)) {
+            while (node) {
+                if (isSameLang(node->lng, lang)) {
+                    if (isSameDescriptorUcs2(node, desc)) {
+                        break;
+                    }
+                }
+                node = findNode(&gfc->tag_spec, frame_id, node);
+            }
+        }
+        if (node == 0) {
+            node = lame_calloc(FrameDataNode, 1);
+            if (node == 0) {
+                return -254; /* memory problem */
+            }
+            appendNode(&gfc->tag_spec, node);
+        }
+        node->fid = frame_id;
+        setLang(node->lng, lang);
+        node->dsc.dim = local_ucs2_strdup(&node->dsc.ptr.u, desc);
+        node->dsc.enc = 1;
+        node->txt.dim = local_ucs2_strdup(&node->txt.ptr.u, text);
+        node->txt.enc = 1;
+        gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);
+        return 0;
+    }
+    return -255;
+}
+
+static int
+id3v2_add_latin1(lame_t gfp, uint32_t frame_id, char const *lng, char const *desc, char const *text)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc != 0) {
+        FrameDataNode *node = findNode(&gfc->tag_spec, frame_id, 0);
+        char lang[4];
+        setLang(lang, lng);
+        if (isMultiFrame(frame_id)) {
+            while (node) {
+                if (isSameLang(node->lng, lang)) {
+                    if (isSameDescriptor(node, desc)) {
+                        break;
+                    }
+                }
+                node = findNode(&gfc->tag_spec, frame_id, node);
+            }
+        }
+        if (node == 0) {
+            node = lame_calloc(FrameDataNode, 1);
+            if (node == 0) {
+                return -254; /* memory problem */
+            }
+            appendNode(&gfc->tag_spec, node);
+        }
+        node->fid = frame_id;
+        setLang(node->lng, lang);
+        node->dsc.dim = local_strdup(&node->dsc.ptr.l, desc);
+        node->dsc.enc = 0;
+        node->txt.dim = local_strdup(&node->txt.ptr.l, text);
+        node->txt.enc = 0;
+        gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);
+        return 0;
+    }
+    return -255;
+}
+
+static char const*
+id3v2_get_language(lame_t gfp)
+{
+    lame_internal_flags const* gfc = gfp ? gfp->internal_flags : 0;
+    if (gfc) return gfc->tag_spec.language;
+    return 0;
+}
+
+static int
+id3v2_add_ucs2_lng(lame_t gfp, uint32_t frame_id, unsigned short const *desc, unsigned short const *text)
+{
+    char const* lang = id3v2_get_language(gfp);
+    return id3v2_add_ucs2(gfp, frame_id, lang, desc, text);
+}
+
+static int
+id3v2_add_latin1_lng(lame_t gfp, uint32_t frame_id, char const *desc, char const *text)
+{
+    char const* lang = id3v2_get_language(gfp);
+    return id3v2_add_latin1(gfp, frame_id, lang, desc, text);
+}
+
+static int
+id3tag_set_userinfo_latin1(lame_t gfp, uint32_t id, char const *fieldvalue)
+{
+    char const separator = '=';
+    int     rc = -7;
+    int     a = local_char_pos(fieldvalue, separator);
+    if (a >= 0) {
+        char*   dup = 0;
+        local_strdup(&dup, fieldvalue);
+        dup[a] = 0;
+        rc = id3v2_add_latin1_lng(gfp, id, dup, dup+a+1);
+        free(dup);
+    }
+    return rc;
+}
+
+static int
+id3tag_set_userinfo_ucs2(lame_t gfp, uint32_t id, unsigned short const *fieldvalue)
+{
+    unsigned short const separator = fromLatin1Char(fieldvalue,'=');
+    int     rc = -7;
+    size_t  b = local_ucs2_strlen(fieldvalue);
+    int     a = local_ucs2_pos(fieldvalue, separator);
+    if (a >= 0) {
+        unsigned short* dsc = 0, *val = 0;
+        local_ucs2_substr(&dsc, fieldvalue, 0, a);
+        local_ucs2_substr(&val, fieldvalue, a+1, b);
+        rc = id3v2_add_ucs2_lng(gfp, id, dsc, val);
+        free(dsc);
+        free(val);
+    }
+    return rc;
+}
+
+int
+id3tag_set_textinfo_utf16(lame_t gfp, char const *id, unsigned short const *text)
+{
+    uint32_t const frame_id = toID3v2TagId(id);
+    if (frame_id == 0) {
+        return -1;
+    }
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    if (text == 0) {
+        return 0;
+    }
+    if (!hasUcs2ByteOrderMarker(text[0])) {
+        return -3;  /* BOM missing */
+    }
+    if (frame_id == ID_TXXX || frame_id == ID_WXXX || frame_id == ID_COMMENT) {
+        return id3tag_set_userinfo_ucs2(gfp, frame_id, text);
+    }
+    if (frame_id == ID_GENRE) {
+        return id3tag_set_genre_utf16(gfp, text);
+    }
+    if (frame_id == ID_PCST) {
+        return id3v2_add_ucs2_lng(gfp, frame_id, 0, text);
+    }
+    if (frame_id == ID_USER) {
+        return id3v2_add_ucs2_lng(gfp, frame_id, text, 0);
+    }
+    if (frame_id == ID_WFED) {
+        return id3v2_add_ucs2_lng(gfp, frame_id, text, 0); /* iTunes expects WFED to be a text frame */
+    }
+    if (isFrameIdMatching(frame_id, FRAME_ID('T', 0, 0, 0))
+      ||isFrameIdMatching(frame_id, FRAME_ID('W', 0, 0, 0))) {
+#if 0
+        if (isNumericString(frame_id)) {
+            return -2;  /* must be Latin-1 encoded */
+        }
+#endif
+        return id3v2_add_ucs2_lng(gfp, frame_id, 0, text);
+    }
+    return -255;        /* not supported by now */
+}
+
+extern int
+id3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text);
+
+int
+id3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text)
+{
+    return id3tag_set_textinfo_utf16(gfp, id, text);
+}
+
+int
+id3tag_set_textinfo_latin1(lame_t gfp, char const *id, char const *text)
+{
+    uint32_t const frame_id = toID3v2TagId(id);
+    if (frame_id == 0) {
+        return -1;
+    }
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    if (text == 0) {
+        return 0;
+    }
+    if (frame_id == ID_TXXX || frame_id == ID_WXXX || frame_id == ID_COMMENT) {
+        return id3tag_set_userinfo_latin1(gfp, frame_id, text);
+    }
+    if (frame_id == ID_GENRE) {
+        return id3tag_set_genre(gfp, text);
+    }
+    if (frame_id == ID_PCST) {
+        return id3v2_add_latin1_lng(gfp, frame_id, 0, text);
+    }
+    if (frame_id == ID_USER) {
+        return id3v2_add_latin1_lng(gfp, frame_id, text, 0);
+    }
+    if (frame_id == ID_WFED) {
+        return id3v2_add_latin1_lng(gfp, frame_id, text, 0); /* iTunes expects WFED to be a text frame */
+    }
+    if (isFrameIdMatching(frame_id, FRAME_ID('T', 0, 0, 0))
+      ||isFrameIdMatching(frame_id, FRAME_ID('W', 0, 0, 0))) {
+        return id3v2_add_latin1_lng(gfp, frame_id, 0, text);
+    }
+    return -255;        /* not supported by now */
+}
+
+
+int
+id3tag_set_comment_latin1(lame_t gfp, char const *lang, char const *desc, char const *text)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    return id3v2_add_latin1(gfp, ID_COMMENT, lang, desc, text);
+}
+
+
+int
+id3tag_set_comment_utf16(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    return id3v2_add_ucs2(gfp, ID_COMMENT, lang, desc, text);
+}
+
+extern int
+id3tag_set_comment_ucs2(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text);
+
+
+int
+id3tag_set_comment_ucs2(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    return id3tag_set_comment_utf16(gfp, lang, desc, text);
+}
+
+
+void
+id3tag_set_title(lame_t gfp, const char *title)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc && title && *title) {
+        local_strdup(&gfc->tag_spec.title, title);
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        copyV1ToV2(gfp, ID_TITLE, title);
+    }
+}
+
+void
+id3tag_set_artist(lame_t gfp, const char *artist)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc && artist && *artist) {
+        local_strdup(&gfc->tag_spec.artist, artist);
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        copyV1ToV2(gfp, ID_ARTIST, artist);
+    }
+}
+
+void
+id3tag_set_album(lame_t gfp, const char *album)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc && album && *album) {
+        local_strdup(&gfc->tag_spec.album, album);
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        copyV1ToV2(gfp, ID_ALBUM, album);
+    }
+}
+
+void
+id3tag_set_year(lame_t gfp, const char *year)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc && year && *year) {
+        int     num = atoi(year);
+        if (num < 0) {
+            num = 0;
+        }
+        /* limit a year to 4 digits so it fits in a version 1 tag */
+        if (num > 9999) {
+            num = 9999;
+        }
+        if (num) {
+            gfc->tag_spec.year = num;
+            gfc->tag_spec.flags |= CHANGED_FLAG;
+        }
+        copyV1ToV2(gfp, ID_YEAR, year);
+    }
+}
+
+void
+id3tag_set_comment(lame_t gfp, const char *comment)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    if (gfc && comment && *comment) {
+        local_strdup(&gfc->tag_spec.comment, comment);
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        {
+            uint32_t const flags = gfc->tag_spec.flags;
+            id3v2_add_latin1_lng(gfp, ID_COMMENT, "", comment);
+            gfc->tag_spec.flags = flags;
+        }
+    }
+}
+
+int
+id3tag_set_track(lame_t gfp, const char *track)
+{
+    char const *trackcount;
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    int     ret = 0;
+
+    if (gfc && track && *track) {
+        int     num = atoi(track);
+        /* check for valid ID3v1 track number range */
+        if (num < 1 || num > 255) {
+            num = 0;
+            ret = -1;   /* track number out of ID3v1 range, ignored for ID3v1 */
+            gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);
+        }
+        if (num) {
+            gfc->tag_spec.track_id3v1 = num;
+            gfc->tag_spec.flags |= CHANGED_FLAG;
+        }
+        /* Look for the total track count after a "/", same restrictions */
+        trackcount = strchr(track, '/');
+        if (trackcount && *trackcount) {
+            gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);
+        }
+        copyV1ToV2(gfp, ID_TRACK, track);
+    }
+    return ret;
+}
+
+/* would use real "strcasecmp" but it isn't portable */
+static int
+local_strcasecmp(const char *s1, const char *s2)
+{
+    unsigned char c1;
+    unsigned char c2;
+    do {
+        c1 = tolower(*s1);
+        c2 = tolower(*s2);
+        if (!c1) {
+            break;
+        }
+        ++s1;
+        ++s2;
+    } while (c1 == c2);
+    return c1 - c2;
+}
+
+
+static 
+const char* nextUpperAlpha(const char* p, char x)
+{
+    char c;
+    for(c = toupper(*p); *p != 0; c = toupper(*++p)) {
+        if ('A' <= c && c <= 'Z') {
+            if (c != x) {
+                return p;
+            }
+        }
+    }
+    return p;
+}
+
+
+static int
+sloppyCompared(const char* p, const char* q)
+{
+    char cp, cq;
+    p = nextUpperAlpha(p, 0);
+    q = nextUpperAlpha(q, 0);
+    cp = toupper(*p);
+    cq = toupper(*q);
+    while (cp == cq) {
+        if (cp == 0) {
+            return 1;
+        }
+        if (p[1] == '.') { /* some abbrevation */
+            while (*q && *q++ != ' ') {
+            }
+        }
+        p = nextUpperAlpha(p, cp);
+        q = nextUpperAlpha(q, cq);
+        cp = toupper(*p);
+        cq = toupper(*q);
+    }
+    return 0;
+}
+
+
+static int 
+sloppySearchGenre(const char *genre)
+{
+    int i;
+    for (i = 0; i < GENRE_NAME_COUNT; ++i) {
+        if (sloppyCompared(genre, genre_names[i])) {
+            return i;
+        }
+    }
+    return GENRE_NAME_COUNT;
+}
+
+
+static int
+searchGenre(const char* genre)
+{
+    int i;
+    for (i = 0; i < GENRE_NAME_COUNT; ++i) {
+        if (!local_strcasecmp(genre, genre_names[i])) {
+            return i;
+        }
+    }
+    return GENRE_NAME_COUNT;
+}
+
+
+int
+id3tag_set_genre(lame_t gfp, const char *genre)
+{
+    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;
+    int     ret = 0;
+    if (gfc && genre && *genre) {
+        int const num = lookupGenre(genre);
+        if (num == -1) return num;
+        gfc->tag_spec.flags |= CHANGED_FLAG;
+        if (num >= 0) {
+            gfc->tag_spec.genre_id3v1 = num;
+            genre = genre_names[num];
+        }
+        else {
+            gfc->tag_spec.genre_id3v1 = GENRE_INDEX_OTHER;
+            gfc->tag_spec.flags |= ADD_V2_FLAG;
+        }
+        copyV1ToV2(gfp, ID_GENRE, genre);
+    }
+    return ret;
+}
+
+
+static  size_t
+sizeOfNode(FrameDataNode const *node)
+{
+    size_t  n = 0;
+    if (node) {
+        n = 10;         /* header size */
+        n += 1;         /* text encoding flag */
+        switch (node->txt.enc) {
+        default:
+        case 0:
+            if (node->dsc.dim > 0) {
+                n += node->dsc.dim + 1;
+            }
+            n += node->txt.dim;
+            break;
+        case 1:
+            if (node->dsc.dim > 0) {
+                n += (node->dsc.dim+1) * 2;
+            }
+            n += node->txt.dim * 2;
+            break;
+        }
+    }
+    return n;
+}
+
+static  size_t
+sizeOfCommentNode(FrameDataNode const *node)
+{
+    size_t  n = 0;
+    if (node) {
+        n = 10;         /* header size */
+        n += 1;         /* text encoding flag */
+        n += 3;         /* language */
+        switch (node->dsc.enc) {
+        default:
+        case 0:
+            n += 1 + node->dsc.dim;
+            break;
+        case 1:
+            n += 2 + node->dsc.dim * 2;
+            break;
+        }
+        switch (node->txt.enc) {
+        default:
+        case 0:
+            n += node->txt.dim;
+            break;
+        case 1:
+            n += node->txt.dim * 2;
+            break;
+        }
+    }
+    return n;
+}
+
+static size_t
+sizeOfWxxxNode(FrameDataNode const *node)
+{
+    size_t  n = 0;
+    if (node) {
+        n = 10;         /* header size */
+        if (node->dsc.dim > 0) {
+            n += 1;         /* text encoding flag */
+            switch (node->dsc.enc) {
+            default:
+            case 0:
+                n += 1 + node->dsc.dim;
+                break;
+            case 1:
+                n += 2 + node->dsc.dim * 2;
+                break;
+            }
+        }
+        if (node->txt.dim > 0) {
+            switch (node->txt.enc) {
+            default:
+            case 0:
+                n += node->txt.dim;
+                break;
+            case 1:
+                n += node->txt.dim - 1; /* UCS2 -> Latin1, skip BOM */
+                break;
+            }
+        }
+    }
+    return n;
+}
+
+static unsigned char *
+writeChars(unsigned char *frame, char const *str, size_t n)
+{
+    while (n--) {
+        *frame++ = *str++;
+    }
+    return frame;
+}
+
+static unsigned char *
+writeUcs2s(unsigned char *frame, unsigned short const *str, size_t n)
+{
+    if (n > 0) {
+        unsigned short const bom = *str;
+        while (n--) {
+            unsigned short const c = toLittleEndian(bom, *str++);
+            *frame++ = 0x00ffu & c;
+            *frame++ = 0x00ffu & (c >> 8);
+        }
+    }
+    return frame;
+}
+
+static unsigned char *
+writeLoBytes(unsigned char *frame, unsigned short const *str, size_t n)
+{
+    if (n > 0) {
+        unsigned short const bom = *str;
+        if (hasUcs2ByteOrderMarker(bom)) {
+            str++; n--; /* skip BOM */
+        }
+        while (n--) {
+            unsigned short const c = toLittleEndian(bom, *str++);
+            if (c < 0x0020u || 0x00ffu < c) {
+                *frame++ = 0x0020; /* blank */
+            }
+            else {
+                *frame++ = c;
+            }
+        }
+    }
+    return frame;
+}
+
+static unsigned char *
+set_frame_comment(unsigned char *frame, FrameDataNode const *node)
+{
+    size_t const n = sizeOfCommentNode(node);
+    if (n > 10) {
+        frame = set_4_byte_value(frame, node->fid);
+        frame = set_4_byte_value(frame, (uint32_t) (n - 10));
+        /* clear 2-byte header flags */
+        *frame++ = 0;
+        *frame++ = 0;
+        /* encoding descriptor byte */
+        *frame++ = node->txt.enc == 1 ? 1 : 0;
+        /* 3 bytes language */
+        *frame++ = node->lng[0];
+        *frame++ = node->lng[1];
+        *frame++ = node->lng[2];
+        /* descriptor with zero byte(s) separator */
+        if (node->dsc.enc != 1) {
+            frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);
+            *frame++ = 0;
+        }
+        else {
+            frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);
+            *frame++ = 0;
+            *frame++ = 0;
+        }
+        /* comment full text */
+        if (node->txt.enc != 1) {
+            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);
+        }
+        else {
+            frame = writeUcs2s(frame, node->txt.ptr.u, node->txt.dim);
+        }
+    }
+    return frame;
+}
+
+static unsigned char *
+set_frame_custom2(unsigned char *frame, FrameDataNode const *node)
+{
+    size_t const n = sizeOfNode(node);
+    if (n > 10) {
+        frame = set_4_byte_value(frame, node->fid);
+        frame = set_4_byte_value(frame, (unsigned long) (n - 10));
+        /* clear 2-byte header flags */
+        *frame++ = 0;
+        *frame++ = 0;
+        /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */
+        *frame++ = node->txt.enc == 1 ? 1 : 0;
+        if (node->dsc.dim > 0) {
+            if (node->dsc.enc != 1) {
+                frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);
+                *frame++ = 0;
+            }
+            else {
+                frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);
+                *frame++ = 0;
+                *frame++ = 0;
+            }
+        }
+        if (node->txt.enc != 1) {
+            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);
+        }
+        else {
+            frame = writeUcs2s(frame, node->txt.ptr.u, node->txt.dim);
+        }
+    }
+    return frame;
+}
+
+static unsigned char *
+set_frame_wxxx(unsigned char *frame, FrameDataNode const *node)
+{
+    size_t const n = sizeOfWxxxNode(node);
+    if (n > 10) {
+        frame = set_4_byte_value(frame, node->fid);
+        frame = set_4_byte_value(frame, (unsigned long) (n - 10));
+        /* clear 2-byte header flags */
+        *frame++ = 0;
+        *frame++ = 0;
+        if (node->dsc.dim > 0) {
+            /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */
+            *frame++ = node->dsc.enc == 1 ? 1 : 0;
+            if (node->dsc.enc != 1) {
+                frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);
+                *frame++ = 0;
+            }
+            else {
+                frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);
+                *frame++ = 0;
+                *frame++ = 0;
+            }
+        }
+        if (node->txt.enc != 1) {
+            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);
+        }
+        else {
+            frame = writeLoBytes(frame, node->txt.ptr.u, node->txt.dim);
+        }
+    }
+    return frame;
+}
+
+static unsigned char *
+set_frame_apic(unsigned char *frame, const char *mimetype, const unsigned char *data, size_t size)
+{
+    /* ID3v2.3 standard APIC frame:
+     *     <Header for 'Attached picture', ID: "APIC">
+     *     Text encoding    $xx
+     *     MIME type        <text string> $00
+     *     Picture type     $xx
+     *     Description      <text string according to encoding> $00 (00)
+     *     Picture data     <binary data>
+     */
+    if (mimetype && data && size) {
+        frame = set_4_byte_value(frame, FRAME_ID('A', 'P', 'I', 'C'));
+        frame = set_4_byte_value(frame, (unsigned long) (4 + strlen(mimetype) + size));
+        /* clear 2-byte header flags */
+        *frame++ = 0;
+        *frame++ = 0;
+        /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */
+        *frame++ = 0;
+        /* copy mime_type */
+        while (*mimetype) {
+            *frame++ = *mimetype++;
+        }
+        *frame++ = 0;
+        /* set picture type to 0 */
+        *frame++ = 0;
+        /* empty description field */
+        *frame++ = 0;
+        /* copy the image data */
+        while (size--) {
+            *frame++ = *data++;
+        }
+    }
+    return frame;
+}
+
+int
+id3tag_set_fieldvalue(lame_t gfp, const char *fieldvalue)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    if (fieldvalue && *fieldvalue) {
+        if (strlen(fieldvalue) < 5 || fieldvalue[4] != '=') {
+            return -1;
+        }
+        return id3tag_set_textinfo_latin1(gfp, fieldvalue, &fieldvalue[5]);
+    }
+    return 0;
+}
+
+int
+id3tag_set_fieldvalue_utf16(lame_t gfp, const unsigned short *fieldvalue)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    if (fieldvalue && *fieldvalue) {
+        size_t dx = hasUcs2ByteOrderMarker(fieldvalue[0]);
+        unsigned short const separator = fromLatin1Char(fieldvalue, '=');
+        char fid[5] = {0,0,0,0,0};
+        uint32_t const frame_id = toID3v2TagId_ucs2(fieldvalue);
+        if (local_ucs2_strlen(fieldvalue) < (5+dx) || fieldvalue[4+dx] != separator) {
+            return -1;
+        }
+        fid[0] = (frame_id >> 24) & 0x0ff;
+        fid[1] = (frame_id >> 16) & 0x0ff;
+        fid[2] = (frame_id >> 8) & 0x0ff;
+        fid[3] = frame_id & 0x0ff;
+        if (frame_id != 0) {
+            unsigned short* txt = 0;
+            int     rc;
+            local_ucs2_substr(&txt, fieldvalue, dx+5, local_ucs2_strlen(fieldvalue));
+            rc = id3tag_set_textinfo_utf16(gfp, fid, txt);
+            free(txt);
+            return rc;
+        }
+    }
+    return -1;
+}
+
+extern int
+id3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue);
+
+int
+id3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue)
+{
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    return id3tag_set_fieldvalue_utf16(gfp, fieldvalue);
+}
+
+size_t
+lame_get_id3v2_tag(lame_t gfp, unsigned char *buffer, size_t size)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    gfc = gfp->internal_flags;
+    if (test_tag_spec_flags(gfc, V1_ONLY_FLAG)) {
+        return 0;
+    }
+#if 0
+    debug_tag_spec_flags(gfc, "lame_get_id3v2_tag");
+#endif
+    {
+        int usev2 = test_tag_spec_flags(gfc, ADD_V2_FLAG | V2_ONLY_FLAG);
+        /* calculate length of four fields which may not fit in verion 1 tag */
+        size_t  title_length = gfc->tag_spec.title ? strlen(gfc->tag_spec.title) : 0;
+        size_t  artist_length = gfc->tag_spec.artist ? strlen(gfc->tag_spec.artist) : 0;
+        size_t  album_length = gfc->tag_spec.album ? strlen(gfc->tag_spec.album) : 0;
+        size_t  comment_length = gfc->tag_spec.comment ? strlen(gfc->tag_spec.comment) : 0;
+        /* write tag if explicitly requested or if fields overflow */
+        if ((title_length > 30)
+            || (artist_length > 30)
+            || (album_length > 30)
+            || (comment_length > 30)
+            || (gfc->tag_spec.track_id3v1 && (comment_length > 28))) {
+            usev2 = 1;
+        }
+        if (usev2) {
+            size_t  tag_size;
+            unsigned char *p;
+            size_t  adjusted_tag_size;
+            const char *albumart_mime = NULL;
+            static const char *mime_jpeg = "image/jpeg";
+            static const char *mime_png = "image/png";
+            static const char *mime_gif = "image/gif";
+
+            if (gfp->num_samples != MAX_U_32_NUM) {
+                id3v2AddAudioDuration(gfp, gfp->num_samples);
+            }
+
+            /* calulate size of tag starting with 10-byte tag header */
+            tag_size = 10;
+            if (gfc->tag_spec.albumart && gfc->tag_spec.albumart_size) {
+                switch (gfc->tag_spec.albumart_mimetype) {
+                case MIMETYPE_JPEG:
+                    albumart_mime = mime_jpeg;
+                    break;
+                case MIMETYPE_PNG:
+                    albumart_mime = mime_png;
+                    break;
+                case MIMETYPE_GIF:
+                    albumart_mime = mime_gif;
+                    break;
+                }
+                if (albumart_mime) {
+                    tag_size += 10 + 4 + strlen(albumart_mime) + gfc->tag_spec.albumart_size;
+                }
+            }
+            {
+                id3tag_spec *tag = &gfc->tag_spec;
+                if (tag->v2_head != 0) {
+                    FrameDataNode *node;
+                    for (node = tag->v2_head; node != 0; node = node->nxt) {
+                        if (node->fid == ID_COMMENT || node->fid == ID_USER) {
+                            tag_size += sizeOfCommentNode(node);
+                        }
+                        else if (isFrameIdMatching(node->fid, FRAME_ID('W',0,0,0))) {
+                            tag_size += sizeOfWxxxNode(node);
+                        }
+                        else {
+                            tag_size += sizeOfNode(node);
+                        }
+                    }
+                }
+            }
+            if (test_tag_spec_flags(gfc, PAD_V2_FLAG)) {
+                /* add some bytes of padding */
+                tag_size += gfc->tag_spec.padding_size;
+            }
+            if (size < tag_size) {
+                return tag_size;
+            }
+            if (buffer == 0) {
+                return 0;
+            }
+            p = buffer;
+            /* set tag header starting with file identifier */
+            *p++ = 'I';
+            *p++ = 'D';
+            *p++ = '3';
+            /* set version number word */
+            *p++ = 3;
+            *p++ = 0;
+            /* clear flags byte */
+            *p++ = 0;
+            /* calculate and set tag size = total size - header size */
+            adjusted_tag_size = tag_size - 10;
+            /* encode adjusted size into four bytes where most significant 
+             * bit is clear in each byte, for 28-bit total */
+            *p++ = (unsigned char) ((adjusted_tag_size >> 21) & 0x7fu);
+            *p++ = (unsigned char) ((adjusted_tag_size >> 14) & 0x7fu);
+            *p++ = (unsigned char) ((adjusted_tag_size >> 7) & 0x7fu);
+            *p++ = (unsigned char) (adjusted_tag_size & 0x7fu);
+
+            /*
+             * NOTE: The remainder of the tag (frames and padding, if any)
+             * are not "unsynchronized" to prevent false MPEG audio headers
+             * from appearing in the bitstream.  Why?  Well, most players
+             * and utilities know how to skip the ID3 version 2 tag by now
+             * even if they don't read its contents, and it's actually
+             * very unlikely that such a false "sync" pattern would occur
+             * in just the simple text frames added here.
+             */
+
+            /* set each frame in tag */
+            {
+                id3tag_spec *tag = &gfc->tag_spec;
+                if (tag->v2_head != 0) {
+                    FrameDataNode *node;
+                    for (node = tag->v2_head; node != 0; node = node->nxt) {
+                        if (node->fid == ID_COMMENT || node->fid == ID_USER) {
+                            p = set_frame_comment(p, node);
+                        }
+                        else if (isFrameIdMatching(node->fid,FRAME_ID('W',0,0,0))) {
+                            p = set_frame_wxxx(p, node);
+                        }
+                        else {
+                            p = set_frame_custom2(p, node);
+                        }
+                    }
+                }
+            }
+            if (albumart_mime) {
+                p = set_frame_apic(p, albumart_mime, gfc->tag_spec.albumart,
+                                   gfc->tag_spec.albumart_size);
+            }
+            /* clear any padding bytes */
+            memset(p, 0, tag_size - (p - buffer));
+            return tag_size;
+        }
+    }
+    return 0;
+}
+
+int
+id3tag_write_v2(lame_t gfp)
+{
+    lame_internal_flags *gfc = 0;
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    gfc = gfp->internal_flags;
+#if 0
+    debug_tag_spec_flags(gfc, "write v2");
+#endif
+    if (test_tag_spec_flags(gfc, V1_ONLY_FLAG)) {
+        return 0;
+    }
+    if (test_tag_spec_flags(gfc, CHANGED_FLAG)) {
+        unsigned char *tag = 0;
+        size_t  tag_size, n;
+
+        n = lame_get_id3v2_tag(gfp, 0, 0);
+        tag = lame_calloc(unsigned char, n);
+        if (tag == 0) {
+            return -1;
+        }
+        tag_size = lame_get_id3v2_tag(gfp, tag, n);
+        if (tag_size > n) {
+            free(tag);
+            return -1;
+        }
+        else {
+            size_t  i;
+            /* write tag directly into bitstream at current position */
+            for (i = 0; i < tag_size; ++i) {
+                add_dummy_byte(gfc, tag[i], 1);
+            }
+        }
+        free(tag);
+        return (int) tag_size; /* ok, tag should not exceed 2GB */
+    }
+    return 0;
+}
+
+static unsigned char *
+set_text_field(unsigned char *field, const char *text, size_t size, int pad)
+{
+    while (size--) {
+        if (text && *text) {
+            *field++ = *text++;
+        }
+        else {
+            *field++ = pad;
+        }
+    }
+    return field;
+}
+
+size_t
+lame_get_id3v1_tag(lame_t gfp, unsigned char *buffer, size_t size)
+{
+    size_t const tag_size = 128;
+    lame_internal_flags *gfc;
+
+    if (gfp == 0) {
+        return 0;
+    }
+    if (size < tag_size) {
+        return tag_size;
+    }
+    gfc = gfp->internal_flags;
+    if (gfc == 0) {
+        return 0;
+    }
+    if (buffer == 0) {
+        return 0;
+    }
+    if (test_tag_spec_flags(gfc, V2_ONLY_FLAG)) {
+        return 0;
+    }
+    if (test_tag_spec_flags(gfc, CHANGED_FLAG)) {
+        unsigned char *p = buffer;
+        int     pad = test_tag_spec_flags(gfc, SPACE_V1_FLAG) ? ' ' : 0;
+        char    year[5];
+
+        /* set tag identifier */
+        *p++ = 'T';
+        *p++ = 'A';
+        *p++ = 'G';
+        /* set each field in tag */
+        p = set_text_field(p, gfc->tag_spec.title, 30, pad);
+        p = set_text_field(p, gfc->tag_spec.artist, 30, pad);
+        p = set_text_field(p, gfc->tag_spec.album, 30, pad);
+        sprintf(year, "%d", gfc->tag_spec.year);
+        p = set_text_field(p, gfc->tag_spec.year ? year : NULL, 4, pad);
+        /* limit comment field to 28 bytes if a track is specified */
+        p = set_text_field(p, gfc->tag_spec.comment, gfc->tag_spec.track_id3v1 ? 28 : 30, pad);
+        if (gfc->tag_spec.track_id3v1) {
+            /* clear the next byte to indicate a version 1.1 tag */
+            *p++ = 0;
+            *p++ = gfc->tag_spec.track_id3v1;
+        }
+        *p++ = gfc->tag_spec.genre_id3v1;
+        return tag_size;
+    }
+    return 0;
+}
+
+int
+id3tag_write_v1(lame_t gfp)
+{
+    lame_internal_flags* gfc = 0;
+    size_t  i, n, m;
+    unsigned char tag[128];
+
+    if (is_lame_internal_flags_null(gfp)) {
+        return 0;
+    }
+    gfc = gfp->internal_flags;
+
+    m = sizeof(tag);
+    n = lame_get_id3v1_tag(gfp, tag, m);
+    if (n > m) {
+        return 0;
+    }
+    /* write tag directly into bitstream at current position */
+    for (i = 0; i < n; ++i) {
+        add_dummy_byte(gfc, tag[i], 1);
+    }
+    return (int) n;     /* ok, tag has fixed size of 128 bytes, well below 2GB */
+}
diff --git a/lame/libmp3lame/id3tag.h b/lame/libmp3lame/id3tag.h
new file mode 100644 (file)
index 0000000..9cd9ad9
--- /dev/null
@@ -0,0 +1,64 @@
+
+#ifndef LAME_ID3_H
+#define LAME_ID3_H
+
+
+#define CHANGED_FLAG    (1U << 0)
+#define ADD_V2_FLAG     (1U << 1)
+#define V1_ONLY_FLAG    (1U << 2)
+#define V2_ONLY_FLAG    (1U << 3)
+#define SPACE_V1_FLAG   (1U << 4)
+#define PAD_V2_FLAG     (1U << 5)
+
+enum {
+    MIMETYPE_NONE = 0,
+    MIMETYPE_JPEG,
+    MIMETYPE_PNG,
+    MIMETYPE_GIF
+};
+
+typedef struct FrameDataNode {
+    struct FrameDataNode *nxt;
+    uint32_t fid;             /* Frame Identifier                 */
+    char    lng[4];          /* 3-character language descriptor  */
+    struct {
+        union {
+            char   *l;       /* ptr to Latin-1 chars             */
+            unsigned short *u; /* ptr to UCS-2 text                */
+            unsigned char *b; /* ptr to raw bytes                 */
+        } ptr;
+        size_t  dim;
+        int     enc;         /* 0:Latin-1, 1:UCS-2, 2:RAW        */
+    } dsc  , txt;
+} FrameDataNode;
+
+
+typedef struct id3tag_spec {
+    /* private data members */
+    unsigned int flags;
+    int     year;
+    char   *title;
+    char   *artist;
+    char   *album;
+    char   *comment;
+    int     track_id3v1;
+    int     genre_id3v1;
+    unsigned char *albumart;
+    unsigned int albumart_size;
+    unsigned int padding_size;
+    int     albumart_mimetype;
+    char    language[4]; /* the language of the frame's content, according to ISO-639-2 */
+    FrameDataNode *v2_head, *v2_tail;
+} id3tag_spec;
+
+
+/* write tag into stream at current position */
+extern int id3tag_write_v2(lame_global_flags * gfp);
+extern int id3tag_write_v1(lame_global_flags * gfp);
+/*
+ * NOTE: A version 2 tag will NOT be added unless one of the text fields won't
+ * fit in a version 1 tag (e.g. the title string is longer than 30 characters),
+ * or the "id3tag_add_v2" or "id3tag_v2_only" functions are used.
+ */
+
+#endif
diff --git a/lame/libmp3lame/l3side.h b/lame/libmp3lame/l3side.h
new file mode 100644 (file)
index 0000000..f65bbed
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ *     Layer 3 side include file
+ *
+ *     Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_L3SIDE_H
+#define LAME_L3SIDE_H
+
+/* max scalefactor band, max(SBMAX_l, SBMAX_s*3, (SBMAX_s-3)*3+8) */
+#define SFBMAX (SBMAX_s*3)
+
+/* Layer III side information. */
+typedef struct {
+    int     l[1 + SBMAX_l];
+    int     s[1 + SBMAX_s];
+    int     psfb21[1 + PSFB21];
+    int     psfb12[1 + PSFB12];
+} scalefac_struct;
+
+
+typedef struct {
+    FLOAT   l[SBMAX_l];
+    FLOAT   s[SBMAX_s][3];
+} III_psy_xmin;
+
+typedef struct {
+    III_psy_xmin thm;
+    III_psy_xmin en;
+} III_psy_ratio;
+
+typedef struct {
+    FLOAT   xr[576];
+    int     l3_enc[576];
+    int     scalefac[SFBMAX];
+    FLOAT   xrpow_max;
+
+    int     part2_3_length;
+    int     big_values;
+    int     count1;
+    int     global_gain;
+    int     scalefac_compress;
+    int     block_type;
+    int     mixed_block_flag;
+    int     table_select[3];
+    int     subblock_gain[3 + 1];
+    int     region0_count;
+    int     region1_count;
+    int     preflag;
+    int     scalefac_scale;
+    int     count1table_select;
+
+    int     part2_length;
+    int     sfb_lmax;
+    int     sfb_smin;
+    int     psy_lmax;
+    int     sfbmax;
+    int     psymax;
+    int     sfbdivide;
+    int     width[SFBMAX];
+    int     window[SFBMAX];
+    int     count1bits;
+    /* added for LSF */
+    const int *sfb_partition_table;
+    int     slen[4];
+
+    int     max_nonzero_coeff;
+    char    energy_above_cutoff[SFBMAX];
+} gr_info;
+
+typedef struct {
+    gr_info tt[2][2];
+    int     main_data_begin;
+    int     private_bits;
+    int     resvDrain_pre;
+    int     resvDrain_post;
+    int     scfsi[2][4];
+} III_side_info_t;
+
+#endif
diff --git a/lame/libmp3lame/lame-analysis.h b/lame/libmp3lame/lame-analysis.h
new file mode 100644 (file)
index 0000000..5055a60
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ *      GTK plotting routines source file
+ *
+ *      Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_GTKANAL_H
+#define LAME_GTKANAL_H
+
+
+#define READ_AHEAD 40   /* number of frames to read ahead */
+#define MAXMPGLAG READ_AHEAD /* if the mpg123 lag becomes bigger than this
+                                we have to stop */
+#define NUMBACK 6       /* number of frames we can back up */
+#define NUMPINFO (NUMBACK+READ_AHEAD+1)
+
+
+
+struct plotting_data {
+    int     frameNum;        /* current frame number */
+    int     frameNum123;
+    int     num_samples;     /* number of pcm samples read for this frame */
+    double  frametime;       /* starting time of frame, in seconds */
+    double  pcmdata[2][1600];
+    double  pcmdata2[2][1152 + 1152 - DECDELAY];
+    double  xr[2][2][576];
+    double  mpg123xr[2][2][576];
+    double  ms_ratio[2];
+    double  ms_ener_ratio[2];
+
+    /* L,R, M and S values */
+    double  energy_save[4][BLKSIZE]; /* psymodel is one ahead */
+    double  energy[2][4][BLKSIZE];
+    double  pe[2][4];
+    double  thr[2][4][SBMAX_l];
+    double  en[2][4][SBMAX_l];
+    double  thr_s[2][4][3 * SBMAX_s];
+    double  en_s[2][4][3 * SBMAX_s];
+    double  ers_save[4];     /* psymodel is one ahead */
+    double  ers[2][4];
+
+    double  sfb[2][2][SBMAX_l];
+    double  sfb_s[2][2][3 * SBMAX_s];
+    double  LAMEsfb[2][2][SBMAX_l];
+    double  LAMEsfb_s[2][2][3 * SBMAX_s];
+
+    int     LAMEqss[2][2];
+    int     qss[2][2];
+    int     big_values[2][2];
+    int     sub_gain[2][2][3];
+
+    double  xfsf[2][2][SBMAX_l];
+    double  xfsf_s[2][2][3 * SBMAX_s];
+
+    int     over[2][2];
+    double  tot_noise[2][2];
+    double  max_noise[2][2];
+    double  over_noise[2][2];
+    int     over_SSD[2][2];
+    int     blocktype[2][2];
+    int     scalefac_scale[2][2];
+    int     preflag[2][2];
+    int     mpg123blocktype[2][2];
+    int     mixed[2][2];
+    int     mainbits[2][2];
+    int     sfbits[2][2];
+    int     LAMEmainbits[2][2];
+    int     LAMEsfbits[2][2];
+    int     framesize, stereo, js, ms_stereo, i_stereo, emph, bitrate, sampfreq, maindata;
+    int     crc, padding;
+    int     scfsi[2], mean_bits, resvsize;
+    int     totbits;
+};
+#ifndef plotting_data_defined
+#define plotting_data_defined
+typedef struct plotting_data plotting_data;
+#endif
+#if 0
+extern plotting_data *pinfo;
+#endif
+#endif
diff --git a/lame/libmp3lame/lame.c b/lame/libmp3lame/lame.c
new file mode 100644 (file)
index 0000000..cb82225
--- /dev/null
@@ -0,0 +1,2665 @@
+/* -*- mode: C; mode: fold -*- */
+/*
+ *      LAME MP3 encoding engine
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *      Copyright (c) 2000-2005 Takehiro Tominaga
+ *      Copyright (c) 2000-2017 Robert Hegemann
+ *      Copyright (c) 2000-2005 Gabriel Bouvigne
+ *      Copyright (c) 2000-2004 Alexander Leidinger
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: lame.c,v 1.377 2017/09/26 12:14:02 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+
+#include "encoder.h"
+#include "util.h"
+#include "lame_global_flags.h"
+#include "gain_analysis.h"
+#include "bitstream.h"
+#include "quantize_pvt.h"
+#include "set_get.h"
+#include "quantize.h"
+#include "psymodel.h"
+#include "version.h"
+#include "VbrTag.h"
+#include "tables.h"
+
+
+#if defined(__FreeBSD__) && !defined(__alpha__)
+#include <floatingpoint.h>
+#endif
+#ifdef __riscos__
+#include "asmstuff.h"
+#endif
+
+#ifdef __sun__
+/* woraround for SunOS 4.x, it has SEEK_* defined here */
+#include <unistd.h>
+#endif
+
+
+#define LAME_DEFAULT_QUALITY 3
+
+
+
+int
+is_lame_global_flags_valid(const lame_global_flags * gfp)
+{
+    if (gfp == NULL)
+        return 0;
+    if (gfp->class_id != LAME_ID)
+        return 0;
+    return 1;
+}
+
+
+int
+is_lame_internal_flags_valid(const lame_internal_flags * gfc)
+{
+    if (gfc == NULL)
+        return 0;
+    if (gfc->class_id != LAME_ID)
+        return 0;
+    if (gfc->lame_init_params_successful <=0)
+        return 0;
+    return 1;
+}
+
+
+
+static  FLOAT
+filter_coef(FLOAT x)
+{
+    if (x > 1.0)
+        return 0.0;
+    if (x <= 0.0)
+        return 1.0;
+
+    return cos(PI / 2 * x);
+}
+
+static void
+lame_init_params_ppflt(lame_internal_flags * gfc)
+{
+    SessionConfig_t *const cfg = &gfc->cfg;
+    
+    /***************************************************************/
+    /* compute info needed for polyphase filter (filter type==0, default) */
+    /***************************************************************/
+
+    int     band, maxband, minband;
+    FLOAT   freq;
+    int     lowpass_band = 32;
+    int     highpass_band = -1;
+
+    if (cfg->lowpass1 > 0) {
+        minband = 999;
+        for (band = 0; band <= 31; band++) {
+            freq = band / 31.0;
+            /* this band and above will be zeroed: */
+            if (freq >= cfg->lowpass2) {
+                lowpass_band = Min(lowpass_band, band);
+            }
+            if (cfg->lowpass1 < freq && freq < cfg->lowpass2) {
+                minband = Min(minband, band);
+            }
+        }
+
+        /* compute the *actual* transition band implemented by
+         * the polyphase filter */
+        if (minband == 999) {
+            cfg->lowpass1 = (lowpass_band - .75) / 31.0;
+        }
+        else {
+            cfg->lowpass1 = (minband - .75) / 31.0;
+        }
+        cfg->lowpass2 = lowpass_band / 31.0;
+    }
+
+    /* make sure highpass filter is within 90% of what the effective
+     * highpass frequency will be */
+    if (cfg->highpass2 > 0) {
+        if (cfg->highpass2 < .9 * (.75 / 31.0)) {
+            cfg->highpass1 = 0;
+            cfg->highpass2 = 0;
+            MSGF(gfc, "Warning: highpass filter disabled.  " "highpass frequency too small\n");
+        }
+    }
+
+    if (cfg->highpass2 > 0) {
+        maxband = -1;
+        for (band = 0; band <= 31; band++) {
+            freq = band / 31.0;
+            /* this band and below will be zereod */
+            if (freq <= cfg->highpass1) {
+                highpass_band = Max(highpass_band, band);
+            }
+            if (cfg->highpass1 < freq && freq < cfg->highpass2) {
+                maxband = Max(maxband, band);
+            }
+        }
+        /* compute the *actual* transition band implemented by
+         * the polyphase filter */
+        cfg->highpass1 = highpass_band / 31.0;
+        if (maxband == -1) {
+            cfg->highpass2 = (highpass_band + .75) / 31.0;
+        }
+        else {
+            cfg->highpass2 = (maxband + .75) / 31.0;
+        }
+    }
+
+    for (band = 0; band < 32; band++) {
+        FLOAT fc1, fc2;
+        freq = band / 31.0f;
+        if (cfg->highpass2 > cfg->highpass1) {
+            fc1 = filter_coef((cfg->highpass2 - freq) / (cfg->highpass2 - cfg->highpass1 + 1e-20));
+        }
+        else {
+            fc1 = 1.0f;
+        }
+        if (cfg->lowpass2 > cfg->lowpass1) {
+            fc2 = filter_coef((freq - cfg->lowpass1)  / (cfg->lowpass2 - cfg->lowpass1 + 1e-20));
+        }
+        else {
+            fc2 = 1.0f;
+        }
+        gfc->sv_enc.amp_filter[band] = fc1 * fc2;
+    }
+}
+
+
+static void
+optimum_bandwidth(double *const lowerlimit, double *const upperlimit, const unsigned bitrate)
+{
+/*
+ *  Input:
+ *      bitrate     total bitrate in kbps
+ *
+ *   Output:
+ *      lowerlimit: best lowpass frequency limit for input filter in Hz
+ *      upperlimit: best highpass frequency limit for input filter in Hz
+ */
+    int     table_index;
+
+    typedef struct {
+        int     bitrate;     /* only indicative value */
+        int     lowpass;
+    } band_pass_t;
+
+    const band_pass_t freq_map[] = {
+        {8, 2000},
+        {16, 3700},
+        {24, 3900},
+        {32, 5500},
+        {40, 7000},
+        {48, 7500},
+        {56, 10000},
+        {64, 11000},
+        {80, 13500},
+        {96, 15100},
+        {112, 15600},
+        {128, 17000},
+        {160, 17500},
+        {192, 18600},
+        {224, 19400},
+        {256, 19700},
+        {320, 20500}
+    };
+
+
+    table_index = nearestBitrateFullIndex(bitrate);
+
+    (void) freq_map[table_index].bitrate;
+    *lowerlimit = freq_map[table_index].lowpass;
+
+
+/*
+ *  Now we try to choose a good high pass filtering frequency.
+ *  This value is currently not used.
+ *    For fu < 16 kHz:  sqrt(fu*fl) = 560 Hz
+ *    For fu = 18 kHz:  no high pass filtering
+ *  This gives:
+ *
+ *   2 kHz => 160 Hz
+ *   3 kHz => 107 Hz
+ *   4 kHz =>  80 Hz
+ *   8 kHz =>  40 Hz
+ *  16 kHz =>  20 Hz
+ *  17 kHz =>  10 Hz
+ *  18 kHz =>   0 Hz
+ *
+ *  These are ad hoc values and these can be optimized if a high pass is available.
+ */
+/*    if (f_low <= 16000)
+        f_high = 16000. * 20. / f_low;
+    else if (f_low <= 18000)
+        f_high = 180. - 0.01 * f_low;
+    else
+        f_high = 0.;*/
+
+    /*
+     *  When we sometimes have a good highpass filter, we can add the highpass
+     *  frequency to the lowpass frequency
+     */
+
+    /*if (upperlimit != NULL)
+     *upperlimit = f_high;*/
+    (void) upperlimit;
+}
+
+
+static int
+optimum_samplefreq(int lowpassfreq, int input_samplefreq)
+{
+/*
+ * Rules:
+ *  - if possible, sfb21 should NOT be used
+ *
+ */
+    int     suggested_samplefreq = 44100;
+
+    if (input_samplefreq >= 48000)
+        suggested_samplefreq = 48000;
+    else if (input_samplefreq >= 44100)
+        suggested_samplefreq = 44100;
+    else if (input_samplefreq >= 32000)
+        suggested_samplefreq = 32000;
+    else if (input_samplefreq >= 24000)
+        suggested_samplefreq = 24000;
+    else if (input_samplefreq >= 22050)
+        suggested_samplefreq = 22050;
+    else if (input_samplefreq >= 16000)
+        suggested_samplefreq = 16000;
+    else if (input_samplefreq >= 12000)
+        suggested_samplefreq = 12000;
+    else if (input_samplefreq >= 11025)
+        suggested_samplefreq = 11025;
+    else if (input_samplefreq >= 8000)
+        suggested_samplefreq = 8000;
+
+    if (lowpassfreq == -1)
+        return suggested_samplefreq;
+
+    if (lowpassfreq <= 15960)
+        suggested_samplefreq = 44100;
+    if (lowpassfreq <= 15250)
+        suggested_samplefreq = 32000;
+    if (lowpassfreq <= 11220)
+        suggested_samplefreq = 24000;
+    if (lowpassfreq <= 9970)
+        suggested_samplefreq = 22050;
+    if (lowpassfreq <= 7230)
+        suggested_samplefreq = 16000;
+    if (lowpassfreq <= 5420)
+        suggested_samplefreq = 12000;
+    if (lowpassfreq <= 4510)
+        suggested_samplefreq = 11025;
+    if (lowpassfreq <= 3970)
+        suggested_samplefreq = 8000;
+
+    if (input_samplefreq < suggested_samplefreq) {
+        /* choose a valid MPEG sample frequency above the input sample frequency
+           to avoid SFB21/12 bitrate bloat
+           rh 061115
+         */
+        if (input_samplefreq > 44100) {
+            return 48000;
+        }
+        if (input_samplefreq > 32000) {
+            return 44100;
+        }
+        if (input_samplefreq > 24000) {
+            return 32000;
+        }
+        if (input_samplefreq > 22050) {
+            return 24000;
+        }
+        if (input_samplefreq > 16000) {
+            return 22050;
+        }
+        if (input_samplefreq > 12000) {
+            return 16000;
+        }
+        if (input_samplefreq > 11025) {
+            return 12000;
+        }
+        if (input_samplefreq > 8000) {
+            return 11025;
+        }
+        return 8000;
+    }
+    return suggested_samplefreq;
+}
+
+
+
+
+
+/* set internal feature flags.  USER should not access these since
+ * some combinations will produce strange results */
+static void
+lame_init_qval(lame_global_flags * gfp)
+{
+    lame_internal_flags *const gfc = gfp->internal_flags;
+    SessionConfig_t *const cfg = &gfc->cfg;
+
+    switch (gfp->quality) {
+    default:
+    case 9:            /* no psymodel, no noise shaping */
+        cfg->noise_shaping = 0;
+        cfg->noise_shaping_amp = 0;
+        cfg->noise_shaping_stop = 0;
+        cfg->use_best_huffman = 0;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 8:
+        gfp->quality = 7;
+        /*lint --fallthrough */
+    case 7:            /* use psymodel (for short block and m/s switching), but no noise shapping */
+        cfg->noise_shaping = 0;
+        cfg->noise_shaping_amp = 0;
+        cfg->noise_shaping_stop = 0;
+        cfg->use_best_huffman = 0;
+        cfg->full_outer_loop = 0;
+        if (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) {
+            cfg->full_outer_loop  = -1;
+        }
+        break;
+
+    case 6:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        cfg->noise_shaping_amp = 0;
+        cfg->noise_shaping_stop = 0;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 0;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 5:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        cfg->noise_shaping_amp = 0;
+        cfg->noise_shaping_stop = 0;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 0;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 4:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        cfg->noise_shaping_amp = 0;
+        cfg->noise_shaping_stop = 0;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 1;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 3:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        cfg->noise_shaping_amp = 1;
+        cfg->noise_shaping_stop = 1;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 1;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 2:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        if (gfc->sv_qnt.substep_shaping == 0)
+            gfc->sv_qnt.substep_shaping = 2;
+        cfg->noise_shaping_amp = 1;
+        cfg->noise_shaping_stop = 1;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 1; /* inner loop */
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 1:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        if (gfc->sv_qnt.substep_shaping == 0)
+            gfc->sv_qnt.substep_shaping = 2;
+        cfg->noise_shaping_amp = 2;
+        cfg->noise_shaping_stop = 1;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 1;
+        cfg->full_outer_loop = 0;
+        break;
+
+    case 0:
+        if (cfg->noise_shaping == 0)
+            cfg->noise_shaping = 1;
+        if (gfc->sv_qnt.substep_shaping == 0)
+            gfc->sv_qnt.substep_shaping = 2;
+        cfg->noise_shaping_amp = 2;
+        cfg->noise_shaping_stop = 1;
+        if (cfg->subblock_gain == -1)
+            cfg->subblock_gain = 1;
+        cfg->use_best_huffman = 1; /*type 2 disabled because of it slowness,
+                                      in favor of full outer loop search */
+        cfg->full_outer_loop = 1;
+        break;
+    }
+
+}
+
+
+
+static double
+linear_int(double a, double b, double m)
+{
+    return a + m * (b - a);
+}
+
+
+
+/********************************************************************
+ *   initialize internal params based on data in gf
+ *   (globalflags struct filled in by calling program)
+ *
+ *  OUTLINE:
+ *
+ * We first have some complex code to determine bitrate,
+ * output samplerate and mode.  It is complicated by the fact
+ * that we allow the user to set some or all of these parameters,
+ * and need to determine best possible values for the rest of them:
+ *
+ *  1. set some CPU related flags
+ *  2. check if we are mono->mono, stereo->mono or stereo->stereo
+ *  3.  compute bitrate and output samplerate:
+ *          user may have set compression ratio
+ *          user may have set a bitrate
+ *          user may have set a output samplerate
+ *  4. set some options which depend on output samplerate
+ *  5. compute the actual compression ratio
+ *  6. set mode based on compression ratio
+ *
+ *  The remaining code is much simpler - it just sets options
+ *  based on the mode & compression ratio:
+ *
+ *   set allow_diff_short based on mode
+ *   select lowpass filter based on compression ratio & mode
+ *   set the bitrate index, and min/max bitrates for VBR modes
+ *   disable VBR tag if it is not appropriate
+ *   initialize the bitstream
+ *   initialize scalefac_band data
+ *   set sideinfo_len (based on channels, CRC, out_samplerate)
+ *   write an id3v2 tag into the bitstream
+ *   write VBR tag into the bitstream
+ *   set mpeg1/2 flag
+ *   estimate the number of frames (based on a lot of data)
+ *
+ *   now we set more flags:
+ *   nspsytune:
+ *      see code
+ *   VBR modes
+ *      see code
+ *   CBR/ABR
+ *      see code
+ *
+ *  Finally, we set the algorithm flags based on the gfp->quality value
+ *  lame_init_qval(gfp);
+ *
+ ********************************************************************/
+int
+lame_init_params(lame_global_flags * gfp)
+{
+
+    int     i;
+    int     j;
+    lame_internal_flags *gfc;
+    SessionConfig_t *cfg;
+
+    if (!is_lame_global_flags_valid(gfp)) 
+        return -1;
+
+    gfc = gfp->internal_flags;
+    if (gfc == 0) 
+        return -1;
+
+    if (is_lame_internal_flags_valid(gfc))
+        return -1; /* already initialized */
+
+    /* start updating lame internal flags */
+    gfc->class_id = LAME_ID;
+    gfc->lame_init_params_successful = 0; /* will be set to one, when we get through until the end */
+
+    if (gfp->samplerate_in < 1)
+        return -1; /* input sample rate makes no sense */
+    if (gfp->num_channels < 1 || 2 < gfp->num_channels)
+        return -1; /* number of input channels makes no sense */
+    if (gfp->samplerate_out != 0) {
+        int   v=0;
+        if (SmpFrqIndex(gfp->samplerate_out, &v) < 0)
+            return -1; /* output sample rate makes no sense */
+    }
+
+    cfg = &gfc->cfg;
+
+    cfg->enforce_min_bitrate = gfp->VBR_hard_min;
+    cfg->analysis = gfp->analysis;
+    if (cfg->analysis)
+        gfp->write_lame_tag = 0;
+
+    /* some file options not allowed if output is: not specified or stdout */
+    if (gfc->pinfo != NULL)
+        gfp->write_lame_tag = 0; /* disable Xing VBR tag */
+
+    /* report functions */
+    gfc->report_msg = gfp->report.msgf;
+    gfc->report_dbg = gfp->report.debugf;
+    gfc->report_err = gfp->report.errorf;
+
+    if (gfp->asm_optimizations.amd3dnow)
+        gfc->CPU_features.AMD_3DNow = has_3DNow();
+    else
+        gfc->CPU_features.AMD_3DNow = 0;
+
+    if (gfp->asm_optimizations.mmx)
+        gfc->CPU_features.MMX = has_MMX();
+    else
+        gfc->CPU_features.MMX = 0;
+
+    if (gfp->asm_optimizations.sse) {
+        gfc->CPU_features.SSE = has_SSE();
+        gfc->CPU_features.SSE2 = has_SSE2();
+    }
+    else {
+        gfc->CPU_features.SSE = 0;
+        gfc->CPU_features.SSE2 = 0;
+    }
+
+
+    cfg->vbr = gfp->VBR;
+    cfg->error_protection = gfp->error_protection;
+    cfg->copyright = gfp->copyright;
+    cfg->original = gfp->original;
+    cfg->extension = gfp->extension;
+    cfg->emphasis = gfp->emphasis;
+
+    cfg->channels_in = gfp->num_channels;
+    if (cfg->channels_in == 1)
+        gfp->mode = MONO;
+    cfg->channels_out = (gfp->mode == MONO) ? 1 : 2;
+    if (gfp->mode != JOINT_STEREO)
+        gfp->force_ms = 0; /* forced mid/side stereo for j-stereo only */
+    cfg->force_ms = gfp->force_ms;
+
+    if (cfg->vbr == vbr_off && gfp->VBR_mean_bitrate_kbps != 128 && gfp->brate == 0)
+        gfp->brate = gfp->VBR_mean_bitrate_kbps;
+
+    switch (cfg->vbr) {
+    case vbr_off:
+    case vbr_mtrh:
+    case vbr_mt:
+        /* these modes can handle free format condition */
+        break;
+    default:
+        gfp->free_format = 0; /* mode can't be mixed with free format */
+        break;
+    }
+
+    cfg->free_format = gfp->free_format;
+
+    if (cfg->vbr == vbr_off && gfp->brate == 0) {
+        /* no bitrate or compression ratio specified, use 11.025 */
+        if (EQ(gfp->compression_ratio, 0))
+            gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */
+    }
+
+    /* find bitrate if user specify a compression ratio */
+    if (cfg->vbr == vbr_off && gfp->compression_ratio > 0) {
+
+        if (gfp->samplerate_out == 0)
+            gfp->samplerate_out = map2MP3Frequency((int) (0.97 * gfp->samplerate_in)); /* round up with a margin of 3% */
+
+        /* choose a bitrate for the output samplerate which achieves
+         * specified compression ratio
+         */
+        gfp->brate = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->compression_ratio);
+
+        /* we need the version for the bitrate table look up */
+        cfg->samplerate_index = SmpFrqIndex(gfp->samplerate_out, &cfg->version);
+        assert(cfg->samplerate_index >=0);
+
+        if (!cfg->free_format) /* for non Free Format find the nearest allowed bitrate */
+            gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, gfp->samplerate_out);
+    }
+    if (gfp->samplerate_out) {
+        if (gfp->samplerate_out < 16000) {
+            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
+            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 64);
+        }
+        else if (gfp->samplerate_out < 32000) {
+            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);
+            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 160);
+        }
+        else {
+            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 32);
+            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 320);
+        }
+    }
+    /* WORK IN PROGRESS */
+    /* mapping VBR scale to internal VBR quality settings */
+    if (gfp->samplerate_out == 0 && (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh)) {
+        float const qval = gfp->VBR_q + gfp->VBR_q_frac;
+        struct q_map { int sr_a; float qa, qb, ta, tb; int lp; };
+        struct q_map const m[9]
+        = { {48000, 0.0,6.5,  0.0,6.5, 23700}
+          , {44100, 0.0,6.5,  0.0,6.5, 21780}
+          , {32000, 6.5,8.0,  5.2,6.5, 15800}
+          , {24000, 8.0,8.5,  5.2,6.0, 11850}
+          , {22050, 8.5,9.01, 5.2,6.5, 10892}
+          , {16000, 9.01,9.4, 4.9,6.5,  7903}
+          , {12000, 9.4,9.6,  4.5,6.0,  5928}
+          , {11025, 9.6,9.9,  5.1,6.5,  5446}
+          , { 8000, 9.9,10.,  4.9,6.5,  3952}
+        };
+        for (i = 2; i < 9; ++i) {
+            if (gfp->samplerate_in == m[i].sr_a) {
+                if (qval < m[i].qa) {
+                    double d = qval / m[i].qa;
+                    d = d * m[i].ta;
+                    gfp->VBR_q = (int)d;
+                    gfp->VBR_q_frac = d - gfp->VBR_q;
+                }
+            }
+            if (gfp->samplerate_in >= m[i].sr_a) {
+                if (m[i].qa <= qval && qval < m[i].qb) {
+                    float const q_ = m[i].qb-m[i].qa;
+                    float const t_ = m[i].tb-m[i].ta;
+                    double d = m[i].ta + t_ * (qval-m[i].qa) / q_;
+                    gfp->VBR_q = (int)d;
+                    gfp->VBR_q_frac = d - gfp->VBR_q;
+                    gfp->samplerate_out = m[i].sr_a;
+                    if (gfp->lowpassfreq == 0) {
+                        gfp->lowpassfreq = -1;
+                    }
+                    break;
+                }
+            }
+        }
+    }
+
+    /****************************************************************/
+    /* if a filter has not been enabled, see if we should add one: */
+    /****************************************************************/
+    if (gfp->lowpassfreq == 0) {
+        double  lowpass = 16000;
+        double  highpass;
+
+        switch (cfg->vbr) {
+        case vbr_off:{
+                optimum_bandwidth(&lowpass, &highpass, gfp->brate);
+                break;
+            }
+        case vbr_abr:{
+                optimum_bandwidth(&lowpass, &highpass, gfp->VBR_mean_bitrate_kbps);
+                break;
+            }
+        case vbr_rh:{
+                int const x[11] = {
+                    19500, 19000, 18600, 18000, 17500, 16000, 15600, 14900, 12500, 10000, 3950
+                };
+                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
+                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
+                    lowpass = linear_int(a, b, m);
+                }
+                else {
+                    lowpass = 19500;
+                }
+                break;
+            }
+        case vbr_mtrh:
+        case vbr_mt:{
+                int const x[11] = {
+                    24000, 19500, 18500, 18000, 17500, 17000, 16500, 15600, 15200, 7230, 3950
+                };
+                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
+                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
+                    lowpass = linear_int(a, b, m);
+                }
+                else {
+                    lowpass = 21500;
+                }
+                break;
+            }
+        default:{
+                int const x[11] = {
+                    19500, 19000, 18500, 18000, 17500, 16500, 15500, 14500, 12500, 9500, 3950
+                };
+                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {
+                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;
+                    lowpass = linear_int(a, b, m);
+                }
+                else {
+                    lowpass = 19500;
+                }
+            }
+        }
+
+        if (gfp->mode == MONO && (cfg->vbr == vbr_off || cfg->vbr == vbr_abr))
+            lowpass *= 1.5;
+
+        gfp->lowpassfreq = lowpass;
+    }
+
+    if (gfp->samplerate_out == 0) {
+        if (2 * gfp->lowpassfreq > gfp->samplerate_in) {
+            gfp->lowpassfreq = gfp->samplerate_in / 2;
+        }
+        gfp->samplerate_out = optimum_samplefreq((int) gfp->lowpassfreq, gfp->samplerate_in);
+    }
+    if (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) {
+        gfp->lowpassfreq = Min(24000, gfp->lowpassfreq);
+    }
+    else {
+        gfp->lowpassfreq = Min(20500, gfp->lowpassfreq);
+    }
+    gfp->lowpassfreq = Min(gfp->samplerate_out / 2, gfp->lowpassfreq);
+
+    if (cfg->vbr == vbr_off) {
+        gfp->compression_ratio = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
+    }
+    if (cfg->vbr == vbr_abr) {
+        gfp->compression_ratio =
+            gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
+    }
+
+    cfg->disable_reservoir = gfp->disable_reservoir;
+    cfg->lowpassfreq = gfp->lowpassfreq;
+    cfg->highpassfreq = gfp->highpassfreq;
+    cfg->samplerate_in = gfp->samplerate_in;
+    cfg->samplerate_out = gfp->samplerate_out;
+    cfg->mode_gr = cfg->samplerate_out <= 24000 ? 1 : 2; /* Number of granules per frame */
+
+
+    /*
+     *  sample freq       bitrate     compression ratio
+     *     [kHz]      [kbps/channel]   for 16 bit input
+     *     44.1            56               12.6
+     *     44.1            64               11.025
+     *     44.1            80                8.82
+     *     22.05           24               14.7
+     *     22.05           32               11.025
+     *     22.05           40                8.82
+     *     16              16               16.0
+     *     16              24               10.667
+     *
+     */
+    /*
+     *  For VBR, take a guess at the compression_ratio.
+     *  For example:
+     *
+     *    VBR_q    compression     like
+     *     -        4.4         320 kbps/44 kHz
+     *   0...1      5.5         256 kbps/44 kHz
+     *     2        7.3         192 kbps/44 kHz
+     *     4        8.8         160 kbps/44 kHz
+     *     6       11           128 kbps/44 kHz
+     *     9       14.7          96 kbps
+     *
+     *  for lower bitrates, downsample with --resample
+     */
+
+    switch (cfg->vbr) {
+    case vbr_mt:
+    case vbr_rh:
+    case vbr_mtrh:
+        {
+            /*numbers are a bit strange, but they determine the lowpass value */
+            FLOAT const cmp[] = { 5.7, 6.5, 7.3, 8.2, 10, 11.9, 13, 14, 15, 16.5 };
+            gfp->compression_ratio = cmp[gfp->VBR_q];
+        }
+        break;
+    case vbr_abr:
+        gfp->compression_ratio =
+            cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);
+        break;
+    default:
+        gfp->compression_ratio = cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);
+        break;
+    }
+
+
+    /* mode = -1 (not set by user) or
+     * mode = MONO (because of only 1 input channel).
+     * If mode has not been set, then select J-STEREO
+     */
+    if (gfp->mode == NOT_SET) {
+        gfp->mode = JOINT_STEREO;
+    }
+
+    cfg->mode = gfp->mode;
+
+
+    /* apply user driven high pass filter */
+    if (cfg->highpassfreq > 0) {
+        cfg->highpass1 = 2. * cfg->highpassfreq;
+
+        if (gfp->highpasswidth >= 0)
+            cfg->highpass2 = 2. * (cfg->highpassfreq + gfp->highpasswidth);
+        else            /* 0% above on default */
+            cfg->highpass2 = (1 + 0.00) * 2. * cfg->highpassfreq;
+
+        cfg->highpass1 /= cfg->samplerate_out;
+        cfg->highpass2 /= cfg->samplerate_out;
+    }
+    else {
+        cfg->highpass1 = 0;
+        cfg->highpass2 = 0;
+    }
+    /* apply user driven low pass filter */
+    cfg->lowpass1 = 0;
+    cfg->lowpass2 = 0;
+    if (cfg->lowpassfreq > 0 && cfg->lowpassfreq < (cfg->samplerate_out / 2) ) {
+        cfg->lowpass2 = 2. * cfg->lowpassfreq;
+        if (gfp->lowpasswidth >= 0) {
+            cfg->lowpass1 = 2. * (cfg->lowpassfreq - gfp->lowpasswidth);
+            if (cfg->lowpass1 < 0) /* has to be >= 0 */
+                cfg->lowpass1 = 0;
+        }
+        else {          /* 0% below on default */
+            cfg->lowpass1 = (1 - 0.00) * 2. * cfg->lowpassfreq;
+        }
+        cfg->lowpass1 /= cfg->samplerate_out;
+        cfg->lowpass2 /= cfg->samplerate_out;
+    }
+
+
+
+
+  /**********************************************************************/
+    /* compute info needed for polyphase filter (filter type==0, default) */
+  /**********************************************************************/
+    lame_init_params_ppflt(gfc);
+
+
+  /*******************************************************
+   * samplerate and bitrate index
+   *******************************************************/
+    cfg->samplerate_index = SmpFrqIndex(cfg->samplerate_out, &cfg->version);
+    assert(cfg->samplerate_index >= 0);
+
+    if (cfg->vbr == vbr_off) {
+        if (cfg->free_format) {
+            gfc->ov_enc.bitrate_index = 0;
+        }
+        else {
+            gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, cfg->samplerate_out);
+            gfc->ov_enc.bitrate_index = BitrateIndex(gfp->brate, cfg->version, cfg->samplerate_out);
+            if (gfc->ov_enc.bitrate_index <= 0) {
+                /* This never happens, because of preceding FindNearestBitrate!
+                 * But, set a sane value, just in case
+                 */
+                assert(0);
+                gfc->ov_enc.bitrate_index = 8;
+            }
+        }
+    }
+    else {
+        gfc->ov_enc.bitrate_index = 1;
+    }
+
+    init_bit_stream_w(gfc);
+
+    j = cfg->samplerate_index + (3 * cfg->version) + 6 * (cfg->samplerate_out < 16000);
+    for (i = 0; i < SBMAX_l + 1; i++)
+        gfc->scalefac_band.l[i] = sfBandIndex[j].l[i];
+
+    for (i = 0; i < PSFB21 + 1; i++) {
+        int const size = (gfc->scalefac_band.l[22] - gfc->scalefac_band.l[21]) / PSFB21;
+        int const start = gfc->scalefac_band.l[21] + i * size;
+        gfc->scalefac_band.psfb21[i] = start;
+    }
+    gfc->scalefac_band.psfb21[PSFB21] = 576;
+
+    for (i = 0; i < SBMAX_s + 1; i++)
+        gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];
+
+    for (i = 0; i < PSFB12 + 1; i++) {
+        int const size = (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) / PSFB12;
+        int const start = gfc->scalefac_band.s[12] + i * size;
+        gfc->scalefac_band.psfb12[i] = start;
+    }
+    gfc->scalefac_band.psfb12[PSFB12] = 192;
+
+    /* determine the mean bitrate for main data */
+    if (cfg->mode_gr == 2) /* MPEG 1 */
+        cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 17 : 4 + 32;
+    else                /* MPEG 2 */
+        cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 9 : 4 + 17;
+
+    if (cfg->error_protection)
+        cfg->sideinfo_len += 2;
+
+    {
+        int     k;
+
+        for (k = 0; k < 19; k++)
+            gfc->sv_enc.pefirbuf[k] = 700 * cfg->mode_gr * cfg->channels_out;
+
+        if (gfp->ATHtype == -1)
+            gfp->ATHtype = 4;
+    }
+
+    assert(gfp->VBR_q <= 9);
+    assert(gfp->VBR_q >= 0);
+
+    switch (cfg->vbr) {
+
+    case vbr_mt:
+    case vbr_mtrh:{
+            if (gfp->strict_ISO < 0) {
+                gfp->strict_ISO = MDB_MAXIMUM;
+            }
+            if (gfp->useTemporal < 0) {
+                gfp->useTemporal = 0; /* off by default for this VBR mode */
+            }
+
+            (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
+            /*  The newer VBR code supports only a limited
+               subset of quality levels:
+               9-5=5 are the same, uses x^3/4 quantization
+               4-0=0 are the same  5 plus best huffman divide code
+             */
+            if (gfp->quality < 0)
+                gfp->quality = LAME_DEFAULT_QUALITY;
+            if (gfp->quality < 5)
+                gfp->quality = 0;
+            if (gfp->quality > 7)
+                gfp->quality = 7;
+
+            /*  sfb21 extra only with MPEG-1 at higher sampling rates
+             */
+            if (gfp->experimentalY)
+                gfc->sv_qnt.sfb21_extra = 0;
+            else
+                gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
+
+            break;
+
+        }
+    case vbr_rh:{
+
+            (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);
+
+            /*  sfb21 extra only with MPEG-1 at higher sampling rates
+             */
+            if (gfp->experimentalY)
+                gfc->sv_qnt.sfb21_extra = 0;
+            else
+                gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);
+
+            /*  VBR needs at least the output of GPSYCHO,
+             *  so we have to garantee that by setting a minimum
+             *  quality level, actually level 6 does it.
+             *  down to level 6
+             */
+            if (gfp->quality > 6)
+                gfp->quality = 6;
+
+
+            if (gfp->quality < 0)
+                gfp->quality = LAME_DEFAULT_QUALITY;
+
+            break;
+        }
+
+    default:           /* cbr/abr */  {
+
+            /*  no sfb21 extra with CBR code
+             */
+            gfc->sv_qnt.sfb21_extra = 0;
+
+            if (gfp->quality < 0)
+                gfp->quality = LAME_DEFAULT_QUALITY;
+
+
+            if (cfg->vbr == vbr_off)
+                (void) lame_set_VBR_mean_bitrate_kbps(gfp, gfp->brate);
+            /* second, set parameters depending on bitrate */
+            (void) apply_preset(gfp, gfp->VBR_mean_bitrate_kbps, 0);
+            gfp->VBR = cfg->vbr;
+
+            break;
+        }
+    }
+
+    /*initialize default values common for all modes */
+
+    gfc->sv_qnt.mask_adjust = gfp->maskingadjust;
+    gfc->sv_qnt.mask_adjust_short = gfp->maskingadjust_short;
+
+    /*  just another daily changing developer switch  */
+    if (gfp->tune) {
+        gfc->sv_qnt.mask_adjust += gfp->tune_value_a;
+        gfc->sv_qnt.mask_adjust_short += gfp->tune_value_a;
+    }
+
+
+    if (cfg->vbr != vbr_off) { /* choose a min/max bitrate for VBR */
+        /* if the user didn't specify VBR_max_bitrate: */
+        cfg->vbr_min_bitrate_index = 1; /* default: allow   8 kbps (MPEG-2) or  32 kbps (MPEG-1) */
+        cfg->vbr_max_bitrate_index = 14; /* default: allow 160 kbps (MPEG-2) or 320 kbps (MPEG-1) */
+        if (cfg->samplerate_out < 16000)
+            cfg->vbr_max_bitrate_index = 8; /* default: allow 64 kbps (MPEG-2.5) */
+        if (gfp->VBR_min_bitrate_kbps) {
+            gfp->VBR_min_bitrate_kbps =
+                FindNearestBitrate(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
+            cfg->vbr_min_bitrate_index =
+                BitrateIndex(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);
+            if (cfg->vbr_min_bitrate_index < 0) {
+                /* This never happens, because of preceding FindNearestBitrate!
+                 * But, set a sane value, just in case
+                 */
+                assert(0);
+                cfg->vbr_min_bitrate_index = 1;
+            }
+        }
+        if (gfp->VBR_max_bitrate_kbps) {
+            gfp->VBR_max_bitrate_kbps =
+                FindNearestBitrate(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
+            cfg->vbr_max_bitrate_index =
+                BitrateIndex(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);
+            if (cfg->vbr_max_bitrate_index < 0) {
+                /* This never happens, because of preceding FindNearestBitrate!
+                 * But, set a sane value, just in case
+                 */
+                assert(0);
+                cfg->vbr_max_bitrate_index = cfg->samplerate_out < 16000 ? 8 : 14;
+            }
+        }
+        gfp->VBR_min_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];
+        gfp->VBR_max_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_max_bitrate_index];
+        gfp->VBR_mean_bitrate_kbps =
+            Min(bitrate_table[cfg->version][cfg->vbr_max_bitrate_index],
+                gfp->VBR_mean_bitrate_kbps);
+        gfp->VBR_mean_bitrate_kbps =
+            Max(bitrate_table[cfg->version][cfg->vbr_min_bitrate_index],
+                gfp->VBR_mean_bitrate_kbps);
+    }
+
+    cfg->preset = gfp->preset;
+    cfg->write_lame_tag = gfp->write_lame_tag;
+    gfc->sv_qnt.substep_shaping = gfp->substep_shaping;
+    cfg->noise_shaping = gfp->noise_shaping;
+    cfg->subblock_gain = gfp->subblock_gain;
+    cfg->use_best_huffman = gfp->use_best_huffman;
+    cfg->avg_bitrate = gfp->brate;
+    cfg->vbr_avg_bitrate_kbps = gfp->VBR_mean_bitrate_kbps;
+    cfg->compression_ratio = gfp->compression_ratio;
+
+    /* initialize internal qval settings */
+    lame_init_qval(gfp);
+
+
+    /*  automatic ATH adjustment on
+     */
+    if (gfp->athaa_type < 0)
+        gfc->ATH->use_adjust = 3;
+    else
+        gfc->ATH->use_adjust = gfp->athaa_type;
+
+
+    /* initialize internal adaptive ATH settings  -jd */
+    gfc->ATH->aa_sensitivity_p = pow(10.0, gfp->athaa_sensitivity / -10.0);
+
+
+    if (gfp->short_blocks == short_block_not_set) {
+        gfp->short_blocks = short_block_allowed;
+    }
+
+    /*Note Jan/2003: Many hardware decoders cannot handle short blocks in regular
+       stereo mode unless they are coupled (same type in both channels)
+       it is a rare event (1 frame per min. or so) that LAME would use
+       uncoupled short blocks, so lets turn them off until we decide
+       how to handle this.  No other encoders allow uncoupled short blocks,
+       even though it is in the standard.  */
+    /* rh 20040217: coupling makes no sense for mono and dual-mono streams
+     */
+    if (gfp->short_blocks == short_block_allowed
+        && (cfg->mode == JOINT_STEREO || cfg->mode == STEREO)) {
+        gfp->short_blocks = short_block_coupled;
+    }
+
+    cfg->short_blocks = gfp->short_blocks;
+
+
+    if (lame_get_quant_comp(gfp) < 0)
+        (void) lame_set_quant_comp(gfp, 1);
+    if (lame_get_quant_comp_short(gfp) < 0)
+        (void) lame_set_quant_comp_short(gfp, 0);
+
+    if (lame_get_msfix(gfp) < 0)
+        lame_set_msfix(gfp, 0);
+
+    /* select psychoacoustic model */
+    (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 1);
+
+    if (gfp->ATHtype < 0)
+        gfp->ATHtype = 4;
+
+    if (gfp->ATHcurve < 0)
+        gfp->ATHcurve = 4;
+
+    if (gfp->interChRatio < 0)
+        gfp->interChRatio = 0;
+
+    if (gfp->useTemporal < 0)
+        gfp->useTemporal = 1; /* on by default */
+
+
+    cfg->interChRatio = gfp->interChRatio;
+    cfg->msfix = gfp->msfix;
+    cfg->ATH_offset_db = 0-gfp->ATH_lower_db;
+    cfg->ATH_offset_factor = powf(10.f, cfg->ATH_offset_db * 0.1f);
+    cfg->ATHcurve = gfp->ATHcurve;
+    cfg->ATHtype = gfp->ATHtype;
+    cfg->ATHonly = gfp->ATHonly;
+    cfg->ATHshort = gfp->ATHshort;
+    cfg->noATH = gfp->noATH;
+
+    cfg->quant_comp = gfp->quant_comp;
+    cfg->quant_comp_short = gfp->quant_comp_short;
+
+    cfg->use_temporal_masking_effect = gfp->useTemporal;
+    if (cfg->mode == JOINT_STEREO) {
+        cfg->use_safe_joint_stereo = gfp->exp_nspsytune & 2;
+    }
+    else {
+        cfg->use_safe_joint_stereo = 0;
+    }
+    {
+        cfg->adjust_bass_db = (gfp->exp_nspsytune >> 2) & 63;
+        if (cfg->adjust_bass_db >= 32.f)
+            cfg->adjust_bass_db -= 64.f;
+        cfg->adjust_bass_db *= 0.25f;
+
+        cfg->adjust_alto_db = (gfp->exp_nspsytune >> 8) & 63;
+        if (cfg->adjust_alto_db >= 32.f)
+            cfg->adjust_alto_db -= 64.f;
+        cfg->adjust_alto_db *= 0.25f;
+
+        cfg->adjust_treble_db = (gfp->exp_nspsytune >> 14) & 63;
+        if (cfg->adjust_treble_db >= 32.f)
+            cfg->adjust_treble_db -= 64.f;
+        cfg->adjust_treble_db *= 0.25f;
+
+        /*  to be compatible with Naoki's original code, the next 6 bits
+         *  define only the amount of changing treble for sfb21 */
+        cfg->adjust_sfb21_db = (gfp->exp_nspsytune >> 20) & 63;
+        if (cfg->adjust_sfb21_db >= 32.f)
+            cfg->adjust_sfb21_db -= 64.f;
+        cfg->adjust_sfb21_db *= 0.25f;
+        cfg->adjust_sfb21_db += cfg->adjust_treble_db;
+    }
+
+    /* Setting up the PCM input data transform matrix, to apply 
+     * user defined re-scaling, and or two-to-one channel downmix.
+     */
+    {
+        FLOAT   m[2][2] = { {1.0f, 0.0f}, {0.0f, 1.0f} };
+
+        /* user selected scaling of the samples */
+        m[0][0] *= gfp->scale;
+        m[0][1] *= gfp->scale;
+        m[1][0] *= gfp->scale;
+        m[1][1] *= gfp->scale;
+        /* user selected scaling of the channel 0 (left) samples */
+        m[0][0] *= gfp->scale_left;
+        m[0][1] *= gfp->scale_left;
+        /* user selected scaling of the channel 1 (right) samples */
+        m[1][0] *= gfp->scale_right;
+        m[1][1] *= gfp->scale_right;
+        /* Downsample to Mono if 2 channels in and 1 channel out */
+        if (cfg->channels_in == 2 && cfg->channels_out == 1) {
+            m[0][0] = 0.5f * (m[0][0] + m[1][0]);
+            m[0][1] = 0.5f * (m[0][1] + m[1][1]);
+            m[1][0] = 0;
+            m[1][1] = 0;
+        }
+        cfg->pcm_transform[0][0] = m[0][0];
+        cfg->pcm_transform[0][1] = m[0][1];
+        cfg->pcm_transform[1][0] = m[1][0];
+        cfg->pcm_transform[1][1] = m[1][1];
+    }
+
+    /* padding method as described in
+     * "MPEG-Layer3 / Bitstream Syntax and Decoding"
+     * by Martin Sieler, Ralph Sperschneider
+     *
+     * note: there is no padding for the very first frame
+     *
+     * Robert Hegemann 2000-06-22
+     */
+    gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF = 0;
+    if (cfg->vbr == vbr_off)
+        gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF
+            = ((cfg->version + 1) * 72000L * cfg->avg_bitrate) % cfg->samplerate_out;
+
+    (void) lame_init_bitstream(gfp);
+
+    iteration_init(gfc);
+    (void) psymodel_init(gfp);
+
+    cfg->buffer_constraint = get_max_frame_buffer_size_by_constraint(cfg, gfp->strict_ISO);
+
+
+    cfg->findReplayGain = gfp->findReplayGain;
+    cfg->decode_on_the_fly = gfp->decode_on_the_fly;
+
+    if (cfg->decode_on_the_fly)
+        cfg->findPeakSample = 1;
+
+    if (cfg->findReplayGain) {
+        if (InitGainAnalysis(gfc->sv_rpg.rgdata, cfg->samplerate_out) == INIT_GAIN_ANALYSIS_ERROR) {
+            /* Actually this never happens, our samplerates are the ones RG accepts!
+             * But just in case, turn RG off
+             */
+            assert(0);
+            cfg->findReplayGain = 0;
+        }
+    }
+
+#ifdef DECODE_ON_THE_FLY
+    if (cfg->decode_on_the_fly && !gfp->decode_only) {
+        if (gfc->hip) {
+            hip_decode_exit(gfc->hip);
+        }
+        gfc->hip = hip_decode_init();
+        /* report functions */
+        hip_set_errorf(gfc->hip, gfp->report.errorf);
+        hip_set_debugf(gfc->hip, gfp->report.debugf);
+        hip_set_msgf(gfc->hip, gfp->report.msgf);
+    }
+#endif
+    /* updating lame internal flags finished successful */
+    gfc->lame_init_params_successful = 1;
+    return 0;
+}
+
+static void
+concatSep(char* dest, char const* sep, char const* str)
+{
+    if (*dest != 0) strcat(dest, sep);
+    strcat(dest, str);
+}
+
+/*
+ *  print_config
+ *
+ *  Prints some selected information about the coding parameters via
+ *  the macro command MSGF(), which is currently mapped to lame_errorf
+ *  (reports via a error function?), which is a printf-like function
+ *  for <stderr>.
+ */
+
+void
+lame_print_config(const lame_global_flags * gfp)
+{
+    lame_internal_flags const *const gfc = gfp->internal_flags;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    double const out_samplerate = cfg->samplerate_out;
+    double const in_samplerate = cfg->samplerate_in;
+
+    MSGF(gfc, "LAME %s %s (%s)\n", get_lame_version(), get_lame_os_bitness(), get_lame_url());
+
+#if (LAME_ALPHA_VERSION)
+    MSGF(gfc, "warning: alpha versions should be used for testing only\n");
+#endif
+    if (gfc->CPU_features.MMX
+        || gfc->CPU_features.AMD_3DNow || gfc->CPU_features.SSE || gfc->CPU_features.SSE2) {
+        char    text[256] = { 0 };
+        int     fft_asm_used = 0;
+#ifdef HAVE_NASM
+        if (gfc->CPU_features.AMD_3DNow) {
+            fft_asm_used = 1;
+        }
+        else if (gfc->CPU_features.SSE) {
+            fft_asm_used = 2;
+        }
+#else
+# if defined( HAVE_XMMINTRIN_H ) && defined( MIN_ARCH_SSE )
+        {
+            fft_asm_used = 3;
+        }
+# endif
+#endif
+        if (gfc->CPU_features.MMX) {
+#ifdef MMX_choose_table
+            concatSep(text, ", ", "MMX (ASM used)");
+#else
+            concatSep(text, ", ", "MMX");
+#endif
+        }
+        if (gfc->CPU_features.AMD_3DNow) {
+            concatSep(text, ", ", (fft_asm_used == 1) ? "3DNow! (ASM used)" : "3DNow!");
+        }
+        if (gfc->CPU_features.SSE) {
+#if defined(HAVE_XMMINTRIN_H)
+            concatSep(text, ", ", "SSE (ASM used)");
+#else
+            concatSep(text, ", ", (fft_asm_used == 2) ? "SSE (ASM used)" : "SSE");
+#endif
+        }
+        if (gfc->CPU_features.SSE2) {
+            concatSep(text, ", ", (fft_asm_used == 3) ? "SSE2 (ASM used)" : "SSE2");
+        }
+        MSGF(gfc, "CPU features: %s\n", text);
+    }
+
+    if (cfg->channels_in == 2 && cfg->channels_out == 1 /* mono */ ) {
+        MSGF(gfc, "Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
+    }
+
+    if (isResamplingNecessary(cfg)) {
+        MSGF(gfc, "Resampling:  input %g kHz  output %g kHz\n",
+             1.e-3 * in_samplerate, 1.e-3 * out_samplerate);
+    }
+
+    if (cfg->highpass2 > 0.)
+        MSGF(gfc,
+             "Using polyphase highpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
+             0.5 * cfg->highpass1 * out_samplerate, 0.5 * cfg->highpass2 * out_samplerate);
+    if (0. < cfg->lowpass1 || 0. < cfg->lowpass2) {
+        MSGF(gfc,
+             "Using polyphase lowpass filter, transition band: %5.0f Hz - %5.0f Hz\n",
+             0.5 * cfg->lowpass1 * out_samplerate, 0.5 * cfg->lowpass2 * out_samplerate);
+    }
+    else {
+        MSGF(gfc, "polyphase lowpass filter disabled\n");
+    }
+
+    if (cfg->free_format) {
+        MSGF(gfc, "Warning: many decoders cannot handle free format bitstreams\n");
+        if (cfg->avg_bitrate > 320) {
+            MSGF(gfc,
+                 "Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\n");
+        }
+    }
+}
+
+
+/**     rh:
+ *      some pretty printing is very welcome at this point!
+ *      so, if someone is willing to do so, please do it!
+ *      add more, if you see more...
+ */
+void
+lame_print_internals(const lame_global_flags * gfp)
+{
+    lame_internal_flags const *const gfc = gfp->internal_flags;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    const char *pc = "";
+
+    /*  compiler/processor optimizations, operational, etc.
+     */
+    MSGF(gfc, "\nmisc:\n\n");
+
+    MSGF(gfc, "\tscaling: %g\n", gfp->scale);
+    MSGF(gfc, "\tch0 (left) scaling: %g\n", gfp->scale_left);
+    MSGF(gfc, "\tch1 (right) scaling: %g\n", gfp->scale_right);
+    switch (cfg->use_best_huffman) {
+    default:
+        pc = "normal";
+        break;
+    case 1:
+        pc = "best (outside loop)";
+        break;
+    case 2:
+        pc = "best (inside loop, slow)";
+        break;
+    }
+    MSGF(gfc, "\thuffman search: %s\n", pc);
+    MSGF(gfc, "\texperimental Y=%d\n", gfp->experimentalY);
+    MSGF(gfc, "\t...\n");
+
+    /*  everything controlling the stream format
+     */
+    MSGF(gfc, "\nstream format:\n\n");
+    switch (cfg->version) {
+    case 0:
+        pc = "2.5";
+        break;
+    case 1:
+        pc = "1";
+        break;
+    case 2:
+        pc = "2";
+        break;
+    default:
+        pc = "?";
+        break;
+    }
+    MSGF(gfc, "\tMPEG-%s Layer 3\n", pc);
+    switch (cfg->mode) {
+    case JOINT_STEREO:
+        pc = "joint stereo";
+        break;
+    case STEREO:
+        pc = "stereo";
+        break;
+    case DUAL_CHANNEL:
+        pc = "dual channel";
+        break;
+    case MONO:
+        pc = "mono";
+        break;
+    case NOT_SET:
+        pc = "not set (error)";
+        break;
+    default:
+        pc = "unknown (error)";
+        break;
+    }
+    MSGF(gfc, "\t%d channel - %s\n", cfg->channels_out, pc);
+
+    switch (cfg->vbr) {
+    case vbr_off:
+        pc = "off";
+        break;
+    default:
+        pc = "all";
+        break;
+    }
+    MSGF(gfc, "\tpadding: %s\n", pc);
+
+    if (vbr_default == cfg->vbr)
+        pc = "(default)";
+    else if (cfg->free_format)
+        pc = "(free format)";
+    else
+        pc = "";
+    switch (cfg->vbr) {
+    case vbr_off:
+        MSGF(gfc, "\tconstant bitrate - CBR %s\n", pc);
+        break;
+    case vbr_abr:
+        MSGF(gfc, "\tvariable bitrate - ABR %s\n", pc);
+        break;
+    case vbr_rh:
+        MSGF(gfc, "\tvariable bitrate - VBR rh %s\n", pc);
+        break;
+    case vbr_mt:
+        MSGF(gfc, "\tvariable bitrate - VBR mt %s\n", pc);
+        break;
+    case vbr_mtrh:
+        MSGF(gfc, "\tvariable bitrate - VBR mtrh %s\n", pc);
+        break;
+    default:
+        MSGF(gfc, "\t ?? oops, some new one ?? \n");
+        break;
+    }
+    if (cfg->write_lame_tag)
+        MSGF(gfc, "\tusing LAME Tag\n");
+    MSGF(gfc, "\t...\n");
+
+    /*  everything controlling psychoacoustic settings, like ATH, etc.
+     */
+    MSGF(gfc, "\npsychoacoustic:\n\n");
+
+    switch (cfg->short_blocks) {
+    default:
+    case short_block_not_set:
+        pc = "?";
+        break;
+    case short_block_allowed:
+        pc = "allowed";
+        break;
+    case short_block_coupled:
+        pc = "channel coupled";
+        break;
+    case short_block_dispensed:
+        pc = "dispensed";
+        break;
+    case short_block_forced:
+        pc = "forced";
+        break;
+    }
+    MSGF(gfc, "\tusing short blocks: %s\n", pc);
+    MSGF(gfc, "\tsubblock gain: %d\n", cfg->subblock_gain);
+    MSGF(gfc, "\tadjust masking: %g dB\n", gfc->sv_qnt.mask_adjust);
+    MSGF(gfc, "\tadjust masking short: %g dB\n", gfc->sv_qnt.mask_adjust_short);
+    MSGF(gfc, "\tquantization comparison: %d\n", cfg->quant_comp);
+    MSGF(gfc, "\t ^ comparison short blocks: %d\n", cfg->quant_comp_short);
+    MSGF(gfc, "\tnoise shaping: %d\n", cfg->noise_shaping);
+    MSGF(gfc, "\t ^ amplification: %d\n", cfg->noise_shaping_amp);
+    MSGF(gfc, "\t ^ stopping: %d\n", cfg->noise_shaping_stop);
+
+    pc = "using";
+    if (cfg->ATHshort)
+        pc = "the only masking for short blocks";
+    if (cfg->ATHonly)
+        pc = "the only masking";
+    if (cfg->noATH)
+        pc = "not used";
+    MSGF(gfc, "\tATH: %s\n", pc);
+    MSGF(gfc, "\t ^ type: %d\n", cfg->ATHtype);
+    MSGF(gfc, "\t ^ shape: %g%s\n", cfg->ATHcurve, " (only for type 4)");
+    MSGF(gfc, "\t ^ level adjustement: %g dB\n", cfg->ATH_offset_db);
+    MSGF(gfc, "\t ^ adjust type: %d\n", gfc->ATH->use_adjust);
+    MSGF(gfc, "\t ^ adjust sensitivity power: %f\n", gfc->ATH->aa_sensitivity_p);
+
+    MSGF(gfc, "\texperimental psy tunings by Naoki Shibata\n");
+    MSGF(gfc, "\t   adjust masking bass=%g dB, alto=%g dB, treble=%g dB, sfb21=%g dB\n",
+         10 * log10(gfc->sv_qnt.longfact[0]),
+         10 * log10(gfc->sv_qnt.longfact[7]),
+         10 * log10(gfc->sv_qnt.longfact[14]), 10 * log10(gfc->sv_qnt.longfact[21]));
+
+    pc = cfg->use_temporal_masking_effect ? "yes" : "no";
+    MSGF(gfc, "\tusing temporal masking effect: %s\n", pc);
+    MSGF(gfc, "\tinterchannel masking ratio: %g\n", cfg->interChRatio);
+    MSGF(gfc, "\t...\n");
+
+    /*  that's all ?
+     */
+    MSGF(gfc, "\n");
+    return;
+}
+
+
+static void
+save_gain_values(lame_internal_flags * gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    RpgStateVar_t const *const rsv = &gfc->sv_rpg;
+    RpgResult_t *const rov = &gfc->ov_rpg;
+    /* save the ReplayGain value */
+    if (cfg->findReplayGain) {
+        FLOAT const RadioGain = (FLOAT) GetTitleGain(rsv->rgdata);
+        if (NEQ(RadioGain, GAIN_NOT_ENOUGH_SAMPLES)) {
+            rov->RadioGain = (int) floor(RadioGain * 10.0 + 0.5); /* round to nearest */
+        }
+        else {
+            rov->RadioGain = 0;
+        }
+    }
+
+    /* find the gain and scale change required for no clipping */
+    if (cfg->findPeakSample) {
+        rov->noclipGainChange = (int) ceil(log10(rov->PeakSample / 32767.0) * 20.0 * 10.0); /* round up */
+
+        if (rov->noclipGainChange > 0) { /* clipping occurs */
+            rov->noclipScale = floor((32767.0f / rov->PeakSample) * 100.0f) / 100.0f; /* round down */
+        }
+        else            /* no clipping */
+            rov->noclipScale = -1.0f;
+    }
+}
+
+
+
+static int
+update_inbuffer_size(lame_internal_flags * gfc, const int nsamples)
+{
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    if (esv->in_buffer_0 == 0 || esv->in_buffer_nsamples < nsamples) {
+        if (esv->in_buffer_0) {
+            free(esv->in_buffer_0);
+        }
+        if (esv->in_buffer_1) {
+            free(esv->in_buffer_1);
+        }
+        esv->in_buffer_0 = lame_calloc(sample_t, nsamples);
+        esv->in_buffer_1 = lame_calloc(sample_t, nsamples);
+        esv->in_buffer_nsamples = nsamples;
+    }
+    if (esv->in_buffer_0 == NULL || esv->in_buffer_1 == NULL) {
+        if (esv->in_buffer_0) {
+            free(esv->in_buffer_0);
+        }
+        if (esv->in_buffer_1) {
+            free(esv->in_buffer_1);
+        }
+        esv->in_buffer_0 = 0;
+        esv->in_buffer_1 = 0;
+        esv->in_buffer_nsamples = 0;
+        ERRORF(gfc, "Error: can't allocate in_buffer buffer\n");
+        return -2;
+    }
+    return 0;
+}
+
+
+static int
+calcNeeded(SessionConfig_t const * cfg)
+{
+    int     mf_needed;
+    int     pcm_samples_per_frame = 576 * cfg->mode_gr;
+
+    /* some sanity checks */
+#if ENCDELAY < MDCTDELAY
+# error ENCDELAY is less than MDCTDELAY, see encoder.h
+#endif
+#if FFTOFFSET > BLKSIZE
+# error FFTOFFSET is greater than BLKSIZE, see encoder.h
+#endif
+
+    mf_needed = BLKSIZE + pcm_samples_per_frame - FFTOFFSET; /* amount needed for FFT */
+    /*mf_needed = Max(mf_needed, 286 + 576 * (1 + gfc->mode_gr)); */
+    mf_needed = Max(mf_needed, 512 + pcm_samples_per_frame - 32);
+
+    assert(MFSIZE >= mf_needed);
+    
+    return mf_needed;
+}
+
+
+/*
+ * THE MAIN LAME ENCODING INTERFACE
+ * mt 3/00
+ *
+ * input pcm data, output (maybe) mp3 frames.
+ * This routine handles all buffering, resampling and filtering for you.
+ * The required mp3buffer_size can be computed from num_samples,
+ * samplerate and encoding rate, but here is a worst case estimate:
+ *
+ * mp3buffer_size in bytes = 1.25*num_samples + 7200
+ *
+ * return code = number of bytes output in mp3buffer.  can be 0
+ *
+ * NOTE: this routine uses LAME's internal PCM data representation,
+ * 'sample_t'.  It should not be used by any application.
+ * applications should use lame_encode_buffer(),
+ *                         lame_encode_buffer_float()
+ *                         lame_encode_buffer_int()
+ * etc... depending on what type of data they are working with.
+*/
+static int
+lame_encode_buffer_sample_t(lame_internal_flags * gfc,
+                            int nsamples, unsigned char *mp3buf, const int mp3buf_size)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     pcm_samples_per_frame = 576 * cfg->mode_gr;
+    int     mp3size = 0, ret, i, ch, mf_needed;
+    int     mp3out;
+    sample_t *mfbuf[2];
+    sample_t *in_buffer[2];
+
+    if (gfc->class_id != LAME_ID)
+        return -3;
+
+    if (nsamples == 0)
+        return 0;
+
+    /* copy out any tags that may have been written into bitstream */
+    {   /* if user specifed buffer size = 0, dont check size */
+        int const buf_size = mp3buf_size == 0 ? INT_MAX : mp3buf_size;
+        mp3out = copy_buffer(gfc, mp3buf, buf_size, 0);
+    }
+    if (mp3out < 0)
+        return mp3out;  /* not enough buffer space */
+    mp3buf += mp3out;
+    mp3size += mp3out;
+
+    in_buffer[0] = esv->in_buffer_0;
+    in_buffer[1] = esv->in_buffer_1;
+
+    mf_needed = calcNeeded(cfg);
+
+    mfbuf[0] = esv->mfbuf[0];
+    mfbuf[1] = esv->mfbuf[1];
+
+    while (nsamples > 0) {
+        sample_t const *in_buffer_ptr[2];
+        int     n_in = 0;    /* number of input samples processed with fill_buffer */
+        int     n_out = 0;   /* number of samples output with fill_buffer */
+        /* n_in <> n_out if we are resampling */
+
+        in_buffer_ptr[0] = in_buffer[0];
+        in_buffer_ptr[1] = in_buffer[1];
+        /* copy in new samples into mfbuf, with resampling */
+        fill_buffer(gfc, mfbuf, &in_buffer_ptr[0], nsamples, &n_in, &n_out);
+
+        /* compute ReplayGain of resampled input if requested */
+        if (cfg->findReplayGain && !cfg->decode_on_the_fly)
+            if (AnalyzeSamples
+                (gfc->sv_rpg.rgdata, &mfbuf[0][esv->mf_size], &mfbuf[1][esv->mf_size], n_out,
+                 cfg->channels_out) == GAIN_ANALYSIS_ERROR)
+                return -6;
+
+
+
+        /* update in_buffer counters */
+        nsamples -= n_in;
+        in_buffer[0] += n_in;
+        if (cfg->channels_out == 2)
+            in_buffer[1] += n_in;
+
+        /* update mfbuf[] counters */
+        esv->mf_size += n_out;
+        assert(esv->mf_size <= MFSIZE);
+        
+        /* lame_encode_flush may have set gfc->mf_sample_to_encode to 0
+         * so we have to reinitialize it here when that happened.
+         */
+        if (esv->mf_samples_to_encode < 1) {
+            esv->mf_samples_to_encode = ENCDELAY + POSTDELAY;
+        }        
+        esv->mf_samples_to_encode += n_out;
+
+
+        if (esv->mf_size >= mf_needed) {
+            /* encode the frame.  */
+            /* mp3buf              = pointer to current location in buffer */
+            /* mp3buf_size         = size of original mp3 output buffer */
+            /*                     = 0 if we should not worry about the */
+            /*                       buffer size because calling program is  */
+            /*                       to lazy to compute it */
+            /* mp3size             = size of data written to buffer so far */
+            /* mp3buf_size-mp3size = amount of space avalable  */
+
+            int     buf_size = mp3buf_size - mp3size;
+            if (mp3buf_size == 0)
+                buf_size = INT_MAX;
+
+            ret = lame_encode_mp3_frame(gfc, mfbuf[0], mfbuf[1], mp3buf, buf_size);
+
+            if (ret < 0)
+                return ret;
+            mp3buf += ret;
+            mp3size += ret;
+
+            /* shift out old samples */
+            esv->mf_size -= pcm_samples_per_frame;
+            esv->mf_samples_to_encode -= pcm_samples_per_frame;
+            for (ch = 0; ch < cfg->channels_out; ch++)
+                for (i = 0; i < esv->mf_size; i++)
+                    mfbuf[ch][i] = mfbuf[ch][i + pcm_samples_per_frame];
+        }
+    }
+    assert(nsamples == 0);
+
+    return mp3size;
+}
+
+enum PCMSampleType 
+{   pcm_short_type
+,   pcm_int_type
+,   pcm_long_type
+,   pcm_float_type
+,   pcm_double_type
+};
+
+static void
+lame_copy_inbuffer(lame_internal_flags* gfc, 
+                   void const* l, void const* r, int nsamples,
+                   enum PCMSampleType pcm_type, int jump, FLOAT s)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    sample_t* ib0 = esv->in_buffer_0;
+    sample_t* ib1 = esv->in_buffer_1;
+    FLOAT   m[2][2];
+
+    /* Apply user defined re-scaling */
+    m[0][0] = s * cfg->pcm_transform[0][0];
+    m[0][1] = s * cfg->pcm_transform[0][1];
+    m[1][0] = s * cfg->pcm_transform[1][0];
+    m[1][1] = s * cfg->pcm_transform[1][1];
+
+    /* make a copy of input buffer, changing type to sample_t */
+#define COPY_AND_TRANSFORM(T) \
+{ \
+    T const *bl = l, *br = r; \
+    int     i; \
+    for (i = 0; i < nsamples; i++) { \
+        sample_t const xl = *bl; \
+        sample_t const xr = *br; \
+        sample_t const u = xl * m[0][0] + xr * m[0][1]; \
+        sample_t const v = xl * m[1][0] + xr * m[1][1]; \
+        ib0[i] = u; \
+        ib1[i] = v; \
+        bl += jump; \
+        br += jump; \
+    } \
+}
+    switch ( pcm_type ) {
+    case pcm_short_type: 
+        COPY_AND_TRANSFORM(short int);
+        break;
+    case pcm_int_type:
+        COPY_AND_TRANSFORM(int);
+        break;
+    case pcm_long_type:
+        COPY_AND_TRANSFORM(long int);
+        break;
+    case pcm_float_type:
+        COPY_AND_TRANSFORM(float);
+        break;
+    case pcm_double_type:
+        COPY_AND_TRANSFORM(double);
+        break;
+    }
+}
+
+
+static int
+lame_encode_buffer_template(lame_global_flags * gfp,
+                            void const* buffer_l, void const* buffer_r, const int nsamples,
+                            unsigned char *mp3buf, const int mp3buf_size, enum PCMSampleType pcm_type, int aa, FLOAT norm)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+
+            if (nsamples == 0)
+                return 0;
+
+            if (update_inbuffer_size(gfc, nsamples) != 0) {
+                return -2;
+            }
+            /* make a copy of input buffer, changing type to sample_t */
+            if (cfg->channels_in > 1) {
+                if (buffer_l == 0 || buffer_r == 0) {
+                    return 0;
+                }
+                lame_copy_inbuffer(gfc, buffer_l, buffer_r, nsamples, pcm_type, aa, norm);
+            }
+            else {
+                if (buffer_l == 0) {
+                    return 0;
+                }
+                lame_copy_inbuffer(gfc, buffer_l, buffer_l, nsamples, pcm_type, aa, norm);
+            }
+
+            return lame_encode_buffer_sample_t(gfc, nsamples, mp3buf, mp3buf_size);
+        }
+    }
+    return -3;
+}
+
+int
+lame_encode_buffer(lame_global_flags * gfp,
+                   const short int pcm_l[], const short int pcm_r[], const int nsamples,
+                   unsigned char *mp3buf, const int mp3buf_size)
+{
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_short_type, 1, 1.0);
+}
+
+
+int
+lame_encode_buffer_float(lame_global_flags * gfp,
+                         const float pcm_l[], const float pcm_r[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 32768 for full scale */
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 1.0);
+}
+
+
+int
+lame_encode_buffer_ieee_float(lame_t gfp,
+                         const float pcm_l[], const float pcm_r[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 1.0 for full scale */
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 32767.0);
+}
+
+
+int
+lame_encode_buffer_interleaved_ieee_float(lame_t gfp,
+                         const float pcm[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 1.0 for full scale */
+    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_float_type, 2, 32767.0);
+}
+
+
+int
+lame_encode_buffer_ieee_double(lame_t gfp,
+                         const double pcm_l[], const double pcm_r[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 1.0 for full scale */
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_double_type, 1, 32767.0);
+}
+
+
+int
+lame_encode_buffer_interleaved_ieee_double(lame_t gfp,
+                         const double pcm[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 1.0 for full scale */
+    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_double_type, 2, 32767.0);
+}
+
+
+int
+lame_encode_buffer_int(lame_global_flags * gfp,
+                       const int pcm_l[], const int pcm_r[], const int nsamples,
+                       unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- MAX_INT for full scale */
+    FLOAT const norm = (1.0 / (1L << (8 * sizeof(int) - 16)));
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_int_type, 1, norm);
+}
+
+
+int
+lame_encode_buffer_long2(lame_global_flags * gfp,
+                         const long pcm_l[],  const long pcm_r[], const int nsamples,
+                         unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- MAX_LONG for full scale */
+    FLOAT const norm = (1.0 / (1L << (8 * sizeof(long) - 16)));
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, norm);
+}
+
+
+int
+lame_encode_buffer_long(lame_global_flags * gfp,
+                        const long pcm_l[], const long pcm_r[], const int nsamples,
+                        unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- 32768 for full scale */
+    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, 1.0);
+}
+
+
+
+int
+lame_encode_buffer_interleaved(lame_global_flags * gfp,
+                               short int pcm[], int nsamples,
+                               unsigned char *mp3buf, int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- MAX_SHORT for full scale */
+    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_short_type, 2, 1.0);
+}
+
+
+int
+lame_encode_buffer_interleaved_int(lame_t gfp,
+                                   const int pcm[], const int nsamples,
+                                   unsigned char *mp3buf, const int mp3buf_size)
+{
+    /* input is assumed to be normalized to +/- MAX(int) for full scale */
+    FLOAT const norm = (1.0 / (1L << (8 * sizeof(int)-16)));
+    return lame_encode_buffer_template(gfp, pcm, pcm + 1, nsamples, mp3buf, mp3buf_size, pcm_int_type, 2, norm);
+}
+
+
+
+
+/*****************************************************************
+ Flush mp3 buffer, pad with ancillary data so last frame is complete.
+ Reset reservoir size to 0
+ but keep all PCM samples and MDCT data in memory
+ This option is used to break a large file into several mp3 files
+ that when concatenated together will decode with no gaps
+ Because we set the reservoir=0, they will also decode seperately
+ with no errors.
+*********************************************************************/
+int
+lame_encode_flush_nogap(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
+{
+    int     rc = -3;
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            flush_bitstream(gfc);
+            /* if user specifed buffer size = 0, dont check size */
+            if (mp3buffer_size == 0)
+                mp3buffer_size = INT_MAX;
+            rc = copy_buffer(gfc, mp3buffer, mp3buffer_size, 1);
+            save_gain_values(gfc);
+        }
+    }
+    return rc;
+}
+
+
+/* called by lame_init_params.  You can also call this after flush_nogap
+   if you want to write new id3v2 and Xing VBR tags into the bitstream */
+int
+lame_init_bitstream(lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags *const gfc = gfp->internal_flags;
+        if (gfc != 0) {
+            gfc->ov_enc.frame_number = 0;
+
+            if (gfp->write_id3tag_automatic) {
+                (void) id3tag_write_v2(gfp);
+            }
+            /* initialize histogram data optionally used by frontend */
+            memset(gfc->ov_enc.bitrate_channelmode_hist, 0,
+                   sizeof(gfc->ov_enc.bitrate_channelmode_hist));
+            memset(gfc->ov_enc.bitrate_blocktype_hist, 0,
+                   sizeof(gfc->ov_enc.bitrate_blocktype_hist));
+
+            gfc->ov_rpg.PeakSample = 0.0;
+
+            /* Write initial VBR Header to bitstream and init VBR data */
+            if (gfc->cfg.write_lame_tag)
+                (void) InitVbrTag(gfp);
+
+
+            return 0;
+        }
+    }
+    return -3;
+}
+
+
+/*****************************************************************/
+/* flush internal PCM sample buffers, then mp3 buffers           */
+/* then write id3 v1 tags into bitstream.                        */
+/*****************************************************************/
+
+int
+lame_encode_flush(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
+{
+    lame_internal_flags *gfc;
+    SessionConfig_t const *cfg;
+    EncStateVar_t *esv;
+    short int buffer[2][1152];
+    int     imp3 = 0, mp3count, mp3buffer_size_remaining;
+
+    /* we always add POSTDELAY=288 padding to make sure granule with real
+     * data can be complety decoded (because of 50% overlap with next granule */
+    int     end_padding;
+    int     frames_left;
+    int     samples_to_encode;
+    int     pcm_samples_per_frame;
+    int     mf_needed;
+    int     is_resampling_necessary;
+    double  resample_ratio = 1;
+
+    if (!is_lame_global_flags_valid(gfp)) {
+        return -3;
+    }
+    gfc = gfp->internal_flags;
+    if (!is_lame_internal_flags_valid(gfc)) {
+        return -3;
+    }
+    cfg = &gfc->cfg;
+    esv = &gfc->sv_enc;
+    
+    /* Was flush already called? */
+    if (esv->mf_samples_to_encode < 1) {
+        return 0;
+    }
+    pcm_samples_per_frame = 576 * cfg->mode_gr;
+    mf_needed = calcNeeded(cfg);
+
+    samples_to_encode = esv->mf_samples_to_encode - POSTDELAY;
+
+    memset(buffer, 0, sizeof(buffer));
+    mp3count = 0;
+
+    is_resampling_necessary = isResamplingNecessary(cfg);
+    if (is_resampling_necessary) {
+        resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;
+        /* delay due to resampling; needs to be fixed, if resampling code gets changed */
+        samples_to_encode += 16. / resample_ratio;
+    }
+    end_padding = pcm_samples_per_frame - (samples_to_encode % pcm_samples_per_frame);
+    if (end_padding < 576)
+        end_padding += pcm_samples_per_frame;
+    gfc->ov_enc.encoder_padding = end_padding;
+    
+    frames_left = (samples_to_encode + end_padding) / pcm_samples_per_frame;
+    while (frames_left > 0 && imp3 >= 0) {
+        int const frame_num = gfc->ov_enc.frame_number;
+        int     bunch = mf_needed - esv->mf_size;
+
+        bunch *= resample_ratio;
+        if (bunch > 1152) bunch = 1152;
+        if (bunch < 1) bunch = 1;
+
+        mp3buffer_size_remaining = mp3buffer_size - mp3count;
+
+        /* if user specifed buffer size = 0, dont check size */
+        if (mp3buffer_size == 0)
+            mp3buffer_size_remaining = 0;
+
+        /* send in a frame of 0 padding until all internal sample buffers
+         * are flushed
+         */
+        imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], bunch,
+                                  mp3buffer, mp3buffer_size_remaining);
+
+        mp3buffer += imp3;
+        mp3count += imp3;
+        {   /* even a single pcm sample can produce several frames!
+             * for example: 1 Hz input file resampled to 8 kHz mpeg2.5
+             */
+            int const new_frames = gfc->ov_enc.frame_number - frame_num;
+            if (new_frames > 0)
+                frames_left -=  new_frames;
+        }
+    }
+    /* Set esv->mf_samples_to_encode to 0, so we may detect
+     * and break loops calling it more than once in a row.
+     */
+    esv->mf_samples_to_encode = 0;
+
+    if (imp3 < 0) {
+        /* some type of fatal error */
+        return imp3;
+    }
+
+    mp3buffer_size_remaining = mp3buffer_size - mp3count;
+    /* if user specifed buffer size = 0, dont check size */
+    if (mp3buffer_size == 0)
+        mp3buffer_size_remaining = INT_MAX;
+
+    /* mp3 related stuff.  bit buffer might still contain some mp3 data */
+    flush_bitstream(gfc);
+    imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 1);
+    save_gain_values(gfc);
+    if (imp3 < 0) {
+        /* some type of fatal error */
+        return imp3;
+    }
+    mp3buffer += imp3;
+    mp3count += imp3;
+    mp3buffer_size_remaining = mp3buffer_size - mp3count;
+    /* if user specifed buffer size = 0, dont check size */
+    if (mp3buffer_size == 0)
+        mp3buffer_size_remaining = INT_MAX;
+
+    if (gfp->write_id3tag_automatic) {
+        /* write a id3 tag to the bitstream */
+        (void) id3tag_write_v1(gfp);
+
+        imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 0);
+
+        if (imp3 < 0) {
+            return imp3;
+        }
+        mp3count += imp3;
+    }
+#if 0
+    {
+        int const ed = gfc->ov_enc.encoder_delay;
+        int const ep = gfc->ov_enc.encoder_padding;
+        int const ns = (gfc->ov_enc.frame_number * pcm_samples_per_frame) - (ed + ep);
+        double  duration = ns;
+        duration /= cfg->samplerate_out;
+        MSGF(gfc, "frames=%d\n", gfc->ov_enc.frame_number);
+        MSGF(gfc, "pcm_samples_per_frame=%d\n", pcm_samples_per_frame);
+        MSGF(gfc, "encoder delay=%d\n", ed);
+        MSGF(gfc, "encoder padding=%d\n", ep);
+        MSGF(gfc, "sample count=%d (%g)\n", ns, cfg->samplerate_in * duration);
+        MSGF(gfc, "duration=%g sec\n", duration);
+    }
+#endif
+    return mp3count;
+}
+
+/***********************************************************************
+ *
+ *      lame_close ()
+ *
+ *  frees internal buffers
+ *
+ ***********************************************************************/
+
+int
+lame_close(lame_global_flags * gfp)
+{
+    int     ret = 0;
+    if (gfp && gfp->class_id == LAME_ID) {
+        lame_internal_flags *const gfc = gfp->internal_flags;
+        gfp->class_id = 0;
+        if (NULL == gfc || gfc->class_id != LAME_ID) {
+            ret = -3;
+        }
+        if (NULL != gfc) {
+            gfc->lame_init_params_successful = 0;
+            gfc->class_id = 0;
+            /* this routine will free all malloc'd data in gfc, and then free gfc: */
+            freegfc(gfc);
+            gfp->internal_flags = NULL;
+        }
+        if (gfp->lame_allocated_gfp) {
+            gfp->lame_allocated_gfp = 0;
+            free(gfp);
+        }
+    }
+    return ret;
+}
+
+/*****************************************************************/
+/* flush internal mp3 buffers, and free internal buffers         */
+/*****************************************************************/
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+int CDECL
+lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size);
+#else
+#endif
+
+int
+lame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)
+{
+    int const ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);
+
+    (void) lame_close(gfp);
+
+    return ret;
+}
+
+/*****************************************************************/
+/* write VBR Xing header, and ID3 version 1 tag, if asked for    */
+/*****************************************************************/
+void    lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream);
+
+void
+lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)
+{
+    lame_internal_flags *gfc;
+    SessionConfig_t const *cfg;
+    if (!is_lame_global_flags_valid(gfp)) {
+        return;
+    }
+    gfc = gfp->internal_flags;
+    if (!is_lame_internal_flags_valid(gfc)) {
+        return;
+    }
+    cfg = &gfc->cfg;
+    if (!cfg->write_lame_tag) {
+        return;
+    }
+    /* Write Xing header again */
+    if (fpStream && !fseek(fpStream, 0, SEEK_SET)) {
+        int     rc = PutVbrTag(gfp, fpStream);
+        switch (rc) {
+        default:
+            /* OK */
+            break;
+
+        case -1:
+            ERRORF(gfc, "Error: could not update LAME tag.\n");
+            break;
+
+        case -2:
+            ERRORF(gfc, "Error: could not update LAME tag, file not seekable.\n");
+            break;
+
+        case -3:
+            ERRORF(gfc, "Error: could not update LAME tag, file not readable.\n");
+            break;
+        }
+    }
+}
+
+
+static int
+lame_init_internal_flags(lame_internal_flags* gfc)
+{
+    if (NULL == gfc)
+        return -1;
+
+    gfc->cfg.vbr_min_bitrate_index = 1; /* not  0 ????? */
+    gfc->cfg.vbr_max_bitrate_index = 13; /* not 14 ????? */
+    gfc->cfg.decode_on_the_fly = 0;
+    gfc->cfg.findReplayGain = 0;
+    gfc->cfg.findPeakSample = 0;
+
+    gfc->sv_qnt.OldValue[0] = 180;
+    gfc->sv_qnt.OldValue[1] = 180;
+    gfc->sv_qnt.CurrentStep[0] = 4;
+    gfc->sv_qnt.CurrentStep[1] = 4;
+    gfc->sv_qnt.masking_lower = 1;
+
+    /* The reason for
+     *       int mf_samples_to_encode = ENCDELAY + POSTDELAY;
+     * ENCDELAY = internal encoder delay.  And then we have to add POSTDELAY=288
+     * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to
+     * 1152 samples.  To synthesize the 576 samples centered under this granule
+     * we need the previous granule for the first 288 samples (no problem), and
+     * the next granule for the next 288 samples (not possible if this is last
+     * granule).  So we need to pad with 288 samples to make sure we can
+     * encode the 576 samples we are interested in.
+     */
+    gfc->sv_enc.mf_samples_to_encode = ENCDELAY + POSTDELAY;
+    gfc->sv_enc.mf_size = ENCDELAY - MDCTDELAY; /* we pad input with this many 0's */
+    gfc->ov_enc.encoder_padding = 0;
+    gfc->ov_enc.encoder_delay = ENCDELAY;
+
+    gfc->ov_rpg.RadioGain = 0;
+    gfc->ov_rpg.noclipGainChange = 0;
+    gfc->ov_rpg.noclipScale = -1.0;
+
+    gfc->ATH = lame_calloc(ATH_t, 1);
+    if (NULL == gfc->ATH)
+        return -2;      /* maybe error codes should be enumerated in lame.h ?? */
+
+    gfc->sv_rpg.rgdata = lame_calloc(replaygain_t, 1);
+    if (NULL == gfc->sv_rpg.rgdata) {
+        return -2;
+    }
+    return 0;
+}
+
+/* initialize mp3 encoder */
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+static
+#else
+#endif
+int
+lame_init_old(lame_global_flags * gfp)
+{
+    disable_FPE();      /* disable floating point exceptions */
+
+    memset(gfp, 0, sizeof(lame_global_flags));
+
+    gfp->class_id = LAME_ID;
+
+    /* Global flags.  set defaults here for non-zero values */
+    /* see lame.h for description */
+    /* set integer values to -1 to mean that LAME will compute the
+     * best value, UNLESS the calling program as set it
+     * (and the value is no longer -1)
+     */
+    gfp->strict_ISO = MDB_MAXIMUM;
+
+    gfp->mode = NOT_SET;
+    gfp->original = 1;
+    gfp->samplerate_in = 44100;
+    gfp->num_channels = 2;
+    gfp->num_samples = MAX_U_32_NUM;
+
+    gfp->write_lame_tag = 1;
+    gfp->quality = -1;
+    gfp->short_blocks = short_block_not_set;
+    gfp->subblock_gain = -1;
+
+    gfp->lowpassfreq = 0;
+    gfp->highpassfreq = 0;
+    gfp->lowpasswidth = -1;
+    gfp->highpasswidth = -1;
+
+    gfp->VBR = vbr_off;
+    gfp->VBR_q = 4;
+    gfp->VBR_mean_bitrate_kbps = 128;
+    gfp->VBR_min_bitrate_kbps = 0;
+    gfp->VBR_max_bitrate_kbps = 0;
+    gfp->VBR_hard_min = 0;
+
+    gfp->quant_comp = -1;
+    gfp->quant_comp_short = -1;
+
+    gfp->msfix = -1;
+
+    gfp->attackthre = -1;
+    gfp->attackthre_s = -1;
+
+    gfp->scale = 1;
+    gfp->scale_left = 1;
+    gfp->scale_right = 1;
+
+    gfp->ATHcurve = -1;
+    gfp->ATHtype = -1;  /* default = -1 = set in lame_init_params */
+    /* 2 = equal loudness curve */
+    gfp->athaa_sensitivity = 0.0; /* no offset */
+    gfp->athaa_type = -1;
+    gfp->useTemporal = -1;
+    gfp->interChRatio = -1;
+
+    gfp->findReplayGain = 0;
+    gfp->decode_on_the_fly = 0;
+
+    gfp->asm_optimizations.mmx = 1;
+    gfp->asm_optimizations.amd3dnow = 1;
+    gfp->asm_optimizations.sse = 1;
+
+    gfp->preset = 0;
+
+    gfp->write_id3tag_automatic = 1;
+
+    gfp->report.debugf = &lame_report_def;
+    gfp->report.errorf = &lame_report_def;
+    gfp->report.msgf = &lame_report_def;
+
+    gfp->internal_flags = lame_calloc(lame_internal_flags, 1);
+
+    if (lame_init_internal_flags(gfp->internal_flags) < 0) {
+        freegfc(gfp->internal_flags);
+        gfp->internal_flags = 0;
+        return -1;
+    }
+    return 0;
+}
+
+
+lame_global_flags *
+lame_init(void)
+{
+    lame_global_flags *gfp;
+    int     ret;
+
+    init_log_table();
+
+    gfp = lame_calloc(lame_global_flags, 1);
+    if (gfp == NULL)
+        return NULL;
+
+    ret = lame_init_old(gfp);
+    if (ret != 0) {
+        free(gfp);
+        return NULL;
+    }
+
+    gfp->lame_allocated_gfp = 1;
+    return gfp;
+}
+
+
+/***********************************************************************
+ *
+ *  some simple statistics
+ *
+ *  Robert Hegemann 2000-10-11
+ *
+ ***********************************************************************/
+
+/*  histogram of used bitrate indexes:
+ *  One has to weight them to calculate the average bitrate in kbps
+ *
+ *  bitrate indices:
+ *  there are 14 possible bitrate indices, 0 has the special meaning
+ *  "free format" which is not possible to mix with VBR and 15 is forbidden
+ *  anyway.
+ *
+ *  stereo modes:
+ *  0: LR   number of left-right encoded frames
+ *  1: LR-I number of left-right and intensity encoded frames
+ *  2: MS   number of mid-side encoded frames
+ *  3: MS-I number of mid-side and intensity encoded frames
+ *
+ *  4: number of encoded frames
+ *
+ */
+
+void
+lame_bitrate_kbps(const lame_global_flags * gfp, int bitrate_kbps[14])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            int     i;
+            if (cfg->free_format) {
+                for (i = 0; i < 14; i++)
+                    bitrate_kbps[i] = -1;
+                bitrate_kbps[0] = cfg->avg_bitrate;
+            }
+            else {
+                for (i = 0; i < 14; i++)
+                    bitrate_kbps[i] = bitrate_table[cfg->version][i + 1];
+            }
+        }
+    }
+}
+
+
+void
+lame_bitrate_hist(const lame_global_flags * gfp, int bitrate_count[14])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            EncResult_t const *const eov = &gfc->ov_enc;
+            int     i;
+
+            if (cfg->free_format) {
+                for (i = 0; i < 14; i++) {
+                    bitrate_count[i] = 0;
+                }
+                bitrate_count[0] = eov->bitrate_channelmode_hist[0][4];
+            }
+            else {
+                for (i = 0; i < 14; i++) {
+                    bitrate_count[i] = eov->bitrate_channelmode_hist[i + 1][4];
+                }
+            }
+        }
+    }
+}
+
+
+void
+lame_stereo_mode_hist(const lame_global_flags * gfp, int stmode_count[4])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            EncResult_t const *const eov = &gfc->ov_enc;
+            int     i;
+
+            for (i = 0; i < 4; i++) {
+                stmode_count[i] = eov->bitrate_channelmode_hist[15][i];
+            }
+        }
+    }
+}
+
+
+
+void
+lame_bitrate_stereo_mode_hist(const lame_global_flags * gfp, int bitrate_stmode_count[14][4])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            EncResult_t const *const eov = &gfc->ov_enc;
+            int     i;
+            int     j;
+
+            if (cfg->free_format) {
+                for (j = 0; j < 14; j++)
+                    for (i = 0; i < 4; i++) {
+                        bitrate_stmode_count[j][i] = 0;
+                    }
+                for (i = 0; i < 4; i++) {
+                    bitrate_stmode_count[0][i] = eov->bitrate_channelmode_hist[0][i];
+                }
+            }
+            else {
+                for (j = 0; j < 14; j++) {
+                    for (i = 0; i < 4; i++) {
+                        bitrate_stmode_count[j][i] = eov->bitrate_channelmode_hist[j + 1][i];
+                    }
+                }
+            }
+        }
+    }
+}
+
+
+void
+lame_block_type_hist(const lame_global_flags * gfp, int btype_count[6])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            EncResult_t const *const eov = &gfc->ov_enc;
+            int     i;
+
+            for (i = 0; i < 6; ++i) {
+                btype_count[i] = eov->bitrate_blocktype_hist[15][i];
+            }
+        }
+    }
+}
+
+
+
+void
+lame_bitrate_block_type_hist(const lame_global_flags * gfp, int bitrate_btype_count[14][6])
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            EncResult_t const *const eov = &gfc->ov_enc;
+            int     i, j;
+
+            if (cfg->free_format) {
+                for (j = 0; j < 14; ++j) {
+                    for (i = 0; i < 6; ++i) {
+                        bitrate_btype_count[j][i] = 0;
+                    }
+                }
+                for (i = 0; i < 6; ++i) {
+                    bitrate_btype_count[0][i] = eov->bitrate_blocktype_hist[0][i];
+                }
+            }
+            else {
+                for (j = 0; j < 14; ++j) {
+                    for (i = 0; i < 6; ++i) {
+                        bitrate_btype_count[j][i] = eov->bitrate_blocktype_hist[j + 1][i];
+                    }
+                }
+            }
+        }
+    }
+}
+
+/* end of lame.c */
diff --git a/lame/libmp3lame/lame.rc b/lame/libmp3lame/lame.rc
new file mode 100644 (file)
index 0000000..12d0193
--- /dev/null
@@ -0,0 +1,50 @@
+#include <winver.h>
+#include "version.h"
+
+#ifdef _DLL
+IDI_ICON1              ICON            DISCARDABLE     "logoe.ico"
+#else
+IDI_ICON1              ICON            DISCARDABLE     "logoe.ico"
+#endif
+
+VS_VERSION_INFO VERSIONINFO
+       FILEVERSION LAME_MAJOR_VERSION,LAME_MINOR_VERSION,LAME_TYPE_VERSION,LAME_PATCH_VERSION
+       PRODUCTVERSION LAME_MAJOR_VERSION,LAME_MINOR_VERSION,LAME_TYPE_VERSION,LAME_PATCH_VERSION
+       FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+       FILEFLAGS VS_FF_DEBUG
+#else
+       FILEFLAGS 0x0L
+#endif
+       FILEOS VOS__WINDOWS32
+#ifdef _DLL
+       FILETYPE VFT_DLL
+#else
+       FILETYPE VFT_APP
+#endif
+       FILESUBTYPE 0x0L
+       BEGIN
+               BLOCK "StringFileInfo"
+               BEGIN
+                       BLOCK "040904E4" // Lang=US English, CharSet=Windows Multilingual
+                       BEGIN
+                               VALUE "CompanyName", LAME_URL "\0"
+                               VALUE "FileDescription", "MP3 Encoder.\0"
+                               VALUE "FileVersion", LAME_VERSION_STRING "\0"
+                               VALUE "LegalCopyright", "Copyright (C) 1999-2011 The L.A.M.E. Team\0"
+#ifdef _DLL
+                               VALUE "OriginalFilename", STR(_DLL) "\0"
+#else
+                               VALUE "OriginalFilename", STR(_APP) "\0"
+#endif
+                               VALUE "ProductName", "L.A.M.E.\0"
+                               VALUE "ProductVersion", LAME_VERSION_STRING "\0"
+                       END
+               END
+               BLOCK "VarFileInfo" 
+               BEGIN
+                       VALUE "Translation", 0x409, 1252 // mandatory by convention
+               END
+       END
+/* End of Version info */
+
diff --git a/lame/libmp3lame/lame_global_flags.h b/lame/libmp3lame/lame_global_flags.h
new file mode 100644 (file)
index 0000000..ad9e677
--- /dev/null
@@ -0,0 +1,184 @@
+#ifndef LAME_GLOBAL_FLAGS_H
+#define LAME_GLOBAL_FLAGS_H
+
+#ifndef lame_internal_flags_defined
+#define lame_internal_flags_defined
+struct lame_internal_flags;
+typedef struct lame_internal_flags lame_internal_flags;
+#endif
+
+
+typedef enum short_block_e {
+    short_block_not_set = -1, /* allow LAME to decide */
+    short_block_allowed = 0, /* LAME may use them, even different block types for L/R */
+    short_block_coupled, /* LAME may use them, but always same block types in L/R */
+    short_block_dispensed, /* LAME will not use short blocks, long blocks only */
+    short_block_forced  /* LAME will not use long blocks, short blocks only */
+} short_block_t;
+
+/***********************************************************************
+*
+*  Control Parameters set by User.  These parameters are here for
+*  backwards compatibility with the old, non-shared lib API.
+*  Please use the lame_set_variablename() functions below
+*
+*
+***********************************************************************/
+struct lame_global_struct {
+    unsigned int class_id;
+
+    /* input description */
+    unsigned long num_samples; /* number of samples. default=2^32-1           */
+    int     num_channels;    /* input number of channels. default=2         */
+    int     samplerate_in;   /* input_samp_rate in Hz. default=44.1 kHz     */
+    int     samplerate_out;  /* output_samp_rate.
+                                default: LAME picks best value
+                                at least not used for MP3 decoding:
+                                Remember 44.1 kHz MP3s and AC97           */
+    float   scale;           /* scale input by this amount before encoding
+                                at least not used for MP3 decoding          */
+    float   scale_left;      /* scale input of channel 0 (left) by this
+                                amount before encoding                      */
+    float   scale_right;     /* scale input of channel 1 (right) by this
+                                amount before encoding                      */
+
+    /* general control params */
+    int     analysis;        /* collect data for a MP3 frame analyzer?      */
+    int     write_lame_tag;  /* add Xing VBR tag?                           */
+    int     decode_only;     /* use lame/mpglib to convert mp3 to wav       */
+    int     quality;         /* quality setting 0=best,  9=worst  default=5 */
+    MPEG_mode mode;          /* see enum in lame.h
+                                default = LAME picks best value             */
+    int     force_ms;        /* force M/S mode.  requires mode=1            */
+    int     free_format;     /* use free format? default=0                  */
+    int     findReplayGain;  /* find the RG value? default=0       */
+    int     decode_on_the_fly; /* decode on the fly? default=0                */
+    int     write_id3tag_automatic; /* 1 (default) writes ID3 tags, 0 not */
+
+    int     nogap_total;
+    int     nogap_current;
+
+    int     substep_shaping;
+    int     noise_shaping;
+    int     subblock_gain;   /*  0 = no, 1 = yes */
+    int     use_best_huffman; /* 0 = no.  1=outside loop  2=inside loop(slow) */
+
+    /*
+     * set either brate>0  or compression_ratio>0, LAME will compute
+     * the value of the variable not set.
+     * Default is compression_ratio = 11.025
+     */
+    int     brate;           /* bitrate                                    */
+    float   compression_ratio; /* sizeof(wav file)/sizeof(mp3 file)          */
+
+
+    /* frame params */
+    int     copyright;       /* mark as copyright. default=0           */
+    int     original;        /* mark as original. default=1            */
+    int     extension;       /* the MP3 'private extension' bit.
+                                Meaningless                            */
+    int     emphasis;        /* Input PCM is emphased PCM (for
+                                instance from one of the rarely
+                                emphased CDs), it is STRONGLY not
+                                recommended to use this, because
+                                psycho does not take it into account,
+                                and last but not least many decoders
+                                don't care about these bits          */
+    int     error_protection; /* use 2 bytes per frame for a CRC
+                                 checksum. default=0                    */
+    int     strict_ISO;      /* enforce ISO spec as much as possible   */
+
+    int     disable_reservoir; /* use bit reservoir?                     */
+
+    /* quantization/noise shaping */
+    int     quant_comp;
+    int     quant_comp_short;
+    int     experimentalY;
+    int     experimentalZ;
+    int     exp_nspsytune;
+
+    int     preset;
+
+    /* VBR control */
+    vbr_mode VBR;
+    float   VBR_q_frac;      /* Range [0,...,1[ */
+    int     VBR_q;           /* Range [0,...,9] */
+    int     VBR_mean_bitrate_kbps;
+    int     VBR_min_bitrate_kbps;
+    int     VBR_max_bitrate_kbps;
+    int     VBR_hard_min;    /* strictly enforce VBR_min_bitrate
+                                normaly, it will be violated for analog
+                                silence                                 */
+
+
+    /* resampling and filtering */
+    int     lowpassfreq;     /* freq in Hz. 0=lame choses.
+                                -1=no filter                          */
+    int     highpassfreq;    /* freq in Hz. 0=lame choses.
+                                -1=no filter                          */
+    int     lowpasswidth;    /* freq width of filter, in Hz
+                                (default=15%)                         */
+    int     highpasswidth;   /* freq width of filter, in Hz
+                                (default=15%)                         */
+
+
+
+    /*
+     * psycho acoustics and other arguments which you should not change
+     * unless you know what you are doing
+     */
+    float   maskingadjust;
+    float   maskingadjust_short;
+    int     ATHonly;         /* only use ATH                         */
+    int     ATHshort;        /* only use ATH for short blocks        */
+    int     noATH;           /* disable ATH                          */
+    int     ATHtype;         /* select ATH formula                   */
+    float   ATHcurve;        /* change ATH formula 4 shape           */
+    float   ATH_lower_db;    /* lower ATH by this many db            */
+    int     athaa_type;      /* select ATH auto-adjust scheme        */
+    float   athaa_sensitivity; /* dB, tune active region of auto-level */
+    short_block_t short_blocks;
+    int     useTemporal;     /* use temporal masking effect          */
+    float   interChRatio;
+    float   msfix;           /* Naoki's adjustment of Mid/Side maskings */
+
+    int     tune;            /* 0 off, 1 on */
+    float   tune_value_a;    /* used to pass values for debugging and stuff */
+
+    float   attackthre;      /* attack threshold for L/R/M channel */
+    float   attackthre_s;    /* attack threshold for S channel */
+
+
+    struct {
+        void    (*msgf) (const char *format, va_list ap);
+        void    (*debugf) (const char *format, va_list ap);
+        void    (*errorf) (const char *format, va_list ap);
+    } report;
+
+  /************************************************************************/
+    /* internal variables, do not set...                                    */
+    /* provided because they may be of use to calling application           */
+  /************************************************************************/
+
+    int     lame_allocated_gfp; /* is this struct owned by calling
+                                   program or lame?                     */
+
+
+
+  /**************************************************************************/
+    /* more internal variables are stored in this structure:                  */
+  /**************************************************************************/
+    lame_internal_flags *internal_flags;
+
+
+    struct {
+        int     mmx;
+        int     amd3dnow;
+        int     sse;
+
+    } asm_optimizations;
+};
+
+int     is_lame_global_flags_valid(const lame_global_flags * gfp);
+
+#endif /* LAME_GLOBAL_FLAGS_H */
diff --git a/lame/libmp3lame/lameerror.h b/lame/libmp3lame/lameerror.h
new file mode 100644 (file)
index 0000000..7d9216b
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ *  A collection of LAME Error Codes
+ *
+ *  Please use the constants defined here instead of some arbitrary
+ *  values. Currently the values starting at -10 to avoid intersection
+ *  with the -1, -2, -3 and -4 used in the current code.
+ *
+ *  May be this should be a part of the include/lame.h.
+ */
+
+typedef enum {
+    LAME_OKAY = 0,
+    LAME_NOERROR = 0,
+    LAME_GENERICERROR = -1,
+    LAME_NOMEM = -10,
+    LAME_BADBITRATE = -11,
+    LAME_BADSAMPFREQ = -12,
+    LAME_INTERNALERROR = -13,
+
+    FRONTEND_READERROR = -80,
+    FRONTEND_WRITEERROR = -81,
+    FRONTEND_FILETOOLARGE = -82,
+
+} lame_errorcodes_t;
+
+/* end of lameerror.h */
diff --git a/lame/libmp3lame/logoe.ico b/lame/libmp3lame/logoe.ico
new file mode 100644 (file)
index 0000000..70994ae
Binary files /dev/null and b/lame/libmp3lame/logoe.ico differ
diff --git a/lame/libmp3lame/machine.h b/lame/libmp3lame/machine.h
new file mode 100644 (file)
index 0000000..bf6fff2
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ *      Machine dependent defines/includes for LAME.
+ *
+ *      Copyright (c) 1999 A.L. Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_MACHINE_H
+#define LAME_MACHINE_H
+
+#include "version.h"
+
+#include <stdio.h>
+#include <assert.h>
+
+#ifdef STDC_HEADERS
+# include <stdlib.h>
+# include <string.h>
+#else
+# ifndef HAVE_STRCHR
+#  define strchr index
+#  define strrchr rindex
+# endif
+char   *strchr(), *strrchr();
+# ifndef HAVE_MEMCPY
+#  define memcpy(d, s, n) bcopy ((s), (d), (n))
+#  define memmove(d, s, n) bcopy ((s), (d), (n))
+# endif
+#endif
+
+#if  defined(__riscos__)  &&  defined(FPA10)
+# include "ymath.h"
+#else
+# include <math.h>
+#endif
+#include <limits.h>
+
+#include <ctype.h>
+
+#ifdef HAVE_ERRNO_H
+# include <errno.h>
+#endif
+#ifdef HAVE_FCNTL_H
+# include <fcntl.h>
+#endif
+
+#if defined(macintosh)
+# include <types.h>
+# include <stat.h>
+#else
+# include <sys/types.h>
+# include <sys/stat.h>
+#endif
+
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#else
+# ifdef HAVE_STDINT_H
+#  include <stdint.h>
+# endif
+#endif
+
+#ifdef WITH_DMALLOC
+#include <dmalloc.h>
+#endif
+
+/*
+ * 3 different types of pow() functions:
+ *   - table lookup
+ *   - pow()
+ *   - exp()   on some machines this is claimed to be faster than pow()
+ */
+
+#define POW20(x) (assert(0 <= (x+Q_MAX2) && x < Q_MAX), pow20[x+Q_MAX2])
+/*#define POW20(x)  pow(2.0,((double)(x)-210)*.25) */
+/*#define POW20(x)  exp( ((double)(x)-210)*(.25*LOG2) ) */
+
+#define IPOW20(x)  (assert(0 <= x && x < Q_MAX), ipow20[x])
+/*#define IPOW20(x)  exp( -((double)(x)-210)*.1875*LOG2 ) */
+/*#define IPOW20(x)  pow(2.0,-((double)(x)-210)*.1875) */
+
+/* in case this is used without configure */
+#ifndef inline
+# define inline
+#endif
+
+#if defined(_MSC_VER)
+# undef inline
+# define inline _inline
+#elif defined(__SASC) || defined(__GNUC__) || defined(__ICC) || defined(__ECC)
+/* if __GNUC__ we always want to inline, not only if the user requests it */
+# undef inline
+# define inline __inline
+#endif
+
+#if    defined(_MSC_VER)
+# pragma warning( disable : 4244 )
+/*# pragma warning( disable : 4305 ) */
+#endif
+
+/*
+ * FLOAT    for variables which require at least 32 bits
+ * FLOAT8   for variables which require at least 64 bits
+ *
+ * On some machines, 64 bit will be faster than 32 bit.  Also, some math
+ * routines require 64 bit float, so setting FLOAT=float will result in a
+ * lot of conversions.
+ */
+
+#if ( defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) )
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+# include <float.h>
+# define FLOAT_MAX FLT_MAX
+#else
+# ifndef FLOAT
+typedef float FLOAT;
+#  ifdef FLT_MAX
+#   define FLOAT_MAX FLT_MAX
+#  else
+#   define FLOAT_MAX 1e37 /* approx */
+#  endif
+# endif
+#endif
+
+#ifndef FLOAT8
+typedef double FLOAT8;
+# ifdef DBL_MAX
+#  define FLOAT8_MAX DBL_MAX
+# else
+#  define FLOAT8_MAX 1e99 /* approx */
+# endif
+#else
+# ifdef FLT_MAX
+#  define FLOAT8_MAX FLT_MAX
+# else
+#  define FLOAT8_MAX 1e37 /* approx */
+# endif
+#endif
+
+/* sample_t must be floating point, at least 32 bits */
+typedef FLOAT sample_t;
+
+#define dimension_of(array) (sizeof(array)/sizeof(array[0]))
+#define beyond(array) (array+dimension_of(array))
+#define compiletime_assert(expression) enum{static_assert_##FILE##_##LINE = 1/((expression)?1:0)}
+#define lame_calloc(TYPE, COUNT) ((TYPE*)calloc(COUNT, sizeof(TYPE)))
+#define multiple_of(CHUNK, COUNT) (\
+  ( (COUNT) < 1 || (CHUNK) < 1 || (COUNT) % (CHUNK) == 0 ) \
+  ? (COUNT) \
+  : ((COUNT) + (CHUNK) - (COUNT) % (CHUNK)) \
+  )
+
+#if 1
+#define EQ(a,b) (\
+(fabs(a) > fabs(b)) \
+ ? (fabs((a)-(b)) <= (fabs(a) * 1e-6f)) \
+ : (fabs((a)-(b)) <= (fabs(b) * 1e-6f)))
+#else
+#define EQ(a,b) (fabs((a)-(b))<1E-37)
+#endif
+
+#define NEQ(a,b) (!EQ(a,b))
+
+#ifdef _MSC_VER
+#  if _MSC_VER < 1400
+#  define fabsf fabs
+#  define powf pow
+#  define log10f log10
+#  endif
+#endif
+
+#endif
+
+/* end of machine.h */
diff --git a/lame/libmp3lame/mpglib_interface.c b/lame/libmp3lame/mpglib_interface.c
new file mode 100644 (file)
index 0000000..d0f0b1d
--- /dev/null
@@ -0,0 +1,477 @@
+/* -*- mode: C; mode: fold -*- */
+/*
+ *      LAME MP3 encoding engine
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *      Copyright (c) 2003 Olcios
+ *      Copyright (c) 2008 Robert Hegemann
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: mpglib_interface.c,v 1.44 2012/02/18 13:09:00 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#ifdef HAVE_MPGLIB
+#define hip_global_struct mpstr_tag 
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "interface.h"
+
+#include "util.h"
+
+
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+/*
+ * OBSOLETE:
+ * - kept to let it link
+ * - forward declaration to silence compiler
+ */
+int CDECL lame_decode_init(void);
+int CDECL lame_decode(
+        unsigned char *  mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[] );
+int CDECL lame_decode_headers(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data );
+int CDECL lame_decode1(
+        unsigned char*  mp3buf,
+        int             len,
+        short           pcm_l[],
+        short           pcm_r[] );
+int CDECL lame_decode1_headers(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data );
+int CDECL lame_decode1_headersB(
+        unsigned char*   mp3buf,
+        int              len,
+        short            pcm_l[],
+        short            pcm_r[],
+        mp3data_struct*  mp3data,
+        int              *enc_delay,
+        int              *enc_padding );
+int CDECL lame_decode_exit(void);
+#endif
+
+
+static MPSTR   mp;
+
+int
+lame_decode_exit(void)
+{
+    ExitMP3(&mp);
+    return 0;
+}
+
+
+int
+lame_decode_init(void)
+{
+    (void) InitMP3(&mp);
+    return 0;
+}
+
+
+
+
+/* copy mono samples */
+#define COPY_MONO(DST_TYPE, SRC_TYPE)                                                           \
+    DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw;                                                    \
+    SRC_TYPE const *p_samples = (SRC_TYPE const *)p;                                            \
+    for (i = 0; i < processed_samples; i++)                                                     \
+      *pcm_l++ = (DST_TYPE)(*p_samples++);
+
+/* copy stereo samples */
+#define COPY_STEREO(DST_TYPE, SRC_TYPE)                                                         \
+    DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw, *pcm_r = (DST_TYPE *)pcm_r_raw;                    \
+    SRC_TYPE const *p_samples = (SRC_TYPE const *)p;                                            \
+    for (i = 0; i < processed_samples; i++) {                                                   \
+      *pcm_l++ = (DST_TYPE)(*p_samples++);                                                      \
+      *pcm_r++ = (DST_TYPE)(*p_samples++);                                                      \
+    }
+
+
+
+/*
+ * For lame_decode:  return code
+ * -1     error
+ *  0     ok, but need more data before outputing any samples
+ *  n     number of samples output.  either 576 or 1152 depending on MP3 file.
+ */
+
+static int
+decode1_headersB_clipchoice(PMPSTR pmp, unsigned char *buffer, size_t len,
+                            char pcm_l_raw[], char pcm_r_raw[], mp3data_struct * mp3data,
+                            int *enc_delay, int *enc_padding,
+                            char *p, size_t psize, int decoded_sample_size,
+                            int (*decodeMP3_ptr) (PMPSTR, unsigned char *, int, char *, int,
+                            int *))
+{
+    static const int smpls[2][4] = {
+        /* Layer   I    II   III */
+        {0, 384, 1152, 1152}, /* MPEG-1     */
+        {0, 384, 1152, 576} /* MPEG-2(.5) */
+    };
+
+    int     processed_bytes;
+    int     processed_samples; /* processed samples per channel */
+    int     ret;
+    int     i;
+    int const len_l = len < INT_MAX ? (int) len : INT_MAX;
+    int const psize_l = psize < INT_MAX ? (int) psize : INT_MAX;
+
+    mp3data->header_parsed = 0;
+    ret = (*decodeMP3_ptr) (pmp, buffer, len_l, p, psize_l, &processed_bytes);
+    /* three cases:  
+     * 1. headers parsed, but data not complete
+     *       pmp->header_parsed==1 
+     *       pmp->framesize=0           
+     *       pmp->fsizeold=size of last frame, or 0 if this is first frame
+     *
+     * 2. headers, data parsed, but ancillary data not complete
+     *       pmp->header_parsed==1 
+     *       pmp->framesize=size of frame           
+     *       pmp->fsizeold=size of last frame, or 0 if this is first frame
+     *
+     * 3. frame fully decoded:  
+     *       pmp->header_parsed==0 
+     *       pmp->framesize=0           
+     *       pmp->fsizeold=size of frame (which is now the last frame)
+     *
+     */
+    if (pmp->header_parsed || pmp->fsizeold > 0 || pmp->framesize > 0) {
+        mp3data->header_parsed = 1;
+        mp3data->stereo = pmp->fr.stereo;
+        mp3data->samplerate = freqs[pmp->fr.sampling_frequency];
+        mp3data->mode = pmp->fr.mode;
+        mp3data->mode_ext = pmp->fr.mode_ext;
+        mp3data->framesize = smpls[pmp->fr.lsf][pmp->fr.lay];
+
+        /* free format, we need the entire frame before we can determine
+         * the bitrate.  If we haven't gotten the entire frame, bitrate=0 */
+        if (pmp->fsizeold > 0) /* works for free format and fixed, no overrun, temporal results are < 400.e6 */
+            mp3data->bitrate = 8 * (4 + pmp->fsizeold) * mp3data->samplerate /
+                (1.e3 * mp3data->framesize) + 0.5;
+        else if (pmp->framesize > 0)
+            mp3data->bitrate = 8 * (4 + pmp->framesize) * mp3data->samplerate /
+                (1.e3 * mp3data->framesize) + 0.5;
+        else
+            mp3data->bitrate = tabsel_123[pmp->fr.lsf][pmp->fr.lay - 1][pmp->fr.bitrate_index];
+
+
+
+        if (pmp->num_frames > 0) {
+            /* Xing VBR header found and num_frames was set */
+            mp3data->totalframes = pmp->num_frames;
+            mp3data->nsamp = mp3data->framesize * pmp->num_frames;
+            *enc_delay = pmp->enc_delay;
+            *enc_padding = pmp->enc_padding;
+        }
+    }
+
+    switch (ret) {
+    case MP3_OK:
+        switch (pmp->fr.stereo) {
+        case 1:
+            processed_samples = processed_bytes / decoded_sample_size;
+            if (decoded_sample_size == sizeof(short)) {
+                COPY_MONO(short, short)
+            }
+            else {
+                COPY_MONO(sample_t, FLOAT)
+            }
+            break;
+        case 2:
+            processed_samples = (processed_bytes / decoded_sample_size) >> 1;
+            if (decoded_sample_size == sizeof(short)) {
+                COPY_STEREO(short, short)
+            }
+            else {
+                COPY_STEREO(sample_t, FLOAT)
+            }
+            break;
+        default:
+            processed_samples = -1;
+            assert(0);
+            break;
+        }
+        break;
+
+    case MP3_NEED_MORE:
+        processed_samples = 0;
+        break;
+
+    case MP3_ERR:
+        processed_samples = -1;
+        break;
+
+    default:
+        processed_samples = -1;
+        assert(0);
+        break;
+    }
+
+    /*fprintf(stderr,"ok, more, err:  %i %i %i\n", MP3_OK, MP3_NEED_MORE, MP3_ERR ); */
+    /*fprintf(stderr,"ret = %i out=%i\n", ret, processed_samples ); */
+    return processed_samples;
+}
+
+
+#define OUTSIZE_CLIPPED   (4096*sizeof(short))
+
+int
+lame_decode1_headersB(unsigned char *buffer,
+                      int len,
+                      short pcm_l[], short pcm_r[], mp3data_struct * mp3data,
+                      int *enc_delay, int *enc_padding)
+{
+    static char out[OUTSIZE_CLIPPED];
+
+    return decode1_headersB_clipchoice(&mp, buffer, len, (char *) pcm_l, (char *) pcm_r, mp3data,
+                                       enc_delay, enc_padding, out, OUTSIZE_CLIPPED,
+                                       sizeof(short), decodeMP3);
+}
+
+
+
+
+
+/*
+ * For lame_decode:  return code
+ *  -1     error
+ *   0     ok, but need more data before outputing any samples
+ *   n     number of samples output.  Will be at most one frame of
+ *         MPEG data.  
+ */
+
+int
+lame_decode1_headers(unsigned char *buffer,
+                     int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
+{
+    int     enc_delay, enc_padding;
+    return lame_decode1_headersB(buffer, len, pcm_l, pcm_r, mp3data, &enc_delay, &enc_padding);
+}
+
+
+int
+lame_decode1(unsigned char *buffer, int len, short pcm_l[], short pcm_r[])
+{
+    mp3data_struct mp3data;
+
+    return lame_decode1_headers(buffer, len, pcm_l, pcm_r, &mp3data);
+}
+
+
+/*
+ * For lame_decode:  return code
+ *  -1     error
+ *   0     ok, but need more data before outputing any samples
+ *   n     number of samples output.  a multiple of 576 or 1152 depending on MP3 file.
+ */
+
+int
+lame_decode_headers(unsigned char *buffer,
+                    int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
+{
+    int     ret;
+    int     totsize = 0;     /* number of decoded samples per channel */
+
+    for (;;) {
+        switch (ret = lame_decode1_headers(buffer, len, pcm_l + totsize, pcm_r + totsize, mp3data)) {
+        case -1:
+            return ret;
+        case 0:
+            return totsize;
+        default:
+            totsize += ret;
+            len = 0;    /* future calls to decodeMP3 are just to flush buffers */
+            break;
+        }
+    }
+}
+
+
+int
+lame_decode(unsigned char *buffer, int len, short pcm_l[], short pcm_r[])
+{
+    mp3data_struct mp3data;
+
+    return lame_decode_headers(buffer, len, pcm_l, pcm_r, &mp3data);
+}
+
+
+
+
+hip_t hip_decode_init(void)
+{
+    hip_t hip = lame_calloc(hip_global_flags, 1);
+    InitMP3(hip);
+    return hip;
+}
+
+
+int hip_decode_exit(hip_t hip)
+{
+    if (hip) {
+        ExitMP3(hip);
+        free(hip);
+    }
+    return 0;
+}
+
+
+/* we forbid input with more than 1152 samples per channel for output in the unclipped mode */
+#define OUTSIZE_UNCLIPPED (1152*2*sizeof(FLOAT))
+
+int
+hip_decode1_unclipped(hip_t hip, unsigned char *buffer, size_t len, sample_t pcm_l[], sample_t pcm_r[])
+{
+    static char out[OUTSIZE_UNCLIPPED];
+    mp3data_struct mp3data;
+    int     enc_delay, enc_padding;
+
+    if (hip) {
+        return decode1_headersB_clipchoice(hip, buffer, len, (char *) pcm_l, (char *) pcm_r, &mp3data,
+                                           &enc_delay, &enc_padding, out, OUTSIZE_UNCLIPPED,
+                                           sizeof(FLOAT), decodeMP3_unclipped);
+    }
+    return 0;
+}
+
+/*
+ * For hip_decode:  return code
+ *  -1     error
+ *   0     ok, but need more data before outputing any samples
+ *   n     number of samples output.  Will be at most one frame of
+ *         MPEG data.  
+ */
+
+int
+hip_decode1_headers(hip_t hip, unsigned char *buffer,
+                     size_t len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
+{
+    int     enc_delay, enc_padding;
+    return hip_decode1_headersB(hip, buffer, len, pcm_l, pcm_r, mp3data, &enc_delay, &enc_padding);
+}
+
+
+int
+hip_decode1(hip_t hip, unsigned char *buffer, size_t len, short pcm_l[], short pcm_r[])
+{
+    mp3data_struct mp3data;
+    return hip_decode1_headers(hip, buffer, len, pcm_l, pcm_r, &mp3data);
+}
+
+
+/*
+ * For hip_decode:  return code
+ *  -1     error
+ *   0     ok, but need more data before outputing any samples
+ *   n     number of samples output.  a multiple of 576 or 1152 depending on MP3 file.
+ */
+
+int
+hip_decode_headers(hip_t hip, unsigned char *buffer,
+                    size_t len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)
+{
+    int     ret;
+    int     totsize = 0;     /* number of decoded samples per channel */
+
+    for (;;) {
+        switch (ret = hip_decode1_headers(hip, buffer, len, pcm_l + totsize, pcm_r + totsize, mp3data)) {
+        case -1:
+            return ret;
+        case 0:
+            return totsize;
+        default:
+            totsize += ret;
+            len = 0;    /* future calls to decodeMP3 are just to flush buffers */
+            break;
+        }
+    }
+}
+
+
+int
+hip_decode(hip_t hip, unsigned char *buffer, size_t len, short pcm_l[], short pcm_r[])
+{
+    mp3data_struct mp3data;
+    return hip_decode_headers(hip, buffer, len, pcm_l, pcm_r, &mp3data);
+}
+
+
+int
+hip_decode1_headersB(hip_t hip, unsigned char *buffer,
+                      size_t len,
+                      short pcm_l[], short pcm_r[], mp3data_struct * mp3data,
+                      int *enc_delay, int *enc_padding)
+{
+    static char out[OUTSIZE_CLIPPED];
+    if (hip) {
+        return decode1_headersB_clipchoice(hip, buffer, len, (char *) pcm_l, (char *) pcm_r, mp3data,
+                                           enc_delay, enc_padding, out, OUTSIZE_CLIPPED,
+                                           sizeof(short), decodeMP3);
+    }
+    return -1;
+}
+
+
+void hip_set_pinfo(hip_t hip, plotting_data* pinfo)
+{
+    if (hip) {
+        hip->pinfo = pinfo;
+    }
+}
+
+
+
+void hip_set_errorf(hip_t hip, lame_report_function func)
+{
+    if (hip) {
+        hip->report_err = func;
+    }
+}
+
+void hip_set_debugf(hip_t hip, lame_report_function func)
+{
+    if (hip) {
+        hip->report_dbg = func;
+    }
+}
+
+void hip_set_msgf  (hip_t hip, lame_report_function func)
+{
+    if (hip) {
+        hip->report_msg = func;
+    }
+}
+
+#endif
+
+/* end of mpglib_interface.c */
diff --git a/lame/libmp3lame/newmdct.c b/lame/libmp3lame/newmdct.c
new file mode 100644 (file)
index 0000000..596cac9
--- /dev/null
@@ -0,0 +1,1039 @@
+/*
+ *      MP3 window subband -> subband filtering -> mdct routine
+ *
+ *      Copyright (c) 1999-2000 Takehiro Tominaga
+ *
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/*
+ *         Special Thanks to Patrick De Smet for your advices.
+ */
+
+/* $Id: newmdct.c,v 1.39 2011/05/07 16:05:17 rbrito Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "newmdct.h"
+
+
+
+#ifndef USE_GOGO_SUBBAND
+static const FLOAT enwindow[] = {
+    -4.77e-07 * 0.740951125354959 / 2.384e-06, 1.03951e-04 * 0.740951125354959 / 2.384e-06,
+    9.53674e-04 * 0.740951125354959 / 2.384e-06, 2.841473e-03 * 0.740951125354959 / 2.384e-06,
+    3.5758972e-02 * 0.740951125354959 / 2.384e-06, 3.401756e-03 * 0.740951125354959 / 2.384e-06, 9.83715e-04 * 0.740951125354959 / 2.384e-06, 9.9182e-05 * 0.740951125354959 / 2.384e-06, /* 15 */
+    1.2398e-05 * 0.740951125354959 / 2.384e-06, 1.91212e-04 * 0.740951125354959 / 2.384e-06,
+    2.283096e-03 * 0.740951125354959 / 2.384e-06, 1.6994476e-02 * 0.740951125354959 / 2.384e-06,
+    -1.8756866e-02 * 0.740951125354959 / 2.384e-06, -2.630711e-03 * 0.740951125354959 / 2.384e-06,
+    -2.47478e-04 * 0.740951125354959 / 2.384e-06, -1.4782e-05 * 0.740951125354959 / 2.384e-06,
+    9.063471690191471e-01,
+    1.960342806591213e-01,
+
+
+    -4.77e-07 * 0.773010453362737 / 2.384e-06, 1.05858e-04 * 0.773010453362737 / 2.384e-06,
+    9.30786e-04 * 0.773010453362737 / 2.384e-06, 2.521515e-03 * 0.773010453362737 / 2.384e-06,
+    3.5694122e-02 * 0.773010453362737 / 2.384e-06, 3.643036e-03 * 0.773010453362737 / 2.384e-06, 9.91821e-04 * 0.773010453362737 / 2.384e-06, 9.6321e-05 * 0.773010453362737 / 2.384e-06, /* 14 */
+    1.1444e-05 * 0.773010453362737 / 2.384e-06, 1.65462e-04 * 0.773010453362737 / 2.384e-06,
+    2.110004e-03 * 0.773010453362737 / 2.384e-06, 1.6112804e-02 * 0.773010453362737 / 2.384e-06,
+    -1.9634247e-02 * 0.773010453362737 / 2.384e-06, -2.803326e-03 * 0.773010453362737 / 2.384e-06,
+    -2.77042e-04 * 0.773010453362737 / 2.384e-06, -1.6689e-05 * 0.773010453362737 / 2.384e-06,
+    8.206787908286602e-01,
+    3.901806440322567e-01,
+
+
+    -4.77e-07 * 0.803207531480645 / 2.384e-06, 1.07288e-04 * 0.803207531480645 / 2.384e-06,
+    9.02653e-04 * 0.803207531480645 / 2.384e-06, 2.174854e-03 * 0.803207531480645 / 2.384e-06,
+    3.5586357e-02 * 0.803207531480645 / 2.384e-06, 3.858566e-03 * 0.803207531480645 / 2.384e-06, 9.95159e-04 * 0.803207531480645 / 2.384e-06, 9.3460e-05 * 0.803207531480645 / 2.384e-06, /* 13 */
+    1.0014e-05 * 0.803207531480645 / 2.384e-06, 1.40190e-04 * 0.803207531480645 / 2.384e-06,
+    1.937389e-03 * 0.803207531480645 / 2.384e-06, 1.5233517e-02 * 0.803207531480645 / 2.384e-06,
+    -2.0506859e-02 * 0.803207531480645 / 2.384e-06, -2.974033e-03 * 0.803207531480645 / 2.384e-06,
+    -3.07560e-04 * 0.803207531480645 / 2.384e-06, -1.8120e-05 * 0.803207531480645 / 2.384e-06,
+    7.416505462720353e-01,
+    5.805693545089249e-01,
+
+
+    -4.77e-07 * 0.831469612302545 / 2.384e-06, 1.08242e-04 * 0.831469612302545 / 2.384e-06,
+    8.68797e-04 * 0.831469612302545 / 2.384e-06, 1.800537e-03 * 0.831469612302545 / 2.384e-06,
+    3.5435200e-02 * 0.831469612302545 / 2.384e-06, 4.049301e-03 * 0.831469612302545 / 2.384e-06, 9.94205e-04 * 0.831469612302545 / 2.384e-06, 9.0599e-05 * 0.831469612302545 / 2.384e-06, /* 12 */
+    9.060e-06 * 0.831469612302545 / 2.384e-06, 1.16348e-04 * 0.831469612302545 / 2.384e-06,
+    1.766682e-03 * 0.831469612302545 / 2.384e-06, 1.4358521e-02 * 0.831469612302545 / 2.384e-06,
+    -2.1372318e-02 * 0.831469612302545 / 2.384e-06, -3.14188e-03 * 0.831469612302545 / 2.384e-06,
+    -3.39031e-04 * 0.831469612302545 / 2.384e-06, -1.9550e-05 * 0.831469612302545 / 2.384e-06,
+    6.681786379192989e-01,
+    7.653668647301797e-01,
+
+
+    -4.77e-07 * 0.857728610000272 / 2.384e-06, 1.08719e-04 * 0.857728610000272 / 2.384e-06,
+    8.29220e-04 * 0.857728610000272 / 2.384e-06, 1.399517e-03 * 0.857728610000272 / 2.384e-06,
+    3.5242081e-02 * 0.857728610000272 / 2.384e-06, 4.215240e-03 * 0.857728610000272 / 2.384e-06, 9.89437e-04 * 0.857728610000272 / 2.384e-06, 8.7261e-05 * 0.857728610000272 / 2.384e-06, /* 11 */
+    8.106e-06 * 0.857728610000272 / 2.384e-06, 9.3937e-05 * 0.857728610000272 / 2.384e-06,
+    1.597881e-03 * 0.857728610000272 / 2.384e-06, 1.3489246e-02 * 0.857728610000272 / 2.384e-06,
+    -2.2228718e-02 * 0.857728610000272 / 2.384e-06, -3.306866e-03 * 0.857728610000272 / 2.384e-06,
+    -3.71456e-04 * 0.857728610000272 / 2.384e-06, -2.1458e-05 * 0.857728610000272 / 2.384e-06,
+    5.993769336819237e-01,
+    9.427934736519954e-01,
+
+
+    -4.77e-07 * 0.881921264348355 / 2.384e-06, 1.08719e-04 * 0.881921264348355 / 2.384e-06,
+    7.8392e-04 * 0.881921264348355 / 2.384e-06, 9.71317e-04 * 0.881921264348355 / 2.384e-06,
+    3.5007000e-02 * 0.881921264348355 / 2.384e-06, 4.357815e-03 * 0.881921264348355 / 2.384e-06, 9.80854e-04 * 0.881921264348355 / 2.384e-06, 8.3923e-05 * 0.881921264348355 / 2.384e-06, /* 10 */
+    7.629e-06 * 0.881921264348355 / 2.384e-06, 7.2956e-05 * 0.881921264348355 / 2.384e-06,
+    1.432419e-03 * 0.881921264348355 / 2.384e-06, 1.2627602e-02 * 0.881921264348355 / 2.384e-06,
+    -2.3074150e-02 * 0.881921264348355 / 2.384e-06, -3.467083e-03 * 0.881921264348355 / 2.384e-06,
+    -4.04358e-04 * 0.881921264348355 / 2.384e-06, -2.3365e-05 * 0.881921264348355 / 2.384e-06,
+    5.345111359507916e-01,
+    1.111140466039205e+00,
+
+
+    -9.54e-07 * 0.903989293123443 / 2.384e-06, 1.08242e-04 * 0.903989293123443 / 2.384e-06,
+    7.31945e-04 * 0.903989293123443 / 2.384e-06, 5.15938e-04 * 0.903989293123443 / 2.384e-06,
+    3.4730434e-02 * 0.903989293123443 / 2.384e-06, 4.477024e-03 * 0.903989293123443 / 2.384e-06, 9.68933e-04 * 0.903989293123443 / 2.384e-06, 8.0585e-05 * 0.903989293123443 / 2.384e-06, /* 9 */
+    6.676e-06 * 0.903989293123443 / 2.384e-06, 5.2929e-05 * 0.903989293123443 / 2.384e-06,
+    1.269817e-03 * 0.903989293123443 / 2.384e-06, 1.1775017e-02 * 0.903989293123443 / 2.384e-06,
+    -2.3907185e-02 * 0.903989293123443 / 2.384e-06, -3.622532e-03 * 0.903989293123443 / 2.384e-06,
+    -4.38213e-04 * 0.903989293123443 / 2.384e-06, -2.5272e-05 * 0.903989293123443 / 2.384e-06,
+    4.729647758913199e-01,
+    1.268786568327291e+00,
+
+
+    -9.54e-07 * 0.92387953251128675613 / 2.384e-06,
+    1.06812e-04 * 0.92387953251128675613 / 2.384e-06,
+    6.74248e-04 * 0.92387953251128675613 / 2.384e-06,
+    3.3379e-05 * 0.92387953251128675613 / 2.384e-06,
+    3.4412861e-02 * 0.92387953251128675613 / 2.384e-06,
+    4.573822e-03 * 0.92387953251128675613 / 2.384e-06,
+    9.54151e-04 * 0.92387953251128675613 / 2.384e-06,
+    7.6771e-05 * 0.92387953251128675613 / 2.384e-06,
+    6.199e-06 * 0.92387953251128675613 / 2.384e-06, 3.4332e-05 * 0.92387953251128675613 / 2.384e-06,
+    1.111031e-03 * 0.92387953251128675613 / 2.384e-06,
+    1.0933399e-02 * 0.92387953251128675613 / 2.384e-06,
+    -2.4725437e-02 * 0.92387953251128675613 / 2.384e-06,
+    -3.771782e-03 * 0.92387953251128675613 / 2.384e-06,
+    -4.72546e-04 * 0.92387953251128675613 / 2.384e-06,
+    -2.7657e-05 * 0.92387953251128675613 / 2.384e-06,
+    4.1421356237309504879e-01, /* tan(PI/8) */
+    1.414213562373095e+00,
+
+
+    -9.54e-07 * 0.941544065183021 / 2.384e-06, 1.05381e-04 * 0.941544065183021 / 2.384e-06,
+    6.10352e-04 * 0.941544065183021 / 2.384e-06, -4.75883e-04 * 0.941544065183021 / 2.384e-06,
+    3.4055710e-02 * 0.941544065183021 / 2.384e-06, 4.649162e-03 * 0.941544065183021 / 2.384e-06, 9.35555e-04 * 0.941544065183021 / 2.384e-06, 7.3433e-05 * 0.941544065183021 / 2.384e-06, /* 7 */
+    5.245e-06 * 0.941544065183021 / 2.384e-06, 1.7166e-05 * 0.941544065183021 / 2.384e-06,
+    9.56535e-04 * 0.941544065183021 / 2.384e-06, 1.0103703e-02 * 0.941544065183021 / 2.384e-06,
+    -2.5527000e-02 * 0.941544065183021 / 2.384e-06, -3.914356e-03 * 0.941544065183021 / 2.384e-06,
+    -5.07355e-04 * 0.941544065183021 / 2.384e-06, -3.0041e-05 * 0.941544065183021 / 2.384e-06,
+    3.578057213145241e-01,
+    1.546020906725474e+00,
+
+
+    -9.54e-07 * 0.956940335732209 / 2.384e-06, 1.02520e-04 * 0.956940335732209 / 2.384e-06,
+    5.39303e-04 * 0.956940335732209 / 2.384e-06, -1.011848e-03 * 0.956940335732209 / 2.384e-06,
+    3.3659935e-02 * 0.956940335732209 / 2.384e-06, 4.703045e-03 * 0.956940335732209 / 2.384e-06, 9.15051e-04 * 0.956940335732209 / 2.384e-06, 7.0095e-05 * 0.956940335732209 / 2.384e-06, /* 6 */
+    4.768e-06 * 0.956940335732209 / 2.384e-06, 9.54e-07 * 0.956940335732209 / 2.384e-06,
+    8.06808e-04 * 0.956940335732209 / 2.384e-06, 9.287834e-03 * 0.956940335732209 / 2.384e-06,
+    -2.6310921e-02 * 0.956940335732209 / 2.384e-06, -4.048824e-03 * 0.956940335732209 / 2.384e-06,
+    -5.42164e-04 * 0.956940335732209 / 2.384e-06, -3.2425e-05 * 0.956940335732209 / 2.384e-06,
+    3.033466836073424e-01,
+    1.662939224605090e+00,
+
+
+    -1.431e-06 * 0.970031253194544 / 2.384e-06, 9.9182e-05 * 0.970031253194544 / 2.384e-06,
+    4.62532e-04 * 0.970031253194544 / 2.384e-06, -1.573563e-03 * 0.970031253194544 / 2.384e-06,
+    3.3225536e-02 * 0.970031253194544 / 2.384e-06, 4.737377e-03 * 0.970031253194544 / 2.384e-06, 8.91685e-04 * 0.970031253194544 / 2.384e-06, 6.6280e-05 * 0.970031253194544 / 2.384e-06, /* 5 */
+    4.292e-06 * 0.970031253194544 / 2.384e-06, -1.3828e-05 * 0.970031253194544 / 2.384e-06,
+    6.61850e-04 * 0.970031253194544 / 2.384e-06, 8.487225e-03 * 0.970031253194544 / 2.384e-06,
+    -2.7073860e-02 * 0.970031253194544 / 2.384e-06, -4.174709e-03 * 0.970031253194544 / 2.384e-06,
+    -5.76973e-04 * 0.970031253194544 / 2.384e-06, -3.4809e-05 * 0.970031253194544 / 2.384e-06,
+    2.504869601913055e-01,
+    1.763842528696710e+00,
+
+
+    -1.431e-06 * 0.98078528040323 / 2.384e-06, 9.5367e-05 * 0.98078528040323 / 2.384e-06,
+    3.78609e-04 * 0.98078528040323 / 2.384e-06, -2.161503e-03 * 0.98078528040323 / 2.384e-06,
+    3.2754898e-02 * 0.98078528040323 / 2.384e-06, 4.752159e-03 * 0.98078528040323 / 2.384e-06, 8.66413e-04 * 0.98078528040323 / 2.384e-06, 6.2943e-05 * 0.98078528040323 / 2.384e-06, /* 4 */
+    3.815e-06 * 0.98078528040323 / 2.384e-06, -2.718e-05 * 0.98078528040323 / 2.384e-06,
+    5.22137e-04 * 0.98078528040323 / 2.384e-06, 7.703304e-03 * 0.98078528040323 / 2.384e-06,
+    -2.7815342e-02 * 0.98078528040323 / 2.384e-06, -4.290581e-03 * 0.98078528040323 / 2.384e-06,
+    -6.11782e-04 * 0.98078528040323 / 2.384e-06, -3.7670e-05 * 0.98078528040323 / 2.384e-06,
+    1.989123673796580e-01,
+    1.847759065022573e+00,
+
+
+    -1.907e-06 * 0.989176509964781 / 2.384e-06, 9.0122e-05 * 0.989176509964781 / 2.384e-06,
+    2.88486e-04 * 0.989176509964781 / 2.384e-06, -2.774239e-03 * 0.989176509964781 / 2.384e-06,
+    3.2248020e-02 * 0.989176509964781 / 2.384e-06, 4.748821e-03 * 0.989176509964781 / 2.384e-06, 8.38757e-04 * 0.989176509964781 / 2.384e-06, 5.9605e-05 * 0.989176509964781 / 2.384e-06, /* 3 */
+    3.338e-06 * 0.989176509964781 / 2.384e-06, -3.9577e-05 * 0.989176509964781 / 2.384e-06,
+    3.88145e-04 * 0.989176509964781 / 2.384e-06, 6.937027e-03 * 0.989176509964781 / 2.384e-06,
+    -2.8532982e-02 * 0.989176509964781 / 2.384e-06, -4.395962e-03 * 0.989176509964781 / 2.384e-06,
+    -6.46591e-04 * 0.989176509964781 / 2.384e-06, -4.0531e-05 * 0.989176509964781 / 2.384e-06,
+    1.483359875383474e-01,
+    1.913880671464418e+00,
+
+
+    -1.907e-06 * 0.995184726672197 / 2.384e-06, 8.4400e-05 * 0.995184726672197 / 2.384e-06,
+    1.91689e-04 * 0.995184726672197 / 2.384e-06, -3.411293e-03 * 0.995184726672197 / 2.384e-06,
+    3.1706810e-02 * 0.995184726672197 / 2.384e-06, 4.728317e-03 * 0.995184726672197 / 2.384e-06,
+    8.09669e-04 * 0.995184726672197 / 2.384e-06, 5.579e-05 * 0.995184726672197 / 2.384e-06,
+    3.338e-06 * 0.995184726672197 / 2.384e-06, -5.0545e-05 * 0.995184726672197 / 2.384e-06,
+    2.59876e-04 * 0.995184726672197 / 2.384e-06, 6.189346e-03 * 0.995184726672197 / 2.384e-06,
+    -2.9224873e-02 * 0.995184726672197 / 2.384e-06, -4.489899e-03 * 0.995184726672197 / 2.384e-06,
+    -6.80923e-04 * 0.995184726672197 / 2.384e-06, -4.3392e-05 * 0.995184726672197 / 2.384e-06,
+    9.849140335716425e-02,
+    1.961570560806461e+00,
+
+
+    -2.384e-06 * 0.998795456205172 / 2.384e-06, 7.7724e-05 * 0.998795456205172 / 2.384e-06,
+    8.8215e-05 * 0.998795456205172 / 2.384e-06, -4.072189e-03 * 0.998795456205172 / 2.384e-06,
+    3.1132698e-02 * 0.998795456205172 / 2.384e-06, 4.691124e-03 * 0.998795456205172 / 2.384e-06,
+    7.79152e-04 * 0.998795456205172 / 2.384e-06, 5.2929e-05 * 0.998795456205172 / 2.384e-06,
+    2.861e-06 * 0.998795456205172 / 2.384e-06, -6.0558e-05 * 0.998795456205172 / 2.384e-06,
+    1.37329e-04 * 0.998795456205172 / 2.384e-06, 5.462170e-03 * 0.998795456205172 / 2.384e-06,
+    -2.9890060e-02 * 0.998795456205172 / 2.384e-06, -4.570484e-03 * 0.998795456205172 / 2.384e-06,
+    -7.14302e-04 * 0.998795456205172 / 2.384e-06, -4.6253e-05 * 0.998795456205172 / 2.384e-06,
+    4.912684976946725e-02,
+    1.990369453344394e+00,
+
+
+    3.5780907e-02 * SQRT2 * 0.5 / 2.384e-06, 1.7876148e-02 * SQRT2 * 0.5 / 2.384e-06,
+    3.134727e-03 * SQRT2 * 0.5 / 2.384e-06, 2.457142e-03 * SQRT2 * 0.5 / 2.384e-06,
+    9.71317e-04 * SQRT2 * 0.5 / 2.384e-06, 2.18868e-04 * SQRT2 * 0.5 / 2.384e-06,
+    1.01566e-04 * SQRT2 * 0.5 / 2.384e-06, 1.3828e-05 * SQRT2 * 0.5 / 2.384e-06,
+
+    3.0526638e-02 / 2.384e-06, 4.638195e-03 / 2.384e-06, 7.47204e-04 / 2.384e-06,
+    4.9591e-05 / 2.384e-06,
+    4.756451e-03 / 2.384e-06, 2.1458e-05 / 2.384e-06, -6.9618e-05 / 2.384e-06, /*    2.384e-06/2.384e-06 */
+};
+#endif
+
+
+#define NS 12
+#define NL 36
+
+static const FLOAT win[4][NL] = {
+    {
+     2.382191739347913e-13,
+     6.423305872147834e-13,
+     9.400849094049688e-13,
+     1.122435026096556e-12,
+     1.183840321267481e-12,
+     1.122435026096556e-12,
+     9.400849094049690e-13,
+     6.423305872147839e-13,
+     2.382191739347918e-13,
+
+     5.456116108943412e-12,
+     4.878985199565852e-12,
+     4.240448995017367e-12,
+     3.559909094758252e-12,
+     2.858043359288075e-12,
+     2.156177623817898e-12,
+     1.475637723558783e-12,
+     8.371015190102974e-13,
+     2.599706096327376e-13,
+
+     -5.456116108943412e-12,
+     -4.878985199565852e-12,
+     -4.240448995017367e-12,
+     -3.559909094758252e-12,
+     -2.858043359288076e-12,
+     -2.156177623817898e-12,
+     -1.475637723558783e-12,
+     -8.371015190102975e-13,
+     -2.599706096327376e-13,
+
+     -2.382191739347923e-13,
+     -6.423305872147843e-13,
+     -9.400849094049696e-13,
+     -1.122435026096556e-12,
+     -1.183840321267481e-12,
+     -1.122435026096556e-12,
+     -9.400849094049694e-13,
+     -6.423305872147840e-13,
+     -2.382191739347918e-13,
+     },
+    {
+     2.382191739347913e-13,
+     6.423305872147834e-13,
+     9.400849094049688e-13,
+     1.122435026096556e-12,
+     1.183840321267481e-12,
+     1.122435026096556e-12,
+     9.400849094049688e-13,
+     6.423305872147841e-13,
+     2.382191739347918e-13,
+
+     5.456116108943413e-12,
+     4.878985199565852e-12,
+     4.240448995017367e-12,
+     3.559909094758253e-12,
+     2.858043359288075e-12,
+     2.156177623817898e-12,
+     1.475637723558782e-12,
+     8.371015190102975e-13,
+     2.599706096327376e-13,
+
+     -5.461314069809755e-12,
+     -4.921085770524055e-12,
+     -4.343405037091838e-12,
+     -3.732668368707687e-12,
+     -3.093523840190885e-12,
+     -2.430835727329465e-12,
+     -1.734679010007751e-12,
+     -9.748253656609281e-13,
+     -2.797435120168326e-13,
+
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     -2.283748241799531e-13,
+     -4.037858874020686e-13,
+     -2.146547464825323e-13,
+     },
+    {
+     1.316524975873958e-01, /* win[SHORT_TYPE] */
+     4.142135623730950e-01,
+     7.673269879789602e-01,
+
+     1.091308501069271e+00, /* tantab_l */
+     1.303225372841206e+00,
+     1.569685577117490e+00,
+     1.920982126971166e+00,
+     2.414213562373094e+00,
+     3.171594802363212e+00,
+     4.510708503662055e+00,
+     7.595754112725146e+00,
+     2.290376554843115e+01,
+
+     0.98480775301220802032, /* cx */
+     0.64278760968653936292,
+     0.34202014332566882393,
+     0.93969262078590842791,
+     -0.17364817766693030343,
+     -0.76604444311897790243,
+     0.86602540378443870761,
+     0.500000000000000e+00,
+
+     -5.144957554275265e-01, /* ca */
+     -4.717319685649723e-01,
+     -3.133774542039019e-01,
+     -1.819131996109812e-01,
+     -9.457419252642064e-02,
+     -4.096558288530405e-02,
+     -1.419856857247115e-02,
+     -3.699974673760037e-03,
+
+     8.574929257125442e-01, /* cs */
+     8.817419973177052e-01,
+     9.496286491027329e-01,
+     9.833145924917901e-01,
+     9.955178160675857e-01,
+     9.991605581781475e-01,
+     9.998991952444470e-01,
+     9.999931550702802e-01,
+     },
+    {
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     0.000000000000000e+00,
+     2.283748241799531e-13,
+     4.037858874020686e-13,
+     2.146547464825323e-13,
+
+     5.461314069809755e-12,
+     4.921085770524055e-12,
+     4.343405037091838e-12,
+     3.732668368707687e-12,
+     3.093523840190885e-12,
+     2.430835727329466e-12,
+     1.734679010007751e-12,
+     9.748253656609281e-13,
+     2.797435120168326e-13,
+
+     -5.456116108943413e-12,
+     -4.878985199565852e-12,
+     -4.240448995017367e-12,
+     -3.559909094758253e-12,
+     -2.858043359288075e-12,
+     -2.156177623817898e-12,
+     -1.475637723558782e-12,
+     -8.371015190102975e-13,
+     -2.599706096327376e-13,
+
+     -2.382191739347913e-13,
+     -6.423305872147834e-13,
+     -9.400849094049688e-13,
+     -1.122435026096556e-12,
+     -1.183840321267481e-12,
+     -1.122435026096556e-12,
+     -9.400849094049688e-13,
+     -6.423305872147841e-13,
+     -2.382191739347918e-13,
+     }
+};
+
+#define tantab_l (win[SHORT_TYPE]+3)
+#define cx (win[SHORT_TYPE]+12)
+#define ca (win[SHORT_TYPE]+20)
+#define cs (win[SHORT_TYPE]+28)
+
+/************************************************************************
+*
+* window_subband()
+*
+* PURPOSE:  Overlapping window on PCM samples
+*
+* SEMANTICS:
+* 32 16-bit pcm samples are scaled to fractional 2's complement and
+* concatenated to the end of the window buffer #x#. The updated window
+* buffer #x# is then windowed by the analysis window #c# to produce the
+* windowed sample #z#
+*
+************************************************************************/
+
+/*
+ *      new IDCT routine written by Takehiro TOMINAGA
+ */
+static const int order[] = {
+    0, 1, 16, 17, 8, 9, 24, 25, 4, 5, 20, 21, 12, 13, 28, 29,
+    2, 3, 18, 19, 10, 11, 26, 27, 6, 7, 22, 23, 14, 15, 30, 31
+};
+
+
+/* returns sum_j=0^31 a[j]*cos(PI*j*(k+1/2)/32), 0<=k<32 */
+inline static void
+window_subband(const sample_t * x1, FLOAT a[SBLIMIT])
+{
+    int     i;
+    FLOAT const *wp = enwindow + 10;
+
+    const sample_t *x2 = &x1[238 - 14 - 286];
+
+    for (i = -15; i < 0; i++) {
+        FLOAT   w, s, t;
+
+        w = wp[-10];
+        s = x2[-224] * w;
+        t = x1[224] * w;
+        w = wp[-9];
+        s += x2[-160] * w;
+        t += x1[160] * w;
+        w = wp[-8];
+        s += x2[-96] * w;
+        t += x1[96] * w;
+        w = wp[-7];
+        s += x2[-32] * w;
+        t += x1[32] * w;
+        w = wp[-6];
+        s += x2[32] * w;
+        t += x1[-32] * w;
+        w = wp[-5];
+        s += x2[96] * w;
+        t += x1[-96] * w;
+        w = wp[-4];
+        s += x2[160] * w;
+        t += x1[-160] * w;
+        w = wp[-3];
+        s += x2[224] * w;
+        t += x1[-224] * w;
+
+        w = wp[-2];
+        s += x1[-256] * w;
+        t -= x2[256] * w;
+        w = wp[-1];
+        s += x1[-192] * w;
+        t -= x2[192] * w;
+        w = wp[0];
+        s += x1[-128] * w;
+        t -= x2[128] * w;
+        w = wp[1];
+        s += x1[-64] * w;
+        t -= x2[64] * w;
+        w = wp[2];
+        s += x1[0] * w;
+        t -= x2[0] * w;
+        w = wp[3];
+        s += x1[64] * w;
+        t -= x2[-64] * w;
+        w = wp[4];
+        s += x1[128] * w;
+        t -= x2[-128] * w;
+        w = wp[5];
+        s += x1[192] * w;
+        t -= x2[-192] * w;
+
+        /*
+         * this multiplyer could be removed, but it needs more 256 FLOAT data.
+         * thinking about the data cache performance, I think we should not
+         * use such a huge table. tt 2000/Oct/25
+         */
+        s *= wp[6];
+        w = t - s;
+        a[30 + i * 2] = t + s;
+        a[31 + i * 2] = wp[7] * w;
+        wp += 18;
+        x1--;
+        x2++;
+    }
+    {
+        FLOAT   s, t, u, v;
+        t = x1[-16] * wp[-10];
+        s = x1[-32] * wp[-2];
+        t += (x1[-48] - x1[16]) * wp[-9];
+        s += x1[-96] * wp[-1];
+        t += (x1[-80] + x1[48]) * wp[-8];
+        s += x1[-160] * wp[0];
+        t += (x1[-112] - x1[80]) * wp[-7];
+        s += x1[-224] * wp[1];
+        t += (x1[-144] + x1[112]) * wp[-6];
+        s -= x1[32] * wp[2];
+        t += (x1[-176] - x1[144]) * wp[-5];
+        s -= x1[96] * wp[3];
+        t += (x1[-208] + x1[176]) * wp[-4];
+        s -= x1[160] * wp[4];
+        t += (x1[-240] - x1[208]) * wp[-3];
+        s -= x1[224];
+
+        u = s - t;
+        v = s + t;
+
+        t = a[14];
+        s = a[15] - t;
+
+        a[31] = v + t;  /* A0 */
+        a[30] = u + s;  /* A1 */
+        a[15] = u - s;  /* A2 */
+        a[14] = v - t;  /* A3 */
+    }
+    {
+        FLOAT   xr;
+        xr = a[28] - a[0];
+        a[0] += a[28];
+        a[28] = xr * wp[-2 * 18 + 7];
+        xr = a[29] - a[1];
+        a[1] += a[29];
+        a[29] = xr * wp[-2 * 18 + 7];
+
+        xr = a[26] - a[2];
+        a[2] += a[26];
+        a[26] = xr * wp[-4 * 18 + 7];
+        xr = a[27] - a[3];
+        a[3] += a[27];
+        a[27] = xr * wp[-4 * 18 + 7];
+
+        xr = a[24] - a[4];
+        a[4] += a[24];
+        a[24] = xr * wp[-6 * 18 + 7];
+        xr = a[25] - a[5];
+        a[5] += a[25];
+        a[25] = xr * wp[-6 * 18 + 7];
+
+        xr = a[22] - a[6];
+        a[6] += a[22];
+        a[22] = xr * SQRT2;
+        xr = a[23] - a[7];
+        a[7] += a[23];
+        a[23] = xr * SQRT2 - a[7];
+        a[7] -= a[6];
+        a[22] -= a[7];
+        a[23] -= a[22];
+
+        xr = a[6];
+        a[6] = a[31] - xr;
+        a[31] = a[31] + xr;
+        xr = a[7];
+        a[7] = a[30] - xr;
+        a[30] = a[30] + xr;
+        xr = a[22];
+        a[22] = a[15] - xr;
+        a[15] = a[15] + xr;
+        xr = a[23];
+        a[23] = a[14] - xr;
+        a[14] = a[14] + xr;
+
+        xr = a[20] - a[8];
+        a[8] += a[20];
+        a[20] = xr * wp[-10 * 18 + 7];
+        xr = a[21] - a[9];
+        a[9] += a[21];
+        a[21] = xr * wp[-10 * 18 + 7];
+
+        xr = a[18] - a[10];
+        a[10] += a[18];
+        a[18] = xr * wp[-12 * 18 + 7];
+        xr = a[19] - a[11];
+        a[11] += a[19];
+        a[19] = xr * wp[-12 * 18 + 7];
+
+        xr = a[16] - a[12];
+        a[12] += a[16];
+        a[16] = xr * wp[-14 * 18 + 7];
+        xr = a[17] - a[13];
+        a[13] += a[17];
+        a[17] = xr * wp[-14 * 18 + 7];
+
+        xr = -a[20] + a[24];
+        a[20] += a[24];
+        a[24] = xr * wp[-12 * 18 + 7];
+        xr = -a[21] + a[25];
+        a[21] += a[25];
+        a[25] = xr * wp[-12 * 18 + 7];
+
+        xr = a[4] - a[8];
+        a[4] += a[8];
+        a[8] = xr * wp[-12 * 18 + 7];
+        xr = a[5] - a[9];
+        a[5] += a[9];
+        a[9] = xr * wp[-12 * 18 + 7];
+
+        xr = a[0] - a[12];
+        a[0] += a[12];
+        a[12] = xr * wp[-4 * 18 + 7];
+        xr = a[1] - a[13];
+        a[1] += a[13];
+        a[13] = xr * wp[-4 * 18 + 7];
+        xr = a[16] - a[28];
+        a[16] += a[28];
+        a[28] = xr * wp[-4 * 18 + 7];
+        xr = -a[17] + a[29];
+        a[17] += a[29];
+        a[29] = xr * wp[-4 * 18 + 7];
+
+        xr = SQRT2 * (a[2] - a[10]);
+        a[2] += a[10];
+        a[10] = xr;
+        xr = SQRT2 * (a[3] - a[11]);
+        a[3] += a[11];
+        a[11] = xr;
+        xr = SQRT2 * (-a[18] + a[26]);
+        a[18] += a[26];
+        a[26] = xr - a[18];
+        xr = SQRT2 * (-a[19] + a[27]);
+        a[19] += a[27];
+        a[27] = xr - a[19];
+
+        xr = a[2];
+        a[19] -= a[3];
+        a[3] -= xr;
+        a[2] = a[31] - xr;
+        a[31] += xr;
+        xr = a[3];
+        a[11] -= a[19];
+        a[18] -= xr;
+        a[3] = a[30] - xr;
+        a[30] += xr;
+        xr = a[18];
+        a[27] -= a[11];
+        a[19] -= xr;
+        a[18] = a[15] - xr;
+        a[15] += xr;
+
+        xr = a[19];
+        a[10] -= xr;
+        a[19] = a[14] - xr;
+        a[14] += xr;
+        xr = a[10];
+        a[11] -= xr;
+        a[10] = a[23] - xr;
+        a[23] += xr;
+        xr = a[11];
+        a[26] -= xr;
+        a[11] = a[22] - xr;
+        a[22] += xr;
+        xr = a[26];
+        a[27] -= xr;
+        a[26] = a[7] - xr;
+        a[7] += xr;
+
+        xr = a[27];
+        a[27] = a[6] - xr;
+        a[6] += xr;
+
+        xr = SQRT2 * (a[0] - a[4]);
+        a[0] += a[4];
+        a[4] = xr;
+        xr = SQRT2 * (a[1] - a[5]);
+        a[1] += a[5];
+        a[5] = xr;
+        xr = SQRT2 * (a[16] - a[20]);
+        a[16] += a[20];
+        a[20] = xr;
+        xr = SQRT2 * (a[17] - a[21]);
+        a[17] += a[21];
+        a[21] = xr;
+
+        xr = -SQRT2 * (a[8] - a[12]);
+        a[8] += a[12];
+        a[12] = xr - a[8];
+        xr = -SQRT2 * (a[9] - a[13]);
+        a[9] += a[13];
+        a[13] = xr - a[9];
+        xr = -SQRT2 * (a[25] - a[29]);
+        a[25] += a[29];
+        a[29] = xr - a[25];
+        xr = -SQRT2 * (a[24] + a[28]);
+        a[24] -= a[28];
+        a[28] = xr - a[24];
+
+        xr = a[24] - a[16];
+        a[24] = xr;
+        xr = a[20] - xr;
+        a[20] = xr;
+        xr = a[28] - xr;
+        a[28] = xr;
+
+        xr = a[25] - a[17];
+        a[25] = xr;
+        xr = a[21] - xr;
+        a[21] = xr;
+        xr = a[29] - xr;
+        a[29] = xr;
+
+        xr = a[17] - a[1];
+        a[17] = xr;
+        xr = a[9] - xr;
+        a[9] = xr;
+        xr = a[25] - xr;
+        a[25] = xr;
+        xr = a[5] - xr;
+        a[5] = xr;
+        xr = a[21] - xr;
+        a[21] = xr;
+        xr = a[13] - xr;
+        a[13] = xr;
+        xr = a[29] - xr;
+        a[29] = xr;
+
+        xr = a[1] - a[0];
+        a[1] = xr;
+        xr = a[16] - xr;
+        a[16] = xr;
+        xr = a[17] - xr;
+        a[17] = xr;
+        xr = a[8] - xr;
+        a[8] = xr;
+        xr = a[9] - xr;
+        a[9] = xr;
+        xr = a[24] - xr;
+        a[24] = xr;
+        xr = a[25] - xr;
+        a[25] = xr;
+        xr = a[4] - xr;
+        a[4] = xr;
+        xr = a[5] - xr;
+        a[5] = xr;
+        xr = a[20] - xr;
+        a[20] = xr;
+        xr = a[21] - xr;
+        a[21] = xr;
+        xr = a[12] - xr;
+        a[12] = xr;
+        xr = a[13] - xr;
+        a[13] = xr;
+        xr = a[28] - xr;
+        a[28] = xr;
+        xr = a[29] - xr;
+        a[29] = xr;
+
+        xr = a[0];
+        a[0] += a[31];
+        a[31] -= xr;
+        xr = a[1];
+        a[1] += a[30];
+        a[30] -= xr;
+        xr = a[16];
+        a[16] += a[15];
+        a[15] -= xr;
+        xr = a[17];
+        a[17] += a[14];
+        a[14] -= xr;
+        xr = a[8];
+        a[8] += a[23];
+        a[23] -= xr;
+        xr = a[9];
+        a[9] += a[22];
+        a[22] -= xr;
+        xr = a[24];
+        a[24] += a[7];
+        a[7] -= xr;
+        xr = a[25];
+        a[25] += a[6];
+        a[6] -= xr;
+        xr = a[4];
+        a[4] += a[27];
+        a[27] -= xr;
+        xr = a[5];
+        a[5] += a[26];
+        a[26] -= xr;
+        xr = a[20];
+        a[20] += a[11];
+        a[11] -= xr;
+        xr = a[21];
+        a[21] += a[10];
+        a[10] -= xr;
+        xr = a[12];
+        a[12] += a[19];
+        a[19] -= xr;
+        xr = a[13];
+        a[13] += a[18];
+        a[18] -= xr;
+        xr = a[28];
+        a[28] += a[3];
+        a[3] -= xr;
+        xr = a[29];
+        a[29] += a[2];
+        a[2] -= xr;
+    }
+
+}
+
+
+/*-------------------------------------------------------------------*/
+/*                                                                   */
+/*   Function: Calculation of the MDCT                               */
+/*   In the case of long blocks (type 0,1,3) there are               */
+/*   36 coefficents in the time domain and 18 in the frequency       */
+/*   domain.                                                         */
+/*   In the case of short blocks (type 2) there are 3                */
+/*   transformations with short length. This leads to 12 coefficents */
+/*   in the time and 6 in the frequency domain. In this case the     */
+/*   results are stored side by side in the vector out[].            */
+/*                                                                   */
+/*   New layer3                                                      */
+/*                                                                   */
+/*-------------------------------------------------------------------*/
+
+inline static void
+mdct_short(FLOAT * inout)
+{
+    int     l;
+    for (l = 0; l < 3; l++) {
+        FLOAT   tc0, tc1, tc2, ts0, ts1, ts2;
+
+        ts0 = inout[2 * 3] * win[SHORT_TYPE][0] - inout[5 * 3];
+        tc0 = inout[0 * 3] * win[SHORT_TYPE][2] - inout[3 * 3];
+        tc1 = ts0 + tc0;
+        tc2 = ts0 - tc0;
+
+        ts0 = inout[5 * 3] * win[SHORT_TYPE][0] + inout[2 * 3];
+        tc0 = inout[3 * 3] * win[SHORT_TYPE][2] + inout[0 * 3];
+        ts1 = ts0 + tc0;
+        ts2 = -ts0 + tc0;
+
+        tc0 = (inout[1 * 3] * win[SHORT_TYPE][1] - inout[4 * 3]) * 2.069978111953089e-11; /* tritab_s[1] */
+        ts0 = (inout[4 * 3] * win[SHORT_TYPE][1] + inout[1 * 3]) * 2.069978111953089e-11; /* tritab_s[1] */
+
+        inout[3 * 0] = tc1 * 1.907525191737280e-11 /* tritab_s[2] */  + tc0;
+        inout[3 * 5] = -ts1 * 1.907525191737280e-11 /* tritab_s[0] */  + ts0;
+
+        tc2 = tc2 * 0.86602540378443870761 * 1.907525191737281e-11 /* tritab_s[2] */ ;
+        ts1 = ts1 * 0.5 * 1.907525191737281e-11 + ts0;
+        inout[3 * 1] = tc2 - ts1;
+        inout[3 * 2] = tc2 + ts1;
+
+        tc1 = tc1 * 0.5 * 1.907525191737281e-11 - tc0;
+        ts2 = ts2 * 0.86602540378443870761 * 1.907525191737281e-11 /* tritab_s[0] */ ;
+        inout[3 * 3] = tc1 + ts2;
+        inout[3 * 4] = tc1 - ts2;
+
+        inout++;
+    }
+}
+
+inline static void
+mdct_long(FLOAT * out, FLOAT const *in)
+{
+    FLOAT   ct, st;
+    {
+        FLOAT   tc1, tc2, tc3, tc4, ts5, ts6, ts7, ts8;
+        /* 1,2, 5,6, 9,10, 13,14, 17 */
+        tc1 = in[17] - in[9];
+        tc3 = in[15] - in[11];
+        tc4 = in[14] - in[12];
+        ts5 = in[0] + in[8];
+        ts6 = in[1] + in[7];
+        ts7 = in[2] + in[6];
+        ts8 = in[3] + in[5];
+
+        out[17] = (ts5 + ts7 - ts8) - (ts6 - in[4]);
+        st = (ts5 + ts7 - ts8) * cx[7] + (ts6 - in[4]);
+        ct = (tc1 - tc3 - tc4) * cx[6];
+        out[5] = ct + st;
+        out[6] = ct - st;
+
+        tc2 = (in[16] - in[10]) * cx[6];
+        ts6 = ts6 * cx[7] + in[4];
+        ct = tc1 * cx[0] + tc2 + tc3 * cx[1] + tc4 * cx[2];
+        st = -ts5 * cx[4] + ts6 - ts7 * cx[5] + ts8 * cx[3];
+        out[1] = ct + st;
+        out[2] = ct - st;
+
+        ct = tc1 * cx[1] - tc2 - tc3 * cx[2] + tc4 * cx[0];
+        st = -ts5 * cx[5] + ts6 - ts7 * cx[3] + ts8 * cx[4];
+        out[9] = ct + st;
+        out[10] = ct - st;
+
+        ct = tc1 * cx[2] - tc2 + tc3 * cx[0] - tc4 * cx[1];
+        st = ts5 * cx[3] - ts6 + ts7 * cx[4] - ts8 * cx[5];
+        out[13] = ct + st;
+        out[14] = ct - st;
+    }
+    {
+        FLOAT   ts1, ts2, ts3, ts4, tc5, tc6, tc7, tc8;
+
+        ts1 = in[8] - in[0];
+        ts3 = in[6] - in[2];
+        ts4 = in[5] - in[3];
+        tc5 = in[17] + in[9];
+        tc6 = in[16] + in[10];
+        tc7 = in[15] + in[11];
+        tc8 = in[14] + in[12];
+
+        out[0] = (tc5 + tc7 + tc8) + (tc6 + in[13]);
+        ct = (tc5 + tc7 + tc8) * cx[7] - (tc6 + in[13]);
+        st = (ts1 - ts3 + ts4) * cx[6];
+        out[11] = ct + st;
+        out[12] = ct - st;
+
+        ts2 = (in[7] - in[1]) * cx[6];
+        tc6 = in[13] - tc6 * cx[7];
+        ct = tc5 * cx[3] - tc6 + tc7 * cx[4] + tc8 * cx[5];
+        st = ts1 * cx[2] + ts2 + ts3 * cx[0] + ts4 * cx[1];
+        out[3] = ct + st;
+        out[4] = ct - st;
+
+        ct = -tc5 * cx[5] + tc6 - tc7 * cx[3] - tc8 * cx[4];
+        st = ts1 * cx[1] + ts2 - ts3 * cx[2] - ts4 * cx[0];
+        out[7] = ct + st;
+        out[8] = ct - st;
+
+        ct = -tc5 * cx[4] + tc6 - tc7 * cx[5] - tc8 * cx[3];
+        st = ts1 * cx[0] - ts2 + ts3 * cx[1] - ts4 * cx[2];
+        out[15] = ct + st;
+        out[16] = ct - st;
+    }
+}
+
+
+void
+mdct_sub48(lame_internal_flags * gfc, const sample_t * w0, const sample_t * w1)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     gr, k, ch;
+    const sample_t *wk;
+
+    wk = w0 + 286;
+    /* thinking cache performance, ch->gr loop is better than gr->ch loop */
+    for (ch = 0; ch < cfg->channels_out; ch++) {
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            int     band;
+            gr_info *const gi = &(gfc->l3_side.tt[gr][ch]);
+            FLOAT  *mdct_enc = gi->xr;
+            FLOAT  *samp = esv->sb_sample[ch][1 - gr][0];
+
+            for (k = 0; k < 18 / 2; k++) {
+                window_subband(wk, samp);
+                window_subband(wk + 32, samp + 32);
+                samp += 64;
+                wk += 64;
+                /*
+                 * Compensate for inversion in the analysis filter
+                 */
+                for (band = 1; band < 32; band += 2) {
+                    samp[band - 32] *= -1;
+                }
+            }
+
+            /*
+             * Perform imdct of 18 previous subband samples
+             * + 18 current subband samples
+             */
+            for (band = 0; band < 32; band++, mdct_enc += 18) {
+                int     type = gi->block_type;
+                FLOAT const *const band0 = esv->sb_sample[ch][gr][0] + order[band];
+                FLOAT  *const band1 = esv->sb_sample[ch][1 - gr][0] + order[band];
+                if (gi->mixed_block_flag && band < 2)
+                    type = 0;
+                if (esv->amp_filter[band] < 1e-12) {
+                    memset(mdct_enc, 0, 18 * sizeof(FLOAT));
+                }
+                else {
+                    if (esv->amp_filter[band] < 1.0) {
+                        for (k = 0; k < 18; k++)
+                            band1[k * 32] *= esv->amp_filter[band];
+                    }
+                    if (type == SHORT_TYPE) {
+                        for (k = -NS / 4; k < 0; k++) {
+                            FLOAT const w = win[SHORT_TYPE][k + 3];
+                            mdct_enc[k * 3 + 9] = band0[(9 + k) * 32] * w - band0[(8 - k) * 32];
+                            mdct_enc[k * 3 + 18] = band0[(14 - k) * 32] * w + band0[(15 + k) * 32];
+                            mdct_enc[k * 3 + 10] = band0[(15 + k) * 32] * w - band0[(14 - k) * 32];
+                            mdct_enc[k * 3 + 19] = band1[(2 - k) * 32] * w + band1[(3 + k) * 32];
+                            mdct_enc[k * 3 + 11] = band1[(3 + k) * 32] * w - band1[(2 - k) * 32];
+                            mdct_enc[k * 3 + 20] = band1[(8 - k) * 32] * w + band1[(9 + k) * 32];
+                        }
+                        mdct_short(mdct_enc);
+                    }
+                    else {
+                        FLOAT   work[18];
+                        for (k = -NL / 4; k < 0; k++) {
+                            FLOAT   a, b;
+                            a = win[type][k + 27] * band1[(k + 9) * 32]
+                                + win[type][k + 36] * band1[(8 - k) * 32];
+                            b = win[type][k + 9] * band0[(k + 9) * 32]
+                                - win[type][k + 18] * band0[(8 - k) * 32];
+                            work[k + 9] = a - b * tantab_l[k + 9];
+                            work[k + 18] = a * tantab_l[k + 9] + b;
+                        }
+
+                        mdct_long(mdct_enc, work);
+                    }
+                }
+                /*
+                 * Perform aliasing reduction butterfly
+                 */
+                if (type != SHORT_TYPE && band != 0) {
+                    for (k = 7; k >= 0; --k) {
+                        FLOAT   bu, bd;
+                        bu = mdct_enc[k] * ca[k] + mdct_enc[-1 - k] * cs[k];
+                        bd = mdct_enc[k] * cs[k] - mdct_enc[-1 - k] * ca[k];
+
+                        mdct_enc[-1 - k] = bu;
+                        mdct_enc[k] = bd;
+                    }
+                }
+            }
+        }
+        wk = w1 + 286;
+        if (cfg->mode_gr == 1) {
+            memcpy(esv->sb_sample[ch][0], esv->sb_sample[ch][1], 576 * sizeof(FLOAT));
+        }
+    }
+}
diff --git a/lame/libmp3lame/newmdct.h b/lame/libmp3lame/newmdct.h
new file mode 100644 (file)
index 0000000..0b58a95
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ *     New Modified DCT include file
+ *
+ *     Copyright (c) 1999 Takehiro TOMINAGA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_NEWMDCT_H
+#define LAME_NEWMDCT_H
+
+void    mdct_sub48(lame_internal_flags * gfc, const sample_t * w0, const sample_t * w1);
+
+#endif /* LAME_NEWMDCT_H */
diff --git a/lame/libmp3lame/presets.c b/lame/libmp3lame/presets.c
new file mode 100644 (file)
index 0000000..93594f5
--- /dev/null
@@ -0,0 +1,404 @@
+/*
+ * presets.c -- Apply presets
+ *
+ *     Copyright (c) 2002-2008 Gabriel Bouvigne
+ *     Copyright (c) 2007-2012 Robert Hegemann
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "set_get.h"
+#include "encoder.h"
+#include "util.h"
+#include "lame_global_flags.h"
+
+#define SET_OPTION(opt, val, def) if (enforce) \
+    (void) lame_set_##opt(gfp, val); \
+    else if (!(fabs(lame_get_##opt(gfp) - def) > 0)) \
+    (void) lame_set_##opt(gfp, val);
+
+#define SET__OPTION(opt, val, def) if (enforce) \
+    lame_set_##opt(gfp, val); \
+    else if (!(fabs(lame_get_##opt(gfp) - def) > 0)) \
+    lame_set_##opt(gfp, val);
+
+#undef Min
+#undef Max
+
+static inline int
+min_int(int a, int b)
+{
+    if (a < b) {
+        return a;
+    }
+    return b;
+}
+
+static inline int
+max_int(int a, int b)
+{
+    if (a > b) {
+        return a;
+    }
+    return b;
+}
+
+
+
+typedef struct {
+    int     vbr_q;
+    int     quant_comp;
+    int     quant_comp_s;
+    int     expY;
+    FLOAT   st_lrm;          /*short threshold */
+    FLOAT   st_s;
+    FLOAT   masking_adj;
+    FLOAT   masking_adj_short;
+    FLOAT   ath_lower;
+    FLOAT   ath_curve;
+    FLOAT   ath_sensitivity;
+    FLOAT   interch;
+    int     safejoint;
+    int     sfb21mod;
+    FLOAT   msfix;
+    FLOAT   minval;
+    FLOAT   ath_fixpoint;
+} vbr_presets_t;
+
+    /* *INDENT-OFF* */
+    
+    /* Switch mappings for VBR mode VBR_RH */
+    static const vbr_presets_t vbr_old_switch_map[] = {
+    /*vbr_q  qcomp_l  qcomp_s  expY  st_lrm   st_s  mask adj_l  adj_s  ath_lower  ath_curve  ath_sens  interChR  safejoint sfb21mod  msfix */
+        {0,       9,       9,    0,   5.20, 125.0,      -4.2,   -6.3,       4.8,       1,          0,   0,              2,      21,  0.97, 5, 100},
+        {1,       9,       9,    0,   5.30, 125.0,      -3.6,   -5.6,       4.5,       1.5,        0,   0,              2,      21,  1.35, 5, 100},
+        {2,       9,       9,    0,   5.60, 125.0,      -2.2,   -3.5,       2.8,       2,          0,   0,              2,      21,  1.49, 5, 100},
+        {3,       9,       9,    1,   5.80, 130.0,      -1.8,   -2.8,       2.6,       3,         -4,   0,              2,      20,  1.64, 5, 100},
+        {4,       9,       9,    1,   6.00, 135.0,      -0.7,   -1.1,       1.1,       3.5,       -8,   0,              2,       0,  1.79, 5, 100},
+        {5,       9,       9,    1,   6.40, 140.0,       0.5,    0.4,      -7.5,       4,        -12,   0.0002,         0,       0,  1.95, 5, 100},
+        {6,       9,       9,    1,   6.60, 145.0,       0.67,   0.65,    -14.7,       6.5,      -19,   0.0004,         0,       0,  2.30, 5, 100},
+        {7,       9,       9,    1,   6.60, 145.0,       0.8,    0.75,    -19.7,       8,        -22,   0.0006,         0,       0,  2.70, 5, 100},
+        {8,       9,       9,    1,   6.60, 145.0,       1.2,    1.15,    -27.5,      10,        -23,   0.0007,         0,       0,  0,    5, 100},
+        {9,       9,       9,    1,   6.60, 145.0,       1.6,    1.6,     -36,        11,        -25,   0.0008,         0,       0,  0,    5, 100},
+        {10,      9,       9,    1,   6.60, 145.0,       2.0,    2.0,     -36,        12,        -25,   0.0008,         0,       0,  0,    5, 100}
+    };
+    
+    static const vbr_presets_t vbr_mt_psy_switch_map[] = {
+    /*vbr_q  qcomp_l  qcomp_s  expY  st_lrm   st_s  mask adj_l  adj_s  ath_lower  ath_curve  ath_sens  ---  safejoint sfb21mod  msfix */
+        {0,       9,       9,    0,   4.20,  25.0,      -6.8,   -6.8,       7.1,       1,          0,   0,         2,      31,  1.000,  5, 100},
+        {1,       9,       9,    0,   4.20,  25.0,      -4.8,   -4.8,       5.4,       1.4,       -1,   0,         2,      27,  1.122,  5,  98},
+        {2,       9,       9,    0,   4.20,  25.0,      -2.6,   -2.6,       3.7,       2.0,       -3,   0,         2,      23,  1.288,  5,  97},
+        {3,       9,       9,    1,   4.20,  25.0,      -1.6,   -1.6,       2.0,       2.0,       -5,   0,         2,      18,  1.479,  5,  96},
+        {4,       9,       9,    1,   4.20,  25.0,      -0.0,   -0.0,       0.0,       2.0,       -8,   0,         2,      12,  1.698,  5,  95},
+        {5,       9,       9,    1,   4.20,  25.0,       1.3,    1.3,      -6,         3.5,      -11,   0,         2,       8,  1.950,  5,  94.2},
+#if 0
+        {6,       9,       9,    1,   4.50, 100.0,       1.5,    1.5,     -24.0,       6.0,      -14,   0,         2,       4,  2.239,  3,  93.9},
+        {7,       9,       9,    1,   4.80, 200.0,       1.7,    1.7,     -28.0,       9.0,      -20,   0,         2,       0,  2.570,  1,  93.6},
+#else
+        {6,       9,       9,    1,   4.50, 100.0,       2.2,    2.3,     -12.0,       6.0,      -14,   0,         2,       4,  2.239,  3,  93.9},
+        {7,       9,       9,    1,   4.80, 200.0,       2.7,    2.7,     -18.0,       9.0,      -17,   0,         2,       0,  2.570,  1,  93.6},
+#endif
+        {8,       9,       9,    1,   5.30, 300.0,       2.8,    2.8,     -21.0,      10.0,      -23,   0.0002,    0,       0,  2.951,  0,  93.3},
+        {9,       9,       9,    1,   6.60, 300.0,       2.8,    2.8,     -23.0,      11.0,      -25,   0.0006,    0,       0,  3.388,  0,  93.3},
+        {10,      9,       9,    1,  25.00, 300.0,       2.8,    2.8,     -25.0,      12.0,      -27,   0.0025,    0,       0,  3.500,  0,  93.3}
+    };
+
+    /* *INDENT-ON* */
+
+static vbr_presets_t const*
+get_vbr_preset(int v)
+{
+    switch (v) {
+    case vbr_mtrh:
+    case vbr_mt:
+        return &vbr_mt_psy_switch_map[0];
+    default:
+        return &vbr_old_switch_map[0];
+    }
+}
+
+#define NOOP(m) (void)p.m
+#define LERP(m) (p.m = p.m + x * (q.m - p.m))
+
+static void
+apply_vbr_preset(lame_global_flags * gfp, int a, int enforce)
+{
+    vbr_presets_t const *vbr_preset = get_vbr_preset(lame_get_VBR(gfp));
+    float   x = gfp->VBR_q_frac;
+    vbr_presets_t p = vbr_preset[a];
+    vbr_presets_t q = vbr_preset[a + 1];
+    vbr_presets_t const *set = &p;
+
+    NOOP(vbr_q);
+    NOOP(quant_comp);
+    NOOP(quant_comp_s);
+    NOOP(expY);
+    LERP(st_lrm);
+    LERP(st_s);
+    LERP(masking_adj);
+    LERP(masking_adj_short);
+    LERP(ath_lower);
+    LERP(ath_curve);
+    LERP(ath_sensitivity);
+    LERP(interch);
+    NOOP(safejoint);
+    LERP(sfb21mod);
+    LERP(msfix);
+    LERP(minval);
+    LERP(ath_fixpoint);
+
+    (void) lame_set_VBR_q(gfp, set->vbr_q);
+    SET_OPTION(quant_comp, set->quant_comp, -1);
+    SET_OPTION(quant_comp_short, set->quant_comp_s, -1);
+    if (set->expY) {
+        (void) lame_set_experimentalY(gfp, set->expY);
+    }
+    SET_OPTION(short_threshold_lrm, set->st_lrm, -1);
+    SET_OPTION(short_threshold_s, set->st_s, -1);
+    SET_OPTION(maskingadjust, set->masking_adj, 0);
+    SET_OPTION(maskingadjust_short, set->masking_adj_short, 0);
+    if (lame_get_VBR(gfp) == vbr_mt || lame_get_VBR(gfp) == vbr_mtrh) {
+        lame_set_ATHtype(gfp, 5);
+    }
+    SET_OPTION(ATHlower, set->ath_lower, 0);
+    SET_OPTION(ATHcurve, set->ath_curve, -1);
+    SET_OPTION(athaa_sensitivity, set->ath_sensitivity, 0);
+    if (set->interch > 0) {
+        SET_OPTION(interChRatio, set->interch, -1);
+    }
+
+    /* parameters for which there is no proper set/get interface */
+    if (set->safejoint > 0) {
+        (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 2);
+    }
+    if (set->sfb21mod > 0) {
+        int const nsp = lame_get_exp_nspsytune(gfp);
+        int const val = (nsp >> 20) & 63;
+        if (val == 0) {
+            int const sf21mod = (set->sfb21mod << 20) | nsp;
+            (void) lame_set_exp_nspsytune(gfp, sf21mod);
+        }
+    }
+    SET__OPTION(msfix, set->msfix, -1);
+
+    if (enforce == 0) {
+        gfp->VBR_q = a;
+        gfp->VBR_q_frac = x;
+    }
+    gfp->internal_flags->cfg.minval = set->minval;
+    {   /* take care of gain adjustments */
+        double const x = fabs(gfp->scale);
+        double const y = (x > 0.f) ? (10.f * log10(x)) : 0.f;
+        gfp->internal_flags->cfg.ATHfixpoint = set->ath_fixpoint - y;
+    }
+}
+
+static int
+apply_abr_preset(lame_global_flags * gfp, int preset, int enforce)
+{
+    typedef struct {
+        int     abr_kbps;
+        int     quant_comp;
+        int     quant_comp_s;
+        int     safejoint;
+        FLOAT   nsmsfix;
+        FLOAT   st_lrm;      /*short threshold */
+        FLOAT   st_s;
+        FLOAT   scale;
+        FLOAT   masking_adj;
+        FLOAT   ath_lower;
+        FLOAT   ath_curve;
+        FLOAT   interch;
+        int     sfscale;
+    } abr_presets_t;
+
+
+    /* *INDENT-OFF* */
+
+    /* 
+     *  Switch mappings for ABR mode
+     */
+    const abr_presets_t abr_switch_map[] = {        
+    /* kbps  quant q_s safejoint nsmsfix st_lrm  st_s  scale   msk ath_lwr ath_curve  interch , sfscale */
+      {  8,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -30.0,     11,    0.0012,        1}, /*   8, impossible to use in stereo */
+      { 16,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -25.0,     11,    0.0010,        1}, /*  16 */
+      { 24,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -20.0,     11,    0.0010,        1}, /*  24 */
+      { 32,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -15.0,     11,    0.0010,        1}, /*  32 */
+      { 40,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -10.0,     11,    0.0009,        1}, /*  40 */
+      { 48,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -10.0,     11,    0.0009,        1}, /*  48 */
+      { 56,     9,  9,        0,      0,  6.60,  145,  0.95,    0,   -6.0,     11,    0.0008,        1}, /*  56 */
+      { 64,     9,  9,        0,      0,  6.60,  145,  0.95,    0,   -2.0,     11,    0.0008,        1}, /*  64 */
+      { 80,     9,  9,        0,      0,  6.60,  145,  0.95,    0,     .0,      8,    0.0007,        1}, /*  80 */
+      { 96,     9,  9,        0,   2.50,  6.60,  145,  0.95,    0,    1.0,      5.5,  0.0006,        1}, /*  96 */
+      {112,     9,  9,        0,   2.25,  6.60,  145,  0.95,    0,    2.0,      4.5,  0.0005,        1}, /* 112 */
+      {128,     9,  9,        0,   1.95,  6.40,  140,  0.95,    0,    3.0,      4,    0.0002,        1}, /* 128 */
+      {160,     9,  9,        1,   1.79,  6.00,  135,  0.95,   -2,    5.0,      3.5,  0,             1}, /* 160 */
+      {192,     9,  9,        1,   1.49,  5.60,  125,  0.97,   -4,    7.0,      3,    0,             0}, /* 192 */
+      {224,     9,  9,        1,   1.25,  5.20,  125,  0.98,   -6,    9.0,      2,    0,             0}, /* 224 */
+      {256,     9,  9,        1,   0.97,  5.20,  125,  1.00,   -8,   10.0,      1,    0,             0}, /* 256 */
+      {320,     9,  9,        1,   0.90,  5.20,  125,  1.00,  -10,   12.0,      0,    0,             0}  /* 320 */
+    };
+
+    /* *INDENT-ON* */
+
+    /* Variables for the ABR stuff */
+    int     r;
+    int     actual_bitrate = preset;
+
+    r = nearestBitrateFullIndex(preset);
+    
+    (void) lame_set_VBR(gfp, vbr_abr);
+    (void) lame_set_VBR_mean_bitrate_kbps(gfp, (actual_bitrate));
+    (void) lame_set_VBR_mean_bitrate_kbps(gfp, min_int(lame_get_VBR_mean_bitrate_kbps(gfp), 320));
+    (void) lame_set_VBR_mean_bitrate_kbps(gfp, max_int(lame_get_VBR_mean_bitrate_kbps(gfp), 8));
+    (void) lame_set_brate(gfp, lame_get_VBR_mean_bitrate_kbps(gfp));
+
+
+    /* parameters for which there is no proper set/get interface */
+    if (abr_switch_map[r].safejoint > 0)
+        (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 2); /* safejoint */
+
+    if (abr_switch_map[r].sfscale > 0)
+        (void) lame_set_sfscale(gfp, 1);
+
+
+    SET_OPTION(quant_comp, abr_switch_map[r].quant_comp, -1);
+    SET_OPTION(quant_comp_short, abr_switch_map[r].quant_comp_s, -1);
+
+    SET__OPTION(msfix, abr_switch_map[r].nsmsfix, -1);
+
+    SET_OPTION(short_threshold_lrm, abr_switch_map[r].st_lrm, -1);
+    SET_OPTION(short_threshold_s, abr_switch_map[r].st_s, -1);
+
+    /* ABR seems to have big problems with clipping, especially at low bitrates */
+    /* so we compensate for that here by using a scale value depending on bitrate */
+    lame_set_scale(gfp, lame_get_scale(gfp) * abr_switch_map[r].scale);
+
+    SET_OPTION(maskingadjust, abr_switch_map[r].masking_adj, 0);
+    if (abr_switch_map[r].masking_adj > 0) {
+        SET_OPTION(maskingadjust_short, abr_switch_map[r].masking_adj * .9, 0);
+    }
+    else {
+        SET_OPTION(maskingadjust_short, abr_switch_map[r].masking_adj * 1.1, 0);
+    }
+
+
+    SET_OPTION(ATHlower, abr_switch_map[r].ath_lower, 0);
+    SET_OPTION(ATHcurve, abr_switch_map[r].ath_curve, -1);
+
+    SET_OPTION(interChRatio, abr_switch_map[r].interch, -1);
+
+    (void) abr_switch_map[r].abr_kbps;
+
+    gfp->internal_flags->cfg.minval = 5. * (abr_switch_map[r].abr_kbps / 320.);
+
+    return preset;
+}
+
+
+
+int
+apply_preset(lame_global_flags * gfp, int preset, int enforce)
+{
+    /*translate legacy presets */
+    switch (preset) {
+    case R3MIX:
+        {
+            preset = V3;
+            (void) lame_set_VBR(gfp, vbr_mtrh);
+            break;
+        }
+    case MEDIUM:
+    case MEDIUM_FAST:
+        {
+            preset = V4;
+            (void) lame_set_VBR(gfp, vbr_mtrh);
+            break;
+        }
+    case STANDARD:
+    case STANDARD_FAST:
+        {
+            preset = V2;
+            (void) lame_set_VBR(gfp, vbr_mtrh);
+            break;
+        }
+    case EXTREME:
+    case EXTREME_FAST:
+        {
+            preset = V0;
+            (void) lame_set_VBR(gfp, vbr_mtrh);
+            break;
+        }
+    case INSANE:
+        {
+            preset = 320;
+            gfp->preset = preset;
+            (void) apply_abr_preset(gfp, preset, enforce);
+            lame_set_VBR(gfp, vbr_off);
+            return preset;
+        }
+    }
+
+    gfp->preset = preset;
+    {
+        switch (preset) {
+        case V9:
+            apply_vbr_preset(gfp, 9, enforce);
+            return preset;
+        case V8:
+            apply_vbr_preset(gfp, 8, enforce);
+            return preset;
+        case V7:
+            apply_vbr_preset(gfp, 7, enforce);
+            return preset;
+        case V6:
+            apply_vbr_preset(gfp, 6, enforce);
+            return preset;
+        case V5:
+            apply_vbr_preset(gfp, 5, enforce);
+            return preset;
+        case V4:
+            apply_vbr_preset(gfp, 4, enforce);
+            return preset;
+        case V3:
+            apply_vbr_preset(gfp, 3, enforce);
+            return preset;
+        case V2:
+            apply_vbr_preset(gfp, 2, enforce);
+            return preset;
+        case V1:
+            apply_vbr_preset(gfp, 1, enforce);
+            return preset;
+        case V0:
+            apply_vbr_preset(gfp, 0, enforce);
+            return preset;
+        default:
+            break;
+        }
+    }
+    if (8 <= preset && preset <= 320) {
+        return apply_abr_preset(gfp, preset, enforce);
+    }
+
+    gfp->preset = 0;    /*no corresponding preset found */
+    return preset;
+}
diff --git a/lame/libmp3lame/psymodel.c b/lame/libmp3lame/psymodel.c
new file mode 100644 (file)
index 0000000..60076ee
--- /dev/null
@@ -0,0 +1,2167 @@
+/*
+ *      psymodel.c
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *      Copyright (c) 2001-2002 Naoki Shibata
+ *      Copyright (c) 2000-2003 Takehiro Tominaga
+ *      Copyright (c) 2000-2012 Robert Hegemann
+ *      Copyright (c) 2000-2005 Gabriel Bouvigne
+ *      Copyright (c) 2000-2005 Alexander Leidinger
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: psymodel.c,v 1.216 2017/09/06 19:38:23 aleidinger Exp $ */
+
+
+/*
+PSYCHO ACOUSTICS
+
+
+This routine computes the psycho acoustics, delayed by one granule.  
+
+Input: buffer of PCM data (1024 samples).  
+
+This window should be centered over the 576 sample granule window.
+The routine will compute the psycho acoustics for
+this granule, but return the psycho acoustics computed
+for the *previous* granule.  This is because the block
+type of the previous granule can only be determined
+after we have computed the psycho acoustics for the following
+granule.  
+
+Output:  maskings and energies for each scalefactor band.
+block type, PE, and some correlation measures.  
+The PE is used by CBR modes to determine if extra bits
+from the bit reservoir should be used.  The correlation
+measures are used to determine mid/side or regular stereo.
+*/
+/*
+Notation:
+
+barks:  a non-linear frequency scale.  Mapping from frequency to
+        barks is given by freq2bark()
+
+scalefactor bands: The spectrum (frequencies) are broken into 
+                   SBMAX "scalefactor bands".  Thes bands
+                   are determined by the MPEG ISO spec.  In
+                   the noise shaping/quantization code, we allocate
+                   bits among the partition bands to achieve the
+                   best possible quality
+
+partition bands:   The spectrum is also broken into about
+                   64 "partition bands".  Each partition 
+                   band is about .34 barks wide.  There are about 2-5
+                   partition bands for each scalefactor band.
+
+LAME computes all psycho acoustic information for each partition
+band.  Then at the end of the computations, this information
+is mapped to scalefactor bands.  The energy in each scalefactor
+band is taken as the sum of the energy in all partition bands
+which overlap the scalefactor band.  The maskings can be computed
+in the same way (and thus represent the average masking in that band)
+or by taking the minmum value multiplied by the number of
+partition bands used (which represents a minimum masking in that band).
+*/
+/*
+The general outline is as follows:
+
+1. compute the energy in each partition band
+2. compute the tonality in each partition band
+3. compute the strength of each partion band "masker"
+4. compute the masking (via the spreading function applied to each masker)
+5. Modifications for mid/side masking.  
+
+Each partition band is considiered a "masker".  The strength
+of the i'th masker in band j is given by:
+
+    s3(bark(i)-bark(j))*strength(i)
+
+The strength of the masker is a function of the energy and tonality.
+The more tonal, the less masking.  LAME uses a simple linear formula
+(controlled by NMT and TMN) which says the strength is given by the
+energy divided by a linear function of the tonality.
+*/
+/*
+s3() is the "spreading function".  It is given by a formula
+determined via listening tests.  
+
+The total masking in the j'th partition band is the sum over
+all maskings i.  It is thus given by the convolution of
+the strength with s3(), the "spreading function."
+
+masking(j) = sum_over_i  s3(i-j)*strength(i)  = s3 o strength
+
+where "o" = convolution operator.  s3 is given by a formula determined
+via listening tests.  It is normalized so that s3 o 1 = 1.
+
+Note: instead of a simple convolution, LAME also has the
+option of using "additive masking"
+
+The most critical part is step 2, computing the tonality of each
+partition band.  LAME has two tonality estimators.  The first
+is based on the ISO spec, and measures how predictiable the
+signal is over time.  The more predictable, the more tonal.
+The second measure is based on looking at the spectrum of
+a single granule.  The more peaky the spectrum, the more
+tonal.  By most indications, the latter approach is better.
+
+Finally, in step 5, the maskings for the mid and side
+channel are possibly increased.  Under certain circumstances,
+noise in the mid & side channels is assumed to also
+be masked by strong maskers in the L or R channels.
+
+
+Other data computed by the psy-model:
+
+ms_ratio        side-channel / mid-channel masking ratio (for previous granule)
+ms_ratio_next   side-channel / mid-channel masking ratio for this granule
+
+percep_entropy[2]     L and R values (prev granule) of PE - A measure of how 
+                      much pre-echo is in the previous granule
+percep_entropy_MS[2]  mid and side channel values (prev granule) of percep_entropy
+energy[4]             L,R,M,S energy in each channel, prev granule
+blocktype_d[2]        block type to use for previous granule
+*/
+
+
+
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <float.h>
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "psymodel.h"
+#include "lame_global_flags.h"
+#include "fft.h"
+#include "lame-analysis.h"
+
+
+#define NSFIRLEN 21
+
+#ifdef M_LN10
+#define  LN_TO_LOG10  (M_LN10/10)
+#else
+#define  LN_TO_LOG10  0.2302585093
+#endif
+
+
+/*
+   L3psycho_anal.  Compute psycho acoustics.
+
+   Data returned to the calling program must be delayed by one 
+   granule. 
+
+   This is done in two places.  
+   If we do not need to know the blocktype, the copying
+   can be done here at the top of the program: we copy the data for
+   the last granule (computed during the last call) before it is
+   overwritten with the new data.  It looks like this:
+  
+   0. static psymodel_data 
+   1. calling_program_data = psymodel_data
+   2. compute psymodel_data
+    
+   For data which needs to know the blocktype, the copying must be
+   done at the end of this loop, and the old values must be saved:
+   
+   0. static psymodel_data_old 
+   1. compute psymodel_data
+   2. compute possible block type of this granule
+   3. compute final block type of previous granule based on #2.
+   4. calling_program_data = psymodel_data_old
+   5. psymodel_data_old = psymodel_data
+*/
+
+
+
+
+
+/* psycho_loudness_approx
+   jd - 2001 mar 12
+in:  energy   - BLKSIZE/2 elements of frequency magnitudes ^ 2
+     gfp      - uses out_samplerate, ATHtype (also needed for ATHformula)
+returns: loudness^2 approximation, a positive value roughly tuned for a value
+         of 1.0 for signals near clipping.
+notes:   When calibrated, feeding this function binary white noise at sample
+         values +32767 or -32768 should return values that approach 3.
+         ATHformula is used to approximate an equal loudness curve.
+future:  Data indicates that the shape of the equal loudness curve varies
+         with intensity.  This function might be improved by using an equal
+         loudness curve shaped for typical playback levels (instead of the
+         ATH, that is shaped for the threshold).  A flexible realization might
+         simply bend the existing ATH curve to achieve the desired shape.
+         However, the potential gain may not be enough to justify an effort.
+*/
+static  FLOAT
+psycho_loudness_approx(FLOAT const *energy, FLOAT const *eql_w)
+{
+    int     i;
+    FLOAT   loudness_power;
+
+    loudness_power = 0.0;
+    /* apply weights to power in freq. bands */
+    for (i = 0; i < BLKSIZE / 2; ++i)
+        loudness_power += energy[i] * eql_w[i];
+    loudness_power *= VO_SCALE;
+
+    return loudness_power;
+}
+
+/* mask_add optimization */
+/* init the limit values used to avoid computing log in mask_add when it is not necessary */
+
+/* For example, with i = 10*log10(m2/m1)/10*16         (= log10(m2/m1)*16)
+ *
+ * abs(i)>8 is equivalent (as i is an integer) to
+ * abs(i)>=9
+ * i>=9 || i<=-9
+ * equivalent to (as i is the biggest integer smaller than log10(m2/m1)*16 
+ * or the smallest integer bigger than log10(m2/m1)*16 depending on the sign of log10(m2/m1)*16)
+ * log10(m2/m1)>=9/16 || log10(m2/m1)<=-9/16
+ * exp10 is strictly increasing thus this is equivalent to
+ * m2/m1 >= 10^(9/16) || m2/m1<=10^(-9/16) which are comparisons to constants
+ */
+
+
+#define I1LIMIT 8       /* as in if(i>8)  */
+#define I2LIMIT 23      /* as in if(i>24) -> changed 23 */
+#define MLIMIT  15      /* as in if(m<15) */
+
+/* pow(10, (I1LIMIT + 1) / 16.0); */
+static const FLOAT ma_max_i1 = 3.6517412725483771;
+/* pow(10, (I2LIMIT + 1) / 16.0); */
+static const FLOAT ma_max_i2 = 31.622776601683793;
+/* pow(10, (MLIMIT) / 10.0); */
+static const FLOAT ma_max_m  = 31.622776601683793;
+
+    /*This is the masking table:
+       According to tonality, values are going from 0dB (TMN)
+       to 9.3dB (NMT).
+       After additive masking computation, 8dB are added, so
+       final values are going from 8dB to 17.3dB
+     */
+static const FLOAT tab[] = {
+    1.0 /*pow(10, -0) */ ,
+    0.79433 /*pow(10, -0.1) */ ,
+    0.63096 /*pow(10, -0.2) */ ,
+    0.63096 /*pow(10, -0.2) */ ,
+    0.63096 /*pow(10, -0.2) */ ,
+    0.63096 /*pow(10, -0.2) */ ,
+    0.63096 /*pow(10, -0.2) */ ,
+    0.25119 /*pow(10, -0.6) */ ,
+    0.11749             /*pow(10, -0.93) */
+};
+
+static const int tab_mask_add_delta[] = { 2, 2, 2, 1, 1, 1, 0, 0, -1 };
+#define STATIC_ASSERT_EQUAL_DIMENSION(A,B) enum{static_assert_##A=1/((dimension_of(A) == dimension_of(B))?1:0)}
+
+inline static int
+mask_add_delta(int i)
+{
+    STATIC_ASSERT_EQUAL_DIMENSION(tab_mask_add_delta,tab);
+    assert(i < (int)dimension_of(tab));
+    return tab_mask_add_delta[i];
+}
+
+
+static void
+init_mask_add_max_values(void)
+{
+#ifndef NDEBUG
+    FLOAT const _ma_max_i1 = pow(10, (I1LIMIT + 1) / 16.0);
+    FLOAT const _ma_max_i2 = pow(10, (I2LIMIT + 1) / 16.0);
+    FLOAT const _ma_max_m = pow(10, (MLIMIT) / 10.0);
+    assert(fabs(ma_max_i1 - _ma_max_i1) <= FLT_EPSILON);
+    assert(fabs(ma_max_i2 - _ma_max_i2) <= FLT_EPSILON);
+    assert(fabs(ma_max_m  - _ma_max_m ) <= FLT_EPSILON);
+#endif
+}
+
+
+
+
+/* addition of simultaneous masking   Naoki Shibata 2000/7 */
+inline static FLOAT
+vbrpsy_mask_add(FLOAT m1, FLOAT m2, int b, int delta)
+{
+    static const FLOAT table2[] = {
+        1.33352 * 1.33352, 1.35879 * 1.35879, 1.38454 * 1.38454, 1.39497 * 1.39497,
+        1.40548 * 1.40548, 1.3537 * 1.3537, 1.30382 * 1.30382, 1.22321 * 1.22321,
+        1.14758 * 1.14758,
+        1
+    };
+
+    FLOAT   ratio;
+
+    if (m1 < 0) {
+        m1 = 0;
+    }
+    if (m2 < 0) {
+        m2 = 0;
+    }
+    if (m1 <= 0) {
+        return m2;
+    }
+    if (m2 <= 0) {
+        return m1;
+    }
+    if (m2 > m1) {
+        ratio = m2 / m1;
+    }
+    else {
+        ratio = m1 / m2;
+    }
+    if (abs(b) <= delta) {       /* approximately, 1 bark = 3 partitions */
+        /* originally 'if(i > 8)' */
+        if (ratio >= ma_max_i1) {
+            return m1 + m2;
+        }
+        else {
+            int     i = (int) (FAST_LOG10_X(ratio, 16.0f));
+            return (m1 + m2) * table2[i];
+        }
+    }
+    if (ratio < ma_max_i2) {
+        return m1 + m2;
+    }
+    if (m1 < m2) {
+        m1 = m2;
+    }
+    return m1;
+}
+
+
+/* short block threshold calculation (part 2)
+
+    partition band bo_s[sfb] is at the transition from scalefactor
+    band sfb to the next one sfb+1; enn and thmm have to be split
+    between them
+*/
+static void
+convert_partition2scalefac(PsyConst_CB2SB_t const *const gd, FLOAT const *eb, FLOAT const *thr,
+                           FLOAT enn_out[], FLOAT thm_out[])
+{
+    FLOAT   enn, thmm;
+    int     sb, b, n = gd->n_sb;
+    enn = thmm = 0.0f;
+    for (sb = b = 0; sb < n; ++b, ++sb) {
+        int const bo_sb = gd->bo[sb];
+        int const npart = gd->npart;
+        int const b_lim = bo_sb < npart ? bo_sb : npart;
+        while (b < b_lim) {
+            assert(eb[b] >= 0); /* iff failed, it may indicate some index error elsewhere */
+            assert(thr[b] >= 0);
+            enn += eb[b];
+            thmm += thr[b];
+            b++;
+        }
+        if (b >= npart) {
+            enn_out[sb] = enn;
+            thm_out[sb] = thmm;
+            ++sb;
+            break;
+        }
+        assert(eb[b] >= 0); /* iff failed, it may indicate some index error elsewhere */
+        assert(thr[b] >= 0);
+        {
+            /* at transition sfb -> sfb+1 */
+            FLOAT const w_curr = gd->bo_weight[sb];
+            FLOAT const w_next = 1.0f - w_curr;
+            enn += w_curr * eb[b];
+            thmm += w_curr * thr[b];
+            enn_out[sb] = enn;
+            thm_out[sb] = thmm;
+            enn = w_next * eb[b];
+            thmm = w_next * thr[b];
+        }
+    }
+    /* zero initialize the rest */
+    for (; sb < n; ++sb) {
+        enn_out[sb] = 0;
+        thm_out[sb] = 0;
+    }
+}
+
+static void
+convert_partition2scalefac_s(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr, int chn,
+                             int sblock)
+{
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;
+    FLOAT   enn[SBMAX_s], thm[SBMAX_s];
+    int     sb;
+    convert_partition2scalefac(gds, eb, thr, enn, thm);
+    for (sb = 0; sb < SBMAX_s; ++sb) {
+        psv->en[chn].s[sb][sblock] = enn[sb];
+        psv->thm[chn].s[sb][sblock] = thm[sb];
+    }
+}
+
+/* longblock threshold calculation (part 2) */
+static void
+convert_partition2scalefac_l(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr, int chn)
+{
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;
+    FLOAT  *enn = &psv->en[chn].l[0];
+    FLOAT  *thm = &psv->thm[chn].l[0];
+    convert_partition2scalefac(gdl, eb, thr, enn, thm);
+}
+
+static void
+convert_partition2scalefac_l_to_s(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr,
+                                  int chn)
+{
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->l_to_s;
+    FLOAT   enn[SBMAX_s], thm[SBMAX_s];
+    int     sb, sblock;
+    convert_partition2scalefac(gds, eb, thr, enn, thm);
+    for (sb = 0; sb < SBMAX_s; ++sb) {
+        FLOAT const scale = 1. / 64.f;
+        FLOAT const tmp_enn = enn[sb];
+        FLOAT const tmp_thm = thm[sb] * scale;
+        for (sblock = 0; sblock < 3; ++sblock) {
+            psv->en[chn].s[sb][sblock] = tmp_enn;
+            psv->thm[chn].s[sb][sblock] = tmp_thm;
+        }
+    }
+}
+
+
+
+static inline FLOAT
+NS_INTERP(FLOAT x, FLOAT y, FLOAT r)
+{
+    /* was pow((x),(r))*pow((y),1-(r)) */
+    if (r >= 1.0f)
+        return x;       /* 99.7% of the time */
+    if (r <= 0.0f)
+        return y;
+    if (y > 0.0f)
+        return powf(x / y, r) * y; /* rest of the time */
+    return 0.0f;        /* never happens */
+}
+
+
+
+static  FLOAT
+pecalc_s(III_psy_ratio const *mr, FLOAT masking_lower)
+{
+    FLOAT   pe_s;
+    static const FLOAT regcoef_s[] = {
+        11.8,           /* these values are tuned only for 44.1kHz... */
+        13.6,
+        17.2,
+        32,
+        46.5,
+        51.3,
+        57.5,
+        67.1,
+        71.5,
+        84.6,
+        97.6,
+        130,
+/*      255.8 */
+    };
+    unsigned int sb, sblock;
+
+    pe_s = 1236.28f / 4;
+    for (sb = 0; sb < SBMAX_s - 1; sb++) {
+        for (sblock = 0; sblock < 3; sblock++) {
+            FLOAT const thm = mr->thm.s[sb][sblock];
+            assert(sb < dimension_of(regcoef_s));
+            if (thm > 0.0f) {
+                FLOAT const x = thm * masking_lower;
+                FLOAT const en = mr->en.s[sb][sblock];
+                if (en > x) {
+                    if (en > x * 1e10f) {
+                        pe_s += regcoef_s[sb] * (10.0f * LOG10);
+                    }
+                    else {
+                        assert(x > 0);
+                        pe_s += regcoef_s[sb] * FAST_LOG10(en / x);
+                    }
+                }
+            }
+        }
+    }
+
+    return pe_s;
+}
+
+static  FLOAT
+pecalc_l(III_psy_ratio const *mr, FLOAT masking_lower)
+{
+    FLOAT   pe_l;
+    static const FLOAT regcoef_l[] = {
+        6.8,            /* these values are tuned only for 44.1kHz... */
+        5.8,
+        5.8,
+        6.4,
+        6.5,
+        9.9,
+        12.1,
+        14.4,
+        15,
+        18.9,
+        21.6,
+        26.9,
+        34.2,
+        40.2,
+        46.8,
+        56.5,
+        60.7,
+        73.9,
+        85.7,
+        93.4,
+        126.1,
+/*      241.3 */
+    };
+    unsigned int sb;
+
+    pe_l = 1124.23f / 4;
+    for (sb = 0; sb < SBMAX_l - 1; sb++) {
+        FLOAT const thm = mr->thm.l[sb];
+        assert(sb < dimension_of(regcoef_l));
+        if (thm > 0.0f) {
+            FLOAT const x = thm * masking_lower;
+            FLOAT const en = mr->en.l[sb];
+            if (en > x) {
+                if (en > x * 1e10f) {
+                    pe_l += regcoef_l[sb] * (10.0f * LOG10);
+                }
+                else {
+                    assert(x > 0);
+                    pe_l += regcoef_l[sb] * FAST_LOG10(en / x);
+                }
+            }
+        }
+    }
+
+    return pe_l;
+}
+
+
+static void
+calc_energy(PsyConst_CB2SB_t const *l, FLOAT const *fftenergy, FLOAT * eb, FLOAT * max, FLOAT * avg)
+{
+    int     b, j;
+
+    for (b = j = 0; b < l->npart; ++b) {
+        FLOAT   ebb = 0, m = 0;
+        int     i;
+        for (i = 0; i < l->numlines[b]; ++i, ++j) {
+            FLOAT const el = fftenergy[j];
+            assert(el >= 0);
+            ebb += el;
+            if (m < el)
+                m = el;
+        }
+        eb[b] = ebb;
+        max[b] = m;
+        avg[b] = ebb * l->rnumlines[b];
+        assert(l->rnumlines[b] >= 0);
+        assert(ebb >= 0);
+        assert(eb[b] >= 0);
+        assert(max[b] >= 0);
+        assert(avg[b] >= 0);
+    }
+}
+
+
+static void
+calc_mask_index_l(lame_internal_flags const *gfc, FLOAT const *max,
+                  FLOAT const *avg, unsigned char *mask_idx)
+{
+    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;
+    FLOAT   m, a;
+    int     b, k;
+    int const last_tab_entry = sizeof(tab) / sizeof(tab[0]) - 1;
+    b = 0;
+    a = avg[b] + avg[b + 1];
+    assert(a >= 0);
+    if (a > 0.0f) {
+        m = max[b];
+        if (m < max[b + 1])
+            m = max[b + 1];
+        assert((gdl->numlines[b] + gdl->numlines[b + 1] - 1) > 0);
+        a = 20.0f * (m * 2.0f - a)
+            / (a * (gdl->numlines[b] + gdl->numlines[b + 1] - 1));
+        k = (int) a;
+        if (k > last_tab_entry)
+            k = last_tab_entry;
+        mask_idx[b] = k;
+    }
+    else {
+        mask_idx[b] = 0;
+    }
+
+    for (b = 1; b < gdl->npart - 1; b++) {
+        a = avg[b - 1] + avg[b] + avg[b + 1];
+        assert(a >= 0);
+        if (a > 0.0f) {
+            m = max[b - 1];
+            if (m < max[b])
+                m = max[b];
+            if (m < max[b + 1])
+                m = max[b + 1];
+            assert((gdl->numlines[b - 1] + gdl->numlines[b] + gdl->numlines[b + 1] - 1) > 0);
+            a = 20.0f * (m * 3.0f - a)
+                / (a * (gdl->numlines[b - 1] + gdl->numlines[b] + gdl->numlines[b + 1] - 1));
+            k = (int) a;
+            if (k > last_tab_entry)
+                k = last_tab_entry;
+            mask_idx[b] = k;
+        }
+        else {
+            mask_idx[b] = 0;
+        }
+    }
+    assert(b > 0);
+    assert(b == gdl->npart - 1);
+
+    a = avg[b - 1] + avg[b];
+    assert(a >= 0);
+    if (a > 0.0f) {
+        m = max[b - 1];
+        if (m < max[b])
+            m = max[b];
+        assert((gdl->numlines[b - 1] + gdl->numlines[b] - 1) > 0);
+        a = 20.0f * (m * 2.0f - a)
+            / (a * (gdl->numlines[b - 1] + gdl->numlines[b] - 1));
+        k = (int) a;
+        if (k > last_tab_entry)
+            k = last_tab_entry;
+        mask_idx[b] = k;
+    }
+    else {
+        mask_idx[b] = 0;
+    }
+    assert(b == (gdl->npart - 1));
+}
+
+
+static void
+vbrpsy_compute_fft_l(lame_internal_flags * gfc, const sample_t * const buffer[2], int chn,
+                     int gr_out, FLOAT fftenergy[HBLKSIZE], FLOAT(*wsamp_l)[BLKSIZE])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    PsyStateVar_t *psv = &gfc->sv_psy;
+    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;
+    int     j;
+
+    if (chn < 2) {
+        fft_long(gfc, *wsamp_l, chn, buffer);
+    }
+    else if (chn == 2) {
+        FLOAT const sqrt2_half = SQRT2 * 0.5f;
+        /* FFT data for mid and side channel is derived from L & R */
+        for (j = BLKSIZE - 1; j >= 0; --j) {
+            FLOAT const l = wsamp_l[0][j];
+            FLOAT const r = wsamp_l[1][j];
+            wsamp_l[0][j] = (l + r) * sqrt2_half;
+            wsamp_l[1][j] = (l - r) * sqrt2_half;
+        }
+    }
+
+    /*********************************************************************
+    *  compute energies
+    *********************************************************************/
+    fftenergy[0] = wsamp_l[0][0];
+    fftenergy[0] *= fftenergy[0];
+
+    for (j = BLKSIZE / 2 - 1; j >= 0; --j) {
+        FLOAT const re = (*wsamp_l)[BLKSIZE / 2 - j];
+        FLOAT const im = (*wsamp_l)[BLKSIZE / 2 + j];
+        fftenergy[BLKSIZE / 2 - j] = (re * re + im * im) * 0.5f;
+    }
+    /* total energy */
+    {
+        FLOAT   totalenergy = 0.0f;
+        for (j = 11; j < HBLKSIZE; j++)
+            totalenergy += fftenergy[j];
+
+        psv->tot_ener[chn] = totalenergy;
+    }
+
+    if (plt) {
+        for (j = 0; j < HBLKSIZE; j++) {
+            plt->energy[gr_out][chn][j] = plt->energy_save[chn][j];
+            plt->energy_save[chn][j] = fftenergy[j];
+        }
+    }
+}
+
+
+static void
+vbrpsy_compute_fft_s(lame_internal_flags const *gfc, const sample_t * const buffer[2], int chn,
+                     int sblock, FLOAT(*fftenergy_s)[HBLKSIZE_s], FLOAT(*wsamp_s)[3][BLKSIZE_s])
+{
+    int     j;
+
+    if (sblock == 0 && chn < 2) {
+        fft_short(gfc, *wsamp_s, chn, buffer);
+    }
+    if (chn == 2) {
+        FLOAT const sqrt2_half = SQRT2 * 0.5f;
+        /* FFT data for mid and side channel is derived from L & R */
+        for (j = BLKSIZE_s - 1; j >= 0; --j) {
+            FLOAT const l = wsamp_s[0][sblock][j];
+            FLOAT const r = wsamp_s[1][sblock][j];
+            wsamp_s[0][sblock][j] = (l + r) * sqrt2_half;
+            wsamp_s[1][sblock][j] = (l - r) * sqrt2_half;
+        }
+    }
+
+    /*********************************************************************
+    *  compute energies
+    *********************************************************************/
+    fftenergy_s[sblock][0] = (*wsamp_s)[sblock][0];
+    fftenergy_s[sblock][0] *= fftenergy_s[sblock][0];
+    for (j = BLKSIZE_s / 2 - 1; j >= 0; --j) {
+        FLOAT const re = (*wsamp_s)[sblock][BLKSIZE_s / 2 - j];
+        FLOAT const im = (*wsamp_s)[sblock][BLKSIZE_s / 2 + j];
+        fftenergy_s[sblock][BLKSIZE_s / 2 - j] = (re * re + im * im) * 0.5f;
+    }
+}
+
+
+    /*********************************************************************
+    * compute loudness approximation (used for ATH auto-level adjustment) 
+    *********************************************************************/
+static void
+vbrpsy_compute_loudness_approximation_l(lame_internal_flags * gfc, int gr_out, int chn,
+                                        const FLOAT fftenergy[HBLKSIZE])
+{
+    PsyStateVar_t *psv = &gfc->sv_psy;
+    if (chn < 2) {      /*no loudness for mid/side ch */
+        gfc->ov_psy.loudness_sq[gr_out][chn] = psv->loudness_sq_save[chn];
+        psv->loudness_sq_save[chn] = psycho_loudness_approx(fftenergy, gfc->ATH->eql_w);
+    }
+}
+
+
+    /**********************************************************************
+    *  Apply HPF of fs/4 to the input signal.
+    *  This is used for attack detection / handling.
+    **********************************************************************/
+static void
+vbrpsy_attack_detection(lame_internal_flags * gfc, const sample_t * const buffer[2], int gr_out,
+                        III_psy_ratio masking_ratio[2][2], III_psy_ratio masking_MS_ratio[2][2],
+                        FLOAT energy[4], FLOAT sub_short_factor[4][3], int ns_attacks[4][4],
+                        int uselongblock[2])
+{
+    FLOAT   ns_hpfsmpl[2][576];
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;
+    int const n_chn_out = cfg->channels_out;
+    /* chn=2 and 3 = Mid and Side channels */
+    int const n_chn_psy = (cfg->mode == JOINT_STEREO) ? 4 : n_chn_out;
+    int     chn, i, j;
+
+    memset(&ns_hpfsmpl[0][0], 0, sizeof(ns_hpfsmpl));
+    /* Don't copy the input buffer into a temporary buffer */
+    /* unroll the loop 2 times */
+    for (chn = 0; chn < n_chn_out; chn++) {
+        static const FLOAT fircoef[] = {
+            -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
+            -3.36639e-17 * 2, -0.0438162 * 2, -1.54175e-17 * 2, 0.0931738 * 2,
+            -5.52212e-17 * 2, -0.313819 * 2
+        };
+        /* apply high pass filter of fs/4 */
+        const sample_t *const firbuf = &buffer[chn][576 - 350 - NSFIRLEN + 192];
+        assert(dimension_of(fircoef) == ((NSFIRLEN - 1) / 2));
+        for (i = 0; i < 576; i++) {
+            FLOAT   sum1, sum2;
+            sum1 = firbuf[i + 10];
+            sum2 = 0.0;
+            for (j = 0; j < ((NSFIRLEN - 1) / 2) - 1; j += 2) {
+                sum1 += fircoef[j] * (firbuf[i + j] + firbuf[i + NSFIRLEN - j]);
+                sum2 += fircoef[j + 1] * (firbuf[i + j + 1] + firbuf[i + NSFIRLEN - j - 1]);
+            }
+            ns_hpfsmpl[chn][i] = sum1 + sum2;
+        }
+        masking_ratio[gr_out][chn].en = psv->en[chn];
+        masking_ratio[gr_out][chn].thm = psv->thm[chn];
+        if (n_chn_psy > 2) {
+            /* MS maskings  */
+            /*percep_MS_entropy         [chn-2]     = gfc -> pe  [chn];  */
+            masking_MS_ratio[gr_out][chn].en = psv->en[chn + 2];
+            masking_MS_ratio[gr_out][chn].thm = psv->thm[chn + 2];
+        }
+    }
+    for (chn = 0; chn < n_chn_psy; chn++) {
+        FLOAT   attack_intensity[12];
+        FLOAT   en_subshort[12];
+        FLOAT   en_short[4] = { 0, 0, 0, 0 };
+        FLOAT const *pf = ns_hpfsmpl[chn & 1];
+        int     ns_uselongblock = 1;
+
+        if (chn == 2) {
+            for (i = 0, j = 576; j > 0; ++i, --j) {
+                FLOAT const l = ns_hpfsmpl[0][i];
+                FLOAT const r = ns_hpfsmpl[1][i];
+                ns_hpfsmpl[0][i] = l + r;
+                ns_hpfsmpl[1][i] = l - r;
+            }
+        }
+        /*************************************************************** 
+        * determine the block type (window type)
+        ***************************************************************/
+        /* calculate energies of each sub-shortblocks */
+        for (i = 0; i < 3; i++) {
+            en_subshort[i] = psv->last_en_subshort[chn][i + 6];
+            assert(psv->last_en_subshort[chn][i + 4] > 0);
+            attack_intensity[i] = en_subshort[i] / psv->last_en_subshort[chn][i + 4];
+            en_short[0] += en_subshort[i];
+        }
+
+        for (i = 0; i < 9; i++) {
+            FLOAT const *const pfe = pf + 576 / 9;
+            FLOAT   p = 1.;
+            for (; pf < pfe; pf++)
+                if (p < fabs(*pf))
+                    p = fabs(*pf);
+            psv->last_en_subshort[chn][i] = en_subshort[i + 3] = p;
+            en_short[1 + i / 3] += p;
+            if (p > en_subshort[i + 3 - 2]) {
+                assert(en_subshort[i + 3 - 2] > 0);
+                p = p / en_subshort[i + 3 - 2];
+            }
+            else if (en_subshort[i + 3 - 2] > p * 10.0f) {
+                assert(p > 0);
+                p = en_subshort[i + 3 - 2] / (p * 10.0f);
+            }
+            else {
+                p = 0.0;
+            }
+            attack_intensity[i + 3] = p;
+        }
+
+        /* pulse like signal detection for fatboy.wav and so on */
+        for (i = 0; i < 3; ++i) {
+            FLOAT const enn =
+                en_subshort[i * 3 + 3] + en_subshort[i * 3 + 4] + en_subshort[i * 3 + 5];
+            FLOAT   factor = 1.f;
+            if (en_subshort[i * 3 + 5] * 6 < enn) {
+                factor *= 0.5f;
+                if (en_subshort[i * 3 + 4] * 6 < enn) {
+                    factor *= 0.5f;
+                }
+            }
+            sub_short_factor[chn][i] = factor;
+        }
+
+        if (plt) {
+            FLOAT   x = attack_intensity[0];
+            for (i = 1; i < 12; i++) {
+                if (x < attack_intensity[i]) {
+                    x = attack_intensity[i];
+                }
+            }
+            plt->ers[gr_out][chn] = plt->ers_save[chn];
+            plt->ers_save[chn] = x;
+        }
+
+        /* compare energies between sub-shortblocks */
+        {
+            FLOAT   x = gfc->cd_psy->attack_threshold[chn];
+            for (i = 0; i < 12; i++) {
+                if (ns_attacks[chn][i / 3] == 0) {
+                    if (attack_intensity[i] > x) {
+                        ns_attacks[chn][i / 3] = (i % 3) + 1;
+                    }
+                }
+            }
+        }
+        /* should have energy change between short blocks, in order to avoid periodic signals */
+        /* Good samples to show the effect are Trumpet test songs */
+        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
+        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
+        for (i = 1; i < 4; i++) {
+            FLOAT const u = en_short[i - 1];
+            FLOAT const v = en_short[i];
+            FLOAT const m = Max(u, v);
+            if (m < 40000) { /* (2) */
+                if (u < 1.7f * v && v < 1.7f * u) { /* (1) */
+                    if (i == 1 && ns_attacks[chn][0] <= ns_attacks[chn][i]) {
+                        ns_attacks[chn][0] = 0;
+                    }
+                    ns_attacks[chn][i] = 0;
+                }
+            }
+        }
+
+        if (ns_attacks[chn][0] <= psv->last_attacks[chn]) {
+            ns_attacks[chn][0] = 0;
+        }
+
+        if (psv->last_attacks[chn] == 3 ||
+            ns_attacks[chn][0] + ns_attacks[chn][1] + ns_attacks[chn][2] + ns_attacks[chn][3]) {
+            ns_uselongblock = 0;
+
+            if (ns_attacks[chn][1] && ns_attacks[chn][0]) {
+                ns_attacks[chn][1] = 0;
+            }
+            if (ns_attacks[chn][2] && ns_attacks[chn][1]) {
+                ns_attacks[chn][2] = 0;
+            }
+            if (ns_attacks[chn][3] && ns_attacks[chn][2]) {
+                ns_attacks[chn][3] = 0;
+            }
+        }
+
+        if (chn < 2) {
+            uselongblock[chn] = ns_uselongblock;
+        }
+        else {
+            if (ns_uselongblock == 0) {
+                uselongblock[0] = uselongblock[1] = 0;
+            }
+        }
+
+        /* there is a one granule delay.  Copy maskings computed last call
+         * into masking_ratio to return to calling program.
+         */
+        energy[chn] = psv->tot_ener[chn];
+    }
+}
+
+
+static void
+vbrpsy_skip_masking_s(lame_internal_flags * gfc, int chn, int sblock)
+{
+    if (sblock == 0) {
+        FLOAT  *nbs2 = &gfc->sv_psy.nb_s2[chn][0];
+        FLOAT  *nbs1 = &gfc->sv_psy.nb_s1[chn][0];
+        int const n = gfc->cd_psy->s.npart;
+        int     b;
+        for (b = 0; b < n; b++) {
+            nbs2[b] = nbs1[b];
+        }
+    }
+}
+
+
+static void
+vbrpsy_calc_mask_index_s(lame_internal_flags const *gfc, FLOAT const *max,
+                         FLOAT const *avg, unsigned char *mask_idx)
+{
+    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;
+    FLOAT   m, a;
+    int     b, k;
+    int const last_tab_entry = dimension_of(tab) - 1;
+    b = 0;
+    a = avg[b] + avg[b + 1];
+    assert(a >= 0);
+    if (a > 0.0f) {
+        m = max[b];
+        if (m < max[b + 1])
+            m = max[b + 1];
+        assert((gds->numlines[b] + gds->numlines[b + 1] - 1) > 0);
+        a = 20.0f * (m * 2.0f - a)
+            / (a * (gds->numlines[b] + gds->numlines[b + 1] - 1));
+        k = (int) a;
+        if (k > last_tab_entry)
+            k = last_tab_entry;
+        mask_idx[b] = k;
+    }
+    else {
+        mask_idx[b] = 0;
+    }
+
+    for (b = 1; b < gds->npart - 1; b++) {
+        a = avg[b - 1] + avg[b] + avg[b + 1];
+        assert(b + 1 < gds->npart);
+        assert(a >= 0);
+        if (a > 0.0) {
+            m = max[b - 1];
+            if (m < max[b])
+                m = max[b];
+            if (m < max[b + 1])
+                m = max[b + 1];
+            assert((gds->numlines[b - 1] + gds->numlines[b] + gds->numlines[b + 1] - 1) > 0);
+            a = 20.0f * (m * 3.0f - a)
+                / (a * (gds->numlines[b - 1] + gds->numlines[b] + gds->numlines[b + 1] - 1));
+            k = (int) a;
+            if (k > last_tab_entry)
+                k = last_tab_entry;
+            mask_idx[b] = k;
+        }
+        else {
+            mask_idx[b] = 0;
+        }
+    }
+    assert(b > 0);
+    assert(b == gds->npart - 1);
+
+    a = avg[b - 1] + avg[b];
+    assert(a >= 0);
+    if (a > 0.0f) {
+        m = max[b - 1];
+        if (m < max[b])
+            m = max[b];
+        assert((gds->numlines[b - 1] + gds->numlines[b] - 1) > 0);
+        a = 20.0f * (m * 2.0f - a)
+            / (a * (gds->numlines[b - 1] + gds->numlines[b] - 1));
+        k = (int) a;
+        if (k > last_tab_entry)
+            k = last_tab_entry;
+        mask_idx[b] = k;
+    }
+    else {
+        mask_idx[b] = 0;
+    }
+    assert(b == (gds->npart - 1));
+}
+
+
+static void
+vbrpsy_compute_masking_s(lame_internal_flags * gfc, const FLOAT(*fftenergy_s)[HBLKSIZE_s],
+                         FLOAT * eb, FLOAT * thr, int chn, int sblock)
+{
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;
+    FLOAT   max[CBANDS], avg[CBANDS];
+    int     i, j, b;
+    unsigned char mask_idx_s[CBANDS];
+
+    memset(max, 0, sizeof(max));
+    memset(avg, 0, sizeof(avg));
+
+    for (b = j = 0; b < gds->npart; ++b) {
+        FLOAT   ebb = 0, m = 0;
+        int const n = gds->numlines[b];
+        for (i = 0; i < n; ++i, ++j) {
+            FLOAT const el = fftenergy_s[sblock][j];
+            ebb += el;
+            if (m < el)
+                m = el;
+        }
+        eb[b] = ebb;
+        assert(ebb >= 0);
+        max[b] = m;
+        assert(n > 0);
+        avg[b] = ebb * gds->rnumlines[b];
+        assert(avg[b] >= 0);
+    }
+    assert(b == gds->npart);
+    assert(j == 129);
+    vbrpsy_calc_mask_index_s(gfc, max, avg, mask_idx_s);
+    for (j = b = 0; b < gds->npart; b++) {
+        int     kk = gds->s3ind[b][0];
+        int const last = gds->s3ind[b][1];
+        int const delta = mask_add_delta(mask_idx_s[b]);
+        int     dd, dd_n;
+        FLOAT   x, ecb, avg_mask;
+        FLOAT const masking_lower = gds->masking_lower[b] * gfc->sv_qnt.masking_lower;
+
+        dd = mask_idx_s[kk];
+        dd_n = 1;
+        ecb = gds->s3[j] * eb[kk] * tab[mask_idx_s[kk]];
+        ++j, ++kk;
+        while (kk <= last) {
+            dd += mask_idx_s[kk];
+            dd_n += 1;
+            x = gds->s3[j] * eb[kk] * tab[mask_idx_s[kk]];
+            ecb = vbrpsy_mask_add(ecb, x, kk - b, delta);
+            ++j, ++kk;
+        }
+        dd = (1 + 2 * dd) / (2 * dd_n);
+        avg_mask = tab[dd] * 0.5f;
+        ecb *= avg_mask;
+#if 0                   /* we can do PRE ECHO control now here, or do it later */
+        if (psv->blocktype_old[chn & 0x01] == SHORT_TYPE) {
+            /* limit calculated threshold by even older granule */
+            FLOAT const t1 = rpelev_s * psv->nb_s1[chn][b];
+            FLOAT const t2 = rpelev2_s * psv->nb_s2[chn][b];
+            FLOAT const tm = (t2 > 0) ? Min(ecb, t2) : ecb;
+            thr[b] = (t1 > 0) ? NS_INTERP(Min(tm, t1), ecb, 0.6) : ecb;
+        }
+        else {
+            /* limit calculated threshold by older granule */
+            FLOAT const t1 = rpelev_s * psv->nb_s1[chn][b];
+            thr[b] = (t1 > 0) ? NS_INTERP(Min(ecb, t1), ecb, 0.6) : ecb;
+        }
+#else /* we do it later */
+        thr[b] = ecb;
+#endif
+        psv->nb_s2[chn][b] = psv->nb_s1[chn][b];
+        psv->nb_s1[chn][b] = ecb;
+        {
+            /*  if THR exceeds EB, the quantization routines will take the difference
+             *  from other bands. in case of strong tonal samples (tonaltest.wav)
+             *  this leads to heavy distortions. that's why we limit THR here.
+             */
+            x = max[b];
+            x *= gds->minval[b];
+            x *= avg_mask;
+            if (thr[b] > x) {
+                thr[b] = x;
+            }
+        }
+        if (masking_lower > 1) {
+            thr[b] *= masking_lower;
+        }
+        if (thr[b] > eb[b]) {
+            thr[b] = eb[b];
+        }
+        if (masking_lower < 1) {
+            thr[b] *= masking_lower;
+        }
+
+        assert(thr[b] >= 0);
+    }
+    for (; b < CBANDS; ++b) {
+        eb[b] = 0;
+        thr[b] = 0;
+    }
+}
+
+
+static void
+vbrpsy_compute_masking_l(lame_internal_flags * gfc, const FLOAT fftenergy[HBLKSIZE],
+                         FLOAT eb_l[CBANDS], FLOAT thr[CBANDS], int chn)
+{
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;
+    FLOAT   max[CBANDS], avg[CBANDS];
+    unsigned char mask_idx_l[CBANDS + 2];
+    int     k, b;
+
+ /*********************************************************************
+    *    Calculate the energy and the tonality of each partition.
+ *********************************************************************/
+    calc_energy(gdl, fftenergy, eb_l, max, avg);
+    calc_mask_index_l(gfc, max, avg, mask_idx_l);
+
+ /*********************************************************************
+    *      convolve the partitioned energy and unpredictability
+    *      with the spreading function, s3_l[b][k]
+ ********************************************************************/
+    k = 0;
+    for (b = 0; b < gdl->npart; b++) {
+        FLOAT   x, ecb, avg_mask, t;
+        FLOAT const masking_lower = gdl->masking_lower[b] * gfc->sv_qnt.masking_lower;
+        /* convolve the partitioned energy with the spreading function */
+        int     kk = gdl->s3ind[b][0];
+        int const last = gdl->s3ind[b][1];
+        int const delta = mask_add_delta(mask_idx_l[b]);
+        int     dd = 0, dd_n = 0;
+
+        dd = mask_idx_l[kk];
+        dd_n += 1;
+        ecb = gdl->s3[k] * eb_l[kk] * tab[mask_idx_l[kk]];
+        ++k, ++kk;
+        while (kk <= last) {
+            dd += mask_idx_l[kk];
+            dd_n += 1;
+            x = gdl->s3[k] * eb_l[kk] * tab[mask_idx_l[kk]];
+            t = vbrpsy_mask_add(ecb, x, kk - b, delta);
+#if 0
+            ecb += eb_l[kk];
+            if (ecb > t) {
+                ecb = t;
+            }
+#else
+            ecb = t;
+#endif
+            ++k, ++kk;
+        }
+        dd = (1 + 2 * dd) / (2 * dd_n);
+        avg_mask = tab[dd] * 0.5f;
+        ecb *= avg_mask;
+
+        /****   long block pre-echo control   ****/
+        /* dont use long block pre-echo control if previous granule was 
+         * a short block.  This is to avoid the situation:   
+         * frame0:  quiet (very low masking)  
+         * frame1:  surge  (triggers short blocks)
+         * frame2:  regular frame.  looks like pre-echo when compared to 
+         *          frame0, but all pre-echo was in frame1.
+         */
+        /* chn=0,1   L and R channels
+           chn=2,3   S and M channels.
+         */
+        if (psv->blocktype_old[chn & 0x01] == SHORT_TYPE) {
+            FLOAT const ecb_limit = rpelev * psv->nb_l1[chn][b];
+            if (ecb_limit > 0) {
+                thr[b] = Min(ecb, ecb_limit);
+            }
+            else {
+                /* Robert 071209:
+                   Because we don't calculate long block psy when we know a granule
+                   should be of short blocks, we don't have any clue how the granule
+                   before would have looked like as a long block. So we have to guess
+                   a little bit for this END_TYPE block.
+                   Most of the time we get away with this sloppyness. (fingers crossed :)
+                   The speed increase is worth it.
+                 */
+                thr[b] = Min(ecb, eb_l[b] * NS_PREECHO_ATT2);
+            }
+        }
+        else {
+            FLOAT   ecb_limit_2 = rpelev2 * psv->nb_l2[chn][b];
+            FLOAT   ecb_limit_1 = rpelev * psv->nb_l1[chn][b];
+            FLOAT   ecb_limit;
+            if (ecb_limit_2 <= 0) {
+                ecb_limit_2 = ecb;
+            }
+            if (ecb_limit_1 <= 0) {
+                ecb_limit_1 = ecb;
+            }
+            if (psv->blocktype_old[chn & 0x01] == NORM_TYPE) {
+                ecb_limit = Min(ecb_limit_1, ecb_limit_2);
+            }
+            else {
+                ecb_limit = ecb_limit_1;
+            }
+            thr[b] = Min(ecb, ecb_limit);
+        }
+        psv->nb_l2[chn][b] = psv->nb_l1[chn][b];
+        psv->nb_l1[chn][b] = ecb;
+        {
+            /*  if THR exceeds EB, the quantization routines will take the difference
+             *  from other bands. in case of strong tonal samples (tonaltest.wav)
+             *  this leads to heavy distortions. that's why we limit THR here.
+             */
+            x = max[b];
+            x *= gdl->minval[b];
+            x *= avg_mask;
+            if (thr[b] > x) {
+                thr[b] = x;
+            }
+        }
+        if (masking_lower > 1) {
+            thr[b] *= masking_lower;
+        }
+        if (thr[b] > eb_l[b]) {
+            thr[b] = eb_l[b];
+        }
+        if (masking_lower < 1) {
+            thr[b] *= masking_lower;
+        }
+        assert(thr[b] >= 0);
+    }
+    for (; b < CBANDS; ++b) {
+        eb_l[b] = 0;
+        thr[b] = 0;
+    }
+}
+
+
+static void
+vbrpsy_compute_block_type(SessionConfig_t const *cfg, int *uselongblock)
+{
+    int     chn;
+
+    if (cfg->short_blocks == short_block_coupled
+        /* force both channels to use the same block type */
+        /* this is necessary if the frame is to be encoded in ms_stereo.  */
+        /* But even without ms_stereo, FhG  does this */
+        && !(uselongblock[0] && uselongblock[1]))
+        uselongblock[0] = uselongblock[1] = 0;
+
+    for (chn = 0; chn < cfg->channels_out; chn++) {
+        /* disable short blocks */
+        if (cfg->short_blocks == short_block_dispensed) {
+            uselongblock[chn] = 1;
+        }
+        if (cfg->short_blocks == short_block_forced) {
+            uselongblock[chn] = 0;
+        }
+    }
+}
+
+
+static void
+vbrpsy_apply_block_type(PsyStateVar_t * psv, int nch, int const *uselongblock, int *blocktype_d)
+{
+    int     chn;
+
+    /* update the blocktype of the previous granule, since it depends on what
+     * happend in this granule */
+    for (chn = 0; chn < nch; chn++) {
+        int     blocktype = NORM_TYPE;
+        /* disable short blocks */
+
+        if (uselongblock[chn]) {
+            /* no attack : use long blocks */
+            assert(psv->blocktype_old[chn] != START_TYPE);
+            if (psv->blocktype_old[chn] == SHORT_TYPE)
+                blocktype = STOP_TYPE;
+        }
+        else {
+            /* attack : use short blocks */
+            blocktype = SHORT_TYPE;
+            if (psv->blocktype_old[chn] == NORM_TYPE) {
+                psv->blocktype_old[chn] = START_TYPE;
+            }
+            if (psv->blocktype_old[chn] == STOP_TYPE)
+                psv->blocktype_old[chn] = SHORT_TYPE;
+        }
+
+        blocktype_d[chn] = psv->blocktype_old[chn]; /* value returned to calling program */
+        psv->blocktype_old[chn] = blocktype; /* save for next call to l3psy_anal */
+    }
+}
+
+
+/*************************************************************** 
+ * compute M/S thresholds from Johnston & Ferreira 1992 ICASSP paper
+ ***************************************************************/
+
+static void
+vbrpsy_compute_MS_thresholds(const FLOAT eb[4][CBANDS], FLOAT thr[4][CBANDS],
+                             const FLOAT cb_mld[CBANDS], const FLOAT ath_cb[CBANDS], FLOAT athlower,
+                             FLOAT msfix, int n)
+{
+    FLOAT const msfix2 = msfix * 2.f;
+    FLOAT   rside, rmid;
+    int     b;
+    for (b = 0; b < n; ++b) {
+        FLOAT const ebM = eb[2][b];
+        FLOAT const ebS = eb[3][b];
+        FLOAT const thmL = thr[0][b];
+        FLOAT const thmR = thr[1][b];
+        FLOAT   thmM = thr[2][b];
+        FLOAT   thmS = thr[3][b];
+
+        /* use this fix if L & R masking differs by 2db or less */
+        /* if db = 10*log10(x2/x1) < 2 */
+        /* if (x2 < 1.58*x1) { */
+        if (thmL <= 1.58f * thmR && thmR <= 1.58f * thmL) {
+            FLOAT const mld_m = cb_mld[b] * ebS;
+            FLOAT const mld_s = cb_mld[b] * ebM;
+            FLOAT const tmp_m = Min(thmS, mld_m);
+            FLOAT const tmp_s = Min(thmM, mld_s);
+            rmid = Max(thmM, tmp_m);
+            rside = Max(thmS, tmp_s);
+        }
+        else {
+            rmid = thmM;
+            rside = thmS;
+        }
+        if (msfix > 0.f) {
+            /***************************************************************/
+            /* Adjust M/S maskings if user set "msfix"                     */
+            /***************************************************************/
+            /* Naoki Shibata 2000 */
+            FLOAT   thmLR, thmMS;
+            FLOAT const ath = ath_cb[b] * athlower;
+            FLOAT const tmp_l = Max(thmL, ath);
+            FLOAT const tmp_r = Max(thmR, ath);
+            thmLR = Min(tmp_l, tmp_r);
+            thmM = Max(rmid, ath);
+            thmS = Max(rside, ath);
+            thmMS = thmM + thmS;
+            if (thmMS > 0.f && (thmLR * msfix2) < thmMS) {
+                FLOAT const f = thmLR * msfix2 / thmMS;
+                thmM *= f;
+                thmS *= f;
+                assert(thmMS > 0.f);
+            }
+            rmid = Min(thmM, rmid);
+            rside = Min(thmS, rside);
+        }
+        if (rmid > ebM) {
+            rmid = ebM;
+        }
+        if (rside > ebS) {
+            rside = ebS;
+        }
+        thr[2][b] = rmid;
+        thr[3][b] = rside;
+    }
+}
+
+
+/*
+ * NOTE: the bitrate reduction from the inter-channel masking effect is low
+ * compared to the chance of getting annyoing artefacts. L3psycho_anal_vbr does
+ * not use this feature. (Robert 071216)
+*/
+
+int
+L3psycho_anal_vbr(lame_internal_flags * gfc,
+                  const sample_t * const buffer[2], int gr_out,
+                  III_psy_ratio masking_ratio[2][2],
+                  III_psy_ratio masking_MS_ratio[2][2],
+                  FLOAT percep_entropy[2], FLOAT percep_MS_entropy[2],
+                  FLOAT energy[4], int blocktype_d[2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;
+    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;
+    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;
+
+    III_psy_xmin last_thm[4];
+
+    /* fft and energy calculation   */
+    FLOAT(*wsamp_l)[BLKSIZE];
+    FLOAT(*wsamp_s)[3][BLKSIZE_s];
+    FLOAT   fftenergy[HBLKSIZE];
+    FLOAT   fftenergy_s[3][HBLKSIZE_s];
+    FLOAT   wsamp_L[2][BLKSIZE];
+    FLOAT   wsamp_S[2][3][BLKSIZE_s];
+    FLOAT   eb[4][CBANDS], thr[4][CBANDS];
+
+    FLOAT   sub_short_factor[4][3];
+    FLOAT   thmm;
+    FLOAT const pcfact = 0.6f;
+    FLOAT const ath_factor =
+        (cfg->msfix > 0.f) ? (cfg->ATH_offset_factor * gfc->ATH->adjust_factor) : 1.f;
+
+    const   FLOAT(*const_eb)[CBANDS] = (const FLOAT(*)[CBANDS]) eb;
+    const   FLOAT(*const_fftenergy_s)[HBLKSIZE_s] = (const FLOAT(*)[HBLKSIZE_s]) fftenergy_s;
+
+    /* block type  */
+    int     ns_attacks[4][4] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} };
+    int     uselongblock[2];
+
+    /* usual variables like loop indices, etc..    */
+    int     chn, sb, sblock;
+
+    /* chn=2 and 3 = Mid and Side channels */
+    int const n_chn_psy = (cfg->mode == JOINT_STEREO) ? 4 : cfg->channels_out;
+
+    memcpy(&last_thm[0], &psv->thm[0], sizeof(last_thm));
+
+    vbrpsy_attack_detection(gfc, buffer, gr_out, masking_ratio, masking_MS_ratio, energy,
+                            sub_short_factor, ns_attacks, uselongblock);
+
+    vbrpsy_compute_block_type(cfg, uselongblock);
+
+    /* LONG BLOCK CASE */
+    {
+        for (chn = 0; chn < n_chn_psy; chn++) {
+            int const ch01 = chn & 0x01;
+
+            wsamp_l = wsamp_L + ch01;
+            vbrpsy_compute_fft_l(gfc, buffer, chn, gr_out, fftenergy, wsamp_l);
+            vbrpsy_compute_loudness_approximation_l(gfc, gr_out, chn, fftenergy);
+            vbrpsy_compute_masking_l(gfc, fftenergy, eb[chn], thr[chn], chn);
+        }
+        if (cfg->mode == JOINT_STEREO) {
+            if ((uselongblock[0] + uselongblock[1]) == 2) {
+                vbrpsy_compute_MS_thresholds(const_eb, thr, gdl->mld_cb, gfc->ATH->cb_l,
+                                             ath_factor, cfg->msfix, gdl->npart);
+            }
+        }
+        /* TODO: apply adaptive ATH masking here ?? */
+        for (chn = 0; chn < n_chn_psy; chn++) {
+            convert_partition2scalefac_l(gfc, eb[chn], thr[chn], chn);
+            convert_partition2scalefac_l_to_s(gfc, eb[chn], thr[chn], chn);
+        }
+    }
+    /* SHORT BLOCKS CASE */
+    {
+        int const force_short_block_calc = gfc->cd_psy->force_short_block_calc;
+        for (sblock = 0; sblock < 3; sblock++) {
+            for (chn = 0; chn < n_chn_psy; ++chn) {
+                int const ch01 = chn & 0x01;
+                if (uselongblock[ch01] && !force_short_block_calc) {
+                    vbrpsy_skip_masking_s(gfc, chn, sblock);
+                }
+                else {
+                    /* compute masking thresholds for short blocks */
+                    wsamp_s = wsamp_S + ch01;
+                    vbrpsy_compute_fft_s(gfc, buffer, chn, sblock, fftenergy_s, wsamp_s);
+                    vbrpsy_compute_masking_s(gfc, const_fftenergy_s, eb[chn], thr[chn], chn,
+                                             sblock);
+                }
+            }
+            if (cfg->mode == JOINT_STEREO) {
+                if ((uselongblock[0] + uselongblock[1]) == 0) {
+                    vbrpsy_compute_MS_thresholds(const_eb, thr, gds->mld_cb, gfc->ATH->cb_s,
+                                                 ath_factor, cfg->msfix, gds->npart);
+                }
+            }
+            /* TODO: apply adaptive ATH masking here ?? */
+            for (chn = 0; chn < n_chn_psy; ++chn) {
+                int const ch01 = chn & 0x01;
+                if (!uselongblock[ch01] || force_short_block_calc) {
+                    convert_partition2scalefac_s(gfc, eb[chn], thr[chn], chn, sblock);
+                }
+            }
+        }
+
+        /****   short block pre-echo control   ****/
+        for (chn = 0; chn < n_chn_psy; chn++) {
+            for (sb = 0; sb < SBMAX_s; sb++) {
+                FLOAT   new_thmm[3], prev_thm, t1, t2;
+                for (sblock = 0; sblock < 3; sblock++) {
+                    thmm = psv->thm[chn].s[sb][sblock];
+                    thmm *= NS_PREECHO_ATT0;
+
+                    t1 = t2 = thmm;
+
+                    if (sblock > 0) {
+                        prev_thm = new_thmm[sblock - 1];
+                    }
+                    else {
+                        prev_thm = last_thm[chn].s[sb][2];
+                    }
+                    if (ns_attacks[chn][sblock] >= 2 || ns_attacks[chn][sblock + 1] == 1) {
+                        t1 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT1 * pcfact);
+                    }
+                    thmm = Min(t1, thmm);
+                    if (ns_attacks[chn][sblock] == 1) {
+                        t2 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT2 * pcfact);
+                    }
+                    else if ((sblock == 0 && psv->last_attacks[chn] == 3)
+                             || (sblock > 0 && ns_attacks[chn][sblock - 1] == 3)) { /* 2nd preceeding block */
+                        switch (sblock) {
+                        case 0:
+                            prev_thm = last_thm[chn].s[sb][1];
+                            break;
+                        case 1:
+                            prev_thm = last_thm[chn].s[sb][2];
+                            break;
+                        case 2:
+                            prev_thm = new_thmm[0];
+                            break;
+                        }
+                        t2 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT2 * pcfact);
+                    }
+
+                    thmm = Min(t1, thmm);
+                    thmm = Min(t2, thmm);
+
+                    /* pulse like signal detection for fatboy.wav and so on */
+                    thmm *= sub_short_factor[chn][sblock];
+
+                    new_thmm[sblock] = thmm;
+                }
+                for (sblock = 0; sblock < 3; sblock++) {
+                    psv->thm[chn].s[sb][sblock] = new_thmm[sblock];
+                }
+            }
+        }
+    }
+    for (chn = 0; chn < n_chn_psy; chn++) {
+        psv->last_attacks[chn] = ns_attacks[chn][2];
+    }
+
+
+    /*************************************************************** 
+    * determine final block type
+    ***************************************************************/
+    vbrpsy_apply_block_type(psv, cfg->channels_out, uselongblock, blocktype_d);
+
+    /*********************************************************************
+    * compute the value of PE to return ... no delay and advance
+    *********************************************************************/
+    for (chn = 0; chn < n_chn_psy; chn++) {
+        FLOAT  *ppe;
+        int     type;
+        III_psy_ratio const *mr;
+
+        if (chn > 1) {
+            ppe = percep_MS_entropy - 2;
+            type = NORM_TYPE;
+            if (blocktype_d[0] == SHORT_TYPE || blocktype_d[1] == SHORT_TYPE)
+                type = SHORT_TYPE;
+            mr = &masking_MS_ratio[gr_out][chn - 2];
+        }
+        else {
+            ppe = percep_entropy;
+            type = blocktype_d[chn];
+            mr = &masking_ratio[gr_out][chn];
+        }
+        if (type == SHORT_TYPE) {
+            ppe[chn] = pecalc_s(mr, gfc->sv_qnt.masking_lower);
+        }
+        else {
+            ppe[chn] = pecalc_l(mr, gfc->sv_qnt.masking_lower);
+        }
+
+        if (plt) {
+            plt->pe[gr_out][chn] = ppe[chn];
+        }
+    }
+    return 0;
+}
+
+
+
+
+/* 
+ *   The spreading function.  Values returned in units of energy
+ */
+static  FLOAT
+s3_func(FLOAT bark)
+{
+    FLOAT   tempx, x, tempy, temp;
+    tempx = bark;
+    if (tempx >= 0)
+        tempx *= 3;
+    else
+        tempx *= 1.5;
+
+    if (tempx >= 0.5 && tempx <= 2.5) {
+        temp = tempx - 0.5;
+        x = 8.0 * (temp * temp - 2.0 * temp);
+    }
+    else
+        x = 0.0;
+    tempx += 0.474;
+    tempy = 15.811389 + 7.5 * tempx - 17.5 * sqrt(1.0 + tempx * tempx);
+
+    if (tempy <= -60.0)
+        return 0.0;
+
+    tempx = exp((x + tempy) * LN_TO_LOG10);
+
+    /* Normalization.  The spreading function should be normalized so that:
+       +inf
+       /
+       |  s3 [ bark ]  d(bark)   =  1
+       /
+       -inf
+     */
+    tempx /= .6609193;
+    return tempx;
+}
+
+#if 0
+static  FLOAT
+norm_s3_func(void)
+{
+    double  lim_a = 0, lim_b = 0;
+    double  x = 0, l, h;
+    for (x = 0; s3_func(x) > 1e-20; x -= 1);
+    l = x;
+    h = 0;
+    while (fabs(h - l) > 1e-12) {
+        x = (h + l) / 2;
+        if (s3_func(x) > 0) {
+            h = x;
+        }
+        else {
+            l = x;
+        }
+    }
+    lim_a = l;
+    for (x = 0; s3_func(x) > 1e-20; x += 1);
+    l = 0;
+    h = x;
+    while (fabs(h - l) > 1e-12) {
+        x = (h + l) / 2;
+        if (s3_func(x) > 0) {
+            l = x;
+        }
+        else {
+            h = x;
+        }
+    }
+    lim_b = h;
+    {
+        double  sum = 0;
+        int const m = 1000;
+        int     i;
+        for (i = 0; i <= m; ++i) {
+            double  x = lim_a + i * (lim_b - lim_a) / m;
+            double  y = s3_func(x);
+            sum += y;
+        }
+        {
+            double  norm = (m + 1) / (sum * (lim_b - lim_a));
+            /*printf( "norm = %lf\n",norm); */
+            return norm;
+        }
+    }
+}
+#endif
+
+static  FLOAT
+stereo_demask(double f)
+{
+    /* setup stereo demasking thresholds */
+    /* formula reverse enginerred from plot in paper */
+    double  arg = freq2bark(f);
+    arg = (Min(arg, 15.5) / 15.5);
+
+    return pow(10.0, 1.25 * (1 - cos(PI * arg)) - 2.5);
+}
+
+static void
+init_numline(PsyConst_CB2SB_t * gd, FLOAT sfreq, int fft_size,
+             int mdct_size, int sbmax, int const *scalepos)
+{
+    FLOAT   b_frq[CBANDS + 1];
+    FLOAT const mdct_freq_frac = sfreq / (2.0f * mdct_size);
+    FLOAT const deltafreq = fft_size / (2.0f * mdct_size);
+    int     partition[HBLKSIZE] = { 0 };
+    int     i, j, ni;
+    int     sfb;
+    sfreq /= fft_size;
+    j = 0;
+    ni = 0;
+    /* compute numlines, the number of spectral lines in each partition band */
+    /* each partition band should be about DELBARK wide. */
+    for (i = 0; i < CBANDS; i++) {
+        FLOAT   bark1;
+        int     j2, nl;
+        bark1 = freq2bark(sfreq * j);
+
+        b_frq[i] = sfreq * j;
+
+        for (j2 = j; freq2bark(sfreq * j2) - bark1 < DELBARK && j2 <= fft_size / 2; j2++);
+
+        nl = j2 - j;
+        gd->numlines[i] = nl;
+        gd->rnumlines[i] = (nl > 0) ? (1.0f / nl) : 0;
+
+        ni = i + 1;
+
+        while (j < j2) {
+            assert(j < HBLKSIZE);
+            partition[j++] = i;
+        }
+        if (j > fft_size / 2) {
+            j = fft_size / 2;
+            ++i;
+            break;
+        }
+    }
+    assert(i < CBANDS);
+    b_frq[i] = sfreq * j;
+
+    gd->n_sb = sbmax;
+    gd->npart = ni;
+
+    {
+        j = 0;
+        for (i = 0; i < gd->npart; i++) {
+            int const nl = gd->numlines[i];
+            FLOAT const freq = sfreq * (j + nl / 2);
+            gd->mld_cb[i] = stereo_demask(freq);
+            j += nl;
+        }
+        for (; i < CBANDS; ++i) {
+            gd->mld_cb[i] = 1;
+        }
+    }
+    for (sfb = 0; sfb < sbmax; sfb++) {
+        int     i1, i2, bo;
+        int     start = scalepos[sfb];
+        int     end = scalepos[sfb + 1];
+
+        i1 = floor(.5 + deltafreq * (start - .5));
+        if (i1 < 0)
+            i1 = 0;
+        i2 = floor(.5 + deltafreq * (end - .5));
+
+        if (i2 > fft_size / 2)
+            i2 = fft_size / 2;
+
+        bo = partition[i2];
+        gd->bm[sfb] = (partition[i1] + partition[i2]) / 2;
+        gd->bo[sfb] = bo;
+
+        /* calculate how much of this band belongs to current scalefactor band */
+        {
+            FLOAT const f_tmp = mdct_freq_frac * end;
+            FLOAT   bo_w = (f_tmp - b_frq[bo]) / (b_frq[bo + 1] - b_frq[bo]);
+            if (bo_w < 0) {
+                bo_w = 0;
+            }
+            else {
+                if (bo_w > 1) {
+                    bo_w = 1;
+                }
+            }
+            gd->bo_weight[sfb] = bo_w;
+        }
+        gd->mld[sfb] = stereo_demask(mdct_freq_frac * start);
+    }
+}
+
+static void
+compute_bark_values(PsyConst_CB2SB_t const *gd, FLOAT sfreq, int fft_size,
+                    FLOAT * bval, FLOAT * bval_width)
+{
+    /* compute bark values of each critical band */
+    int     k, j = 0, ni = gd->npart;
+    sfreq /= fft_size;
+    for (k = 0; k < ni; k++) {
+        int const w = gd->numlines[k];
+        FLOAT   bark1, bark2;
+
+        bark1 = freq2bark(sfreq * (j));
+        bark2 = freq2bark(sfreq * (j + w - 1));
+        bval[k] = .5 * (bark1 + bark2);
+
+        bark1 = freq2bark(sfreq * (j - .5));
+        bark2 = freq2bark(sfreq * (j + w - .5));
+        bval_width[k] = bark2 - bark1;
+        j += w;
+    }
+}
+
+static int
+init_s3_values(FLOAT ** p, int (*s3ind)[2], int npart,
+               FLOAT const *bval, FLOAT const *bval_width, FLOAT const *norm)
+{
+    FLOAT   s3[CBANDS][CBANDS];
+    /* The s3 array is not linear in the bark scale.
+     * bval[x] should be used to get the bark value.
+     */
+    int     i, j, k;
+    int     numberOfNoneZero = 0;
+
+    memset(&s3[0][0], 0, sizeof(s3));
+
+    /* s[i][j], the value of the spreading function,
+     * centered at band j (masker), for band i (maskee)
+     *
+     * i.e.: sum over j to spread into signal barkval=i
+     * NOTE: i and j are used opposite as in the ISO docs
+     */
+    for (i = 0; i < npart; i++) {
+        for (j = 0; j < npart; j++) {
+            FLOAT   v = s3_func(bval[i] - bval[j]) * bval_width[j];
+            s3[i][j] = v * norm[i];
+        }
+    }
+    for (i = 0; i < npart; i++) {
+        for (j = 0; j < npart; j++) {
+            if (s3[i][j] > 0.0f)
+                break;
+        }
+        s3ind[i][0] = j;
+
+        for (j = npart - 1; j > 0; j--) {
+            if (s3[i][j] > 0.0f)
+                break;
+        }
+        s3ind[i][1] = j;
+        numberOfNoneZero += (s3ind[i][1] - s3ind[i][0] + 1);
+    }
+    *p = lame_calloc(FLOAT, numberOfNoneZero);
+    if (!*p)
+        return -1;
+
+    k = 0;
+    for (i = 0; i < npart; i++)
+        for (j = s3ind[i][0]; j <= s3ind[i][1]; j++)
+            (*p)[k++] = s3[i][j];
+
+    return 0;
+}
+
+int
+psymodel_init(lame_global_flags const *gfp)
+{
+    lame_internal_flags *const gfc = gfp->internal_flags;
+    SessionConfig_t *const cfg = &gfc->cfg;
+    PsyStateVar_t *const psv = &gfc->sv_psy;
+    PsyConst_t *gd;
+    int     i, j, b, sb, k;
+    FLOAT   bvl_a = 13, bvl_b = 24;
+    FLOAT   snr_l_a = 0, snr_l_b = 0;
+    FLOAT   snr_s_a = -8.25, snr_s_b = -4.5;
+
+    FLOAT   bval[CBANDS];
+    FLOAT   bval_width[CBANDS];
+    FLOAT   norm[CBANDS];
+    FLOAT const sfreq = cfg->samplerate_out;
+
+    FLOAT   xav = 10, xbv = 12;
+    FLOAT const minval_low = (0.f - cfg->minval);
+
+    if (gfc->cd_psy != 0) {
+        return 0;
+    }
+    memset(norm, 0, sizeof(norm));
+
+    gd = lame_calloc(PsyConst_t, 1);
+    gfc->cd_psy = gd;
+
+    gd->force_short_block_calc = gfp->experimentalZ;
+
+    psv->blocktype_old[0] = psv->blocktype_old[1] = NORM_TYPE; /* the vbr header is long blocks */
+
+    for (i = 0; i < 4; ++i) {
+        for (j = 0; j < CBANDS; ++j) {
+            psv->nb_l1[i][j] = 1e20;
+            psv->nb_l2[i][j] = 1e20;
+            psv->nb_s1[i][j] = psv->nb_s2[i][j] = 1.0;
+        }
+        for (sb = 0; sb < SBMAX_l; sb++) {
+            psv->en[i].l[sb] = 1e20;
+            psv->thm[i].l[sb] = 1e20;
+        }
+        for (j = 0; j < 3; ++j) {
+            for (sb = 0; sb < SBMAX_s; sb++) {
+                psv->en[i].s[sb][j] = 1e20;
+                psv->thm[i].s[sb][j] = 1e20;
+            }
+            psv->last_attacks[i] = 0;
+        }
+        for (j = 0; j < 9; j++)
+            psv->last_en_subshort[i][j] = 10.;
+    }
+
+
+    /* init. for loudness approx. -jd 2001 mar 27 */
+    psv->loudness_sq_save[0] = psv->loudness_sq_save[1] = 0.0;
+
+
+
+    /*************************************************************************
+     * now compute the psychoacoustic model specific constants
+     ************************************************************************/
+    /* compute numlines, bo, bm, bval, bval_width, mld */
+    init_numline(&gd->l, sfreq, BLKSIZE, 576, SBMAX_l, gfc->scalefac_band.l);
+    assert(gd->l.npart < CBANDS);
+    compute_bark_values(&gd->l, sfreq, BLKSIZE, bval, bval_width);
+
+    /* compute the spreading function */
+    for (i = 0; i < gd->l.npart; i++) {
+        double  snr = snr_l_a;
+        if (bval[i] >= bvl_a) {
+            snr = snr_l_b * (bval[i] - bvl_a) / (bvl_b - bvl_a)
+                + snr_l_a * (bvl_b - bval[i]) / (bvl_b - bvl_a);
+        }
+        norm[i] = pow(10.0, snr / 10.0);
+    }
+    i = init_s3_values(&gd->l.s3, gd->l.s3ind, gd->l.npart, bval, bval_width, norm);
+    if (i)
+        return i;
+
+    /* compute long block specific values, ATH and MINVAL */
+    j = 0;
+    for (i = 0; i < gd->l.npart; i++) {
+        double  x;
+
+        /* ATH */
+        x = FLOAT_MAX;
+        for (k = 0; k < gd->l.numlines[i]; k++, j++) {
+            FLOAT const freq = sfreq * j / (1000.0 * BLKSIZE);
+            FLOAT   level;
+            /* freq = Min(.1,freq); *//* ATH below 100 Hz constant, not further climbing */
+            level = ATHformula(cfg, freq * 1000) - 20; /* scale to FFT units; returned value is in dB */
+            level = pow(10., 0.1 * level); /* convert from dB -> energy */
+            level *= gd->l.numlines[i];
+            if (x > level)
+                x = level;
+        }
+        gfc->ATH->cb_l[i] = x;
+
+        /* MINVAL.
+           For low freq, the strength of the masking is limited by minval
+           this is an ISO MPEG1 thing, dont know if it is really needed */
+        /* FIXME: it does work to reduce low-freq problems in S53-Wind-Sax
+           and lead-voice samples, but introduces some 3 kbps bit bloat too.
+           TODO: Further refinement of the shape of this hack.
+         */
+        x = 20.0 * (bval[i] / xav - 1.0);
+        if (x > 6) {
+            x = 30;
+        }
+        if (x < minval_low) {
+            x = minval_low;
+        }
+        if (cfg->samplerate_out < 44000) {
+            x = 30;
+        }
+        x -= 8.;
+        gd->l.minval[i] = pow(10.0, x / 10.) * gd->l.numlines[i];
+    }
+
+    /************************************************************************
+     * do the same things for short blocks
+     ************************************************************************/
+    init_numline(&gd->s, sfreq, BLKSIZE_s, 192, SBMAX_s, gfc->scalefac_band.s);
+    assert(gd->s.npart < CBANDS);
+    compute_bark_values(&gd->s, sfreq, BLKSIZE_s, bval, bval_width);
+
+    /* SNR formula. short block is normalized by SNR. is it still right ? */
+    j = 0;
+    for (i = 0; i < gd->s.npart; i++) {
+        double  x;
+        double  snr = snr_s_a;
+        if (bval[i] >= bvl_a) {
+            snr = snr_s_b * (bval[i] - bvl_a) / (bvl_b - bvl_a)
+                + snr_s_a * (bvl_b - bval[i]) / (bvl_b - bvl_a);
+        }
+        norm[i] = pow(10.0, snr / 10.0);
+
+        /* ATH */
+        x = FLOAT_MAX;
+        for (k = 0; k < gd->s.numlines[i]; k++, j++) {
+            FLOAT const freq = sfreq * j / (1000.0 * BLKSIZE_s);
+            FLOAT   level;
+            /* freq = Min(.1,freq); *//* ATH below 100 Hz constant, not further climbing */
+            level = ATHformula(cfg, freq * 1000) - 20; /* scale to FFT units; returned value is in dB */
+            level = pow(10., 0.1 * level); /* convert from dB -> energy */
+            level *= gd->s.numlines[i];
+            if (x > level)
+                x = level;
+        }
+        gfc->ATH->cb_s[i] = x;
+
+        /* MINVAL.
+           For low freq, the strength of the masking is limited by minval
+           this is an ISO MPEG1 thing, dont know if it is really needed */
+        x = 7.0 * (bval[i] / xbv - 1.0);
+        if (bval[i] > xbv) {
+            x *= 1 + log(1 + x) * 3.1;
+        }
+        if (bval[i] < xbv) {
+            x *= 1 + log(1 - x) * 2.3;
+        }
+        if (x > 6) {
+            x = 30;
+        }
+        if (x < minval_low) {
+            x = minval_low;
+        }
+        if (cfg->samplerate_out < 44000) {
+            x = 30;
+        }
+        x -= 8;
+        gd->s.minval[i] = pow(10.0, x / 10) * gd->s.numlines[i];
+    }
+
+    i = init_s3_values(&gd->s.s3, gd->s.s3ind, gd->s.npart, bval, bval_width, norm);
+    if (i)
+        return i;
+
+
+    init_mask_add_max_values();
+    init_fft(gfc);
+
+    /* setup temporal masking */
+    gd->decay = exp(-1.0 * LOG10 / (temporalmask_sustain_sec * sfreq / 192.0));
+
+    {
+        FLOAT   msfix;
+        msfix = NS_MSFIX;
+        if (cfg->use_safe_joint_stereo)
+            msfix = 1.0;
+        if (fabs(cfg->msfix) > 0.0)
+            msfix = cfg->msfix;
+        cfg->msfix = msfix;
+
+        /* spread only from npart_l bands.  Normally, we use the spreading
+         * function to convolve from npart_l down to npart_l bands 
+         */
+        for (b = 0; b < gd->l.npart; b++)
+            if (gd->l.s3ind[b][1] > gd->l.npart - 1)
+                gd->l.s3ind[b][1] = gd->l.npart - 1;
+    }
+
+    /*  prepare for ATH auto adjustment:
+     *  we want to decrease the ATH by 12 dB per second
+     */
+#define  frame_duration (576. * cfg->mode_gr / sfreq)
+    gfc->ATH->decay = pow(10., -12. / 10. * frame_duration);
+    gfc->ATH->adjust_factor = 0.01; /* minimum, for leading low loudness */
+    gfc->ATH->adjust_limit = 1.0; /* on lead, allow adjust up to maximum */
+#undef  frame_duration
+
+    assert(gd->l.bo[SBMAX_l - 1] <= gd->l.npart);
+    assert(gd->s.bo[SBMAX_s - 1] <= gd->s.npart);
+
+    if (cfg->ATHtype != -1) {
+        /* compute equal loudness weights (eql_w) */
+        FLOAT   freq;
+        FLOAT const freq_inc = (FLOAT) cfg->samplerate_out / (FLOAT) (BLKSIZE);
+        FLOAT   eql_balance = 0.0;
+        freq = 0.0;
+        for (i = 0; i < BLKSIZE / 2; ++i) {
+            /* convert ATH dB to relative power (not dB) */
+            /*  to determine eql_w */
+            freq += freq_inc;
+            gfc->ATH->eql_w[i] = 1. / pow(10, ATHformula(cfg, freq) / 10);
+            eql_balance += gfc->ATH->eql_w[i];
+        }
+        eql_balance = 1.0 / eql_balance;
+        for (i = BLKSIZE / 2; --i >= 0;) { /* scale weights */
+            gfc->ATH->eql_w[i] *= eql_balance;
+        }
+    }
+    {
+        for (b = j = 0; b < gd->s.npart; ++b) {
+            for (i = 0; i < gd->s.numlines[b]; ++i) {
+                ++j;
+            }
+        }
+        assert(j == 129);
+        for (b = j = 0; b < gd->l.npart; ++b) {
+            for (i = 0; i < gd->l.numlines[b]; ++i) {
+                ++j;
+            }
+        }
+        assert(j == 513);
+    }
+    /* short block attack threshold */
+    {
+        float   x = gfp->attackthre;
+        float   y = gfp->attackthre_s;
+        if (x < 0) {
+            x = NSATTACKTHRE;
+        }
+        if (y < 0) {
+            y = NSATTACKTHRE_S;
+        }
+        gd->attack_threshold[0] = gd->attack_threshold[1] = gd->attack_threshold[2] = x;
+        gd->attack_threshold[3] = y;
+    }
+    {
+        float   sk_s = -10.f, sk_l = -4.7f;
+        static float const sk[] =
+            { -7.4, -7.4, -7.4, -9.5, -7.4, -6.1, -5.5, -4.7, -4.7, -4.7, -4.7 };
+        if (gfp->VBR_q < 4) {
+            sk_l = sk_s = sk[0];
+        }
+        else {
+            sk_l = sk_s = sk[gfp->VBR_q] + gfp->VBR_q_frac * (sk[gfp->VBR_q] - sk[gfp->VBR_q + 1]);
+        }
+        b = 0;
+        for (; b < gd->s.npart; b++) {
+            float   m = (float) (gd->s.npart - b) / gd->s.npart;
+            gd->s.masking_lower[b] = powf(10.f, sk_s * m * 0.1f);
+        }
+        for (; b < CBANDS; ++b) {
+            gd->s.masking_lower[b] = 1.f;
+        }
+        b = 0;
+        for (; b < gd->l.npart; b++) {
+            float   m = (float) (gd->l.npart - b) / gd->l.npart;
+            gd->l.masking_lower[b] = powf(10.f, sk_l * m * 0.1f);
+        }
+        for (; b < CBANDS; ++b) {
+            gd->l.masking_lower[b] = 1.f;
+        }
+    }
+    memcpy(&gd->l_to_s, &gd->l, sizeof(gd->l_to_s));
+    init_numline(&gd->l_to_s, sfreq, BLKSIZE, 192, SBMAX_s, gfc->scalefac_band.s);
+    return 0;
+}
diff --git a/lame/libmp3lame/psymodel.h b/lame/libmp3lame/psymodel.h
new file mode 100644 (file)
index 0000000..f46083c
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ *     psymodel.h
+ *
+ *     Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_PSYMODEL_H
+#define LAME_PSYMODEL_H
+
+
+int     L3psycho_anal_ns(lame_internal_flags * gfc,
+                         const sample_t *const buffer[2], int gr,
+                         III_psy_ratio ratio[2][2],
+                         III_psy_ratio MS_ratio[2][2],
+                         FLOAT pe[2], FLOAT pe_MS[2], FLOAT ener[2], int blocktype_d[2]);
+
+int     L3psycho_anal_vbr(lame_internal_flags * gfc,
+                          const sample_t *const buffer[2], int gr,
+                          III_psy_ratio ratio[2][2],
+                          III_psy_ratio MS_ratio[2][2],
+                          FLOAT pe[2], FLOAT pe_MS[2], FLOAT ener[2], int blocktype_d[2]);
+
+
+int     psymodel_init(lame_global_flags const* gfp);
+
+
+#define rpelev 2
+#define rpelev2 16
+#define rpelev_s 2
+#define rpelev2_s 16
+
+/* size of each partition band, in barks: */
+#define DELBARK .34
+
+
+/* tuned for output level (sensitive to energy scale) */
+#define VO_SCALE (1./( 14752*14752 )/(BLKSIZE/2))
+
+#define temporalmask_sustain_sec 0.01
+
+#define NS_PREECHO_ATT0 0.8
+#define NS_PREECHO_ATT1 0.6
+#define NS_PREECHO_ATT2 0.3
+
+#define NS_MSFIX 3.5
+#define NSATTACKTHRE 4.4
+#define NSATTACKTHRE_S 25
+
+#endif /* LAME_PSYMODEL_H */
diff --git a/lame/libmp3lame/quantize.c b/lame/libmp3lame/quantize.c
new file mode 100644 (file)
index 0000000..9ba9c16
--- /dev/null
@@ -0,0 +1,2050 @@
+/*
+ * MP3 quantization
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *      Copyright (c) 1999-2003 Takehiro Tominaga
+ *      Copyright (c) 2000-2011 Robert Hegemann
+ *      Copyright (c) 2001-2005 Gabriel Bouvigne
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: quantize.c,v 1.219 2017/08/02 19:48:05 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "quantize_pvt.h"
+#include "reservoir.h"
+#include "bitstream.h"
+#include "vbrquantize.h"
+#include "quantize.h"
+#ifdef HAVE_XMMINTRIN_H
+#include "vector/lame_intrin.h"
+#endif
+
+
+
+
+/* convert from L/R <-> Mid/Side */
+static void
+ms_convert(III_side_info_t * l3_side, int gr)
+{
+    int     i;
+    for (i = 0; i < 576; ++i) {
+        FLOAT   l, r;
+        l = l3_side->tt[gr][0].xr[i];
+        r = l3_side->tt[gr][1].xr[i];
+        l3_side->tt[gr][0].xr[i] = (l + r) * (FLOAT) (SQRT2 * 0.5);
+        l3_side->tt[gr][1].xr[i] = (l - r) * (FLOAT) (SQRT2 * 0.5);
+    }
+}
+
+/************************************************************************
+ *
+ *      init_outer_loop()
+ *  mt 6/99
+ *
+ *  initializes cod_info, scalefac and xrpow
+ *
+ *  returns 0 if all energies in xr are zero, else 1
+ *
+ ************************************************************************/
+
+static void
+init_xrpow_core_c(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)
+{
+    int     i;
+    FLOAT   tmp;
+    *sum = 0;
+    for (i = 0; i <= upper; ++i) {
+        tmp = fabs(cod_info->xr[i]);
+        *sum += tmp;
+        xrpow[i] = sqrt(tmp * sqrt(tmp));
+
+        if (xrpow[i] > cod_info->xrpow_max)
+            cod_info->xrpow_max = xrpow[i];
+    }
+}
+
+
+
+
+
+void
+init_xrpow_core_init(lame_internal_flags * const gfc)
+{
+    gfc->init_xrpow_core = init_xrpow_core_c;
+
+#if defined(HAVE_XMMINTRIN_H)
+    if (gfc->CPU_features.SSE)
+        gfc->init_xrpow_core = init_xrpow_core_sse;
+#endif
+#ifndef HAVE_NASM
+#ifdef MIN_ARCH_SSE
+    gfc->init_xrpow_core = init_xrpow_core_sse;
+#endif
+#endif
+}
+
+
+
+static int
+init_xrpow(lame_internal_flags * gfc, gr_info * const cod_info, FLOAT xrpow[576])
+{
+    FLOAT   sum = 0;
+    int     i;
+    int const upper = cod_info->max_nonzero_coeff;
+
+    assert(xrpow != NULL);
+    cod_info->xrpow_max = 0;
+
+    /*  check if there is some energy we have to quantize
+     *  and calculate xrpow matching our fresh scalefactors
+     */
+    assert(0 <= upper && upper <= 575);
+    memset(&(xrpow[upper]), 0, (576 - upper) * sizeof(xrpow[0]));
+
+
+    gfc->init_xrpow_core(cod_info, xrpow, upper, &sum);
+
+    /*  return 1 if we have something to quantize, else 0
+     */
+    if (sum > (FLOAT) 1E-20) {
+        int     j = 0;
+        if (gfc->sv_qnt.substep_shaping & 2)
+            j = 1;
+
+        for (i = 0; i < cod_info->psymax; i++)
+            gfc->sv_qnt.pseudohalf[i] = j;
+
+        return 1;
+    }
+
+    memset(&cod_info->l3_enc[0], 0, sizeof(int) * 576);
+    return 0;
+}
+
+
+
+
+
+/*
+Gabriel Bouvigne feb/apr 2003
+Analog silence detection in partitionned sfb21
+or sfb12 for short blocks
+
+From top to bottom of sfb, changes to 0
+coeffs which are below ath. It stops on the first
+coeff higher than ath.
+*/
+static void
+psfb21_analogsilence(lame_internal_flags const *gfc, gr_info * const cod_info)
+{
+    ATH_t const *const ATH = gfc->ATH;
+    FLOAT  *const xr = cod_info->xr;
+
+    if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT blocks */
+        int     gsfb;
+        int     stop = 0;
+        for (gsfb = PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {
+            int const start = gfc->scalefac_band.psfb21[gsfb];
+            int const end = gfc->scalefac_band.psfb21[gsfb + 1];
+            int     j;
+            FLOAT   ath21;
+            ath21 = athAdjust(ATH->adjust_factor, ATH->psfb21[gsfb], ATH->floor, 0);
+
+            if (gfc->sv_qnt.longfact[21] > 1e-12f)
+                ath21 *= gfc->sv_qnt.longfact[21];
+
+            for (j = end - 1; j >= start; j--) {
+                if (fabs(xr[j]) < ath21)
+                    xr[j] = 0;
+                else {
+                    stop = 1;
+                    break;
+                }
+            }
+        }
+    }
+    else {
+        /*note: short blocks coeffs are reordered */
+        int     block;
+        for (block = 0; block < 3; block++) {
+
+            int     gsfb;
+            int     stop = 0;
+            for (gsfb = PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {
+                int const start = gfc->scalefac_band.s[12] * 3 +
+                    (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) * block +
+                    (gfc->scalefac_band.psfb12[gsfb] - gfc->scalefac_band.psfb12[0]);
+                int const end =
+                    start + (gfc->scalefac_band.psfb12[gsfb + 1] - gfc->scalefac_band.psfb12[gsfb]);
+                int     j;
+                FLOAT   ath12;
+                ath12 = athAdjust(ATH->adjust_factor, ATH->psfb12[gsfb], ATH->floor, 0);
+
+                if (gfc->sv_qnt.shortfact[12] > 1e-12f)
+                    ath12 *= gfc->sv_qnt.shortfact[12];
+
+                for (j = end - 1; j >= start; j--) {
+                    if (fabs(xr[j]) < ath12)
+                        xr[j] = 0;
+                    else {
+                        stop = 1;
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+}
+
+
+
+
+
+static void
+init_outer_loop(lame_internal_flags const *gfc, gr_info * const cod_info)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     sfb, j;
+    /*  initialize fresh cod_info
+     */
+    cod_info->part2_3_length = 0;
+    cod_info->big_values = 0;
+    cod_info->count1 = 0;
+    cod_info->global_gain = 210;
+    cod_info->scalefac_compress = 0;
+    /* mixed_block_flag, block_type was set in psymodel.c */
+    cod_info->table_select[0] = 0;
+    cod_info->table_select[1] = 0;
+    cod_info->table_select[2] = 0;
+    cod_info->subblock_gain[0] = 0;
+    cod_info->subblock_gain[1] = 0;
+    cod_info->subblock_gain[2] = 0;
+    cod_info->subblock_gain[3] = 0; /* this one is always 0 */
+    cod_info->region0_count = 0;
+    cod_info->region1_count = 0;
+    cod_info->preflag = 0;
+    cod_info->scalefac_scale = 0;
+    cod_info->count1table_select = 0;
+    cod_info->part2_length = 0;
+    if (cfg->samplerate_out <= 8000) {
+      cod_info->sfb_lmax = 17;
+      cod_info->sfb_smin = 9;
+      cod_info->psy_lmax = 17;
+    }
+    else {
+      cod_info->sfb_lmax = SBPSY_l;
+      cod_info->sfb_smin = SBPSY_s;
+      cod_info->psy_lmax = gfc->sv_qnt.sfb21_extra ? SBMAX_l : SBPSY_l;
+    }
+    cod_info->psymax = cod_info->psy_lmax;
+    cod_info->sfbmax = cod_info->sfb_lmax;
+    cod_info->sfbdivide = 11;
+    for (sfb = 0; sfb < SBMAX_l; sfb++) {
+        cod_info->width[sfb]
+            = gfc->scalefac_band.l[sfb + 1] - gfc->scalefac_band.l[sfb];
+        cod_info->window[sfb] = 3; /* which is always 0. */
+    }
+    if (cod_info->block_type == SHORT_TYPE) {
+        FLOAT   ixwork[576];
+        FLOAT  *ix;
+
+        cod_info->sfb_smin = 0;
+        cod_info->sfb_lmax = 0;
+        if (cod_info->mixed_block_flag) {
+            /*
+             *  MPEG-1:      sfbs 0-7 long block, 3-12 short blocks
+             *  MPEG-2(.5):  sfbs 0-5 long block, 3-12 short blocks
+             */
+            cod_info->sfb_smin = 3;
+            cod_info->sfb_lmax = cfg->mode_gr * 2 + 4;
+        }
+        if (cfg->samplerate_out <= 8000) {
+            cod_info->psymax
+                = cod_info->sfb_lmax
+                + 3 * (9 - cod_info->sfb_smin);
+            cod_info->sfbmax = cod_info->sfb_lmax + 3 * (9 - cod_info->sfb_smin);
+        }
+        else {
+            cod_info->psymax
+                = cod_info->sfb_lmax
+                + 3 * ((gfc->sv_qnt.sfb21_extra ? SBMAX_s : SBPSY_s) - cod_info->sfb_smin);
+            cod_info->sfbmax = cod_info->sfb_lmax + 3 * (SBPSY_s - cod_info->sfb_smin);
+        }
+        cod_info->sfbdivide = cod_info->sfbmax - 18;
+        cod_info->psy_lmax = cod_info->sfb_lmax;
+        /* re-order the short blocks, for more efficient encoding below */
+        /* By Takehiro TOMINAGA */
+        /*
+           Within each scalefactor band, data is given for successive
+           time windows, beginning with window 0 and ending with window 2.
+           Within each window, the quantized values are then arranged in
+           order of increasing frequency...
+         */
+        ix = &cod_info->xr[gfc->scalefac_band.l[cod_info->sfb_lmax]];
+        memcpy(ixwork, cod_info->xr, 576 * sizeof(FLOAT));
+        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
+            int const start = gfc->scalefac_band.s[sfb];
+            int const end = gfc->scalefac_band.s[sfb + 1];
+            int     window, l;
+            for (window = 0; window < 3; window++) {
+                for (l = start; l < end; l++) {
+                    *ix++ = ixwork[3 * l + window];
+                }
+            }
+        }
+
+        j = cod_info->sfb_lmax;
+        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
+            cod_info->width[j] = cod_info->width[j + 1] = cod_info->width[j + 2]
+                = gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb];
+            cod_info->window[j] = 0;
+            cod_info->window[j + 1] = 1;
+            cod_info->window[j + 2] = 2;
+            j += 3;
+        }
+    }
+
+    cod_info->count1bits = 0;
+    cod_info->sfb_partition_table = nr_of_sfb_block[0][0];
+    cod_info->slen[0] = 0;
+    cod_info->slen[1] = 0;
+    cod_info->slen[2] = 0;
+    cod_info->slen[3] = 0;
+
+    cod_info->max_nonzero_coeff = 575;
+
+    /*  fresh scalefactors are all zero
+     */
+    memset(cod_info->scalefac, 0, sizeof(cod_info->scalefac));
+
+    if (cfg->vbr != vbr_mt && cfg->vbr != vbr_mtrh && cfg->vbr != vbr_abr && cfg->vbr != vbr_off) {
+        psfb21_analogsilence(gfc, cod_info);
+    }
+}
+
+
+
+/************************************************************************
+ *
+ *      bin_search_StepSize()
+ *
+ *  author/date??
+ *
+ *  binary step size search
+ *  used by outer_loop to get a quantizer step size to start with
+ *
+ ************************************************************************/
+
+typedef enum {
+    BINSEARCH_NONE,
+    BINSEARCH_UP,
+    BINSEARCH_DOWN
+} binsearchDirection_t;
+
+static int
+bin_search_StepSize(lame_internal_flags * const gfc, gr_info * const cod_info,
+                    int desired_rate, const int ch, const FLOAT xrpow[576])
+{
+    int     nBits;
+    int     CurrentStep = gfc->sv_qnt.CurrentStep[ch];
+    int     flag_GoneOver = 0;
+    int const start = gfc->sv_qnt.OldValue[ch];
+    binsearchDirection_t Direction = BINSEARCH_NONE;
+    cod_info->global_gain = start;
+    desired_rate -= cod_info->part2_length;
+
+    assert(CurrentStep);
+    for (;;) {
+        int     step;
+        nBits = count_bits(gfc, xrpow, cod_info, 0);
+
+        if (CurrentStep == 1 || nBits == desired_rate)
+            break;      /* nothing to adjust anymore */
+
+        if (nBits > desired_rate) {
+            /* increase Quantize_StepSize */
+            if (Direction == BINSEARCH_DOWN)
+                flag_GoneOver = 1;
+
+            if (flag_GoneOver)
+                CurrentStep /= 2;
+            Direction = BINSEARCH_UP;
+            step = CurrentStep;
+        }
+        else {
+            /* decrease Quantize_StepSize */
+            if (Direction == BINSEARCH_UP)
+                flag_GoneOver = 1;
+
+            if (flag_GoneOver)
+                CurrentStep /= 2;
+            Direction = BINSEARCH_DOWN;
+            step = -CurrentStep;
+        }
+        cod_info->global_gain += step;
+        if (cod_info->global_gain < 0) {
+            cod_info->global_gain = 0;
+            flag_GoneOver = 1;
+        }
+        if (cod_info->global_gain > 255) {
+            cod_info->global_gain = 255;
+            flag_GoneOver = 1;
+        }
+    }
+
+    assert(cod_info->global_gain >= 0);
+    assert(cod_info->global_gain < 256);
+
+    while (nBits > desired_rate && cod_info->global_gain < 255) {
+        cod_info->global_gain++;
+        nBits = count_bits(gfc, xrpow, cod_info, 0);
+    }
+    gfc->sv_qnt.CurrentStep[ch] = (start - cod_info->global_gain >= 4) ? 4 : 2;
+    gfc->sv_qnt.OldValue[ch] = cod_info->global_gain;
+    cod_info->part2_3_length = nBits;
+    return nBits;
+}
+
+
+
+
+/************************************************************************
+ *
+ *      trancate_smallspectrums()
+ *
+ *  Takehiro TOMINAGA 2002-07-21
+ *
+ *  trancate smaller nubmers into 0 as long as the noise threshold is allowed.
+ *
+ ************************************************************************/
+static int
+floatcompare(const void *v1, const void *v2)
+{
+    const FLOAT *const a = v1, *const b = v2;
+    if (*a > *b)
+        return 1;
+    if (*a < *b)
+        return -1;
+    return 0;
+}
+
+static void
+trancate_smallspectrums(lame_internal_flags const *gfc,
+                        gr_info * const gi, const FLOAT * const l3_xmin, FLOAT * const work)
+{
+    int     sfb, j, width;
+    FLOAT   distort[SFBMAX];
+    calc_noise_result dummy;
+
+    if ((!(gfc->sv_qnt.substep_shaping & 4) && gi->block_type == SHORT_TYPE)
+        || gfc->sv_qnt.substep_shaping & 0x80)
+        return;
+    (void) calc_noise(gi, l3_xmin, distort, &dummy, 0);
+    for (j = 0; j < 576; j++) {
+        FLOAT   xr = 0.0;
+        if (gi->l3_enc[j] != 0)
+            xr = fabs(gi->xr[j]);
+        work[j] = xr;
+    }
+
+    j = 0;
+    sfb = 8;
+    if (gi->block_type == SHORT_TYPE)
+        sfb = 6;
+    do {
+        FLOAT   allowedNoise, trancateThreshold;
+        int     nsame, start;
+
+        width = gi->width[sfb];
+        j += width;
+        if (distort[sfb] >= 1.0)
+            continue;
+
+        qsort(&work[j - width], width, sizeof(FLOAT), floatcompare);
+        if (EQ(work[j - 1], 0.0))
+            continue;   /* all zero sfb */
+
+        allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];
+        trancateThreshold = 0.0;
+        start = 0;
+        do {
+            FLOAT   noise;
+            for (nsame = 1; start + nsame < width; nsame++)
+                if (NEQ(work[start + j - width], work[start + j + nsame - width]))
+                    break;
+
+            noise = work[start + j - width] * work[start + j - width] * nsame;
+            if (allowedNoise < noise) {
+                if (start != 0)
+                    trancateThreshold = work[start + j - width - 1];
+                break;
+            }
+            allowedNoise -= noise;
+            start += nsame;
+        } while (start < width);
+        if (EQ(trancateThreshold, 0.0))
+            continue;
+
+/*      printf("%e %e %e\n", */
+/*             trancateThreshold/l3_xmin[sfb], */
+/*             trancateThreshold/(l3_xmin[sfb]*start), */
+/*             trancateThreshold/(l3_xmin[sfb]*(start+width)) */
+/*          ); */
+/*      if (trancateThreshold > 1000*l3_xmin[sfb]*start) */
+/*          trancateThreshold = 1000*l3_xmin[sfb]*start; */
+
+        do {
+            if (fabs(gi->xr[j - width]) <= trancateThreshold)
+                gi->l3_enc[j - width] = 0;
+        } while (--width > 0);
+    } while (++sfb < gi->psymax);
+
+    gi->part2_3_length = noquant_count_bits(gfc, gi, 0);
+}
+
+
+/*************************************************************************
+ *
+ *      loop_break()
+ *
+ *  author/date??
+ *
+ *  Function: Returns zero if there is a scalefac which has not been
+ *            amplified. Otherwise it returns one.
+ *
+ *************************************************************************/
+
+inline static int
+loop_break(const gr_info * const cod_info)
+{
+    int     sfb;
+
+    for (sfb = 0; sfb < cod_info->sfbmax; sfb++)
+        if (cod_info->scalefac[sfb]
+            + cod_info->subblock_gain[cod_info->window[sfb]] == 0)
+            return 0;
+
+    return 1;
+}
+
+
+
+
+/*  mt 5/99:  Function: Improved calc_noise for a single channel   */
+
+/*************************************************************************
+ *
+ *      quant_compare()
+ *
+ *  author/date??
+ *
+ *  several different codes to decide which quantization is better
+ *
+ *************************************************************************/
+
+static double
+penalties(double noise)
+{
+    return FAST_LOG10(0.368 + 0.632 * noise * noise * noise);
+}
+
+static double
+get_klemm_noise(const FLOAT * distort, const gr_info * const gi)
+{
+    int     sfb;
+    double  klemm_noise = 1E-37;
+    for (sfb = 0; sfb < gi->psymax; sfb++)
+        klemm_noise += penalties(distort[sfb]);
+
+    return Max(1e-20, klemm_noise);
+}
+
+inline static int
+quant_compare(const int quant_comp,
+              const calc_noise_result * const best,
+              calc_noise_result * const calc, const gr_info * const gi, const FLOAT * distort)
+{
+    /*
+       noise is given in decibels (dB) relative to masking thesholds.
+
+       over_noise:  ??? (the previous comment is fully wrong)
+       tot_noise:   ??? (the previous comment is fully wrong)
+       max_noise:   max quantization noise
+
+     */
+    int     better;
+
+    switch (quant_comp) {
+    default:
+    case 9:{
+            if (best->over_count > 0) {
+                /* there are distorted sfb */
+                better = calc->over_SSD <= best->over_SSD;
+                if (calc->over_SSD == best->over_SSD)
+                    better = calc->bits < best->bits;
+            }
+            else {
+                /* no distorted sfb */
+                better = ((calc->max_noise < 0) &&
+                          ((calc->max_noise * 10 + calc->bits) <=
+                           (best->max_noise * 10 + best->bits)));
+            }
+            break;
+        }
+
+    case 0:
+        better = calc->over_count < best->over_count
+            || (calc->over_count == best->over_count && calc->over_noise < best->over_noise)
+            || (calc->over_count == best->over_count &&
+                EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
+        break;
+
+    case 8:
+        calc->max_noise = get_klemm_noise(distort, gi);
+        /*lint --fallthrough */
+    case 1:
+        better = calc->max_noise < best->max_noise;
+        break;
+    case 2:
+        better = calc->tot_noise < best->tot_noise;
+        break;
+    case 3:
+        better = (calc->tot_noise < best->tot_noise)
+            && (calc->max_noise < best->max_noise);
+        break;
+    case 4:
+        better = (calc->max_noise <= 0.0 && best->max_noise > 0.2)
+            || (calc->max_noise <= 0.0 &&
+                best->max_noise < 0.0 &&
+                best->max_noise > calc->max_noise - 0.2 && calc->tot_noise < best->tot_noise)
+            || (calc->max_noise <= 0.0 &&
+                best->max_noise > 0.0 &&
+                best->max_noise > calc->max_noise - 0.2 &&
+                calc->tot_noise < best->tot_noise + best->over_noise)
+            || (calc->max_noise > 0.0 &&
+                best->max_noise > -0.05 &&
+                best->max_noise > calc->max_noise - 0.1 &&
+                calc->tot_noise + calc->over_noise < best->tot_noise + best->over_noise)
+            || (calc->max_noise > 0.0 &&
+                best->max_noise > -0.1 &&
+                best->max_noise > calc->max_noise - 0.15 &&
+                calc->tot_noise + calc->over_noise + calc->over_noise <
+                best->tot_noise + best->over_noise + best->over_noise);
+        break;
+    case 5:
+        better = calc->over_noise < best->over_noise
+            || (EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);
+        break;
+    case 6:
+        better = calc->over_noise < best->over_noise
+            || (EQ(calc->over_noise, best->over_noise) &&
+                (calc->max_noise < best->max_noise
+                 || (EQ(calc->max_noise, best->max_noise) && calc->tot_noise <= best->tot_noise)
+                ));
+        break;
+    case 7:
+        better = calc->over_count < best->over_count || calc->over_noise < best->over_noise;
+        break;
+    }
+
+
+    if (best->over_count == 0) {
+        /*
+           If no distorted bands, only use this quantization
+           if it is better, and if it uses less bits.
+           Unfortunately, part2_3_length is sometimes a poor
+           estimator of the final size at low bitrates.
+         */
+        better = better && calc->bits < best->bits;
+    }
+
+
+    return better;
+}
+
+
+
+/*************************************************************************
+ *
+ *          amp_scalefac_bands()
+ *
+ *  author/date??
+ *
+ *  Amplify the scalefactor bands that violate the masking threshold.
+ *  See ISO 11172-3 Section C.1.5.4.3.5
+ *
+ *  distort[] = noise/masking
+ *  distort[] > 1   ==> noise is not masked
+ *  distort[] < 1   ==> noise is masked
+ *  max_dist = maximum value of distort[]
+ *
+ *  Three algorithms:
+ *  noise_shaping_amp
+ *        0             Amplify all bands with distort[]>1.
+ *
+ *        1             Amplify all bands with distort[] >= max_dist^(.5);
+ *                     ( 50% in the db scale)
+ *
+ *        2             Amplify first band with distort[] >= max_dist;
+ *
+ *
+ *  For algorithms 0 and 1, if max_dist < 1, then amplify all bands
+ *  with distort[] >= .95*max_dist.  This is to make sure we always
+ *  amplify at least one band.
+ *
+ *
+ *************************************************************************/
+static void
+amp_scalefac_bands(lame_internal_flags * gfc,
+                   gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     j, sfb;
+    FLOAT   ifqstep34, trigger;
+    int     noise_shaping_amp;
+
+    if (cod_info->scalefac_scale == 0) {
+        ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5) */
+    }
+    else {
+        ifqstep34 = 1.68179283050742922612; /* 2**(.75*1) */
+    }
+
+    /* compute maximum value of distort[]  */
+    trigger = 0;
+    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
+        if (trigger < distort[sfb])
+            trigger = distort[sfb];
+    }
+
+    noise_shaping_amp = cfg->noise_shaping_amp;
+    if (noise_shaping_amp == 3) {
+        if (bRefine == 1)
+            noise_shaping_amp = 2;
+        else
+            noise_shaping_amp = 1;
+    }
+    switch (noise_shaping_amp) {
+    case 2:
+        /* amplify exactly 1 band */
+        break;
+
+    case 1:
+        /* amplify bands within 50% of max (on db scale) */
+        if (trigger > 1.0)
+            trigger = pow(trigger, .5);
+        else
+            trigger *= .95;
+        break;
+
+    case 0:
+    default:
+        /* ISO algorithm.  amplify all bands with distort>1 */
+        if (trigger > 1.0)
+            trigger = 1.0;
+        else
+            trigger *= .95;
+        break;
+    }
+
+    j = 0;
+    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
+        int const width = cod_info->width[sfb];
+        int     l;
+        j += width;
+        if (distort[sfb] < trigger)
+            continue;
+
+        if (gfc->sv_qnt.substep_shaping & 2) {
+            gfc->sv_qnt.pseudohalf[sfb] = !gfc->sv_qnt.pseudohalf[sfb];
+            if (!gfc->sv_qnt.pseudohalf[sfb] && cfg->noise_shaping_amp == 2)
+                return;
+        }
+        cod_info->scalefac[sfb]++;
+        for (l = -width; l < 0; l++) {
+            xrpow[j + l] *= ifqstep34;
+            if (xrpow[j + l] > cod_info->xrpow_max)
+                cod_info->xrpow_max = xrpow[j + l];
+        }
+
+        if (cfg->noise_shaping_amp == 2)
+            return;
+    }
+}
+
+/*************************************************************************
+ *
+ *      inc_scalefac_scale()
+ *
+ *  Takehiro Tominaga 2000-xx-xx
+ *
+ *  turns on scalefac scale and adjusts scalefactors
+ *
+ *************************************************************************/
+
+static void
+inc_scalefac_scale(gr_info * const cod_info, FLOAT xrpow[576])
+{
+    int     l, j, sfb;
+    const FLOAT ifqstep34 = 1.29683955465100964055;
+
+    j = 0;
+    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {
+        int const width = cod_info->width[sfb];
+        int     s = cod_info->scalefac[sfb];
+        if (cod_info->preflag)
+            s += pretab[sfb];
+        j += width;
+        if (s & 1) {
+            s++;
+            for (l = -width; l < 0; l++) {
+                xrpow[j + l] *= ifqstep34;
+                if (xrpow[j + l] > cod_info->xrpow_max)
+                    cod_info->xrpow_max = xrpow[j + l];
+            }
+        }
+        cod_info->scalefac[sfb] = s >> 1;
+    }
+    cod_info->preflag = 0;
+    cod_info->scalefac_scale = 1;
+}
+
+
+
+/*************************************************************************
+ *
+ *      inc_subblock_gain()
+ *
+ *  Takehiro Tominaga 2000-xx-xx
+ *
+ *  increases the subblock gain and adjusts scalefactors
+ *
+ *************************************************************************/
+
+static int
+inc_subblock_gain(const lame_internal_flags * const gfc, gr_info * const cod_info, FLOAT xrpow[576])
+{
+    int     sfb, window;
+    int    *const scalefac = cod_info->scalefac;
+
+    /* subbloc_gain can't do anything in the long block region */
+    for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
+        if (scalefac[sfb] >= 16)
+            return 1;
+    }
+
+    for (window = 0; window < 3; window++) {
+        int     s1, s2, l, j;
+        s1 = s2 = 0;
+
+        for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbdivide; sfb += 3) {
+            if (s1 < scalefac[sfb])
+                s1 = scalefac[sfb];
+        }
+        for (; sfb < cod_info->sfbmax; sfb += 3) {
+            if (s2 < scalefac[sfb])
+                s2 = scalefac[sfb];
+        }
+
+        if (s1 < 16 && s2 < 8)
+            continue;
+
+        if (cod_info->subblock_gain[window] >= 7)
+            return 1;
+
+        /* even though there is no scalefactor for sfb12
+         * subblock gain affects upper frequencies too, that's why
+         * we have to go up to SBMAX_s
+         */
+        cod_info->subblock_gain[window]++;
+        j = gfc->scalefac_band.l[cod_info->sfb_lmax];
+        for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbmax; sfb += 3) {
+            FLOAT   amp;
+            int const width = cod_info->width[sfb];
+            int     s = scalefac[sfb];
+            assert(s >= 0);
+            s = s - (4 >> cod_info->scalefac_scale);
+            if (s >= 0) {
+                scalefac[sfb] = s;
+                j += width * 3;
+                continue;
+            }
+
+            scalefac[sfb] = 0;
+            {
+                int const gain = 210 + (s << (cod_info->scalefac_scale + 1));
+                amp = IPOW20(gain);
+            }
+            j += width * (window + 1);
+            for (l = -width; l < 0; l++) {
+                xrpow[j + l] *= amp;
+                if (xrpow[j + l] > cod_info->xrpow_max)
+                    cod_info->xrpow_max = xrpow[j + l];
+            }
+            j += width * (3 - window - 1);
+        }
+
+        {
+            FLOAT const amp = IPOW20(202);
+            j += cod_info->width[sfb] * (window + 1);
+            for (l = -cod_info->width[sfb]; l < 0; l++) {
+                xrpow[j + l] *= amp;
+                if (xrpow[j + l] > cod_info->xrpow_max)
+                    cod_info->xrpow_max = xrpow[j + l];
+            }
+        }
+    }
+    return 0;
+}
+
+
+
+/********************************************************************
+ *
+ *      balance_noise()
+ *
+ *  Takehiro Tominaga /date??
+ *  Robert Hegemann 2000-09-06: made a function of it
+ *
+ *  amplifies scalefactor bands,
+ *   - if all are already amplified returns 0
+ *   - if some bands are amplified too much:
+ *      * try to increase scalefac_scale
+ *      * if already scalefac_scale was set
+ *          try on short blocks to increase subblock gain
+ *
+ ********************************************************************/
+inline static int
+balance_noise(lame_internal_flags * gfc,
+              gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     status;
+
+    amp_scalefac_bands(gfc, cod_info, distort, xrpow, bRefine);
+
+    /* check to make sure we have not amplified too much
+     * loop_break returns 0 if there is an unamplified scalefac
+     * scale_bitcount returns 0 if no scalefactors are too large
+     */
+
+    status = loop_break(cod_info);
+
+    if (status)
+        return 0;       /* all bands amplified */
+
+    /* not all scalefactors have been amplified.  so these
+     * scalefacs are possibly valid.  encode them:
+     */
+    status = scale_bitcount(gfc, cod_info);
+
+    if (!status)
+        return 1;       /* amplified some bands not exceeding limits */
+
+    /*  some scalefactors are too large.
+     *  lets try setting scalefac_scale=1
+     */
+    if (cfg->noise_shaping > 1) {
+        memset(&gfc->sv_qnt.pseudohalf[0], 0, sizeof(gfc->sv_qnt.pseudohalf));
+        if (!cod_info->scalefac_scale) {
+            inc_scalefac_scale(cod_info, xrpow);
+            status = 0;
+        }
+        else {
+            if (cod_info->block_type == SHORT_TYPE && cfg->subblock_gain > 0) {
+                status = inc_subblock_gain(gfc, cod_info, xrpow)
+                    || loop_break(cod_info);
+            }
+        }
+    }
+
+    if (!status) {
+        status = scale_bitcount(gfc, cod_info);
+    }
+    return !status;
+}
+
+
+
+/************************************************************************
+ *
+ *  outer_loop ()
+ *
+ *  Function: The outer iteration loop controls the masking conditions
+ *  of all scalefactorbands. It computes the best scalefac and
+ *  global gain. This module calls the inner iteration loop
+ *
+ *  mt 5/99 completely rewritten to allow for bit reservoir control,
+ *  mid/side channels with L/R or mid/side masking thresholds,
+ *  and chooses best quantization instead of last quantization when
+ *  no distortion free quantization can be found.
+ *
+ *  added VBR support mt 5/99
+ *
+ *  some code shuffle rh 9/00
+ ************************************************************************/
+
+static int
+outer_loop(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion */
+           FLOAT xrpow[576], /* coloured magnitudes of spectral */
+           const int ch, const int targ_bits)
+{                       /* maximum allowed bits */
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    gr_info cod_info_w;
+    FLOAT   save_xrpow[576];
+    FLOAT   distort[SFBMAX];
+    calc_noise_result best_noise_info;
+    int     huff_bits;
+    int     better;
+    int     age;
+    calc_noise_data prev_noise;
+    int     best_part2_3_length = 9999999;
+    int     bEndOfSearch = 0;
+    int     bRefine = 0;
+    int     best_ggain_pass1 = 0;
+
+    (void) bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);
+
+    if (!cfg->noise_shaping)
+        /* fast mode, no noise shaping, we are ready */
+        return 100;     /* default noise_info.over_count */
+
+    memset(&prev_noise, 0, sizeof(calc_noise_data));
+
+
+    /* compute the distortion in this quantization */
+    /* coefficients and thresholds both l/r (or both mid/side) */
+    (void) calc_noise(cod_info, l3_xmin, distort, &best_noise_info, &prev_noise);
+    best_noise_info.bits = cod_info->part2_3_length;
+
+    cod_info_w = *cod_info;
+    age = 0;
+    /* if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */
+    memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
+
+    while (!bEndOfSearch) {
+        /* BEGIN MAIN LOOP */
+        do {
+            calc_noise_result noise_info;
+            int     search_limit;
+            int     maxggain = 255;
+
+            /* When quantization with no distorted bands is found,
+             * allow up to X new unsuccesful tries in serial. This
+             * gives us more possibilities for different quant_compare modes.
+             * Much more than 3 makes not a big difference, it is only slower.
+             */
+
+            if (gfc->sv_qnt.substep_shaping & 2) {
+                search_limit = 20;
+            }
+            else {
+                search_limit = 3;
+            }
+
+
+
+            /* Check if the last scalefactor band is distorted.
+             * in VBR mode we can't get rid of the distortion, so quit now
+             * and VBR mode will try again with more bits.
+             * (makes a 10% speed increase, the files I tested were
+             * binary identical, 2000/05/20 Robert Hegemann)
+             * distort[] > 1 means noise > allowed noise
+             */
+            if (gfc->sv_qnt.sfb21_extra) {
+                if (distort[cod_info_w.sfbmax] > 1.0)
+                    break;
+                if (cod_info_w.block_type == SHORT_TYPE
+                    && (distort[cod_info_w.sfbmax + 1] > 1.0
+                        || distort[cod_info_w.sfbmax + 2] > 1.0))
+                    break;
+            }
+
+            /* try a new scalefactor conbination on cod_info_w */
+            if (balance_noise(gfc, &cod_info_w, distort, xrpow, bRefine) == 0)
+                break;
+            if (cod_info_w.scalefac_scale)
+                maxggain = 254;
+
+            /* inner_loop starts with the initial quantization step computed above
+             * and slowly increases until the bits < huff_bits.
+             * Thus it is important not to start with too large of an inital
+             * quantization step.  Too small is ok, but inner_loop will take longer
+             */
+            huff_bits = targ_bits - cod_info_w.part2_length;
+            if (huff_bits <= 0)
+                break;
+
+            /*  increase quantizer stepsize until needed bits are below maximum
+             */
+            while ((cod_info_w.part2_3_length
+                    = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > huff_bits
+                   && cod_info_w.global_gain <= maxggain)
+                cod_info_w.global_gain++;
+
+            if (cod_info_w.global_gain > maxggain)
+                break;
+
+            if (best_noise_info.over_count == 0) {
+
+                while ((cod_info_w.part2_3_length
+                        = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > best_part2_3_length
+                       && cod_info_w.global_gain <= maxggain)
+                    cod_info_w.global_gain++;
+
+                if (cod_info_w.global_gain > maxggain)
+                    break;
+            }
+
+            /* compute the distortion in this quantization */
+            (void) calc_noise(&cod_info_w, l3_xmin, distort, &noise_info, &prev_noise);
+            noise_info.bits = cod_info_w.part2_3_length;
+
+            /* check if this quantization is better
+             * than our saved quantization */
+            if (cod_info->block_type != SHORT_TYPE) /* NORM, START or STOP type */
+                better = cfg->quant_comp;
+            else
+                better = cfg->quant_comp_short;
+
+
+            better = quant_compare(better, &best_noise_info, &noise_info, &cod_info_w, distort);
+
+
+            /* save data so we can restore this quantization later */
+            if (better) {
+                best_part2_3_length = cod_info->part2_3_length;
+                best_noise_info = noise_info;
+                *cod_info = cod_info_w;
+                age = 0;
+                /* save data so we can restore this quantization later */
+                /*if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */  {
+                    /* store for later reuse */
+                    memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);
+                }
+            }
+            else {
+                /* early stop? */
+                if (cfg->full_outer_loop == 0) {
+                    if (++age > search_limit && best_noise_info.over_count == 0)
+                        break;
+                    if ((cfg->noise_shaping_amp == 3) && bRefine && age > 30)
+                        break;
+                    if ((cfg->noise_shaping_amp == 3) && bRefine &&
+                        (cod_info_w.global_gain - best_ggain_pass1) > 15)
+                        break;
+                }
+            }
+        }
+        while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);
+
+        if (cfg->noise_shaping_amp == 3) {
+            if (!bRefine) {
+                /* refine search */
+                cod_info_w = *cod_info;
+                memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
+                age = 0;
+                best_ggain_pass1 = cod_info_w.global_gain;
+
+                bRefine = 1;
+            }
+            else {
+                /* search already refined, stop */
+                bEndOfSearch = 1;
+            }
+
+        }
+        else {
+            bEndOfSearch = 1;
+        }
+    }
+
+    assert((cod_info->global_gain + cod_info->scalefac_scale) <= 255);
+    /*  finish up
+     */
+    if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh || cfg->vbr == vbr_mt)
+        /* restore for reuse on next try */
+        memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);
+    /*  do the 'substep shaping'
+     */
+    else if (gfc->sv_qnt.substep_shaping & 1)
+        trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);
+
+    return best_noise_info.over_count;
+}
+
+
+
+
+
+/************************************************************************
+ *
+ *      iteration_finish_one()
+ *
+ *  Robert Hegemann 2000-09-06
+ *
+ *  update reservoir status after FINAL quantization/bitrate
+ *
+ ************************************************************************/
+
+static void
+iteration_finish_one(lame_internal_flags * gfc, int gr, int ch)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+    gr_info *const cod_info = &l3_side->tt[gr][ch];
+
+    /*  try some better scalefac storage
+     */
+    best_scalefac_store(gfc, gr, ch, l3_side);
+
+    /*  best huffman_divide may save some bits too
+     */
+    if (cfg->use_best_huffman == 1)
+        best_huffman_divide(gfc, cod_info);
+
+    /*  update reservoir status after FINAL quantization/bitrate
+     */
+    ResvAdjust(gfc, cod_info);
+}
+
+
+
+/*********************************************************************
+ *
+ *      VBR_encode_granule()
+ *
+ *  2000-09-04 Robert Hegemann
+ *
+ *********************************************************************/
+
+static void
+VBR_encode_granule(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion of the scalefactor */
+                   FLOAT xrpow[576], /* coloured magnitudes of spectral values */
+                   const int ch, int min_bits, int max_bits)
+{
+    gr_info bst_cod_info;
+    FLOAT   bst_xrpow[576];
+    int const Max_bits = max_bits;
+    int     real_bits = max_bits + 1;
+    int     this_bits = (max_bits + min_bits) / 2;
+    int     dbits, over, found = 0;
+    int const sfb21_extra = gfc->sv_qnt.sfb21_extra;
+
+    assert(Max_bits <= MAX_BITS_PER_CHANNEL);
+    memset(bst_cod_info.l3_enc, 0, sizeof(bst_cod_info.l3_enc));
+
+    /*  search within round about 40 bits of optimal
+     */
+    do {
+        assert(this_bits >= min_bits);
+        assert(this_bits <= max_bits);
+        assert(min_bits <= max_bits);
+
+        if (this_bits > Max_bits - 42)
+            gfc->sv_qnt.sfb21_extra = 0;
+        else
+            gfc->sv_qnt.sfb21_extra = sfb21_extra;
+
+        over = outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, this_bits);
+
+        /*  is quantization as good as we are looking for ?
+         *  in this case: is no scalefactor band distorted?
+         */
+        if (over <= 0) {
+            found = 1;
+            /*  now we know it can be done with "real_bits"
+             *  and maybe we can skip some iterations
+             */
+            real_bits = cod_info->part2_3_length;
+
+            /*  store best quantization so far
+             */
+            bst_cod_info = *cod_info;
+            memcpy(bst_xrpow, xrpow, sizeof(FLOAT) * 576);
+
+            /*  try with fewer bits
+             */
+            max_bits = real_bits - 32;
+            dbits = max_bits - min_bits;
+            this_bits = (max_bits + min_bits) / 2;
+        }
+        else {
+            /*  try with more bits
+             */
+            min_bits = this_bits + 32;
+            dbits = max_bits - min_bits;
+            this_bits = (max_bits + min_bits) / 2;
+
+            if (found) {
+                found = 2;
+                /*  start again with best quantization so far
+                 */
+                *cod_info = bst_cod_info;
+                memcpy(xrpow, bst_xrpow, sizeof(FLOAT) * 576);
+            }
+        }
+    } while (dbits > 12);
+
+    gfc->sv_qnt.sfb21_extra = sfb21_extra;
+
+    /*  found=0 => nothing found, use last one
+     *  found=1 => we just found the best and left the loop
+     *  found=2 => we restored a good one and have now l3_enc to restore too
+     */
+    if (found == 2) {
+        memcpy(cod_info->l3_enc, bst_cod_info.l3_enc, sizeof(int) * 576);
+    }
+    assert(cod_info->part2_3_length <= Max_bits);
+
+}
+
+
+
+/************************************************************************
+ *
+ *      get_framebits()
+ *
+ *  Robert Hegemann 2000-09-05
+ *
+ *  calculates
+ *  * how many bits are available for analog silent granules
+ *  * how many bits to use for the lowest allowed bitrate
+ *  * how many bits each bitrate would provide
+ *
+ ************************************************************************/
+
+static void
+get_framebits(lame_internal_flags * gfc, int frameBits[15])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+    int     bitsPerFrame, i;
+
+    /*  always use at least this many bits per granule per channel
+     *  unless we detect analog silence, see below
+     */
+    eov->bitrate_index = cfg->vbr_min_bitrate_index;
+    bitsPerFrame = getframebits(gfc);
+
+    /*  bits for analog silence
+     */
+    eov->bitrate_index = 1;
+    bitsPerFrame = getframebits(gfc);
+
+    for (i = 1; i <= cfg->vbr_max_bitrate_index; i++) {
+        eov->bitrate_index = i;
+        frameBits[i] = ResvFrameBegin(gfc, &bitsPerFrame);
+    }
+}
+
+
+
+/*********************************************************************
+ *
+ *      VBR_prepare()
+ *
+ *  2000-09-04 Robert Hegemann
+ *
+ *  * converts LR to MS coding when necessary
+ *  * calculates allowed/adjusted quantization noise amounts
+ *  * detects analog silent frames
+ *
+ *  some remarks:
+ *  - lower masking depending on Quality setting
+ *  - quality control together with adjusted ATH MDCT scaling
+ *    on lower quality setting allocate more noise from
+ *    ATH masking, and on higher quality setting allocate
+ *    less noise from ATH masking.
+ *  - experiments show that going more than 2dB over GPSYCHO's
+ *    limits ends up in very annoying artefacts
+ *
+ *********************************************************************/
+
+/* RH: this one needs to be overhauled sometime */
+
+static int
+VBR_old_prepare(lame_internal_flags * gfc,
+                const FLOAT pe[2][2], FLOAT const ms_ener_ratio[2],
+                const III_psy_ratio ratio[2][2],
+                FLOAT l3_xmin[2][2][SFBMAX],
+                int frameBits[16], int min_bits[2][2], int max_bits[2][2], int bands[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+
+    FLOAT   masking_lower_db, adjust = 0.0;
+    int     gr, ch;
+    int     analog_silence = 1;
+    int     avg, mxb, bits = 0;
+
+    eov->bitrate_index = cfg->vbr_max_bitrate_index;
+    avg = ResvFrameBegin(gfc, &avg) / cfg->mode_gr;
+
+    get_framebits(gfc, frameBits);
+
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        mxb = on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
+        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+            ms_convert(&gfc->l3_side, gr);
+            reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);
+        }
+        for (ch = 0; ch < cfg->channels_out; ++ch) {
+            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
+
+            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
+                adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;
+                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
+            }
+            else {
+                adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;
+                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
+            }
+            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
+
+            init_outer_loop(gfc, cod_info);
+            bands[gr][ch] = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]);
+            if (bands[gr][ch])
+                analog_silence = 0;
+
+            min_bits[gr][ch] = 126;
+
+            bits += max_bits[gr][ch];
+        }
+    }
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            if (bits > frameBits[cfg->vbr_max_bitrate_index] && bits > 0) {
+                max_bits[gr][ch] *= frameBits[cfg->vbr_max_bitrate_index];
+                max_bits[gr][ch] /= bits;
+            }
+            if (min_bits[gr][ch] > max_bits[gr][ch])
+                min_bits[gr][ch] = max_bits[gr][ch];
+
+        }               /* for ch */
+    }                   /* for gr */
+
+    return analog_silence;
+}
+
+static void
+bitpressure_strategy(lame_internal_flags const *gfc,
+                     FLOAT l3_xmin[2][2][SFBMAX], const int min_bits[2][2], int max_bits[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     gr, ch, sfb;
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            gr_info const *const gi = &gfc->l3_side.tt[gr][ch];
+            FLOAT  *pxmin = l3_xmin[gr][ch];
+            for (sfb = 0; sfb < gi->psy_lmax; sfb++)
+                *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_l / SBMAX_l;
+
+            if (gi->block_type == SHORT_TYPE) {
+                for (sfb = gi->sfb_smin; sfb < SBMAX_s; sfb++) {
+                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
+                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
+                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;
+                }
+            }
+            max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9 * max_bits[gr][ch]);
+        }
+    }
+}
+
+/************************************************************************
+ *
+ *      VBR_iteration_loop()
+ *
+ *  tries to find out how many bits are needed for each granule and channel
+ *  to get an acceptable quantization. An appropriate bitrate will then be
+ *  choosed for quantization.  rh 8/99
+ *
+ *  Robert Hegemann 2000-09-06 rewrite
+ *
+ ************************************************************************/
+
+void
+VBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                       const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+    FLOAT   l3_xmin[2][2][SFBMAX];
+
+    FLOAT   xrpow[576];
+    int     bands[2][2];
+    int     frameBits[15];
+    int     used_bits;
+    int     bits;
+    int     min_bits[2][2], max_bits[2][2];
+    int     mean_bits;
+    int     ch, gr, analog_silence;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+
+    analog_silence = VBR_old_prepare(gfc, pe, ms_ener_ratio, ratio,
+                                     l3_xmin, frameBits, min_bits, max_bits, bands);
+
+    /*---------------------------------*/
+    for (;;) {
+
+        /*  quantize granules with lowest possible number of bits
+         */
+
+        used_bits = 0;
+
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                int     ret;
+                gr_info *const cod_info = &l3_side->tt[gr][ch];
+
+                /*  init_outer_loop sets up cod_info, scalefac and xrpow
+                 */
+                ret = init_xrpow(gfc, cod_info, xrpow);
+                if (ret == 0 || max_bits[gr][ch] == 0) {
+                    /*  xr contains no energy
+                     *  l3_enc, our encoding data, will be quantized to zero
+                     */
+                    continue; /* with next channel */
+                }
+
+                VBR_encode_granule(gfc, cod_info, l3_xmin[gr][ch], xrpow,
+                                   ch, min_bits[gr][ch], max_bits[gr][ch]);
+
+                /*  do the 'substep shaping'
+                 */
+                if (gfc->sv_qnt.substep_shaping & 1) {
+                    trancate_smallspectrums(gfc, &l3_side->tt[gr][ch], l3_xmin[gr][ch], xrpow);
+                }
+
+                ret = cod_info->part2_3_length + cod_info->part2_length;
+                used_bits += ret;
+            }           /* for ch */
+        }               /* for gr */
+
+        /*  find lowest bitrate able to hold used bits
+         */
+        if (analog_silence && !cfg->enforce_min_bitrate)
+            /*  we detected analog silence and the user did not specify
+             *  any hard framesize limit, so start with smallest possible frame
+             */
+            eov->bitrate_index = 1;
+        else
+            eov->bitrate_index = cfg->vbr_min_bitrate_index;
+
+        for (; eov->bitrate_index < cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
+            if (used_bits <= frameBits[eov->bitrate_index])
+                break;
+        }
+        bits = ResvFrameBegin(gfc, &mean_bits);
+
+        if (used_bits <= bits)
+            break;
+
+        bitpressure_strategy(gfc, l3_xmin, (const int (*)[2])min_bits, max_bits);
+
+    }                   /* breaks adjusted */
+    /*--------------------------------------*/
+
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            iteration_finish_one(gfc, gr, ch);
+        }               /* for ch */
+    }                   /* for gr */
+    ResvFrameEnd(gfc, mean_bits);
+}
+
+
+
+static int
+VBR_new_prepare(lame_internal_flags * gfc,
+                const FLOAT pe[2][2], const III_psy_ratio ratio[2][2],
+                FLOAT l3_xmin[2][2][SFBMAX], int frameBits[16], int max_bits[2][2],
+                int* max_resv)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+
+    int     gr, ch;
+    int     analog_silence = 1;
+    int     avg, bits = 0;
+    int     maximum_framebits;
+
+    if (!cfg->free_format) {
+        eov->bitrate_index = cfg->vbr_max_bitrate_index;
+        (void) ResvFrameBegin(gfc, &avg);
+        *max_resv = gfc->sv_enc.ResvMax;
+
+        get_framebits(gfc, frameBits);
+        maximum_framebits = frameBits[cfg->vbr_max_bitrate_index];
+    }
+    else {
+        eov->bitrate_index = 0;
+        maximum_framebits = ResvFrameBegin(gfc, &avg);
+        frameBits[0] = maximum_framebits;
+        *max_resv = gfc->sv_enc.ResvMax;
+    }
+
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        (void) on_pe(gfc, pe, max_bits[gr], avg, gr, 0);
+        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+            ms_convert(&gfc->l3_side, gr);
+        }
+        for (ch = 0; ch < cfg->channels_out; ++ch) {
+            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
+
+            gfc->sv_qnt.masking_lower = pow(10.0, gfc->sv_qnt.mask_adjust * 0.1);
+
+            init_outer_loop(gfc, cod_info);
+            if (0 != calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]))
+                analog_silence = 0;
+
+            bits += max_bits[gr][ch];
+        }
+    }
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            if (bits > maximum_framebits && bits > 0) {
+                max_bits[gr][ch] *= maximum_framebits;
+                max_bits[gr][ch] /= bits;
+            }
+
+        }               /* for ch */
+    }                   /* for gr */
+    if (analog_silence) {
+        *max_resv = 0;
+    }
+    return analog_silence;
+}
+
+
+
+void
+VBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                       const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+    FLOAT   l3_xmin[2][2][SFBMAX];
+
+    FLOAT   xrpow[2][2][576];
+    int     frameBits[15];
+    int     used_bits;
+    int     max_bits[2][2];
+    int     ch, gr, analog_silence, pad;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+
+    const FLOAT (*const_l3_xmin)[2][SFBMAX] = (const FLOAT (*)[2][SFBMAX])l3_xmin;
+    const FLOAT (*const_xrpow)[2][576] = (const FLOAT (*)[2][576])xrpow;
+    const int (*const_max_bits)[2] = (const int (*)[2])max_bits;
+    
+    (void) ms_ener_ratio; /* not used */
+
+    memset(xrpow, 0, sizeof(xrpow));
+
+    analog_silence = VBR_new_prepare(gfc, pe, ratio, l3_xmin, frameBits, max_bits, &pad);
+
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            gr_info *const cod_info = &l3_side->tt[gr][ch];
+
+            /*  init_outer_loop sets up cod_info, scalefac and xrpow
+             */
+            if (0 == init_xrpow(gfc, cod_info, xrpow[gr][ch])) {
+                max_bits[gr][ch] = 0; /* silent granule needs no bits */
+            }
+        }               /* for ch */
+    }                   /* for gr */
+
+    /*  quantize granules with lowest possible number of bits
+     */
+
+    used_bits = VBR_encode_frame(gfc, const_xrpow, const_l3_xmin, const_max_bits);
+
+    if (!cfg->free_format) {
+        int     i, j;
+
+        /*  find lowest bitrate able to hold used bits
+         */
+        if (analog_silence && !cfg->enforce_min_bitrate) {
+            /*  we detected analog silence and the user did not specify
+             *  any hard framesize limit, so start with smallest possible frame
+             */
+            i = 1;
+        }
+        else {
+            i = cfg->vbr_min_bitrate_index;
+        }
+
+        for (; i < cfg->vbr_max_bitrate_index; i++) {
+            if (used_bits <= frameBits[i]) 
+                break;
+        }
+        if (i > cfg->vbr_max_bitrate_index) {
+            i = cfg->vbr_max_bitrate_index;
+        }
+        if (pad > 0) {
+            for (j = cfg->vbr_max_bitrate_index; j > i; --j) {
+                int const unused = frameBits[j] - used_bits;
+                if (unused <= pad) 
+                    break;
+            }
+            eov->bitrate_index = j;
+        }
+        else {
+            eov->bitrate_index = i;
+        }
+    }
+    else {
+#if 0
+        static int mmm = 0;
+        int     fff = getFramesize_kbps(gfc, used_bits);
+        int     hhh = getFramesize_kbps(gfc, MAX_BITS_PER_GRANULE * cfg->mode_gr);
+        if (mmm < fff)
+            mmm = fff;
+        printf("demand=%3d kbps  max=%3d kbps   limit=%3d kbps\n", fff, mmm, hhh);
+#endif
+        eov->bitrate_index = 0;
+    }
+    if (used_bits <= frameBits[eov->bitrate_index]) {
+        /* update Reservoire status */
+        int     mean_bits, fullframebits;
+        fullframebits = ResvFrameBegin(gfc, &mean_bits);
+        assert(used_bits <= fullframebits);
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                gr_info const *const cod_info = &l3_side->tt[gr][ch];
+                ResvAdjust(gfc, cod_info);
+            }
+        }
+        ResvFrameEnd(gfc, mean_bits);
+    }
+    else {
+        /* SHOULD NOT HAPPEN INTERNAL ERROR
+         */
+        ERRORF(gfc, "INTERNAL ERROR IN VBR NEW CODE, please send bug report\n");
+        exit(-1);
+    }
+}
+
+
+
+
+
+/********************************************************************
+ *
+ *  calc_target_bits()
+ *
+ *  calculates target bits for ABR encoding
+ *
+ *  mt 2000/05/31
+ *
+ ********************************************************************/
+
+static void
+calc_target_bits(lame_internal_flags * gfc,
+                 const FLOAT pe[2][2],
+                 FLOAT const ms_ener_ratio[2],
+                 int targ_bits[2][2], int *analog_silence_bits, int *max_frame_bits)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+    III_side_info_t const *const l3_side = &gfc->l3_side;
+    FLOAT   res_factor;
+    int     gr, ch, totbits, mean_bits;
+    int     framesize = 576 * cfg->mode_gr;
+
+    eov->bitrate_index = cfg->vbr_max_bitrate_index;
+    *max_frame_bits = ResvFrameBegin(gfc, &mean_bits);
+
+    eov->bitrate_index = 1;
+    mean_bits = getframebits(gfc) - cfg->sideinfo_len * 8;
+    *analog_silence_bits = mean_bits / (cfg->mode_gr * cfg->channels_out);
+
+    mean_bits = cfg->vbr_avg_bitrate_kbps * framesize * 1000;
+    if (gfc->sv_qnt.substep_shaping & 1)
+        mean_bits *= 1.09;
+    mean_bits /= cfg->samplerate_out;
+    mean_bits -= cfg->sideinfo_len * 8;
+    mean_bits /= (cfg->mode_gr * cfg->channels_out);
+
+    /*
+       res_factor is the percentage of the target bitrate that should
+       be used on average.  the remaining bits are added to the
+       bitreservoir and used for difficult to encode frames.
+
+       Since we are tracking the average bitrate, we should adjust
+       res_factor "on the fly", increasing it if the average bitrate
+       is greater than the requested bitrate, and decreasing it
+       otherwise.  Reasonable ranges are from .9 to 1.0
+
+       Until we get the above suggestion working, we use the following
+       tuning:
+       compression ratio    res_factor
+       5.5  (256kbps)         1.0      no need for bitreservoir
+       11   (128kbps)         .93      7% held for reservoir
+
+       with linear interpolation for other values.
+
+     */
+    res_factor = .93 + .07 * (11.0 - cfg->compression_ratio) / (11.0 - 5.5);
+    if (res_factor < .90)
+        res_factor = .90;
+    if (res_factor > 1.00)
+        res_factor = 1.00;
+
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        int     sum = 0;
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            targ_bits[gr][ch] = res_factor * mean_bits;
+
+            if (pe[gr][ch] > 700) {
+                int     add_bits = (pe[gr][ch] - 700) / 1.4;
+
+                gr_info const *const cod_info = &l3_side->tt[gr][ch];
+                targ_bits[gr][ch] = res_factor * mean_bits;
+
+                /* short blocks use a little extra, no matter what the pe */
+                if (cod_info->block_type == SHORT_TYPE) {
+                    if (add_bits < mean_bits / 2)
+                        add_bits = mean_bits / 2;
+                }
+                /* at most increase bits by 1.5*average */
+                if (add_bits > mean_bits * 3 / 2)
+                    add_bits = mean_bits * 3 / 2;
+                else if (add_bits < 0)
+                    add_bits = 0;
+
+                targ_bits[gr][ch] += add_bits;
+            }
+            if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL) {
+                targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
+            }
+            sum += targ_bits[gr][ch];
+        }               /* for ch */
+        if (sum > MAX_BITS_PER_GRANULE) {
+            for (ch = 0; ch < cfg->channels_out; ++ch) {
+                targ_bits[gr][ch] *= MAX_BITS_PER_GRANULE;
+                targ_bits[gr][ch] /= sum;
+            }
+        }
+    }                   /* for gr */
+
+    if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR)
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits * cfg->channels_out,
+                        MAX_BITS_PER_GRANULE);
+        }
+
+    /*  sum target bits
+     */
+    totbits = 0;
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL)
+                targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;
+            totbits += targ_bits[gr][ch];
+        }
+    }
+
+    /*  repartion target bits if needed
+     */
+    if (totbits > *max_frame_bits && totbits > 0) {
+        for (gr = 0; gr < cfg->mode_gr; gr++) {
+            for (ch = 0; ch < cfg->channels_out; ch++) {
+                targ_bits[gr][ch] *= *max_frame_bits;
+                targ_bits[gr][ch] /= totbits;
+            }
+        }
+    }
+}
+
+
+
+
+
+
+/********************************************************************
+ *
+ *  ABR_iteration_loop()
+ *
+ *  encode a frame with a disired average bitrate
+ *
+ *  mt 2000/05/31
+ *
+ ********************************************************************/
+
+void
+ABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                   const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncResult_t *const eov = &gfc->ov_enc;
+    FLOAT   l3_xmin[SFBMAX];
+    FLOAT   xrpow[576];
+    int     targ_bits[2][2];
+    int     mean_bits, max_frame_bits;
+    int     ch, gr, ath_over;
+    int     analog_silence_bits;
+    gr_info *cod_info;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+
+    mean_bits = 0;
+
+    calc_target_bits(gfc, pe, ms_ener_ratio, targ_bits, &analog_silence_bits, &max_frame_bits);
+
+    /*  encode granules
+     */
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+
+        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+            ms_convert(&gfc->l3_side, gr);
+        }
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            FLOAT   adjust, masking_lower_db;
+            cod_info = &l3_side->tt[gr][ch];
+
+            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
+                /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
+                adjust = 0;
+                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
+            }
+            else {
+                /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
+                adjust = 0;
+                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
+            }
+            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
+
+
+            /*  cod_info, scalefac and xrpow get initialized in init_outer_loop
+             */
+            init_outer_loop(gfc, cod_info);
+            if (init_xrpow(gfc, cod_info, xrpow)) {
+                /*  xr contains energy we will have to encode
+                 *  calculate the masking abilities
+                 *  find some good quantization in outer_loop
+                 */
+                ath_over = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
+                if (0 == ath_over) /* analog silence */
+                    targ_bits[gr][ch] = analog_silence_bits;
+
+                (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[gr][ch]);
+            }
+            iteration_finish_one(gfc, gr, ch);
+        }               /* ch */
+    }                   /* gr */
+
+    /*  find a bitrate which can refill the resevoir to positive size.
+     */
+    for (eov->bitrate_index = cfg->vbr_min_bitrate_index;
+         eov->bitrate_index <= cfg->vbr_max_bitrate_index; eov->bitrate_index++) {
+        if (ResvFrameBegin(gfc, &mean_bits) >= 0)
+            break;
+    }
+    assert(eov->bitrate_index <= cfg->vbr_max_bitrate_index);
+
+    ResvFrameEnd(gfc, mean_bits);
+}
+
+
+
+
+
+
+/************************************************************************
+ *
+ *      CBR_iteration_loop()
+ *
+ *  author/date??
+ *
+ *  encodes one frame of MP3 data with constant bitrate
+ *
+ ************************************************************************/
+
+void
+CBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                   const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    FLOAT   l3_xmin[SFBMAX];
+    FLOAT   xrpow[576];
+    int     targ_bits[2];
+    int     mean_bits, max_bits;
+    int     gr, ch;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+    gr_info *cod_info;
+
+    (void) ResvFrameBegin(gfc, &mean_bits);
+
+    /* quantize! */
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+
+        /*  calculate needed bits
+         */
+        max_bits = on_pe(gfc, pe, targ_bits, mean_bits, gr, gr);
+
+        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {
+            ms_convert(&gfc->l3_side, gr);
+            reduce_side(targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);
+        }
+
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            FLOAT   adjust, masking_lower_db;
+            cod_info = &l3_side->tt[gr][ch];
+
+            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */
+                /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */
+                adjust = 0;
+                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;
+            }
+            else {
+                /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */
+                adjust = 0;
+                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;
+            }
+            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);
+
+            /*  init_outer_loop sets up cod_info, scalefac and xrpow
+             */
+            init_outer_loop(gfc, cod_info);
+            if (init_xrpow(gfc, cod_info, xrpow)) {
+                /*  xr contains energy we will have to encode
+                 *  calculate the masking abilities
+                 *  find some good quantization in outer_loop
+                 */
+                (void) calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);
+                (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[ch]);
+            }
+
+            iteration_finish_one(gfc, gr, ch);
+            assert(cod_info->part2_3_length <= MAX_BITS_PER_CHANNEL);
+            assert(cod_info->part2_3_length <= targ_bits[ch]);
+        }               /* for ch */
+    }                   /* for gr */
+
+    ResvFrameEnd(gfc, mean_bits);
+}
diff --git a/lame/libmp3lame/quantize.h b/lame/libmp3lame/quantize.h
new file mode 100644 (file)
index 0000000..56edcc7
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * MP3 quantization
+ *
+ * Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_QUANTIZE_H
+#define LAME_QUANTIZE_H
+
+void    CBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                           const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);
+
+void    VBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                               const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);
+
+void    VBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                               const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);
+
+void    ABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],
+                           const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);
+
+
+#endif /* LAME_QUANTIZE_H */
diff --git a/lame/libmp3lame/quantize_pvt.c b/lame/libmp3lame/quantize_pvt.c
new file mode 100644 (file)
index 0000000..d8d6447
--- /dev/null
@@ -0,0 +1,1074 @@
+/*
+ *      quantize_pvt source file
+ *
+ *      Copyright (c) 1999-2002 Takehiro Tominaga
+ *      Copyright (c) 2000-2012 Robert Hegemann
+ *      Copyright (c) 2001 Naoki Shibata
+ *      Copyright (c) 2002-2005 Gabriel Bouvigne
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: quantize_pvt.c,v 1.175 2017/09/06 15:07:30 robert Exp $ */
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "quantize_pvt.h"
+#include "reservoir.h"
+#include "lame-analysis.h"
+#include <float.h>
+
+
+#define NSATHSCALE 100  /* Assuming dynamic range=96dB, this value should be 92 */
+
+/*
+  The following table is used to implement the scalefactor
+  partitioning for MPEG2 as described in section
+  2.4.3.2 of the IS. The indexing corresponds to the
+  way the tables are presented in the IS:
+
+  [table_number][row_in_table][column of nr_of_sfb]
+*/
+const int nr_of_sfb_block[6][3][4] = {
+    {
+     {6, 5, 5, 5},
+     {9, 9, 9, 9},
+     {6, 9, 9, 9}
+     },
+    {
+     {6, 5, 7, 3},
+     {9, 9, 12, 6},
+     {6, 9, 12, 6}
+     },
+    {
+     {11, 10, 0, 0},
+     {18, 18, 0, 0},
+     {15, 18, 0, 0}
+     },
+    {
+     {7, 7, 7, 0},
+     {12, 12, 12, 0},
+     {6, 15, 12, 0}
+     },
+    {
+     {6, 6, 6, 3},
+     {12, 9, 9, 6},
+     {6, 12, 9, 6}
+     },
+    {
+     {8, 8, 5, 0},
+     {15, 12, 9, 0},
+     {6, 18, 9, 0}
+     }
+};
+
+
+/* Table B.6: layer3 preemphasis */
+const int pretab[SBMAX_l] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0
+};
+
+/*
+  Here are MPEG1 Table B.8 and MPEG2 Table B.1
+  -- Layer III scalefactor bands. 
+  Index into this using a method such as:
+    idx  = fr_ps->header->sampling_frequency
+           + (fr_ps->header->version * 3)
+*/
+
+
+const scalefac_struct sfBandIndex[9] = {
+    {                   /* Table B.2.b: 22.05 kHz */
+     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,
+      522, 576},
+     {0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* Table B.2.c: 24 kHz */ /* docs: 332. mpg123(broken): 330 */
+     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464,
+      540, 576},
+     {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* Table B.2.a: 16 kHz */
+     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,
+      522, 576},
+     {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* Table B.8.b: 44.1 kHz */
+     {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418,
+      576},
+     {0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* Table B.8.c: 48 kHz */
+     {0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384,
+      576},
+     {0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* Table B.8.a: 32 kHz */
+     {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550,
+      576},
+     {0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* MPEG-2.5 11.025 kHz */
+     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,
+      522, 576},
+     {0 / 3, 12 / 3, 24 / 3, 36 / 3, 54 / 3, 78 / 3, 108 / 3, 144 / 3, 186 / 3, 240 / 3, 312 / 3,
+      402 / 3, 522 / 3, 576 / 3}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* MPEG-2.5 12 kHz */
+     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,
+      522, 576},
+     {0 / 3, 12 / 3, 24 / 3, 36 / 3, 54 / 3, 78 / 3, 108 / 3, 144 / 3, 186 / 3, 240 / 3, 312 / 3,
+      402 / 3, 522 / 3, 576 / 3}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     },
+    {                   /* MPEG-2.5 8 kHz */
+     {0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570,
+      572, 574, 576},
+     {0 / 3, 24 / 3, 48 / 3, 72 / 3, 108 / 3, 156 / 3, 216 / 3, 288 / 3, 372 / 3, 480 / 3, 486 / 3,
+      492 / 3, 498 / 3, 576 / 3}
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */
+     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */
+     }
+};
+
+
+/* FIXME: move global variables in some struct */
+
+FLOAT   pow20[Q_MAX + Q_MAX2 + 1];
+FLOAT   ipow20[Q_MAX];
+FLOAT   pow43[PRECALC_SIZE];
+/* initialized in first call to iteration_init */
+#ifdef TAKEHIRO_IEEE754_HACK
+FLOAT   adj43asm[PRECALC_SIZE];
+#else
+FLOAT   adj43[PRECALC_SIZE];
+#endif
+
+/* 
+compute the ATH for each scalefactor band 
+cd range:  0..96db
+
+Input:  3.3kHz signal  32767 amplitude  (3.3kHz is where ATH is smallest = -5db)
+longblocks:  sfb=12   en0/bw=-11db    max_en0 = 1.3db
+shortblocks: sfb=5           -9db              0db
+
+Input:  1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 (repeated)
+longblocks:  amp=1      sfb=12   en0/bw=-103 db      max_en0 = -92db
+            amp=32767   sfb=12           -12 db                 -1.4db 
+
+Input:  1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 (repeated)
+shortblocks: amp=1      sfb=5   en0/bw= -99                    -86 
+            amp=32767   sfb=5           -9  db                  4db 
+
+
+MAX energy of largest wave at 3.3kHz = 1db
+AVE energy of largest wave at 3.3kHz = -11db
+Let's take AVE:  -11db = maximum signal in sfb=12.  
+Dynamic range of CD: 96db.  Therefor energy of smallest audible wave 
+in sfb=12  = -11  - 96 = -107db = ATH at 3.3kHz.  
+
+ATH formula for this wave: -5db.  To adjust to LAME scaling, we need
+ATH = ATH_formula  - 103  (db)
+ATH = ATH * 2.5e-10      (ener)
+
+*/
+
+static  FLOAT
+ATHmdct(SessionConfig_t const *cfg, FLOAT f)
+{
+    FLOAT   ath;
+
+    ath = ATHformula(cfg, f);
+
+    if (cfg->ATHfixpoint > 0) {
+        ath -= cfg->ATHfixpoint;
+    }
+    else {
+        ath -= NSATHSCALE;
+    }
+    ath += cfg->ATH_offset_db;
+
+    /* modify the MDCT scaling for the ATH and convert to energy */
+    ath = powf(10.0f, ath * 0.1f);
+    return ath;
+}
+
+static void
+compute_ath(lame_internal_flags const* gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    FLOAT  *const ATH_l = gfc->ATH->l;
+    FLOAT  *const ATH_psfb21 = gfc->ATH->psfb21;
+    FLOAT  *const ATH_s = gfc->ATH->s;
+    FLOAT  *const ATH_psfb12 = gfc->ATH->psfb12;
+    int     sfb, i, start, end;
+    FLOAT   ATH_f;
+    FLOAT const samp_freq = cfg->samplerate_out;
+
+    for (sfb = 0; sfb < SBMAX_l; sfb++) {
+        start = gfc->scalefac_band.l[sfb];
+        end = gfc->scalefac_band.l[sfb + 1];
+        ATH_l[sfb] = FLOAT_MAX;
+        for (i = start; i < end; i++) {
+            FLOAT const freq = i * samp_freq / (2 * 576);
+            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */
+            ATH_l[sfb] = Min(ATH_l[sfb], ATH_f);
+        }
+    }
+
+    for (sfb = 0; sfb < PSFB21; sfb++) {
+        start = gfc->scalefac_band.psfb21[sfb];
+        end = gfc->scalefac_band.psfb21[sfb + 1];
+        ATH_psfb21[sfb] = FLOAT_MAX;
+        for (i = start; i < end; i++) {
+            FLOAT const freq = i * samp_freq / (2 * 576);
+            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */
+            ATH_psfb21[sfb] = Min(ATH_psfb21[sfb], ATH_f);
+        }
+    }
+
+    for (sfb = 0; sfb < SBMAX_s; sfb++) {
+        start = gfc->scalefac_band.s[sfb];
+        end = gfc->scalefac_band.s[sfb + 1];
+        ATH_s[sfb] = FLOAT_MAX;
+        for (i = start; i < end; i++) {
+            FLOAT const freq = i * samp_freq / (2 * 192);
+            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */
+            ATH_s[sfb] = Min(ATH_s[sfb], ATH_f);
+        }
+        ATH_s[sfb] *= (gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb]);
+    }
+
+    for (sfb = 0; sfb < PSFB12; sfb++) {
+        start = gfc->scalefac_band.psfb12[sfb];
+        end = gfc->scalefac_band.psfb12[sfb + 1];
+        ATH_psfb12[sfb] = FLOAT_MAX;
+        for (i = start; i < end; i++) {
+            FLOAT const freq = i * samp_freq / (2 * 192);
+            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */
+            ATH_psfb12[sfb] = Min(ATH_psfb12[sfb], ATH_f);
+        }
+        /*not sure about the following */
+        ATH_psfb12[sfb] *= (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]);
+    }
+
+
+    /*  no-ATH mode:
+     *  reduce ATH to -200 dB
+     */
+
+    if (cfg->noATH) {
+        for (sfb = 0; sfb < SBMAX_l; sfb++) {
+            ATH_l[sfb] = 1E-20;
+        }
+        for (sfb = 0; sfb < PSFB21; sfb++) {
+            ATH_psfb21[sfb] = 1E-20;
+        }
+        for (sfb = 0; sfb < SBMAX_s; sfb++) {
+            ATH_s[sfb] = 1E-20;
+        }
+        for (sfb = 0; sfb < PSFB12; sfb++) {
+            ATH_psfb12[sfb] = 1E-20;
+        }
+    }
+
+    /*  work in progress, don't rely on it too much
+     */
+    gfc->ATH->floor = 10. * log10(ATHmdct(cfg, -1.));
+
+    /*
+       {   FLOAT g=10000, t=1e30, x;
+       for ( f = 100; f < 10000; f++ ) {
+       x = ATHmdct( cfg, f );
+       if ( t > x ) t = x, g = f;
+       }
+       printf("min=%g\n", g);
+       } */
+}
+
+
+static float const payload_long[2][4] = 
+{ {-0.000f, -0.000f, -0.000f, +0.000f}
+, {-0.500f, -0.250f, -0.025f, +0.500f}
+};
+static float const payload_short[2][4] = 
+{ {-0.000f, -0.000f, -0.000f, +0.000f}
+, {-2.000f, -1.000f, -0.050f, +0.500f}
+};
+
+/************************************************************************/
+/*  initialization for iteration_loop */
+/************************************************************************/
+void
+iteration_init(lame_internal_flags * gfc)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+    FLOAT   adjust, db;
+    int     i, sel;
+
+    if (gfc->iteration_init_init == 0) {
+        gfc->iteration_init_init = 1;
+
+        l3_side->main_data_begin = 0;
+        compute_ath(gfc);
+
+        pow43[0] = 0.0;
+        for (i = 1; i < PRECALC_SIZE; i++)
+            pow43[i] = pow((FLOAT) i, 4.0 / 3.0);
+
+#ifdef TAKEHIRO_IEEE754_HACK
+        adj43asm[0] = 0.0;
+        for (i = 1; i < PRECALC_SIZE; i++)
+            adj43asm[i] = i - 0.5 - pow(0.5 * (pow43[i - 1] + pow43[i]), 0.75);
+#else
+        for (i = 0; i < PRECALC_SIZE - 1; i++)
+            adj43[i] = (i + 1) - pow(0.5 * (pow43[i] + pow43[i + 1]), 0.75);
+        adj43[i] = 0.5;
+#endif
+        for (i = 0; i < Q_MAX; i++)
+            ipow20[i] = pow(2.0, (double) (i - 210) * -0.1875);
+        for (i = 0; i <= Q_MAX + Q_MAX2; i++)
+            pow20[i] = pow(2.0, (double) (i - 210 - Q_MAX2) * 0.25);
+
+        huffman_init(gfc);
+        init_xrpow_core_init(gfc);
+
+        sel = 1;/* RH: all modes like vbr-new (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) ? 1 : 0;*/
+
+        /* long */
+        db = cfg->adjust_bass_db + payload_long[sel][0];
+        adjust = powf(10.f, db * 0.1f);
+        for (i = 0; i <= 6; ++i) {
+            gfc->sv_qnt.longfact[i] = adjust;
+        }
+        db = cfg->adjust_alto_db + payload_long[sel][1];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i <= 13; ++i) {
+            gfc->sv_qnt.longfact[i] = adjust;
+        }
+        db = cfg->adjust_treble_db + payload_long[sel][2];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i <= 20; ++i) {
+            gfc->sv_qnt.longfact[i] = adjust;
+        }
+        db = cfg->adjust_sfb21_db + payload_long[sel][3];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i < SBMAX_l; ++i) {
+            gfc->sv_qnt.longfact[i] = adjust;
+        }
+
+        /* short */
+        db = cfg->adjust_bass_db + payload_short[sel][0];
+        adjust = powf(10.f, db * 0.1f);
+        for (i = 0; i <= 2; ++i) {
+            gfc->sv_qnt.shortfact[i] = adjust;
+        }
+        db = cfg->adjust_alto_db + payload_short[sel][1];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i <= 6; ++i) {
+            gfc->sv_qnt.shortfact[i] = adjust;
+        }
+        db = cfg->adjust_treble_db + payload_short[sel][2];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i <= 11; ++i) {
+            gfc->sv_qnt.shortfact[i] = adjust;
+        }
+        db = cfg->adjust_sfb21_db + payload_short[sel][3];
+        adjust = powf(10.f, db * 0.1f);
+        for (; i < SBMAX_s; ++i) {
+            gfc->sv_qnt.shortfact[i] = adjust;
+        }
+    }
+}
+
+
+
+
+
+/************************************************************************
+ * allocate bits among 2 channels based on PE
+ * mt 6/99
+ * bugfixes rh 8/01: often allocated more than the allowed 4095 bits
+ ************************************************************************/
+int
+on_pe(lame_internal_flags * gfc, const FLOAT pe[][2], int targ_bits[2], int mean_bits, int gr, int cbr)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     extra_bits = 0, tbits, bits;
+    int     add_bits[2] = {0, 0};
+    int     max_bits;        /* maximum allowed bits for this granule */
+    int     ch;
+
+    /* allocate targ_bits for granule */
+    ResvMaxBits(gfc, mean_bits, &tbits, &extra_bits, cbr);
+    max_bits = tbits + extra_bits;
+    if (max_bits > MAX_BITS_PER_GRANULE) /* hard limit per granule */
+        max_bits = MAX_BITS_PER_GRANULE;
+
+    for (bits = 0, ch = 0; ch < cfg->channels_out; ++ch) {
+        /******************************************************************
+         * allocate bits for each channel 
+         ******************************************************************/
+        targ_bits[ch] = Min(MAX_BITS_PER_CHANNEL, tbits / cfg->channels_out);
+
+        add_bits[ch] = targ_bits[ch] * pe[gr][ch] / 700.0 - targ_bits[ch];
+
+        /* at most increase bits by 1.5*average */
+        if (add_bits[ch] > mean_bits * 3 / 4)
+            add_bits[ch] = mean_bits * 3 / 4;
+        if (add_bits[ch] < 0)
+            add_bits[ch] = 0;
+
+        if (add_bits[ch] + targ_bits[ch] > MAX_BITS_PER_CHANNEL)
+            add_bits[ch] = Max(0, MAX_BITS_PER_CHANNEL - targ_bits[ch]);
+
+        bits += add_bits[ch];
+    }
+    if (bits > extra_bits && bits > 0) {
+        for (ch = 0; ch < cfg->channels_out; ++ch) {
+            add_bits[ch] = extra_bits * add_bits[ch] / bits;
+        }
+    }
+
+    for (ch = 0; ch < cfg->channels_out; ++ch) {
+        targ_bits[ch] += add_bits[ch];
+        extra_bits -= add_bits[ch];
+    }
+
+    for (bits = 0, ch = 0; ch < cfg->channels_out; ++ch) {
+        bits += targ_bits[ch];
+    }
+    if (bits > MAX_BITS_PER_GRANULE) {
+        int     sum = 0;
+        for (ch = 0; ch < cfg->channels_out; ++ch) {
+            targ_bits[ch] *= MAX_BITS_PER_GRANULE;
+            targ_bits[ch] /= bits;
+            sum += targ_bits[ch];
+        }
+        assert(sum <= MAX_BITS_PER_GRANULE);
+    }
+
+    return max_bits;
+}
+
+
+
+
+void
+reduce_side(int targ_bits[2], FLOAT ms_ener_ratio, int mean_bits, int max_bits)
+{
+    int     move_bits;
+    FLOAT   fac;
+
+    assert(max_bits <= MAX_BITS_PER_GRANULE);
+    assert(targ_bits[0] + targ_bits[1] <= MAX_BITS_PER_GRANULE);
+
+    /*  ms_ener_ratio = 0:  allocate 66/33  mid/side  fac=.33  
+     *  ms_ener_ratio =.5:  allocate 50/50 mid/side   fac= 0 */
+    /* 75/25 split is fac=.5 */
+    /* float fac = .50*(.5-ms_ener_ratio[gr])/.5; */
+    fac = .33 * (.5 - ms_ener_ratio) / .5;
+    if (fac < 0)
+        fac = 0;
+    if (fac > .5)
+        fac = .5;
+
+    /* number of bits to move from side channel to mid channel */
+    /*    move_bits = fac*targ_bits[1];  */
+    move_bits = fac * .5 * (targ_bits[0] + targ_bits[1]);
+
+    if (move_bits > MAX_BITS_PER_CHANNEL - targ_bits[0]) {
+        move_bits = MAX_BITS_PER_CHANNEL - targ_bits[0];
+    }
+    if (move_bits < 0)
+        move_bits = 0;
+
+    if (targ_bits[1] >= 125) {
+        /* dont reduce side channel below 125 bits */
+        if (targ_bits[1] - move_bits > 125) {
+
+            /* if mid channel already has 2x more than average, dont bother */
+            /* mean_bits = bits per granule (for both channels) */
+            if (targ_bits[0] < mean_bits)
+                targ_bits[0] += move_bits;
+            targ_bits[1] -= move_bits;
+        }
+        else {
+            targ_bits[0] += targ_bits[1] - 125;
+            targ_bits[1] = 125;
+        }
+    }
+
+    move_bits = targ_bits[0] + targ_bits[1];
+    if (move_bits > max_bits) {
+        targ_bits[0] = (max_bits * targ_bits[0]) / move_bits;
+        targ_bits[1] = (max_bits * targ_bits[1]) / move_bits;
+    }
+    assert(targ_bits[0] <= MAX_BITS_PER_CHANNEL);
+    assert(targ_bits[1] <= MAX_BITS_PER_CHANNEL);
+    assert(targ_bits[0] + targ_bits[1] <= MAX_BITS_PER_GRANULE);
+}
+
+
+/**
+ *  Robert Hegemann 2001-04-27:
+ *  this adjusts the ATH, keeping the original noise floor
+ *  affects the higher frequencies more than the lower ones
+ */
+
+FLOAT
+athAdjust(FLOAT a, FLOAT x, FLOAT athFloor, float ATHfixpoint)
+{
+    /*  work in progress
+     */
+    FLOAT const o = 90.30873362f;
+    FLOAT const p = (ATHfixpoint < 1.f) ? 94.82444863f : ATHfixpoint;
+    FLOAT   u = FAST_LOG10_X(x, 10.0f);
+    FLOAT const v = a * a;
+    FLOAT   w = 0.0f;
+    u -= athFloor;      /* undo scaling */
+    if (v > 1E-20f)
+        w = 1.f + FAST_LOG10_X(v, 10.0f / o);
+    if (w < 0)
+        w = 0.f;
+    u *= w;
+    u += athFloor + o - p; /* redo scaling */
+
+    return powf(10.f, 0.1f * u);
+}
+
+
+
+/*************************************************************************/
+/*            calc_xmin                                                  */
+/*************************************************************************/
+
+/*
+  Calculate the allowed distortion for each scalefactor band,
+  as determined by the psychoacoustic model.
+  xmin(sb) = ratio(sb) * en(sb) / bw(sb)
+
+  returns number of sfb's with energy > ATH
+*/
+
+int
+calc_xmin(lame_internal_flags const *gfc,
+          III_psy_ratio const *const ratio, gr_info * const cod_info, FLOAT * pxmin)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     sfb, gsfb, j = 0, ath_over = 0, k;
+    ATH_t const *const ATH = gfc->ATH;
+    const FLOAT *const xr = cod_info->xr;
+    int     max_nonzero;
+
+    for (gsfb = 0; gsfb < cod_info->psy_lmax; gsfb++) {
+        FLOAT   en0, xmin;
+        FLOAT   rh1, rh2, rh3;
+        int     width, l;
+
+        xmin = athAdjust(ATH->adjust_factor, ATH->l[gsfb], ATH->floor, cfg->ATHfixpoint);
+        xmin *= gfc->sv_qnt.longfact[gsfb];
+
+        width = cod_info->width[gsfb];
+        rh1 = xmin / width;
+#ifdef DBL_EPSILON
+        rh2 = DBL_EPSILON;
+#else
+        rh2 = 2.2204460492503131e-016;
+#endif
+        en0 = 0.0;
+        for (l = 0; l < width; ++l) {
+            FLOAT const xa = xr[j++];
+            FLOAT const x2 = xa * xa;
+            en0 += x2;
+            rh2 += (x2 < rh1) ? x2 : rh1;
+        }
+        if (en0 > xmin)
+            ath_over++;
+
+        if (en0 < xmin) {
+            rh3 = en0;
+        }
+        else if (rh2 < xmin) {
+            rh3 = xmin;
+        }
+        else {
+            rh3 = rh2;
+        }
+        xmin = rh3;
+        {
+            FLOAT const e = ratio->en.l[gsfb];
+            if (e > 1e-12f) {
+                FLOAT   x;
+                x = en0 * ratio->thm.l[gsfb] / e;
+                x *= gfc->sv_qnt.longfact[gsfb];
+                if (xmin < x)
+                    xmin = x;
+            }
+        }
+        xmin = Max(xmin, DBL_EPSILON);
+        cod_info->energy_above_cutoff[gsfb] = (en0 > xmin+1e-14f) ? 1 : 0;
+        *pxmin++ = xmin;
+    }                   /* end of long block loop */
+
+
+
+
+    /*use this function to determine the highest non-zero coeff */
+    max_nonzero = 0;
+    for (k = 575; k > 0; --k) {
+        if (fabs(xr[k]) > 1e-12f) {
+            max_nonzero = k;
+            break;
+        }
+    }
+    if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT */
+        max_nonzero |= 1; /* only odd numbers */
+    }
+    else {
+        max_nonzero /= 6; /* 3 short blocks */
+        max_nonzero *= 6;
+        max_nonzero += 5;
+    }
+
+    if (gfc->sv_qnt.sfb21_extra == 0 && cfg->samplerate_out < 44000) {
+      int const sfb_l = (cfg->samplerate_out <= 8000) ? 17 : 21;
+      int const sfb_s = (cfg->samplerate_out <= 8000) ?  9 : 12;
+      int   limit = 575;
+      if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT */
+          limit = gfc->scalefac_band.l[sfb_l]-1;
+      }
+      else {
+          limit = 3*gfc->scalefac_band.s[sfb_s]-1;
+      }
+      if (max_nonzero > limit) {
+          max_nonzero = limit;
+      }
+    }
+    cod_info->max_nonzero_coeff = max_nonzero;
+
+
+
+    for (sfb = cod_info->sfb_smin; gsfb < cod_info->psymax; sfb++, gsfb += 3) {
+        int     width, b, l;
+        FLOAT   tmpATH;
+
+        tmpATH = athAdjust(ATH->adjust_factor, ATH->s[sfb], ATH->floor, cfg->ATHfixpoint);
+        tmpATH *= gfc->sv_qnt.shortfact[sfb];
+        
+        width = cod_info->width[gsfb];
+        for (b = 0; b < 3; b++) {
+            FLOAT   en0 = 0.0, xmin = tmpATH;
+            FLOAT   rh1, rh2, rh3;
+
+            rh1 = tmpATH / width;
+#ifdef DBL_EPSILON
+            rh2 = DBL_EPSILON;
+#else
+            rh2 = 2.2204460492503131e-016;
+#endif
+            for (l = 0; l < width; ++l) {
+                FLOAT const xa = xr[j++];
+                FLOAT const x2 = xa * xa;
+                en0 += x2;
+                rh2 += (x2 < rh1) ? x2 : rh1;
+            }
+            if (en0 > tmpATH)
+                ath_over++;
+            
+            if (en0 < tmpATH) {
+                rh3 = en0;
+            }
+            else if (rh2 < tmpATH) {
+                rh3 = tmpATH;
+            }
+            else {
+                rh3 = rh2;
+            }
+            xmin = rh3;
+            {
+                FLOAT const e = ratio->en.s[sfb][b];
+                if (e > 1e-12f) {
+                    FLOAT   x;
+                    x = en0 * ratio->thm.s[sfb][b] / e;
+                    x *= gfc->sv_qnt.shortfact[sfb];
+                    if (xmin < x)
+                        xmin = x;
+                }
+            }
+            xmin = Max(xmin, DBL_EPSILON);
+            cod_info->energy_above_cutoff[gsfb+b] = (en0 > xmin+1e-14f) ? 1 : 0;
+            *pxmin++ = xmin;
+        }               /* b */
+        if (cfg->use_temporal_masking_effect) {
+            if (pxmin[-3] > pxmin[-3 + 1])
+                pxmin[-3 + 1] += (pxmin[-3] - pxmin[-3 + 1]) * gfc->cd_psy->decay;
+            if (pxmin[-3 + 1] > pxmin[-3 + 2])
+                pxmin[-3 + 2] += (pxmin[-3 + 1] - pxmin[-3 + 2]) * gfc->cd_psy->decay;
+        }
+    }                   /* end of short block sfb loop */
+
+    return ath_over;
+}
+
+
+static  FLOAT
+calc_noise_core_c(const gr_info * const cod_info, int *startline, int l, FLOAT step)
+{
+    FLOAT   noise = 0;
+    int     j = *startline;
+    const int *const ix = cod_info->l3_enc;
+
+    if (j > cod_info->count1) {
+        while (l--) {
+            FLOAT   temp;
+            temp = cod_info->xr[j];
+            j++;
+            noise += temp * temp;
+            temp = cod_info->xr[j];
+            j++;
+            noise += temp * temp;
+        }
+    }
+    else if (j > cod_info->big_values) {
+        FLOAT   ix01[2];
+        ix01[0] = 0;
+        ix01[1] = step;
+        while (l--) {
+            FLOAT   temp;
+            temp = fabs(cod_info->xr[j]) - ix01[ix[j]];
+            j++;
+            noise += temp * temp;
+            temp = fabs(cod_info->xr[j]) - ix01[ix[j]];
+            j++;
+            noise += temp * temp;
+        }
+    }
+    else {
+        while (l--) {
+            FLOAT   temp;
+            temp = fabs(cod_info->xr[j]) - pow43[ix[j]] * step;
+            j++;
+            noise += temp * temp;
+            temp = fabs(cod_info->xr[j]) - pow43[ix[j]] * step;
+            j++;
+            noise += temp * temp;
+        }
+    }
+
+    *startline = j;
+    return noise;
+}
+
+
+/*************************************************************************/
+/*            calc_noise                                                 */
+/*************************************************************************/
+
+/* -oo dB  =>  -1.00 */
+/* - 6 dB  =>  -0.97 */
+/* - 3 dB  =>  -0.80 */
+/* - 2 dB  =>  -0.64 */
+/* - 1 dB  =>  -0.38 */
+/*   0 dB  =>   0.00 */
+/* + 1 dB  =>  +0.49 */
+/* + 2 dB  =>  +1.06 */
+/* + 3 dB  =>  +1.68 */
+/* + 6 dB  =>  +3.69 */
+/* +10 dB  =>  +6.45 */
+
+int
+calc_noise(gr_info const *const cod_info,
+           FLOAT const *l3_xmin,
+           FLOAT * distort, calc_noise_result * const res, calc_noise_data * prev_noise)
+{
+    int     sfb, l, over = 0;
+    FLOAT   over_noise_db = 0;
+    FLOAT   tot_noise_db = 0; /*    0 dB relative to masking */
+    FLOAT   max_noise = -20.0; /* -200 dB relative to masking */
+    int     j = 0;
+    const int *scalefac = cod_info->scalefac;
+
+    res->over_SSD = 0;
+
+
+    for (sfb = 0; sfb < cod_info->psymax; sfb++) {
+        int const s =
+            cod_info->global_gain - (((*scalefac++) + (cod_info->preflag ? pretab[sfb] : 0))
+                                     << (cod_info->scalefac_scale + 1))
+            - cod_info->subblock_gain[cod_info->window[sfb]] * 8;
+        FLOAT const r_l3_xmin = 1.f / *l3_xmin++;
+        FLOAT   distort_ = 0.0f;
+        FLOAT   noise = 0.0f;
+
+        if (prev_noise && (prev_noise->step[sfb] == s)) {
+
+            /* use previously computed values */
+            j += cod_info->width[sfb];
+            distort_ = r_l3_xmin * prev_noise->noise[sfb];
+
+            noise = prev_noise->noise_log[sfb];
+
+        }
+        else {
+            FLOAT const step = POW20(s);
+            l = cod_info->width[sfb] >> 1;
+
+            if ((j + cod_info->width[sfb]) > cod_info->max_nonzero_coeff) {
+                int     usefullsize;
+                usefullsize = cod_info->max_nonzero_coeff - j + 1;
+
+                if (usefullsize > 0)
+                    l = usefullsize >> 1;
+                else
+                    l = 0;
+            }
+
+            noise = calc_noise_core_c(cod_info, &j, l, step);
+
+
+            if (prev_noise) {
+                /* save noise values */
+                prev_noise->step[sfb] = s;
+                prev_noise->noise[sfb] = noise;
+            }
+
+            distort_ = r_l3_xmin * noise;
+
+            /* multiplying here is adding in dB, but can overflow */
+            noise = FAST_LOG10(Max(distort_, 1E-20f));
+
+            if (prev_noise) {
+                /* save noise values */
+                prev_noise->noise_log[sfb] = noise;
+            }
+        }
+        *distort++ = distort_;
+
+        if (prev_noise) {
+            /* save noise values */
+            prev_noise->global_gain = cod_info->global_gain;;
+        }
+
+
+        /*tot_noise *= Max(noise, 1E-20); */
+        tot_noise_db += noise;
+
+        if (noise > 0.0) {
+            int     tmp;
+
+            tmp = Max((int) (noise * 10 + .5), 1);
+            res->over_SSD += tmp * tmp;
+
+            over++;
+            /* multiplying here is adding in dB -but can overflow */
+            /*over_noise *= noise; */
+            over_noise_db += noise;
+        }
+        max_noise = Max(max_noise, noise);
+
+    }
+
+    res->over_count = over;
+    res->tot_noise = tot_noise_db;
+    res->over_noise = over_noise_db;
+    res->max_noise = max_noise;
+
+    return over;
+}
+
+
+
+
+
+
+
+
+/************************************************************************
+ *
+ *  set_pinfo()
+ *
+ *  updates plotting data    
+ *
+ *  Mark Taylor 2000-??-??                
+ *
+ *  Robert Hegemann: moved noise/distortion calc into it
+ *
+ ************************************************************************/
+
+static void
+set_pinfo(lame_internal_flags const *gfc,
+          gr_info * const cod_info, const III_psy_ratio * const ratio, const int gr, const int ch)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     sfb, sfb2;
+    int     j, i, l, start, end, bw;
+    FLOAT   en0, en1;
+    FLOAT const ifqstep = (cod_info->scalefac_scale == 0) ? .5 : 1.0;
+    int const *const scalefac = cod_info->scalefac;
+
+    FLOAT   l3_xmin[SFBMAX], xfsf[SFBMAX];
+    calc_noise_result noise;
+
+    (void) calc_xmin(gfc, ratio, cod_info, l3_xmin);
+    (void) calc_noise(cod_info, l3_xmin, xfsf, &noise, 0);
+
+    j = 0;
+    sfb2 = cod_info->sfb_lmax;
+    if (cod_info->block_type != SHORT_TYPE && !cod_info->mixed_block_flag)
+        sfb2 = 22;
+    for (sfb = 0; sfb < sfb2; sfb++) {
+        start = gfc->scalefac_band.l[sfb];
+        end = gfc->scalefac_band.l[sfb + 1];
+        bw = end - start;
+        for (en0 = 0.0; j < end; j++)
+            en0 += cod_info->xr[j] * cod_info->xr[j];
+        en0 /= bw;
+        /* convert to MDCT units */
+        en1 = 1e15;     /* scaling so it shows up on FFT plot */
+        gfc->pinfo->en[gr][ch][sfb] = en1 * en0;
+        gfc->pinfo->xfsf[gr][ch][sfb] = en1 * l3_xmin[sfb] * xfsf[sfb] / bw;
+
+        if (ratio->en.l[sfb] > 0 && !cfg->ATHonly)
+            en0 = en0 / ratio->en.l[sfb];
+        else
+            en0 = 0.0;
+
+        gfc->pinfo->thr[gr][ch][sfb] = en1 * Max(en0 * ratio->thm.l[sfb], gfc->ATH->l[sfb]);
+
+        /* there is no scalefactor bands >= SBPSY_l */
+        gfc->pinfo->LAMEsfb[gr][ch][sfb] = 0;
+        if (cod_info->preflag && sfb >= 11)
+            gfc->pinfo->LAMEsfb[gr][ch][sfb] = -ifqstep * pretab[sfb];
+
+        if (sfb < SBPSY_l) {
+            assert(scalefac[sfb] >= 0); /* scfsi should be decoded by caller side */
+            gfc->pinfo->LAMEsfb[gr][ch][sfb] -= ifqstep * scalefac[sfb];
+        }
+    }                   /* for sfb */
+
+    if (cod_info->block_type == SHORT_TYPE) {
+        sfb2 = sfb;
+        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {
+            start = gfc->scalefac_band.s[sfb];
+            end = gfc->scalefac_band.s[sfb + 1];
+            bw = end - start;
+            for (i = 0; i < 3; i++) {
+                for (en0 = 0.0, l = start; l < end; l++) {
+                    en0 += cod_info->xr[j] * cod_info->xr[j];
+                    j++;
+                }
+                en0 = Max(en0 / bw, 1e-20);
+                /* convert to MDCT units */
+                en1 = 1e15; /* scaling so it shows up on FFT plot */
+
+                gfc->pinfo->en_s[gr][ch][3 * sfb + i] = en1 * en0;
+                gfc->pinfo->xfsf_s[gr][ch][3 * sfb + i] = en1 * l3_xmin[sfb2] * xfsf[sfb2] / bw;
+                if (ratio->en.s[sfb][i] > 0)
+                    en0 = en0 / ratio->en.s[sfb][i];
+                else
+                    en0 = 0.0;
+                if (cfg->ATHonly || cfg->ATHshort)
+                    en0 = 0;
+
+                gfc->pinfo->thr_s[gr][ch][3 * sfb + i] =
+                    en1 * Max(en0 * ratio->thm.s[sfb][i], gfc->ATH->s[sfb]);
+
+                /* there is no scalefactor bands >= SBPSY_s */
+                gfc->pinfo->LAMEsfb_s[gr][ch][3 * sfb + i]
+                    = -2.0 * cod_info->subblock_gain[i];
+                if (sfb < SBPSY_s) {
+                    gfc->pinfo->LAMEsfb_s[gr][ch][3 * sfb + i] -= ifqstep * scalefac[sfb2];
+                }
+                sfb2++;
+            }
+        }
+    }                   /* block type short */
+    gfc->pinfo->LAMEqss[gr][ch] = cod_info->global_gain;
+    gfc->pinfo->LAMEmainbits[gr][ch] = cod_info->part2_3_length + cod_info->part2_length;
+    gfc->pinfo->LAMEsfbits[gr][ch] = cod_info->part2_length;
+
+    gfc->pinfo->over[gr][ch] = noise.over_count;
+    gfc->pinfo->max_noise[gr][ch] = noise.max_noise * 10.0;
+    gfc->pinfo->over_noise[gr][ch] = noise.over_noise * 10.0;
+    gfc->pinfo->tot_noise[gr][ch] = noise.tot_noise * 10.0;
+    gfc->pinfo->over_SSD[gr][ch] = noise.over_SSD;
+}
+
+
+/************************************************************************
+ *
+ *  set_frame_pinfo()
+ *
+ *  updates plotting data for a whole frame  
+ *
+ *  Robert Hegemann 2000-10-21                          
+ *
+ ************************************************************************/
+
+void
+set_frame_pinfo(lame_internal_flags * gfc, const III_psy_ratio ratio[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     ch;
+    int     gr;
+
+    /* for every granule and channel patch l3_enc and set info
+     */
+    for (gr = 0; gr < cfg->mode_gr; gr++) {
+        for (ch = 0; ch < cfg->channels_out; ch++) {
+            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
+            int     scalefac_sav[SFBMAX];
+            memcpy(scalefac_sav, cod_info->scalefac, sizeof(scalefac_sav));
+
+            /* reconstruct the scalefactors in case SCFSI was used 
+             */
+            if (gr == 1) {
+                int     sfb;
+                for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {
+                    if (cod_info->scalefac[sfb] < 0) /* scfsi */
+                        cod_info->scalefac[sfb] = gfc->l3_side.tt[0][ch].scalefac[sfb];
+                }
+            }
+
+            set_pinfo(gfc, cod_info, &ratio[gr][ch], gr, ch);
+            memcpy(cod_info->scalefac, scalefac_sav, sizeof(scalefac_sav));
+        }               /* for ch */
+    }                   /* for gr */
+}
diff --git a/lame/libmp3lame/quantize_pvt.h b/lame/libmp3lame/quantize_pvt.h
new file mode 100644 (file)
index 0000000..b8333e7
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ *     quantize_pvt include file
+ *
+ *     Copyright (c) 1999 Takehiro TOMINAGA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_QUANTIZE_PVT_H
+#define LAME_QUANTIZE_PVT_H
+
+#define IXMAX_VAL 8206  /* ix always <= 8191+15.    see count_bits() */
+
+/* buggy Winamp decoder cannot handle values > 8191 */
+/* #define IXMAX_VAL 8191 */
+
+#define PRECALC_SIZE (IXMAX_VAL+2)
+
+
+extern const int nr_of_sfb_block[6][3][4];
+extern const int pretab[SBMAX_l];
+extern const int slen1_tab[16];
+extern const int slen2_tab[16];
+
+extern const scalefac_struct sfBandIndex[9];
+
+extern FLOAT pow43[PRECALC_SIZE];
+#ifdef TAKEHIRO_IEEE754_HACK
+extern FLOAT adj43asm[PRECALC_SIZE];
+#else
+extern FLOAT adj43[PRECALC_SIZE];
+#endif
+
+#define Q_MAX (256+1)
+#define Q_MAX2 116      /* minimum possible number of
+                           -cod_info->global_gain
+                           + ((scalefac[] + (cod_info->preflag ? pretab[sfb] : 0))
+                           << (cod_info->scalefac_scale + 1))
+                           + cod_info->subblock_gain[cod_info->window[sfb]] * 8;
+
+                           for long block, 0+((15+3)<<2) = 18*4 = 72
+                           for short block, 0+(15<<2)+7*8 = 15*4+56 = 116
+                         */
+
+extern FLOAT pow20[Q_MAX + Q_MAX2 + 1];
+extern FLOAT ipow20[Q_MAX];
+
+typedef struct calc_noise_result_t {
+    FLOAT   over_noise;      /* sum of quantization noise > masking */
+    FLOAT   tot_noise;       /* sum of all quantization noise */
+    FLOAT   max_noise;       /* max quantization noise */
+    int     over_count;      /* number of quantization noise > masking */
+    int     over_SSD;        /* SSD-like cost of distorted bands */
+    int     bits;
+} calc_noise_result;
+
+
+/**
+* allows re-use of previously
+* computed noise values
+*/
+typedef struct calc_noise_data_t {
+    int     global_gain;
+    int     sfb_count1;
+    int     step[39];
+    FLOAT   noise[39];
+    FLOAT   noise_log[39];
+} calc_noise_data;
+
+
+int     on_pe(lame_internal_flags * gfc, const FLOAT pe[2][2],
+              int targ_bits[2], int mean_bits, int gr, int cbr);
+
+void    reduce_side(int targ_bits[2], FLOAT ms_ener_ratio, int mean_bits, int max_bits);
+
+
+void    iteration_init(lame_internal_flags * gfc);
+
+
+int     calc_xmin(lame_internal_flags const *gfc,
+                  III_psy_ratio const *const ratio, gr_info * const cod_info, FLOAT * l3_xmin);
+
+int     calc_noise(const gr_info * const cod_info,
+                   const FLOAT * l3_xmin,
+                   FLOAT * distort, calc_noise_result * const res, calc_noise_data * prev_noise);
+
+void    set_frame_pinfo(lame_internal_flags * gfc, const III_psy_ratio ratio[2][2]);
+
+
+
+
+/* takehiro.c */
+
+int     count_bits(lame_internal_flags const *const gfc, const FLOAT * const xr,
+                   gr_info * const cod_info, calc_noise_data * prev_noise);
+int     noquant_count_bits(lame_internal_flags const *const gfc,
+                           gr_info * const cod_info, calc_noise_data * prev_noise);
+
+
+void    best_huffman_divide(const lame_internal_flags * const gfc, gr_info * const cod_info);
+
+void    best_scalefac_store(const lame_internal_flags * gfc, const int gr, const int ch,
+                            III_side_info_t * const l3_side);
+
+int     scale_bitcount(const lame_internal_flags * gfc, gr_info * cod_info);
+
+void    huffman_init(lame_internal_flags * const gfc);
+
+void    init_xrpow_core_init(lame_internal_flags * const gfc);
+
+FLOAT   athAdjust(FLOAT a, FLOAT x, FLOAT athFloor, float ATHfixpoint);
+
+#define LARGE_BITS 100000
+
+#endif /* LAME_QUANTIZE_PVT_H */
diff --git a/lame/libmp3lame/reservoir.c b/lame/libmp3lame/reservoir.c
new file mode 100644 (file)
index 0000000..4fdaa8d
--- /dev/null
@@ -0,0 +1,293 @@
+/*
+ *      bit reservoir source file
+ *
+ *      Copyright (c) 1999-2000 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: reservoir.c,v 1.45 2011/05/07 16:05:17 rbrito Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "reservoir.h"
+
+#include "bitstream.h"
+#include "lame-analysis.h"
+#include "lame_global_flags.h"
+
+
+/*
+  ResvFrameBegin:
+  Called (repeatedly) at the beginning of a frame. Updates the maximum
+  size of the reservoir, and checks to make sure main_data_begin
+  was set properly by the formatter
+*/
+
+/*
+ *  Background information:
+ *
+ *  This is the original text from the ISO standard. Because of
+ *  sooo many bugs and irritations correcting comments are added
+ *  in brackets []. A '^W' means you should remove the last word.
+ *
+ *  1) The following rule can be used to calculate the maximum
+ *     number of bits used for one granule [^W frame]:
+ *     At the highest possible bitrate of Layer III (320 kbps
+ *     per stereo signal [^W^W^W], 48 kHz) the frames must be of
+ *     [^W^W^W are designed to have] constant length, i.e.
+ *     one buffer [^W^W the frame] length is:
+ *
+ *         320 kbps * 1152/48 kHz = 7680 bit = 960 byte
+ *
+ *     This value is used as the maximum buffer per channel [^W^W] at
+ *     lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps
+ *     stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit
+ *     [per granule and channel] at 48 kHz sampling frequency.
+ *     This means that there is a maximum deviation (short time buffer
+ *     [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps.
+ *     The actual deviation is equal to the number of bytes [with the
+ *     meaning of octets] denoted by the main_data_end offset pointer.
+ *     The actual maximum deviation is (2^9-1)*8 bit = 4088 bits
+ *     [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].
+ *     ... The xchange of buffer bits between the left and right channel
+ *     is allowed without restrictions [exception: dual channel].
+ *     Because of the [constructed] constraint on the buffer size
+ *     main_data_end is always set to 0 in the case of bit_rate_index==14,
+ *     i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case
+ *     all data are allocated between adjacent header [^W sync] words
+ *     [, i.e. there is no buffering at all].
+ */
+
+int
+ResvFrameBegin(lame_internal_flags * gfc, int *mean_bits)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     fullFrameBits;
+    int     resvLimit;
+    int     maxmp3buf;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+    int     frameLength;
+    int     meanBits;
+
+    frameLength = getframebits(gfc);
+    meanBits = (frameLength - cfg->sideinfo_len * 8) / cfg->mode_gr;
+
+/*
+ *  Meaning of the variables:
+ *      resvLimit: (0, 8, ..., 8*255 (MPEG-2), 8*511 (MPEG-1))
+ *          Number of bits can be stored in previous frame(s) due to
+ *          counter size constaints
+ *      maxmp3buf: ( ??? ... 8*1951 (MPEG-1 and 2), 8*2047 (MPEG-2.5))
+ *          Number of bits allowed to encode one frame (you can take 8*511 bit
+ *          from the bit reservoir and at most 8*1440 bit from the current
+ *          frame (320 kbps, 32 kHz), so 8*1951 bit is the largest possible
+ *          value for MPEG-1 and -2)
+ *
+ *          maximum allowed granule/channel size times 4 = 8*2047 bits.,
+ *          so this is the absolute maximum supported by the format.
+ *
+ *
+ *      fullFrameBits:  maximum number of bits available for encoding
+ *                      the current frame.
+ *
+ *      mean_bits:      target number of bits per granule.
+ *
+ *      frameLength:
+ *
+ *      gfc->ResvMax:   maximum allowed reservoir
+ *
+ *      gfc->ResvSize:  current reservoir size
+ *
+ *      l3_side->resvDrain_pre:
+ *         ancillary data to be added to previous frame:
+ *         (only usefull in VBR modes if it is possible to have
+ *         maxmp3buf < fullFrameBits)).  Currently disabled,
+ *         see #define NEW_DRAIN
+ *         2010-02-13: RH now enabled, it seems to be needed for CBR too,
+ *                     as there exists one example, where the FhG decoder
+ *                     can't decode a -b320 CBR file anymore.
+ *
+ *      l3_side->resvDrain_post:
+ *         ancillary data to be added to this frame:
+ *
+ */
+
+    /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */
+    resvLimit = (8 * 256) * cfg->mode_gr - 8;
+
+    /* maximum allowed frame size.  dont use more than this number of
+       bits, even if the frame has the space for them: */
+    maxmp3buf = cfg->buffer_constraint;
+    esv->ResvMax = maxmp3buf - frameLength;
+    if (esv->ResvMax > resvLimit)
+        esv->ResvMax = resvLimit;
+    if (esv->ResvMax < 0 || cfg->disable_reservoir)
+        esv->ResvMax = 0;
+    
+    fullFrameBits = meanBits * cfg->mode_gr + Min(esv->ResvSize, esv->ResvMax);
+
+    if (fullFrameBits > maxmp3buf)
+        fullFrameBits = maxmp3buf;
+
+    assert(0 == esv->ResvMax % 8);
+    assert(esv->ResvMax >= 0);
+
+    l3_side->resvDrain_pre = 0;
+
+    if (gfc->pinfo != NULL) {
+        gfc->pinfo->mean_bits = meanBits / 2; /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */
+        gfc->pinfo->resvsize = esv->ResvSize;
+    }
+    *mean_bits = meanBits;
+    return fullFrameBits;
+}
+
+
+/*
+  ResvMaxBits
+  returns targ_bits:  target number of bits to use for 1 granule
+         extra_bits:  amount extra available from reservoir
+  Mark Taylor 4/99
+*/
+void
+ResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *extra_bits, int cbr)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    int     add_bits, targBits, extraBits;
+    int     ResvSize = esv->ResvSize, ResvMax = esv->ResvMax;
+
+    /* conpensate the saved bits used in the 1st granule */
+    if (cbr)
+        ResvSize += mean_bits;
+
+    if (gfc->sv_qnt.substep_shaping & 1)
+        ResvMax *= 0.9;
+
+    targBits = mean_bits;
+
+    /* extra bits if the reservoir is almost full */
+    if (ResvSize * 10 > ResvMax * 9) {
+        add_bits = ResvSize - (ResvMax * 9) / 10;
+        targBits += add_bits;
+        gfc->sv_qnt.substep_shaping |= 0x80;
+    }
+    else {
+        add_bits = 0;
+        gfc->sv_qnt.substep_shaping &= 0x7f;
+        /* build up reservoir.  this builds the reservoir a little slower
+         * than FhG.  It could simple be mean_bits/15, but this was rigged
+         * to always produce 100 (the old value) at 128kbs */
+        /*    *targ_bits -= (int) (mean_bits/15.2); */
+        if (!cfg->disable_reservoir && !(gfc->sv_qnt.substep_shaping & 1))
+            targBits -= .1 * mean_bits;
+    }
+
+
+    /* amount from the reservoir we are allowed to use. ISO says 6/10 */
+    extraBits = (ResvSize < (esv->ResvMax * 6) / 10 ? ResvSize : (esv->ResvMax * 6) / 10);
+    extraBits -= add_bits;
+
+    if (extraBits < 0)
+        extraBits = 0;
+
+    *targ_bits = targBits;
+    *extra_bits = extraBits;
+}
+
+/*
+  ResvAdjust:
+  Called after a granule's bit allocation. Readjusts the size of
+  the reservoir to reflect the granule's usage.
+*/
+void
+ResvAdjust(lame_internal_flags * gfc, gr_info const *gi)
+{
+    gfc->sv_enc.ResvSize -= gi->part2_3_length + gi->part2_length;
+}
+
+
+/*
+  ResvFrameEnd:
+  Called after all granules in a frame have been allocated. Makes sure
+  that the reservoir size is within limits, possibly by adding stuffing
+  bits.
+*/
+void
+ResvFrameEnd(lame_internal_flags * gfc, int mean_bits)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *const esv = &gfc->sv_enc;
+    III_side_info_t *const l3_side = &gfc->l3_side;
+    int     stuffingBits;
+    int     over_bits;
+
+    esv->ResvSize += mean_bits * cfg->mode_gr;
+    stuffingBits = 0;
+    l3_side->resvDrain_post = 0;
+    l3_side->resvDrain_pre = 0;
+
+    /* we must be byte aligned */
+    if ((over_bits = esv->ResvSize % 8) != 0)
+        stuffingBits += over_bits;
+
+
+    over_bits = (esv->ResvSize - stuffingBits) - esv->ResvMax;
+    if (over_bits > 0) {
+        assert(0 == over_bits % 8);
+        assert(over_bits >= 0);
+        stuffingBits += over_bits;
+    }
+
+
+    /* NOTE: enabling the NEW_DRAIN code fixes some problems with FhG decoder
+             shipped with MS Windows operating systems. Using this, it is even
+             possible to use Gabriel's lax buffer consideration again, which
+             assumes, any decoder should have a buffer large enough
+             for a 320 kbps frame at 32 kHz sample rate.
+
+       old drain code:
+             lame -b320 BlackBird.wav ---> does not play with GraphEdit.exe using FhG decoder V1.5 Build 50
+
+       new drain code:
+             lame -b320 BlackBird.wav ---> plays fine with GraphEdit.exe using FhG decoder V1.5 Build 50
+
+             Robert Hegemann, 2010-02-13.
+     */
+    /* drain as many bits as possible into previous frame ancillary data
+     * In particular, in VBR mode ResvMax may have changed, and we have
+     * to make sure main_data_begin does not create a reservoir bigger
+     * than ResvMax  mt 4/00*/
+    {
+        int     mdb_bytes = Min(l3_side->main_data_begin * 8, stuffingBits) / 8;
+        l3_side->resvDrain_pre += 8 * mdb_bytes;
+        stuffingBits -= 8 * mdb_bytes;
+        esv->ResvSize -= 8 * mdb_bytes;
+        l3_side->main_data_begin -= mdb_bytes;
+    }
+    /* drain the rest into this frames ancillary data */
+    l3_side->resvDrain_post += stuffingBits;
+    esv->ResvSize -= stuffingBits;
+}
diff --git a/lame/libmp3lame/reservoir.h b/lame/libmp3lame/reservoir.h
new file mode 100644 (file)
index 0000000..7c58593
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ *     bit reservoir include file
+ *
+ *     Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_RESERVOIR_H
+#define LAME_RESERVOIR_H
+
+int     ResvFrameBegin(lame_internal_flags * gfc, int *mean_bits);
+void    ResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *max_bits,
+                    int cbr);
+void    ResvAdjust(lame_internal_flags * gfc, gr_info const *gi);
+void    ResvFrameEnd(lame_internal_flags * gfc, int mean_bits);
+
+#endif /* LAME_RESERVOIR_H */
diff --git a/lame/libmp3lame/set_get.c b/lame/libmp3lame/set_get.c
new file mode 100644 (file)
index 0000000..f763900
--- /dev/null
@@ -0,0 +1,2346 @@
+/* -*- mode: C; mode: fold -*- */
+/*
+ * set/get functions for lame_global_flags
+ *
+ * Copyright (c) 2001-2005 Alexander Leidinger
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: set_get.c,v 1.104 2017/09/06 15:07:30 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "bitstream.h"  /* because of compute_flushbits */
+
+#include "set_get.h"
+#include "lame_global_flags.h"
+
+/*
+ * input stream description
+ */
+
+
+/* number of samples */
+/* it's unlikely for this function to return an error */
+int
+lame_set_num_samples(lame_global_flags * gfp, unsigned long num_samples)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 2^32-1 */
+        gfp->num_samples = num_samples;
+        return 0;
+    }
+    return -1;
+}
+
+unsigned long
+lame_get_num_samples(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->num_samples;
+    }
+    return 0;
+}
+
+
+/* input samplerate */
+int
+lame_set_in_samplerate(lame_global_flags * gfp, int in_samplerate)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        if (in_samplerate < 1)
+            return -1;
+        /* input sample rate in Hz,  default = 44100 Hz */
+        gfp->samplerate_in = in_samplerate;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_in_samplerate(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->samplerate_in;
+    }
+    return 0;
+}
+
+
+/* number of channels in input stream */
+int
+lame_set_num_channels(lame_global_flags * gfp, int num_channels)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 2 */
+        if (2 < num_channels || 0 >= num_channels) {
+            return -1;  /* we don't support more than 2 channels */
+        }
+        gfp->num_channels = num_channels;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_num_channels(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->num_channels;
+    }
+    return 0;
+}
+
+
+/* scale the input by this amount before encoding (not used for decoding) */
+int
+lame_set_scale(lame_global_flags * gfp, float scale)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 */
+        gfp->scale = scale;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_scale(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->scale;
+    }
+    return 0;
+}
+
+
+/* scale the channel 0 (left) input by this amount before 
+   encoding (not used for decoding) */
+int
+lame_set_scale_left(lame_global_flags * gfp, float scale)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 */
+        gfp->scale_left = scale;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_scale_left(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->scale_left;
+    }
+    return 0;
+}
+
+
+/* scale the channel 1 (right) input by this amount before 
+   encoding (not used for decoding) */
+int
+lame_set_scale_right(lame_global_flags * gfp, float scale)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 */
+        gfp->scale_right = scale;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_scale_right(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->scale_right;
+    }
+    return 0;
+}
+
+
+/* output sample rate in Hz */
+int
+lame_set_out_samplerate(lame_global_flags * gfp, int out_samplerate)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /*
+         * default = 0: LAME picks best value based on the amount
+         *              of compression
+         * MPEG only allows:
+         *  MPEG1    32, 44.1,   48khz
+         *  MPEG2    16, 22.05,  24
+         *  MPEG2.5   8, 11.025, 12
+         *
+         * (not used by decoding routines)
+         */
+        if (out_samplerate != 0) {
+            int     v=0;
+            if (SmpFrqIndex(out_samplerate, &v) < 0)
+                return -1;
+        }
+        gfp->samplerate_out = out_samplerate;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_out_samplerate(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->samplerate_out;
+    }
+    return 0;
+}
+
+
+
+
+/*
+ * general control parameters
+ */
+
+/* collect data for an MP3 frame analzyer */
+int
+lame_set_analysis(lame_global_flags * gfp, int analysis)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > analysis || 1 < analysis)
+            return -1;
+        gfp->analysis = analysis;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_analysis(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->analysis && 1 >= gfp->analysis);
+        return gfp->analysis;
+    }
+    return 0;
+}
+
+
+/* write a Xing VBR header frame */
+int
+lame_set_bWriteVbrTag(lame_global_flags * gfp, int bWriteVbrTag)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 (on) for VBR/ABR modes, 0 (off) for CBR mode */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > bWriteVbrTag || 1 < bWriteVbrTag)
+            return -1;
+        gfp->write_lame_tag = bWriteVbrTag;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_bWriteVbrTag(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->write_lame_tag && 1 >= gfp->write_lame_tag);
+        return gfp->write_lame_tag;
+    }
+    return 0;
+}
+
+
+
+/* decode only, use lame/mpglib to convert mp3 to wav */
+int
+lame_set_decode_only(lame_global_flags * gfp, int decode_only)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > decode_only || 1 < decode_only)
+            return -1;
+        gfp->decode_only = decode_only;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_decode_only(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->decode_only && 1 >= gfp->decode_only);
+        return gfp->decode_only;
+    }
+    return 0;
+}
+
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+/* 1=encode a Vorbis .ogg file.  default=0 */
+/* DEPRECATED */
+int CDECL lame_set_ogg(lame_global_flags *, int);
+int CDECL lame_get_ogg(const lame_global_flags *);
+#else
+#endif
+
+/* encode a Vorbis .ogg file */
+/* DEPRECATED */
+int
+lame_set_ogg(lame_global_flags * gfp, int ogg)
+{
+    (void) gfp;
+    (void) ogg;
+    return -1;
+}
+
+int
+lame_get_ogg(const lame_global_flags * gfp)
+{
+    (void) gfp;
+    return 0;
+}
+
+
+/*
+ * Internal algorithm selection.
+ * True quality is determined by the bitrate but this variable will effect
+ * quality by selecting expensive or cheap algorithms.
+ * quality=0..9.  0=best (very slow).  9=worst.  
+ * recommended:  3     near-best quality, not too slow
+ *               5     good quality, fast
+ *               7     ok quality, really fast
+ */
+int
+lame_set_quality(lame_global_flags * gfp, int quality)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        if (quality < 0) {
+            gfp->quality = 0;
+        }
+        else if (quality > 9) {
+            gfp->quality = 9;
+        }
+        else {
+            gfp->quality = quality;
+        }
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_quality(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->quality;
+    }
+    return 0;
+}
+
+
+/* mode = STEREO, JOINT_STEREO, DUAL_CHANNEL (not supported), MONO */
+int
+lame_set_mode(lame_global_flags * gfp, MPEG_mode mode)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        int     mpg_mode = mode;
+        /* default: lame chooses based on compression ratio and input channels */
+        if (mpg_mode < 0 || MAX_INDICATOR <= mpg_mode)
+            return -1;  /* Unknown MPEG mode! */
+        gfp->mode = mode;
+        return 0;
+    }
+    return -1;
+}
+
+MPEG_mode
+lame_get_mode(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(gfp->mode < MAX_INDICATOR);
+        return gfp->mode;
+    }
+    return NOT_SET;
+}
+
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+/*
+  mode_automs.  Use a M/S mode with a switching threshold based on
+  compression ratio
+  DEPRECATED
+*/
+int CDECL lame_set_mode_automs(lame_global_flags *, int);
+int CDECL lame_get_mode_automs(const lame_global_flags *);
+#else
+#endif
+
+/* Us a M/S mode with a switching threshold based on compression ratio */
+/* DEPRECATED */
+int
+lame_set_mode_automs(lame_global_flags * gfp, int mode_automs)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > mode_automs || 1 < mode_automs)
+            return -1;
+        lame_set_mode(gfp, JOINT_STEREO);
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_mode_automs(const lame_global_flags * gfp)
+{
+    (void) gfp;
+    return 1;
+}
+
+
+/*
+ * Force M/S for all frames.  For testing only.
+ * Requires mode = 1.
+ */
+int
+lame_set_force_ms(lame_global_flags * gfp, int force_ms)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > force_ms || 1 < force_ms)
+            return -1;
+        gfp->force_ms = force_ms;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_force_ms(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->force_ms && 1 >= gfp->force_ms);
+        return gfp->force_ms;
+    }
+    return 0;
+}
+
+
+/* Use free_format. */
+int
+lame_set_free_format(lame_global_flags * gfp, int free_format)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > free_format || 1 < free_format)
+            return -1;
+        gfp->free_format = free_format;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_free_format(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->free_format && 1 >= gfp->free_format);
+        return gfp->free_format;
+    }
+    return 0;
+}
+
+
+
+/* Perform ReplayGain analysis */
+int
+lame_set_findReplayGain(lame_global_flags * gfp, int findReplayGain)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > findReplayGain || 1 < findReplayGain)
+            return -1;
+        gfp->findReplayGain = findReplayGain;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_findReplayGain(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->findReplayGain && 1 >= gfp->findReplayGain);
+        return gfp->findReplayGain;
+    }
+    return 0;
+}
+
+
+/* Decode on the fly. Find the peak sample. If ReplayGain analysis is 
+   enabled then perform it on the decoded data. */
+int
+lame_set_decode_on_the_fly(lame_global_flags * gfp, int decode_on_the_fly)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+#ifndef DECODE_ON_THE_FLY
+        return -1;
+#else
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > decode_on_the_fly || 1 < decode_on_the_fly)
+            return -1;
+
+        gfp->decode_on_the_fly = decode_on_the_fly;
+
+        return 0;
+#endif
+    }
+    return -1;
+}
+
+int
+lame_get_decode_on_the_fly(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->decode_on_the_fly && 1 >= gfp->decode_on_the_fly);
+        return gfp->decode_on_the_fly;
+    }
+    return 0;
+}
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+/* DEPRECATED: now does the same as lame_set_findReplayGain()
+   default = 0 (disabled) */
+int CDECL lame_set_ReplayGain_input(lame_global_flags *, int);
+int CDECL lame_get_ReplayGain_input(const lame_global_flags *);
+
+/* DEPRECATED: now does the same as
+   lame_set_decode_on_the_fly() && lame_set_findReplayGain()
+   default = 0 (disabled) */
+int CDECL lame_set_ReplayGain_decode(lame_global_flags *, int);
+int CDECL lame_get_ReplayGain_decode(const lame_global_flags *);
+
+/* DEPRECATED: now does the same as lame_set_decode_on_the_fly()
+   default = 0 (disabled) */
+int CDECL lame_set_findPeakSample(lame_global_flags *, int);
+int CDECL lame_get_findPeakSample(const lame_global_flags *);
+#else
+#endif
+
+/* DEPRECATED. same as lame_set_decode_on_the_fly() */
+int
+lame_set_findPeakSample(lame_global_flags * gfp, int arg)
+{
+    return lame_set_decode_on_the_fly(gfp, arg);
+}
+
+int
+lame_get_findPeakSample(const lame_global_flags * gfp)
+{
+    return lame_get_decode_on_the_fly(gfp);
+}
+
+/* DEPRECATED. same as lame_set_findReplayGain() */
+int
+lame_set_ReplayGain_input(lame_global_flags * gfp, int arg)
+{
+    return lame_set_findReplayGain(gfp, arg);
+}
+
+int
+lame_get_ReplayGain_input(const lame_global_flags * gfp)
+{
+    return lame_get_findReplayGain(gfp);
+}
+
+/* DEPRECATED. same as lame_set_decode_on_the_fly() &&
+   lame_set_findReplayGain() */
+int
+lame_set_ReplayGain_decode(lame_global_flags * gfp, int arg)
+{
+    if (lame_set_decode_on_the_fly(gfp, arg) < 0 || lame_set_findReplayGain(gfp, arg) < 0)
+        return -1;
+    else
+        return 0;
+}
+
+int
+lame_get_ReplayGain_decode(const lame_global_flags * gfp)
+{
+    if (lame_get_decode_on_the_fly(gfp) > 0 && lame_get_findReplayGain(gfp) > 0)
+        return 1;
+    else
+        return 0;
+}
+
+
+/* set and get some gapless encoding flags */
+
+int
+lame_set_nogap_total(lame_global_flags * gfp, int the_nogap_total)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->nogap_total = the_nogap_total;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_nogap_total(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->nogap_total;
+    }
+    return 0;
+}
+
+int
+lame_set_nogap_currentindex(lame_global_flags * gfp, int the_nogap_index)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->nogap_current = the_nogap_index;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_nogap_currentindex(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->nogap_current;
+    }
+    return 0;
+}
+
+
+/* message handlers */
+int
+lame_set_errorf(lame_global_flags * gfp, void (*func) (const char *, va_list))
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->report.errorf = func;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_set_debugf(lame_global_flags * gfp, void (*func) (const char *, va_list))
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->report.debugf = func;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_set_msgf(lame_global_flags * gfp, void (*func) (const char *, va_list))
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->report.msgf = func;
+        return 0;
+    }
+    return -1;
+}
+
+
+/*
+ * Set one of
+ *  - brate
+ *  - compression ratio.
+ *
+ * Default is compression ratio of 11.
+ */
+int
+lame_set_brate(lame_global_flags * gfp, int brate)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->brate = brate;
+        if (brate > 320) {
+            gfp->disable_reservoir = 1;
+        }
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_brate(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->brate;
+    }
+    return 0;
+}
+
+int
+lame_set_compression_ratio(lame_global_flags * gfp, float compression_ratio)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->compression_ratio = compression_ratio;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_compression_ratio(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->compression_ratio;
+    }
+    return 0;
+}
+
+
+
+
+/*
+ * frame parameters
+ */
+
+/* Mark as copyright protected. */
+int
+lame_set_copyright(lame_global_flags * gfp, int copyright)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > copyright || 1 < copyright)
+            return -1;
+        gfp->copyright = copyright;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_copyright(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->copyright && 1 >= gfp->copyright);
+        return gfp->copyright;
+    }
+    return 0;
+}
+
+
+/* Mark as original. */
+int
+lame_set_original(lame_global_flags * gfp, int original)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 (enabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > original || 1 < original)
+            return -1;
+        gfp->original = original;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_original(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->original && 1 >= gfp->original);
+        return gfp->original;
+    }
+    return 0;
+}
+
+
+/*
+ * error_protection.
+ * Use 2 bytes from each frame for CRC checksum.
+ */
+int
+lame_set_error_protection(lame_global_flags * gfp, int error_protection)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > error_protection || 1 < error_protection)
+            return -1;
+        gfp->error_protection = error_protection;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_error_protection(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->error_protection && 1 >= gfp->error_protection);
+        return gfp->error_protection;
+    }
+    return 0;
+}
+
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+/* padding_type. 0=pad no frames  1=pad all frames 2=adjust padding(default) */
+int CDECL lame_set_padding_type(lame_global_flags *, Padding_type);
+Padding_type CDECL lame_get_padding_type(const lame_global_flags *);
+#else
+#endif
+
+/*
+ * padding_type.
+ *  PAD_NO     = pad no frames
+ *  PAD_ALL    = pad all frames
+ *  PAD_ADJUST = adjust padding
+ */
+int
+lame_set_padding_type(lame_global_flags * gfp, Padding_type padding_type)
+{
+    (void) gfp;
+    (void) padding_type;
+    return 0;
+}
+
+Padding_type
+lame_get_padding_type(const lame_global_flags * gfp)
+{
+    (void) gfp;
+    return PAD_ADJUST;
+}
+
+
+/* MP3 'private extension' bit. Meaningless. */
+int
+lame_set_extension(lame_global_flags * gfp, int extension)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > extension || 1 < extension)
+            return -1;
+        gfp->extension = extension;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_extension(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->extension && 1 >= gfp->extension);
+        return gfp->extension;
+    }
+    return 0;
+}
+
+
+/* Enforce strict ISO compliance. */
+int
+lame_set_strict_ISO(lame_global_flags * gfp, int val)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (val < MDB_DEFAULT || MDB_MAXIMUM < val)
+            return -1;
+        gfp->strict_ISO = val;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_strict_ISO(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->strict_ISO;
+    }
+    return 0;
+}
+
+
+
+
+/********************************************************************
+ * quantization/noise shaping 
+ ***********************************************************************/
+
+/* Disable the bit reservoir. For testing only. */
+int
+lame_set_disable_reservoir(lame_global_flags * gfp, int disable_reservoir)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > disable_reservoir || 1 < disable_reservoir)
+            return -1;
+        gfp->disable_reservoir = disable_reservoir;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_disable_reservoir(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->disable_reservoir && 1 >= gfp->disable_reservoir);
+        return gfp->disable_reservoir;
+    }
+    return 0;
+}
+
+
+
+
+int
+lame_set_experimentalX(lame_global_flags * gfp, int experimentalX)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_set_quant_comp(gfp, experimentalX);
+        lame_set_quant_comp_short(gfp, experimentalX);
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_experimentalX(const lame_global_flags * gfp)
+{
+    return lame_get_quant_comp(gfp);
+}
+
+
+/* Select a different "best quantization" function. default = 0 */
+int
+lame_set_quant_comp(lame_global_flags * gfp, int quant_type)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->quant_comp = quant_type;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_quant_comp(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->quant_comp;
+    }
+    return 0;
+}
+
+
+/* Select a different "best quantization" function. default = 0 */
+int
+lame_set_quant_comp_short(lame_global_flags * gfp, int quant_type)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->quant_comp_short = quant_type;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_quant_comp_short(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->quant_comp_short;
+    }
+    return 0;
+}
+
+
+/* Another experimental option. For testing only. */
+int
+lame_set_experimentalY(lame_global_flags * gfp, int experimentalY)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->experimentalY = experimentalY;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_experimentalY(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->experimentalY;
+    }
+    return 0;
+}
+
+
+int
+lame_set_experimentalZ(lame_global_flags * gfp, int experimentalZ)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->experimentalZ = experimentalZ;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_experimentalZ(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->experimentalZ;
+    }
+    return 0;
+}
+
+
+/* Naoki's psycho acoustic model. */
+int
+lame_set_exp_nspsytune(lame_global_flags * gfp, int exp_nspsytune)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+        gfp->exp_nspsytune = exp_nspsytune;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_exp_nspsytune(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->exp_nspsytune;
+    }
+    return 0;
+}
+
+
+
+
+/********************************************************************
+ * VBR control
+ ***********************************************************************/
+
+/* Types of VBR.  default = vbr_off = CBR */
+int
+lame_set_VBR(lame_global_flags * gfp, vbr_mode VBR)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        int     vbr_q = VBR;
+        if (0 > vbr_q || vbr_max_indicator <= vbr_q)
+            return -1;  /* Unknown VBR mode! */
+        gfp->VBR = VBR;
+        return 0;
+    }
+    return -1;
+}
+
+vbr_mode
+lame_get_VBR(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(gfp->VBR < vbr_max_indicator);
+        return gfp->VBR;
+    }
+    return vbr_off;
+}
+
+
+/*
+ * VBR quality level.
+ *  0 = highest
+ *  9 = lowest 
+ */
+int
+lame_set_VBR_q(lame_global_flags * gfp, int VBR_q)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        int     ret = 0;
+
+        if (0 > VBR_q) {
+            ret = -1;   /* Unknown VBR quality level! */
+            VBR_q = 0;
+        }
+        if (9 < VBR_q) {
+            ret = -1;
+            VBR_q = 9;
+        }
+        gfp->VBR_q = VBR_q;
+        gfp->VBR_q_frac = 0;
+        return ret;
+    }
+    return -1;
+}
+
+int
+lame_get_VBR_q(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->VBR_q && 10 > gfp->VBR_q);
+        return gfp->VBR_q;
+    }
+    return 0;
+}
+
+int
+lame_set_VBR_quality(lame_global_flags * gfp, float VBR_q)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        int     ret = 0;
+
+        if (0 > VBR_q) {
+            ret = -1;   /* Unknown VBR quality level! */
+            VBR_q = 0;
+        }
+        if (9.999 < VBR_q) {
+            ret = -1;
+            VBR_q = 9.999;
+        }
+
+        gfp->VBR_q = (int) VBR_q;
+        gfp->VBR_q_frac = VBR_q - gfp->VBR_q;
+
+        return ret;
+    }
+    return -1;
+}
+
+float
+lame_get_VBR_quality(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->VBR_q + gfp->VBR_q_frac;
+    }
+    return 0;
+}
+
+
+/* Ignored except for VBR = vbr_abr (ABR mode) */
+int
+lame_set_VBR_mean_bitrate_kbps(lame_global_flags * gfp, int VBR_mean_bitrate_kbps)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->VBR_mean_bitrate_kbps = VBR_mean_bitrate_kbps;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_VBR_mean_bitrate_kbps(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->VBR_mean_bitrate_kbps;
+    }
+    return 0;
+}
+
+int
+lame_set_VBR_min_bitrate_kbps(lame_global_flags * gfp, int VBR_min_bitrate_kbps)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->VBR_min_bitrate_kbps = VBR_min_bitrate_kbps;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_VBR_min_bitrate_kbps(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->VBR_min_bitrate_kbps;
+    }
+    return 0;
+}
+
+int
+lame_set_VBR_max_bitrate_kbps(lame_global_flags * gfp, int VBR_max_bitrate_kbps)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->VBR_max_bitrate_kbps = VBR_max_bitrate_kbps;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_VBR_max_bitrate_kbps(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->VBR_max_bitrate_kbps;
+    }
+    return 0;
+}
+
+
+/*
+ * Strictly enforce VBR_min_bitrate.
+ * Normally it will be violated for analog silence.
+ */
+int
+lame_set_VBR_hard_min(lame_global_flags * gfp, int VBR_hard_min)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 (disabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > VBR_hard_min || 1 < VBR_hard_min)
+            return -1;
+
+        gfp->VBR_hard_min = VBR_hard_min;
+
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_VBR_hard_min(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->VBR_hard_min && 1 >= gfp->VBR_hard_min);
+        return gfp->VBR_hard_min;
+    }
+    return 0;
+}
+
+
+/********************************************************************
+ * Filtering control
+ ***********************************************************************/
+
+/*
+ * Freqency in Hz to apply lowpass.
+ *   0 = default = lame chooses
+ *  -1 = disabled
+ */
+int
+lame_set_lowpassfreq(lame_global_flags * gfp, int lowpassfreq)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->lowpassfreq = lowpassfreq;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_lowpassfreq(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->lowpassfreq;
+    }
+    return 0;
+}
+
+
+/*
+ * Width of transition band (in Hz).
+ *  default = one polyphase filter band
+ */
+int
+lame_set_lowpasswidth(lame_global_flags * gfp, int lowpasswidth)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->lowpasswidth = lowpasswidth;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_lowpasswidth(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->lowpasswidth;
+    }
+    return 0;
+}
+
+
+/*
+ * Frequency in Hz to apply highpass.
+ *   0 = default = lame chooses
+ *  -1 = disabled
+ */
+int
+lame_set_highpassfreq(lame_global_flags * gfp, int highpassfreq)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->highpassfreq = highpassfreq;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_highpassfreq(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->highpassfreq;
+    }
+    return 0;
+}
+
+
+/*
+ * Width of transition band (in Hz).
+ *  default = one polyphase filter band
+ */
+int
+lame_set_highpasswidth(lame_global_flags * gfp, int highpasswidth)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->highpasswidth = highpasswidth;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_highpasswidth(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->highpasswidth;
+    }
+    return 0;
+}
+
+
+
+
+/*
+ * psycho acoustics and other arguments which you should not change 
+ * unless you know what you are doing
+ */
+
+
+/* Adjust masking values. */
+int
+lame_set_maskingadjust(lame_global_flags * gfp, float adjust)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->maskingadjust = adjust;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_maskingadjust(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->maskingadjust;
+    }
+    return 0;
+}
+
+int
+lame_set_maskingadjust_short(lame_global_flags * gfp, float adjust)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->maskingadjust_short = adjust;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_maskingadjust_short(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->maskingadjust_short;
+    }
+    return 0;
+}
+
+/* Only use ATH for masking. */
+int
+lame_set_ATHonly(lame_global_flags * gfp, int ATHonly)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->ATHonly = ATHonly;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_ATHonly(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->ATHonly;
+    }
+    return 0;
+}
+
+
+/* Only use ATH for short blocks. */
+int
+lame_set_ATHshort(lame_global_flags * gfp, int ATHshort)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->ATHshort = ATHshort;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_ATHshort(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->ATHshort;
+    }
+    return 0;
+}
+
+
+/* Disable ATH. */
+int
+lame_set_noATH(lame_global_flags * gfp, int noATH)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->noATH = noATH;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_noATH(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->noATH;
+    }
+    return 0;
+}
+
+
+/* Select ATH formula. */
+int
+lame_set_ATHtype(lame_global_flags * gfp, int ATHtype)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* XXX: ATHtype should be converted to an enum. */
+        gfp->ATHtype = ATHtype;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_ATHtype(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->ATHtype;
+    }
+    return 0;
+}
+
+
+/* Select ATH formula 4 shape. */
+int
+lame_set_ATHcurve(lame_global_flags * gfp, float ATHcurve)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->ATHcurve = ATHcurve;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_ATHcurve(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->ATHcurve;
+    }
+    return 0;
+}
+
+
+/* Lower ATH by this many db. */
+int
+lame_set_ATHlower(lame_global_flags * gfp, float ATHlower)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->ATH_lower_db = ATHlower;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_ATHlower(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->ATH_lower_db;
+    }
+    return 0;
+}
+
+
+/* Select ATH adaptive adjustment scheme. */
+int
+lame_set_athaa_type(lame_global_flags * gfp, int athaa_type)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->athaa_type = athaa_type;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_athaa_type(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->athaa_type;
+    }
+    return 0;
+}
+
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+int CDECL lame_set_athaa_loudapprox(lame_global_flags * gfp, int athaa_loudapprox);
+int CDECL lame_get_athaa_loudapprox(const lame_global_flags * gfp);
+#else
+#endif
+
+/* Select the loudness approximation used by the ATH adaptive auto-leveling. */
+int
+lame_set_athaa_loudapprox(lame_global_flags * gfp, int athaa_loudapprox)
+{
+    (void) gfp;
+    (void) athaa_loudapprox;
+    return 0;
+}
+
+int
+lame_get_athaa_loudapprox(const lame_global_flags * gfp)
+{
+    (void) gfp;
+    /* obsolete, the type known under number 2 is the only survival */
+    return 2;
+}
+
+
+/* Adjust (in dB) the point below which adaptive ATH level adjustment occurs. */
+int
+lame_set_athaa_sensitivity(lame_global_flags * gfp, float athaa_sensitivity)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->athaa_sensitivity = athaa_sensitivity;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_athaa_sensitivity(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->athaa_sensitivity;
+    }
+    return 0;
+}
+
+
+/* Predictability limit (ISO tonality formula) */
+int     lame_set_cwlimit(lame_global_flags * gfp, int cwlimit);
+int     lame_get_cwlimit(const lame_global_flags * gfp);
+
+int
+lame_set_cwlimit(lame_global_flags * gfp, int cwlimit)
+{
+    (void) gfp;
+    (void) cwlimit;
+    return 0;
+}
+
+int
+lame_get_cwlimit(const lame_global_flags * gfp)
+{
+    (void) gfp;
+    return 0;
+}
+
+
+
+/*
+ * Allow blocktypes to differ between channels.
+ * default:
+ *  0 for jstereo => block types coupled
+ *  1 for stereo  => block types may differ
+ */
+int
+lame_set_allow_diff_short(lame_global_flags * gfp, int allow_diff_short)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->short_blocks = allow_diff_short ? short_block_allowed : short_block_coupled;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_allow_diff_short(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        if (gfp->short_blocks == short_block_allowed)
+            return 1;   /* short blocks allowed to differ */
+        else
+            return 0;   /* not set, dispensed, forced or coupled */
+    }
+    return 0;
+}
+
+
+/* Use temporal masking effect */
+int
+lame_set_useTemporal(lame_global_flags * gfp, int useTemporal)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 1 (enabled) */
+
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 <= useTemporal && useTemporal <= 1) {
+            gfp->useTemporal = useTemporal;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+int
+lame_get_useTemporal(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->useTemporal && 1 >= gfp->useTemporal);
+        return gfp->useTemporal;
+    }
+    return 0;
+}
+
+
+/* Use inter-channel masking effect */
+int
+lame_set_interChRatio(lame_global_flags * gfp, float ratio)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0.0 (no inter-channel maskin) */
+        if (0 <= ratio && ratio <= 1.0) {
+            gfp->interChRatio = ratio;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+float
+lame_get_interChRatio(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert((0 <= gfp->interChRatio && gfp->interChRatio <= 1.0) || EQ(gfp->interChRatio, -1));
+        return gfp->interChRatio;
+    }
+    return 0;
+}
+
+
+/* Use pseudo substep shaping method */
+int
+lame_set_substep(lame_global_flags * gfp, int method)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0.0 (no substep noise shaping) */
+        if (0 <= method && method <= 7) {
+            gfp->substep_shaping = method;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+int
+lame_get_substep(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->substep_shaping && gfp->substep_shaping <= 7);
+        return gfp->substep_shaping;
+    }
+    return 0;
+}
+
+/* scalefactors scale */
+int
+lame_set_sfscale(lame_global_flags * gfp, int val)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->noise_shaping = (val != 0) ? 2 : 1;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_sfscale(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return (gfp->noise_shaping == 2) ? 1 : 0;
+    }
+    return 0;
+}
+
+/* subblock gain */
+int
+lame_set_subblock_gain(lame_global_flags * gfp, int sbgain)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->subblock_gain = sbgain;
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_subblock_gain(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->subblock_gain;
+    }
+    return 0;
+}
+
+
+/* Disable short blocks. */
+int
+lame_set_no_short_blocks(lame_global_flags * gfp, int no_short_blocks)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 <= no_short_blocks && no_short_blocks <= 1) {
+            gfp->short_blocks = no_short_blocks ? short_block_dispensed : short_block_allowed;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+int
+lame_get_no_short_blocks(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        switch (gfp->short_blocks) {
+        default:
+        case short_block_not_set:
+            return -1;
+        case short_block_dispensed:
+            return 1;
+        case short_block_allowed:
+        case short_block_coupled:
+        case short_block_forced:
+            return 0;
+        }
+    }
+    return -1;
+}
+
+
+/* Force short blocks. */
+int
+lame_set_force_short_blocks(lame_global_flags * gfp, int short_blocks)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* enforce disable/enable meaning, if we need more than two values
+           we need to switch to an enum to have an apropriate representation
+           of the possible meanings of the value */
+        if (0 > short_blocks || 1 < short_blocks)
+            return -1;
+
+        if (short_blocks == 1)
+            gfp->short_blocks = short_block_forced;
+        else if (gfp->short_blocks == short_block_forced)
+            gfp->short_blocks = short_block_allowed;
+
+        return 0;
+    }
+    return -1;
+}
+
+int
+lame_get_force_short_blocks(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        switch (gfp->short_blocks) {
+        default:
+        case short_block_not_set:
+            return -1;
+        case short_block_dispensed:
+        case short_block_allowed:
+        case short_block_coupled:
+            return 0;
+        case short_block_forced:
+            return 1;
+        }
+    }
+    return -1;
+}
+
+int
+lame_set_short_threshold_lrm(lame_global_flags * gfp, float lrm)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->attackthre = lrm;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_short_threshold_lrm(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->attackthre;
+    }
+    return 0;
+}
+
+int
+lame_set_short_threshold_s(lame_global_flags * gfp, float s)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->attackthre_s = s;
+        return 0;
+    }
+    return -1;
+}
+
+float
+lame_get_short_threshold_s(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->attackthre_s;
+    }
+    return 0;
+}
+
+int
+lame_set_short_threshold(lame_global_flags * gfp, float lrm, float s)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_set_short_threshold_lrm(gfp, lrm);
+        lame_set_short_threshold_s(gfp, s);
+        return 0;
+    }
+    return -1;
+}
+
+
+/*
+ * Input PCM is emphased PCM
+ * (for instance from one of the rarely emphased CDs).
+ *
+ * It is STRONGLY not recommended to use this, because psycho does not
+ * take it into account, and last but not least many decoders
+ * ignore these bits
+ */
+int
+lame_set_emphasis(lame_global_flags * gfp, int emphasis)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* XXX: emphasis should be converted to an enum */
+        if (0 <= emphasis && emphasis < 4) {
+            gfp->emphasis = emphasis;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+int
+lame_get_emphasis(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        assert(0 <= gfp->emphasis && gfp->emphasis < 4);
+        return gfp->emphasis;
+    }
+    return 0;
+}
+
+
+
+
+/***************************************************************/
+/* internal variables, cannot be set...                        */
+/* provided because they may be of use to calling application  */
+/***************************************************************/
+
+/* MPEG version.
+ *  0 = MPEG-2
+ *  1 = MPEG-1
+ * (2 = MPEG-2.5)    
+ */
+int
+lame_get_version(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->cfg.version;
+        }
+    }
+    return 0;
+}
+
+
+/* Encoder delay. */
+int
+lame_get_encoder_delay(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_enc.encoder_delay;
+        }
+    }
+    return 0;
+}
+
+/* padding added to the end of the input */
+int
+lame_get_encoder_padding(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_enc.encoder_padding;
+        }
+    }
+    return 0;
+}
+
+
+/* Size of MPEG frame. */
+int
+lame_get_framesize(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            return 576 * cfg->mode_gr;
+        }
+    }
+    return 0;
+}
+
+
+/* Number of frames encoded so far. */
+int
+lame_get_frameNum(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_enc.frame_number;
+        }
+    }
+    return 0;
+}
+
+int
+lame_get_mf_samples_to_encode(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->sv_enc.mf_samples_to_encode;
+        }
+    }
+    return 0;
+}
+
+int     CDECL
+lame_get_size_mp3buffer(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            int     size;
+            compute_flushbits(gfc, &size);
+            return size;
+        }
+    }
+    return 0;
+}
+
+int
+lame_get_RadioGain(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_rpg.RadioGain;
+        }
+    }
+    return 0;
+}
+
+int
+lame_get_AudiophileGain(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return 0;
+        }
+    }
+    return 0;
+}
+
+float
+lame_get_PeakSample(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return (float) gfc->ov_rpg.PeakSample;
+        }
+    }
+    return 0;
+}
+
+int
+lame_get_noclipGainChange(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_rpg.noclipGainChange;
+        }
+    }
+    return 0;
+}
+
+float
+lame_get_noclipScale(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return gfc->ov_rpg.noclipScale;
+        }
+    }
+    return 0;
+}
+
+
+/*
+ * LAME's estimate of the total number of frames to be encoded.
+ * Only valid if calling program set num_samples.
+ */
+int
+lame_get_totalframes(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            SessionConfig_t const *const cfg = &gfc->cfg;
+            unsigned long const pcm_samples_per_frame = 576 * cfg->mode_gr;
+            unsigned long pcm_samples_to_encode = gfp->num_samples;
+            unsigned long end_padding = 0;
+            int frames = 0;
+
+            if (pcm_samples_to_encode == (0ul-1ul))
+                return 0; /* unknown */
+
+            /* estimate based on user set num_samples: */
+            if (cfg->samplerate_in != cfg->samplerate_out) {
+                /* resampling, estimate new samples_to_encode */
+                double resampled_samples_to_encode = 0.0, frames_f = 0.0;
+                if (cfg->samplerate_in > 0) {
+                    resampled_samples_to_encode = pcm_samples_to_encode;
+                    resampled_samples_to_encode *= cfg->samplerate_out;
+                    resampled_samples_to_encode /= cfg->samplerate_in;
+                }
+                if (resampled_samples_to_encode <= 0.0)
+                    return 0; /* unlikely to happen, so what, no estimate! */
+                frames_f = floor(resampled_samples_to_encode / pcm_samples_per_frame);
+                if (frames_f >= (INT_MAX-2))
+                    return 0; /* overflow, happens eventually, no estimate! */
+                frames = frames_f;
+                resampled_samples_to_encode -= frames * pcm_samples_per_frame;
+                pcm_samples_to_encode = ceil(resampled_samples_to_encode);
+            }
+            else {
+                frames = pcm_samples_to_encode / pcm_samples_per_frame;
+                pcm_samples_to_encode -= frames * pcm_samples_per_frame;
+            }
+            pcm_samples_to_encode += 576ul;
+            end_padding = pcm_samples_per_frame - (pcm_samples_to_encode % pcm_samples_per_frame);
+            if (end_padding < 576ul) {
+                end_padding += pcm_samples_per_frame;
+            }
+            pcm_samples_to_encode += end_padding;
+            frames += (pcm_samples_to_encode / pcm_samples_per_frame);
+            /* check to see if we underestimated totalframes */
+            /*    if (totalframes < gfp->frameNum) */
+            /*        totalframes = gfp->frameNum; */
+            return frames;
+        }
+    }
+    return 0;
+}
+
+
+
+
+
+int
+lame_set_preset(lame_global_flags * gfp, int preset)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->preset = preset;
+        return apply_preset(gfp, preset, 1);
+    }
+    return -1;
+}
+
+
+
+int
+lame_set_asm_optimizations(lame_global_flags * gfp, int optim, int mode)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        mode = (mode == 1 ? 1 : 0);
+        switch (optim) {
+        case MMX:{
+                gfp->asm_optimizations.mmx = mode;
+                return optim;
+            }
+        case AMD_3DNOW:{
+                gfp->asm_optimizations.amd3dnow = mode;
+                return optim;
+            }
+        case SSE:{
+                gfp->asm_optimizations.sse = mode;
+                return optim;
+            }
+        default:
+            return optim;
+        }
+    }
+    return -1;
+}
+
+
+void
+lame_set_write_id3tag_automatic(lame_global_flags * gfp, int v)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->write_id3tag_automatic = v;
+    }
+}
+
+
+int
+lame_get_write_id3tag_automatic(lame_global_flags const *gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->write_id3tag_automatic;
+    }
+    return 1;
+}
+
+
+/*
+
+UNDOCUMENTED, experimental settings.  These routines are not prototyped
+in lame.h.  You should not use them, they are experimental and may
+change.  
+
+*/
+
+
+/*
+ *  just another daily changing developer switch  
+ */
+void CDECL lame_set_tune(lame_global_flags *, float);
+
+void
+lame_set_tune(lame_global_flags * gfp, float val)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        gfp->tune_value_a = val;
+        gfp->tune = 1;
+    }
+}
+
+/* Custom msfix hack */
+void
+lame_set_msfix(lame_global_flags * gfp, double msfix)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        /* default = 0 */
+        gfp->msfix = msfix;
+    }
+}
+
+float
+lame_get_msfix(const lame_global_flags * gfp)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        return gfp->msfix;
+    }
+    return 0;
+}
+
+#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED
+int CDECL lame_set_preset_expopts(lame_global_flags *, int);
+#else
+#endif
+
+int
+lame_set_preset_expopts(lame_global_flags * gfp, int preset_expopts)
+{
+    (void) gfp;
+    (void) preset_expopts;
+    return 0;
+}
+
+
+int
+lame_set_preset_notune(lame_global_flags * gfp, int preset_notune)
+{
+    (void) gfp;
+    (void) preset_notune;
+    return 0;
+}
+
+static int
+calc_maximum_input_samples_for_buffer_size(lame_internal_flags const* gfc, size_t buffer_size)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int const pcm_samples_per_frame = 576 * cfg->mode_gr;
+    int     frames_per_buffer = 0, input_samples_per_buffer = 0;
+    int     kbps = 320;
+
+    if (cfg->samplerate_out < 16000)
+        kbps = 64;
+    else if (cfg->samplerate_out < 32000)
+        kbps = 160;
+    else
+        kbps = 320;
+    if (cfg->free_format)
+        kbps = cfg->avg_bitrate;
+    else if (cfg->vbr == vbr_off) {
+        kbps = cfg->avg_bitrate;
+    }
+    {
+        int const pad = 1;
+        int const bpf = ((cfg->version + 1) * 72000 * kbps / cfg->samplerate_out + pad);
+        frames_per_buffer = buffer_size / bpf;
+    }
+    {
+        double ratio = (double) cfg->samplerate_in / cfg->samplerate_out;
+        input_samples_per_buffer = pcm_samples_per_frame * frames_per_buffer * ratio;
+    }
+    return input_samples_per_buffer;
+}
+
+int
+lame_get_maximum_number_of_samples(lame_t gfp, size_t buffer_size)
+{
+    if (is_lame_global_flags_valid(gfp)) {
+        lame_internal_flags const *const gfc = gfp->internal_flags;
+        if (is_lame_internal_flags_valid(gfc)) {
+            return calc_maximum_input_samples_for_buffer_size(gfc, buffer_size);
+        }
+    }
+    return LAME_GENERICERROR;
+}
diff --git a/lame/libmp3lame/set_get.h b/lame/libmp3lame/set_get.h
new file mode 100644 (file)
index 0000000..37e4bcd
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * set_get.h -- Internal set/get definitions
+ *
+ * Copyright (C) 2003 Gabriel Bouvigne / Lame project
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __SET_GET_H__
+#define __SET_GET_H__
+
+#include <lame.h>
+
+#if defined(__cplusplus)
+extern  "C" {
+#endif
+
+/* select psychoacoustic model */
+
+/* manage short blocks */
+    int CDECL lame_set_short_threshold(lame_global_flags *, float, float);
+    int CDECL lame_set_short_threshold_lrm(lame_global_flags *, float);
+    float CDECL lame_get_short_threshold_lrm(const lame_global_flags *);
+    int CDECL lame_set_short_threshold_s(lame_global_flags *, float);
+    float CDECL lame_get_short_threshold_s(const lame_global_flags *);
+
+
+    int CDECL lame_set_maskingadjust(lame_global_flags *, float);
+    float CDECL lame_get_maskingadjust(const lame_global_flags *);
+
+    int CDECL lame_set_maskingadjust_short(lame_global_flags *, float);
+    float CDECL lame_get_maskingadjust_short(const lame_global_flags *);
+
+/* select ATH formula 4 shape */
+    int CDECL lame_set_ATHcurve(lame_global_flags *, float);
+    float CDECL lame_get_ATHcurve(const lame_global_flags *);
+
+    int CDECL lame_set_preset_notune(lame_global_flags *, int);
+
+/* substep shaping method */
+    int CDECL lame_set_substep(lame_global_flags *, int);
+    int CDECL lame_get_substep(const lame_global_flags *);
+
+/* scalefactors scale */
+    int CDECL lame_set_sfscale(lame_global_flags *, int);
+    int CDECL lame_get_sfscale(const lame_global_flags *);
+
+/* subblock gain */
+    int CDECL lame_set_subblock_gain(lame_global_flags *, int);
+    int CDECL lame_get_subblock_gain(const lame_global_flags *);
+
+
+
+/*presets*/
+    int     apply_preset(lame_global_flags *, int preset, int enforce);
+
+    void CDECL lame_set_tune(lame_t, float); /* FOR INTERNAL USE ONLY */
+    void CDECL lame_set_msfix(lame_t gfp, double msfix);
+
+
+#if defined(__cplusplus)
+}
+#endif
+#endif
diff --git a/lame/libmp3lame/tables.c b/lame/libmp3lame/tables.c
new file mode 100644 (file)
index 0000000..a023099
--- /dev/null
@@ -0,0 +1,564 @@
+/*
+ *     MPEG layer 3 tables source file
+ *
+ *     Copyright (c) 1999 Albert L Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: tables.c,v 1.29 2011/05/07 16:05:17 rbrito Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "machine.h"
+
+#include "lame.h"
+#include "tables.h"
+
+
+static const uint16_t t1HB[] = {
+    1, 1,
+    1, 0
+};
+
+static const uint16_t t2HB[] = {
+    1, 2, 1,
+    3, 1, 1,
+    3, 2, 0
+};
+
+static const uint16_t t3HB[] = {
+    3, 2, 1,
+    1, 1, 1,
+    3, 2, 0
+};
+
+static const uint16_t t5HB[] = {
+    1, 2, 6, 5,
+    3, 1, 4, 4,
+    7, 5, 7, 1,
+    6, 1, 1, 0
+};
+
+static const uint16_t t6HB[] = {
+    7, 3, 5, 1,
+    6, 2, 3, 2,
+    5, 4, 4, 1,
+    3, 3, 2, 0
+};
+
+static const uint16_t t7HB[] = {
+    1, 2, 10, 19, 16, 10,
+    3, 3, 7, 10, 5, 3,
+    11, 4, 13, 17, 8, 4,
+    12, 11, 18, 15, 11, 2,
+    7, 6, 9, 14, 3, 1,
+    6, 4, 5, 3, 2, 0
+};
+
+static const uint16_t t8HB[] = {
+    3, 4, 6, 18, 12, 5,
+    5, 1, 2, 16, 9, 3,
+    7, 3, 5, 14, 7, 3,
+    19, 17, 15, 13, 10, 4,
+    13, 5, 8, 11, 5, 1,
+    12, 4, 4, 1, 1, 0
+};
+
+static const uint16_t t9HB[] = {
+    7, 5, 9, 14, 15, 7,
+    6, 4, 5, 5, 6, 7,
+    7, 6, 8, 8, 8, 5,
+    15, 6, 9, 10, 5, 1,
+    11, 7, 9, 6, 4, 1,
+    14, 4, 6, 2, 6, 0
+};
+
+static const uint16_t t10HB[] = {
+    1, 2, 10, 23, 35, 30, 12, 17,
+    3, 3, 8, 12, 18, 21, 12, 7,
+    11, 9, 15, 21, 32, 40, 19, 6,
+    14, 13, 22, 34, 46, 23, 18, 7,
+    20, 19, 33, 47, 27, 22, 9, 3,
+    31, 22, 41, 26, 21, 20, 5, 3,
+    14, 13, 10, 11, 16, 6, 5, 1,
+    9, 8, 7, 8, 4, 4, 2, 0
+};
+
+static const uint16_t t11HB[] = {
+    3, 4, 10, 24, 34, 33, 21, 15,
+    5, 3, 4, 10, 32, 17, 11, 10,
+    11, 7, 13, 18, 30, 31, 20, 5,
+    25, 11, 19, 59, 27, 18, 12, 5,
+    35, 33, 31, 58, 30, 16, 7, 5,
+    28, 26, 32, 19, 17, 15, 8, 14,
+    14, 12, 9, 13, 14, 9, 4, 1,
+    11, 4, 6, 6, 6, 3, 2, 0
+};
+
+static const uint16_t t12HB[] = {
+    9, 6, 16, 33, 41, 39, 38, 26,
+    7, 5, 6, 9, 23, 16, 26, 11,
+    17, 7, 11, 14, 21, 30, 10, 7,
+    17, 10, 15, 12, 18, 28, 14, 5,
+    32, 13, 22, 19, 18, 16, 9, 5,
+    40, 17, 31, 29, 17, 13, 4, 2,
+    27, 12, 11, 15, 10, 7, 4, 1,
+    27, 12, 8, 12, 6, 3, 1, 0
+};
+
+static const uint16_t t13HB[] = {
+    1, 5, 14, 21, 34, 51, 46, 71, 42, 52, 68, 52, 67, 44, 43, 19,
+    3, 4, 12, 19, 31, 26, 44, 33, 31, 24, 32, 24, 31, 35, 22, 14,
+    15, 13, 23, 36, 59, 49, 77, 65, 29, 40, 30, 40, 27, 33, 42, 16,
+    22, 20, 37, 61, 56, 79, 73, 64, 43, 76, 56, 37, 26, 31, 25, 14,
+    35, 16, 60, 57, 97, 75, 114, 91, 54, 73, 55, 41, 48, 53, 23, 24,
+    58, 27, 50, 96, 76, 70, 93, 84, 77, 58, 79, 29, 74, 49, 41, 17,
+    47, 45, 78, 74, 115, 94, 90, 79, 69, 83, 71, 50, 59, 38, 36, 15,
+    72, 34, 56, 95, 92, 85, 91, 90, 86, 73, 77, 65, 51, 44, 43, 42,
+    43, 20, 30, 44, 55, 78, 72, 87, 78, 61, 46, 54, 37, 30, 20, 16,
+    53, 25, 41, 37, 44, 59, 54, 81, 66, 76, 57, 54, 37, 18, 39, 11,
+    35, 33, 31, 57, 42, 82, 72, 80, 47, 58, 55, 21, 22, 26, 38, 22,
+    53, 25, 23, 38, 70, 60, 51, 36, 55, 26, 34, 23, 27, 14, 9, 7,
+    34, 32, 28, 39, 49, 75, 30, 52, 48, 40, 52, 28, 18, 17, 9, 5,
+    45, 21, 34, 64, 56, 50, 49, 45, 31, 19, 12, 15, 10, 7, 6, 3,
+    48, 23, 20, 39, 36, 35, 53, 21, 16, 23, 13, 10, 6, 1, 4, 2,
+    16, 15, 17, 27, 25, 20, 29, 11, 17, 12, 16, 8, 1, 1, 0, 1
+};
+
+static const uint16_t t15HB[] = {
+    7, 12, 18, 53, 47, 76, 124, 108, 89, 123, 108, 119, 107, 81, 122, 63,
+    13, 5, 16, 27, 46, 36, 61, 51, 42, 70, 52, 83, 65, 41, 59, 36,
+    19, 17, 15, 24, 41, 34, 59, 48, 40, 64, 50, 78, 62, 80, 56, 33,
+    29, 28, 25, 43, 39, 63, 55, 93, 76, 59, 93, 72, 54, 75, 50, 29,
+    52, 22, 42, 40, 67, 57, 95, 79, 72, 57, 89, 69, 49, 66, 46, 27,
+    77, 37, 35, 66, 58, 52, 91, 74, 62, 48, 79, 63, 90, 62, 40, 38,
+    125, 32, 60, 56, 50, 92, 78, 65, 55, 87, 71, 51, 73, 51, 70, 30,
+    109, 53, 49, 94, 88, 75, 66, 122, 91, 73, 56, 42, 64, 44, 21, 25,
+    90, 43, 41, 77, 73, 63, 56, 92, 77, 66, 47, 67, 48, 53, 36, 20,
+    71, 34, 67, 60, 58, 49, 88, 76, 67, 106, 71, 54, 38, 39, 23, 15,
+    109, 53, 51, 47, 90, 82, 58, 57, 48, 72, 57, 41, 23, 27, 62, 9,
+    86, 42, 40, 37, 70, 64, 52, 43, 70, 55, 42, 25, 29, 18, 11, 11,
+    118, 68, 30, 55, 50, 46, 74, 65, 49, 39, 24, 16, 22, 13, 14, 7,
+    91, 44, 39, 38, 34, 63, 52, 45, 31, 52, 28, 19, 14, 8, 9, 3,
+    123, 60, 58, 53, 47, 43, 32, 22, 37, 24, 17, 12, 15, 10, 2, 1,
+    71, 37, 34, 30, 28, 20, 17, 26, 21, 16, 10, 6, 8, 6, 2, 0
+};
+
+static const uint16_t t16HB[] = {
+    1, 5, 14, 44, 74, 63, 110, 93, 172, 149, 138, 242, 225, 195, 376, 17,
+    3, 4, 12, 20, 35, 62, 53, 47, 83, 75, 68, 119, 201, 107, 207, 9,
+    15, 13, 23, 38, 67, 58, 103, 90, 161, 72, 127, 117, 110, 209, 206, 16,
+    45, 21, 39, 69, 64, 114, 99, 87, 158, 140, 252, 212, 199, 387, 365, 26,
+    75, 36, 68, 65, 115, 101, 179, 164, 155, 264, 246, 226, 395, 382, 362, 9,
+    66, 30, 59, 56, 102, 185, 173, 265, 142, 253, 232, 400, 388, 378, 445, 16,
+    111, 54, 52, 100, 184, 178, 160, 133, 257, 244, 228, 217, 385, 366, 715, 10,
+    98, 48, 91, 88, 165, 157, 148, 261, 248, 407, 397, 372, 380, 889, 884, 8,
+    85, 84, 81, 159, 156, 143, 260, 249, 427, 401, 392, 383, 727, 713, 708, 7,
+    154, 76, 73, 141, 131, 256, 245, 426, 406, 394, 384, 735, 359, 710, 352, 11,
+    139, 129, 67, 125, 247, 233, 229, 219, 393, 743, 737, 720, 885, 882, 439, 4,
+    243, 120, 118, 115, 227, 223, 396, 746, 742, 736, 721, 712, 706, 223, 436, 6,
+    202, 224, 222, 218, 216, 389, 386, 381, 364, 888, 443, 707, 440, 437, 1728, 4,
+    747, 211, 210, 208, 370, 379, 734, 723, 714, 1735, 883, 877, 876, 3459, 865, 2,
+    377, 369, 102, 187, 726, 722, 358, 711, 709, 866, 1734, 871, 3458, 870, 434, 0,
+    12, 10, 7, 11, 10, 17, 11, 9, 13, 12, 10, 7, 5, 3, 1, 3
+};
+
+static const uint16_t t24HB[] = {
+    15, 13, 46, 80, 146, 262, 248, 434, 426, 669, 653, 649, 621, 517, 1032, 88,
+    14, 12, 21, 38, 71, 130, 122, 216, 209, 198, 327, 345, 319, 297, 279, 42,
+    47, 22, 41, 74, 68, 128, 120, 221, 207, 194, 182, 340, 315, 295, 541, 18,
+    81, 39, 75, 70, 134, 125, 116, 220, 204, 190, 178, 325, 311, 293, 271, 16,
+    147, 72, 69, 135, 127, 118, 112, 210, 200, 188, 352, 323, 306, 285, 540, 14,
+    263, 66, 129, 126, 119, 114, 214, 202, 192, 180, 341, 317, 301, 281, 262, 12,
+    249, 123, 121, 117, 113, 215, 206, 195, 185, 347, 330, 308, 291, 272, 520, 10,
+    435, 115, 111, 109, 211, 203, 196, 187, 353, 332, 313, 298, 283, 531, 381, 17,
+    427, 212, 208, 205, 201, 193, 186, 177, 169, 320, 303, 286, 268, 514, 377, 16,
+    335, 199, 197, 191, 189, 181, 174, 333, 321, 305, 289, 275, 521, 379, 371, 11,
+    668, 184, 183, 179, 175, 344, 331, 314, 304, 290, 277, 530, 383, 373, 366, 10,
+    652, 346, 171, 168, 164, 318, 309, 299, 287, 276, 263, 513, 375, 368, 362, 6,
+    648, 322, 316, 312, 307, 302, 292, 284, 269, 261, 512, 376, 370, 364, 359, 4,
+    620, 300, 296, 294, 288, 282, 273, 266, 515, 380, 374, 369, 365, 361, 357, 2,
+    1033, 280, 278, 274, 267, 264, 259, 382, 378, 372, 367, 363, 360, 358, 356, 0,
+    43, 20, 19, 17, 15, 13, 11, 9, 7, 6, 4, 7, 5, 3, 1, 3
+};
+
+static const uint16_t t32HB[] = {
+    1 << 0, 5 << 1, 4 << 1, 5 << 2, 6 << 1, 5 << 2, 4 << 2, 4 << 3,
+    7 << 1, 3 << 2, 6 << 2, 0 << 3, 7 << 2, 2 << 3, 3 << 3, 1 << 4
+};
+
+static const uint16_t t33HB[] = {
+    15 << 0, 14 << 1, 13 << 1, 12 << 2, 11 << 1, 10 << 2, 9 << 2, 8 << 3,
+    7 << 1, 6 << 2, 5 << 2, 4 << 3, 3 << 2, 2 << 3, 1 << 3, 0 << 4
+};
+
+
+const uint8_t t1l[] = {
+    1, 4,
+    3, 5
+};
+
+static const uint8_t t2l[] = {
+    1, 4, 7,
+    4, 5, 7,
+    6, 7, 8
+};
+
+static const uint8_t t3l[] = {
+    2, 3, 7,
+    4, 4, 7,
+    6, 7, 8
+};
+
+static const uint8_t t5l[] = {
+    1, 4, 7, 8,
+    4, 5, 8, 9,
+    7, 8, 9, 10,
+    8, 8, 9, 10
+};
+
+static const uint8_t t6l[] = {
+    3, 4, 6, 8,
+    4, 4, 6, 7,
+    5, 6, 7, 8,
+    7, 7, 8, 9
+};
+
+static const uint8_t t7l[] = {
+    1, 4, 7, 9, 9, 10,
+    4, 6, 8, 9, 9, 10,
+    7, 7, 9, 10, 10, 11,
+    8, 9, 10, 11, 11, 11,
+    8, 9, 10, 11, 11, 12,
+    9, 10, 11, 12, 12, 12
+};
+
+static const uint8_t t8l[] = {
+    2, 4, 7, 9, 9, 10,
+    4, 4, 6, 10, 10, 10,
+    7, 6, 8, 10, 10, 11,
+    9, 10, 10, 11, 11, 12,
+    9, 9, 10, 11, 12, 12,
+    10, 10, 11, 11, 13, 13
+};
+
+static const uint8_t t9l[] = {
+    3, 4, 6, 7, 9, 10,
+    4, 5, 6, 7, 8, 10,
+    5, 6, 7, 8, 9, 10,
+    7, 7, 8, 9, 9, 10,
+    8, 8, 9, 9, 10, 11,
+    9, 9, 10, 10, 11, 11
+};
+
+static const uint8_t t10l[] = {
+    1, 4, 7, 9, 10, 10, 10, 11,
+    4, 6, 8, 9, 10, 11, 10, 10,
+    7, 8, 9, 10, 11, 12, 11, 11,
+    8, 9, 10, 11, 12, 12, 11, 12,
+    9, 10, 11, 12, 12, 12, 12, 12,
+    10, 11, 12, 12, 13, 13, 12, 13,
+    9, 10, 11, 12, 12, 12, 13, 13,
+    10, 10, 11, 12, 12, 13, 13, 13
+};
+
+static const uint8_t t11l[] = {
+    2, 4, 6, 8, 9, 10, 9, 10,
+    4, 5, 6, 8, 10, 10, 9, 10,
+    6, 7, 8, 9, 10, 11, 10, 10,
+    8, 8, 9, 11, 10, 12, 10, 11,
+    9, 10, 10, 11, 11, 12, 11, 12,
+    9, 10, 11, 12, 12, 13, 12, 13,
+    9, 9, 9, 10, 11, 12, 12, 12,
+    9, 9, 10, 11, 12, 12, 12, 12
+};
+
+static const uint8_t t12l[] = {
+    4, 4, 6, 8, 9, 10, 10, 10,
+    4, 5, 6, 7, 9, 9, 10, 10,
+    6, 6, 7, 8, 9, 10, 9, 10,
+    7, 7, 8, 8, 9, 10, 10, 10,
+    8, 8, 9, 9, 10, 10, 10, 11,
+    9, 9, 10, 10, 10, 11, 10, 11,
+    9, 9, 9, 10, 10, 11, 11, 12,
+    10, 10, 10, 11, 11, 11, 11, 12
+};
+
+static const uint8_t t13l[] = {
+    1, 5, 7, 8, 9, 10, 10, 11, 10, 11, 12, 12, 13, 13, 14, 14,
+    4, 6, 8, 9, 10, 10, 11, 11, 11, 11, 12, 12, 13, 14, 14, 14,
+    7, 8, 9, 10, 11, 11, 12, 12, 11, 12, 12, 13, 13, 14, 15, 15,
+    8, 9, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 15,
+    9, 9, 11, 11, 12, 12, 13, 13, 12, 13, 13, 14, 14, 15, 15, 16,
+    10, 10, 11, 12, 12, 12, 13, 13, 13, 13, 14, 13, 15, 15, 16, 16,
+    10, 11, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16,
+    11, 11, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 18, 18,
+    10, 10, 11, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17,
+    11, 11, 12, 12, 13, 13, 13, 15, 14, 15, 15, 16, 16, 16, 18, 17,
+    11, 12, 12, 13, 13, 14, 14, 15, 14, 15, 16, 15, 16, 17, 18, 19,
+    12, 12, 12, 13, 14, 14, 14, 14, 15, 15, 15, 16, 17, 17, 17, 18,
+    12, 13, 13, 14, 14, 15, 14, 15, 16, 16, 17, 17, 17, 18, 18, 18,
+    13, 13, 14, 15, 15, 15, 16, 16, 16, 16, 16, 17, 18, 17, 18, 18,
+    14, 14, 14, 15, 15, 15, 17, 16, 16, 19, 17, 17, 17, 19, 18, 18,
+    13, 14, 15, 16, 16, 16, 17, 16, 17, 17, 18, 18, 21, 20, 21, 18
+};
+
+static const uint8_t t15l[] = {
+    3, 5, 6, 8, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 14,
+    5, 5, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 13,
+    6, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 13, 13,
+    7, 8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13,
+    8, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13,
+    9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14,
+    10, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14,
+    10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 14,
+    10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14,
+    10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14,
+    11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 14,
+    11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15,
+    12, 12, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 15, 15,
+    12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15,
+    13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 14, 15,
+    13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15
+};
+
+static const uint8_t t16_5l[] = {
+    1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 11,
+    4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 11,
+    7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 12,
+    9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 13,
+    10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 12,
+    10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 13,
+    11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 13,
+    11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 13,
+    11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 13,
+    12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 14,
+    12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 13,
+    13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 14,
+    13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 14,
+    15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 14,
+    14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 14,
+    11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 12
+};
+
+static const uint8_t t16l[] = {
+    1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 10,
+    4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 10,
+    7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 11,
+    9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 12,
+    10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 11,
+    10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 12,
+    11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 12,
+    11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 12,
+    11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 12,
+    12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 13,
+    12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 12,
+    13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 13,
+    13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 13,
+    15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 13,
+    14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 13,
+    10, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10
+};
+
+static const uint8_t t24l[] = {
+    4, 5, 7, 8, 9, 10, 10, 11, 11, 12, 12, 12, 12, 12, 13, 10,
+    5, 6, 7, 8, 9, 10, 10, 11, 11, 11, 12, 12, 12, 12, 12, 10,
+    7, 7, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 9,
+    8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 9,
+    9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 13, 9,
+    10, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 9,
+    10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 9,
+    11, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 10,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 10,
+    11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 10,
+    12, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10,
+    12, 12, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10,
+    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 10,
+    12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10,
+    13, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 10,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 6
+};
+
+const uint8_t t32l[] = {
+    1 + 0, 4 + 1, 4 + 1, 5 + 2, 4 + 1, 6 + 2, 5 + 2, 6 + 3,
+    4 + 1, 5 + 2, 5 + 2, 6 + 3, 5 + 2, 6 + 3, 6 + 3, 6 + 4
+};
+
+const uint8_t t33l[] = {
+    4 + 0, 4 + 1, 4 + 1, 4 + 2, 4 + 1, 4 + 2, 4 + 2, 4 + 3,
+    4 + 1, 4 + 2, 4 + 2, 4 + 3, 4 + 2, 4 + 3, 4 + 3, 4 + 4
+};
+
+
+const struct huffcodetab ht[HTN] = {
+    /* xlen, linmax, table, hlen */
+    {0, 0, NULL, NULL},
+    {2, 0, t1HB, t1l},
+    {3, 0, t2HB, t2l},
+    {3, 0, t3HB, t3l},
+    {0, 0, NULL, NULL}, /* Apparently not used */
+    {4, 0, t5HB, t5l},
+    {4, 0, t6HB, t6l},
+    {6, 0, t7HB, t7l},
+    {6, 0, t8HB, t8l},
+    {6, 0, t9HB, t9l},
+    {8, 0, t10HB, t10l},
+    {8, 0, t11HB, t11l},
+    {8, 0, t12HB, t12l},
+    {16, 0, t13HB, t13l},
+    {0, 0, NULL, t16_5l}, /* Apparently not used */
+    {16, 0, t15HB, t15l},
+
+    {1, 1, t16HB, t16l},
+    {2, 3, t16HB, t16l},
+    {3, 7, t16HB, t16l},
+    {4, 15, t16HB, t16l},
+    {6, 63, t16HB, t16l},
+    {8, 255, t16HB, t16l},
+    {10, 1023, t16HB, t16l},
+    {13, 8191, t16HB, t16l},
+
+    {4, 15, t24HB, t24l},
+    {5, 31, t24HB, t24l},
+    {6, 63, t24HB, t24l},
+    {7, 127, t24HB, t24l},
+    {8, 255, t24HB, t24l},
+    {9, 511, t24HB, t24l},
+    {11, 2047, t24HB, t24l},
+    {13, 8191, t24HB, t24l},
+
+    {0, 0, t32HB, t32l},
+    {0, 0, t33HB, t33l},
+};
+
+
+
+
+
+/*  for (i = 0; i < 16*16; i++) {
+ *      largetbl[i] = ((ht[16].hlen[i]) << 16) + ht[24].hlen[i];
+ *  }
+ */
+const uint32_t largetbl[16 * 16] = {
+    0x010004, 0x050005, 0x070007, 0x090008, 0x0a0009, 0x0a000a, 0x0b000a, 0x0b000b,
+    0x0c000b, 0x0c000c, 0x0c000c, 0x0d000c, 0x0d000c, 0x0d000c, 0x0e000d, 0x0a000a,
+    0x040005, 0x060006, 0x080007, 0x090008, 0x0a0009, 0x0b000a, 0x0b000a, 0x0b000b,
+    0x0c000b, 0x0c000b, 0x0c000c, 0x0d000c, 0x0e000c, 0x0d000c, 0x0e000c, 0x0a000a,
+    0x070007, 0x080007, 0x090008, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000b,
+    0x0d000b, 0x0c000b, 0x0d000b, 0x0d000c, 0x0d000c, 0x0e000c, 0x0e000d, 0x0b0009,
+    0x090008, 0x090008, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000a, 0x0c000b,
+    0x0d000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0c0009,
+    0x0a0009, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000a, 0x0d000a, 0x0d000b,
+    0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000d, 0x0b0009,
+    0x0a000a, 0x0a0009, 0x0b000a, 0x0b000a, 0x0c000a, 0x0d000a, 0x0d000b, 0x0e000b,
+    0x0d000b, 0x0e000b, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x0c0009,
+    0x0b000a, 0x0b000a, 0x0b000a, 0x0c000a, 0x0d000a, 0x0d000b, 0x0d000b, 0x0d000b,
+    0x0e000b, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x10000d, 0x0c0009,
+    0x0b000b, 0x0b000a, 0x0c000a, 0x0c000a, 0x0d000b, 0x0d000b, 0x0d000b, 0x0e000b,
+    0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x11000d, 0x11000d, 0x0c000a,
+    0x0b000b, 0x0c000b, 0x0c000b, 0x0d000b, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000b,
+    0x0f000b, 0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x10000d, 0x10000d, 0x0c000a,
+    0x0c000b, 0x0c000b, 0x0c000b, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000b, 0x0f000c,
+    0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x0f000d, 0x10000d, 0x0f000d, 0x0d000a,
+    0x0c000c, 0x0d000b, 0x0c000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0e000c,
+    0x0f000c, 0x10000c, 0x10000c, 0x10000d, 0x11000d, 0x11000d, 0x10000d, 0x0c000a,
+    0x0d000c, 0x0d000c, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0f000c, 0x10000c,
+    0x10000c, 0x10000c, 0x10000c, 0x10000d, 0x10000d, 0x0f000d, 0x10000d, 0x0d000a,
+    0x0d000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c,
+    0x0f000c, 0x11000c, 0x10000d, 0x10000d, 0x10000d, 0x10000d, 0x12000d, 0x0d000a,
+    0x0f000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x10000c, 0x10000c,
+    0x10000d, 0x12000d, 0x11000d, 0x11000d, 0x11000d, 0x13000d, 0x11000d, 0x0d000a,
+    0x0e000d, 0x0f000c, 0x0d000c, 0x0e000c, 0x10000c, 0x10000c, 0x0f000c, 0x10000d,
+    0x10000d, 0x11000d, 0x12000d, 0x11000d, 0x13000d, 0x11000d, 0x10000d, 0x0d000a,
+    0x0a0009, 0x0a0009, 0x0a0009, 0x0b0009, 0x0b0009, 0x0c0009, 0x0c0009, 0x0c0009,
+    0x0d0009, 0x0d0009, 0x0d0009, 0x0d000a, 0x0d000a, 0x0d000a, 0x0d000a, 0x0a0006
+};
+
+/*  for (i = 0; i < 3*3; i++) {
+ *      table23[i] = ((ht[2].hlen[i]) << 16) + ht[3].hlen[i];
+ *  }
+ */
+const uint32_t table23[3 * 3] = {
+    0x010002, 0x040003, 0x070007,
+    0x040004, 0x050004, 0x070007,
+    0x060006, 0x070007, 0x080008
+};
+
+/*   for (i = 0; i < 4*4; i++) {
+ *       table56[i] = ((ht[5].hlen[i]) << 16) + ht[6].hlen[i];
+ *   }
+ */
+const uint32_t table56[4 * 4] = {
+    0x010003, 0x040004, 0x070006, 0x080008, 0x040004, 0x050004, 0x080006, 0x090007,
+    0x070005, 0x080006, 0x090007, 0x0a0008, 0x080007, 0x080007, 0x090008, 0x0a0009
+};
+
+
+
+/* 
+ * 0: MPEG-2 LSF
+ * 1: MPEG-1
+ * 2: MPEG-2.5 LSF FhG extention                  (1995-07-11 shn)
+ */
+
+typedef enum {
+    MPEG_2 = 0,
+    MPEG_1 = 1,
+    MPEG_25 = 2
+} MPEG_t;
+
+const int bitrate_table[3][16] = {
+    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1}, /* MPEG 2 */
+    {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1}, /* MPEG 1 */
+    {0, 8, 16, 24, 32, 40, 48, 56, 64, -1, -1, -1, -1, -1, -1, -1}, /* MPEG 2.5 */
+};
+
+const int samplerate_table[3][4] = {
+    {22050, 24000, 16000, -1}, /* MPEG 2 */
+    {44100, 48000, 32000, -1}, /* MPEG 1 */
+    {11025, 12000, 8000, -1}, /* MPEG 2.5 */
+};
+
+int
+lame_get_bitrate(int mpeg_version, int table_index)
+{
+    if (0 <= mpeg_version && mpeg_version <= 2) {
+        if (0 <= table_index && table_index <= 15) {
+            return bitrate_table[mpeg_version][table_index];
+        }
+    }
+    return -1;
+}
+
+int
+lame_get_samplerate(int mpeg_version, int table_index)
+{
+    if (0 <= mpeg_version && mpeg_version <= 2) {
+        if (0 <= table_index && table_index <= 3) {
+            return samplerate_table[mpeg_version][table_index];
+        }
+    }
+    return -1;
+}
+
+
+/* This is the scfsi_band table from 2.4.2.7 of the IS */
+const int scfsi_band[5] = { 0, 6, 11, 16, 21 };
+
+/* end of tables.c */
diff --git a/lame/libmp3lame/tables.h b/lame/libmp3lame/tables.h
new file mode 100644 (file)
index 0000000..0dd7deb
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ *     MPEG layer 3 tables include file
+ *
+ *     Copyright (c) 1999 Albert L Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_TABLES_H
+#define LAME_TABLES_H
+
+#if 0
+typedef struct {
+    unsigned char no;
+    unsigned char width;
+    unsigned char minval_2;
+    float   quiet_thr;
+    float   norm;
+    float   bark;
+} type1_t;
+
+typedef struct {
+    unsigned char no;
+    unsigned char width;
+    float   quiet_thr;
+    float   norm;
+    float   SNR;
+    float   bark;
+} type2_t;
+
+typedef struct {
+    unsigned int no:5;
+    unsigned int cbw:3;
+    unsigned int bu:6;
+    unsigned int bo:6;
+    unsigned int w1_576:10;
+    unsigned int w2_576:10;
+} type34_t;
+
+typedef struct {
+    size_t  len1;
+    const type1_t *const tab1;
+    size_t  len2;
+    const type2_t *const tab2;
+    size_t  len3;
+    const type34_t *const tab3;
+    size_t  len4;
+    const type34_t *const tab4;
+} type5_t;
+
+extern const type5_t table5[6];
+
+#endif
+
+#define HTN    34
+
+struct huffcodetab {
+    const unsigned int xlen;          /* max. x-index+   */
+    const unsigned int linmax;        /* max number to be stored in linbits */
+    const uint16_t *table;      /* pointer to array[xlen][ylen]  */
+    const uint8_t *hlen;        /* pointer to array[xlen][ylen]  */
+};
+
+extern const struct huffcodetab ht[HTN];
+    /* global memory block   */
+    /* array of all huffcodtable headers */
+    /* 0..31 Huffman code table 0..31  */
+    /* 32,33 count1-tables   */
+
+extern const uint8_t t32l[];
+extern const uint8_t t33l[];
+
+extern const uint32_t largetbl[16 * 16];
+extern const uint32_t table23[3 * 3];
+extern const uint32_t table56[4 * 4];
+
+extern const int scfsi_band[5];
+
+extern const int bitrate_table    [3][16];
+extern const int samplerate_table [3][ 4];
+
+#endif /* LAME_TABLES_H */
diff --git a/lame/libmp3lame/takehiro.c b/lame/libmp3lame/takehiro.c
new file mode 100644 (file)
index 0000000..67aba1b
--- /dev/null
@@ -0,0 +1,1375 @@
+/*
+ *     MP3 huffman table selecting and bit counting
+ *
+ *     Copyright (c) 1999-2005 Takehiro TOMINAGA
+ *     Copyright (c) 2002-2005 Gabriel Bouvigne
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: takehiro.c,v 1.80 2017/09/06 15:07:30 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "quantize_pvt.h"
+#include "tables.h"
+
+
+static const struct {
+    const int region0_count;
+    const int region1_count;
+} subdv_table[23] = {
+    {
+    0, 0},              /* 0 bands */
+    {
+    0, 0},              /* 1 bands */
+    {
+    0, 0},              /* 2 bands */
+    {
+    0, 0},              /* 3 bands */
+    {
+    0, 0},              /* 4 bands */
+    {
+    0, 1},              /* 5 bands */
+    {
+    1, 1},              /* 6 bands */
+    {
+    1, 1},              /* 7 bands */
+    {
+    1, 2},              /* 8 bands */
+    {
+    2, 2},              /* 9 bands */
+    {
+    2, 3},              /* 10 bands */
+    {
+    2, 3},              /* 11 bands */
+    {
+    3, 4},              /* 12 bands */
+    {
+    3, 4},              /* 13 bands */
+    {
+    3, 4},              /* 14 bands */
+    {
+    4, 5},              /* 15 bands */
+    {
+    4, 5},              /* 16 bands */
+    {
+    4, 6},              /* 17 bands */
+    {
+    5, 6},              /* 18 bands */
+    {
+    5, 6},              /* 19 bands */
+    {
+    5, 7},              /* 20 bands */
+    {
+    6, 7},              /* 21 bands */
+    {
+    6, 7},              /* 22 bands */
+};
+
+
+
+
+
+/*********************************************************************
+ * nonlinear quantization of xr 
+ * More accurate formula than the ISO formula.  Takes into account
+ * the fact that we are quantizing xr -> ix, but we want ix^4/3 to be 
+ * as close as possible to x^4/3.  (taking the nearest int would mean
+ * ix is as close as possible to xr, which is different.)
+ *
+ * From Segher Boessenkool <segher@eastsite.nl>  11/1999
+ *
+ * 09/2000: ASM code removed in favor of IEEE754 hack by Takehiro
+ * Tominaga. If you need the ASM code, check CVS circa Aug 2000.
+ *
+ * 01/2004: Optimizations by Gabriel Bouvigne
+ *********************************************************************/
+
+
+
+
+
+static void
+quantize_lines_xrpow_01(unsigned int l, FLOAT istep, const FLOAT * xr, int *ix)
+{
+    const FLOAT compareval0 = (1.0f - 0.4054f) / istep;
+    unsigned int i;
+
+    assert(l > 0);
+    assert(l % 2 == 0);
+    for (i = 0; i < l; i += 2) {
+        FLOAT const xr_0 = xr[i+0];
+        FLOAT const xr_1 = xr[i+1];
+        int const ix_0 = (compareval0 > xr_0) ? 0 : 1;
+        int const ix_1 = (compareval0 > xr_1) ? 0 : 1;
+        ix[i+0] = ix_0;
+        ix[i+1] = ix_1;
+    }
+}
+
+
+
+#ifdef TAKEHIRO_IEEE754_HACK
+
+typedef union {
+    float   f;
+    int     i;
+} fi_union;
+
+#define MAGIC_FLOAT (65536*(128))
+#define MAGIC_INT 0x4b000000
+
+
+static void
+quantize_lines_xrpow(unsigned int l, FLOAT istep, const FLOAT * xp, int *pi)
+{
+    fi_union *fi;
+    unsigned int remaining;
+
+    assert(l > 0);
+
+    fi = (fi_union *) pi;
+
+    l = l >> 1;
+    remaining = l % 2;
+    l = l >> 1;
+    while (l--) {
+        double  x0 = istep * xp[0];
+        double  x1 = istep * xp[1];
+        double  x2 = istep * xp[2];
+        double  x3 = istep * xp[3];
+
+        x0 += MAGIC_FLOAT;
+        fi[0].f = x0;
+        x1 += MAGIC_FLOAT;
+        fi[1].f = x1;
+        x2 += MAGIC_FLOAT;
+        fi[2].f = x2;
+        x3 += MAGIC_FLOAT;
+        fi[3].f = x3;
+
+        fi[0].f = x0 + adj43asm[fi[0].i - MAGIC_INT];
+        fi[1].f = x1 + adj43asm[fi[1].i - MAGIC_INT];
+        fi[2].f = x2 + adj43asm[fi[2].i - MAGIC_INT];
+        fi[3].f = x3 + adj43asm[fi[3].i - MAGIC_INT];
+
+        fi[0].i -= MAGIC_INT;
+        fi[1].i -= MAGIC_INT;
+        fi[2].i -= MAGIC_INT;
+        fi[3].i -= MAGIC_INT;
+        fi += 4;
+        xp += 4;
+    };
+    if (remaining) {
+        double  x0 = istep * xp[0];
+        double  x1 = istep * xp[1];
+
+        x0 += MAGIC_FLOAT;
+        fi[0].f = x0;
+        x1 += MAGIC_FLOAT;
+        fi[1].f = x1;
+
+        fi[0].f = x0 + adj43asm[fi[0].i - MAGIC_INT];
+        fi[1].f = x1 + adj43asm[fi[1].i - MAGIC_INT];
+
+        fi[0].i -= MAGIC_INT;
+        fi[1].i -= MAGIC_INT;
+    }
+
+}
+
+
+#else
+
+/*********************************************************************
+ * XRPOW_FTOI is a macro to convert floats to ints.  
+ * if XRPOW_FTOI(x) = nearest_int(x), then QUANTFAC(x)=adj43asm[x]
+ *                                         ROUNDFAC= -0.0946
+ *
+ * if XRPOW_FTOI(x) = floor(x), then QUANTFAC(x)=asj43[x]   
+ *                                   ROUNDFAC=0.4054
+ *
+ * Note: using floor() or (int) is extremely slow. On machines where
+ * the TAKEHIRO_IEEE754_HACK code above does not work, it is worthwile
+ * to write some ASM for XRPOW_FTOI().  
+ *********************************************************************/
+#define XRPOW_FTOI(src,dest) ((dest) = (int)(src))
+#define QUANTFAC(rx)  adj43[rx]
+#define ROUNDFAC 0.4054
+
+
+static void
+quantize_lines_xrpow(unsigned int l, FLOAT istep, const FLOAT * xr, int *ix)
+{
+    unsigned int remaining;
+
+    assert(l > 0);
+
+    l = l >> 1;
+    remaining = l % 2;
+    l = l >> 1;
+    while (l--) {
+        FLOAT   x0, x1, x2, x3;
+        int     rx0, rx1, rx2, rx3;
+
+        x0 = *xr++ * istep;
+        x1 = *xr++ * istep;
+        XRPOW_FTOI(x0, rx0);
+        x2 = *xr++ * istep;
+        XRPOW_FTOI(x1, rx1);
+        x3 = *xr++ * istep;
+        XRPOW_FTOI(x2, rx2);
+        x0 += QUANTFAC(rx0);
+        XRPOW_FTOI(x3, rx3);
+        x1 += QUANTFAC(rx1);
+        XRPOW_FTOI(x0, *ix++);
+        x2 += QUANTFAC(rx2);
+        XRPOW_FTOI(x1, *ix++);
+        x3 += QUANTFAC(rx3);
+        XRPOW_FTOI(x2, *ix++);
+        XRPOW_FTOI(x3, *ix++);
+    };
+    if (remaining) {
+        FLOAT   x0, x1;
+        int     rx0, rx1;
+
+        x0 = *xr++ * istep;
+        x1 = *xr++ * istep;
+        XRPOW_FTOI(x0, rx0);
+        XRPOW_FTOI(x1, rx1);
+        x0 += QUANTFAC(rx0);
+        x1 += QUANTFAC(rx1);
+        XRPOW_FTOI(x0, *ix++);
+        XRPOW_FTOI(x1, *ix++);
+    }
+
+}
+
+
+
+#endif
+
+
+
+/*********************************************************************
+ * Quantization function
+ * This function will select which lines to quantize and call the
+ * proper quantization function
+ *********************************************************************/
+
+static void
+quantize_xrpow(const FLOAT * xp, int *pi, FLOAT istep, gr_info const *const cod_info,
+               calc_noise_data const *prev_noise)
+{
+    /* quantize on xr^(3/4) instead of xr */
+    int     sfb;
+    int     sfbmax;
+    int     j = 0;
+    int     prev_data_use;
+    int    *iData;
+    int     accumulate = 0;
+    int     accumulate01 = 0;
+    int    *acc_iData;
+    const FLOAT *acc_xp;
+
+    iData = pi;
+    acc_xp = xp;
+    acc_iData = iData;
+
+
+    /* Reusing previously computed data does not seems to work if global gain
+       is changed. Finding why it behaves this way would allow to use a cache of 
+       previously computed values (let's 10 cached values per sfb) that would 
+       probably provide a noticeable speedup */
+    prev_data_use = (prev_noise && (cod_info->global_gain == prev_noise->global_gain));
+
+    if (cod_info->block_type == SHORT_TYPE)
+        sfbmax = 38;
+    else
+        sfbmax = 21;
+
+    for (sfb = 0; sfb <= sfbmax; sfb++) {
+        int     step = -1;
+
+        if (prev_data_use || cod_info->block_type == NORM_TYPE) {
+            step =
+                cod_info->global_gain
+                - ((cod_info->scalefac[sfb] + (cod_info->preflag ? pretab[sfb] : 0))
+                   << (cod_info->scalefac_scale + 1))
+                - cod_info->subblock_gain[cod_info->window[sfb]] * 8;
+        }
+        assert(cod_info->width[sfb] >= 0);
+        if (prev_data_use && (prev_noise->step[sfb] == step)) {
+            /* do not recompute this part,
+               but compute accumulated lines */
+            if (accumulate) {
+                quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);
+                accumulate = 0;
+            }
+            if (accumulate01) {
+                quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);
+                accumulate01 = 0;
+            }
+        }
+        else {          /*should compute this part */
+            int     l;
+            l = cod_info->width[sfb];
+
+            if ((j + cod_info->width[sfb]) > cod_info->max_nonzero_coeff) {
+                /*do not compute upper zero part */
+                int     usefullsize;
+                usefullsize = cod_info->max_nonzero_coeff - j + 1;
+                memset(&pi[cod_info->max_nonzero_coeff], 0,
+                       sizeof(int) * (576 - cod_info->max_nonzero_coeff));
+                l = usefullsize;
+
+                if (l < 0) {
+                    l = 0;
+                }
+
+                /* no need to compute higher sfb values */
+                sfb = sfbmax + 1;
+            }
+
+            /*accumulate lines to quantize */
+            if (!accumulate && !accumulate01) {
+                acc_iData = iData;
+                acc_xp = xp;
+            }
+            if (prev_noise &&
+                prev_noise->sfb_count1 > 0 &&
+                sfb >= prev_noise->sfb_count1 &&
+                prev_noise->step[sfb] > 0 && step >= prev_noise->step[sfb]) {
+
+                if (accumulate) {
+                    quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);
+                    accumulate = 0;
+                    acc_iData = iData;
+                    acc_xp = xp;
+                }
+                accumulate01 += l;
+            }
+            else {
+                if (accumulate01) {
+                    quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);
+                    accumulate01 = 0;
+                    acc_iData = iData;
+                    acc_xp = xp;
+                }
+                accumulate += l;
+            }
+
+            if (l <= 0) {
+                /*  rh: 20040215
+                 *  may happen due to "prev_data_use" optimization 
+                 */
+                if (accumulate01) {
+                    quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);
+                    accumulate01 = 0;
+                }
+                if (accumulate) {
+                    quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);
+                    accumulate = 0;
+                }
+
+                break;  /* ends for-loop */
+            }
+        }
+        if (sfb <= sfbmax) {
+            iData += cod_info->width[sfb];
+            xp += cod_info->width[sfb];
+            j += cod_info->width[sfb];
+        }
+    }
+    if (accumulate) {   /*last data part */
+        quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);
+        accumulate = 0;
+    }
+    if (accumulate01) { /*last data part */
+        quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);
+        accumulate01 = 0;
+    }
+
+}
+
+
+
+
+/*************************************************************************/
+/*           ix_max                                                     */
+/*************************************************************************/
+
+static int
+ix_max(const int *ix, const int *end)
+{
+    int     max1 = 0, max2 = 0;
+
+    do {
+        int const x1 = *ix++;
+        int const x2 = *ix++;
+        if (max1 < x1)
+            max1 = x1;
+
+        if (max2 < x2)
+            max2 = x2;
+    } while (ix < end);
+    if (max1 < max2)
+        max1 = max2;
+    return max1;
+}
+
+
+
+
+
+
+
+
+static int
+count_bit_ESC(const int *ix, const int *const end, int t1, const int t2, unsigned int *const s)
+{
+    /* ESC-table is used */
+    unsigned int const linbits = ht[t1].xlen * 65536u + ht[t2].xlen;
+    unsigned int sum = 0, sum2;
+
+    do {
+        unsigned int x = *ix++;
+        unsigned int y = *ix++;
+
+        if (x >= 15u) {
+            x = 15u;
+            sum += linbits;
+        }
+        if (y >= 15u) {
+            y = 15u;
+            sum += linbits;
+        }
+        x <<= 4u;
+        x += y;
+        sum += largetbl[x];
+    } while (ix < end);
+
+    sum2 = sum & 0xffffu;
+    sum >>= 16u;
+
+    if (sum > sum2) {
+        sum = sum2;
+        t1 = t2;
+    }
+
+    *s += sum;
+    return t1;
+}
+
+
+static int
+count_bit_noESC(const int *ix, const int *end, int mx, unsigned int *s)
+{
+    /* No ESC-words */
+    unsigned int sum1 = 0;
+    const uint8_t *const hlen1 = ht[1].hlen;
+    (void) mx;
+
+    do {
+        unsigned int const x0 = *ix++;
+        unsigned int const x1 = *ix++;
+        sum1 += hlen1[ x0+x0 + x1 ];
+    } while (ix < end);
+
+    *s += sum1;
+    return 1;
+}
+
+
+static const int huf_tbl_noESC[] = {
+    1, 2, 5, 7, 7, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13
+};
+
+
+static int
+count_bit_noESC_from2(const int *ix, const int *end, int max, unsigned int *s)
+{
+    int t1 = huf_tbl_noESC[max - 1];
+    /* No ESC-words */
+    const unsigned int xlen = ht[t1].xlen;
+    uint32_t const* table = (t1 == 2) ? &table23[0] : &table56[0];
+    unsigned int sum = 0, sum2;
+
+    do {
+        unsigned int const x0 = *ix++;
+        unsigned int const x1 = *ix++;
+        sum += table[ x0 * xlen + x1 ];
+    } while (ix < end);
+
+    sum2 = sum & 0xffffu;
+    sum >>= 16u;
+
+    if (sum > sum2) {
+        sum = sum2;
+        t1++;
+    }
+
+    *s += sum;
+    return t1;
+}
+
+
+inline static int
+count_bit_noESC_from3(const int *ix, const int *end, int max, unsigned int * s)
+{
+    int t1 = huf_tbl_noESC[max - 1];
+    /* No ESC-words */
+    unsigned int sum1 = 0;
+    unsigned int sum2 = 0;
+    unsigned int sum3 = 0;
+    const unsigned int xlen = ht[t1].xlen;
+    const uint8_t *const hlen1 = ht[t1].hlen;
+    const uint8_t *const hlen2 = ht[t1 + 1].hlen;
+    const uint8_t *const hlen3 = ht[t1 + 2].hlen;
+    int     t;
+
+    do {
+        unsigned int x0 = *ix++;
+        unsigned int x1 = *ix++;
+        unsigned int x = x0 * xlen + x1;
+        sum1 += hlen1[x];
+        sum2 += hlen2[x];
+        sum3 += hlen3[x];
+    } while (ix < end);
+
+    t = t1;
+    if (sum1 > sum2) {
+        sum1 = sum2;
+        t++;
+    }
+    if (sum1 > sum3) {
+        sum1 = sum3;
+        t = t1 + 2;
+    }
+    *s += sum1;
+
+    return t;  
+}
+
+
+/*************************************************************************/
+/*           choose table                                               */
+/*************************************************************************/
+
+/*
+  Choose the Huffman table that will encode ix[begin..end] with
+  the fewest bits.
+
+  Note: This code contains knowledge about the sizes and characteristics
+  of the Huffman tables as defined in the IS (Table B.7), and will not work
+  with any arbitrary tables.
+*/
+static int count_bit_null(const int* ix, const int* end, int max, unsigned int* s)
+{
+    (void) ix;
+    (void) end;
+    (void) max;
+    (void) s;
+    return 0;
+}
+
+typedef int (*count_fnc)(const int* ix, const int* end, int max, unsigned int* s);
+  
+static const count_fnc count_fncs[] = 
+{ &count_bit_null
+, &count_bit_noESC
+, &count_bit_noESC_from2
+, &count_bit_noESC_from2
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+, &count_bit_noESC_from3
+};
+
+static int
+choose_table_nonMMX(const int *ix, const int *const end, int *const _s)
+{
+    unsigned int* s = (unsigned int*)_s;
+    unsigned int  max;
+    int     choice, choice2;
+    max = ix_max(ix, end);
+
+    if (max <= 15) {
+      return count_fncs[max](ix, end, max, s);
+    }
+    /* try tables with linbits */
+    if (max > IXMAX_VAL) {
+        *s = LARGE_BITS;
+        return -1;
+    }
+    max -= 15u;
+    for (choice2 = 24; choice2 < 32; choice2++) {
+        if (ht[choice2].linmax >= max) {
+            break;
+        }
+    }
+
+    for (choice = choice2 - 8; choice < 24; choice++) {
+        if (ht[choice].linmax >= max) {
+            break;
+        }
+    }
+    return count_bit_ESC(ix, end, choice, choice2, s);
+}
+
+
+
+/*************************************************************************/
+/*           count_bit                                                  */
+/*************************************************************************/
+int
+noquant_count_bits(lame_internal_flags const *const gfc,
+                   gr_info * const gi, calc_noise_data * prev_noise)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     bits = 0;
+    int     i, a1, a2;
+    int const *const ix = gi->l3_enc;
+
+    i = Min(576, ((gi->max_nonzero_coeff + 2) >> 1) << 1);
+
+    if (prev_noise)
+        prev_noise->sfb_count1 = 0;
+
+    /* Determine count1 region */
+    for (; i > 1; i -= 2)
+        if (ix[i - 1] | ix[i - 2])
+            break;
+    gi->count1 = i;
+
+    /* Determines the number of bits to encode the quadruples. */
+    a1 = a2 = 0;
+    for (; i > 3; i -= 4) {
+        int x4 = ix[i-4];
+        int x3 = ix[i-3];
+        int x2 = ix[i-2];
+        int x1 = ix[i-1];
+        int     p;
+        /* hack to check if all values <= 1 */
+        if ((unsigned int) (x4 | x3 | x2 | x1) > 1)
+            break;
+
+        p = ((x4 * 2 + x3) * 2 + x2) * 2 + x1;
+        a1 += t32l[p];
+        a2 += t33l[p];
+    }
+
+    bits = a1;
+    gi->count1table_select = 0;
+    if (a1 > a2) {
+        bits = a2;
+        gi->count1table_select = 1;
+    }
+
+    gi->count1bits = bits;
+    gi->big_values = i;
+    if (i == 0)
+        return bits;
+
+    if (gi->block_type == SHORT_TYPE) {
+        a1 = 3 * gfc->scalefac_band.s[3];
+        if (a1 > gi->big_values)
+            a1 = gi->big_values;
+        a2 = gi->big_values;
+
+    }
+    else if (gi->block_type == NORM_TYPE) {
+        assert(i <= 576); /* bv_scf has 576 entries (0..575) */
+        a1 = gi->region0_count = gfc->sv_qnt.bv_scf[i - 2];
+        a2 = gi->region1_count = gfc->sv_qnt.bv_scf[i - 1];
+
+        assert(a1 + a2 + 2 < SBPSY_l);
+        a2 = gfc->scalefac_band.l[a1 + a2 + 2];
+        a1 = gfc->scalefac_band.l[a1 + 1];
+        if (a2 < i)
+            gi->table_select[2] = gfc->choose_table(ix + a2, ix + i, &bits);
+
+    }
+    else {
+        gi->region0_count = 7;
+        /*gi->region1_count = SBPSY_l - 7 - 1; */
+        gi->region1_count = SBMAX_l - 1 - 7 - 1;
+        a1 = gfc->scalefac_band.l[7 + 1];
+        a2 = i;
+        if (a1 > a2) {
+            a1 = a2;
+        }
+    }
+
+
+    /* have to allow for the case when bigvalues < region0 < region1 */
+    /* (and region0, region1 are ignored) */
+    a1 = Min(a1, i);
+    a2 = Min(a2, i);
+
+    assert(a1 >= 0);
+    assert(a2 >= 0);
+
+    /* Count the number of bits necessary to code the bigvalues region. */
+    if (0 < a1)
+        gi->table_select[0] = gfc->choose_table(ix, ix + a1, &bits);
+    if (a1 < a2)
+        gi->table_select[1] = gfc->choose_table(ix + a1, ix + a2, &bits);
+    if (cfg->use_best_huffman == 2) {
+        gi->part2_3_length = bits;
+        best_huffman_divide(gfc, gi);
+        bits = gi->part2_3_length;
+    }
+
+
+    if (prev_noise) {
+        if (gi->block_type == NORM_TYPE) {
+            int     sfb = 0;
+            while (gfc->scalefac_band.l[sfb] < gi->big_values) {
+                sfb++;
+            }
+            prev_noise->sfb_count1 = sfb;
+        }
+    }
+
+    return bits;
+}
+
+int
+count_bits(lame_internal_flags const *const gfc,
+           const FLOAT * const xr, gr_info * const gi, calc_noise_data * prev_noise)
+{
+    int    *const ix = gi->l3_enc;
+
+    /* since quantize_xrpow uses table lookup, we need to check this first: */
+    FLOAT const w = (IXMAX_VAL) / IPOW20(gi->global_gain);
+
+    if (gi->xrpow_max > w)
+        return LARGE_BITS;
+
+    quantize_xrpow(xr, ix, IPOW20(gi->global_gain), gi, prev_noise);
+
+    if (gfc->sv_qnt.substep_shaping & 2) {
+        int     sfb, j = 0;
+        /* 0.634521682242439 = 0.5946*2**(.5*0.1875) */
+        int const gain = gi->global_gain + gi->scalefac_scale;
+        const FLOAT roundfac = 0.634521682242439 / IPOW20(gain);
+        for (sfb = 0; sfb < gi->sfbmax; sfb++) {
+            int const width = gi->width[sfb];
+            assert(width >= 0);
+            if (!gfc->sv_qnt.pseudohalf[sfb]) {
+                j += width;
+            }
+            else {
+                int     k;
+                for (k = j, j += width; k < j; ++k) {
+                    ix[k] = (xr[k] >= roundfac) ? ix[k] : 0;
+                }
+            }
+        }
+    }
+    return noquant_count_bits(gfc, gi, prev_noise);
+}
+
+/***********************************************************************
+  re-calculate the best scalefac_compress using scfsi
+  the saved bits are kept in the bit reservoir.
+ **********************************************************************/
+
+
+inline static void
+recalc_divide_init(const lame_internal_flags * const gfc,
+                   gr_info const *cod_info,
+                   int const *const ix, int r01_bits[], int r01_div[], int r0_tbl[], int r1_tbl[])
+{
+    int     r0, r1, bigv, r0t, r1t, bits;
+
+    bigv = cod_info->big_values;
+
+    for (r0 = 0; r0 <= 7 + 15; r0++) {
+        r01_bits[r0] = LARGE_BITS;
+    }
+
+    for (r0 = 0; r0 < 16; r0++) {
+        int const a1 = gfc->scalefac_band.l[r0 + 1];
+        int     r0bits;
+        if (a1 >= bigv)
+            break;
+        r0bits = 0;
+        r0t = gfc->choose_table(ix, ix + a1, &r0bits);
+
+        for (r1 = 0; r1 < 8; r1++) {
+            int const a2 = gfc->scalefac_band.l[r0 + r1 + 2];
+            if (a2 >= bigv)
+                break;
+
+            bits = r0bits;
+            r1t = gfc->choose_table(ix + a1, ix + a2, &bits);
+            if (r01_bits[r0 + r1] > bits) {
+                r01_bits[r0 + r1] = bits;
+                r01_div[r0 + r1] = r0;
+                r0_tbl[r0 + r1] = r0t;
+                r1_tbl[r0 + r1] = r1t;
+            }
+        }
+    }
+}
+
+inline static void
+recalc_divide_sub(const lame_internal_flags * const gfc,
+                  const gr_info * cod_info2,
+                  gr_info * const gi,
+                  const int *const ix,
+                  const int r01_bits[], const int r01_div[], const int r0_tbl[], const int r1_tbl[])
+{
+    int     bits, r2, a2, bigv, r2t;
+
+    bigv = cod_info2->big_values;
+
+    for (r2 = 2; r2 < SBMAX_l + 1; r2++) {
+        a2 = gfc->scalefac_band.l[r2];
+        if (a2 >= bigv)
+            break;
+
+        bits = r01_bits[r2 - 2] + cod_info2->count1bits;
+        if (gi->part2_3_length <= bits)
+            break;
+
+        r2t = gfc->choose_table(ix + a2, ix + bigv, &bits);
+        if (gi->part2_3_length <= bits)
+            continue;
+
+        memcpy(gi, cod_info2, sizeof(gr_info));
+        gi->part2_3_length = bits;
+        gi->region0_count = r01_div[r2 - 2];
+        gi->region1_count = r2 - 2 - r01_div[r2 - 2];
+        gi->table_select[0] = r0_tbl[r2 - 2];
+        gi->table_select[1] = r1_tbl[r2 - 2];
+        gi->table_select[2] = r2t;
+    }
+}
+
+
+
+
+void
+best_huffman_divide(const lame_internal_flags * const gfc, gr_info * const gi)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     i, a1, a2;
+    gr_info cod_info2;
+    int const *const ix = gi->l3_enc;
+
+    int     r01_bits[7 + 15 + 1];
+    int     r01_div[7 + 15 + 1];
+    int     r0_tbl[7 + 15 + 1];
+    int     r1_tbl[7 + 15 + 1];
+
+
+    /* SHORT BLOCK stuff fails for MPEG2 */
+    if (gi->block_type == SHORT_TYPE && cfg->mode_gr == 1)
+        return;
+
+
+    memcpy(&cod_info2, gi, sizeof(gr_info));
+    if (gi->block_type == NORM_TYPE) {
+        recalc_divide_init(gfc, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);
+        recalc_divide_sub(gfc, &cod_info2, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);
+    }
+
+    i = cod_info2.big_values;
+    if (i == 0 || (unsigned int) (ix[i - 2] | ix[i - 1]) > 1)
+        return;
+
+    i = gi->count1 + 2;
+    if (i > 576)
+        return;
+
+    /* Determines the number of bits to encode the quadruples. */
+    memcpy(&cod_info2, gi, sizeof(gr_info));
+    cod_info2.count1 = i;
+    a1 = a2 = 0;
+
+    assert(i <= 576);
+
+    for (; i > cod_info2.big_values; i -= 4) {
+        int const p = ((ix[i - 4] * 2 + ix[i - 3]) * 2 + ix[i - 2]) * 2 + ix[i - 1];
+        a1 += t32l[p];
+        a2 += t33l[p];
+    }
+    cod_info2.big_values = i;
+
+    cod_info2.count1table_select = 0;
+    if (a1 > a2) {
+        a1 = a2;
+        cod_info2.count1table_select = 1;
+    }
+
+    cod_info2.count1bits = a1;
+
+    if (cod_info2.block_type == NORM_TYPE)
+        recalc_divide_sub(gfc, &cod_info2, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);
+    else {
+        /* Count the number of bits necessary to code the bigvalues region. */
+        cod_info2.part2_3_length = a1;
+        a1 = gfc->scalefac_band.l[7 + 1];
+        if (a1 > i) {
+            a1 = i;
+        }
+        if (a1 > 0)
+            cod_info2.table_select[0] =
+                gfc->choose_table(ix, ix + a1, (int *) &cod_info2.part2_3_length);
+        if (i > a1)
+            cod_info2.table_select[1] =
+                gfc->choose_table(ix + a1, ix + i, (int *) &cod_info2.part2_3_length);
+        if (gi->part2_3_length > cod_info2.part2_3_length)
+            memcpy(gi, &cod_info2, sizeof(gr_info));
+    }
+}
+
+static const int slen1_n[16] = { 1, 1, 1, 1, 8, 2, 2, 2, 4, 4, 4, 8, 8, 8, 16, 16 };
+static const int slen2_n[16] = { 1, 2, 4, 8, 1, 2, 4, 8, 2, 4, 8, 2, 4, 8, 4, 8 };
+const int slen1_tab[16] = { 0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4 };
+const int slen2_tab[16] = { 0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3 };
+
+static void
+scfsi_calc(int ch, III_side_info_t * l3_side)
+{
+    unsigned int i;
+    int     s1, s2, c1, c2;
+    int     sfb;
+    gr_info *const gi = &l3_side->tt[1][ch];
+    gr_info const *const g0 = &l3_side->tt[0][ch];
+
+    for (i = 0; i < (sizeof(scfsi_band) / sizeof(int)) - 1; i++) {
+        for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1]; sfb++) {
+            if (g0->scalefac[sfb] != gi->scalefac[sfb]
+                && gi->scalefac[sfb] >= 0)
+                break;
+        }
+        if (sfb == scfsi_band[i + 1]) {
+            for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1]; sfb++) {
+                gi->scalefac[sfb] = -1;
+            }
+            l3_side->scfsi[ch][i] = 1;
+        }
+    }
+
+    s1 = c1 = 0;
+    for (sfb = 0; sfb < 11; sfb++) {
+        if (gi->scalefac[sfb] == -1)
+            continue;
+        c1++;
+        if (s1 < gi->scalefac[sfb])
+            s1 = gi->scalefac[sfb];
+    }
+
+    s2 = c2 = 0;
+    for (; sfb < SBPSY_l; sfb++) {
+        if (gi->scalefac[sfb] == -1)
+            continue;
+        c2++;
+        if (s2 < gi->scalefac[sfb])
+            s2 = gi->scalefac[sfb];
+    }
+
+    for (i = 0; i < 16; i++) {
+        if (s1 < slen1_n[i] && s2 < slen2_n[i]) {
+            int const c = slen1_tab[i] * c1 + slen2_tab[i] * c2;
+            if (gi->part2_length > c) {
+                gi->part2_length = c;
+                gi->scalefac_compress = (int)i;
+            }
+        }
+    }
+}
+
+/*
+Find the optimal way to store the scalefactors.
+Only call this routine after final scalefactors have been
+chosen and the channel/granule will not be re-encoded.
+ */
+void
+best_scalefac_store(const lame_internal_flags * gfc,
+                    const int gr, const int ch, III_side_info_t * const l3_side)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    /* use scalefac_scale if we can */
+    gr_info *const gi = &l3_side->tt[gr][ch];
+    int     sfb, i, j, l;
+    int     recalc = 0;
+
+    /* remove scalefacs from bands with ix=0.  This idea comes
+     * from the AAC ISO docs.  added mt 3/00 */
+    /* check if l3_enc=0 */
+    j = 0;
+    for (sfb = 0; sfb < gi->sfbmax; sfb++) {
+        int const width = gi->width[sfb];
+        assert(width >= 0);
+        for (l = j, j += width; l < j; ++l) {
+            if (gi->l3_enc[l] != 0)
+                break;
+        }
+        if (l == j)
+            gi->scalefac[sfb] = recalc = -2; /* anything goes. */
+        /*  only best_scalefac_store and calc_scfsi 
+         *  know--and only they should know--about the magic number -2. 
+         */
+    }
+
+    if (!gi->scalefac_scale && !gi->preflag) {
+        int     s = 0;
+        for (sfb = 0; sfb < gi->sfbmax; sfb++)
+            if (gi->scalefac[sfb] > 0)
+                s |= gi->scalefac[sfb];
+
+        if (!(s & 1) && s != 0) {
+            for (sfb = 0; sfb < gi->sfbmax; sfb++)
+                if (gi->scalefac[sfb] > 0)
+                    gi->scalefac[sfb] >>= 1;
+
+            gi->scalefac_scale = recalc = 1;
+        }
+    }
+
+    if (!gi->preflag && gi->block_type != SHORT_TYPE && cfg->mode_gr == 2) {
+        for (sfb = 11; sfb < SBPSY_l; sfb++)
+            if (gi->scalefac[sfb] < pretab[sfb] && gi->scalefac[sfb] != -2)
+                break;
+        if (sfb == SBPSY_l) {
+            for (sfb = 11; sfb < SBPSY_l; sfb++)
+                if (gi->scalefac[sfb] > 0)
+                    gi->scalefac[sfb] -= pretab[sfb];
+
+            gi->preflag = recalc = 1;
+        }
+    }
+
+    for (i = 0; i < 4; i++)
+        l3_side->scfsi[ch][i] = 0;
+
+    if (cfg->mode_gr == 2 && gr == 1
+        && l3_side->tt[0][ch].block_type != SHORT_TYPE
+        && l3_side->tt[1][ch].block_type != SHORT_TYPE) {
+        scfsi_calc(ch, l3_side);
+        recalc = 0;
+    }
+    for (sfb = 0; sfb < gi->sfbmax; sfb++) {
+        if (gi->scalefac[sfb] == -2) {
+            gi->scalefac[sfb] = 0; /* if anything goes, then 0 is a good choice */
+        }
+    }
+    if (recalc) {
+        (void) scale_bitcount(gfc, gi);
+    }
+}
+
+
+#ifndef NDEBUG
+static int
+all_scalefactors_not_negative(int const *scalefac, int n)
+{
+    int     i;
+    for (i = 0; i < n; ++i) {
+        if (scalefac[i] < 0)
+            return 0;
+    }
+    return 1;
+}
+#endif
+
+
+/* number of bits used to encode scalefacs */
+
+/* 18*slen1_tab[i] + 18*slen2_tab[i] */
+static const int scale_short[16] = {
+    0, 18, 36, 54, 54, 36, 54, 72, 54, 72, 90, 72, 90, 108, 108, 126
+};
+
+/* 17*slen1_tab[i] + 18*slen2_tab[i] */
+static const int scale_mixed[16] = {
+    0, 18, 36, 54, 51, 35, 53, 71, 52, 70, 88, 69, 87, 105, 104, 122
+};
+
+/* 11*slen1_tab[i] + 10*slen2_tab[i] */
+static const int scale_long[16] = {
+    0, 10, 20, 30, 33, 21, 31, 41, 32, 42, 52, 43, 53, 63, 64, 74
+};
+
+
+/*************************************************************************/
+/*            scale_bitcount                                             */
+/*************************************************************************/
+
+/* Also calculates the number of bits necessary to code the scalefactors. */
+
+static int
+mpeg1_scale_bitcount(const lame_internal_flags * gfc, gr_info * const cod_info)
+{
+    int     k, sfb, max_slen1 = 0, max_slen2 = 0;
+
+    /* maximum values */
+    const int *tab;
+    int    *const scalefac = cod_info->scalefac;
+
+    (void) gfc;
+    assert(all_scalefactors_not_negative(scalefac, cod_info->sfbmax));
+
+    if (cod_info->block_type == SHORT_TYPE) {
+        tab = scale_short;
+        if (cod_info->mixed_block_flag)
+            tab = scale_mixed;
+    }
+    else {              /* block_type == 1,2,or 3 */
+        tab = scale_long;
+        if (!cod_info->preflag) {
+            for (sfb = 11; sfb < SBPSY_l; sfb++)
+                if (scalefac[sfb] < pretab[sfb])
+                    break;
+
+            if (sfb == SBPSY_l) {
+                cod_info->preflag = 1;
+                for (sfb = 11; sfb < SBPSY_l; sfb++)
+                    scalefac[sfb] -= pretab[sfb];
+            }
+        }
+    }
+
+    for (sfb = 0; sfb < cod_info->sfbdivide; sfb++)
+        if (max_slen1 < scalefac[sfb])
+            max_slen1 = scalefac[sfb];
+
+    for (; sfb < cod_info->sfbmax; sfb++)
+        if (max_slen2 < scalefac[sfb])
+            max_slen2 = scalefac[sfb];
+
+    /* from Takehiro TOMINAGA <tominaga@isoternet.org> 10/99
+     * loop over *all* posible values of scalefac_compress to find the
+     * one which uses the smallest number of bits.  ISO would stop
+     * at first valid index */
+    cod_info->part2_length = LARGE_BITS;
+    for (k = 0; k < 16; k++) {
+        if (max_slen1 < slen1_n[k] && max_slen2 < slen2_n[k]
+            && cod_info->part2_length > tab[k]) {
+            cod_info->part2_length = tab[k];
+            cod_info->scalefac_compress = k;
+        }
+    }
+    return cod_info->part2_length == LARGE_BITS;
+}
+
+
+
+/*
+  table of largest scalefactor values for MPEG2
+*/
+static const int max_range_sfac_tab[6][4] = {
+    {15, 15, 7, 7},
+    {15, 15, 7, 0},
+    {7, 3, 0, 0},
+    {15, 31, 31, 0},
+    {7, 7, 7, 0},
+    {3, 3, 0, 0}
+};
+
+
+
+
+/*************************************************************************/
+/*            scale_bitcount_lsf                                         */
+/*************************************************************************/
+
+/* Also counts the number of bits to encode the scalefacs but for MPEG 2 */
+/* Lower sampling frequencies  (24, 22.05 and 16 kHz.)                   */
+
+/*  This is reverse-engineered from section 2.4.3.2 of the MPEG2 IS,     */
+/* "Audio Decoding Layer III"                                            */
+
+static int
+mpeg2_scale_bitcount(const lame_internal_flags * gfc, gr_info * const cod_info)
+{
+    int     table_number, row_in_table, partition, nr_sfb, window, over;
+    int     i, sfb, max_sfac[4];
+    const int *partition_table;
+    int const *const scalefac = cod_info->scalefac;
+
+    /*
+       Set partition table. Note that should try to use table one,
+       but do not yet...
+     */
+    if (cod_info->preflag)
+        table_number = 2;
+    else
+        table_number = 0;
+
+    for (i = 0; i < 4; i++)
+        max_sfac[i] = 0;
+
+    if (cod_info->block_type == SHORT_TYPE) {
+        row_in_table = 1;
+        partition_table = &nr_of_sfb_block[table_number][row_in_table][0];
+        for (sfb = 0, partition = 0; partition < 4; partition++) {
+            nr_sfb = partition_table[partition] / 3;
+            for (i = 0; i < nr_sfb; i++, sfb++)
+                for (window = 0; window < 3; window++)
+                    if (scalefac[sfb * 3 + window] > max_sfac[partition])
+                        max_sfac[partition] = scalefac[sfb * 3 + window];
+        }
+    }
+    else {
+        row_in_table = 0;
+        partition_table = &nr_of_sfb_block[table_number][row_in_table][0];
+        for (sfb = 0, partition = 0; partition < 4; partition++) {
+            nr_sfb = partition_table[partition];
+            for (i = 0; i < nr_sfb; i++, sfb++)
+                if (scalefac[sfb] > max_sfac[partition])
+                    max_sfac[partition] = scalefac[sfb];
+        }
+    }
+
+    for (over = 0, partition = 0; partition < 4; partition++) {
+        if (max_sfac[partition] > max_range_sfac_tab[table_number][partition])
+            over++;
+    }
+    if (!over) {
+        /*
+           Since no bands have been over-amplified, we can set scalefac_compress
+           and slen[] for the formatter
+         */
+        static const int log2tab[] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 };
+
+        int     slen1, slen2, slen3, slen4;
+
+        cod_info->sfb_partition_table = nr_of_sfb_block[table_number][row_in_table];
+        for (partition = 0; partition < 4; partition++)
+            cod_info->slen[partition] = log2tab[max_sfac[partition]];
+
+        /* set scalefac_compress */
+        slen1 = cod_info->slen[0];
+        slen2 = cod_info->slen[1];
+        slen3 = cod_info->slen[2];
+        slen4 = cod_info->slen[3];
+
+        switch (table_number) {
+        case 0:
+            cod_info->scalefac_compress = (((slen1 * 5) + slen2) << 4)
+                + (slen3 << 2)
+                + slen4;
+            break;
+
+        case 1:
+            cod_info->scalefac_compress = 400 + (((slen1 * 5) + slen2) << 2)
+                + slen3;
+            break;
+
+        case 2:
+            cod_info->scalefac_compress = 500 + (slen1 * 3) + slen2;
+            break;
+
+        default:
+            ERRORF(gfc, "intensity stereo not implemented yet\n");
+            break;
+        }
+    }
+#ifdef DEBUG
+    if (over)
+        ERRORF(gfc, "---WARNING !! Amplification of some bands over limits\n");
+#endif
+    if (!over) {
+        assert(cod_info->sfb_partition_table);
+        cod_info->part2_length = 0;
+        for (partition = 0; partition < 4; partition++)
+            cod_info->part2_length +=
+                cod_info->slen[partition] * cod_info->sfb_partition_table[partition];
+    }
+    return over;
+}
+
+
+int
+scale_bitcount(const lame_internal_flags * gfc, gr_info * cod_info)
+{
+    if (gfc->cfg.mode_gr == 2) {
+        return mpeg1_scale_bitcount(gfc, cod_info);
+    }
+    else {
+        return mpeg2_scale_bitcount(gfc, cod_info);
+    }
+}
+
+
+#ifdef MMX_choose_table
+extern int choose_table_MMX(const int *ix, const int *const end, int *const s);
+#endif
+
+void
+huffman_init(lame_internal_flags * const gfc)
+{
+    int     i;
+
+    gfc->choose_table = choose_table_nonMMX;
+
+#ifdef MMX_choose_table
+    if (gfc->CPU_features.MMX) {
+        gfc->choose_table = choose_table_MMX;
+    }
+#endif
+
+    for (i = 2; i <= 576; i += 2) {
+        int     scfb_anz = 0, bv_index;
+        while (gfc->scalefac_band.l[++scfb_anz] < i);
+
+        bv_index = subdv_table[scfb_anz].region0_count;
+        while (gfc->scalefac_band.l[bv_index + 1] > i)
+            bv_index--;
+
+        if (bv_index < 0) {
+            /* this is an indication that everything is going to
+               be encoded as region0:  bigvalues < region0 < region1
+               so lets set region0, region1 to some value larger
+               than bigvalues */
+            bv_index = subdv_table[scfb_anz].region0_count;
+        }
+
+        gfc->sv_qnt.bv_scf[i - 2] = bv_index;
+
+        bv_index = subdv_table[scfb_anz].region1_count;
+        while (gfc->scalefac_band.l[bv_index + gfc->sv_qnt.bv_scf[i - 2] + 2] > i)
+            bv_index--;
+
+        if (bv_index < 0) {
+            bv_index = subdv_table[scfb_anz].region1_count;
+        }
+
+        gfc->sv_qnt.bv_scf[i - 1] = bv_index;
+    }
+}
diff --git a/lame/libmp3lame/util.c b/lame/libmp3lame/util.c
new file mode 100644 (file)
index 0000000..43b457c
--- /dev/null
@@ -0,0 +1,1018 @@
+/*
+ *     lame utility library source file
+ *
+ *     Copyright (c) 1999 Albert L Faber
+ *     Copyright (c) 2000-2005 Alexander Leidinger
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: util.c,v 1.159 2017/09/06 15:07:30 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <float.h>
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "tables.h"
+
+#define PRECOMPUTE
+#if defined(__FreeBSD__) && !defined(__alpha__)
+# include <machine/floatingpoint.h>
+#endif
+
+
+/***********************************************************************
+*
+*  Global Function Definitions
+*
+***********************************************************************/
+/*empty and close mallocs in gfc */
+
+void
+free_id3tag(lame_internal_flags * const gfc)
+{
+    gfc->tag_spec.language[0] = 0;
+    if (gfc->tag_spec.title != 0) {
+        free(gfc->tag_spec.title);
+        gfc->tag_spec.title = 0;
+    }
+    if (gfc->tag_spec.artist != 0) {
+        free(gfc->tag_spec.artist);
+        gfc->tag_spec.artist = 0;
+    }
+    if (gfc->tag_spec.album != 0) {
+        free(gfc->tag_spec.album);
+        gfc->tag_spec.album = 0;
+    }
+    if (gfc->tag_spec.comment != 0) {
+        free(gfc->tag_spec.comment);
+        gfc->tag_spec.comment = 0;
+    }
+
+    if (gfc->tag_spec.albumart != 0) {
+        free(gfc->tag_spec.albumart);
+        gfc->tag_spec.albumart = 0;
+        gfc->tag_spec.albumart_size = 0;
+        gfc->tag_spec.albumart_mimetype = MIMETYPE_NONE;
+    }
+    if (gfc->tag_spec.v2_head != 0) {
+        FrameDataNode *node = gfc->tag_spec.v2_head;
+        do {
+            void   *p = node->dsc.ptr.b;
+            void   *q = node->txt.ptr.b;
+            void   *r = node;
+            node = node->nxt;
+            free(p);
+            free(q);
+            free(r);
+        } while (node != 0);
+        gfc->tag_spec.v2_head = 0;
+        gfc->tag_spec.v2_tail = 0;
+    }
+}
+
+
+static void
+free_global_data(lame_internal_flags * gfc)
+{
+    if (gfc && gfc->cd_psy) {
+        if (gfc->cd_psy->l.s3) {
+            /* XXX allocated in psymodel_init() */
+            free(gfc->cd_psy->l.s3);
+        }
+        if (gfc->cd_psy->s.s3) {
+            /* XXX allocated in psymodel_init() */
+            free(gfc->cd_psy->s.s3);
+        }
+        free(gfc->cd_psy);
+        gfc->cd_psy = 0;
+    }
+}
+
+
+void
+freegfc(lame_internal_flags * const gfc)
+{                       /* bit stream structure */
+    int     i;
+
+    if (gfc == 0) return;
+
+    for (i = 0; i <= 2 * BPC; i++)
+        if (gfc->sv_enc.blackfilt[i] != NULL) {
+            free(gfc->sv_enc.blackfilt[i]);
+            gfc->sv_enc.blackfilt[i] = NULL;
+        }
+    if (gfc->sv_enc.inbuf_old[0]) {
+        free(gfc->sv_enc.inbuf_old[0]);
+        gfc->sv_enc.inbuf_old[0] = NULL;
+    }
+    if (gfc->sv_enc.inbuf_old[1]) {
+        free(gfc->sv_enc.inbuf_old[1]);
+        gfc->sv_enc.inbuf_old[1] = NULL;
+    }
+
+    if (gfc->bs.buf != NULL) {
+        free(gfc->bs.buf);
+        gfc->bs.buf = NULL;
+    }
+
+    if (gfc->VBR_seek_table.bag) {
+        free(gfc->VBR_seek_table.bag);
+        gfc->VBR_seek_table.bag = NULL;
+        gfc->VBR_seek_table.size = 0;
+    }
+    if (gfc->ATH) {
+        free(gfc->ATH);
+    }
+    if (gfc->sv_rpg.rgdata) {
+        free(gfc->sv_rpg.rgdata);
+    }
+    if (gfc->sv_enc.in_buffer_0) {
+        free(gfc->sv_enc.in_buffer_0);
+    }
+    if (gfc->sv_enc.in_buffer_1) {
+        free(gfc->sv_enc.in_buffer_1);
+    }
+    free_id3tag(gfc);
+
+#ifdef DECODE_ON_THE_FLY
+    if (gfc->hip) {
+        hip_decode_exit(gfc->hip);
+        gfc->hip = 0;
+    }
+#endif
+
+    free_global_data(gfc);
+
+    free(gfc);
+}
+
+void
+calloc_aligned(aligned_pointer_t * ptr, unsigned int size, unsigned int bytes)
+{
+    if (ptr) {
+        if (!ptr->pointer) {
+            ptr->pointer = malloc(size + bytes);
+            if (ptr->pointer != 0) {
+                memset(ptr->pointer, 0, size + bytes);
+                if (bytes > 0) {
+                    ptr->aligned = (void *) ((((size_t) ptr->pointer + bytes - 1) / bytes) * bytes);
+                }
+                else {
+                    ptr->aligned = ptr->pointer;
+                }
+            }
+            else {
+                ptr->aligned = 0;
+            }
+        }
+    }
+}
+
+void
+free_aligned(aligned_pointer_t * ptr)
+{
+    if (ptr) {
+        if (ptr->pointer) {
+            free(ptr->pointer);
+            ptr->pointer = 0;
+            ptr->aligned = 0;
+        }
+    }
+}
+
+/*those ATH formulas are returning
+their minimum value for input = -1*/
+
+static  FLOAT
+ATHformula_GB(FLOAT f, FLOAT value, FLOAT f_min, FLOAT f_max)
+{
+    /* from Painter & Spanias
+       modified by Gabriel Bouvigne to better fit the reality
+       ath =    3.640 * pow(f,-0.8)
+       - 6.800 * exp(-0.6*pow(f-3.4,2.0))
+       + 6.000 * exp(-0.15*pow(f-8.7,2.0))
+       + 0.6* 0.001 * pow(f,4.0);
+
+
+       In the past LAME was using the Painter &Spanias formula.
+       But we had some recurrent problems with HF content.
+       We measured real ATH values, and found the older formula
+       to be inacurate in the higher part. So we made this new
+       formula and this solved most of HF problematic testcases.
+       The tradeoff is that in VBR mode it increases a lot the
+       bitrate. */
+
+
+/*this curve can be udjusted according to the VBR scale:
+it adjusts from something close to Painter & Spanias
+on V9 up to Bouvigne's formula for V0. This way the VBR
+bitrate is more balanced according to the -V value.*/
+
+    FLOAT   ath;
+
+    /* the following Hack allows to ask for the lowest value */
+    if (f < -.3)
+        f = 3410;
+
+    f /= 1000;          /* convert to khz */
+    f = Max(f_min, f);
+    f = Min(f_max, f);
+
+    ath = 3.640 * pow(f, -0.8)
+        - 6.800 * exp(-0.6 * pow(f - 3.4, 2.0))
+        + 6.000 * exp(-0.15 * pow(f - 8.7, 2.0))
+        + (0.6 + 0.04 * value) * 0.001 * pow(f, 4.0);
+    return ath;
+}
+
+
+
+FLOAT
+ATHformula(SessionConfig_t const *cfg, FLOAT f)
+{
+    FLOAT   ath;
+    switch (cfg->ATHtype) {
+    case 0:
+        ath = ATHformula_GB(f, 9, 0.1f, 24.0f);
+        break;
+    case 1:
+        ath = ATHformula_GB(f, -1, 0.1f, 24.0f); /*over sensitive, should probably be removed */
+        break;
+    case 2:
+        ath = ATHformula_GB(f, 0, 0.1f, 24.0f);
+        break;
+    case 3:
+        ath = ATHformula_GB(f, 1, 0.1f, 24.0f) + 6; /*modification of GB formula by Roel */
+        break;
+    case 4:
+        ath = ATHformula_GB(f, cfg->ATHcurve, 0.1f, 24.0f);
+        break;
+    case 5:
+        ath = ATHformula_GB(f, cfg->ATHcurve, 3.41f, 16.1f);
+        break;
+    default:
+        ath = ATHformula_GB(f, 0, 0.1f, 24.0f);
+        break;
+    }
+    return ath;
+}
+
+/* see for example "Zwicker: Psychoakustik, 1982; ISBN 3-540-11401-7 */
+FLOAT
+freq2bark(FLOAT freq)
+{
+    /* input: freq in hz  output: barks */
+    if (freq < 0)
+        freq = 0;
+    freq = freq * 0.001;
+    return 13.0 * atan(.76 * freq) + 3.5 * atan(freq * freq / (7.5 * 7.5));
+}
+
+#if 0
+extern FLOAT freq2cbw(FLOAT freq);
+
+/* see for example "Zwicker: Psychoakustik, 1982; ISBN 3-540-11401-7 */
+FLOAT
+freq2cbw(FLOAT freq)
+{
+    /* input: freq in hz  output: critical band width */
+    freq = freq * 0.001;
+    return 25 + 75 * pow(1 + 1.4 * (freq * freq), 0.69);
+}
+
+#endif
+
+
+
+
+#define ABS(A) (((A)>0) ? (A) : -(A))
+
+int
+FindNearestBitrate(int bRate, /* legal rates from 8 to 320 */
+                   int version, int samplerate)
+{                       /* MPEG-1 or MPEG-2 LSF */
+    int     bitrate;
+    int     i;
+
+    if (samplerate < 16000)
+        version = 2;
+
+    bitrate = bitrate_table[version][1];
+
+    for (i = 2; i <= 14; i++) {
+        if (bitrate_table[version][i] > 0) {
+            if (ABS(bitrate_table[version][i] - bRate) < ABS(bitrate - bRate))
+                bitrate = bitrate_table[version][i];
+        }
+    }
+    return bitrate;
+}
+
+
+
+
+
+#ifndef Min
+#define         Min(A, B)       ((A) < (B) ? (A) : (B))
+#endif
+#ifndef Max
+#define         Max(A, B)       ((A) > (B) ? (A) : (B))
+#endif
+
+
+/* Used to find table index when
+ * we need bitrate-based values
+ * determined using tables
+ *
+ * bitrate in kbps
+ *
+ * Gabriel Bouvigne 2002-11-03
+ */
+int
+nearestBitrateFullIndex(uint16_t bitrate)
+{
+    /* borrowed from DM abr presets */
+
+    const int full_bitrate_table[] =
+        { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 };
+
+
+    int     lower_range = 0, lower_range_kbps = 0, upper_range = 0, upper_range_kbps = 0;
+
+
+    int     b;
+
+
+    /* We assume specified bitrate will be 320kbps */
+    upper_range_kbps = full_bitrate_table[16];
+    upper_range = 16;
+    lower_range_kbps = full_bitrate_table[16];
+    lower_range = 16;
+
+    /* Determine which significant bitrates the value specified falls between,
+     * if loop ends without breaking then we were correct above that the value was 320
+     */
+    for (b = 0; b < 16; b++) {
+        if ((Max(bitrate, full_bitrate_table[b + 1])) != bitrate) {
+            upper_range_kbps = full_bitrate_table[b + 1];
+            upper_range = b + 1;
+            lower_range_kbps = full_bitrate_table[b];
+            lower_range = (b);
+            break;      /* We found upper range */
+        }
+    }
+
+    /* Determine which range the value specified is closer to */
+    if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps)) {
+        return lower_range;
+    }
+    return upper_range;
+}
+
+
+
+
+
+/* map frequency to a valid MP3 sample frequency
+ *
+ * Robert Hegemann 2000-07-01
+ */
+int
+map2MP3Frequency(int freq)
+{
+    if (freq <= 8000)
+        return 8000;
+    if (freq <= 11025)
+        return 11025;
+    if (freq <= 12000)
+        return 12000;
+    if (freq <= 16000)
+        return 16000;
+    if (freq <= 22050)
+        return 22050;
+    if (freq <= 24000)
+        return 24000;
+    if (freq <= 32000)
+        return 32000;
+    if (freq <= 44100)
+        return 44100;
+
+    return 48000;
+}
+
+int
+BitrateIndex(int bRate,      /* legal rates from 32 to 448 kbps */
+             int version,    /* MPEG-1 or MPEG-2/2.5 LSF */
+             int samplerate)
+{                       /* convert bitrate in kbps to index */
+    int     i;
+    if (samplerate < 16000)
+        version = 2;
+    for (i = 0; i <= 14; i++) {
+        if (bitrate_table[version][i] > 0) {
+            if (bitrate_table[version][i] == bRate) {
+                return i;
+            }
+        }
+    }
+    return -1;
+}
+
+/* convert samp freq in Hz to index */
+
+int
+SmpFrqIndex(int sample_freq, int *const version)
+{
+    switch (sample_freq) {
+    case 44100:
+        *version = 1;
+        return 0;
+    case 48000:
+        *version = 1;
+        return 1;
+    case 32000:
+        *version = 1;
+        return 2;
+    case 22050:
+        *version = 0;
+        return 0;
+    case 24000:
+        *version = 0;
+        return 1;
+    case 16000:
+        *version = 0;
+        return 2;
+    case 11025:
+        *version = 0;
+        return 0;
+    case 12000:
+        *version = 0;
+        return 1;
+    case 8000:
+        *version = 0;
+        return 2;
+    default:
+        *version = 0;
+        return -1;
+    }
+}
+
+
+/*****************************************************************************
+*
+*  End of bit_stream.c package
+*
+*****************************************************************************/
+
+
+
+
+
+
+
+
+
+
+/* resampling via FIR filter, blackman window */
+inline static FLOAT
+blackman(FLOAT x, FLOAT fcn, int l)
+{
+    /* This algorithm from:
+       SIGNAL PROCESSING ALGORITHMS IN FORTRAN AND C
+       S.D. Stearns and R.A. David, Prentice-Hall, 1992
+     */
+    FLOAT   bkwn, x2;
+    FLOAT const wcn = (PI * fcn);
+
+    x /= l;
+    if (x < 0)
+        x = 0;
+    if (x > 1)
+        x = 1;
+    x2 = x - .5;
+
+    bkwn = 0.42 - 0.5 * cos(2 * x * PI) + 0.08 * cos(4 * x * PI);
+    if (fabs(x2) < 1e-9)
+        return wcn / PI;
+    else
+        return (bkwn * sin(l * wcn * x2) / (PI * l * x2));
+
+
+}
+
+
+
+
+/* gcd - greatest common divisor */
+/* Joint work of Euclid and M. Hendry */
+
+static int
+gcd(int i, int j)
+{
+    /*    assert ( i > 0  &&  j > 0 ); */
+    return j ? gcd(j, i % j) : i;
+}
+
+
+
+static int
+fill_buffer_resample(lame_internal_flags * gfc,
+                     sample_t * outbuf,
+                     int desired_len, sample_t const *inbuf, int len, int *num_used, int ch)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    EncStateVar_t *esv = &gfc->sv_enc;
+    double  resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;
+    int     BLACKSIZE;
+    FLOAT   offset, xvalue;
+    int     i, j = 0, k;
+    int     filter_l;
+    FLOAT   fcn, intratio;
+    FLOAT  *inbuf_old;
+    int     bpc;             /* number of convolution functions to pre-compute */
+    bpc = cfg->samplerate_out / gcd(cfg->samplerate_out, cfg->samplerate_in);
+    if (bpc > BPC)
+        bpc = BPC;
+
+    intratio = (fabs(resample_ratio - floor(.5 + resample_ratio)) < FLT_EPSILON);
+    fcn = 1.00 / resample_ratio;
+    if (fcn > 1.00)
+        fcn = 1.00;
+    filter_l = 31;     /* must be odd */
+    filter_l += intratio; /* unless resample_ratio=int, it must be even */
+
+
+    BLACKSIZE = filter_l + 1; /* size of data needed for FIR */
+
+    if (gfc->fill_buffer_resample_init == 0) {
+        esv->inbuf_old[0] = lame_calloc(sample_t, BLACKSIZE);
+        esv->inbuf_old[1] = lame_calloc(sample_t, BLACKSIZE);
+        for (i = 0; i <= 2 * bpc; ++i)
+            esv->blackfilt[i] = lame_calloc(sample_t, BLACKSIZE);
+
+        esv->itime[0] = 0;
+        esv->itime[1] = 0;
+
+        /* precompute blackman filter coefficients */
+        for (j = 0; j <= 2 * bpc; j++) {
+            FLOAT   sum = 0.;
+            offset = (j - bpc) / (2. * bpc);
+            for (i = 0; i <= filter_l; i++)
+                sum += esv->blackfilt[j][i] = blackman(i - offset, fcn, filter_l);
+            for (i = 0; i <= filter_l; i++)
+                esv->blackfilt[j][i] /= sum;
+        }
+        gfc->fill_buffer_resample_init = 1;
+    }
+
+    inbuf_old = esv->inbuf_old[ch];
+
+    /* time of j'th element in inbuf = itime + j/ifreq; */
+    /* time of k'th element in outbuf   =  j/ofreq */
+    for (k = 0; k < desired_len; k++) {
+        double  time0 = k * resample_ratio; /* time of k'th output sample */
+        int     joff;
+
+        j = floor(time0 - esv->itime[ch]);
+
+        /* check if we need more input data */
+        if ((filter_l + j - filter_l / 2) >= len)
+            break;
+
+        /* blackman filter.  by default, window centered at j+.5(filter_l%2) */
+        /* but we want a window centered at time0.   */
+        offset = (time0 - esv->itime[ch] - (j + .5 * (filter_l % 2)));
+        assert(fabs(offset) <= .501);
+
+        /* find the closest precomputed window for this offset: */
+        joff = floor((offset * 2 * bpc) + bpc + .5);
+
+        xvalue = 0.;
+        for (i = 0; i <= filter_l; ++i) {
+            int const j2 = i + j - filter_l / 2;
+            sample_t y;
+            assert(j2 < len);
+            assert(j2 + BLACKSIZE >= 0);
+            y = (j2 < 0) ? inbuf_old[BLACKSIZE + j2] : inbuf[j2];
+#ifdef PRECOMPUTE
+            xvalue += y * esv->blackfilt[joff][i];
+#else
+            xvalue += y * blackman(i - offset, fcn, filter_l); /* very slow! */
+#endif
+        }
+        outbuf[k] = xvalue;
+    }
+
+
+    /* k = number of samples added to outbuf */
+    /* last k sample used data from [j-filter_l/2,j+filter_l-filter_l/2]  */
+
+    /* how many samples of input data were used:  */
+    *num_used = Min(len, filter_l + j - filter_l / 2);
+
+    /* adjust our input time counter.  Incriment by the number of samples used,
+     * then normalize so that next output sample is at time 0, next
+     * input buffer is at time itime[ch] */
+    esv->itime[ch] += *num_used - k * resample_ratio;
+
+    /* save the last BLACKSIZE samples into the inbuf_old buffer */
+    if (*num_used >= BLACKSIZE) {
+        for (i = 0; i < BLACKSIZE; i++)
+            inbuf_old[i] = inbuf[*num_used + i - BLACKSIZE];
+    }
+    else {
+        /* shift in *num_used samples into inbuf_old  */
+        int const n_shift = BLACKSIZE - *num_used; /* number of samples to shift */
+
+        /* shift n_shift samples by *num_used, to make room for the
+         * num_used new samples */
+        for (i = 0; i < n_shift; ++i)
+            inbuf_old[i] = inbuf_old[i + *num_used];
+
+        /* shift in the *num_used samples */
+        for (j = 0; i < BLACKSIZE; ++i, ++j)
+            inbuf_old[i] = inbuf[j];
+
+        assert(j == *num_used);
+    }
+    return k;           /* return the number samples created at the new samplerate */
+}
+
+int
+isResamplingNecessary(SessionConfig_t const* cfg)
+{
+    int const l = cfg->samplerate_out * 0.9995f;
+    int const h = cfg->samplerate_out * 1.0005f;
+    return (cfg->samplerate_in < l) || (h < cfg->samplerate_in) ? 1 : 0;
+}
+
+/* copy in new samples from in_buffer into mfbuf, with resampling
+   if necessary.  n_in = number of samples from the input buffer that
+   were used.  n_out = number of samples copied into mfbuf  */
+
+void
+fill_buffer(lame_internal_flags * gfc,
+            sample_t * const mfbuf[2], sample_t const * const in_buffer[2], int nsamples, int *n_in, int *n_out)
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     mf_size = gfc->sv_enc.mf_size;
+    int     framesize = 576 * cfg->mode_gr;
+    int     nout, ch = 0;
+    int     nch = cfg->channels_out;
+
+    /* copy in new samples into mfbuf, with resampling if necessary */
+    if (isResamplingNecessary(cfg)) {
+        do {
+            nout =
+                fill_buffer_resample(gfc, &mfbuf[ch][mf_size],
+                                     framesize, in_buffer[ch], nsamples, n_in, ch);
+        } while (++ch < nch);
+        *n_out = nout;
+    }
+    else {
+        nout = Min(framesize, nsamples);
+        do {
+            memcpy(&mfbuf[ch][mf_size], &in_buffer[ch][0], nout * sizeof(mfbuf[0][0]));
+        } while (++ch < nch);
+        *n_out = nout;
+        *n_in = nout;
+    }
+}
+
+
+
+
+
+
+
+/***********************************************************************
+*
+*  Message Output
+*
+***********************************************************************/
+
+void
+lame_report_def(const char *format, va_list args)
+{
+    (void) vfprintf(stderr, format, args);
+    fflush(stderr); /* an debug function should flush immediately */
+}
+
+void 
+lame_report_fnc(lame_report_function print_f, const char *format, ...)
+{
+    if (print_f) {
+        va_list args;
+        va_start(args, format);
+        print_f(format, args);
+        va_end(args);
+    }
+}
+
+
+void
+lame_debugf(const lame_internal_flags* gfc, const char *format, ...)
+{
+    if (gfc && gfc->report_dbg) {
+        va_list args;
+        va_start(args, format);
+        gfc->report_dbg(format, args);
+        va_end(args);
+    }
+}
+
+
+void
+lame_msgf(const lame_internal_flags* gfc, const char *format, ...)
+{
+    if (gfc && gfc->report_msg) {
+        va_list args;
+        va_start(args, format);
+        gfc->report_msg(format, args);
+        va_end(args);
+    }
+}
+
+
+void
+lame_errorf(const lame_internal_flags* gfc, const char *format, ...)
+{
+    if (gfc && gfc->report_err) {
+        va_list args;
+        va_start(args, format);
+        gfc->report_err(format, args);
+        va_end(args);
+    }
+}
+
+
+
+/***********************************************************************
+ *
+ *      routines to detect CPU specific features like 3DNow, MMX, SSE
+ *
+ *  donated by Frank Klemm
+ *  added Robert Hegemann 2000-10-10
+ *
+ ***********************************************************************/
+
+#ifdef HAVE_NASM
+extern int has_MMX_nasm(void);
+extern int has_3DNow_nasm(void);
+extern int has_SSE_nasm(void);
+extern int has_SSE2_nasm(void);
+#endif
+
+int
+has_MMX(void)
+{
+#ifdef HAVE_NASM
+    return has_MMX_nasm();
+#else
+    return 0;           /* don't know, assume not */
+#endif
+}
+
+int
+has_3DNow(void)
+{
+#ifdef HAVE_NASM
+    return has_3DNow_nasm();
+#else
+    return 0;           /* don't know, assume not */
+#endif
+}
+
+int
+has_SSE(void)
+{
+#ifdef HAVE_NASM
+    return has_SSE_nasm();
+#else
+#if defined( _M_X64 ) || defined( MIN_ARCH_SSE )
+    return 1;
+#else
+    return 0;           /* don't know, assume not */
+#endif
+#endif
+}
+
+int
+has_SSE2(void)
+{
+#ifdef HAVE_NASM
+    return has_SSE2_nasm();
+#else
+#if defined( _M_X64 ) || defined( MIN_ARCH_SSE )
+    return 1;
+#else
+    return 0;           /* don't know, assume not */
+#endif
+#endif
+}
+
+void
+disable_FPE(void)
+{
+/* extremly system dependent stuff, move to a lib to make the code readable */
+/*==========================================================================*/
+
+
+
+    /*
+     *  Disable floating point exceptions
+     */
+
+
+
+
+#if defined(__FreeBSD__) && !defined(__alpha__)
+    {
+        /* seet floating point mask to the Linux default */
+        fp_except_t mask;
+        mask = fpgetmask();
+        /* if bit is set, we get SIGFPE on that error! */
+        fpsetmask(mask & ~(FP_X_INV | FP_X_DZ));
+        /*  DEBUGF("FreeBSD mask is 0x%x\n",mask); */
+    }
+#endif
+
+#if defined(__riscos__) && !defined(ABORTFP)
+    /* Disable FPE's under RISC OS */
+    /* if bit is set, we disable trapping that error! */
+    /*   _FPE_IVO : invalid operation */
+    /*   _FPE_DVZ : divide by zero */
+    /*   _FPE_OFL : overflow */
+    /*   _FPE_UFL : underflow */
+    /*   _FPE_INX : inexact */
+    DisableFPETraps(_FPE_IVO | _FPE_DVZ | _FPE_OFL);
+#endif
+
+    /*
+     *  Debugging stuff
+     *  The default is to ignore FPE's, unless compiled with -DABORTFP
+     *  so add code below to ENABLE FPE's.
+     */
+
+#if defined(ABORTFP)
+#if defined(_MSC_VER)
+    {
+#if 0
+        /* rh 061207
+           the following fix seems to be a workaround for a problem in the
+           parent process calling LAME. It would be better to fix the broken
+           application => code disabled.
+         */
+
+        /* set affinity to a single CPU.  Fix for EAC/lame on SMP systems from
+           "Todd Richmond" <todd.richmond@openwave.com> */
+        SYSTEM_INFO si;
+        GetSystemInfo(&si);
+        SetProcessAffinityMask(GetCurrentProcess(), si.dwActiveProcessorMask);
+#endif
+#include <float.h>
+        unsigned int mask;
+        mask = _controlfp(0, 0);
+        mask &= ~(_EM_OVERFLOW | _EM_UNDERFLOW | _EM_ZERODIVIDE | _EM_INVALID);
+        mask = _controlfp(mask, _MCW_EM);
+    }
+#elif defined(__CYGWIN__)
+#  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
+#  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
+
+#  define _EM_INEXACT     0x00000020 /* inexact (precision) */
+#  define _EM_UNDERFLOW   0x00000010 /* underflow */
+#  define _EM_OVERFLOW    0x00000008 /* overflow */
+#  define _EM_ZERODIVIDE  0x00000004 /* zero divide */
+#  define _EM_INVALID     0x00000001 /* invalid */
+    {
+        unsigned int mask;
+        _FPU_GETCW(mask);
+        /* Set the FPU control word to abort on most FPEs */
+        mask &= ~(_EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID);
+        _FPU_SETCW(mask);
+    }
+# elif defined(__linux__)
+    {
+
+#  include <fpu_control.h>
+#  ifndef _FPU_GETCW
+#  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
+#  endif
+#  ifndef _FPU_SETCW
+#  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
+#  endif
+
+        /* 
+         * Set the Linux mask to abort on most FPE's
+         * if bit is set, we _mask_ SIGFPE on that error!
+         *  mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM | _FPU_MASK_UM );
+         */
+
+        unsigned int mask;
+        _FPU_GETCW(mask);
+        mask &= ~(_FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM);
+        _FPU_SETCW(mask);
+    }
+#endif
+#endif /* ABORTFP */
+}
+
+
+
+
+
+#ifdef USE_FAST_LOG
+/***********************************************************************
+ *
+ * Fast Log Approximation for log2, used to approximate every other log
+ * (log10 and log)
+ * maximum absolute error for log10 is around 10-6
+ * maximum *relative* error can be high when x is almost 1 because error/log10(x) tends toward x/e
+ *
+ * use it if typical RESULT values are > 1e-5 (for example if x>1.00001 or x<0.99999)
+ * or if the relative precision in the domain around 1 is not important (result in 1 is exact and 0)
+ *
+ ***********************************************************************/
+
+
+#define LOG2_SIZE       (512)
+#define LOG2_SIZE_L2    (9)
+
+static ieee754_float32_t log_table[LOG2_SIZE + 1];
+
+
+
+void
+init_log_table(void)
+{
+    int     j;
+    static int init = 0;
+
+    /* Range for log2(x) over [1,2[ is [0,1[ */
+    assert((1 << LOG2_SIZE_L2) == LOG2_SIZE);
+
+    if (!init) {
+        for (j = 0; j < LOG2_SIZE + 1; j++)
+            log_table[j] = log(1.0f + j / (ieee754_float32_t) LOG2_SIZE) / log(2.0f);
+    }
+    init = 1;
+}
+
+
+
+ieee754_float32_t
+fast_log2(ieee754_float32_t x)
+{
+    ieee754_float32_t log2val, partial;
+    union {
+        ieee754_float32_t f;
+        int     i;
+    } fi;
+    int     mantisse;
+    fi.f = x;
+    mantisse = fi.i & 0x7fffff;
+    log2val = ((fi.i >> 23) & 0xFF) - 0x7f;
+    partial = (mantisse & ((1 << (23 - LOG2_SIZE_L2)) - 1));
+    partial *= 1.0f / ((1 << (23 - LOG2_SIZE_L2)));
+
+
+    mantisse >>= (23 - LOG2_SIZE_L2);
+
+    /* log2val += log_table[mantisse];  without interpolation the results are not good */
+    log2val += log_table[mantisse] * (1.0f - partial) + log_table[mantisse + 1] * partial;
+
+    return log2val;
+}
+
+#else /* Don't use FAST_LOG */
+
+
+void
+init_log_table(void)
+{
+}
+
+
+#endif
+
+/* end of util.c */
diff --git a/lame/libmp3lame/util.h b/lame/libmp3lame/util.h
new file mode 100644 (file)
index 0000000..13f0cd4
--- /dev/null
@@ -0,0 +1,616 @@
+/*
+ *      lame utility library include file
+ *
+ *      Copyright (c) 1999 Albert L Faber
+ *      Copyright (c) 2008 Robert Hegemann
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_UTIL_H
+#define LAME_UTIL_H
+
+#include "l3side.h"
+#include "id3tag.h"
+#include "lame_global_flags.h"
+
+#ifdef __cplusplus
+extern  "C" {
+#endif
+
+/***********************************************************************
+*
+*  Global Definitions
+*
+***********************************************************************/
+
+#ifndef FALSE
+#define         FALSE                   0
+#endif
+
+#ifndef TRUE
+#define         TRUE                    (!FALSE)
+#endif
+
+#ifdef UINT_MAX
+# define         MAX_U_32_NUM            UINT_MAX
+#else
+# define         MAX_U_32_NUM            0xFFFFFFFF
+#endif
+
+#ifndef PI
+# ifdef M_PI
+#  define       PI                      M_PI
+# else
+#  define       PI                      3.14159265358979323846
+# endif
+#endif
+
+
+#ifdef M_LN2
+# define        LOG2                    M_LN2
+#else
+# define        LOG2                    0.69314718055994530942
+#endif
+
+#ifdef M_LN10
+# define        LOG10                   M_LN10
+#else
+# define        LOG10                   2.30258509299404568402
+#endif
+
+
+#ifdef M_SQRT2
+# define        SQRT2                   M_SQRT2
+#else
+# define        SQRT2                   1.41421356237309504880
+#endif
+
+
+#define         CRC16_POLYNOMIAL        0x8005
+
+#define MAX_BITS_PER_CHANNEL 4095
+#define MAX_BITS_PER_GRANULE 7680
+
+/* "bit_stream.h" Definitions */
+#define         BUFFER_SIZE     LAME_MAXMP3BUFFER
+
+#define         Min(A, B)       ((A) < (B) ? (A) : (B))
+#define         Max(A, B)       ((A) > (B) ? (A) : (B))
+
+/* log/log10 approximations */
+#ifdef USE_FAST_LOG
+#define         FAST_LOG10(x)       (fast_log2(x)*(LOG2/LOG10))
+#define         FAST_LOG(x)         (fast_log2(x)*LOG2)
+#define         FAST_LOG10_X(x,y)   (fast_log2(x)*(LOG2/LOG10*(y)))
+#define         FAST_LOG_X(x,y)     (fast_log2(x)*(LOG2*(y)))
+#else
+#define         FAST_LOG10(x)       log10(x)
+#define         FAST_LOG(x)         log(x)
+#define         FAST_LOG10_X(x,y)   (log10(x)*(y))
+#define         FAST_LOG_X(x,y)     (log(x)*(y))
+#endif
+
+
+    struct replaygain_data;
+#ifndef replaygain_data_defined
+#define replaygain_data_defined
+    typedef struct replaygain_data replaygain_t;
+#endif
+    struct plotting_data;
+#ifndef plotting_data_defined
+#define plotting_data_defined
+    typedef struct plotting_data plotting_data;
+#endif
+
+/***********************************************************************
+*
+*  Global Type Definitions
+*
+***********************************************************************/
+
+    typedef struct {
+        void   *aligned;     /* pointer to ie. 128 bit aligned memory */
+        void   *pointer;     /* to use with malloc/free */
+    } aligned_pointer_t;
+
+    void    calloc_aligned(aligned_pointer_t * ptr, unsigned int size, unsigned int bytes);
+    void    free_aligned(aligned_pointer_t * ptr);
+
+
+    /* "bit_stream.h" Type Definitions */
+
+    typedef struct bit_stream_struc {
+        unsigned char *buf;  /* bit stream buffer */
+        int     buf_size;    /* size of buffer (in number of bytes) */
+        int     totbit;      /* bit counter of bit stream */
+        int     buf_byte_idx; /* pointer to top byte in buffer */
+        int     buf_bit_idx; /* pointer to top bit of top byte in buffer */
+
+        /* format of file in rd mode (BINARY/ASCII) */
+    } Bit_stream_struc;
+
+
+
+    typedef struct {
+        int     sum;         /* what we have seen so far */
+        int     seen;        /* how many frames we have seen in this chunk */
+        int     want;        /* how many frames we want to collect into one chunk */
+        int     pos;         /* actual position in our bag */
+        int     size;        /* size of our bag */
+        int    *bag;         /* pointer to our bag */
+        unsigned int nVbrNumFrames;
+        unsigned long nBytesWritten;
+        /* VBR tag data */
+        unsigned int TotalFrameSize;
+    } VBR_seek_info_t;
+
+
+    /**
+     *  ATH related stuff, if something new ATH related has to be added,
+     *  please plugg it here into the ATH_t struct
+     */
+    typedef struct {
+        int     use_adjust;  /* method for the auto adjustment  */
+        FLOAT   aa_sensitivity_p; /* factor for tuning the (sample power)
+                                     point below which adaptive threshold
+                                     of hearing adjustment occurs */
+        FLOAT   adjust_factor; /* lowering based on peak volume, 1 = no lowering */
+        FLOAT   adjust_limit; /* limit for dynamic ATH adjust */
+        FLOAT   decay;       /* determined to lower x dB each second */
+        FLOAT   floor;       /* lowest ATH value */
+        FLOAT   l[SBMAX_l];  /* ATH for sfbs in long blocks */
+        FLOAT   s[SBMAX_s];  /* ATH for sfbs in short blocks */
+        FLOAT   psfb21[PSFB21]; /* ATH for partitionned sfb21 in long blocks */
+        FLOAT   psfb12[PSFB12]; /* ATH for partitionned sfb12 in short blocks */
+        FLOAT   cb_l[CBANDS]; /* ATH for long block convolution bands */
+        FLOAT   cb_s[CBANDS]; /* ATH for short block convolution bands */
+        FLOAT   eql_w[BLKSIZE / 2]; /* equal loudness weights (based on ATH) */
+    } ATH_t;
+
+    /**
+     *  PSY Model related stuff
+     */
+
+    typedef struct {
+        FLOAT   masking_lower[CBANDS];
+        FLOAT   minval[CBANDS];
+        FLOAT   rnumlines[CBANDS];
+        FLOAT   mld_cb[CBANDS];
+        FLOAT   mld[Max(SBMAX_l,SBMAX_s)];
+        FLOAT   bo_weight[Max(SBMAX_l,SBMAX_s)]; /* band weight long scalefactor bands, at transition */
+        FLOAT   attack_threshold; /* short block tuning */
+        int     s3ind[CBANDS][2];
+        int     numlines[CBANDS];
+        int     bm[Max(SBMAX_l,SBMAX_s)];
+        int     bo[Max(SBMAX_l,SBMAX_s)];
+        int     npart;
+        int     n_sb; /* SBMAX_l or SBMAX_s */
+        FLOAT  *s3;
+    } PsyConst_CB2SB_t;
+
+
+    /**
+     *  global data constants
+     */
+    typedef struct {
+        FLOAT window[BLKSIZE], window_s[BLKSIZE_s / 2];
+        PsyConst_CB2SB_t l;
+        PsyConst_CB2SB_t s;
+        PsyConst_CB2SB_t l_to_s;
+        FLOAT   attack_threshold[4];
+        FLOAT   decay;
+        int     force_short_block_calc;
+    } PsyConst_t;
+
+
+    typedef struct {
+
+        FLOAT   nb_l1[4][CBANDS], nb_l2[4][CBANDS];
+        FLOAT   nb_s1[4][CBANDS], nb_s2[4][CBANDS];
+
+        III_psy_xmin thm[4];
+        III_psy_xmin en[4];
+
+        /* loudness calculation (for adaptive threshold of hearing) */
+        FLOAT   loudness_sq_save[2]; /* account for granule delay of L3psycho_anal */
+
+        FLOAT   tot_ener[4];
+
+        FLOAT   last_en_subshort[4][9];
+        int     last_attacks[4];
+
+        int     blocktype_old[2];
+    } PsyStateVar_t;
+
+
+    typedef struct {
+        /* loudness calculation (for adaptive threshold of hearing) */
+        FLOAT   loudness_sq[2][2]; /* loudness^2 approx. per granule and channel */
+    } PsyResult_t;
+
+
+    /* variables used by encoder.c */
+    typedef struct {
+        /* variables for newmdct.c */
+        FLOAT   sb_sample[2][2][18][SBLIMIT];
+        FLOAT   amp_filter[32];
+
+        /* variables used by util.c */
+        /* BPC = maximum number of filter convolution windows to precompute */
+#define BPC 320
+        double  itime[2]; /* float precision seems to be not enough */
+        sample_t *inbuf_old[2];
+        sample_t *blackfilt[2 * BPC + 1];
+
+        FLOAT   pefirbuf[19];
+        
+        /* used for padding */
+        int     frac_SpF;
+        int     slot_lag;
+
+        /* variables for bitstream.c */
+        /* mpeg1: buffer=511 bytes  smallest frame: 96-38(sideinfo)=58
+         * max number of frames in reservoir:  8
+         * mpeg2: buffer=255 bytes.  smallest frame: 24-23bytes=1
+         * with VBR, if you are encoding all silence, it is possible to
+         * have 8kbs/24khz frames with 1byte of data each, which means we need
+         * to buffer up to 255 headers! */
+        /* also, max_header_buf has to be a power of two */
+#define MAX_HEADER_BUF 256
+#define MAX_HEADER_LEN 40    /* max size of header is 38 */
+        struct {
+            int     write_timing;
+            int     ptr;
+            char    buf[MAX_HEADER_LEN];
+        } header[MAX_HEADER_BUF];
+
+        int     h_ptr;
+        int     w_ptr;
+        int     ancillary_flag;
+
+        /* variables for reservoir.c */
+        int     ResvSize;    /* in bits */
+        int     ResvMax;     /* in bits */
+
+        int     in_buffer_nsamples;
+        sample_t *in_buffer_0;
+        sample_t *in_buffer_1;
+
+#ifndef  MFSIZE
+# define MFSIZE  ( 3*1152 + ENCDELAY - MDCTDELAY )
+#endif
+        sample_t mfbuf[2][MFSIZE];
+
+        int     mf_samples_to_encode;
+        int     mf_size;
+
+    } EncStateVar_t;
+
+
+    typedef struct {
+        /* simple statistics */
+        int     bitrate_channelmode_hist[16][4 + 1];
+        int     bitrate_blocktype_hist[16][4 + 1 + 1]; /*norm/start/short/stop/mixed(short)/sum */
+
+        int     bitrate_index;
+        int     frame_number; /* number of frames encoded             */
+        int     padding;     /* padding for the current frame? */
+        int     mode_ext;
+        int     encoder_delay;
+        int     encoder_padding; /* number of samples of padding appended to input */
+    } EncResult_t;
+
+
+    /* variables used by quantize.c */
+    typedef struct {
+        /* variables for nspsytune */
+        FLOAT   longfact[SBMAX_l];
+        FLOAT   shortfact[SBMAX_s];
+        FLOAT   masking_lower;
+        FLOAT   mask_adjust; /* the dbQ stuff */
+        FLOAT   mask_adjust_short; /* the dbQ stuff */
+        int     OldValue[2];
+        int     CurrentStep[2];
+        int     pseudohalf[SFBMAX];
+        int     sfb21_extra; /* will be set in lame_init_params */
+        int     substep_shaping; /* 0 = no substep
+                                    1 = use substep shaping at last step(VBR only)
+                                    (not implemented yet)
+                                    2 = use substep inside loop
+                                    3 = use substep inside loop and last step
+                                  */
+
+
+        char    bv_scf[576];
+    } QntStateVar_t;
+
+
+    typedef struct {
+        replaygain_t *rgdata;
+        /* ReplayGain */
+    } RpgStateVar_t;
+
+
+    typedef struct {
+        FLOAT   noclipScale; /* user-specified scale factor required for preventing clipping */
+        sample_t PeakSample;
+        int     RadioGain;
+        int     noclipGainChange; /* gain change required for preventing clipping */
+    } RpgResult_t;
+
+
+    typedef struct {
+        int     version;     /* 0=MPEG-2/2.5  1=MPEG-1               */
+        int     samplerate_index;
+        int     sideinfo_len;
+
+        int     noise_shaping; /* 0 = none
+                                  1 = ISO AAC model
+                                  2 = allow scalefac_select=1
+                                */
+
+        int     subblock_gain; /*  0 = no, 1 = yes */
+        int     use_best_huffman; /* 0 = no.  1=outside loop  2=inside loop(slow) */
+        int     noise_shaping_amp; /*  0 = ISO model: amplify all distorted bands
+                                      1 = amplify within 50% of max (on db scale)
+                                      2 = amplify only most distorted band
+                                      3 = method 1 and refine with method 2
+                                    */
+
+        int     noise_shaping_stop; /* 0 = stop at over=0, all scalefacs amplified or
+                                       a scalefac has reached max value
+                                       1 = stop when all scalefacs amplified or
+                                       a scalefac has reached max value
+                                       2 = stop when all scalefacs amplified
+                                     */
+
+
+        int     full_outer_loop; /* 0 = stop early after 0 distortion found. 1 = full search */
+
+        int     lowpassfreq;
+        int     highpassfreq;
+        int     samplerate_in; /* input_samp_rate in Hz. default=44.1 kHz     */
+        int     samplerate_out; /* output_samp_rate. */
+        int     channels_in; /* number of channels in the input data stream (PCM or decoded PCM) */
+        int     channels_out; /* number of channels in the output data stream (not used for decoding) */
+        int     mode_gr;     /* granules per frame */
+        int     force_ms;    /* force M/S mode.  requires mode=1            */
+
+        int     quant_comp;
+        int     quant_comp_short;
+
+        int     use_temporal_masking_effect;
+        int     use_safe_joint_stereo;
+
+        int     preset;
+
+        vbr_mode vbr;
+        int     vbr_avg_bitrate_kbps;
+        int     vbr_min_bitrate_index; /* min bitrate index */
+        int     vbr_max_bitrate_index; /* max bitrate index */
+        int     avg_bitrate;
+        int     enforce_min_bitrate; /* strictly enforce VBR_min_bitrate normaly, it will be violated for analog silence */
+
+        int     findReplayGain; /* find the RG value? default=0       */
+        int     findPeakSample;
+        int     decode_on_the_fly; /* decode on the fly? default=0                */
+        int     analysis;
+        int     disable_reservoir;
+        int     buffer_constraint;  /* enforce ISO spec as much as possible   */
+        int     free_format;
+        int     write_lame_tag; /* add Xing VBR tag?                           */
+
+        int     error_protection; /* use 2 bytes per frame for a CRC checksum. default=0 */
+        int     copyright;   /* mark as copyright. default=0           */
+        int     original;    /* mark as original. default=1            */
+        int     extension;   /* the MP3 'private extension' bit. Meaningless */
+        int     emphasis;    /* Input PCM is emphased PCM (for
+                                instance from one of the rarely
+                                emphased CDs), it is STRONGLY not
+                                recommended to use this, because
+                                psycho does not take it into account,
+                                and last but not least many decoders
+                                don't care about these bits          */
+
+
+        MPEG_mode mode;
+        short_block_t short_blocks;
+
+        float   interChRatio;
+        float   msfix;       /* Naoki's adjustment of Mid/Side maskings */
+        float   ATH_offset_db;/* add to ATH this many db            */
+        float   ATH_offset_factor;/* change ATH by this factor, derived from ATH_offset_db */
+        float   ATHcurve;    /* change ATH formula 4 shape           */
+        int     ATHtype;
+        int     ATHonly;     /* only use ATH                         */
+        int     ATHshort;    /* only use ATH for short blocks        */
+        int     noATH;       /* disable ATH                          */
+        
+        float   ATHfixpoint;
+
+        float   adjust_alto_db;
+        float   adjust_bass_db;
+        float   adjust_treble_db;
+        float   adjust_sfb21_db;
+
+        float   compression_ratio; /* sizeof(wav file)/sizeof(mp3 file)          */
+
+        /* lowpass and highpass filter control */
+        FLOAT   lowpass1, lowpass2; /* normalized frequency bounds of passband */
+        FLOAT   highpass1, highpass2; /* normalized frequency bounds of passband */
+
+        /* scale input by this amount before encoding at least not used for MP3 decoding */
+        FLOAT   pcm_transform[2][2];
+
+        FLOAT   minval;
+    } SessionConfig_t;
+
+
+    struct lame_internal_flags {
+
+  /********************************************************************
+   * internal variables NOT set by calling program, and should not be *
+   * modified by the calling program                                  *
+   ********************************************************************/
+
+        /*
+         * Some remarks to the Class_ID field:
+         * The Class ID is an Identifier for a pointer to this struct.
+         * It is very unlikely that a pointer to lame_global_flags has the same 32 bits
+         * in it's structure (large and other special properties, for instance prime).
+         *
+         * To test that the structure is right and initialized, use:
+         *     if ( gfc -> Class_ID == LAME_ID ) ...
+         * Other remark:
+         *     If you set a flag to 0 for uninit data and 1 for init data, the right test
+         *     should be "if (flag == 1)" and NOT "if (flag)". Unintended modification
+         *     of this element will be otherwise misinterpreted as an init.
+         */
+#  define  LAME_ID   0xFFF88E3B
+        unsigned long class_id;
+
+        int     lame_init_params_successful;
+        int     lame_encode_frame_init;
+        int     iteration_init_init;
+        int     fill_buffer_resample_init;
+
+        SessionConfig_t cfg;
+
+        /* variables used by lame.c */
+        Bit_stream_struc bs;
+        III_side_info_t l3_side;
+
+        scalefac_struct scalefac_band;
+
+        PsyStateVar_t sv_psy; /* DATA FROM PSYMODEL.C */
+        PsyResult_t ov_psy;
+        EncStateVar_t sv_enc; /* DATA FROM ENCODER.C */
+        EncResult_t ov_enc;
+        QntStateVar_t sv_qnt; /* DATA FROM QUANTIZE.C */
+
+        RpgStateVar_t sv_rpg;
+        RpgResult_t ov_rpg;
+
+        /* optional ID3 tags, used in id3tag.c  */
+        struct id3tag_spec tag_spec;
+        uint16_t nMusicCRC;
+
+        uint16_t _unused;
+
+        /* CPU features */
+        struct {
+            unsigned int MMX:1; /* Pentium MMX, Pentium II...IV, K6, K6-2,
+                                   K6-III, Athlon */
+            unsigned int AMD_3DNow:1; /* K6-2, K6-III, Athlon      */
+            unsigned int SSE:1; /* Pentium III, Pentium 4    */
+            unsigned int SSE2:1; /* Pentium 4, K8             */
+            unsigned int _unused:28;
+        } CPU_features;
+
+
+        VBR_seek_info_t VBR_seek_table; /* used for Xing VBR header */
+
+        ATH_t  *ATH;         /* all ATH related stuff */
+
+        PsyConst_t *cd_psy;
+
+        /* used by the frame analyzer */
+        plotting_data *pinfo;
+        hip_t hip;
+
+        /* functions to replace with CPU feature optimized versions in takehiro.c */
+        int     (*choose_table) (const int *ix, const int *const end, int *const s);
+        void    (*fft_fht) (FLOAT *, int);
+        void    (*init_xrpow_core) (gr_info * const cod_info, FLOAT xrpow[576], int upper,
+                                    FLOAT * sum);
+
+        lame_report_function report_msg;
+        lame_report_function report_dbg;
+        lame_report_function report_err;
+    };
+
+#ifndef lame_internal_flags_defined
+#define lame_internal_flags_defined
+    typedef struct lame_internal_flags lame_internal_flags;
+#endif
+
+
+/***********************************************************************
+*
+*  Global Function Prototype Declarations
+*
+***********************************************************************/
+    void    freegfc(lame_internal_flags * const gfc);
+    void    free_id3tag(lame_internal_flags * const gfc);
+    extern int BitrateIndex(int, int, int);
+    extern int FindNearestBitrate(int, int, int);
+    extern int map2MP3Frequency(int freq);
+    extern int SmpFrqIndex(int, int *const);
+    extern int nearestBitrateFullIndex(uint16_t brate);
+    extern FLOAT ATHformula(SessionConfig_t const *cfg, FLOAT freq);
+    extern FLOAT freq2bark(FLOAT freq);
+    void    disable_FPE(void);
+
+/* log/log10 approximations */
+    extern void init_log_table(void);
+    extern ieee754_float32_t fast_log2(ieee754_float32_t x);
+
+    int     isResamplingNecessary(SessionConfig_t const* cfg);
+
+    void    fill_buffer(lame_internal_flags * gfc,
+                        sample_t *const mfbuf[2],
+                        sample_t const *const in_buffer[2], int nsamples, int *n_in, int *n_out);
+
+/* same as lame_decode1 (look in lame.h), but returns
+   unclipped raw floating-point samples. It is declared
+   here, not in lame.h, because it returns LAME's
+   internal type sample_t. No more than 1152 samples
+   per channel are allowed. */
+    int     hip_decode1_unclipped(hip_t hip, unsigned char *mp3buf,
+                                   size_t len, sample_t pcm_l[], sample_t pcm_r[]);
+
+
+    extern int has_MMX(void);
+    extern int has_3DNow(void);
+    extern int has_SSE(void);
+    extern int has_SSE2(void);
+
+
+
+/***********************************************************************
+*
+*  Macros about Message Printing and Exit
+*
+***********************************************************************/
+
+    extern void lame_report_def(const char* format, va_list args);
+    extern void lame_report_fnc(lame_report_function print_f, const char *, ...);
+    extern void lame_errorf(const lame_internal_flags * gfc, const char *, ...);
+    extern void lame_debugf(const lame_internal_flags * gfc, const char *, ...);
+    extern void lame_msgf(const lame_internal_flags * gfc, const char *, ...);
+#define DEBUGF  lame_debugf
+#define ERRORF  lame_errorf
+#define MSGF    lame_msgf
+
+    int     is_lame_internal_flags_valid(const lame_internal_flags * gfp);
+    
+    extern void hip_set_pinfo(hip_t hip, plotting_data* pinfo);
+
+#ifdef __cplusplus
+}
+#endif
+#endif                       /* LAME_UTIL_H */
diff --git a/lame/libmp3lame/vbrquantize.c b/lame/libmp3lame/vbrquantize.c
new file mode 100644 (file)
index 0000000..0f703b7
--- /dev/null
@@ -0,0 +1,1580 @@
+/*
+ *     MP3 quantization
+ *
+ *     Copyright (c) 1999-2000 Mark Taylor
+ *     Copyright (c) 2000-2012 Robert Hegemann
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* $Id: vbrquantize.c,v 1.142 2012/02/07 13:36:35 robert Exp $ */
+
+#ifdef HAVE_CONFIG_H
+#  include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+#include "encoder.h"
+#include "util.h"
+#include "vbrquantize.h"
+#include "quantize_pvt.h"
+
+
+
+
+struct algo_s;
+typedef struct algo_s algo_t;
+
+typedef void (*alloc_sf_f) (const algo_t *, const int *, const int *, int);
+typedef uint8_t (*find_sf_f) (const FLOAT *, const FLOAT *, FLOAT, unsigned int, uint8_t);
+
+struct algo_s {
+    alloc_sf_f alloc;
+    find_sf_f  find;
+    const FLOAT *xr34orig;
+    lame_internal_flags *gfc;
+    gr_info *cod_info;
+    int     mingain_l;
+    int     mingain_s[3];
+};
+
+
+
+/*  Remarks on optimizing compilers:
+ *
+ *  the MSVC compiler may get into aliasing problems when accessing
+ *  memory through the fi_union. declaring it volatile does the trick here
+ *
+ *  the calc_sfb_noise_* functions are not inlined because the intel compiler
+ *  optimized executeables won't work as expected anymore
+ */
+
+#ifdef _MSC_VER
+#  if _MSC_VER < 1400
+#  define VOLATILE volatile
+#  else
+#  define VOLATILE
+#  endif
+#else
+#  define VOLATILE
+#endif
+
+typedef VOLATILE union {
+    float   f;
+    int     i;
+} fi_union;
+
+
+
+#ifdef TAKEHIRO_IEEE754_HACK
+#define DOUBLEX double
+#else
+#define DOUBLEX FLOAT
+#endif
+#define MAGIC_FLOAT_def (65536*(128))
+#define MAGIC_INT_def    0x4b000000
+
+#ifdef TAKEHIRO_IEEE754_HACK
+#else
+/*********************************************************************
+ * XRPOW_FTOI is a macro to convert floats to ints.
+ * if XRPOW_FTOI(x) = nearest_int(x), then QUANTFAC(x)=adj43asm[x]
+ *                                         ROUNDFAC= -0.0946
+ *
+ * if XRPOW_FTOI(x) = floor(x), then QUANTFAC(x)=asj43[x]
+ *                                   ROUNDFAC=0.4054
+ *********************************************************************/
+#  define QUANTFAC(rx)  adj43[rx]
+#  define ROUNDFAC_def 0.4054f
+#  define XRPOW_FTOI(src,dest) ((dest) = (int)(src))
+#endif
+
+static int const MAGIC_INT = MAGIC_INT_def;
+#ifndef TAKEHIRO_IEEE754_HACK
+static DOUBLEX const ROUNDFAC = ROUNDFAC_def;
+#endif
+static DOUBLEX const MAGIC_FLOAT = MAGIC_FLOAT_def;
+
+
+inline static  float
+vec_max_c(const float * xr34, unsigned int bw)
+{
+    float   xfsf = 0;
+    unsigned int i = bw >> 2u;
+    unsigned int const remaining = (bw & 0x03u);
+
+    while (i-- > 0) {
+        if (xfsf < xr34[0]) {
+            xfsf = xr34[0];
+        }
+        if (xfsf < xr34[1]) {
+            xfsf = xr34[1];
+        }
+        if (xfsf < xr34[2]) {
+            xfsf = xr34[2];
+        }
+        if (xfsf < xr34[3]) {
+            xfsf = xr34[3];
+        }
+        xr34 += 4;
+    }
+    switch( remaining ) {
+    case 3: if (xfsf < xr34[2]) xfsf = xr34[2];
+    case 2: if (xfsf < xr34[1]) xfsf = xr34[1];
+    case 1: if (xfsf < xr34[0]) xfsf = xr34[0];
+    default: break;
+    }
+    return xfsf;
+}
+
+
+inline static  uint8_t
+find_lowest_scalefac(const FLOAT xr34)
+{
+    uint8_t sf_ok = 255;
+    uint8_t sf = 128, delsf = 64;
+    uint8_t i;
+    FLOAT const ixmax_val = IXMAX_VAL;
+    for (i = 0; i < 8; ++i) {
+        FLOAT const xfsf = ipow20[sf] * xr34;
+        if (xfsf <= ixmax_val) {
+            sf_ok = sf;
+            sf -= delsf;
+        }
+        else {
+            sf += delsf;
+        }
+        delsf >>= 1;
+    }
+    return sf_ok;
+}
+
+
+inline static void
+k_34_4(DOUBLEX x[4], int l3[4])
+{
+#ifdef TAKEHIRO_IEEE754_HACK
+    fi_union fi[4];
+
+    assert(x[0] <= IXMAX_VAL && x[1] <= IXMAX_VAL && x[2] <= IXMAX_VAL && x[3] <= IXMAX_VAL);
+    x[0] += MAGIC_FLOAT;
+    fi[0].f = x[0];
+    x[1] += MAGIC_FLOAT;
+    fi[1].f = x[1];
+    x[2] += MAGIC_FLOAT;
+    fi[2].f = x[2];
+    x[3] += MAGIC_FLOAT;
+    fi[3].f = x[3];
+    fi[0].f = x[0] + adj43asm[fi[0].i - MAGIC_INT];
+    fi[1].f = x[1] + adj43asm[fi[1].i - MAGIC_INT];
+    fi[2].f = x[2] + adj43asm[fi[2].i - MAGIC_INT];
+    fi[3].f = x[3] + adj43asm[fi[3].i - MAGIC_INT];
+    l3[0] = fi[0].i - MAGIC_INT;
+    l3[1] = fi[1].i - MAGIC_INT;
+    l3[2] = fi[2].i - MAGIC_INT;
+    l3[3] = fi[3].i - MAGIC_INT;
+#else
+    assert(x[0] <= IXMAX_VAL && x[1] <= IXMAX_VAL && x[2] <= IXMAX_VAL && x[3] <= IXMAX_VAL);
+    XRPOW_FTOI(x[0], l3[0]);
+    XRPOW_FTOI(x[1], l3[1]);
+    XRPOW_FTOI(x[2], l3[2]);
+    XRPOW_FTOI(x[3], l3[3]);
+    x[0] += QUANTFAC(l3[0]);
+    x[1] += QUANTFAC(l3[1]);
+    x[2] += QUANTFAC(l3[2]);
+    x[3] += QUANTFAC(l3[3]);
+    XRPOW_FTOI(x[0], l3[0]);
+    XRPOW_FTOI(x[1], l3[1]);
+    XRPOW_FTOI(x[2], l3[2]);
+    XRPOW_FTOI(x[3], l3[3]);
+#endif
+}
+
+
+
+
+
+/*  do call the calc_sfb_noise_* functions only with sf values
+ *  for which holds: sfpow34*xr34 <= IXMAX_VAL
+ */
+
+static  FLOAT
+calc_sfb_noise_x34(const FLOAT * xr, const FLOAT * xr34, unsigned int bw, uint8_t sf)
+{
+    DOUBLEX x[4];
+    int     l3[4];
+    const FLOAT sfpow = pow20[sf + Q_MAX2]; /*pow(2.0,sf/4.0); */
+    const FLOAT sfpow34 = ipow20[sf]; /*pow(sfpow,-3.0/4.0); */
+
+    FLOAT   xfsf = 0;
+    unsigned int i = bw >> 2u;
+    unsigned int const remaining = (bw & 0x03u);
+
+    while (i-- > 0) {
+        x[0] = sfpow34 * xr34[0];
+        x[1] = sfpow34 * xr34[1];
+        x[2] = sfpow34 * xr34[2];
+        x[3] = sfpow34 * xr34[3];
+
+        k_34_4(x, l3);
+
+        x[0] = fabsf(xr[0]) - sfpow * pow43[l3[0]];
+        x[1] = fabsf(xr[1]) - sfpow * pow43[l3[1]];
+        x[2] = fabsf(xr[2]) - sfpow * pow43[l3[2]];
+        x[3] = fabsf(xr[3]) - sfpow * pow43[l3[3]];
+        xfsf += (x[0] * x[0] + x[1] * x[1]) + (x[2] * x[2] + x[3] * x[3]);
+
+        xr += 4;
+        xr34 += 4;
+    }
+    if (remaining) {
+        x[0] = x[1] = x[2] = x[3] = 0;
+        switch( remaining ) {
+        case 3: x[2] = sfpow34 * xr34[2];
+        case 2: x[1] = sfpow34 * xr34[1];
+        case 1: x[0] = sfpow34 * xr34[0];
+        }
+
+        k_34_4(x, l3);
+        x[0] = x[1] = x[2] = x[3] = 0;
+
+        switch( remaining ) {
+        case 3: x[2] = fabsf(xr[2]) - sfpow * pow43[l3[2]];
+        case 2: x[1] = fabsf(xr[1]) - sfpow * pow43[l3[1]];
+        case 1: x[0] = fabsf(xr[0]) - sfpow * pow43[l3[0]];
+        }
+        xfsf += (x[0] * x[0] + x[1] * x[1]) + (x[2] * x[2] + x[3] * x[3]);
+    }
+    return xfsf;
+}
+
+
+
+struct calc_noise_cache {
+    int     valid;
+    FLOAT   value;
+};
+
+typedef struct calc_noise_cache calc_noise_cache_t;
+
+
+static  uint8_t
+tri_calc_sfb_noise_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw,
+                       uint8_t sf, calc_noise_cache_t * did_it)
+{
+    if (did_it[sf].valid == 0) {
+        did_it[sf].valid = 1;
+        did_it[sf].value = calc_sfb_noise_x34(xr, xr34, bw, sf);
+    }
+    if (l3_xmin < did_it[sf].value) {
+        return 1;
+    }
+    if (sf < 255) {
+        uint8_t const sf_x = sf + 1;
+        if (did_it[sf_x].valid == 0) {
+            did_it[sf_x].valid = 1;
+            did_it[sf_x].value = calc_sfb_noise_x34(xr, xr34, bw, sf_x);
+        }
+        if (l3_xmin < did_it[sf_x].value) {
+            return 1;
+        }
+    }
+    if (sf > 0) {
+        uint8_t const sf_x = sf - 1;
+        if (did_it[sf_x].valid == 0) {
+            did_it[sf_x].valid = 1;
+            did_it[sf_x].value = calc_sfb_noise_x34(xr, xr34, bw, sf_x);
+        }
+        if (l3_xmin < did_it[sf_x].value) {
+            return 1;
+        }
+    }
+    return 0;
+}
+
+
+/**
+ *  Robert Hegemann 2001-05-01
+ *  calculates quantization step size determined by allowed masking
+ */
+static int
+calc_scalefac(FLOAT l3_xmin, int bw)
+{
+    FLOAT const c = 5.799142446; /* 10 * 10^(2/3) * log10(4/3) */
+    return 210 + (int) (c * log10f(l3_xmin / bw) - .5f);
+}
+
+static uint8_t
+guess_scalefac_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw, uint8_t sf_min)
+{
+    int const guess = calc_scalefac(l3_xmin, bw);
+    if (guess < sf_min) return sf_min;
+    if (guess >= 255) return 255;
+    (void) xr;
+    (void) xr34;
+    return guess;
+}
+
+
+/* the find_scalefac* routines calculate
+ * a quantization step size which would
+ * introduce as much noise as is allowed.
+ * The larger the step size the more
+ * quantization noise we'll get. The
+ * scalefactors are there to lower the
+ * global step size, allowing limited
+ * differences in quantization step sizes
+ * per band (shaping the noise).
+ */
+
+static  uint8_t
+find_scalefac_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw,
+                  uint8_t sf_min)
+{
+    calc_noise_cache_t did_it[256];
+    uint8_t sf = 128, sf_ok = 255, delsf = 128, seen_good_one = 0, i;
+    memset(did_it, 0, sizeof(did_it));
+    for (i = 0; i < 8; ++i) {
+        delsf >>= 1;
+        if (sf <= sf_min) {
+            sf += delsf;
+        }
+        else {
+            uint8_t const bad = tri_calc_sfb_noise_x34(xr, xr34, l3_xmin, bw, sf, did_it);
+            if (bad) {  /* distortion.  try a smaller scalefactor */
+                sf -= delsf;
+            }
+            else {
+                sf_ok = sf;
+                sf += delsf;
+                seen_good_one = 1;
+            }
+        }
+    }
+    /*  returning a scalefac without distortion, if possible
+     */
+    if (seen_good_one > 0) {
+        sf = sf_ok;
+    }
+    if (sf <= sf_min) {
+        sf = sf_min;
+    }
+    return sf;
+}
+
+
+
+/***********************************************************************
+ *
+ *      calc_short_block_vbr_sf()
+ *      calc_long_block_vbr_sf()
+ *
+ *  Mark Taylor 2000-??-??
+ *  Robert Hegemann 2000-10-25 made functions of it
+ *
+ ***********************************************************************/
+
+/* a variation for vbr-mtrh */
+static int
+block_sf(algo_t * that, const FLOAT l3_xmin[SFBMAX], int vbrsf[SFBMAX], int vbrsfmin[SFBMAX])
+{
+    FLOAT   max_xr34;
+    const FLOAT *const xr = &that->cod_info->xr[0];
+    const FLOAT *const xr34_orig = &that->xr34orig[0];
+    const int *const width = &that->cod_info->width[0];
+    const char *const energy_above_cutoff = &that->cod_info->energy_above_cutoff[0];
+    unsigned int const max_nonzero_coeff = (unsigned int) that->cod_info->max_nonzero_coeff;
+    uint8_t maxsf = 0;
+    int     sfb = 0, m_o = -1;
+    unsigned int j = 0, i = 0;
+    int const psymax = that->cod_info->psymax;
+
+    assert(that->cod_info->max_nonzero_coeff >= 0);
+
+    that->mingain_l = 0;
+    that->mingain_s[0] = 0;
+    that->mingain_s[1] = 0;
+    that->mingain_s[2] = 0;
+    while (j <= max_nonzero_coeff) {
+        unsigned int const w = (unsigned int) width[sfb];
+        unsigned int const m = (unsigned int) (max_nonzero_coeff - j + 1);
+        unsigned int l = w;
+        uint8_t m1, m2;
+        if (l > m) {
+            l = m;
+        }
+        max_xr34 = vec_max_c(&xr34_orig[j], l);
+
+        m1 = find_lowest_scalefac(max_xr34);
+        vbrsfmin[sfb] = m1;
+        if (that->mingain_l < m1) {
+            that->mingain_l = m1;
+        }
+        if (that->mingain_s[i] < m1) {
+            that->mingain_s[i] = m1;
+        }
+        if (++i > 2) {
+            i = 0;
+        }
+        if (sfb < psymax && w > 2) { /* mpeg2.5 at 8 kHz doesn't use all scalefactors, unused have width 2 */
+            if (energy_above_cutoff[sfb]) {
+                m2 = that->find(&xr[j], &xr34_orig[j], l3_xmin[sfb], l, m1);
+#if 0
+                if (0) {
+                    /** Robert Hegemann 2007-09-29:
+                     *  It seems here is some more potential for speed improvements.
+                     *  Current find method does 11-18 quantization calculations.
+                     *  Using a "good guess" may help to reduce this amount.
+                     */
+                    uint8_t guess = calc_scalefac(l3_xmin[sfb], l);
+                    DEBUGF(that->gfc, "sfb=%3d guess=%3d found=%3d diff=%3d\n", sfb, guess, m2,
+                           m2 - guess);
+                }
+#endif
+                if (maxsf < m2) {
+                    maxsf = m2;
+                }
+                if (m_o < m2 && m2 < 255) {
+                    m_o = m2;
+                }
+            }
+            else {
+                m2 = 255;
+                maxsf = 255;
+            }
+        }
+        else {
+            if (maxsf < m1) {
+                maxsf = m1;
+            }
+            m2 = maxsf;
+        }
+        vbrsf[sfb] = m2;
+        ++sfb;
+        j += w;        
+    }
+    for (; sfb < SFBMAX; ++sfb) {
+        vbrsf[sfb] = maxsf;
+        vbrsfmin[sfb] = 0;
+    }
+    if (m_o > -1) {
+        maxsf = m_o;
+        for (sfb = 0; sfb < SFBMAX; ++sfb) {
+            if (vbrsf[sfb] == 255) {
+                vbrsf[sfb] = m_o;
+            }
+        }
+    }
+    return maxsf;
+}
+
+
+
+/***********************************************************************
+ *
+ *  quantize xr34 based on scalefactors
+ *
+ *  block_xr34
+ *
+ *  Mark Taylor 2000-??-??
+ *  Robert Hegemann 2000-10-20 made functions of them
+ *
+ ***********************************************************************/
+
+static void
+quantize_x34(const algo_t * that)
+{
+    DOUBLEX x[4];
+    const FLOAT *xr34_orig = that->xr34orig;
+    gr_info *const cod_info = that->cod_info;
+    int const ifqstep = (cod_info->scalefac_scale == 0) ? 2 : 4;
+    int    *l3 = cod_info->l3_enc;
+    unsigned int j = 0, sfb = 0;
+    unsigned int const max_nonzero_coeff = (unsigned int) cod_info->max_nonzero_coeff;
+
+    assert(cod_info->max_nonzero_coeff >= 0);
+    assert(cod_info->max_nonzero_coeff < 576);
+
+    while (j <= max_nonzero_coeff) {
+        int const s =
+            (cod_info->scalefac[sfb] + (cod_info->preflag ? pretab[sfb] : 0)) * ifqstep
+            + cod_info->subblock_gain[cod_info->window[sfb]] * 8;
+        uint8_t const sfac = (uint8_t) (cod_info->global_gain - s);
+        FLOAT const sfpow34 = ipow20[sfac];
+        unsigned int const w = (unsigned int) cod_info->width[sfb];
+        unsigned int const m = (unsigned int) (max_nonzero_coeff - j + 1);
+        unsigned int i, remaining;
+
+        assert((cod_info->global_gain - s) >= 0);
+        assert(cod_info->width[sfb] >= 0);
+        j += w;
+        ++sfb;
+        
+        i = (w <= m) ? w : m;
+        remaining = (i & 0x03u);
+        i >>= 2u;
+
+        while (i-- > 0) {
+            x[0] = sfpow34 * xr34_orig[0];
+            x[1] = sfpow34 * xr34_orig[1];
+            x[2] = sfpow34 * xr34_orig[2];
+            x[3] = sfpow34 * xr34_orig[3];
+
+            k_34_4(x, l3);
+
+            l3 += 4;
+            xr34_orig += 4;
+        }
+        if (remaining) {
+            int tmp_l3[4];
+            x[0] = x[1] = x[2] = x[3] = 0;
+            switch( remaining ) {
+            case 3: x[2] = sfpow34 * xr34_orig[2];
+            case 2: x[1] = sfpow34 * xr34_orig[1];
+            case 1: x[0] = sfpow34 * xr34_orig[0];
+            }
+
+            k_34_4(x, tmp_l3);
+
+            switch( remaining ) {
+            case 3: l3[2] = tmp_l3[2];
+            case 2: l3[1] = tmp_l3[1];
+            case 1: l3[0] = tmp_l3[0];
+            }
+
+            l3 += remaining;
+            xr34_orig += remaining;
+        }
+    }
+}
+
+
+
+static const uint8_t max_range_short[SBMAX_s * 3] = {
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+    0, 0, 0
+};
+
+static const uint8_t max_range_long[SBMAX_l] = {
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0
+};
+
+static const uint8_t max_range_long_lsf_pretab[SBMAX_l] = {
+    7, 7, 7, 7, 7, 7, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+
+
+/*
+    sfb=0..5  scalefac < 16
+    sfb>5     scalefac < 8
+
+    ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
+    ol_sf =  (cod_info->global_gain-210.0);
+    ol_sf -= 8*cod_info->subblock_gain[i];
+    ol_sf -= ifqstep*scalefac[gr][ch].s[sfb][i];
+*/
+
+static void
+set_subblock_gain(gr_info * cod_info, const int mingain_s[3], int sf[])
+{
+    const int maxrange1 = 15, maxrange2 = 7;
+    const int ifqstepShift = (cod_info->scalefac_scale == 0) ? 1 : 2;
+    int    *const sbg = cod_info->subblock_gain;
+    unsigned int const psymax = (unsigned int) cod_info->psymax;
+    unsigned int psydiv = 18;
+    int     sbg0, sbg1, sbg2;
+    unsigned int sfb, i;
+    int     min_sbg = 7;
+
+    if (psydiv > psymax) {
+        psydiv = psymax;
+    }
+    for (i = 0; i < 3; ++i) {
+        int     maxsf1 = 0, maxsf2 = 0, minsf = 1000;
+        /* see if we should use subblock gain */
+        for (sfb = i; sfb < psydiv; sfb += 3) { /* part 1 */
+            int const v = -sf[sfb];
+            if (maxsf1 < v) {
+                maxsf1 = v;
+            }
+            if (minsf > v) {
+                minsf = v;
+            }
+        }
+        for (; sfb < SFBMAX; sfb += 3) { /* part 2 */
+            int const v = -sf[sfb];
+            if (maxsf2 < v) {
+                maxsf2 = v;
+            }
+            if (minsf > v) {
+                minsf = v;
+            }
+        }
+
+        /* boost subblock gain as little as possible so we can
+         * reach maxsf1 with scalefactors
+         * 8*sbg >= maxsf1
+         */
+        {
+            int const m1 = maxsf1 - (maxrange1 << ifqstepShift);
+            int const m2 = maxsf2 - (maxrange2 << ifqstepShift);
+
+            maxsf1 = Max(m1, m2);
+        }
+        if (minsf > 0) {
+            sbg[i] = minsf >> 3;
+        }
+        else {
+            sbg[i] = 0;
+        }
+        if (maxsf1 > 0) {
+            int const m1 = sbg[i];
+            int const m2 = (maxsf1 + 7) >> 3;
+            sbg[i] = Max(m1, m2);
+        }
+        if (sbg[i] > 0 && mingain_s[i] > (cod_info->global_gain - sbg[i] * 8)) {
+            sbg[i] = (cod_info->global_gain - mingain_s[i]) >> 3;
+        }
+        if (sbg[i] > 7) {
+            sbg[i] = 7;
+        }
+        if (min_sbg > sbg[i]) {
+            min_sbg = sbg[i];
+        }
+    }
+    sbg0 = sbg[0] * 8;
+    sbg1 = sbg[1] * 8;
+    sbg2 = sbg[2] * 8;
+    for (sfb = 0; sfb < SFBMAX; sfb += 3) {
+        sf[sfb + 0] += sbg0;
+        sf[sfb + 1] += sbg1;
+        sf[sfb + 2] += sbg2;
+    }
+    if (min_sbg > 0) {
+        for (i = 0; i < 3; ++i) {
+            sbg[i] -= min_sbg;
+        }
+        cod_info->global_gain -= min_sbg * 8;
+    }
+}
+
+
+
+/*
+         ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;
+         ol_sf =  (cod_info->global_gain-210.0);
+         ol_sf -= ifqstep*scalefac[gr][ch].l[sfb];
+         if (cod_info->preflag && sfb>=11)
+         ol_sf -= ifqstep*pretab[sfb];
+*/
+static void
+set_scalefacs(gr_info * cod_info, const int *vbrsfmin, int sf[], const uint8_t * max_range)
+{
+    const int ifqstep = (cod_info->scalefac_scale == 0) ? 2 : 4;
+    const int ifqstepShift = (cod_info->scalefac_scale == 0) ? 1 : 2;
+    int    *const scalefac = cod_info->scalefac;
+    int const sfbmax = cod_info->sfbmax;
+    int     sfb;
+    int const *const sbg = cod_info->subblock_gain;
+    int const *const window = cod_info->window;
+    int const preflag = cod_info->preflag;
+
+    if (preflag) {
+        for (sfb = 11; sfb < sfbmax; ++sfb) {
+            sf[sfb] += pretab[sfb] * ifqstep;
+        }
+    }
+    for (sfb = 0; sfb < sfbmax; ++sfb) {
+        int const gain = cod_info->global_gain - (sbg[window[sfb]] * 8)
+            - ((preflag ? pretab[sfb] : 0) * ifqstep);
+
+        if (sf[sfb] < 0) {
+            int const m = gain - vbrsfmin[sfb];
+            /* ifqstep*scalefac >= -sf[sfb], so round UP */
+            scalefac[sfb] = (ifqstep - 1 - sf[sfb]) >> ifqstepShift;
+
+            if (scalefac[sfb] > max_range[sfb]) {
+                scalefac[sfb] = max_range[sfb];
+            }
+            if (scalefac[sfb] > 0 && (scalefac[sfb] << ifqstepShift) > m) {
+                scalefac[sfb] = m >> ifqstepShift;
+            }
+        }
+        else {
+            scalefac[sfb] = 0;
+        }
+    }
+    for (; sfb < SFBMAX; ++sfb) {
+        scalefac[sfb] = 0; /* sfb21 */
+    }
+}
+
+
+#ifndef NDEBUG
+static int
+checkScalefactor(const gr_info * cod_info, const int vbrsfmin[SFBMAX])
+{
+    int const ifqstep = cod_info->scalefac_scale == 0 ? 2 : 4;
+    int     sfb;
+    for (sfb = 0; sfb < cod_info->psymax; ++sfb) {
+        const int s =
+            ((cod_info->scalefac[sfb] +
+              (cod_info->preflag ? pretab[sfb] : 0)) * ifqstep) +
+            cod_info->subblock_gain[cod_info->window[sfb]] * 8;
+
+        if ((cod_info->global_gain - s) < vbrsfmin[sfb]) {
+            /*
+               fprintf( stdout, "sf %d\n", sfb );
+               fprintf( stdout, "min %d\n", vbrsfmin[sfb] );
+               fprintf( stdout, "ggain %d\n", cod_info->global_gain );
+               fprintf( stdout, "scalefac %d\n", cod_info->scalefac[sfb] );
+               fprintf( stdout, "pretab %d\n", (cod_info->preflag ? pretab[sfb] : 0) );
+               fprintf( stdout, "scale %d\n", (cod_info->scalefac_scale + 1) );
+               fprintf( stdout, "subgain %d\n", cod_info->subblock_gain[cod_info->window[sfb]] * 8 );
+               fflush( stdout );
+               exit(-1);
+             */
+            return 0;
+        }
+    }
+    return 1;
+}
+#endif
+
+
+/******************************************************************
+ *
+ *  short block scalefacs
+ *
+ ******************************************************************/
+
+static void
+short_block_constrain(const algo_t * that, const int vbrsf[SFBMAX],
+                      const int vbrsfmin[SFBMAX], int vbrmax)
+{
+    gr_info *const cod_info = that->cod_info;
+    lame_internal_flags const *const gfc = that->gfc;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int const maxminsfb = that->mingain_l;
+    int     mover, maxover0 = 0, maxover1 = 0, delta = 0;
+    int     v, v0, v1;
+    int     sfb;
+    int const psymax = cod_info->psymax;
+
+    for (sfb = 0; sfb < psymax; ++sfb) {
+        assert(vbrsf[sfb] >= vbrsfmin[sfb]);
+        v = vbrmax - vbrsf[sfb];
+        if (delta < v) {
+            delta = v;
+        }
+        v0 = v - (4 * 14 + 2 * max_range_short[sfb]);
+        v1 = v - (4 * 14 + 4 * max_range_short[sfb]);
+        if (maxover0 < v0) {
+            maxover0 = v0;
+        }
+        if (maxover1 < v1) {
+            maxover1 = v1;
+        }
+    }
+    if (cfg->noise_shaping == 2) {
+        /* allow scalefac_scale=1 */
+        mover = Min(maxover0, maxover1);
+    }
+    else {
+        mover = maxover0;
+    }
+    if (delta > mover) {
+        delta = mover;
+    }
+    vbrmax -= delta;
+    maxover0 -= mover;
+    maxover1 -= mover;
+
+    if (maxover0 == 0) {
+        cod_info->scalefac_scale = 0;
+    }
+    else if (maxover1 == 0) {
+        cod_info->scalefac_scale = 1;
+    }
+    if (vbrmax < maxminsfb) {
+        vbrmax = maxminsfb;
+    }
+    cod_info->global_gain = vbrmax;
+
+    if (cod_info->global_gain < 0) {
+        cod_info->global_gain = 0;
+    }
+    else if (cod_info->global_gain > 255) {
+        cod_info->global_gain = 255;
+    }
+    {
+        int     sf_temp[SFBMAX];
+        for (sfb = 0; sfb < SFBMAX; ++sfb) {
+            sf_temp[sfb] = vbrsf[sfb] - vbrmax;
+        }
+        set_subblock_gain(cod_info, &that->mingain_s[0], sf_temp);
+        set_scalefacs(cod_info, vbrsfmin, sf_temp, max_range_short);
+    }
+    assert(checkScalefactor(cod_info, vbrsfmin));
+}
+
+
+
+/******************************************************************
+ *
+ *  long block scalefacs
+ *
+ ******************************************************************/
+
+static void
+long_block_constrain(const algo_t * that, const int vbrsf[SFBMAX], const int vbrsfmin[SFBMAX],
+                     int vbrmax)
+{
+    gr_info *const cod_info = that->cod_info;
+    lame_internal_flags const *const gfc = that->gfc;
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    uint8_t const *max_rangep;
+    int const maxminsfb = that->mingain_l;
+    int     sfb;
+    int     maxover0, maxover1, maxover0p, maxover1p, mover, delta = 0;
+    int     v, v0, v1, v0p, v1p, vm0p = 1, vm1p = 1;
+    int const psymax = cod_info->psymax;
+
+    max_rangep = cfg->mode_gr == 2 ? max_range_long : max_range_long_lsf_pretab;
+
+    maxover0 = 0;
+    maxover1 = 0;
+    maxover0p = 0;      /* pretab */
+    maxover1p = 0;      /* pretab */
+
+    for (sfb = 0; sfb < psymax; ++sfb) {
+        assert(vbrsf[sfb] >= vbrsfmin[sfb]);
+        v = vbrmax - vbrsf[sfb];
+        if (delta < v) {
+            delta = v;
+        }
+        v0 = v - 2 * max_range_long[sfb];
+        v1 = v - 4 * max_range_long[sfb];
+        v0p = v - 2 * (max_rangep[sfb] + pretab[sfb]);
+        v1p = v - 4 * (max_rangep[sfb] + pretab[sfb]);
+        if (maxover0 < v0) {
+            maxover0 = v0;
+        }
+        if (maxover1 < v1) {
+            maxover1 = v1;
+        }
+        if (maxover0p < v0p) {
+            maxover0p = v0p;
+        }
+        if (maxover1p < v1p) {
+            maxover1p = v1p;
+        }
+    }
+    if (vm0p == 1) {
+        int     gain = vbrmax - maxover0p;
+        if (gain < maxminsfb) {
+            gain = maxminsfb;
+        }
+        for (sfb = 0; sfb < psymax; ++sfb) {
+            int const a = (gain - vbrsfmin[sfb]) - 2 * pretab[sfb];
+            if (a <= 0) {
+                vm0p = 0;
+                vm1p = 0;
+                break;
+            }
+        }
+    }
+    if (vm1p == 1) {
+        int     gain = vbrmax - maxover1p;
+        if (gain < maxminsfb) {
+            gain = maxminsfb;
+        }
+        for (sfb = 0; sfb < psymax; ++sfb) {
+            int const b = (gain - vbrsfmin[sfb]) - 4 * pretab[sfb];
+            if (b <= 0) {
+                vm1p = 0;
+                break;
+            }
+        }
+    }
+    if (vm0p == 0) {
+        maxover0p = maxover0;
+    }
+    if (vm1p == 0) {
+        maxover1p = maxover1;
+    }
+    if (cfg->noise_shaping != 2) {
+        maxover1 = maxover0;
+        maxover1p = maxover0p;
+    }
+    mover = Min(maxover0, maxover0p);
+    mover = Min(mover, maxover1);
+    mover = Min(mover, maxover1p);
+
+    if (delta > mover) {
+        delta = mover;
+    }
+    vbrmax -= delta;
+    if (vbrmax < maxminsfb) {
+        vbrmax = maxminsfb;
+    }
+    maxover0 -= mover;
+    maxover0p -= mover;
+    maxover1 -= mover;
+    maxover1p -= mover;
+
+    if (maxover0 == 0) {
+        cod_info->scalefac_scale = 0;
+        cod_info->preflag = 0;
+        max_rangep = max_range_long;
+    }
+    else if (maxover0p == 0) {
+        cod_info->scalefac_scale = 0;
+        cod_info->preflag = 1;
+    }
+    else if (maxover1 == 0) {
+        cod_info->scalefac_scale = 1;
+        cod_info->preflag = 0;
+        max_rangep = max_range_long;
+    }
+    else if (maxover1p == 0) {
+        cod_info->scalefac_scale = 1;
+        cod_info->preflag = 1;
+    }
+    else {
+        assert(0);      /* this should not happen */
+    }
+    cod_info->global_gain = vbrmax;
+    if (cod_info->global_gain < 0) {
+        cod_info->global_gain = 0;
+    }
+    else if (cod_info->global_gain > 255) {
+        cod_info->global_gain = 255;
+    }
+    {
+        int     sf_temp[SFBMAX];
+        for (sfb = 0; sfb < SFBMAX; ++sfb) {
+            sf_temp[sfb] = vbrsf[sfb] - vbrmax;
+        }
+        set_scalefacs(cod_info, vbrsfmin, sf_temp, max_rangep);
+    }
+    assert(checkScalefactor(cod_info, vbrsfmin));
+}
+
+
+
+static void
+bitcount(const algo_t * that)
+{
+    int     rc = scale_bitcount(that->gfc, that->cod_info);
+
+    if (rc == 0) {
+        return;
+    }
+    /*  this should not happen due to the way the scalefactors are selected  */
+    ERRORF(that->gfc, "INTERNAL ERROR IN VBR NEW CODE (986), please send bug report\n");
+    exit(-1);
+}
+
+
+
+static int
+quantizeAndCountBits(const algo_t * that)
+{
+    quantize_x34(that);
+    that->cod_info->part2_3_length = noquant_count_bits(that->gfc, that->cod_info, 0);
+    return that->cod_info->part2_3_length;
+}
+
+
+
+
+
+static int
+tryGlobalStepsize(const algo_t * that, const int sfwork[SFBMAX],
+                  const int vbrsfmin[SFBMAX], int delta)
+{
+    FLOAT const xrpow_max = that->cod_info->xrpow_max;
+    int     sftemp[SFBMAX], i, nbits;
+    int     gain, vbrmax = 0;
+    for (i = 0; i < SFBMAX; ++i) {
+        gain = sfwork[i] + delta;
+        if (gain < vbrsfmin[i]) {
+            gain = vbrsfmin[i];
+        }
+        if (gain > 255) {
+            gain = 255;
+        }
+        if (vbrmax < gain) {
+            vbrmax = gain;
+        }
+        sftemp[i] = gain;
+    }
+    that->alloc(that, sftemp, vbrsfmin, vbrmax);
+    bitcount(that);
+    nbits = quantizeAndCountBits(that);
+    that->cod_info->xrpow_max = xrpow_max;
+    return nbits;
+}
+
+
+
+static void
+searchGlobalStepsizeMax(const algo_t * that, const int sfwork[SFBMAX],
+                        const int vbrsfmin[SFBMAX], int target)
+{
+    gr_info const *const cod_info = that->cod_info;
+    const int gain = cod_info->global_gain;
+    int     curr = gain;
+    int     gain_ok = 1024;
+    int     nbits = LARGE_BITS;
+    int     l = gain, r = 512;
+
+    assert(gain >= 0);
+    while (l <= r) {
+        curr = (l + r) >> 1;
+        nbits = tryGlobalStepsize(that, sfwork, vbrsfmin, curr - gain);
+        if (nbits == 0 || (nbits + cod_info->part2_length) < target) {
+            r = curr - 1;
+            gain_ok = curr;
+        }
+        else {
+            l = curr + 1;
+            if (gain_ok == 1024) {
+                gain_ok = curr;
+            }
+        }
+    }
+    if (gain_ok != curr) {
+        curr = gain_ok;
+        nbits = tryGlobalStepsize(that, sfwork, vbrsfmin, curr - gain);
+    }
+}
+
+
+
+static int
+sfDepth(const int sfwork[SFBMAX])
+{
+    int     m = 0;
+    unsigned int i, j;
+    for (j = SFBMAX, i = 0; j > 0; --j, ++i) {
+        int const di = 255 - sfwork[i];
+        if (m < di) {
+            m = di;
+        }
+        assert(sfwork[i] >= 0);
+        assert(sfwork[i] <= 255);
+    }
+    assert(m >= 0);
+    assert(m <= 255);
+    return m;
+}
+
+
+static void
+cutDistribution(const int sfwork[SFBMAX], int sf_out[SFBMAX], int cut)
+{
+    unsigned int i, j;
+    for (j = SFBMAX, i = 0; j > 0; --j, ++i) {
+        int const x = sfwork[i];
+        sf_out[i] = x < cut ? x : cut;
+    }
+}
+
+
+static int
+flattenDistribution(const int sfwork[SFBMAX], int sf_out[SFBMAX], int dm, int k, int p)
+{
+    unsigned int i, j;
+    int     x, sfmax = 0;
+    if (dm > 0) {
+        for (j = SFBMAX, i = 0; j > 0; --j, ++i) {
+            int const di = p - sfwork[i];
+            x = sfwork[i] + (k * di) / dm;
+            if (x < 0) {
+                x = 0;
+            }
+            else {
+                if (x > 255) {
+                    x = 255;
+                }
+            }
+            sf_out[i] = x;
+            if (sfmax < x) {
+                sfmax = x;
+            }
+        }
+    }
+    else {
+        for (j = SFBMAX, i = 0; j > 0u; --j, ++i) {
+            x = sfwork[i];
+            sf_out[i] = x;
+            if (sfmax < x) {
+                sfmax = x;
+            }
+        }
+    }
+    return sfmax;
+}
+
+
+static int
+tryThatOne(algo_t const* that, const int sftemp[SFBMAX], const int vbrsfmin[SFBMAX], int vbrmax)
+{
+    FLOAT const xrpow_max = that->cod_info->xrpow_max;
+    int     nbits = LARGE_BITS;
+    that->alloc(that, sftemp, vbrsfmin, vbrmax);
+    bitcount(that);
+    nbits = quantizeAndCountBits(that);
+    nbits += that->cod_info->part2_length;
+    that->cod_info->xrpow_max = xrpow_max;
+    return nbits;
+}
+
+
+static void
+outOfBitsStrategy(algo_t const* that, const int sfwork[SFBMAX], const int vbrsfmin[SFBMAX], int target)
+{
+    int     wrk[SFBMAX];
+    int const dm = sfDepth(sfwork);
+    int const p = that->cod_info->global_gain;
+    int     nbits;
+
+    /* PART 1 */
+    {
+        int     bi = dm / 2;
+        int     bi_ok = -1;
+        int     bu = 0;
+        int     bo = dm;
+        for (;;) {
+            int const sfmax = flattenDistribution(sfwork, wrk, dm, bi, p);
+            nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);
+            if (nbits <= target) {
+                bi_ok = bi;
+                bo = bi - 1;
+            }
+            else {
+                bu = bi + 1;
+            }
+            if (bu <= bo) {
+                bi = (bu + bo) / 2;
+            }
+            else {
+                break;
+            }
+        }
+        if (bi_ok >= 0) {
+            if (bi != bi_ok) {
+                int const sfmax = flattenDistribution(sfwork, wrk, dm, bi_ok, p);
+                nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);
+            }
+            return;
+        }
+    }
+
+    /* PART 2: */
+    {
+        int     bi = (255 + p) / 2;
+        int     bi_ok = -1;
+        int     bu = p;
+        int     bo = 255;
+        for (;;) {
+            int const sfmax = flattenDistribution(sfwork, wrk, dm, dm, bi);
+            nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);
+            if (nbits <= target) {
+                bi_ok = bi;
+                bo = bi - 1;
+            }
+            else {
+                bu = bi + 1;
+            }
+            if (bu <= bo) {
+                bi = (bu + bo) / 2;
+            }
+            else {
+                break;
+            }
+        }
+        if (bi_ok >= 0) {
+            if (bi != bi_ok) {
+                int const sfmax = flattenDistribution(sfwork, wrk, dm, dm, bi_ok);
+                nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);
+            }
+            return;
+        }
+    }
+
+    /* fall back to old code, likely to be never called */
+    searchGlobalStepsizeMax(that, wrk, vbrsfmin, target);
+}
+
+
+static int
+reduce_bit_usage(lame_internal_flags * gfc, int gr, int ch
+#if 0
+                 , const FLOAT xr34orig[576], const FLOAT l3_xmin[SFBMAX], int maxbits
+#endif
+    )
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];
+    /*  try some better scalefac storage
+     */
+    best_scalefac_store(gfc, gr, ch, &gfc->l3_side);
+
+    /*  best huffman_divide may save some bits too
+     */
+    if (cfg->use_best_huffman == 1)
+        best_huffman_divide(gfc, cod_info);
+    return cod_info->part2_3_length + cod_info->part2_length;
+}
+
+
+
+
+int
+VBR_encode_frame(lame_internal_flags * gfc, const FLOAT xr34orig[2][2][576],
+                 const FLOAT l3_xmin[2][2][SFBMAX], const int max_bits[2][2])
+{
+    SessionConfig_t const *const cfg = &gfc->cfg;
+    int     sfwork_[2][2][SFBMAX];
+    int     vbrsfmin_[2][2][SFBMAX];
+    algo_t  that_[2][2];
+    int const ngr = cfg->mode_gr;
+    int const nch = cfg->channels_out;
+    int     max_nbits_ch[2][2] = {{0, 0}, {0 ,0}};
+    int     max_nbits_gr[2] = {0, 0};
+    int     max_nbits_fr = 0;
+    int     use_nbits_ch[2][2] = {{MAX_BITS_PER_CHANNEL+1, MAX_BITS_PER_CHANNEL+1}
+                                 ,{MAX_BITS_PER_CHANNEL+1, MAX_BITS_PER_CHANNEL+1}};
+    int     use_nbits_gr[2] = { MAX_BITS_PER_GRANULE+1, MAX_BITS_PER_GRANULE+1 };
+    int     use_nbits_fr = MAX_BITS_PER_GRANULE+MAX_BITS_PER_GRANULE;
+    int     gr, ch;
+    int     ok, sum_fr;
+
+    /* set up some encoding parameters
+     */
+    for (gr = 0; gr < ngr; ++gr) {
+        max_nbits_gr[gr] = 0;
+        for (ch = 0; ch < nch; ++ch) {
+            max_nbits_ch[gr][ch] = max_bits[gr][ch];
+            use_nbits_ch[gr][ch] = 0;
+            max_nbits_gr[gr] += max_bits[gr][ch];
+            max_nbits_fr += max_bits[gr][ch];
+            that_[gr][ch].find = (cfg->full_outer_loop < 0) ? guess_scalefac_x34 : find_scalefac_x34;
+            that_[gr][ch].gfc = gfc;
+            that_[gr][ch].cod_info = &gfc->l3_side.tt[gr][ch];
+            that_[gr][ch].xr34orig = xr34orig[gr][ch];
+            if (that_[gr][ch].cod_info->block_type == SHORT_TYPE) {
+                that_[gr][ch].alloc = short_block_constrain;
+            }
+            else {
+                that_[gr][ch].alloc = long_block_constrain;
+            }
+        }               /* for ch */
+    }
+    /* searches scalefactors
+     */
+    for (gr = 0; gr < ngr; ++gr) {
+        for (ch = 0; ch < nch; ++ch) {
+            if (max_bits[gr][ch] > 0) {
+                algo_t *that = &that_[gr][ch];
+                int    *sfwork = sfwork_[gr][ch];
+                int    *vbrsfmin = vbrsfmin_[gr][ch];
+                int     vbrmax;
+
+                vbrmax = block_sf(that, l3_xmin[gr][ch], sfwork, vbrsfmin);
+                that->alloc(that, sfwork, vbrsfmin, vbrmax);
+                bitcount(that);
+            }
+            else {
+                /*  xr contains no energy 
+                 *  l3_enc, our encoding data, will be quantized to zero
+                 *  continue with next channel
+                 */
+            }
+        }               /* for ch */
+    }
+    /* encode 'as is'
+     */
+    use_nbits_fr = 0;
+    for (gr = 0; gr < ngr; ++gr) {
+        use_nbits_gr[gr] = 0;
+        for (ch = 0; ch < nch; ++ch) {
+            algo_t const *that = &that_[gr][ch];
+            if (max_bits[gr][ch] > 0) {
+                memset(&that->cod_info->l3_enc[0], 0, sizeof(that->cod_info->l3_enc));
+                (void) quantizeAndCountBits(that);
+            }
+            else {
+                /*  xr contains no energy 
+                 *  l3_enc, our encoding data, will be quantized to zero
+                 *  continue with next channel
+                 */
+            }
+            use_nbits_ch[gr][ch] = reduce_bit_usage(gfc, gr, ch);
+            use_nbits_gr[gr] += use_nbits_ch[gr][ch];
+        }               /* for ch */
+        use_nbits_fr += use_nbits_gr[gr];
+    }
+
+    /* check bit constrains
+     */
+    if (use_nbits_fr <= max_nbits_fr) {
+        ok = 1;
+        for (gr = 0; gr < ngr; ++gr) {
+            if (use_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {
+                /* violates the rule that every granule has to use no more
+                 * bits than MAX_BITS_PER_GRANULE
+                 */
+                ok = 0;
+            }
+            for (ch = 0; ch < nch; ++ch) {
+                if (use_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {
+                    /* violates the rule that every gr_ch has to use no more
+                     * bits than MAX_BITS_PER_CHANNEL
+                     *
+                     * This isn't explicitly stated in the ISO docs, but the
+                     * part2_3_length field has only 12 bits, that makes it
+                     * up to a maximum size of 4095 bits!!!
+                     */
+                    ok = 0;
+                }
+            }
+        }
+        if (ok) {
+            return use_nbits_fr;
+        }
+    }
+    
+    /* OK, we are in trouble and have to define how many bits are
+     * to be used for each granule
+     */
+    {
+        ok = 1;
+        sum_fr = 0;
+
+        for (gr = 0; gr < ngr; ++gr) {
+            max_nbits_gr[gr] = 0;
+            for (ch = 0; ch < nch; ++ch) {
+                if (use_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {
+                    max_nbits_ch[gr][ch] = MAX_BITS_PER_CHANNEL;
+                }
+                else {
+                    max_nbits_ch[gr][ch] = use_nbits_ch[gr][ch];
+                }
+                max_nbits_gr[gr] += max_nbits_ch[gr][ch];
+            }
+            if (max_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {
+                float   f[2] = {0.0f, 0.0f}, s = 0.0f;
+                for (ch = 0; ch < nch; ++ch) {
+                    if (max_nbits_ch[gr][ch] > 0) {
+                        f[ch] = sqrt(sqrt(max_nbits_ch[gr][ch]));
+                        s += f[ch];
+                    }
+                    else {
+                        f[ch] = 0;
+                    }
+                }
+                for (ch = 0; ch < nch; ++ch) {
+                    if (s > 0) {
+                        max_nbits_ch[gr][ch] = MAX_BITS_PER_GRANULE * f[ch] / s;
+                    }
+                    else {
+                        max_nbits_ch[gr][ch] = 0;
+                    }
+                }
+                if (nch > 1) {
+                    if (max_nbits_ch[gr][0] > use_nbits_ch[gr][0] + 32) {
+                        max_nbits_ch[gr][1] += max_nbits_ch[gr][0];
+                        max_nbits_ch[gr][1] -= use_nbits_ch[gr][0] + 32;
+                        max_nbits_ch[gr][0] = use_nbits_ch[gr][0] + 32;
+                    }
+                    if (max_nbits_ch[gr][1] > use_nbits_ch[gr][1] + 32) {
+                        max_nbits_ch[gr][0] += max_nbits_ch[gr][1];
+                        max_nbits_ch[gr][0] -= use_nbits_ch[gr][1] + 32;
+                        max_nbits_ch[gr][1] = use_nbits_ch[gr][1] + 32;
+                    }
+                    if (max_nbits_ch[gr][0] > MAX_BITS_PER_CHANNEL) {
+                        max_nbits_ch[gr][0] = MAX_BITS_PER_CHANNEL;
+                    }
+                    if (max_nbits_ch[gr][1] > MAX_BITS_PER_CHANNEL) {
+                        max_nbits_ch[gr][1] = MAX_BITS_PER_CHANNEL;
+                    }
+                }
+                max_nbits_gr[gr] = 0;
+                for (ch = 0; ch < nch; ++ch) {
+                    max_nbits_gr[gr] += max_nbits_ch[gr][ch];
+                }
+            }
+            sum_fr += max_nbits_gr[gr];
+        }
+        if (sum_fr > max_nbits_fr) {
+            {
+                float   f[2] = {0.0f, 0.0f}, s = 0.0f;
+                for (gr = 0; gr < ngr; ++gr) {
+                    if (max_nbits_gr[gr] > 0) {
+                        f[gr] = sqrt(max_nbits_gr[gr]);
+                        s += f[gr];
+                    }
+                    else {
+                        f[gr] = 0;
+                    }
+                }
+                for (gr = 0; gr < ngr; ++gr) {
+                    if (s > 0) {
+                        max_nbits_gr[gr] = max_nbits_fr * f[gr] / s;
+                    }
+                    else {
+                        max_nbits_gr[gr] = 0;
+                    }
+                }
+            }
+            if (ngr > 1) {
+                if (max_nbits_gr[0] > use_nbits_gr[0] + 125) {
+                    max_nbits_gr[1] += max_nbits_gr[0];
+                    max_nbits_gr[1] -= use_nbits_gr[0] + 125;
+                    max_nbits_gr[0] = use_nbits_gr[0] + 125;
+                }
+                if (max_nbits_gr[1] > use_nbits_gr[1] + 125) {
+                    max_nbits_gr[0] += max_nbits_gr[1];
+                    max_nbits_gr[0] -= use_nbits_gr[1] + 125;
+                    max_nbits_gr[1] = use_nbits_gr[1] + 125;
+                }
+                for (gr = 0; gr < ngr; ++gr) {
+                    if (max_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {
+                        max_nbits_gr[gr] = MAX_BITS_PER_GRANULE;
+                    }
+                }
+            }
+            for (gr = 0; gr < ngr; ++gr) {
+                float   f[2] = {0.0f, 0.0f}, s = 0.0f;
+                for (ch = 0; ch < nch; ++ch) {
+                    if (max_nbits_ch[gr][ch] > 0) {
+                        f[ch] = sqrt(max_nbits_ch[gr][ch]);
+                        s += f[ch];
+                    }
+                    else {
+                        f[ch] = 0;
+                    }
+                }
+                for (ch = 0; ch < nch; ++ch) {
+                    if (s > 0) {
+                        max_nbits_ch[gr][ch] = max_nbits_gr[gr] * f[ch] / s;
+                    }
+                    else {
+                        max_nbits_ch[gr][ch] = 0;
+                    }
+                }
+                if (nch > 1) {
+                    if (max_nbits_ch[gr][0] > use_nbits_ch[gr][0] + 32) {
+                        max_nbits_ch[gr][1] += max_nbits_ch[gr][0];
+                        max_nbits_ch[gr][1] -= use_nbits_ch[gr][0] + 32;
+                        max_nbits_ch[gr][0] = use_nbits_ch[gr][0] + 32;
+                    }
+                    if (max_nbits_ch[gr][1] > use_nbits_ch[gr][1] + 32) {
+                        max_nbits_ch[gr][0] += max_nbits_ch[gr][1];
+                        max_nbits_ch[gr][0] -= use_nbits_ch[gr][1] + 32;
+                        max_nbits_ch[gr][1] = use_nbits_ch[gr][1] + 32;
+                    }
+                    for (ch = 0; ch < nch; ++ch) {
+                        if (max_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {
+                            max_nbits_ch[gr][ch] = MAX_BITS_PER_CHANNEL;
+                        }
+                    }
+                }
+            }
+        }
+        /* sanity check */
+        sum_fr = 0;
+        for (gr = 0; gr < ngr; ++gr) {
+            int     sum_gr = 0;
+            for (ch = 0; ch < nch; ++ch) {
+                sum_gr += max_nbits_ch[gr][ch];
+                if (max_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {
+                    ok = 0;
+                }
+            }
+            sum_fr += sum_gr;
+            if (sum_gr > MAX_BITS_PER_GRANULE) {
+                ok = 0;
+            }
+        }
+        if (sum_fr > max_nbits_fr) {
+            ok = 0;
+        }
+        if (!ok) {
+            /* we must have done something wrong, fallback to 'on_pe' based constrain */
+            for (gr = 0; gr < ngr; ++gr) {
+                for (ch = 0; ch < nch; ++ch) {
+                    max_nbits_ch[gr][ch] = max_bits[gr][ch];
+                }
+            }
+        }
+    }
+
+    /* we already called the 'best_scalefac_store' function, so we need to reset some
+     * variables before we can do it again.
+     */
+    for (ch = 0; ch < nch; ++ch) {
+        gfc->l3_side.scfsi[ch][0] = 0;
+        gfc->l3_side.scfsi[ch][1] = 0;
+        gfc->l3_side.scfsi[ch][2] = 0;
+        gfc->l3_side.scfsi[ch][3] = 0;
+    }
+    for (gr = 0; gr < ngr; ++gr) {
+        for (ch = 0; ch < nch; ++ch) {
+            gfc->l3_side.tt[gr][ch].scalefac_compress = 0;
+        }
+    }
+
+    /* alter our encoded data, until it fits into the target bitrate
+     */
+    use_nbits_fr = 0;
+    for (gr = 0; gr < ngr; ++gr) {
+        use_nbits_gr[gr] = 0;
+        for (ch = 0; ch < nch; ++ch) {
+            algo_t const *that = &that_[gr][ch];
+            use_nbits_ch[gr][ch] = 0;
+            if (max_bits[gr][ch] > 0) {
+                int    *sfwork = sfwork_[gr][ch];
+                int const *vbrsfmin = vbrsfmin_[gr][ch];
+                cutDistribution(sfwork, sfwork, that->cod_info->global_gain);
+                outOfBitsStrategy(that, sfwork, vbrsfmin, max_nbits_ch[gr][ch]);
+            }
+            use_nbits_ch[gr][ch] = reduce_bit_usage(gfc, gr, ch);
+            assert(use_nbits_ch[gr][ch] <= max_nbits_ch[gr][ch]);
+            use_nbits_gr[gr] += use_nbits_ch[gr][ch];
+        }               /* for ch */
+        use_nbits_fr += use_nbits_gr[gr];
+    }
+
+    /* check bit constrains, but it should always be ok, iff there are no bugs ;-)
+     */
+    if (use_nbits_fr <= max_nbits_fr) {
+        return use_nbits_fr;
+    }
+
+    ERRORF(gfc, "INTERNAL ERROR IN VBR NEW CODE (1313), please send bug report\n"
+           "maxbits=%d usedbits=%d\n", max_nbits_fr, use_nbits_fr);
+    exit(-1);
+}
diff --git a/lame/libmp3lame/vbrquantize.h b/lame/libmp3lame/vbrquantize.h
new file mode 100644 (file)
index 0000000..1c0d18f
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * MP3 VBR quantization
+ *
+ * Copyright (c) 1999 Mark Taylor
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_VBRQUANTIZE_H
+#define LAME_VBRQUANTIZE_H
+
+int     VBR_encode_frame(lame_internal_flags * gfc, const FLOAT xr34orig[2][2][576],
+                         const FLOAT l3_xmin[2][2][SFBMAX], const int maxbits[2][2]);
+
+#endif /* LAME_VBRQUANTIZE_H */
diff --git a/lame/libmp3lame/vector/lame_intrin.h b/lame/libmp3lame/vector/lame_intrin.h
new file mode 100644 (file)
index 0000000..bc4c189
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ *      lame_intrin.h include file
+ *
+ *      Copyright (c) 2006 Gabriel Bouvigne
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+
+#ifndef LAME_INTRIN_H
+#define LAME_INTRIN_H
+
+
+void
+init_xrpow_core_sse(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum);
+
+void
+fht_SSE2(FLOAT* , int);
+
+#endif
diff --git a/lame/libmp3lame/vector/xmm_quantize_sub.c b/lame/libmp3lame/vector/xmm_quantize_sub.c
new file mode 100644 (file)
index 0000000..e0948e2
--- /dev/null
@@ -0,0 +1,240 @@
+/*
+ * MP3 quantization, intrinsics functions
+ *
+ *      Copyright (c) 2005-2006 Gabriel Bouvigne
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "lame.h"
+#include "../machine.h"
+#include "../encoder.h"
+#include "../util.h"
+#include "lame_intrin.h"
+
+
+
+#ifdef HAVE_XMMINTRIN_H
+
+#include <xmmintrin.h>
+
+typedef union {
+    int32_t _i_32[4]; /* unions are initialized by its first member */
+    float   _float[4];
+    __m128  _m128;
+} vecfloat_union;
+
+#define TRI_SIZE (5-1)  /* 1024 =  4**5 */
+static const FLOAT costab[TRI_SIZE * 2] = {
+    9.238795325112867e-01, 3.826834323650898e-01,
+    9.951847266721969e-01, 9.801714032956060e-02,
+    9.996988186962042e-01, 2.454122852291229e-02,
+    9.999811752826011e-01, 6.135884649154475e-03
+};
+
+
+/* make sure functions with SSE instructions maintain their own properly aligned stack */
+#if defined (__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)))
+#define SSE_FUNCTION __attribute__((force_align_arg_pointer))
+#else
+#define SSE_FUNCTION
+#endif
+
+
+SSE_FUNCTION void
+init_xrpow_core_sse(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)
+{
+    int     i;
+    float   tmp_max = 0;
+    float   tmp_sum = 0;
+    int     upper4 = (upper / 4) * 4;
+    int     rest = upper-upper4;
+
+    const vecfloat_union fabs_mask = {{ 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF }};
+    const __m128 vec_fabs_mask = _mm_loadu_ps(&fabs_mask._float[0]);
+    vecfloat_union vec_xrpow_max;
+    vecfloat_union vec_sum;
+    vecfloat_union vec_tmp;
+
+    _mm_prefetch((char *) cod_info->xr, _MM_HINT_T0);
+    _mm_prefetch((char *) xrpow, _MM_HINT_T0);
+
+    vec_xrpow_max._m128 = _mm_set_ps1(0);
+    vec_sum._m128 = _mm_set_ps1(0);
+
+    for (i = 0; i < upper4; i += 4) {
+        vec_tmp._m128 = _mm_loadu_ps(&(cod_info->xr[i])); /* load */
+        vec_tmp._m128 = _mm_and_ps(vec_tmp._m128, vec_fabs_mask); /* fabs */
+        vec_sum._m128 = _mm_add_ps(vec_sum._m128, vec_tmp._m128);
+        vec_tmp._m128 = _mm_sqrt_ps(_mm_mul_ps(vec_tmp._m128, _mm_sqrt_ps(vec_tmp._m128)));
+        vec_xrpow_max._m128 = _mm_max_ps(vec_xrpow_max._m128, vec_tmp._m128); /* retrieve max */
+        _mm_storeu_ps(&(xrpow[i]), vec_tmp._m128); /* store into xrpow[] */
+    }
+    vec_tmp._m128 = _mm_set_ps1(0);
+    switch (rest) {
+        case 3: vec_tmp._float[2] = cod_info->xr[upper4+2];
+        case 2: vec_tmp._float[1] = cod_info->xr[upper4+1];
+        case 1: vec_tmp._float[0] = cod_info->xr[upper4+0];
+            vec_tmp._m128 = _mm_and_ps(vec_tmp._m128, vec_fabs_mask); /* fabs */
+            vec_sum._m128 = _mm_add_ps(vec_sum._m128, vec_tmp._m128);
+            vec_tmp._m128 = _mm_sqrt_ps(_mm_mul_ps(vec_tmp._m128, _mm_sqrt_ps(vec_tmp._m128)));
+            vec_xrpow_max._m128 = _mm_max_ps(vec_xrpow_max._m128, vec_tmp._m128); /* retrieve max */
+            switch (rest) {
+                case 3: xrpow[upper4+2] = vec_tmp._float[2];
+                case 2: xrpow[upper4+1] = vec_tmp._float[1];
+                case 1: xrpow[upper4+0] = vec_tmp._float[0];
+                default:
+                    break;
+            }
+        default:
+            break;
+    }
+    tmp_sum = vec_sum._float[0] + vec_sum._float[1] + vec_sum._float[2] + vec_sum._float[3];
+    {
+        float ma = vec_xrpow_max._float[0] > vec_xrpow_max._float[1]
+                ? vec_xrpow_max._float[0] : vec_xrpow_max._float[1];
+        float mb = vec_xrpow_max._float[2] > vec_xrpow_max._float[3]
+                ? vec_xrpow_max._float[2] : vec_xrpow_max._float[3];
+        tmp_max = ma > mb ? ma : mb;
+    }
+    cod_info->xrpow_max = tmp_max;
+    *sum = tmp_sum;
+}
+
+
+SSE_FUNCTION static void
+store4(__m128 v, float* f0, float* f1, float* f2, float* f3)
+{
+    vecfloat_union r;
+    r._m128 = v;
+    *f0 = r._float[0];
+    *f1 = r._float[1];
+    *f2 = r._float[2];
+    *f3 = r._float[3];
+}
+
+
+SSE_FUNCTION void
+fht_SSE2(FLOAT * fz, int n)
+{
+    const FLOAT *tri = costab;
+    int     k4;
+    FLOAT  *fi, *gi;
+    FLOAT const *fn;
+
+    n <<= 1;            /* to get BLKSIZE, because of 3DNow! ASM routine */
+    fn = fz + n;
+    k4 = 4;
+    do {
+        FLOAT   s1, c1;
+        int     i, k1, k2, k3, kx;
+        kx = k4 >> 1;
+        k1 = k4;
+        k2 = k4 << 1;
+        k3 = k2 + k1;
+        k4 = k2 << 1;
+        fi = fz;
+        gi = fi + kx;
+        do {
+            FLOAT   f0, f1, f2, f3;
+            f1 = fi[0] - fi[k1];
+            f0 = fi[0] + fi[k1];
+            f3 = fi[k2] - fi[k3];
+            f2 = fi[k2] + fi[k3];
+            fi[k2] = f0 - f2;
+            fi[0] = f0 + f2;
+            fi[k3] = f1 - f3;
+            fi[k1] = f1 + f3;
+            f1 = gi[0] - gi[k1];
+            f0 = gi[0] + gi[k1];
+            f3 = SQRT2 * gi[k3];
+            f2 = SQRT2 * gi[k2];
+            gi[k2] = f0 - f2;
+            gi[0] = f0 + f2;
+            gi[k3] = f1 - f3;
+            gi[k1] = f1 + f3;
+            gi += k4;
+            fi += k4;
+        } while (fi < fn);
+        c1 = tri[0];
+        s1 = tri[1];
+        for (i = 1; i < kx; i++) {
+            __m128 v_s2;
+            __m128 v_c2;
+            __m128 v_c1;
+            __m128 v_s1;
+            FLOAT   c2, s2, s1_2 = s1+s1;
+            c2 = 1 - s1_2 * s1;
+            s2 = s1_2 * c1;
+            fi = fz + i;
+            gi = fz + k1 - i;
+            v_c1 = _mm_set_ps1(c1);
+            v_s1 = _mm_set_ps1(s1);
+            v_c2 = _mm_set_ps1(c2);
+            v_s2 = _mm_set_ps1(s2);
+            {
+                static const vecfloat_union sign_mask = {{0x80000000,0,0,0}};
+                v_c1 = _mm_xor_ps(sign_mask._m128, v_c1); /* v_c1 := {-c1, +c1, +c1, +c1} */
+            }
+            {
+                static const vecfloat_union sign_mask = {{0,0x80000000,0,0}};
+                v_s1 = _mm_xor_ps(sign_mask._m128, v_s1); /* v_s1 := {+s1, -s1, +s1, +s1} */
+            }
+            {
+                static const vecfloat_union sign_mask = {{0,0,0x80000000,0x80000000}};
+                v_c2 = _mm_xor_ps(sign_mask._m128, v_c2); /* v_c2 := {+c2, +c2, -c2, -c2} */
+            }
+            do {
+                __m128 p, q, r;
+
+                q = _mm_setr_ps(fi[k1], fi[k3], gi[k1], gi[k3]); /* Q := {fi_k1,fi_k3,gi_k1,gi_k3}*/
+                p = _mm_mul_ps(_mm_set_ps1(s2), q);              /* P := s2 * Q */
+                q = _mm_mul_ps(v_c2, q);                         /* Q := c2 * Q */
+                q = _mm_shuffle_ps(q, q, _MM_SHUFFLE(1,0,3,2));  /* Q := {-c2*gi_k1,-c2*gi_k3,c2*fi_k1,c2*fi_k3} */
+                p = _mm_add_ps(p, q);
+                
+                r = _mm_setr_ps(gi[0], gi[k2], fi[0], fi[k2]);   /* R := {gi_0,gi_k2,fi_0,fi_k2} */
+                q = _mm_sub_ps(r, p);                            /* Q := {gi_0-p0,gi_k2-p1,fi_0-p2,fi_k2-p3} */
+                r = _mm_add_ps(r, p);                            /* R := {gi_0+p0,gi_k2+p1,fi_0+p2,fi_k2+p3} */
+                p = _mm_shuffle_ps(q, r, _MM_SHUFFLE(2,0,2,0));  /* P := {q0,q2,r0,r2} */
+                p = _mm_shuffle_ps(p, p, _MM_SHUFFLE(3,1,2,0));  /* P := {q0,r0,q2,r2} */
+                q = _mm_shuffle_ps(q, r, _MM_SHUFFLE(3,1,3,1));  /* Q := {q1,q3,r1,r3} */
+                r = _mm_mul_ps(v_c1, q);
+                q = _mm_mul_ps(v_s1, q);
+                q = _mm_shuffle_ps(q, q, _MM_SHUFFLE(0,1,2,3));  /* Q := {q3,q2,q1,q0} */
+                q = _mm_add_ps(q, r);
+
+                store4(_mm_sub_ps(p, q), &gi[k3], &gi[k2], &fi[k3], &fi[k2]);
+                store4(_mm_add_ps(p, q), &gi[k1], &gi[ 0], &fi[k1], &fi[ 0]);
+
+                gi += k4;
+                fi += k4;
+            } while (fi < fn);
+            c2 = c1;
+            c1 = c2 * tri[0] - s1 * tri[1];
+            s1 = c2 * tri[1] + s1 * tri[0];
+        }
+        tri += 2;
+    } while (k4 < n);
+}
+
+#endif /* HAVE_XMMINTRIN_H */
+
diff --git a/lame/libmp3lame/version.c b/lame/libmp3lame/version.c
new file mode 100644 (file)
index 0000000..2943406
--- /dev/null
@@ -0,0 +1,254 @@
+/*
+ *      Version numbering for LAME.
+ *
+ *      Copyright (c) 1999 A.L. Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/*!
+  \file   version.c
+  \brief  Version numbering for LAME.
+
+  Contains functions which describe the version of LAME.
+
+  \author A.L. Faber
+  \version \$Id: version.c,v 1.34 2011/11/18 09:51:02 robert Exp $
+  \ingroup libmp3lame
+*/
+
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+
+#include "lame.h"
+#include "machine.h"
+
+#include "version.h"    /* macros of version numbers */
+
+
+
+
+
+/*! Get the LAME version string. */
+/*!
+  \param void
+  \return a pointer to a string which describes the version of LAME.
+*/
+const char *
+get_lame_version(void)
+{                       /* primary to write screen reports */
+    /* Here we can also add informations about compile time configurations */
+
+#if   LAME_ALPHA_VERSION
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) " "
+        "(alpha " STR(LAME_PATCH_VERSION) ", " __DATE__ " " __TIME__ ")";
+#elif LAME_BETA_VERSION
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) " "
+        "(beta " STR(LAME_PATCH_VERSION) ", " __DATE__ ")";
+#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) "." STR(LAME_PATCH_VERSION);
+#else
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION);
+#endif
+
+    return str;
+}
+
+
+/*! Get the short LAME version string. */
+/*!
+  It's mainly for inclusion into the MP3 stream.
+
+  \param void   
+  \return a pointer to the short version of the LAME version string.
+*/
+const char *
+get_lame_short_version(void)
+{
+    /* adding date and time to version string makes it harder for output
+       validation */
+
+#if   LAME_ALPHA_VERSION
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) " (alpha " STR(LAME_PATCH_VERSION) ")";
+#elif LAME_BETA_VERSION
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) " (beta " STR(LAME_PATCH_VERSION) ")";
+#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) "." STR(LAME_PATCH_VERSION);
+#else
+    static /*@observer@ */ const char *const str =
+        STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION);
+#endif
+
+    return str;
+}
+
+/*! Get the _very_ short LAME version string. */
+/*!
+  It's used in the LAME VBR tag only.
+
+  \param void   
+  \return a pointer to the short version of the LAME version string.
+*/
+const char *
+get_lame_very_short_version(void)
+{
+    /* adding date and time to version string makes it harder for output
+       validation */
+#if   LAME_ALPHA_VERSION
+#define P "a"
+#elif LAME_BETA_VERSION
+#define P "b"
+#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)
+#define P "r"
+#else
+#define P " "
+#endif
+    static /*@observer@ */ const char *const str =
+#if (LAME_PATCH_VERSION > 0)
+      "LAME" STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) P STR(LAME_PATCH_VERSION)
+#else
+      "LAME" STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) P
+#endif
+      ;
+    return str;
+}
+
+/*! Get the _very_ short LAME version string. */
+/*!
+  It's used in the LAME VBR tag only, limited to 9 characters max.
+  Due to some 3rd party HW/SW decoders, it has to start with LAME.
+
+  \param void   
+  \return a pointer to the short version of the LAME version string.
+ */
+const char*
+get_lame_tag_encoder_short_version(void)
+{
+    static /*@observer@ */ const char *const str =
+            /* FIXME: new scheme / new version counting / drop versioning here ? */
+    "LAME" STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) P
+    ;
+    return str;
+}
+
+/*! Get the version string for GPSYCHO. */
+/*!
+  \param void
+  \return a pointer to a string which describes the version of GPSYCHO.
+*/
+const char *
+get_psy_version(void)
+{
+#if   PSY_ALPHA_VERSION > 0
+    static /*@observer@ */ const char *const str =
+        STR(PSY_MAJOR_VERSION) "." STR(PSY_MINOR_VERSION)
+        " (alpha " STR(PSY_ALPHA_VERSION) ", " __DATE__ " " __TIME__ ")";
+#elif PSY_BETA_VERSION > 0
+    static /*@observer@ */ const char *const str =
+        STR(PSY_MAJOR_VERSION) "." STR(PSY_MINOR_VERSION)
+        " (beta " STR(PSY_BETA_VERSION) ", " __DATE__ ")";
+#else
+    static /*@observer@ */ const char *const str =
+        STR(PSY_MAJOR_VERSION) "." STR(PSY_MINOR_VERSION);
+#endif
+
+    return str;
+}
+
+
+/*! Get the URL for the LAME website. */
+/*!
+  \param void
+  \return a pointer to a string which is a URL for the LAME website.
+*/
+const char *
+get_lame_url(void)
+{
+    static /*@observer@ */ const char *const str = LAME_URL;
+
+    return str;
+}
+
+
+/*! Get the numerical representation of the version. */
+/*!
+  Writes the numerical representation of the version of LAME and
+  GPSYCHO into lvp.
+
+  \param lvp    
+*/
+void
+get_lame_version_numerical(lame_version_t * lvp)
+{
+    static /*@observer@ */ const char *const features = ""; /* obsolete */
+
+    /* generic version */
+    lvp->major = LAME_MAJOR_VERSION;
+    lvp->minor = LAME_MINOR_VERSION;
+#if LAME_ALPHA_VERSION
+    lvp->alpha = LAME_PATCH_VERSION;
+    lvp->beta = 0;
+#elif LAME_BETA_VERSION
+    lvp->alpha = 0;
+    lvp->beta = LAME_PATCH_VERSION;
+#else
+    lvp->alpha = 0;
+    lvp->beta = 0;
+#endif
+
+    /* psy version */
+    lvp->psy_major = PSY_MAJOR_VERSION;
+    lvp->psy_minor = PSY_MINOR_VERSION;
+    lvp->psy_alpha = PSY_ALPHA_VERSION;
+    lvp->psy_beta = PSY_BETA_VERSION;
+
+    /* compile time features */
+    /*@-mustfree@ */
+    lvp->features = features;
+    /*@=mustfree@ */
+}
+
+
+const char *
+get_lame_os_bitness(void)
+{
+    static /*@observer@ */ const char *const strXX = "";
+    static /*@observer@ */ const char *const str32 = "32bits";
+    static /*@observer@ */ const char *const str64 = "64bits";
+
+    switch (sizeof(void *)) {
+    case 4:
+        return str32;
+
+    case 8:
+        return str64;
+
+    default:
+        return strXX;
+    }
+}
+
+/* end of version.c */
diff --git a/lame/libmp3lame/version.h b/lame/libmp3lame/version.h
new file mode 100644 (file)
index 0000000..f5fef50
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ *      Version numbering for LAME.
+ *
+ *      Copyright (c) 1999 A.L. Faber
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef LAME_VERSION_H
+#define LAME_VERSION_H
+
+
+/*
+ * To make a string from a token, use the # operator:
+ */
+#ifndef STR
+# define __STR(x)  #x
+# define STR(x)    __STR(x)
+#endif
+
+# define LAME_URL              "http://lame.sf.net"
+
+
+# define LAME_MAJOR_VERSION      3 /* Major version number */
+# define LAME_MINOR_VERSION    100 /* Minor version number */
+# define LAME_TYPE_VERSION       2 /* 0:alpha 1:beta 2:release */
+# define LAME_PATCH_VERSION      0 /* Patch level */
+# define LAME_ALPHA_VERSION     (LAME_TYPE_VERSION==0)
+# define LAME_BETA_VERSION      (LAME_TYPE_VERSION==1)
+# define LAME_RELEASE_VERSION   (LAME_TYPE_VERSION==2)
+
+# define PSY_MAJOR_VERSION       1 /* Major version number */
+# define PSY_MINOR_VERSION       0 /* Minor version number */
+# define PSY_ALPHA_VERSION       0 /* Set number if this is an alpha version, otherwise zero */
+# define PSY_BETA_VERSION        0 /* Set number if this is a beta version, otherwise zero */
+
+#if LAME_ALPHA_VERSION
+#define LAME_PATCH_LEVEL_STRING " alpha " STR(LAME_PATCH_VERSION)
+#endif
+#if LAME_BETA_VERSION
+#define LAME_PATCH_LEVEL_STRING " beta " STR(LAME_PATCH_VERSION)
+#endif
+#if LAME_RELEASE_VERSION
+#if LAME_PATCH_VERSION
+#define LAME_PATCH_LEVEL_STRING " release " STR(LAME_PATCH_VERSION)
+#else
+#define LAME_PATCH_LEVEL_STRING ""
+#endif
+#endif
+
+# define LAME_VERSION_STRING STR(LAME_MAJOR_VERSION) "." STR(LAME_MINOR_VERSION) LAME_PATCH_LEVEL_STRING
+
+#endif /* LAME_VERSION_H */
+
+/* End of version.h */
diff --git a/lgpl-2.0.txt b/lgpl-2.0.txt
new file mode 100644 (file)
index 0000000..5bc8fb2
--- /dev/null
@@ -0,0 +1,481 @@
+                  GNU LIBRARY GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL.  It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it.  You can use it for
+your libraries, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library.  If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+\f
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software.  To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+  Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs.  This
+license, the GNU Library General Public License, applies to certain
+designated libraries.  This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+  The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it.  Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program.  However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+  Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries.  We
+concluded that weaker conditions might promote sharing better.
+
+  However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves.  This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them.  (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.)  The hope is that this
+will lead to faster development of free libraries.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+  Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+\f
+                  GNU LIBRARY GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License").  Each licensee is
+addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    c) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    d) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                            NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/lgpl-2.1.txt b/lgpl-2.1.txt
new file mode 100644 (file)
index 0000000..4362b49
--- /dev/null
@@ -0,0 +1,502 @@
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+                  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                            NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/libarc/libarc.cbp b/libarc/libarc.cbp
deleted file mode 100644 (file)
index b0f1520..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
-<CodeBlocks_project_file>
-       <FileVersion major="1" minor="6" />
-       <Project>
-               <Option title="libarc" />
-               <Option pch_mode="2" />
-               <Option compiler="gcc" />
-               <Build>
-                       <Target title="Debug">
-                               <Option output="../Debug-cb/arc" prefix_auto="1" extension_auto="1" />
-                               <Option working_dir="" />
-                               <Option object_output="../Debug-cb/obj/libarc/" />
-                               <Option type="2" />
-                               <Option compiler="gcc" />
-                               <Option createDefFile="1" />
-                               <Compiler>
-                                       <Add option="-Wextra" />
-                                       <Add option="-Wall" />
-                                       <Add option="-g" />
-                                       <Add option="-O0" />
-                                       <Add option="-D_DEBUG" />
-                               </Compiler>
-                       </Target>
-                       <Target title="Release">
-                               <Option output="../Release-cb/arc" prefix_auto="1" extension_auto="1" />
-                               <Option working_dir="" />
-                               <Option object_output="../Release-cb/obj/libarc/" />
-                               <Option type="2" />
-                               <Option compiler="gcc" />
-                               <Option createDefFile="1" />
-                               <Compiler>
-                                       <Add option="-O3" />
-                                       <Add option="-DNDEBUG" />
-                               </Compiler>
-                               <Linker>
-                                       <Add option="-s" />
-                               </Linker>
-                       </Target>
-               </Build>
-               <Compiler>
-                       <Add option="-Wno-unused" />
-                       <Add option="-Wno-sign-compare" />
-                       <Add option="-DHAVE_CONFIG_H" />
-                       <Add directory="." />
-                       <Add directory=".." />
-                       <Add directory="../timidity/" />
-                       <Add directory="../utils/" />
-               </Compiler>
-               <Unit filename="../config.h" />
-               <Unit filename="../timidity/common.h" />
-               <Unit filename="../timidity/optcode.h" />
-               <Unit filename="../timidity/sysdep.h" />
-               <Unit filename="../timidity/timidity.h" />
-               <Unit filename="../utils/bitset.h" />
-               <Unit filename="../utils/mblock.h" />
-               <Unit filename="../utils/memb.h" />
-               <Unit filename="../utils/net.h" />
-               <Unit filename="../utils/support.h" />
-               <Unit filename="arc.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="arc.h" />
-               <Unit filename="arc_lzh.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="arc_mime.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="arc_tar.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="arc_zip.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="deflate.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="explode.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="explode.h" />
-               <Unit filename="inflate.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="unlzh.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="unlzh.h" />
-               <Unit filename="url.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url.h" />
-               <Unit filename="url_b64decode.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_buff.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_cache.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_dir.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_file.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_ftp.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_hqxdecode.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_http.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_inflate.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_mem.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_news.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_newsgroup.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_pipe.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_qsdecode.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="url_uudecode.c">
-                       <Option compilerVar="CC" />
-               </Unit>
-               <Unit filename="zip.h" />
-               <Extensions>
-                       <code_completion />
-                       <debugger />
-               </Extensions>
-       </Project>
-</CodeBlocks_project_file>
diff --git a/libarc/libarc.dsp b/libarc/libarc.dsp
deleted file mode 100644 (file)
index 2c77150..0000000
+++ /dev/null
@@ -1,212 +0,0 @@
-# Microsoft Developer Studio Project File - Name="libarc" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Static Library" 0x0104
-
-CFG=libarc - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "libarc.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "libarc.mak" CFG="libarc - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "libarc - Win32 Release" ("Win32 (x86) Static Library" \97p)
-!MESSAGE "libarc - Win32 Debug" ("Win32 (x86) Static Library" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "libarc - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "NDEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Release\libarc.lib"
-
-!ELSEIF  "$(CFG)" == "libarc - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "_DEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Debug\libarc.lib"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "libarc - Win32 Release"
-# Name "libarc - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\libarc\arc.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\arc_lzh.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\arc_mime.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\arc_tar.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\arc_zip.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\deflate.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\explode.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\inflate.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\unlzh.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_b64decode.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_buff.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_cache.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_dir.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_file.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_ftp.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_hqxdecode.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_http.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_inflate.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_mem.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_news.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_newsgroup.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_pipe.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_qsdecode.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url_uudecode.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\libarc\arc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\explode.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\unlzh.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\url.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libarc\zip.h"
-# End Source File
-# End Group
-# End Target
-# End Project
diff --git a/libarc/libarc.vcproj b/libarc/libarc.vcproj
deleted file mode 100644 (file)
index 2f190aa..0000000
+++ /dev/null
@@ -1,323 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="libarc"
-       ProjectGUID="{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="_DEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/libarc.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\libarc.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               InlineFunctionExpansion="1"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="NDEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/libarc.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\libarc.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\arc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\arc_lzh.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\arc_mime.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\arc_tar.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\arc_zip.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\deflate.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\explode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\inflate.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\unlzh.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_b64decode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_buff.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_cache.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_dir.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_file.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_ftp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_hqxdecode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_http.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_inflate.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_mem.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_news.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_newsgroup.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_pipe.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_qsdecode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url_uudecode.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\arc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\explode.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\unlzh.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\url.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\zip.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/libarc/libarc.vcxproj b/libarc/libarc.vcxproj
deleted file mode 100644 (file)
index 035aa37..0000000
+++ /dev/null
@@ -1,274 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{11CDD90A-20E1-45AF-879E-F355742B38B7}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/libarc.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\libarc.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/libarc.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\libarc.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/libarc.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\libarc.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/libarc.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\libarc.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="arc.c" />
-    <ClCompile Include="arc_lzh.c" />
-    <ClCompile Include="arc_mime.c" />
-    <ClCompile Include="arc_tar.c" />
-    <ClCompile Include="arc_zip.c" />
-    <ClCompile Include="deflate.c" />
-    <ClCompile Include="explode.c" />
-    <ClCompile Include="inflate.c" />
-    <ClCompile Include="unlzh.c" />
-    <ClCompile Include="url.c" />
-    <ClCompile Include="url_b64decode.c" />
-    <ClCompile Include="url_buff.c" />
-    <ClCompile Include="url_cache.c" />
-    <ClCompile Include="url_dir.c" />
-    <ClCompile Include="url_file.c" />
-    <ClCompile Include="url_ftp.c" />
-    <ClCompile Include="url_hqxdecode.c" />
-    <ClCompile Include="url_http.c" />
-    <ClCompile Include="url_inflate.c" />
-    <ClCompile Include="url_mem.c" />
-    <ClCompile Include="url_news.c" />
-    <ClCompile Include="url_newsgroup.c" />
-    <ClCompile Include="url_pipe.c" />
-    <ClCompile Include="url_qsdecode.c" />
-    <ClCompile Include="url_uudecode.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="arc.h" />
-    <ClInclude Include="explode.h" />
-    <ClInclude Include="unlzh.h" />
-    <ClInclude Include="url.h" />
-    <ClInclude Include="zip.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/libarc/libarc.vcxproj.filters b/libarc/libarc.vcxproj.filters
deleted file mode 100644 (file)
index 5ef72d9..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{bfdbea22-4062-4d56-8274-218fba372953}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{c499a7c7-abb8-4a0e-b761-a172ceeb589c}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="arc.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="arc_lzh.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="arc_mime.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="arc_tar.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="arc_zip.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="deflate.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="explode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="inflate.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="unlzh.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_b64decode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_buff.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_cache.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_dir.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_file.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_ftp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_hqxdecode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_http.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_inflate.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_mem.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_news.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_newsgroup.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_pipe.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_qsdecode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="url_uudecode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="arc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="explode.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="unlzh.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="url.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="zip.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/libarc/libarc.vcxproj.user b/libarc/libarc.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/libmpg123/libmpg123.vcproj b/libmpg123/libmpg123.vcproj
deleted file mode 100644 (file)
index 8598d85..0000000
+++ /dev/null
@@ -1,404 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="libmpg123"
-       ProjectGUID="{7D19161F-9206-4637-AFE6-C82951FFDD8E}"
-       RootNamespace="libmpg123"
-       TargetFrameworkVersion="196613"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-                       IntermediateDirectory="$(ConfigurationName)"
-                       ConfigurationType="1"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="../;.\include;.\src;.\src\compat;.\src\libmpg123;"
-                               MinimalRebuild="true"
-                               BasicRuntimeChecks="3"
-                               RuntimeLibrary="3"
-                               EnableEnhancedInstructionSet="2"
-                               WarningLevel="3"
-                               DebugInformationFormat="4"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               GenerateDebugInformation="true"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-                       IntermediateDirectory="$(ConfigurationName)"
-                       ConfigurationType="4"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="1"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               AdditionalIncludeDirectories="../;.\include;.\src;.\src\compat;.\src\libmpg123;"
-                               PreprocessorDefinitions="_LIB;OPT_SSE;"
-                               RuntimeLibrary="2"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               WarningLevel="1"
-                               DebugInformationFormat="3"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
-                       UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
-                       >
-                       <File
-                               RelativePath=".\src\compat\compat.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\compat\compat_str.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\dct64.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\equalizer.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\feature.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\format.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\frame.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\icy.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\icy2utf8.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\id3.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\index.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\layer1.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\layer2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\layer3.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\libmpg123.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\msvc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\ntom.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\optimize.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\parse.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\readers.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\stringbuf.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_8bit.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_real.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_s32.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\tabinit.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl;inc;xsd"
-                       UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
-                       >
-                       <File
-                               RelativePath=".\src\libmpg123\abi_align.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\compat\compat.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\debug.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\decode.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\fmt123.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\frame.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\gapless.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\getbits.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\getcpuflags.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\huffman.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\icy.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\icy2utf8.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\id3.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\index.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\intsym.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\l2tables.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\mangle.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\mpeghead.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\include\mpg123.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\mpg123lib_intern.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\newhuffman.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\optimize.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\parse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\reader.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\sample.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_8bit.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_mono.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synth_ntom.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\synths.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\src\libmpg123\true.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/libmpg123/libmpg123.vcxproj b/libmpg123/libmpg123.vcxproj
deleted file mode 100644 (file)
index c2e87e5..0000000
+++ /dev/null
@@ -1,209 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{D3CD5655-ECDB-41A2-A310-7B931E9E495D}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>libmpg123</RootNamespace>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup />
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;OPT_SSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <AdditionalIncludeDirectories>../;.\include;.\src;.\src\compat;.\src\libmpg123;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;OPT_SSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <AdditionalIncludeDirectories>../;.\include;.\src;.\src\compat;.\src\libmpg123;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level1</WarningLevel>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <Optimization>Full</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;OPT_SSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>../;.\include;.\src;.\src\compat;.\src\libmpg123;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <StringPooling>true</StringPooling>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level1</WarningLevel>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <Optimization>Full</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;OPT_SSE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>../;.\include;.\src;.\src\compat;.\src\libmpg123;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <StringPooling>true</StringPooling>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="include\mpg123.h" />
-    <ClInclude Include="src\compat\compat.h" />
-    <ClInclude Include="src\config.h" />
-    <ClInclude Include="src\intsym.h" />
-    <ClInclude Include="src\libmpg123\abi_align.h" />
-    <ClInclude Include="src\libmpg123\debug.h" />
-    <ClInclude Include="src\libmpg123\decode.h" />
-    <ClInclude Include="src\libmpg123\fmt123.h" />
-    <ClInclude Include="src\libmpg123\frame.h" />
-    <ClInclude Include="src\libmpg123\gapless.h" />
-    <ClInclude Include="src\libmpg123\getbits.h" />
-    <ClInclude Include="src\libmpg123\getcpuflags.h" />
-    <ClInclude Include="src\libmpg123\huffman.h" />
-    <ClInclude Include="src\libmpg123\icy.h" />
-    <ClInclude Include="src\libmpg123\icy2utf8.h" />
-    <ClInclude Include="src\libmpg123\id3.h" />
-    <ClInclude Include="src\libmpg123\index.h" />
-    <ClInclude Include="src\libmpg123\l2tables.h" />
-    <ClInclude Include="src\libmpg123\mangle.h" />
-    <ClInclude Include="src\libmpg123\mpeghead.h" />
-    <ClInclude Include="src\libmpg123\mpg123lib_intern.h" />
-    <ClInclude Include="src\libmpg123\newhuffman.h" />
-    <ClInclude Include="src\libmpg123\optimize.h" />
-    <ClInclude Include="src\libmpg123\parse.h" />
-    <ClInclude Include="src\libmpg123\reader.h" />
-    <ClInclude Include="src\libmpg123\sample.h" />
-    <ClInclude Include="src\libmpg123\synth.h" />
-    <ClInclude Include="src\libmpg123\synths.h" />
-    <ClInclude Include="src\libmpg123\synth_8bit.h" />
-    <ClInclude Include="src\libmpg123\synth_mono.h" />
-    <ClInclude Include="src\libmpg123\synth_ntom.h" />
-    <ClInclude Include="src\libmpg123\true.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="src\compat\compat.c" />
-    <ClCompile Include="src\compat\compat_str.c" />
-    <ClCompile Include="src\libmpg123\dct64.c" />
-    <ClCompile Include="src\libmpg123\equalizer.c" />
-    <ClCompile Include="src\libmpg123\feature.c" />
-    <ClCompile Include="src\libmpg123\format.c" />
-    <ClCompile Include="src\libmpg123\frame.c" />
-    <ClCompile Include="src\libmpg123\icy.c" />
-    <ClCompile Include="src\libmpg123\icy2utf8.c" />
-    <ClCompile Include="src\libmpg123\id3.c" />
-    <ClCompile Include="src\libmpg123\index.c" />
-    <ClCompile Include="src\libmpg123\layer1.c" />
-    <ClCompile Include="src\libmpg123\layer2.c" />
-    <ClCompile Include="src\libmpg123\layer3.c" />
-    <ClCompile Include="src\libmpg123\libmpg123.c" />
-    <ClCompile Include="src\libmpg123\msvc.c" />
-    <ClCompile Include="src\libmpg123\ntom.c" />
-    <ClCompile Include="src\libmpg123\optimize.c" />
-    <ClCompile Include="src\libmpg123\parse.c" />
-    <ClCompile Include="src\libmpg123\readers.c" />
-    <ClCompile Include="src\libmpg123\stringbuf.c" />
-    <ClCompile Include="src\libmpg123\synth.c" />
-    <ClCompile Include="src\libmpg123\synth_8bit.c" />
-    <ClCompile Include="src\libmpg123\synth_real.c" />
-    <ClCompile Include="src\libmpg123\synth_s32.c" />
-    <ClCompile Include="src\libmpg123\tabinit.c" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/libunimod/libunimod.dsp b/libunimod/libunimod.dsp
deleted file mode 100644 (file)
index 55c0976..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-# Microsoft Developer Studio Project File - Name="libunimod" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Static Library" 0x0104
-
-CFG=libunimod - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "libunimod.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "libunimod.mak" CFG="libunimod - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "libunimod - Win32 Release" ("Win32 (x86) Static Library" \97p)
-!MESSAGE "libunimod - Win32 Debug" ("Win32 (x86) Static Library" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "libunimod - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "NDEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Release\libunimod.lib"
-
-!ELSEIF  "$(CFG)" == "libunimod - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "_DEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Debug\libunimod.lib"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "libunimod - Win32 Release"
-# Name "libunimod - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\libunimod\load_669.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_amf.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_dsm.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_far.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_gdm.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_imf.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_it.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_m15.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_med.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_mod.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_mtm.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_okt.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_s3m.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_stm.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_stx.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_ult.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_uni.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\load_xm.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\mloader.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\mlutil.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\mmsup.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\munitrk.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\libunimod\unimod.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\libunimod\unimod_priv.h"
-# End Source File
-# End Group
-# End Target
-# End Project
diff --git a/libunimod/libunimod.vcproj b/libunimod/libunimod.vcproj
deleted file mode 100644 (file)
index 0e11bdc..0000000
+++ /dev/null
@@ -1,300 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="libunimod"
-       ProjectGUID="{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="_DEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/libunimod.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\libunimod.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="NDEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/libunimod.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\libunimod.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\load_669.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_amf.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_dsm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_far.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_gdm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_imf.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_it.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_m15.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_med.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_mod.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_mtm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_okt.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_s3m.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_stm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_stx.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_ult.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_uni.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\load_xm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mloader.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mlutil.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mmsup.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\munitrk.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\unimod.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\unimod_priv.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/libunimod/libunimod.vcxproj b/libunimod/libunimod.vcxproj
deleted file mode 100644 (file)
index 3536664..0000000
+++ /dev/null
@@ -1,268 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/libunimod.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\libunimod.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/libunimod.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\libunimod.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/libunimod.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\libunimod.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/libunimod.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\libunimod.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="load_669.c" />
-    <ClCompile Include="load_amf.c" />
-    <ClCompile Include="load_dsm.c" />
-    <ClCompile Include="load_far.c" />
-    <ClCompile Include="load_gdm.c" />
-    <ClCompile Include="load_imf.c" />
-    <ClCompile Include="load_it.c" />
-    <ClCompile Include="load_m15.c" />
-    <ClCompile Include="load_med.c" />
-    <ClCompile Include="load_mod.c" />
-    <ClCompile Include="load_mtm.c" />
-    <ClCompile Include="load_okt.c" />
-    <ClCompile Include="load_s3m.c" />
-    <ClCompile Include="load_stm.c" />
-    <ClCompile Include="load_stx.c" />
-    <ClCompile Include="load_ult.c" />
-    <ClCompile Include="load_uni.c" />
-    <ClCompile Include="load_xm.c" />
-    <ClCompile Include="mloader.c" />
-    <ClCompile Include="mlutil.c" />
-    <ClCompile Include="mmsup.c" />
-    <ClCompile Include="munitrk.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="unimod.h" />
-    <ClInclude Include="unimod_priv.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/libunimod/libunimod.vcxproj.filters b/libunimod/libunimod.vcxproj.filters
deleted file mode 100644 (file)
index 901f565..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{fc84d6df-47f7-4a80-b3e8-a46fb8d4f524}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{cd74209e-a143-4386-8cd4-912b0d77c524}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="load_669.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_amf.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_dsm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_far.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_gdm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_imf.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_it.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_m15.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_med.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_mod.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_mtm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_okt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_s3m.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_stm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_stx.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_ult.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_uni.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="load_xm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mloader.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mlutil.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mmsup.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="munitrk.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="unimod.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="unimod_priv.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/libunimod/libunimod.vcxproj.user b/libunimod/libunimod.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/nouse/nouse.dsp b/nouse/nouse.dsp
deleted file mode 100644 (file)
index 6310a98..0000000
+++ /dev/null
@@ -1,287 +0,0 @@
-# Microsoft Developer Studio Project File - Name="nouse" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Generic Project" 0x010a
-
-CFG=nouse - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "nouse.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "nouse.mak" CFG="nouse - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "nouse - Win32 Release" ("Win32 (x86) Generic Project" \97p)
-!MESSAGE "nouse - Win32 Debug" ("Win32 (x86) Generic Project" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-MTL=midl.exe
-
-!IF  "$(CFG)" == "nouse - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-
-!ELSEIF  "$(CFG)" == "nouse - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-
-!ENDIF 
-
-# Begin Target
-
-# Name "nouse - Win32 Release"
-# Name "nouse - Win32 Debug"
-# Begin Source File
-
-SOURCE="..\timidity\alsa_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audriv_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audriv_al.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audriv_mme.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audriv_none.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\bsd20_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\dl_dld.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\dl_dlopen.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\dl_hpux.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\dl_w32.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\dynamic_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\emacs_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\esd_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\gtk_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\gtk_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\gtk_p.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\hpux_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\hpux_d_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_dlog.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_mag.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_main.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_qt_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mac_readdir.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_soundspec.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_trace.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mac_util.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\mac_wrdwindow.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\motif_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\motif_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\motif_p.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\nas_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\ncurs_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\oss_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\server_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\slang_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\soundspec.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sun_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\tk_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_wrdwindow.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_mac.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_w32g.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_wcon.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_x.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_mag.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_sherry.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\x_wrdwindow.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xaw_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xaw_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xaw_redef.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xskin_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xskin_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xskin_loadBMP.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\xskin_spectrum.c"
-# End Source File
-# End Target
-# End Project
diff --git a/nouse/nouse.vcproj b/nouse/nouse.vcproj
deleted file mode 100644 (file)
index 488a92c..0000000
+++ /dev/null
@@ -1,292 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="nouse"
-       ProjectGUID="{99E98188-BE49-4367-9577-4681F1D50E9C}"
-       Keyword="MakeFileProj"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="10"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="10"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <File
-                       RelativePath="..\timidity\alsa_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\audriv_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\audriv_al.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\audriv_mme.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\audriv_none.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\bsd20_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\dl_dld.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\dl_dlopen.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\dl_hpux.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\dl_w32.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\dynamic_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\emacs_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\esd_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\gtk_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\gtk_i.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\gtk_p.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\hpux_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\hpux_d_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\mac_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\mac_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\mac_dlog.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\mac_mag.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\mac_main.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\mac_qt_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\utils\mac_readdir.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\mac_soundspec.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\mac_trace.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\utils\mac_util.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\mac_wrdwindow.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\motif_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\motif_i.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\motif_p.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\nas_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\ncurs_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\oss_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\server_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\slang_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\soundspec.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\sun_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\tk_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\timidity\w32g_a.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\w32g_wrdwindow.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\wrdt_mac.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\wrdt_w32g.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\wrdt_wcon.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\wrdt_x.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\x_mag.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\x_sherry.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\x_wrdwindow.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xaw_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xaw_i.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xaw_redef.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xskin_c.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xskin_i.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xskin_loadBMP.c"
-                       >
-               </File>
-               <File
-                       RelativePath="..\interface\xskin_spectrum.c"
-                       >
-               </File>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/nouse/nouse.vcxproj b/nouse/nouse.vcxproj
deleted file mode 100644 (file)
index 62729f4..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{99E98188-BE49-4367-9577-4681F1D50E9C}</ProjectGuid>
-    <Keyword>MakeFileProj</Keyword>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Utility</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Utility</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Utility</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>v100</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Utility</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\Debug\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\Debug\</IntDir>
-  </PropertyGroup>
-  <ItemDefinitionGroup>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\alsa_a.c" />
-    <ClCompile Include="..\timidity\audriv_a.c" />
-    <ClCompile Include="..\timidity\audriv_al.c" />
-    <ClCompile Include="..\timidity\audriv_mme.c" />
-    <ClCompile Include="..\timidity\audriv_none.c" />
-    <ClCompile Include="..\timidity\bsd20_a.c" />
-    <ClCompile Include="..\timidity\dl_dld.c" />
-    <ClCompile Include="..\timidity\dl_dlopen.c" />
-    <ClCompile Include="..\timidity\dl_hpux.c" />
-    <ClCompile Include="..\timidity\dl_w32.c" />
-    <ClCompile Include="..\interface\dynamic_c.c" />
-    <ClCompile Include="..\interface\emacs_c.c" />
-    <ClCompile Include="..\timidity\esd_a.c" />
-    <ClCompile Include="..\interface\gtk_c.c" />
-    <ClCompile Include="..\interface\gtk_i.c" />
-    <ClCompile Include="..\interface\gtk_p.c" />
-    <ClCompile Include="..\timidity\hpux_a.c" />
-    <ClCompile Include="..\timidity\hpux_d_a.c" />
-    <ClCompile Include="..\timidity\mac_a.c" />
-    <ClCompile Include="..\interface\mac_c.c" />
-    <ClCompile Include="..\timidity\mac_dlog.c" />
-    <ClCompile Include="..\interface\mac_mag.c" />
-    <ClCompile Include="..\timidity\mac_main.c" />
-    <ClCompile Include="..\timidity\mac_qt_a.c" />
-    <ClCompile Include="..\utils\mac_readdir.c" />
-    <ClCompile Include="..\timidity\mac_soundspec.c" />
-    <ClCompile Include="..\interface\mac_trace.c" />
-    <ClCompile Include="..\utils\mac_util.c" />
-    <ClCompile Include="..\interface\mac_wrdwindow.c" />
-    <ClCompile Include="..\interface\motif_c.c" />
-    <ClCompile Include="..\interface\motif_i.c" />
-    <ClCompile Include="..\interface\motif_p.c" />
-    <ClCompile Include="..\timidity\nas_a.c" />
-    <ClCompile Include="..\interface\ncurs_c.c" />
-    <ClCompile Include="..\timidity\oss_a.c" />
-    <ClCompile Include="..\interface\server_c.c" />
-    <ClCompile Include="..\interface\slang_c.c" />
-    <ClCompile Include="..\interface\soundspec.c" />
-    <ClCompile Include="..\timidity\sun_a.c" />
-    <ClCompile Include="..\interface\tk_c.c" />
-    <ClCompile Include="..\timidity\w32g_a.c" />
-    <ClCompile Include="..\interface\w32g_wrdwindow.c" />
-    <ClCompile Include="..\interface\wrdt_mac.c" />
-    <ClCompile Include="..\interface\wrdt_w32g.c" />
-    <ClCompile Include="..\interface\wrdt_wcon.c" />
-    <ClCompile Include="..\interface\wrdt_x.c" />
-    <ClCompile Include="..\interface\x_mag.c" />
-    <ClCompile Include="..\interface\x_sherry.c" />
-    <ClCompile Include="..\interface\x_wrdwindow.c" />
-    <ClCompile Include="..\interface\xaw_c.c" />
-    <ClCompile Include="..\interface\xaw_i.c" />
-    <ClCompile Include="..\interface\xaw_redef.c" />
-    <ClCompile Include="..\interface\xskin_c.c" />
-    <ClCompile Include="..\interface\xskin_i.c" />
-    <ClCompile Include="..\interface\xskin_loadBMP.c" />
-    <ClCompile Include="..\interface\xskin_spectrum.c" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/nouse/nouse.vcxproj.user b/nouse/nouse.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/ogg/AUTHORS b/ogg/AUTHORS
new file mode 100644 (file)
index 0000000..a0023f2
--- /dev/null
@@ -0,0 +1,7 @@
+Monty <monty@xiph.org>
+Greg Maxwell <greg@xiph.org>
+Ralph Giles <giles@xiph.org>
+Cristian Adam <cristian.adam@gmail.com>
+Tim Terriberry <tterribe@xiph.org>
+
+and the rest of the Xiph.Org Foundation.
diff --git a/ogg/CMakeLists.txt b/ogg/CMakeLists.txt
new file mode 100644 (file)
index 0000000..eb75ba5
--- /dev/null
@@ -0,0 +1,12 @@
+
+add_library(
+    ogg SHARED
+
+    include/ogg/ogg.h
+    include/ogg/os_types.h
+
+    src/bitwise.c
+    src/framing.c
+
+    win32/ogg.def
+)
diff --git a/ogg/COPYING b/ogg/COPYING
new file mode 100644 (file)
index 0000000..6111c6c
--- /dev/null
@@ -0,0 +1,28 @@
+Copyright (c) 2002, Xiph.org Foundation
+
+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.
diff --git a/ogg/README.md b/ogg/README.md
new file mode 100644 (file)
index 0000000..2e8a3d7
--- /dev/null
@@ -0,0 +1,131 @@
+# Ogg
+
+[![Travis Build Status](https://travis-ci.org/xiph/ogg.svg?branch=master)](https://travis-ci.org/xiph/ogg)
+[![Jenkins Build Status](https://mf4.xiph.org/jenkins/job/libogg/badge/icon)](https://mf4.xiph.org/jenkins/job/libogg/)
+[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/xiph/ogg?branch=master&svg=true)](https://ci.appveyor.com/project/rillian/ogg)
+
+Ogg project codecs use the Ogg bitstream format to arrange the raw,
+compressed bitstream into a more robust, useful form. For example,
+the Ogg bitstream makes seeking, time stamping and error recovery
+possible, as well as mixing several sepearate, concurrent media
+streams into a single physical bitstream.
+
+## What's here ##
+This source distribution includes libogg and nothing else. Other modules
+(eg, the modules libvorbis, vorbis-tools for the Vorbis music codec,
+libtheora for the Theora video codec) contain the codec libraries for
+use with Ogg bitstreams.
+
+Directory:
+
+- `src` The source for libogg, a BSD-license inplementation of the public domain Ogg bitstream format
+
+- `include` Library API headers
+
+- `doc` Ogg specification and libogg API documents
+
+- `win32` Win32 projects and build automation
+
+- `macosx` Mac OS X project and build files
+
+## Contact ##
+
+The Ogg homepage is located at https://www.xiph.org/ogg/ .
+Up to date technical documents, contact information, source code and
+pre-built utilities may be found there.
+
+## Building ##
+
+#### Building from tarball distributions ####
+
+    ./configure
+    make
+
+and optionally (as root):
+
+    make install
+
+This will install the Ogg libraries (static and shared) into
+/usr/local/lib, includes into /usr/local/include and API
+documentation into /usr/local/share/doc.
+
+#### Building from repository source ####
+
+A standard svn build should consist of nothing more than:
+
+    ./autogen.sh
+    ./configure
+    make
+
+and as root if desired :
+
+    make install
+
+#### Building on Windows ####
+
+Use the project file in the win32 directory. It should compile out of the box.
+
+#### Cross-compiling from Linux to Windows ####
+
+It is also possible to cross compile from Linux to windows using the MinGW
+cross tools and even to run the test suite under Wine, the Linux/*nix
+windows emulator.
+
+On Debian and Ubuntu systems, these cross compiler tools can be installed
+by doing:
+
+    sudo apt-get mingw32 mingw32-binutils mingw32-runtime wine
+
+Once these tools are installed its possible to compile and test by
+executing the following commands, or something similar depending on
+your system:
+
+    ./configure --host=i586-mingw32msvc --target=i586-mingw32msvc --build=i586-linux
+    make
+    make check
+
+(Build instructions for Ogg codecs such as vorbis are similar and may
+be found in those source modules' README files)
+
+## Building with CMake ##
+
+Ogg supports building using [CMake](http://www.cmake.org/). CMake is a meta build system that generates native projects for each platform.
+To generate projects just run cmake replacing `YOUR-PROJECT-GENERATOR` with a proper generator from a list [here](http://www.cmake.org/cmake/help/v3.2/manual/cmake-generators.7.html):
+
+    cmake -G YOUR-PROJECT-GENERATOR .
+
+Note that by default cmake generates projects that will build static libraries.
+To generate projects that will build dynamic library use `BUILD_SHARED_LIBS` option like this:
+
+    cmake -G YOUR-PROJECT-GENERATOR -DBUILD_SHARED_LIBS=1 .
+
+After projects are generated use them as usual
+
+#### Building on Windows ####
+
+Use proper generator for your Visual Studio version like:
+
+    cmake -G "Visual Studio 12 2013" .
+
+#### Building on Mac OS X ####
+
+Use Xcode generator. To build framework run:
+
+    cmake -G Xcode -DBUILD_FRAMEWORK=1 .
+
+#### Building on Linux ####
+
+Use Makefile generator which is default one.
+
+    cmake .
+    make
+
+## License ##
+
+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 COPYRIGHT (C) 1994-2015
+by the Xiph.Org Foundation https://www.xiph.org/
similarity index 79%
rename from ogg/ogg.h
rename to ogg/include/ogg/ogg.h
index e8bb9bf..7609fc2 100644 (file)
--- a/ogg/ogg.h
@@ -5,13 +5,13 @@
  * 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             *
+ * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007             *
  * by the Xiph.Org Foundation http://www.xiph.org/                  *
  *                                                                  *
  ********************************************************************
 
  function: toplevel libogg include
- last mod: $Id: ogg.h,v 1.19 2002/09/15 23:48:02 xiphmont Exp $
+ last mod: $Id$
 
  ********************************************************************/
 #ifndef _OGG_H
 extern "C" {
 #endif
 
+#include <stddef.h>
 #include <ogg/os_types.h>
 
 typedef struct {
+  void *iov_base;
+  size_t iov_len;
+} ogg_iovec_t;
+
+typedef struct {
   long endbyte;
   int  endbit;
 
@@ -53,8 +59,8 @@ typedef struct {
 
   int     *lacing_vals;      /* The values that will go to the segment table */
   ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
-                               this way, but it is simple coupled to the
-                               lacing fifo */
+                                this way, but it is simple coupled to the
+                                lacing fifo */
   long    lacing_storage;
   long    lacing_fill;
   long    lacing_packet;
@@ -69,10 +75,10 @@ typedef struct {
                              of a logical bitstream */
   long    serialno;
   long    pageno;
-  ogg_int64_t  packetno;      /* sequence number for decode; the framing
+  ogg_int64_t  packetno;  /* sequence number for decode; the framing
                              knows where there's a hole in the data,
                              but we need coupling so that the codec
-                             (which is in a seperate abstraction
+                             (which is in a separate abstraction
                              layer) also knows about the gap */
   ogg_int64_t   granulepos;
 
@@ -88,12 +94,12 @@ typedef struct {
   long  e_o_s;
 
   ogg_int64_t  granulepos;
-  
+
   ogg_int64_t  packetno;     /* sequence number for decode; the framing
-                               knows where there's a hole in the data,
-                               but we need coupling so that the codec
-                               (which is in a seperate abstraction
-                               layer) also knows about the gap */
+                                knows where there's a hole in the data,
+                                but we need coupling so that the codec
+                                (which is in a separate abstraction
+                                layer) also knows about the gap */
 } ogg_packet;
 
 typedef struct {
@@ -110,6 +116,7 @@ typedef struct {
 /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
 
 extern void  oggpack_writeinit(oggpack_buffer *b);
+extern int   oggpack_writecheck(oggpack_buffer *b);
 extern void  oggpack_writetrunc(oggpack_buffer *b,long bits);
 extern void  oggpack_writealign(oggpack_buffer *b);
 extern void  oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
@@ -128,6 +135,7 @@ extern long  oggpack_bits(oggpack_buffer *b);
 extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
 
 extern void  oggpackB_writeinit(oggpack_buffer *b);
+extern int   oggpackB_writecheck(oggpack_buffer *b);
 extern void  oggpackB_writetrunc(oggpack_buffer *b,long bits);
 extern void  oggpackB_writealign(oggpack_buffer *b);
 extern void  oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
@@ -148,15 +156,20 @@ extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
 /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
 
 extern int      ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
+extern int      ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov,
+                                   int count, long e_o_s, ogg_int64_t granulepos);
 extern int      ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
+extern int      ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill);
 extern int      ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
+extern int      ogg_stream_flush_fill(ogg_stream_state *os, ogg_page *og, int nfill);
 
 /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
 
 extern int      ogg_sync_init(ogg_sync_state *oy);
 extern int      ogg_sync_clear(ogg_sync_state *oy);
 extern int      ogg_sync_reset(ogg_sync_state *oy);
-extern int     ogg_sync_destroy(ogg_sync_state *oy);
+extern int      ogg_sync_destroy(ogg_sync_state *oy);
+extern int      ogg_sync_check(ogg_sync_state *oy);
 
 extern char    *ogg_sync_buffer(ogg_sync_state *oy, long size);
 extern int      ogg_sync_wrote(ogg_sync_state *oy, long bytes);
@@ -173,18 +186,19 @@ extern int      ogg_stream_clear(ogg_stream_state *os);
 extern int      ogg_stream_reset(ogg_stream_state *os);
 extern int      ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
 extern int      ogg_stream_destroy(ogg_stream_state *os);
+extern int      ogg_stream_check(ogg_stream_state *os);
 extern int      ogg_stream_eos(ogg_stream_state *os);
 
 extern void     ogg_page_checksum_set(ogg_page *og);
 
-extern int      ogg_page_version(ogg_page *og);
-extern int      ogg_page_continued(ogg_page *og);
-extern int      ogg_page_bos(ogg_page *og);
-extern int      ogg_page_eos(ogg_page *og);
-extern ogg_int64_t  ogg_page_granulepos(ogg_page *og);
-extern int      ogg_page_serialno(ogg_page *og);
-extern long     ogg_page_pageno(ogg_page *og);
-extern int      ogg_page_packets(ogg_page *og);
+extern int      ogg_page_version(const ogg_page *og);
+extern int      ogg_page_continued(const ogg_page *og);
+extern int      ogg_page_bos(const ogg_page *og);
+extern int      ogg_page_eos(const ogg_page *og);
+extern ogg_int64_t  ogg_page_granulepos(const ogg_page *og);
+extern int      ogg_page_serialno(const ogg_page *og);
+extern long     ogg_page_pageno(const ogg_page *og);
+extern int      ogg_page_packets(const ogg_page *og);
 
 extern void     ogg_packet_clear(ogg_packet *op);
 
@@ -194,9 +208,3 @@ extern void     ogg_packet_clear(ogg_packet *op);
 #endif
 
 #endif  /* _OGG_H */
-
-
-
-
-
-
diff --git a/ogg/include/ogg/os_types.h b/ogg/include/ogg/os_types.h
new file mode 100644 (file)
index 0000000..b8f5630
--- /dev/null
@@ -0,0 +1,148 @@
+/********************************************************************
+ *                                                                  *
+ * 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$
+
+ ********************************************************************/
+#ifndef _OS_TYPES_H
+#define _OS_TYPES_H
+
+/* make it easy on the folks that want to compile the libs with a
+   different malloc than stdlib */
+#define _ogg_malloc  malloc
+#define _ogg_calloc  calloc
+#define _ogg_realloc realloc
+#define _ogg_free    free
+
+#if defined(_WIN32)
+
+#  if defined(__CYGWIN__)
+#    include <stdint.h>
+     typedef int16_t ogg_int16_t;
+     typedef uint16_t ogg_uint16_t;
+     typedef int32_t ogg_int32_t;
+     typedef uint32_t ogg_uint32_t;
+     typedef int64_t ogg_int64_t;
+     typedef uint64_t ogg_uint64_t;
+#  elif defined(__MINGW32__)
+#    include <sys/types.h>
+     typedef short ogg_int16_t;
+     typedef unsigned short ogg_uint16_t;
+     typedef int ogg_int32_t;
+     typedef unsigned int ogg_uint32_t;
+     typedef long long ogg_int64_t;
+     typedef unsigned long long ogg_uint64_t;
+#  elif defined(__MWERKS__)
+     typedef long long ogg_int64_t;
+     typedef int ogg_int32_t;
+     typedef unsigned int ogg_uint32_t;
+     typedef short ogg_int16_t;
+     typedef unsigned short ogg_uint16_t;
+#  else
+#    if defined(_MSC_VER) && (_MSC_VER >= 1800) /* MSVC 2013 and newer */
+#      include <stdint.h>
+       typedef int16_t ogg_int16_t;
+       typedef uint16_t ogg_uint16_t;
+       typedef int32_t ogg_int32_t;
+       typedef uint32_t ogg_uint32_t;
+       typedef int64_t ogg_int64_t;
+       typedef uint64_t ogg_uint64_t;
+#    else
+       /* MSVC/Borland */
+       typedef __int64 ogg_int64_t;
+       typedef __int32 ogg_int32_t;
+       typedef unsigned __int32 ogg_uint32_t;
+       typedef __int16 ogg_int16_t;
+       typedef unsigned __int16 ogg_uint16_t;
+#    endif
+#  endif
+
+#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */
+
+#  include <inttypes.h>
+   typedef int16_t ogg_int16_t;
+   typedef uint16_t ogg_uint16_t;
+   typedef int32_t ogg_int32_t;
+   typedef uint32_t ogg_uint32_t;
+   typedef int64_t ogg_int64_t;
+
+#elif defined(__HAIKU__)
+
+  /* Haiku */
+#  include <sys/types.h>
+   typedef short ogg_int16_t;
+   typedef unsigned short ogg_uint16_t;
+   typedef int ogg_int32_t;
+   typedef unsigned int ogg_uint32_t;
+   typedef long long ogg_int64_t;
+
+#elif defined(__BEOS__)
+
+   /* Be */
+#  include <inttypes.h>
+   typedef int16_t ogg_int16_t;
+   typedef uint16_t ogg_uint16_t;
+   typedef int32_t ogg_int32_t;
+   typedef uint32_t ogg_uint32_t;
+   typedef int64_t ogg_int64_t;
+
+#elif defined (__EMX__)
+
+   /* OS/2 GCC */
+   typedef short ogg_int16_t;
+   typedef unsigned short ogg_uint16_t;
+   typedef int ogg_int32_t;
+   typedef unsigned int ogg_uint32_t;
+   typedef long long ogg_int64_t;
+
+#elif defined (DJGPP)
+
+   /* DJGPP */
+   typedef short ogg_int16_t;
+   typedef int ogg_int32_t;
+   typedef unsigned int ogg_uint32_t;
+   typedef long long ogg_int64_t;
+
+#elif defined(R5900)
+
+   /* PS2 EE */
+   typedef long ogg_int64_t;
+   typedef int ogg_int32_t;
+   typedef unsigned ogg_uint32_t;
+   typedef short ogg_int16_t;
+
+#elif defined(__SYMBIAN32__)
+
+   /* Symbian GCC */
+   typedef signed short ogg_int16_t;
+   typedef unsigned short ogg_uint16_t;
+   typedef signed int ogg_int32_t;
+   typedef unsigned int ogg_uint32_t;
+   typedef long long int ogg_int64_t;
+
+#elif defined(__TMS320C6X__)
+
+   /* TI C64x compiler */
+   typedef signed short ogg_int16_t;
+   typedef unsigned short ogg_uint16_t;
+   typedef signed int ogg_int32_t;
+   typedef unsigned int ogg_uint32_t;
+   typedef long long int ogg_int64_t;
+
+#else
+
+#  include <ogg/config_types.h>
+
+#endif
+
+#endif  /* _OS_TYPES_H */
diff --git a/ogg/os_types.h b/ogg/os_types.h
deleted file mode 100644 (file)
index 92ccb4b..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-/********************************************************************
- *                                                                  *
- * 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,v 1.14 2003/09/02 05:09:14 xiphmont Exp $
-
- ********************************************************************/
-#ifndef _OS_TYPES_H
-#define _OS_TYPES_H
-
-/* make it easy on the folks that want to compile the libs with a
-   different malloc than stdlib */
-#define _ogg_malloc  malloc
-#define _ogg_calloc  calloc
-#define _ogg_realloc realloc
-#define _ogg_free    free
-
-#ifdef _WIN32 
-
-#  ifndef __GNUC__
-   /* MSVC/Borland */
-   typedef __int64 ogg_int64_t;
-   typedef __int32 ogg_int32_t;
-   typedef unsigned __int32 ogg_uint32_t;
-   typedef __int16 ogg_int16_t;
-   typedef unsigned __int16 ogg_uint16_t;
-#  else
-   /* Cygwin */
-   #include <_G_config.h>
-   typedef _G_int64_t ogg_int64_t;
-   typedef _G_int32_t ogg_int32_t;
-   typedef _G_uint32_t ogg_uint32_t;
-   typedef _G_int16_t ogg_int16_t;
-   typedef _G_uint16_t ogg_uint16_t;
-#  endif
-
-#elif defined(__MACOS__)
-
-#  include <sys/types.h>
-   typedef SInt16 ogg_int16_t;
-   typedef UInt16 ogg_uint16_t;
-   typedef SInt32 ogg_int32_t;
-   typedef UInt32 ogg_uint32_t;
-   typedef SInt64 ogg_int64_t;
-
-#elif defined(__MACOSX__) /* MacOS X Framework build */
-
-#  include <sys/types.h>
-   typedef int16_t ogg_int16_t;
-   typedef u_int16_t ogg_uint16_t;
-   typedef int32_t ogg_int32_t;
-   typedef u_int32_t ogg_uint32_t;
-   typedef int64_t ogg_int64_t;
-
-#elif defined(__BEOS__)
-
-   /* Be */
-#  include <inttypes.h>
-   typedef int16_t ogg_int16_t;
-   typedef u_int16_t ogg_uint16_t;
-   typedef int32_t ogg_int32_t;
-   typedef u_int32_t ogg_uint32_t;
-   typedef int64_t ogg_int64_t;
-
-#elif defined (__EMX__)
-
-   /* OS/2 GCC */
-   typedef short ogg_int16_t;
-   typedef unsigned short ogg_uint16_t;
-   typedef int ogg_int32_t;
-   typedef unsigned int ogg_uint32_t;
-   typedef long long ogg_int64_t;
-
-#elif defined (DJGPP)
-
-   /* DJGPP */
-   typedef short ogg_int16_t;
-   typedef int ogg_int32_t;
-   typedef unsigned int ogg_uint32_t;
-   typedef long long ogg_int64_t;
-
-#elif defined(R5900)
-
-   /* PS2 EE */
-   typedef long ogg_int64_t;
-   typedef int ogg_int32_t;
-   typedef unsigned ogg_uint32_t;
-   typedef short ogg_int16_t;
-
-#else
-
-#  include <sys/types.h>
-#  include <ogg/config_types.h>
-
-#endif
-
-#endif  /* _OS_TYPES_H */
diff --git a/ogg/src/bitwise.c b/ogg/src/bitwise.c
new file mode 100644 (file)
index 0000000..fa2b572
--- /dev/null
@@ -0,0 +1,1088 @@
+/********************************************************************
+ *                                                                  *
+ * THIS FILE IS PART OF THE Ogg CONTAINER 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-2014             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: packing variable sized words into an octet stream
+  last mod: $Id$
+
+ ********************************************************************/
+
+/* We're 'LSb' endian; if we write a word but read individual bits,
+   then we'll read the lsb first */
+
+#include <string.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <ogg/ogg.h>
+
+#define BUFFER_INCREMENT 256
+
+static const unsigned long mask[]=
+{0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
+ 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
+ 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
+ 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
+ 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
+ 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
+ 0x3fffffff,0x7fffffff,0xffffffff };
+
+static const unsigned int mask8B[]=
+{0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
+
+void oggpack_writeinit(oggpack_buffer *b){
+  memset(b,0,sizeof(*b));
+  b->ptr=b->buffer=_ogg_malloc(BUFFER_INCREMENT);
+  b->buffer[0]='\0';
+  b->storage=BUFFER_INCREMENT;
+}
+
+void oggpackB_writeinit(oggpack_buffer *b){
+  oggpack_writeinit(b);
+}
+
+int oggpack_writecheck(oggpack_buffer *b){
+  if(!b->ptr || !b->storage)return -1;
+  return 0;
+}
+
+int oggpackB_writecheck(oggpack_buffer *b){
+  return oggpack_writecheck(b);
+}
+
+void oggpack_writetrunc(oggpack_buffer *b,long bits){
+  long bytes=bits>>3;
+  if(b->ptr){
+    bits-=bytes*8;
+    b->ptr=b->buffer+bytes;
+    b->endbit=bits;
+    b->endbyte=bytes;
+    *b->ptr&=mask[bits];
+  }
+}
+
+void oggpackB_writetrunc(oggpack_buffer *b,long bits){
+  long bytes=bits>>3;
+  if(b->ptr){
+    bits-=bytes*8;
+    b->ptr=b->buffer+bytes;
+    b->endbit=bits;
+    b->endbyte=bytes;
+    *b->ptr&=mask8B[bits];
+  }
+}
+
+/* Takes only up to 32 bits. */
+void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
+  if(bits<0 || bits>32) goto err;
+  if(b->endbyte>=b->storage-4){
+    void *ret;
+    if(!b->ptr)return;
+    if(b->storage>LONG_MAX-BUFFER_INCREMENT) goto err;
+    ret=_ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
+    if(!ret) goto err;
+    b->buffer=ret;
+    b->storage+=BUFFER_INCREMENT;
+    b->ptr=b->buffer+b->endbyte;
+  }
+
+  value&=mask[bits];
+  bits+=b->endbit;
+
+  b->ptr[0]|=value<<b->endbit;
+
+  if(bits>=8){
+    b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
+    if(bits>=16){
+      b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
+      if(bits>=24){
+        b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
+        if(bits>=32){
+          if(b->endbit)
+            b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
+          else
+            b->ptr[4]=0;
+        }
+      }
+    }
+  }
+
+  b->endbyte+=bits/8;
+  b->ptr+=bits/8;
+  b->endbit=bits&7;
+  return;
+ err:
+  oggpack_writeclear(b);
+}
+
+/* Takes only up to 32 bits. */
+void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
+  if(bits<0 || bits>32) goto err;
+  if(b->endbyte>=b->storage-4){
+    void *ret;
+    if(!b->ptr)return;
+    if(b->storage>LONG_MAX-BUFFER_INCREMENT) goto err;
+    ret=_ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
+    if(!ret) goto err;
+    b->buffer=ret;
+    b->storage+=BUFFER_INCREMENT;
+    b->ptr=b->buffer+b->endbyte;
+  }
+
+  value=(value&mask[bits])<<(32-bits);
+  bits+=b->endbit;
+
+  b->ptr[0]|=value>>(24+b->endbit);
+
+  if(bits>=8){
+    b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
+    if(bits>=16){
+      b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
+      if(bits>=24){
+        b->ptr[3]=(unsigned char)(value>>(b->endbit));
+        if(bits>=32){
+          if(b->endbit)
+            b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
+          else
+            b->ptr[4]=0;
+        }
+      }
+    }
+  }
+
+  b->endbyte+=bits/8;
+  b->ptr+=bits/8;
+  b->endbit=bits&7;
+  return;
+ err:
+  oggpack_writeclear(b);
+}
+
+void oggpack_writealign(oggpack_buffer *b){
+  int bits=8-b->endbit;
+  if(bits<8)
+    oggpack_write(b,0,bits);
+}
+
+void oggpackB_writealign(oggpack_buffer *b){
+  int bits=8-b->endbit;
+  if(bits<8)
+    oggpackB_write(b,0,bits);
+}
+
+static void oggpack_writecopy_helper(oggpack_buffer *b,
+                                     void *source,
+                                     long bits,
+                                     void (*w)(oggpack_buffer *,
+                                               unsigned long,
+                                               int),
+                                     int msb){
+  unsigned char *ptr=(unsigned char *)source;
+
+  long bytes=bits/8;
+  long pbytes=(b->endbit+bits)/8;
+  bits-=bytes*8;
+
+  /* expand storage up-front */
+  if(b->endbyte+pbytes>=b->storage){
+    void *ret;
+    if(!b->ptr) goto err;
+    if(b->storage>b->endbyte+pbytes+BUFFER_INCREMENT) goto err;
+    b->storage=b->endbyte+pbytes+BUFFER_INCREMENT;
+    ret=_ogg_realloc(b->buffer,b->storage);
+    if(!ret) goto err;
+    b->buffer=ret;
+    b->ptr=b->buffer+b->endbyte;
+  }
+
+  /* copy whole octets */
+  if(b->endbit){
+    int i;
+    /* unaligned copy.  Do it the hard way. */
+    for(i=0;i<bytes;i++)
+      w(b,(unsigned long)(ptr[i]),8);
+  }else{
+    /* aligned block copy */
+    memmove(b->ptr,source,bytes);
+    b->ptr+=bytes;
+    b->endbyte+=bytes;
+    *b->ptr=0;
+  }
+
+  /* copy trailing bits */
+  if(bits){
+    if(msb)
+      w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
+    else
+      w(b,(unsigned long)(ptr[bytes]),bits);
+  }
+  return;
+ err:
+  oggpack_writeclear(b);
+}
+
+void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
+  oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
+}
+
+void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
+  oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
+}
+
+void oggpack_reset(oggpack_buffer *b){
+  if(!b->ptr)return;
+  b->ptr=b->buffer;
+  b->buffer[0]=0;
+  b->endbit=b->endbyte=0;
+}
+
+void oggpackB_reset(oggpack_buffer *b){
+  oggpack_reset(b);
+}
+
+void oggpack_writeclear(oggpack_buffer *b){
+  if(b->buffer)_ogg_free(b->buffer);
+  memset(b,0,sizeof(*b));
+}
+
+void oggpackB_writeclear(oggpack_buffer *b){
+  oggpack_writeclear(b);
+}
+
+void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
+  memset(b,0,sizeof(*b));
+  b->buffer=b->ptr=buf;
+  b->storage=bytes;
+}
+
+void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
+  oggpack_readinit(b,buf,bytes);
+}
+
+/* Read in bits without advancing the bitptr; bits <= 32 */
+long oggpack_look(oggpack_buffer *b,int bits){
+  unsigned long ret;
+  unsigned long m;
+
+  if(bits<0 || bits>32) return -1;
+  m=mask[bits];
+  bits+=b->endbit;
+
+  if(b->endbyte >= b->storage-4){
+    /* not the main path */
+    if(b->endbyte > b->storage-((bits+7)>>3)) return -1;
+    /* special case to avoid reading b->ptr[0], which might be past the end of
+        the buffer; also skips some useless accounting */
+    else if(!bits)return(0L);
+  }
+
+  ret=b->ptr[0]>>b->endbit;
+  if(bits>8){
+    ret|=b->ptr[1]<<(8-b->endbit);
+    if(bits>16){
+      ret|=b->ptr[2]<<(16-b->endbit);
+      if(bits>24){
+        ret|=b->ptr[3]<<(24-b->endbit);
+        if(bits>32 && b->endbit)
+          ret|=b->ptr[4]<<(32-b->endbit);
+      }
+    }
+  }
+  return(m&ret);
+}
+
+/* Read in bits without advancing the bitptr; bits <= 32 */
+long oggpackB_look(oggpack_buffer *b,int bits){
+  unsigned long ret;
+  int m=32-bits;
+
+  if(m<0 || m>32) return -1;
+  bits+=b->endbit;
+
+  if(b->endbyte >= b->storage-4){
+    /* not the main path */
+    if(b->endbyte > b->storage-((bits+7)>>3)) return -1;
+    /* special case to avoid reading b->ptr[0], which might be past the end of
+        the buffer; also skips some useless accounting */
+    else if(!bits)return(0L);
+  }
+
+  ret=b->ptr[0]<<(24+b->endbit);
+  if(bits>8){
+    ret|=b->ptr[1]<<(16+b->endbit);
+    if(bits>16){
+      ret|=b->ptr[2]<<(8+b->endbit);
+      if(bits>24){
+        ret|=b->ptr[3]<<(b->endbit);
+        if(bits>32 && b->endbit)
+          ret|=b->ptr[4]>>(8-b->endbit);
+      }
+    }
+  }
+  return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
+}
+
+long oggpack_look1(oggpack_buffer *b){
+  if(b->endbyte>=b->storage)return(-1);
+  return((b->ptr[0]>>b->endbit)&1);
+}
+
+long oggpackB_look1(oggpack_buffer *b){
+  if(b->endbyte>=b->storage)return(-1);
+  return((b->ptr[0]>>(7-b->endbit))&1);
+}
+
+void oggpack_adv(oggpack_buffer *b,int bits){
+  bits+=b->endbit;
+
+  if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
+
+  b->ptr+=bits/8;
+  b->endbyte+=bits/8;
+  b->endbit=bits&7;
+  return;
+
+ overflow:
+  b->ptr=NULL;
+  b->endbyte=b->storage;
+  b->endbit=1;
+}
+
+void oggpackB_adv(oggpack_buffer *b,int bits){
+  oggpack_adv(b,bits);
+}
+
+void oggpack_adv1(oggpack_buffer *b){
+  if(++(b->endbit)>7){
+    b->endbit=0;
+    b->ptr++;
+    b->endbyte++;
+  }
+}
+
+void oggpackB_adv1(oggpack_buffer *b){
+  oggpack_adv1(b);
+}
+
+/* bits <= 32 */
+long oggpack_read(oggpack_buffer *b,int bits){
+  long ret;
+  unsigned long m;
+
+  if(bits<0 || bits>32) goto err;
+  m=mask[bits];
+  bits+=b->endbit;
+
+  if(b->endbyte >= b->storage-4){
+    /* not the main path */
+    if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
+    /* special case to avoid reading b->ptr[0], which might be past the end of
+        the buffer; also skips some useless accounting */
+    else if(!bits)return(0L);
+  }
+
+  ret=b->ptr[0]>>b->endbit;
+  if(bits>8){
+    ret|=b->ptr[1]<<(8-b->endbit);
+    if(bits>16){
+      ret|=b->ptr[2]<<(16-b->endbit);
+      if(bits>24){
+        ret|=b->ptr[3]<<(24-b->endbit);
+        if(bits>32 && b->endbit){
+          ret|=b->ptr[4]<<(32-b->endbit);
+        }
+      }
+    }
+  }
+  ret&=m;
+  b->ptr+=bits/8;
+  b->endbyte+=bits/8;
+  b->endbit=bits&7;
+  return ret;
+
+ overflow:
+ err:
+  b->ptr=NULL;
+  b->endbyte=b->storage;
+  b->endbit=1;
+  return -1L;
+}
+
+/* bits <= 32 */
+long oggpackB_read(oggpack_buffer *b,int bits){
+  long ret;
+  long m=32-bits;
+
+  if(m<0 || m>32) goto err;
+  bits+=b->endbit;
+
+  if(b->endbyte+4>=b->storage){
+    /* not the main path */
+    if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
+    /* special case to avoid reading b->ptr[0], which might be past the end of
+        the buffer; also skips some useless accounting */
+    else if(!bits)return(0L);
+  }
+
+  ret=b->ptr[0]<<(24+b->endbit);
+  if(bits>8){
+    ret|=b->ptr[1]<<(16+b->endbit);
+    if(bits>16){
+      ret|=b->ptr[2]<<(8+b->endbit);
+      if(bits>24){
+        ret|=b->ptr[3]<<(b->endbit);
+        if(bits>32 && b->endbit)
+          ret|=b->ptr[4]>>(8-b->endbit);
+      }
+    }
+  }
+  ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
+
+  b->ptr+=bits/8;
+  b->endbyte+=bits/8;
+  b->endbit=bits&7;
+  return ret;
+
+ overflow:
+ err:
+  b->ptr=NULL;
+  b->endbyte=b->storage;
+  b->endbit=1;
+  return -1L;
+}
+
+long oggpack_read1(oggpack_buffer *b){
+  long ret;
+
+  if(b->endbyte >= b->storage) goto overflow;
+  ret=(b->ptr[0]>>b->endbit)&1;
+
+  b->endbit++;
+  if(b->endbit>7){
+    b->endbit=0;
+    b->ptr++;
+    b->endbyte++;
+  }
+  return ret;
+
+ overflow:
+  b->ptr=NULL;
+  b->endbyte=b->storage;
+  b->endbit=1;
+  return -1L;
+}
+
+long oggpackB_read1(oggpack_buffer *b){
+  long ret;
+
+  if(b->endbyte >= b->storage) goto overflow;
+  ret=(b->ptr[0]>>(7-b->endbit))&1;
+
+  b->endbit++;
+  if(b->endbit>7){
+    b->endbit=0;
+    b->ptr++;
+    b->endbyte++;
+  }
+  return ret;
+
+ overflow:
+  b->ptr=NULL;
+  b->endbyte=b->storage;
+  b->endbit=1;
+  return -1L;
+}
+
+long oggpack_bytes(oggpack_buffer *b){
+  return(b->endbyte+(b->endbit+7)/8);
+}
+
+long oggpack_bits(oggpack_buffer *b){
+  return(b->endbyte*8+b->endbit);
+}
+
+long oggpackB_bytes(oggpack_buffer *b){
+  return oggpack_bytes(b);
+}
+
+long oggpackB_bits(oggpack_buffer *b){
+  return oggpack_bits(b);
+}
+
+unsigned char *oggpack_get_buffer(oggpack_buffer *b){
+  return(b->buffer);
+}
+
+unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
+  return oggpack_get_buffer(b);
+}
+
+/* Self test of the bitwise routines; everything else is based on
+   them, so they damned well better be solid. */
+
+#ifdef _V_SELFTEST
+#include <stdio.h>
+
+static int ilog(unsigned int v){
+  int ret=0;
+  while(v){
+    ret++;
+    v>>=1;
+  }
+  return(ret);
+}
+
+oggpack_buffer o;
+oggpack_buffer r;
+
+void report(char *in){
+  fprintf(stderr,"%s",in);
+  exit(1);
+}
+
+void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
+  long bytes,i;
+  unsigned char *buffer;
+
+  oggpack_reset(&o);
+  for(i=0;i<vals;i++)
+    oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
+  buffer=oggpack_get_buffer(&o);
+  bytes=oggpack_bytes(&o);
+  if(bytes!=compsize)report("wrong number of bytes!\n");
+  for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
+    for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
+    report("wrote incorrect value!\n");
+  }
+  oggpack_readinit(&r,buffer,bytes);
+  for(i=0;i<vals;i++){
+    int tbit=bits?bits:ilog(b[i]);
+    if(oggpack_look(&r,tbit)==-1)
+      report("out of data!\n");
+    if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
+      report("looked at incorrect value!\n");
+    if(tbit==1)
+      if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
+        report("looked at single bit incorrect value!\n");
+    if(tbit==1){
+      if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
+        report("read incorrect single bit value!\n");
+    }else{
+    if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
+      report("read incorrect value!\n");
+    }
+  }
+  if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
+}
+
+void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
+  long bytes,i;
+  unsigned char *buffer;
+
+  oggpackB_reset(&o);
+  for(i=0;i<vals;i++)
+    oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
+  buffer=oggpackB_get_buffer(&o);
+  bytes=oggpackB_bytes(&o);
+  if(bytes!=compsize)report("wrong number of bytes!\n");
+  for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
+    for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
+    report("wrote incorrect value!\n");
+  }
+  oggpackB_readinit(&r,buffer,bytes);
+  for(i=0;i<vals;i++){
+    int tbit=bits?bits:ilog(b[i]);
+    if(oggpackB_look(&r,tbit)==-1)
+      report("out of data!\n");
+    if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
+      report("looked at incorrect value!\n");
+    if(tbit==1)
+      if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
+        report("looked at single bit incorrect value!\n");
+    if(tbit==1){
+      if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
+        report("read incorrect single bit value!\n");
+    }else{
+    if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
+      report("read incorrect value!\n");
+    }
+  }
+  if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
+}
+
+void copytest(int prefill, int copy){
+  oggpack_buffer source_write;
+  oggpack_buffer dest_write;
+  oggpack_buffer source_read;
+  oggpack_buffer dest_read;
+  unsigned char *source;
+  unsigned char *dest;
+  long source_bytes,dest_bytes;
+  int i;
+
+  oggpack_writeinit(&source_write);
+  oggpack_writeinit(&dest_write);
+
+  for(i=0;i<(prefill+copy+7)/8;i++)
+    oggpack_write(&source_write,(i^0x5a)&0xff,8);
+  source=oggpack_get_buffer(&source_write);
+  source_bytes=oggpack_bytes(&source_write);
+
+  /* prefill */
+  oggpack_writecopy(&dest_write,source,prefill);
+
+  /* check buffers; verify end byte masking */
+  dest=oggpack_get_buffer(&dest_write);
+  dest_bytes=oggpack_bytes(&dest_write);
+  if(dest_bytes!=(prefill+7)/8){
+    fprintf(stderr,"wrong number of bytes after prefill! %ld!=%d\n",dest_bytes,(prefill+7)/8);
+    exit(1);
+  }
+  oggpack_readinit(&source_read,source,source_bytes);
+  oggpack_readinit(&dest_read,dest,dest_bytes);
+
+  for(i=0;i<prefill;i+=8){
+    int s=oggpack_read(&source_read,prefill-i<8?prefill-i:8);
+    int d=oggpack_read(&dest_read,prefill-i<8?prefill-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d mismatch! byte %d, %x!=%x\n",prefill,i/8,s,d);
+      exit(1);
+    }
+  }
+  if(prefill<dest_bytes){
+    if(oggpack_read(&dest_read,dest_bytes-prefill)!=0){
+      fprintf(stderr,"prefill=%d mismatch! trailing bits not zero\n",prefill);
+      exit(1);
+    }
+  }
+
+  /* second copy */
+  oggpack_writecopy(&dest_write,source,copy);
+
+  /* check buffers; verify end byte masking */
+  dest=oggpack_get_buffer(&dest_write);
+  dest_bytes=oggpack_bytes(&dest_write);
+  if(dest_bytes!=(copy+prefill+7)/8){
+    fprintf(stderr,"wrong number of bytes after prefill+copy! %ld!=%d\n",dest_bytes,(copy+prefill+7)/8);
+    exit(1);
+  }
+  oggpack_readinit(&source_read,source,source_bytes);
+  oggpack_readinit(&dest_read,dest,dest_bytes);
+
+  for(i=0;i<prefill;i+=8){
+    int s=oggpack_read(&source_read,prefill-i<8?prefill-i:8);
+    int d=oggpack_read(&dest_read,prefill-i<8?prefill-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d mismatch! byte %d, %x!=%x\n",prefill,i/8,s,d);
+      exit(1);
+    }
+  }
+
+  oggpack_readinit(&source_read,source,source_bytes);
+  for(i=0;i<copy;i+=8){
+    int s=oggpack_read(&source_read,copy-i<8?copy-i:8);
+    int d=oggpack_read(&dest_read,copy-i<8?copy-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d copy=%d mismatch! byte %d, %x!=%x\n",prefill,copy,i/8,s,d);
+      exit(1);
+    }
+  }
+
+  if(copy+prefill<dest_bytes){
+    if(oggpack_read(&dest_read,dest_bytes-copy-prefill)!=0){
+      fprintf(stderr,"prefill=%d copy=%d mismatch! trailing bits not zero\n",prefill,copy);
+      exit(1);
+    }
+  }
+
+  oggpack_writeclear(&source_write);
+  oggpack_writeclear(&dest_write);
+
+
+}
+
+void copytestB(int prefill, int copy){
+  oggpack_buffer source_write;
+  oggpack_buffer dest_write;
+  oggpack_buffer source_read;
+  oggpack_buffer dest_read;
+  unsigned char *source;
+  unsigned char *dest;
+  long source_bytes,dest_bytes;
+  int i;
+
+  oggpackB_writeinit(&source_write);
+  oggpackB_writeinit(&dest_write);
+
+  for(i=0;i<(prefill+copy+7)/8;i++)
+    oggpackB_write(&source_write,(i^0x5a)&0xff,8);
+  source=oggpackB_get_buffer(&source_write);
+  source_bytes=oggpackB_bytes(&source_write);
+
+  /* prefill */
+  oggpackB_writecopy(&dest_write,source,prefill);
+
+  /* check buffers; verify end byte masking */
+  dest=oggpackB_get_buffer(&dest_write);
+  dest_bytes=oggpackB_bytes(&dest_write);
+  if(dest_bytes!=(prefill+7)/8){
+    fprintf(stderr,"wrong number of bytes after prefill! %ld!=%d\n",dest_bytes,(prefill+7)/8);
+    exit(1);
+  }
+  oggpackB_readinit(&source_read,source,source_bytes);
+  oggpackB_readinit(&dest_read,dest,dest_bytes);
+
+  for(i=0;i<prefill;i+=8){
+    int s=oggpackB_read(&source_read,prefill-i<8?prefill-i:8);
+    int d=oggpackB_read(&dest_read,prefill-i<8?prefill-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d mismatch! byte %d, %x!=%x\n",prefill,i/8,s,d);
+      exit(1);
+    }
+  }
+  if(prefill<dest_bytes){
+    if(oggpackB_read(&dest_read,dest_bytes-prefill)!=0){
+      fprintf(stderr,"prefill=%d mismatch! trailing bits not zero\n",prefill);
+      exit(1);
+    }
+  }
+
+  /* second copy */
+  oggpackB_writecopy(&dest_write,source,copy);
+
+  /* check buffers; verify end byte masking */
+  dest=oggpackB_get_buffer(&dest_write);
+  dest_bytes=oggpackB_bytes(&dest_write);
+  if(dest_bytes!=(copy+prefill+7)/8){
+    fprintf(stderr,"wrong number of bytes after prefill+copy! %ld!=%d\n",dest_bytes,(copy+prefill+7)/8);
+    exit(1);
+  }
+  oggpackB_readinit(&source_read,source,source_bytes);
+  oggpackB_readinit(&dest_read,dest,dest_bytes);
+
+  for(i=0;i<prefill;i+=8){
+    int s=oggpackB_read(&source_read,prefill-i<8?prefill-i:8);
+    int d=oggpackB_read(&dest_read,prefill-i<8?prefill-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d mismatch! byte %d, %x!=%x\n",prefill,i/8,s,d);
+      exit(1);
+    }
+  }
+
+  oggpackB_readinit(&source_read,source,source_bytes);
+  for(i=0;i<copy;i+=8){
+    int s=oggpackB_read(&source_read,copy-i<8?copy-i:8);
+    int d=oggpackB_read(&dest_read,copy-i<8?copy-i:8);
+    if(s!=d){
+      fprintf(stderr,"prefill=%d copy=%d mismatch! byte %d, %x!=%x\n",prefill,copy,i/8,s,d);
+      exit(1);
+    }
+  }
+
+  if(copy+prefill<dest_bytes){
+    if(oggpackB_read(&dest_read,dest_bytes-copy-prefill)!=0){
+      fprintf(stderr,"prefill=%d copy=%d mismatch! trailing bits not zero\n",prefill,copy);
+      exit(1);
+    }
+  }
+
+  oggpackB_writeclear(&source_write);
+  oggpackB_writeclear(&dest_write);
+
+}
+
+int main(void){
+  unsigned char *buffer;
+  long bytes,i,j;
+  static unsigned long testbuffer1[]=
+    {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
+       567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
+  int test1size=43;
+
+  static unsigned long testbuffer2[]=
+    {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
+       1233432,534,5,346435231,14436467,7869299,76326614,167548585,
+       85525151,0,12321,1,349528352};
+  int test2size=21;
+
+  static unsigned long testbuffer3[]=
+    {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
+       0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
+  int test3size=56;
+
+  static unsigned long large[]=
+    {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
+       1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
+       85525151,0,12321,1,2146528352};
+
+  int onesize=33;
+  static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
+                    34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
+                    223,4};
+  static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
+                       8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
+                       245,251,128};
+
+  int twosize=6;
+  static int two[6]={61,255,255,251,231,29};
+  static int twoB[6]={247,63,255,253,249,120};
+
+  int threesize=54;
+  static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
+                      142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
+                      58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
+                      100,52,4,14,18,86,77,1};
+  static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
+                         130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
+                         233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
+                         200,20,254,4,58,106,176,144,0};
+
+  int foursize=38;
+  static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
+                     132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
+                     28,2,133,0,1};
+  static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
+                        1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
+                        129,10,4,32};
+
+  int fivesize=45;
+  static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
+                     241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
+                     84,75,159,2,1,0,132,192,8,0,0,18,22};
+  static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
+                        124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
+                        172,150,169,129,79,128,0,6,4,32,0,27,9,0};
+
+  int sixsize=7;
+  static int six[7]={17,177,170,242,169,19,148};
+  static int sixB[7]={136,141,85,79,149,200,41};
+
+  /* Test read/write together */
+  /* Later we test against pregenerated bitstreams */
+  oggpack_writeinit(&o);
+
+  fprintf(stderr,"\nSmall preclipped packing (LSb): ");
+  cliptest(testbuffer1,test1size,0,one,onesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nNull bit call (LSb): ");
+  cliptest(testbuffer3,test3size,0,two,twosize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nLarge preclipped packing (LSb): ");
+  cliptest(testbuffer2,test2size,0,three,threesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
+  oggpack_reset(&o);
+  for(i=0;i<test2size;i++)
+    oggpack_write(&o,large[i],32);
+  buffer=oggpack_get_buffer(&o);
+  bytes=oggpack_bytes(&o);
+  oggpack_readinit(&r,buffer,bytes);
+  for(i=0;i<test2size;i++){
+    if(oggpack_look(&r,32)==-1)report("out of data. failed!");
+    if(oggpack_look(&r,32)!=large[i]){
+      fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
+              oggpack_look(&r,32),large[i]);
+      report("read incorrect value!\n");
+    }
+    oggpack_adv(&r,32);
+  }
+  if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nSmall unclipped packing (LSb): ");
+  cliptest(testbuffer1,test1size,7,four,foursize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nLarge unclipped packing (LSb): ");
+  cliptest(testbuffer2,test2size,17,five,fivesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
+  cliptest(testbuffer3,test3size,1,six,sixsize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nTesting read past end (LSb): ");
+  oggpack_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
+  for(i=0;i<64;i++){
+    if(oggpack_read(&r,1)!=0){
+      fprintf(stderr,"failed; got -1 prematurely.\n");
+      exit(1);
+    }
+  }
+  if(oggpack_look(&r,1)!=-1 ||
+     oggpack_read(&r,1)!=-1){
+      fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  oggpack_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
+  if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
+      fprintf(stderr,"failed 2; got -1 prematurely.\n");
+      exit(1);
+  }
+
+  if(oggpack_look(&r,18)!=0 ||
+     oggpack_look(&r,18)!=0){
+    fprintf(stderr,"failed 3; got -1 prematurely.\n");
+      exit(1);
+  }
+  if(oggpack_look(&r,19)!=-1 ||
+     oggpack_look(&r,19)!=-1){
+    fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  if(oggpack_look(&r,32)!=-1 ||
+     oggpack_look(&r,32)!=-1){
+    fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  oggpack_writeclear(&o);
+  fprintf(stderr,"ok.");
+
+  /* this is partly glassbox; we're mostly concerned about the allocation boundaries */
+
+  fprintf(stderr,"\nTesting aligned writecopies (LSb): ");
+  for(i=0;i<71;i++)
+    for(j=0;j<5;j++)
+      copytest(j*8,i);
+  for(i=BUFFER_INCREMENT*8-71;i<BUFFER_INCREMENT*8+71;i++)
+    for(j=0;j<5;j++)
+      copytest(j*8,i);
+  fprintf(stderr,"ok.      ");
+
+  fprintf(stderr,"\nTesting unaligned writecopies (LSb): ");
+  for(i=0;i<71;i++)
+    for(j=1;j<40;j++)
+      if(j&0x7)
+        copytest(j,i);
+  for(i=BUFFER_INCREMENT*8-71;i<BUFFER_INCREMENT*8+71;i++)
+    for(j=1;j<40;j++)
+      if(j&0x7)
+        copytest(j,i);
+  
+  fprintf(stderr,"ok.      \n");
+
+
+  /********** lazy, cut-n-paste retest with MSb packing ***********/
+
+  /* Test read/write together */
+  /* Later we test against pregenerated bitstreams */
+  oggpackB_writeinit(&o);
+
+  fprintf(stderr,"\nSmall preclipped packing (MSb): ");
+  cliptestB(testbuffer1,test1size,0,oneB,onesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nNull bit call (MSb): ");
+  cliptestB(testbuffer3,test3size,0,twoB,twosize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nLarge preclipped packing (MSb): ");
+  cliptestB(testbuffer2,test2size,0,threeB,threesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
+  oggpackB_reset(&o);
+  for(i=0;i<test2size;i++)
+    oggpackB_write(&o,large[i],32);
+  buffer=oggpackB_get_buffer(&o);
+  bytes=oggpackB_bytes(&o);
+  oggpackB_readinit(&r,buffer,bytes);
+  for(i=0;i<test2size;i++){
+    if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
+    if(oggpackB_look(&r,32)!=large[i]){
+      fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
+              oggpackB_look(&r,32),large[i]);
+      report("read incorrect value!\n");
+    }
+    oggpackB_adv(&r,32);
+  }
+  if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nSmall unclipped packing (MSb): ");
+  cliptestB(testbuffer1,test1size,7,fourB,foursize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nLarge unclipped packing (MSb): ");
+  cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
+  cliptestB(testbuffer3,test3size,1,sixB,sixsize);
+  fprintf(stderr,"ok.");
+
+  fprintf(stderr,"\nTesting read past end (MSb): ");
+  oggpackB_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
+  for(i=0;i<64;i++){
+    if(oggpackB_read(&r,1)!=0){
+      fprintf(stderr,"failed; got -1 prematurely.\n");
+      exit(1);
+    }
+  }
+  if(oggpackB_look(&r,1)!=-1 ||
+     oggpackB_read(&r,1)!=-1){
+      fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  oggpackB_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
+  if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
+      fprintf(stderr,"failed 2; got -1 prematurely.\n");
+      exit(1);
+  }
+
+  if(oggpackB_look(&r,18)!=0 ||
+     oggpackB_look(&r,18)!=0){
+    fprintf(stderr,"failed 3; got -1 prematurely.\n");
+      exit(1);
+  }
+  if(oggpackB_look(&r,19)!=-1 ||
+     oggpackB_look(&r,19)!=-1){
+    fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  if(oggpackB_look(&r,32)!=-1 ||
+     oggpackB_look(&r,32)!=-1){
+    fprintf(stderr,"failed; read past end without -1.\n");
+      exit(1);
+  }
+  fprintf(stderr,"ok.");
+  oggpackB_writeclear(&o);
+
+  /* this is partly glassbox; we're mostly concerned about the allocation boundaries */
+
+  fprintf(stderr,"\nTesting aligned writecopies (MSb): ");
+  for(i=0;i<71;i++)
+    for(j=0;j<5;j++)
+      copytestB(j*8,i);
+  for(i=BUFFER_INCREMENT*8-71;i<BUFFER_INCREMENT*8+71;i++)
+    for(j=0;j<5;j++)
+      copytestB(j*8,i);
+  fprintf(stderr,"ok.      ");
+
+  fprintf(stderr,"\nTesting unaligned writecopies (MSb): ");
+  for(i=0;i<71;i++)
+    for(j=1;j<40;j++)
+      if(j&0x7)
+        copytestB(j,i);
+  for(i=BUFFER_INCREMENT*8-71;i<BUFFER_INCREMENT*8+71;i++)
+    for(j=1;j<40;j++)
+      if(j&0x7)
+        copytestB(j,i);
+  
+  fprintf(stderr,"ok.      \n\n");
+
+  return(0);
+}
+#endif  /* _V_SELFTEST */
+
+#undef BUFFER_INCREMENT
diff --git a/ogg/src/framing.c b/ogg/src/framing.c
new file mode 100644 (file)
index 0000000..79fc715
--- /dev/null
@@ -0,0 +1,2140 @@
+/********************************************************************
+ *                                                                  *
+ * THIS FILE IS PART OF THE Ogg CONTAINER 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: code raw packets into framed OggSquish stream and
+           decode Ogg streams back into raw packets
+ last mod: $Id$
+
+ note: The CRC code is directly derived from public domain code by
+ Ross Williams (ross@guest.adelaide.edu.au).  See docs/framing.html
+ for details.
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <limits.h>
+#include <string.h>
+#include <ogg/ogg.h>
+
+/* A complete description of Ogg framing exists in docs/framing.html */
+
+int ogg_page_version(const ogg_page *og){
+  return((int)(og->header[4]));
+}
+
+int ogg_page_continued(const ogg_page *og){
+  return((int)(og->header[5]&0x01));
+}
+
+int ogg_page_bos(const ogg_page *og){
+  return((int)(og->header[5]&0x02));
+}
+
+int ogg_page_eos(const ogg_page *og){
+  return((int)(og->header[5]&0x04));
+}
+
+ogg_int64_t ogg_page_granulepos(const ogg_page *og){
+  unsigned char *page=og->header;
+  ogg_int64_t granulepos=page[13]&(0xff);
+  granulepos= (granulepos<<8)|(page[12]&0xff);
+  granulepos= (granulepos<<8)|(page[11]&0xff);
+  granulepos= (granulepos<<8)|(page[10]&0xff);
+  granulepos= (granulepos<<8)|(page[9]&0xff);
+  granulepos= (granulepos<<8)|(page[8]&0xff);
+  granulepos= (granulepos<<8)|(page[7]&0xff);
+  granulepos= (granulepos<<8)|(page[6]&0xff);
+  return(granulepos);
+}
+
+int ogg_page_serialno(const ogg_page *og){
+  return(og->header[14] |
+         (og->header[15]<<8) |
+         (og->header[16]<<16) |
+         (og->header[17]<<24));
+}
+
+long ogg_page_pageno(const ogg_page *og){
+  return(og->header[18] |
+         (og->header[19]<<8) |
+         (og->header[20]<<16) |
+         (og->header[21]<<24));
+}
+
+
+
+/* returns the number of packets that are completed on this page (if
+   the leading packet is begun on a previous page, but ends on this
+   page, it's counted */
+
+/* NOTE:
+   If a page consists of a packet begun on a previous page, and a new
+   packet begun (but not completed) on this page, the return will be:
+     ogg_page_packets(page)   ==1,
+     ogg_page_continued(page) !=0
+
+   If a page happens to be a single packet that was begun on a
+   previous page, and spans to the next page (in the case of a three or
+   more page packet), the return will be:
+     ogg_page_packets(page)   ==0,
+     ogg_page_continued(page) !=0
+*/
+
+int ogg_page_packets(const ogg_page *og){
+  int i,n=og->header[26],count=0;
+  for(i=0;i<n;i++)
+    if(og->header[27+i]<255)count++;
+  return(count);
+}
+
+
+#if 0
+/* helper to initialize lookup for direct-table CRC (illustrative; we
+   use the static init below) */
+
+static ogg_uint32_t _ogg_crc_entry(unsigned long index){
+  int           i;
+  unsigned long r;
+
+  r = index << 24;
+  for (i=0; i<8; i++)
+    if (r & 0x80000000UL)
+      r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
+                                    polynomial, although we use an
+                                    unreflected alg and an init/final
+                                    of 0, not 0xffffffff */
+    else
+       r<<=1;
+ return (r & 0xffffffffUL);
+}
+#endif
+
+static const ogg_uint32_t crc_lookup[256]={
+  0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
+  0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
+  0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
+  0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
+  0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
+  0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
+  0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
+  0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
+  0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
+  0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
+  0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
+  0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
+  0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
+  0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
+  0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
+  0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
+  0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
+  0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
+  0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
+  0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
+  0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
+  0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
+  0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
+  0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
+  0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
+  0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
+  0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
+  0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
+  0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
+  0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
+  0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
+  0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
+  0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
+  0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
+  0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
+  0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
+  0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
+  0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
+  0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
+  0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
+  0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
+  0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
+  0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
+  0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
+  0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
+  0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
+  0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
+  0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
+  0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
+  0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
+  0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
+  0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
+  0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
+  0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
+  0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
+  0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
+  0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
+  0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
+  0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
+  0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
+  0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
+  0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
+  0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
+  0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
+
+/* init the encode/decode logical stream state */
+
+int ogg_stream_init(ogg_stream_state *os,int serialno){
+  if(os){
+    memset(os,0,sizeof(*os));
+    os->body_storage=16*1024;
+    os->lacing_storage=1024;
+
+    os->body_data=_ogg_malloc(os->body_storage*sizeof(*os->body_data));
+    os->lacing_vals=_ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
+    os->granule_vals=_ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
+
+    if(!os->body_data || !os->lacing_vals || !os->granule_vals){
+      ogg_stream_clear(os);
+      return -1;
+    }
+
+    os->serialno=serialno;
+
+    return(0);
+  }
+  return(-1);
+}
+
+/* async/delayed error detection for the ogg_stream_state */
+int ogg_stream_check(ogg_stream_state *os){
+  if(!os || !os->body_data) return -1;
+  return 0;
+}
+
+/* _clear does not free os, only the non-flat storage within */
+int ogg_stream_clear(ogg_stream_state *os){
+  if(os){
+    if(os->body_data)_ogg_free(os->body_data);
+    if(os->lacing_vals)_ogg_free(os->lacing_vals);
+    if(os->granule_vals)_ogg_free(os->granule_vals);
+
+    memset(os,0,sizeof(*os));
+  }
+  return(0);
+}
+
+int ogg_stream_destroy(ogg_stream_state *os){
+  if(os){
+    ogg_stream_clear(os);
+    _ogg_free(os);
+  }
+  return(0);
+}
+
+/* Helpers for ogg_stream_encode; this keeps the structure and
+   what's happening fairly clear */
+
+static int _os_body_expand(ogg_stream_state *os,long needed){
+  if(os->body_storage-needed<=os->body_fill){
+    long body_storage;
+    void *ret;
+    if(os->body_storage>LONG_MAX-needed){
+      ogg_stream_clear(os);
+      return -1;
+    }
+    body_storage=os->body_storage+needed;
+    if(body_storage<LONG_MAX-1024)body_storage+=1024;
+    ret=_ogg_realloc(os->body_data,body_storage*sizeof(*os->body_data));
+    if(!ret){
+      ogg_stream_clear(os);
+      return -1;
+    }
+    os->body_storage=body_storage;
+    os->body_data=ret;
+  }
+  return 0;
+}
+
+static int _os_lacing_expand(ogg_stream_state *os,long needed){
+  if(os->lacing_storage-needed<=os->lacing_fill){
+    long lacing_storage;
+    void *ret;
+    if(os->lacing_storage>LONG_MAX-needed){
+      ogg_stream_clear(os);
+      return -1;
+    }
+    lacing_storage=os->lacing_storage+needed;
+    if(lacing_storage<LONG_MAX-32)lacing_storage+=32;
+    ret=_ogg_realloc(os->lacing_vals,lacing_storage*sizeof(*os->lacing_vals));
+    if(!ret){
+      ogg_stream_clear(os);
+      return -1;
+    }
+    os->lacing_vals=ret;
+    ret=_ogg_realloc(os->granule_vals,lacing_storage*
+                     sizeof(*os->granule_vals));
+    if(!ret){
+      ogg_stream_clear(os);
+      return -1;
+    }
+    os->granule_vals=ret;
+    os->lacing_storage=lacing_storage;
+  }
+  return 0;
+}
+
+/* checksum the page */
+/* Direct table CRC; note that this will be faster in the future if we
+   perform the checksum simultaneously with other copies */
+
+void ogg_page_checksum_set(ogg_page *og){
+  if(og){
+    ogg_uint32_t crc_reg=0;
+    int i;
+
+    /* safety; needed for API behavior, but not framing code */
+    og->header[22]=0;
+    og->header[23]=0;
+    og->header[24]=0;
+    og->header[25]=0;
+
+    for(i=0;i<og->header_len;i++)
+      crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
+    for(i=0;i<og->body_len;i++)
+      crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
+
+    og->header[22]=(unsigned char)(crc_reg&0xff);
+    og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
+    og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
+    og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
+  }
+}
+
+/* submit data to the internal buffer of the framing engine */
+int ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov, int count,
+                       long e_o_s, ogg_int64_t granulepos){
+
+  long bytes = 0, lacing_vals;
+  int i;
+
+  if(ogg_stream_check(os)) return -1;
+  if(!iov) return 0;
+
+  for (i = 0; i < count; ++i){
+    if(iov[i].iov_len>LONG_MAX) return -1;
+    if(bytes>LONG_MAX-(long)iov[i].iov_len) return -1;
+    bytes += (long)iov[i].iov_len;
+  }
+  lacing_vals=bytes/255+1;
+
+  if(os->body_returned){
+    /* advance packet data according to the body_returned pointer. We
+       had to keep it around to return a pointer into the buffer last
+       call */
+
+    os->body_fill-=os->body_returned;
+    if(os->body_fill)
+      memmove(os->body_data,os->body_data+os->body_returned,
+              os->body_fill);
+    os->body_returned=0;
+  }
+
+  /* make sure we have the buffer storage */
+  if(_os_body_expand(os,bytes) || _os_lacing_expand(os,lacing_vals))
+    return -1;
+
+  /* Copy in the submitted packet.  Yes, the copy is a waste; this is
+     the liability of overly clean abstraction for the time being.  It
+     will actually be fairly easy to eliminate the extra copy in the
+     future */
+
+  for (i = 0; i < count; ++i) {
+    memcpy(os->body_data+os->body_fill, iov[i].iov_base, iov[i].iov_len);
+    os->body_fill += (int)iov[i].iov_len;
+  }
+
+  /* Store lacing vals for this packet */
+  for(i=0;i<lacing_vals-1;i++){
+    os->lacing_vals[os->lacing_fill+i]=255;
+    os->granule_vals[os->lacing_fill+i]=os->granulepos;
+  }
+  os->lacing_vals[os->lacing_fill+i]=bytes%255;
+  os->granulepos=os->granule_vals[os->lacing_fill+i]=granulepos;
+
+  /* flag the first segment as the beginning of the packet */
+  os->lacing_vals[os->lacing_fill]|= 0x100;
+
+  os->lacing_fill+=lacing_vals;
+
+  /* for the sake of completeness */
+  os->packetno++;
+
+  if(e_o_s)os->e_o_s=1;
+
+  return(0);
+}
+
+int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
+  ogg_iovec_t iov;
+  iov.iov_base = op->packet;
+  iov.iov_len = op->bytes;
+  return ogg_stream_iovecin(os, &iov, 1, op->e_o_s, op->granulepos);
+}
+
+/* Conditionally flush a page; force==0 will only flush nominal-size
+   pages, force==1 forces us to flush a page regardless of page size
+   so long as there's any data available at all. */
+static int ogg_stream_flush_i(ogg_stream_state *os,ogg_page *og, int force, int nfill){
+  int i;
+  int vals=0;
+  int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
+  int bytes=0;
+  long acc=0;
+  ogg_int64_t granule_pos=-1;
+
+  if(ogg_stream_check(os)) return(0);
+  if(maxvals==0) return(0);
+
+  /* construct a page */
+  /* decide how many segments to include */
+
+  /* If this is the initial header case, the first page must only include
+     the initial header packet */
+  if(os->b_o_s==0){  /* 'initial header page' case */
+    granule_pos=0;
+    for(vals=0;vals<maxvals;vals++){
+      if((os->lacing_vals[vals]&0x0ff)<255){
+        vals++;
+        break;
+      }
+    }
+  }else{
+
+    /* The extra packets_done, packet_just_done logic here attempts to do two things:
+       1) Don't unneccessarily span pages.
+       2) Unless necessary, don't flush pages if there are less than four packets on
+          them; this expands page size to reduce unneccessary overhead if incoming packets
+          are large.
+       These are not necessary behaviors, just 'always better than naive flushing'
+       without requiring an application to explicitly request a specific optimized
+       behavior. We'll want an explicit behavior setup pathway eventually as well. */
+
+    int packets_done=0;
+    int packet_just_done=0;
+    for(vals=0;vals<maxvals;vals++){
+      if(acc>nfill && packet_just_done>=4){
+        force=1;
+        break;
+      }
+      acc+=os->lacing_vals[vals]&0x0ff;
+      if((os->lacing_vals[vals]&0xff)<255){
+        granule_pos=os->granule_vals[vals];
+        packet_just_done=++packets_done;
+      }else
+        packet_just_done=0;
+    }
+    if(vals==255)force=1;
+  }
+
+  if(!force) return(0);
+
+  /* construct the header in temp storage */
+  memcpy(os->header,"OggS",4);
+
+  /* stream structure version */
+  os->header[4]=0x00;
+
+  /* continued packet flag? */
+  os->header[5]=0x00;
+  if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
+  /* first page flag? */
+  if(os->b_o_s==0)os->header[5]|=0x02;
+  /* last page flag? */
+  if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
+  os->b_o_s=1;
+
+  /* 64 bits of PCM position */
+  for(i=6;i<14;i++){
+    os->header[i]=(unsigned char)(granule_pos&0xff);
+    granule_pos>>=8;
+  }
+
+  /* 32 bits of stream serial number */
+  {
+    long serialno=os->serialno;
+    for(i=14;i<18;i++){
+      os->header[i]=(unsigned char)(serialno&0xff);
+      serialno>>=8;
+    }
+  }
+
+  /* 32 bits of page counter (we have both counter and page header
+     because this val can roll over) */
+  if(os->pageno==-1)os->pageno=0; /* because someone called
+                                     stream_reset; this would be a
+                                     strange thing to do in an
+                                     encode stream, but it has
+                                     plausible uses */
+  {
+    long pageno=os->pageno++;
+    for(i=18;i<22;i++){
+      os->header[i]=(unsigned char)(pageno&0xff);
+      pageno>>=8;
+    }
+  }
+
+  /* zero for computation; filled in later */
+  os->header[22]=0;
+  os->header[23]=0;
+  os->header[24]=0;
+  os->header[25]=0;
+
+  /* segment table */
+  os->header[26]=(unsigned char)(vals&0xff);
+  for(i=0;i<vals;i++)
+    bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
+
+  /* set pointers in the ogg_page struct */
+  og->header=os->header;
+  og->header_len=os->header_fill=vals+27;
+  og->body=os->body_data+os->body_returned;
+  og->body_len=bytes;
+
+  /* advance the lacing data and set the body_returned pointer */
+
+  os->lacing_fill-=vals;
+  memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
+  memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
+  os->body_returned+=bytes;
+
+  /* calculate the checksum */
+
+  ogg_page_checksum_set(og);
+
+  /* done */
+  return(1);
+}
+
+/* This will flush remaining packets into a page (returning nonzero),
+   even if there is not enough data to trigger a flush normally
+   (undersized page). If there are no packets or partial packets to
+   flush, ogg_stream_flush returns 0.  Note that ogg_stream_flush will
+   try to flush a normal sized page like ogg_stream_pageout; a call to
+   ogg_stream_flush does not guarantee that all packets have flushed.
+   Only a return value of 0 from ogg_stream_flush indicates all packet
+   data is flushed into pages.
+
+   since ogg_stream_flush will flush the last page in a stream even if
+   it's undersized, you almost certainly want to use ogg_stream_pageout
+   (and *not* ogg_stream_flush) unless you specifically need to flush
+   a page regardless of size in the middle of a stream. */
+
+int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
+  return ogg_stream_flush_i(os,og,1,4096);
+}
+
+/* Like the above, but an argument is provided to adjust the nominal
+   page size for applications which are smart enough to provide their
+   own delay based flushing */
+
+int ogg_stream_flush_fill(ogg_stream_state *os,ogg_page *og, int nfill){
+  return ogg_stream_flush_i(os,og,1,nfill);
+}
+
+/* This constructs pages from buffered packet segments.  The pointers
+returned are to static buffers; do not free. The returned buffers are
+good only until the next call (using the same ogg_stream_state) */
+
+int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
+  int force=0;
+  if(ogg_stream_check(os)) return 0;
+
+  if((os->e_o_s&&os->lacing_fill) ||          /* 'were done, now flush' case */
+     (os->lacing_fill&&!os->b_o_s))           /* 'initial header page' case */
+    force=1;
+
+  return(ogg_stream_flush_i(os,og,force,4096));
+}
+
+/* Like the above, but an argument is provided to adjust the nominal
+page size for applications which are smart enough to provide their
+own delay based flushing */
+
+int ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill){
+  int force=0;
+  if(ogg_stream_check(os)) return 0;
+
+  if((os->e_o_s&&os->lacing_fill) ||          /* 'were done, now flush' case */
+     (os->lacing_fill&&!os->b_o_s))           /* 'initial header page' case */
+    force=1;
+
+  return(ogg_stream_flush_i(os,og,force,nfill));
+}
+
+int ogg_stream_eos(ogg_stream_state *os){
+  if(ogg_stream_check(os)) return 1;
+  return os->e_o_s;
+}
+
+/* DECODING PRIMITIVES: packet streaming layer **********************/
+
+/* This has two layers to place more of the multi-serialno and paging
+   control in the application's hands.  First, we expose a data buffer
+   using ogg_sync_buffer().  The app either copies into the
+   buffer, or passes it directly to read(), etc.  We then call
+   ogg_sync_wrote() to tell how many bytes we just added.
+
+   Pages are returned (pointers into the buffer in ogg_sync_state)
+   by ogg_sync_pageout().  The page is then submitted to
+   ogg_stream_pagein() along with the appropriate
+   ogg_stream_state* (ie, matching serialno).  We then get raw
+   packets out calling ogg_stream_packetout() with a
+   ogg_stream_state. */
+
+/* initialize the struct to a known state */
+int ogg_sync_init(ogg_sync_state *oy){
+  if(oy){
+    oy->storage = -1; /* used as a readiness flag */
+    memset(oy,0,sizeof(*oy));
+  }
+  return(0);
+}
+
+/* clear non-flat storage within */
+int ogg_sync_clear(ogg_sync_state *oy){
+  if(oy){
+    if(oy->data)_ogg_free(oy->data);
+    memset(oy,0,sizeof(*oy));
+  }
+  return(0);
+}
+
+int ogg_sync_destroy(ogg_sync_state *oy){
+  if(oy){
+    ogg_sync_clear(oy);
+    _ogg_free(oy);
+  }
+  return(0);
+}
+
+int ogg_sync_check(ogg_sync_state *oy){
+  if(oy->storage<0) return -1;
+  return 0;
+}
+
+char *ogg_sync_buffer(ogg_sync_state *oy, long size){
+  if(ogg_sync_check(oy)) return NULL;
+
+  /* first, clear out any space that has been previously returned */
+  if(oy->returned){
+    oy->fill-=oy->returned;
+    if(oy->fill>0)
+      memmove(oy->data,oy->data+oy->returned,oy->fill);
+    oy->returned=0;
+  }
+
+  if(size>oy->storage-oy->fill){
+    /* We need to extend the internal buffer */
+    long newsize=size+oy->fill+4096; /* an extra page to be nice */
+    void *ret;
+
+    if(oy->data)
+      ret=_ogg_realloc(oy->data,newsize);
+    else
+      ret=_ogg_malloc(newsize);
+    if(!ret){
+      ogg_sync_clear(oy);
+      return NULL;
+    }
+    oy->data=ret;
+    oy->storage=newsize;
+  }
+
+  /* expose a segment at least as large as requested at the fill mark */
+  return((char *)oy->data+oy->fill);
+}
+
+int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
+  if(ogg_sync_check(oy))return -1;
+  if(oy->fill+bytes>oy->storage)return -1;
+  oy->fill+=bytes;
+  return(0);
+}
+
+/* sync the stream.  This is meant to be useful for finding page
+   boundaries.
+
+   return values for this:
+  -n) skipped n bytes
+   0) page not ready; more data (no bytes skipped)
+   n) page synced at current location; page length n bytes
+
+*/
+
+long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
+  unsigned char *page=oy->data+oy->returned;
+  unsigned char *next;
+  long bytes=oy->fill-oy->returned;
+
+  if(ogg_sync_check(oy))return 0;
+
+  if(oy->headerbytes==0){
+    int headerbytes,i;
+    if(bytes<27)return(0); /* not enough for a header */
+
+    /* verify capture pattern */
+    if(memcmp(page,"OggS",4))goto sync_fail;
+
+    headerbytes=page[26]+27;
+    if(bytes<headerbytes)return(0); /* not enough for header + seg table */
+
+    /* count up body length in the segment table */
+
+    for(i=0;i<page[26];i++)
+      oy->bodybytes+=page[27+i];
+    oy->headerbytes=headerbytes;
+  }
+
+  if(oy->bodybytes+oy->headerbytes>bytes)return(0);
+
+  /* The whole test page is buffered.  Verify the checksum */
+  {
+    /* Grab the checksum bytes, set the header field to zero */
+    char chksum[4];
+    ogg_page log;
+
+    memcpy(chksum,page+22,4);
+    memset(page+22,0,4);
+
+    /* set up a temp page struct and recompute the checksum */
+    log.header=page;
+    log.header_len=oy->headerbytes;
+    log.body=page+oy->headerbytes;
+    log.body_len=oy->bodybytes;
+    ogg_page_checksum_set(&log);
+
+    /* Compare */
+    if(memcmp(chksum,page+22,4)){
+      /* D'oh.  Mismatch! Corrupt page (or miscapture and not a page
+         at all) */
+      /* replace the computed checksum with the one actually read in */
+      memcpy(page+22,chksum,4);
+
+      /* Bad checksum. Lose sync */
+      goto sync_fail;
+    }
+  }
+
+  /* yes, have a whole page all ready to go */
+  {
+    unsigned char *page=oy->data+oy->returned;
+    long bytes;
+
+    if(og){
+      og->header=page;
+      og->header_len=oy->headerbytes;
+      og->body=page+oy->headerbytes;
+      og->body_len=oy->bodybytes;
+    }
+
+    oy->unsynced=0;
+    oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
+    oy->headerbytes=0;
+    oy->bodybytes=0;
+    return(bytes);
+  }
+
+ sync_fail:
+
+  oy->headerbytes=0;
+  oy->bodybytes=0;
+
+  /* search for possible capture */
+  next=memchr(page+1,'O',bytes-1);
+  if(!next)
+    next=oy->data+oy->fill;
+
+  oy->returned=(int)(next-oy->data);
+  return((long)-(next-page));
+}
+
+/* sync the stream and get a page.  Keep trying until we find a page.
+   Suppress 'sync errors' after reporting the first.
+
+   return values:
+   -1) recapture (hole in data)
+    0) need more data
+    1) page returned
+
+   Returns pointers into buffered data; invalidated by next call to
+   _stream, _clear, _init, or _buffer */
+
+int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
+
+  if(ogg_sync_check(oy))return 0;
+
+  /* all we need to do is verify a page at the head of the stream
+     buffer.  If it doesn't verify, we look for the next potential
+     frame */
+
+  for(;;){
+    long ret=ogg_sync_pageseek(oy,og);
+    if(ret>0){
+      /* have a page */
+      return(1);
+    }
+    if(ret==0){
+      /* need more data */
+      return(0);
+    }
+
+    /* head did not start a synced page... skipped some bytes */
+    if(!oy->unsynced){
+      oy->unsynced=1;
+      return(-1);
+    }
+
+    /* loop. keep looking */
+
+  }
+}
+
+/* add the incoming page to the stream state; we decompose the page
+   into packet segments here as well. */
+
+int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
+  unsigned char *header=og->header;
+  unsigned char *body=og->body;
+  long           bodysize=og->body_len;
+  int            segptr=0;
+
+  int version=ogg_page_version(og);
+  int continued=ogg_page_continued(og);
+  int bos=ogg_page_bos(og);
+  int eos=ogg_page_eos(og);
+  ogg_int64_t granulepos=ogg_page_granulepos(og);
+  int serialno=ogg_page_serialno(og);
+  long pageno=ogg_page_pageno(og);
+  int segments=header[26];
+
+  if(ogg_stream_check(os)) return -1;
+
+  /* clean up 'returned data' */
+  {
+    long lr=os->lacing_returned;
+    long br=os->body_returned;
+
+    /* body data */
+    if(br){
+      os->body_fill-=br;
+      if(os->body_fill)
+        memmove(os->body_data,os->body_data+br,os->body_fill);
+      os->body_returned=0;
+    }
+
+    if(lr){
+      /* segment table */
+      if(os->lacing_fill-lr){
+        memmove(os->lacing_vals,os->lacing_vals+lr,
+                (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
+        memmove(os->granule_vals,os->granule_vals+lr,
+                (os->lacing_fill-lr)*sizeof(*os->granule_vals));
+      }
+      os->lacing_fill-=lr;
+      os->lacing_packet-=lr;
+      os->lacing_returned=0;
+    }
+  }
+
+  /* check the serial number */
+  if(serialno!=os->serialno)return(-1);
+  if(version>0)return(-1);
+
+  if(_os_lacing_expand(os,segments+1)) return -1;
+
+  /* are we in sequence? */
+  if(pageno!=os->pageno){
+    int i;
+
+    /* unroll previous partial packet (if any) */
+    for(i=os->lacing_packet;i<os->lacing_fill;i++)
+      os->body_fill-=os->lacing_vals[i]&0xff;
+    os->lacing_fill=os->lacing_packet;
+
+    /* make a note of dropped data in segment table */
+    if(os->pageno!=-1){
+      os->lacing_vals[os->lacing_fill++]=0x400;
+      os->lacing_packet++;
+    }
+  }
+
+  /* are we a 'continued packet' page?  If so, we may need to skip
+     some segments */
+  if(continued){
+    if(os->lacing_fill<1 ||
+       (os->lacing_vals[os->lacing_fill-1]&0xff)<255 ||
+       os->lacing_vals[os->lacing_fill-1]==0x400){
+      bos=0;
+      for(;segptr<segments;segptr++){
+        int val=header[27+segptr];
+        body+=val;
+        bodysize-=val;
+        if(val<255){
+          segptr++;
+          break;
+        }
+      }
+    }
+  }
+
+  if(bodysize){
+    if(_os_body_expand(os,bodysize)) return -1;
+    memcpy(os->body_data+os->body_fill,body,bodysize);
+    os->body_fill+=bodysize;
+  }
+
+  {
+    int saved=-1;
+    while(segptr<segments){
+      int val=header[27+segptr];
+      os->lacing_vals[os->lacing_fill]=val;
+      os->granule_vals[os->lacing_fill]=-1;
+
+      if(bos){
+        os->lacing_vals[os->lacing_fill]|=0x100;
+        bos=0;
+      }
+
+      if(val<255)saved=os->lacing_fill;
+
+      os->lacing_fill++;
+      segptr++;
+
+      if(val<255)os->lacing_packet=os->lacing_fill;
+    }
+
+    /* set the granulepos on the last granuleval of the last full packet */
+    if(saved!=-1){
+      os->granule_vals[saved]=granulepos;
+    }
+
+  }
+
+  if(eos){
+    os->e_o_s=1;
+    if(os->lacing_fill>0)
+      os->lacing_vals[os->lacing_fill-1]|=0x200;
+  }
+
+  os->pageno=pageno+1;
+
+  return(0);
+}
+
+/* clear things to an initial state.  Good to call, eg, before seeking */
+int ogg_sync_reset(ogg_sync_state *oy){
+  if(ogg_sync_check(oy))return -1;
+
+  oy->fill=0;
+  oy->returned=0;
+  oy->unsynced=0;
+  oy->headerbytes=0;
+  oy->bodybytes=0;
+  return(0);
+}
+
+int ogg_stream_reset(ogg_stream_state *os){
+  if(ogg_stream_check(os)) return -1;
+
+  os->body_fill=0;
+  os->body_returned=0;
+
+  os->lacing_fill=0;
+  os->lacing_packet=0;
+  os->lacing_returned=0;
+
+  os->header_fill=0;
+
+  os->e_o_s=0;
+  os->b_o_s=0;
+  os->pageno=-1;
+  os->packetno=0;
+  os->granulepos=0;
+
+  return(0);
+}
+
+int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
+  if(ogg_stream_check(os)) return -1;
+  ogg_stream_reset(os);
+  os->serialno=serialno;
+  return(0);
+}
+
+static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
+
+  /* The last part of decode. We have the stream broken into packet
+     segments.  Now we need to group them into packets (or return the
+     out of sync markers) */
+
+  int ptr=os->lacing_returned;
+
+  if(os->lacing_packet<=ptr)return(0);
+
+  if(os->lacing_vals[ptr]&0x400){
+    /* we need to tell the codec there's a gap; it might need to
+       handle previous packet dependencies. */
+    os->lacing_returned++;
+    os->packetno++;
+    return(-1);
+  }
+
+  if(!op && !adv)return(1); /* just using peek as an inexpensive way
+                               to ask if there's a whole packet
+                               waiting */
+
+  /* Gather the whole packet. We'll have no holes or a partial packet */
+  {
+    int size=os->lacing_vals[ptr]&0xff;
+    long bytes=size;
+    int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
+    int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
+
+    while(size==255){
+      int val=os->lacing_vals[++ptr];
+      size=val&0xff;
+      if(val&0x200)eos=0x200;
+      bytes+=size;
+    }
+
+    if(op){
+      op->e_o_s=eos;
+      op->b_o_s=bos;
+      op->packet=os->body_data+os->body_returned;
+      op->packetno=os->packetno;
+      op->granulepos=os->granule_vals[ptr];
+      op->bytes=bytes;
+    }
+
+    if(adv){
+      os->body_returned+=bytes;
+      os->lacing_returned=ptr+1;
+      os->packetno++;
+    }
+  }
+  return(1);
+}
+
+int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
+  if(ogg_stream_check(os)) return 0;
+  return _packetout(os,op,1);
+}
+
+int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
+  if(ogg_stream_check(os)) return 0;
+  return _packetout(os,op,0);
+}
+
+void ogg_packet_clear(ogg_packet *op) {
+  _ogg_free(op->packet);
+  memset(op, 0, sizeof(*op));
+}
+
+#ifdef _V_SELFTEST
+#include <stdio.h>
+
+ogg_stream_state os_en, os_de;
+ogg_sync_state oy;
+
+void checkpacket(ogg_packet *op,long len, int no, long pos){
+  long j;
+  static int sequence=0;
+  static int lastno=0;
+
+  if(op->bytes!=len){
+    fprintf(stderr,"incorrect packet length (%ld != %ld)!\n",op->bytes,len);
+    exit(1);
+  }
+  if(op->granulepos!=pos){
+    fprintf(stderr,"incorrect packet granpos (%ld != %ld)!\n",(long)op->granulepos,pos);
+    exit(1);
+  }
+
+  /* packet number just follows sequence/gap; adjust the input number
+     for that */
+  if(no==0){
+    sequence=0;
+  }else{
+    sequence++;
+    if(no>lastno+1)
+      sequence++;
+  }
+  lastno=no;
+  if(op->packetno!=sequence){
+    fprintf(stderr,"incorrect packet sequence %ld != %d\n",
+            (long)(op->packetno),sequence);
+    exit(1);
+  }
+
+  /* Test data */
+  for(j=0;j<op->bytes;j++)
+    if(op->packet[j]!=((j+no)&0xff)){
+      fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
+              j,op->packet[j],(j+no)&0xff);
+      exit(1);
+    }
+}
+
+void check_page(unsigned char *data,const int *header,ogg_page *og){
+  long j;
+  /* Test data */
+  for(j=0;j<og->body_len;j++)
+    if(og->body[j]!=data[j]){
+      fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
+              j,data[j],og->body[j]);
+      exit(1);
+    }
+
+  /* Test header */
+  for(j=0;j<og->header_len;j++){
+    if(og->header[j]!=header[j]){
+      fprintf(stderr,"header content mismatch at pos %ld:\n",j);
+      for(j=0;j<header[26]+27;j++)
+        fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
+      fprintf(stderr,"\n");
+      exit(1);
+    }
+  }
+  if(og->header_len!=header[26]+27){
+    fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
+            og->header_len,header[26]+27);
+    exit(1);
+  }
+}
+
+void print_header(ogg_page *og){
+  int j;
+  fprintf(stderr,"\nHEADER:\n");
+  fprintf(stderr,"  capture: %c %c %c %c  version: %d  flags: %x\n",
+          og->header[0],og->header[1],og->header[2],og->header[3],
+          (int)og->header[4],(int)og->header[5]);
+
+  fprintf(stderr,"  granulepos: %d  serialno: %d  pageno: %ld\n",
+          (og->header[9]<<24)|(og->header[8]<<16)|
+          (og->header[7]<<8)|og->header[6],
+          (og->header[17]<<24)|(og->header[16]<<16)|
+          (og->header[15]<<8)|og->header[14],
+          ((long)(og->header[21])<<24)|(og->header[20]<<16)|
+          (og->header[19]<<8)|og->header[18]);
+
+  fprintf(stderr,"  checksum: %02x:%02x:%02x:%02x\n  segments: %d (",
+          (int)og->header[22],(int)og->header[23],
+          (int)og->header[24],(int)og->header[25],
+          (int)og->header[26]);
+
+  for(j=27;j<og->header_len;j++)
+    fprintf(stderr,"%d ",(int)og->header[j]);
+  fprintf(stderr,")\n\n");
+}
+
+void copy_page(ogg_page *og){
+  unsigned char *temp=_ogg_malloc(og->header_len);
+  memcpy(temp,og->header,og->header_len);
+  og->header=temp;
+
+  temp=_ogg_malloc(og->body_len);
+  memcpy(temp,og->body,og->body_len);
+  og->body=temp;
+}
+
+void free_page(ogg_page *og){
+  _ogg_free (og->header);
+  _ogg_free (og->body);
+}
+
+void error(void){
+  fprintf(stderr,"error!\n");
+  exit(1);
+}
+
+/* 17 only */
+const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0x15,0xed,0xec,0x91,
+                       1,
+                       17};
+
+/* 17, 254, 255, 256, 500, 510, 600 byte, pad */
+const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0x59,0x10,0x6c,0x2c,
+                       1,
+                       17};
+const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
+                       0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0x89,0x33,0x85,0xce,
+                       13,
+                       254,255,0,255,1,255,245,255,255,0,
+                       255,255,90};
+
+/* nil packets; beginning,middle,end */
+const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0xff,0x7b,0x23,0x17,
+                       1,
+                       0};
+const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
+                       0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0x5c,0x3f,0x66,0xcb,
+                       17,
+                       17,254,255,0,0,255,1,0,255,245,255,255,0,
+                       255,255,90,0};
+
+/* large initial packet */
+const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0x01,0x27,0x31,0xaa,
+                       18,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,255,10};
+
+const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
+                       0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0x7f,0x4e,0x8a,0xd2,
+                       4,
+                       255,4,255,0};
+
+
+/* continuing packet test */
+const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0xff,0x7b,0x23,0x17,
+                       1,
+                       0};
+
+const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
+                       0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0xf8,0x3c,0x19,0x79,
+                       255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255};
+
+const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
+                       0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,2,0,0,0,
+                       0x38,0xe6,0xb6,0x28,
+                       6,
+                       255,220,255,4,255,0};
+
+
+/* spill expansion test */
+const int head1_4b[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                        0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                        0x01,0x02,0x03,0x04,0,0,0,0,
+                        0xff,0x7b,0x23,0x17,
+                        1,
+                        0};
+
+const int head2_4b[] = {0x4f,0x67,0x67,0x53,0,0x00,
+                        0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
+                        0x01,0x02,0x03,0x04,1,0,0,0,
+                        0xce,0x8f,0x17,0x1a,
+                        23,
+                        255,255,255,255,255,255,255,255,
+                        255,255,255,255,255,255,255,255,255,10,255,4,255,0,0};
+
+
+const int head3_4b[] = {0x4f,0x67,0x67,0x53,0,0x04,
+                        0x07,0x14,0x00,0x00,0x00,0x00,0x00,0x00,
+                        0x01,0x02,0x03,0x04,2,0,0,0,
+                        0x9b,0xb2,0x50,0xa1,
+                        1,
+                        0};
+
+/* page with the 255 segment limit */
+const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0xff,0x7b,0x23,0x17,
+                       1,
+                       0};
+
+const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
+                       0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0xed,0x2a,0x2e,0xa7,
+                       255,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10,10,
+                       10,10,10,10,10,10,10};
+
+const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
+                       0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,2,0,0,0,
+                       0x6c,0x3b,0x82,0x3d,
+                       1,
+                       50};
+
+
+/* packet that overspans over an entire page */
+const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0xff,0x7b,0x23,0x17,
+                       1,
+                       0};
+
+const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
+                       0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0x68,0x22,0x7c,0x3d,
+                       255,
+                       100,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255};
+
+const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
+                       0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
+                       0x01,0x02,0x03,0x04,2,0,0,0,
+                       0xf4,0x87,0xba,0xf3,
+                       255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255};
+
+const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
+                       0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,3,0,0,0,
+                       0xf7,0x2f,0x6c,0x60,
+                       5,
+                       254,255,4,255,0};
+
+/* packet that overspans over an entire page */
+const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
+                       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,0,0,0,0,
+                       0xff,0x7b,0x23,0x17,
+                       1,
+                       0};
+
+const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
+                       0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,1,0,0,0,
+                       0x68,0x22,0x7c,0x3d,
+                       255,
+                       100,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255,255,255,
+                       255,255,255,255,255,255};
+
+const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
+                       0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
+                       0x01,0x02,0x03,0x04,2,0,0,0,
+                       0xd4,0xe0,0x60,0xe5,
+                       1,
+                       0};
+
+int compare_packet(const ogg_packet *op1, const ogg_packet *op2){
+  if(op1->packet!=op2->packet){
+    fprintf(stderr,"op1->packet != op2->packet\n");
+    return(1);
+  }
+  if(op1->bytes!=op2->bytes){
+    fprintf(stderr,"op1->bytes != op2->bytes\n");
+    return(1);
+  }
+  if(op1->b_o_s!=op2->b_o_s){
+    fprintf(stderr,"op1->b_o_s != op2->b_o_s\n");
+    return(1);
+  }
+  if(op1->e_o_s!=op2->e_o_s){
+    fprintf(stderr,"op1->e_o_s != op2->e_o_s\n");
+    return(1);
+  }
+  if(op1->granulepos!=op2->granulepos){
+    fprintf(stderr,"op1->granulepos != op2->granulepos\n");
+    return(1);
+  }
+  if(op1->packetno!=op2->packetno){
+    fprintf(stderr,"op1->packetno != op2->packetno\n");
+    return(1);
+  }
+  return(0);
+}
+
+void test_pack(const int *pl, const int **headers, int byteskip,
+               int pageskip, int packetskip){
+  unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
+  long inptr=0;
+  long outptr=0;
+  long deptr=0;
+  long depacket=0;
+  long granule_pos=7,pageno=0;
+  int i,j,packets,pageout=pageskip;
+  int eosflag=0;
+  int bosflag=0;
+
+  int byteskipcount=0;
+
+  ogg_stream_reset(&os_en);
+  ogg_stream_reset(&os_de);
+  ogg_sync_reset(&oy);
+
+  for(packets=0;packets<packetskip;packets++)
+    depacket+=pl[packets];
+
+  for(packets=0;;packets++)if(pl[packets]==-1)break;
+
+  for(i=0;i<packets;i++){
+    /* construct a test packet */
+    ogg_packet op;
+    int len=pl[i];
+
+    op.packet=data+inptr;
+    op.bytes=len;
+    op.e_o_s=(pl[i+1]<0?1:0);
+    op.granulepos=granule_pos;
+
+    granule_pos+=1024;
+
+    for(j=0;j<len;j++)data[inptr++]=i+j;
+
+    /* submit the test packet */
+    ogg_stream_packetin(&os_en,&op);
+
+    /* retrieve any finished pages */
+    {
+      ogg_page og;
+
+      while(ogg_stream_pageout(&os_en,&og)){
+        /* We have a page.  Check it carefully */
+
+        fprintf(stderr,"%ld, ",pageno);
+
+        if(headers[pageno]==NULL){
+          fprintf(stderr,"coded too many pages!\n");
+          exit(1);
+        }
+
+        check_page(data+outptr,headers[pageno],&og);
+
+        outptr+=og.body_len;
+        pageno++;
+        if(pageskip){
+          bosflag=1;
+          pageskip--;
+          deptr+=og.body_len;
+        }
+
+        /* have a complete page; submit it to sync/decode */
+
+        {
+          ogg_page og_de;
+          ogg_packet op_de,op_de2;
+          char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
+          char *next=buf;
+          byteskipcount+=og.header_len;
+          if(byteskipcount>byteskip){
+            memcpy(next,og.header,byteskipcount-byteskip);
+            next+=byteskipcount-byteskip;
+            byteskipcount=byteskip;
+          }
+
+          byteskipcount+=og.body_len;
+          if(byteskipcount>byteskip){
+            memcpy(next,og.body,byteskipcount-byteskip);
+            next+=byteskipcount-byteskip;
+            byteskipcount=byteskip;
+          }
+
+          ogg_sync_wrote(&oy,next-buf);
+
+          while(1){
+            int ret=ogg_sync_pageout(&oy,&og_de);
+            if(ret==0)break;
+            if(ret<0)continue;
+            /* got a page.  Happy happy.  Verify that it's good. */
+
+            fprintf(stderr,"(%d), ",pageout);
+
+            check_page(data+deptr,headers[pageout],&og_de);
+            deptr+=og_de.body_len;
+            pageout++;
+
+            /* submit it to deconstitution */
+            ogg_stream_pagein(&os_de,&og_de);
+
+            /* packets out? */
+            while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
+              ogg_stream_packetpeek(&os_de,NULL);
+              ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
+
+              /* verify peek and out match */
+              if(compare_packet(&op_de,&op_de2)){
+                fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
+                        depacket);
+                exit(1);
+              }
+
+              /* verify the packet! */
+              /* check data */
+              if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
+                fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
+                        depacket);
+                exit(1);
+              }
+              /* check bos flag */
+              if(bosflag==0 && op_de.b_o_s==0){
+                fprintf(stderr,"b_o_s flag not set on packet!\n");
+                exit(1);
+              }
+              if(bosflag && op_de.b_o_s){
+                fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
+                exit(1);
+              }
+              bosflag=1;
+              depacket+=op_de.bytes;
+
+              /* check eos flag */
+              if(eosflag){
+                fprintf(stderr,"Multiple decoded packets with eos flag!\n");
+                exit(1);
+              }
+
+              if(op_de.e_o_s)eosflag=1;
+
+              /* check granulepos flag */
+              if(op_de.granulepos!=-1){
+                fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+  _ogg_free(data);
+  if(headers[pageno]!=NULL){
+    fprintf(stderr,"did not write last page!\n");
+    exit(1);
+  }
+  if(headers[pageout]!=NULL){
+    fprintf(stderr,"did not decode last page!\n");
+    exit(1);
+  }
+  if(inptr!=outptr){
+    fprintf(stderr,"encoded page data incomplete!\n");
+    exit(1);
+  }
+  if(inptr!=deptr){
+    fprintf(stderr,"decoded page data incomplete!\n");
+    exit(1);
+  }
+  if(inptr!=depacket){
+    fprintf(stderr,"decoded packet data incomplete!\n");
+    exit(1);
+  }
+  if(!eosflag){
+    fprintf(stderr,"Never got a packet with EOS set!\n");
+    exit(1);
+  }
+  fprintf(stderr,"ok.\n");
+}
+
+int main(void){
+
+  ogg_stream_init(&os_en,0x04030201);
+  ogg_stream_init(&os_de,0x04030201);
+  ogg_sync_init(&oy);
+
+  /* Exercise each code path in the framing code.  Also verify that
+     the checksums are working.  */
+
+  {
+    /* 17 only */
+    const int packets[]={17, -1};
+    const int *headret[]={head1_0,NULL};
+
+    fprintf(stderr,"testing single page encoding... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
+    const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
+    const int *headret[]={head1_1,head2_1,NULL};
+
+    fprintf(stderr,"testing basic page encoding... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* nil packets; beginning,middle,end */
+    const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
+    const int *headret[]={head1_2,head2_2,NULL};
+
+    fprintf(stderr,"testing basic nil packets... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* large initial packet */
+    const int packets[]={4345,259,255,-1};
+    const int *headret[]={head1_3,head2_3,NULL};
+
+    fprintf(stderr,"testing initial-packet lacing > 4k... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* continuing packet test; with page spill expansion, we have to
+       overflow the lacing table. */
+    const int packets[]={0,65500,259,255,-1};
+    const int *headret[]={head1_4,head2_4,head3_4,NULL};
+
+    fprintf(stderr,"testing single packet page span... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* spill expand packet test */
+    const int packets[]={0,4345,259,255,0,0,-1};
+    const int *headret[]={head1_4b,head2_4b,head3_4b,NULL};
+
+    fprintf(stderr,"testing page spill expansion... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  /* page with the 255 segment limit */
+  {
+
+    const int packets[]={0,10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,10,
+                   10,10,10,10,10,10,10,50,-1};
+    const int *headret[]={head1_5,head2_5,head3_5,NULL};
+
+    fprintf(stderr,"testing max packet segments... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* packet that overspans over an entire page */
+    const int packets[]={0,100,130049,259,255,-1};
+    const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
+
+    fprintf(stderr,"testing very large packets... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+  {
+    /* test for the libogg 1.1.1 resync in large continuation bug
+       found by Josh Coalson)  */
+    const int packets[]={0,100,130049,259,255,-1};
+    const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
+
+    fprintf(stderr,"testing continuation resync in very large packets... ");
+    test_pack(packets,headret,100,2,3);
+  }
+
+  {
+    /* term only page.  why not? */
+    const int packets[]={0,100,64770,-1};
+    const int *headret[]={head1_7,head2_7,head3_7,NULL};
+
+    fprintf(stderr,"testing zero data page (1 nil packet)... ");
+    test_pack(packets,headret,0,0,0);
+  }
+
+
+
+  {
+    /* build a bunch of pages for testing */
+    unsigned char *data=_ogg_malloc(1024*1024);
+    int pl[]={0, 1,1,98,4079, 1,1,2954,2057, 76,34,912,0,234,1000,1000, 1000,300,-1};
+    int inptr=0,i,j;
+    ogg_page og[5];
+
+    ogg_stream_reset(&os_en);
+
+    for(i=0;pl[i]!=-1;i++){
+      ogg_packet op;
+      int len=pl[i];
+
+      op.packet=data+inptr;
+      op.bytes=len;
+      op.e_o_s=(pl[i+1]<0?1:0);
+      op.granulepos=(i+1)*1000;
+
+      for(j=0;j<len;j++)data[inptr++]=i+j;
+      ogg_stream_packetin(&os_en,&op);
+    }
+
+    _ogg_free(data);
+
+    /* retrieve finished pages */
+    for(i=0;i<5;i++){
+      if(ogg_stream_pageout(&os_en,&og[i])==0){
+        fprintf(stderr,"Too few pages output building sync tests!\n");
+        exit(1);
+      }
+      copy_page(&og[i]);
+    }
+
+    /* Test lost pages on pagein/packetout: no rollback */
+    {
+      ogg_page temp;
+      ogg_packet test;
+
+      fprintf(stderr,"Testing loss of pages... ");
+
+      ogg_sync_reset(&oy);
+      ogg_stream_reset(&os_de);
+      for(i=0;i<5;i++){
+        memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
+               og[i].header_len);
+        ogg_sync_wrote(&oy,og[i].header_len);
+        memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
+        ogg_sync_wrote(&oy,og[i].body_len);
+      }
+
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+      ogg_sync_pageout(&oy,&temp);
+      /* skip */
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+
+      /* do we get the expected results/packets? */
+
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,0,0,0);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,1,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,2,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,98,3,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,4079,4,5000);
+      if(ogg_stream_packetout(&os_de,&test)!=-1){
+        fprintf(stderr,"Error: loss of page did not return error\n");
+        exit(1);
+      }
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,76,9,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,34,10,-1);
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* Test lost pages on pagein/packetout: rollback with continuation */
+    {
+      ogg_page temp;
+      ogg_packet test;
+
+      fprintf(stderr,"Testing loss of pages (rollback required)... ");
+
+      ogg_sync_reset(&oy);
+      ogg_stream_reset(&os_de);
+      for(i=0;i<5;i++){
+        memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
+               og[i].header_len);
+        ogg_sync_wrote(&oy,og[i].header_len);
+        memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
+        ogg_sync_wrote(&oy,og[i].body_len);
+      }
+
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+      ogg_sync_pageout(&oy,&temp);
+      /* skip */
+      ogg_sync_pageout(&oy,&temp);
+      ogg_stream_pagein(&os_de,&temp);
+
+      /* do we get the expected results/packets? */
+
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,0,0,0);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,1,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,2,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,98,3,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,4079,4,5000);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,5,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,1,6,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,2954,7,-1);
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,2057,8,9000);
+      if(ogg_stream_packetout(&os_de,&test)!=-1){
+        fprintf(stderr,"Error: loss of page did not return error\n");
+        exit(1);
+      }
+      if(ogg_stream_packetout(&os_de,&test)!=1)error();
+      checkpacket(&test,300,17,18000);
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* the rest only test sync */
+    {
+      ogg_page og_de;
+      /* Test fractional page inputs: incomplete capture */
+      fprintf(stderr,"Testing sync on partial inputs... ");
+      ogg_sync_reset(&oy);
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
+             3);
+      ogg_sync_wrote(&oy,3);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      /* Test fractional page inputs: incomplete fixed header */
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
+             20);
+      ogg_sync_wrote(&oy,20);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      /* Test fractional page inputs: incomplete header */
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
+             5);
+      ogg_sync_wrote(&oy,5);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      /* Test fractional page inputs: incomplete body */
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
+             og[1].header_len-28);
+      ogg_sync_wrote(&oy,og[1].header_len-28);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
+      ogg_sync_wrote(&oy,1000);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
+             og[1].body_len-1000);
+      ogg_sync_wrote(&oy,og[1].body_len-1000);
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* Test fractional page inputs: page + incomplete capture */
+    {
+      ogg_page og_de;
+      fprintf(stderr,"Testing sync on 1+partial inputs... ");
+      ogg_sync_reset(&oy);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
+             og[1].header_len);
+      ogg_sync_wrote(&oy,og[1].header_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
+             og[1].body_len);
+      ogg_sync_wrote(&oy,og[1].body_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
+             20);
+      ogg_sync_wrote(&oy,20);
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
+             og[1].header_len-20);
+      ogg_sync_wrote(&oy,og[1].header_len-20);
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
+             og[1].body_len);
+      ogg_sync_wrote(&oy,og[1].body_len);
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* Test recapture: garbage + page */
+    {
+      ogg_page og_de;
+      fprintf(stderr,"Testing search for capture... ");
+      ogg_sync_reset(&oy);
+
+      /* 'garbage' */
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
+             og[1].body_len);
+      ogg_sync_wrote(&oy,og[1].body_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
+             og[1].header_len);
+      ogg_sync_wrote(&oy,og[1].header_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
+             og[1].body_len);
+      ogg_sync_wrote(&oy,og[1].body_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
+             20);
+      ogg_sync_wrote(&oy,20);
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+
+      memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
+             og[2].header_len-20);
+      ogg_sync_wrote(&oy,og[2].header_len-20);
+      memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
+             og[2].body_len);
+      ogg_sync_wrote(&oy,og[2].body_len);
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* Test recapture: page + garbage + page */
+    {
+      ogg_page og_de;
+      fprintf(stderr,"Testing recapture... ");
+      ogg_sync_reset(&oy);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
+             og[1].header_len);
+      ogg_sync_wrote(&oy,og[1].header_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
+             og[1].body_len);
+      ogg_sync_wrote(&oy,og[1].body_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
+             og[2].header_len);
+      ogg_sync_wrote(&oy,og[2].header_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
+             og[2].header_len);
+      ogg_sync_wrote(&oy,og[2].header_len);
+
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+
+      memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
+             og[2].body_len-5);
+      ogg_sync_wrote(&oy,og[2].body_len-5);
+
+      memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
+             og[3].header_len);
+      ogg_sync_wrote(&oy,og[3].header_len);
+
+      memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
+             og[3].body_len);
+      ogg_sync_wrote(&oy,og[3].body_len);
+
+      if(ogg_sync_pageout(&oy,&og_de)>0)error();
+      if(ogg_sync_pageout(&oy,&og_de)<=0)error();
+
+      fprintf(stderr,"ok.\n");
+    }
+
+    /* Free page data that was previously copied */
+    {
+      for(i=0;i<5;i++){
+        free_page(&og[i]);
+      }
+    }
+  }
+
+  return(0);
+}
+
+#endif
diff --git a/ogg/win32/ogg.def b/ogg/win32/ogg.def
new file mode 100644 (file)
index 0000000..3c8424b
--- /dev/null
@@ -0,0 +1,79 @@
+; $Id$
+;
+; ogg.def
+;
+EXPORTS
+;
+oggpack_writeinit
+oggpack_writetrunc
+oggpack_writealign
+oggpack_writecopy
+oggpack_reset
+oggpack_writeclear
+oggpack_readinit
+oggpack_write
+oggpack_look
+oggpack_look1
+oggpack_adv
+oggpack_adv1
+oggpack_read
+oggpack_read1
+oggpack_bytes
+oggpack_bits
+oggpack_get_buffer
+;
+oggpackB_writeinit
+oggpackB_writetrunc
+oggpackB_writealign
+oggpackB_writecopy
+oggpackB_reset
+oggpackB_writeclear
+oggpackB_readinit
+oggpackB_write
+oggpackB_look
+oggpackB_look1
+oggpackB_adv
+oggpackB_adv1
+oggpackB_read
+oggpackB_read1
+oggpackB_bytes
+oggpackB_bits
+oggpackB_get_buffer
+;
+ogg_stream_packetin
+ogg_stream_pageout
+ogg_stream_flush
+;
+ogg_sync_init
+ogg_sync_clear
+ogg_sync_reset
+ogg_sync_destroy
+ogg_sync_buffer
+ogg_sync_wrote
+ogg_sync_pageseek
+ogg_sync_pageout
+ogg_stream_pagein
+ogg_stream_packetout
+ogg_stream_packetpeek
+;
+ogg_stream_init
+ogg_stream_clear
+ogg_stream_reset
+ogg_stream_reset_serialno
+ogg_stream_destroy
+ogg_stream_eos
+ogg_stream_pageout_fill
+ogg_stream_flush_fill
+;
+ogg_page_checksum_set
+ogg_page_version
+ogg_page_continued
+ogg_page_bos
+ogg_page_eos
+ogg_page_granulepos
+ogg_page_serialno
+ogg_page_pageno
+ogg_page_packets
+ogg_packet_clear
+                                                        
+
diff --git a/opus/AUTHORS b/opus/AUTHORS
new file mode 100644 (file)
index 0000000..b3d22a2
--- /dev/null
@@ -0,0 +1,6 @@
+Jean-Marc Valin (jmvalin@jmvalin.ca)
+Koen Vos (koenvos74@gmail.com)
+Timothy Terriberry (tterribe@xiph.org)
+Karsten Vandborg Sorensen (karsten.vandborg.sorensen@skype.net)
+Soren Skak Jensen (ssjensen@gn.com)
+Gregory Maxwell (greg@xiph.org)
diff --git a/opus/CMakeLists.txt b/opus/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4cd402c
--- /dev/null
@@ -0,0 +1,243 @@
+
+include_directories(
+    "."
+    celt
+    include/opus
+    silk
+    silk/float
+)
+
+add_definitions(
+    -DUSE_ALLOCA
+    -DOPUS_BUILD
+    -DFLOAT_APPROX
+    -DDLL_EXPORT
+    -DOPUS_X86_MAY_HAVE_SSE
+    -DOPUS_X86_MAY_HAVE_SSE2
+    -DOPUS_X86_MAY_HAVE_SSE4_1
+    -DOPUS_X86_PRESUME_SSE
+    -DOPUS_X86_PRESUME_SSE2
+    -DOPUS_X86_PRESUME_SSE4_1
+)
+
+add_library(
+    opus SHARED
+
+    include/opus/opus.h
+    include/opus/opus_custom.h
+    include/opus/opus_defines.h
+    include/opus/opus_multistream.h
+    include/opus/opus_types.h
+
+    src/analysis.c
+    src/analysis.h
+    src/mlp.c
+    src/mlp.h
+    src/mlp_data.c
+    src/opus.c
+    src/opus_decoder.c
+    src/opus_encoder.c
+    src/opus_multistream.c
+    src/opus_multistream_decoder.c
+    src/opus_multistream_encoder.c
+    src/opus_private.h
+    src/repacketizer.c
+    src/tansig_table.h
+
+    celt/arch.h
+    celt/bands.c
+    celt/bands.h
+    celt/celt.c
+    celt/celt.h
+    celt/celt_decoder.c
+    celt/celt_encoder.c
+    celt/celt_lpc.c
+    celt/celt_lpc.h
+    celt/cpu_support.h
+    celt/cwrs.c
+    celt/cwrs.h
+    celt/ecintrin.h
+    celt/entcode.c
+    celt/entcode.h
+    celt/entdec.c
+    celt/entdec.h
+    celt/entenc.c
+    celt/entenc.h
+    celt/fixed_debug.h
+    celt/fixed_generic.h
+    celt/float_cast.h
+    celt/kiss_fft.c
+    celt/kiss_fft.h
+    celt/laplace.c
+    celt/laplace.h
+    celt/mathops.c
+    celt/mathops.h
+    celt/mdct.c
+    celt/mdct.h
+    celt/mfrngcod.h
+    celt/modes.c
+    celt/modes.h
+    celt/os_support.h
+    celt/pitch.c
+    celt/pitch.h
+    celt/quant_bands.c
+    celt/quant_bands.h
+    celt/rate.c
+    celt/rate.h
+    celt/stack_alloc.h
+    celt/static_modes_fixed.h
+    celt/static_modes_fixed_arm_ne10.h
+    celt/static_modes_float.h
+    celt/static_modes_float_arm_ne10.h
+    celt/vq.c
+    celt/vq.h
+    celt/_kiss_fft_guts.h
+    celt/x86/celt_lpc_sse.c
+    celt/x86/celt_lpc_sse.h
+    celt/x86/pitch_sse.c
+    celt/x86/pitch_sse.h
+    celt/x86/pitch_sse2.c
+    celt/x86/pitch_sse4_1.c
+    celt/x86/vq_sse.h
+    celt/x86/vq_sse2.c
+    celt/x86/x86cpu.c
+    celt/x86/x86cpu.h
+    celt/x86/x86_celt_map.c
+
+    silk/A2NLSF.c
+    silk/ana_filt_bank_1.c
+    silk/API.h
+    silk/biquad_alt.c
+    silk/bwexpander.c
+    silk/bwexpander_32.c
+    silk/check_control_input.c
+    silk/CNG.c
+    silk/code_signs.c
+    silk/control.h
+    silk/control_audio_bandwidth.c
+    silk/control_codec.c
+    silk/control_SNR.c
+    silk/debug.c
+    silk/debug.h
+    silk/decoder_set_fs.c
+    silk/decode_core.c
+    silk/decode_frame.c
+    silk/decode_indices.c
+    silk/decode_parameters.c
+    silk/decode_pitch.c
+    silk/decode_pulses.c
+    silk/dec_API.c
+    silk/define.h
+    silk/encode_indices.c
+    silk/encode_pulses.c
+    silk/enc_API.c
+    silk/errors.h
+    silk/gain_quant.c
+    silk/HP_variable_cutoff.c
+    silk/init_decoder.c
+    silk/init_encoder.c
+    silk/Inlines.h
+    silk/inner_prod_aligned.c
+    silk/interpolate.c
+    silk/lin2log.c
+    silk/log2lin.c
+    silk/LPC_analysis_filter.c
+    silk/LPC_fit.c
+    silk/LPC_inv_pred_gain.c
+    silk/LP_variable_cutoff.c
+    silk/MacroCount.h
+    silk/MacroDebug.h
+    silk/macros.h
+    silk/main.h
+    silk/NLSF2A.c
+    silk/NLSF_decode.c
+    silk/NLSF_del_dec_quant.c
+    silk/NLSF_encode.c
+    silk/NLSF_stabilize.c
+    silk/NLSF_unpack.c
+    silk/NLSF_VQ.c
+    silk/NLSF_VQ_weights_laroia.c
+    silk/NSQ.c
+    silk/NSQ.h
+    silk/NSQ_del_dec.c
+    silk/pitch_est_defines.h
+    silk/pitch_est_tables.c
+    silk/PLC.c
+    silk/PLC.h
+    silk/process_NLSFs.c
+    silk/quant_LTP_gains.c
+    silk/resampler.c
+    silk/resampler_down2.c
+    silk/resampler_down2_3.c
+    silk/resampler_private.h
+    silk/resampler_private_AR2.c
+    silk/resampler_private_down_FIR.c
+    silk/resampler_private_IIR_FIR.c
+    silk/resampler_private_up2_HQ.c
+    silk/resampler_rom.c
+    silk/resampler_rom.h
+    silk/resampler_structs.h
+    silk/shell_coder.c
+    silk/sigm_Q15.c
+    silk/SigProc_FIX.h
+    silk/sort.c
+    silk/stereo_decode_pred.c
+    silk/stereo_encode_pred.c
+    silk/stereo_find_predictor.c
+    silk/stereo_LR_to_MS.c
+    silk/stereo_MS_to_LR.c
+    silk/stereo_quant_pred.c
+    silk/structs.h
+    silk/sum_sqr_shift.c
+    silk/tables.h
+    silk/tables_gain.c
+    silk/tables_LTP.c
+    silk/tables_NLSF_CB_NB_MB.c
+    silk/tables_NLSF_CB_WB.c
+    silk/tables_other.c
+    silk/tables_pitch_lag.c
+    silk/tables_pulses_per_block.c
+    silk/table_LSF_cos.c
+    silk/tuning_parameters.h
+    silk/typedef.h
+    silk/VAD.c
+    silk/VQ_WMat_EC.c
+    silk/float/apply_sine_window_FLP.c
+    silk/float/autocorrelation_FLP.c
+    silk/float/burg_modified_FLP.c
+    silk/float/bwexpander_FLP.c
+    silk/float/corrMatrix_FLP.c
+    silk/float/encode_frame_FLP.c
+    silk/float/energy_FLP.c
+    silk/float/find_LPC_FLP.c
+    silk/float/find_LTP_FLP.c
+    silk/float/find_pitch_lags_FLP.c
+    silk/float/find_pred_coefs_FLP.c
+    silk/float/inner_product_FLP.c
+    silk/float/k2a_FLP.c
+    silk/float/LPC_analysis_filter_FLP.c
+    silk/float/LPC_inv_pred_gain_FLP.c
+    silk/float/LTP_analysis_filter_FLP.c
+    silk/float/LTP_scale_ctrl_FLP.c
+    silk/float/main_FLP.h
+    silk/float/noise_shape_analysis_FLP.c
+    silk/float/pitch_analysis_core_FLP.c
+    silk/float/process_gains_FLP.c
+    silk/float/regularize_correlations_FLP.c
+    silk/float/residual_energy_FLP.c
+    silk/float/scale_copy_vector_FLP.c
+    silk/float/scale_vector_FLP.c
+    silk/float/schur_FLP.c
+    silk/float/SigProc_FLP.h
+    silk/float/sort_FLP.c
+    silk/float/structs_FLP.h
+    silk/float/warped_autocorrelation_FLP.c
+    silk/float/wrappers_FLP.c
+    silk/x86/main_sse.h
+    silk/x86/NSQ_del_dec_sse.c
+    silk/x86/NSQ_sse.c
+    silk/x86/SigProc_FIX_sse.h
+    silk/x86/VAD_sse.c
+    silk/x86/VQ_WMat_EC_sse.c
+    silk/x86/x86_silk_map.c
+)
diff --git a/opus/COPYING b/opus/COPYING
new file mode 100644 (file)
index 0000000..9c739c3
--- /dev/null
@@ -0,0 +1,44 @@
+Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,
+                    Jean-Marc Valin, Timothy B. Terriberry,
+                    CSIRO, Gregory Maxwell, Mark Borgerding,
+                    Erik de Castro Lopo
+
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+
+Opus is subject to the royalty-free patent licenses which are
+specified at:
+
+Xiph.Org Foundation:
+https://datatracker.ietf.org/ipr/1524/
+
+Microsoft Corporation:
+https://datatracker.ietf.org/ipr/1914/
+
+Broadcom Corporation:
+https://datatracker.ietf.org/ipr/1526/
diff --git a/opus/README b/opus/README
new file mode 100644 (file)
index 0000000..f09766d
--- /dev/null
@@ -0,0 +1,161 @@
+== Opus audio codec ==
+
+Opus is a codec for interactive speech and audio transmission over the Internet.
+
+  Opus can handle a wide range of interactive audio applications, including
+Voice over IP, videoconferencing, in-game  chat, and even remote live music
+performances. It can scale from low bit-rate narrowband speech to very high
+quality stereo music.
+
+  Opus, when coupled with an appropriate container format, is also suitable
+for non-realtime  stored-file applications such as music distribution, game
+soundtracks, portable music players, jukeboxes, and other applications that
+have historically used high latency formats such as MP3, AAC, or Vorbis.
+
+                    Opus is specified by IETF RFC 6716:
+                    https://tools.ietf.org/html/rfc6716
+
+  The Opus format and this implementation of it are subject to the royalty-
+free patent and copyright licenses specified in the file COPYING.
+
+This package implements a shared library for encoding and decoding raw Opus
+bitstreams. Raw Opus bitstreams should be used over RTP according to
+ https://tools.ietf.org/html/rfc7587
+
+The package also includes a number of test  tools used for testing the
+correct operation of the library. The bitstreams read/written by these
+tools should not be used for Opus file distribution: They include
+additional debugging data and cannot support seeking.
+
+Opus stored in files should use the Ogg encapsulation for Opus which is
+described at:
+ https://wiki.xiph.org/OggOpus
+
+An opus-tools package is available which provides encoding and decoding of
+Ogg encapsulated Opus files and includes a number of useful features.
+
+Opus-tools can be found at:
+ https://git.xiph.org/?p=opus-tools.git
+or on the main Opus website:
+ https://opus-codec.org/
+
+== Compiling libopus ==
+
+To build from a distribution tarball, you only need to do the following:
+
+    % ./configure
+    % make
+
+To build from the git repository, the following steps are necessary:
+
+0) Set up a development environment:
+
+On an Ubuntu or Debian family Linux distribution:
+
+    % sudo apt-get install git autoconf automake libtool gcc make
+
+On a Fedora/Redhat based Linux:
+
+    % sudo dnf install git autoconf automake libtool gcc make
+
+Or for older Redhat/Centos Linux releases:
+
+    % sudo yum install git autoconf automake libtool gcc make
+
+On Apple macOS, install Xcode and brew.sh, then in the Terminal enter:
+
+    % brew install autoconf automake libtool
+
+1) Clone the repository:
+
+    % git clone https://git.xiph.org/opus.git
+    % cd opus
+
+2) Compiling the source
+
+    % ./autogen.sh
+    % ./configure
+    % make
+
+3) Install the codec libraries (optional)
+
+    % sudo make install
+
+Once you have compiled the codec, there will be a opus_demo executable
+in the top directory.
+
+Usage: opus_demo [-e] <application> <sampling rate (Hz)> <channels (1/2)>
+         <bits per second> [options] <input> <output>
+       opus_demo -d <sampling rate (Hz)> <channels (1/2)> [options]
+         <input> <output>
+
+mode: voip | audio | restricted-lowdelay
+options:
+  -e                : only runs the encoder (output the bit-stream)
+  -d                : only runs the decoder (reads the bit-stream as input)
+  -cbr              : enable constant bitrate; default: variable bitrate
+  -cvbr             : enable constrained variable bitrate; default:
+                      unconstrained
+  -bandwidth <NB|MB|WB|SWB|FB>
+                    : audio bandwidth (from narrowband to fullband);
+                      default: sampling rate
+  -framesize <2.5|5|10|20|40|60>
+                    : frame size in ms; default: 20
+  -max_payload <bytes>
+                    : maximum payload size in bytes, default: 1024
+  -complexity <comp>
+                    : complexity, 0 (lowest) ... 10 (highest); default: 10
+  -inbandfec        : enable SILK inband FEC
+  -forcemono        : force mono encoding, even for stereo input
+  -dtx              : enable SILK DTX
+  -loss <perc>      : simulate packet loss, in percent (0-100); default: 0
+
+input and output are little-endian signed 16-bit PCM files or opus
+bitstreams with simple opus_demo proprietary framing.
+
+== Testing ==
+
+This package includes a collection of automated unit and system tests
+which SHOULD be run after compiling the package especially the first
+time it is run on a new platform.
+
+To run the integrated tests:
+
+    % make check
+
+There is also collection of standard test vectors which are not
+included in this package for size reasons but can be obtained from:
+https://opus-codec.org/testvectors/opus_testvectors.tar.gz
+
+To run compare the code to these test vectors:
+
+    % curl -O https://opus-codec.org/testvectors/opus_testvectors.tar.gz
+    % tar -zxf opus_testvectors.tar.gz
+    % ./tests/run_vectors.sh ./ opus_testvectors 48000
+
+== Portability notes ==
+
+This implementation uses floating-point by default but can be compiled to
+use only fixed-point arithmetic by setting --enable-fixed-point (if using
+autoconf) or by defining the FIXED_POINT macro (if building manually).
+The fixed point implementation has somewhat lower audio quality and is
+slower on platforms with fast FPUs, it is normally only used in embedded
+environments.
+
+The implementation can be compiled with either a C89 or a C99 compiler.
+While it does not rely on any _undefined behavior_ as defined by C89 or
+C99, it relies on common _implementation-defined behavior_ for two's
+complement architectures:
+
+o Right shifts of negative values are consistent with two's
+  complement arithmetic, so that a>>b is equivalent to
+  floor(a/(2^b)),
+
+o For conversion to a signed integer of N bits, the value is reduced
+  modulo 2^N to be within range of the type,
+
+o The result of integer division of a negative value is truncated
+  towards zero, and
+
+o The compiler provides a 64-bit integer type (a C99 requirement
+  which is supported by most C89 compilers).
diff --git a/opus/celt/_kiss_fft_guts.h b/opus/celt/_kiss_fft_guts.h
new file mode 100644 (file)
index 0000000..17392b3
--- /dev/null
@@ -0,0 +1,182 @@
+/*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.
+
+  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"
+
+/*
+  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"
+
+
+#define SAMP_MAX 2147483647
+#define TWID_MAX 32767
+#define TRIG_UPSCALE 1
+
+#define SAMP_MIN -SAMP_MAX
+
+
+#   define S_MUL(a,b) MULT16_32_Q15(b, a)
+
+#   define C_MUL(m,a,b) \
+      do{ (m).r = SUB32_ovflw(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
+          (m).i = ADD32_ovflw(S_MUL((a).r,(b).i) , S_MUL((a).i,(b).r)); }while(0)
+
+#   define C_MULC(m,a,b) \
+      do{ (m).r = ADD32_ovflw(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
+          (m).i = SUB32_ovflw(S_MUL((a).i,(b).r) , S_MUL((a).r,(b).i)); }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_ovflw((a).r,(b).r);  (res).i=ADD32_ovflw((a).i,(b).i); \
+    }while(0)
+#define  C_SUB( res, a,b)\
+    do {(res).r=SUB32_ovflw((a).r,(b).r);  (res).i=SUB32_ovflw((a).i,(b).i); \
+    }while(0)
+#define C_ADDTO( res , a)\
+    do {(res).r = ADD32_ovflw((res).r, (a).r);  (res).i = ADD32_ovflw((res).i,(a).i);\
+    }while(0)
+
+#define C_SUBFROM( res , a)\
+    do {(res).r = ADD32_ovflw((res).r,(a).r);  (res).i = SUB32_ovflw((res).i,(a).i); \
+    }while(0)
+
+#if defined(OPUS_ARM_INLINE_ASM)
+#include "arm/kiss_fft_armv4.h"
+#endif
+
+#if defined(OPUS_ARM_INLINE_EDSP)
+#include "arm/kiss_fft_armv5e.h"
+#endif
+#if defined(MIPSr1_ASM)
+#include "mips/kiss_fft_mipsr1.h"
+#endif
+
+#else  /* not FIXED_POINT*/
+
+#   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(.5f))
+#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)*.5f)
+#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 */
diff --git a/opus/celt/arch.h b/opus/celt/arch.h
new file mode 100644 (file)
index 0000000..d1e6457
--- /dev/null
@@ -0,0 +1,269 @@
+/* Copyright (c) 2003-2008 Jean-Marc Valin
+   Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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 ARCH_H
+#define ARCH_H
+
+#include "opus_types.h"
+#include "opus_defines.h"
+
+# if !defined(__GNUC_PREREQ)
+#  if defined(__GNUC__)&&defined(__GNUC_MINOR__)
+#   define __GNUC_PREREQ(_maj,_min) \
+ ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
+#  else
+#   define __GNUC_PREREQ(_maj,_min) 0
+#  endif
+# endif
+
+#if OPUS_GNUC_PREREQ(3, 0)
+#define opus_likely(x)       (__builtin_expect(!!(x), 1))
+#define opus_unlikely(x)     (__builtin_expect(!!(x), 0))
+#else
+#define opus_likely(x)       (!!(x))
+#define opus_unlikely(x)     (!!(x))
+#endif
+
+#define CELT_SIG_SCALE 32768.f
+
+#define celt_fatal(str) _celt_fatal(str, __FILE__, __LINE__);
+#ifdef ENABLE_ASSERTIONS
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef __GNUC__
+__attribute__((noreturn))
+#endif
+static OPUS_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();
+}
+#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 MIN16(a,b) ((a) < (b) ? (a) : (b))   /**< Minimum 16-bit value.   */
+#define MAX16(a,b) ((a) > (b) ? (a) : (b))   /**< Maximum 16-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))
+
+/* Set this if opus_int64 is a native type of the CPU. */
+/* Assume that all LP64 architectures have fast 64-bit types; also x86_64
+   (which can be ILP32 for x32) and Win64 (which is LLP64). */
+#if defined(__x86_64__) || defined(__LP64__) || defined(_WIN64)
+#define OPUS_FAST_INT64 1
+#else
+#define OPUS_FAST_INT64 0
+#endif
+
+#define PRINT_MIPS(file)
+
+#ifdef FIXED_POINT
+
+typedef opus_int16 opus_val16;
+typedef opus_int32 opus_val32;
+typedef opus_int64 opus_val64;
+
+typedef opus_val32 celt_sig;
+typedef opus_val16 celt_norm;
+typedef opus_val32 celt_ener;
+
+#define Q15ONE 32767
+
+#define SIG_SHIFT 12
+/* Safe saturation value for 32-bit signals. Should be less than
+   2^31*(1-0.85) to avoid blowing up on DC at deemphasis.*/
+#define SIG_SAT (300000000)
+
+#define NORM_SCALING 16384
+
+#define DB_SHIFT 10
+
+#define EPSILON 1
+#define VERY_SMALL 0
+#define VERY_LARGE16 ((opus_val16)32767)
+#define Q15_ONE ((opus_val16)32767)
+
+#define SCALEIN(a)      (a)
+#define SCALEOUT(a)     (a)
+
+#define ABS16(x) ((x) < 0 ? (-(x)) : (x))
+#define ABS32(x) ((x) < 0 ? (-(x)) : (x))
+
+static OPUS_INLINE opus_int16 SAT16(opus_int32 x) {
+   return x > 32767 ? 32767 : x < -32768 ? -32768 : (opus_int16)x;
+}
+
+#ifdef FIXED_DEBUG
+#include "fixed_debug.h"
+#else
+
+#include "fixed_generic.h"
+
+#ifdef OPUS_ARM_PRESUME_AARCH64_NEON_INTR
+#include "arm/fixed_arm64.h"
+#elif OPUS_ARM_INLINE_EDSP
+#include "arm/fixed_armv5e.h"
+#elif defined (OPUS_ARM_INLINE_ASM)
+#include "arm/fixed_armv4.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 opus_val16;
+typedef float opus_val32;
+typedef float opus_val64;
+
+typedef float celt_sig;
+typedef float celt_norm;
+typedef float celt_ener;
+
+#ifdef FLOAT_APPROX
+/* This code should reliably detect NaN/inf even when -ffast-math is used.
+   Assumes IEEE 754 format. */
+static OPUS_INLINE int celt_isnan(float x)
+{
+   union {float f; opus_uint32 i;} in;
+   in.f = x;
+   return ((in.i>>23)&0xFF)==0xFF && (in.i&0x007FFFFF)!=0;
+}
+#else
+#ifdef __FAST_MATH__
+#error Cannot build libopus with -ffast-math unless FLOAT_APPROX is defined. This could result in crashes on extreme (e.g. NaN) input
+#endif
+#define celt_isnan(x) ((x)!=(x))
+#endif
+
+#define Q15ONE 1.0f
+
+#define NORM_SCALING 1.f
+
+#define EPSILON 1e-15f
+#define VERY_SMALL 1e-30f
+#define VERY_LARGE16 1e15f
+#define Q15_ONE ((opus_val16)1.f)
+
+/* This appears to be the same speed as C99's fabsf() but it's more portable. */
+#define ABS16(x) ((float)fabs(x))
+#define ABS32(x) ((float)fabs(x))
+
+#define QCONST16(x,bits) (x)
+#define QCONST32(x,bits) (x)
+
+#define NEG16(x) (-(x))
+#define NEG32(x) (-(x))
+#define NEG32_ovflw(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 PSHR32(a,shift) (a)
+#define VSHR32(a,shift) (a)
+
+#define PSHR(a,shift)   (a)
+#define SHR(a,shift)    (a)
+#define SHL(a,shift)    (a)
+#define SATURATE(x,a)   (x)
+#define SATURATE16(x)   (x)
+
+#define ROUND16(a,shift)  (a)
+#define SROUND16(a,shift) (a)
+#define HALF16(x)       (.5f*(x))
+#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 ADD32_ovflw(a,b) ((a)+(b))
+#define SUB32_ovflw(a,b) ((a)-(b))
+#define MULT16_16_16(a,b)     ((a)*(b))
+#define MULT16_16(a,b)     ((opus_val32)(a)*(opus_val32)(b))
+#define MAC16_16(c,a,b)     ((c)+(opus_val32)(a)*(opus_val32)(b))
+
+#define MULT16_32_Q15(a,b)     ((a)*(b))
+#define MULT16_32_Q16(a,b)     ((a)*(b))
+
+#define MULT32_32_Q31(a,b)     ((a)*(b))
+
+#define MAC16_32_Q15(c,a,b)     ((c)+(a)*(b))
+#define MAC16_32_Q16(c,a,b)     ((c)+(a)*(b))
+
+#define MULT16_16_Q11_32(a,b)     ((a)*(b))
+#define MULT16_16_Q11(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 MULT16_32_P16(a,b)     ((a)*(b))
+
+#define DIV32_16(a,b)     (((opus_val32)(a))/(opus_val16)(b))
+#define DIV32(a,b)     (((opus_val32)(a))/(opus_val32)(b))
+
+#define SCALEIN(a)      ((a)*CELT_SIG_SCALE)
+#define SCALEOUT(a)     ((a)*(1/CELT_SIG_SCALE))
+
+#define SIG2WORD16(x) (x)
+
+#endif /* !FIXED_POINT */
+
+#ifndef GLOBAL_STACK_SIZE
+#ifdef FIXED_POINT
+#define GLOBAL_STACK_SIZE 120000
+#else
+#define GLOBAL_STACK_SIZE 120000
+#endif
+#endif
+
+#endif /* ARCH_H */
diff --git a/opus/celt/arm/arm2gnu.pl b/opus/celt/arm/arm2gnu.pl
new file mode 100644 (file)
index 0000000..a2895f7
--- /dev/null
@@ -0,0 +1,353 @@
+#!/usr/bin/perl
+# Copyright (C) 2002-2013 Xiph.org Foundation
+#
+# 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.
+#
+# 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.
+
+my $bigend;  # little/big endian
+my $nxstack;
+my $apple = 0;
+my $symprefix = "";
+
+$nxstack = 0;
+
+eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
+    if $running_under_some_shell;
+
+while ($ARGV[0] =~ /^-/) {
+    $_ = shift;
+  last if /^--$/;
+    if (/^-n$/) {
+    $nflag++;
+    next;
+    }
+    if (/^--apple$/) {
+        $apple = 1;
+        $symprefix = "_";
+        next;
+    }
+    die "I don't recognize this switch: $_\\n";
+}
+$printit++ unless $nflag;
+
+$\ = "\n";      # automatically add newline on print
+$n=0;
+
+$thumb = 0;     # ARM mode by default, not Thumb.
+@proc_stack = ();
+
+printf ("    .syntax unified\n");
+
+LINE:
+while (<>) {
+
+    # For ADRLs we need to add a new line after the substituted one.
+    $addPadding = 0;
+
+    # First, we do not dare to touch *anything* inside double quotes, do we?
+    # Second, if you want a dollar character in the string,
+    # insert two of them -- that's how ARM C and assembler treat strings.
+    s/^([A-Za-z_]\w*)[ \t]+DCB[ \t]*\"/$1:   .ascii \"/   && do { s/\$\$/\$/g; next };
+    s/\bDCB\b[ \t]*\"/.ascii \"/                          && do { s/\$\$/\$/g; next };
+    s/^(\S+)\s+RN\s+(\S+)/$1 .req r$2/                    && do { s/\$\$/\$/g; next };
+    # If there's nothing on a line but a comment, don't try to apply any further
+    #  substitutions (this is a cheap hack to avoid mucking up the license header)
+    s/^([ \t]*);/$1@/                                     && do { s/\$\$/\$/g; next };
+    # If substituted -- leave immediately !
+
+    s/@/,:/;
+    s/;/@/;
+    while ( /@.*'/ ) {
+      s/(@.*)'/$1/g;
+    }
+    s/\{FALSE\}/0/g;
+    s/\{TRUE\}/1/g;
+    s/\{(\w\w\w\w+)\}/$1/g;
+    s/\bINCLUDE[ \t]*([^ \t\n]+)/.include \"$1\"/;
+    s/\bGET[ \t]*([^ \t\n]+)/.include \"${ my $x=$1; $x =~ s|\.s|-gnu.S|; \$x }\"/;
+    s/\bIMPORT\b/.extern/;
+    s/\bEXPORT\b\s*/.global $symprefix/;
+    s/^(\s+)\[/$1IF/;
+    s/^(\s+)\|/$1ELSE/;
+    s/^(\s+)\]/$1ENDIF/;
+    s/IF *:DEF:/ .ifdef/;
+    s/IF *:LNOT: *:DEF:/ .ifndef/;
+    s/ELSE/ .else/;
+    s/ENDIF/ .endif/;
+
+    if( /\bIF\b/ ) {
+      s/\bIF\b/ .if/;
+      s/=/==/;
+    }
+    if ( $n == 2) {
+        s/\$/\\/g;
+    }
+    if ($n == 1) {
+        s/\$//g;
+        s/label//g;
+    $n = 2;
+      }
+    if ( /MACRO/ ) {
+      s/MACRO *\n/.macro/;
+      $n=1;
+    }
+    if ( /\bMEND\b/ ) {
+      s/\bMEND\b/.endm/;
+      $n=0;
+    }
+
+    # ".rdata" doesn't work in 'as' version 2.13.2, as it is ".rodata" there.
+    #
+    if ( /\bAREA\b/ ) {
+        my $align;
+        $align = "2";
+        if ( /ALIGN=(\d+)/ ) {
+            $align = $1;
+        }
+        if ( /CODE/ ) {
+            $nxstack = 1;
+        }
+        s/^(.+)CODE(.+)READONLY(.*)/    .text/;
+        s/^(.+)DATA(.+)READONLY(.*)/    .section .rdata/;
+        s/^(.+)\|\|\.data\|\|(.+)/    .data/;
+        s/^(.+)\|\|\.bss\|\|(.+)/    .bss/;
+        s/$/;   .p2align $align/;
+        # Enable NEON instructions but don't produce a binary that requires
+        # ARMv7. RVCT does not have equivalent directives, so we just do this
+        # for all CODE areas.
+        if ( /.text/ ) {
+            # Separating .arch, .fpu, etc., by semicolons does not work (gas
+            # thinks the semicolon is part of the arch name, even when there's
+            # whitespace separating them). Sadly this means our line numbers
+            # won't match the original source file (we could use the .line
+            # directive, which is documented to be obsolete, but then gdb will
+            # show the wrong line in the translated source file).
+            s/$/;   .arch armv7-a\n   .fpu neon\n   .object_arch armv4t/ unless ($apple);
+        }
+    }
+
+    s/\|\|\.constdata\$(\d+)\|\|/.L_CONST$1/;       # ||.constdata$3||
+    s/\|\|\.bss\$(\d+)\|\|/.L_BSS$1/;               # ||.bss$2||
+    s/\|\|\.data\$(\d+)\|\|/.L_DATA$1/;             # ||.data$2||
+    s/\|\|([a-zA-Z0-9_]+)\@([a-zA-Z0-9_]+)\|\|/@ $&/;
+    s/^(\s+)\%(\s)/    .space $1/;
+
+    s/\|(.+)\.(\d+)\|/\.$1_$2/;                     # |L80.123| -> .L80_123
+    s/\bCODE32\b/.code 32/ && do {$thumb = 0};
+    s/\bCODE16\b/.code 16/ && do {$thumb = 1};
+    if (/\bPROC\b/)
+    {
+        my $prefix;
+        my $proc;
+        /^([A-Za-z_\.]\w+)\b/;
+        $proc = $1;
+        $prefix = "";
+        if ($proc)
+        {
+            $prefix = $prefix.sprintf("\t.type\t%s, %%function", $proc) unless ($apple);
+            # Make sure we $prefix isn't empty here (for the $apple case).
+            # We handle mangling the label here, make sure it doesn't match
+            # the label handling below (if $prefix would be empty).
+            $prefix = $prefix."; ";
+            push(@proc_stack, $proc);
+            s/^[A-Za-z_\.]\w+/$symprefix$&:/;
+        }
+        $prefix = $prefix."\t.thumb_func; " if ($thumb);
+        s/\bPROC\b/@ $&/;
+        $_ = $prefix.$_;
+    }
+    s/^(\s*)(S|Q|SH|U|UQ|UH)ASX\b/$1$2ADDSUBX/;
+    s/^(\s*)(S|Q|SH|U|UQ|UH)SAX\b/$1$2SUBADDX/;
+    if (/\bENDP\b/)
+    {
+        my $proc;
+        s/\bENDP\b/@ $&/;
+        $proc = pop(@proc_stack);
+        $_ = "\t.size $proc, .-$proc".$_ if ($proc && !$apple);
+    }
+    s/\bSUBT\b/@ $&/;
+    s/\bDATA\b/@ $&/;   # DATA directive is deprecated -- Asm guide, p.7-25
+    s/\bKEEP\b/@ $&/;
+    s/\bEXPORTAS\b/@ $&/;
+    s/\|\|(.)+\bEQU\b/@ $&/;
+    s/\|\|([\w\$]+)\|\|/$1/;
+    s/\bENTRY\b/@ $&/;
+    s/\bASSERT\b/@ $&/;
+    s/\bGBLL\b/@ $&/;
+    s/\bGBLA\b/@ $&/;
+    s/^\W+OPT\b/@ $&/;
+    s/:OR:/|/g;
+    s/:SHL:/<</g;
+    s/:SHR:/>>/g;
+    s/:AND:/&/g;
+    s/:LAND:/&&/g;
+    s/CPSR/cpsr/;
+    s/SPSR/spsr/;
+    s/ALIGN$/.balign 4/;
+    s/ALIGN\s+([0-9x]+)$/.balign $1/;
+    s/psr_cxsf/psr_all/;
+    s/LTORG/.ltorg/;
+    s/^([A-Za-z_]\w*)[ \t]+EQU/ .set $1,/;
+    s/^([A-Za-z_]\w*)[ \t]+SETL/ .set $1,/;
+    s/^([A-Za-z_]\w*)[ \t]+SETA/ .set $1,/;
+    s/^([A-Za-z_]\w*)[ \t]+\*/ .set $1,/;
+
+    #  {PC} + 0xdeadfeed  -->  . + 0xdeadfeed
+    s/\{PC\} \+/ \. +/;
+
+    # Single hex constant on the line !
+    #
+    # >>> NOTE <<<
+    #   Double-precision floats in gcc are always mixed-endian, which means
+    #   bytes in two words are little-endian, but words are big-endian.
+    #   So, 0x0000deadfeed0000 would be stored as 0x0000dead at low address
+    #   and 0xfeed0000 at high address.
+    #
+    s/\bDCFD\b[ \t]+0x([a-fA-F0-9]{8})([a-fA-F0-9]{8})/.long 0x$1, 0x$2/;
+    # Only decimal constants on the line, no hex !
+    s/\bDCFD\b[ \t]+([0-9\.\-]+)/.double $1/;
+
+    # Single hex constant on the line !
+#    s/\bDCFS\b[ \t]+0x([a-f0-9]{8})([a-f0-9]{8})/.long 0x$1, 0x$2/;
+    # Only decimal constants on the line, no hex !
+#    s/\bDCFS\b[ \t]+([0-9\.\-]+)/.double $1/;
+    s/\bDCFS[ \t]+0x/.word 0x/;
+    s/\bDCFS\b/.float/;
+
+    s/^([A-Za-z_]\w*)[ \t]+DCD/$1 .word/;
+    s/\bDCD\b/.word/;
+    s/^([A-Za-z_]\w*)[ \t]+DCW/$1 .short/;
+    s/\bDCW\b/.short/;
+    s/^([A-Za-z_]\w*)[ \t]+DCB/$1 .byte/;
+    s/\bDCB\b/.byte/;
+    s/^([A-Za-z_]\w*)[ \t]+\%/.comm $1,/;
+    s/^[A-Za-z_\.]\w+/$&:/;
+    s/^(\d+)/$1:/;
+    s/\%(\d+)/$1b_or_f/;
+    s/\%[Bb](\d+)/$1b/;
+    s/\%[Ff](\d+)/$1f/;
+    s/\%[Ff][Tt](\d+)/$1f/;
+    s/&([\dA-Fa-f]+)/0x$1/;
+    if ( /\b2_[01]+\b/ ) {
+      s/\b2_([01]+)\b/conv$1&&&&/g;
+      while ( /[01][01][01][01]&&&&/ ) {
+        s/0000&&&&/&&&&0/g;
+        s/0001&&&&/&&&&1/g;
+        s/0010&&&&/&&&&2/g;
+        s/0011&&&&/&&&&3/g;
+        s/0100&&&&/&&&&4/g;
+        s/0101&&&&/&&&&5/g;
+        s/0110&&&&/&&&&6/g;
+        s/0111&&&&/&&&&7/g;
+        s/1000&&&&/&&&&8/g;
+        s/1001&&&&/&&&&9/g;
+        s/1010&&&&/&&&&A/g;
+        s/1011&&&&/&&&&B/g;
+        s/1100&&&&/&&&&C/g;
+        s/1101&&&&/&&&&D/g;
+        s/1110&&&&/&&&&E/g;
+        s/1111&&&&/&&&&F/g;
+      }
+      s/000&&&&/&&&&0/g;
+      s/001&&&&/&&&&1/g;
+      s/010&&&&/&&&&2/g;
+      s/011&&&&/&&&&3/g;
+      s/100&&&&/&&&&4/g;
+      s/101&&&&/&&&&5/g;
+      s/110&&&&/&&&&6/g;
+      s/111&&&&/&&&&7/g;
+      s/00&&&&/&&&&0/g;
+      s/01&&&&/&&&&1/g;
+      s/10&&&&/&&&&2/g;
+      s/11&&&&/&&&&3/g;
+      s/0&&&&/&&&&0/g;
+      s/1&&&&/&&&&1/g;
+      s/conv&&&&/0x/g;
+    }
+
+    if ( /commandline/)
+    {
+        if( /-bigend/)
+        {
+            $bigend=1;
+        }
+    }
+
+    if ( /\bDCDU\b/ )
+    {
+        my $cmd=$_;
+        my $value;
+        my $prefix;
+        my $w1;
+        my $w2;
+        my $w3;
+        my $w4;
+
+        s/\s+DCDU\b/@ $&/;
+
+        $cmd =~ /\bDCDU\b\s+0x(\d+)/;
+        $value = $1;
+        $value =~ /(\w\w)(\w\w)(\w\w)(\w\w)/;
+        $w1 = $1;
+        $w2 = $2;
+        $w3 = $3;
+        $w4 = $4;
+
+        if( $bigend ne "")
+        {
+            # big endian
+            $prefix = "\t.byte\t0x".$w1.";".
+                      "\t.byte\t0x".$w2.";".
+                      "\t.byte\t0x".$w3.";".
+                      "\t.byte\t0x".$w4."; ";
+        }
+        else
+        {
+            # little endian
+            $prefix = "\t.byte\t0x".$w4.";".
+                      "\t.byte\t0x".$w3.";".
+                      "\t.byte\t0x".$w2.";".
+                      "\t.byte\t0x".$w1."; ";
+        }
+        $_=$prefix.$_;
+    }
+
+    if ( /\badrl\b/i )
+    {
+        s/\badrl\s+(\w+)\s*,\s*(\w+)/ldr $1,=$2/i;
+        $addPadding = 1;
+    }
+    s/\bEND\b/@ END/;
+} continue {
+    printf ("%s", $_) if $printit;
+    if ($addPadding != 0)
+    {
+        printf ("   mov r0,r0\n");
+        $addPadding = 0;
+    }
+}
+#If we had a code section, mark that this object doesn't need an executable
+# stack.
+if ($nxstack && !$apple) {
+    printf ("    .section\t.note.GNU-stack,\"\",\%\%progbits\n");
+}
diff --git a/opus/celt/arm/arm_celt_map.c b/opus/celt/arm/arm_celt_map.c
new file mode 100644 (file)
index 0000000..ca988b6
--- /dev/null
@@ -0,0 +1,160 @@
+/* Copyright (c) 2010 Xiph.Org Foundation
+ * Copyright (c) 2013 Parrot */
+/*
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "pitch.h"
+#include "kiss_fft.h"
+#include "mdct.h"
+
+#if defined(OPUS_HAVE_RTCD)
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR)
+opus_val32 (*const CELT_INNER_PROD_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *x, const opus_val16 *y, int N) = {
+  celt_inner_prod_c,   /* ARMv4 */
+  celt_inner_prod_c,   /* EDSP */
+  celt_inner_prod_c,   /* Media */
+  celt_inner_prod_neon /* NEON */
+};
+
+void (*const DUAL_INNER_PROD_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+      int N, opus_val32 *xy1, opus_val32 *xy2) = {
+  dual_inner_prod_c,   /* ARMv4 */
+  dual_inner_prod_c,   /* EDSP */
+  dual_inner_prod_c,   /* Media */
+  dual_inner_prod_neon /* NEON */
+};
+# endif
+
+# if defined(FIXED_POINT)
+#  if ((defined(OPUS_ARM_MAY_HAVE_NEON) && !defined(OPUS_ARM_PRESUME_NEON)) || \
+    (defined(OPUS_ARM_MAY_HAVE_MEDIA) && !defined(OPUS_ARM_PRESUME_MEDIA)) || \
+    (defined(OPUS_ARM_MAY_HAVE_EDSP) && !defined(OPUS_ARM_PRESUME_EDSP)))
+opus_val32 (*const CELT_PITCH_XCORR_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *,
+    const opus_val16 *, opus_val32 *, int, int, int) = {
+  celt_pitch_xcorr_c,               /* ARMv4 */
+  MAY_HAVE_EDSP(celt_pitch_xcorr),  /* EDSP */
+  MAY_HAVE_MEDIA(celt_pitch_xcorr), /* Media */
+  MAY_HAVE_NEON(celt_pitch_xcorr)   /* NEON */
+};
+
+#  endif
+# else /* !FIXED_POINT */
+#  if defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR)
+void (*const CELT_PITCH_XCORR_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *,
+    const opus_val16 *, opus_val32 *, int, int, int) = {
+  celt_pitch_xcorr_c,              /* ARMv4 */
+  celt_pitch_xcorr_c,              /* EDSP */
+  celt_pitch_xcorr_c,              /* Media */
+  celt_pitch_xcorr_float_neon      /* Neon */
+};
+#  endif
+# endif /* FIXED_POINT */
+
+#if defined(FIXED_POINT) && defined(OPUS_HAVE_RTCD) && \
+ defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR)
+
+void (*const XCORR_KERNEL_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *y,
+         opus_val32       sum[4],
+         int              len
+) = {
+  xcorr_kernel_c,                /* ARMv4 */
+  xcorr_kernel_c,                /* EDSP */
+  xcorr_kernel_c,                /* Media */
+  xcorr_kernel_neon_fixed,       /* Neon */
+};
+
+#endif
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+#  if defined(HAVE_ARM_NE10)
+#   if defined(CUSTOM_MODES)
+int (*const OPUS_FFT_ALLOC_ARCH_IMPL[OPUS_ARCHMASK+1])(kiss_fft_state *st) = {
+   opus_fft_alloc_arch_c,        /* ARMv4 */
+   opus_fft_alloc_arch_c,        /* EDSP */
+   opus_fft_alloc_arch_c,        /* Media */
+   opus_fft_alloc_arm_neon       /* Neon with NE10 library support */
+};
+
+void (*const OPUS_FFT_FREE_ARCH_IMPL[OPUS_ARCHMASK+1])(kiss_fft_state *st) = {
+   opus_fft_free_arch_c,         /* ARMv4 */
+   opus_fft_free_arch_c,         /* EDSP */
+   opus_fft_free_arch_c,         /* Media */
+   opus_fft_free_arm_neon        /* Neon with NE10 */
+};
+#   endif /* CUSTOM_MODES */
+
+void (*const OPUS_FFT[OPUS_ARCHMASK+1])(const kiss_fft_state *cfg,
+                                        const kiss_fft_cpx *fin,
+                                        kiss_fft_cpx *fout) = {
+   opus_fft_c,                   /* ARMv4 */
+   opus_fft_c,                   /* EDSP */
+   opus_fft_c,                   /* Media */
+   opus_fft_neon                 /* Neon with NE10 */
+};
+
+void (*const OPUS_IFFT[OPUS_ARCHMASK+1])(const kiss_fft_state *cfg,
+                                         const kiss_fft_cpx *fin,
+                                         kiss_fft_cpx *fout) = {
+   opus_ifft_c,                   /* ARMv4 */
+   opus_ifft_c,                   /* EDSP */
+   opus_ifft_c,                   /* Media */
+   opus_ifft_neon                 /* Neon with NE10 */
+};
+
+void (*const CLT_MDCT_FORWARD_IMPL[OPUS_ARCHMASK+1])(const mdct_lookup *l,
+                                                     kiss_fft_scalar *in,
+                                                     kiss_fft_scalar * OPUS_RESTRICT out,
+                                                     const opus_val16 *window,
+                                                     int overlap, int shift,
+                                                     int stride, int arch) = {
+   clt_mdct_forward_c,           /* ARMv4 */
+   clt_mdct_forward_c,           /* EDSP */
+   clt_mdct_forward_c,           /* Media */
+   clt_mdct_forward_neon         /* Neon with NE10 */
+};
+
+void (*const CLT_MDCT_BACKWARD_IMPL[OPUS_ARCHMASK+1])(const mdct_lookup *l,
+                                                      kiss_fft_scalar *in,
+                                                      kiss_fft_scalar * OPUS_RESTRICT out,
+                                                      const opus_val16 *window,
+                                                      int overlap, int shift,
+                                                      int stride, int arch) = {
+   clt_mdct_backward_c,           /* ARMv4 */
+   clt_mdct_backward_c,           /* EDSP */
+   clt_mdct_backward_c,           /* Media */
+   clt_mdct_backward_neon         /* Neon with NE10 */
+};
+
+#  endif /* HAVE_ARM_NE10 */
+# endif /* OPUS_ARM_MAY_HAVE_NEON_INTR */
+
+#endif /* OPUS_HAVE_RTCD */
diff --git a/opus/celt/arm/armcpu.c b/opus/celt/arm/armcpu.c
new file mode 100644 (file)
index 0000000..694a63b
--- /dev/null
@@ -0,0 +1,185 @@
+/* Copyright (c) 2010 Xiph.Org Foundation
+ * Copyright (c) 2013 Parrot */
+/*
+   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.
+
+   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.
+*/
+
+/* Original code from libtheora modified to suit to Opus */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef OPUS_HAVE_RTCD
+
+#include "armcpu.h"
+#include "cpu_support.h"
+#include "os_support.h"
+#include "opus_types.h"
+#include "arch.h"
+
+#define OPUS_CPU_ARM_V4_FLAG    (1<<OPUS_ARCH_ARM_V4)
+#define OPUS_CPU_ARM_EDSP_FLAG  (1<<OPUS_ARCH_ARM_EDSP)
+#define OPUS_CPU_ARM_MEDIA_FLAG (1<<OPUS_ARCH_ARM_MEDIA)
+#define OPUS_CPU_ARM_NEON_FLAG  (1<<OPUS_ARCH_ARM_NEON)
+
+#if defined(_MSC_VER)
+/*For GetExceptionCode() and EXCEPTION_ILLEGAL_INSTRUCTION.*/
+# define WIN32_LEAN_AND_MEAN
+# define WIN32_EXTRA_LEAN
+# include <windows.h>
+
+static OPUS_INLINE opus_uint32 opus_cpu_capabilities(void){
+  opus_uint32 flags;
+  flags=0;
+  /* MSVC has no OPUS_INLINE __asm support for ARM, but it does let you __emit
+   * instructions via their assembled hex code.
+   * All of these instructions should be essentially nops. */
+# if defined(OPUS_ARM_MAY_HAVE_EDSP) || defined(OPUS_ARM_MAY_HAVE_MEDIA) \
+ || defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+  __try{
+    /*PLD [r13]*/
+    __emit(0xF5DDF000);
+    flags|=OPUS_CPU_ARM_EDSP_FLAG;
+  }
+  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
+    /*Ignore exception.*/
+  }
+#  if defined(OPUS_ARM_MAY_HAVE_MEDIA) \
+ || defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+  __try{
+    /*SHADD8 r3,r3,r3*/
+    __emit(0xE6333F93);
+    flags|=OPUS_CPU_ARM_MEDIA_FLAG;
+  }
+  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
+    /*Ignore exception.*/
+  }
+#   if defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+  __try{
+    /*VORR q0,q0,q0*/
+    __emit(0xF2200150);
+    flags|=OPUS_CPU_ARM_NEON_FLAG;
+  }
+  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
+    /*Ignore exception.*/
+  }
+#   endif
+#  endif
+# endif
+  return flags;
+}
+
+#elif defined(__linux__)
+/* Linux based */
+opus_uint32 opus_cpu_capabilities(void)
+{
+  opus_uint32 flags = 0;
+  FILE *cpuinfo;
+
+  /* Reading /proc/self/auxv would be easier, but that doesn't work reliably on
+   * Android */
+  cpuinfo = fopen("/proc/cpuinfo", "r");
+
+  if(cpuinfo != NULL)
+  {
+    /* 512 should be enough for anybody (it's even enough for all the flags that
+     * x86 has accumulated... so far). */
+    char buf[512];
+
+    while(fgets(buf, 512, cpuinfo) != NULL)
+    {
+# if defined(OPUS_ARM_MAY_HAVE_EDSP) || defined(OPUS_ARM_MAY_HAVE_MEDIA) \
+ || defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+      /* Search for edsp and neon flag */
+      if(memcmp(buf, "Features", 8) == 0)
+      {
+        char *p;
+        p = strstr(buf, " edsp");
+        if(p != NULL && (p[5] == ' ' || p[5] == '\n'))
+          flags |= OPUS_CPU_ARM_EDSP_FLAG;
+
+#  if defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+        p = strstr(buf, " neon");
+        if(p != NULL && (p[5] == ' ' || p[5] == '\n'))
+          flags |= OPUS_CPU_ARM_NEON_FLAG;
+#  endif
+      }
+# endif
+
+# if defined(OPUS_ARM_MAY_HAVE_MEDIA) \
+ || defined(OPUS_ARM_MAY_HAVE_NEON) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+      /* Search for media capabilities (>= ARMv6) */
+      if(memcmp(buf, "CPU architecture:", 17) == 0)
+      {
+        int version;
+        version = atoi(buf+17);
+
+        if(version >= 6)
+          flags |= OPUS_CPU_ARM_MEDIA_FLAG;
+      }
+# endif
+    }
+
+    fclose(cpuinfo);
+  }
+  return flags;
+}
+#else
+/* The feature registers which can tell us what the processor supports are
+ * accessible in priveleged modes only, so we can't have a general user-space
+ * detection method like on x86.*/
+# error "Configured to use ARM asm but no CPU detection method available for " \
+   "your platform.  Reconfigure with --disable-rtcd (or send patches)."
+#endif
+
+int opus_select_arch(void)
+{
+  opus_uint32 flags = opus_cpu_capabilities();
+  int arch = 0;
+
+  if(!(flags & OPUS_CPU_ARM_EDSP_FLAG)) {
+    /* Asserts ensure arch values are sequential */
+    celt_assert(arch == OPUS_ARCH_ARM_V4);
+    return arch;
+  }
+  arch++;
+
+  if(!(flags & OPUS_CPU_ARM_MEDIA_FLAG)) {
+    celt_assert(arch == OPUS_ARCH_ARM_EDSP);
+    return arch;
+  }
+  arch++;
+
+  if(!(flags & OPUS_CPU_ARM_NEON_FLAG)) {
+    celt_assert(arch == OPUS_ARCH_ARM_MEDIA);
+    return arch;
+  }
+  arch++;
+
+  celt_assert(arch == OPUS_ARCH_ARM_NEON);
+  return arch;
+}
+
+#endif
diff --git a/opus/celt/arm/armcpu.h b/opus/celt/arm/armcpu.h
new file mode 100644 (file)
index 0000000..820262f
--- /dev/null
@@ -0,0 +1,77 @@
+/* Copyright (c) 2010 Xiph.Org Foundation
+ * Copyright (c) 2013 Parrot */
+/*
+   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.
+
+   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.
+*/
+
+#if !defined(ARMCPU_H)
+# define ARMCPU_H
+
+# if defined(OPUS_ARM_MAY_HAVE_EDSP)
+#  define MAY_HAVE_EDSP(name) name ## _edsp
+# else
+#  define MAY_HAVE_EDSP(name) name ## _c
+# endif
+
+# if defined(OPUS_ARM_MAY_HAVE_MEDIA)
+#  define MAY_HAVE_MEDIA(name) name ## _media
+# else
+#  define MAY_HAVE_MEDIA(name) MAY_HAVE_EDSP(name)
+# endif
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON)
+#  define MAY_HAVE_NEON(name) name ## _neon
+# else
+#  define MAY_HAVE_NEON(name) MAY_HAVE_MEDIA(name)
+# endif
+
+# if defined(OPUS_ARM_PRESUME_EDSP)
+#  define PRESUME_EDSP(name) name ## _edsp
+# else
+#  define PRESUME_EDSP(name) name ## _c
+# endif
+
+# if defined(OPUS_ARM_PRESUME_MEDIA)
+#  define PRESUME_MEDIA(name) name ## _media
+# else
+#  define PRESUME_MEDIA(name) PRESUME_EDSP(name)
+# endif
+
+# if defined(OPUS_ARM_PRESUME_NEON)
+#  define PRESUME_NEON(name) name ## _neon
+# else
+#  define PRESUME_NEON(name) PRESUME_MEDIA(name)
+# endif
+
+# if defined(OPUS_HAVE_RTCD)
+int opus_select_arch(void);
+
+#define OPUS_ARCH_ARM_V4    (0)
+#define OPUS_ARCH_ARM_EDSP  (1)
+#define OPUS_ARCH_ARM_MEDIA (2)
+#define OPUS_ARCH_ARM_NEON  (3)
+
+# endif
+
+#endif
diff --git a/opus/celt/arm/armopts.s.in b/opus/celt/arm/armopts.s.in
new file mode 100644 (file)
index 0000000..3d8aaf2
--- /dev/null
@@ -0,0 +1,37 @@
+/* Copyright (C) 2013 Mozilla Corporation */
+/*
+   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.
+
+   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.
+*/
+
+; Set the following to 1 if we have EDSP instructions
+;  (LDRD/STRD, etc., ARMv5E and later).
+OPUS_ARM_MAY_HAVE_EDSP  * @OPUS_ARM_MAY_HAVE_EDSP@
+
+; Set the following to 1 if we have ARMv6 media instructions.
+OPUS_ARM_MAY_HAVE_MEDIA * @OPUS_ARM_MAY_HAVE_MEDIA@
+
+; Set the following to 1 if we have NEON (some ARMv7)
+OPUS_ARM_MAY_HAVE_NEON  * @OPUS_ARM_MAY_HAVE_NEON@
+
+END
diff --git a/opus/celt/arm/celt_ne10_fft.c b/opus/celt/arm/celt_ne10_fft.c
new file mode 100644 (file)
index 0000000..b8c60ab
--- /dev/null
@@ -0,0 +1,173 @@
+/* Copyright (c) 2015 Xiph.Org Foundation
+   Written by Viswanath Puttagunta */
+/**
+   @file celt_ne10_fft.c
+   @brief ARM Neon optimizations for fft using NE10 library
+ */
+
+/*
+   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.
+
+   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 <NE10_dsp.h>
+#include "os_support.h"
+#include "kiss_fft.h"
+#include "stack_alloc.h"
+
+#if !defined(FIXED_POINT)
+# define NE10_FFT_ALLOC_C2C_TYPE_NEON ne10_fft_alloc_c2c_float32_neon
+# define NE10_FFT_CFG_TYPE_T ne10_fft_cfg_float32_t
+# define NE10_FFT_STATE_TYPE_T ne10_fft_state_float32_t
+# define NE10_FFT_DESTROY_C2C_TYPE ne10_fft_destroy_c2c_float32
+# define NE10_FFT_CPX_TYPE_T ne10_fft_cpx_float32_t
+# define NE10_FFT_C2C_1D_TYPE_NEON ne10_fft_c2c_1d_float32_neon
+#else
+# define NE10_FFT_ALLOC_C2C_TYPE_NEON(nfft) ne10_fft_alloc_c2c_int32_neon(nfft)
+# define NE10_FFT_CFG_TYPE_T ne10_fft_cfg_int32_t
+# define NE10_FFT_STATE_TYPE_T ne10_fft_state_int32_t
+# define NE10_FFT_DESTROY_C2C_TYPE ne10_fft_destroy_c2c_int32
+# define NE10_FFT_DESTROY_C2C_TYPE ne10_fft_destroy_c2c_int32
+# define NE10_FFT_CPX_TYPE_T ne10_fft_cpx_int32_t
+# define NE10_FFT_C2C_1D_TYPE_NEON ne10_fft_c2c_1d_int32_neon
+#endif
+
+#if defined(CUSTOM_MODES)
+
+/* nfft lengths in NE10 that support scaled fft */
+# define NE10_FFTSCALED_SUPPORT_MAX 4
+static const int ne10_fft_scaled_support[NE10_FFTSCALED_SUPPORT_MAX] = {
+   480, 240, 120, 60
+};
+
+int opus_fft_alloc_arm_neon(kiss_fft_state *st)
+{
+   int i;
+   size_t memneeded = sizeof(struct arch_fft_state);
+
+   st->arch_fft = (arch_fft_state *)opus_alloc(memneeded);
+   if (!st->arch_fft)
+      return -1;
+
+   for (i = 0; i < NE10_FFTSCALED_SUPPORT_MAX; i++) {
+      if(st->nfft == ne10_fft_scaled_support[i])
+         break;
+   }
+   if (i == NE10_FFTSCALED_SUPPORT_MAX) {
+      /* This nfft length (scaled fft) is not supported in NE10 */
+      st->arch_fft->is_supported = 0;
+      st->arch_fft->priv = NULL;
+   }
+   else {
+      st->arch_fft->is_supported = 1;
+      st->arch_fft->priv = (void *)NE10_FFT_ALLOC_C2C_TYPE_NEON(st->nfft);
+      if (st->arch_fft->priv == NULL) {
+         return -1;
+      }
+   }
+   return 0;
+}
+
+void opus_fft_free_arm_neon(kiss_fft_state *st)
+{
+   NE10_FFT_CFG_TYPE_T cfg;
+
+   if (!st->arch_fft)
+      return;
+
+   cfg = (NE10_FFT_CFG_TYPE_T)st->arch_fft->priv;
+   if (cfg)
+      NE10_FFT_DESTROY_C2C_TYPE(cfg);
+   opus_free(st->arch_fft);
+}
+#endif
+
+void opus_fft_neon(const kiss_fft_state *st,
+                   const kiss_fft_cpx *fin,
+                   kiss_fft_cpx *fout)
+{
+   NE10_FFT_STATE_TYPE_T state;
+   NE10_FFT_CFG_TYPE_T cfg = &state;
+   VARDECL(NE10_FFT_CPX_TYPE_T, buffer);
+   SAVE_STACK;
+   ALLOC(buffer, st->nfft, NE10_FFT_CPX_TYPE_T);
+
+   if (!st->arch_fft->is_supported) {
+      /* This nfft length (scaled fft) not supported in NE10 */
+      opus_fft_c(st, fin, fout);
+   }
+   else {
+      memcpy((void *)cfg, st->arch_fft->priv, sizeof(NE10_FFT_STATE_TYPE_T));
+      state.buffer = (NE10_FFT_CPX_TYPE_T *)&buffer[0];
+#if !defined(FIXED_POINT)
+      state.is_forward_scaled = 1;
+
+      NE10_FFT_C2C_1D_TYPE_NEON((NE10_FFT_CPX_TYPE_T *)fout,
+                                (NE10_FFT_CPX_TYPE_T *)fin,
+                                cfg, 0);
+#else
+      NE10_FFT_C2C_1D_TYPE_NEON((NE10_FFT_CPX_TYPE_T *)fout,
+                                (NE10_FFT_CPX_TYPE_T *)fin,
+                                cfg, 0, 1);
+#endif
+   }
+   RESTORE_STACK;
+}
+
+void opus_ifft_neon(const kiss_fft_state *st,
+                    const kiss_fft_cpx *fin,
+                    kiss_fft_cpx *fout)
+{
+   NE10_FFT_STATE_TYPE_T state;
+   NE10_FFT_CFG_TYPE_T cfg = &state;
+   VARDECL(NE10_FFT_CPX_TYPE_T, buffer);
+   SAVE_STACK;
+   ALLOC(buffer, st->nfft, NE10_FFT_CPX_TYPE_T);
+
+   if (!st->arch_fft->is_supported) {
+      /* This nfft length (scaled fft) not supported in NE10 */
+      opus_ifft_c(st, fin, fout);
+   }
+   else {
+      memcpy((void *)cfg, st->arch_fft->priv, sizeof(NE10_FFT_STATE_TYPE_T));
+      state.buffer = (NE10_FFT_CPX_TYPE_T *)&buffer[0];
+#if !defined(FIXED_POINT)
+      state.is_backward_scaled = 0;
+
+      NE10_FFT_C2C_1D_TYPE_NEON((NE10_FFT_CPX_TYPE_T *)fout,
+                                (NE10_FFT_CPX_TYPE_T *)fin,
+                                cfg, 1);
+#else
+      NE10_FFT_C2C_1D_TYPE_NEON((NE10_FFT_CPX_TYPE_T *)fout,
+                                (NE10_FFT_CPX_TYPE_T *)fin,
+                                cfg, 1, 0);
+#endif
+   }
+   RESTORE_STACK;
+}
diff --git a/opus/celt/arm/celt_ne10_mdct.c b/opus/celt/arm/celt_ne10_mdct.c
new file mode 100644 (file)
index 0000000..293c3ef
--- /dev/null
@@ -0,0 +1,258 @@
+/* Copyright (c) 2015 Xiph.Org Foundation
+   Written by Viswanath Puttagunta */
+/**
+   @file celt_ne10_mdct.c
+   @brief ARM Neon optimizations for mdct using NE10 library
+ */
+
+/*
+   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.
+
+   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.h"
+#include "_kiss_fft_guts.h"
+#include "mdct.h"
+#include "stack_alloc.h"
+
+void clt_mdct_forward_neon(const mdct_lookup *l,
+                           kiss_fft_scalar *in,
+                           kiss_fft_scalar * OPUS_RESTRICT out,
+                           const opus_val16 *window,
+                           int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   VARDECL(kiss_fft_scalar, f);
+   VARDECL(kiss_fft_cpx, f2);
+   const kiss_fft_state *st = l->kfft[shift];
+   const kiss_twiddle_scalar *trig;
+
+   SAVE_STACK;
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   ALLOC(f, N2, kiss_fft_scalar);
+   ALLOC(f2, N4, kiss_fft_cpx);
+
+   /* Consider the input to be composed 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 * OPUS_RESTRICT xp1 = in+(overlap>>1);
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+N2-1+(overlap>>1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = f;
+      const opus_val16 * OPUS_RESTRICT wp1 = window+(overlap>>1);
+      const opus_val16 * OPUS_RESTRICT wp2 = window+(overlap>>1)-1;
+      for(i=0;i<((overlap+3)>>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+3)>>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 * OPUS_RESTRICT yp = f;
+      const kiss_twiddle_scalar *t = &trig[0];
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_cpx yc;
+         kiss_twiddle_scalar t0, t1;
+         kiss_fft_scalar re, im, yr, yi;
+         t0 = t[i];
+         t1 = t[N4+i];
+         re = *yp++;
+         im = *yp++;
+         yr = S_MUL(re,t0)  -  S_MUL(im,t1);
+         yi = S_MUL(im,t0)  +  S_MUL(re,t1);
+         yc.r = yr;
+         yc.i = yi;
+         f2[i] = yc;
+      }
+   }
+
+   opus_fft(st, f2, (kiss_fft_cpx *)f, arch);
+
+   /* Post-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_cpx * OPUS_RESTRICT fp = (kiss_fft_cpx *)f;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      kiss_fft_scalar * OPUS_RESTRICT yp2 = out+stride*(N2-1);
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_scalar yr, yi;
+         yr = S_MUL(fp->i,t[N4+i]) - S_MUL(fp->r,t[i]);
+         yi = S_MUL(fp->r,t[N4+i]) + S_MUL(fp->i,t[i]);
+         *yp1 = yr;
+         *yp2 = yi;
+         fp++;
+         yp1 += 2*stride;
+         yp2 -= 2*stride;
+      }
+   }
+   RESTORE_STACK;
+}
+
+void clt_mdct_backward_neon(const mdct_lookup *l,
+                            kiss_fft_scalar *in,
+                            kiss_fft_scalar * OPUS_RESTRICT out,
+                            const opus_val16 * OPUS_RESTRICT window,
+                            int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   VARDECL(kiss_fft_scalar, f);
+   const kiss_twiddle_scalar *trig;
+   const kiss_fft_state *st = l->kfft[shift];
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   ALLOC(f, N2, kiss_fft_scalar);
+
+   /* Pre-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_scalar * OPUS_RESTRICT xp1 = in;
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+stride*(N2-1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = f;
+      const kiss_twiddle_scalar * OPUS_RESTRICT t = &trig[0];
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_scalar yr, yi;
+         yr = S_MUL(*xp2, t[i]) + S_MUL(*xp1, t[N4+i]);
+         yi = S_MUL(*xp1, t[i]) - S_MUL(*xp2, t[N4+i]);
+         yp[2*i] = yr;
+         yp[2*i+1] = yi;
+         xp1+=2*stride;
+         xp2-=2*stride;
+      }
+   }
+
+   opus_ifft(st, (kiss_fft_cpx *)f, (kiss_fft_cpx*)(out+(overlap>>1)), arch);
+
+   /* Post-rotate and de-shuffle from both ends of the buffer at once to make
+      it in-place. */
+   {
+      kiss_fft_scalar * yp0 = out+(overlap>>1);
+      kiss_fft_scalar * yp1 = out+(overlap>>1)+N2-2;
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Loop to (N4+1)>>1 to handle odd N4. When N4 is odd, the
+         middle pair will be computed twice. */
+      for(i=0;i<(N4+1)>>1;i++)
+      {
+         kiss_fft_scalar re, im, yr, yi;
+         kiss_twiddle_scalar t0, t1;
+         re = yp0[0];
+         im = yp0[1];
+         t0 = t[i];
+         t1 = t[N4+i];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = S_MUL(re,t0) + S_MUL(im,t1);
+         yi = S_MUL(re,t1) - S_MUL(im,t0);
+         re = yp1[0];
+         im = yp1[1];
+         yp0[0] = yr;
+         yp1[1] = yi;
+
+         t0 = t[(N4-i-1)];
+         t1 = t[(N2-i-1)];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = S_MUL(re,t0) + S_MUL(im,t1);
+         yi = S_MUL(re,t1) - S_MUL(im,t0);
+         yp1[0] = yr;
+         yp0[1] = yi;
+         yp0 += 2;
+         yp1 -= 2;
+      }
+   }
+
+   /* Mirror on both sides for TDAC */
+   {
+      kiss_fft_scalar * OPUS_RESTRICT xp1 = out+overlap-1;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      const opus_val16 * OPUS_RESTRICT wp1 = window;
+      const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
+
+      for(i = 0; i < overlap/2; i++)
+      {
+         kiss_fft_scalar x1, x2;
+         x1 = *xp1;
+         x2 = *yp1;
+         *yp1++ = MULT16_32_Q15(*wp2, x2) - MULT16_32_Q15(*wp1, x1);
+         *xp1-- = MULT16_32_Q15(*wp1, x2) + MULT16_32_Q15(*wp2, x1);
+         wp1++;
+         wp2--;
+      }
+   }
+   RESTORE_STACK;
+}
diff --git a/opus/celt/arm/celt_neon_intr.c b/opus/celt/arm/celt_neon_intr.c
new file mode 100644 (file)
index 0000000..cf44398
--- /dev/null
@@ -0,0 +1,211 @@
+/* Copyright (c) 2014-2015 Xiph.Org Foundation
+   Written by Viswanath Puttagunta */
+/**
+   @file celt_neon_intr.c
+   @brief ARM Neon Intrinsic optimizations 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#include "../pitch.h"
+
+#if defined(FIXED_POINT)
+void xcorr_kernel_neon_fixed(const opus_val16 * x, const opus_val16 * y, opus_val32 sum[4], int len)
+{
+   int j;
+   int32x4_t a = vld1q_s32(sum);
+   /* Load y[0...3] */
+   /* This requires len>0 to always be valid (which we assert in the C code). */
+   int16x4_t y0 = vld1_s16(y);
+   y += 4;
+
+   for (j = 0; j + 8 <= len; j += 8)
+   {
+      /* Load x[0...7] */
+      int16x8_t xx = vld1q_s16(x);
+      int16x4_t x0 = vget_low_s16(xx);
+      int16x4_t x4 = vget_high_s16(xx);
+      /* Load y[4...11] */
+      int16x8_t yy = vld1q_s16(y);
+      int16x4_t y4 = vget_low_s16(yy);
+      int16x4_t y8 = vget_high_s16(yy);
+      int32x4_t a0 = vmlal_lane_s16(a, y0, x0, 0);
+      int32x4_t a1 = vmlal_lane_s16(a0, y4, x4, 0);
+
+      int16x4_t y1 = vext_s16(y0, y4, 1);
+      int16x4_t y5 = vext_s16(y4, y8, 1);
+      int32x4_t a2 = vmlal_lane_s16(a1, y1, x0, 1);
+      int32x4_t a3 = vmlal_lane_s16(a2, y5, x4, 1);
+
+      int16x4_t y2 = vext_s16(y0, y4, 2);
+      int16x4_t y6 = vext_s16(y4, y8, 2);
+      int32x4_t a4 = vmlal_lane_s16(a3, y2, x0, 2);
+      int32x4_t a5 = vmlal_lane_s16(a4, y6, x4, 2);
+
+      int16x4_t y3 = vext_s16(y0, y4, 3);
+      int16x4_t y7 = vext_s16(y4, y8, 3);
+      int32x4_t a6 = vmlal_lane_s16(a5, y3, x0, 3);
+      int32x4_t a7 = vmlal_lane_s16(a6, y7, x4, 3);
+
+      y0 = y8;
+      a = a7;
+      x += 8;
+      y += 8;
+   }
+
+   for (; j < len; j++)
+   {
+      int16x4_t x0 = vld1_dup_s16(x);  /* load next x */
+      int32x4_t a0 = vmlal_s16(a, y0, x0);
+
+      int16x4_t y4 = vld1_dup_s16(y);  /* load next y */
+      y0 = vext_s16(y0, y4, 1);
+      a = a0;
+      x++;
+      y++;
+   }
+
+   vst1q_s32(sum, a);
+}
+
+#else
+/*
+ * Function: xcorr_kernel_neon_float
+ * ---------------------------------
+ * Computes 4 correlation values and stores them in sum[4]
+ */
+static void xcorr_kernel_neon_float(const float32_t *x, const float32_t *y,
+      float32_t sum[4], int len) {
+   float32x4_t YY[3];
+   float32x4_t YEXT[3];
+   float32x4_t XX[2];
+   float32x2_t XX_2;
+   float32x4_t SUMM;
+   const float32_t *xi = x;
+   const float32_t *yi = y;
+
+   celt_assert(len>0);
+
+   YY[0] = vld1q_f32(yi);
+   SUMM = vdupq_n_f32(0);
+
+   /* Consume 8 elements in x vector and 12 elements in y
+    * vector. However, the 12'th element never really gets
+    * touched in this loop. So, if len == 8, then we only
+    * must access y[0] to y[10]. y[11] must not be accessed
+    * hence make sure len > 8 and not len >= 8
+    */
+   while (len > 8) {
+      yi += 4;
+      YY[1] = vld1q_f32(yi);
+      yi += 4;
+      YY[2] = vld1q_f32(yi);
+
+      XX[0] = vld1q_f32(xi);
+      xi += 4;
+      XX[1] = vld1q_f32(xi);
+      xi += 4;
+
+      SUMM = vmlaq_lane_f32(SUMM, YY[0], vget_low_f32(XX[0]), 0);
+      YEXT[0] = vextq_f32(YY[0], YY[1], 1);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[0], vget_low_f32(XX[0]), 1);
+      YEXT[1] = vextq_f32(YY[0], YY[1], 2);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[1], vget_high_f32(XX[0]), 0);
+      YEXT[2] = vextq_f32(YY[0], YY[1], 3);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[2], vget_high_f32(XX[0]), 1);
+
+      SUMM = vmlaq_lane_f32(SUMM, YY[1], vget_low_f32(XX[1]), 0);
+      YEXT[0] = vextq_f32(YY[1], YY[2], 1);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[0], vget_low_f32(XX[1]), 1);
+      YEXT[1] = vextq_f32(YY[1], YY[2], 2);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[1], vget_high_f32(XX[1]), 0);
+      YEXT[2] = vextq_f32(YY[1], YY[2], 3);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[2], vget_high_f32(XX[1]), 1);
+
+      YY[0] = YY[2];
+      len -= 8;
+   }
+
+   /* Consume 4 elements in x vector and 8 elements in y
+    * vector. However, the 8'th element in y never really gets
+    * touched in this loop. So, if len == 4, then we only
+    * must access y[0] to y[6]. y[7] must not be accessed
+    * hence make sure len>4 and not len>=4
+    */
+   if (len > 4) {
+      yi += 4;
+      YY[1] = vld1q_f32(yi);
+
+      XX[0] = vld1q_f32(xi);
+      xi += 4;
+
+      SUMM = vmlaq_lane_f32(SUMM, YY[0], vget_low_f32(XX[0]), 0);
+      YEXT[0] = vextq_f32(YY[0], YY[1], 1);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[0], vget_low_f32(XX[0]), 1);
+      YEXT[1] = vextq_f32(YY[0], YY[1], 2);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[1], vget_high_f32(XX[0]), 0);
+      YEXT[2] = vextq_f32(YY[0], YY[1], 3);
+      SUMM = vmlaq_lane_f32(SUMM, YEXT[2], vget_high_f32(XX[0]), 1);
+
+      YY[0] = YY[1];
+      len -= 4;
+   }
+
+   while (--len > 0) {
+      XX_2 = vld1_dup_f32(xi++);
+      SUMM = vmlaq_lane_f32(SUMM, YY[0], XX_2, 0);
+      YY[0]= vld1q_f32(++yi);
+   }
+
+   XX_2 = vld1_dup_f32(xi);
+   SUMM = vmlaq_lane_f32(SUMM, YY[0], XX_2, 0);
+
+   vst1q_f32(sum, SUMM);
+}
+
+void celt_pitch_xcorr_float_neon(const opus_val16 *_x, const opus_val16 *_y,
+                        opus_val32 *xcorr, int len, int max_pitch, int arch) {
+   int i;
+   (void)arch;
+   celt_assert(max_pitch > 0);
+   celt_assert((((unsigned char *)_x-(unsigned char *)NULL)&3)==0);
+
+   for (i = 0; i < (max_pitch-3); i += 4) {
+      xcorr_kernel_neon_float((const float32_t *)_x, (const float32_t *)_y+i,
+            (float32_t *)xcorr+i, len);
+   }
+
+   /* In case max_pitch isn't a multiple of 4, do non-unrolled version. */
+   for (; i < max_pitch; i++) {
+      xcorr[i] = celt_inner_prod_neon(_x, _y+i, len);
+   }
+}
+#endif
diff --git a/opus/celt/arm/celt_pitch_xcorr_arm-gnu.S b/opus/celt/arm/celt_pitch_xcorr_arm-gnu.S
new file mode 100644 (file)
index 0000000..10668e5
--- /dev/null
@@ -0,0 +1,555 @@
+    .syntax unified
+@ Copyright (c) 2007-2008 CSIRO
+@ Copyright (c) 2007-2009 Xiph.Org Foundation
+@ Copyright (c) 2013      Parrot
+@ Written by Aurélien Zanelli
+@
+@ 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.
+@
+@ 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.
+
+    .text;   .p2align 2;   .arch armv7-a
+   .fpu neon
+   .object_arch armv4t
+
+  .include "celt/arm/armopts-gnu.S"
+
+ .if OPUS_ARM_MAY_HAVE_EDSP
+  .global celt_pitch_xcorr_edsp
+ .endif
+
+ .if OPUS_ARM_MAY_HAVE_NEON
+  .global celt_pitch_xcorr_neon
+ .endif
+
+ .if OPUS_ARM_MAY_HAVE_NEON
+
+@ Compute sum[k]=sum(x[j]*y[j+k],j=0...len-1), k=0...3
+       .type   xcorr_kernel_neon, %function; xcorr_kernel_neon: @ PROC
+xcorr_kernel_neon_start:
+  @ input:
+  @   r3     = int         len
+  @   r4     = opus_val16 *x
+  @   r5     = opus_val16 *y
+  @   q0     = opus_val32  sum[4]
+  @ output:
+  @   q0     = opus_val32  sum[4]
+  @ preserved: r0-r3, r6-r11, d2, q4-q7, q9-q15
+  @ internal usage:
+  @   r12 = int j
+  @   d3  = y_3|y_2|y_1|y_0
+  @   q2  = y_B|y_A|y_9|y_8|y_7|y_6|y_5|y_4
+  @   q3  = x_7|x_6|x_5|x_4|x_3|x_2|x_1|x_0
+  @   q8  = scratch
+  @
+  @ Load y[0...3]
+  @ This requires len>0 to always be valid (which we assert in the C code).
+  VLD1.16      {d5}, [r5]!
+  SUBS         r12, r3, #8
+  BLE xcorr_kernel_neon_process4
+@ Process 8 samples at a time.
+@ This loop loads one y value more than we actually need. Therefore we have to
+@ stop as soon as there are 8 or fewer samples left (instead of 7), to avoid
+@ reading past the end of the array.
+xcorr_kernel_neon_process8:
+  @ This loop has 19 total instructions (10 cycles to issue, minimum), with
+  @ - 2 cycles of ARM insrtuctions,
+  @ - 10 cycles of load/store/byte permute instructions, and
+  @ - 9 cycles of data processing instructions.
+  @ On a Cortex A8, we dual-issue the maximum amount (9 cycles) between the
+  @ latter two categories, meaning the whole loop should run in 10 cycles per
+  @ iteration, barring cache misses.
+  @
+  @ Load x[0...7]
+  VLD1.16      {d6, d7}, [r4]!
+  @ Unlike VMOV, VAND is a data processsing instruction (and doesn't get
+  @ assembled to VMOV, like VORR would), so it dual-issues with the prior VLD1.
+  VAND         d3, d5, d5
+  SUBS         r12, r12, #8
+  @ Load y[4...11]
+  VLD1.16      {d4, d5}, [r5]!
+  VMLAL.S16    q0, d3, d6[0]
+  VEXT.16      d16, d3, d4, #1
+  VMLAL.S16    q0, d4, d7[0]
+  VEXT.16      d17, d4, d5, #1
+  VMLAL.S16    q0, d16, d6[1]
+  VEXT.16      d16, d3, d4, #2
+  VMLAL.S16    q0, d17, d7[1]
+  VEXT.16      d17, d4, d5, #2
+  VMLAL.S16    q0, d16, d6[2]
+  VEXT.16      d16, d3, d4, #3
+  VMLAL.S16    q0, d17, d7[2]
+  VEXT.16      d17, d4, d5, #3
+  VMLAL.S16    q0, d16, d6[3]
+  VMLAL.S16    q0, d17, d7[3]
+  BGT xcorr_kernel_neon_process8
+@ Process 4 samples here if we have > 4 left (still reading one extra y value).
+xcorr_kernel_neon_process4:
+  ADDS         r12, r12, #4
+  BLE xcorr_kernel_neon_process2
+  @ Load x[0...3]
+  VLD1.16      d6, [r4]!
+  @ Use VAND since it's a data processing instruction again.
+  VAND         d4, d5, d5
+  SUB          r12, r12, #4
+  @ Load y[4...7]
+  VLD1.16      d5, [r5]!
+  VMLAL.S16    q0, d4, d6[0]
+  VEXT.16      d16, d4, d5, #1
+  VMLAL.S16    q0, d16, d6[1]
+  VEXT.16      d16, d4, d5, #2
+  VMLAL.S16    q0, d16, d6[2]
+  VEXT.16      d16, d4, d5, #3
+  VMLAL.S16    q0, d16, d6[3]
+@ Process 2 samples here if we have > 2 left (still reading one extra y value).
+xcorr_kernel_neon_process2:
+  ADDS         r12, r12, #2
+  BLE xcorr_kernel_neon_process1
+  @ Load x[0...1]
+  VLD2.16      {d6[],d7[]}, [r4]!
+  @ Use VAND since it's a data processing instruction again.
+  VAND         d4, d5, d5
+  SUB          r12, r12, #2
+  @ Load y[4...5]
+  VLD1.32      {d5[]}, [r5]!
+  VMLAL.S16    q0, d4, d6
+  VEXT.16      d16, d4, d5, #1
+  @ Replace bottom copy of {y5,y4} in d5 with {y3,y2} from d4, using VSRI
+  @ instead of VEXT, since it's a data-processing instruction.
+  VSRI.64      d5, d4, #32
+  VMLAL.S16    q0, d16, d7
+@ Process 1 sample using the extra y value we loaded above.
+xcorr_kernel_neon_process1:
+  @ Load next *x
+  VLD1.16      {d6[]}, [r4]!
+  ADDS         r12, r12, #1
+  @ y[0...3] are left in d5 from prior iteration(s) (if any)
+  VMLAL.S16    q0, d5, d6
+  MOVLE        pc, lr
+@ Now process 1 last sample, not reading ahead.
+  @ Load last *y
+  VLD1.16      {d4[]}, [r5]!
+  VSRI.64      d4, d5, #16
+  @ Load last *x
+  VLD1.16      {d6[]}, [r4]!
+  VMLAL.S16    q0, d4, d6
+  MOV          pc, lr
+       .size xcorr_kernel_neon, .-xcorr_kernel_neon  @ ENDP
+
+@ opus_val32 celt_pitch_xcorr_neon(opus_val16 *_x, opus_val16 *_y,
+@  opus_val32 *xcorr, int len, int max_pitch, int arch)
+       .type   celt_pitch_xcorr_neon, %function; celt_pitch_xcorr_neon: @ PROC
+  @ input:
+  @   r0  = opus_val16 *_x
+  @   r1  = opus_val16 *_y
+  @   r2  = opus_val32 *xcorr
+  @   r3  = int         len
+  @ output:
+  @   r0  = int         maxcorr
+  @ internal usage:
+  @   r4  = opus_val16 *x (for xcorr_kernel_neon())
+  @   r5  = opus_val16 *y (for xcorr_kernel_neon())
+  @   r6  = int         max_pitch
+  @   r12 = int         j
+  @   q15 = int         maxcorr[4] (q15 is not used by xcorr_kernel_neon())
+  @ ignored:
+  @         int         arch
+  STMFD        sp!, {r4-r6, lr}
+  LDR          r6, [sp, #16]
+  VMOV.S32     q15, #1
+  @ if (max_pitch < 4) goto celt_pitch_xcorr_neon_process4_done
+  SUBS         r6, r6, #4
+  BLT celt_pitch_xcorr_neon_process4_done
+celt_pitch_xcorr_neon_process4:
+  @ xcorr_kernel_neon parameters:
+  @ r3 = len, r4 = _x, r5 = _y, q0 = {0, 0, 0, 0}
+  MOV          r4, r0
+  MOV          r5, r1
+  VEOR         q0, q0, q0
+  @ xcorr_kernel_neon only modifies r4, r5, r12, and q0...q3.
+  @ So we don't save/restore any other registers.
+  BL xcorr_kernel_neon_start
+  SUBS         r6, r6, #4
+  VST1.32      {q0}, [r2]!
+  @ _y += 4
+  ADD          r1, r1, #8
+  VMAX.S32     q15, q15, q0
+  @ if (max_pitch < 4) goto celt_pitch_xcorr_neon_process4_done
+  BGE celt_pitch_xcorr_neon_process4
+@ We have less than 4 sums left to compute.
+celt_pitch_xcorr_neon_process4_done:
+  ADDS         r6, r6, #4
+  @ Reduce maxcorr to a single value
+  VMAX.S32     d30, d30, d31
+  VPMAX.S32    d30, d30, d30
+  @ if (max_pitch <= 0) goto celt_pitch_xcorr_neon_done
+  BLE celt_pitch_xcorr_neon_done
+@ Now compute each remaining sum one at a time.
+celt_pitch_xcorr_neon_process_remaining:
+  MOV          r4, r0
+  MOV          r5, r1
+  VMOV.I32     q0, #0
+  SUBS         r12, r3, #8
+  BLT celt_pitch_xcorr_neon_process_remaining4
+@ Sum terms 8 at a time.
+celt_pitch_xcorr_neon_process_remaining_loop8:
+  @ Load x[0...7]
+  VLD1.16      {q1}, [r4]!
+  @ Load y[0...7]
+  VLD1.16      {q2}, [r5]!
+  SUBS         r12, r12, #8
+  VMLAL.S16    q0, d4, d2
+  VMLAL.S16    q0, d5, d3
+  BGE celt_pitch_xcorr_neon_process_remaining_loop8
+@ Sum terms 4 at a time.
+celt_pitch_xcorr_neon_process_remaining4:
+  ADDS         r12, r12, #4
+  BLT celt_pitch_xcorr_neon_process_remaining4_done
+  @ Load x[0...3]
+  VLD1.16      {d2}, [r4]!
+  @ Load y[0...3]
+  VLD1.16      {d3}, [r5]!
+  SUB          r12, r12, #4
+  VMLAL.S16    q0, d3, d2
+celt_pitch_xcorr_neon_process_remaining4_done:
+  @ Reduce the sum to a single value.
+  VADD.S32     d0, d0, d1
+  VPADDL.S32   d0, d0
+  ADDS         r12, r12, #4
+  BLE celt_pitch_xcorr_neon_process_remaining_loop_done
+@ Sum terms 1 at a time.
+celt_pitch_xcorr_neon_process_remaining_loop1:
+  VLD1.16      {d2[]}, [r4]!
+  VLD1.16      {d3[]}, [r5]!
+  SUBS         r12, r12, #1
+  VMLAL.S16    q0, d2, d3
+  BGT celt_pitch_xcorr_neon_process_remaining_loop1
+celt_pitch_xcorr_neon_process_remaining_loop_done:
+  VST1.32      {d0[0]}, [r2]!
+  VMAX.S32     d30, d30, d0
+  SUBS         r6, r6, #1
+  @ _y++
+  ADD          r1, r1, #2
+  @ if (--max_pitch > 0) goto celt_pitch_xcorr_neon_process_remaining
+  BGT celt_pitch_xcorr_neon_process_remaining
+celt_pitch_xcorr_neon_done:
+  VMOV.32      r0, d30[0]
+  LDMFD        sp!, {r4-r6, pc}
+       .size celt_pitch_xcorr_neon, .-celt_pitch_xcorr_neon  @ ENDP
+
+ .endif
+
+ .if OPUS_ARM_MAY_HAVE_EDSP
+
+@ This will get used on ARMv7 devices without NEON, so it has been optimized
+@ to take advantage of dual-issuing where possible.
+       .type   xcorr_kernel_edsp, %function; xcorr_kernel_edsp: @ PROC
+xcorr_kernel_edsp_start:
+  @ input:
+  @   r3      = int         len
+  @   r4      = opus_val16 *_x (must be 32-bit aligned)
+  @   r5      = opus_val16 *_y (must be 32-bit aligned)
+  @   r6...r9 = opus_val32  sum[4]
+  @ output:
+  @   r6...r9 = opus_val32  sum[4]
+  @ preserved: r0-r5
+  @ internal usage
+  @   r2      = int         j
+  @   r12,r14 = opus_val16  x[4]
+  @   r10,r11 = opus_val16  y[4]
+  STMFD        sp!, {r2,r4,r5,lr}
+  LDR          r10, [r5], #4      @ Load y[0...1]
+  SUBS         r2, r3, #4         @ j = len-4
+  LDR          r11, [r5], #4      @ Load y[2...3]
+  BLE xcorr_kernel_edsp_process4_done
+  LDR          r12, [r4], #4      @ Load x[0...1]
+  @ Stall
+xcorr_kernel_edsp_process4:
+  @ The multiplies must issue from pipeline 0, and can't dual-issue with each
+  @ other. Every other instruction here dual-issues with a multiply, and is
+  @ thus "free". There should be no stalls in the body of the loop.
+  SMLABB       r6, r12, r10, r6   @ sum[0] = MAC16_16(sum[0],x_0,y_0)
+  LDR          r14, [r4], #4      @ Load x[2...3]
+  SMLABT       r7, r12, r10, r7   @ sum[1] = MAC16_16(sum[1],x_0,y_1)
+  SUBS         r2, r2, #4         @ j-=4
+  SMLABB       r8, r12, r11, r8   @ sum[2] = MAC16_16(sum[2],x_0,y_2)
+  SMLABT       r9, r12, r11, r9   @ sum[3] = MAC16_16(sum[3],x_0,y_3)
+  SMLATT       r6, r12, r10, r6   @ sum[0] = MAC16_16(sum[0],x_1,y_1)
+  LDR          r10, [r5], #4      @ Load y[4...5]
+  SMLATB       r7, r12, r11, r7   @ sum[1] = MAC16_16(sum[1],x_1,y_2)
+  SMLATT       r8, r12, r11, r8   @ sum[2] = MAC16_16(sum[2],x_1,y_3)
+  SMLATB       r9, r12, r10, r9   @ sum[3] = MAC16_16(sum[3],x_1,y_4)
+  LDRGT        r12, [r4], #4      @ Load x[0...1]
+  SMLABB       r6, r14, r11, r6   @ sum[0] = MAC16_16(sum[0],x_2,y_2)
+  SMLABT       r7, r14, r11, r7   @ sum[1] = MAC16_16(sum[1],x_2,y_3)
+  SMLABB       r8, r14, r10, r8   @ sum[2] = MAC16_16(sum[2],x_2,y_4)
+  SMLABT       r9, r14, r10, r9   @ sum[3] = MAC16_16(sum[3],x_2,y_5)
+  SMLATT       r6, r14, r11, r6   @ sum[0] = MAC16_16(sum[0],x_3,y_3)
+  LDR          r11, [r5], #4      @ Load y[6...7]
+  SMLATB       r7, r14, r10, r7   @ sum[1] = MAC16_16(sum[1],x_3,y_4)
+  SMLATT       r8, r14, r10, r8   @ sum[2] = MAC16_16(sum[2],x_3,y_5)
+  SMLATB       r9, r14, r11, r9   @ sum[3] = MAC16_16(sum[3],x_3,y_6)
+  BGT xcorr_kernel_edsp_process4
+xcorr_kernel_edsp_process4_done:
+  ADDS         r2, r2, #4
+  BLE xcorr_kernel_edsp_done
+  LDRH         r12, [r4], #2      @ r12 = *x++
+  SUBS         r2, r2, #1         @ j--
+  @ Stall
+  SMLABB       r6, r12, r10, r6   @ sum[0] = MAC16_16(sum[0],x,y_0)
+  LDRHGT       r14, [r4], #2      @ r14 = *x++
+  SMLABT       r7, r12, r10, r7   @ sum[1] = MAC16_16(sum[1],x,y_1)
+  SMLABB       r8, r12, r11, r8   @ sum[2] = MAC16_16(sum[2],x,y_2)
+  SMLABT       r9, r12, r11, r9   @ sum[3] = MAC16_16(sum[3],x,y_3)
+  BLE xcorr_kernel_edsp_done
+  SMLABT       r6, r14, r10, r6   @ sum[0] = MAC16_16(sum[0],x,y_1)
+  SUBS         r2, r2, #1         @ j--
+  SMLABB       r7, r14, r11, r7   @ sum[1] = MAC16_16(sum[1],x,y_2)
+  LDRH         r10, [r5], #2      @ r10 = y_4 = *y++
+  SMLABT       r8, r14, r11, r8   @ sum[2] = MAC16_16(sum[2],x,y_3)
+  LDRHGT       r12, [r4], #2      @ r12 = *x++
+  SMLABB       r9, r14, r10, r9   @ sum[3] = MAC16_16(sum[3],x,y_4)
+  BLE xcorr_kernel_edsp_done
+  SMLABB       r6, r12, r11, r6   @ sum[0] = MAC16_16(sum[0],tmp,y_2)
+  CMP          r2, #1             @ j--
+  SMLABT       r7, r12, r11, r7   @ sum[1] = MAC16_16(sum[1],tmp,y_3)
+  LDRH         r2, [r5], #2       @ r2 = y_5 = *y++
+  SMLABB       r8, r12, r10, r8   @ sum[2] = MAC16_16(sum[2],tmp,y_4)
+  LDRHGT       r14, [r4]          @ r14 = *x
+  SMLABB       r9, r12, r2, r9    @ sum[3] = MAC16_16(sum[3],tmp,y_5)
+  BLE xcorr_kernel_edsp_done
+  SMLABT       r6, r14, r11, r6   @ sum[0] = MAC16_16(sum[0],tmp,y_3)
+  LDRH         r11, [r5]          @ r11 = y_6 = *y
+  SMLABB       r7, r14, r10, r7   @ sum[1] = MAC16_16(sum[1],tmp,y_4)
+  SMLABB       r8, r14, r2, r8    @ sum[2] = MAC16_16(sum[2],tmp,y_5)
+  SMLABB       r9, r14, r11, r9   @ sum[3] = MAC16_16(sum[3],tmp,y_6)
+xcorr_kernel_edsp_done:
+  LDMFD        sp!, {r2,r4,r5,pc}
+       .size xcorr_kernel_edsp, .-xcorr_kernel_edsp  @ ENDP
+
+       .type   celt_pitch_xcorr_edsp, %function; celt_pitch_xcorr_edsp: @ PROC
+  @ input:
+  @   r0  = opus_val16 *_x (must be 32-bit aligned)
+  @   r1  = opus_val16 *_y (only needs to be 16-bit aligned)
+  @   r2  = opus_val32 *xcorr
+  @   r3  = int         len
+  @ output:
+  @   r0  = maxcorr
+  @ internal usage
+  @   r4  = opus_val16 *x
+  @   r5  = opus_val16 *y
+  @   r6  = opus_val32  sum0
+  @   r7  = opus_val32  sum1
+  @   r8  = opus_val32  sum2
+  @   r9  = opus_val32  sum3
+  @   r1  = int         max_pitch
+  @   r12 = int         j
+  @ ignored:
+  @         int         arch
+  STMFD        sp!, {r4-r11, lr}
+  MOV          r5, r1
+  LDR          r1, [sp, #36]
+  MOV          r4, r0
+  TST          r5, #3
+  @ maxcorr = 1
+  MOV          r0, #1
+  BEQ          celt_pitch_xcorr_edsp_process1u_done
+@ Compute one sum at the start to make y 32-bit aligned.
+  SUBS         r12, r3, #4
+  @ r14 = sum = 0
+  MOV          r14, #0
+  LDRH         r8, [r5], #2
+  BLE celt_pitch_xcorr_edsp_process1u_loop4_done
+  LDR          r6, [r4], #4
+  MOV          r8, r8, LSL #16
+celt_pitch_xcorr_edsp_process1u_loop4:
+  LDR          r9, [r5], #4
+  SMLABT       r14, r6, r8, r14     @ sum = MAC16_16(sum, x_0, y_0)
+  LDR          r7, [r4], #4
+  SMLATB       r14, r6, r9, r14     @ sum = MAC16_16(sum, x_1, y_1)
+  LDR          r8, [r5], #4
+  SMLABT       r14, r7, r9, r14     @ sum = MAC16_16(sum, x_2, y_2)
+  SUBS         r12, r12, #4         @ j-=4
+  SMLATB       r14, r7, r8, r14     @ sum = MAC16_16(sum, x_3, y_3)
+  LDRGT        r6, [r4], #4
+  BGT celt_pitch_xcorr_edsp_process1u_loop4
+  MOV          r8, r8, LSR #16
+celt_pitch_xcorr_edsp_process1u_loop4_done:
+  ADDS         r12, r12, #4
+celt_pitch_xcorr_edsp_process1u_loop1:
+  LDRHGE       r6, [r4], #2
+  @ Stall
+  SMLABBGE     r14, r6, r8, r14    @ sum = MAC16_16(sum, *x, *y)
+  SUBSGE       r12, r12, #1
+  LDRHGT       r8, [r5], #2
+  BGT celt_pitch_xcorr_edsp_process1u_loop1
+  @ Restore _x
+  SUB          r4, r4, r3, LSL #1
+  @ Restore and advance _y
+  SUB          r5, r5, r3, LSL #1
+  @ maxcorr = max(maxcorr, sum)
+  CMP          r0, r14
+  ADD          r5, r5, #2
+  MOVLT        r0, r14
+  SUBS         r1, r1, #1
+  @ xcorr[i] = sum
+  STR          r14, [r2], #4
+  BLE celt_pitch_xcorr_edsp_done
+celt_pitch_xcorr_edsp_process1u_done:
+  @ if (max_pitch < 4) goto celt_pitch_xcorr_edsp_process2
+  SUBS         r1, r1, #4
+  BLT celt_pitch_xcorr_edsp_process2
+celt_pitch_xcorr_edsp_process4:
+  @ xcorr_kernel_edsp parameters:
+  @ r3 = len, r4 = _x, r5 = _y, r6...r9 = sum[4] = {0, 0, 0, 0}
+  MOV          r6, #0
+  MOV          r7, #0
+  MOV          r8, #0
+  MOV          r9, #0
+  BL xcorr_kernel_edsp_start  @ xcorr_kernel_edsp(_x, _y+i, xcorr+i, len)
+  @ maxcorr = max(maxcorr, sum0, sum1, sum2, sum3)
+  CMP          r0, r6
+  @ _y+=4
+  ADD          r5, r5, #8
+  MOVLT        r0, r6
+  CMP          r0, r7
+  MOVLT        r0, r7
+  CMP          r0, r8
+  MOVLT        r0, r8
+  CMP          r0, r9
+  MOVLT        r0, r9
+  STMIA        r2!, {r6-r9}
+  SUBS         r1, r1, #4
+  BGE celt_pitch_xcorr_edsp_process4
+celt_pitch_xcorr_edsp_process2:
+  ADDS         r1, r1, #2
+  BLT celt_pitch_xcorr_edsp_process1a
+  SUBS         r12, r3, #4
+  @ {r10, r11} = {sum0, sum1} = {0, 0}
+  MOV          r10, #0
+  MOV          r11, #0
+  LDR          r8, [r5], #4
+  BLE celt_pitch_xcorr_edsp_process2_loop_done
+  LDR          r6, [r4], #4
+  LDR          r9, [r5], #4
+celt_pitch_xcorr_edsp_process2_loop4:
+  SMLABB       r10, r6, r8, r10     @ sum0 = MAC16_16(sum0, x_0, y_0)
+  LDR          r7, [r4], #4
+  SMLABT       r11, r6, r8, r11     @ sum1 = MAC16_16(sum1, x_0, y_1)
+  SUBS         r12, r12, #4         @ j-=4
+  SMLATT       r10, r6, r8, r10     @ sum0 = MAC16_16(sum0, x_1, y_1)
+  LDR          r8, [r5], #4
+  SMLATB       r11, r6, r9, r11     @ sum1 = MAC16_16(sum1, x_1, y_2)
+  LDRGT        r6, [r4], #4
+  SMLABB       r10, r7, r9, r10     @ sum0 = MAC16_16(sum0, x_2, y_2)
+  SMLABT       r11, r7, r9, r11     @ sum1 = MAC16_16(sum1, x_2, y_3)
+  SMLATT       r10, r7, r9, r10     @ sum0 = MAC16_16(sum0, x_3, y_3)
+  LDRGT        r9, [r5], #4
+  SMLATB       r11, r7, r8, r11     @ sum1 = MAC16_16(sum1, x_3, y_4)
+  BGT celt_pitch_xcorr_edsp_process2_loop4
+celt_pitch_xcorr_edsp_process2_loop_done:
+  ADDS         r12, r12, #2
+  BLE  celt_pitch_xcorr_edsp_process2_1
+  LDR          r6, [r4], #4
+  @ Stall
+  SMLABB       r10, r6, r8, r10     @ sum0 = MAC16_16(sum0, x_0, y_0)
+  LDR          r9, [r5], #4
+  SMLABT       r11, r6, r8, r11     @ sum1 = MAC16_16(sum1, x_0, y_1)
+  SUB          r12, r12, #2
+  SMLATT       r10, r6, r8, r10     @ sum0 = MAC16_16(sum0, x_1, y_1)
+  MOV          r8, r9
+  SMLATB       r11, r6, r9, r11     @ sum1 = MAC16_16(sum1, x_1, y_2)
+celt_pitch_xcorr_edsp_process2_1:
+  LDRH         r6, [r4], #2
+  ADDS         r12, r12, #1
+  @ Stall
+  SMLABB       r10, r6, r8, r10     @ sum0 = MAC16_16(sum0, x_0, y_0)
+  LDRHGT       r7, [r4], #2
+  SMLABT       r11, r6, r8, r11     @ sum1 = MAC16_16(sum1, x_0, y_1)
+  BLE celt_pitch_xcorr_edsp_process2_done
+  LDRH         r9, [r5], #2
+  SMLABT       r10, r7, r8, r10     @ sum0 = MAC16_16(sum0, x_0, y_1)
+  SMLABB       r11, r7, r9, r11     @ sum1 = MAC16_16(sum1, x_0, y_2)
+celt_pitch_xcorr_edsp_process2_done:
+  @ Restore _x
+  SUB          r4, r4, r3, LSL #1
+  @ Restore and advance _y
+  SUB          r5, r5, r3, LSL #1
+  @ maxcorr = max(maxcorr, sum0)
+  CMP          r0, r10
+  ADD          r5, r5, #2
+  MOVLT        r0, r10
+  SUB          r1, r1, #2
+  @ maxcorr = max(maxcorr, sum1)
+  CMP          r0, r11
+  @ xcorr[i] = sum
+  STR          r10, [r2], #4
+  MOVLT        r0, r11
+  STR          r11, [r2], #4
+celt_pitch_xcorr_edsp_process1a:
+  ADDS         r1, r1, #1
+  BLT celt_pitch_xcorr_edsp_done
+  SUBS         r12, r3, #4
+  @ r14 = sum = 0
+  MOV          r14, #0
+  BLT celt_pitch_xcorr_edsp_process1a_loop_done
+  LDR          r6, [r4], #4
+  LDR          r8, [r5], #4
+  LDR          r7, [r4], #4
+  LDR          r9, [r5], #4
+celt_pitch_xcorr_edsp_process1a_loop4:
+  SMLABB       r14, r6, r8, r14     @ sum = MAC16_16(sum, x_0, y_0)
+  SUBS         r12, r12, #4         @ j-=4
+  SMLATT       r14, r6, r8, r14     @ sum = MAC16_16(sum, x_1, y_1)
+  LDRGE        r6, [r4], #4
+  SMLABB       r14, r7, r9, r14     @ sum = MAC16_16(sum, x_2, y_2)
+  LDRGE        r8, [r5], #4
+  SMLATT       r14, r7, r9, r14     @ sum = MAC16_16(sum, x_3, y_3)
+  LDRGE        r7, [r4], #4
+  LDRGE        r9, [r5], #4
+  BGE celt_pitch_xcorr_edsp_process1a_loop4
+celt_pitch_xcorr_edsp_process1a_loop_done:
+  ADDS         r12, r12, #2
+  LDRGE        r6, [r4], #4
+  LDRGE        r8, [r5], #4
+  @ Stall
+  SMLABBGE     r14, r6, r8, r14     @ sum = MAC16_16(sum, x_0, y_0)
+  SUBGE        r12, r12, #2
+  SMLATTGE     r14, r6, r8, r14     @ sum = MAC16_16(sum, x_1, y_1)
+  ADDS         r12, r12, #1
+  LDRHGE       r6, [r4], #2
+  LDRHGE       r8, [r5], #2
+  @ Stall
+  SMLABBGE     r14, r6, r8, r14     @ sum = MAC16_16(sum, *x, *y)
+  @ maxcorr = max(maxcorr, sum)
+  CMP          r0, r14
+  @ xcorr[i] = sum
+  STR          r14, [r2], #4
+  MOVLT        r0, r14
+celt_pitch_xcorr_edsp_done:
+  LDMFD        sp!, {r4-r11, pc}
+       .size celt_pitch_xcorr_edsp, .-celt_pitch_xcorr_edsp  @ ENDP
+
+ .endif
+
+@ END:
+    .section   .note.GNU-stack,"",%progbits
diff --git a/opus/celt/arm/celt_pitch_xcorr_arm.s b/opus/celt/arm/celt_pitch_xcorr_arm.s
new file mode 100644 (file)
index 0000000..6e873af
--- /dev/null
@@ -0,0 +1,551 @@
+; Copyright (c) 2007-2008 CSIRO
+; Copyright (c) 2007-2009 Xiph.Org Foundation
+; Copyright (c) 2013      Parrot
+; Written by Aurélien Zanelli
+;
+; 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.
+;
+; 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.
+
+  AREA  |.text|, CODE, READONLY
+
+  GET    celt/arm/armopts.s
+
+IF OPUS_ARM_MAY_HAVE_EDSP
+  EXPORT celt_pitch_xcorr_edsp
+ENDIF
+
+IF OPUS_ARM_MAY_HAVE_NEON
+  EXPORT celt_pitch_xcorr_neon
+ENDIF
+
+IF OPUS_ARM_MAY_HAVE_NEON
+
+; Compute sum[k]=sum(x[j]*y[j+k],j=0...len-1), k=0...3
+xcorr_kernel_neon PROC
+xcorr_kernel_neon_start
+  ; input:
+  ;   r3     = int         len
+  ;   r4     = opus_val16 *x
+  ;   r5     = opus_val16 *y
+  ;   q0     = opus_val32  sum[4]
+  ; output:
+  ;   q0     = opus_val32  sum[4]
+  ; preserved: r0-r3, r6-r11, d2, q4-q7, q9-q15
+  ; internal usage:
+  ;   r12 = int j
+  ;   d3  = y_3|y_2|y_1|y_0
+  ;   q2  = y_B|y_A|y_9|y_8|y_7|y_6|y_5|y_4
+  ;   q3  = x_7|x_6|x_5|x_4|x_3|x_2|x_1|x_0
+  ;   q8  = scratch
+  ;
+  ; Load y[0...3]
+  ; This requires len>0 to always be valid (which we assert in the C code).
+  VLD1.16      {d5}, [r5]!
+  SUBS         r12, r3, #8
+  BLE xcorr_kernel_neon_process4
+; Process 8 samples at a time.
+; This loop loads one y value more than we actually need. Therefore we have to
+; stop as soon as there are 8 or fewer samples left (instead of 7), to avoid
+; reading past the end of the array.
+xcorr_kernel_neon_process8
+  ; This loop has 19 total instructions (10 cycles to issue, minimum), with
+  ; - 2 cycles of ARM insrtuctions,
+  ; - 10 cycles of load/store/byte permute instructions, and
+  ; - 9 cycles of data processing instructions.
+  ; On a Cortex A8, we dual-issue the maximum amount (9 cycles) between the
+  ; latter two categories, meaning the whole loop should run in 10 cycles per
+  ; iteration, barring cache misses.
+  ;
+  ; Load x[0...7]
+  VLD1.16      {d6, d7}, [r4]!
+  ; Unlike VMOV, VAND is a data processsing instruction (and doesn't get
+  ; assembled to VMOV, like VORR would), so it dual-issues with the prior VLD1.
+  VAND         d3, d5, d5
+  SUBS         r12, r12, #8
+  ; Load y[4...11]
+  VLD1.16      {d4, d5}, [r5]!
+  VMLAL.S16    q0, d3, d6[0]
+  VEXT.16      d16, d3, d4, #1
+  VMLAL.S16    q0, d4, d7[0]
+  VEXT.16      d17, d4, d5, #1
+  VMLAL.S16    q0, d16, d6[1]
+  VEXT.16      d16, d3, d4, #2
+  VMLAL.S16    q0, d17, d7[1]
+  VEXT.16      d17, d4, d5, #2
+  VMLAL.S16    q0, d16, d6[2]
+  VEXT.16      d16, d3, d4, #3
+  VMLAL.S16    q0, d17, d7[2]
+  VEXT.16      d17, d4, d5, #3
+  VMLAL.S16    q0, d16, d6[3]
+  VMLAL.S16    q0, d17, d7[3]
+  BGT xcorr_kernel_neon_process8
+; Process 4 samples here if we have > 4 left (still reading one extra y value).
+xcorr_kernel_neon_process4
+  ADDS         r12, r12, #4
+  BLE xcorr_kernel_neon_process2
+  ; Load x[0...3]
+  VLD1.16      d6, [r4]!
+  ; Use VAND since it's a data processing instruction again.
+  VAND         d4, d5, d5
+  SUB          r12, r12, #4
+  ; Load y[4...7]
+  VLD1.16      d5, [r5]!
+  VMLAL.S16    q0, d4, d6[0]
+  VEXT.16      d16, d4, d5, #1
+  VMLAL.S16    q0, d16, d6[1]
+  VEXT.16      d16, d4, d5, #2
+  VMLAL.S16    q0, d16, d6[2]
+  VEXT.16      d16, d4, d5, #3
+  VMLAL.S16    q0, d16, d6[3]
+; Process 2 samples here if we have > 2 left (still reading one extra y value).
+xcorr_kernel_neon_process2
+  ADDS         r12, r12, #2
+  BLE xcorr_kernel_neon_process1
+  ; Load x[0...1]
+  VLD2.16      {d6[],d7[]}, [r4]!
+  ; Use VAND since it's a data processing instruction again.
+  VAND         d4, d5, d5
+  SUB          r12, r12, #2
+  ; Load y[4...5]
+  VLD1.32      {d5[]}, [r5]!
+  VMLAL.S16    q0, d4, d6
+  VEXT.16      d16, d4, d5, #1
+  ; Replace bottom copy of {y5,y4} in d5 with {y3,y2} from d4, using VSRI
+  ; instead of VEXT, since it's a data-processing instruction.
+  VSRI.64      d5, d4, #32
+  VMLAL.S16    q0, d16, d7
+; Process 1 sample using the extra y value we loaded above.
+xcorr_kernel_neon_process1
+  ; Load next *x
+  VLD1.16      {d6[]}, [r4]!
+  ADDS         r12, r12, #1
+  ; y[0...3] are left in d5 from prior iteration(s) (if any)
+  VMLAL.S16    q0, d5, d6
+  MOVLE        pc, lr
+; Now process 1 last sample, not reading ahead.
+  ; Load last *y
+  VLD1.16      {d4[]}, [r5]!
+  VSRI.64      d4, d5, #16
+  ; Load last *x
+  VLD1.16      {d6[]}, [r4]!
+  VMLAL.S16    q0, d4, d6
+  MOV          pc, lr
+  ENDP
+
+; opus_val32 celt_pitch_xcorr_neon(opus_val16 *_x, opus_val16 *_y,
+;  opus_val32 *xcorr, int len, int max_pitch, int arch)
+celt_pitch_xcorr_neon PROC
+  ; input:
+  ;   r0  = opus_val16 *_x
+  ;   r1  = opus_val16 *_y
+  ;   r2  = opus_val32 *xcorr
+  ;   r3  = int         len
+  ; output:
+  ;   r0  = int         maxcorr
+  ; internal usage:
+  ;   r4  = opus_val16 *x (for xcorr_kernel_neon())
+  ;   r5  = opus_val16 *y (for xcorr_kernel_neon())
+  ;   r6  = int         max_pitch
+  ;   r12 = int         j
+  ;   q15 = int         maxcorr[4] (q15 is not used by xcorr_kernel_neon())
+  ; ignored:
+  ;         int         arch
+  STMFD        sp!, {r4-r6, lr}
+  LDR          r6, [sp, #16]
+  VMOV.S32     q15, #1
+  ; if (max_pitch < 4) goto celt_pitch_xcorr_neon_process4_done
+  SUBS         r6, r6, #4
+  BLT celt_pitch_xcorr_neon_process4_done
+celt_pitch_xcorr_neon_process4
+  ; xcorr_kernel_neon parameters:
+  ; r3 = len, r4 = _x, r5 = _y, q0 = {0, 0, 0, 0}
+  MOV          r4, r0
+  MOV          r5, r1
+  VEOR         q0, q0, q0
+  ; xcorr_kernel_neon only modifies r4, r5, r12, and q0...q3.
+  ; So we don't save/restore any other registers.
+  BL xcorr_kernel_neon_start
+  SUBS         r6, r6, #4
+  VST1.32      {q0}, [r2]!
+  ; _y += 4
+  ADD          r1, r1, #8
+  VMAX.S32     q15, q15, q0
+  ; if (max_pitch < 4) goto celt_pitch_xcorr_neon_process4_done
+  BGE celt_pitch_xcorr_neon_process4
+; We have less than 4 sums left to compute.
+celt_pitch_xcorr_neon_process4_done
+  ADDS         r6, r6, #4
+  ; Reduce maxcorr to a single value
+  VMAX.S32     d30, d30, d31
+  VPMAX.S32    d30, d30, d30
+  ; if (max_pitch <= 0) goto celt_pitch_xcorr_neon_done
+  BLE celt_pitch_xcorr_neon_done
+; Now compute each remaining sum one at a time.
+celt_pitch_xcorr_neon_process_remaining
+  MOV          r4, r0
+  MOV          r5, r1
+  VMOV.I32     q0, #0
+  SUBS         r12, r3, #8
+  BLT celt_pitch_xcorr_neon_process_remaining4
+; Sum terms 8 at a time.
+celt_pitch_xcorr_neon_process_remaining_loop8
+  ; Load x[0...7]
+  VLD1.16      {q1}, [r4]!
+  ; Load y[0...7]
+  VLD1.16      {q2}, [r5]!
+  SUBS         r12, r12, #8
+  VMLAL.S16    q0, d4, d2
+  VMLAL.S16    q0, d5, d3
+  BGE celt_pitch_xcorr_neon_process_remaining_loop8
+; Sum terms 4 at a time.
+celt_pitch_xcorr_neon_process_remaining4
+  ADDS         r12, r12, #4
+  BLT celt_pitch_xcorr_neon_process_remaining4_done
+  ; Load x[0...3]
+  VLD1.16      {d2}, [r4]!
+  ; Load y[0...3]
+  VLD1.16      {d3}, [r5]!
+  SUB          r12, r12, #4
+  VMLAL.S16    q0, d3, d2
+celt_pitch_xcorr_neon_process_remaining4_done
+  ; Reduce the sum to a single value.
+  VADD.S32     d0, d0, d1
+  VPADDL.S32   d0, d0
+  ADDS         r12, r12, #4
+  BLE celt_pitch_xcorr_neon_process_remaining_loop_done
+; Sum terms 1 at a time.
+celt_pitch_xcorr_neon_process_remaining_loop1
+  VLD1.16      {d2[]}, [r4]!
+  VLD1.16      {d3[]}, [r5]!
+  SUBS         r12, r12, #1
+  VMLAL.S16    q0, d2, d3
+  BGT celt_pitch_xcorr_neon_process_remaining_loop1
+celt_pitch_xcorr_neon_process_remaining_loop_done
+  VST1.32      {d0[0]}, [r2]!
+  VMAX.S32     d30, d30, d0
+  SUBS         r6, r6, #1
+  ; _y++
+  ADD          r1, r1, #2
+  ; if (--max_pitch > 0) goto celt_pitch_xcorr_neon_process_remaining
+  BGT celt_pitch_xcorr_neon_process_remaining
+celt_pitch_xcorr_neon_done
+  VMOV.32      r0, d30[0]
+  LDMFD        sp!, {r4-r6, pc}
+  ENDP
+
+ENDIF
+
+IF OPUS_ARM_MAY_HAVE_EDSP
+
+; This will get used on ARMv7 devices without NEON, so it has been optimized
+; to take advantage of dual-issuing where possible.
+xcorr_kernel_edsp PROC
+xcorr_kernel_edsp_start
+  ; input:
+  ;   r3      = int         len
+  ;   r4      = opus_val16 *_x (must be 32-bit aligned)
+  ;   r5      = opus_val16 *_y (must be 32-bit aligned)
+  ;   r6...r9 = opus_val32  sum[4]
+  ; output:
+  ;   r6...r9 = opus_val32  sum[4]
+  ; preserved: r0-r5
+  ; internal usage
+  ;   r2      = int         j
+  ;   r12,r14 = opus_val16  x[4]
+  ;   r10,r11 = opus_val16  y[4]
+  STMFD        sp!, {r2,r4,r5,lr}
+  LDR          r10, [r5], #4      ; Load y[0...1]
+  SUBS         r2, r3, #4         ; j = len-4
+  LDR          r11, [r5], #4      ; Load y[2...3]
+  BLE xcorr_kernel_edsp_process4_done
+  LDR          r12, [r4], #4      ; Load x[0...1]
+  ; Stall
+xcorr_kernel_edsp_process4
+  ; The multiplies must issue from pipeline 0, and can't dual-issue with each
+  ; other. Every other instruction here dual-issues with a multiply, and is
+  ; thus "free". There should be no stalls in the body of the loop.
+  SMLABB       r6, r12, r10, r6   ; sum[0] = MAC16_16(sum[0],x_0,y_0)
+  LDR          r14, [r4], #4      ; Load x[2...3]
+  SMLABT       r7, r12, r10, r7   ; sum[1] = MAC16_16(sum[1],x_0,y_1)
+  SUBS         r2, r2, #4         ; j-=4
+  SMLABB       r8, r12, r11, r8   ; sum[2] = MAC16_16(sum[2],x_0,y_2)
+  SMLABT       r9, r12, r11, r9   ; sum[3] = MAC16_16(sum[3],x_0,y_3)
+  SMLATT       r6, r12, r10, r6   ; sum[0] = MAC16_16(sum[0],x_1,y_1)
+  LDR          r10, [r5], #4      ; Load y[4...5]
+  SMLATB       r7, r12, r11, r7   ; sum[1] = MAC16_16(sum[1],x_1,y_2)
+  SMLATT       r8, r12, r11, r8   ; sum[2] = MAC16_16(sum[2],x_1,y_3)
+  SMLATB       r9, r12, r10, r9   ; sum[3] = MAC16_16(sum[3],x_1,y_4)
+  LDRGT        r12, [r4], #4      ; Load x[0...1]
+  SMLABB       r6, r14, r11, r6   ; sum[0] = MAC16_16(sum[0],x_2,y_2)
+  SMLABT       r7, r14, r11, r7   ; sum[1] = MAC16_16(sum[1],x_2,y_3)
+  SMLABB       r8, r14, r10, r8   ; sum[2] = MAC16_16(sum[2],x_2,y_4)
+  SMLABT       r9, r14, r10, r9   ; sum[3] = MAC16_16(sum[3],x_2,y_5)
+  SMLATT       r6, r14, r11, r6   ; sum[0] = MAC16_16(sum[0],x_3,y_3)
+  LDR          r11, [r5], #4      ; Load y[6...7]
+  SMLATB       r7, r14, r10, r7   ; sum[1] = MAC16_16(sum[1],x_3,y_4)
+  SMLATT       r8, r14, r10, r8   ; sum[2] = MAC16_16(sum[2],x_3,y_5)
+  SMLATB       r9, r14, r11, r9   ; sum[3] = MAC16_16(sum[3],x_3,y_6)
+  BGT xcorr_kernel_edsp_process4
+xcorr_kernel_edsp_process4_done
+  ADDS         r2, r2, #4
+  BLE xcorr_kernel_edsp_done
+  LDRH         r12, [r4], #2      ; r12 = *x++
+  SUBS         r2, r2, #1         ; j--
+  ; Stall
+  SMLABB       r6, r12, r10, r6   ; sum[0] = MAC16_16(sum[0],x,y_0)
+  LDRHGT       r14, [r4], #2      ; r14 = *x++
+  SMLABT       r7, r12, r10, r7   ; sum[1] = MAC16_16(sum[1],x,y_1)
+  SMLABB       r8, r12, r11, r8   ; sum[2] = MAC16_16(sum[2],x,y_2)
+  SMLABT       r9, r12, r11, r9   ; sum[3] = MAC16_16(sum[3],x,y_3)
+  BLE xcorr_kernel_edsp_done
+  SMLABT       r6, r14, r10, r6   ; sum[0] = MAC16_16(sum[0],x,y_1)
+  SUBS         r2, r2, #1         ; j--
+  SMLABB       r7, r14, r11, r7   ; sum[1] = MAC16_16(sum[1],x,y_2)
+  LDRH         r10, [r5], #2      ; r10 = y_4 = *y++
+  SMLABT       r8, r14, r11, r8   ; sum[2] = MAC16_16(sum[2],x,y_3)
+  LDRHGT       r12, [r4], #2      ; r12 = *x++
+  SMLABB       r9, r14, r10, r9   ; sum[3] = MAC16_16(sum[3],x,y_4)
+  BLE xcorr_kernel_edsp_done
+  SMLABB       r6, r12, r11, r6   ; sum[0] = MAC16_16(sum[0],tmp,y_2)
+  CMP          r2, #1             ; j--
+  SMLABT       r7, r12, r11, r7   ; sum[1] = MAC16_16(sum[1],tmp,y_3)
+  LDRH         r2, [r5], #2       ; r2 = y_5 = *y++
+  SMLABB       r8, r12, r10, r8   ; sum[2] = MAC16_16(sum[2],tmp,y_4)
+  LDRHGT       r14, [r4]          ; r14 = *x
+  SMLABB       r9, r12, r2, r9    ; sum[3] = MAC16_16(sum[3],tmp,y_5)
+  BLE xcorr_kernel_edsp_done
+  SMLABT       r6, r14, r11, r6   ; sum[0] = MAC16_16(sum[0],tmp,y_3)
+  LDRH         r11, [r5]          ; r11 = y_6 = *y
+  SMLABB       r7, r14, r10, r7   ; sum[1] = MAC16_16(sum[1],tmp,y_4)
+  SMLABB       r8, r14, r2, r8    ; sum[2] = MAC16_16(sum[2],tmp,y_5)
+  SMLABB       r9, r14, r11, r9   ; sum[3] = MAC16_16(sum[3],tmp,y_6)
+xcorr_kernel_edsp_done
+  LDMFD        sp!, {r2,r4,r5,pc}
+  ENDP
+
+celt_pitch_xcorr_edsp PROC
+  ; input:
+  ;   r0  = opus_val16 *_x (must be 32-bit aligned)
+  ;   r1  = opus_val16 *_y (only needs to be 16-bit aligned)
+  ;   r2  = opus_val32 *xcorr
+  ;   r3  = int         len
+  ; output:
+  ;   r0  = maxcorr
+  ; internal usage
+  ;   r4  = opus_val16 *x
+  ;   r5  = opus_val16 *y
+  ;   r6  = opus_val32  sum0
+  ;   r7  = opus_val32  sum1
+  ;   r8  = opus_val32  sum2
+  ;   r9  = opus_val32  sum3
+  ;   r1  = int         max_pitch
+  ;   r12 = int         j
+  ; ignored:
+  ;         int         arch
+  STMFD        sp!, {r4-r11, lr}
+  MOV          r5, r1
+  LDR          r1, [sp, #36]
+  MOV          r4, r0
+  TST          r5, #3
+  ; maxcorr = 1
+  MOV          r0, #1
+  BEQ          celt_pitch_xcorr_edsp_process1u_done
+; Compute one sum at the start to make y 32-bit aligned.
+  SUBS         r12, r3, #4
+  ; r14 = sum = 0
+  MOV          r14, #0
+  LDRH         r8, [r5], #2
+  BLE celt_pitch_xcorr_edsp_process1u_loop4_done
+  LDR          r6, [r4], #4
+  MOV          r8, r8, LSL #16
+celt_pitch_xcorr_edsp_process1u_loop4
+  LDR          r9, [r5], #4
+  SMLABT       r14, r6, r8, r14     ; sum = MAC16_16(sum, x_0, y_0)
+  LDR          r7, [r4], #4
+  SMLATB       r14, r6, r9, r14     ; sum = MAC16_16(sum, x_1, y_1)
+  LDR          r8, [r5], #4
+  SMLABT       r14, r7, r9, r14     ; sum = MAC16_16(sum, x_2, y_2)
+  SUBS         r12, r12, #4         ; j-=4
+  SMLATB       r14, r7, r8, r14     ; sum = MAC16_16(sum, x_3, y_3)
+  LDRGT        r6, [r4], #4
+  BGT celt_pitch_xcorr_edsp_process1u_loop4
+  MOV          r8, r8, LSR #16
+celt_pitch_xcorr_edsp_process1u_loop4_done
+  ADDS         r12, r12, #4
+celt_pitch_xcorr_edsp_process1u_loop1
+  LDRHGE       r6, [r4], #2
+  ; Stall
+  SMLABBGE     r14, r6, r8, r14    ; sum = MAC16_16(sum, *x, *y)
+  SUBSGE       r12, r12, #1
+  LDRHGT       r8, [r5], #2
+  BGT celt_pitch_xcorr_edsp_process1u_loop1
+  ; Restore _x
+  SUB          r4, r4, r3, LSL #1
+  ; Restore and advance _y
+  SUB          r5, r5, r3, LSL #1
+  ; maxcorr = max(maxcorr, sum)
+  CMP          r0, r14
+  ADD          r5, r5, #2
+  MOVLT        r0, r14
+  SUBS         r1, r1, #1
+  ; xcorr[i] = sum
+  STR          r14, [r2], #4
+  BLE celt_pitch_xcorr_edsp_done
+celt_pitch_xcorr_edsp_process1u_done
+  ; if (max_pitch < 4) goto celt_pitch_xcorr_edsp_process2
+  SUBS         r1, r1, #4
+  BLT celt_pitch_xcorr_edsp_process2
+celt_pitch_xcorr_edsp_process4
+  ; xcorr_kernel_edsp parameters:
+  ; r3 = len, r4 = _x, r5 = _y, r6...r9 = sum[4] = {0, 0, 0, 0}
+  MOV          r6, #0
+  MOV          r7, #0
+  MOV          r8, #0
+  MOV          r9, #0
+  BL xcorr_kernel_edsp_start  ; xcorr_kernel_edsp(_x, _y+i, xcorr+i, len)
+  ; maxcorr = max(maxcorr, sum0, sum1, sum2, sum3)
+  CMP          r0, r6
+  ; _y+=4
+  ADD          r5, r5, #8
+  MOVLT        r0, r6
+  CMP          r0, r7
+  MOVLT        r0, r7
+  CMP          r0, r8
+  MOVLT        r0, r8
+  CMP          r0, r9
+  MOVLT        r0, r9
+  STMIA        r2!, {r6-r9}
+  SUBS         r1, r1, #4
+  BGE celt_pitch_xcorr_edsp_process4
+celt_pitch_xcorr_edsp_process2
+  ADDS         r1, r1, #2
+  BLT celt_pitch_xcorr_edsp_process1a
+  SUBS         r12, r3, #4
+  ; {r10, r11} = {sum0, sum1} = {0, 0}
+  MOV          r10, #0
+  MOV          r11, #0
+  LDR          r8, [r5], #4
+  BLE celt_pitch_xcorr_edsp_process2_loop_done
+  LDR          r6, [r4], #4
+  LDR          r9, [r5], #4
+celt_pitch_xcorr_edsp_process2_loop4
+  SMLABB       r10, r6, r8, r10     ; sum0 = MAC16_16(sum0, x_0, y_0)
+  LDR          r7, [r4], #4
+  SMLABT       r11, r6, r8, r11     ; sum1 = MAC16_16(sum1, x_0, y_1)
+  SUBS         r12, r12, #4         ; j-=4
+  SMLATT       r10, r6, r8, r10     ; sum0 = MAC16_16(sum0, x_1, y_1)
+  LDR          r8, [r5], #4
+  SMLATB       r11, r6, r9, r11     ; sum1 = MAC16_16(sum1, x_1, y_2)
+  LDRGT        r6, [r4], #4
+  SMLABB       r10, r7, r9, r10     ; sum0 = MAC16_16(sum0, x_2, y_2)
+  SMLABT       r11, r7, r9, r11     ; sum1 = MAC16_16(sum1, x_2, y_3)
+  SMLATT       r10, r7, r9, r10     ; sum0 = MAC16_16(sum0, x_3, y_3)
+  LDRGT        r9, [r5], #4
+  SMLATB       r11, r7, r8, r11     ; sum1 = MAC16_16(sum1, x_3, y_4)
+  BGT celt_pitch_xcorr_edsp_process2_loop4
+celt_pitch_xcorr_edsp_process2_loop_done
+  ADDS         r12, r12, #2
+  BLE  celt_pitch_xcorr_edsp_process2_1
+  LDR          r6, [r4], #4
+  ; Stall
+  SMLABB       r10, r6, r8, r10     ; sum0 = MAC16_16(sum0, x_0, y_0)
+  LDR          r9, [r5], #4
+  SMLABT       r11, r6, r8, r11     ; sum1 = MAC16_16(sum1, x_0, y_1)
+  SUB          r12, r12, #2
+  SMLATT       r10, r6, r8, r10     ; sum0 = MAC16_16(sum0, x_1, y_1)
+  MOV          r8, r9
+  SMLATB       r11, r6, r9, r11     ; sum1 = MAC16_16(sum1, x_1, y_2)
+celt_pitch_xcorr_edsp_process2_1
+  LDRH         r6, [r4], #2
+  ADDS         r12, r12, #1
+  ; Stall
+  SMLABB       r10, r6, r8, r10     ; sum0 = MAC16_16(sum0, x_0, y_0)
+  LDRHGT       r7, [r4], #2
+  SMLABT       r11, r6, r8, r11     ; sum1 = MAC16_16(sum1, x_0, y_1)
+  BLE celt_pitch_xcorr_edsp_process2_done
+  LDRH         r9, [r5], #2
+  SMLABT       r10, r7, r8, r10     ; sum0 = MAC16_16(sum0, x_0, y_1)
+  SMLABB       r11, r7, r9, r11     ; sum1 = MAC16_16(sum1, x_0, y_2)
+celt_pitch_xcorr_edsp_process2_done
+  ; Restore _x
+  SUB          r4, r4, r3, LSL #1
+  ; Restore and advance _y
+  SUB          r5, r5, r3, LSL #1
+  ; maxcorr = max(maxcorr, sum0)
+  CMP          r0, r10
+  ADD          r5, r5, #2
+  MOVLT        r0, r10
+  SUB          r1, r1, #2
+  ; maxcorr = max(maxcorr, sum1)
+  CMP          r0, r11
+  ; xcorr[i] = sum
+  STR          r10, [r2], #4
+  MOVLT        r0, r11
+  STR          r11, [r2], #4
+celt_pitch_xcorr_edsp_process1a
+  ADDS         r1, r1, #1
+  BLT celt_pitch_xcorr_edsp_done
+  SUBS         r12, r3, #4
+  ; r14 = sum = 0
+  MOV          r14, #0
+  BLT celt_pitch_xcorr_edsp_process1a_loop_done
+  LDR          r6, [r4], #4
+  LDR          r8, [r5], #4
+  LDR          r7, [r4], #4
+  LDR          r9, [r5], #4
+celt_pitch_xcorr_edsp_process1a_loop4
+  SMLABB       r14, r6, r8, r14     ; sum = MAC16_16(sum, x_0, y_0)
+  SUBS         r12, r12, #4         ; j-=4
+  SMLATT       r14, r6, r8, r14     ; sum = MAC16_16(sum, x_1, y_1)
+  LDRGE        r6, [r4], #4
+  SMLABB       r14, r7, r9, r14     ; sum = MAC16_16(sum, x_2, y_2)
+  LDRGE        r8, [r5], #4
+  SMLATT       r14, r7, r9, r14     ; sum = MAC16_16(sum, x_3, y_3)
+  LDRGE        r7, [r4], #4
+  LDRGE        r9, [r5], #4
+  BGE celt_pitch_xcorr_edsp_process1a_loop4
+celt_pitch_xcorr_edsp_process1a_loop_done
+  ADDS         r12, r12, #2
+  LDRGE        r6, [r4], #4
+  LDRGE        r8, [r5], #4
+  ; Stall
+  SMLABBGE     r14, r6, r8, r14     ; sum = MAC16_16(sum, x_0, y_0)
+  SUBGE        r12, r12, #2
+  SMLATTGE     r14, r6, r8, r14     ; sum = MAC16_16(sum, x_1, y_1)
+  ADDS         r12, r12, #1
+  LDRHGE       r6, [r4], #2
+  LDRHGE       r8, [r5], #2
+  ; Stall
+  SMLABBGE     r14, r6, r8, r14     ; sum = MAC16_16(sum, *x, *y)
+  ; maxcorr = max(maxcorr, sum)
+  CMP          r0, r14
+  ; xcorr[i] = sum
+  STR          r14, [r2], #4
+  MOVLT        r0, r14
+celt_pitch_xcorr_edsp_done
+  LDMFD        sp!, {r4-r11, pc}
+  ENDP
+
+ENDIF
+
+END
diff --git a/opus/celt/arm/fft_arm.h b/opus/celt/arm/fft_arm.h
new file mode 100644 (file)
index 0000000..0b78175
--- /dev/null
@@ -0,0 +1,71 @@
+/* Copyright (c) 2015 Xiph.Org Foundation
+   Written by Viswanath Puttagunta */
+/**
+   @file fft_arm.h
+   @brief ARM Neon Intrinsic optimizations for fft using NE10 library
+ */
+
+/*
+   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.
+
+   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.
+*/
+
+
+#if !defined(FFT_ARM_H)
+#define FFT_ARM_H
+
+#include "kiss_fft.h"
+
+#if defined(HAVE_ARM_NE10)
+
+int opus_fft_alloc_arm_neon(kiss_fft_state *st);
+void opus_fft_free_arm_neon(kiss_fft_state *st);
+
+void opus_fft_neon(const kiss_fft_state *st,
+                   const kiss_fft_cpx *fin,
+                   kiss_fft_cpx *fout);
+
+void opus_ifft_neon(const kiss_fft_state *st,
+                    const kiss_fft_cpx *fin,
+                    kiss_fft_cpx *fout);
+
+#if !defined(OPUS_HAVE_RTCD)
+#define OVERRIDE_OPUS_FFT (1)
+
+#define opus_fft_alloc_arch(_st, arch) \
+   ((void)(arch), opus_fft_alloc_arm_neon(_st))
+
+#define opus_fft_free_arch(_st, arch) \
+   ((void)(arch), opus_fft_free_arm_neon(_st))
+
+#define opus_fft(_st, _fin, _fout, arch) \
+   ((void)(arch), opus_fft_neon(_st, _fin, _fout))
+
+#define opus_ifft(_st, _fin, _fout, arch) \
+   ((void)(arch), opus_ifft_neon(_st, _fin, _fout))
+
+#endif /* OPUS_HAVE_RTCD */
+
+#endif /* HAVE_ARM_NE10 */
+
+#endif
diff --git a/opus/celt/arm/fixed_arm64.h b/opus/celt/arm/fixed_arm64.h
new file mode 100644 (file)
index 0000000..c6fbd3d
--- /dev/null
@@ -0,0 +1,35 @@
+/* Copyright (C) 2015 Vidyo */
+/*
+   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.
+
+   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 FIXED_ARM64_H
+#define FIXED_ARM64_H
+
+#include <arm_neon.h>
+
+#undef SIG2WORD16
+#define SIG2WORD16(x) (vqmovns_s32(PSHR32((x), SIG_SHIFT)))
+
+#endif
diff --git a/opus/celt/arm/fixed_armv4.h b/opus/celt/arm/fixed_armv4.h
new file mode 100644 (file)
index 0000000..d84888a
--- /dev/null
@@ -0,0 +1,80 @@
+/* Copyright (C) 2013 Xiph.Org Foundation and contributors */
+/*
+   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.
+
+   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 FIXED_ARMv4_H
+#define FIXED_ARMv4_H
+
+/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
+#undef MULT16_32_Q16
+static OPUS_INLINE opus_val32 MULT16_32_Q16_armv4(opus_val16 a, opus_val32 b)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+      "#MULT16_32_Q16\n\t"
+      "smull %0, %1, %2, %3\n\t"
+      : "=&r"(rd_lo), "=&r"(rd_hi)
+      : "%r"(b),"r"(SHL32(a,16))
+  );
+  return rd_hi;
+}
+#define MULT16_32_Q16(a, b) (MULT16_32_Q16_armv4(a, b))
+
+
+/** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
+#undef MULT16_32_Q15
+static OPUS_INLINE opus_val32 MULT16_32_Q15_armv4(opus_val16 a, opus_val32 b)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+      "#MULT16_32_Q15\n\t"
+      "smull %0, %1, %2, %3\n\t"
+      : "=&r"(rd_lo), "=&r"(rd_hi)
+      : "%r"(b), "r"(SHL32(a,16))
+  );
+  /*We intentionally don't OR in the high bit of rd_lo for speed.*/
+  return SHL32(rd_hi,1);
+}
+#define MULT16_32_Q15(a, b) (MULT16_32_Q15_armv4(a, b))
+
+
+/** 16x32 multiply, followed by a 15-bit shift right and 32-bit add.
+    b must fit in 31 bits.
+    Result fits in 32 bits. */
+#undef MAC16_32_Q15
+#define MAC16_32_Q15(c, a, b) ADD32(c, MULT16_32_Q15(a, b))
+
+/** 16x32 multiply, followed by a 16-bit shift right and 32-bit add.
+    Result fits in 32 bits. */
+#undef MAC16_32_Q16
+#define MAC16_32_Q16(c, a, b) ADD32(c, MULT16_32_Q16(a, b))
+
+/** 32x32 multiplication, followed by a 31-bit shift right. Results fits in 32 bits */
+#undef MULT32_32_Q31
+#define MULT32_32_Q31(a,b) (opus_val32)((((opus_int64)(a)) * ((opus_int64)(b)))>>31)
+
+#endif
diff --git a/opus/celt/arm/fixed_armv5e.h b/opus/celt/arm/fixed_armv5e.h
new file mode 100644 (file)
index 0000000..6bf73cb
--- /dev/null
@@ -0,0 +1,151 @@
+/* Copyright (C) 2007-2009 Xiph.Org Foundation
+   Copyright (C) 2003-2008 Jean-Marc Valin
+   Copyright (C) 2007-2008 CSIRO
+   Copyright (C) 2013      Parrot */
+/*
+   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.
+
+   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 FIXED_ARMv5E_H
+#define FIXED_ARMv5E_H
+
+#include "fixed_armv4.h"
+
+/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
+#undef MULT16_32_Q16
+static OPUS_INLINE opus_val32 MULT16_32_Q16_armv5e(opus_val16 a, opus_val32 b)
+{
+  int res;
+  __asm__(
+      "#MULT16_32_Q16\n\t"
+      "smulwb %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(b),"r"(a)
+  );
+  return res;
+}
+#define MULT16_32_Q16(a, b) (MULT16_32_Q16_armv5e(a, b))
+
+
+/** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
+#undef MULT16_32_Q15
+static OPUS_INLINE opus_val32 MULT16_32_Q15_armv5e(opus_val16 a, opus_val32 b)
+{
+  int res;
+  __asm__(
+      "#MULT16_32_Q15\n\t"
+      "smulwb %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(b), "r"(a)
+  );
+  return SHL32(res,1);
+}
+#define MULT16_32_Q15(a, b) (MULT16_32_Q15_armv5e(a, b))
+
+
+/** 16x32 multiply, followed by a 15-bit shift right and 32-bit add.
+    b must fit in 31 bits.
+    Result fits in 32 bits. */
+#undef MAC16_32_Q15
+static OPUS_INLINE opus_val32 MAC16_32_Q15_armv5e(opus_val32 c, opus_val16 a,
+ opus_val32 b)
+{
+  int res;
+  __asm__(
+      "#MAC16_32_Q15\n\t"
+      "smlawb %0, %1, %2, %3;\n"
+      : "=r"(res)
+      : "r"(SHL32(b,1)), "r"(a), "r"(c)
+  );
+  return res;
+}
+#define MAC16_32_Q15(c, a, b) (MAC16_32_Q15_armv5e(c, a, b))
+
+/** 16x32 multiply, followed by a 16-bit shift right and 32-bit add.
+    Result fits in 32 bits. */
+#undef MAC16_32_Q16
+static OPUS_INLINE opus_val32 MAC16_32_Q16_armv5e(opus_val32 c, opus_val16 a,
+ opus_val32 b)
+{
+  int res;
+  __asm__(
+      "#MAC16_32_Q16\n\t"
+      "smlawb %0, %1, %2, %3;\n"
+      : "=r"(res)
+      : "r"(b), "r"(a), "r"(c)
+  );
+  return res;
+}
+#define MAC16_32_Q16(c, a, b) (MAC16_32_Q16_armv5e(c, a, b))
+
+/** 16x16 multiply-add where the result fits in 32 bits */
+#undef MAC16_16
+static OPUS_INLINE opus_val32 MAC16_16_armv5e(opus_val32 c, opus_val16 a,
+ opus_val16 b)
+{
+  int res;
+  __asm__(
+      "#MAC16_16\n\t"
+      "smlabb %0, %1, %2, %3;\n"
+      : "=r"(res)
+      : "r"(a), "r"(b), "r"(c)
+  );
+  return res;
+}
+#define MAC16_16(c, a, b) (MAC16_16_armv5e(c, a, b))
+
+/** 16x16 multiplication where the result fits in 32 bits */
+#undef MULT16_16
+static OPUS_INLINE opus_val32 MULT16_16_armv5e(opus_val16 a, opus_val16 b)
+{
+  int res;
+  __asm__(
+      "#MULT16_16\n\t"
+      "smulbb %0, %1, %2;\n"
+      : "=r"(res)
+      : "r"(a), "r"(b)
+  );
+  return res;
+}
+#define MULT16_16(a, b) (MULT16_16_armv5e(a, b))
+
+#ifdef OPUS_ARM_INLINE_MEDIA
+
+#undef SIG2WORD16
+static OPUS_INLINE opus_val16 SIG2WORD16_armv6(opus_val32 x)
+{
+   celt_sig res;
+   __asm__(
+       "#SIG2WORD16\n\t"
+       "ssat %0, #16, %1, ASR #12\n\t"
+       : "=r"(res)
+       : "r"(x+2048)
+   );
+   return EXTRACT16(res);
+}
+#define SIG2WORD16(x) (SIG2WORD16_armv6(x))
+
+#endif /* OPUS_ARM_INLINE_MEDIA */
+
+#endif
diff --git a/opus/celt/arm/kiss_fft_armv4.h b/opus/celt/arm/kiss_fft_armv4.h
new file mode 100644 (file)
index 0000000..e4faad6
--- /dev/null
@@ -0,0 +1,121 @@
+/*Copyright (c) 2013, Xiph.Org Foundation and contributors.
+
+  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.
+
+  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_ARMv4_H
+#define KISS_FFT_ARMv4_H
+
+#if !defined(KISS_FFT_GUTS_H)
+#error "This file should only be included from _kiss_fft_guts.h"
+#endif
+
+#ifdef FIXED_POINT
+
+#undef C_MUL
+#define C_MUL(m,a,b) \
+    do{ \
+       int br__; \
+       int bi__; \
+       int tt__; \
+        __asm__ __volatile__( \
+            "#C_MUL\n\t" \
+            "ldrsh %[br], [%[bp], #0]\n\t" \
+            "ldm %[ap], {r0,r1}\n\t" \
+            "ldrsh %[bi], [%[bp], #2]\n\t" \
+            "smull %[tt], %[mi], r1, %[br]\n\t" \
+            "smlal %[tt], %[mi], r0, %[bi]\n\t" \
+            "rsb %[bi], %[bi], #0\n\t" \
+            "smull %[br], %[mr], r0, %[br]\n\t" \
+            "mov %[tt], %[tt], lsr #15\n\t" \
+            "smlal %[br], %[mr], r1, %[bi]\n\t" \
+            "orr %[mi], %[tt], %[mi], lsl #17\n\t" \
+            "mov %[br], %[br], lsr #15\n\t" \
+            "orr %[mr], %[br], %[mr], lsl #17\n\t" \
+            : [mr]"=r"((m).r), [mi]"=r"((m).i), \
+              [br]"=&r"(br__), [bi]"=r"(bi__), [tt]"=r"(tt__) \
+            : [ap]"r"(&(a)), [bp]"r"(&(b)) \
+            : "r0", "r1" \
+        ); \
+    } \
+    while(0)
+
+#undef C_MUL4
+#define C_MUL4(m,a,b) \
+    do{ \
+       int br__; \
+       int bi__; \
+       int tt__; \
+        __asm__ __volatile__( \
+            "#C_MUL4\n\t" \
+            "ldrsh %[br], [%[bp], #0]\n\t" \
+            "ldm %[ap], {r0,r1}\n\t" \
+            "ldrsh %[bi], [%[bp], #2]\n\t" \
+            "smull %[tt], %[mi], r1, %[br]\n\t" \
+            "smlal %[tt], %[mi], r0, %[bi]\n\t" \
+            "rsb %[bi], %[bi], #0\n\t" \
+            "smull %[br], %[mr], r0, %[br]\n\t" \
+            "mov %[tt], %[tt], lsr #17\n\t" \
+            "smlal %[br], %[mr], r1, %[bi]\n\t" \
+            "orr %[mi], %[tt], %[mi], lsl #15\n\t" \
+            "mov %[br], %[br], lsr #17\n\t" \
+            "orr %[mr], %[br], %[mr], lsl #15\n\t" \
+            : [mr]"=r"((m).r), [mi]"=r"((m).i), \
+              [br]"=&r"(br__), [bi]"=r"(bi__), [tt]"=r"(tt__) \
+            : [ap]"r"(&(a)), [bp]"r"(&(b)) \
+            : "r0", "r1" \
+        ); \
+    } \
+    while(0)
+
+#undef C_MULC
+#define C_MULC(m,a,b) \
+    do{ \
+       int br__; \
+       int bi__; \
+       int tt__; \
+        __asm__ __volatile__( \
+            "#C_MULC\n\t" \
+            "ldrsh %[br], [%[bp], #0]\n\t" \
+            "ldm %[ap], {r0,r1}\n\t" \
+            "ldrsh %[bi], [%[bp], #2]\n\t" \
+            "smull %[tt], %[mr], r0, %[br]\n\t" \
+            "smlal %[tt], %[mr], r1, %[bi]\n\t" \
+            "rsb %[bi], %[bi], #0\n\t" \
+            "smull %[br], %[mi], r1, %[br]\n\t" \
+            "mov %[tt], %[tt], lsr #15\n\t" \
+            "smlal %[br], %[mi], r0, %[bi]\n\t" \
+            "orr %[mr], %[tt], %[mr], lsl #17\n\t" \
+            "mov %[br], %[br], lsr #15\n\t" \
+            "orr %[mi], %[br], %[mi], lsl #17\n\t" \
+            : [mr]"=r"((m).r), [mi]"=r"((m).i), \
+              [br]"=&r"(br__), [bi]"=r"(bi__), [tt]"=r"(tt__) \
+            : [ap]"r"(&(a)), [bp]"r"(&(b)) \
+            : "r0", "r1" \
+        ); \
+    } \
+    while(0)
+
+#endif /* FIXED_POINT */
+
+#endif /* KISS_FFT_ARMv4_H */
diff --git a/opus/celt/arm/kiss_fft_armv5e.h b/opus/celt/arm/kiss_fft_armv5e.h
new file mode 100644 (file)
index 0000000..9eca183
--- /dev/null
@@ -0,0 +1,118 @@
+/*Copyright (c) 2013, Xiph.Org Foundation and contributors.
+
+  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.
+
+  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_ARMv5E_H
+#define KISS_FFT_ARMv5E_H
+
+#if !defined(KISS_FFT_GUTS_H)
+#error "This file should only be included from _kiss_fft_guts.h"
+#endif
+
+#ifdef FIXED_POINT
+
+#if defined(__thumb__)||defined(__thumb2__)
+#define LDRD_CONS "Q"
+#else
+#define LDRD_CONS "Uq"
+#endif
+
+#undef C_MUL
+#define C_MUL(m,a,b) \
+    do{ \
+        int mr1__; \
+        int mr2__; \
+        int mi__; \
+        long long aval__; \
+        int bval__; \
+        __asm__( \
+            "#C_MUL\n\t" \
+            "ldrd %[aval], %H[aval], %[ap]\n\t" \
+            "ldr %[bval], %[bp]\n\t" \
+            "smulwb %[mi], %H[aval], %[bval]\n\t" \
+            "smulwb %[mr1], %[aval], %[bval]\n\t" \
+            "smulwt %[mr2], %H[aval], %[bval]\n\t" \
+            "smlawt %[mi], %[aval], %[bval], %[mi]\n\t" \
+            : [mr1]"=r"(mr1__), [mr2]"=r"(mr2__), [mi]"=r"(mi__), \
+              [aval]"=&r"(aval__), [bval]"=r"(bval__) \
+            : [ap]LDRD_CONS(a), [bp]"m"(b) \
+        ); \
+        (m).r = SHL32(SUB32(mr1__, mr2__), 1); \
+        (m).i = SHL32(mi__, 1); \
+    } \
+    while(0)
+
+#undef C_MUL4
+#define C_MUL4(m,a,b) \
+    do{ \
+        int mr1__; \
+        int mr2__; \
+        int mi__; \
+        long long aval__; \
+        int bval__; \
+        __asm__( \
+            "#C_MUL4\n\t" \
+            "ldrd %[aval], %H[aval], %[ap]\n\t" \
+            "ldr %[bval], %[bp]\n\t" \
+            "smulwb %[mi], %H[aval], %[bval]\n\t" \
+            "smulwb %[mr1], %[aval], %[bval]\n\t" \
+            "smulwt %[mr2], %H[aval], %[bval]\n\t" \
+            "smlawt %[mi], %[aval], %[bval], %[mi]\n\t" \
+            : [mr1]"=r"(mr1__), [mr2]"=r"(mr2__), [mi]"=r"(mi__), \
+              [aval]"=&r"(aval__), [bval]"=r"(bval__) \
+            : [ap]LDRD_CONS(a), [bp]"m"(b) \
+        ); \
+        (m).r = SHR32(SUB32(mr1__, mr2__), 1); \
+        (m).i = SHR32(mi__, 1); \
+    } \
+    while(0)
+
+#undef C_MULC
+#define C_MULC(m,a,b) \
+    do{ \
+        int mr__; \
+        int mi1__; \
+        int mi2__; \
+        long long aval__; \
+        int bval__; \
+        __asm__( \
+            "#C_MULC\n\t" \
+            "ldrd %[aval], %H[aval], %[ap]\n\t" \
+            "ldr %[bval], %[bp]\n\t" \
+            "smulwb %[mr], %[aval], %[bval]\n\t" \
+            "smulwb %[mi1], %H[aval], %[bval]\n\t" \
+            "smulwt %[mi2], %[aval], %[bval]\n\t" \
+            "smlawt %[mr], %H[aval], %[bval], %[mr]\n\t" \
+            : [mr]"=r"(mr__), [mi1]"=r"(mi1__), [mi2]"=r"(mi2__), \
+              [aval]"=&r"(aval__), [bval]"=r"(bval__) \
+            : [ap]LDRD_CONS(a), [bp]"m"(b) \
+        ); \
+        (m).r = SHL32(mr__, 1); \
+        (m).i = SHL32(SUB32(mi1__, mi2__), 1); \
+    } \
+    while(0)
+
+#endif /* FIXED_POINT */
+
+#endif /* KISS_FFT_GUTS_H */
diff --git a/opus/celt/arm/mdct_arm.h b/opus/celt/arm/mdct_arm.h
new file mode 100644 (file)
index 0000000..14200ba
--- /dev/null
@@ -0,0 +1,59 @@
+/* Copyright (c) 2015 Xiph.Org Foundation
+   Written by Viswanath Puttagunta */
+/**
+   @file arm_mdct.h
+   @brief ARM Neon Intrinsic optimizations for mdct using NE10 library
+ */
+
+/*
+   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.
+
+   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.
+*/
+
+#if !defined(MDCT_ARM_H)
+#define MDCT_ARM_H
+
+#include "mdct.h"
+
+#if defined(HAVE_ARM_NE10)
+/** Compute a forward MDCT and scale by 4/N, trashes the input array */
+void clt_mdct_forward_neon(const mdct_lookup *l, kiss_fft_scalar *in,
+                           kiss_fft_scalar * OPUS_RESTRICT out,
+                           const opus_val16 *window, int overlap,
+                           int shift, int stride, int arch);
+
+void clt_mdct_backward_neon(const mdct_lookup *l, kiss_fft_scalar *in,
+                            kiss_fft_scalar * OPUS_RESTRICT out,
+                            const opus_val16 *window, int overlap,
+                            int shift, int stride, int arch);
+
+#if !defined(OPUS_HAVE_RTCD)
+#define OVERRIDE_OPUS_MDCT (1)
+#define clt_mdct_forward(_l, _in, _out, _window, _int, _shift, _stride, _arch) \
+      clt_mdct_forward_neon(_l, _in, _out, _window, _int, _shift, _stride, _arch)
+#define clt_mdct_backward(_l, _in, _out, _window, _int, _shift, _stride, _arch) \
+      clt_mdct_backward_neon(_l, _in, _out, _window, _int, _shift, _stride, _arch)
+#endif /* OPUS_HAVE_RTCD */
+#endif /* HAVE_ARM_NE10 */
+
+#endif
diff --git a/opus/celt/arm/pitch_arm.h b/opus/celt/arm/pitch_arm.h
new file mode 100644 (file)
index 0000000..4ee13bd
--- /dev/null
@@ -0,0 +1,156 @@
+/* Copyright (c) 2010 Xiph.Org Foundation
+ * Copyright (c) 2013 Parrot */
+/*
+   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.
+
+   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.
+*/
+
+#if !defined(PITCH_ARM_H)
+# define PITCH_ARM_H
+
+# include "armcpu.h"
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+opus_val32 celt_inner_prod_neon(const opus_val16 *x, const opus_val16 *y, int N);
+void dual_inner_prod_neon(const opus_val16 *x, const opus_val16 *y01,
+        const opus_val16 *y02, int N, opus_val32 *xy1, opus_val32 *xy2);
+
+#  if !defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_PRESUME_NEON)
+#   define OVERRIDE_CELT_INNER_PROD (1)
+#   define OVERRIDE_DUAL_INNER_PROD (1)
+#   define celt_inner_prod(x, y, N, arch) ((void)(arch), PRESUME_NEON(celt_inner_prod)(x, y, N))
+#   define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) ((void)(arch), PRESUME_NEON(dual_inner_prod)(x, y01, y02, N, xy1, xy2))
+#  endif
+# endif
+
+# if !defined(OVERRIDE_CELT_INNER_PROD)
+#  if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern opus_val32 (*const CELT_INNER_PROD_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *x, const opus_val16 *y, int N);
+#   define OVERRIDE_CELT_INNER_PROD (1)
+#   define celt_inner_prod(x, y, N, arch) ((*CELT_INNER_PROD_IMPL[(arch)&OPUS_ARCHMASK])(x, y, N))
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#   define OVERRIDE_CELT_INNER_PROD (1)
+#   define celt_inner_prod(x, y, N, arch) ((void)(arch), celt_inner_prod_neon(x, y, N))
+#  endif
+# endif
+
+# if !defined(OVERRIDE_DUAL_INNER_PROD)
+#  if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern void (*const DUAL_INNER_PROD_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *x,
+        const opus_val16 *y01, const opus_val16 *y02, int N, opus_val32 *xy1, opus_val32 *xy2);
+#   define OVERRIDE_DUAL_INNER_PROD (1)
+#   define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) ((*DUAL_INNER_PROD_IMPL[(arch)&OPUS_ARCHMASK])(x, y01, y02, N, xy1, xy2))
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#   define OVERRIDE_DUAL_INNER_PROD (1)
+#   define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) ((void)(arch), dual_inner_prod_neon(x, y01, y02, N, xy1, xy2))
+#  endif
+# endif
+
+# if defined(FIXED_POINT)
+
+#  if defined(OPUS_ARM_MAY_HAVE_NEON)
+opus_val32 celt_pitch_xcorr_neon(const opus_val16 *_x, const opus_val16 *_y,
+    opus_val32 *xcorr, int len, int max_pitch, int arch);
+#  endif
+
+#  if defined(OPUS_ARM_MAY_HAVE_MEDIA)
+#   define celt_pitch_xcorr_media MAY_HAVE_EDSP(celt_pitch_xcorr)
+#  endif
+
+#  if defined(OPUS_ARM_MAY_HAVE_EDSP)
+opus_val32 celt_pitch_xcorr_edsp(const opus_val16 *_x, const opus_val16 *_y,
+    opus_val32 *xcorr, int len, int max_pitch, int arch);
+#  endif
+
+#  if defined(OPUS_HAVE_RTCD) && \
+    ((defined(OPUS_ARM_MAY_HAVE_NEON) && !defined(OPUS_ARM_PRESUME_NEON)) || \
+     (defined(OPUS_ARM_MAY_HAVE_MEDIA) && !defined(OPUS_ARM_PRESUME_MEDIA)) || \
+     (defined(OPUS_ARM_MAY_HAVE_EDSP) && !defined(OPUS_ARM_PRESUME_EDSP)))
+extern opus_val32
+(*const CELT_PITCH_XCORR_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *,
+      const opus_val16 *, opus_val32 *, int, int, int);
+#   define OVERRIDE_PITCH_XCORR (1)
+#   define celt_pitch_xcorr (*CELT_PITCH_XCORR_IMPL[(arch)&OPUS_ARCHMASK])
+
+#  elif defined(OPUS_ARM_PRESUME_EDSP) || \
+    defined(OPUS_ARM_PRESUME_MEDIA) || \
+    defined(OPUS_ARM_PRESUME_NEON)
+#   define OVERRIDE_PITCH_XCORR (1)
+#   define celt_pitch_xcorr (PRESUME_NEON(celt_pitch_xcorr))
+
+#  endif
+
+#  if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+void xcorr_kernel_neon_fixed(
+                    const opus_val16 *x,
+                    const opus_val16 *y,
+                    opus_val32       sum[4],
+                    int              len);
+#  endif
+
+#  if defined(OPUS_HAVE_RTCD) && \
+    (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+
+extern void (*const XCORR_KERNEL_IMPL[OPUS_ARCHMASK + 1])(
+                    const opus_val16 *x,
+                    const opus_val16 *y,
+                    opus_val32       sum[4],
+                    int              len);
+
+#   define OVERRIDE_XCORR_KERNEL (1)
+#   define xcorr_kernel(x, y, sum, len, arch) \
+     ((*XCORR_KERNEL_IMPL[(arch) & OPUS_ARCHMASK])(x, y, sum, len))
+
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#   define OVERRIDE_XCORR_KERNEL (1)
+#   define xcorr_kernel(x, y, sum, len, arch) \
+      ((void)arch, xcorr_kernel_neon_fixed(x, y, sum, len))
+
+#  endif
+
+#else /* Start !FIXED_POINT */
+/* Float case */
+#if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+void celt_pitch_xcorr_float_neon(const opus_val16 *_x, const opus_val16 *_y,
+                                 opus_val32 *xcorr, int len, int max_pitch, int arch);
+#endif
+
+#  if defined(OPUS_HAVE_RTCD) && \
+    (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern void
+(*const CELT_PITCH_XCORR_IMPL[OPUS_ARCHMASK+1])(const opus_val16 *,
+      const opus_val16 *, opus_val32 *, int, int, int);
+
+#  define OVERRIDE_PITCH_XCORR (1)
+#  define celt_pitch_xcorr (*CELT_PITCH_XCORR_IMPL[(arch)&OPUS_ARCHMASK])
+
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+
+#   define OVERRIDE_PITCH_XCORR (1)
+#   define celt_pitch_xcorr celt_pitch_xcorr_float_neon
+
+#  endif
+
+#endif /* end !FIXED_POINT */
+
+#endif
diff --git a/opus/celt/arm/pitch_neon_intr.c b/opus/celt/arm/pitch_neon_intr.c
new file mode 100644 (file)
index 0000000..1ac38c4
--- /dev/null
@@ -0,0 +1,290 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#include "pitch.h"
+
+#ifdef FIXED_POINT
+
+opus_val32 celt_inner_prod_neon(const opus_val16 *x, const opus_val16 *y, int N)
+{
+    int i;
+    opus_val32 xy;
+    int16x8_t x_s16x8, y_s16x8;
+    int32x4_t xy_s32x4 = vdupq_n_s32(0);
+    int64x2_t xy_s64x2;
+    int64x1_t xy_s64x1;
+
+    for (i = 0; i < N - 7; i += 8) {
+        x_s16x8  = vld1q_s16(&x[i]);
+        y_s16x8  = vld1q_s16(&y[i]);
+        xy_s32x4 = vmlal_s16(xy_s32x4, vget_low_s16 (x_s16x8), vget_low_s16 (y_s16x8));
+        xy_s32x4 = vmlal_s16(xy_s32x4, vget_high_s16(x_s16x8), vget_high_s16(y_s16x8));
+    }
+
+    if (N - i >= 4) {
+        const int16x4_t x_s16x4 = vld1_s16(&x[i]);
+        const int16x4_t y_s16x4 = vld1_s16(&y[i]);
+        xy_s32x4 = vmlal_s16(xy_s32x4, x_s16x4, y_s16x4);
+        i += 4;
+    }
+
+    xy_s64x2 = vpaddlq_s32(xy_s32x4);
+    xy_s64x1 = vadd_s64(vget_low_s64(xy_s64x2), vget_high_s64(xy_s64x2));
+    xy       = vget_lane_s32(vreinterpret_s32_s64(xy_s64x1), 0);
+
+    for (; i < N; i++) {
+        xy = MAC16_16(xy, x[i], y[i]);
+    }
+
+#ifdef OPUS_CHECK_ASM
+    celt_assert(celt_inner_prod_c(x, y, N) == xy);
+#endif
+
+    return xy;
+}
+
+void dual_inner_prod_neon(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+        int N, opus_val32 *xy1, opus_val32 *xy2)
+{
+    int i;
+    opus_val32 xy01, xy02;
+    int16x8_t x_s16x8, y01_s16x8, y02_s16x8;
+    int32x4_t xy01_s32x4 = vdupq_n_s32(0);
+    int32x4_t xy02_s32x4 = vdupq_n_s32(0);
+    int64x2_t xy01_s64x2, xy02_s64x2;
+    int64x1_t xy01_s64x1, xy02_s64x1;
+
+    for (i = 0; i < N - 7; i += 8) {
+        x_s16x8    = vld1q_s16(&x[i]);
+        y01_s16x8  = vld1q_s16(&y01[i]);
+        y02_s16x8  = vld1q_s16(&y02[i]);
+        xy01_s32x4 = vmlal_s16(xy01_s32x4, vget_low_s16 (x_s16x8), vget_low_s16 (y01_s16x8));
+        xy02_s32x4 = vmlal_s16(xy02_s32x4, vget_low_s16 (x_s16x8), vget_low_s16 (y02_s16x8));
+        xy01_s32x4 = vmlal_s16(xy01_s32x4, vget_high_s16(x_s16x8), vget_high_s16(y01_s16x8));
+        xy02_s32x4 = vmlal_s16(xy02_s32x4, vget_high_s16(x_s16x8), vget_high_s16(y02_s16x8));
+    }
+
+    if (N - i >= 4) {
+        const int16x4_t x_s16x4   = vld1_s16(&x[i]);
+        const int16x4_t y01_s16x4 = vld1_s16(&y01[i]);
+        const int16x4_t y02_s16x4 = vld1_s16(&y02[i]);
+        xy01_s32x4 = vmlal_s16(xy01_s32x4, x_s16x4, y01_s16x4);
+        xy02_s32x4 = vmlal_s16(xy02_s32x4, x_s16x4, y02_s16x4);
+        i += 4;
+    }
+
+    xy01_s64x2 = vpaddlq_s32(xy01_s32x4);
+    xy02_s64x2 = vpaddlq_s32(xy02_s32x4);
+    xy01_s64x1 = vadd_s64(vget_low_s64(xy01_s64x2), vget_high_s64(xy01_s64x2));
+    xy02_s64x1 = vadd_s64(vget_low_s64(xy02_s64x2), vget_high_s64(xy02_s64x2));
+    xy01       = vget_lane_s32(vreinterpret_s32_s64(xy01_s64x1), 0);
+    xy02       = vget_lane_s32(vreinterpret_s32_s64(xy02_s64x1), 0);
+
+    for (; i < N; i++) {
+        xy01 = MAC16_16(xy01, x[i], y01[i]);
+        xy02 = MAC16_16(xy02, x[i], y02[i]);
+    }
+    *xy1 = xy01;
+    *xy2 = xy02;
+
+#ifdef OPUS_CHECK_ASM
+    {
+        opus_val32 xy1_c, xy2_c;
+        dual_inner_prod_c(x, y01, y02, N, &xy1_c, &xy2_c);
+        celt_assert(xy1_c == *xy1);
+        celt_assert(xy2_c == *xy2);
+    }
+#endif
+}
+
+#else /* !FIXED_POINT */
+
+/* ========================================================================== */
+
+#ifdef OPUS_CHECK_ASM
+
+/* This part of code simulates floating-point NEON operations. */
+
+/* celt_inner_prod_neon_float_c_simulation() simulates the floating-point   */
+/* operations of celt_inner_prod_neon(), and both functions should have bit */
+/* exact output.                                                            */
+static opus_val32 celt_inner_prod_neon_float_c_simulation(const opus_val16 *x, const opus_val16 *y, int N)
+{
+   int i;
+   opus_val32 xy, xy0 = 0, xy1 = 0, xy2 = 0, xy3 = 0;
+   for (i = 0; i < N - 3; i += 4) {
+      xy0 = MAC16_16(xy0, x[i + 0], y[i + 0]);
+      xy1 = MAC16_16(xy1, x[i + 1], y[i + 1]);
+      xy2 = MAC16_16(xy2, x[i + 2], y[i + 2]);
+      xy3 = MAC16_16(xy3, x[i + 3], y[i + 3]);
+   }
+   xy0 += xy2;
+   xy1 += xy3;
+   xy = xy0 + xy1;
+   for (; i < N; i++) {
+      xy = MAC16_16(xy, x[i], y[i]);
+   }
+   return xy;
+}
+
+/* dual_inner_prod_neon_float_c_simulation() simulates the floating-point   */
+/* operations of dual_inner_prod_neon(), and both functions should have bit */
+/* exact output.                                                            */
+static void dual_inner_prod_neon_float_c_simulation(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+      int N, opus_val32 *xy1, opus_val32 *xy2)
+{
+   int i;
+   opus_val32 xy01, xy02, xy01_0 = 0, xy01_1 = 0, xy01_2 = 0, xy01_3 = 0, xy02_0 = 0, xy02_1 = 0, xy02_2 = 0, xy02_3 = 0;
+   for (i = 0; i < N - 3; i += 4) {
+      xy01_0 = MAC16_16(xy01_0, x[i + 0], y01[i + 0]);
+      xy01_1 = MAC16_16(xy01_1, x[i + 1], y01[i + 1]);
+      xy01_2 = MAC16_16(xy01_2, x[i + 2], y01[i + 2]);
+      xy01_3 = MAC16_16(xy01_3, x[i + 3], y01[i + 3]);
+      xy02_0 = MAC16_16(xy02_0, x[i + 0], y02[i + 0]);
+      xy02_1 = MAC16_16(xy02_1, x[i + 1], y02[i + 1]);
+      xy02_2 = MAC16_16(xy02_2, x[i + 2], y02[i + 2]);
+      xy02_3 = MAC16_16(xy02_3, x[i + 3], y02[i + 3]);
+   }
+   xy01_0 += xy01_2;
+   xy02_0 += xy02_2;
+   xy01_1 += xy01_3;
+   xy02_1 += xy02_3;
+   xy01 = xy01_0 + xy01_1;
+   xy02 = xy02_0 + xy02_1;
+   for (; i < N; i++) {
+      xy01 = MAC16_16(xy01, x[i], y01[i]);
+      xy02 = MAC16_16(xy02, x[i], y02[i]);
+   }
+   *xy1 = xy01;
+   *xy2 = xy02;
+}
+
+#endif /* OPUS_CHECK_ASM */
+
+/* ========================================================================== */
+
+opus_val32 celt_inner_prod_neon(const opus_val16 *x, const opus_val16 *y, int N)
+{
+    int i;
+    opus_val32 xy;
+    float32x4_t xy_f32x4 = vdupq_n_f32(0);
+    float32x2_t xy_f32x2;
+
+    for (i = 0; i < N - 7; i += 8) {
+        float32x4_t x_f32x4, y_f32x4;
+        x_f32x4  = vld1q_f32(&x[i]);
+        y_f32x4  = vld1q_f32(&y[i]);
+        xy_f32x4 = vmlaq_f32(xy_f32x4, x_f32x4, y_f32x4);
+        x_f32x4  = vld1q_f32(&x[i + 4]);
+        y_f32x4  = vld1q_f32(&y[i + 4]);
+        xy_f32x4 = vmlaq_f32(xy_f32x4, x_f32x4, y_f32x4);
+    }
+
+    if (N - i >= 4) {
+        const float32x4_t x_f32x4 = vld1q_f32(&x[i]);
+        const float32x4_t y_f32x4 = vld1q_f32(&y[i]);
+        xy_f32x4 = vmlaq_f32(xy_f32x4, x_f32x4, y_f32x4);
+        i += 4;
+    }
+
+    xy_f32x2 = vadd_f32(vget_low_f32(xy_f32x4), vget_high_f32(xy_f32x4));
+    xy_f32x2 = vpadd_f32(xy_f32x2, xy_f32x2);
+    xy       = vget_lane_f32(xy_f32x2, 0);
+
+    for (; i < N; i++) {
+        xy = MAC16_16(xy, x[i], y[i]);
+    }
+
+#ifdef OPUS_CHECK_ASM
+    celt_assert(ABS32(celt_inner_prod_neon_float_c_simulation(x, y, N) - xy) <= VERY_SMALL);
+#endif
+
+    return xy;
+}
+
+void dual_inner_prod_neon(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+        int N, opus_val32 *xy1, opus_val32 *xy2)
+{
+    int i;
+    opus_val32 xy01, xy02;
+    float32x4_t xy01_f32x4 = vdupq_n_f32(0);
+    float32x4_t xy02_f32x4 = vdupq_n_f32(0);
+    float32x2_t xy01_f32x2, xy02_f32x2;
+
+    for (i = 0; i < N - 7; i += 8) {
+        float32x4_t x_f32x4, y01_f32x4, y02_f32x4;
+        x_f32x4    = vld1q_f32(&x[i]);
+        y01_f32x4  = vld1q_f32(&y01[i]);
+        y02_f32x4  = vld1q_f32(&y02[i]);
+        xy01_f32x4 = vmlaq_f32(xy01_f32x4, x_f32x4, y01_f32x4);
+        xy02_f32x4 = vmlaq_f32(xy02_f32x4, x_f32x4, y02_f32x4);
+        x_f32x4    = vld1q_f32(&x[i + 4]);
+        y01_f32x4  = vld1q_f32(&y01[i + 4]);
+        y02_f32x4  = vld1q_f32(&y02[i + 4]);
+        xy01_f32x4 = vmlaq_f32(xy01_f32x4, x_f32x4, y01_f32x4);
+        xy02_f32x4 = vmlaq_f32(xy02_f32x4, x_f32x4, y02_f32x4);
+    }
+
+    if (N - i >= 4) {
+        const float32x4_t x_f32x4   = vld1q_f32(&x[i]);
+        const float32x4_t y01_f32x4 = vld1q_f32(&y01[i]);
+        const float32x4_t y02_f32x4 = vld1q_f32(&y02[i]);
+        xy01_f32x4 = vmlaq_f32(xy01_f32x4, x_f32x4, y01_f32x4);
+        xy02_f32x4 = vmlaq_f32(xy02_f32x4, x_f32x4, y02_f32x4);
+        i += 4;
+    }
+
+    xy01_f32x2 = vadd_f32(vget_low_f32(xy01_f32x4), vget_high_f32(xy01_f32x4));
+    xy02_f32x2 = vadd_f32(vget_low_f32(xy02_f32x4), vget_high_f32(xy02_f32x4));
+    xy01_f32x2 = vpadd_f32(xy01_f32x2, xy01_f32x2);
+    xy02_f32x2 = vpadd_f32(xy02_f32x2, xy02_f32x2);
+    xy01       = vget_lane_f32(xy01_f32x2, 0);
+    xy02       = vget_lane_f32(xy02_f32x2, 0);
+
+    for (; i < N; i++) {
+        xy01 = MAC16_16(xy01, x[i], y01[i]);
+        xy02 = MAC16_16(xy02, x[i], y02[i]);
+    }
+    *xy1 = xy01;
+    *xy2 = xy02;
+
+#ifdef OPUS_CHECK_ASM
+    {
+        opus_val32 xy1_c, xy2_c;
+        dual_inner_prod_neon_float_c_simulation(x, y01, y02, N, &xy1_c, &xy2_c);
+        celt_assert(ABS32(xy1_c - *xy1) <= VERY_SMALL);
+        celt_assert(ABS32(xy2_c - *xy2) <= VERY_SMALL);
+    }
+#endif
+}
+
+#endif /* FIXED_POINT */
diff --git a/opus/celt/bands.c b/opus/celt/bands.c
new file mode 100644 (file)
index 0000000..3b1f5cf
--- /dev/null
@@ -0,0 +1,1669 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2008-2009 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#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"
+#include "quant_bands.h"
+#include "pitch.h"
+
+int hysteresis_decision(opus_val16 val, const opus_val16 *thresholds, const opus_val16 *hysteresis, int N, int prev)
+{
+   int i;
+   for (i=0;i<N;i++)
+   {
+      if (val < thresholds[i])
+         break;
+   }
+   if (i>prev && val < thresholds[prev]+hysteresis[prev])
+      i=prev;
+   if (i<prev && val > thresholds[prev-1]-hysteresis[prev-1])
+      i=prev;
+   return i;
+}
+
+opus_uint32 celt_lcg_rand(opus_uint32 seed)
+{
+   return 1664525 * seed + 1013904223;
+}
+
+/* This is a cos() approximation designed to be bit-exact on any platform. Bit exactness
+   with this approximation is important because it has an impact on the bit allocation */
+opus_int16 bitexact_cos(opus_int16 x)
+{
+   opus_int32 tmp;
+   opus_int16 x2;
+   tmp = (4096+((opus_int32)(x)*(x)))>>13;
+   celt_assert(tmp<=32767);
+   x2 = tmp;
+   x2 = (32767-x2) + FRAC_MUL16(x2, (-7651 + FRAC_MUL16(x2, (8277 + FRAC_MUL16(-626, x2)))));
+   celt_assert(x2<=32766);
+   return 1+x2;
+}
+
+int bitexact_log2tan(int isin,int icos)
+{
+   int lc;
+   int ls;
+   lc=EC_ILOG(icos);
+   ls=EC_ILOG(isin);
+   icos<<=15-lc;
+   isin<<=15-ls;
+   return (ls-lc)*(1<<11)
+         +FRAC_MUL16(isin, FRAC_MUL16(isin, -2597) + 7932)
+         -FRAC_MUL16(icos, FRAC_MUL16(icos, -2597) + 7932);
+}
+
+#ifdef FIXED_POINT
+/* Compute the amplitude (sqrt energy) in each of the bands */
+void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int LM, int arch)
+{
+   int i, c, N;
+   const opus_int16 *eBands = m->eBands;
+   (void)arch;
+   N = m->shortMdctSize<<LM;
+   c=0; do {
+      for (i=0;i<end;i++)
+      {
+         int j;
+         opus_val32 maxval=0;
+         opus_val32 sum = 0;
+
+         maxval = celt_maxabs32(&X[c*N+(eBands[i]<<LM)], (eBands[i+1]-eBands[i])<<LM);
+         if (maxval > 0)
+         {
+            int shift = celt_ilog2(maxval) - 14 + (((m->logN[i]>>BITRES)+LM+1)>>1);
+            j=eBands[i]<<LM;
+            if (shift>0)
+            {
+               do {
+                  sum = MAC16_16(sum, EXTRACT16(SHR32(X[j+c*N],shift)),
+                        EXTRACT16(SHR32(X[j+c*N],shift)));
+               } while (++j<eBands[i+1]<<LM);
+            } else {
+               do {
+                  sum = MAC16_16(sum, EXTRACT16(SHL32(X[j+c*N],-shift)),
+                        EXTRACT16(SHL32(X[j+c*N],-shift)));
+               } while (++j<eBands[i+1]<<LM);
+            }
+            /* We're adding one here to ensure the normalized band isn't larger than unity norm */
+            bandE[i+c*m->nbEBands] = EPSILON+VSHR32(EXTEND32(celt_sqrt(sum)),-shift);
+         } else {
+            bandE[i+c*m->nbEBands] = EPSILON;
+         }
+         /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
+      }
+   } while (++c<C);
+   /*printf ("\n");*/
+}
+
+/* Normalise each band such that the energy is one. */
+void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
+{
+   int i, c, N;
+   const opus_int16 *eBands = m->eBands;
+   N = M*m->shortMdctSize;
+   c=0; do {
+      i=0; do {
+         opus_val16 g;
+         int j,shift;
+         opus_val16 E;
+         shift = celt_zlog2(bandE[i+c*m->nbEBands])-13;
+         E = VSHR32(bandE[i+c*m->nbEBands], shift);
+         g = EXTRACT16(celt_rcp(SHL32(E,3)));
+         j=M*eBands[i]; do {
+            X[j+c*N] = MULT16_16_Q15(VSHR32(freq[j+c*N],shift-1),g);
+         } while (++j<M*eBands[i+1]);
+      } while (++i<end);
+   } while (++c<C);
+}
+
+#else /* FIXED_POINT */
+/* Compute the amplitude (sqrt energy) in each of the bands */
+void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int LM, int arch)
+{
+   int i, c, N;
+   const opus_int16 *eBands = m->eBands;
+   N = m->shortMdctSize<<LM;
+   c=0; do {
+      for (i=0;i<end;i++)
+      {
+         opus_val32 sum;
+         sum = 1e-27f + celt_inner_prod(&X[c*N+(eBands[i]<<LM)], &X[c*N+(eBands[i]<<LM)], (eBands[i+1]-eBands[i])<<LM, arch);
+         bandE[i+c*m->nbEBands] = celt_sqrt(sum);
+         /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
+      }
+   } while (++c<C);
+   /*printf ("\n");*/
+}
+
+/* Normalise each band such that the energy is one. */
+void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
+{
+   int i, c, N;
+   const opus_int16 *eBands = m->eBands;
+   N = M*m->shortMdctSize;
+   c=0; do {
+      for (i=0;i<end;i++)
+      {
+         int j;
+         opus_val16 g = 1.f/(1e-27f+bandE[i+c*m->nbEBands]);
+         for (j=M*eBands[i];j<M*eBands[i+1];j++)
+            X[j+c*N] = freq[j+c*N]*g;
+      }
+   } while (++c<C);
+}
+
+#endif /* FIXED_POINT */
+
+/* De-normalise the energy to produce the synthesis from the unit-energy bands */
+void denormalise_bands(const CELTMode *m, const celt_norm * OPUS_RESTRICT X,
+      celt_sig * OPUS_RESTRICT freq, const opus_val16 *bandLogE, int start,
+      int end, int M, int downsample, int silence)
+{
+   int i, N;
+   int bound;
+   celt_sig * OPUS_RESTRICT f;
+   const celt_norm * OPUS_RESTRICT x;
+   const opus_int16 *eBands = m->eBands;
+   N = M*m->shortMdctSize;
+   bound = M*eBands[end];
+   if (downsample!=1)
+      bound = IMIN(bound, N/downsample);
+   if (silence)
+   {
+      bound = 0;
+      start = end = 0;
+   }
+   f = freq;
+   x = X+M*eBands[start];
+   for (i=0;i<M*eBands[start];i++)
+      *f++ = 0;
+   for (i=start;i<end;i++)
+   {
+      int j, band_end;
+      opus_val16 g;
+      opus_val16 lg;
+#ifdef FIXED_POINT
+      int shift;
+#endif
+      j=M*eBands[i];
+      band_end = M*eBands[i+1];
+      lg = SATURATE16(ADD32(bandLogE[i], SHL32((opus_val32)eMeans[i],6)));
+#ifndef FIXED_POINT
+      g = celt_exp2(MIN32(32.f, lg));
+#else
+      /* Handle the integer part of the log energy */
+      shift = 16-(lg>>DB_SHIFT);
+      if (shift>31)
+      {
+         shift=0;
+         g=0;
+      } else {
+         /* Handle the fractional part. */
+         g = celt_exp2_frac(lg&((1<<DB_SHIFT)-1));
+      }
+      /* Handle extreme gains with negative shift. */
+      if (shift<0)
+      {
+         /* For shift <= -2 and g > 16384 we'd be likely to overflow, so we're
+            capping the gain here, which is equivalent to a cap of 18 on lg.
+            This shouldn't trigger unless the bitstream is already corrupted. */
+         if (shift <= -2)
+         {
+            g = 16384;
+            shift = -2;
+         }
+         do {
+            *f++ = SHL32(MULT16_16(*x++, g), -shift);
+         } while (++j<band_end);
+      } else
+#endif
+         /* Be careful of the fixed-point "else" just above when changing this code */
+         do {
+            *f++ = SHR32(MULT16_16(*x++, g), shift);
+         } while (++j<band_end);
+   }
+   celt_assert(start <= end);
+   OPUS_CLEAR(&freq[bound], N-bound);
+}
+
+/* This prevents energy collapse for transients with multiple short MDCTs */
+void anti_collapse(const CELTMode *m, celt_norm *X_, unsigned char *collapse_masks, int LM, int C, int size,
+      int start, int end, const opus_val16 *logE, const opus_val16 *prev1logE,
+      const opus_val16 *prev2logE, const int *pulses, opus_uint32 seed, int arch)
+{
+   int c, i, j, k;
+   for (i=start;i<end;i++)
+   {
+      int N0;
+      opus_val16 thresh, sqrt_1;
+      int depth;
+#ifdef FIXED_POINT
+      int shift;
+      opus_val32 thresh32;
+#endif
+
+      N0 = m->eBands[i+1]-m->eBands[i];
+      /* depth in 1/8 bits */
+      celt_assert(pulses[i]>=0);
+      depth = celt_udiv(1+pulses[i], (m->eBands[i+1]-m->eBands[i]))>>LM;
+
+#ifdef FIXED_POINT
+      thresh32 = SHR32(celt_exp2(-SHL16(depth, 10-BITRES)),1);
+      thresh = MULT16_32_Q15(QCONST16(0.5f, 15), MIN32(32767,thresh32));
+      {
+         opus_val32 t;
+         t = N0<<LM;
+         shift = celt_ilog2(t)>>1;
+         t = SHL32(t, (7-shift)<<1);
+         sqrt_1 = celt_rsqrt_norm(t);
+      }
+#else
+      thresh = .5f*celt_exp2(-.125f*depth);
+      sqrt_1 = celt_rsqrt(N0<<LM);
+#endif
+
+      c=0; do
+      {
+         celt_norm *X;
+         opus_val16 prev1;
+         opus_val16 prev2;
+         opus_val32 Ediff;
+         opus_val16 r;
+         int renormalize=0;
+         prev1 = prev1logE[c*m->nbEBands+i];
+         prev2 = prev2logE[c*m->nbEBands+i];
+         if (C==1)
+         {
+            prev1 = MAX16(prev1,prev1logE[m->nbEBands+i]);
+            prev2 = MAX16(prev2,prev2logE[m->nbEBands+i]);
+         }
+         Ediff = EXTEND32(logE[c*m->nbEBands+i])-EXTEND32(MIN16(prev1,prev2));
+         Ediff = MAX32(0, Ediff);
+
+#ifdef FIXED_POINT
+         if (Ediff < 16384)
+         {
+            opus_val32 r32 = SHR32(celt_exp2(-EXTRACT16(Ediff)),1);
+            r = 2*MIN16(16383,r32);
+         } else {
+            r = 0;
+         }
+         if (LM==3)
+            r = MULT16_16_Q14(23170, MIN32(23169, r));
+         r = SHR16(MIN16(thresh, r),1);
+         r = SHR32(MULT16_16_Q15(sqrt_1, r),shift);
+#else
+         /* r needs to be multiplied by 2 or 2*sqrt(2) depending on LM because
+            short blocks don't have the same energy as long */
+         r = 2.f*celt_exp2(-Ediff);
+         if (LM==3)
+            r *= 1.41421356f;
+         r = MIN16(thresh, r);
+         r = r*sqrt_1;
+#endif
+         X = X_+c*size+(m->eBands[i]<<LM);
+         for (k=0;k<1<<LM;k++)
+         {
+            /* Detect collapse */
+            if (!(collapse_masks[i*C+c]&1<<k))
+            {
+               /* Fill with noise */
+               for (j=0;j<N0;j++)
+               {
+                  seed = celt_lcg_rand(seed);
+                  X[(j<<LM)+k] = (seed&0x8000 ? r : -r);
+               }
+               renormalize = 1;
+            }
+         }
+         /* We just added some energy, so we need to renormalise */
+         if (renormalize)
+            renormalise_vector(X, N0<<LM, Q15ONE, arch);
+      } while (++c<C);
+   }
+}
+
+/* Compute the weights to use for optimizing normalized distortion across
+   channels. We use the amplitude to weight square distortion, which means
+   that we use the square root of the value we would have been using if we
+   wanted to minimize the MSE in the non-normalized domain. This roughly
+   corresponds to some quick-and-dirty perceptual experiments I ran to
+   measure inter-aural masking (there doesn't seem to be any published data
+   on the topic). */
+static void compute_channel_weights(celt_ener Ex, celt_ener Ey, opus_val16 w[2])
+{
+   celt_ener minE;
+#if FIXED_POINT
+   int shift;
+#endif
+   minE = MIN32(Ex, Ey);
+   /* Adjustment to make the weights a bit more conservative. */
+   Ex = ADD32(Ex, minE/3);
+   Ey = ADD32(Ey, minE/3);
+#if FIXED_POINT
+   shift = celt_ilog2(EPSILON+MAX32(Ex, Ey))-14;
+#endif
+   w[0] = VSHR32(Ex, shift);
+   w[1] = VSHR32(Ey, shift);
+}
+
+static void intensity_stereo(const CELTMode *m, celt_norm * OPUS_RESTRICT X, const celt_norm * OPUS_RESTRICT Y, const celt_ener *bandE, int bandID, int N)
+{
+   int i = bandID;
+   int j;
+   opus_val16 a1, a2;
+   opus_val16 left, right;
+   opus_val16 norm;
+#ifdef FIXED_POINT
+   int shift = celt_zlog2(MAX32(bandE[i], bandE[i+m->nbEBands]))-13;
+#endif
+   left = VSHR32(bandE[i],shift);
+   right = VSHR32(bandE[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 = DIV32_16(SHL32(EXTEND32(right),14),norm);
+   for (j=0;j<N;j++)
+   {
+      celt_norm r, l;
+      l = X[j];
+      r = Y[j];
+      X[j] = EXTRACT16(SHR32(MAC16_16(MULT16_16(a1, l), a2, r), 14));
+      /* Side is not encoded, no need to calculate */
+   }
+}
+
+static void stereo_split(celt_norm * OPUS_RESTRICT X, celt_norm * OPUS_RESTRICT Y, int N)
+{
+   int j;
+   for (j=0;j<N;j++)
+   {
+      opus_val32 r, l;
+      l = MULT16_16(QCONST16(.70710678f, 15), X[j]);
+      r = MULT16_16(QCONST16(.70710678f, 15), Y[j]);
+      X[j] = EXTRACT16(SHR32(ADD32(l, r), 15));
+      Y[j] = EXTRACT16(SHR32(SUB32(r, l), 15));
+   }
+}
+
+static void stereo_merge(celt_norm * OPUS_RESTRICT X, celt_norm * OPUS_RESTRICT Y, opus_val16 mid, int N, int arch)
+{
+   int j;
+   opus_val32 xp=0, side=0;
+   opus_val32 El, Er;
+   opus_val16 mid2;
+#ifdef FIXED_POINT
+   int kl, kr;
+#endif
+   opus_val32 t, lgain, rgain;
+
+   /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
+   dual_inner_prod(Y, X, Y, N, &xp, &side, arch);
+   /* Compensating for the mid normalization */
+   xp = MULT16_32_Q15(mid, xp);
+   /* mid and side are in Q15, not Q14 like X and Y */
+   mid2 = SHR16(mid, 1);
+   El = MULT16_16(mid2, mid2) + side - 2*xp;
+   Er = MULT16_16(mid2, mid2) + side + 2*xp;
+   if (Er < QCONST32(6e-4f, 28) || El < QCONST32(6e-4f, 28))
+   {
+      OPUS_COPY(Y, X, N);
+      return;
+   }
+
+#ifdef FIXED_POINT
+   kl = celt_ilog2(El)>>1;
+   kr = celt_ilog2(Er)>>1;
+#endif
+   t = VSHR32(El, (kl-7)<<1);
+   lgain = celt_rsqrt_norm(t);
+   t = VSHR32(Er, (kr-7)<<1);
+   rgain = celt_rsqrt_norm(t);
+
+#ifdef FIXED_POINT
+   if (kl < 7)
+      kl = 7;
+   if (kr < 7)
+      kr = 7;
+#endif
+
+   for (j=0;j<N;j++)
+   {
+      celt_norm r, l;
+      /* Apply mid scaling (side is already scaled) */
+      l = MULT16_16_P15(mid, X[j]);
+      r = Y[j];
+      X[j] = EXTRACT16(PSHR32(MULT16_16(lgain, SUB16(l,r)), kl+1));
+      Y[j] = EXTRACT16(PSHR32(MULT16_16(rgain, ADD16(l,r)), kr+1));
+   }
+}
+
+/* Decide whether we should spread the pulses in the current frame */
+int spreading_decision(const CELTMode *m, const celt_norm *X, int *average,
+      int last_decision, int *hf_average, int *tapset_decision, int update_hf,
+      int end, int C, int M)
+{
+   int i, c, N0;
+   int sum = 0, nbBands=0;
+   const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
+   int decision;
+   int hf_sum=0;
+
+   celt_assert(end>0);
+
+   N0 = M*m->shortMdctSize;
+
+   if (M*(eBands[end]-eBands[end-1]) <= 8)
+      return SPREAD_NONE;
+   c=0; do {
+      for (i=0;i<end;i++)
+      {
+         int j, N, tmp=0;
+         int tcount[3] = {0,0,0};
+         const celt_norm * OPUS_RESTRICT x = X+M*eBands[i]+c*N0;
+         N = M*(eBands[i+1]-eBands[i]);
+         if (N<=8)
+            continue;
+         /* Compute rough CDF of |x[j]| */
+         for (j=0;j<N;j++)
+         {
+            opus_val32 x2N; /* Q13 */
+
+            x2N = MULT16_16(MULT16_16_Q15(x[j], x[j]), N);
+            if (x2N < QCONST16(0.25f,13))
+               tcount[0]++;
+            if (x2N < QCONST16(0.0625f,13))
+               tcount[1]++;
+            if (x2N < QCONST16(0.015625f,13))
+               tcount[2]++;
+         }
+
+         /* Only include four last bands (8 kHz and up) */
+         if (i>m->nbEBands-4)
+            hf_sum += celt_udiv(32*(tcount[1]+tcount[0]), N);
+         tmp = (2*tcount[2] >= N) + (2*tcount[1] >= N) + (2*tcount[0] >= N);
+         sum += tmp*256;
+         nbBands++;
+      }
+   } while (++c<C);
+
+   if (update_hf)
+   {
+      if (hf_sum)
+         hf_sum = celt_udiv(hf_sum, C*(4-m->nbEBands+end));
+      *hf_average = (*hf_average+hf_sum)>>1;
+      hf_sum = *hf_average;
+      if (*tapset_decision==2)
+         hf_sum += 4;
+      else if (*tapset_decision==0)
+         hf_sum -= 4;
+      if (hf_sum > 22)
+         *tapset_decision=2;
+      else if (hf_sum > 18)
+         *tapset_decision=1;
+      else
+         *tapset_decision=0;
+   }
+   /*printf("%d %d %d\n", hf_sum, *hf_average, *tapset_decision);*/
+   celt_assert(nbBands>0); /* end has to be non-zero */
+   celt_assert(sum>=0);
+   sum = celt_udiv(sum, nbBands);
+   /* Recursive averaging */
+   sum = (sum+*average)>>1;
+   *average = sum;
+   /* Hysteresis */
+   sum = (3*sum + (((3-last_decision)<<7) + 64) + 2)>>2;
+   if (sum < 80)
+   {
+      decision = SPREAD_AGGRESSIVE;
+   } else if (sum < 256)
+   {
+      decision = SPREAD_NORMAL;
+   } else if (sum < 384)
+   {
+      decision = SPREAD_LIGHT;
+   } else {
+      decision = SPREAD_NONE;
+   }
+#ifdef FUZZING
+   decision = rand()&0x3;
+   *tapset_decision=rand()%3;
+#endif
+   return decision;
+}
+
+/* Indexing table for converting from natural Hadamard to ordery Hadamard
+   This is essentially a bit-reversed Gray, on top of which we've added
+   an inversion of the order because we want the DC at the end rather than
+   the beginning. The lines are for N=2, 4, 8, 16 */
+static const int ordery_table[] = {
+       1,  0,
+       3,  0,  2,  1,
+       7,  0,  4,  3,  6,  1,  5,  2,
+      15,  0,  8,  7, 12,  3, 11,  4, 14,  1,  9,  6, 13,  2, 10,  5,
+};
+
+static void deinterleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
+{
+   int i,j;
+   VARDECL(celt_norm, tmp);
+   int N;
+   SAVE_STACK;
+   N = N0*stride;
+   ALLOC(tmp, N, celt_norm);
+   celt_assert(stride>0);
+   if (hadamard)
+   {
+      const int *ordery = ordery_table+stride-2;
+      for (i=0;i<stride;i++)
+      {
+         for (j=0;j<N0;j++)
+            tmp[ordery[i]*N0+j] = X[j*stride+i];
+      }
+   } else {
+      for (i=0;i<stride;i++)
+         for (j=0;j<N0;j++)
+            tmp[i*N0+j] = X[j*stride+i];
+   }
+   OPUS_COPY(X, tmp, N);
+   RESTORE_STACK;
+}
+
+static void interleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
+{
+   int i,j;
+   VARDECL(celt_norm, tmp);
+   int N;
+   SAVE_STACK;
+   N = N0*stride;
+   ALLOC(tmp, N, celt_norm);
+   if (hadamard)
+   {
+      const int *ordery = ordery_table+stride-2;
+      for (i=0;i<stride;i++)
+         for (j=0;j<N0;j++)
+            tmp[j*stride+i] = X[ordery[i]*N0+j];
+   } else {
+      for (i=0;i<stride;i++)
+         for (j=0;j<N0;j++)
+            tmp[j*stride+i] = X[i*N0+j];
+   }
+   OPUS_COPY(X, tmp, N);
+   RESTORE_STACK;
+}
+
+void haar1(celt_norm *X, int N0, int stride)
+{
+   int i, j;
+   N0 >>= 1;
+   for (i=0;i<stride;i++)
+      for (j=0;j<N0;j++)
+      {
+         opus_val32 tmp1, tmp2;
+         tmp1 = MULT16_16(QCONST16(.70710678f,15), X[stride*2*j+i]);
+         tmp2 = MULT16_16(QCONST16(.70710678f,15), X[stride*(2*j+1)+i]);
+         X[stride*2*j+i] = EXTRACT16(PSHR32(ADD32(tmp1, tmp2), 15));
+         X[stride*(2*j+1)+i] = EXTRACT16(PSHR32(SUB32(tmp1, tmp2), 15));
+      }
+}
+
+static int compute_qn(int N, int b, int offset, int pulse_cap, int stereo)
+{
+   static const opus_int16 exp2_table8[8] =
+      {16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048};
+   int qn, qb;
+   int N2 = 2*N-1;
+   if (stereo && N==2)
+      N2--;
+   /* The upper limit ensures that in a stereo split with itheta==16384, we'll
+       always have enough bits left over to code at least one pulse in the
+       side; otherwise it would collapse, since it doesn't get folded. */
+   qb = celt_sudiv(b+N2*offset, N2);
+   qb = IMIN(b-pulse_cap-(4<<BITRES), qb);
+
+   qb = IMIN(8<<BITRES, qb);
+
+   if (qb<(1<<BITRES>>1)) {
+      qn = 1;
+   } else {
+      qn = exp2_table8[qb&0x7]>>(14-(qb>>BITRES));
+      qn = (qn+1)>>1<<1;
+   }
+   celt_assert(qn <= 256);
+   return qn;
+}
+
+struct band_ctx {
+   int encode;
+   int resynth;
+   const CELTMode *m;
+   int i;
+   int intensity;
+   int spread;
+   int tf_change;
+   ec_ctx *ec;
+   opus_int32 remaining_bits;
+   const celt_ener *bandE;
+   opus_uint32 seed;
+   int arch;
+   int theta_round;
+   int disable_inv;
+   int avoid_split_noise;
+};
+
+struct split_ctx {
+   int inv;
+   int imid;
+   int iside;
+   int delta;
+   int itheta;
+   int qalloc;
+};
+
+static void compute_theta(struct band_ctx *ctx, struct split_ctx *sctx,
+      celt_norm *X, celt_norm *Y, int N, int *b, int B, int B0,
+      int LM,
+      int stereo, int *fill)
+{
+   int qn;
+   int itheta=0;
+   int delta;
+   int imid, iside;
+   int qalloc;
+   int pulse_cap;
+   int offset;
+   opus_int32 tell;
+   int inv=0;
+   int encode;
+   const CELTMode *m;
+   int i;
+   int intensity;
+   ec_ctx *ec;
+   const celt_ener *bandE;
+
+   encode = ctx->encode;
+   m = ctx->m;
+   i = ctx->i;
+   intensity = ctx->intensity;
+   ec = ctx->ec;
+   bandE = ctx->bandE;
+
+   /* Decide on the resolution to give to the split parameter theta */
+   pulse_cap = m->logN[i]+LM*(1<<BITRES);
+   offset = (pulse_cap>>1) - (stereo&&N==2 ? QTHETA_OFFSET_TWOPHASE : QTHETA_OFFSET);
+   qn = compute_qn(N, *b, offset, pulse_cap, stereo);
+   if (stereo && i>=intensity)
+      qn = 1;
+   if (encode)
+   {
+      /* theta is the atan() of the ratio between the (normalized)
+         side and mid. With just that parameter, we can re-scale both
+         mid and side because we know that 1) they have unit norm and
+         2) they are orthogonal. */
+      itheta = stereo_itheta(X, Y, stereo, N, ctx->arch);
+   }
+   tell = ec_tell_frac(ec);
+   if (qn!=1)
+   {
+      if (encode)
+      {
+         if (!stereo || ctx->theta_round == 0)
+         {
+            itheta = (itheta*(opus_int32)qn+8192)>>14;
+            if (!stereo && ctx->avoid_split_noise && itheta > 0 && itheta < qn)
+            {
+               /* Check if the selected value of theta will cause the bit allocation
+                  to inject noise on one side. If so, make sure the energy of that side
+                  is zero. */
+               int unquantized = celt_udiv((opus_int32)itheta*16384, qn);
+               imid = bitexact_cos((opus_int16)unquantized);
+               iside = bitexact_cos((opus_int16)(16384-unquantized));
+               delta = FRAC_MUL16((N-1)<<7,bitexact_log2tan(iside,imid));
+               if (delta > *b)
+                  itheta = qn;
+               else if (delta < -*b)
+                  itheta = 0;
+            }
+         } else {
+            int down;
+            /* Bias quantization towards itheta=0 and itheta=16384. */
+            int bias = itheta > 8192 ? 32767/qn : -32767/qn;
+            down = IMIN(qn-1, IMAX(0, (itheta*(opus_int32)qn + bias)>>14));
+            if (ctx->theta_round < 0)
+               itheta = down;
+            else
+               itheta = down+1;
+         }
+      }
+      /* Entropy coding of the angle. We use a uniform pdf for the
+         time split, a step for stereo, and a triangular one for the rest. */
+      if (stereo && N>2)
+      {
+         int p0 = 3;
+         int x = itheta;
+         int x0 = qn/2;
+         int ft = p0*(x0+1) + x0;
+         /* Use a probability of p0 up to itheta=8192 and then use 1 after */
+         if (encode)
+         {
+            ec_encode(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
+         } else {
+            int fs;
+            fs=ec_decode(ec,ft);
+            if (fs<(x0+1)*p0)
+               x=fs/p0;
+            else
+               x=x0+1+(fs-(x0+1)*p0);
+            ec_dec_update(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
+            itheta = x;
+         }
+      } else if (B0>1 || stereo) {
+         /* Uniform pdf */
+         if (encode)
+            ec_enc_uint(ec, itheta, qn+1);
+         else
+            itheta = ec_dec_uint(ec, qn+1);
+      } else {
+         int fs=1, ft;
+         ft = ((qn>>1)+1)*((qn>>1)+1);
+         if (encode)
+         {
+            int fl;
+
+            fs = itheta <= (qn>>1) ? itheta + 1 : qn + 1 - itheta;
+            fl = itheta <= (qn>>1) ? itheta*(itheta + 1)>>1 :
+             ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
+
+            ec_encode(ec, fl, fl+fs, ft);
+         } else {
+            /* Triangular pdf */
+            int fl=0;
+            int fm;
+            fm = ec_decode(ec, ft);
+
+            if (fm < ((qn>>1)*((qn>>1) + 1)>>1))
+            {
+               itheta = (isqrt32(8*(opus_uint32)fm + 1) - 1)>>1;
+               fs = itheta + 1;
+               fl = itheta*(itheta + 1)>>1;
+            }
+            else
+            {
+               itheta = (2*(qn + 1)
+                - isqrt32(8*(opus_uint32)(ft - fm - 1) + 1))>>1;
+               fs = qn + 1 - itheta;
+               fl = ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
+            }
+
+            ec_dec_update(ec, fl, fl+fs, ft);
+         }
+      }
+      celt_assert(itheta>=0);
+      itheta = celt_udiv((opus_int32)itheta*16384, qn);
+      if (encode && stereo)
+      {
+         if (itheta==0)
+            intensity_stereo(m, X, Y, bandE, i, N);
+         else
+            stereo_split(X, Y, N);
+      }
+      /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
+               Let's do that at higher complexity */
+   } else if (stereo) {
+      if (encode)
+      {
+         inv = itheta > 8192 && !ctx->disable_inv;
+         if (inv)
+         {
+            int j;
+            for (j=0;j<N;j++)
+               Y[j] = -Y[j];
+         }
+         intensity_stereo(m, X, Y, bandE, i, N);
+      }
+      if (*b>2<<BITRES && ctx->remaining_bits > 2<<BITRES)
+      {
+         if (encode)
+            ec_enc_bit_logp(ec, inv, 2);
+         else
+            inv = ec_dec_bit_logp(ec, 2);
+      } else
+         inv = 0;
+      /* inv flag override to avoid problems with downmixing. */
+      if (ctx->disable_inv)
+         inv = 0;
+      itheta = 0;
+   }
+   qalloc = ec_tell_frac(ec) - tell;
+   *b -= qalloc;
+
+   if (itheta == 0)
+   {
+      imid = 32767;
+      iside = 0;
+      *fill &= (1<<B)-1;
+      delta = -16384;
+   } else if (itheta == 16384)
+   {
+      imid = 0;
+      iside = 32767;
+      *fill &= ((1<<B)-1)<<B;
+      delta = 16384;
+   } else {
+      imid = bitexact_cos((opus_int16)itheta);
+      iside = bitexact_cos((opus_int16)(16384-itheta));
+      /* This is the mid vs side allocation that minimizes squared error
+         in that band. */
+      delta = FRAC_MUL16((N-1)<<7,bitexact_log2tan(iside,imid));
+   }
+
+   sctx->inv = inv;
+   sctx->imid = imid;
+   sctx->iside = iside;
+   sctx->delta = delta;
+   sctx->itheta = itheta;
+   sctx->qalloc = qalloc;
+}
+static unsigned quant_band_n1(struct band_ctx *ctx, celt_norm *X, celt_norm *Y, int b,
+      celt_norm *lowband_out)
+{
+   int c;
+   int stereo;
+   celt_norm *x = X;
+   int encode;
+   ec_ctx *ec;
+
+   encode = ctx->encode;
+   ec = ctx->ec;
+
+   stereo = Y != NULL;
+   c=0; do {
+      int sign=0;
+      if (ctx->remaining_bits>=1<<BITRES)
+      {
+         if (encode)
+         {
+            sign = x[0]<0;
+            ec_enc_bits(ec, sign, 1);
+         } else {
+            sign = ec_dec_bits(ec, 1);
+         }
+         ctx->remaining_bits -= 1<<BITRES;
+         b-=1<<BITRES;
+      }
+      if (ctx->resynth)
+         x[0] = sign ? -NORM_SCALING : NORM_SCALING;
+      x = Y;
+   } while (++c<1+stereo);
+   if (lowband_out)
+      lowband_out[0] = SHR16(X[0],4);
+   return 1;
+}
+
+/* This function is responsible for encoding and decoding a mono partition.
+   It can split the band in two and transmit the energy difference with
+   the two half-bands. It can be called recursively so bands can end up being
+   split in 8 parts. */
+static unsigned quant_partition(struct band_ctx *ctx, celt_norm *X,
+      int N, int b, int B, celt_norm *lowband,
+      int LM,
+      opus_val16 gain, int fill)
+{
+   const unsigned char *cache;
+   int q;
+   int curr_bits;
+   int imid=0, iside=0;
+   int B0=B;
+   opus_val16 mid=0, side=0;
+   unsigned cm=0;
+   celt_norm *Y=NULL;
+   int encode;
+   const CELTMode *m;
+   int i;
+   int spread;
+   ec_ctx *ec;
+
+   encode = ctx->encode;
+   m = ctx->m;
+   i = ctx->i;
+   spread = ctx->spread;
+   ec = ctx->ec;
+
+   /* If we need 1.5 more bit than we can produce, split the band in two. */
+   cache = m->cache.bits + m->cache.index[(LM+1)*m->nbEBands+i];
+   if (LM != -1 && b > cache[cache[0]]+12 && N>2)
+   {
+      int mbits, sbits, delta;
+      int itheta;
+      int qalloc;
+      struct split_ctx sctx;
+      celt_norm *next_lowband2=NULL;
+      opus_int32 rebalance;
+
+      N >>= 1;
+      Y = X+N;
+      LM -= 1;
+      if (B==1)
+         fill = (fill&1)|(fill<<1);
+      B = (B+1)>>1;
+
+      compute_theta(ctx, &sctx, X, Y, N, &b, B, B0, LM, 0, &fill);
+      imid = sctx.imid;
+      iside = sctx.iside;
+      delta = sctx.delta;
+      itheta = sctx.itheta;
+      qalloc = sctx.qalloc;
+#ifdef FIXED_POINT
+      mid = imid;
+      side = iside;
+#else
+      mid = (1.f/32768)*imid;
+      side = (1.f/32768)*iside;
+#endif
+
+      /* Give more bits to low-energy MDCTs than they would otherwise deserve */
+      if (B0>1 && (itheta&0x3fff))
+      {
+         if (itheta > 8192)
+            /* Rough approximation for pre-echo masking */
+            delta -= delta>>(4-LM);
+         else
+            /* Corresponds to a forward-masking slope of 1.5 dB per 10 ms */
+            delta = IMIN(0, delta + (N<<BITRES>>(5-LM)));
+      }
+      mbits = IMAX(0, IMIN(b, (b-delta)/2));
+      sbits = b-mbits;
+      ctx->remaining_bits -= qalloc;
+
+      if (lowband)
+         next_lowband2 = lowband+N; /* >32-bit split case */
+
+      rebalance = ctx->remaining_bits;
+      if (mbits >= sbits)
+      {
+         cm = quant_partition(ctx, X, N, mbits, B, lowband, LM,
+               MULT16_16_P15(gain,mid), fill);
+         rebalance = mbits - (rebalance-ctx->remaining_bits);
+         if (rebalance > 3<<BITRES && itheta!=0)
+            sbits += rebalance - (3<<BITRES);
+         cm |= quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
+               MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
+      } else {
+         cm = quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
+               MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
+         rebalance = sbits - (rebalance-ctx->remaining_bits);
+         if (rebalance > 3<<BITRES && itheta!=16384)
+            mbits += rebalance - (3<<BITRES);
+         cm |= quant_partition(ctx, X, N, mbits, B, lowband, LM,
+               MULT16_16_P15(gain,mid), fill);
+      }
+   } else {
+      /* This is the basic no-split case */
+      q = bits2pulses(m, i, LM, b);
+      curr_bits = pulses2bits(m, i, LM, q);
+      ctx->remaining_bits -= curr_bits;
+
+      /* Ensures we can never bust the budget */
+      while (ctx->remaining_bits < 0 && q > 0)
+      {
+         ctx->remaining_bits += curr_bits;
+         q--;
+         curr_bits = pulses2bits(m, i, LM, q);
+         ctx->remaining_bits -= curr_bits;
+      }
+
+      if (q!=0)
+      {
+         int K = get_pulses(q);
+
+         /* Finally do the actual quantization */
+         if (encode)
+         {
+            cm = alg_quant(X, N, K, spread, B, ec, gain, ctx->resynth, ctx->arch);
+         } else {
+            cm = alg_unquant(X, N, K, spread, B, ec, gain);
+         }
+      } else {
+         /* If there's no pulse, fill the band anyway */
+         int j;
+         if (ctx->resynth)
+         {
+            unsigned cm_mask;
+            /* B can be as large as 16, so this shift might overflow an int on a
+               16-bit platform; use a long to get defined behavior.*/
+            cm_mask = (unsigned)(1UL<<B)-1;
+            fill &= cm_mask;
+            if (!fill)
+            {
+               OPUS_CLEAR(X, N);
+            } else {
+               if (lowband == NULL)
+               {
+                  /* Noise */
+                  for (j=0;j<N;j++)
+                  {
+                     ctx->seed = celt_lcg_rand(ctx->seed);
+                     X[j] = (celt_norm)((opus_int32)ctx->seed>>20);
+                  }
+                  cm = cm_mask;
+               } else {
+                  /* Folded spectrum */
+                  for (j=0;j<N;j++)
+                  {
+                     opus_val16 tmp;
+                     ctx->seed = celt_lcg_rand(ctx->seed);
+                     /* About 48 dB below the "normal" folding level */
+                     tmp = QCONST16(1.0f/256, 10);
+                     tmp = (ctx->seed)&0x8000 ? tmp : -tmp;
+                     X[j] = lowband[j]+tmp;
+                  }
+                  cm = fill;
+               }
+               renormalise_vector(X, N, gain, ctx->arch);
+            }
+         }
+      }
+   }
+
+   return cm;
+}
+
+
+/* This function is responsible for encoding and decoding a band for the mono case. */
+static unsigned quant_band(struct band_ctx *ctx, celt_norm *X,
+      int N, int b, int B, celt_norm *lowband,
+      int LM, celt_norm *lowband_out,
+      opus_val16 gain, celt_norm *lowband_scratch, int fill)
+{
+   int N0=N;
+   int N_B=N;
+   int N_B0;
+   int B0=B;
+   int time_divide=0;
+   int recombine=0;
+   int longBlocks;
+   unsigned cm=0;
+   int k;
+   int encode;
+   int tf_change;
+
+   encode = ctx->encode;
+   tf_change = ctx->tf_change;
+
+   longBlocks = B0==1;
+
+   N_B = celt_udiv(N_B, B);
+
+   /* Special case for one sample */
+   if (N==1)
+   {
+      return quant_band_n1(ctx, X, NULL, b, lowband_out);
+   }
+
+   if (tf_change>0)
+      recombine = tf_change;
+   /* Band recombining to increase frequency resolution */
+
+   if (lowband_scratch && lowband && (recombine || ((N_B&1) == 0 && tf_change<0) || B0>1))
+   {
+      OPUS_COPY(lowband_scratch, lowband, N);
+      lowband = lowband_scratch;
+   }
+
+   for (k=0;k<recombine;k++)
+   {
+      static const unsigned char bit_interleave_table[16]={
+            0,1,1,1,2,3,3,3,2,3,3,3,2,3,3,3
+      };
+      if (encode)
+         haar1(X, N>>k, 1<<k);
+      if (lowband)
+         haar1(lowband, N>>k, 1<<k);
+      fill = bit_interleave_table[fill&0xF]|bit_interleave_table[fill>>4]<<2;
+   }
+   B>>=recombine;
+   N_B<<=recombine;
+
+   /* Increasing the time resolution */
+   while ((N_B&1) == 0 && tf_change<0)
+   {
+      if (encode)
+         haar1(X, N_B, B);
+      if (lowband)
+         haar1(lowband, N_B, B);
+      fill |= fill<<B;
+      B <<= 1;
+      N_B >>= 1;
+      time_divide++;
+      tf_change++;
+   }
+   B0=B;
+   N_B0 = N_B;
+
+   /* Reorganize the samples in time order instead of frequency order */
+   if (B0>1)
+   {
+      if (encode)
+         deinterleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
+      if (lowband)
+         deinterleave_hadamard(lowband, N_B>>recombine, B0<<recombine, longBlocks);
+   }
+
+   cm = quant_partition(ctx, X, N, b, B, lowband, LM, gain, fill);
+
+   /* This code is used by the decoder and by the resynthesis-enabled encoder */
+   if (ctx->resynth)
+   {
+      /* Undo the sample reorganization going from time order to frequency order */
+      if (B0>1)
+         interleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
+
+      /* Undo time-freq changes that we did earlier */
+      N_B = N_B0;
+      B = B0;
+      for (k=0;k<time_divide;k++)
+      {
+         B >>= 1;
+         N_B <<= 1;
+         cm |= cm>>B;
+         haar1(X, N_B, B);
+      }
+
+      for (k=0;k<recombine;k++)
+      {
+         static const unsigned char bit_deinterleave_table[16]={
+               0x00,0x03,0x0C,0x0F,0x30,0x33,0x3C,0x3F,
+               0xC0,0xC3,0xCC,0xCF,0xF0,0xF3,0xFC,0xFF
+         };
+         cm = bit_deinterleave_table[cm];
+         haar1(X, N0>>k, 1<<k);
+      }
+      B<<=recombine;
+
+      /* Scale output for later folding */
+      if (lowband_out)
+      {
+         int j;
+         opus_val16 n;
+         n = celt_sqrt(SHL32(EXTEND32(N0),22));
+         for (j=0;j<N0;j++)
+            lowband_out[j] = MULT16_16_Q15(n,X[j]);
+      }
+      cm &= (1<<B)-1;
+   }
+   return cm;
+}
+
+
+/* This function is responsible for encoding and decoding a band for the stereo case. */
+static unsigned quant_band_stereo(struct band_ctx *ctx, celt_norm *X, celt_norm *Y,
+      int N, int b, int B, celt_norm *lowband,
+      int LM, celt_norm *lowband_out,
+      celt_norm *lowband_scratch, int fill)
+{
+   int imid=0, iside=0;
+   int inv = 0;
+   opus_val16 mid=0, side=0;
+   unsigned cm=0;
+   int mbits, sbits, delta;
+   int itheta;
+   int qalloc;
+   struct split_ctx sctx;
+   int orig_fill;
+   int encode;
+   ec_ctx *ec;
+
+   encode = ctx->encode;
+   ec = ctx->ec;
+
+   /* Special case for one sample */
+   if (N==1)
+   {
+      return quant_band_n1(ctx, X, Y, b, lowband_out);
+   }
+
+   orig_fill = fill;
+
+   compute_theta(ctx, &sctx, X, Y, N, &b, B, B, LM, 1, &fill);
+   inv = sctx.inv;
+   imid = sctx.imid;
+   iside = sctx.iside;
+   delta = sctx.delta;
+   itheta = sctx.itheta;
+   qalloc = sctx.qalloc;
+#ifdef FIXED_POINT
+   mid = imid;
+   side = iside;
+#else
+   mid = (1.f/32768)*imid;
+   side = (1.f/32768)*iside;
+#endif
+
+   /* This is a special case for N=2 that only works for stereo and takes
+      advantage of the fact that mid and side are orthogonal to encode
+      the side with just one bit. */
+   if (N==2)
+   {
+      int c;
+      int sign=0;
+      celt_norm *x2, *y2;
+      mbits = b;
+      sbits = 0;
+      /* Only need one bit for the side. */
+      if (itheta != 0 && itheta != 16384)
+         sbits = 1<<BITRES;
+      mbits -= sbits;
+      c = itheta > 8192;
+      ctx->remaining_bits -= qalloc+sbits;
+
+      x2 = c ? Y : X;
+      y2 = c ? X : Y;
+      if (sbits)
+      {
+         if (encode)
+         {
+            /* Here we only need to encode a sign for the side. */
+            sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
+            ec_enc_bits(ec, sign, 1);
+         } else {
+            sign = ec_dec_bits(ec, 1);
+         }
+      }
+      sign = 1-2*sign;
+      /* We use orig_fill here because we want to fold the side, but if
+         itheta==16384, we'll have cleared the low bits of fill. */
+      cm = quant_band(ctx, x2, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
+            lowband_scratch, orig_fill);
+      /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
+         and there's no need to worry about mixing with the other channel. */
+      y2[0] = -sign*x2[1];
+      y2[1] = sign*x2[0];
+      if (ctx->resynth)
+      {
+         celt_norm tmp;
+         X[0] = MULT16_16_Q15(mid, X[0]);
+         X[1] = MULT16_16_Q15(mid, X[1]);
+         Y[0] = MULT16_16_Q15(side, Y[0]);
+         Y[1] = MULT16_16_Q15(side, Y[1]);
+         tmp = X[0];
+         X[0] = SUB16(tmp,Y[0]);
+         Y[0] = ADD16(tmp,Y[0]);
+         tmp = X[1];
+         X[1] = SUB16(tmp,Y[1]);
+         Y[1] = ADD16(tmp,Y[1]);
+      }
+   } else {
+      /* "Normal" split code */
+      opus_int32 rebalance;
+
+      mbits = IMAX(0, IMIN(b, (b-delta)/2));
+      sbits = b-mbits;
+      ctx->remaining_bits -= qalloc;
+
+      rebalance = ctx->remaining_bits;
+      if (mbits >= sbits)
+      {
+         /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
+            mid for folding later. */
+         cm = quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
+               lowband_scratch, fill);
+         rebalance = mbits - (rebalance-ctx->remaining_bits);
+         if (rebalance > 3<<BITRES && itheta!=0)
+            sbits += rebalance - (3<<BITRES);
+
+         /* For a stereo split, the high bits of fill are always zero, so no
+            folding will be done to the side. */
+         cm |= quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
+      } else {
+         /* For a stereo split, the high bits of fill are always zero, so no
+            folding will be done to the side. */
+         cm = quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
+         rebalance = sbits - (rebalance-ctx->remaining_bits);
+         if (rebalance > 3<<BITRES && itheta!=16384)
+            mbits += rebalance - (3<<BITRES);
+         /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
+            mid for folding later. */
+         cm |= quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
+               lowband_scratch, fill);
+      }
+   }
+
+
+   /* This code is used by the decoder and by the resynthesis-enabled encoder */
+   if (ctx->resynth)
+   {
+      if (N!=2)
+         stereo_merge(X, Y, mid, N, ctx->arch);
+      if (inv)
+      {
+         int j;
+         for (j=0;j<N;j++)
+            Y[j] = -Y[j];
+      }
+   }
+   return cm;
+}
+
+static void special_hybrid_folding(const CELTMode *m, celt_norm *norm, celt_norm *norm2, int start, int M, int dual_stereo)
+{
+   int n1, n2;
+   const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
+   n1 = M*(eBands[start+1]-eBands[start]);
+   n2 = M*(eBands[start+2]-eBands[start+1]);
+   /* Duplicate enough of the first band folding data to be able to fold the second band.
+      Copies no data for CELT-only mode. */
+   OPUS_COPY(&norm[n1], &norm[2*n1 - n2], n2-n1);
+   if (dual_stereo)
+      OPUS_COPY(&norm2[n1], &norm2[2*n1 - n2], n2-n1);
+}
+
+void quant_all_bands(int encode, const CELTMode *m, int start, int end,
+      celt_norm *X_, celt_norm *Y_, unsigned char *collapse_masks,
+      const celt_ener *bandE, int *pulses, int shortBlocks, int spread,
+      int dual_stereo, int intensity, int *tf_res, opus_int32 total_bits,
+      opus_int32 balance, ec_ctx *ec, int LM, int codedBands,
+      opus_uint32 *seed, int complexity, int arch, int disable_inv)
+{
+   int i;
+   opus_int32 remaining_bits;
+   const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
+   celt_norm * OPUS_RESTRICT norm, * OPUS_RESTRICT norm2;
+   VARDECL(celt_norm, _norm);
+   VARDECL(celt_norm, _lowband_scratch);
+   VARDECL(celt_norm, X_save);
+   VARDECL(celt_norm, Y_save);
+   VARDECL(celt_norm, X_save2);
+   VARDECL(celt_norm, Y_save2);
+   VARDECL(celt_norm, norm_save2);
+   int resynth_alloc;
+   celt_norm *lowband_scratch;
+   int B;
+   int M;
+   int lowband_offset;
+   int update_lowband = 1;
+   int C = Y_ != NULL ? 2 : 1;
+   int norm_offset;
+   int theta_rdo = encode && Y_!=NULL && !dual_stereo && complexity>=8;
+#ifdef RESYNTH
+   int resynth = 1;
+#else
+   int resynth = !encode || theta_rdo;
+#endif
+   struct band_ctx ctx;
+   SAVE_STACK;
+
+   M = 1<<LM;
+   B = shortBlocks ? M : 1;
+   norm_offset = M*eBands[start];
+   /* No need to allocate norm for the last band because we don't need an
+      output in that band. */
+   ALLOC(_norm, C*(M*eBands[m->nbEBands-1]-norm_offset), celt_norm);
+   norm = _norm;
+   norm2 = norm + M*eBands[m->nbEBands-1]-norm_offset;
+
+   /* For decoding, we can use the last band as scratch space because we don't need that
+      scratch space for the last band and we don't care about the data there until we're
+      decoding the last band. */
+   if (encode && resynth)
+      resynth_alloc = M*(eBands[m->nbEBands]-eBands[m->nbEBands-1]);
+   else
+      resynth_alloc = ALLOC_NONE;
+   ALLOC(_lowband_scratch, resynth_alloc, celt_norm);
+   if (encode && resynth)
+      lowband_scratch = _lowband_scratch;
+   else
+      lowband_scratch = X_+M*eBands[m->nbEBands-1];
+   ALLOC(X_save, resynth_alloc, celt_norm);
+   ALLOC(Y_save, resynth_alloc, celt_norm);
+   ALLOC(X_save2, resynth_alloc, celt_norm);
+   ALLOC(Y_save2, resynth_alloc, celt_norm);
+   ALLOC(norm_save2, resynth_alloc, celt_norm);
+
+   lowband_offset = 0;
+   ctx.bandE = bandE;
+   ctx.ec = ec;
+   ctx.encode = encode;
+   ctx.intensity = intensity;
+   ctx.m = m;
+   ctx.seed = *seed;
+   ctx.spread = spread;
+   ctx.arch = arch;
+   ctx.disable_inv = disable_inv;
+   ctx.resynth = resynth;
+   ctx.theta_round = 0;
+   /* Avoid injecting noise in the first band on transients. */
+   ctx.avoid_split_noise = B > 1;
+   for (i=start;i<end;i++)
+   {
+      opus_int32 tell;
+      int b;
+      int N;
+      opus_int32 curr_balance;
+      int effective_lowband=-1;
+      celt_norm * OPUS_RESTRICT X, * OPUS_RESTRICT Y;
+      int tf_change=0;
+      unsigned x_cm;
+      unsigned y_cm;
+      int last;
+
+      ctx.i = i;
+      last = (i==end-1);
+
+      X = X_+M*eBands[i];
+      if (Y_!=NULL)
+         Y = Y_+M*eBands[i];
+      else
+         Y = NULL;
+      N = M*eBands[i+1]-M*eBands[i];
+      tell = ec_tell_frac(ec);
+
+      /* Compute how many bits we want to allocate to this band */
+      if (i != start)
+         balance -= tell;
+      remaining_bits = total_bits-tell-1;
+      ctx.remaining_bits = remaining_bits;
+      if (i <= codedBands-1)
+      {
+         curr_balance = celt_sudiv(balance, IMIN(3, codedBands-i));
+         b = IMAX(0, IMIN(16383, IMIN(remaining_bits+1,pulses[i]+curr_balance)));
+      } else {
+         b = 0;
+      }
+
+#ifdef ENABLE_UPDATE_DRAFT
+      if (resynth && (M*eBands[i]-N >= M*eBands[start] || i==start+1) && (update_lowband || lowband_offset==0))
+            lowband_offset = i;
+      if (i == start+1)
+         special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
+#else
+      if (resynth && M*eBands[i]-N >= M*eBands[start] && (update_lowband || lowband_offset==0))
+            lowband_offset = i;
+#endif
+
+      tf_change = tf_res[i];
+      ctx.tf_change = tf_change;
+      if (i>=m->effEBands)
+      {
+         X=norm;
+         if (Y_!=NULL)
+            Y = norm;
+         lowband_scratch = NULL;
+      }
+      if (last && !theta_rdo)
+         lowband_scratch = NULL;
+
+      /* Get a conservative estimate of the collapse_mask's for the bands we're
+         going to be folding from. */
+      if (lowband_offset != 0 && (spread!=SPREAD_AGGRESSIVE || B>1 || tf_change<0))
+      {
+         int fold_start;
+         int fold_end;
+         int fold_i;
+         /* This ensures we never repeat spectral content within one band */
+         effective_lowband = IMAX(0, M*eBands[lowband_offset]-norm_offset-N);
+         fold_start = lowband_offset;
+         while(M*eBands[--fold_start] > effective_lowband+norm_offset);
+         fold_end = lowband_offset-1;
+#ifdef ENABLE_UPDATE_DRAFT
+         while(++fold_end < i && M*eBands[fold_end] < effective_lowband+norm_offset+N);
+#else
+         while(M*eBands[++fold_end] < effective_lowband+norm_offset+N);
+#endif
+         x_cm = y_cm = 0;
+         fold_i = fold_start; do {
+           x_cm |= collapse_masks[fold_i*C+0];
+           y_cm |= collapse_masks[fold_i*C+C-1];
+         } while (++fold_i<fold_end);
+      }
+      /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
+         always) be non-zero. */
+      else
+         x_cm = y_cm = (1<<B)-1;
+
+      if (dual_stereo && i==intensity)
+      {
+         int j;
+
+         /* Switch off dual stereo to do intensity. */
+         dual_stereo = 0;
+         if (resynth)
+            for (j=0;j<M*eBands[i]-norm_offset;j++)
+               norm[j] = HALF32(norm[j]+norm2[j]);
+      }
+      if (dual_stereo)
+      {
+         x_cm = quant_band(&ctx, X, N, b/2, B,
+               effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
+               last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm);
+         y_cm = quant_band(&ctx, Y, N, b/2, B,
+               effective_lowband != -1 ? norm2+effective_lowband : NULL, LM,
+               last?NULL:norm2+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, y_cm);
+      } else {
+         if (Y!=NULL)
+         {
+            if (theta_rdo && i < intensity)
+            {
+               ec_ctx ec_save, ec_save2;
+               struct band_ctx ctx_save, ctx_save2;
+               opus_val32 dist0, dist1;
+               unsigned cm, cm2;
+               int nstart_bytes, nend_bytes, save_bytes;
+               unsigned char *bytes_buf;
+               unsigned char bytes_save[1275];
+               opus_val16 w[2];
+               compute_channel_weights(bandE[i], bandE[i+m->nbEBands], w);
+               /* Make a copy. */
+               cm = x_cm|y_cm;
+               ec_save = *ec;
+               ctx_save = ctx;
+               OPUS_COPY(X_save, X, N);
+               OPUS_COPY(Y_save, Y, N);
+               /* Encode and round down. */
+               ctx.theta_round = -1;
+               x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
+                     effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
+                     last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
+               dist0 = MULT16_32_Q15(w[0], celt_inner_prod(X_save, X, N, arch)) + MULT16_32_Q15(w[1], celt_inner_prod(Y_save, Y, N, arch));
+
+               /* Save first result. */
+               cm2 = x_cm;
+               ec_save2 = *ec;
+               ctx_save2 = ctx;
+               OPUS_COPY(X_save2, X, N);
+               OPUS_COPY(Y_save2, Y, N);
+               if (!last)
+                  OPUS_COPY(norm_save2, norm+M*eBands[i]-norm_offset, N);
+               nstart_bytes = ec_save.offs;
+               nend_bytes = ec_save.storage;
+               bytes_buf = ec_save.buf+nstart_bytes;
+               save_bytes = nend_bytes-nstart_bytes;
+               OPUS_COPY(bytes_save, bytes_buf, save_bytes);
+
+               /* Restore */
+               *ec = ec_save;
+               ctx = ctx_save;
+               OPUS_COPY(X, X_save, N);
+               OPUS_COPY(Y, Y_save, N);
+               if (i == start+1)
+                  special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
+               /* Encode and round up. */
+               ctx.theta_round = 1;
+               x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
+                     effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
+                     last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
+               dist1 = MULT16_32_Q15(w[0], celt_inner_prod(X_save, X, N, arch)) + MULT16_32_Q15(w[1], celt_inner_prod(Y_save, Y, N, arch));
+               if (dist0 >= dist1) {
+                  x_cm = cm2;
+                  *ec = ec_save2;
+                  ctx = ctx_save2;
+                  OPUS_COPY(X, X_save2, N);
+                  OPUS_COPY(Y, Y_save2, N);
+                  if (!last)
+                     OPUS_COPY(norm+M*eBands[i]-norm_offset, norm_save2, N);
+                  OPUS_COPY(bytes_buf, bytes_save, save_bytes);
+               }
+            } else {
+               ctx.theta_round = 0;
+               x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
+                     effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
+                     last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, x_cm|y_cm);
+            }
+         } else {
+            x_cm = quant_band(&ctx, X, N, b, B,
+                  effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
+                  last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm|y_cm);
+         }
+         y_cm = x_cm;
+      }
+      collapse_masks[i*C+0] = (unsigned char)x_cm;
+      collapse_masks[i*C+C-1] = (unsigned char)y_cm;
+      balance += pulses[i] + tell;
+
+      /* Update the folding position only as long as we have 1 bit/sample depth. */
+      update_lowband = b>(N<<BITRES);
+      /* We only need to avoid noise on a split for the first band. After that, we
+         have folding. */
+      ctx.avoid_split_noise = 0;
+   }
+   *seed = ctx.seed;
+
+   RESTORE_STACK;
+}
+
diff --git a/opus/celt/bands.h b/opus/celt/bands.h
new file mode 100644 (file)
index 0000000..2488c18
--- /dev/null
@@ -0,0 +1,123 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2008-2009 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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 BANDS_H
+#define BANDS_H
+
+#include "arch.h"
+#include "modes.h"
+#include "entenc.h"
+#include "entdec.h"
+#include "rate.h"
+
+opus_int16 bitexact_cos(opus_int16 x);
+int bitexact_log2tan(int isin,int icos);
+
+/** Compute the amplitude (sqrt energy) in each of the bands
+ * @param m Mode data
+ * @param X Spectrum
+ * @param bandE Square root of the energy for each band (returned)
+ */
+void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int LM, int arch);
+
+/*void compute_noise_energies(const CELTMode *m, const celt_sig *X, const opus_val16 *tonality, celt_ener *bandE);*/
+
+/** 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 bandE Square root of the energy for each band
+ */
+void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M);
+
+/** Denormalise each band of X to restore full amplitude
+ * @param m Mode data
+ * @param X Spectrum (returned de-normalised)
+ * @param bandE Square root of the energy for each band
+ */
+void denormalise_bands(const CELTMode *m, const celt_norm * OPUS_RESTRICT X,
+      celt_sig * OPUS_RESTRICT freq, const opus_val16 *bandE, int start,
+      int end, int M, int downsample, int silence);
+
+#define SPREAD_NONE       (0)
+#define SPREAD_LIGHT      (1)
+#define SPREAD_NORMAL     (2)
+#define SPREAD_AGGRESSIVE (3)
+
+int spreading_decision(const CELTMode *m, const celt_norm *X, int *average,
+      int last_decision, int *hf_average, int *tapset_decision, int update_hf,
+      int end, int C, int M);
+
+#ifdef MEASURE_NORM_MSE
+void measure_norm_mse(const CELTMode *m, float *X, float *X0, float *bandE, float *bandE0, int M, int N, int C);
+#endif
+
+void haar1(celt_norm *X, int N0, int stride);
+
+/** Quantisation/encoding of the residual spectrum
+ * @param encode flag that indicates whether we're encoding (1) or decoding (0)
+ * @param m Mode data
+ * @param start First band to process
+ * @param end Last band to process + 1
+ * @param X Residual (normalised)
+ * @param Y Residual (normalised) for second channel (or NULL for mono)
+ * @param collapse_masks Anti-collapse tracking mask
+ * @param bandE Square root of the energy for each band
+ * @param pulses Bit allocation (per band) for PVQ
+ * @param shortBlocks Zero for long blocks, non-zero for short blocks
+ * @param spread Amount of spreading to use
+ * @param dual_stereo Zero for MS stereo, non-zero for dual stereo
+ * @param intensity First band to use intensity stereo
+ * @param tf_res Time-frequency resolution change
+ * @param total_bits Total number of bits that can be used for the frame (including the ones already spent)
+ * @param balance Number of unallocated bits
+ * @param en Entropy coder state
+ * @param LM log2() of the number of 2.5 subframes in the frame
+ * @param codedBands Last band to receive bits + 1
+ * @param seed Random generator seed
+ * @param arch Run-time architecture (see opus_select_arch())
+ */
+void quant_all_bands(int encode, const CELTMode *m, int start, int end,
+      celt_norm * X, celt_norm * Y, unsigned char *collapse_masks,
+      const celt_ener *bandE, int *pulses, int shortBlocks, int spread,
+      int dual_stereo, int intensity, int *tf_res, opus_int32 total_bits,
+      opus_int32 balance, ec_ctx *ec, int M, int codedBands, opus_uint32 *seed,
+      int complexity, int arch, int disable_inv);
+
+void anti_collapse(const CELTMode *m, celt_norm *X_,
+      unsigned char *collapse_masks, int LM, int C, int size, int start,
+      int end, const opus_val16 *logE, const opus_val16 *prev1logE,
+      const opus_val16 *prev2logE, const int *pulses, opus_uint32 seed,
+      int arch);
+
+opus_uint32 celt_lcg_rand(opus_uint32 seed);
+
+int hysteresis_decision(opus_val16 val, const opus_val16 *thresholds, const opus_val16 *hysteresis, int N, int prev);
+
+#endif /* BANDS_H */
diff --git a/opus/celt/celt.c b/opus/celt/celt.c
new file mode 100644 (file)
index 0000000..9ce2346
--- /dev/null
@@ -0,0 +1,316 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2010 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#define CELT_C
+
+#include "os_support.h"
+#include "mdct.h"
+#include <math.h>
+#include "celt.h"
+#include "pitch.h"
+#include "bands.h"
+#include "modes.h"
+#include "entcode.h"
+#include "quant_bands.h"
+#include "rate.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "float_cast.h"
+#include <stdarg.h>
+#include "celt_lpc.h"
+#include "vq.h"
+
+#ifndef PACKAGE_VERSION
+#define PACKAGE_VERSION "unknown"
+#endif
+
+#if defined(MIPSr1_ASM)
+#include "mips/celt_mipsr1.h"
+#endif
+
+
+int resampling_factor(opus_int32 rate)
+{
+   int ret;
+   switch (rate)
+   {
+   case 48000:
+      ret = 1;
+      break;
+   case 24000:
+      ret = 2;
+      break;
+   case 16000:
+      ret = 3;
+      break;
+   case 12000:
+      ret = 4;
+      break;
+   case 8000:
+      ret = 6;
+      break;
+   default:
+#ifndef CUSTOM_MODES
+      celt_assert(0);
+#endif
+      ret = 0;
+      break;
+   }
+   return ret;
+}
+
+#if !defined(OVERRIDE_COMB_FILTER_CONST) || defined(NON_STATIC_COMB_FILTER_CONST_C)
+/* This version should be faster on ARM */
+#ifdef OPUS_ARM_ASM
+#ifndef NON_STATIC_COMB_FILTER_CONST_C
+static
+#endif
+void comb_filter_const_c(opus_val32 *y, opus_val32 *x, int T, int N,
+      opus_val16 g10, opus_val16 g11, opus_val16 g12)
+{
+   opus_val32 x0, x1, x2, x3, x4;
+   int i;
+   x4 = SHL32(x[-T-2], 1);
+   x3 = SHL32(x[-T-1], 1);
+   x2 = SHL32(x[-T], 1);
+   x1 = SHL32(x[-T+1], 1);
+   for (i=0;i<N-4;i+=5)
+   {
+      opus_val32 t;
+      x0=SHL32(x[i-T+2],1);
+      t = MAC16_32_Q16(x[i], g10, x2);
+      t = MAC16_32_Q16(t, g11, ADD32(x1,x3));
+      t = MAC16_32_Q16(t, g12, ADD32(x0,x4));
+      t = SATURATE(t, SIG_SAT);
+      y[i] = t;
+      x4=SHL32(x[i-T+3],1);
+      t = MAC16_32_Q16(x[i+1], g10, x1);
+      t = MAC16_32_Q16(t, g11, ADD32(x0,x2));
+      t = MAC16_32_Q16(t, g12, ADD32(x4,x3));
+      t = SATURATE(t, SIG_SAT);
+      y[i+1] = t;
+      x3=SHL32(x[i-T+4],1);
+      t = MAC16_32_Q16(x[i+2], g10, x0);
+      t = MAC16_32_Q16(t, g11, ADD32(x4,x1));
+      t = MAC16_32_Q16(t, g12, ADD32(x3,x2));
+      t = SATURATE(t, SIG_SAT);
+      y[i+2] = t;
+      x2=SHL32(x[i-T+5],1);
+      t = MAC16_32_Q16(x[i+3], g10, x4);
+      t = MAC16_32_Q16(t, g11, ADD32(x3,x0));
+      t = MAC16_32_Q16(t, g12, ADD32(x2,x1));
+      t = SATURATE(t, SIG_SAT);
+      y[i+3] = t;
+      x1=SHL32(x[i-T+6],1);
+      t = MAC16_32_Q16(x[i+4], g10, x3);
+      t = MAC16_32_Q16(t, g11, ADD32(x2,x4));
+      t = MAC16_32_Q16(t, g12, ADD32(x1,x0));
+      t = SATURATE(t, SIG_SAT);
+      y[i+4] = t;
+   }
+#ifdef CUSTOM_MODES
+   for (;i<N;i++)
+   {
+      opus_val32 t;
+      x0=SHL32(x[i-T+2],1);
+      t = MAC16_32_Q16(x[i], g10, x2);
+      t = MAC16_32_Q16(t, g11, ADD32(x1,x3));
+      t = MAC16_32_Q16(t, g12, ADD32(x0,x4));
+      t = SATURATE(t, SIG_SAT);
+      y[i] = t;
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
+   }
+#endif
+}
+#else
+#ifndef NON_STATIC_COMB_FILTER_CONST_C
+static
+#endif
+void comb_filter_const_c(opus_val32 *y, opus_val32 *x, int T, int N,
+      opus_val16 g10, opus_val16 g11, opus_val16 g12)
+{
+   opus_val32 x0, x1, x2, x3, x4;
+   int i;
+   x4 = x[-T-2];
+   x3 = x[-T-1];
+   x2 = x[-T];
+   x1 = x[-T+1];
+   for (i=0;i<N;i++)
+   {
+      x0=x[i-T+2];
+      y[i] = x[i]
+               + MULT16_32_Q15(g10,x2)
+               + MULT16_32_Q15(g11,ADD32(x1,x3))
+               + MULT16_32_Q15(g12,ADD32(x0,x4));
+      y[i] = SATURATE(y[i], SIG_SAT);
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
+   }
+
+}
+#endif
+#endif
+
+#ifndef OVERRIDE_comb_filter
+void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
+      opus_val16 g0, opus_val16 g1, int tapset0, int tapset1,
+      const opus_val16 *window, int overlap, int arch)
+{
+   int i;
+   /* printf ("%d %d %f %f\n", T0, T1, g0, g1); */
+   opus_val16 g00, g01, g02, g10, g11, g12;
+   opus_val32 x0, x1, x2, x3, x4;
+   static const opus_val16 gains[3][3] = {
+         {QCONST16(0.3066406250f, 15), QCONST16(0.2170410156f, 15), QCONST16(0.1296386719f, 15)},
+         {QCONST16(0.4638671875f, 15), QCONST16(0.2680664062f, 15), QCONST16(0.f, 15)},
+         {QCONST16(0.7998046875f, 15), QCONST16(0.1000976562f, 15), QCONST16(0.f, 15)}};
+
+   if (g0==0 && g1==0)
+   {
+      /* OPT: Happens to work without the OPUS_MOVE(), but only because the current encoder already copies x to y */
+      if (x!=y)
+         OPUS_MOVE(y, x, N);
+      return;
+   }
+   /* When the gain is zero, T0 and/or T1 is set to zero. We need
+      to have then be at least 2 to avoid processing garbage data. */
+   T0 = IMAX(T0, COMBFILTER_MINPERIOD);
+   T1 = IMAX(T1, COMBFILTER_MINPERIOD);
+   g00 = MULT16_16_P15(g0, gains[tapset0][0]);
+   g01 = MULT16_16_P15(g0, gains[tapset0][1]);
+   g02 = MULT16_16_P15(g0, gains[tapset0][2]);
+   g10 = MULT16_16_P15(g1, gains[tapset1][0]);
+   g11 = MULT16_16_P15(g1, gains[tapset1][1]);
+   g12 = MULT16_16_P15(g1, gains[tapset1][2]);
+   x1 = x[-T1+1];
+   x2 = x[-T1  ];
+   x3 = x[-T1-1];
+   x4 = x[-T1-2];
+   /* If the filter didn't change, we don't need the overlap */
+   if (g0==g1 && T0==T1 && tapset0==tapset1)
+      overlap=0;
+   for (i=0;i<overlap;i++)
+   {
+      opus_val16 f;
+      x0=x[i-T1+2];
+      f = MULT16_16_Q15(window[i],window[i]);
+      y[i] = x[i]
+               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g00),x[i-T0])
+               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),ADD32(x[i-T0+1],x[i-T0-1]))
+               + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),ADD32(x[i-T0+2],x[i-T0-2]))
+               + MULT16_32_Q15(MULT16_16_Q15(f,g10),x2)
+               + MULT16_32_Q15(MULT16_16_Q15(f,g11),ADD32(x1,x3))
+               + MULT16_32_Q15(MULT16_16_Q15(f,g12),ADD32(x0,x4));
+      y[i] = SATURATE(y[i], SIG_SAT);
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
+
+   }
+   if (g1==0)
+   {
+      /* OPT: Happens to work without the OPUS_MOVE(), but only because the current encoder already copies x to y */
+      if (x!=y)
+         OPUS_MOVE(y+overlap, x+overlap, N-overlap);
+      return;
+   }
+
+   /* Compute the part with the constant filter. */
+   comb_filter_const(y+i, x+i, T1, N-i, g10, g11, g12, arch);
+}
+#endif /* OVERRIDE_comb_filter */
+
+/* TF change table. Positive values mean better frequency resolution (longer
+   effective window), whereas negative values mean better time resolution
+   (shorter effective window). The second index is computed as:
+   4*isTransient + 2*tf_select + per_band_flag */
+const signed char tf_select_table[4][8] = {
+    /*isTransient=0     isTransient=1 */
+      {0, -1, 0, -1,    0,-1, 0,-1}, /* 2.5 ms */
+      {0, -1, 0, -2,    1, 0, 1,-1}, /* 5 ms */
+      {0, -2, 0, -3,    2, 0, 1,-1}, /* 10 ms */
+      {0, -2, 0, -3,    3, 0, 1,-1}, /* 20 ms */
+};
+
+
+void init_caps(const CELTMode *m,int *cap,int LM,int C)
+{
+   int i;
+   for (i=0;i<m->nbEBands;i++)
+   {
+      int N;
+      N=(m->eBands[i+1]-m->eBands[i])<<LM;
+      cap[i] = (m->cache.caps[m->nbEBands*(2*LM+C-1)+i]+64)*C*N>>2;
+   }
+}
+
+
+
+const char *opus_strerror(int error)
+{
+   static const char * const error_strings[8] = {
+      "success",
+      "invalid argument",
+      "buffer too small",
+      "internal error",
+      "corrupted stream",
+      "request not implemented",
+      "invalid state",
+      "memory allocation failed"
+   };
+   if (error > 0 || error < -7)
+      return "unknown error";
+   else
+      return error_strings[-error];
+}
+
+const char *opus_get_version_string(void)
+{
+    return "libopus " PACKAGE_VERSION
+    /* Applications may rely on the presence of this substring in the version
+       string to determine if they have a fixed-point or floating-point build
+       at runtime. */
+#ifdef FIXED_POINT
+          "-fixed"
+#endif
+#ifdef FUZZING
+          "-fuzzing"
+#endif
+          ;
+}
diff --git a/opus/celt/celt.h b/opus/celt/celt.h
new file mode 100644 (file)
index 0000000..7017530
--- /dev/null
@@ -0,0 +1,242 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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 CELT_H
+#define CELT_H
+
+#include "opus_types.h"
+#include "opus_defines.h"
+#include "opus_custom.h"
+#include "entenc.h"
+#include "entdec.h"
+#include "arch.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CELTEncoder OpusCustomEncoder
+#define CELTDecoder OpusCustomDecoder
+#define CELTMode OpusCustomMode
+
+#define LEAK_BANDS 19
+
+typedef struct {
+   int valid;
+   float tonality;
+   float tonality_slope;
+   float noisiness;
+   float activity;
+   float music_prob;
+   float vad_prob;
+   int   bandwidth;
+   float activity_probability;
+   /* Store as Q6 char to save space. */
+   unsigned char leak_boost[LEAK_BANDS];
+} AnalysisInfo;
+
+typedef struct {
+   int signalType;
+   int offset;
+} SILKInfo;
+
+#define __celt_check_mode_ptr_ptr(ptr) ((ptr) + ((ptr) - (const CELTMode**)(ptr)))
+
+#define __celt_check_analysis_ptr(ptr) ((ptr) + ((ptr) - (const AnalysisInfo*)(ptr)))
+
+#define __celt_check_silkinfo_ptr(ptr) ((ptr) + ((ptr) - (const SILKInfo*)(ptr)))
+
+/* Encoder/decoder Requests */
+
+
+#define CELT_SET_PREDICTION_REQUEST    10002
+/** 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, __opus_check_int(x)
+
+#define CELT_SET_INPUT_CLIPPING_REQUEST    10004
+#define CELT_SET_INPUT_CLIPPING(x) CELT_SET_INPUT_CLIPPING_REQUEST, __opus_check_int(x)
+
+#define CELT_GET_AND_CLEAR_ERROR_REQUEST   10007
+#define CELT_GET_AND_CLEAR_ERROR(x) CELT_GET_AND_CLEAR_ERROR_REQUEST, __opus_check_int_ptr(x)
+
+#define CELT_SET_CHANNELS_REQUEST    10008
+#define CELT_SET_CHANNELS(x) CELT_SET_CHANNELS_REQUEST, __opus_check_int(x)
+
+
+/* Internal */
+#define CELT_SET_START_BAND_REQUEST    10010
+#define CELT_SET_START_BAND(x) CELT_SET_START_BAND_REQUEST, __opus_check_int(x)
+
+#define CELT_SET_END_BAND_REQUEST    10012
+#define CELT_SET_END_BAND(x) CELT_SET_END_BAND_REQUEST, __opus_check_int(x)
+
+#define CELT_GET_MODE_REQUEST    10015
+/** 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_SIGNALLING_REQUEST    10016
+#define CELT_SET_SIGNALLING(x) CELT_SET_SIGNALLING_REQUEST, __opus_check_int(x)
+
+#define CELT_SET_TONALITY_REQUEST    10018
+#define CELT_SET_TONALITY(x) CELT_SET_TONALITY_REQUEST, __opus_check_int(x)
+#define CELT_SET_TONALITY_SLOPE_REQUEST    10020
+#define CELT_SET_TONALITY_SLOPE(x) CELT_SET_TONALITY_SLOPE_REQUEST, __opus_check_int(x)
+
+#define CELT_SET_ANALYSIS_REQUEST    10022
+#define CELT_SET_ANALYSIS(x) CELT_SET_ANALYSIS_REQUEST, __celt_check_analysis_ptr(x)
+
+#define OPUS_SET_LFE_REQUEST    10024
+#define OPUS_SET_LFE(x) OPUS_SET_LFE_REQUEST, __opus_check_int(x)
+
+#define OPUS_SET_ENERGY_MASK_REQUEST    10026
+#define OPUS_SET_ENERGY_MASK(x) OPUS_SET_ENERGY_MASK_REQUEST, __opus_check_val16_ptr(x)
+
+#define CELT_SET_SILK_INFO_REQUEST    10028
+#define CELT_SET_SILK_INFO(x) CELT_SET_SILK_INFO_REQUEST, __celt_check_silkinfo_ptr(x)
+
+/* Encoder stuff */
+
+int celt_encoder_get_size(int channels);
+
+int celt_encode_with_ec(OpusCustomEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc);
+
+int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels,
+                      int arch);
+
+
+
+/* Decoder stuff */
+
+int celt_decoder_get_size(int channels);
+
+
+int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels);
+
+int celt_decode_with_ec(OpusCustomDecoder * OPUS_RESTRICT st, const unsigned char *data,
+      int len, opus_val16 * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec, int accum);
+
+#define celt_encoder_ctl opus_custom_encoder_ctl
+#define celt_decoder_ctl opus_custom_decoder_ctl
+
+
+#ifdef CUSTOM_MODES
+#define OPUS_CUSTOM_NOSTATIC
+#else
+#define OPUS_CUSTOM_NOSTATIC static OPUS_INLINE
+#endif
+
+static const unsigned char trim_icdf[11] = {126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0};
+/* Probs: NONE: 21.875%, LIGHT: 6.25%, NORMAL: 65.625%, AGGRESSIVE: 6.25% */
+static const unsigned char spread_icdf[4] = {25, 23, 2, 0};
+
+static const unsigned char tapset_icdf[3]={2,1,0};
+
+#ifdef CUSTOM_MODES
+static const unsigned char toOpusTable[20] = {
+      0xE0, 0xE8, 0xF0, 0xF8,
+      0xC0, 0xC8, 0xD0, 0xD8,
+      0xA0, 0xA8, 0xB0, 0xB8,
+      0x00, 0x00, 0x00, 0x00,
+      0x80, 0x88, 0x90, 0x98,
+};
+
+static const unsigned char fromOpusTable[16] = {
+      0x80, 0x88, 0x90, 0x98,
+      0x40, 0x48, 0x50, 0x58,
+      0x20, 0x28, 0x30, 0x38,
+      0x00, 0x08, 0x10, 0x18
+};
+
+static OPUS_INLINE int toOpus(unsigned char c)
+{
+   int ret=0;
+   if (c<0xA0)
+      ret = toOpusTable[c>>3];
+   if (ret == 0)
+      return -1;
+   else
+      return ret|(c&0x7);
+}
+
+static OPUS_INLINE int fromOpus(unsigned char c)
+{
+   if (c<0x80)
+      return -1;
+   else
+      return fromOpusTable[(c>>3)-16] | (c&0x7);
+}
+#endif /* CUSTOM_MODES */
+
+#define COMBFILTER_MAXPERIOD 1024
+#define COMBFILTER_MINPERIOD 15
+
+extern const signed char tf_select_table[4][8];
+
+int resampling_factor(opus_int32 rate);
+
+void celt_preemphasis(const opus_val16 * OPUS_RESTRICT pcmp, celt_sig * OPUS_RESTRICT inp,
+                        int N, int CC, int upsample, const opus_val16 *coef, celt_sig *mem, int clip);
+
+void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
+      opus_val16 g0, opus_val16 g1, int tapset0, int tapset1,
+      const opus_val16 *window, int overlap, int arch);
+
+#ifdef NON_STATIC_COMB_FILTER_CONST_C
+void comb_filter_const_c(opus_val32 *y, opus_val32 *x, int T, int N,
+                         opus_val16 g10, opus_val16 g11, opus_val16 g12);
+#endif
+
+#ifndef OVERRIDE_COMB_FILTER_CONST
+# define comb_filter_const(y, x, T, N, g10, g11, g12, arch) \
+    ((void)(arch),comb_filter_const_c(y, x, T, N, g10, g11, g12))
+#endif
+
+void init_caps(const CELTMode *m,int *cap,int LM,int C);
+
+#ifdef RESYNTH
+void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int C, int downsample, const opus_val16 *coef, celt_sig *mem);
+void celt_synthesis(const CELTMode *mode, celt_norm *X, celt_sig * out_syn[],
+      opus_val16 *oldBandE, int start, int effEnd, int C, int CC, int isTransient,
+      int LM, int downsample, int silence);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CELT_H */
diff --git a/opus/celt/celt_decoder.c b/opus/celt/celt_decoder.c
new file mode 100644 (file)
index 0000000..567d745
--- /dev/null
@@ -0,0 +1,1340 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2010 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#define CELT_DECODER_C
+
+#include "cpu_support.h"
+#include "os_support.h"
+#include "mdct.h"
+#include <math.h>
+#include "celt.h"
+#include "pitch.h"
+#include "bands.h"
+#include "modes.h"
+#include "entcode.h"
+#include "quant_bands.h"
+#include "rate.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "float_cast.h"
+#include <stdarg.h>
+#include "celt_lpc.h"
+#include "vq.h"
+
+#if defined(SMALL_FOOTPRINT) && defined(FIXED_POINT)
+#define NORM_ALIASING_HACK
+#endif
+/**********************************************************************/
+/*                                                                    */
+/*                             DECODER                                */
+/*                                                                    */
+/**********************************************************************/
+#define DECODE_BUFFER_SIZE 2048
+
+/** Decoder state
+ @brief Decoder state
+ */
+struct OpusCustomDecoder {
+   const OpusCustomMode *mode;
+   int overlap;
+   int channels;
+   int stream_channels;
+
+   int downsample;
+   int start, end;
+   int signalling;
+   int disable_inv;
+   int arch;
+
+   /* Everything beyond this point gets cleared on a reset */
+#define DECODER_RESET_START rng
+
+   opus_uint32 rng;
+   int error;
+   int last_pitch_index;
+   int loss_count;
+   int skip_plc;
+   int postfilter_period;
+   int postfilter_period_old;
+   opus_val16 postfilter_gain;
+   opus_val16 postfilter_gain_old;
+   int postfilter_tapset;
+   int postfilter_tapset_old;
+
+   celt_sig preemph_memD[2];
+
+   celt_sig _decode_mem[1]; /* Size = channels*(DECODE_BUFFER_SIZE+mode->overlap) */
+   /* opus_val16 lpc[],  Size = channels*LPC_ORDER */
+   /* opus_val16 oldEBands[], Size = 2*mode->nbEBands */
+   /* opus_val16 oldLogE[], Size = 2*mode->nbEBands */
+   /* opus_val16 oldLogE2[], Size = 2*mode->nbEBands */
+   /* opus_val16 backgroundLogE[], Size = 2*mode->nbEBands */
+};
+
+int celt_decoder_get_size(int channels)
+{
+   const CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
+   return opus_custom_decoder_get_size(mode, channels);
+}
+
+OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_get_size(const CELTMode *mode, int channels)
+{
+   int size = sizeof(struct CELTDecoder)
+            + (channels*(DECODE_BUFFER_SIZE+mode->overlap)-1)*sizeof(celt_sig)
+            + channels*LPC_ORDER*sizeof(opus_val16)
+            + 4*2*mode->nbEBands*sizeof(opus_val16);
+   return size;
+}
+
+#ifdef CUSTOM_MODES
+CELTDecoder *opus_custom_decoder_create(const CELTMode *mode, int channels, int *error)
+{
+   int ret;
+   CELTDecoder *st = (CELTDecoder *)opus_alloc(opus_custom_decoder_get_size(mode, channels));
+   ret = opus_custom_decoder_init(st, mode, channels);
+   if (ret != OPUS_OK)
+   {
+      opus_custom_decoder_destroy(st);
+      st = NULL;
+   }
+   if (error)
+      *error = ret;
+   return st;
+}
+#endif /* CUSTOM_MODES */
+
+int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels)
+{
+   int ret;
+   ret = opus_custom_decoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
+   if (ret != OPUS_OK)
+      return ret;
+   st->downsample = resampling_factor(sampling_rate);
+   if (st->downsample==0)
+      return OPUS_BAD_ARG;
+   else
+      return OPUS_OK;
+}
+
+OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_init(CELTDecoder *st, const CELTMode *mode, int channels)
+{
+   if (channels < 0 || channels > 2)
+      return OPUS_BAD_ARG;
+
+   if (st==NULL)
+      return OPUS_ALLOC_FAIL;
+
+   OPUS_CLEAR((char*)st, opus_custom_decoder_get_size(mode, channels));
+
+   st->mode = mode;
+   st->overlap = mode->overlap;
+   st->stream_channels = st->channels = channels;
+
+   st->downsample = 1;
+   st->start = 0;
+   st->end = st->mode->effEBands;
+   st->signalling = 1;
+#ifdef ENABLE_UPDATE_DRAFT
+   st->disable_inv = channels == 1;
+#else
+   st->disable_inv = 0;
+#endif
+   st->arch = opus_select_arch();
+
+   opus_custom_decoder_ctl(st, OPUS_RESET_STATE);
+
+   return OPUS_OK;
+}
+
+#ifdef CUSTOM_MODES
+void opus_custom_decoder_destroy(CELTDecoder *st)
+{
+   opus_free(st);
+}
+#endif /* CUSTOM_MODES */
+
+#ifndef CUSTOM_MODES
+/* Special case for stereo with no downsampling and no accumulation. This is
+   quite common and we can make it faster by processing both channels in the
+   same loop, reducing overhead due to the dependency loop in the IIR filter. */
+static void deemphasis_stereo_simple(celt_sig *in[], opus_val16 *pcm, int N, const opus_val16 coef0,
+      celt_sig *mem)
+{
+   celt_sig * OPUS_RESTRICT x0;
+   celt_sig * OPUS_RESTRICT x1;
+   celt_sig m0, m1;
+   int j;
+   x0=in[0];
+   x1=in[1];
+   m0 = mem[0];
+   m1 = mem[1];
+   for (j=0;j<N;j++)
+   {
+      celt_sig tmp0, tmp1;
+      /* Add VERY_SMALL to x[] first to reduce dependency chain. */
+      tmp0 = x0[j] + VERY_SMALL + m0;
+      tmp1 = x1[j] + VERY_SMALL + m1;
+      m0 = MULT16_32_Q15(coef0, tmp0);
+      m1 = MULT16_32_Q15(coef0, tmp1);
+      pcm[2*j  ] = SCALEOUT(SIG2WORD16(tmp0));
+      pcm[2*j+1] = SCALEOUT(SIG2WORD16(tmp1));
+   }
+   mem[0] = m0;
+   mem[1] = m1;
+}
+#endif
+
+#ifndef RESYNTH
+static
+#endif
+void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int C, int downsample, const opus_val16 *coef,
+      celt_sig *mem, int accum)
+{
+   int c;
+   int Nd;
+   int apply_downsampling=0;
+   opus_val16 coef0;
+   VARDECL(celt_sig, scratch);
+   SAVE_STACK;
+#ifndef CUSTOM_MODES
+   /* Short version for common case. */
+   if (downsample == 1 && C == 2 && !accum)
+   {
+      deemphasis_stereo_simple(in, pcm, N, coef[0], mem);
+      return;
+   }
+#endif
+#ifndef FIXED_POINT
+   (void)accum;
+   celt_assert(accum==0);
+#endif
+   ALLOC(scratch, N, celt_sig);
+   coef0 = coef[0];
+   Nd = N/downsample;
+   c=0; do {
+      int j;
+      celt_sig * OPUS_RESTRICT x;
+      opus_val16  * OPUS_RESTRICT y;
+      celt_sig m = mem[c];
+      x =in[c];
+      y = pcm+c;
+#ifdef CUSTOM_MODES
+      if (coef[1] != 0)
+      {
+         opus_val16 coef1 = coef[1];
+         opus_val16 coef3 = coef[3];
+         for (j=0;j<N;j++)
+         {
+            celt_sig tmp = x[j] + m + VERY_SMALL;
+            m = MULT16_32_Q15(coef0, tmp)
+                          - MULT16_32_Q15(coef1, x[j]);
+            tmp = SHL32(MULT16_32_Q15(coef3, tmp), 2);
+            scratch[j] = tmp;
+         }
+         apply_downsampling=1;
+      } else
+#endif
+      if (downsample>1)
+      {
+         /* Shortcut for the standard (non-custom modes) case */
+         for (j=0;j<N;j++)
+         {
+            celt_sig tmp = x[j] + VERY_SMALL + m;
+            m = MULT16_32_Q15(coef0, tmp);
+            scratch[j] = tmp;
+         }
+         apply_downsampling=1;
+      } else {
+         /* Shortcut for the standard (non-custom modes) case */
+#ifdef FIXED_POINT
+         if (accum)
+         {
+            for (j=0;j<N;j++)
+            {
+               celt_sig tmp = x[j] + m + VERY_SMALL;
+               m = MULT16_32_Q15(coef0, tmp);
+               y[j*C] = SAT16(ADD32(y[j*C], SCALEOUT(SIG2WORD16(tmp))));
+            }
+         } else
+#endif
+         {
+            for (j=0;j<N;j++)
+            {
+               celt_sig tmp = x[j] + VERY_SMALL + m;
+               m = MULT16_32_Q15(coef0, tmp);
+               y[j*C] = SCALEOUT(SIG2WORD16(tmp));
+            }
+         }
+      }
+      mem[c] = m;
+
+      if (apply_downsampling)
+      {
+         /* Perform down-sampling */
+#ifdef FIXED_POINT
+         if (accum)
+         {
+            for (j=0;j<Nd;j++)
+               y[j*C] = SAT16(ADD32(y[j*C], SCALEOUT(SIG2WORD16(scratch[j*downsample]))));
+         } else
+#endif
+         {
+            for (j=0;j<Nd;j++)
+               y[j*C] = SCALEOUT(SIG2WORD16(scratch[j*downsample]));
+         }
+      }
+   } while (++c<C);
+   RESTORE_STACK;
+}
+
+#ifndef RESYNTH
+static
+#endif
+void celt_synthesis(const CELTMode *mode, celt_norm *X, celt_sig * out_syn[],
+                    opus_val16 *oldBandE, int start, int effEnd, int C, int CC,
+                    int isTransient, int LM, int downsample,
+                    int silence, int arch)
+{
+   int c, i;
+   int M;
+   int b;
+   int B;
+   int N, NB;
+   int shift;
+   int nbEBands;
+   int overlap;
+   VARDECL(celt_sig, freq);
+   SAVE_STACK;
+
+   overlap = mode->overlap;
+   nbEBands = mode->nbEBands;
+   N = mode->shortMdctSize<<LM;
+   ALLOC(freq, N, celt_sig); /**< Interleaved signal MDCTs */
+   M = 1<<LM;
+
+   if (isTransient)
+   {
+      B = M;
+      NB = mode->shortMdctSize;
+      shift = mode->maxLM;
+   } else {
+      B = 1;
+      NB = mode->shortMdctSize<<LM;
+      shift = mode->maxLM-LM;
+   }
+
+   if (CC==2&&C==1)
+   {
+      /* Copying a mono streams to two channels */
+      celt_sig *freq2;
+      denormalise_bands(mode, X, freq, oldBandE, start, effEnd, M,
+            downsample, silence);
+      /* Store a temporary copy in the output buffer because the IMDCT destroys its input. */
+      freq2 = out_syn[1]+overlap/2;
+      OPUS_COPY(freq2, freq, N);
+      for (b=0;b<B;b++)
+         clt_mdct_backward(&mode->mdct, &freq2[b], out_syn[0]+NB*b, mode->window, overlap, shift, B, arch);
+      for (b=0;b<B;b++)
+         clt_mdct_backward(&mode->mdct, &freq[b], out_syn[1]+NB*b, mode->window, overlap, shift, B, arch);
+   } else if (CC==1&&C==2)
+   {
+      /* Downmixing a stereo stream to mono */
+      celt_sig *freq2;
+      freq2 = out_syn[0]+overlap/2;
+      denormalise_bands(mode, X, freq, oldBandE, start, effEnd, M,
+            downsample, silence);
+      /* Use the output buffer as temp array before downmixing. */
+      denormalise_bands(mode, X+N, freq2, oldBandE+nbEBands, start, effEnd, M,
+            downsample, silence);
+      for (i=0;i<N;i++)
+         freq[i] = ADD32(HALF32(freq[i]), HALF32(freq2[i]));
+      for (b=0;b<B;b++)
+         clt_mdct_backward(&mode->mdct, &freq[b], out_syn[0]+NB*b, mode->window, overlap, shift, B, arch);
+   } else {
+      /* Normal case (mono or stereo) */
+      c=0; do {
+         denormalise_bands(mode, X+c*N, freq, oldBandE+c*nbEBands, start, effEnd, M,
+               downsample, silence);
+         for (b=0;b<B;b++)
+            clt_mdct_backward(&mode->mdct, &freq[b], out_syn[c]+NB*b, mode->window, overlap, shift, B, arch);
+      } while (++c<CC);
+   }
+   /* Saturate IMDCT output so that we can't overflow in the pitch postfilter
+      or in the */
+   c=0; do {
+      for (i=0;i<N;i++)
+         out_syn[c][i] = SATURATE(out_syn[c][i], SIG_SAT);
+   } while (++c<CC);
+   RESTORE_STACK;
+}
+
+static void tf_decode(int start, int end, int isTransient, int *tf_res, int LM, ec_dec *dec)
+{
+   int i, curr, tf_select;
+   int tf_select_rsv;
+   int tf_changed;
+   int logp;
+   opus_uint32 budget;
+   opus_uint32 tell;
+
+   budget = dec->storage*8;
+   tell = ec_tell(dec);
+   logp = isTransient ? 2 : 4;
+   tf_select_rsv = LM>0 && tell+logp+1<=budget;
+   budget -= tf_select_rsv;
+   tf_changed = curr = 0;
+   for (i=start;i<end;i++)
+   {
+      if (tell+logp<=budget)
+      {
+         curr ^= ec_dec_bit_logp(dec, logp);
+         tell = ec_tell(dec);
+         tf_changed |= curr;
+      }
+      tf_res[i] = curr;
+      logp = isTransient ? 4 : 5;
+   }
+   tf_select = 0;
+   if (tf_select_rsv &&
+     tf_select_table[LM][4*isTransient+0+tf_changed] !=
+     tf_select_table[LM][4*isTransient+2+tf_changed])
+   {
+      tf_select = ec_dec_bit_logp(dec, 1);
+   }
+   for (i=start;i<end;i++)
+   {
+      tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
+   }
+}
+
+/* The maximum pitch lag to allow in the pitch-based PLC. It's possible to save
+   CPU time in the PLC pitch search by making this smaller than MAX_PERIOD. The
+   current value corresponds to a pitch of 66.67 Hz. */
+#define PLC_PITCH_LAG_MAX (720)
+/* The minimum pitch lag to allow in the pitch-based PLC. This corresponds to a
+   pitch of 480 Hz. */
+#define PLC_PITCH_LAG_MIN (100)
+
+static int celt_plc_pitch_search(celt_sig *decode_mem[2], int C, int arch)
+{
+   int pitch_index;
+   VARDECL( opus_val16, lp_pitch_buf );
+   SAVE_STACK;
+   ALLOC( lp_pitch_buf, DECODE_BUFFER_SIZE>>1, opus_val16 );
+   pitch_downsample(decode_mem, lp_pitch_buf,
+         DECODE_BUFFER_SIZE, C, arch);
+   pitch_search(lp_pitch_buf+(PLC_PITCH_LAG_MAX>>1), lp_pitch_buf,
+         DECODE_BUFFER_SIZE-PLC_PITCH_LAG_MAX,
+         PLC_PITCH_LAG_MAX-PLC_PITCH_LAG_MIN, &pitch_index, arch);
+   pitch_index = PLC_PITCH_LAG_MAX-pitch_index;
+   RESTORE_STACK;
+   return pitch_index;
+}
+
+static void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, int N, int LM)
+{
+   int c;
+   int i;
+   const int C = st->channels;
+   celt_sig *decode_mem[2];
+   celt_sig *out_syn[2];
+   opus_val16 *lpc;
+   opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
+   const OpusCustomMode *mode;
+   int nbEBands;
+   int overlap;
+   int start;
+   int loss_count;
+   int noise_based;
+   const opus_int16 *eBands;
+   SAVE_STACK;
+
+   mode = st->mode;
+   nbEBands = mode->nbEBands;
+   overlap = mode->overlap;
+   eBands = mode->eBands;
+
+   c=0; do {
+      decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+overlap);
+      out_syn[c] = decode_mem[c]+DECODE_BUFFER_SIZE-N;
+   } while (++c<C);
+   lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+overlap)*C);
+   oldBandE = lpc+C*LPC_ORDER;
+   oldLogE = oldBandE + 2*nbEBands;
+   oldLogE2 = oldLogE + 2*nbEBands;
+   backgroundLogE = oldLogE2  + 2*nbEBands;
+
+   loss_count = st->loss_count;
+   start = st->start;
+   noise_based = loss_count >= 5 || start != 0 || st->skip_plc;
+   if (noise_based)
+   {
+      /* Noise-based PLC/CNG */
+#ifdef NORM_ALIASING_HACK
+      celt_norm *X;
+#else
+      VARDECL(celt_norm, X);
+#endif
+      opus_uint32 seed;
+      int end;
+      int effEnd;
+      opus_val16 decay;
+      end = st->end;
+      effEnd = IMAX(start, IMIN(end, mode->effEBands));
+
+#ifdef NORM_ALIASING_HACK
+      /* This is an ugly hack that breaks aliasing rules and would be easily broken,
+         but it saves almost 4kB of stack. */
+      X = (celt_norm*)(out_syn[C-1]+overlap/2);
+#else
+      ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
+#endif
+
+      /* Energy decay */
+      decay = loss_count==0 ? QCONST16(1.5f, DB_SHIFT) : QCONST16(.5f, DB_SHIFT);
+      c=0; do
+      {
+         for (i=start;i<end;i++)
+            oldBandE[c*nbEBands+i] = MAX16(backgroundLogE[c*nbEBands+i], oldBandE[c*nbEBands+i] - decay);
+      } while (++c<C);
+      seed = st->rng;
+      for (c=0;c<C;c++)
+      {
+         for (i=start;i<effEnd;i++)
+         {
+            int j;
+            int boffs;
+            int blen;
+            boffs = N*c+(eBands[i]<<LM);
+            blen = (eBands[i+1]-eBands[i])<<LM;
+            for (j=0;j<blen;j++)
+            {
+               seed = celt_lcg_rand(seed);
+               X[boffs+j] = (celt_norm)((opus_int32)seed>>20);
+            }
+            renormalise_vector(X+boffs, blen, Q15ONE, st->arch);
+         }
+      }
+      st->rng = seed;
+
+      c=0; do {
+         OPUS_MOVE(decode_mem[c], decode_mem[c]+N,
+               DECODE_BUFFER_SIZE-N+(overlap>>1));
+      } while (++c<C);
+
+      celt_synthesis(mode, X, out_syn, oldBandE, start, effEnd, C, C, 0, LM, st->downsample, 0, st->arch);
+   } else {
+      /* Pitch-based PLC */
+      const opus_val16 *window;
+      opus_val16 *exc;
+      opus_val16 fade = Q15ONE;
+      int pitch_index;
+      VARDECL(opus_val32, etmp);
+      VARDECL(opus_val16, _exc);
+
+      if (loss_count == 0)
+      {
+         st->last_pitch_index = pitch_index = celt_plc_pitch_search(decode_mem, C, st->arch);
+      } else {
+         pitch_index = st->last_pitch_index;
+         fade = QCONST16(.8f,15);
+      }
+
+      ALLOC(etmp, overlap, opus_val32);
+      ALLOC(_exc, MAX_PERIOD+LPC_ORDER, opus_val16);
+      exc = _exc+LPC_ORDER;
+      window = mode->window;
+      c=0; do {
+         opus_val16 decay;
+         opus_val16 attenuation;
+         opus_val32 S1=0;
+         celt_sig *buf;
+         int extrapolation_offset;
+         int extrapolation_len;
+         int exc_length;
+         int j;
+
+         buf = decode_mem[c];
+         for (i=0;i<MAX_PERIOD;i++) {
+            exc[i] = ROUND16(buf[DECODE_BUFFER_SIZE-MAX_PERIOD+i], SIG_SHIFT);
+         }
+
+         if (loss_count == 0)
+         {
+            opus_val32 ac[LPC_ORDER+1];
+            /* Compute LPC coefficients for the last MAX_PERIOD samples before
+               the first loss so we can work in the excitation-filter domain. */
+            _celt_autocorr(exc, ac, window, overlap,
+                   LPC_ORDER, MAX_PERIOD, st->arch);
+            /* Add a noise floor of -40 dB. */
+#ifdef FIXED_POINT
+            ac[0] += SHR32(ac[0],13);
+#else
+            ac[0] *= 1.0001f;
+#endif
+            /* Use lag windowing to stabilize the Levinson-Durbin recursion. */
+            for (i=1;i<=LPC_ORDER;i++)
+            {
+               /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
+#ifdef FIXED_POINT
+               ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
+#else
+               ac[i] -= ac[i]*(0.008f*0.008f)*i*i;
+#endif
+            }
+            _celt_lpc(lpc+c*LPC_ORDER, ac, LPC_ORDER);
+#ifdef FIXED_POINT
+         /* For fixed-point, apply bandwidth expansion until we can guarantee that
+            no overflow can happen in the IIR filter. This means:
+            32768*sum(abs(filter)) < 2^31 */
+         while (1) {
+            opus_val16 tmp=Q15ONE;
+            opus_val32 sum=QCONST16(1., SIG_SHIFT);
+            for (i=0;i<LPC_ORDER;i++)
+               sum += ABS16(lpc[c*LPC_ORDER+i]);
+            if (sum < 65535) break;
+            for (i=0;i<LPC_ORDER;i++)
+            {
+               tmp = MULT16_16_Q15(QCONST16(.99f,15), tmp);
+               lpc[c*LPC_ORDER+i] = MULT16_16_Q15(lpc[c*LPC_ORDER+i], tmp);
+            }
+         }
+#endif
+         }
+         /* We want the excitation for 2 pitch periods in order to look for a
+            decaying signal, but we can't get more than MAX_PERIOD. */
+         exc_length = IMIN(2*pitch_index, MAX_PERIOD);
+         /* Initialize the LPC history with the samples just before the start
+            of the region for which we're computing the excitation. */
+         {
+            for (i=0;i<LPC_ORDER;i++)
+            {
+               exc[MAX_PERIOD-exc_length-LPC_ORDER+i] =
+                     ROUND16(buf[DECODE_BUFFER_SIZE-exc_length-LPC_ORDER+i], SIG_SHIFT);
+            }
+            /* Compute the excitation for exc_length samples before the loss. */
+            celt_fir(exc+MAX_PERIOD-exc_length, lpc+c*LPC_ORDER,
+                  exc+MAX_PERIOD-exc_length, exc_length, LPC_ORDER, st->arch);
+         }
+
+         /* Check if the waveform is decaying, and if so how fast.
+            We do this to avoid adding energy when concealing in a segment
+            with decaying energy. */
+         {
+            opus_val32 E1=1, E2=1;
+            int decay_length;
+#ifdef FIXED_POINT
+            int shift = IMAX(0,2*celt_zlog2(celt_maxabs16(&exc[MAX_PERIOD-exc_length], exc_length))-20);
+#endif
+            decay_length = exc_length>>1;
+            for (i=0;i<decay_length;i++)
+            {
+               opus_val16 e;
+               e = exc[MAX_PERIOD-decay_length+i];
+               E1 += SHR32(MULT16_16(e, e), shift);
+               e = exc[MAX_PERIOD-2*decay_length+i];
+               E2 += SHR32(MULT16_16(e, e), shift);
+            }
+            E1 = MIN32(E1, E2);
+            decay = celt_sqrt(frac_div32(SHR32(E1, 1), E2));
+         }
+
+         /* Move the decoder memory one frame to the left to give us room to
+            add the data for the new frame. We ignore the overlap that extends
+            past the end of the buffer, because we aren't going to use it. */
+         OPUS_MOVE(buf, buf+N, DECODE_BUFFER_SIZE-N);
+
+         /* Extrapolate from the end of the excitation with a period of
+            "pitch_index", scaling down each period by an additional factor of
+            "decay". */
+         extrapolation_offset = MAX_PERIOD-pitch_index;
+         /* We need to extrapolate enough samples to cover a complete MDCT
+            window (including overlap/2 samples on both sides). */
+         extrapolation_len = N+overlap;
+         /* We also apply fading if this is not the first loss. */
+         attenuation = MULT16_16_Q15(fade, decay);
+         for (i=j=0;i<extrapolation_len;i++,j++)
+         {
+            opus_val16 tmp;
+            if (j >= pitch_index) {
+               j -= pitch_index;
+               attenuation = MULT16_16_Q15(attenuation, decay);
+            }
+            buf[DECODE_BUFFER_SIZE-N+i] =
+                  SHL32(EXTEND32(MULT16_16_Q15(attenuation,
+                        exc[extrapolation_offset+j])), SIG_SHIFT);
+            /* Compute the energy of the previously decoded signal whose
+               excitation we're copying. */
+            tmp = ROUND16(
+                  buf[DECODE_BUFFER_SIZE-MAX_PERIOD-N+extrapolation_offset+j],
+                  SIG_SHIFT);
+            S1 += SHR32(MULT16_16(tmp, tmp), 10);
+         }
+         {
+            opus_val16 lpc_mem[LPC_ORDER];
+            /* Copy the last decoded samples (prior to the overlap region) to
+               synthesis filter memory so we can have a continuous signal. */
+            for (i=0;i<LPC_ORDER;i++)
+               lpc_mem[i] = ROUND16(buf[DECODE_BUFFER_SIZE-N-1-i], SIG_SHIFT);
+            /* Apply the synthesis filter to convert the excitation back into
+               the signal domain. */
+            celt_iir(buf+DECODE_BUFFER_SIZE-N, lpc+c*LPC_ORDER,
+                  buf+DECODE_BUFFER_SIZE-N, extrapolation_len, LPC_ORDER,
+                  lpc_mem, st->arch);
+#ifdef FIXED_POINT
+            for (i=0; i < extrapolation_len; i++)
+               buf[DECODE_BUFFER_SIZE-N+i] = SATURATE(buf[DECODE_BUFFER_SIZE-N+i], SIG_SAT);
+#endif
+         }
+
+         /* Check if the synthesis energy is higher than expected, which can
+            happen with the signal changes during our window. If so,
+            attenuate. */
+         {
+            opus_val32 S2=0;
+            for (i=0;i<extrapolation_len;i++)
+            {
+               opus_val16 tmp = ROUND16(buf[DECODE_BUFFER_SIZE-N+i], SIG_SHIFT);
+               S2 += SHR32(MULT16_16(tmp, tmp), 10);
+            }
+            /* This checks for an "explosion" in the synthesis. */
+#ifdef FIXED_POINT
+            if (!(S1 > SHR32(S2,2)))
+#else
+            /* The float test is written this way to catch NaNs in the output
+               of the IIR filter at the same time. */
+            if (!(S1 > 0.2f*S2))
+#endif
+            {
+               for (i=0;i<extrapolation_len;i++)
+                  buf[DECODE_BUFFER_SIZE-N+i] = 0;
+            } else if (S1 < S2)
+            {
+               opus_val16 ratio = celt_sqrt(frac_div32(SHR32(S1,1)+1,S2+1));
+               for (i=0;i<overlap;i++)
+               {
+                  opus_val16 tmp_g = Q15ONE
+                        - MULT16_16_Q15(window[i], Q15ONE-ratio);
+                  buf[DECODE_BUFFER_SIZE-N+i] =
+                        MULT16_32_Q15(tmp_g, buf[DECODE_BUFFER_SIZE-N+i]);
+               }
+               for (i=overlap;i<extrapolation_len;i++)
+               {
+                  buf[DECODE_BUFFER_SIZE-N+i] =
+                        MULT16_32_Q15(ratio, buf[DECODE_BUFFER_SIZE-N+i]);
+               }
+            }
+         }
+
+         /* Apply the pre-filter to the MDCT overlap for the next frame because
+            the post-filter will be re-applied in the decoder after the MDCT
+            overlap. */
+         comb_filter(etmp, buf+DECODE_BUFFER_SIZE,
+              st->postfilter_period, st->postfilter_period, overlap,
+              -st->postfilter_gain, -st->postfilter_gain,
+              st->postfilter_tapset, st->postfilter_tapset, NULL, 0, st->arch);
+
+         /* Simulate TDAC on the concealed audio so that it blends with the
+            MDCT of the next frame. */
+         for (i=0;i<overlap/2;i++)
+         {
+            buf[DECODE_BUFFER_SIZE+i] =
+               MULT16_32_Q15(window[i], etmp[overlap-1-i])
+               + MULT16_32_Q15(window[overlap-i-1], etmp[i]);
+         }
+      } while (++c<C);
+   }
+
+   st->loss_count = loss_count+1;
+
+   RESTORE_STACK;
+}
+
+int celt_decode_with_ec(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data,
+      int len, opus_val16 * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec, int accum)
+{
+   int c, i, N;
+   int spread_decision;
+   opus_int32 bits;
+   ec_dec _dec;
+#ifdef NORM_ALIASING_HACK
+   celt_norm *X;
+#else
+   VARDECL(celt_norm, X);
+#endif
+   VARDECL(int, fine_quant);
+   VARDECL(int, pulses);
+   VARDECL(int, cap);
+   VARDECL(int, offsets);
+   VARDECL(int, fine_priority);
+   VARDECL(int, tf_res);
+   VARDECL(unsigned char, collapse_masks);
+   celt_sig *decode_mem[2];
+   celt_sig *out_syn[2];
+   opus_val16 *lpc;
+   opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
+
+   int shortBlocks;
+   int isTransient;
+   int intra_ener;
+   const int CC = st->channels;
+   int LM, M;
+   int start;
+   int end;
+   int effEnd;
+   int codedBands;
+   int alloc_trim;
+   int postfilter_pitch;
+   opus_val16 postfilter_gain;
+   int intensity=0;
+   int dual_stereo=0;
+   opus_int32 total_bits;
+   opus_int32 balance;
+   opus_int32 tell;
+   int dynalloc_logp;
+   int postfilter_tapset;
+   int anti_collapse_rsv;
+   int anti_collapse_on=0;
+   int silence;
+   int C = st->stream_channels;
+   const OpusCustomMode *mode;
+   int nbEBands;
+   int overlap;
+   const opus_int16 *eBands;
+   ALLOC_STACK;
+
+   mode = st->mode;
+   nbEBands = mode->nbEBands;
+   overlap = mode->overlap;
+   eBands = mode->eBands;
+   start = st->start;
+   end = st->end;
+   frame_size *= st->downsample;
+
+   lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+overlap)*CC);
+   oldBandE = lpc+CC*LPC_ORDER;
+   oldLogE = oldBandE + 2*nbEBands;
+   oldLogE2 = oldLogE + 2*nbEBands;
+   backgroundLogE = oldLogE2  + 2*nbEBands;
+
+#ifdef CUSTOM_MODES
+   if (st->signalling && data!=NULL)
+   {
+      int data0=data[0];
+      /* Convert "standard mode" to Opus header */
+      if (mode->Fs==48000 && mode->shortMdctSize==120)
+      {
+         data0 = fromOpus(data0);
+         if (data0<0)
+            return OPUS_INVALID_PACKET;
+      }
+      st->end = end = IMAX(1, mode->effEBands-2*(data0>>5));
+      LM = (data0>>3)&0x3;
+      C = 1 + ((data0>>2)&0x1);
+      data++;
+      len--;
+      if (LM>mode->maxLM)
+         return OPUS_INVALID_PACKET;
+      if (frame_size < mode->shortMdctSize<<LM)
+         return OPUS_BUFFER_TOO_SMALL;
+      else
+         frame_size = mode->shortMdctSize<<LM;
+   } else {
+#else
+   {
+#endif
+      for (LM=0;LM<=mode->maxLM;LM++)
+         if (mode->shortMdctSize<<LM==frame_size)
+            break;
+      if (LM>mode->maxLM)
+         return OPUS_BAD_ARG;
+   }
+   M=1<<LM;
+
+   if (len<0 || len>1275 || pcm==NULL)
+      return OPUS_BAD_ARG;
+
+   N = M*mode->shortMdctSize;
+   c=0; do {
+      decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+overlap);
+      out_syn[c] = decode_mem[c]+DECODE_BUFFER_SIZE-N;
+   } while (++c<CC);
+
+   effEnd = end;
+   if (effEnd > mode->effEBands)
+      effEnd = mode->effEBands;
+
+   if (data == NULL || len<=1)
+   {
+      celt_decode_lost(st, N, LM);
+      deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, accum);
+      RESTORE_STACK;
+      return frame_size/st->downsample;
+   }
+
+   /* Check if there are at least two packets received consecutively before
+    * turning on the pitch-based PLC */
+   st->skip_plc = st->loss_count != 0;
+
+   if (dec == NULL)
+   {
+      ec_dec_init(&_dec,(unsigned char*)data,len);
+      dec = &_dec;
+   }
+
+   if (C==1)
+   {
+      for (i=0;i<nbEBands;i++)
+         oldBandE[i]=MAX16(oldBandE[i],oldBandE[nbEBands+i]);
+   }
+
+   total_bits = len*8;
+   tell = ec_tell(dec);
+
+   if (tell >= total_bits)
+      silence = 1;
+   else if (tell==1)
+      silence = ec_dec_bit_logp(dec, 15);
+   else
+      silence = 0;
+   if (silence)
+   {
+      /* Pretend we've read all the remaining bits */
+      tell = len*8;
+      dec->nbits_total+=tell-ec_tell(dec);
+   }
+
+   postfilter_gain = 0;
+   postfilter_pitch = 0;
+   postfilter_tapset = 0;
+   if (start==0 && tell+16 <= total_bits)
+   {
+      if(ec_dec_bit_logp(dec, 1))
+      {
+         int qg, octave;
+         octave = ec_dec_uint(dec, 6);
+         postfilter_pitch = (16<<octave)+ec_dec_bits(dec, 4+octave)-1;
+         qg = ec_dec_bits(dec, 3);
+         if (ec_tell(dec)+2<=total_bits)
+            postfilter_tapset = ec_dec_icdf(dec, tapset_icdf, 2);
+         postfilter_gain = QCONST16(.09375f,15)*(qg+1);
+      }
+      tell = ec_tell(dec);
+   }
+
+   if (LM > 0 && tell+3 <= total_bits)
+   {
+      isTransient = ec_dec_bit_logp(dec, 3);
+      tell = ec_tell(dec);
+   }
+   else
+      isTransient = 0;
+
+   if (isTransient)
+      shortBlocks = M;
+   else
+      shortBlocks = 0;
+
+   /* Decode the global flags (first symbols in the stream) */
+   intra_ener = tell+3<=total_bits ? ec_dec_bit_logp(dec, 3) : 0;
+   /* Get band energies */
+   unquant_coarse_energy(mode, start, end, oldBandE,
+         intra_ener, dec, C, LM);
+
+   ALLOC(tf_res, nbEBands, int);
+   tf_decode(start, end, isTransient, tf_res, LM, dec);
+
+   tell = ec_tell(dec);
+   spread_decision = SPREAD_NORMAL;
+   if (tell+4 <= total_bits)
+      spread_decision = ec_dec_icdf(dec, spread_icdf, 5);
+
+   ALLOC(cap, nbEBands, int);
+
+   init_caps(mode,cap,LM,C);
+
+   ALLOC(offsets, nbEBands, int);
+
+   dynalloc_logp = 6;
+   total_bits<<=BITRES;
+   tell = ec_tell_frac(dec);
+   for (i=start;i<end;i++)
+   {
+      int width, quanta;
+      int dynalloc_loop_logp;
+      int boost;
+      width = C*(eBands[i+1]-eBands[i])<<LM;
+      /* quanta is 6 bits, but no more than 1 bit/sample
+         and no less than 1/8 bit/sample */
+      quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
+      dynalloc_loop_logp = dynalloc_logp;
+      boost = 0;
+      while (tell+(dynalloc_loop_logp<<BITRES) < total_bits && boost < cap[i])
+      {
+         int flag;
+         flag = ec_dec_bit_logp(dec, dynalloc_loop_logp);
+         tell = ec_tell_frac(dec);
+         if (!flag)
+            break;
+         boost += quanta;
+         total_bits -= quanta;
+         dynalloc_loop_logp = 1;
+      }
+      offsets[i] = boost;
+      /* Making dynalloc more likely */
+      if (boost>0)
+         dynalloc_logp = IMAX(2, dynalloc_logp-1);
+   }
+
+   ALLOC(fine_quant, nbEBands, int);
+   alloc_trim = tell+(6<<BITRES) <= total_bits ?
+         ec_dec_icdf(dec, trim_icdf, 7) : 5;
+
+   bits = (((opus_int32)len*8)<<BITRES) - ec_tell_frac(dec) - 1;
+   anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
+   bits -= anti_collapse_rsv;
+
+   ALLOC(pulses, nbEBands, int);
+   ALLOC(fine_priority, nbEBands, int);
+
+   codedBands = compute_allocation(mode, start, end, offsets, cap,
+         alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
+         fine_quant, fine_priority, C, LM, dec, 0, 0, 0);
+
+   unquant_fine_energy(mode, start, end, oldBandE, fine_quant, dec, C);
+
+   c=0; do {
+      OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap/2);
+   } while (++c<CC);
+
+   /* Decode fixed codebook */
+   ALLOC(collapse_masks, C*nbEBands, unsigned char);
+
+#ifdef NORM_ALIASING_HACK
+   /* This is an ugly hack that breaks aliasing rules and would be easily broken,
+      but it saves almost 4kB of stack. */
+   X = (celt_norm*)(out_syn[CC-1]+overlap/2);
+#else
+   ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
+#endif
+
+   quant_all_bands(0, mode, start, end, X, C==2 ? X+N : NULL, collapse_masks,
+         NULL, pulses, shortBlocks, spread_decision, dual_stereo, intensity, tf_res,
+         len*(8<<BITRES)-anti_collapse_rsv, balance, dec, LM, codedBands, &st->rng, 0,
+         st->arch, st->disable_inv);
+
+   if (anti_collapse_rsv > 0)
+   {
+      anti_collapse_on = ec_dec_bits(dec, 1);
+   }
+
+   unquant_energy_finalise(mode, start, end, oldBandE,
+         fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
+
+   if (anti_collapse_on)
+      anti_collapse(mode, X, collapse_masks, LM, C, N,
+            start, end, oldBandE, oldLogE, oldLogE2, pulses, st->rng, st->arch);
+
+   if (silence)
+   {
+      for (i=0;i<C*nbEBands;i++)
+         oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
+   }
+
+   celt_synthesis(mode, X, out_syn, oldBandE, start, effEnd,
+                  C, CC, isTransient, LM, st->downsample, silence, st->arch);
+
+   c=0; do {
+      st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
+      st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
+      comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, mode->shortMdctSize,
+            st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
+            mode->window, overlap, st->arch);
+      if (LM!=0)
+         comb_filter(out_syn[c]+mode->shortMdctSize, out_syn[c]+mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-mode->shortMdctSize,
+               st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
+               mode->window, overlap, st->arch);
+
+   } while (++c<CC);
+   st->postfilter_period_old = st->postfilter_period;
+   st->postfilter_gain_old = st->postfilter_gain;
+   st->postfilter_tapset_old = st->postfilter_tapset;
+   st->postfilter_period = postfilter_pitch;
+   st->postfilter_gain = postfilter_gain;
+   st->postfilter_tapset = postfilter_tapset;
+   if (LM!=0)
+   {
+      st->postfilter_period_old = st->postfilter_period;
+      st->postfilter_gain_old = st->postfilter_gain;
+      st->postfilter_tapset_old = st->postfilter_tapset;
+   }
+
+   if (C==1)
+      OPUS_COPY(&oldBandE[nbEBands], oldBandE, nbEBands);
+
+   /* In case start or end were to change */
+   if (!isTransient)
+   {
+      opus_val16 max_background_increase;
+      OPUS_COPY(oldLogE2, oldLogE, 2*nbEBands);
+      OPUS_COPY(oldLogE, oldBandE, 2*nbEBands);
+      /* In normal circumstances, we only allow the noise floor to increase by
+         up to 2.4 dB/second, but when we're in DTX, we allow up to 6 dB
+         increase for each update.*/
+      if (st->loss_count < 10)
+         max_background_increase = M*QCONST16(0.001f,DB_SHIFT);
+      else
+         max_background_increase = QCONST16(1.f,DB_SHIFT);
+      for (i=0;i<2*nbEBands;i++)
+         backgroundLogE[i] = MIN16(backgroundLogE[i] + max_background_increase, oldBandE[i]);
+   } else {
+      for (i=0;i<2*nbEBands;i++)
+         oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
+   }
+   c=0; do
+   {
+      for (i=0;i<start;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+      for (i=end;i<nbEBands;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+   } while (++c<2);
+   st->rng = dec->rng;
+
+   deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, accum);
+   st->loss_count = 0;
+   RESTORE_STACK;
+   if (ec_tell(dec) > 8*len)
+      return OPUS_INTERNAL_ERROR;
+   if(ec_get_error(dec))
+      st->error = 1;
+   return frame_size/st->downsample;
+}
+
+
+#ifdef CUSTOM_MODES
+
+#ifdef FIXED_POINT
+int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
+{
+   return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL, 0);
+}
+
+#ifndef DISABLE_FLOAT_API
+int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
+{
+   int j, ret, C, N;
+   VARDECL(opus_int16, out);
+   ALLOC_STACK;
+
+   if (pcm==NULL)
+      return OPUS_BAD_ARG;
+
+   C = st->channels;
+   N = frame_size;
+
+   ALLOC(out, C*N, opus_int16);
+   ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL, 0);
+   if (ret>0)
+      for (j=0;j<C*ret;j++)
+         pcm[j]=out[j]*(1.f/32768.f);
+
+   RESTORE_STACK;
+   return ret;
+}
+#endif /* DISABLE_FLOAT_API */
+
+#else
+
+int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
+{
+   return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL, 0);
+}
+
+int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
+{
+   int j, ret, C, N;
+   VARDECL(celt_sig, out);
+   ALLOC_STACK;
+
+   if (pcm==NULL)
+      return OPUS_BAD_ARG;
+
+   C = st->channels;
+   N = frame_size;
+   ALLOC(out, C*N, celt_sig);
+
+   ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL, 0);
+
+   if (ret>0)
+      for (j=0;j<C*ret;j++)
+         pcm[j] = FLOAT2INT16 (out[j]);
+
+   RESTORE_STACK;
+   return ret;
+}
+
+#endif
+#endif /* CUSTOM_MODES */
+
+int opus_custom_decoder_ctl(CELTDecoder * OPUS_RESTRICT st, int request, ...)
+{
+   va_list ap;
+
+   va_start(ap, request);
+   switch (request)
+   {
+      case CELT_SET_START_BAND_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<0 || value>=st->mode->nbEBands)
+            goto bad_arg;
+         st->start = value;
+      }
+      break;
+      case CELT_SET_END_BAND_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<1 || value>st->mode->nbEBands)
+            goto bad_arg;
+         st->end = value;
+      }
+      break;
+      case CELT_SET_CHANNELS_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<1 || value>2)
+            goto bad_arg;
+         st->stream_channels = value;
+      }
+      break;
+      case CELT_GET_AND_CLEAR_ERROR_REQUEST:
+      {
+         opus_int32 *value = va_arg(ap, opus_int32*);
+         if (value==NULL)
+            goto bad_arg;
+         *value=st->error;
+         st->error = 0;
+      }
+      break;
+      case OPUS_GET_LOOKAHEAD_REQUEST:
+      {
+         opus_int32 *value = va_arg(ap, opus_int32*);
+         if (value==NULL)
+            goto bad_arg;
+         *value = st->overlap/st->downsample;
+      }
+      break;
+      case OPUS_RESET_STATE:
+      {
+         int i;
+         opus_val16 *lpc, *oldBandE, *oldLogE, *oldLogE2;
+         lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*st->channels);
+         oldBandE = lpc+st->channels*LPC_ORDER;
+         oldLogE = oldBandE + 2*st->mode->nbEBands;
+         oldLogE2 = oldLogE + 2*st->mode->nbEBands;
+         OPUS_CLEAR((char*)&st->DECODER_RESET_START,
+               opus_custom_decoder_get_size(st->mode, st->channels)-
+               ((char*)&st->DECODER_RESET_START - (char*)st));
+         for (i=0;i<2*st->mode->nbEBands;i++)
+            oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
+         st->skip_plc = 1;
+      }
+      break;
+      case OPUS_GET_PITCH_REQUEST:
+      {
+         opus_int32 *value = va_arg(ap, opus_int32*);
+         if (value==NULL)
+            goto bad_arg;
+         *value = st->postfilter_period;
+      }
+      break;
+      case CELT_GET_MODE_REQUEST:
+      {
+         const CELTMode ** value = va_arg(ap, const CELTMode**);
+         if (value==0)
+            goto bad_arg;
+         *value=st->mode;
+      }
+      break;
+      case CELT_SET_SIGNALLING_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         st->signalling = value;
+      }
+      break;
+      case OPUS_GET_FINAL_RANGE_REQUEST:
+      {
+         opus_uint32 * value = va_arg(ap, opus_uint32 *);
+         if (value==0)
+            goto bad_arg;
+         *value=st->rng;
+      }
+      break;
+      case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+      {
+          opus_int32 value = va_arg(ap, opus_int32);
+          if(value<0 || value>1)
+          {
+             goto bad_arg;
+          }
+          st->disable_inv = value;
+      }
+      break;
+      case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+      {
+          opus_int32 *value = va_arg(ap, opus_int32*);
+          if (!value)
+          {
+             goto bad_arg;
+          }
+          *value = st->disable_inv;
+      }
+      break;
+      default:
+         goto bad_request;
+   }
+   va_end(ap);
+   return OPUS_OK;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
+bad_request:
+      va_end(ap);
+  return OPUS_UNIMPLEMENTED;
+}
diff --git a/opus/celt/celt_encoder.c b/opus/celt/celt_encoder.c
new file mode 100644 (file)
index 0000000..053e5a3
--- /dev/null
@@ -0,0 +1,2537 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2010 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#define CELT_ENCODER_C
+
+#include "cpu_support.h"
+#include "os_support.h"
+#include "mdct.h"
+#include <math.h>
+#include "celt.h"
+#include "pitch.h"
+#include "bands.h"
+#include "modes.h"
+#include "entcode.h"
+#include "quant_bands.h"
+#include "rate.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "float_cast.h"
+#include <stdarg.h>
+#include "celt_lpc.h"
+#include "vq.h"
+
+
+/** Encoder state
+ @brief Encoder state
+ */
+struct OpusCustomEncoder {
+   const OpusCustomMode *mode;     /**< Mode used by the encoder */
+   int channels;
+   int stream_channels;
+
+   int force_intra;
+   int clip;
+   int disable_pf;
+   int complexity;
+   int upsample;
+   int start, end;
+
+   opus_int32 bitrate;
+   int vbr;
+   int signalling;
+   int constrained_vbr;      /* If zero, VBR can do whatever it likes with the rate */
+   int loss_rate;
+   int lsb_depth;
+   int lfe;
+   int disable_inv;
+   int arch;
+
+   /* Everything beyond this point gets cleared on a reset */
+#define ENCODER_RESET_START rng
+
+   opus_uint32 rng;
+   int spread_decision;
+   opus_val32 delayedIntra;
+   int tonal_average;
+   int lastCodedBands;
+   int hf_average;
+   int tapset_decision;
+
+   int prefilter_period;
+   opus_val16 prefilter_gain;
+   int prefilter_tapset;
+#ifdef RESYNTH
+   int prefilter_period_old;
+   opus_val16 prefilter_gain_old;
+   int prefilter_tapset_old;
+#endif
+   int consec_transient;
+   AnalysisInfo analysis;
+   SILKInfo silk_info;
+
+   opus_val32 preemph_memE[2];
+   opus_val32 preemph_memD[2];
+
+   /* VBR-related parameters */
+   opus_int32 vbr_reservoir;
+   opus_int32 vbr_drift;
+   opus_int32 vbr_offset;
+   opus_int32 vbr_count;
+   opus_val32 overlap_max;
+   opus_val16 stereo_saving;
+   int intensity;
+   opus_val16 *energy_mask;
+   opus_val16 spec_avg;
+
+#ifdef RESYNTH
+   /* +MAX_PERIOD/2 to make space for overlap */
+   celt_sig syn_mem[2][2*MAX_PERIOD+MAX_PERIOD/2];
+#endif
+
+   celt_sig in_mem[1]; /* Size = channels*mode->overlap */
+   /* celt_sig prefilter_mem[],  Size = channels*COMBFILTER_MAXPERIOD */
+   /* opus_val16 oldBandE[],     Size = channels*mode->nbEBands */
+   /* opus_val16 oldLogE[],      Size = channels*mode->nbEBands */
+   /* opus_val16 oldLogE2[],     Size = channels*mode->nbEBands */
+   /* opus_val16 energyError[],  Size = channels*mode->nbEBands */
+};
+
+int celt_encoder_get_size(int channels)
+{
+   CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
+   return opus_custom_encoder_get_size(mode, channels);
+}
+
+OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels)
+{
+   int size = sizeof(struct CELTEncoder)
+         + (channels*mode->overlap-1)*sizeof(celt_sig)    /* celt_sig in_mem[channels*mode->overlap]; */
+         + channels*COMBFILTER_MAXPERIOD*sizeof(celt_sig) /* celt_sig prefilter_mem[channels*COMBFILTER_MAXPERIOD]; */
+         + 4*channels*mode->nbEBands*sizeof(opus_val16);  /* opus_val16 oldBandE[channels*mode->nbEBands]; */
+                                                          /* opus_val16 oldLogE[channels*mode->nbEBands]; */
+                                                          /* opus_val16 oldLogE2[channels*mode->nbEBands]; */
+                                                          /* opus_val16 energyError[channels*mode->nbEBands]; */
+   return size;
+}
+
+#ifdef CUSTOM_MODES
+CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error)
+{
+   int ret;
+   CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels));
+   /* init will handle the NULL case */
+   ret = opus_custom_encoder_init(st, mode, channels);
+   if (ret != OPUS_OK)
+   {
+      opus_custom_encoder_destroy(st);
+      st = NULL;
+   }
+   if (error)
+      *error = ret;
+   return st;
+}
+#endif /* CUSTOM_MODES */
+
+static int opus_custom_encoder_init_arch(CELTEncoder *st, const CELTMode *mode,
+                                         int channels, int arch)
+{
+   if (channels < 0 || channels > 2)
+      return OPUS_BAD_ARG;
+
+   if (st==NULL || mode==NULL)
+      return OPUS_ALLOC_FAIL;
+
+   OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels));
+
+   st->mode = mode;
+   st->stream_channels = st->channels = channels;
+
+   st->upsample = 1;
+   st->start = 0;
+   st->end = st->mode->effEBands;
+   st->signalling = 1;
+   st->arch = arch;
+
+   st->constrained_vbr = 1;
+   st->clip = 1;
+
+   st->bitrate = OPUS_BITRATE_MAX;
+   st->vbr = 0;
+   st->force_intra  = 0;
+   st->complexity = 5;
+   st->lsb_depth=24;
+
+   opus_custom_encoder_ctl(st, OPUS_RESET_STATE);
+
+   return OPUS_OK;
+}
+
+#ifdef CUSTOM_MODES
+int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
+{
+   return opus_custom_encoder_init_arch(st, mode, channels, opus_select_arch());
+}
+#endif
+
+int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels,
+                      int arch)
+{
+   int ret;
+   ret = opus_custom_encoder_init_arch(st,
+           opus_custom_mode_create(48000, 960, NULL), channels, arch);
+   if (ret != OPUS_OK)
+      return ret;
+   st->upsample = resampling_factor(sampling_rate);
+   return OPUS_OK;
+}
+
+#ifdef CUSTOM_MODES
+void opus_custom_encoder_destroy(CELTEncoder *st)
+{
+   opus_free(st);
+}
+#endif /* CUSTOM_MODES */
+
+
+static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C,
+                              opus_val16 *tf_estimate, int *tf_chan, int allow_weak_transients,
+                              int *weak_transient)
+{
+   int i;
+   VARDECL(opus_val16, tmp);
+   opus_val32 mem0,mem1;
+   int is_transient = 0;
+   opus_int32 mask_metric = 0;
+   int c;
+   opus_val16 tf_max;
+   int len2;
+   /* Forward masking: 6.7 dB/ms. */
+#ifdef FIXED_POINT
+   int forward_shift = 4;
+#else
+   opus_val16 forward_decay = QCONST16(.0625f,15);
+#endif
+   /* Table of 6*64/x, trained on real data to minimize the average error */
+   static const unsigned char inv_table[128] = {
+         255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,
+          23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12,
+          12, 12, 11, 11, 11, 10, 10, 10,  9,  9,  9,  9,  9,  9,  8,  8,
+           8,  8,  8,  7,  7,  7,  7,  7,  7,  6,  6,  6,  6,  6,  6,  6,
+           6,  6,  6,  6,  6,  6,  6,  6,  6,  5,  5,  5,  5,  5,  5,  5,
+           5,  5,  5,  5,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
+           4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  3,  3,
+           3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  2,
+   };
+   SAVE_STACK;
+   ALLOC(tmp, len, opus_val16);
+
+   *weak_transient = 0;
+   /* For lower bitrates, let's be more conservative and have a forward masking
+      decay of 3.3 dB/ms. This avoids having to code transients at very low
+      bitrate (mostly for hybrid), which can result in unstable energy and/or
+      partial collapse. */
+   if (allow_weak_transients)
+   {
+#ifdef FIXED_POINT
+      forward_shift = 5;
+#else
+      forward_decay = QCONST16(.03125f,15);
+#endif
+   }
+   len2=len/2;
+   for (c=0;c<C;c++)
+   {
+      opus_val32 mean;
+      opus_int32 unmask=0;
+      opus_val32 norm;
+      opus_val16 maxE;
+      mem0=0;
+      mem1=0;
+      /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */
+      for (i=0;i<len;i++)
+      {
+         opus_val32 x,y;
+         x = SHR32(in[i+c*len],SIG_SHIFT);
+         y = ADD32(mem0, x);
+#ifdef FIXED_POINT
+         mem0 = mem1 + y - SHL32(x,1);
+         mem1 = x - SHR32(y,1);
+#else
+         mem0 = mem1 + y - 2*x;
+         mem1 = x - .5f*y;
+#endif
+         tmp[i] = SROUND16(y, 2);
+         /*printf("%f ", tmp[i]);*/
+      }
+      /*printf("\n");*/
+      /* First few samples are bad because we don't propagate the memory */
+      OPUS_CLEAR(tmp, 12);
+
+#ifdef FIXED_POINT
+      /* Normalize tmp to max range */
+      {
+         int shift=0;
+         shift = 14-celt_ilog2(MAX16(1, celt_maxabs16(tmp, len)));
+         if (shift!=0)
+         {
+            for (i=0;i<len;i++)
+               tmp[i] = SHL16(tmp[i], shift);
+         }
+      }
+#endif
+
+      mean=0;
+      mem0=0;
+      /* Grouping by two to reduce complexity */
+      /* Forward pass to compute the post-echo threshold*/
+      for (i=0;i<len2;i++)
+      {
+         opus_val16 x2 = PSHR32(MULT16_16(tmp[2*i],tmp[2*i]) + MULT16_16(tmp[2*i+1],tmp[2*i+1]),16);
+         mean += x2;
+#ifdef FIXED_POINT
+         /* FIXME: Use PSHR16() instead */
+         tmp[i] = mem0 + PSHR32(x2-mem0,forward_shift);
+#else
+         tmp[i] = mem0 + MULT16_16_P15(forward_decay,x2-mem0);
+#endif
+         mem0 = tmp[i];
+      }
+
+      mem0=0;
+      maxE=0;
+      /* Backward pass to compute the pre-echo threshold */
+      for (i=len2-1;i>=0;i--)
+      {
+         /* Backward masking: 13.9 dB/ms. */
+#ifdef FIXED_POINT
+         /* FIXME: Use PSHR16() instead */
+         tmp[i] = mem0 + PSHR32(tmp[i]-mem0,3);
+#else
+         tmp[i] = mem0 + MULT16_16_P15(QCONST16(0.125f,15),tmp[i]-mem0);
+#endif
+         mem0 = tmp[i];
+         maxE = MAX16(maxE, mem0);
+      }
+      /*for (i=0;i<len2;i++)printf("%f ", tmp[i]/mean);printf("\n");*/
+
+      /* Compute the ratio of the "frame energy" over the harmonic mean of the energy.
+         This essentially corresponds to a bitrate-normalized temporal noise-to-mask
+         ratio */
+
+      /* As a compromise with the old transient detector, frame energy is the
+         geometric mean of the energy and half the max */
+#ifdef FIXED_POINT
+      /* Costs two sqrt() to avoid overflows */
+      mean = MULT16_16(celt_sqrt(mean), celt_sqrt(MULT16_16(maxE,len2>>1)));
+#else
+      mean = celt_sqrt(mean * maxE*.5*len2);
+#endif
+      /* Inverse of the mean energy in Q15+6 */
+      norm = SHL32(EXTEND32(len2),6+14)/ADD32(EPSILON,SHR32(mean,1));
+      /* Compute harmonic mean discarding the unreliable boundaries
+         The data is smooth, so we only take 1/4th of the samples */
+      unmask=0;
+      for (i=12;i<len2-5;i+=4)
+      {
+         int id;
+#ifdef FIXED_POINT
+         id = MAX32(0,MIN32(127,MULT16_32_Q15(tmp[i]+EPSILON,norm))); /* Do not round to nearest */
+#else
+         id = (int)MAX32(0,MIN32(127,floor(64*norm*(tmp[i]+EPSILON)))); /* Do not round to nearest */
+#endif
+         unmask += inv_table[id];
+      }
+      /*printf("%d\n", unmask);*/
+      /* Normalize, compensate for the 1/4th of the sample and the factor of 6 in the inverse table */
+      unmask = 64*unmask*4/(6*(len2-17));
+      if (unmask>mask_metric)
+      {
+         *tf_chan = c;
+         mask_metric = unmask;
+      }
+   }
+   is_transient = mask_metric>200;
+   /* For low bitrates, define "weak transients" that need to be
+      handled differently to avoid partial collapse. */
+   if (allow_weak_transients && is_transient && mask_metric<600) {
+      is_transient = 0;
+      *weak_transient = 1;
+   }
+   /* Arbitrary metric for VBR boost */
+   tf_max = MAX16(0,celt_sqrt(27*mask_metric)-42);
+   /* *tf_estimate = 1 + MIN16(1, sqrt(MAX16(0, tf_max-30))/20); */
+   *tf_estimate = celt_sqrt(MAX32(0, SHL32(MULT16_16(QCONST16(0.0069,14),MIN16(163,tf_max)),14)-QCONST32(0.139,28)));
+   /*printf("%d %f\n", tf_max, mask_metric);*/
+   RESTORE_STACK;
+#ifdef FUZZING
+   is_transient = rand()&0x1;
+#endif
+   /*printf("%d %f %d\n", is_transient, (float)*tf_estimate, tf_max);*/
+   return is_transient;
+}
+
+/* Looks for sudden increases of energy to decide whether we need to patch
+   the transient decision */
+static int patch_transient_decision(opus_val16 *newE, opus_val16 *oldE, int nbEBands,
+      int start, int end, int C)
+{
+   int i, c;
+   opus_val32 mean_diff=0;
+   opus_val16 spread_old[26];
+   /* Apply an aggressive (-6 dB/Bark) spreading function to the old frame to
+      avoid false detection caused by irrelevant bands */
+   if (C==1)
+   {
+      spread_old[start] = oldE[start];
+      for (i=start+1;i<end;i++)
+         spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT), oldE[i]);
+   } else {
+      spread_old[start] = MAX16(oldE[start],oldE[start+nbEBands]);
+      for (i=start+1;i<end;i++)
+         spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT),
+                               MAX16(oldE[i],oldE[i+nbEBands]));
+   }
+   for (i=end-2;i>=start;i--)
+      spread_old[i] = MAX16(spread_old[i], spread_old[i+1]-QCONST16(1.0f, DB_SHIFT));
+   /* Compute mean increase */
+   c=0; do {
+      for (i=IMAX(2,start);i<end-1;i++)
+      {
+         opus_val16 x1, x2;
+         x1 = MAX16(0, newE[i + c*nbEBands]);
+         x2 = MAX16(0, spread_old[i]);
+         mean_diff = ADD32(mean_diff, EXTEND32(MAX16(0, SUB16(x1, x2))));
+      }
+   } while (++c<C);
+   mean_diff = DIV32(mean_diff, C*(end-1-IMAX(2,start)));
+   /*printf("%f %f %d\n", mean_diff, max_diff, count);*/
+   return mean_diff > QCONST16(1.f, DB_SHIFT);
+}
+
+/** Apply window and compute the MDCT for all sub-frames and
+    all channels in a frame */
+static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * OPUS_RESTRICT in,
+                          celt_sig * OPUS_RESTRICT out, int C, int CC, int LM, int upsample,
+                          int arch)
+{
+   const int overlap = mode->overlap;
+   int N;
+   int B;
+   int shift;
+   int i, b, c;
+   if (shortBlocks)
+   {
+      B = shortBlocks;
+      N = mode->shortMdctSize;
+      shift = mode->maxLM;
+   } else {
+      B = 1;
+      N = mode->shortMdctSize<<LM;
+      shift = mode->maxLM-LM;
+   }
+   c=0; do {
+      for (b=0;b<B;b++)
+      {
+         /* Interleaving the sub-frames while doing the MDCTs */
+         clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N,
+                          &out[b+c*N*B], mode->window, overlap, shift, B,
+                          arch);
+      }
+   } while (++c<CC);
+   if (CC==2&&C==1)
+   {
+      for (i=0;i<B*N;i++)
+         out[i] = ADD32(HALF32(out[i]), HALF32(out[B*N+i]));
+   }
+   if (upsample != 1)
+   {
+      c=0; do
+      {
+         int bound = B*N/upsample;
+         for (i=0;i<bound;i++)
+            out[c*B*N+i] *= upsample;
+         OPUS_CLEAR(&out[c*B*N+bound], B*N-bound);
+      } while (++c<C);
+   }
+}
+
+
+void celt_preemphasis(const opus_val16 * OPUS_RESTRICT pcmp, celt_sig * OPUS_RESTRICT inp,
+                        int N, int CC, int upsample, const opus_val16 *coef, celt_sig *mem, int clip)
+{
+   int i;
+   opus_val16 coef0;
+   celt_sig m;
+   int Nu;
+
+   coef0 = coef[0];
+   m = *mem;
+
+   /* Fast path for the normal 48kHz case and no clipping */
+   if (coef[1] == 0 && upsample == 1 && !clip)
+   {
+      for (i=0;i<N;i++)
+      {
+         opus_val16 x;
+         x = SCALEIN(pcmp[CC*i]);
+         /* Apply pre-emphasis */
+         inp[i] = SHL32(x, SIG_SHIFT) - m;
+         m = SHR32(MULT16_16(coef0, x), 15-SIG_SHIFT);
+      }
+      *mem = m;
+      return;
+   }
+
+   Nu = N/upsample;
+   if (upsample!=1)
+   {
+      OPUS_CLEAR(inp, N);
+   }
+   for (i=0;i<Nu;i++)
+      inp[i*upsample] = SCALEIN(pcmp[CC*i]);
+
+#ifndef FIXED_POINT
+   if (clip)
+   {
+      /* Clip input to avoid encoding non-portable files */
+      for (i=0;i<Nu;i++)
+         inp[i*upsample] = MAX32(-65536.f, MIN32(65536.f,inp[i*upsample]));
+   }
+#else
+   (void)clip; /* Avoids a warning about clip being unused. */
+#endif
+#ifdef CUSTOM_MODES
+   if (coef[1] != 0)
+   {
+      opus_val16 coef1 = coef[1];
+      opus_val16 coef2 = coef[2];
+      for (i=0;i<N;i++)
+      {
+         celt_sig x, tmp;
+         x = inp[i];
+         /* Apply pre-emphasis */
+         tmp = MULT16_16(coef2, x);
+         inp[i] = tmp + m;
+         m = MULT16_32_Q15(coef1, inp[i]) - MULT16_32_Q15(coef0, tmp);
+      }
+   } else
+#endif
+   {
+      for (i=0;i<N;i++)
+      {
+         opus_val16 x;
+         x = inp[i];
+         /* Apply pre-emphasis */
+         inp[i] = SHL32(x, SIG_SHIFT) - m;
+         m = SHR32(MULT16_16(coef0, x), 15-SIG_SHIFT);
+      }
+   }
+   *mem = m;
+}
+
+
+
+static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, opus_val16 bias)
+{
+   int i;
+   opus_val32 L1;
+   L1 = 0;
+   for (i=0;i<N;i++)
+      L1 += EXTEND32(ABS16(tmp[i]));
+   /* When in doubt, prefer good freq resolution */
+   L1 = MAC16_32_Q15(L1, LM*bias, L1);
+   return L1;
+
+}
+
+static int tf_analysis(const CELTMode *m, int len, int isTransient,
+      int *tf_res, int lambda, celt_norm *X, int N0, int LM,
+      opus_val16 tf_estimate, int tf_chan)
+{
+   int i;
+   VARDECL(int, metric);
+   int cost0;
+   int cost1;
+   VARDECL(int, path0);
+   VARDECL(int, path1);
+   VARDECL(celt_norm, tmp);
+   VARDECL(celt_norm, tmp_1);
+   int sel;
+   int selcost[2];
+   int tf_select=0;
+   opus_val16 bias;
+
+   SAVE_STACK;
+   bias = MULT16_16_Q14(QCONST16(.04f,15), MAX16(-QCONST16(.25f,14), QCONST16(.5f,14)-tf_estimate));
+   /*printf("%f ", bias);*/
+
+   ALLOC(metric, len, int);
+   ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
+   ALLOC(tmp_1, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
+   ALLOC(path0, len, int);
+   ALLOC(path1, len, int);
+
+   for (i=0;i<len;i++)
+   {
+      int k, N;
+      int narrow;
+      opus_val32 L1, best_L1;
+      int best_level=0;
+      N = (m->eBands[i+1]-m->eBands[i])<<LM;
+      /* band is too narrow to be split down to LM=-1 */
+      narrow = (m->eBands[i+1]-m->eBands[i])==1;
+      OPUS_COPY(tmp, &X[tf_chan*N0 + (m->eBands[i]<<LM)], N);
+      /* Just add the right channel if we're in stereo */
+      /*if (C==2)
+         for (j=0;j<N;j++)
+            tmp[j] = ADD16(SHR16(tmp[j], 1),SHR16(X[N0+j+(m->eBands[i]<<LM)], 1));*/
+      L1 = l1_metric(tmp, N, isTransient ? LM : 0, bias);
+      best_L1 = L1;
+      /* Check the -1 case for transients */
+      if (isTransient && !narrow)
+      {
+         OPUS_COPY(tmp_1, tmp, N);
+         haar1(tmp_1, N>>LM, 1<<LM);
+         L1 = l1_metric(tmp_1, N, LM+1, bias);
+         if (L1<best_L1)
+         {
+            best_L1 = L1;
+            best_level = -1;
+         }
+      }
+      /*printf ("%f ", L1);*/
+      for (k=0;k<LM+!(isTransient||narrow);k++)
+      {
+         int B;
+
+         if (isTransient)
+            B = (LM-k-1);
+         else
+            B = k+1;
+
+         haar1(tmp, N>>k, 1<<k);
+
+         L1 = l1_metric(tmp, N, B, bias);
+
+         if (L1 < best_L1)
+         {
+            best_L1 = L1;
+            best_level = k+1;
+         }
+      }
+      /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
+      /* metric is in Q1 to be able to select the mid-point (-0.5) for narrower bands */
+      if (isTransient)
+         metric[i] = 2*best_level;
+      else
+         metric[i] = -2*best_level;
+      /* For bands that can't be split to -1, set the metric to the half-way point to avoid
+         biasing the decision */
+      if (narrow && (metric[i]==0 || metric[i]==-2*LM))
+         metric[i]-=1;
+      /*printf("%d ", metric[i]);*/
+   }
+   /*printf("\n");*/
+   /* Search for the optimal tf resolution, including tf_select */
+   tf_select = 0;
+   for (sel=0;sel<2;sel++)
+   {
+      cost0 = 0;
+      cost1 = isTransient ? 0 : lambda;
+      for (i=1;i<len;i++)
+      {
+         int curr0, curr1;
+         curr0 = IMIN(cost0, cost1 + lambda);
+         curr1 = IMIN(cost0 + lambda, cost1);
+         cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+0]);
+         cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+1]);
+      }
+      cost0 = IMIN(cost0, cost1);
+      selcost[sel]=cost0;
+   }
+   /* For now, we're conservative and only allow tf_select=1 for transients.
+    * If tests confirm it's useful for non-transients, we could allow it. */
+   if (selcost[1]<selcost[0] && isTransient)
+      tf_select=1;
+   cost0 = 0;
+   cost1 = isTransient ? 0 : lambda;
+   /* Viterbi forward pass */
+   for (i=1;i<len;i++)
+   {
+      int curr0, curr1;
+      int from0, from1;
+
+      from0 = cost0;
+      from1 = cost1 + lambda;
+      if (from0 < from1)
+      {
+         curr0 = from0;
+         path0[i]= 0;
+      } else {
+         curr0 = from1;
+         path0[i]= 1;
+      }
+
+      from0 = cost0 + lambda;
+      from1 = cost1;
+      if (from0 < from1)
+      {
+         curr1 = from0;
+         path1[i]= 0;
+      } else {
+         curr1 = from1;
+         path1[i]= 1;
+      }
+      cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+0]);
+      cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+1]);
+   }
+   tf_res[len-1] = cost0 < cost1 ? 0 : 1;
+   /* Viterbi backward pass to check the decisions */
+   for (i=len-2;i>=0;i--)
+   {
+      if (tf_res[i+1] == 1)
+         tf_res[i] = path1[i+1];
+      else
+         tf_res[i] = path0[i+1];
+   }
+   /*printf("%d %f\n", *tf_sum, tf_estimate);*/
+   RESTORE_STACK;
+#ifdef FUZZING
+   tf_select = rand()&0x1;
+   tf_res[0] = rand()&0x1;
+   for (i=1;i<len;i++)
+      tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0);
+#endif
+   return tf_select;
+}
+
+static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc)
+{
+   int curr, i;
+   int tf_select_rsv;
+   int tf_changed;
+   int logp;
+   opus_uint32 budget;
+   opus_uint32 tell;
+   budget = enc->storage*8;
+   tell = ec_tell(enc);
+   logp = isTransient ? 2 : 4;
+   /* Reserve space to code the tf_select decision. */
+   tf_select_rsv = LM>0 && tell+logp+1 <= budget;
+   budget -= tf_select_rsv;
+   curr = tf_changed = 0;
+   for (i=start;i<end;i++)
+   {
+      if (tell+logp<=budget)
+      {
+         ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp);
+         tell = ec_tell(enc);
+         curr = tf_res[i];
+         tf_changed |= curr;
+      }
+      else
+         tf_res[i] = curr;
+      logp = isTransient ? 4 : 5;
+   }
+   /* Only code tf_select if it would actually make a difference. */
+   if (tf_select_rsv &&
+         tf_select_table[LM][4*isTransient+0+tf_changed]!=
+         tf_select_table[LM][4*isTransient+2+tf_changed])
+      ec_enc_bit_logp(enc, tf_select, 1);
+   else
+      tf_select = 0;
+   for (i=start;i<end;i++)
+      tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
+   /*for(i=0;i<end;i++)printf("%d ", isTransient ? tf_res[i] : LM+tf_res[i]);printf("\n");*/
+}
+
+
+static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
+      const opus_val16 *bandLogE, int end, int LM, int C, int N0,
+      AnalysisInfo *analysis, opus_val16 *stereo_saving, opus_val16 tf_estimate,
+      int intensity, opus_val16 surround_trim, opus_int32 equiv_rate, int arch)
+{
+   int i;
+   opus_val32 diff=0;
+   int c;
+   int trim_index;
+   opus_val16 trim = QCONST16(5.f, 8);
+   opus_val16 logXC, logXC2;
+   /* At low bitrate, reducing the trim seems to help. At higher bitrates, it's less
+      clear what's best, so we're keeping it as it was before, at least for now. */
+   if (equiv_rate < 64000) {
+      trim = QCONST16(4.f, 8);
+   } else if (equiv_rate < 80000) {
+      opus_int32 frac = (equiv_rate-64000) >> 10;
+      trim = QCONST16(4.f, 8) + QCONST16(1.f/16.f, 8)*frac;
+   }
+   if (C==2)
+   {
+      opus_val16 sum = 0; /* Q10 */
+      opus_val16 minXC; /* Q10 */
+      /* Compute inter-channel correlation for low frequencies */
+      for (i=0;i<8;i++)
+      {
+         opus_val32 partial;
+         partial = celt_inner_prod(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
+               (m->eBands[i+1]-m->eBands[i])<<LM, arch);
+         sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
+      }
+      sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
+      sum = MIN16(QCONST16(1.f, 10), ABS16(sum));
+      minXC = sum;
+      for (i=8;i<intensity;i++)
+      {
+         opus_val32 partial;
+         partial = celt_inner_prod(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
+               (m->eBands[i+1]-m->eBands[i])<<LM, arch);
+         minXC = MIN16(minXC, ABS16(EXTRACT16(SHR32(partial, 18))));
+      }
+      minXC = MIN16(QCONST16(1.f, 10), ABS16(minXC));
+      /*printf ("%f\n", sum);*/
+      /* mid-side savings estimations based on the LF average*/
+      logXC = celt_log2(QCONST32(1.001f, 20)-MULT16_16(sum, sum));
+      /* mid-side savings estimations based on min correlation */
+      logXC2 = MAX16(HALF16(logXC), celt_log2(QCONST32(1.001f, 20)-MULT16_16(minXC, minXC)));
+#ifdef FIXED_POINT
+      /* Compensate for Q20 vs Q14 input and convert output to Q8 */
+      logXC = PSHR32(logXC-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8);
+      logXC2 = PSHR32(logXC2-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8);
+#endif
+
+      trim += MAX16(-QCONST16(4.f, 8), MULT16_16_Q15(QCONST16(.75f,15),logXC));
+      *stereo_saving = MIN16(*stereo_saving + QCONST16(0.25f, 8), -HALF16(logXC2));
+   }
+
+   /* Estimate spectral tilt */
+   c=0; do {
+      for (i=0;i<end-1;i++)
+      {
+         diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-end);
+      }
+   } while (++c<C);
+   diff /= C*(end-1);
+   /*printf("%f\n", diff);*/
+   trim -= MAX32(-QCONST16(2.f, 8), MIN32(QCONST16(2.f, 8), SHR32(diff+QCONST16(1.f, DB_SHIFT),DB_SHIFT-8)/6 ));
+   trim -= SHR16(surround_trim, DB_SHIFT-8);
+   trim -= 2*SHR16(tf_estimate, 14-8);
+#ifndef DISABLE_FLOAT_API
+   if (analysis->valid)
+   {
+      trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8),
+            (opus_val16)(QCONST16(2.f, 8)*(analysis->tonality_slope+.05f))));
+   }
+#else
+   (void)analysis;
+#endif
+
+#ifdef FIXED_POINT
+   trim_index = PSHR32(trim, 8);
+#else
+   trim_index = (int)floor(.5f+trim);
+#endif
+   trim_index = IMAX(0, IMIN(10, trim_index));
+   /*printf("%d\n", trim_index);*/
+#ifdef FUZZING
+   trim_index = rand()%11;
+#endif
+   return trim_index;
+}
+
+static int stereo_analysis(const CELTMode *m, const celt_norm *X,
+      int LM, int N0)
+{
+   int i;
+   int thetas;
+   opus_val32 sumLR = EPSILON, sumMS = EPSILON;
+
+   /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */
+   for (i=0;i<13;i++)
+   {
+      int j;
+      for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
+      {
+         opus_val32 L, R, M, S;
+         /* We cast to 32-bit first because of the -32768 case */
+         L = EXTEND32(X[j]);
+         R = EXTEND32(X[N0+j]);
+         M = ADD32(L, R);
+         S = SUB32(L, R);
+         sumLR = ADD32(sumLR, ADD32(ABS32(L), ABS32(R)));
+         sumMS = ADD32(sumMS, ADD32(ABS32(M), ABS32(S)));
+      }
+   }
+   sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS);
+   thetas = 13;
+   /* We don't need thetas for lower bands with LM<=1 */
+   if (LM<=1)
+      thetas -= 8;
+   return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS)
+         > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR);
+}
+
+#define MSWAP(a,b) do {opus_val16 tmp = a;a=b;b=tmp;} while(0)
+static opus_val16 median_of_5(const opus_val16 *x)
+{
+   opus_val16 t0, t1, t2, t3, t4;
+   t2 = x[2];
+   if (x[0] > x[1])
+   {
+      t0 = x[1];
+      t1 = x[0];
+   } else {
+      t0 = x[0];
+      t1 = x[1];
+   }
+   if (x[3] > x[4])
+   {
+      t3 = x[4];
+      t4 = x[3];
+   } else {
+      t3 = x[3];
+      t4 = x[4];
+   }
+   if (t0 > t3)
+   {
+      MSWAP(t0, t3);
+      MSWAP(t1, t4);
+   }
+   if (t2 > t1)
+   {
+      if (t1 < t3)
+         return MIN16(t2, t3);
+      else
+         return MIN16(t4, t1);
+   } else {
+      if (t2 < t3)
+         return MIN16(t1, t3);
+      else
+         return MIN16(t2, t4);
+   }
+}
+
+static opus_val16 median_of_3(const opus_val16 *x)
+{
+   opus_val16 t0, t1, t2;
+   if (x[0] > x[1])
+   {
+      t0 = x[1];
+      t1 = x[0];
+   } else {
+      t0 = x[0];
+      t1 = x[1];
+   }
+   t2 = x[2];
+   if (t1 < t2)
+      return t1;
+   else if (t0 < t2)
+      return t2;
+   else
+      return t0;
+}
+
+static opus_val16 dynalloc_analysis(const opus_val16 *bandLogE, const opus_val16 *bandLogE2,
+      int nbEBands, int start, int end, int C, int *offsets, int lsb_depth, const opus_int16 *logN,
+      int isTransient, int vbr, int constrained_vbr, const opus_int16 *eBands, int LM,
+      int effectiveBytes, opus_int32 *tot_boost_, int lfe, opus_val16 *surround_dynalloc, AnalysisInfo *analysis)
+{
+   int i, c;
+   opus_int32 tot_boost=0;
+   opus_val16 maxDepth;
+   VARDECL(opus_val16, follower);
+   VARDECL(opus_val16, noise_floor);
+   SAVE_STACK;
+   ALLOC(follower, C*nbEBands, opus_val16);
+   ALLOC(noise_floor, C*nbEBands, opus_val16);
+   OPUS_CLEAR(offsets, nbEBands);
+   /* Dynamic allocation code */
+   maxDepth=-QCONST16(31.9f, DB_SHIFT);
+   for (i=0;i<end;i++)
+   {
+      /* Noise floor must take into account eMeans, the depth, the width of the bands
+         and the preemphasis filter (approx. square of bark band ID) */
+      noise_floor[i] = MULT16_16(QCONST16(0.0625f, DB_SHIFT),logN[i])
+            +QCONST16(.5f,DB_SHIFT)+SHL16(9-lsb_depth,DB_SHIFT)-SHL16(eMeans[i],6)
+            +MULT16_16(QCONST16(.0062,DB_SHIFT),(i+5)*(i+5));
+   }
+   c=0;do
+   {
+      for (i=0;i<end;i++)
+         maxDepth = MAX16(maxDepth, bandLogE[c*nbEBands+i]-noise_floor[i]);
+   } while (++c<C);
+   /* Make sure that dynamic allocation can't make us bust the budget */
+   if (effectiveBytes > 50 && LM>=1 && !lfe)
+   {
+      int last=0;
+      c=0;do
+      {
+         opus_val16 offset;
+         opus_val16 tmp;
+         opus_val16 *f;
+         f = &follower[c*nbEBands];
+         f[0] = bandLogE2[c*nbEBands];
+         for (i=1;i<end;i++)
+         {
+            /* The last band to be at least 3 dB higher than the previous one
+               is the last we'll consider. Otherwise, we run into problems on
+               bandlimited signals. */
+            if (bandLogE2[c*nbEBands+i] > bandLogE2[c*nbEBands+i-1]+QCONST16(.5f,DB_SHIFT))
+               last=i;
+            f[i] = MIN16(f[i-1]+QCONST16(1.5f,DB_SHIFT), bandLogE2[c*nbEBands+i]);
+         }
+         for (i=last-1;i>=0;i--)
+            f[i] = MIN16(f[i], MIN16(f[i+1]+QCONST16(2.f,DB_SHIFT), bandLogE2[c*nbEBands+i]));
+
+         /* Combine with a median filter to avoid dynalloc triggering unnecessarily.
+            The "offset" value controls how conservative we are -- a higher offset
+            reduces the impact of the median filter and makes dynalloc use more bits. */
+         offset = QCONST16(1.f, DB_SHIFT);
+         for (i=2;i<end-2;i++)
+            f[i] = MAX16(f[i], median_of_5(&bandLogE2[c*nbEBands+i-2])-offset);
+         tmp = median_of_3(&bandLogE2[c*nbEBands])-offset;
+         f[0] = MAX16(f[0], tmp);
+         f[1] = MAX16(f[1], tmp);
+         tmp = median_of_3(&bandLogE2[c*nbEBands+end-3])-offset;
+         f[end-2] = MAX16(f[end-2], tmp);
+         f[end-1] = MAX16(f[end-1], tmp);
+
+         for (i=0;i<end;i++)
+            f[i] = MAX16(f[i], noise_floor[i]);
+      } while (++c<C);
+      if (C==2)
+      {
+         for (i=start;i<end;i++)
+         {
+            /* Consider 24 dB "cross-talk" */
+            follower[nbEBands+i] = MAX16(follower[nbEBands+i], follower[         i]-QCONST16(4.f,DB_SHIFT));
+            follower[         i] = MAX16(follower[         i], follower[nbEBands+i]-QCONST16(4.f,DB_SHIFT));
+            follower[i] = HALF16(MAX16(0, bandLogE[i]-follower[i]) + MAX16(0, bandLogE[nbEBands+i]-follower[nbEBands+i]));
+         }
+      } else {
+         for (i=start;i<end;i++)
+         {
+            follower[i] = MAX16(0, bandLogE[i]-follower[i]);
+         }
+      }
+      for (i=start;i<end;i++)
+         follower[i] = MAX16(follower[i], surround_dynalloc[i]);
+      /* For non-transient CBR/CVBR frames, halve the dynalloc contribution */
+      if ((!vbr || constrained_vbr)&&!isTransient)
+      {
+         for (i=start;i<end;i++)
+            follower[i] = HALF16(follower[i]);
+      }
+      for (i=start;i<end;i++)
+      {
+         if (i<8)
+            follower[i] *= 2;
+         if (i>=12)
+            follower[i] = HALF16(follower[i]);
+      }
+#ifdef DISABLE_FLOAT_API
+      (void)analysis;
+#else
+      if (analysis->valid)
+      {
+         for (i=start;i<IMIN(LEAK_BANDS, end);i++)
+            follower[i] = follower[i] +  QCONST16(1.f/64.f, DB_SHIFT)*analysis->leak_boost[i];
+      }
+#endif
+      for (i=start;i<end;i++)
+      {
+         int width;
+         int boost;
+         int boost_bits;
+
+         follower[i] = MIN16(follower[i], QCONST16(4, DB_SHIFT));
+
+         width = C*(eBands[i+1]-eBands[i])<<LM;
+         if (width<6)
+         {
+            boost = (int)SHR32(EXTEND32(follower[i]),DB_SHIFT);
+            boost_bits = boost*width<<BITRES;
+         } else if (width > 48) {
+            boost = (int)SHR32(EXTEND32(follower[i])*8,DB_SHIFT);
+            boost_bits = (boost*width<<BITRES)/8;
+         } else {
+            boost = (int)SHR32(EXTEND32(follower[i])*width/6,DB_SHIFT);
+            boost_bits = boost*6<<BITRES;
+         }
+         /* For CBR and non-transient CVBR frames, limit dynalloc to 2/3 of the bits */
+         if ((!vbr || (constrained_vbr&&!isTransient))
+               && (tot_boost+boost_bits)>>BITRES>>3 > 2*effectiveBytes/3)
+         {
+            opus_int32 cap = ((2*effectiveBytes/3)<<BITRES<<3);
+            offsets[i] = cap-tot_boost;
+            tot_boost = cap;
+            break;
+         } else {
+            offsets[i] = boost;
+            tot_boost += boost_bits;
+         }
+      }
+   }
+   *tot_boost_ = tot_boost;
+   RESTORE_STACK;
+   return maxDepth;
+}
+
+
+static int run_prefilter(CELTEncoder *st, celt_sig *in, celt_sig *prefilter_mem, int CC, int N,
+      int prefilter_tapset, int *pitch, opus_val16 *gain, int *qgain, int enabled, int nbAvailableBytes)
+{
+   int c;
+   VARDECL(celt_sig, _pre);
+   celt_sig *pre[2];
+   const CELTMode *mode;
+   int pitch_index;
+   opus_val16 gain1;
+   opus_val16 pf_threshold;
+   int pf_on;
+   int qg;
+   int overlap;
+   SAVE_STACK;
+
+   mode = st->mode;
+   overlap = mode->overlap;
+   ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig);
+
+   pre[0] = _pre;
+   pre[1] = _pre + (N+COMBFILTER_MAXPERIOD);
+
+
+   c=0; do {
+      OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD);
+      OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+overlap)+overlap, N);
+   } while (++c<CC);
+
+   if (enabled)
+   {
+      VARDECL(opus_val16, pitch_buf);
+      ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16);
+
+      pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC, st->arch);
+      /* Don't search for the fir last 1.5 octave of the range because
+         there's too many false-positives due to short-term correlation */
+      pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N,
+            COMBFILTER_MAXPERIOD-3*COMBFILTER_MINPERIOD, &pitch_index,
+            st->arch);
+      pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
+
+      gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
+            N, &pitch_index, st->prefilter_period, st->prefilter_gain, st->arch);
+      if (pitch_index > COMBFILTER_MAXPERIOD-2)
+         pitch_index = COMBFILTER_MAXPERIOD-2;
+      gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
+      /*printf("%d %d %f %f\n", pitch_change, pitch_index, gain1, st->analysis.tonality);*/
+      if (st->loss_rate>2)
+         gain1 = HALF32(gain1);
+      if (st->loss_rate>4)
+         gain1 = HALF32(gain1);
+      if (st->loss_rate>8)
+         gain1 = 0;
+   } else {
+      gain1 = 0;
+      pitch_index = COMBFILTER_MINPERIOD;
+   }
+
+   /* Gain threshold for enabling the prefilter/postfilter */
+   pf_threshold = QCONST16(.2f,15);
+
+   /* Adjusting the threshold based on rate and continuity */
+   if (abs(pitch_index-st->prefilter_period)*10>pitch_index)
+      pf_threshold += QCONST16(.2f,15);
+   if (nbAvailableBytes<25)
+      pf_threshold += QCONST16(.1f,15);
+   if (nbAvailableBytes<35)
+      pf_threshold += QCONST16(.1f,15);
+   if (st->prefilter_gain > QCONST16(.4f,15))
+      pf_threshold -= QCONST16(.1f,15);
+   if (st->prefilter_gain > QCONST16(.55f,15))
+      pf_threshold -= QCONST16(.1f,15);
+
+   /* Hard threshold at 0.2 */
+   pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15));
+   if (gain1<pf_threshold)
+   {
+      gain1 = 0;
+      pf_on = 0;
+      qg = 0;
+   } else {
+      /*This block is not gated by a total bits check only because
+        of the nbAvailableBytes check above.*/
+      if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15))
+         gain1=st->prefilter_gain;
+
+#ifdef FIXED_POINT
+      qg = ((gain1+1536)>>10)/3-1;
+#else
+      qg = (int)floor(.5f+gain1*32/3)-1;
+#endif
+      qg = IMAX(0, IMIN(7, qg));
+      gain1 = QCONST16(0.09375f,15)*(qg+1);
+      pf_on = 1;
+   }
+   /*printf("%d %f\n", pitch_index, gain1);*/
+
+   c=0; do {
+      int offset = mode->shortMdctSize-overlap;
+      st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
+      OPUS_COPY(in+c*(N+overlap), st->in_mem+c*(overlap), overlap);
+      if (offset)
+         comb_filter(in+c*(N+overlap)+overlap, pre[c]+COMBFILTER_MAXPERIOD,
+               st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain,
+               st->prefilter_tapset, st->prefilter_tapset, NULL, 0, st->arch);
+
+      comb_filter(in+c*(N+overlap)+overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset,
+            st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
+            st->prefilter_tapset, prefilter_tapset, mode->window, overlap, st->arch);
+      OPUS_COPY(st->in_mem+c*(overlap), in+c*(N+overlap)+N, overlap);
+
+      if (N>COMBFILTER_MAXPERIOD)
+      {
+         OPUS_COPY(prefilter_mem+c*COMBFILTER_MAXPERIOD, pre[c]+N, COMBFILTER_MAXPERIOD);
+      } else {
+         OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, prefilter_mem+c*COMBFILTER_MAXPERIOD+N, COMBFILTER_MAXPERIOD-N);
+         OPUS_COPY(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N);
+      }
+   } while (++c<CC);
+
+   RESTORE_STACK;
+   *gain = gain1;
+   *pitch = pitch_index;
+   *qgain = qg;
+   return pf_on;
+}
+
+static int compute_vbr(const CELTMode *mode, AnalysisInfo *analysis, opus_int32 base_target,
+      int LM, opus_int32 bitrate, int lastCodedBands, int C, int intensity,
+      int constrained_vbr, opus_val16 stereo_saving, int tot_boost,
+      opus_val16 tf_estimate, int pitch_change, opus_val16 maxDepth,
+      int lfe, int has_surround_mask, opus_val16 surround_masking,
+      opus_val16 temporal_vbr)
+{
+   /* The target rate in 8th bits per frame */
+   opus_int32 target;
+   int coded_bins;
+   int coded_bands;
+   opus_val16 tf_calibration;
+   int nbEBands;
+   const opus_int16 *eBands;
+
+   nbEBands = mode->nbEBands;
+   eBands = mode->eBands;
+
+   coded_bands = lastCodedBands ? lastCodedBands : nbEBands;
+   coded_bins = eBands[coded_bands]<<LM;
+   if (C==2)
+      coded_bins += eBands[IMIN(intensity, coded_bands)]<<LM;
+
+   target = base_target;
+
+   /*printf("%f %f %f %f %d %d ", st->analysis.activity, st->analysis.tonality, tf_estimate, st->stereo_saving, tot_boost, coded_bands);*/
+#ifndef DISABLE_FLOAT_API
+   if (analysis->valid && analysis->activity<.4)
+      target -= (opus_int32)((coded_bins<<BITRES)*(.4f-analysis->activity));
+#endif
+   /* Stereo savings */
+   if (C==2)
+   {
+      int coded_stereo_bands;
+      int coded_stereo_dof;
+      opus_val16 max_frac;
+      coded_stereo_bands = IMIN(intensity, coded_bands);
+      coded_stereo_dof = (eBands[coded_stereo_bands]<<LM)-coded_stereo_bands;
+      /* Maximum fraction of the bits we can save if the signal is mono. */
+      max_frac = DIV32_16(MULT16_16(QCONST16(0.8f, 15), coded_stereo_dof), coded_bins);
+      stereo_saving = MIN16(stereo_saving, QCONST16(1.f, 8));
+      /*printf("%d %d %d ", coded_stereo_dof, coded_bins, tot_boost);*/
+      target -= (opus_int32)MIN32(MULT16_32_Q15(max_frac,target),
+                      SHR32(MULT16_16(stereo_saving-QCONST16(0.1f,8),(coded_stereo_dof<<BITRES)),8));
+   }
+   /* Boost the rate according to dynalloc (minus the dynalloc average for calibration). */
+   target += tot_boost-(19<<LM);
+   /* Apply transient boost, compensating for average boost. */
+   tf_calibration = QCONST16(0.044f,14);
+   target += (opus_int32)SHL32(MULT16_32_Q15(tf_estimate-tf_calibration, target),1);
+
+#ifndef DISABLE_FLOAT_API
+   /* Apply tonality boost */
+   if (analysis->valid && !lfe)
+   {
+      opus_int32 tonal_target;
+      float tonal;
+
+      /* Tonality boost (compensating for the average). */
+      tonal = MAX16(0.f,analysis->tonality-.15f)-0.12f;
+      tonal_target = target + (opus_int32)((coded_bins<<BITRES)*1.2f*tonal);
+      if (pitch_change)
+         tonal_target +=  (opus_int32)((coded_bins<<BITRES)*.8f);
+      /*printf("%f %f ", analysis->tonality, tonal);*/
+      target = tonal_target;
+   }
+#else
+   (void)analysis;
+   (void)pitch_change;
+#endif
+
+   if (has_surround_mask&&!lfe)
+   {
+      opus_int32 surround_target = target + (opus_int32)SHR32(MULT16_16(surround_masking,coded_bins<<BITRES), DB_SHIFT);
+      /*printf("%f %d %d %d %d %d %d ", surround_masking, coded_bins, st->end, st->intensity, surround_target, target, st->bitrate);*/
+      target = IMAX(target/4, surround_target);
+   }
+
+   {
+      opus_int32 floor_depth;
+      int bins;
+      bins = eBands[nbEBands-2]<<LM;
+      /*floor_depth = SHR32(MULT16_16((C*bins<<BITRES),celt_log2(SHL32(MAX16(1,sample_max),13))), DB_SHIFT);*/
+      floor_depth = (opus_int32)SHR32(MULT16_16((C*bins<<BITRES),maxDepth), DB_SHIFT);
+      floor_depth = IMAX(floor_depth, target>>2);
+      target = IMIN(target, floor_depth);
+      /*printf("%f %d\n", maxDepth, floor_depth);*/
+   }
+
+   /* Make VBR less aggressive for constrained VBR because we can't keep a higher bitrate
+      for long. Needs tuning. */
+   if ((!has_surround_mask||lfe) && constrained_vbr)
+   {
+      target = base_target + (opus_int32)MULT16_32_Q15(QCONST16(0.67f, 15), target-base_target);
+   }
+
+   if (!has_surround_mask && tf_estimate < QCONST16(.2f, 14))
+   {
+      opus_val16 amount;
+      opus_val16 tvbr_factor;
+      amount = MULT16_16_Q15(QCONST16(.0000031f, 30), IMAX(0, IMIN(32000, 96000-bitrate)));
+      tvbr_factor = SHR32(MULT16_16(temporal_vbr, amount), DB_SHIFT);
+      target += (opus_int32)MULT16_32_Q15(tvbr_factor, target);
+   }
+
+   /* Don't allow more than doubling the rate */
+   target = IMIN(2*base_target, target);
+
+   return target;
+}
+
+int celt_encode_with_ec(CELTEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc)
+{
+   int i, c, N;
+   opus_int32 bits;
+   ec_enc _enc;
+   VARDECL(celt_sig, in);
+   VARDECL(celt_sig, freq);
+   VARDECL(celt_norm, X);
+   VARDECL(celt_ener, bandE);
+   VARDECL(opus_val16, bandLogE);
+   VARDECL(opus_val16, bandLogE2);
+   VARDECL(int, fine_quant);
+   VARDECL(opus_val16, error);
+   VARDECL(int, pulses);
+   VARDECL(int, cap);
+   VARDECL(int, offsets);
+   VARDECL(int, fine_priority);
+   VARDECL(int, tf_res);
+   VARDECL(unsigned char, collapse_masks);
+   celt_sig *prefilter_mem;
+   opus_val16 *oldBandE, *oldLogE, *oldLogE2, *energyError;
+   int shortBlocks=0;
+   int isTransient=0;
+   const int CC = st->channels;
+   const int C = st->stream_channels;
+   int LM, M;
+   int tf_select;
+   int nbFilledBytes, nbAvailableBytes;
+   int start;
+   int end;
+   int effEnd;
+   int codedBands;
+   int alloc_trim;
+   int pitch_index=COMBFILTER_MINPERIOD;
+   opus_val16 gain1 = 0;
+   int dual_stereo=0;
+   int effectiveBytes;
+   int dynalloc_logp;
+   opus_int32 vbr_rate;
+   opus_int32 total_bits;
+   opus_int32 total_boost;
+   opus_int32 balance;
+   opus_int32 tell;
+   opus_int32 tell0_frac;
+   int prefilter_tapset=0;
+   int pf_on;
+   int anti_collapse_rsv;
+   int anti_collapse_on=0;
+   int silence=0;
+   int tf_chan = 0;
+   opus_val16 tf_estimate;
+   int pitch_change=0;
+   opus_int32 tot_boost;
+   opus_val32 sample_max;
+   opus_val16 maxDepth;
+   const OpusCustomMode *mode;
+   int nbEBands;
+   int overlap;
+   const opus_int16 *eBands;
+   int secondMdct;
+   int signalBandwidth;
+   int transient_got_disabled=0;
+   opus_val16 surround_masking=0;
+   opus_val16 temporal_vbr=0;
+   opus_val16 surround_trim = 0;
+   opus_int32 equiv_rate;
+   int hybrid;
+   int weak_transient = 0;
+   VARDECL(opus_val16, surround_dynalloc);
+   ALLOC_STACK;
+
+   mode = st->mode;
+   nbEBands = mode->nbEBands;
+   overlap = mode->overlap;
+   eBands = mode->eBands;
+   start = st->start;
+   end = st->end;
+   hybrid = start != 0;
+   tf_estimate = 0;
+   if (nbCompressedBytes<2 || pcm==NULL)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+
+   frame_size *= st->upsample;
+   for (LM=0;LM<=mode->maxLM;LM++)
+      if (mode->shortMdctSize<<LM==frame_size)
+         break;
+   if (LM>mode->maxLM)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   M=1<<LM;
+   N = M*mode->shortMdctSize;
+
+   prefilter_mem = st->in_mem+CC*(overlap);
+   oldBandE = (opus_val16*)(st->in_mem+CC*(overlap+COMBFILTER_MAXPERIOD));
+   oldLogE = oldBandE + CC*nbEBands;
+   oldLogE2 = oldLogE + CC*nbEBands;
+   energyError = oldLogE2 + CC*nbEBands;
+
+   if (enc==NULL)
+   {
+      tell0_frac=tell=1;
+      nbFilledBytes=0;
+   } else {
+      tell0_frac=tell=ec_tell_frac(enc);
+      tell=ec_tell(enc);
+      nbFilledBytes=(tell+4)>>3;
+   }
+
+#ifdef CUSTOM_MODES
+   if (st->signalling && enc==NULL)
+   {
+      int tmp = (mode->effEBands-end)>>1;
+      end = st->end = IMAX(1, mode->effEBands-tmp);
+      compressed[0] = tmp<<5;
+      compressed[0] |= LM<<3;
+      compressed[0] |= (C==2)<<2;
+      /* Convert "standard mode" to Opus header */
+      if (mode->Fs==48000 && mode->shortMdctSize==120)
+      {
+         int c0 = toOpus(compressed[0]);
+         if (c0<0)
+         {
+            RESTORE_STACK;
+            return OPUS_BAD_ARG;
+         }
+         compressed[0] = c0;
+      }
+      compressed++;
+      nbCompressedBytes--;
+   }
+#else
+   celt_assert(st->signalling==0);
+#endif
+
+   /* Can't produce more than 1275 output bytes */
+   nbCompressedBytes = IMIN(nbCompressedBytes,1275);
+   nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
+
+   if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX)
+   {
+      opus_int32 den=mode->Fs>>BITRES;
+      vbr_rate=(st->bitrate*frame_size+(den>>1))/den;
+#ifdef CUSTOM_MODES
+      if (st->signalling)
+         vbr_rate -= 8<<BITRES;
+#endif
+      effectiveBytes = vbr_rate>>(3+BITRES);
+   } else {
+      opus_int32 tmp;
+      vbr_rate = 0;
+      tmp = st->bitrate*frame_size;
+      if (tell>1)
+         tmp += tell;
+      if (st->bitrate!=OPUS_BITRATE_MAX)
+         nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes,
+               (tmp+4*mode->Fs)/(8*mode->Fs)-!!st->signalling));
+      effectiveBytes = nbCompressedBytes - nbFilledBytes;
+   }
+   equiv_rate = ((opus_int32)nbCompressedBytes*8*50 >> (3-LM)) - (40*C+20)*((400>>LM) - 50);
+   if (st->bitrate != OPUS_BITRATE_MAX)
+      equiv_rate = IMIN(equiv_rate, st->bitrate - (40*C+20)*((400>>LM) - 50));
+
+   if (enc==NULL)
+   {
+      ec_enc_init(&_enc, compressed, nbCompressedBytes);
+      enc = &_enc;
+   }
+
+   if (vbr_rate>0)
+   {
+      /* Computes the max bit-rate allowed in VBR mode to avoid violating the
+          target rate and buffering.
+         We must do this up front so that bust-prevention logic triggers
+          correctly if we don't have enough bits. */
+      if (st->constrained_vbr)
+      {
+         opus_int32 vbr_bound;
+         opus_int32 max_allowed;
+         /* We could use any multiple of vbr_rate as bound (depending on the
+             delay).
+            This is clamped to ensure we use at least two bytes if the encoder
+             was entirely empty, but to allow 0 in hybrid mode. */
+         vbr_bound = vbr_rate;
+         max_allowed = IMIN(IMAX(tell==1?2:0,
+               (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)),
+               nbAvailableBytes);
+         if(max_allowed < nbAvailableBytes)
+         {
+            nbCompressedBytes = nbFilledBytes+max_allowed;
+            nbAvailableBytes = max_allowed;
+            ec_enc_shrink(enc, nbCompressedBytes);
+         }
+      }
+   }
+   total_bits = nbCompressedBytes*8;
+
+   effEnd = end;
+   if (effEnd > mode->effEBands)
+      effEnd = mode->effEBands;
+
+   ALLOC(in, CC*(N+overlap), celt_sig);
+
+   sample_max=MAX32(st->overlap_max, celt_maxabs16(pcm, C*(N-overlap)/st->upsample));
+   st->overlap_max=celt_maxabs16(pcm+C*(N-overlap)/st->upsample, C*overlap/st->upsample);
+   sample_max=MAX32(sample_max, st->overlap_max);
+#ifdef FIXED_POINT
+   silence = (sample_max==0);
+#else
+   silence = (sample_max <= (opus_val16)1/(1<<st->lsb_depth));
+#endif
+#ifdef FUZZING
+   if ((rand()&0x3F)==0)
+      silence = 1;
+#endif
+   if (tell==1)
+      ec_enc_bit_logp(enc, silence, 15);
+   else
+      silence=0;
+   if (silence)
+   {
+      /*In VBR mode there is no need to send more than the minimum. */
+      if (vbr_rate>0)
+      {
+         effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2);
+         total_bits=nbCompressedBytes*8;
+         nbAvailableBytes=2;
+         ec_enc_shrink(enc, nbCompressedBytes);
+      }
+      /* Pretend we've filled all the remaining bits with zeros
+            (that's what the initialiser did anyway) */
+      tell = nbCompressedBytes*8;
+      enc->nbits_total+=tell-ec_tell(enc);
+   }
+   c=0; do {
+      int need_clip=0;
+#ifndef FIXED_POINT
+      need_clip = st->clip && sample_max>65536.f;
+#endif
+      celt_preemphasis(pcm+c, in+c*(N+overlap)+overlap, N, CC, st->upsample,
+                  mode->preemph, st->preemph_memE+c, need_clip);
+   } while (++c<CC);
+
+
+
+   /* Find pitch period and gain */
+   {
+      int enabled;
+      int qg;
+      enabled = ((st->lfe&&nbAvailableBytes>3) || nbAvailableBytes>12*C) && !hybrid && !silence && !st->disable_pf
+            && st->complexity >= 5;
+
+      prefilter_tapset = st->tapset_decision;
+      pf_on = run_prefilter(st, in, prefilter_mem, CC, N, prefilter_tapset, &pitch_index, &gain1, &qg, enabled, nbAvailableBytes);
+      if ((gain1 > QCONST16(.4f,15) || st->prefilter_gain > QCONST16(.4f,15)) && (!st->analysis.valid || st->analysis.tonality > .3)
+            && (pitch_index > 1.26*st->prefilter_period || pitch_index < .79*st->prefilter_period))
+         pitch_change = 1;
+      if (pf_on==0)
+      {
+         if(!hybrid && tell+16<=total_bits)
+            ec_enc_bit_logp(enc, 0, 1);
+      } else {
+         /*This block is not gated by a total bits check only because
+           of the nbAvailableBytes check above.*/
+         int octave;
+         ec_enc_bit_logp(enc, 1, 1);
+         pitch_index += 1;
+         octave = EC_ILOG(pitch_index)-5;
+         ec_enc_uint(enc, octave, 6);
+         ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave);
+         pitch_index -= 1;
+         ec_enc_bits(enc, qg, 3);
+         ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
+      }
+   }
+
+   isTransient = 0;
+   shortBlocks = 0;
+   if (st->complexity >= 1 && !st->lfe)
+   {
+      /* Reduces the likelihood of energy instability on fricatives at low bitrate
+         in hybrid mode. It seems like we still want to have real transients on vowels
+         though (small SILK quantization offset value). */
+      int allow_weak_transients = hybrid && effectiveBytes<15 && st->silk_info.offset >= 100;
+      isTransient = transient_analysis(in, N+overlap, CC,
+            &tf_estimate, &tf_chan, allow_weak_transients, &weak_transient);
+   }
+   if (LM>0 && ec_tell(enc)+3<=total_bits)
+   {
+      if (isTransient)
+         shortBlocks = M;
+   } else {
+      isTransient = 0;
+      transient_got_disabled=1;
+   }
+
+   ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
+   ALLOC(bandE,nbEBands*CC, celt_ener);
+   ALLOC(bandLogE,nbEBands*CC, opus_val16);
+
+   secondMdct = shortBlocks && st->complexity>=8;
+   ALLOC(bandLogE2, C*nbEBands, opus_val16);
+   if (secondMdct)
+   {
+      compute_mdcts(mode, 0, in, freq, C, CC, LM, st->upsample, st->arch);
+      compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
+      amp2Log2(mode, effEnd, end, bandE, bandLogE2, C);
+      for (i=0;i<C*nbEBands;i++)
+         bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT));
+   }
+
+   compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
+   if (CC==2&&C==1)
+      tf_chan = 0;
+   compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
+
+   if (st->lfe)
+   {
+      for (i=2;i<end;i++)
+      {
+         bandE[i] = IMIN(bandE[i], MULT16_32_Q15(QCONST16(1e-4f,15),bandE[0]));
+         bandE[i] = MAX32(bandE[i], EPSILON);
+      }
+   }
+   amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
+
+   ALLOC(surround_dynalloc, C*nbEBands, opus_val16);
+   OPUS_CLEAR(surround_dynalloc, end);
+   /* This computes how much masking takes place between surround channels */
+   if (!hybrid&&st->energy_mask&&!st->lfe)
+   {
+      int mask_end;
+      int midband;
+      int count_dynalloc;
+      opus_val32 mask_avg=0;
+      opus_val32 diff=0;
+      int count=0;
+      mask_end = IMAX(2,st->lastCodedBands);
+      for (c=0;c<C;c++)
+      {
+         for(i=0;i<mask_end;i++)
+         {
+            opus_val16 mask;
+            mask = MAX16(MIN16(st->energy_mask[nbEBands*c+i],
+                   QCONST16(.25f, DB_SHIFT)), -QCONST16(2.0f, DB_SHIFT));
+            if (mask > 0)
+               mask = HALF16(mask);
+            mask_avg += MULT16_16(mask, eBands[i+1]-eBands[i]);
+            count += eBands[i+1]-eBands[i];
+            diff += MULT16_16(mask, 1+2*i-mask_end);
+         }
+      }
+      celt_assert(count>0);
+      mask_avg = DIV32_16(mask_avg,count);
+      mask_avg += QCONST16(.2f, DB_SHIFT);
+      diff = diff*6/(C*(mask_end-1)*(mask_end+1)*mask_end);
+      /* Again, being conservative */
+      diff = HALF32(diff);
+      diff = MAX32(MIN32(diff, QCONST32(.031f, DB_SHIFT)), -QCONST32(.031f, DB_SHIFT));
+      /* Find the band that's in the middle of the coded spectrum */
+      for (midband=0;eBands[midband+1] < eBands[mask_end]/2;midband++);
+      count_dynalloc=0;
+      for(i=0;i<mask_end;i++)
+      {
+         opus_val32 lin;
+         opus_val16 unmask;
+         lin = mask_avg + diff*(i-midband);
+         if (C==2)
+            unmask = MAX16(st->energy_mask[i], st->energy_mask[nbEBands+i]);
+         else
+            unmask = st->energy_mask[i];
+         unmask = MIN16(unmask, QCONST16(.0f, DB_SHIFT));
+         unmask -= lin;
+         if (unmask > QCONST16(.25f, DB_SHIFT))
+         {
+            surround_dynalloc[i] = unmask - QCONST16(.25f, DB_SHIFT);
+            count_dynalloc++;
+         }
+      }
+      if (count_dynalloc>=3)
+      {
+         /* If we need dynalloc in many bands, it's probably because our
+            initial masking rate was too low. */
+         mask_avg += QCONST16(.25f, DB_SHIFT);
+         if (mask_avg>0)
+         {
+            /* Something went really wrong in the original calculations,
+               disabling masking. */
+            mask_avg = 0;
+            diff = 0;
+            OPUS_CLEAR(surround_dynalloc, mask_end);
+         } else {
+            for(i=0;i<mask_end;i++)
+               surround_dynalloc[i] = MAX16(0, surround_dynalloc[i]-QCONST16(.25f, DB_SHIFT));
+         }
+      }
+      mask_avg += QCONST16(.2f, DB_SHIFT);
+      /* Convert to 1/64th units used for the trim */
+      surround_trim = 64*diff;
+      /*printf("%d %d ", mask_avg, surround_trim);*/
+      surround_masking = mask_avg;
+   }
+   /* Temporal VBR (but not for LFE) */
+   if (!st->lfe)
+   {
+      opus_val16 follow=-QCONST16(10.0f,DB_SHIFT);
+      opus_val32 frame_avg=0;
+      opus_val16 offset = shortBlocks?HALF16(SHL16(LM, DB_SHIFT)):0;
+      for(i=start;i<end;i++)
+      {
+         follow = MAX16(follow-QCONST16(1.f, DB_SHIFT), bandLogE[i]-offset);
+         if (C==2)
+            follow = MAX16(follow, bandLogE[i+nbEBands]-offset);
+         frame_avg += follow;
+      }
+      frame_avg /= (end-start);
+      temporal_vbr = SUB16(frame_avg,st->spec_avg);
+      temporal_vbr = MIN16(QCONST16(3.f, DB_SHIFT), MAX16(-QCONST16(1.5f, DB_SHIFT), temporal_vbr));
+      st->spec_avg += MULT16_16_Q15(QCONST16(.02f, 15), temporal_vbr);
+   }
+   /*for (i=0;i<21;i++)
+      printf("%f ", bandLogE[i]);
+   printf("\n");*/
+
+   if (!secondMdct)
+   {
+      OPUS_COPY(bandLogE2, bandLogE, C*nbEBands);
+   }
+
+   /* Last chance to catch any transient we might have missed in the
+      time-domain analysis */
+   if (LM>0 && ec_tell(enc)+3<=total_bits && !isTransient && st->complexity>=5 && !st->lfe && !hybrid)
+   {
+      if (patch_transient_decision(bandLogE, oldBandE, nbEBands, start, end, C))
+      {
+         isTransient = 1;
+         shortBlocks = M;
+         compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
+         compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
+         amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
+         /* Compensate for the scaling of short vs long mdcts */
+         for (i=0;i<C*nbEBands;i++)
+            bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT));
+         tf_estimate = QCONST16(.2f,14);
+      }
+   }
+
+   if (LM>0 && ec_tell(enc)+3<=total_bits)
+      ec_enc_bit_logp(enc, isTransient, 3);
+
+   ALLOC(X, C*N, celt_norm);         /**< Interleaved normalised MDCTs */
+
+   /* Band normalisation */
+   normalise_bands(mode, freq, X, bandE, effEnd, C, M);
+
+   ALLOC(tf_res, nbEBands, int);
+   /* Disable variable tf resolution for hybrid and at very low bitrate */
+   if (effectiveBytes>=15*C && !hybrid && st->complexity>=2 && !st->lfe)
+   {
+      int lambda;
+      lambda = IMAX(5, 1280/effectiveBytes + 2);
+      tf_select = tf_analysis(mode, effEnd, isTransient, tf_res, lambda, X, N, LM, tf_estimate, tf_chan);
+      for (i=effEnd;i<end;i++)
+         tf_res[i] = tf_res[effEnd-1];
+   } else if (hybrid && weak_transient)
+   {
+      /* For weak transients, we rely on the fact that improving time resolution using
+         TF on a long window is imperfect and will not result in an energy collapse at
+         low bitrate. */
+      for (i=0;i<end;i++)
+         tf_res[i] = 1;
+      tf_select=0;
+   } else if (hybrid && effectiveBytes<15)
+   {
+      /* For low bitrate hybrid, we force temporal resolution to 5 ms rather than 2.5 ms. */
+      for (i=0;i<end;i++)
+         tf_res[i] = 0;
+      tf_select=isTransient;
+   } else {
+      for (i=0;i<end;i++)
+         tf_res[i] = isTransient;
+      tf_select=0;
+   }
+
+   ALLOC(error, C*nbEBands, opus_val16);
+   c=0;
+   do {
+      for (i=start;i<end;i++)
+      {
+         /* When the energy is stable, slightly bias energy quantization towards
+            the previous error to make the gain more stable (a constant offset is
+            better than fluctuations). */
+         if (ABS32(SUB32(bandLogE[i+c*nbEBands], oldBandE[i+c*nbEBands])) < QCONST16(2.f, DB_SHIFT))
+         {
+            bandLogE[i+c*nbEBands] -= MULT16_16_Q15(energyError[i+c*nbEBands], QCONST16(0.25f, 15));
+         }
+      }
+   } while (++c < C);
+   quant_coarse_energy(mode, start, end, effEnd, bandLogE,
+         oldBandE, total_bits, error, enc,
+         C, LM, nbAvailableBytes, st->force_intra,
+         &st->delayedIntra, st->complexity >= 4, st->loss_rate, st->lfe);
+
+   tf_encode(start, end, isTransient, tf_res, LM, tf_select, enc);
+
+   if (ec_tell(enc)+4<=total_bits)
+   {
+      if (st->lfe)
+      {
+         st->tapset_decision = 0;
+         st->spread_decision = SPREAD_NORMAL;
+      } else if (hybrid)
+      {
+         if (st->complexity == 0)
+            st->spread_decision = SPREAD_NONE;
+         else if (isTransient)
+            st->spread_decision = SPREAD_NORMAL;
+         else
+            st->spread_decision = SPREAD_AGGRESSIVE;
+      } else if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C)
+      {
+         if (st->complexity == 0)
+            st->spread_decision = SPREAD_NONE;
+         else
+            st->spread_decision = SPREAD_NORMAL;
+      } else {
+         /* Disable new spreading+tapset estimator until we can show it works
+            better than the old one. So far it seems like spreading_decision()
+            works best. */
+#if 0
+         if (st->analysis.valid)
+         {
+            static const opus_val16 spread_thresholds[3] = {-QCONST16(.6f, 15), -QCONST16(.2f, 15), -QCONST16(.07f, 15)};
+            static const opus_val16 spread_histeresis[3] = {QCONST16(.15f, 15), QCONST16(.07f, 15), QCONST16(.02f, 15)};
+            static const opus_val16 tapset_thresholds[2] = {QCONST16(.0f, 15), QCONST16(.15f, 15)};
+            static const opus_val16 tapset_histeresis[2] = {QCONST16(.1f, 15), QCONST16(.05f, 15)};
+            st->spread_decision = hysteresis_decision(-st->analysis.tonality, spread_thresholds, spread_histeresis, 3, st->spread_decision);
+            st->tapset_decision = hysteresis_decision(st->analysis.tonality_slope, tapset_thresholds, tapset_histeresis, 2, st->tapset_decision);
+         } else
+#endif
+         {
+            st->spread_decision = spreading_decision(mode, X,
+                  &st->tonal_average, st->spread_decision, &st->hf_average,
+                  &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M);
+         }
+         /*printf("%d %d\n", st->tapset_decision, st->spread_decision);*/
+         /*printf("%f %d %f %d\n\n", st->analysis.tonality, st->spread_decision, st->analysis.tonality_slope, st->tapset_decision);*/
+      }
+      ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
+   }
+
+   ALLOC(offsets, nbEBands, int);
+
+   maxDepth = dynalloc_analysis(bandLogE, bandLogE2, nbEBands, start, end, C, offsets,
+         st->lsb_depth, mode->logN, isTransient, st->vbr, st->constrained_vbr,
+         eBands, LM, effectiveBytes, &tot_boost, st->lfe, surround_dynalloc, &st->analysis);
+   /* For LFE, everything interesting is in the first band */
+   if (st->lfe)
+      offsets[0] = IMIN(8, effectiveBytes/3);
+   ALLOC(cap, nbEBands, int);
+   init_caps(mode,cap,LM,C);
+
+   dynalloc_logp = 6;
+   total_bits<<=BITRES;
+   total_boost = 0;
+   tell = ec_tell_frac(enc);
+   for (i=start;i<end;i++)
+   {
+      int width, quanta;
+      int dynalloc_loop_logp;
+      int boost;
+      int j;
+      width = C*(eBands[i+1]-eBands[i])<<LM;
+      /* quanta is 6 bits, but no more than 1 bit/sample
+         and no less than 1/8 bit/sample */
+      quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
+      dynalloc_loop_logp = dynalloc_logp;
+      boost = 0;
+      for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost
+            && boost < cap[i]; j++)
+      {
+         int flag;
+         flag = j<offsets[i];
+         ec_enc_bit_logp(enc, flag, dynalloc_loop_logp);
+         tell = ec_tell_frac(enc);
+         if (!flag)
+            break;
+         boost += quanta;
+         total_boost += quanta;
+         dynalloc_loop_logp = 1;
+      }
+      /* Making dynalloc more likely */
+      if (j)
+         dynalloc_logp = IMAX(2, dynalloc_logp-1);
+      offsets[i] = boost;
+   }
+
+   if (C==2)
+   {
+      static const opus_val16 intensity_thresholds[21]=
+      /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19  20  off*/
+        {  1, 2, 3, 4, 5, 6, 7, 8,16,24,36,44,50,56,62,67,72,79,88,106,134};
+      static const opus_val16 intensity_histeresis[21]=
+        {  1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6,  8, 8};
+
+      /* Always use MS for 2.5 ms frames until we can do a better analysis */
+      if (LM!=0)
+         dual_stereo = stereo_analysis(mode, X, LM, N);
+
+      st->intensity = hysteresis_decision((opus_val16)(equiv_rate/1000),
+            intensity_thresholds, intensity_histeresis, 21, st->intensity);
+      st->intensity = IMIN(end,IMAX(start, st->intensity));
+   }
+
+   alloc_trim = 5;
+   if (tell+(6<<BITRES) <= total_bits - total_boost)
+   {
+      if (start > 0 || st->lfe)
+      {
+         st->stereo_saving = 0;
+         alloc_trim = 5;
+      } else {
+         alloc_trim = alloc_trim_analysis(mode, X, bandLogE,
+            end, LM, C, N, &st->analysis, &st->stereo_saving, tf_estimate,
+            st->intensity, surround_trim, equiv_rate, st->arch);
+      }
+      ec_enc_icdf(enc, alloc_trim, trim_icdf, 7);
+      tell = ec_tell_frac(enc);
+   }
+
+   /* Variable bitrate */
+   if (vbr_rate>0)
+   {
+     opus_val16 alpha;
+     opus_int32 delta;
+     /* The target rate in 8th bits per frame */
+     opus_int32 target, base_target;
+     opus_int32 min_allowed;
+     int lm_diff = mode->maxLM - LM;
+
+     /* Don't attempt to use more than 510 kb/s, even for frames smaller than 20 ms.
+        The CELT allocator will just not be able to use more than that anyway. */
+     nbCompressedBytes = IMIN(nbCompressedBytes,1275>>(3-LM));
+     if (!hybrid)
+     {
+        base_target = vbr_rate - ((40*C+20)<<BITRES);
+     } else {
+        base_target = IMAX(0, vbr_rate - ((9*C+4)<<BITRES));
+     }
+
+     if (st->constrained_vbr)
+        base_target += (st->vbr_offset>>lm_diff);
+
+     if (!hybrid)
+     {
+        target = compute_vbr(mode, &st->analysis, base_target, LM, equiv_rate,
+           st->lastCodedBands, C, st->intensity, st->constrained_vbr,
+           st->stereo_saving, tot_boost, tf_estimate, pitch_change, maxDepth,
+           st->lfe, st->energy_mask!=NULL, surround_masking,
+           temporal_vbr);
+     } else {
+        target = base_target;
+        /* Tonal frames (offset<100) need more bits than noisy (offset>100) ones. */
+        if (st->silk_info.offset < 100) target += 12 << BITRES >> (3-LM);
+        if (st->silk_info.offset > 100) target -= 18 << BITRES >> (3-LM);
+        /* Boosting bitrate on transients and vowels with significant temporal
+           spikes. */
+        target += (opus_int32)MULT16_16_Q14(tf_estimate-QCONST16(.25f,14), (50<<BITRES));
+        /* If we have a strong transient, let's make sure it has enough bits to code
+           the first two bands, so that it can use folding rather than noise. */
+        if (tf_estimate > QCONST16(.7f,14))
+           target = IMAX(target, 50<<BITRES);
+     }
+     /* The current offset is removed from the target and the space used
+        so far is added*/
+     target=target+tell;
+     /* In VBR mode the frame size must not be reduced so much that it would
+         result in the encoder running out of bits.
+        The margin of 2 bytes ensures that none of the bust-prevention logic
+         in the decoder will have triggered so far. */
+     min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2;
+     /* Take into account the 37 bits we need to have left in the packet to
+        signal a redundant frame in hybrid mode. Creating a shorter packet would
+        create an entropy coder desync. */
+     if (hybrid)
+        min_allowed = IMAX(min_allowed, (tell0_frac+(37<<BITRES)+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3));
+
+     nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
+     nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
+     nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes);
+
+     /* By how much did we "miss" the target on that frame */
+     delta = target - vbr_rate;
+
+     target=nbAvailableBytes<<(BITRES+3);
+
+     /*If the frame is silent we don't adjust our drift, otherwise
+       the encoder will shoot to very high rates after hitting a
+       span of silence, but we do allow the bitres to refill.
+       This means that we'll undershoot our target in CVBR/VBR modes
+       on files with lots of silence. */
+     if(silence)
+     {
+       nbAvailableBytes = 2;
+       target = 2*8<<BITRES;
+       delta = 0;
+     }
+
+     if (st->vbr_count < 970)
+     {
+        st->vbr_count++;
+        alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16));
+     } else
+        alpha = QCONST16(.001f,15);
+     /* How many bits have we used in excess of what we're allowed */
+     if (st->constrained_vbr)
+        st->vbr_reservoir += target - vbr_rate;
+     /*printf ("%d\n", st->vbr_reservoir);*/
+
+     /* Compute the offset we need to apply in order to reach the target */
+     if (st->constrained_vbr)
+     {
+        st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift);
+        st->vbr_offset = -st->vbr_drift;
+     }
+     /*printf ("%d\n", st->vbr_drift);*/
+
+     if (st->constrained_vbr && st->vbr_reservoir < 0)
+     {
+        /* We're under the min value -- increase rate */
+        int adjust = (-st->vbr_reservoir)/(8<<BITRES);
+        /* Unless we're just coding silence */
+        nbAvailableBytes += silence?0:adjust;
+        st->vbr_reservoir = 0;
+        /*printf ("+%d\n", adjust);*/
+     }
+     nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes);
+     /*printf("%d\n", nbCompressedBytes*50*8);*/
+     /* This moves the raw bits to take into account the new compressed size */
+     ec_enc_shrink(enc, nbCompressedBytes);
+   }
+
+   /* Bit allocation */
+   ALLOC(fine_quant, nbEBands, int);
+   ALLOC(pulses, nbEBands, int);
+   ALLOC(fine_priority, nbEBands, int);
+
+   /* bits =           packet size                    - where we are - safety*/
+   bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - ec_tell_frac(enc) - 1;
+   anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
+   bits -= anti_collapse_rsv;
+   signalBandwidth = end-1;
+#ifndef DISABLE_FLOAT_API
+   if (st->analysis.valid)
+   {
+      int min_bandwidth;
+      if (equiv_rate < (opus_int32)32000*C)
+         min_bandwidth = 13;
+      else if (equiv_rate < (opus_int32)48000*C)
+         min_bandwidth = 16;
+      else if (equiv_rate < (opus_int32)60000*C)
+         min_bandwidth = 18;
+      else  if (equiv_rate < (opus_int32)80000*C)
+         min_bandwidth = 19;
+      else
+         min_bandwidth = 20;
+      signalBandwidth = IMAX(st->analysis.bandwidth, min_bandwidth);
+   }
+#endif
+   if (st->lfe)
+      signalBandwidth = 1;
+   codedBands = compute_allocation(mode, start, end, offsets, cap,
+         alloc_trim, &st->intensity, &dual_stereo, bits, &balance, pulses,
+         fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands, signalBandwidth);
+   if (st->lastCodedBands)
+      st->lastCodedBands = IMIN(st->lastCodedBands+1,IMAX(st->lastCodedBands-1,codedBands));
+   else
+      st->lastCodedBands = codedBands;
+
+   quant_fine_energy(mode, start, end, oldBandE, error, fine_quant, enc, C);
+
+   /* Residual quantisation */
+   ALLOC(collapse_masks, C*nbEBands, unsigned char);
+   quant_all_bands(1, mode, start, end, X, C==2 ? X+N : NULL, collapse_masks,
+         bandE, pulses, shortBlocks, st->spread_decision,
+         dual_stereo, st->intensity, tf_res, nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv,
+         balance, enc, LM, codedBands, &st->rng, st->complexity, st->arch, st->disable_inv);
+
+   if (anti_collapse_rsv > 0)
+   {
+      anti_collapse_on = st->consec_transient<2;
+#ifdef FUZZING
+      anti_collapse_on = rand()&0x1;
+#endif
+      ec_enc_bits(enc, anti_collapse_on, 1);
+   }
+   quant_energy_finalise(mode, start, end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
+   OPUS_CLEAR(energyError, nbEBands*CC);
+   c=0;
+   do {
+      for (i=start;i<end;i++)
+      {
+         energyError[i+c*nbEBands] = MAX16(-QCONST16(0.5f, 15), MIN16(QCONST16(0.5f, 15), error[i+c*nbEBands]));
+      }
+   } while (++c < C);
+
+   if (silence)
+   {
+      for (i=0;i<C*nbEBands;i++)
+         oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
+   }
+
+#ifdef RESYNTH
+   /* Re-synthesis of the coded audio if required */
+   {
+      celt_sig *out_mem[2];
+
+      if (anti_collapse_on)
+      {
+         anti_collapse(mode, X, collapse_masks, LM, C, N,
+               start, end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
+      }
+
+      c=0; do {
+         OPUS_MOVE(st->syn_mem[c], st->syn_mem[c]+N, 2*MAX_PERIOD-N+overlap/2);
+      } while (++c<CC);
+
+      c=0; do {
+         out_mem[c] = st->syn_mem[c]+2*MAX_PERIOD-N;
+      } while (++c<CC);
+
+      celt_synthesis(mode, X, out_mem, oldBandE, start, effEnd,
+                     C, CC, isTransient, LM, st->upsample, silence, st->arch);
+
+      c=0; do {
+         st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
+         st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD);
+         comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, mode->shortMdctSize,
+               st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
+               mode->window, overlap);
+         if (LM!=0)
+            comb_filter(out_mem[c]+mode->shortMdctSize, out_mem[c]+mode->shortMdctSize, st->prefilter_period, pitch_index, N-mode->shortMdctSize,
+                  st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
+                  mode->window, overlap);
+      } while (++c<CC);
+
+      /* We reuse freq[] as scratch space for the de-emphasis */
+      deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, mode->preemph, st->preemph_memD);
+      st->prefilter_period_old = st->prefilter_period;
+      st->prefilter_gain_old = st->prefilter_gain;
+      st->prefilter_tapset_old = st->prefilter_tapset;
+   }
+#endif
+
+   st->prefilter_period = pitch_index;
+   st->prefilter_gain = gain1;
+   st->prefilter_tapset = prefilter_tapset;
+#ifdef RESYNTH
+   if (LM!=0)
+   {
+      st->prefilter_period_old = st->prefilter_period;
+      st->prefilter_gain_old = st->prefilter_gain;
+      st->prefilter_tapset_old = st->prefilter_tapset;
+   }
+#endif
+
+   if (CC==2&&C==1) {
+      OPUS_COPY(&oldBandE[nbEBands], oldBandE, nbEBands);
+   }
+
+   if (!isTransient)
+   {
+      OPUS_COPY(oldLogE2, oldLogE, CC*nbEBands);
+      OPUS_COPY(oldLogE, oldBandE, CC*nbEBands);
+   } else {
+      for (i=0;i<CC*nbEBands;i++)
+         oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
+   }
+   /* In case start or end were to change */
+   c=0; do
+   {
+      for (i=0;i<start;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+      for (i=end;i<nbEBands;i++)
+      {
+         oldBandE[c*nbEBands+i]=0;
+         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
+      }
+   } while (++c<CC);
+
+   if (isTransient || transient_got_disabled)
+      st->consec_transient++;
+   else
+      st->consec_transient=0;
+   st->rng = enc->rng;
+
+   /* If there's any room left (can only happen for very high rates),
+      it's already filled with zeros */
+   ec_enc_done(enc);
+
+#ifdef CUSTOM_MODES
+   if (st->signalling)
+      nbCompressedBytes++;
+#endif
+
+   RESTORE_STACK;
+   if (ec_get_error(enc))
+      return OPUS_INTERNAL_ERROR;
+   else
+      return nbCompressedBytes;
+}
+
+
+#ifdef CUSTOM_MODES
+
+#ifdef FIXED_POINT
+int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
+{
+   return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
+}
+
+#ifndef DISABLE_FLOAT_API
+int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
+{
+   int j, ret, C, N;
+   VARDECL(opus_int16, in);
+   ALLOC_STACK;
+
+   if (pcm==NULL)
+      return OPUS_BAD_ARG;
+
+   C = st->channels;
+   N = frame_size;
+   ALLOC(in, C*N, opus_int16);
+
+   for (j=0;j<C*N;j++)
+     in[j] = FLOAT2INT16(pcm[j]);
+
+   ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
+#ifdef RESYNTH
+   for (j=0;j<C*N;j++)
+      ((float*)pcm)[j]=in[j]*(1.f/32768.f);
+#endif
+   RESTORE_STACK;
+   return ret;
+}
+#endif /* DISABLE_FLOAT_API */
+#else
+
+int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
+{
+   int j, ret, C, N;
+   VARDECL(celt_sig, in);
+   ALLOC_STACK;
+
+   if (pcm==NULL)
+      return OPUS_BAD_ARG;
+
+   C=st->channels;
+   N=frame_size;
+   ALLOC(in, C*N, celt_sig);
+   for (j=0;j<C*N;j++) {
+     in[j] = SCALEOUT(pcm[j]);
+   }
+
+   ret = celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
+#ifdef RESYNTH
+   for (j=0;j<C*N;j++)
+      ((opus_int16*)pcm)[j] = FLOAT2INT16(in[j]);
+#endif
+   RESTORE_STACK;
+   return ret;
+}
+
+int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
+{
+   return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
+}
+
+#endif
+
+#endif /* CUSTOM_MODES */
+
+int opus_custom_encoder_ctl(CELTEncoder * OPUS_RESTRICT st, int request, ...)
+{
+   va_list ap;
+
+   va_start(ap, request);
+   switch (request)
+   {
+      case OPUS_SET_COMPLEXITY_REQUEST:
+      {
+         int value = va_arg(ap, opus_int32);
+         if (value<0 || value>10)
+            goto bad_arg;
+         st->complexity = value;
+      }
+      break;
+      case CELT_SET_START_BAND_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<0 || value>=st->mode->nbEBands)
+            goto bad_arg;
+         st->start = value;
+      }
+      break;
+      case CELT_SET_END_BAND_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<1 || value>st->mode->nbEBands)
+            goto bad_arg;
+         st->end = value;
+      }
+      break;
+      case CELT_SET_PREDICTION_REQUEST:
+      {
+         int value = va_arg(ap, opus_int32);
+         if (value<0 || value>2)
+            goto bad_arg;
+         st->disable_pf = value<=1;
+         st->force_intra = value==0;
+      }
+      break;
+      case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
+      {
+         int value = va_arg(ap, opus_int32);
+         if (value<0 || value>100)
+            goto bad_arg;
+         st->loss_rate = value;
+      }
+      break;
+      case OPUS_SET_VBR_CONSTRAINT_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         st->constrained_vbr = value;
+      }
+      break;
+      case OPUS_SET_VBR_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         st->vbr = value;
+      }
+      break;
+      case OPUS_SET_BITRATE_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<=500 && value!=OPUS_BITRATE_MAX)
+            goto bad_arg;
+         value = IMIN(value, 260000*st->channels);
+         st->bitrate = value;
+      }
+      break;
+      case CELT_SET_CHANNELS_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         if (value<1 || value>2)
+            goto bad_arg;
+         st->stream_channels = value;
+      }
+      break;
+      case OPUS_SET_LSB_DEPTH_REQUEST:
+      {
+          opus_int32 value = va_arg(ap, opus_int32);
+          if (value<8 || value>24)
+             goto bad_arg;
+          st->lsb_depth=value;
+      }
+      break;
+      case OPUS_GET_LSB_DEPTH_REQUEST:
+      {
+          opus_int32 *value = va_arg(ap, opus_int32*);
+          *value=st->lsb_depth;
+      }
+      break;
+      case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+      {
+          opus_int32 value = va_arg(ap, opus_int32);
+          if(value<0 || value>1)
+          {
+             goto bad_arg;
+          }
+          st->disable_inv = value;
+      }
+      break;
+      case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+      {
+          opus_int32 *value = va_arg(ap, opus_int32*);
+          if (!value)
+          {
+             goto bad_arg;
+          }
+          *value = st->disable_inv;
+      }
+      break;
+      case OPUS_RESET_STATE:
+      {
+         int i;
+         opus_val16 *oldBandE, *oldLogE, *oldLogE2;
+         oldBandE = (opus_val16*)(st->in_mem+st->channels*(st->mode->overlap+COMBFILTER_MAXPERIOD));
+         oldLogE = oldBandE + st->channels*st->mode->nbEBands;
+         oldLogE2 = oldLogE + st->channels*st->mode->nbEBands;
+         OPUS_CLEAR((char*)&st->ENCODER_RESET_START,
+               opus_custom_encoder_get_size(st->mode, st->channels)-
+               ((char*)&st->ENCODER_RESET_START - (char*)st));
+         for (i=0;i<st->channels*st->mode->nbEBands;i++)
+            oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
+         st->vbr_offset = 0;
+         st->delayedIntra = 1;
+         st->spread_decision = SPREAD_NORMAL;
+         st->tonal_average = 256;
+         st->hf_average = 0;
+         st->tapset_decision = 0;
+      }
+      break;
+#ifdef CUSTOM_MODES
+      case CELT_SET_INPUT_CLIPPING_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         st->clip = value;
+      }
+      break;
+#endif
+      case CELT_SET_SIGNALLING_REQUEST:
+      {
+         opus_int32 value = va_arg(ap, opus_int32);
+         st->signalling = value;
+      }
+      break;
+      case CELT_SET_ANALYSIS_REQUEST:
+      {
+         AnalysisInfo *info = va_arg(ap, AnalysisInfo *);
+         if (info)
+            OPUS_COPY(&st->analysis, info, 1);
+      }
+      break;
+      case CELT_SET_SILK_INFO_REQUEST:
+      {
+         SILKInfo *info = va_arg(ap, SILKInfo *);
+         if (info)
+            OPUS_COPY(&st->silk_info, info, 1);
+      }
+      break;
+      case CELT_GET_MODE_REQUEST:
+      {
+         const CELTMode ** value = va_arg(ap, const CELTMode**);
+         if (value==0)
+            goto bad_arg;
+         *value=st->mode;
+      }
+      break;
+      case OPUS_GET_FINAL_RANGE_REQUEST:
+      {
+         opus_uint32 * value = va_arg(ap, opus_uint32 *);
+         if (value==0)
+            goto bad_arg;
+         *value=st->rng;
+      }
+      break;
+      case OPUS_SET_LFE_REQUEST:
+      {
+          opus_int32 value = va_arg(ap, opus_int32);
+          st->lfe = value;
+      }
+      break;
+      case OPUS_SET_ENERGY_MASK_REQUEST:
+      {
+          opus_val16 *value = va_arg(ap, opus_val16*);
+          st->energy_mask = value;
+      }
+      break;
+      default:
+         goto bad_request;
+   }
+   va_end(ap);
+   return OPUS_OK;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
+bad_request:
+   va_end(ap);
+   return OPUS_UNIMPLEMENTED;
+}
diff --git a/opus/celt/celt_lpc.c b/opus/celt/celt_lpc.c
new file mode 100644 (file)
index 0000000..57bc5f3
--- /dev/null
@@ -0,0 +1,296 @@
+/* Copyright (c) 2009-2010 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "pitch.h"
+
+void _celt_lpc(
+      opus_val16       *_lpc, /* out: [0...p-1] LPC coefficients      */
+const opus_val32 *ac,  /* in:  [0...p] autocorrelation values  */
+int          p
+)
+{
+   int i, j;
+   opus_val32 r;
+   opus_val32 error = ac[0];
+#ifdef FIXED_POINT
+   opus_val32 lpc[LPC_ORDER];
+#else
+   float *lpc = _lpc;
+#endif
+
+   OPUS_CLEAR(lpc, p);
+   if (ac[0] != 0)
+   {
+      for (i = 0; i < p; i++) {
+         /* Sum up this iteration's reflection coefficient */
+         opus_val32 rr = 0;
+         for (j = 0; j < i; j++)
+            rr += MULT32_32_Q31(lpc[j],ac[i - j]);
+         rr += SHR32(ac[i + 1],3);
+         r = -frac_div32(SHL32(rr,3), error);
+         /*  Update LPC coefficients and total error */
+         lpc[i] = SHR32(r,3);
+         for (j = 0; j < (i+1)>>1; j++)
+         {
+            opus_val32 tmp1, tmp2;
+            tmp1 = lpc[j];
+            tmp2 = lpc[i-1-j];
+            lpc[j]     = tmp1 + MULT32_32_Q31(r,tmp2);
+            lpc[i-1-j] = tmp2 + MULT32_32_Q31(r,tmp1);
+         }
+
+         error = error - MULT32_32_Q31(MULT32_32_Q31(r,r),error);
+         /* Bail out once we get 30 dB gain */
+#ifdef FIXED_POINT
+         if (error<SHR32(ac[0],10))
+            break;
+#else
+         if (error<.001f*ac[0])
+            break;
+#endif
+      }
+   }
+#ifdef FIXED_POINT
+   for (i=0;i<p;i++)
+      _lpc[i] = ROUND16(lpc[i],16);
+#endif
+}
+
+
+void celt_fir_c(
+         const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         int ord,
+         int arch)
+{
+   int i,j;
+   VARDECL(opus_val16, rnum);
+   SAVE_STACK;
+
+   ALLOC(rnum, ord, opus_val16);
+   for(i=0;i<ord;i++)
+      rnum[i] = num[ord-i-1];
+   for (i=0;i<N-3;i+=4)
+   {
+      opus_val32 sum[4];
+      sum[0] = SHL32(EXTEND32(x[i  ]), SIG_SHIFT);
+      sum[1] = SHL32(EXTEND32(x[i+1]), SIG_SHIFT),
+      sum[2] = SHL32(EXTEND32(x[i+2]), SIG_SHIFT);
+      sum[3] = SHL32(EXTEND32(x[i+3]), SIG_SHIFT);
+      xcorr_kernel(rnum, x+i-ord, sum, ord, arch);
+      y[i  ] = ROUND16(sum[0], SIG_SHIFT);
+      y[i+1] = ROUND16(sum[1], SIG_SHIFT);
+      y[i+2] = ROUND16(sum[2], SIG_SHIFT);
+      y[i+3] = ROUND16(sum[3], SIG_SHIFT);
+   }
+   for (;i<N;i++)
+   {
+      opus_val32 sum = SHL32(EXTEND32(x[i]), SIG_SHIFT);
+      for (j=0;j<ord;j++)
+         sum = MAC16_16(sum,rnum[j],x[i+j-ord]);
+      y[i] = ROUND16(sum, SIG_SHIFT);
+   }
+   RESTORE_STACK;
+}
+
+void celt_iir(const opus_val32 *_x,
+         const opus_val16 *den,
+         opus_val32 *_y,
+         int N,
+         int ord,
+         opus_val16 *mem,
+         int arch)
+{
+#ifdef SMALL_FOOTPRINT
+   int i,j;
+   (void)arch;
+   for (i=0;i<N;i++)
+   {
+      opus_val32 sum = _x[i];
+      for (j=0;j<ord;j++)
+      {
+         sum -= MULT16_16(den[j],mem[j]);
+      }
+      for (j=ord-1;j>=1;j--)
+      {
+         mem[j]=mem[j-1];
+      }
+      mem[0] = SROUND16(sum, SIG_SHIFT);
+      _y[i] = sum;
+   }
+#else
+   int i,j;
+   VARDECL(opus_val16, rden);
+   VARDECL(opus_val16, y);
+   SAVE_STACK;
+
+   celt_assert((ord&3)==0);
+   ALLOC(rden, ord, opus_val16);
+   ALLOC(y, N+ord, opus_val16);
+   for(i=0;i<ord;i++)
+      rden[i] = den[ord-i-1];
+   for(i=0;i<ord;i++)
+      y[i] = -mem[ord-i-1];
+   for(;i<N+ord;i++)
+      y[i]=0;
+   for (i=0;i<N-3;i+=4)
+   {
+      /* Unroll by 4 as if it were an FIR filter */
+      opus_val32 sum[4];
+      sum[0]=_x[i];
+      sum[1]=_x[i+1];
+      sum[2]=_x[i+2];
+      sum[3]=_x[i+3];
+      xcorr_kernel(rden, y+i, sum, ord, arch);
+
+      /* Patch up the result to compensate for the fact that this is an IIR */
+      y[i+ord  ] = -SROUND16(sum[0],SIG_SHIFT);
+      _y[i  ] = sum[0];
+      sum[1] = MAC16_16(sum[1], y[i+ord  ], den[0]);
+      y[i+ord+1] = -SROUND16(sum[1],SIG_SHIFT);
+      _y[i+1] = sum[1];
+      sum[2] = MAC16_16(sum[2], y[i+ord+1], den[0]);
+      sum[2] = MAC16_16(sum[2], y[i+ord  ], den[1]);
+      y[i+ord+2] = -SROUND16(sum[2],SIG_SHIFT);
+      _y[i+2] = sum[2];
+
+      sum[3] = MAC16_16(sum[3], y[i+ord+2], den[0]);
+      sum[3] = MAC16_16(sum[3], y[i+ord+1], den[1]);
+      sum[3] = MAC16_16(sum[3], y[i+ord  ], den[2]);
+      y[i+ord+3] = -SROUND16(sum[3],SIG_SHIFT);
+      _y[i+3] = sum[3];
+   }
+   for (;i<N;i++)
+   {
+      opus_val32 sum = _x[i];
+      for (j=0;j<ord;j++)
+         sum -= MULT16_16(rden[j],y[i+j]);
+      y[i+ord] = SROUND16(sum,SIG_SHIFT);
+      _y[i] = sum;
+   }
+   for(i=0;i<ord;i++)
+      mem[i] = _y[N-i-1];
+   RESTORE_STACK;
+#endif
+}
+
+int _celt_autocorr(
+                   const opus_val16 *x,   /*  in: [0...n-1] samples x   */
+                   opus_val32       *ac,  /* out: [0...lag-1] ac values */
+                   const opus_val16       *window,
+                   int          overlap,
+                   int          lag,
+                   int          n,
+                   int          arch
+                  )
+{
+   opus_val32 d;
+   int i, k;
+   int fastN=n-lag;
+   int shift;
+   const opus_val16 *xptr;
+   VARDECL(opus_val16, xx);
+   SAVE_STACK;
+   ALLOC(xx, n, opus_val16);
+   celt_assert(n>0);
+   celt_assert(overlap>=0);
+   if (overlap == 0)
+   {
+      xptr = x;
+   } else {
+      for (i=0;i<n;i++)
+         xx[i] = x[i];
+      for (i=0;i<overlap;i++)
+      {
+         xx[i] = MULT16_16_Q15(x[i],window[i]);
+         xx[n-i-1] = MULT16_16_Q15(x[n-i-1],window[i]);
+      }
+      xptr = xx;
+   }
+   shift=0;
+#ifdef FIXED_POINT
+   {
+      opus_val32 ac0;
+      ac0 = 1+(n<<7);
+      if (n&1) ac0 += SHR32(MULT16_16(xptr[0],xptr[0]),9);
+      for(i=(n&1);i<n;i+=2)
+      {
+         ac0 += SHR32(MULT16_16(xptr[i],xptr[i]),9);
+         ac0 += SHR32(MULT16_16(xptr[i+1],xptr[i+1]),9);
+      }
+
+      shift = celt_ilog2(ac0)-30+10;
+      shift = (shift)/2;
+      if (shift>0)
+      {
+         for(i=0;i<n;i++)
+            xx[i] = PSHR32(xptr[i], shift);
+         xptr = xx;
+      } else
+         shift = 0;
+   }
+#endif
+   celt_pitch_xcorr(xptr, xptr, ac, fastN, lag+1, arch);
+   for (k=0;k<=lag;k++)
+   {
+      for (i = k+fastN, d = 0; i < n; i++)
+         d = MAC16_16(d, xptr[i], xptr[i-k]);
+      ac[k] += d;
+   }
+#ifdef FIXED_POINT
+   shift = 2*shift;
+   if (shift<=0)
+      ac[0] += SHL32((opus_int32)1, -shift);
+   if (ac[0] < 268435456)
+   {
+      int shift2 = 29 - EC_ILOG(ac[0]);
+      for (i=0;i<=lag;i++)
+         ac[i] = SHL32(ac[i], shift2);
+      shift -= shift2;
+   } else if (ac[0] >= 536870912)
+   {
+      int shift2=1;
+      if (ac[0] >= 1073741824)
+         shift2++;
+      for (i=0;i<=lag;i++)
+         ac[i] = SHR32(ac[i], shift2);
+      shift += shift2;
+   }
+#endif
+
+   RESTORE_STACK;
+   return shift;
+}
diff --git a/opus/celt/celt_lpc.h b/opus/celt/celt_lpc.h
new file mode 100644 (file)
index 0000000..a4c5fd6
--- /dev/null
@@ -0,0 +1,66 @@
+/* Copyright (c) 2009-2010 Xiph.Org Foundation
+   Written by 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.
+
+   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 PLC_H
+#define PLC_H
+
+#include "arch.h"
+#include "cpu_support.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#include "x86/celt_lpc_sse.h"
+#endif
+
+#define LPC_ORDER 24
+
+void _celt_lpc(opus_val16 *_lpc, const opus_val32 *ac, int p);
+
+void celt_fir_c(
+         const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         int ord,
+         int arch);
+
+#if !defined(OVERRIDE_CELT_FIR)
+#define celt_fir(x, num, y, N, ord, arch) \
+    (celt_fir_c(x, num, y, N, ord, arch))
+#endif
+
+void celt_iir(const opus_val32 *x,
+         const opus_val16 *den,
+         opus_val32 *y,
+         int N,
+         int ord,
+         opus_val16 *mem,
+         int arch);
+
+int _celt_autocorr(const opus_val16 *x, opus_val32 *ac,
+         const opus_val16 *window, int overlap, int lag, int n, int arch);
+
+#endif /* PLC_H */
diff --git a/opus/celt/cpu_support.h b/opus/celt/cpu_support.h
new file mode 100644 (file)
index 0000000..68fc606
--- /dev/null
@@ -0,0 +1,70 @@
+/* Copyright (c) 2010 Xiph.Org Foundation
+ * Copyright (c) 2013 Parrot */
+/*
+   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.
+
+   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 CPU_SUPPORT_H
+#define CPU_SUPPORT_H
+
+#include "opus_types.h"
+#include "opus_defines.h"
+
+#if defined(OPUS_HAVE_RTCD) && \
+  (defined(OPUS_ARM_ASM) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR))
+#include "arm/armcpu.h"
+
+/* We currently support 4 ARM variants:
+ * arch[0] -> ARMv4
+ * arch[1] -> ARMv5E
+ * arch[2] -> ARMv6
+ * arch[3] -> NEON
+ */
+#define OPUS_ARCHMASK 3
+
+#elif (defined(OPUS_X86_MAY_HAVE_SSE) && !defined(OPUS_X86_PRESUME_SSE)) || \
+  (defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(OPUS_X86_PRESUME_SSE2)) || \
+  (defined(OPUS_X86_MAY_HAVE_SSE4_1) && !defined(OPUS_X86_PRESUME_SSE4_1)) || \
+  (defined(OPUS_X86_MAY_HAVE_AVX) && !defined(OPUS_X86_PRESUME_AVX))
+
+#include "x86/x86cpu.h"
+/* We currently support 5 x86 variants:
+ * arch[0] -> non-sse
+ * arch[1] -> sse
+ * arch[2] -> sse2
+ * arch[3] -> sse4.1
+ * arch[4] -> avx
+ */
+#define OPUS_ARCHMASK 7
+int opus_select_arch(void);
+
+#else
+#define OPUS_ARCHMASK 0
+
+static OPUS_INLINE int opus_select_arch(void)
+{
+  return 0;
+}
+#endif
+#endif
diff --git a/opus/celt/cwrs.c b/opus/celt/cwrs.c
new file mode 100644 (file)
index 0000000..9722f0a
--- /dev/null
@@ -0,0 +1,715 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2007-2009 Timothy B. Terriberry
+   Written by Timothy B. Terriberry and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "os_support.h"
+#include "cwrs.h"
+#include "mathops.h"
+#include "arch.h"
+
+#ifdef CUSTOM_MODES
+
+/*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(opus_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).
+       Doesn't work for val=0, but that case fails the test above.*/
+    if(l>16)val=((val-1)>>(l-16))+1;
+    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;
+}
+#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
+   https://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
+  }*/
+
+#if !defined(SMALL_FOOTPRINT)
+
+/*U(N,K) = U(K,N) := N>0?K>0?U(N-1,K)+U(N,K-1)+U(N-1,K-1):0:K>0?1:0*/
+# define CELT_PVQ_U(_n,_k) (CELT_PVQ_U_ROW[IMIN(_n,_k)][IMAX(_n,_k)])
+/*V(N,K) := U(N,K)+U(N,K+1) = the number of PVQ codewords for a band of size N
+   with K pulses allocated to it.*/
+# define CELT_PVQ_V(_n,_k) (CELT_PVQ_U(_n,_k)+CELT_PVQ_U(_n,(_k)+1))
+
+/*For each V(N,K) supported, we will access element U(min(N,K+1),max(N,K+1)).
+  Thus, the number of entries in row I is the larger of the maximum number of
+   pulses we will ever allocate for a given N=I (K=128, or however many fit in
+   32 bits, whichever is smaller), plus one, and the maximum N for which
+   K=I-1 pulses fit in 32 bits.
+  The largest band size in an Opus Custom mode is 208.
+  Otherwise, we can limit things to the set of N which can be achieved by
+   splitting a band from a standard Opus mode: 176, 144, 96, 88, 72, 64, 48,
+   44, 36, 32, 24, 22, 18, 16, 8, 4, 2).*/
+#if defined(CUSTOM_MODES)
+static const opus_uint32 CELT_PVQ_U_DATA[1488]={
+#else
+static const opus_uint32 CELT_PVQ_U_DATA[1272]={
+#endif
+  /*N=0, K=0...176:*/
+  1, 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,
+  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, 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, 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, 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, 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, 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, 0,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  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, 0,
+  0, 0, 0, 0, 0, 0,
+#endif
+  /*N=1, K=1...176:*/
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+  1, 1, 1, 1, 1, 1,
+#endif
+  /*N=2, K=2...176:*/
+  3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41,
+  43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79,
+  81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113,
+  115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143,
+  145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173,
+  175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203,
+  205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233,
+  235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257, 259, 261, 263,
+  265, 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 287, 289, 291, 293,
+  295, 297, 299, 301, 303, 305, 307, 309, 311, 313, 315, 317, 319, 321, 323,
+  325, 327, 329, 331, 333, 335, 337, 339, 341, 343, 345, 347, 349, 351,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 377, 379, 381,
+  383, 385, 387, 389, 391, 393, 395, 397, 399, 401, 403, 405, 407, 409, 411,
+  413, 415,
+#endif
+  /*N=3, K=3...176:*/
+  13, 25, 41, 61, 85, 113, 145, 181, 221, 265, 313, 365, 421, 481, 545, 613,
+  685, 761, 841, 925, 1013, 1105, 1201, 1301, 1405, 1513, 1625, 1741, 1861,
+  1985, 2113, 2245, 2381, 2521, 2665, 2813, 2965, 3121, 3281, 3445, 3613, 3785,
+  3961, 4141, 4325, 4513, 4705, 4901, 5101, 5305, 5513, 5725, 5941, 6161, 6385,
+  6613, 6845, 7081, 7321, 7565, 7813, 8065, 8321, 8581, 8845, 9113, 9385, 9661,
+  9941, 10225, 10513, 10805, 11101, 11401, 11705, 12013, 12325, 12641, 12961,
+  13285, 13613, 13945, 14281, 14621, 14965, 15313, 15665, 16021, 16381, 16745,
+  17113, 17485, 17861, 18241, 18625, 19013, 19405, 19801, 20201, 20605, 21013,
+  21425, 21841, 22261, 22685, 23113, 23545, 23981, 24421, 24865, 25313, 25765,
+  26221, 26681, 27145, 27613, 28085, 28561, 29041, 29525, 30013, 30505, 31001,
+  31501, 32005, 32513, 33025, 33541, 34061, 34585, 35113, 35645, 36181, 36721,
+  37265, 37813, 38365, 38921, 39481, 40045, 40613, 41185, 41761, 42341, 42925,
+  43513, 44105, 44701, 45301, 45905, 46513, 47125, 47741, 48361, 48985, 49613,
+  50245, 50881, 51521, 52165, 52813, 53465, 54121, 54781, 55445, 56113, 56785,
+  57461, 58141, 58825, 59513, 60205, 60901, 61601,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  62305, 63013, 63725, 64441, 65161, 65885, 66613, 67345, 68081, 68821, 69565,
+  70313, 71065, 71821, 72581, 73345, 74113, 74885, 75661, 76441, 77225, 78013,
+  78805, 79601, 80401, 81205, 82013, 82825, 83641, 84461, 85285, 86113,
+#endif
+  /*N=4, K=4...176:*/
+  63, 129, 231, 377, 575, 833, 1159, 1561, 2047, 2625, 3303, 4089, 4991, 6017,
+  7175, 8473, 9919, 11521, 13287, 15225, 17343, 19649, 22151, 24857, 27775,
+  30913, 34279, 37881, 41727, 45825, 50183, 54809, 59711, 64897, 70375, 76153,
+  82239, 88641, 95367, 102425, 109823, 117569, 125671, 134137, 142975, 152193,
+  161799, 171801, 182207, 193025, 204263, 215929, 228031, 240577, 253575,
+  267033, 280959, 295361, 310247, 325625, 341503, 357889, 374791, 392217,
+  410175, 428673, 447719, 467321, 487487, 508225, 529543, 551449, 573951,
+  597057, 620775, 645113, 670079, 695681, 721927, 748825, 776383, 804609,
+  833511, 863097, 893375, 924353, 956039, 988441, 1021567, 1055425, 1090023,
+  1125369, 1161471, 1198337, 1235975, 1274393, 1313599, 1353601, 1394407,
+  1436025, 1478463, 1521729, 1565831, 1610777, 1656575, 1703233, 1750759,
+  1799161, 1848447, 1898625, 1949703, 2001689, 2054591, 2108417, 2163175,
+  2218873, 2275519, 2333121, 2391687, 2451225, 2511743, 2573249, 2635751,
+  2699257, 2763775, 2829313, 2895879, 2963481, 3032127, 3101825, 3172583,
+  3244409, 3317311, 3391297, 3466375, 3542553, 3619839, 3698241, 3777767,
+  3858425, 3940223, 4023169, 4107271, 4192537, 4278975, 4366593, 4455399,
+  4545401, 4636607, 4729025, 4822663, 4917529, 5013631, 5110977, 5209575,
+  5309433, 5410559, 5512961, 5616647, 5721625, 5827903, 5935489, 6044391,
+  6154617, 6266175, 6379073, 6493319, 6608921, 6725887, 6844225, 6963943,
+  7085049, 7207551,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  7331457, 7456775, 7583513, 7711679, 7841281, 7972327, 8104825, 8238783,
+  8374209, 8511111, 8649497, 8789375, 8930753, 9073639, 9218041, 9363967,
+  9511425, 9660423, 9810969, 9963071, 10116737, 10271975, 10428793, 10587199,
+  10747201, 10908807, 11072025, 11236863, 11403329, 11571431, 11741177,
+  11912575,
+#endif
+  /*N=5, K=5...176:*/
+  321, 681, 1289, 2241, 3649, 5641, 8361, 11969, 16641, 22569, 29961, 39041,
+  50049, 63241, 78889, 97281, 118721, 143529, 172041, 204609, 241601, 283401,
+  330409, 383041, 441729, 506921, 579081, 658689, 746241, 842249, 947241,
+  1061761, 1186369, 1321641, 1468169, 1626561, 1797441, 1981449, 2179241,
+  2391489, 2618881, 2862121, 3121929, 3399041, 3694209, 4008201, 4341801,
+  4695809, 5071041, 5468329, 5888521, 6332481, 6801089, 7295241, 7815849,
+  8363841, 8940161, 9545769, 10181641, 10848769, 11548161, 12280841, 13047849,
+  13850241, 14689089, 15565481, 16480521, 17435329, 18431041, 19468809,
+  20549801, 21675201, 22846209, 24064041, 25329929, 26645121, 28010881,
+  29428489, 30899241, 32424449, 34005441, 35643561, 37340169, 39096641,
+  40914369, 42794761, 44739241, 46749249, 48826241, 50971689, 53187081,
+  55473921, 57833729, 60268041, 62778409, 65366401, 68033601, 70781609,
+  73612041, 76526529, 79526721, 82614281, 85790889, 89058241, 92418049,
+  95872041, 99421961, 103069569, 106816641, 110664969, 114616361, 118672641,
+  122835649, 127107241, 131489289, 135983681, 140592321, 145317129, 150160041,
+  155123009, 160208001, 165417001, 170752009, 176215041, 181808129, 187533321,
+  193392681, 199388289, 205522241, 211796649, 218213641, 224775361, 231483969,
+  238341641, 245350569, 252512961, 259831041, 267307049, 274943241, 282741889,
+  290705281, 298835721, 307135529, 315607041, 324252609, 333074601, 342075401,
+  351257409, 360623041, 370174729, 379914921, 389846081, 399970689, 410291241,
+  420810249, 431530241, 442453761, 453583369, 464921641, 476471169, 488234561,
+  500214441, 512413449, 524834241, 537479489, 550351881, 563454121, 576788929,
+  590359041, 604167209, 618216201, 632508801,
+#if defined(CUSTOM_MODES)
+  /*...208:*/
+  647047809, 661836041, 676876329, 692171521, 707724481, 723538089, 739615241,
+  755958849, 772571841, 789457161, 806617769, 824056641, 841776769, 859781161,
+  878072841, 896654849, 915530241, 934702089, 954173481, 973947521, 994027329,
+  1014416041, 1035116809, 1056132801, 1077467201, 1099123209, 1121104041,
+  1143412929, 1166053121, 1189027881, 1212340489, 1235994241,
+#endif
+  /*N=6, K=6...96:*/
+  1683, 3653, 7183, 13073, 22363, 36365, 56695, 85305, 124515, 177045, 246047,
+  335137, 448427, 590557, 766727, 982729, 1244979, 1560549, 1937199, 2383409,
+  2908411, 3522221, 4235671, 5060441, 6009091, 7095093, 8332863, 9737793,
+  11326283, 13115773, 15124775, 17372905, 19880915, 22670725, 25765455,
+  29189457, 32968347, 37129037, 41699767, 46710137, 52191139, 58175189,
+  64696159, 71789409, 79491819, 87841821, 96879431, 106646281, 117185651,
+  128542501, 140763503, 153897073, 167993403, 183104493, 199284183, 216588185,
+  235074115, 254801525, 275831935, 298228865, 322057867, 347386557, 374284647,
+  402823977, 433078547, 465124549, 499040399, 534906769, 572806619, 612825229,
+  655050231, 699571641, 746481891, 795875861, 847850911, 902506913, 959946283,
+  1020274013, 1083597703, 1150027593, 1219676595, 1292660325, 1369097135,
+  1449108145, 1532817275, 1620351277, 1711839767, 1807415257, 1907213187,
+  2011371957, 2120032959,
+#if defined(CUSTOM_MODES)
+  /*...109:*/
+  2233340609U, 2351442379U, 2474488829U, 2602633639U, 2736033641U, 2874848851U,
+  3019242501U, 3169381071U, 3325434321U, 3487575323U, 3655980493U, 3830829623U,
+  4012305913U,
+#endif
+  /*N=7, K=7...54*/
+  8989, 19825, 40081, 75517, 134245, 227305, 369305, 579125, 880685, 1303777,
+  1884961, 2668525, 3707509, 5064793, 6814249, 9041957, 11847485, 15345233,
+  19665841, 24957661, 31388293, 39146185, 48442297, 59511829, 72616013,
+  88043969, 106114625, 127178701, 151620757, 179861305, 212358985, 249612805,
+  292164445, 340600625, 395555537, 457713341, 527810725, 606639529, 695049433,
+  793950709, 904317037, 1027188385, 1163673953, 1314955181, 1482288821,
+  1667010073, 1870535785, 2094367717,
+#if defined(CUSTOM_MODES)
+  /*...60:*/
+  2340095869U, 2609401873U, 2904062449U, 3225952925U, 3577050821U, 3959439497U,
+#endif
+  /*N=8, K=8...37*/
+  48639, 108545, 224143, 433905, 795455, 1392065, 2340495, 3800305, 5984767,
+  9173505, 13726991, 20103025, 28875327, 40754369, 56610575, 77500017,
+  104692735, 139703809, 184327311, 240673265, 311207743, 398796225, 506750351,
+  638878193, 799538175, 993696769, 1226990095, 1505789553, 1837271615,
+  2229491905U,
+#if defined(CUSTOM_MODES)
+  /*...40:*/
+  2691463695U, 3233240945U, 3866006015U,
+#endif
+  /*N=9, K=9...28:*/
+  265729, 598417, 1256465, 2485825, 4673345, 8405905, 14546705, 24331777,
+  39490049, 62390545, 96220561, 145198913, 214828609, 312193553, 446304145,
+  628496897, 872893441, 1196924561, 1621925137, 2173806145U,
+#if defined(CUSTOM_MODES)
+  /*...29:*/
+  2883810113U,
+#endif
+  /*N=10, K=10...24:*/
+  1462563, 3317445, 7059735, 14218905, 27298155, 50250765, 89129247, 152951073,
+  254831667, 413442773, 654862247, 1014889769, 1541911931, 2300409629U,
+  3375210671U,
+  /*N=11, K=11...19:*/
+  8097453, 18474633, 39753273, 81270333, 158819253, 298199265, 540279585,
+  948062325, 1616336765,
+#if defined(CUSTOM_MODES)
+  /*...20:*/
+  2684641785U,
+#endif
+  /*N=12, K=12...18:*/
+  45046719, 103274625, 224298231, 464387817, 921406335, 1759885185,
+  3248227095U,
+  /*N=13, K=13...16:*/
+  251595969, 579168825, 1267854873, 2653649025U,
+  /*N=14, K=14:*/
+  1409933619
+};
+
+#if defined(CUSTOM_MODES)
+static const opus_uint32 *const CELT_PVQ_U_ROW[15]={
+  CELT_PVQ_U_DATA+   0,CELT_PVQ_U_DATA+ 208,CELT_PVQ_U_DATA+ 415,
+  CELT_PVQ_U_DATA+ 621,CELT_PVQ_U_DATA+ 826,CELT_PVQ_U_DATA+1030,
+  CELT_PVQ_U_DATA+1233,CELT_PVQ_U_DATA+1336,CELT_PVQ_U_DATA+1389,
+  CELT_PVQ_U_DATA+1421,CELT_PVQ_U_DATA+1441,CELT_PVQ_U_DATA+1455,
+  CELT_PVQ_U_DATA+1464,CELT_PVQ_U_DATA+1470,CELT_PVQ_U_DATA+1473
+};
+#else
+static const opus_uint32 *const CELT_PVQ_U_ROW[15]={
+  CELT_PVQ_U_DATA+   0,CELT_PVQ_U_DATA+ 176,CELT_PVQ_U_DATA+ 351,
+  CELT_PVQ_U_DATA+ 525,CELT_PVQ_U_DATA+ 698,CELT_PVQ_U_DATA+ 870,
+  CELT_PVQ_U_DATA+1041,CELT_PVQ_U_DATA+1131,CELT_PVQ_U_DATA+1178,
+  CELT_PVQ_U_DATA+1207,CELT_PVQ_U_DATA+1226,CELT_PVQ_U_DATA+1240,
+  CELT_PVQ_U_DATA+1248,CELT_PVQ_U_DATA+1254,CELT_PVQ_U_DATA+1257
+};
+#endif
+
+#if defined(CUSTOM_MODES)
+void get_required_bits(opus_int16 *_bits,int _n,int _maxk,int _frac){
+  int k;
+  /*_maxk==0 => there's nothing to do.*/
+  celt_assert(_maxk>0);
+  _bits[0]=0;
+  for(k=1;k<=_maxk;k++)_bits[k]=log2_frac(CELT_PVQ_V(_n,k),_frac);
+}
+#endif
+
+static opus_uint32 icwrs(int _n,const int *_y){
+  opus_uint32 i;
+  int         j;
+  int         k;
+  celt_assert(_n>=2);
+  j=_n-1;
+  i=_y[j]<0;
+  k=abs(_y[j]);
+  do{
+    j--;
+    i+=CELT_PVQ_U(_n-j,k);
+    k+=abs(_y[j]);
+    if(_y[j]<0)i+=CELT_PVQ_U(_n-j,k+1);
+  }
+  while(j>0);
+  return i;
+}
+
+void encode_pulses(const int *_y,int _n,int _k,ec_enc *_enc){
+  celt_assert(_k>0);
+  ec_enc_uint(_enc,icwrs(_n,_y),CELT_PVQ_V(_n,_k));
+}
+
+static opus_val32 cwrsi(int _n,int _k,opus_uint32 _i,int *_y){
+  opus_uint32 p;
+  int         s;
+  int         k0;
+  opus_int16  val;
+  opus_val32  yy=0;
+  celt_assert(_k>0);
+  celt_assert(_n>1);
+  while(_n>2){
+    opus_uint32 q;
+    /*Lots of pulses case:*/
+    if(_k>=_n){
+      const opus_uint32 *row;
+      row=CELT_PVQ_U_ROW[_n];
+      /*Are the pulses in this dimension negative?*/
+      p=row[_k+1];
+      s=-(_i>=p);
+      _i-=p&s;
+      /*Count how many pulses were placed in this dimension.*/
+      k0=_k;
+      q=row[_n];
+      if(q>_i){
+        celt_assert(p>q);
+        _k=_n;
+        do p=CELT_PVQ_U_ROW[--_k][_n];
+        while(p>_i);
+      }
+      else for(p=row[_k];p>_i;p=row[_k])_k--;
+      _i-=p;
+      val=(k0-_k+s)^s;
+      *_y++=val;
+      yy=MAC16_16(yy,val,val);
+    }
+    /*Lots of dimensions case:*/
+    else{
+      /*Are there any pulses in this dimension at all?*/
+      p=CELT_PVQ_U_ROW[_k][_n];
+      q=CELT_PVQ_U_ROW[_k+1][_n];
+      if(p<=_i&&_i<q){
+        _i-=p;
+        *_y++=0;
+      }
+      else{
+        /*Are the pulses in this dimension negative?*/
+        s=-(_i>=q);
+        _i-=q&s;
+        /*Count how many pulses were placed in this dimension.*/
+        k0=_k;
+        do p=CELT_PVQ_U_ROW[--_k][_n];
+        while(p>_i);
+        _i-=p;
+        val=(k0-_k+s)^s;
+        *_y++=val;
+        yy=MAC16_16(yy,val,val);
+      }
+    }
+    _n--;
+  }
+  /*_n==2*/
+  p=2*_k+1;
+  s=-(_i>=p);
+  _i-=p&s;
+  k0=_k;
+  _k=(_i+1)>>1;
+  if(_k)_i-=2*_k-1;
+  val=(k0-_k+s)^s;
+  *_y++=val;
+  yy=MAC16_16(yy,val,val);
+  /*_n==1*/
+  s=-(int)_i;
+  val=(_k+s)^s;
+  *_y=val;
+  yy=MAC16_16(yy,val,val);
+  return yy;
+}
+
+opus_val32 decode_pulses(int *_y,int _n,int _k,ec_dec *_dec){
+  return cwrsi(_n,_k,ec_dec_uint(_dec,CELT_PVQ_V(_n,_k)),_y);
+}
+
+#else /* SMALL_FOOTPRINT */
+
+/*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 OPUS_INLINE void unext(opus_uint32 *_ui,unsigned _len,opus_uint32 _ui0){
+  opus_uint32 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 OPUS_INLINE void uprev(opus_uint32 *_ui,unsigned _n,opus_uint32 _ui0){
+  opus_uint32 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 opus_uint32 ncwrs_urow(unsigned _n,unsigned _k,opus_uint32 *_u){
+  opus_uint32 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==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);
+  return _u[_k]+_u[_k+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 opus_val32 cwrsi(int _n,int _k,opus_uint32 _i,int *_y,opus_uint32 *_u){
+  int j;
+  opus_int16 val;
+  opus_val32 yy=0;
+  celt_assert(_n>0);
+  j=0;
+  do{
+    opus_uint32 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;
+    val=(yj+s)^s;
+    _y[j]=val;
+    yy=MAC16_16(yy,val,val);
+    uprev(_u,_k+2,0);
+  }
+  while(++j<_n);
+  return yy;
+}
+
+/*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 OPUS_INLINE opus_uint32 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 _n with associated sign bits.
+  _y:  The vector of pulses, whose sum of absolute values must be _k.
+  _nc: Returns V(_n,_k).*/
+static OPUS_INLINE opus_uint32 icwrs(int _n,int _k,opus_uint32 *_nc,const int *_y,
+ opus_uint32 *_u){
+  opus_uint32 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;
+}
+
+#ifdef CUSTOM_MODES
+void get_required_bits(opus_int16 *_bits,int _n,int _maxk,int _frac){
+  int k;
+  /*_maxk==0 => there's nothing to do.*/
+  celt_assert(_maxk>0);
+  _bits[0]=0;
+  if (_n==1)
+  {
+    for (k=1;k<=_maxk;k++)
+      _bits[k] = 1<<_frac;
+  }
+  else {
+    VARDECL(opus_uint32,u);
+    SAVE_STACK;
+    ALLOC(u,_maxk+2U,opus_uint32);
+    ncwrs_urow(_n,_maxk,u);
+    for(k=1;k<=_maxk;k++)
+      _bits[k]=log2_frac(u[k]+u[k+1],_frac);
+    RESTORE_STACK;
+  }
+}
+#endif /* CUSTOM_MODES */
+
+void encode_pulses(const int *_y,int _n,int _k,ec_enc *_enc){
+  opus_uint32 i;
+  VARDECL(opus_uint32,u);
+  opus_uint32 nc;
+  SAVE_STACK;
+  celt_assert(_k>0);
+  ALLOC(u,_k+2U,opus_uint32);
+  i=icwrs(_n,_k,&nc,_y,u);
+  ec_enc_uint(_enc,i,nc);
+  RESTORE_STACK;
+}
+
+opus_val32 decode_pulses(int *_y,int _n,int _k,ec_dec *_dec){
+  VARDECL(opus_uint32,u);
+  int ret;
+  SAVE_STACK;
+  celt_assert(_k>0);
+  ALLOC(u,_k+2U,opus_uint32);
+  ret = cwrsi(_n,_k,ec_dec_uint(_dec,ncwrs_urow(_n,_k,u)),_y,u);
+  RESTORE_STACK;
+  return ret;
+}
+
+#endif /* SMALL_FOOTPRINT */
diff --git a/opus/celt/cwrs.h b/opus/celt/cwrs.h
new file mode 100644 (file)
index 0000000..7cd4717
--- /dev/null
@@ -0,0 +1,48 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2007-2009 Timothy B. Terriberry
+   Written by Timothy B. Terriberry and 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.
+
+   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 CWRS_H
+#define CWRS_H
+
+#include "arch.h"
+#include "stack_alloc.h"
+#include "entenc.h"
+#include "entdec.h"
+
+#ifdef CUSTOM_MODES
+int log2_frac(opus_uint32 val, int frac);
+#endif
+
+void get_required_bits(opus_int16 *bits, int N, int K, int frac);
+
+void encode_pulses(const int *_y, int N, int K, ec_enc *enc);
+
+opus_val32 decode_pulses(int *_y, int N, int K, ec_dec *dec);
+
+#endif /* CWRS_H */
diff --git a/opus/celt/ecintrin.h b/opus/celt/ecintrin.h
new file mode 100644 (file)
index 0000000..2263cff
--- /dev/null
@@ -0,0 +1,87 @@
+/* Copyright (c) 2003-2008 Timothy B. Terriberry
+   Copyright (c) 2008 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+/*Some common macros for potential platform-specific optimization.*/
+#include "opus_types.h"
+#include <math.h>
+#include <limits.h>
+#include "arch.h"
+#if !defined(_ecintrin_H)
+# define _ecintrin_H (1)
+
+/*Some specific platforms may have optimized intrinsic or OPUS_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.*/
+
+/*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_MINI(_a,_b)      ((_a)+(((_b)-(_a))&-((_b)<(_a))))
+
+/*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.*/
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+# include <intrin.h>
+/*In _DEBUG mode this is not an intrinsic by default.*/
+# pragma intrinsic(_BitScanReverse)
+
+static __inline int ec_bsr(unsigned long _x){
+  unsigned long ret;
+  _BitScanReverse(&ret,_x);
+  return (int)ret;
+}
+# define EC_CLZ0    (1)
+# define EC_CLZ(_x) (-ec_bsr(_x))
+#elif defined(ENABLE_TI_DSPLIB)
+# include "dsplib.h"
+# define EC_CLZ0    (31)
+# define EC_CLZ(_x) (_lnorm(_x))
+#elif __GNUC_PREREQ(3,4)
+# if INT_MAX>=2147483647
+#  define EC_CLZ0    ((int)sizeof(unsigned)*CHAR_BIT)
+#  define EC_CLZ(_x) (__builtin_clz(_x))
+# elif LONG_MAX>=2147483647L
+#  define EC_CLZ0    ((int)sizeof(unsigned long)*CHAR_BIT)
+#  define EC_CLZ(_x) (__builtin_clzl(_x))
+# 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))
+#else
+int ec_ilog(opus_uint32 _v);
+# define EC_ILOG(_x) (ec_ilog(_x))
+#endif
+#endif
diff --git a/opus/celt/entcode.c b/opus/celt/entcode.c
new file mode 100644 (file)
index 0000000..70f3201
--- /dev/null
@@ -0,0 +1,153 @@
+/* Copyright (c) 2001-2011 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "entcode.h"
+#include "arch.h"
+
+#if !defined(EC_CLZ)
+/*This is a fallback for systems where we don't know how to access
+   a BSR or CLZ instruction (see ecintrin.h).
+  If you are optimizing Opus on a new platform and it has a native CLZ or
+   BZR (e.g. cell, MIPS, x86, etc) then making it available to Opus will be
+   an easy performance win.*/
+int ec_ilog(opus_uint32 _v){
+  /*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
+
+#if 1
+/* This is a faster version of ec_tell_frac() that takes advantage
+   of the low (1/8 bit) resolution to use just a linear function
+   followed by a lookup to determine the exact transition thresholds. */
+opus_uint32 ec_tell_frac(ec_ctx *_this){
+  static const unsigned correction[8] =
+    {35733, 38967, 42495, 46340,
+     50535, 55109, 60097, 65535};
+  opus_uint32 nbits;
+  opus_uint32 r;
+  int         l;
+  unsigned    b;
+  nbits=_this->nbits_total<<BITRES;
+  l=EC_ILOG(_this->rng);
+  r=_this->rng>>(l-16);
+  b = (r>>12)-8;
+  b += r>correction[b];
+  l = (l<<3)+b;
+  return nbits-l;
+}
+#else
+opus_uint32 ec_tell_frac(ec_ctx *_this){
+  opus_uint32 nbits;
+  opus_uint32 r;
+  int         l;
+  int         i;
+  /*To handle the non-integral number of bits still left in the encoder/decoder
+     state, we compute the worst-case number of bits of val that must be
+     encoded to ensure that the value is inside the range for any possible
+     subsequent bits.
+    The computation here is independent of val itself (the decoder does not
+     even track that value), even though the real number of bits used after
+     ec_enc_done() may be 1 smaller if rng is a power of two and the
+     corresponding trailing bits of val are all zeros.
+    If we did try to track that special case, then coding a value with a
+     probability of 1/(1<<n) might sometimes appear to use more than n bits.
+    This may help explain the surprising result that a newly initialized
+     encoder or decoder claims to have used 1 bit.*/
+  nbits=_this->nbits_total<<BITRES;
+  l=EC_ILOG(_this->rng);
+  r=_this->rng>>(l-16);
+  for(i=BITRES;i-->0;){
+    int b;
+    r=r*r>>15;
+    b=(int)(r>>16);
+    l=l<<1|b;
+    r>>=b;
+  }
+  return nbits-l;
+}
+#endif
+
+#ifdef USE_SMALL_DIV_TABLE
+/* Result of 2^32/(2*i+1), except for i=0. */
+const opus_uint32 SMALL_DIV_TABLE[129] = {
+   0xFFFFFFFF, 0x55555555, 0x33333333, 0x24924924,
+   0x1C71C71C, 0x1745D174, 0x13B13B13, 0x11111111,
+   0x0F0F0F0F, 0x0D79435E, 0x0C30C30C, 0x0B21642C,
+   0x0A3D70A3, 0x097B425E, 0x08D3DCB0, 0x08421084,
+   0x07C1F07C, 0x07507507, 0x06EB3E45, 0x06906906,
+   0x063E7063, 0x05F417D0, 0x05B05B05, 0x0572620A,
+   0x05397829, 0x05050505, 0x04D4873E, 0x04A7904A,
+   0x047DC11F, 0x0456C797, 0x04325C53, 0x04104104,
+   0x03F03F03, 0x03D22635, 0x03B5CC0E, 0x039B0AD1,
+   0x0381C0E0, 0x0369D036, 0x03531DEC, 0x033D91D2,
+   0x0329161F, 0x03159721, 0x03030303, 0x02F14990,
+   0x02E05C0B, 0x02D02D02, 0x02C0B02C, 0x02B1DA46,
+   0x02A3A0FD, 0x0295FAD4, 0x0288DF0C, 0x027C4597,
+   0x02702702, 0x02647C69, 0x02593F69, 0x024E6A17,
+   0x0243F6F0, 0x0239E0D5, 0x02302302, 0x0226B902,
+   0x021D9EAD, 0x0214D021, 0x020C49BA, 0x02040810,
+   0x01FC07F0, 0x01F44659, 0x01ECC07B, 0x01E573AC,
+   0x01DE5D6E, 0x01D77B65, 0x01D0CB58, 0x01CA4B30,
+   0x01C3F8F0, 0x01BDD2B8, 0x01B7D6C3, 0x01B20364,
+   0x01AC5701, 0x01A6D01A, 0x01A16D3F, 0x019C2D14,
+   0x01970E4F, 0x01920FB4, 0x018D3018, 0x01886E5F,
+   0x0183C977, 0x017F405F, 0x017AD220, 0x01767DCE,
+   0x01724287, 0x016E1F76, 0x016A13CD, 0x01661EC6,
+   0x01623FA7, 0x015E75BB, 0x015AC056, 0x01571ED3,
+   0x01539094, 0x01501501, 0x014CAB88, 0x0149539E,
+   0x01460CBC, 0x0142D662, 0x013FB013, 0x013C995A,
+   0x013991C2, 0x013698DF, 0x0133AE45, 0x0130D190,
+   0x012E025C, 0x012B404A, 0x01288B01, 0x0125E227,
+   0x01234567, 0x0120B470, 0x011E2EF3, 0x011BB4A4,
+   0x01194538, 0x0116E068, 0x011485F0, 0x0112358E,
+   0x010FEF01, 0x010DB20A, 0x010B7E6E, 0x010953F3,
+   0x01073260, 0x0105197F, 0x0103091B, 0x01010101
+};
+#endif
diff --git a/opus/celt/entcode.h b/opus/celt/entcode.h
new file mode 100644 (file)
index 0000000..13d6c84
--- /dev/null
@@ -0,0 +1,152 @@
+/* Copyright (c) 2001-2011 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#include "opus_types.h"
+#include "opus_defines.h"
+
+#if !defined(_entcode_H)
+# define _entcode_H (1)
+# include <limits.h>
+# include <stddef.h>
+# include "ecintrin.h"
+
+extern const opus_uint32 SMALL_DIV_TABLE[129];
+
+#ifdef OPUS_ARM_ASM
+#define USE_SMALL_DIV_TABLE
+#endif
+
+/*OPT: ec_window must be at least 32 bits, but if you have fast arithmetic on a
+   larger type, you can speed up the decoder by using it here.*/
+typedef opus_uint32           ec_window;
+typedef struct ec_ctx         ec_ctx;
+typedef struct ec_ctx         ec_enc;
+typedef struct ec_ctx         ec_dec;
+
+# define EC_WINDOW_SIZE ((int)sizeof(ec_window)*CHAR_BIT)
+
+/*The number of bits to use for the range-coded part of unsigned integers.*/
+# define EC_UINT_BITS   (8)
+
+/*The resolution of fractional-precision bit usage measurements, i.e.,
+   3 => 1/8th bits.*/
+# define BITRES 3
+
+/*The entropy encoder/decoder context.
+  We use the same structure for both, so that common functions like ec_tell()
+   can be used on either one.*/
+struct ec_ctx{
+   /*Buffered input/output.*/
+   unsigned char *buf;
+   /*The size of the buffer.*/
+   opus_uint32    storage;
+   /*The offset at which the last byte containing raw bits was read/written.*/
+   opus_uint32    end_offs;
+   /*Bits that will be read from/written at the end.*/
+   ec_window      end_window;
+   /*Number of valid bits in end_window.*/
+   int            nend_bits;
+   /*The total number of whole bits read/written.
+     This does not include partial bits currently in the range coder.*/
+   int            nbits_total;
+   /*The offset at which the next range coder byte will be read/written.*/
+   opus_uint32    offs;
+   /*The number of values in the current range.*/
+   opus_uint32    rng;
+   /*In the decoder: the difference between the top of the current range and
+      the input value, minus one.
+     In the encoder: the low end of the current range.*/
+   opus_uint32    val;
+   /*In the decoder: the saved normalization factor from ec_decode().
+     In the encoder: the number of oustanding carry propagating symbols.*/
+   opus_uint32    ext;
+   /*A buffered input/output symbol, awaiting carry propagation.*/
+   int            rem;
+   /*Nonzero if an error occurred.*/
+   int            error;
+};
+
+static OPUS_INLINE opus_uint32 ec_range_bytes(ec_ctx *_this){
+  return _this->offs;
+}
+
+static OPUS_INLINE unsigned char *ec_get_buffer(ec_ctx *_this){
+  return _this->buf;
+}
+
+static OPUS_INLINE int ec_get_error(ec_ctx *_this){
+  return _this->error;
+}
+
+/*Returns the number of bits "used" by the encoded or decoded symbols so far.
+  This same number can be computed in either the encoder or the decoder, and is
+   suitable for making coding decisions.
+  Return: The number of bits.
+          This will always be slightly larger than the exact value (e.g., all
+           rounding error is in the positive direction).*/
+static OPUS_INLINE int ec_tell(ec_ctx *_this){
+  return _this->nbits_total-EC_ILOG(_this->rng);
+}
+
+/*Returns the number of bits "used" by the encoded or decoded symbols so far.
+  This same number can be computed in either the encoder or the decoder, and is
+   suitable for making coding decisions.
+  Return: The number of bits scaled by 2**BITRES.
+          This will always be slightly larger than the exact value (e.g., all
+           rounding error is in the positive direction).*/
+opus_uint32 ec_tell_frac(ec_ctx *_this);
+
+/* Tested exhaustively for all n and for 1<=d<=256 */
+static OPUS_INLINE opus_uint32 celt_udiv(opus_uint32 n, opus_uint32 d) {
+   celt_assert(d>0);
+#ifdef USE_SMALL_DIV_TABLE
+   if (d>256)
+      return n/d;
+   else {
+      opus_uint32 t, q;
+      t = EC_ILOG(d&-d);
+      q = (opus_uint64)SMALL_DIV_TABLE[d>>t]*(n>>(t-1))>>32;
+      return q+(n-q*d >= d);
+   }
+#else
+   return n/d;
+#endif
+}
+
+static OPUS_INLINE opus_int32 celt_sudiv(opus_int32 n, opus_int32 d) {
+   celt_assert(d>0);
+#ifdef USE_SMALL_DIV_TABLE
+   if (n<0)
+      return -(opus_int32)celt_udiv(-n, d);
+   else
+      return celt_udiv(n, d);
+#else
+   return n/d;
+#endif
+}
+
+#endif
diff --git a/opus/celt/entdec.c b/opus/celt/entdec.c
new file mode 100644 (file)
index 0000000..0b3433e
--- /dev/null
@@ -0,0 +1,245 @@
+/* Copyright (c) 2001-2011 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stddef.h>
+#include "os_support.h"
+#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.
+
+  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.
+
+  End of stream is handled by writing out the smallest number of bits that
+   ensures that the stream will be correctly decoded regardless of the value of
+   any subsequent bits.
+  ec_tell() can be used to determine how many bits were needed to decode
+   all the symbols thus far; other data can be packed in the remaining bits of
+   the input buffer.
+  @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/ee398a/handouts/papers/Moffat98ArithmCoding.pdf"
+  }*/
+
+static int ec_read_byte(ec_dec *_this){
+  return _this->offs<_this->storage?_this->buf[_this->offs++]:0;
+}
+
+static int ec_read_byte_from_end(ec_dec *_this){
+  return _this->end_offs<_this->storage?
+   _this->buf[_this->storage-++(_this->end_offs)]:0;
+}
+
+/*Normalizes the contents of val and rng so that rng lies entirely in the
+   high-order symbol.*/
+static 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->nbits_total+=EC_SYM_BITS;
+    _this->rng<<=EC_SYM_BITS;
+    /*Use up the remaining bits from our last symbol.*/
+    sym=_this->rem;
+    /*Read the next value from the input.*/
+    _this->rem=ec_read_byte(_this);
+    /*Take the rest of the bits we need from this new symbol.*/
+    sym=(sym<<EC_SYM_BITS|_this->rem)>>(EC_SYM_BITS-EC_CODE_EXTRA);
+    /*And subtract them from val, capped to be less than EC_CODE_TOP.*/
+    _this->val=((_this->val<<EC_SYM_BITS)+(EC_SYM_MAX&~sym))&(EC_CODE_TOP-1);
+  }
+}
+
+void ec_dec_init(ec_dec *_this,unsigned char *_buf,opus_uint32 _storage){
+  _this->buf=_buf;
+  _this->storage=_storage;
+  _this->end_offs=0;
+  _this->end_window=0;
+  _this->nend_bits=0;
+  /*This is the offset from which ec_tell() will subtract partial bits.
+    The final value after the ec_dec_normalize() call will be the same as in
+     the encoder, but we have to compensate for the bits that are added there.*/
+  _this->nbits_total=EC_CODE_BITS+1
+   -((EC_CODE_BITS-EC_CODE_EXTRA)/EC_SYM_BITS)*EC_SYM_BITS;
+  _this->offs=0;
+  _this->rng=1U<<EC_CODE_EXTRA;
+  _this->rem=ec_read_byte(_this);
+  _this->val=_this->rng-1-(_this->rem>>(EC_SYM_BITS-EC_CODE_EXTRA));
+  _this->error=0;
+  /*Normalize the interval.*/
+  ec_dec_normalize(_this);
+}
+
+unsigned ec_decode(ec_dec *_this,unsigned _ft){
+  unsigned s;
+  _this->ext=celt_udiv(_this->rng,_ft);
+  s=(unsigned)(_this->val/_this->ext);
+  return _ft-EC_MINI(s+1,_ft);
+}
+
+unsigned ec_decode_bin(ec_dec *_this,unsigned _bits){
+   unsigned s;
+   _this->ext=_this->rng>>_bits;
+   s=(unsigned)(_this->val/_this->ext);
+   return (1U<<_bits)-EC_MINI(s+1U,1U<<_bits);
+}
+
+void ec_dec_update(ec_dec *_this,unsigned _fl,unsigned _fh,unsigned _ft){
+  opus_uint32 s;
+  s=IMUL32(_this->ext,_ft-_fh);
+  _this->val-=s;
+  _this->rng=_fl>0?IMUL32(_this->ext,_fh-_fl):_this->rng-s;
+  ec_dec_normalize(_this);
+}
+
+/*The probability of having a "one" is 1/(1<<_logp).*/
+int ec_dec_bit_logp(ec_dec *_this,unsigned _logp){
+  opus_uint32 r;
+  opus_uint32 d;
+  opus_uint32 s;
+  int         ret;
+  r=_this->rng;
+  d=_this->val;
+  s=r>>_logp;
+  ret=d<s;
+  if(!ret)_this->val=d-s;
+  _this->rng=ret?s:r-s;
+  ec_dec_normalize(_this);
+  return ret;
+}
+
+int ec_dec_icdf(ec_dec *_this,const unsigned char *_icdf,unsigned _ftb){
+  opus_uint32 r;
+  opus_uint32 d;
+  opus_uint32 s;
+  opus_uint32 t;
+  int         ret;
+  s=_this->rng;
+  d=_this->val;
+  r=s>>_ftb;
+  ret=-1;
+  do{
+    t=s;
+    s=IMUL32(r,_icdf[++ret]);
+  }
+  while(d<s);
+  _this->val=d-s;
+  _this->rng=t-s;
+  ec_dec_normalize(_this);
+  return ret;
+}
+
+opus_uint32 ec_dec_uint(ec_dec *_this,opus_uint32 _ft){
+  unsigned ft;
+  unsigned s;
+  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_UINT_BITS){
+    opus_uint32 t;
+    ftb-=EC_UINT_BITS;
+    ft=(unsigned)(_ft>>ftb)+1;
+    s=ec_decode(_this,ft);
+    ec_dec_update(_this,s,s+1,ft);
+    t=(opus_uint32)s<<ftb|ec_dec_bits(_this,ftb);
+    if(t<=_ft)return t;
+    _this->error=1;
+    return _ft;
+  }
+  else{
+    _ft++;
+    s=ec_decode(_this,(unsigned)_ft);
+    ec_dec_update(_this,s,s+1,(unsigned)_ft);
+    return s;
+  }
+}
+
+opus_uint32 ec_dec_bits(ec_dec *_this,unsigned _bits){
+  ec_window   window;
+  int         available;
+  opus_uint32 ret;
+  window=_this->end_window;
+  available=_this->nend_bits;
+  if((unsigned)available<_bits){
+    do{
+      window|=(ec_window)ec_read_byte_from_end(_this)<<available;
+      available+=EC_SYM_BITS;
+    }
+    while(available<=EC_WINDOW_SIZE-EC_SYM_BITS);
+  }
+  ret=(opus_uint32)window&(((opus_uint32)1<<_bits)-1U);
+  window>>=_bits;
+  available-=_bits;
+  _this->end_window=window;
+  _this->nend_bits=available;
+  _this->nbits_total+=_bits;
+  return ret;
+}
diff --git a/opus/celt/entdec.h b/opus/celt/entdec.h
new file mode 100644 (file)
index 0000000..d8ab318
--- /dev/null
@@ -0,0 +1,100 @@
+/* Copyright (c) 2001-2011 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#if !defined(_entdec_H)
+# define _entdec_H (1)
+# include <limits.h>
+# include "entcode.h"
+
+/*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,unsigned char *_buf,opus_uint32 _storage);
+
+/*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);
+
+/*Equivalent to ec_decode() with _ft==1<<_bits.*/
+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);
+
+/* Decode a bit that has a 1/(1<<_logp) probability of being a one */
+int ec_dec_bit_logp(ec_dec *_this,unsigned _logp);
+
+/*Decodes a symbol given an "inverse" CDF table.
+  No call to ec_dec_update() is necessary after this call.
+  _icdf: The "inverse" CDF, such that symbol s falls in the range
+          [s>0?ft-_icdf[s-1]:0,ft-_icdf[s]), where ft=1<<_ftb.
+         The values must be monotonically non-increasing, and the last value
+          must be 0.
+  _ftb: The number of bits of precision in the cumulative distribution.
+  Return: The decoded symbol s.*/
+int ec_dec_icdf(ec_dec *_this,const unsigned char *_icdf,unsigned _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.*/
+opus_uint32 ec_dec_uint(ec_dec *_this,opus_uint32 _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 between 0 and 25, inclusive.
+  Return: The decoded bits.*/
+opus_uint32 ec_dec_bits(ec_dec *_this,unsigned _ftb);
+
+#endif
diff --git a/opus/celt/entenc.c b/opus/celt/entenc.c
new file mode 100644 (file)
index 0000000..f1750d2
--- /dev/null
@@ -0,0 +1,294 @@
+/* Copyright (c) 2001-2011 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#if defined(HAVE_CONFIG_H)
+# include "config.h"
+#endif
+#include "os_support.h"
+#include "arch.h"
+#include "entenc.h"
+#include "mfrngcod.h"
+
+/*A range encoder.
+  See entdec.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"
+  }*/
+
+static int ec_write_byte(ec_enc *_this,unsigned _value){
+  if(_this->offs+_this->end_offs>=_this->storage)return -1;
+  _this->buf[_this->offs++]=(unsigned char)_value;
+  return 0;
+}
+
+static int ec_write_byte_at_end(ec_enc *_this,unsigned _value){
+  if(_this->offs+_this->end_offs>=_this->storage)return -1;
+  _this->buf[_this->storage-++(_this->end_offs)]=(unsigned char)_value;
+  return 0;
+}
+
+/*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)_this->error|=ec_write_byte(_this,_this->rem+carry);
+    if(_this->ext>0){
+      unsigned sym;
+      sym=(EC_SYM_MAX+carry)&EC_SYM_MAX;
+      do _this->error|=ec_write_byte(_this,sym);
+      while(--(_this->ext)>0);
+    }
+    _this->rem=_c&EC_SYM_MAX;
+  }
+  else _this->ext++;
+}
+
+static OPUS_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->val>>EC_CODE_SHIFT));
+    /*Move the next-to-high-order symbol into the high-order position.*/
+    _this->val=(_this->val<<EC_SYM_BITS)&(EC_CODE_TOP-1);
+    _this->rng<<=EC_SYM_BITS;
+    _this->nbits_total+=EC_SYM_BITS;
+  }
+}
+
+void ec_enc_init(ec_enc *_this,unsigned char *_buf,opus_uint32 _size){
+  _this->buf=_buf;
+  _this->end_offs=0;
+  _this->end_window=0;
+  _this->nend_bits=0;
+  /*This is the offset from which ec_tell() will subtract partial bits.*/
+  _this->nbits_total=EC_CODE_BITS+1;
+  _this->offs=0;
+  _this->rng=EC_CODE_TOP;
+  _this->rem=-1;
+  _this->val=0;
+  _this->ext=0;
+  _this->storage=_size;
+  _this->error=0;
+}
+
+void ec_encode(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _ft){
+  opus_uint32 r;
+  r=celt_udiv(_this->rng,_ft);
+  if(_fl>0){
+    _this->val+=_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){
+  opus_uint32 r;
+  r=_this->rng>>_bits;
+  if(_fl>0){
+    _this->val+=_this->rng-IMUL32(r,((1U<<_bits)-_fl));
+    _this->rng=IMUL32(r,(_fh-_fl));
+  }
+  else _this->rng-=IMUL32(r,((1U<<_bits)-_fh));
+  ec_enc_normalize(_this);
+}
+
+/*The probability of having a "one" is 1/(1<<_logp).*/
+void ec_enc_bit_logp(ec_enc *_this,int _val,unsigned _logp){
+  opus_uint32 r;
+  opus_uint32 s;
+  opus_uint32 l;
+  r=_this->rng;
+  l=_this->val;
+  s=r>>_logp;
+  r-=s;
+  if(_val)_this->val=l+r;
+  _this->rng=_val?s:r;
+  ec_enc_normalize(_this);
+}
+
+void ec_enc_icdf(ec_enc *_this,int _s,const unsigned char *_icdf,unsigned _ftb){
+  opus_uint32 r;
+  r=_this->rng>>_ftb;
+  if(_s>0){
+    _this->val+=_this->rng-IMUL32(r,_icdf[_s-1]);
+    _this->rng=IMUL32(r,_icdf[_s-1]-_icdf[_s]);
+  }
+  else _this->rng-=IMUL32(r,_icdf[_s]);
+  ec_enc_normalize(_this);
+}
+
+void ec_enc_uint(ec_enc *_this,opus_uint32 _fl,opus_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_UINT_BITS){
+    ftb-=EC_UINT_BITS;
+    ft=(_ft>>ftb)+1;
+    fl=(unsigned)(_fl>>ftb);
+    ec_encode(_this,fl,fl+1,ft);
+    ec_enc_bits(_this,_fl&(((opus_uint32)1<<ftb)-1U),ftb);
+  }
+  else ec_encode(_this,_fl,_fl+1,_ft+1);
+}
+
+void ec_enc_bits(ec_enc *_this,opus_uint32 _fl,unsigned _bits){
+  ec_window window;
+  int       used;
+  window=_this->end_window;
+  used=_this->nend_bits;
+  celt_assert(_bits>0);
+  if(used+_bits>EC_WINDOW_SIZE){
+    do{
+      _this->error|=ec_write_byte_at_end(_this,(unsigned)window&EC_SYM_MAX);
+      window>>=EC_SYM_BITS;
+      used-=EC_SYM_BITS;
+    }
+    while(used>=EC_SYM_BITS);
+  }
+  window|=(ec_window)_fl<<used;
+  used+=_bits;
+  _this->end_window=window;
+  _this->nend_bits=used;
+  _this->nbits_total+=_bits;
+}
+
+void ec_enc_patch_initial_bits(ec_enc *_this,unsigned _val,unsigned _nbits){
+  int      shift;
+  unsigned mask;
+  celt_assert(_nbits<=EC_SYM_BITS);
+  shift=EC_SYM_BITS-_nbits;
+  mask=((1<<_nbits)-1)<<shift;
+  if(_this->offs>0){
+    /*The first byte has been finalized.*/
+    _this->buf[0]=(unsigned char)((_this->buf[0]&~mask)|_val<<shift);
+  }
+  else if(_this->rem>=0){
+    /*The first byte is still awaiting carry propagation.*/
+    _this->rem=(_this->rem&~mask)|_val<<shift;
+  }
+  else if(_this->rng<=(EC_CODE_TOP>>_nbits)){
+    /*The renormalization loop has never been run.*/
+    _this->val=(_this->val&~((opus_uint32)mask<<EC_CODE_SHIFT))|
+     (opus_uint32)_val<<(EC_CODE_SHIFT+shift);
+  }
+  /*The encoder hasn't even encoded _nbits of data yet.*/
+  else _this->error=-1;
+}
+
+void ec_enc_shrink(ec_enc *_this,opus_uint32 _size){
+  celt_assert(_this->offs+_this->end_offs<=_size);
+  OPUS_MOVE(_this->buf+_size-_this->end_offs,
+   _this->buf+_this->storage-_this->end_offs,_this->end_offs);
+  _this->storage=_size;
+}
+
+void ec_enc_done(ec_enc *_this){
+  ec_window   window;
+  int         used;
+  opus_uint32 msk;
+  opus_uint32 end;
+  int         l;
+  /*We output the minimum number of bits that ensures that the symbols encoded
+     thus far will be decoded correctly regardless of the bits that follow.*/
+  l=EC_CODE_BITS-EC_ILOG(_this->rng);
+  msk=(EC_CODE_TOP-1)>>l;
+  end=(_this->val+msk)&~msk;
+  if((end|msk)>=_this->val+_this->rng){
+    l++;
+    msk>>=1;
+    end=(_this->val+msk)&~msk;
+  }
+  while(l>0){
+    ec_enc_carry_out(_this,(int)(end>>EC_CODE_SHIFT));
+    end=(end<<EC_SYM_BITS)&(EC_CODE_TOP-1);
+    l-=EC_SYM_BITS;
+  }
+  /*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);
+  /*If we have buffered extra bits, flush them as well.*/
+  window=_this->end_window;
+  used=_this->nend_bits;
+  while(used>=EC_SYM_BITS){
+    _this->error|=ec_write_byte_at_end(_this,(unsigned)window&EC_SYM_MAX);
+    window>>=EC_SYM_BITS;
+    used-=EC_SYM_BITS;
+  }
+  /*Clear any excess space and add any remaining extra bits to the last byte.*/
+  if(!_this->error){
+    OPUS_CLEAR(_this->buf+_this->offs,
+     _this->storage-_this->offs-_this->end_offs);
+    if(used>0){
+      /*If there's no range coder data at all, give up.*/
+      if(_this->end_offs>=_this->storage)_this->error=-1;
+      else{
+        l=-l;
+        /*If we've busted, don't add too many extra bits to the last byte; it
+           would corrupt the range coder data, and that's more important.*/
+        if(_this->offs+_this->end_offs>=_this->storage&&l<used){
+          window&=(1<<l)-1;
+          _this->error=-1;
+        }
+        _this->buf[_this->storage-_this->end_offs-1]|=(unsigned char)window;
+      }
+    }
+  }
+}
diff --git a/opus/celt/entenc.h b/opus/celt/entenc.h
new file mode 100644 (file)
index 0000000..796bc4d
--- /dev/null
@@ -0,0 +1,110 @@
+/* Copyright (c) 2001-2011 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#if !defined(_entenc_H)
+# define _entenc_H (1)
+# include <stddef.h>
+# include "entcode.h"
+
+/*Initializes the encoder.
+  _buf:  The buffer to store output bytes in.
+  _size: The size of the buffer, in chars.*/
+void ec_enc_init(ec_enc *_this,unsigned char *_buf,opus_uint32 _size);
+/*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);
+
+/*Equivalent to ec_encode() with _ft==1<<_bits.*/
+void ec_encode_bin(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _bits);
+
+/* Encode a bit that has a 1/(1<<_logp) probability of being a one */
+void ec_enc_bit_logp(ec_enc *_this,int _val,unsigned _logp);
+
+/*Encodes a symbol given an "inverse" CDF table.
+  _s:    The index of the symbol to encode.
+  _icdf: The "inverse" CDF, such that symbol _s falls in the range
+          [_s>0?ft-_icdf[_s-1]:0,ft-_icdf[_s]), where ft=1<<_ftb.
+         The values must be monotonically non-increasing, and the last value
+          must be 0.
+  _ftb: The number of bits of precision in the cumulative distribution.*/
+void ec_enc_icdf(ec_enc *_this,int _s,const unsigned char *_icdf,unsigned _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,opus_uint32 _fl,opus_uint32 _ft);
+
+/*Encodes a sequence of raw bits in the stream.
+  _fl:  The bits to encode.
+  _ftb: The number of bits to encode.
+        This must be between 1 and 25, inclusive.*/
+void ec_enc_bits(ec_enc *_this,opus_uint32 _fl,unsigned _ftb);
+
+/*Overwrites a few bits at the very start of an existing stream, after they
+   have already been encoded.
+  This makes it possible to have a few flags up front, where it is easy for
+   decoders to access them without parsing the whole stream, even if their
+   values are not determined until late in the encoding process, without having
+   to buffer all the intermediate symbols in the encoder.
+  In order for this to work, at least _nbits bits must have already been
+   encoded using probabilities that are an exact power of two.
+  The encoder can verify the number of encoded bits is sufficient, but cannot
+   check this latter condition.
+  _val:   The bits to encode (in the least _nbits significant bits).
+          They will be decoded in order from most-significant to least.
+  _nbits: The number of bits to overwrite.
+          This must be no more than 8.*/
+void ec_enc_patch_initial_bits(ec_enc *_this,unsigned _val,unsigned _nbits);
+
+/*Compacts the data to fit in the target size.
+  This moves up the raw bits at the end of the current buffer so they are at
+   the end of the new buffer size.
+  The caller must ensure that the amount of data that's already been written
+   will fit in the new size.
+  _size: The number of bytes in the new buffer.
+         This must be large enough to contain the bits already written, and
+          must be no larger than the existing size.*/
+void ec_enc_shrink(ec_enc *_this,opus_uint32 _size);
+
+/*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
diff --git a/opus/celt/fixed_debug.h b/opus/celt/fixed_debug.h
new file mode 100644 (file)
index 0000000..f435295
--- /dev/null
@@ -0,0 +1,791 @@
+/* Copyright (C) 2003-2008 Jean-Marc Valin
+   Copyright (C) 2007-2012 Xiph.Org Foundation */
+/**
+   @file fixed_debug.h
+   @brief Fixed-point operations with debugging
+*/
+/*
+   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.
+
+   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 FIXED_DEBUG_H
+#define FIXED_DEBUG_H
+
+#include <stdio.h>
+#include "opus_defines.h"
+
+#ifdef CELT_C
+OPUS_EXPORT opus_int64 celt_mips=0;
+#else
+extern opus_int64 celt_mips;
+#endif
+
+#define MULT16_16SU(a,b) ((opus_val32)(opus_val16)(a)*(opus_val32)(opus_uint16)(b))
+#define MULT32_32_Q31(a,b) ADD32(ADD32(SHL32(MULT16_16(SHR32((a),16),SHR((b),16)),1), SHR32(MULT16_16SU(SHR32((a),16),((b)&0x0000ffff)),15)), SHR32(MULT16_16SU(SHR32((b),16),((a)&0x0000ffff)),15))
+
+/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
+#define MULT16_32_Q16(a,b) ADD32(MULT16_16((a),SHR32((b),16)), SHR32(MULT16_16SU((a),((b)&0x0000ffff)),16))
+
+#define MULT16_32_P16(a,b) MULT16_32_PX(a,b,16)
+
+#define QCONST16(x,bits) ((opus_val16)(.5+(x)*(((opus_val32)1)<<(bits))))
+#define QCONST32(x,bits) ((opus_val32)(.5+(x)*(((opus_val32)1)<<(bits))))
+
+#define VERIFY_SHORT(x) ((x)<=32767&&(x)>=-32768)
+#define VERIFY_INT(x) ((x)<=2147483647LL&&(x)>=-2147483648LL)
+#define VERIFY_UINT(x) ((x)<=(2147483647LLU<<1))
+
+#define SHR(a,b) SHR32(a,b)
+#define PSHR(a,b) PSHR32(a,b)
+
+/** Add two 32-bit values, ignore any overflows */
+#define ADD32_ovflw(a,b) (celt_mips+=2,(opus_val32)((opus_uint32)(a)+(opus_uint32)(b)))
+/** Subtract two 32-bit values, ignore any overflows */
+#define SUB32_ovflw(a,b) (celt_mips+=2,(opus_val32)((opus_uint32)(a)-(opus_uint32)(b)))
+/* Avoid MSVC warning C4146: unary minus operator applied to unsigned type */
+/** Negate 32-bit value, ignore any overflows */
+#define NEG32_ovflw(a) (celt_mips+=2,(opus_val32)(0-(opus_uint32)(a)))
+
+static OPUS_INLINE short NEG16(int x)
+{
+   int res;
+   if (!VERIFY_SHORT(x))
+   {
+      fprintf (stderr, "NEG16: input is not short: %d\n", (int)x);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = -x;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "NEG16: output is not short: %d\n", (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+static OPUS_INLINE int NEG32(opus_int64 x)
+{
+   opus_int64 res;
+   if (!VERIFY_INT(x))
+   {
+      fprintf (stderr, "NEG16: input is not int: %d\n", (int)x);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = -x;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "NEG16: output is not int: %d\n", (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#define EXTRACT16(x) EXTRACT16_(x, __FILE__, __LINE__)
+static OPUS_INLINE short EXTRACT16_(int x, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(x))
+   {
+      fprintf (stderr, "EXTRACT16: input is not short: %d in %s: line %d\n", x, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = x;
+   celt_mips++;
+   return res;
+}
+
+#define EXTEND32(x) EXTEND32_(x, __FILE__, __LINE__)
+static OPUS_INLINE int EXTEND32_(int x, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(x))
+   {
+      fprintf (stderr, "EXTEND32: input is not short: %d in %s: line %d\n", x, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = x;
+   celt_mips++;
+   return res;
+}
+
+#define SHR16(a, shift) SHR16_(a, shift, __FILE__, __LINE__)
+static OPUS_INLINE short SHR16_(int a, int shift, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift))
+   {
+      fprintf (stderr, "SHR16: inputs are not short: %d >> %d in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a>>shift;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "SHR16: output is not short: %d in %s: line %d\n", res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+#define SHL16(a, shift) SHL16_(a, shift, __FILE__, __LINE__)
+static OPUS_INLINE short SHL16_(int a, int shift, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift))
+   {
+      fprintf (stderr, "SHL16: inputs are not short: %d %d in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a<<shift;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "SHL16: output is not short: %d in %s: line %d\n", res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+
+static OPUS_INLINE int SHR32(opus_int64 a, int shift)
+{
+   opus_int64  res;
+   if (!VERIFY_INT(a) || !VERIFY_SHORT(shift))
+   {
+      fprintf (stderr, "SHR32: inputs are not int: %d %d\n", (int)a, shift);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a>>shift;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "SHR32: output is not int: %d\n", (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+#define SHL32(a, shift) SHL32_(a, shift, __FILE__, __LINE__)
+static OPUS_INLINE int SHL32_(opus_int64 a, int shift, char *file, int line)
+{
+   opus_int64  res;
+   if (!VERIFY_INT(a) || !VERIFY_SHORT(shift))
+   {
+      fprintf (stderr, "SHL32: inputs are not int: %lld %d in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a<<shift;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "SHL32: output is not int: %lld<<%d = %lld in %s: line %d\n", a, shift, res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#define PSHR32(a,shift) (celt_mips--,SHR32(ADD32((a),(((opus_val32)(1)<<((shift))>>1))),shift))
+#define VSHR32(a, shift) (((shift)>0) ? SHR32(a, shift) : SHL32(a, -(shift)))
+
+#define ROUND16(x,a) (celt_mips--,EXTRACT16(PSHR32((x),(a))))
+#define SROUND16(x,a) (celt_mips--,EXTRACT16(SATURATE(PSHR32(x,a), 32767)));
+
+#define HALF16(x)  (SHR16(x,1))
+#define HALF32(x)  (SHR32(x,1))
+
+#define ADD16(a, b) ADD16_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE short ADD16_(int a, int b, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "ADD16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a+b;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "ADD16: output is not short: %d+%d=%d in %s: line %d\n", a,b,res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+
+#define SUB16(a, b) SUB16_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE short SUB16_(int a, int b, char *file, int line)
+{
+   int res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "SUB16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a-b;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "SUB16: output is not short: %d in %s: line %d\n", res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+
+#define ADD32(a, b) ADD32_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE int ADD32_(opus_int64 a, opus_int64 b, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_INT(a) || !VERIFY_INT(b))
+   {
+      fprintf (stderr, "ADD32: inputs are not int: %d %d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a+b;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "ADD32: output is not int: %d in %s: line %d\n", (int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#define SUB32(a, b) SUB32_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE int SUB32_(opus_int64 a, opus_int64 b, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_INT(a) || !VERIFY_INT(b))
+   {
+      fprintf (stderr, "SUB32: inputs are not int: %d %d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a-b;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "SUB32: output is not int: %d in %s: line %d\n", (int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#undef UADD32
+#define UADD32(a, b) UADD32_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE unsigned int UADD32_(opus_uint64 a, opus_uint64 b, char *file, int line)
+{
+   opus_uint64 res;
+   if (!VERIFY_UINT(a) || !VERIFY_UINT(b))
+   {
+      fprintf (stderr, "UADD32: inputs are not uint32: %llu %llu in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a+b;
+   if (!VERIFY_UINT(res))
+   {
+      fprintf (stderr, "UADD32: output is not uint32: %llu in %s: line %d\n", res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#undef USUB32
+#define USUB32(a, b) USUB32_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE unsigned int USUB32_(opus_uint64 a, opus_uint64 b, char *file, int line)
+{
+   opus_uint64 res;
+   if (!VERIFY_UINT(a) || !VERIFY_UINT(b))
+   {
+      fprintf (stderr, "USUB32: inputs are not uint32: %llu %llu in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   if (a<b)
+   {
+      fprintf (stderr, "USUB32: inputs underflow: %llu < %llu in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a-b;
+   if (!VERIFY_UINT(res))
+   {
+      fprintf (stderr, "USUB32: output is not uint32: %llu - %llu = %llu in %s: line %d\n", a, b, res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+/* result fits in 16 bits */
+static OPUS_INLINE short MULT16_16_16(int a, int b)
+{
+   int res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_16: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a*b;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_16: output is not short: %d\n", res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+
+#define MULT16_16(a, b) MULT16_16_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE int MULT16_16_(int a, int b, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16: inputs are not short: %d %d in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_16: output is not int: %d in %s: line %d\n", (int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips++;
+   return res;
+}
+
+#define MAC16_16(c,a,b)     (celt_mips-=2,ADD32((c),MULT16_16((a),(b))))
+
+#define MULT16_32_QX(a, b, Q) MULT16_32_QX_(a, b, Q, __FILE__, __LINE__)
+static OPUS_INLINE int MULT16_32_QX_(int a, opus_int64 b, int Q, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_INT(b))
+   {
+      fprintf (stderr, "MULT16_32_Q%d: inputs are not short+int: %d %d in %s: line %d\n", Q, (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   if (ABS32(b)>=((opus_val32)(1)<<(15+Q)))
+   {
+      fprintf (stderr, "MULT16_32_Q%d: second operand too large: %d %d in %s: line %d\n", Q, (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = (((opus_int64)a)*(opus_int64)b) >> Q;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_32_Q%d: output is not int: %d*%d=%d in %s: line %d\n", Q, (int)a, (int)b,(int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   if (Q==15)
+      celt_mips+=3;
+   else
+      celt_mips+=4;
+   return res;
+}
+
+#define MULT16_32_PX(a, b, Q) MULT16_32_PX_(a, b, Q, __FILE__, __LINE__)
+static OPUS_INLINE int MULT16_32_PX_(int a, opus_int64 b, int Q, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_INT(b))
+   {
+      fprintf (stderr, "MULT16_32_P%d: inputs are not short+int: %d %d in %s: line %d\n\n", Q, (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   if (ABS32(b)>=((opus_int64)(1)<<(15+Q)))
+   {
+      fprintf (stderr, "MULT16_32_Q%d: second operand too large: %d %d in %s: line %d\n\n", Q, (int)a, (int)b,file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((((opus_int64)a)*(opus_int64)b) + (((opus_val32)(1)<<Q)>>1))>> Q;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_32_P%d: output is not int: %d*%d=%d in %s: line %d\n\n", Q, (int)a, (int)b,(int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   if (Q==15)
+      celt_mips+=4;
+   else
+      celt_mips+=5;
+   return res;
+}
+
+#define MULT16_32_Q15(a,b) MULT16_32_QX(a,b,15)
+#define MAC16_32_Q15(c,a,b) (celt_mips-=2,ADD32((c),MULT16_32_Q15((a),(b))))
+#define MAC16_32_Q16(c,a,b) (celt_mips-=2,ADD32((c),MULT16_32_Q16((a),(b))))
+
+static OPUS_INLINE int SATURATE(int a, int b)
+{
+   if (a>b)
+      a=b;
+   if (a<-b)
+      a = -b;
+   celt_mips+=3;
+   return a;
+}
+
+static OPUS_INLINE opus_int16 SATURATE16(opus_int32 a)
+{
+   celt_mips+=3;
+   if (a>32767)
+      return 32767;
+   else if (a<-32768)
+      return -32768;
+   else return a;
+}
+
+static OPUS_INLINE int MULT16_16_Q11_32(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_Q11: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res >>= 11;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_16_Q11: output is not short: %d*%d=%d\n", (int)a, (int)b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=3;
+   return res;
+}
+static OPUS_INLINE short MULT16_16_Q13(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_Q13: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res >>= 13;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_Q13: output is not short: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=3;
+   return res;
+}
+static OPUS_INLINE short MULT16_16_Q14(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_Q14: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res >>= 14;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_Q14: output is not short: %d\n", (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=3;
+   return res;
+}
+
+#define MULT16_16_Q15(a, b) MULT16_16_Q15_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE short MULT16_16_Q15_(int a, int b, char *file, int line)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_Q15: inputs are not short: %d %d in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res >>= 15;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_Q15: output is not short: %d in %s: line %d\n", (int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=1;
+   return res;
+}
+
+static OPUS_INLINE short MULT16_16_P13(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_P13: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res += 4096;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_16_P13: overflow: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res >>= 13;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_P13: output is not short: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=4;
+   return res;
+}
+static OPUS_INLINE short MULT16_16_P14(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_P14: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res += 8192;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_16_P14: overflow: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res >>= 14;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_P14: output is not short: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=4;
+   return res;
+}
+static OPUS_INLINE short MULT16_16_P15(int a, int b)
+{
+   opus_int64 res;
+   if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "MULT16_16_P15: inputs are not short: %d %d\n", a, b);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = ((opus_int64)a)*b;
+   res += 16384;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "MULT16_16_P15: overflow: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res >>= 15;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "MULT16_16_P15: output is not short: %d*%d=%d\n", a, b, (int)res);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=2;
+   return res;
+}
+
+#define DIV32_16(a, b) DIV32_16_(a, b, __FILE__, __LINE__)
+
+static OPUS_INLINE int DIV32_16_(opus_int64 a, opus_int64 b, char *file, int line)
+{
+   opus_int64 res;
+   if (b==0)
+   {
+      fprintf(stderr, "DIV32_16: divide by zero: %d/%d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+      return 0;
+   }
+   if (!VERIFY_INT(a) || !VERIFY_SHORT(b))
+   {
+      fprintf (stderr, "DIV32_16: inputs are not int/short: %d %d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a/b;
+   if (!VERIFY_SHORT(res))
+   {
+      fprintf (stderr, "DIV32_16: output is not short: %d / %d = %d in %s: line %d\n", (int)a,(int)b,(int)res, file, line);
+      if (res>32767)
+         res = 32767;
+      if (res<-32768)
+         res = -32768;
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=35;
+   return res;
+}
+
+#define DIV32(a, b) DIV32_(a, b, __FILE__, __LINE__)
+static OPUS_INLINE int DIV32_(opus_int64 a, opus_int64 b, char *file, int line)
+{
+   opus_int64 res;
+   if (b==0)
+   {
+      fprintf(stderr, "DIV32: divide by zero: %d/%d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+      return 0;
+   }
+
+   if (!VERIFY_INT(a) || !VERIFY_INT(b))
+   {
+      fprintf (stderr, "DIV32: inputs are not int/short: %d %d in %s: line %d\n", (int)a, (int)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   res = a/b;
+   if (!VERIFY_INT(res))
+   {
+      fprintf (stderr, "DIV32: output is not int: %d in %s: line %d\n", (int)res, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+      celt_assert(0);
+#endif
+   }
+   celt_mips+=70;
+   return res;
+}
+
+static OPUS_INLINE opus_val16 SIG2WORD16_generic(celt_sig x)
+{
+   x = PSHR32(x, SIG_SHIFT);
+   x = MAX32(x, -32768);
+   x = MIN32(x, 32767);
+   return EXTRACT16(x);
+}
+#define SIG2WORD16(x) (SIG2WORD16_generic(x))
+
+
+#undef PRINT_MIPS
+#define PRINT_MIPS(file) do {fprintf (file, "total complexity = %llu MIPS\n", celt_mips);} while (0);
+
+#endif
diff --git a/opus/celt/fixed_generic.h b/opus/celt/fixed_generic.h
new file mode 100644 (file)
index 0000000..5f4abda
--- /dev/null
@@ -0,0 +1,178 @@
+/* Copyright (C) 2007-2009 Xiph.Org Foundation
+   Copyright (C) 2003-2008 Jean-Marc Valin
+   Copyright (C) 2007-2008 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.
+
+   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 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) ((opus_val32)(opus_val16)(a)*(opus_val32)(opus_uint16)(b))
+
+/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
+#if OPUS_FAST_INT64
+#define MULT16_32_Q16(a,b) ((opus_val32)SHR((opus_int64)((opus_val16)(a))*(b),16))
+#else
+#define MULT16_32_Q16(a,b) ADD32(MULT16_16((a),SHR((b),16)), SHR(MULT16_16SU((a),((b)&0x0000ffff)),16))
+#endif
+
+/** 16x32 multiplication, followed by a 16-bit shift right (round-to-nearest). Results fits in 32 bits */
+#if OPUS_FAST_INT64
+#define MULT16_32_P16(a,b) ((opus_val32)PSHR((opus_int64)((opus_val16)(a))*(b),16))
+#else
+#define MULT16_32_P16(a,b) ADD32(MULT16_16((a),SHR((b),16)), PSHR(MULT16_16SU((a),((b)&0x0000ffff)),16))
+#endif
+
+/** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
+#if OPUS_FAST_INT64
+#define MULT16_32_Q15(a,b) ((opus_val32)SHR((opus_int64)((opus_val16)(a))*(b),15))
+#else
+#define MULT16_32_Q15(a,b) ADD32(SHL(MULT16_16((a),SHR((b),16)),1), SHR(MULT16_16SU((a),((b)&0x0000ffff)),15))
+#endif
+
+/** 32x32 multiplication, followed by a 31-bit shift right. Results fits in 32 bits */
+#if OPUS_FAST_INT64
+#define MULT32_32_Q31(a,b) ((opus_val32)SHR((opus_int64)(a)*(opus_int64)(b),31))
+#else
+#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))
+#endif
+
+/** Compile-time conversion of float constant to 16-bit value */
+#define QCONST16(x,bits) ((opus_val16)(.5+(x)*(((opus_val32)1)<<(bits))))
+
+/** Compile-time conversion of float constant to 32-bit value */
+#define QCONST32(x,bits) ((opus_val32)(.5+(x)*(((opus_val32)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) ((opus_val16)(x))
+/** Change a 16-bit value into a 32-bit value */
+#define EXTEND32(x) ((opus_val32)(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) ((opus_int16)((opus_uint16)(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) ((opus_int32)((opus_uint32)(a)<<(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)))
+
+/** "RAW" macros, should not be used outside of this header file */
+#define SHR(a,shift) ((a) >> (shift))
+#define SHL(a,shift) SHL32(a,shift)
+#define PSHR(a,shift) (SHR((a)+((EXTEND32(1)<<((shift))>>1)),shift))
+#define SATURATE(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x)))
+
+#define SATURATE16(x) (EXTRACT16((x)>32767 ? 32767 : (x)<-32768 ? -32768 : (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))))
+/** Shift by a and round-to-neareast 32-bit value. Result is a saturated 16-bit value */
+#define SROUND16(x,a) EXTRACT16(SATURATE(PSHR32(x,a), 32767));
+
+/** Divide by two */
+#define HALF16(x)  (SHR16(x,1))
+#define HALF32(x)  (SHR32(x,1))
+
+/** Add two 16-bit values */
+#define ADD16(a,b) ((opus_val16)((opus_val16)(a)+(opus_val16)(b)))
+/** Subtract two 16-bit values */
+#define SUB16(a,b) ((opus_val16)(a)-(opus_val16)(b))
+/** Add two 32-bit values */
+#define ADD32(a,b) ((opus_val32)(a)+(opus_val32)(b))
+/** Subtract two 32-bit values */
+#define SUB32(a,b) ((opus_val32)(a)-(opus_val32)(b))
+
+/** Add two 32-bit values, ignore any overflows */
+#define ADD32_ovflw(a,b) ((opus_val32)((opus_uint32)(a)+(opus_uint32)(b)))
+/** Subtract two 32-bit values, ignore any overflows */
+#define SUB32_ovflw(a,b) ((opus_val32)((opus_uint32)(a)-(opus_uint32)(b)))
+/* Avoid MSVC warning C4146: unary minus operator applied to unsigned type */
+/** Negate 32-bit value, ignore any overflows */
+#define NEG32_ovflw(a) ((opus_val32)(0-(opus_uint32)(a)))
+
+/** 16x16 multiplication where the result fits in 16 bits */
+#define MULT16_16_16(a,b)     ((((opus_val16)(a))*((opus_val16)(b))))
+
+/* (opus_val32)(opus_val16) 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)     (((opus_val32)(opus_val16)(a))*((opus_val32)(opus_val16)(b)))
+
+/** 16x16 multiply-add where the result fits in 32 bits */
+#define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b))))
+/** 16x32 multiply, followed by a 15-bit shift right and 32-bit add.
+    b must fit in 31 bits.
+    Result 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)))
+
+/** 16x32 multiplication, followed by a 16-bit shift right and 32-bit add.
+    Results fits in 32 bits */
+#define MAC16_32_Q16(c,a,b) ADD32((c),ADD32(MULT16_16((a),SHR((b),16)), SHR(MULT16_16SU((a),((b)&0x0000ffff)),16)))
+
+#define MULT16_16_Q11_32(a,b) (SHR(MULT16_16((a),(b)),11))
+#define MULT16_16_Q11(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) ((opus_val16)(((opus_val32)(a))/((opus_val16)(b))))
+
+/** Divide a 32-bit value by a 32-bit value. Result fits in 32 bits */
+#define DIV32(a,b) (((opus_val32)(a))/((opus_val32)(b)))
+
+#if defined(MIPSr1_ASM)
+#include "mips/fixed_generic_mipsr1.h"
+#endif
+
+static OPUS_INLINE opus_val16 SIG2WORD16_generic(celt_sig x)
+{
+   x = PSHR32(x, SIG_SHIFT);
+   x = MAX32(x, -32768);
+   x = MIN32(x, 32767);
+   return EXTRACT16(x);
+}
+#define SIG2WORD16(x) (SIG2WORD16_generic(x))
+
+#endif
diff --git a/opus/celt/float_cast.h b/opus/celt/float_cast.h
new file mode 100644 (file)
index 0000000..98b40ab
--- /dev/null
@@ -0,0 +1,146 @@
+/* Copyright (C) 2001 Erik de Castro Lopo <erikd AT mega-nerd DOT com> */
+/*
+   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.
+
+   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.
+*/
+
+/* Version 1.1 */
+
+#ifndef FLOAT_CAST_H
+#define FLOAT_CAST_H
+
+
+#include "arch.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.
+*/
+
+/* With GCC, when SSE is available, the fastest conversion is cvtss2si. */
+#if defined(__GNUC__) && defined(__SSE__)
+
+#include <xmmintrin.h>
+static OPUS_INLINE opus_int32 float2int(float x) {return _mm_cvt_ss2si(_mm_set_ss(x));}
+
+#elif defined(HAVE_LRINTF)
+
+/*      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(_MSC_VER) && _MSC_VER >= 1400) && defined (_M_X64)
+        #include <xmmintrin.h>
+
+        __inline long int float2int(float value)
+        {
+                return _mm_cvtss_si32(_mm_load_ss(&value));
+        }
+#elif (defined(_MSC_VER) && _MSC_VER >= 1400) && defined (_M_IX86)
+        #include <math.h>
+
+        /*      Win32 doesn't seem to have these functions.
+        **      Therefore implement OPUS_INLINE versions of these functions here.
+        */
+
+        __inline long int
+        float2int (float flt)
+        {       int intgr;
+
+                _asm
+                {       fld flt
+                        fistp intgr
+                } ;
+
+                return intgr ;
+        }
+
+#else
+
+#if (defined(__GNUC__) && defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L)
+        /* supported by gcc in C99 mode, 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 /* __STDC_VERSION__ >= 199901L */
+        #include <math.h>
+        #define float2int(flt) ((int)(floor(.5+flt)))
+#endif
+
+#ifndef DISABLE_FLOAT_API
+static OPUS_INLINE opus_int16 FLOAT2INT16(float x)
+{
+   x = x*CELT_SIG_SCALE;
+   x = MAX32(x, -32768);
+   x = MIN32(x, 32767);
+   return (opus_int16)float2int(x);
+}
+#endif /* DISABLE_FLOAT_API */
+
+#endif /* FLOAT_CAST_H */
diff --git a/opus/celt/kiss_fft.c b/opus/celt/kiss_fft.c
new file mode 100644 (file)
index 0000000..8377516
--- /dev/null
@@ -0,0 +1,604 @@
+/*Copyright (c) 2003-2004, Mark Borgerding
+  Lots of modifications by Jean-Marc Valin
+  Copyright (c) 2005-2007, Xiph.Org Foundation
+  Copyright (c) 2008,      Xiph.Org Foundation, 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.
+
+  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.*/
+
+/* This code is originally from Mark Borgerding's KISS-FFT but has been
+   heavily modified to better suit Opus */
+
+#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,
+                     int m,
+                     int N
+                    )
+{
+   kiss_fft_cpx * Fout2;
+   int i;
+   (void)m;
+#ifdef CUSTOM_MODES
+   if (m==1)
+   {
+      celt_assert(m==1);
+      for (i=0;i<N;i++)
+      {
+         kiss_fft_cpx t;
+         Fout2 = Fout + 1;
+         t = *Fout2;
+         C_SUB( *Fout2 ,  *Fout , t );
+         C_ADDTO( *Fout ,  t );
+         Fout += 2;
+      }
+   } else
+#endif
+   {
+      opus_val16 tw;
+      tw = QCONST16(0.7071067812f, 15);
+      /* We know that m==4 here because the radix-2 is just after a radix-4 */
+      celt_assert(m==4);
+      for (i=0;i<N;i++)
+      {
+         kiss_fft_cpx t;
+         Fout2 = Fout + 4;
+         t = Fout2[0];
+         C_SUB( Fout2[0] ,  Fout[0] , t );
+         C_ADDTO( Fout[0] ,  t );
+
+         t.r = S_MUL(ADD32_ovflw(Fout2[1].r, Fout2[1].i), tw);
+         t.i = S_MUL(SUB32_ovflw(Fout2[1].i, Fout2[1].r), tw);
+         C_SUB( Fout2[1] ,  Fout[1] , t );
+         C_ADDTO( Fout[1] ,  t );
+
+         t.r = Fout2[2].i;
+         t.i = -Fout2[2].r;
+         C_SUB( Fout2[2] ,  Fout[2] , t );
+         C_ADDTO( Fout[2] ,  t );
+
+         t.r = S_MUL(SUB32_ovflw(Fout2[3].i, Fout2[3].r), tw);
+         t.i = S_MUL(NEG32_ovflw(ADD32_ovflw(Fout2[3].i, Fout2[3].r)), tw);
+         C_SUB( Fout2[3] ,  Fout[3] , t );
+         C_ADDTO( Fout[3] ,  t );
+         Fout += 8;
+      }
+   }
+}
+
+static void kf_bfly4(
+                     kiss_fft_cpx * Fout,
+                     const size_t fstride,
+                     const kiss_fft_state *st,
+                     int m,
+                     int N,
+                     int mm
+                    )
+{
+   int i;
+
+   if (m==1)
+   {
+      /* Degenerate case where all the twiddles are 1. */
+      for (i=0;i<N;i++)
+      {
+         kiss_fft_cpx scratch0, scratch1;
+
+         C_SUB( scratch0 , *Fout, Fout[2] );
+         C_ADDTO(*Fout, Fout[2]);
+         C_ADD( scratch1 , Fout[1] , Fout[3] );
+         C_SUB( Fout[2], *Fout, scratch1 );
+         C_ADDTO( *Fout , scratch1 );
+         C_SUB( scratch1 , Fout[1] , Fout[3] );
+
+         Fout[1].r = ADD32_ovflw(scratch0.r, scratch1.i);
+         Fout[1].i = SUB32_ovflw(scratch0.i, scratch1.r);
+         Fout[3].r = SUB32_ovflw(scratch0.r, scratch1.i);
+         Fout[3].i = ADD32_ovflw(scratch0.i, scratch1.r);
+         Fout+=4;
+      }
+   } else {
+      int j;
+      kiss_fft_cpx scratch[6];
+      const kiss_twiddle_cpx *tw1,*tw2,*tw3;
+      const int m2=2*m;
+      const int m3=3*m;
+      kiss_fft_cpx * Fout_beg = Fout;
+      for (i=0;i<N;i++)
+      {
+         Fout = Fout_beg + i*mm;
+         tw3 = tw2 = tw1 = st->twiddles;
+         /* m is guaranteed to be a multiple of 4. */
+         for (j=0;j<m;j++)
+         {
+            C_MUL(scratch[0],Fout[m] , *tw1 );
+            C_MUL(scratch[1],Fout[m2] , *tw2 );
+            C_MUL(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 = ADD32_ovflw(scratch[5].r, scratch[4].i);
+            Fout[m].i = SUB32_ovflw(scratch[5].i, scratch[4].r);
+            Fout[m3].r = SUB32_ovflw(scratch[5].r, scratch[4].i);
+            Fout[m3].i = ADD32_ovflw(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_state *st,
+                     int m,
+                     int N,
+                     int mm
+                    )
+{
+   int i;
+   size_t k;
+   const size_t m2 = 2*m;
+   const kiss_twiddle_cpx *tw1,*tw2;
+   kiss_fft_cpx scratch[5];
+   kiss_twiddle_cpx epi3;
+
+   kiss_fft_cpx * Fout_beg = Fout;
+#ifdef FIXED_POINT
+   /*epi3.r = -16384;*/ /* Unused */
+   epi3.i = -28378;
+#else
+   epi3 = st->twiddles[fstride*m];
+#endif
+   for (i=0;i<N;i++)
+   {
+      Fout = Fout_beg + i*mm;
+      tw1=tw2=st->twiddles;
+      /* For non-custom modes, m is guaranteed to be a multiple of 4. */
+      k=m;
+      do {
+
+         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 = SUB32_ovflw(Fout->r, HALF_OF(scratch[3].r));
+         Fout[m].i = SUB32_ovflw(Fout->i, HALF_OF(scratch[3].i));
+
+         C_MULBYSCALAR( scratch[0] , epi3.i );
+
+         C_ADDTO(*Fout,scratch[3]);
+
+         Fout[m2].r = ADD32_ovflw(Fout[m].r, scratch[0].i);
+         Fout[m2].i = SUB32_ovflw(Fout[m].i, scratch[0].r);
+
+         Fout[m].r = SUB32_ovflw(Fout[m].r, scratch[0].i);
+         Fout[m].i = ADD32_ovflw(Fout[m].i, scratch[0].r);
+
+         ++Fout;
+      } while(--k);
+   }
+}
+
+
+#ifndef OVERRIDE_kf_bfly5
+static void kf_bfly5(
+                     kiss_fft_cpx * Fout,
+                     const size_t fstride,
+                     const kiss_fft_state *st,
+                     int m,
+                     int N,
+                     int mm
+                    )
+{
+   kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
+   int i, u;
+   kiss_fft_cpx scratch[13];
+   const kiss_twiddle_cpx *tw;
+   kiss_twiddle_cpx ya,yb;
+   kiss_fft_cpx * Fout_beg = Fout;
+
+#ifdef FIXED_POINT
+   ya.r = 10126;
+   ya.i = -31164;
+   yb.r = -26510;
+   yb.i = -19261;
+#else
+   ya = st->twiddles[fstride*m];
+   yb = st->twiddles[fstride*2*m];
+#endif
+   tw=st->twiddles;
+
+   for (i=0;i<N;i++)
+   {
+      Fout = Fout_beg + i*mm;
+      Fout0=Fout;
+      Fout1=Fout0+m;
+      Fout2=Fout0+2*m;
+      Fout3=Fout0+3*m;
+      Fout4=Fout0+4*m;
+
+      /* For non-custom modes, m is guaranteed to be a multiple of 4. */
+      for ( u=0; u<m; ++u ) {
+         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 = ADD32_ovflw(Fout0->r, ADD32_ovflw(scratch[7].r, scratch[8].r));
+         Fout0->i = ADD32_ovflw(Fout0->i, ADD32_ovflw(scratch[7].i, scratch[8].i));
+
+         scratch[5].r = ADD32_ovflw(scratch[0].r, ADD32_ovflw(S_MUL(scratch[7].r,ya.r), S_MUL(scratch[8].r,yb.r)));
+         scratch[5].i = ADD32_ovflw(scratch[0].i, ADD32_ovflw(S_MUL(scratch[7].i,ya.r), S_MUL(scratch[8].i,yb.r)));
+
+         scratch[6].r =  ADD32_ovflw(S_MUL(scratch[10].i,ya.i), S_MUL(scratch[9].i,yb.i));
+         scratch[6].i = NEG32_ovflw(ADD32_ovflw(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 = ADD32_ovflw(scratch[0].r, ADD32_ovflw(S_MUL(scratch[7].r,yb.r), S_MUL(scratch[8].r,ya.r)));
+         scratch[11].i = ADD32_ovflw(scratch[0].i, ADD32_ovflw(S_MUL(scratch[7].i,yb.r), S_MUL(scratch[8].i,ya.r)));
+         scratch[12].r = SUB32_ovflw(S_MUL(scratch[9].i,ya.i), S_MUL(scratch[10].i,yb.i));
+         scratch[12].i = SUB32_ovflw(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;
+      }
+   }
+}
+#endif /* OVERRIDE_kf_bfly5 */
+
+
+#endif
+
+
+#ifdef CUSTOM_MODES
+
+static
+void compute_bitrev_table(
+         int Fout,
+         opus_int16 *f,
+         const size_t fstride,
+         int in_stride,
+         opus_int16 * factors,
+         const kiss_fft_state *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;
+      }
+   }
+}
+
+/*  facbuf is populated by p1,m1,p2,m2, ...
+    where
+    p[i] * m[i] = m[i-1]
+    m0 = n                  */
+static
+int kf_factor(int n,opus_int16 * facbuf)
+{
+    int p=4;
+    int i;
+    int stages=0;
+    int nbak = n;
+
+    /*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 || (opus_int32)p*(opus_int32)p > n)
+                p = n;          /* no more factors, skip to end */
+        }
+        n /= p;
+#ifdef RADIX_TWO_ONLY
+        if (p!=2 && p != 4)
+#else
+        if (p>5)
+#endif
+        {
+           return 0;
+        }
+        facbuf[2*stages] = p;
+        if (p==2 && stages > 1)
+        {
+           facbuf[2*stages] = 4;
+           facbuf[2] = 2;
+        }
+        stages++;
+    } while (n > 1);
+    n = nbak;
+    /* Reverse the order to get the radix 4 at the end, so we can use the
+       fast degenerate case. It turns out that reversing the order also
+       improves the noise behaviour. */
+    for (i=0;i<stages/2;i++)
+    {
+       int tmp;
+       tmp = facbuf[2*i];
+       facbuf[2*i] = facbuf[2*(stages-i-1)];
+       facbuf[2*(stages-i-1)] = tmp;
+    }
+    for (i=0;i<stages;i++)
+    {
+        n /= facbuf[2*i];
+        facbuf[2*i+1] = n;
+    }
+    return 1;
+}
+
+static void compute_twiddles(kiss_twiddle_cpx *twiddles, int nfft)
+{
+   int i;
+#ifdef FIXED_POINT
+   for (i=0;i<nfft;++i) {
+      opus_val32 phase = -i;
+      kf_cexp2(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(twiddles+i, phase );
+   }
+#endif
+}
+
+int opus_fft_alloc_arch_c(kiss_fft_state *st) {
+   (void)st;
+   return 0;
+}
+
+/*
+ *
+ * Allocates all necessary storage space for the fft and ifft.
+ * The return value is a contiguous block of memory.  As such,
+ * It can be freed with free().
+ * */
+kiss_fft_state *opus_fft_alloc_twiddles(int nfft,void * mem,size_t * lenmem,
+                                        const kiss_fft_state *base, int arch)
+{
+    kiss_fft_state *st=NULL;
+    size_t memneeded = sizeof(struct kiss_fft_state); /* twiddle factors*/
+
+    if ( lenmem==NULL ) {
+        st = ( kiss_fft_state*)KISS_FFT_MALLOC( memneeded );
+    }else{
+        if (mem != NULL && *lenmem >= memneeded)
+            st = (kiss_fft_state*)mem;
+        *lenmem = memneeded;
+    }
+    if (st) {
+        opus_int16 *bitrev;
+        kiss_twiddle_cpx *twiddles;
+
+        st->nfft=nfft;
+#ifdef FIXED_POINT
+        st->scale_shift = celt_ilog2(st->nfft);
+        if (st->nfft == 1<<st->scale_shift)
+           st->scale = Q15ONE;
+        else
+           st->scale = (1073741824+st->nfft/2)/st->nfft>>(15-st->scale_shift);
+#else
+        st->scale = 1.f/nfft;
+#endif
+        if (base != NULL)
+        {
+           st->twiddles = base->twiddles;
+           st->shift = 0;
+           while (st->shift < 32 && nfft<<st->shift != base->nfft)
+              st->shift++;
+           if (st->shift>=32)
+              goto fail;
+        } else {
+           st->twiddles = twiddles = (kiss_twiddle_cpx*)KISS_FFT_MALLOC(sizeof(kiss_twiddle_cpx)*nfft);
+           compute_twiddles(twiddles, nfft);
+           st->shift = -1;
+        }
+        if (!kf_factor(nfft,st->factors))
+        {
+           goto fail;
+        }
+
+        /* bitrev */
+        st->bitrev = bitrev = (opus_int16*)KISS_FFT_MALLOC(sizeof(opus_int16)*nfft);
+        if (st->bitrev==NULL)
+            goto fail;
+        compute_bitrev_table(0, bitrev, 1,1, st->factors,st);
+
+        /* Initialize architecture specific fft parameters */
+        if (opus_fft_alloc_arch(st, arch))
+            goto fail;
+    }
+    return st;
+fail:
+    opus_fft_free(st, arch);
+    return NULL;
+}
+
+kiss_fft_state *opus_fft_alloc(int nfft,void * mem,size_t * lenmem, int arch)
+{
+   return opus_fft_alloc_twiddles(nfft, mem, lenmem, NULL, arch);
+}
+
+void opus_fft_free_arch_c(kiss_fft_state *st) {
+   (void)st;
+}
+
+void opus_fft_free(const kiss_fft_state *cfg, int arch)
+{
+   if (cfg)
+   {
+      opus_fft_free_arch((kiss_fft_state *)cfg, arch);
+      opus_free((opus_int16*)cfg->bitrev);
+      if (cfg->shift < 0)
+         opus_free((kiss_twiddle_cpx*)cfg->twiddles);
+      opus_free((kiss_fft_state*)cfg);
+   }
+}
+
+#endif /* CUSTOM_MODES */
+
+void opus_fft_impl(const kiss_fft_state *st,kiss_fft_cpx *fout)
+{
+    int m2, m;
+    int p;
+    int L;
+    int fstride[MAXFACTORS];
+    int i;
+    int shift;
+
+    /* st->shift can be -1 */
+    shift = st->shift>0 ? st->shift : 0;
+
+    fstride[0] = 1;
+    L=0;
+    do {
+       p = st->factors[2*L];
+       m = st->factors[2*L+1];
+       fstride[L+1] = fstride[L]*p;
+       L++;
+    } while(m!=1);
+    m = st->factors[2*L-1];
+    for (i=L-1;i>=0;i--)
+    {
+       if (i!=0)
+          m2 = st->factors[2*i-1];
+       else
+          m2 = 1;
+       switch (st->factors[2*i])
+       {
+       case 2:
+          kf_bfly2(fout, m, fstride[i]);
+          break;
+       case 4:
+          kf_bfly4(fout,fstride[i]<<shift,st,m, fstride[i], m2);
+          break;
+ #ifndef RADIX_TWO_ONLY
+       case 3:
+          kf_bfly3(fout,fstride[i]<<shift,st,m, fstride[i], m2);
+          break;
+       case 5:
+          kf_bfly5(fout,fstride[i]<<shift,st,m, fstride[i], m2);
+          break;
+ #endif
+       }
+       m = m2;
+    }
+}
+
+void opus_fft_c(const kiss_fft_state *st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
+{
+   int i;
+   opus_val16 scale;
+#ifdef FIXED_POINT
+   /* Allows us to scale with MULT16_32_Q16(), which is faster than
+      MULT16_32_Q15() on ARM. */
+   int scale_shift = st->scale_shift-1;
+#endif
+   scale = st->scale;
+
+   celt_assert2 (fin != fout, "In-place FFT not supported");
+   /* Bit-reverse the input */
+   for (i=0;i<st->nfft;i++)
+   {
+      kiss_fft_cpx x = fin[i];
+      fout[st->bitrev[i]].r = SHR32(MULT16_32_Q16(scale, x.r), scale_shift);
+      fout[st->bitrev[i]].i = SHR32(MULT16_32_Q16(scale, x.i), scale_shift);
+   }
+   opus_fft_impl(st, fout);
+}
+
+
+void opus_ifft_c(const kiss_fft_state *st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
+{
+   int i;
+   celt_assert2 (fin != fout, "In-place FFT not supported");
+   /* Bit-reverse the input */
+   for (i=0;i<st->nfft;i++)
+      fout[st->bitrev[i]] = fin[i];
+   for (i=0;i<st->nfft;i++)
+      fout[i].i = -fout[i].i;
+   opus_fft_impl(st, fout);
+   for (i=0;i<st->nfft;i++)
+      fout[i].i = -fout[i].i;
+}
diff --git a/opus/celt/kiss_fft.h b/opus/celt/kiss_fft.h
new file mode 100644 (file)
index 0000000..bffa2bf
--- /dev/null
@@ -0,0 +1,200 @@
+/*Copyright (c) 2003-2004, Mark Borgerding
+  Lots of modifications by Jean-Marc Valin
+  Copyright (c) 2005-2007, Xiph.Org Foundation
+  Copyright (c) 2008,      Xiph.Org Foundation, 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.
+
+  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"
+#include "cpu_support.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef USE_SIMD
+# include <xmmintrin.h>
+# define kiss_fft_scalar __m128
+#define KISS_FFT_MALLOC(nbytes) memalign(16,nbytes)
+#else
+#define KISS_FFT_MALLOC opus_alloc
+#endif
+
+#ifdef FIXED_POINT
+#include "arch.h"
+
+#  define kiss_fft_scalar opus_int32
+#  define kiss_twiddle_scalar opus_int16
+
+
+#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
+
+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;
+
+#define MAXFACTORS 8
+/* e.g. an fft of length 128 has 4 factors
+ as far as kissfft is concerned
+ 4*4*4*2
+ */
+
+typedef struct arch_fft_state{
+   int is_supported;
+   void *priv;
+} arch_fft_state;
+
+typedef struct kiss_fft_state{
+    int nfft;
+    opus_val16 scale;
+#ifdef FIXED_POINT
+    int scale_shift;
+#endif
+    int shift;
+    opus_int16 factors[2*MAXFACTORS];
+    const opus_int16 *bitrev;
+    const kiss_twiddle_cpx *twiddles;
+    arch_fft_state *arch_fft;
+} kiss_fft_state;
+
+#if defined(HAVE_ARM_NE10)
+#include "arm/fft_arm.h"
+#endif
+
+/*typedef struct kiss_fft_state* kiss_fft_cfg;*/
+
+/**
+ *  opus_fft_alloc
+ *
+ *  Initialize a FFT (or IFFT) algorithm's cfg/state buffer.
+ *
+ *  typical usage:      kiss_fft_cfg mycfg=opus_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 opus_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_state *opus_fft_alloc_twiddles(int nfft,void * mem,size_t * lenmem, const kiss_fft_state *base, int arch);
+
+kiss_fft_state *opus_fft_alloc(int nfft,void * mem,size_t * lenmem, int arch);
+
+/**
+ * opus_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 opus_fft_c(const kiss_fft_state *cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
+void opus_ifft_c(const kiss_fft_state *cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
+
+void opus_fft_impl(const kiss_fft_state *st,kiss_fft_cpx *fout);
+void opus_ifft_impl(const kiss_fft_state *st,kiss_fft_cpx *fout);
+
+void opus_fft_free(const kiss_fft_state *cfg, int arch);
+
+
+void opus_fft_free_arch_c(kiss_fft_state *st);
+int opus_fft_alloc_arch_c(kiss_fft_state *st);
+
+#if !defined(OVERRIDE_OPUS_FFT)
+/* Is run-time CPU detection enabled on this platform? */
+#if defined(OPUS_HAVE_RTCD) && (defined(HAVE_ARM_NE10))
+
+extern int (*const OPUS_FFT_ALLOC_ARCH_IMPL[OPUS_ARCHMASK+1])(
+ kiss_fft_state *st);
+
+#define opus_fft_alloc_arch(_st, arch) \
+         ((*OPUS_FFT_ALLOC_ARCH_IMPL[(arch)&OPUS_ARCHMASK])(_st))
+
+extern void (*const OPUS_FFT_FREE_ARCH_IMPL[OPUS_ARCHMASK+1])(
+ kiss_fft_state *st);
+#define opus_fft_free_arch(_st, arch) \
+         ((*OPUS_FFT_FREE_ARCH_IMPL[(arch)&OPUS_ARCHMASK])(_st))
+
+extern void (*const OPUS_FFT[OPUS_ARCHMASK+1])(const kiss_fft_state *cfg,
+ const kiss_fft_cpx *fin, kiss_fft_cpx *fout);
+#define opus_fft(_cfg, _fin, _fout, arch) \
+   ((*OPUS_FFT[(arch)&OPUS_ARCHMASK])(_cfg, _fin, _fout))
+
+extern void (*const OPUS_IFFT[OPUS_ARCHMASK+1])(const kiss_fft_state *cfg,
+ const kiss_fft_cpx *fin, kiss_fft_cpx *fout);
+#define opus_ifft(_cfg, _fin, _fout, arch) \
+   ((*OPUS_IFFT[(arch)&OPUS_ARCHMASK])(_cfg, _fin, _fout))
+
+#else /* else for if defined(OPUS_HAVE_RTCD) && (defined(HAVE_ARM_NE10)) */
+
+#define opus_fft_alloc_arch(_st, arch) \
+         ((void)(arch), opus_fft_alloc_arch_c(_st))
+
+#define opus_fft_free_arch(_st, arch) \
+         ((void)(arch), opus_fft_free_arch_c(_st))
+
+#define opus_fft(_cfg, _fin, _fout, arch) \
+         ((void)(arch), opus_fft_c(_cfg, _fin, _fout))
+
+#define opus_ifft(_cfg, _fin, _fout, arch) \
+         ((void)(arch), opus_ifft_c(_cfg, _fin, _fout))
+
+#endif /* end if defined(OPUS_HAVE_RTCD) && (defined(HAVE_ARM_NE10)) */
+#endif /* end if !defined(OVERRIDE_OPUS_FFT) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/celt/laplace.c b/opus/celt/laplace.c
new file mode 100644 (file)
index 0000000..a7bca87
--- /dev/null
@@ -0,0 +1,134 @@
+/* Copyright (c) 2007 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "laplace.h"
+#include "mathops.h"
+
+/* The minimum probability of an energy delta (out of 32768). */
+#define LAPLACE_LOG_MINP (0)
+#define LAPLACE_MINP (1<<LAPLACE_LOG_MINP)
+/* The minimum number of guaranteed representable energy deltas (in one
+    direction). */
+#define LAPLACE_NMIN (16)
+
+/* When called, decay is positive and at most 11456. */
+static unsigned ec_laplace_get_freq1(unsigned fs0, int decay)
+{
+   unsigned ft;
+   ft = 32768 - LAPLACE_MINP*(2*LAPLACE_NMIN) - fs0;
+   return ft*(opus_int32)(16384-decay)>>15;
+}
+
+void ec_laplace_encode(ec_enc *enc, int *value, unsigned fs, int decay)
+{
+   unsigned fl;
+   int val = *value;
+   fl = 0;
+   if (val)
+   {
+      int s;
+      int i;
+      s = -(val<0);
+      val = (val+s)^s;
+      fl = fs;
+      fs = ec_laplace_get_freq1(fs, decay);
+      /* Search the decaying part of the PDF.*/
+      for (i=1; fs > 0 && i < val; i++)
+      {
+         fs *= 2;
+         fl += fs+2*LAPLACE_MINP;
+         fs = (fs*(opus_int32)decay)>>15;
+      }
+      /* Everything beyond that has probability LAPLACE_MINP. */
+      if (!fs)
+      {
+         int di;
+         int ndi_max;
+         ndi_max = (32768-fl+LAPLACE_MINP-1)>>LAPLACE_LOG_MINP;
+         ndi_max = (ndi_max-s)>>1;
+         di = IMIN(val - i, ndi_max - 1);
+         fl += (2*di+1+s)*LAPLACE_MINP;
+         fs = IMIN(LAPLACE_MINP, 32768-fl);
+         *value = (i+di+s)^s;
+      }
+      else
+      {
+         fs += LAPLACE_MINP;
+         fl += fs&~s;
+      }
+      celt_assert(fl+fs<=32768);
+      celt_assert(fs>0);
+   }
+   ec_encode_bin(enc, fl, fl+fs, 15);
+}
+
+int ec_laplace_decode(ec_dec *dec, unsigned fs, int decay)
+{
+   int val=0;
+   unsigned fl;
+   unsigned fm;
+   fm = ec_decode_bin(dec, 15);
+   fl = 0;
+   if (fm >= fs)
+   {
+      val++;
+      fl = fs;
+      fs = ec_laplace_get_freq1(fs, decay)+LAPLACE_MINP;
+      /* Search the decaying part of the PDF.*/
+      while(fs > LAPLACE_MINP && fm >= fl+2*fs)
+      {
+         fs *= 2;
+         fl += fs;
+         fs = ((fs-2*LAPLACE_MINP)*(opus_int32)decay)>>15;
+         fs += LAPLACE_MINP;
+         val++;
+      }
+      /* Everything beyond that has probability LAPLACE_MINP. */
+      if (fs <= LAPLACE_MINP)
+      {
+         int di;
+         di = (fm-fl)>>(LAPLACE_LOG_MINP+1);
+         val += di;
+         fl += 2*di*LAPLACE_MINP;
+      }
+      if (fm < fl+fs)
+         val = -val;
+      else
+         fl += fs;
+   }
+   celt_assert(fl<32768);
+   celt_assert(fs>0);
+   celt_assert(fl<=fm);
+   celt_assert(fm<IMIN(fl+fs,32768));
+   ec_dec_update(dec, fl, IMIN(fl+fs,32768), 32768);
+   return val;
+}
diff --git a/opus/celt/laplace.h b/opus/celt/laplace.h
new file mode 100644 (file)
index 0000000..46c14b5
--- /dev/null
@@ -0,0 +1,48 @@
+/* Copyright (c) 2007 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#include "entenc.h"
+#include "entdec.h"
+
+/** 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 fs Probability of 0, multiplied by 32768
+ @param decay Probability of the value +/- 1, multiplied by 16384
+*/
+void ec_laplace_encode(ec_enc *enc, int *value, unsigned fs, int decay);
+
+/** Decode a value that is assumed to be the realisation of a
+    Laplace-distributed random process
+ @param dec Entropy decoder state
+ @param fs Probability of 0, multiplied by 32768
+ @param decay Probability of the value +/- 1, multiplied by 16384
+ @return Value decoded
+ */
+int ec_laplace_decode(ec_dec *dec, unsigned fs, int decay);
diff --git a/opus/celt/mathops.c b/opus/celt/mathops.c
new file mode 100644 (file)
index 0000000..21a01f5
--- /dev/null
@@ -0,0 +1,208 @@
+/* Copyright (c) 2002-2008 Jean-Marc Valin
+   Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "mathops.h"
+
+/*Compute floor(sqrt(_val)) with exact arithmetic.
+  This has been tested on all possible 32-bit inputs.*/
+unsigned isqrt32(opus_uint32 _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{
+    opus_uint32 t;
+    t=(((opus_uint32)g<<1)+b)<<bshift;
+    if(t<=_val){
+      g+=b;
+      _val-=t;
+    }
+    b>>=1;
+    bshift--;
+  }
+  while(bshift>=0);
+  return g;
+}
+
+#ifdef FIXED_POINT
+
+opus_val32 frac_div32(opus_val32 a, opus_val32 b)
+{
+   opus_val16 rcp;
+   opus_val32 result, rem;
+   int shift = celt_ilog2(b)-29;
+   a = VSHR32(a,shift);
+   b = VSHR32(b,shift);
+   /* 16-bit reciprocal */
+   rcp = ROUND16(celt_rcp(ROUND16(b,16)),3);
+   result = MULT16_32_Q15(rcp, a);
+   rem = PSHR32(a,2)-MULT32_32_Q31(result, b);
+   result = ADD32(result, SHL32(MULT16_32_Q15(rcp, rem),2));
+   if (result >= 536870912)       /*  2^29 */
+      return 2147483647;          /*  2^31 - 1 */
+   else if (result <= -536870912) /* -2^29 */
+      return -2147483647;         /* -2^31 */
+   else
+      return SHL32(result, 2);
+}
+
+/** Reciprocal sqrt approximation in the range [0.25,1) (Q16 in, Q14 out) */
+opus_val16 celt_rsqrt_norm(opus_val32 x)
+{
+   opus_val16 n;
+   opus_val16 r;
+   opus_val16 r2;
+   opus_val16 y;
+   /* Range of n is [-16384,32767] ([-0.5,1) in Q15). */
+   n = x-32768;
+   /* Get a rough initial guess for the root.
+      The optimal minimax quadratic approximation (using relative error) is
+       r = 1.437799046117536+n*(-0.823394375837328+n*0.4096419668459485).
+      Coefficients here, and the final result r, are Q14.*/
+   r = ADD16(23557, MULT16_16_Q15(n, ADD16(-13490, MULT16_16_Q15(n, 6713))));
+   /* We want y = x*r*r-1 in Q15, but x is 32-bit Q16 and r is Q14.
+      We can compute the result from n and r using Q15 multiplies with some
+       adjustment, carefully done to avoid overflow.
+      Range of y is [-1564,1594]. */
+   r2 = MULT16_16_Q15(r, r);
+   y = SHL16(SUB16(ADD16(MULT16_16_Q15(r2, n), r2), 16384), 1);
+   /* Apply a 2nd-order Householder iteration: r += r*y*(y*0.375-0.5).
+      This yields the Q14 reciprocal square root of the Q16 x, with a maximum
+       relative error of 1.04956E-4, a (relative) RMSE of 2.80979E-5, and a
+       peak absolute error of 2.26591/16384. */
+   return ADD16(r, MULT16_16_Q15(r, MULT16_16_Q15(y,
+              SUB16(MULT16_16_Q15(y, 12288), 16384))));
+}
+
+/** Sqrt approximation (QX input, QX/2 output) */
+opus_val32 celt_sqrt(opus_val32 x)
+{
+   int k;
+   opus_val16 n;
+   opus_val32 rt;
+   static const opus_val16 C[5] = {23175, 11561, -3011, 1699, -664};
+   if (x==0)
+      return 0;
+   else if (x>=1073741824)
+      return 32767;
+   k = (celt_ilog2(x)>>1)-7;
+   x = VSHR32(x, 2*k);
+   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 OPUS_INLINE opus_val16 _celt_cos_pi_2(opus_val16 x)
+{
+   opus_val16 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
+
+opus_val16 celt_cos_norm(opus_val32 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 NEG16(_celt_cos_pi_2(EXTRACT16(65536-x)));
+      }
+   } else {
+      if (x&0x0000ffff)
+         return 0;
+      else if (x&0x0001ffff)
+         return -32767;
+      else
+         return 32767;
+   }
+}
+
+/** Reciprocal approximation (Q15 input, Q16 output) */
+opus_val32 celt_rcp(opus_val32 x)
+{
+   int i;
+   opus_val16 n;
+   opus_val16 r;
+   celt_assert2(x>0, "celt_rcp() only defined for positive values");
+   i = celt_ilog2(x);
+   /* n is Q15 with range [0,1). */
+   n = VSHR32(x,i-15)-32768;
+   /* Start with a linear approximation:
+      r = 1.8823529411764706-0.9411764705882353*n.
+      The coefficients and the result are Q14 in the range [15420,30840].*/
+   r = ADD16(30840, MULT16_16_Q15(-15420, n));
+   /* Perform two Newton iterations:
+      r -= r*((r*n)-1.Q15)
+         = r*((r*n)+(r-1.Q15)). */
+   r = SUB16(r, MULT16_16_Q15(r,
+             ADD16(MULT16_16_Q15(r, n), ADD16(r, -32768))));
+   /* We subtract an extra 1 in the second iteration to avoid overflow; it also
+       neatly compensates for truncation error in the rest of the process. */
+   r = SUB16(r, ADD16(1, MULT16_16_Q15(r,
+             ADD16(MULT16_16_Q15(r, n), ADD16(r, -32768)))));
+   /* r is now the Q15 solution to 2/(n+1), with a maximum relative error
+       of 7.05346E-5, a (relative) RMSE of 2.14418E-5, and a peak absolute
+       error of 1.24665/32768. */
+   return VSHR32(EXTEND32(r),i-16);
+}
+
+#endif
diff --git a/opus/celt/mathops.h b/opus/celt/mathops.h
new file mode 100644 (file)
index 0000000..1f8a20c
--- /dev/null
@@ -0,0 +1,290 @@
+/* Copyright (c) 2002-2008 Jean-Marc Valin
+   Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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 MATHOPS_H
+#define MATHOPS_H
+
+#include "arch.h"
+#include "entcode.h"
+#include "os_support.h"
+
+#define PI 3.141592653f
+
+/* Multiplies two 16-bit fractional values. Bit-exactness of this macro is important */
+#define FRAC_MUL16(a,b) ((16384+((opus_int32)(opus_int16)(a)*(opus_int16)(b)))>>15)
+
+unsigned isqrt32(opus_uint32 _val);
+
+/* CELT doesn't need it for fixed-point, by analysis.c does. */
+#if !defined(FIXED_POINT) || defined(ANALYSIS_C)
+#define cA 0.43157974f
+#define cB 0.67848403f
+#define cC 0.08595542f
+#define cE ((float)PI/2)
+static OPUS_INLINE float fast_atan2f(float y, float x) {
+   float x2, y2;
+   x2 = x*x;
+   y2 = y*y;
+   /* For very small values, we don't care about the answer, so
+      we can just return 0. */
+   if (x2 + y2 < 1e-18f)
+   {
+      return 0;
+   }
+   if(x2<y2){
+      float den = (y2 + cB*x2) * (y2 + cC*x2);
+      return -x*y*(y2 + cA*x2) / den + (y<0 ? -cE : cE);
+   }else{
+      float den = (x2 + cB*y2) * (x2 + cC*y2);
+      return  x*y*(x2 + cA*y2) / den + (y<0 ? -cE : cE) - (x*y<0 ? -cE : cE);
+   }
+}
+#undef cA
+#undef cB
+#undef cC
+#undef cD
+#endif
+
+
+#ifndef OVERRIDE_CELT_MAXABS16
+static OPUS_INLINE opus_val32 celt_maxabs16(const opus_val16 *x, int len)
+{
+   int i;
+   opus_val16 maxval = 0;
+   opus_val16 minval = 0;
+   for (i=0;i<len;i++)
+   {
+      maxval = MAX16(maxval, x[i]);
+      minval = MIN16(minval, x[i]);
+   }
+   return MAX32(EXTEND32(maxval),-EXTEND32(minval));
+}
+#endif
+
+#ifndef OVERRIDE_CELT_MAXABS32
+#ifdef FIXED_POINT
+static OPUS_INLINE opus_val32 celt_maxabs32(const opus_val32 *x, int len)
+{
+   int i;
+   opus_val32 maxval = 0;
+   opus_val32 minval = 0;
+   for (i=0;i<len;i++)
+   {
+      maxval = MAX32(maxval, x[i]);
+      minval = MIN32(minval, x[i]);
+   }
+   return MAX32(maxval, -minval);
+}
+#else
+#define celt_maxabs32(x,len) celt_maxabs16(x,len)
+#endif
+#endif
+
+
+#ifndef FIXED_POINT
+
+#define celt_sqrt(x) ((float)sqrt(x))
+#define celt_rsqrt(x) (1.f/celt_sqrt(x))
+#define celt_rsqrt_norm(x) (celt_rsqrt(x))
+#define celt_cos_norm(x) ((float)cos((.5f*PI)*(x)))
+#define celt_rcp(x) (1.f/(x))
+#define celt_div(a,b) ((a)/(b))
+#define frac_div32(a,b) ((float)(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 OPUS_INLINE float celt_log2(float x)
+{
+   int integer;
+   float frac;
+   union {
+      float f;
+      opus_uint32 i;
+   } in;
+   in.f = x;
+   integer = (in.i>>23)-127;
+   in.i -= integer<<23;
+   frac = in.f - 1.5f;
+   frac = -0.41445418f + frac*(0.95909232f
+          + frac*(-0.33951290f + frac*0.16541097f));
+   return 1+integer+frac;
+}
+
+/** Base-2 exponential approximation (2^x). */
+static OPUS_INLINE float celt_exp2(float x)
+{
+   int integer;
+   float frac;
+   union {
+      float f;
+      opus_uint32 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 = 0.99992522f + frac * (0.69583354f
+           + frac * (0.22606716f + 0.078024523f*frac));
+   res.i = (res.i + (integer<<23)) & 0x7fffffff;
+   return res.f;
+}
+
+#else
+#define celt_log2(x) ((float)(1.442695040888963387*log(x)))
+#define celt_exp2(x) ((float)exp(0.6931471805599453094*(x)))
+#endif
+
+#endif
+
+#ifdef FIXED_POINT
+
+#include "os_support.h"
+
+#ifndef OVERRIDE_CELT_ILOG2
+/** Integer log in base2. Undefined for zero and negative numbers */
+static OPUS_INLINE opus_int16 celt_ilog2(opus_int32 x)
+{
+   celt_assert2(x>0, "celt_ilog2() only defined for strictly positive numbers");
+   return EC_ILOG(x)-1;
+}
+#endif
+
+
+/** Integer log in base2. Defined for zero, but not for negative numbers */
+static OPUS_INLINE opus_int16 celt_zlog2(opus_val32 x)
+{
+   return x <= 0 ? 0 : celt_ilog2(x);
+}
+
+opus_val16 celt_rsqrt_norm(opus_val32 x);
+
+opus_val32 celt_sqrt(opus_val32 x);
+
+opus_val16 celt_cos_norm(opus_val32 x);
+
+/** Base-2 logarithm approximation (log2(x)). (Q14 input, Q10 output) */
+static OPUS_INLINE opus_val16 celt_log2(opus_val32 x)
+{
+   int i;
+   opus_val16 n, frac;
+   /* -0.41509302963303146, 0.9609890551383969, -0.31836011537636605,
+       0.15530808010959576, -0.08556153059057618 */
+   static const opus_val16 C[5] = {-6801+(1<<(13-DB_SHIFT)), 15746, -5217, 2545, -1401};
+   if (x==0)
+      return -32767;
+   i = celt_ilog2(x);
+   n = VSHR32(x,i-15)-32768-16384;
+   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 SHL16(i-13,DB_SHIFT)+SHR16(frac,14-DB_SHIFT);
+}
+
+/*
+ K0 = 1
+ K1 = log(2)
+ K2 = 3-4*log(2)
+ K3 = 3*log(2) - 2
+*/
+#define D0 16383
+#define D1 22804
+#define D2 14819
+#define D3 10204
+
+static OPUS_INLINE opus_val32 celt_exp2_frac(opus_val16 x)
+{
+   opus_val16 frac;
+   frac = SHL16(x, 4);
+   return ADD16(D0, MULT16_16_Q15(frac, ADD16(D1, MULT16_16_Q15(frac, ADD16(D2 , MULT16_16_Q15(D3,frac))))));
+}
+/** Base-2 exponential approximation (2^x). (Q10 input, Q16 output) */
+static OPUS_INLINE opus_val32 celt_exp2(opus_val16 x)
+{
+   int integer;
+   opus_val16 frac;
+   integer = SHR16(x,10);
+   if (integer>14)
+      return 0x7f000000;
+   else if (integer < -15)
+      return 0;
+   frac = celt_exp2_frac(x-SHL16(integer,10));
+   return VSHR32(EXTEND32(frac), -integer-2);
+}
+
+opus_val32 celt_rcp(opus_val32 x);
+
+#define celt_div(a,b) MULT32_32_Q31((opus_val32)(a),celt_rcp(b))
+
+opus_val32 frac_div32(opus_val32 a, opus_val32 b);
+
+#define M1 32767
+#define M2 -21
+#define M3 -11943
+#define M4 4936
+
+/* Atan approximation using a 4th order polynomial. Input is in Q15 format
+   and normalized by pi/4. Output is in Q15 format */
+static OPUS_INLINE opus_val16 celt_atan01(opus_val16 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
+
+/* atan2() approximation valid for positive input values */
+static OPUS_INLINE opus_val16 celt_atan2p(opus_val16 y, opus_val16 x)
+{
+   if (y < x)
+   {
+      opus_val32 arg;
+      arg = celt_div(SHL32(EXTEND32(y),15),x);
+      if (arg >= 32767)
+         arg = 32767;
+      return SHR16(celt_atan01(EXTRACT16(arg)),1);
+   } else {
+      opus_val32 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 */
diff --git a/opus/celt/mdct.c b/opus/celt/mdct.c
new file mode 100644 (file)
index 0000000..5c6dab5
--- /dev/null
@@ -0,0 +1,343 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2008 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+/* 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 SKIP_CONFIG_H
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#endif
+
+#include "mdct.h"
+#include "kiss_fft.h"
+#include "_kiss_fft_guts.h"
+#include <math.h>
+#include "os_support.h"
+#include "mathops.h"
+#include "stack_alloc.h"
+
+#if defined(MIPSr1_ASM)
+#include "mips/mdct_mipsr1.h"
+#endif
+
+
+#ifdef CUSTOM_MODES
+
+int clt_mdct_init(mdct_lookup *l,int N, int maxshift, int arch)
+{
+   int i;
+   kiss_twiddle_scalar *trig;
+   int shift;
+   int N2=N>>1;
+   l->n = N;
+   l->maxshift = maxshift;
+   for (i=0;i<=maxshift;i++)
+   {
+      if (i==0)
+         l->kfft[i] = opus_fft_alloc(N>>2>>i, 0, 0, arch);
+      else
+         l->kfft[i] = opus_fft_alloc_twiddles(N>>2>>i, 0, 0, l->kfft[0], arch);
+#ifndef ENABLE_TI_DSPLIB55
+      if (l->kfft[i]==NULL)
+         return 0;
+#endif
+   }
+   l->trig = trig = (kiss_twiddle_scalar*)opus_alloc((N-(N2>>maxshift))*sizeof(kiss_twiddle_scalar));
+   if (l->trig==NULL)
+     return 0;
+   for (shift=0;shift<=maxshift;shift++)
+   {
+      /* We have enough points that sine isn't necessary */
+#if defined(FIXED_POINT)
+#if 1
+      for (i=0;i<N2;i++)
+         trig[i] = TRIG_UPSCALE*celt_cos_norm(DIV32(ADD32(SHL32(EXTEND32(i),17),N2+16384),N));
+#else
+      for (i=0;i<N2;i++)
+         trig[i] = (kiss_twiddle_scalar)MAX32(-32767,MIN32(32767,floor(.5+32768*cos(2*M_PI*(i+.125)/N))));
+#endif
+#else
+      for (i=0;i<N2;i++)
+         trig[i] = (kiss_twiddle_scalar)cos(2*PI*(i+.125)/N);
+#endif
+      trig += N2;
+      N2 >>= 1;
+      N >>= 1;
+   }
+   return 1;
+}
+
+void clt_mdct_clear(mdct_lookup *l, int arch)
+{
+   int i;
+   for (i=0;i<=l->maxshift;i++)
+      opus_fft_free(l->kfft[i], arch);
+   opus_free((kiss_twiddle_scalar*)l->trig);
+}
+
+#endif /* CUSTOM_MODES */
+
+/* Forward MDCT trashes the input array */
+#ifndef OVERRIDE_clt_mdct_forward
+void clt_mdct_forward_c(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
+      const opus_val16 *window, int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   VARDECL(kiss_fft_scalar, f);
+   VARDECL(kiss_fft_cpx, f2);
+   const kiss_fft_state *st = l->kfft[shift];
+   const kiss_twiddle_scalar *trig;
+   opus_val16 scale;
+#ifdef FIXED_POINT
+   /* Allows us to scale with MULT16_32_Q16(), which is faster than
+      MULT16_32_Q15() on ARM. */
+   int scale_shift = st->scale_shift-1;
+#endif
+   SAVE_STACK;
+   (void)arch;
+   scale = st->scale;
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   ALLOC(f, N2, kiss_fft_scalar);
+   ALLOC(f2, N4, kiss_fft_cpx);
+
+   /* Consider the input to be composed 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 * OPUS_RESTRICT xp1 = in+(overlap>>1);
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+N2-1+(overlap>>1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = f;
+      const opus_val16 * OPUS_RESTRICT wp1 = window+(overlap>>1);
+      const opus_val16 * OPUS_RESTRICT wp2 = window+(overlap>>1)-1;
+      for(i=0;i<((overlap+3)>>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+3)>>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 * OPUS_RESTRICT yp = f;
+      const kiss_twiddle_scalar *t = &trig[0];
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_cpx yc;
+         kiss_twiddle_scalar t0, t1;
+         kiss_fft_scalar re, im, yr, yi;
+         t0 = t[i];
+         t1 = t[N4+i];
+         re = *yp++;
+         im = *yp++;
+         yr = S_MUL(re,t0)  -  S_MUL(im,t1);
+         yi = S_MUL(im,t0)  +  S_MUL(re,t1);
+         yc.r = yr;
+         yc.i = yi;
+         yc.r = PSHR32(MULT16_32_Q16(scale, yc.r), scale_shift);
+         yc.i = PSHR32(MULT16_32_Q16(scale, yc.i), scale_shift);
+         f2[st->bitrev[i]] = yc;
+      }
+   }
+
+   /* N/4 complex FFT, does not downscale anymore */
+   opus_fft_impl(st, f2);
+
+   /* Post-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_cpx * OPUS_RESTRICT fp = f2;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      kiss_fft_scalar * OPUS_RESTRICT yp2 = out+stride*(N2-1);
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_scalar yr, yi;
+         yr = S_MUL(fp->i,t[N4+i]) - S_MUL(fp->r,t[i]);
+         yi = S_MUL(fp->r,t[N4+i]) + S_MUL(fp->i,t[i]);
+         *yp1 = yr;
+         *yp2 = yi;
+         fp++;
+         yp1 += 2*stride;
+         yp2 -= 2*stride;
+      }
+   }
+   RESTORE_STACK;
+}
+#endif /* OVERRIDE_clt_mdct_forward */
+
+#ifndef OVERRIDE_clt_mdct_backward
+void clt_mdct_backward_c(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
+      const opus_val16 * OPUS_RESTRICT window, int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   const kiss_twiddle_scalar *trig;
+   (void) arch;
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   /* Pre-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_scalar * OPUS_RESTRICT xp1 = in;
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+stride*(N2-1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = out+(overlap>>1);
+      const kiss_twiddle_scalar * OPUS_RESTRICT t = &trig[0];
+      const opus_int16 * OPUS_RESTRICT bitrev = l->kfft[shift]->bitrev;
+      for(i=0;i<N4;i++)
+      {
+         int rev;
+         kiss_fft_scalar yr, yi;
+         rev = *bitrev++;
+         yr = ADD32_ovflw(S_MUL(*xp2, t[i]), S_MUL(*xp1, t[N4+i]));
+         yi = SUB32_ovflw(S_MUL(*xp1, t[i]), S_MUL(*xp2, t[N4+i]));
+         /* We swap real and imag because we use an FFT instead of an IFFT. */
+         yp[2*rev+1] = yr;
+         yp[2*rev] = yi;
+         /* Storing the pre-rotation directly in the bitrev order. */
+         xp1+=2*stride;
+         xp2-=2*stride;
+      }
+   }
+
+   opus_fft_impl(l->kfft[shift], (kiss_fft_cpx*)(out+(overlap>>1)));
+
+   /* Post-rotate and de-shuffle from both ends of the buffer at once to make
+      it in-place. */
+   {
+      kiss_fft_scalar * yp0 = out+(overlap>>1);
+      kiss_fft_scalar * yp1 = out+(overlap>>1)+N2-2;
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Loop to (N4+1)>>1 to handle odd N4. When N4 is odd, the
+         middle pair will be computed twice. */
+      for(i=0;i<(N4+1)>>1;i++)
+      {
+         kiss_fft_scalar re, im, yr, yi;
+         kiss_twiddle_scalar t0, t1;
+         /* We swap real and imag because we're using an FFT instead of an IFFT. */
+         re = yp0[1];
+         im = yp0[0];
+         t0 = t[i];
+         t1 = t[N4+i];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = ADD32_ovflw(S_MUL(re,t0), S_MUL(im,t1));
+         yi = SUB32_ovflw(S_MUL(re,t1), S_MUL(im,t0));
+         /* We swap real and imag because we're using an FFT instead of an IFFT. */
+         re = yp1[1];
+         im = yp1[0];
+         yp0[0] = yr;
+         yp1[1] = yi;
+
+         t0 = t[(N4-i-1)];
+         t1 = t[(N2-i-1)];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = ADD32_ovflw(S_MUL(re,t0), S_MUL(im,t1));
+         yi = SUB32_ovflw(S_MUL(re,t1), S_MUL(im,t0));
+         yp1[0] = yr;
+         yp0[1] = yi;
+         yp0 += 2;
+         yp1 -= 2;
+      }
+   }
+
+   /* Mirror on both sides for TDAC */
+   {
+      kiss_fft_scalar * OPUS_RESTRICT xp1 = out+overlap-1;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      const opus_val16 * OPUS_RESTRICT wp1 = window;
+      const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
+
+      for(i = 0; i < overlap/2; i++)
+      {
+         kiss_fft_scalar x1, x2;
+         x1 = *xp1;
+         x2 = *yp1;
+         *yp1++ = SUB32_ovflw(MULT16_32_Q15(*wp2, x2), MULT16_32_Q15(*wp1, x1));
+         *xp1-- = ADD32_ovflw(MULT16_32_Q15(*wp1, x2), MULT16_32_Q15(*wp2, x1));
+         wp1++;
+         wp2--;
+      }
+   }
+}
+#endif /* OVERRIDE_clt_mdct_backward */
diff --git a/opus/celt/mdct.h b/opus/celt/mdct.h
new file mode 100644 (file)
index 0000000..160ae4e
--- /dev/null
@@ -0,0 +1,112 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2008 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+/* 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 "opus_defines.h"
+#include "kiss_fft.h"
+#include "arch.h"
+
+typedef struct {
+   int n;
+   int maxshift;
+   const kiss_fft_state *kfft[4];
+   const kiss_twiddle_scalar * OPUS_RESTRICT trig;
+} mdct_lookup;
+
+#if defined(HAVE_ARM_NE10)
+#include "arm/mdct_arm.h"
+#endif
+
+
+int clt_mdct_init(mdct_lookup *l,int N, int maxshift, int arch);
+void clt_mdct_clear(mdct_lookup *l, int arch);
+
+/** Compute a forward MDCT and scale by 4/N, trashes the input array */
+void clt_mdct_forward_c(const mdct_lookup *l, kiss_fft_scalar *in,
+                        kiss_fft_scalar * OPUS_RESTRICT out,
+                        const opus_val16 *window, int overlap,
+                        int shift, int stride, int arch);
+
+/** Compute a backward MDCT (no scaling) and performs weighted overlap-add
+    (scales implicitly by 1/2) */
+void clt_mdct_backward_c(const mdct_lookup *l, kiss_fft_scalar *in,
+      kiss_fft_scalar * OPUS_RESTRICT out,
+      const opus_val16 * OPUS_RESTRICT window,
+      int overlap, int shift, int stride, int arch);
+
+#if !defined(OVERRIDE_OPUS_MDCT)
+/* Is run-time CPU detection enabled on this platform? */
+#if defined(OPUS_HAVE_RTCD) && defined(HAVE_ARM_NE10)
+
+extern void (*const CLT_MDCT_FORWARD_IMPL[OPUS_ARCHMASK+1])(
+      const mdct_lookup *l, kiss_fft_scalar *in,
+      kiss_fft_scalar * OPUS_RESTRICT out, const opus_val16 *window,
+      int overlap, int shift, int stride, int arch);
+
+#define clt_mdct_forward(_l, _in, _out, _window, _overlap, _shift, _stride, _arch) \
+   ((*CLT_MDCT_FORWARD_IMPL[(arch)&OPUS_ARCHMASK])(_l, _in, _out, \
+                                                   _window, _overlap, _shift, \
+                                                   _stride, _arch))
+
+extern void (*const CLT_MDCT_BACKWARD_IMPL[OPUS_ARCHMASK+1])(
+      const mdct_lookup *l, kiss_fft_scalar *in,
+      kiss_fft_scalar * OPUS_RESTRICT out, const opus_val16 *window,
+      int overlap, int shift, int stride, int arch);
+
+#define clt_mdct_backward(_l, _in, _out, _window, _overlap, _shift, _stride, _arch) \
+   (*CLT_MDCT_BACKWARD_IMPL[(arch)&OPUS_ARCHMASK])(_l, _in, _out, \
+                                                   _window, _overlap, _shift, \
+                                                   _stride, _arch)
+
+#else /* if defined(OPUS_HAVE_RTCD) && defined(HAVE_ARM_NE10) */
+
+#define clt_mdct_forward(_l, _in, _out, _window, _overlap, _shift, _stride, _arch) \
+   clt_mdct_forward_c(_l, _in, _out, _window, _overlap, _shift, _stride, _arch)
+
+#define clt_mdct_backward(_l, _in, _out, _window, _overlap, _shift, _stride, _arch) \
+   clt_mdct_backward_c(_l, _in, _out, _window, _overlap, _shift, _stride, _arch)
+
+#endif /* end if defined(OPUS_HAVE_RTCD) && defined(HAVE_ARM_NE10) && !defined(FIXED_POINT) */
+#endif /* end if !defined(OVERRIDE_OPUS_MDCT) */
+
+#endif
diff --git a/opus/celt/mfrngcod.h b/opus/celt/mfrngcod.h
new file mode 100644 (file)
index 0000000..809152a
--- /dev/null
@@ -0,0 +1,48 @@
+/* Copyright (c) 2001-2008 Timothy B. Terriberry
+   Copyright (c) 2008-2009 Xiph.Org Foundation */
+/*
+   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.
+
+   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.
+*/
+
+#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   (((opus_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)
+/*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)
+#endif
diff --git a/opus/celt/mips/celt_mipsr1.h b/opus/celt/mips/celt_mipsr1.h
new file mode 100644 (file)
index 0000000..e85661a
--- /dev/null
@@ -0,0 +1,151 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2010 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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 __CELT_MIPSR1_H__
+#define __CELT_MIPSR1_H__
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#define CELT_C
+
+#include "os_support.h"
+#include "mdct.h"
+#include <math.h>
+#include "celt.h"
+#include "pitch.h"
+#include "bands.h"
+#include "modes.h"
+#include "entcode.h"
+#include "quant_bands.h"
+#include "rate.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "float_cast.h"
+#include <stdarg.h>
+#include "celt_lpc.h"
+#include "vq.h"
+
+#define OVERRIDE_comb_filter
+void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
+      opus_val16 g0, opus_val16 g1, int tapset0, int tapset1,
+      const opus_val16 *window, int overlap, int arch)
+{
+   int i;
+   opus_val32 x0, x1, x2, x3, x4;
+
+   (void)arch;
+
+   /* printf ("%d %d %f %f\n", T0, T1, g0, g1); */
+   opus_val16 g00, g01, g02, g10, g11, g12;
+   static const opus_val16 gains[3][3] = {
+         {QCONST16(0.3066406250f, 15), QCONST16(0.2170410156f, 15), QCONST16(0.1296386719f, 15)},
+         {QCONST16(0.4638671875f, 15), QCONST16(0.2680664062f, 15), QCONST16(0.f, 15)},
+         {QCONST16(0.7998046875f, 15), QCONST16(0.1000976562f, 15), QCONST16(0.f, 15)}};
+
+   if (g0==0 && g1==0)
+   {
+      /* OPT: Happens to work without the OPUS_MOVE(), but only because the current encoder already copies x to y */
+      if (x!=y)
+         OPUS_MOVE(y, x, N);
+      return;
+   }
+
+   g00 = MULT16_16_P15(g0, gains[tapset0][0]);
+   g01 = MULT16_16_P15(g0, gains[tapset0][1]);
+   g02 = MULT16_16_P15(g0, gains[tapset0][2]);
+   g10 = MULT16_16_P15(g1, gains[tapset1][0]);
+   g11 = MULT16_16_P15(g1, gains[tapset1][1]);
+   g12 = MULT16_16_P15(g1, gains[tapset1][2]);
+   x1 = x[-T1+1];
+   x2 = x[-T1  ];
+   x3 = x[-T1-1];
+   x4 = x[-T1-2];
+   /* If the filter didn't change, we don't need the overlap */
+   if (g0==g1 && T0==T1 && tapset0==tapset1)
+      overlap=0;
+
+   for (i=0;i<overlap;i++)
+   {
+      opus_val16 f;
+      opus_val32 res;
+      f = MULT16_16_Q15(window[i],window[i]);
+      x0= x[i-T1+2];
+
+      asm volatile("MULT $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15((Q15ONE-f),g00)), "r" ((int)x[i-T0]));
+
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15((Q15ONE-f),g01)), "r" ((int)ADD32(x[i-T0-1],x[i-T0+1])));
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15((Q15ONE-f),g02)), "r" ((int)ADD32(x[i-T0-2],x[i-T0+2])));
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15(f,g10)), "r" ((int)x2));
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15(f,g11)), "r" ((int)ADD32(x3,x1)));
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)MULT16_16_Q15(f,g12)), "r" ((int)ADD32(x4,x0)));
+
+      asm volatile("EXTR.W %0,$ac1, %1" : "=r" (res): "i" (15));
+
+      y[i] = x[i] + res;
+
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
+   }
+
+   x4 = x[i-T1-2];
+   x3 = x[i-T1-1];
+   x2 = x[i-T1];
+   x1 = x[i-T1+1];
+
+   if (g1==0)
+   {
+      /* OPT: Happens to work without the OPUS_MOVE(), but only because the current encoder already copies x to y */
+      if (x!=y)
+         OPUS_MOVE(y+overlap, x+overlap, N-overlap);
+      return;
+   }
+
+   for (i=overlap;i<N;i++)
+   {
+      opus_val32 res;
+      x0=x[i-T1+2];
+
+      asm volatile("MULT $ac1, %0, %1" : : "r" ((int)g10), "r" ((int)x2));
+
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)g11), "r" ((int)ADD32(x3,x1)));
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)g12), "r" ((int)ADD32(x4,x0)));
+      asm volatile("EXTR.W %0,$ac1, %1" : "=r" (res): "i" (15));
+      y[i] = x[i] + res;
+      x4=x3;
+      x3=x2;
+      x2=x1;
+      x1=x0;
+   }
+}
+
+#endif /* __CELT_MIPSR1_H__ */
diff --git a/opus/celt/mips/fixed_generic_mipsr1.h b/opus/celt/mips/fixed_generic_mipsr1.h
new file mode 100644 (file)
index 0000000..4a05efb
--- /dev/null
@@ -0,0 +1,126 @@
+/* Copyright (C) 2007-2009 Xiph.Org Foundation
+   Copyright (C) 2003-2008 Jean-Marc Valin
+   Copyright (C) 2007-2008 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.
+
+   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 CELT_FIXED_GENERIC_MIPSR1_H
+#define CELT_FIXED_GENERIC_MIPSR1_H
+
+#undef MULT16_32_Q15_ADD
+static inline int MULT16_32_Q15_ADD(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("madd $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+#undef MULT16_32_Q15_SUB
+static inline int MULT16_32_Q15_SUB(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("msub $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+#undef MULT16_16_Q15_ADD
+static inline int MULT16_16_Q15_ADD(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("madd $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+#undef MULT16_16_Q15_SUB
+static inline int MULT16_16_Q15_SUB(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("msub $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+
+#undef MULT16_32_Q16
+static inline int MULT16_32_Q16(int a, int b)
+{
+    int c;
+    asm volatile("MULT $ac1,%0, %1" : : "r" (a), "r" (b));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (c): "i" (16));
+    return c;
+}
+
+#undef MULT16_32_P16
+static inline int MULT16_32_P16(int a, int b)
+{
+    int c;
+    asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b));
+    asm volatile("EXTR_R.W %0,$ac1, %1" : "=r" (c): "i" (16));
+    return c;
+}
+
+#undef MULT16_32_Q15
+static inline int MULT16_32_Q15(int a, int b)
+{
+    int c;
+    asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (c): "i" (15));
+    return c;
+}
+
+#undef MULT32_32_Q31
+static inline int MULT32_32_Q31(int a, int b)
+{
+    int r;
+    asm volatile("MULT $ac1, %0, %1" : : "r" (a), "r" (b));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (r): "i" (31));
+    return r;
+}
+
+#undef PSHR32
+static inline int PSHR32(int a, int shift)
+{
+    int r;
+    asm volatile ("SHRAV_R.W %0, %1, %2" :"=r" (r): "r" (a), "r" (shift));
+    return r;
+}
+
+#undef MULT16_16_P15
+static inline int MULT16_16_P15(int a, int b)
+{
+    int r;
+    asm volatile ("mul %0, %1, %2" :"=r" (r): "r" (a), "r" (b));
+    asm volatile ("SHRA_R.W %0, %1, %2" : "+r" (r):  "0" (r), "i"(15));
+    return r;
+}
+
+#endif /* CELT_FIXED_GENERIC_MIPSR1_H */
diff --git a/opus/celt/mips/kiss_fft_mipsr1.h b/opus/celt/mips/kiss_fft_mipsr1.h
new file mode 100644 (file)
index 0000000..400ca4d
--- /dev/null
@@ -0,0 +1,167 @@
+/*Copyright (c) 2013, Xiph.Org Foundation and contributors.
+
+  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.
+
+  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_MIPSR1_H
+#define KISS_FFT_MIPSR1_H
+
+#if !defined(KISS_FFT_GUTS_H)
+#error "This file should only be included from _kiss_fft_guts.h"
+#endif
+
+#ifdef FIXED_POINT
+
+#define S_MUL_ADD(a, b, c, d) (S_MUL(a,b)+S_MUL(c,d))
+#define S_MUL_SUB(a, b, c, d) (S_MUL(a,b)-S_MUL(c,d))
+
+#undef S_MUL_ADD
+static inline int S_MUL_ADD(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("madd $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+#undef S_MUL_SUB
+static inline int S_MUL_SUB(int a, int b, int c, int d) {
+    int m;
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a), "r" ((int)b));
+    asm volatile("msub $ac1, %0, %1" : : "r" ((int)c), "r" ((int)d));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m): "i" (15));
+    return m;
+}
+
+#undef C_MUL
+#   define C_MUL(m,a,b) (m=C_MUL_fun(a,b))
+static inline kiss_fft_cpx C_MUL_fun(kiss_fft_cpx a, kiss_twiddle_cpx b) {
+    kiss_fft_cpx m;
+
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a.r), "r" ((int)b.r));
+    asm volatile("msub $ac1, %0, %1" : : "r" ((int)a.i), "r" ((int)b.i));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m.r): "i" (15));
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a.r), "r" ((int)b.i));
+    asm volatile("madd $ac1, %0, %1" : : "r" ((int)a.i), "r" ((int)b.r));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m.i): "i" (15));
+
+    return m;
+}
+#undef C_MULC
+#   define C_MULC(m,a,b) (m=C_MULC_fun(a,b))
+static inline kiss_fft_cpx C_MULC_fun(kiss_fft_cpx a, kiss_twiddle_cpx b) {
+    kiss_fft_cpx m;
+
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a.r), "r" ((int)b.r));
+    asm volatile("madd $ac1, %0, %1" : : "r" ((int)a.i), "r" ((int)b.i));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m.r): "i" (15));
+    asm volatile("MULT $ac1, %0, %1" : : "r" ((int)a.i), "r" ((int)b.r));
+    asm volatile("msub $ac1, %0, %1" : : "r" ((int)a.r), "r" ((int)b.i));
+    asm volatile("EXTR.W %0,$ac1, %1" : "=r" (m.i): "i" (15));
+
+    return m;
+}
+
+#endif /* FIXED_POINT */
+
+#define OVERRIDE_kf_bfly5
+static void kf_bfly5(
+                     kiss_fft_cpx * Fout,
+                     const size_t fstride,
+                     const kiss_fft_state *st,
+                     int m,
+                     int N,
+                     int mm
+                    )
+{
+   kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
+   int i, u;
+   kiss_fft_cpx scratch[13];
+
+   const kiss_twiddle_cpx *tw;
+   kiss_twiddle_cpx ya,yb;
+   kiss_fft_cpx * Fout_beg = Fout;
+
+#ifdef FIXED_POINT
+   ya.r = 10126;
+   ya.i = -31164;
+   yb.r = -26510;
+   yb.i = -19261;
+#else
+   ya = st->twiddles[fstride*m];
+   yb = st->twiddles[fstride*2*m];
+#endif
+
+   tw=st->twiddles;
+
+   for (i=0;i<N;i++)
+   {
+      Fout = Fout_beg + i*mm;
+      Fout0=Fout;
+      Fout1=Fout0+m;
+      Fout2=Fout0+2*m;
+      Fout3=Fout0+3*m;
+      Fout4=Fout0+4*m;
+
+      /* For non-custom modes, m is guaranteed to be a multiple of 4. */
+      for ( u=0; u<m; ++u ) {
+         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_ADD(scratch[7].r,ya.r,scratch[8].r,yb.r);
+         scratch[5].i = scratch[0].i + S_MUL_ADD(scratch[7].i,ya.r,scratch[8].i,yb.r);
+
+         scratch[6].r =  S_MUL_ADD(scratch[10].i,ya.i,scratch[9].i,yb.i);
+         scratch[6].i =  -S_MUL_ADD(scratch[10].r,ya.i,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_ADD(scratch[7].r,yb.r,scratch[8].r,ya.r);
+         scratch[11].i = scratch[0].i + S_MUL_ADD(scratch[7].i,yb.r,scratch[8].i,ya.r);
+
+         scratch[12].r =  S_MUL_SUB(scratch[9].i,ya.i,scratch[10].i,yb.i);
+         scratch[12].i =  S_MUL_SUB(scratch[10].r,yb.i,scratch[9].r,ya.i);
+
+         C_ADD(*Fout2,scratch[11],scratch[12]);
+         C_SUB(*Fout3,scratch[11],scratch[12]);
+
+         ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
+      }
+   }
+}
+
+
+#endif /* KISS_FFT_MIPSR1_H */
diff --git a/opus/celt/mips/mdct_mipsr1.h b/opus/celt/mips/mdct_mipsr1.h
new file mode 100644 (file)
index 0000000..2934dab
--- /dev/null
@@ -0,0 +1,288 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2008 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+/* 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_MIPSR1_H__
+#define __MDCT_MIPSR1_H__
+
+#ifndef SKIP_CONFIG_H
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#endif
+
+#include "mdct.h"
+#include "kiss_fft.h"
+#include "_kiss_fft_guts.h"
+#include <math.h>
+#include "os_support.h"
+#include "mathops.h"
+#include "stack_alloc.h"
+
+/* Forward MDCT trashes the input array */
+#define OVERRIDE_clt_mdct_forward
+void clt_mdct_forward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
+      const opus_val16 *window, int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   VARDECL(kiss_fft_scalar, f);
+   VARDECL(kiss_fft_cpx, f2);
+   const kiss_fft_state *st = l->kfft[shift];
+   const kiss_twiddle_scalar *trig;
+   opus_val16 scale;
+#ifdef FIXED_POINT
+   /* Allows us to scale with MULT16_32_Q16(), which is faster than
+      MULT16_32_Q15() on ARM. */
+   int scale_shift = st->scale_shift-1;
+#endif
+
+    (void)arch;
+
+   SAVE_STACK;
+   scale = st->scale;
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   ALLOC(f, N2, kiss_fft_scalar);
+   ALLOC(f2, N4, kiss_fft_cpx);
+
+   /* Consider the input to be composed 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 * OPUS_RESTRICT xp1 = in+(overlap>>1);
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+N2-1+(overlap>>1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = f;
+      const opus_val16 * OPUS_RESTRICT wp1 = window+(overlap>>1);
+      const opus_val16 * OPUS_RESTRICT wp2 = window+(overlap>>1)-1;
+      for(i=0;i<((overlap+3)>>2);i++)
+      {
+         /* Real part arranged as -d-cR, Imag part arranged as -b+aR*/
+          *yp++ = S_MUL_ADD(*wp2, xp1[N2],*wp1,*xp2);
+          *yp++ = S_MUL_SUB(*wp1, *xp1,*wp2, xp2[-N2]);
+         xp1+=2;
+         xp2-=2;
+         wp1+=2;
+         wp2-=2;
+      }
+      wp1 = window;
+      wp2 = window+overlap-1;
+      for(;i<N4-((overlap+3)>>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++ =  S_MUL_SUB(*wp2, *xp2, *wp1, xp1[-N2]);
+          *yp++ = S_MUL_ADD(*wp2, *xp1, *wp1, xp2[N2]);
+         xp1+=2;
+         xp2-=2;
+         wp1+=2;
+         wp2-=2;
+      }
+   }
+   /* Pre-rotation */
+   {
+      kiss_fft_scalar * OPUS_RESTRICT yp = f;
+      const kiss_twiddle_scalar *t = &trig[0];
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_cpx yc;
+         kiss_twiddle_scalar t0, t1;
+         kiss_fft_scalar re, im, yr, yi;
+         t0 = t[i];
+         t1 = t[N4+i];
+         re = *yp++;
+         im = *yp++;
+
+         yr = S_MUL_SUB(re,t0,im,t1);
+         yi = S_MUL_ADD(im,t0,re,t1);
+
+         yc.r = yr;
+         yc.i = yi;
+         yc.r = PSHR32(MULT16_32_Q16(scale, yc.r), scale_shift);
+         yc.i = PSHR32(MULT16_32_Q16(scale, yc.i), scale_shift);
+         f2[st->bitrev[i]] = yc;
+      }
+   }
+
+   /* N/4 complex FFT, does not downscale anymore */
+   opus_fft_impl(st, f2);
+
+   /* Post-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_cpx * OPUS_RESTRICT fp = f2;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      kiss_fft_scalar * OPUS_RESTRICT yp2 = out+stride*(N2-1);
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      for(i=0;i<N4;i++)
+      {
+         kiss_fft_scalar yr, yi;
+         yr = S_MUL_SUB(fp->i,t[N4+i] , fp->r,t[i]);
+         yi = S_MUL_ADD(fp->r,t[N4+i] ,fp->i,t[i]);
+         *yp1 = yr;
+         *yp2 = yi;
+         fp++;
+         yp1 += 2*stride;
+         yp2 -= 2*stride;
+      }
+   }
+   RESTORE_STACK;
+}
+
+#define OVERRIDE_clt_mdct_backward
+void clt_mdct_backward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
+      const opus_val16 * OPUS_RESTRICT window, int overlap, int shift, int stride, int arch)
+{
+   int i;
+   int N, N2, N4;
+   const kiss_twiddle_scalar *trig;
+
+    (void)arch;
+
+   N = l->n;
+   trig = l->trig;
+   for (i=0;i<shift;i++)
+   {
+      N >>= 1;
+      trig += N;
+   }
+   N2 = N>>1;
+   N4 = N>>2;
+
+   /* Pre-rotate */
+   {
+      /* Temp pointers to make it really clear to the compiler what we're doing */
+      const kiss_fft_scalar * OPUS_RESTRICT xp1 = in;
+      const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+stride*(N2-1);
+      kiss_fft_scalar * OPUS_RESTRICT yp = out+(overlap>>1);
+      const kiss_twiddle_scalar * OPUS_RESTRICT t = &trig[0];
+      const opus_int16 * OPUS_RESTRICT bitrev = l->kfft[shift]->bitrev;
+      for(i=0;i<N4;i++)
+      {
+         int rev;
+         kiss_fft_scalar yr, yi;
+         rev = *bitrev++;
+         yr = S_MUL_ADD(*xp2, t[i] , *xp1, t[N4+i]);
+         yi = S_MUL_SUB(*xp1, t[i] , *xp2, t[N4+i]);
+         /* We swap real and imag because we use an FFT instead of an IFFT. */
+         yp[2*rev+1] = yr;
+         yp[2*rev] = yi;
+         /* Storing the pre-rotation directly in the bitrev order. */
+         xp1+=2*stride;
+         xp2-=2*stride;
+      }
+   }
+
+   opus_fft_impl(l->kfft[shift], (kiss_fft_cpx*)(out+(overlap>>1)));
+
+   /* Post-rotate and de-shuffle from both ends of the buffer at once to make
+      it in-place. */
+   {
+      kiss_fft_scalar * OPUS_RESTRICT yp0 = out+(overlap>>1);
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out+(overlap>>1)+N2-2;
+      const kiss_twiddle_scalar *t = &trig[0];
+      /* Loop to (N4+1)>>1 to handle odd N4. When N4 is odd, the
+         middle pair will be computed twice. */
+      for(i=0;i<(N4+1)>>1;i++)
+      {
+         kiss_fft_scalar re, im, yr, yi;
+         kiss_twiddle_scalar t0, t1;
+         /* We swap real and imag because we're using an FFT instead of an IFFT. */
+         re = yp0[1];
+         im = yp0[0];
+         t0 = t[i];
+         t1 = t[N4+i];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = S_MUL_ADD(re,t0 , im,t1);
+         yi = S_MUL_SUB(re,t1 , im,t0);
+         /* We swap real and imag because we're using an FFT instead of an IFFT. */
+         re = yp1[1];
+         im = yp1[0];
+         yp0[0] = yr;
+         yp1[1] = yi;
+
+         t0 = t[(N4-i-1)];
+         t1 = t[(N2-i-1)];
+         /* We'd scale up by 2 here, but instead it's done when mixing the windows */
+         yr = S_MUL_ADD(re,t0,im,t1);
+         yi = S_MUL_SUB(re,t1,im,t0);
+         yp1[0] = yr;
+         yp0[1] = yi;
+         yp0 += 2;
+         yp1 -= 2;
+      }
+   }
+
+   /* Mirror on both sides for TDAC */
+   {
+      kiss_fft_scalar * OPUS_RESTRICT xp1 = out+overlap-1;
+      kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
+      const opus_val16 * OPUS_RESTRICT wp1 = window;
+      const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
+
+      for(i = 0; i < overlap/2; i++)
+      {
+         kiss_fft_scalar x1, x2;
+         x1 = *xp1;
+         x2 = *yp1;
+         *yp1++ = MULT16_32_Q15(*wp2, x2) - MULT16_32_Q15(*wp1, x1);
+         *xp1-- = MULT16_32_Q15(*wp1, x2) + MULT16_32_Q15(*wp2, x1);
+         wp1++;
+         wp2--;
+      }
+   }
+}
+#endif /* __MDCT_MIPSR1_H__ */
diff --git a/opus/celt/mips/pitch_mipsr1.h b/opus/celt/mips/pitch_mipsr1.h
new file mode 100644 (file)
index 0000000..a9500af
--- /dev/null
@@ -0,0 +1,161 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by Jean-Marc Valin */
+/**
+   @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.
+
+   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 PITCH_MIPSR1_H
+#define PITCH_MIPSR1_H
+
+#define OVERRIDE_DUAL_INNER_PROD
+static inline void dual_inner_prod(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+      int N, opus_val32 *xy1, opus_val32 *xy2, int arch)
+{
+   int j;
+   opus_val32 xy01=0;
+   opus_val32 xy02=0;
+
+   (void)arch;
+
+   asm volatile("MULT $ac1, $0, $0");
+   asm volatile("MULT $ac2, $0, $0");
+   /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
+   for (j=0;j<N;j++)
+   {
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)x[j]), "r" ((int)y01[j]));
+      asm volatile("MADD $ac2, %0, %1" : : "r" ((int)x[j]), "r" ((int)y02[j]));
+      ++j;
+      asm volatile("MADD $ac1, %0, %1" : : "r" ((int)x[j]), "r" ((int)y01[j]));
+      asm volatile("MADD $ac2, %0, %1" : : "r" ((int)x[j]), "r" ((int)y02[j]));
+   }
+   asm volatile ("mflo %0, $ac1": "=r"(xy01));
+   asm volatile ("mflo %0, $ac2": "=r"(xy02));
+   *xy1 = xy01;
+   *xy2 = xy02;
+}
+
+static inline void xcorr_kernel_mips(const opus_val16 * x,
+      const opus_val16 * y, opus_val32 sum[4], int len)
+{
+   int j;
+   opus_val16 y_0, y_1, y_2, y_3;
+
+    opus_int64 sum_0, sum_1, sum_2, sum_3;
+    sum_0 =  (opus_int64)sum[0];
+    sum_1 =  (opus_int64)sum[1];
+    sum_2 =  (opus_int64)sum[2];
+    sum_3 =  (opus_int64)sum[3];
+
+    y_3=0; /* gcc doesn't realize that y_3 can't be used uninitialized */
+    y_0=*y++;
+    y_1=*y++;
+    y_2=*y++;
+    for (j=0;j<len-3;j+=4)
+    {
+        opus_val16 tmp;
+        tmp = *x++;
+        y_3=*y++;
+
+        sum_0 = __builtin_mips_madd( sum_0, tmp, y_0);
+        sum_1 = __builtin_mips_madd( sum_1, tmp, y_1);
+        sum_2 = __builtin_mips_madd( sum_2, tmp, y_2);
+        sum_3 = __builtin_mips_madd( sum_3, tmp, y_3);
+
+        tmp=*x++;
+        y_0=*y++;
+
+        sum_0 = __builtin_mips_madd( sum_0, tmp, y_1 );
+        sum_1 = __builtin_mips_madd( sum_1, tmp, y_2 );
+        sum_2 = __builtin_mips_madd( sum_2, tmp, y_3);
+        sum_3 = __builtin_mips_madd( sum_3, tmp, y_0);
+
+       tmp=*x++;
+       y_1=*y++;
+
+       sum_0 = __builtin_mips_madd( sum_0, tmp, y_2 );
+       sum_1 = __builtin_mips_madd( sum_1, tmp, y_3 );
+       sum_2 = __builtin_mips_madd( sum_2, tmp, y_0);
+       sum_3 = __builtin_mips_madd( sum_3, tmp, y_1);
+
+
+      tmp=*x++;
+      y_2=*y++;
+
+       sum_0 = __builtin_mips_madd( sum_0, tmp, y_3 );
+       sum_1 = __builtin_mips_madd( sum_1, tmp, y_0 );
+       sum_2 = __builtin_mips_madd( sum_2, tmp, y_1);
+       sum_3 = __builtin_mips_madd( sum_3, tmp, y_2);
+
+   }
+   if (j++<len)
+   {
+      opus_val16 tmp = *x++;
+      y_3=*y++;
+
+       sum_0 = __builtin_mips_madd( sum_0, tmp, y_0 );
+       sum_1 = __builtin_mips_madd( sum_1, tmp, y_1 );
+       sum_2 = __builtin_mips_madd( sum_2, tmp, y_2);
+       sum_3 = __builtin_mips_madd( sum_3, tmp, y_3);
+   }
+
+   if (j++<len)
+   {
+      opus_val16 tmp=*x++;
+      y_0=*y++;
+
+      sum_0 = __builtin_mips_madd( sum_0, tmp, y_1 );
+      sum_1 = __builtin_mips_madd( sum_1, tmp, y_2 );
+      sum_2 = __builtin_mips_madd( sum_2, tmp, y_3);
+      sum_3 = __builtin_mips_madd( sum_3, tmp, y_0);
+   }
+
+   if (j<len)
+   {
+      opus_val16 tmp=*x++;
+      y_1=*y++;
+
+       sum_0 = __builtin_mips_madd( sum_0, tmp, y_2 );
+       sum_1 = __builtin_mips_madd( sum_1, tmp, y_3 );
+       sum_2 = __builtin_mips_madd( sum_2, tmp, y_0);
+       sum_3 = __builtin_mips_madd( sum_3, tmp, y_1);
+
+   }
+
+   sum[0] = (opus_val32)sum_0;
+   sum[1] = (opus_val32)sum_1;
+   sum[2] = (opus_val32)sum_2;
+   sum[3] = (opus_val32)sum_3;
+}
+
+#define OVERRIDE_XCORR_KERNEL
+#define xcorr_kernel(x, y, sum, len, arch) \
+    ((void)(arch), xcorr_kernel_mips(x, y, sum, len))
+
+#endif /* PITCH_MIPSR1_H */
diff --git a/opus/celt/mips/vq_mipsr1.h b/opus/celt/mips/vq_mipsr1.h
new file mode 100644 (file)
index 0000000..fd18eab
--- /dev/null
@@ -0,0 +1,122 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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 __VQ_MIPSR1_H__
+#define __VQ_MIPSR1_H__
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "mathops.h"
+#include "arch.h"
+
+static void renormalise_vector_mips(celt_norm *X, int N, opus_val16 gain, int arch);
+
+#define OVERRIDE_vq_exp_rotation1
+static void exp_rotation1(celt_norm *X, int len, int stride, opus_val16 c, opus_val16 s)
+{
+   int i;
+   opus_val16 ms;
+   celt_norm *Xptr;
+   Xptr = X;
+   ms = NEG16(s);
+   for (i=0;i<len-stride;i++)
+   {
+      celt_norm x1, x2;
+      x1 = Xptr[0];
+      x2 = Xptr[stride];
+      Xptr[stride] = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x2),  s, x1), 15));
+      *Xptr++      = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x1), ms, x2), 15));
+   }
+   Xptr = &X[len-2*stride-1];
+   for (i=len-2*stride-1;i>=0;i--)
+   {
+      celt_norm x1, x2;
+      x1 = Xptr[0];
+      x2 = Xptr[stride];
+      Xptr[stride] = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x2),  s, x1), 15));
+      *Xptr--      = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x1), ms, x2), 15));
+   }
+}
+
+#define OVERRIDE_renormalise_vector
+
+#define renormalise_vector(X, N, gain, arch) \
+ (renormalise_vector_mips(X, N, gain, arch))
+
+void renormalise_vector_mips(celt_norm *X, int N, opus_val16 gain, int arch)
+{
+   int i;
+#ifdef FIXED_POINT
+   int k;
+#endif
+   opus_val32 E = EPSILON;
+   opus_val16 g;
+   opus_val32 t;
+   celt_norm *xptr = X;
+   int X0, X1;
+
+   (void)arch;
+
+   asm volatile("mult $ac1, $0, $0");
+   asm volatile("MTLO %0, $ac1" : :"r" (E));
+   /*if(N %4)
+       printf("error");*/
+   for (i=0;i<N-2;i+=2)
+   {
+      X0 = (int)*xptr++;
+      asm volatile("MADD $ac1, %0, %1" : : "r" (X0), "r" (X0));
+
+      X1 = (int)*xptr++;
+      asm volatile("MADD $ac1, %0, %1" : : "r" (X1), "r" (X1));
+   }
+
+   for (;i<N;i++)
+   {
+      X0 = (int)*xptr++;
+      asm volatile("MADD $ac1, %0, %1" : : "r" (X0), "r" (X0));
+   }
+
+   asm volatile("MFLO %0, $ac1" : "=r" (E));
+#ifdef FIXED_POINT
+   k = celt_ilog2(E)>>1;
+#endif
+   t = VSHR32(E, 2*(k-7));
+   g = MULT16_16_P15(celt_rsqrt_norm(t),gain);
+
+   xptr = X;
+   for (i=0;i<N;i++)
+   {
+      *xptr = EXTRACT16(PSHR32(MULT16_16(g, *xptr), k+1));
+      xptr++;
+   }
+   /*return celt_sqrt(E);*/
+}
+
+#endif /* __VQ_MIPSR1_H__ */
diff --git a/opus/celt/modes.c b/opus/celt/modes.c
new file mode 100644 (file)
index 0000000..390c5e8
--- /dev/null
@@ -0,0 +1,442 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#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"
+#include "cpu_support.h"
+
+static const opus_int16 eband5ms[] = {
+/*0  200 400 600 800  1k 1.2 1.4 1.6  2k 2.4 2.8 3.2  4k 4.8 5.6 6.8  8k 9.6 12k 15.6 */
+  0,  1,  2,  3,  4,  5,  6,  7,  8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100
+};
+
+/* Alternate tuning (partially derived from Vorbis) */
+#define BITALLOC_SIZE 11
+/* Bit allocation table in units of 1/32 bit/sample (0.1875 dB SNR) */
+static const unsigned char band_allocation[] = {
+/*0  200 400 600 800  1k 1.2 1.4 1.6  2k 2.4 2.8 3.2  4k 4.8 5.6 6.8  8k 9.6 12k 15.6 */
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+ 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10,  0,  0,  0,  0,  0,  0,  0,  0,
+110,100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12,  0,  0,  0,  0,  0,  0,
+118,110,103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15,  4,  0,  0,  0,  0,
+126,119,112,104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12,  1,  0,  0,
+134,127,120,114,103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10,  1,
+144,137,130,124,113,107,101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15,  1,
+152,145,138,132,123,117,111,105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20,  1,
+162,155,148,142,133,127,121,115,108,102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30,  1,
+172,165,158,152,143,137,131,125,118,112,106,100, 94, 87, 81, 75, 69, 63, 56, 45, 20,
+200,200,200,200,200,200,200,200,198,193,188,183,178,173,168,163,158,153,148,129,104,
+};
+
+#ifndef CUSTOM_MODES_ONLY
+ #ifdef FIXED_POINT
+  #include "static_modes_fixed.h"
+ #else
+  #include "static_modes_float.h"
+ #endif
+#endif /* CUSTOM_MODES_ONLY */
+
+#ifndef M_PI
+#define M_PI 3.141592653
+#endif
+
+#ifdef CUSTOM_MODES
+
+/* 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 opus_int16 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 opus_int16 *compute_ebands(opus_int32 Fs, int frame_size, int res, int *nbEBands)
+{
+   opus_int16 *eBands;
+   int i, j, lin, low, high, nBark, offset=0;
+
+   /* All modes that have 2.5 ms short blocks use the same definition */
+   if (Fs == 400*(opus_int32)frame_size)
+   {
+      *nbEBands = sizeof(eband5ms)/sizeof(eband5ms[0])-1;
+      eBands = opus_alloc(sizeof(opus_int16)*(*nbEBands+1));
+      for (i=0;i<*nbEBands+1;i++)
+         eBands[i] = eband5ms[i];
+      return eBands;
+   }
+   /* 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] >= res)
+         break;
+
+   low = (bark_freq[lin]+res/2)/res;
+   high = nBark-lin;
+   *nbEBands = low+high;
+   eBands = opus_alloc(sizeof(opus_int16)*(*nbEBands+2));
+
+   if (eBands==NULL)
+      return NULL;
+
+   /* Linear spacing (min_width) */
+   for (i=0;i<low;i++)
+      eBands[i] = i;
+   if (low>0)
+      offset = eBands[low-1]*res - bark_freq[lin-1];
+   /* Spacing follows critical bands */
+   for (i=0;i<high;i++)
+   {
+      int target = bark_freq[lin+i];
+      /* Round to an even value */
+      eBands[i+low] = (target+offset/2+res)/(2*res)*2;
+      offset = eBands[i+low]*res - target;
+   }
+   /* Enforce the minimum spacing at the boundary */
+   for (i=0;i<*nbEBands;i++)
+      if (eBands[i] < i)
+         eBands[i] = i;
+   /* Round to an even value */
+   eBands[*nbEBands] = (bark_freq[nBark]+res)/(2*res)*2;
+   if (eBands[*nbEBands] > frame_size)
+      eBands[*nbEBands] = frame_size;
+   for (i=1;i<*nbEBands-1;i++)
+   {
+      if (eBands[i+1]-eBands[i] < eBands[i]-eBands[i-1])
+      {
+         eBands[i] -= (2*eBands[i]-eBands[i-1]-eBands[i+1])/2;
+      }
+   }
+   /* Remove any empty bands. */
+   for (i=j=0;i<*nbEBands;i++)
+      if(eBands[i+1]>eBands[j])
+         eBands[++j]=eBands[i+1];
+   *nbEBands=j;
+
+   for (i=1;i<*nbEBands;i++)
+   {
+      /* Every band must be smaller than the last band. */
+      celt_assert(eBands[i]-eBands[i-1]<=eBands[*nbEBands]-eBands[*nbEBands-1]);
+      /* Each band must be no larger than twice the size of the previous one. */
+      celt_assert(eBands[i+1]-eBands[i]<=2*(eBands[i]-eBands[i-1]));
+   }
+
+   return eBands;
+}
+
+static void compute_allocation_table(CELTMode *mode)
+{
+   int i, j;
+   unsigned char *allocVectors;
+   int maxBands = sizeof(eband5ms)/sizeof(eband5ms[0])-1;
+
+   mode->nbAllocVectors = BITALLOC_SIZE;
+   allocVectors = opus_alloc(sizeof(unsigned char)*(BITALLOC_SIZE*mode->nbEBands));
+   if (allocVectors==NULL)
+      return;
+
+   /* Check for standard mode */
+   if (mode->Fs == 400*(opus_int32)mode->shortMdctSize)
+   {
+      for (i=0;i<BITALLOC_SIZE*mode->nbEBands;i++)
+         allocVectors[i] = band_allocation[i];
+      mode->allocVectors = allocVectors;
+      return;
+   }
+   /* If not the standard mode, interpolate */
+   /* Compute per-codec-band allocation from per-critical-band matrix */
+   for (i=0;i<BITALLOC_SIZE;i++)
+   {
+      for (j=0;j<mode->nbEBands;j++)
+      {
+         int k;
+         for (k=0;k<maxBands;k++)
+         {
+            if (400*(opus_int32)eband5ms[k] > mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize)
+               break;
+         }
+         if (k>maxBands-1)
+            allocVectors[i*mode->nbEBands+j] = band_allocation[i*maxBands + maxBands-1];
+         else {
+            opus_int32 a0, a1;
+            a1 = mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize - 400*(opus_int32)eband5ms[k-1];
+            a0 = 400*(opus_int32)eband5ms[k] - mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize;
+            allocVectors[i*mode->nbEBands+j] = (a0*band_allocation[i*maxBands+k-1]
+                                             + a1*band_allocation[i*maxBands+k])/(a0+a1);
+         }
+      }
+   }
+
+   /*printf ("\n");
+   for (i=0;i<BITALLOC_SIZE;i++)
+   {
+      for (j=0;j<mode->nbEBands;j++)
+         printf ("%d ", allocVectors[i*mode->nbEBands+j]);
+      printf ("\n");
+   }
+   exit(0);*/
+
+   mode->allocVectors = allocVectors;
+}
+
+#endif /* CUSTOM_MODES */
+
+CELTMode *opus_custom_mode_create(opus_int32 Fs, int frame_size, int *error)
+{
+   int i;
+#ifdef CUSTOM_MODES
+   CELTMode *mode=NULL;
+   int res;
+   opus_val16 *window;
+   opus_int16 *logN;
+   int LM;
+   int arch = opus_select_arch();
+   ALLOC_STACK;
+#if !defined(VAR_ARRAYS) && !defined(USE_ALLOCA)
+   if (global_stack==NULL)
+      goto failure;
+#endif
+#endif
+
+#ifndef CUSTOM_MODES_ONLY
+   for (i=0;i<TOTAL_MODES;i++)
+   {
+      int j;
+      for (j=0;j<4;j++)
+      {
+         if (Fs == static_mode_list[i]->Fs &&
+               (frame_size<<j) == static_mode_list[i]->shortMdctSize*static_mode_list[i]->nbShortMdcts)
+         {
+            if (error)
+               *error = OPUS_OK;
+            return (CELTMode*)static_mode_list[i];
+         }
+      }
+   }
+#endif /* CUSTOM_MODES_ONLY */
+
+#ifndef CUSTOM_MODES
+   if (error)
+      *error = OPUS_BAD_ARG;
+   return NULL;
+#else
+
+   /* The good thing here is that permutation of the arguments will automatically be invalid */
+
+   if (Fs < 8000 || Fs > 96000)
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   if (frame_size < 40 || frame_size > 1024 || frame_size%2!=0)
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   /* Frames of less than 1ms are not supported. */
+   if ((opus_int32)frame_size*1000 < Fs)
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+
+   if ((opus_int32)frame_size*75 >= Fs && (frame_size%16)==0)
+   {
+     LM = 3;
+   } else if ((opus_int32)frame_size*150 >= Fs && (frame_size%8)==0)
+   {
+     LM = 2;
+   } else if ((opus_int32)frame_size*300 >= Fs && (frame_size%4)==0)
+   {
+     LM = 1;
+   } else
+   {
+     LM = 0;
+   }
+
+   /* Shorts longer than 3.3ms are not supported. */
+   if ((opus_int32)(frame_size>>LM)*300 > Fs)
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+
+   mode = opus_alloc(sizeof(CELTMode));
+   if (mode==NULL)
+      goto failure;
+   mode->Fs = Fs;
+
+   /* Pre/de-emphasis depends on sampling rate. The "standard" pre-emphasis
+      is defined as A(z) = 1 - 0.85*z^-1 at 48 kHz. Other rates should
+      approximate that. */
+   if(Fs < 12000) /* 8 kHz */
+   {
+      mode->preemph[0] =  QCONST16(0.3500061035f, 15);
+      mode->preemph[1] = -QCONST16(0.1799926758f, 15);
+      mode->preemph[2] =  QCONST16(0.2719968125f, SIG_SHIFT); /* exact 1/preemph[3] */
+      mode->preemph[3] =  QCONST16(3.6765136719f, 13);
+   } else if(Fs < 24000) /* 16 kHz */
+   {
+      mode->preemph[0] =  QCONST16(0.6000061035f, 15);
+      mode->preemph[1] = -QCONST16(0.1799926758f, 15);
+      mode->preemph[2] =  QCONST16(0.4424998650f, SIG_SHIFT); /* exact 1/preemph[3] */
+      mode->preemph[3] =  QCONST16(2.2598876953f, 13);
+   } else if(Fs < 40000) /* 32 kHz */
+   {
+      mode->preemph[0] =  QCONST16(0.7799987793f, 15);
+      mode->preemph[1] = -QCONST16(0.1000061035f, 15);
+      mode->preemph[2] =  QCONST16(0.7499771125f, SIG_SHIFT); /* exact 1/preemph[3] */
+      mode->preemph[3] =  QCONST16(1.3333740234f, 13);
+   } else /* 48 kHz */
+   {
+      mode->preemph[0] =  QCONST16(0.8500061035f, 15);
+      mode->preemph[1] =  QCONST16(0.0f, 15);
+      mode->preemph[2] =  QCONST16(1.f, SIG_SHIFT);
+      mode->preemph[3] =  QCONST16(1.f, 13);
+   }
+
+   mode->maxLM = LM;
+   mode->nbShortMdcts = 1<<LM;
+   mode->shortMdctSize = frame_size/mode->nbShortMdcts;
+   res = (mode->Fs+mode->shortMdctSize)/(2*mode->shortMdctSize);
+
+   mode->eBands = compute_ebands(Fs, mode->shortMdctSize, res, &mode->nbEBands);
+   if (mode->eBands==NULL)
+      goto failure;
+#if !defined(SMALL_FOOTPRINT)
+   /* Make sure we don't allocate a band larger than our PVQ table.
+      208 should be enough, but let's be paranoid. */
+   if ((mode->eBands[mode->nbEBands] - mode->eBands[mode->nbEBands-1])<<LM >
+    208) {
+       goto failure;
+   }
+#endif
+
+   mode->effEBands = mode->nbEBands;
+   while (mode->eBands[mode->effEBands] > mode->shortMdctSize)
+      mode->effEBands--;
+
+   /* Overlap must be divisible by 4 */
+   mode->overlap = ((mode->shortMdctSize>>2)<<2);
+
+   compute_allocation_table(mode);
+   if (mode->allocVectors==NULL)
+      goto failure;
+
+   window = (opus_val16*)opus_alloc(mode->overlap*sizeof(opus_val16));
+   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,floor(.5+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;
+
+   logN = (opus_int16*)opus_alloc(mode->nbEBands*sizeof(opus_int16));
+   if (logN==NULL)
+      goto failure;
+
+   for (i=0;i<mode->nbEBands;i++)
+      logN[i] = log2_frac(mode->eBands[i+1]-mode->eBands[i], BITRES);
+   mode->logN = logN;
+
+   compute_pulse_cache(mode, mode->maxLM);
+
+   if (clt_mdct_init(&mode->mdct, 2*mode->shortMdctSize*mode->nbShortMdcts,
+           mode->maxLM, arch) == 0)
+      goto failure;
+
+   if (error)
+      *error = OPUS_OK;
+
+   return mode;
+failure:
+   if (error)
+      *error = OPUS_ALLOC_FAIL;
+   if (mode!=NULL)
+      opus_custom_mode_destroy(mode);
+   return NULL;
+#endif /* !CUSTOM_MODES */
+}
+
+#ifdef CUSTOM_MODES
+void opus_custom_mode_destroy(CELTMode *mode)
+{
+   int arch = opus_select_arch();
+
+   if (mode == NULL)
+      return;
+#ifndef CUSTOM_MODES_ONLY
+   {
+     int i;
+     for (i=0;i<TOTAL_MODES;i++)
+     {
+        if (mode == static_mode_list[i])
+        {
+           return;
+        }
+     }
+   }
+#endif /* CUSTOM_MODES_ONLY */
+   opus_free((opus_int16*)mode->eBands);
+   opus_free((unsigned char*)mode->allocVectors);
+
+   opus_free((opus_val16*)mode->window);
+   opus_free((opus_int16*)mode->logN);
+
+   opus_free((opus_int16*)mode->cache.index);
+   opus_free((unsigned char*)mode->cache.bits);
+   opus_free((unsigned char*)mode->cache.caps);
+   clt_mdct_clear(&mode->mdct, arch);
+
+   opus_free((CELTMode *)mode);
+}
+#endif
diff --git a/opus/celt/modes.h b/opus/celt/modes.h
new file mode 100644 (file)
index 0000000..be813cc
--- /dev/null
@@ -0,0 +1,75 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2008 Gregory Maxwell
+   Written by Jean-Marc Valin and 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.
+
+   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 MODES_H
+#define MODES_H
+
+#include "opus_types.h"
+#include "celt.h"
+#include "arch.h"
+#include "mdct.h"
+#include "entenc.h"
+#include "entdec.h"
+
+#define MAX_PERIOD 1024
+
+typedef struct {
+   int size;
+   const opus_int16 *index;
+   const unsigned char *bits;
+   const unsigned char *caps;
+} PulseCache;
+
+/** Mode definition (opaque)
+ @brief Mode definition
+ */
+struct OpusCustomMode {
+   opus_int32 Fs;
+   int          overlap;
+
+   int          nbEBands;
+   int          effEBands;
+   opus_val16    preemph[4];
+   const opus_int16   *eBands;   /**< Definition for each "pseudo-critical band" */
+
+   int         maxLM;
+   int         nbShortMdcts;
+   int         shortMdctSize;
+
+   int          nbAllocVectors; /**< Number of lines in the matrix below */
+   const unsigned char   *allocVectors;   /**< Number of bits in each band for several rates */
+   const opus_int16 *logN;
+
+   const opus_val16 *window;
+   mdct_lookup mdct;
+   PulseCache cache;
+};
+
+
+#endif
diff --git a/opus/celt/opus_custom_demo.c b/opus/celt/opus_custom_demo.c
new file mode 100644 (file)
index 0000000..ae41c0d
--- /dev/null
@@ -0,0 +1,210 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_custom.h"
+#include "arch.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+
+#define MAX_PACKET 1275
+
+int main(int argc, char *argv[])
+{
+   int err;
+   char *inFile, *outFile;
+   FILE *fin, *fout;
+   OpusCustomMode *mode=NULL;
+   OpusCustomEncoder *enc;
+   OpusCustomDecoder *dec;
+   int len;
+   opus_int32 frame_size, channels, rate;
+   int bytes_per_packet;
+   unsigned char data[MAX_PACKET];
+   int complexity;
+#if !(defined (FIXED_POINT) && !defined(CUSTOM_MODES)) && defined(RESYNTH)
+   int i;
+   double rmsd = 0;
+#endif
+   int count = 0;
+   opus_int32 skip;
+   opus_int16 *in, *out;
+   if (argc != 9 && argc != 8 && argc != 7)
+   {
+      fprintf (stderr, "Usage: test_opus_custom <rate> <channels> <frame size> "
+               " <bytes per packet> [<complexity> [packet loss rate]] "
+               "<input> <output>\n");
+      return 1;
+   }
+
+   rate = (opus_int32)atol(argv[1]);
+   channels = atoi(argv[2]);
+   frame_size = atoi(argv[3]);
+   mode = opus_custom_mode_create(rate, frame_size, NULL);
+   if (mode == NULL)
+   {
+      fprintf(stderr, "failed to create a mode\n");
+      return 1;
+   }
+
+   bytes_per_packet = atoi(argv[4]);
+   if (bytes_per_packet < 0 || bytes_per_packet > MAX_PACKET)
+   {
+      fprintf (stderr, "bytes per packet must be between 0 and %d\n",
+                        MAX_PACKET);
+      return 1;
+   }
+
+   inFile = argv[argc-2];
+   fin = fopen(inFile, "rb");
+   if (!fin)
+   {
+      fprintf (stderr, "Could not open input file %s\n", argv[argc-2]);
+      return 1;
+   }
+   outFile = argv[argc-1];
+   fout = fopen(outFile, "wb+");
+   if (!fout)
+   {
+      fprintf (stderr, "Could not open output file %s\n", argv[argc-1]);
+      fclose(fin);
+      return 1;
+   }
+
+   enc = opus_custom_encoder_create(mode, channels, &err);
+   if (err != 0)
+   {
+      fprintf(stderr, "Failed to create the encoder: %s\n", opus_strerror(err));
+      fclose(fin);
+      fclose(fout);
+      return 1;
+   }
+   dec = opus_custom_decoder_create(mode, channels, &err);
+   if (err != 0)
+   {
+      fprintf(stderr, "Failed to create the decoder: %s\n", opus_strerror(err));
+      fclose(fin);
+      fclose(fout);
+      return 1;
+   }
+   opus_custom_decoder_ctl(dec, OPUS_GET_LOOKAHEAD(&skip));
+
+   if (argc>7)
+   {
+      complexity=atoi(argv[5]);
+      opus_custom_encoder_ctl(enc,OPUS_SET_COMPLEXITY(complexity));
+   }
+
+   in = (opus_int16*)malloc(frame_size*channels*sizeof(opus_int16));
+   out = (opus_int16*)malloc(frame_size*channels*sizeof(opus_int16));
+
+   while (!feof(fin))
+   {
+      int ret;
+      err = fread(in, sizeof(short), frame_size*channels, fin);
+      if (feof(fin))
+         break;
+      len = opus_custom_encode(enc, in, frame_size, data, bytes_per_packet);
+      if (len <= 0)
+         fprintf (stderr, "opus_custom_encode() failed: %s\n", opus_strerror(len));
+
+      /* This is for simulating bit errors */
+#if 0
+      int errors = 0;
+      int eid = 0;
+      /* This simulates random bit error */
+      for (i=0;i<len*8;i++)
+      {
+         if (rand()%atoi(argv[8])==0)
+         {
+            if (i<64)
+            {
+               errors++;
+               eid = i;
+            }
+            data[i/8] ^= 1<<(7-(i%8));
+         }
+      }
+      if (errors == 1)
+         data[eid/8] ^= 1<<(7-(eid%8));
+      else if (errors%2 == 1)
+         data[rand()%8] ^= 1<<rand()%8;
+#endif
+
+#if 1 /* Set to zero to use the encoder's output instead */
+      /* This is to simulate packet loss */
+      if (argc==9 && rand()%1000<atoi(argv[argc-3]))
+      /*if (errors && (errors%2==0))*/
+         ret = opus_custom_decode(dec, NULL, len, out, frame_size);
+      else
+         ret = opus_custom_decode(dec, data, len, out, frame_size);
+      if (ret < 0)
+         fprintf(stderr, "opus_custom_decode() failed: %s\n", opus_strerror(ret));
+#else
+      for (i=0;i<ret*channels;i++)
+         out[i] = in[i];
+#endif
+#if !(defined (FIXED_POINT) && !defined(CUSTOM_MODES)) && defined(RESYNTH)
+      for (i=0;i<ret*channels;i++)
+      {
+         rmsd += (in[i]-out[i])*1.0*(in[i]-out[i]);
+         /*out[i] -= in[i];*/
+      }
+#endif
+      count++;
+      fwrite(out+skip*channels, sizeof(short), (ret-skip)*channels, fout);
+      skip = 0;
+   }
+   PRINT_MIPS(stderr);
+
+   opus_custom_encoder_destroy(enc);
+   opus_custom_decoder_destroy(dec);
+   fclose(fin);
+   fclose(fout);
+   opus_custom_mode_destroy(mode);
+   free(in);
+   free(out);
+#if !(defined (FIXED_POINT) && !defined(CUSTOM_MODES)) && defined(RESYNTH)
+   if (rmsd > 0)
+   {
+      rmsd = sqrt(rmsd/(1.0*frame_size*channels*count));
+      fprintf (stderr, "Error: encoder doesn't match decoder\n");
+      fprintf (stderr, "RMS mismatch is %f\n", rmsd);
+      return 1;
+   } else {
+      fprintf (stderr, "Encoder matches decoder!!\n");
+   }
+#endif
+   return 0;
+}
+
diff --git a/opus/celt/os_support.h b/opus/celt/os_support.h
new file mode 100644 (file)
index 0000000..a217197
--- /dev/null
@@ -0,0 +1,92 @@
+/* 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.
+
+   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 "opus_types.h"
+#include "opus_defines.h"
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/** Opus wrapper for malloc(). To do your own dynamic allocation, all you need to do is replace this function and opus_free */
+#ifndef OVERRIDE_OPUS_ALLOC
+static OPUS_INLINE void *opus_alloc (size_t size)
+{
+   return malloc(size);
+}
+#endif
+
+/** Same as celt_alloc(), except that the area is only needed inside a CELT call (might cause problem with wideband though) */
+#ifndef OVERRIDE_OPUS_ALLOC_SCRATCH
+static OPUS_INLINE void *opus_alloc_scratch (size_t size)
+{
+   /* Scratch space doesn't need to be cleared */
+   return opus_alloc(size);
+}
+#endif
+
+/** Opus wrapper for free(). To do your own dynamic allocation, all you need to do is replace this function and opus_alloc */
+#ifndef OVERRIDE_OPUS_FREE
+static OPUS_INLINE void opus_free (void *ptr)
+{
+   free(ptr);
+}
+#endif
+
+/** Copy n elements from src to dst. The 0* term provides compile-time type checking  */
+#ifndef OVERRIDE_OPUS_COPY
+#define OPUS_COPY(dst, src, n) (memcpy((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
+#endif
+
+/** Copy n elements from src to dst, allowing overlapping regions. The 0* term
+    provides compile-time type checking */
+#ifndef OVERRIDE_OPUS_MOVE
+#define OPUS_MOVE(dst, src, n) (memmove((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
+#endif
+
+/** Set n elements of dst to zero */
+#ifndef OVERRIDE_OPUS_CLEAR
+#define OPUS_CLEAR(dst, n) (memset((dst), 0, (n)*sizeof(*(dst))))
+#endif
+
+/*#ifdef __GNUC__
+#pragma GCC poison printf sprintf
+#pragma GCC poison malloc free realloc calloc
+#endif*/
+
+#endif /* OS_SUPPORT_H */
+
diff --git a/opus/celt/pitch.c b/opus/celt/pitch.c
new file mode 100644 (file)
index 0000000..5b061d8
--- /dev/null
@@ -0,0 +1,544 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by Jean-Marc Valin */
+/**
+   @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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "pitch.h"
+#include "os_support.h"
+#include "modes.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "celt_lpc.h"
+
+static void find_best_pitch(opus_val32 *xcorr, opus_val16 *y, int len,
+                            int max_pitch, int *best_pitch
+#ifdef FIXED_POINT
+                            , int yshift, opus_val32 maxcorr
+#endif
+                            )
+{
+   int i, j;
+   opus_val32 Syy=1;
+   opus_val16 best_num[2];
+   opus_val32 best_den[2];
+#ifdef FIXED_POINT
+   int xshift;
+
+   xshift = celt_ilog2(maxcorr)-14;
+#endif
+
+   best_num[0] = -1;
+   best_num[1] = -1;
+   best_den[0] = 0;
+   best_den[1] = 0;
+   best_pitch[0] = 0;
+   best_pitch[1] = 1;
+   for (j=0;j<len;j++)
+      Syy = ADD32(Syy, SHR32(MULT16_16(y[j],y[j]), yshift));
+   for (i=0;i<max_pitch;i++)
+   {
+      if (xcorr[i]>0)
+      {
+         opus_val16 num;
+         opus_val32 xcorr16;
+         xcorr16 = EXTRACT16(VSHR32(xcorr[i], xshift));
+#ifndef FIXED_POINT
+         /* Considering the range of xcorr16, this should avoid both underflows
+            and overflows (inf) when squaring xcorr16 */
+         xcorr16 *= 1e-12f;
+#endif
+         num = MULT16_16_Q15(xcorr16,xcorr16);
+         if (MULT16_32_Q15(num,best_den[1]) > MULT16_32_Q15(best_num[1],Syy))
+         {
+            if (MULT16_32_Q15(num,best_den[0]) > MULT16_32_Q15(best_num[0],Syy))
+            {
+               best_num[1] = best_num[0];
+               best_den[1] = best_den[0];
+               best_pitch[1] = best_pitch[0];
+               best_num[0] = num;
+               best_den[0] = Syy;
+               best_pitch[0] = i;
+            } else {
+               best_num[1] = num;
+               best_den[1] = Syy;
+               best_pitch[1] = i;
+            }
+         }
+      }
+      Syy += SHR32(MULT16_16(y[i+len],y[i+len]),yshift) - SHR32(MULT16_16(y[i],y[i]),yshift);
+      Syy = MAX32(1, Syy);
+   }
+}
+
+static void celt_fir5(const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         opus_val16 *mem)
+{
+   int i;
+   opus_val16 num0, num1, num2, num3, num4;
+   opus_val32 mem0, mem1, mem2, mem3, mem4;
+   num0=num[0];
+   num1=num[1];
+   num2=num[2];
+   num3=num[3];
+   num4=num[4];
+   mem0=mem[0];
+   mem1=mem[1];
+   mem2=mem[2];
+   mem3=mem[3];
+   mem4=mem[4];
+   for (i=0;i<N;i++)
+   {
+      opus_val32 sum = SHL32(EXTEND32(x[i]), SIG_SHIFT);
+      sum = MAC16_16(sum,num0,mem0);
+      sum = MAC16_16(sum,num1,mem1);
+      sum = MAC16_16(sum,num2,mem2);
+      sum = MAC16_16(sum,num3,mem3);
+      sum = MAC16_16(sum,num4,mem4);
+      mem4 = mem3;
+      mem3 = mem2;
+      mem2 = mem1;
+      mem1 = mem0;
+      mem0 = x[i];
+      y[i] = ROUND16(sum, SIG_SHIFT);
+   }
+   mem[0]=mem0;
+   mem[1]=mem1;
+   mem[2]=mem2;
+   mem[3]=mem3;
+   mem[4]=mem4;
+}
+
+
+void pitch_downsample(celt_sig * OPUS_RESTRICT x[], opus_val16 * OPUS_RESTRICT x_lp,
+      int len, int C, int arch)
+{
+   int i;
+   opus_val32 ac[5];
+   opus_val16 tmp=Q15ONE;
+   opus_val16 lpc[4], mem[5]={0,0,0,0,0};
+   opus_val16 lpc2[5];
+   opus_val16 c1 = QCONST16(.8f,15);
+#ifdef FIXED_POINT
+   int shift;
+   opus_val32 maxabs = celt_maxabs32(x[0], len);
+   if (C==2)
+   {
+      opus_val32 maxabs_1 = celt_maxabs32(x[1], len);
+      maxabs = MAX32(maxabs, maxabs_1);
+   }
+   if (maxabs<1)
+      maxabs=1;
+   shift = celt_ilog2(maxabs)-10;
+   if (shift<0)
+      shift=0;
+   if (C==2)
+      shift++;
+#endif
+   for (i=1;i<len>>1;i++)
+      x_lp[i] = SHR32(HALF32(HALF32(x[0][(2*i-1)]+x[0][(2*i+1)])+x[0][2*i]), shift);
+   x_lp[0] = SHR32(HALF32(HALF32(x[0][1])+x[0][0]), shift);
+   if (C==2)
+   {
+      for (i=1;i<len>>1;i++)
+         x_lp[i] += SHR32(HALF32(HALF32(x[1][(2*i-1)]+x[1][(2*i+1)])+x[1][2*i]), shift);
+      x_lp[0] += SHR32(HALF32(HALF32(x[1][1])+x[1][0]), shift);
+   }
+
+   _celt_autocorr(x_lp, ac, NULL, 0,
+                  4, len>>1, arch);
+
+   /* Noise floor -40 dB */
+#ifdef FIXED_POINT
+   ac[0] += SHR32(ac[0],13);
+#else
+   ac[0] *= 1.0001f;
+#endif
+   /* Lag windowing */
+   for (i=1;i<=4;i++)
+   {
+      /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
+#ifdef FIXED_POINT
+      ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
+#else
+      ac[i] -= ac[i]*(.008f*i)*(.008f*i);
+#endif
+   }
+
+   _celt_lpc(lpc, ac, 4);
+   for (i=0;i<4;i++)
+   {
+      tmp = MULT16_16_Q15(QCONST16(.9f,15), tmp);
+      lpc[i] = MULT16_16_Q15(lpc[i], tmp);
+   }
+   /* Add a zero */
+   lpc2[0] = lpc[0] + QCONST16(.8f,SIG_SHIFT);
+   lpc2[1] = lpc[1] + MULT16_16_Q15(c1,lpc[0]);
+   lpc2[2] = lpc[2] + MULT16_16_Q15(c1,lpc[1]);
+   lpc2[3] = lpc[3] + MULT16_16_Q15(c1,lpc[2]);
+   lpc2[4] = MULT16_16_Q15(c1,lpc[3]);
+   celt_fir5(x_lp, lpc2, x_lp, len>>1, mem);
+}
+
+/* Pure C implementation. */
+#ifdef FIXED_POINT
+opus_val32
+#else
+void
+#endif
+celt_pitch_xcorr_c(const opus_val16 *_x, const opus_val16 *_y,
+      opus_val32 *xcorr, int len, int max_pitch, int arch)
+{
+
+#if 0 /* This is a simple version of the pitch correlation that should work
+         well on DSPs like Blackfin and TI C5x/C6x */
+   int i, j;
+#ifdef FIXED_POINT
+   opus_val32 maxcorr=1;
+#endif
+#if !defined(OVERRIDE_PITCH_XCORR)
+   (void)arch;
+#endif
+   for (i=0;i<max_pitch;i++)
+   {
+      opus_val32 sum = 0;
+      for (j=0;j<len;j++)
+         sum = MAC16_16(sum, _x[j], _y[i+j]);
+      xcorr[i] = sum;
+#ifdef FIXED_POINT
+      maxcorr = MAX32(maxcorr, sum);
+#endif
+   }
+#ifdef FIXED_POINT
+   return maxcorr;
+#endif
+
+#else /* Unrolled version of the pitch correlation -- runs faster on x86 and ARM */
+   int i;
+   /*The EDSP version requires that max_pitch is at least 1, and that _x is
+      32-bit aligned.
+     Since it's hard to put asserts in assembly, put them here.*/
+#ifdef FIXED_POINT
+   opus_val32 maxcorr=1;
+#endif
+   celt_assert(max_pitch>0);
+   celt_assert((((unsigned char *)_x-(unsigned char *)NULL)&3)==0);
+   for (i=0;i<max_pitch-3;i+=4)
+   {
+      opus_val32 sum[4]={0,0,0,0};
+      xcorr_kernel(_x, _y+i, sum, len, arch);
+      xcorr[i]=sum[0];
+      xcorr[i+1]=sum[1];
+      xcorr[i+2]=sum[2];
+      xcorr[i+3]=sum[3];
+#ifdef FIXED_POINT
+      sum[0] = MAX32(sum[0], sum[1]);
+      sum[2] = MAX32(sum[2], sum[3]);
+      sum[0] = MAX32(sum[0], sum[2]);
+      maxcorr = MAX32(maxcorr, sum[0]);
+#endif
+   }
+   /* In case max_pitch isn't a multiple of 4, do non-unrolled version. */
+   for (;i<max_pitch;i++)
+   {
+      opus_val32 sum;
+      sum = celt_inner_prod(_x, _y+i, len, arch);
+      xcorr[i] = sum;
+#ifdef FIXED_POINT
+      maxcorr = MAX32(maxcorr, sum);
+#endif
+   }
+#ifdef FIXED_POINT
+   return maxcorr;
+#endif
+#endif
+}
+
+void pitch_search(const opus_val16 * OPUS_RESTRICT x_lp, opus_val16 * OPUS_RESTRICT y,
+                  int len, int max_pitch, int *pitch, int arch)
+{
+   int i, j;
+   int lag;
+   int best_pitch[2]={0,0};
+   VARDECL(opus_val16, x_lp4);
+   VARDECL(opus_val16, y_lp4);
+   VARDECL(opus_val32, xcorr);
+#ifdef FIXED_POINT
+   opus_val32 maxcorr;
+   opus_val32 xmax, ymax;
+   int shift=0;
+#endif
+   int offset;
+
+   SAVE_STACK;
+
+   celt_assert(len>0);
+   celt_assert(max_pitch>0);
+   lag = len+max_pitch;
+
+   ALLOC(x_lp4, len>>2, opus_val16);
+   ALLOC(y_lp4, lag>>2, opus_val16);
+   ALLOC(xcorr, max_pitch>>1, opus_val32);
+
+   /* Downsample by 2 again */
+   for (j=0;j<len>>2;j++)
+      x_lp4[j] = x_lp[2*j];
+   for (j=0;j<lag>>2;j++)
+      y_lp4[j] = y[2*j];
+
+#ifdef FIXED_POINT
+   xmax = celt_maxabs16(x_lp4, len>>2);
+   ymax = celt_maxabs16(y_lp4, lag>>2);
+   shift = celt_ilog2(MAX32(1, MAX32(xmax, ymax)))-11;
+   if (shift>0)
+   {
+      for (j=0;j<len>>2;j++)
+         x_lp4[j] = SHR16(x_lp4[j], shift);
+      for (j=0;j<lag>>2;j++)
+         y_lp4[j] = SHR16(y_lp4[j], shift);
+      /* Use double the shift for a MAC */
+      shift *= 2;
+   } else {
+      shift = 0;
+   }
+#endif
+
+   /* Coarse search with 4x decimation */
+
+#ifdef FIXED_POINT
+   maxcorr =
+#endif
+   celt_pitch_xcorr(x_lp4, y_lp4, xcorr, len>>2, max_pitch>>2, arch);
+
+   find_best_pitch(xcorr, y_lp4, len>>2, max_pitch>>2, best_pitch
+#ifdef FIXED_POINT
+                   , 0, maxcorr
+#endif
+                   );
+
+   /* Finer search with 2x decimation */
+#ifdef FIXED_POINT
+   maxcorr=1;
+#endif
+   for (i=0;i<max_pitch>>1;i++)
+   {
+      opus_val32 sum;
+      xcorr[i] = 0;
+      if (abs(i-2*best_pitch[0])>2 && abs(i-2*best_pitch[1])>2)
+         continue;
+#ifdef FIXED_POINT
+      sum = 0;
+      for (j=0;j<len>>1;j++)
+         sum += SHR32(MULT16_16(x_lp[j],y[i+j]), shift);
+#else
+      sum = celt_inner_prod(x_lp, y+i, len>>1, arch);
+#endif
+      xcorr[i] = MAX32(-1, sum);
+#ifdef FIXED_POINT
+      maxcorr = MAX32(maxcorr, sum);
+#endif
+   }
+   find_best_pitch(xcorr, y, len>>1, max_pitch>>1, best_pitch
+#ifdef FIXED_POINT
+                   , shift+1, maxcorr
+#endif
+                   );
+
+   /* Refine by pseudo-interpolation */
+   if (best_pitch[0]>0 && best_pitch[0]<(max_pitch>>1)-1)
+   {
+      opus_val32 a, b, c;
+      a = xcorr[best_pitch[0]-1];
+      b = xcorr[best_pitch[0]];
+      c = xcorr[best_pitch[0]+1];
+      if ((c-a) > MULT16_32_Q15(QCONST16(.7f,15),b-a))
+         offset = 1;
+      else if ((a-c) > MULT16_32_Q15(QCONST16(.7f,15),b-c))
+         offset = -1;
+      else
+         offset = 0;
+   } else {
+      offset = 0;
+   }
+   *pitch = 2*best_pitch[0]-offset;
+
+   RESTORE_STACK;
+}
+
+#ifdef FIXED_POINT
+static opus_val16 compute_pitch_gain(opus_val32 xy, opus_val32 xx, opus_val32 yy)
+{
+   opus_val32 x2y2;
+   int sx, sy, shift;
+   opus_val32 g;
+   opus_val16 den;
+   if (xy == 0 || xx == 0 || yy == 0)
+      return 0;
+   sx = celt_ilog2(xx)-14;
+   sy = celt_ilog2(yy)-14;
+   shift = sx + sy;
+   x2y2 = SHR32(MULT16_16(VSHR32(xx, sx), VSHR32(yy, sy)), 14);
+   if (shift & 1) {
+      if (x2y2 < 32768)
+      {
+         x2y2 <<= 1;
+         shift--;
+      } else {
+         x2y2 >>= 1;
+         shift++;
+      }
+   }
+   den = celt_rsqrt_norm(x2y2);
+   g = MULT16_32_Q15(den, xy);
+   g = VSHR32(g, (shift>>1)-1);
+   return EXTRACT16(MIN32(g, Q15ONE));
+}
+#else
+static opus_val16 compute_pitch_gain(opus_val32 xy, opus_val32 xx, opus_val32 yy)
+{
+   return xy/celt_sqrt(1+xx*yy);
+}
+#endif
+
+static const int second_check[16] = {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2};
+opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod,
+      int N, int *T0_, int prev_period, opus_val16 prev_gain, int arch)
+{
+   int k, i, T, T0;
+   opus_val16 g, g0;
+   opus_val16 pg;
+   opus_val32 xy,xx,yy,xy2;
+   opus_val32 xcorr[3];
+   opus_val32 best_xy, best_yy;
+   int offset;
+   int minperiod0;
+   VARDECL(opus_val32, yy_lookup);
+   SAVE_STACK;
+
+   minperiod0 = minperiod;
+   maxperiod /= 2;
+   minperiod /= 2;
+   *T0_ /= 2;
+   prev_period /= 2;
+   N /= 2;
+   x += maxperiod;
+   if (*T0_>=maxperiod)
+      *T0_=maxperiod-1;
+
+   T = T0 = *T0_;
+   ALLOC(yy_lookup, maxperiod+1, opus_val32);
+   dual_inner_prod(x, x, x-T0, N, &xx, &xy, arch);
+   yy_lookup[0] = xx;
+   yy=xx;
+   for (i=1;i<=maxperiod;i++)
+   {
+      yy = yy+MULT16_16(x[-i],x[-i])-MULT16_16(x[N-i],x[N-i]);
+      yy_lookup[i] = MAX32(0, yy);
+   }
+   yy = yy_lookup[T0];
+   best_xy = xy;
+   best_yy = yy;
+   g = g0 = compute_pitch_gain(xy, xx, yy);
+   /* Look for any pitch at T/k */
+   for (k=2;k<=15;k++)
+   {
+      int T1, T1b;
+      opus_val16 g1;
+      opus_val16 cont=0;
+      opus_val16 thresh;
+      T1 = celt_udiv(2*T0+k, 2*k);
+      if (T1 < minperiod)
+         break;
+      /* Look for another strong correlation at T1b */
+      if (k==2)
+      {
+         if (T1+T0>maxperiod)
+            T1b = T0;
+         else
+            T1b = T0+T1;
+      } else
+      {
+         T1b = celt_udiv(2*second_check[k]*T0+k, 2*k);
+      }
+      dual_inner_prod(x, &x[-T1], &x[-T1b], N, &xy, &xy2, arch);
+      xy = HALF32(xy + xy2);
+      yy = HALF32(yy_lookup[T1] + yy_lookup[T1b]);
+      g1 = compute_pitch_gain(xy, xx, yy);
+      if (abs(T1-prev_period)<=1)
+         cont = prev_gain;
+      else if (abs(T1-prev_period)<=2 && 5*k*k < T0)
+         cont = HALF16(prev_gain);
+      else
+         cont = 0;
+      thresh = MAX16(QCONST16(.3f,15), MULT16_16_Q15(QCONST16(.7f,15),g0)-cont);
+      /* Bias against very high pitch (very short period) to avoid false-positives
+         due to short-term correlation */
+      if (T1<3*minperiod)
+         thresh = MAX16(QCONST16(.4f,15), MULT16_16_Q15(QCONST16(.85f,15),g0)-cont);
+      else if (T1<2*minperiod)
+         thresh = MAX16(QCONST16(.5f,15), MULT16_16_Q15(QCONST16(.9f,15),g0)-cont);
+      if (g1 > thresh)
+      {
+         best_xy = xy;
+         best_yy = yy;
+         T = T1;
+         g = g1;
+      }
+   }
+   best_xy = MAX32(0, best_xy);
+   if (best_yy <= best_xy)
+      pg = Q15ONE;
+   else
+      pg = SHR32(frac_div32(best_xy,best_yy+1),16);
+
+   for (k=0;k<3;k++)
+      xcorr[k] = celt_inner_prod(x, x-(T+k-1), N, arch);
+   if ((xcorr[2]-xcorr[0]) > MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[0]))
+      offset = 1;
+   else if ((xcorr[0]-xcorr[2]) > MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[2]))
+      offset = -1;
+   else
+      offset = 0;
+   if (pg > g)
+      pg = g;
+   *T0_ = 2*T+offset;
+
+   if (*T0_<minperiod0)
+      *T0_=minperiod0;
+   RESTORE_STACK;
+   return pg;
+}
diff --git a/opus/celt/pitch.h b/opus/celt/pitch.h
new file mode 100644 (file)
index 0000000..e425f56
--- /dev/null
@@ -0,0 +1,192 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by Jean-Marc Valin */
+/**
+   @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.
+
+   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 PITCH_H
+#define PITCH_H
+
+#include "modes.h"
+#include "cpu_support.h"
+
+#if (defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT)) \
+  || ((defined(OPUS_X86_MAY_HAVE_SSE4_1) || defined(OPUS_X86_MAY_HAVE_SSE2)) && defined(FIXED_POINT))
+#include "x86/pitch_sse.h"
+#endif
+
+#if defined(MIPSr1_ASM)
+#include "mips/pitch_mipsr1.h"
+#endif
+
+#if (defined(OPUS_ARM_ASM) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR))
+# include "arm/pitch_arm.h"
+#endif
+
+void pitch_downsample(celt_sig * OPUS_RESTRICT x[], opus_val16 * OPUS_RESTRICT x_lp,
+      int len, int C, int arch);
+
+void pitch_search(const opus_val16 * OPUS_RESTRICT x_lp, opus_val16 * OPUS_RESTRICT y,
+                  int len, int max_pitch, int *pitch, int arch);
+
+opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod,
+      int N, int *T0, int prev_period, opus_val16 prev_gain, int arch);
+
+
+/* OPT: This is the kernel you really want to optimize. It gets used a lot
+   by the prefilter and by the PLC. */
+static OPUS_INLINE void xcorr_kernel_c(const opus_val16 * x, const opus_val16 * y, opus_val32 sum[4], int len)
+{
+   int j;
+   opus_val16 y_0, y_1, y_2, y_3;
+   celt_assert(len>=3);
+   y_3=0; /* gcc doesn't realize that y_3 can't be used uninitialized */
+   y_0=*y++;
+   y_1=*y++;
+   y_2=*y++;
+   for (j=0;j<len-3;j+=4)
+   {
+      opus_val16 tmp;
+      tmp = *x++;
+      y_3=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_0);
+      sum[1] = MAC16_16(sum[1],tmp,y_1);
+      sum[2] = MAC16_16(sum[2],tmp,y_2);
+      sum[3] = MAC16_16(sum[3],tmp,y_3);
+      tmp=*x++;
+      y_0=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_1);
+      sum[1] = MAC16_16(sum[1],tmp,y_2);
+      sum[2] = MAC16_16(sum[2],tmp,y_3);
+      sum[3] = MAC16_16(sum[3],tmp,y_0);
+      tmp=*x++;
+      y_1=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_2);
+      sum[1] = MAC16_16(sum[1],tmp,y_3);
+      sum[2] = MAC16_16(sum[2],tmp,y_0);
+      sum[3] = MAC16_16(sum[3],tmp,y_1);
+      tmp=*x++;
+      y_2=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_3);
+      sum[1] = MAC16_16(sum[1],tmp,y_0);
+      sum[2] = MAC16_16(sum[2],tmp,y_1);
+      sum[3] = MAC16_16(sum[3],tmp,y_2);
+   }
+   if (j++<len)
+   {
+      opus_val16 tmp = *x++;
+      y_3=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_0);
+      sum[1] = MAC16_16(sum[1],tmp,y_1);
+      sum[2] = MAC16_16(sum[2],tmp,y_2);
+      sum[3] = MAC16_16(sum[3],tmp,y_3);
+   }
+   if (j++<len)
+   {
+      opus_val16 tmp=*x++;
+      y_0=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_1);
+      sum[1] = MAC16_16(sum[1],tmp,y_2);
+      sum[2] = MAC16_16(sum[2],tmp,y_3);
+      sum[3] = MAC16_16(sum[3],tmp,y_0);
+   }
+   if (j<len)
+   {
+      opus_val16 tmp=*x++;
+      y_1=*y++;
+      sum[0] = MAC16_16(sum[0],tmp,y_2);
+      sum[1] = MAC16_16(sum[1],tmp,y_3);
+      sum[2] = MAC16_16(sum[2],tmp,y_0);
+      sum[3] = MAC16_16(sum[3],tmp,y_1);
+   }
+}
+
+#ifndef OVERRIDE_XCORR_KERNEL
+#define xcorr_kernel(x, y, sum, len, arch) \
+    ((void)(arch),xcorr_kernel_c(x, y, sum, len))
+#endif /* OVERRIDE_XCORR_KERNEL */
+
+
+static OPUS_INLINE void dual_inner_prod_c(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+      int N, opus_val32 *xy1, opus_val32 *xy2)
+{
+   int i;
+   opus_val32 xy01=0;
+   opus_val32 xy02=0;
+   for (i=0;i<N;i++)
+   {
+      xy01 = MAC16_16(xy01, x[i], y01[i]);
+      xy02 = MAC16_16(xy02, x[i], y02[i]);
+   }
+   *xy1 = xy01;
+   *xy2 = xy02;
+}
+
+#ifndef OVERRIDE_DUAL_INNER_PROD
+# define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) \
+    ((void)(arch),dual_inner_prod_c(x, y01, y02, N, xy1, xy2))
+#endif
+
+/*We make sure a C version is always available for cases where the overhead of
+  vectorization and passing around an arch flag aren't worth it.*/
+static OPUS_INLINE opus_val32 celt_inner_prod_c(const opus_val16 *x,
+      const opus_val16 *y, int N)
+{
+   int i;
+   opus_val32 xy=0;
+   for (i=0;i<N;i++)
+      xy = MAC16_16(xy, x[i], y[i]);
+   return xy;
+}
+
+#if !defined(OVERRIDE_CELT_INNER_PROD)
+# define celt_inner_prod(x, y, N, arch) \
+    ((void)(arch),celt_inner_prod_c(x, y, N))
+#endif
+
+#ifdef NON_STATIC_COMB_FILTER_CONST_C
+void comb_filter_const_c(opus_val32 *y, opus_val32 *x, int T, int N,
+     opus_val16 g10, opus_val16 g11, opus_val16 g12);
+#endif
+
+
+#ifdef FIXED_POINT
+opus_val32
+#else
+void
+#endif
+celt_pitch_xcorr_c(const opus_val16 *_x, const opus_val16 *_y,
+      opus_val32 *xcorr, int len, int max_pitch, int arch);
+
+#ifndef OVERRIDE_PITCH_XCORR
+# define celt_pitch_xcorr celt_pitch_xcorr_c
+#endif
+
+#endif
diff --git a/opus/celt/quant_bands.c b/opus/celt/quant_bands.c
new file mode 100644 (file)
index 0000000..56101b1
--- /dev/null
@@ -0,0 +1,563 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#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"
+#include "rate.h"
+
+#ifdef FIXED_POINT
+/* Mean energy in each band quantized in Q4 */
+const signed char eMeans[25] = {
+      103,100, 92, 85, 81,
+       77, 72, 70, 78, 75,
+       73, 71, 78, 74, 69,
+       72, 70, 74, 76, 71,
+       60, 60, 60, 60, 60
+};
+#else
+/* Mean energy in each band quantized in Q4 and converted back to float */
+const opus_val16 eMeans[25] = {
+      6.437500f, 6.250000f, 5.750000f, 5.312500f, 5.062500f,
+      4.812500f, 4.500000f, 4.375000f, 4.875000f, 4.687500f,
+      4.562500f, 4.437500f, 4.875000f, 4.625000f, 4.312500f,
+      4.500000f, 4.375000f, 4.625000f, 4.750000f, 4.437500f,
+      3.750000f, 3.750000f, 3.750000f, 3.750000f, 3.750000f
+};
+#endif
+/* prediction coefficients: 0.9, 0.8, 0.65, 0.5 */
+#ifdef FIXED_POINT
+static const opus_val16 pred_coef[4] = {29440, 26112, 21248, 16384};
+static const opus_val16 beta_coef[4] = {30147, 22282, 12124, 6554};
+static const opus_val16 beta_intra = 4915;
+#else
+static const opus_val16 pred_coef[4] = {29440/32768., 26112/32768., 21248/32768., 16384/32768.};
+static const opus_val16 beta_coef[4] = {30147/32768., 22282/32768., 12124/32768., 6554/32768.};
+static const opus_val16 beta_intra = 4915/32768.;
+#endif
+
+/*Parameters of the Laplace-like probability models used for the coarse energy.
+  There is one pair of parameters for each frame size, prediction type
+   (inter/intra), and band number.
+  The first number of each pair is the probability of 0, and the second is the
+   decay rate, both in Q8 precision.*/
+static const unsigned char e_prob_model[4][2][42] = {
+   /*120 sample frames.*/
+   {
+      /*Inter*/
+      {
+          72, 127,  65, 129,  66, 128,  65, 128,  64, 128,  62, 128,  64, 128,
+          64, 128,  92,  78,  92,  79,  92,  78,  90,  79, 116,  41, 115,  40,
+         114,  40, 132,  26, 132,  26, 145,  17, 161,  12, 176,  10, 177,  11
+      },
+      /*Intra*/
+      {
+          24, 179,  48, 138,  54, 135,  54, 132,  53, 134,  56, 133,  55, 132,
+          55, 132,  61, 114,  70,  96,  74,  88,  75,  88,  87,  74,  89,  66,
+          91,  67, 100,  59, 108,  50, 120,  40, 122,  37,  97,  43,  78,  50
+      }
+   },
+   /*240 sample frames.*/
+   {
+      /*Inter*/
+      {
+          83,  78,  84,  81,  88,  75,  86,  74,  87,  71,  90,  73,  93,  74,
+          93,  74, 109,  40, 114,  36, 117,  34, 117,  34, 143,  17, 145,  18,
+         146,  19, 162,  12, 165,  10, 178,   7, 189,   6, 190,   8, 177,   9
+      },
+      /*Intra*/
+      {
+          23, 178,  54, 115,  63, 102,  66,  98,  69,  99,  74,  89,  71,  91,
+          73,  91,  78,  89,  86,  80,  92,  66,  93,  64, 102,  59, 103,  60,
+         104,  60, 117,  52, 123,  44, 138,  35, 133,  31,  97,  38,  77,  45
+      }
+   },
+   /*480 sample frames.*/
+   {
+      /*Inter*/
+      {
+          61,  90,  93,  60, 105,  42, 107,  41, 110,  45, 116,  38, 113,  38,
+         112,  38, 124,  26, 132,  27, 136,  19, 140,  20, 155,  14, 159,  16,
+         158,  18, 170,  13, 177,  10, 187,   8, 192,   6, 175,   9, 159,  10
+      },
+      /*Intra*/
+      {
+          21, 178,  59, 110,  71,  86,  75,  85,  84,  83,  91,  66,  88,  73,
+          87,  72,  92,  75,  98,  72, 105,  58, 107,  54, 115,  52, 114,  55,
+         112,  56, 129,  51, 132,  40, 150,  33, 140,  29,  98,  35,  77,  42
+      }
+   },
+   /*960 sample frames.*/
+   {
+      /*Inter*/
+      {
+          42, 121,  96,  66, 108,  43, 111,  40, 117,  44, 123,  32, 120,  36,
+         119,  33, 127,  33, 134,  34, 139,  21, 147,  23, 152,  20, 158,  25,
+         154,  26, 166,  21, 173,  16, 184,  13, 184,  10, 150,  13, 139,  15
+      },
+      /*Intra*/
+      {
+          22, 178,  63, 114,  74,  82,  84,  83,  92,  82, 103,  62,  96,  72,
+          96,  67, 101,  73, 107,  72, 113,  55, 118,  52, 125,  52, 118,  52,
+         117,  55, 135,  49, 137,  39, 157,  32, 145,  29,  97,  33,  77,  40
+      }
+   }
+};
+
+static const unsigned char small_energy_icdf[3]={2,1,0};
+
+static opus_val32 loss_distortion(const opus_val16 *eBands, opus_val16 *oldEBands, int start, int end, int len, int C)
+{
+   int c, i;
+   opus_val32 dist = 0;
+   c=0; do {
+      for (i=start;i<end;i++)
+      {
+         opus_val16 d = SUB16(SHR16(eBands[i+c*len], 3), SHR16(oldEBands[i+c*len], 3));
+         dist = MAC16_16(dist, d,d);
+      }
+   } while (++c<C);
+   return MIN32(200,SHR32(dist,2*DB_SHIFT-6));
+}
+
+static int quant_coarse_energy_impl(const CELTMode *m, int start, int end,
+      const opus_val16 *eBands, opus_val16 *oldEBands,
+      opus_int32 budget, opus_int32 tell,
+      const unsigned char *prob_model, opus_val16 *error, ec_enc *enc,
+      int C, int LM, int intra, opus_val16 max_decay, int lfe)
+{
+   int i, c;
+   int badness = 0;
+   opus_val32 prev[2] = {0,0};
+   opus_val16 coef;
+   opus_val16 beta;
+
+   if (tell+3 <= budget)
+      ec_enc_bit_logp(enc, intra, 3);
+   if (intra)
+   {
+      coef = 0;
+      beta = beta_intra;
+   } else {
+      beta = beta_coef[LM];
+      coef = pred_coef[LM];
+   }
+
+   /* Encode at a fixed coarse resolution */
+   for (i=start;i<end;i++)
+   {
+      c=0;
+      do {
+         int bits_left;
+         int qi, qi0;
+         opus_val32 q;
+         opus_val16 x;
+         opus_val32 f, tmp;
+         opus_val16 oldE;
+         opus_val16 decay_bound;
+         x = eBands[i+c*m->nbEBands];
+         oldE = MAX16(-QCONST16(9.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]);
+#ifdef FIXED_POINT
+         f = SHL32(EXTEND32(x),7) - PSHR32(MULT16_16(coef,oldE), 8) - prev[c];
+         /* Rounding to nearest integer here is really important! */
+         qi = (f+QCONST32(.5f,DB_SHIFT+7))>>(DB_SHIFT+7);
+         decay_bound = EXTRACT16(MAX32(-QCONST16(28.f,DB_SHIFT),
+               SUB32((opus_val32)oldEBands[i+c*m->nbEBands],max_decay)));
+#else
+         f = x-coef*oldE-prev[c];
+         /* Rounding to nearest integer here is really important! */
+         qi = (int)floor(.5f+f);
+         decay_bound = MAX16(-QCONST16(28.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]) - max_decay;
+#endif
+         /* Prevent the energy from going down too quickly (e.g. for bands
+            that have just one bin) */
+         if (qi < 0 && x < decay_bound)
+         {
+            qi += (int)SHR16(SUB16(decay_bound,x), DB_SHIFT);
+            if (qi > 0)
+               qi = 0;
+         }
+         qi0 = qi;
+         /* If we don't have enough bits to encode all the energy, just assume
+             something safe. */
+         tell = ec_tell(enc);
+         bits_left = budget-tell-3*C*(end-i);
+         if (i!=start && bits_left < 30)
+         {
+            if (bits_left < 24)
+               qi = IMIN(1, qi);
+            if (bits_left < 16)
+               qi = IMAX(-1, qi);
+         }
+         if (lfe && i>=2)
+            qi = IMIN(qi, 0);
+         if (budget-tell >= 15)
+         {
+            int pi;
+            pi = 2*IMIN(i,20);
+            ec_laplace_encode(enc, &qi,
+                  prob_model[pi]<<7, prob_model[pi+1]<<6);
+         }
+         else if(budget-tell >= 2)
+         {
+            qi = IMAX(-1, IMIN(qi, 1));
+            ec_enc_icdf(enc, 2*qi^-(qi<0), small_energy_icdf, 2);
+         }
+         else if(budget-tell >= 1)
+         {
+            qi = IMIN(0, qi);
+            ec_enc_bit_logp(enc, -qi, 1);
+         }
+         else
+            qi = -1;
+         error[i+c*m->nbEBands] = PSHR32(f,7) - SHL16(qi,DB_SHIFT);
+         badness += abs(qi0-qi);
+         q = (opus_val32)SHL32(EXTEND32(qi),DB_SHIFT);
+
+         tmp = PSHR32(MULT16_16(coef,oldE),8) + prev[c] + SHL32(q,7);
+#ifdef FIXED_POINT
+         tmp = MAX32(-QCONST32(28.f, DB_SHIFT+7), tmp);
+#endif
+         oldEBands[i+c*m->nbEBands] = PSHR32(tmp, 7);
+         prev[c] = prev[c] + SHL32(q,7) - MULT16_16(beta,PSHR32(q,8));
+      } while (++c < C);
+   }
+   return lfe ? 0 : badness;
+}
+
+void quant_coarse_energy(const CELTMode *m, int start, int end, int effEnd,
+      const opus_val16 *eBands, opus_val16 *oldEBands, opus_uint32 budget,
+      opus_val16 *error, ec_enc *enc, int C, int LM, int nbAvailableBytes,
+      int force_intra, opus_val32 *delayedIntra, int two_pass, int loss_rate, int lfe)
+{
+   int intra;
+   opus_val16 max_decay;
+   VARDECL(opus_val16, oldEBands_intra);
+   VARDECL(opus_val16, error_intra);
+   ec_enc enc_start_state;
+   opus_uint32 tell;
+   int badness1=0;
+   opus_int32 intra_bias;
+   opus_val32 new_distortion;
+   SAVE_STACK;
+
+   intra = force_intra || (!two_pass && *delayedIntra>2*C*(end-start) && nbAvailableBytes > (end-start)*C);
+   intra_bias = (opus_int32)((budget**delayedIntra*loss_rate)/(C*512));
+   new_distortion = loss_distortion(eBands, oldEBands, start, effEnd, m->nbEBands, C);
+
+   tell = ec_tell(enc);
+   if (tell+3 > budget)
+      two_pass = intra = 0;
+
+   max_decay = QCONST16(16.f,DB_SHIFT);
+   if (end-start>10)
+   {
+#ifdef FIXED_POINT
+      max_decay = MIN32(max_decay, SHL32(EXTEND32(nbAvailableBytes),DB_SHIFT-3));
+#else
+      max_decay = MIN32(max_decay, .125f*nbAvailableBytes);
+#endif
+   }
+   if (lfe)
+      max_decay = QCONST16(3.f,DB_SHIFT);
+   enc_start_state = *enc;
+
+   ALLOC(oldEBands_intra, C*m->nbEBands, opus_val16);
+   ALLOC(error_intra, C*m->nbEBands, opus_val16);
+   OPUS_COPY(oldEBands_intra, oldEBands, C*m->nbEBands);
+
+   if (two_pass || intra)
+   {
+      badness1 = quant_coarse_energy_impl(m, start, end, eBands, oldEBands_intra, budget,
+            tell, e_prob_model[LM][1], error_intra, enc, C, LM, 1, max_decay, lfe);
+   }
+
+   if (!intra)
+   {
+      unsigned char *intra_buf;
+      ec_enc enc_intra_state;
+      opus_int32 tell_intra;
+      opus_uint32 nstart_bytes;
+      opus_uint32 nintra_bytes;
+      opus_uint32 save_bytes;
+      int badness2;
+      VARDECL(unsigned char, intra_bits);
+
+      tell_intra = ec_tell_frac(enc);
+
+      enc_intra_state = *enc;
+
+      nstart_bytes = ec_range_bytes(&enc_start_state);
+      nintra_bytes = ec_range_bytes(&enc_intra_state);
+      intra_buf = ec_get_buffer(&enc_intra_state) + nstart_bytes;
+      save_bytes = nintra_bytes-nstart_bytes;
+      if (save_bytes == 0)
+         save_bytes = ALLOC_NONE;
+      ALLOC(intra_bits, save_bytes, unsigned char);
+      /* Copy bits from intra bit-stream */
+      OPUS_COPY(intra_bits, intra_buf, nintra_bytes - nstart_bytes);
+
+      *enc = enc_start_state;
+
+      badness2 = quant_coarse_energy_impl(m, start, end, eBands, oldEBands, budget,
+            tell, e_prob_model[LM][intra], error, enc, C, LM, 0, max_decay, lfe);
+
+      if (two_pass && (badness1 < badness2 || (badness1 == badness2 && ((opus_int32)ec_tell_frac(enc))+intra_bias > tell_intra)))
+      {
+         *enc = enc_intra_state;
+         /* Copy intra bits to bit-stream */
+         OPUS_COPY(intra_buf, intra_bits, nintra_bytes - nstart_bytes);
+         OPUS_COPY(oldEBands, oldEBands_intra, C*m->nbEBands);
+         OPUS_COPY(error, error_intra, C*m->nbEBands);
+         intra = 1;
+      }
+   } else {
+      OPUS_COPY(oldEBands, oldEBands_intra, C*m->nbEBands);
+      OPUS_COPY(error, error_intra, C*m->nbEBands);
+   }
+
+   if (intra)
+      *delayedIntra = new_distortion;
+   else
+      *delayedIntra = ADD32(MULT16_32_Q15(MULT16_16_Q15(pred_coef[LM], pred_coef[LM]),*delayedIntra),
+            new_distortion);
+
+   RESTORE_STACK;
+}
+
+void quant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, ec_enc *enc, int C)
+{
+   int i, c;
+
+   /* Encode finer resolution */
+   for (i=start;i<end;i++)
+   {
+      opus_int16 frac = 1<<fine_quant[i];
+      if (fine_quant[i] <= 0)
+         continue;
+      c=0;
+      do {
+         int q2;
+         opus_val16 offset;
+#ifdef FIXED_POINT
+         /* Has to be without rounding */
+         q2 = (error[i+c*m->nbEBands]+QCONST16(.5f,DB_SHIFT))>>(DB_SHIFT-fine_quant[i]);
+#else
+         q2 = (int)floor((error[i+c*m->nbEBands]+.5f)*frac);
+#endif
+         if (q2 > frac-1)
+            q2 = frac-1;
+         if (q2<0)
+            q2 = 0;
+         ec_enc_bits(enc, q2, fine_quant[i]);
+#ifdef FIXED_POINT
+         offset = SUB16(SHR32(SHL32(EXTEND32(q2),DB_SHIFT)+QCONST16(.5f,DB_SHIFT),fine_quant[i]),QCONST16(.5f,DB_SHIFT));
+#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;
+         /*printf ("%f ", error[i] - offset);*/
+      } while (++c < C);
+   }
+}
+
+void quant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc, int C)
+{
+   int i, prio, c;
+
+   /* Use up the remaining bits */
+   for (prio=0;prio<2;prio++)
+   {
+      for (i=start;i<end && bits_left>=C ;i++)
+      {
+         if (fine_quant[i] >= MAX_FINE_BITS || fine_priority[i]!=prio)
+            continue;
+         c=0;
+         do {
+            int q2;
+            opus_val16 offset;
+            q2 = error[i+c*m->nbEBands]<0 ? 0 : 1;
+            ec_enc_bits(enc, q2, 1);
+#ifdef FIXED_POINT
+            offset = SHR16(SHL16(q2,DB_SHIFT)-QCONST16(.5f,DB_SHIFT),fine_quant[i]+1);
+#else
+            offset = (q2-.5f)*(1<<(14-fine_quant[i]-1))*(1.f/16384);
+#endif
+            oldEBands[i+c*m->nbEBands] += offset;
+            error[i+c*m->nbEBands] -= offset;
+            bits_left--;
+         } while (++c < C);
+      }
+   }
+}
+
+void unquant_coarse_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int intra, ec_dec *dec, int C, int LM)
+{
+   const unsigned char *prob_model = e_prob_model[LM][intra];
+   int i, c;
+   opus_val32 prev[2] = {0, 0};
+   opus_val16 coef;
+   opus_val16 beta;
+   opus_int32 budget;
+   opus_int32 tell;
+
+   if (intra)
+   {
+      coef = 0;
+      beta = beta_intra;
+   } else {
+      beta = beta_coef[LM];
+      coef = pred_coef[LM];
+   }
+
+   budget = dec->storage*8;
+
+   /* Decode at a fixed coarse resolution */
+   for (i=start;i<end;i++)
+   {
+      c=0;
+      do {
+         int qi;
+         opus_val32 q;
+         opus_val32 tmp;
+         /* It would be better to express this invariant as a
+            test on C at function entry, but that isn't enough
+            to make the static analyzer happy. */
+         celt_assert(c<2);
+         tell = ec_tell(dec);
+         if(budget-tell>=15)
+         {
+            int pi;
+            pi = 2*IMIN(i,20);
+            qi = ec_laplace_decode(dec,
+                  prob_model[pi]<<7, prob_model[pi+1]<<6);
+         }
+         else if(budget-tell>=2)
+         {
+            qi = ec_dec_icdf(dec, small_energy_icdf, 2);
+            qi = (qi>>1)^-(qi&1);
+         }
+         else if(budget-tell>=1)
+         {
+            qi = -ec_dec_bit_logp(dec, 1);
+         }
+         else
+            qi = -1;
+         q = (opus_val32)SHL32(EXTEND32(qi),DB_SHIFT);
+
+         oldEBands[i+c*m->nbEBands] = MAX16(-QCONST16(9.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]);
+         tmp = PSHR32(MULT16_16(coef,oldEBands[i+c*m->nbEBands]),8) + prev[c] + SHL32(q,7);
+#ifdef FIXED_POINT
+         tmp = MAX32(-QCONST32(28.f, DB_SHIFT+7), tmp);
+#endif
+         oldEBands[i+c*m->nbEBands] = PSHR32(tmp, 7);
+         prev[c] = prev[c] + SHL32(q,7) - MULT16_16(beta,PSHR32(q,8));
+      } while (++c < C);
+   }
+}
+
+void unquant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, ec_dec *dec, int C)
+{
+   int i, c;
+   /* Decode finer resolution */
+   for (i=start;i<end;i++)
+   {
+      if (fine_quant[i] <= 0)
+         continue;
+      c=0;
+      do {
+         int q2;
+         opus_val16 offset;
+         q2 = ec_dec_bits(dec, fine_quant[i]);
+#ifdef FIXED_POINT
+         offset = SUB16(SHR32(SHL32(EXTEND32(q2),DB_SHIFT)+QCONST16(.5f,DB_SHIFT),fine_quant[i]),QCONST16(.5f,DB_SHIFT));
+#else
+         offset = (q2+.5f)*(1<<(14-fine_quant[i]))*(1.f/16384) - .5f;
+#endif
+         oldEBands[i+c*m->nbEBands] += offset;
+      } while (++c < C);
+   }
+}
+
+void unquant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant,  int *fine_priority, int bits_left, ec_dec *dec, int C)
+{
+   int i, prio, c;
+
+   /* Use up the remaining bits */
+   for (prio=0;prio<2;prio++)
+   {
+      for (i=start;i<end && bits_left>=C ;i++)
+      {
+         if (fine_quant[i] >= MAX_FINE_BITS || fine_priority[i]!=prio)
+            continue;
+         c=0;
+         do {
+            int q2;
+            opus_val16 offset;
+            q2 = ec_dec_bits(dec, 1);
+#ifdef FIXED_POINT
+            offset = SHR16(SHL16(q2,DB_SHIFT)-QCONST16(.5f,DB_SHIFT),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);
+      }
+   }
+}
+
+void amp2Log2(const CELTMode *m, int effEnd, int end,
+      celt_ener *bandE, opus_val16 *bandLogE, int C)
+{
+   int c, i;
+   c=0;
+   do {
+      for (i=0;i<effEnd;i++)
+      {
+         bandLogE[i+c*m->nbEBands] =
+               celt_log2(bandE[i+c*m->nbEBands])
+               - SHL16((opus_val16)eMeans[i],6);
+#ifdef FIXED_POINT
+         /* Compensate for bandE[] being Q12 but celt_log2() taking a Q14 input. */
+         bandLogE[i+c*m->nbEBands] += QCONST16(2.f, DB_SHIFT);
+#endif
+      }
+      for (i=effEnd;i<end;i++)
+         bandLogE[c*m->nbEBands+i] = -QCONST16(14.f,DB_SHIFT);
+   } while (++c < C);
+}
diff --git a/opus/celt/quant_bands.h b/opus/celt/quant_bands.h
new file mode 100644 (file)
index 0000000..0490bca
--- /dev/null
@@ -0,0 +1,66 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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 QUANT_BANDS
+#define QUANT_BANDS
+
+#include "arch.h"
+#include "modes.h"
+#include "entenc.h"
+#include "entdec.h"
+#include "mathops.h"
+
+#ifdef FIXED_POINT
+extern const signed char eMeans[25];
+#else
+extern const opus_val16 eMeans[25];
+#endif
+
+void amp2Log2(const CELTMode *m, int effEnd, int end,
+      celt_ener *bandE, opus_val16 *bandLogE, int C);
+
+void log2Amp(const CELTMode *m, int start, int end,
+      celt_ener *eBands, const opus_val16 *oldEBands, int C);
+
+void quant_coarse_energy(const CELTMode *m, int start, int end, int effEnd,
+      const opus_val16 *eBands, opus_val16 *oldEBands, opus_uint32 budget,
+      opus_val16 *error, ec_enc *enc, int C, int LM,
+      int nbAvailableBytes, int force_intra, opus_val32 *delayedIntra,
+      int two_pass, int loss_rate, int lfe);
+
+void quant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, ec_enc *enc, int C);
+
+void quant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc, int C);
+
+void unquant_coarse_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int intra, ec_dec *dec, int C, int LM);
+
+void unquant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, ec_dec *dec, int C);
+
+void unquant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, int *fine_priority, int bits_left, ec_dec *dec, int C);
+
+#endif /* QUANT_BANDS */
diff --git a/opus/celt/rate.c b/opus/celt/rate.c
new file mode 100644 (file)
index 0000000..ca4cc87
--- /dev/null
@@ -0,0 +1,644 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#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"
+
+static const unsigned char LOG2_FRAC_TABLE[24]={
+   0,
+   8,13,
+  16,19,21,23,
+  24,26,27,28,29,30,31,32,
+  32,33,34,34,35,36,36,37,37
+};
+
+#ifdef CUSTOM_MODES
+
+/*Determines if V(N,K) fits in a 32-bit unsigned integer.
+  N and K are themselves limited to 15 bits.*/
+static int fits_in32(int _n, int _k)
+{
+   static const opus_int16 maxN[15] = {
+      32767, 32767, 32767, 1476, 283, 109,  60,  40,
+       29,  24,  20,  18,  16,  14,  13};
+   static const opus_int16 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];
+   }
+}
+
+void compute_pulse_cache(CELTMode *m, int LM)
+{
+   int C;
+   int i;
+   int j;
+   int curr=0;
+   int nbEntries=0;
+   int entryN[100], entryK[100], entryI[100];
+   const opus_int16 *eBands = m->eBands;
+   PulseCache *cache = &m->cache;
+   opus_int16 *cindex;
+   unsigned char *bits;
+   unsigned char *cap;
+
+   cindex = (opus_int16 *)opus_alloc(sizeof(cache->index[0])*m->nbEBands*(LM+2));
+   cache->index = cindex;
+
+   /* Scan for all unique band sizes */
+   for (i=0;i<=LM+1;i++)
+   {
+      for (j=0;j<m->nbEBands;j++)
+      {
+         int k;
+         int N = (eBands[j+1]-eBands[j])<<i>>1;
+         cindex[i*m->nbEBands+j] = -1;
+         /* Find other bands that have the same size */
+         for (k=0;k<=i;k++)
+         {
+            int n;
+            for (n=0;n<m->nbEBands && (k!=i || n<j);n++)
+            {
+               if (N == (eBands[n+1]-eBands[n])<<k>>1)
+               {
+                  cindex[i*m->nbEBands+j] = cindex[k*m->nbEBands+n];
+                  break;
+               }
+            }
+         }
+         if (cache->index[i*m->nbEBands+j] == -1 && N!=0)
+         {
+            int K;
+            entryN[nbEntries] = N;
+            K = 0;
+            while (fits_in32(N,get_pulses(K+1)) && K<MAX_PSEUDO)
+               K++;
+            entryK[nbEntries] = K;
+            cindex[i*m->nbEBands+j] = curr;
+            entryI[nbEntries] = curr;
+
+            curr += K+1;
+            nbEntries++;
+         }
+      }
+   }
+   bits = (unsigned char *)opus_alloc(sizeof(unsigned char)*curr);
+   cache->bits = bits;
+   cache->size = curr;
+   /* Compute the cache for all unique sizes */
+   for (i=0;i<nbEntries;i++)
+   {
+      unsigned char *ptr = bits+entryI[i];
+      opus_int16 tmp[CELT_MAX_PULSES+1];
+      get_required_bits(tmp, entryN[i], get_pulses(entryK[i]), BITRES);
+      for (j=1;j<=entryK[i];j++)
+         ptr[j] = tmp[get_pulses(j)]-1;
+      ptr[0] = entryK[i];
+   }
+
+   /* Compute the maximum rate for each band at which we'll reliably use as
+       many bits as we ask for. */
+   cache->caps = cap = (unsigned char *)opus_alloc(sizeof(cache->caps[0])*(LM+1)*2*m->nbEBands);
+   for (i=0;i<=LM;i++)
+   {
+      for (C=1;C<=2;C++)
+      {
+         for (j=0;j<m->nbEBands;j++)
+         {
+            int N0;
+            int max_bits;
+            N0 = m->eBands[j+1]-m->eBands[j];
+            /* N=1 bands only have a sign bit and fine bits. */
+            if (N0<<i == 1)
+               max_bits = C*(1+MAX_FINE_BITS)<<BITRES;
+            else
+            {
+               const unsigned char *pcache;
+               opus_int32           num;
+               opus_int32           den;
+               int                  LM0;
+               int                  N;
+               int                  offset;
+               int                  ndof;
+               int                  qb;
+               int                  k;
+               LM0 = 0;
+               /* Even-sized bands bigger than N=2 can be split one more time.
+                  As of commit 44203907 all bands >1 are even, including custom modes.*/
+               if (N0 > 2)
+               {
+                  N0>>=1;
+                  LM0--;
+               }
+               /* N0=1 bands can't be split down to N<2. */
+               else if (N0 <= 1)
+               {
+                  LM0=IMIN(i,1);
+                  N0<<=LM0;
+               }
+               /* Compute the cost for the lowest-level PVQ of a fully split
+                   band. */
+               pcache = bits + cindex[(LM0+1)*m->nbEBands+j];
+               max_bits = pcache[pcache[0]]+1;
+               /* Add in the cost of coding regular splits. */
+               N = N0;
+               for(k=0;k<i-LM0;k++){
+                  max_bits <<= 1;
+                  /* Offset the number of qtheta bits by log2(N)/2
+                      + QTHETA_OFFSET compared to their "fair share" of
+                      total/N */
+                  offset = ((m->logN[j]+((LM0+k)<<BITRES))>>1)-QTHETA_OFFSET;
+                  /* The number of qtheta bits we'll allocate if the remainder
+                      is to be max_bits.
+                     The average measured cost for theta is 0.89701 times qb,
+                      approximated here as 459/512. */
+                  num=459*(opus_int32)((2*N-1)*offset+max_bits);
+                  den=((opus_int32)(2*N-1)<<9)-459;
+                  qb = IMIN((num+(den>>1))/den, 57);
+                  celt_assert(qb >= 0);
+                  max_bits += qb;
+                  N <<= 1;
+               }
+               /* Add in the cost of a stereo split, if necessary. */
+               if (C==2)
+               {
+                  max_bits <<= 1;
+                  offset = ((m->logN[j]+(i<<BITRES))>>1)-(N==2?QTHETA_OFFSET_TWOPHASE:QTHETA_OFFSET);
+                  ndof = 2*N-1-(N==2);
+                  /* The average measured cost for theta with the step PDF is
+                      0.95164 times qb, approximated here as 487/512. */
+                  num = (N==2?512:487)*(opus_int32)(max_bits+ndof*offset);
+                  den = ((opus_int32)ndof<<9)-(N==2?512:487);
+                  qb = IMIN((num+(den>>1))/den, (N==2?64:61));
+                  celt_assert(qb >= 0);
+                  max_bits += qb;
+               }
+               /* Add the fine bits we'll use. */
+               /* Compensate for the extra DoF in stereo */
+               ndof = C*N + ((C==2 && N>2) ? 1 : 0);
+               /* Offset the number of fine bits by log2(N)/2 + FINE_OFFSET
+                   compared to their "fair share" of total/N */
+               offset = ((m->logN[j] + (i<<BITRES))>>1)-FINE_OFFSET;
+               /* N=2 is the only point that doesn't match the curve */
+               if (N==2)
+                  offset += 1<<BITRES>>2;
+               /* The number of fine bits we'll allocate if the remainder is
+                   to be max_bits. */
+               num = max_bits+ndof*offset;
+               den = (ndof-1)<<BITRES;
+               qb = IMIN((num+(den>>1))/den, MAX_FINE_BITS);
+               celt_assert(qb >= 0);
+               max_bits += C*qb<<BITRES;
+            }
+            max_bits = (4*max_bits/(C*((m->eBands[j+1]-m->eBands[j])<<i)))-64;
+            celt_assert(max_bits >= 0);
+            celt_assert(max_bits < 256);
+            *cap++ = (unsigned char)max_bits;
+         }
+      }
+   }
+}
+
+#endif /* CUSTOM_MODES */
+
+#define ALLOC_STEPS 6
+
+static OPUS_INLINE int interp_bits2pulses(const CELTMode *m, int start, int end, int skip_start,
+      const int *bits1, const int *bits2, const int *thresh, const int *cap, opus_int32 total, opus_int32 *_balance,
+      int skip_rsv, int *intensity, int intensity_rsv, int *dual_stereo, int dual_stereo_rsv, int *bits,
+      int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev, int signalBandwidth)
+{
+   opus_int32 psum;
+   int lo, hi;
+   int i, j;
+   int logM;
+   int stereo;
+   int codedBands=-1;
+   int alloc_floor;
+   opus_int32 left, percoeff;
+   int done;
+   opus_int32 balance;
+   SAVE_STACK;
+
+   alloc_floor = C<<BITRES;
+   stereo = C>1;
+
+   logM = LM<<BITRES;
+   lo = 0;
+   hi = 1<<ALLOC_STEPS;
+   for (i=0;i<ALLOC_STEPS;i++)
+   {
+      int mid = (lo+hi)>>1;
+      psum = 0;
+      done = 0;
+      for (j=end;j-->start;)
+      {
+         int tmp = bits1[j] + (mid*(opus_int32)bits2[j]>>ALLOC_STEPS);
+         if (tmp >= thresh[j] || done)
+         {
+            done = 1;
+            /* Don't allocate more than we can actually use */
+            psum += IMIN(tmp, cap[j]);
+         } else {
+            if (tmp >= alloc_floor)
+               psum += alloc_floor;
+         }
+      }
+      if (psum > total)
+         hi = mid;
+      else
+         lo = mid;
+   }
+   psum = 0;
+   /*printf ("interp bisection gave %d\n", lo);*/
+   done = 0;
+   for (j=end;j-->start;)
+   {
+      int tmp = bits1[j] + ((opus_int32)lo*bits2[j]>>ALLOC_STEPS);
+      if (tmp < thresh[j] && !done)
+      {
+         if (tmp >= alloc_floor)
+            tmp = alloc_floor;
+         else
+            tmp = 0;
+      } else
+         done = 1;
+      /* Don't allocate more than we can actually use */
+      tmp = IMIN(tmp, cap[j]);
+      bits[j] = tmp;
+      psum += tmp;
+   }
+
+   /* Decide which bands to skip, working backwards from the end. */
+   for (codedBands=end;;codedBands--)
+   {
+      int band_width;
+      int band_bits;
+      int rem;
+      j = codedBands-1;
+      /* Never skip the first band, nor a band that has been boosted by
+          dynalloc.
+         In the first case, we'd be coding a bit to signal we're going to waste
+          all the other bits.
+         In the second case, we'd be coding a bit to redistribute all the bits
+          we just signaled should be cocentrated in this band. */
+      if (j<=skip_start)
+      {
+         /* Give the bit we reserved to end skipping back. */
+         total += skip_rsv;
+         break;
+      }
+      /*Figure out how many left-over bits we would be adding to this band.
+        This can include bits we've stolen back from higher, skipped bands.*/
+      left = total-psum;
+      percoeff = celt_udiv(left, m->eBands[codedBands]-m->eBands[start]);
+      left -= (m->eBands[codedBands]-m->eBands[start])*percoeff;
+      rem = IMAX(left-(m->eBands[j]-m->eBands[start]),0);
+      band_width = m->eBands[codedBands]-m->eBands[j];
+      band_bits = (int)(bits[j] + percoeff*band_width + rem);
+      /*Only code a skip decision if we're above the threshold for this band.
+        Otherwise it is force-skipped.
+        This ensures that we have enough bits to code the skip flag.*/
+      if (band_bits >= IMAX(thresh[j], alloc_floor+(1<<BITRES)))
+      {
+         if (encode)
+         {
+            /*This if() block is the only part of the allocation function that
+               is not a mandatory part of the bitstream: any bands we choose to
+               skip here must be explicitly signaled.*/
+            int depth_threshold;
+            /*We choose a threshold with some hysteresis to keep bands from
+               fluctuating in and out, but we try not to fold below a certain point. */
+            if (codedBands > 17)
+               depth_threshold = j<prev ? 7 : 9;
+            else
+               depth_threshold = 0;
+#ifdef FUZZING
+            if ((rand()&0x1) == 0)
+#else
+            if (codedBands<=start+2 || (band_bits > (depth_threshold*band_width<<LM<<BITRES)>>4 && j<=signalBandwidth))
+#endif
+            {
+               ec_enc_bit_logp(ec, 1, 1);
+               break;
+            }
+            ec_enc_bit_logp(ec, 0, 1);
+         } else if (ec_dec_bit_logp(ec, 1)) {
+            break;
+         }
+         /*We used a bit to skip this band.*/
+         psum += 1<<BITRES;
+         band_bits -= 1<<BITRES;
+      }
+      /*Reclaim the bits originally allocated to this band.*/
+      psum -= bits[j]+intensity_rsv;
+      if (intensity_rsv > 0)
+         intensity_rsv = LOG2_FRAC_TABLE[j-start];
+      psum += intensity_rsv;
+      if (band_bits >= alloc_floor)
+      {
+         /*If we have enough for a fine energy bit per channel, use it.*/
+         psum += alloc_floor;
+         bits[j] = alloc_floor;
+      } else {
+         /*Otherwise this band gets nothing at all.*/
+         bits[j] = 0;
+      }
+   }
+
+   celt_assert(codedBands > start);
+   /* Code the intensity and dual stereo parameters. */
+   if (intensity_rsv > 0)
+   {
+      if (encode)
+      {
+         *intensity = IMIN(*intensity, codedBands);
+         ec_enc_uint(ec, *intensity-start, codedBands+1-start);
+      }
+      else
+         *intensity = start+ec_dec_uint(ec, codedBands+1-start);
+   }
+   else
+      *intensity = 0;
+   if (*intensity <= start)
+   {
+      total += dual_stereo_rsv;
+      dual_stereo_rsv = 0;
+   }
+   if (dual_stereo_rsv > 0)
+   {
+      if (encode)
+         ec_enc_bit_logp(ec, *dual_stereo, 1);
+      else
+         *dual_stereo = ec_dec_bit_logp(ec, 1);
+   }
+   else
+      *dual_stereo = 0;
+
+   /* Allocate the remaining bits */
+   left = total-psum;
+   percoeff = celt_udiv(left, m->eBands[codedBands]-m->eBands[start]);
+   left -= (m->eBands[codedBands]-m->eBands[start])*percoeff;
+   for (j=start;j<codedBands;j++)
+      bits[j] += ((int)percoeff*(m->eBands[j+1]-m->eBands[j]));
+   for (j=start;j<codedBands;j++)
+   {
+      int tmp = (int)IMIN(left, m->eBands[j+1]-m->eBands[j]);
+      bits[j] += tmp;
+      left -= tmp;
+   }
+   /*for (j=0;j<end;j++)printf("%d ", bits[j]);printf("\n");*/
+
+   balance = 0;
+   for (j=start;j<codedBands;j++)
+   {
+      int N0, N, den;
+      int offset;
+      int NClogN;
+      opus_int32 excess, bit;
+
+      celt_assert(bits[j] >= 0);
+      N0 = m->eBands[j+1]-m->eBands[j];
+      N=N0<<LM;
+      bit = (opus_int32)bits[j]+balance;
+
+      if (N>1)
+      {
+         excess = MAX32(bit-cap[j],0);
+         bits[j] = bit-excess;
+
+         /* Compensate for the extra DoF in stereo */
+         den=(C*N+ ((C==2 && N>2 && !*dual_stereo && j<*intensity) ? 1 : 0));
+
+         NClogN = den*(m->logN[j] + logM);
+
+         /* Offset for the number of fine bits by log2(N)/2 + FINE_OFFSET
+            compared to their "fair share" of total/N */
+         offset = (NClogN>>1)-den*FINE_OFFSET;
+
+         /* N=2 is the only point that doesn't match the curve */
+         if (N==2)
+            offset += den<<BITRES>>2;
+
+         /* Changing the offset for allocating the second and third
+             fine energy bit */
+         if (bits[j] + offset < den*2<<BITRES)
+            offset += NClogN>>2;
+         else if (bits[j] + offset < den*3<<BITRES)
+            offset += NClogN>>3;
+
+         /* Divide with rounding */
+         ebits[j] = IMAX(0, (bits[j] + offset + (den<<(BITRES-1))));
+         ebits[j] = celt_udiv(ebits[j], den)>>BITRES;
+
+         /* Make sure not to bust */
+         if (C*ebits[j] > (bits[j]>>BITRES))
+            ebits[j] = bits[j] >> stereo >> BITRES;
+
+         /* More than that is useless because that's about as far as PVQ can go */
+         ebits[j] = IMIN(ebits[j], MAX_FINE_BITS);
+
+         /* If we rounded down or capped this band, make it a candidate for the
+             final fine energy pass */
+         fine_priority[j] = ebits[j]*(den<<BITRES) >= bits[j]+offset;
+
+         /* Remove the allocated fine bits; the rest are assigned to PVQ */
+         bits[j] -= C*ebits[j]<<BITRES;
+
+      } else {
+         /* For N=1, all bits go to fine energy except for a single sign bit */
+         excess = MAX32(0,bit-(C<<BITRES));
+         bits[j] = bit-excess;
+         ebits[j] = 0;
+         fine_priority[j] = 1;
+      }
+
+      /* Fine energy can't take advantage of the re-balancing in
+          quant_all_bands().
+         Instead, do the re-balancing here.*/
+      if(excess > 0)
+      {
+         int extra_fine;
+         int extra_bits;
+         extra_fine = IMIN(excess>>(stereo+BITRES),MAX_FINE_BITS-ebits[j]);
+         ebits[j] += extra_fine;
+         extra_bits = extra_fine*C<<BITRES;
+         fine_priority[j] = extra_bits >= excess-balance;
+         excess -= extra_bits;
+      }
+      balance = excess;
+
+      celt_assert(bits[j] >= 0);
+      celt_assert(ebits[j] >= 0);
+   }
+   /* Save any remaining bits over the cap for the rebalancing in
+       quant_all_bands(). */
+   *_balance = balance;
+
+   /* The skipped bands use all their bits for fine energy. */
+   for (;j<end;j++)
+   {
+      ebits[j] = bits[j] >> stereo >> BITRES;
+      celt_assert(C*ebits[j]<<BITRES == bits[j]);
+      bits[j] = 0;
+      fine_priority[j] = ebits[j]<1;
+   }
+   RESTORE_STACK;
+   return codedBands;
+}
+
+int compute_allocation(const CELTMode *m, int start, int end, const int *offsets, const int *cap, int alloc_trim, int *intensity, int *dual_stereo,
+      opus_int32 total, opus_int32 *balance, int *pulses, int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev, int signalBandwidth)
+{
+   int lo, hi, len, j;
+   int codedBands;
+   int skip_start;
+   int skip_rsv;
+   int intensity_rsv;
+   int dual_stereo_rsv;
+   VARDECL(int, bits1);
+   VARDECL(int, bits2);
+   VARDECL(int, thresh);
+   VARDECL(int, trim_offset);
+   SAVE_STACK;
+
+   total = IMAX(total, 0);
+   len = m->nbEBands;
+   skip_start = start;
+   /* Reserve a bit to signal the end of manually skipped bands. */
+   skip_rsv = total >= 1<<BITRES ? 1<<BITRES : 0;
+   total -= skip_rsv;
+   /* Reserve bits for the intensity and dual stereo parameters. */
+   intensity_rsv = dual_stereo_rsv = 0;
+   if (C==2)
+   {
+      intensity_rsv = LOG2_FRAC_TABLE[end-start];
+      if (intensity_rsv>total)
+         intensity_rsv = 0;
+      else
+      {
+         total -= intensity_rsv;
+         dual_stereo_rsv = total>=1<<BITRES ? 1<<BITRES : 0;
+         total -= dual_stereo_rsv;
+      }
+   }
+   ALLOC(bits1, len, int);
+   ALLOC(bits2, len, int);
+   ALLOC(thresh, len, int);
+   ALLOC(trim_offset, len, int);
+
+   for (j=start;j<end;j++)
+   {
+      /* Below this threshold, we're sure not to allocate any PVQ bits */
+      thresh[j] = IMAX((C)<<BITRES, (3*(m->eBands[j+1]-m->eBands[j])<<LM<<BITRES)>>4);
+      /* Tilt of the allocation curve */
+      trim_offset[j] = C*(m->eBands[j+1]-m->eBands[j])*(alloc_trim-5-LM)*(end-j-1)
+            *(1<<(LM+BITRES))>>6;
+      /* Giving less resolution to single-coefficient bands because they get
+         more benefit from having one coarse value per coefficient*/
+      if ((m->eBands[j+1]-m->eBands[j])<<LM==1)
+         trim_offset[j] -= C<<BITRES;
+   }
+   lo = 1;
+   hi = m->nbAllocVectors - 1;
+   do
+   {
+      int done = 0;
+      int psum = 0;
+      int mid = (lo+hi) >> 1;
+      for (j=end;j-->start;)
+      {
+         int bitsj;
+         int N = m->eBands[j+1]-m->eBands[j];
+         bitsj = C*N*m->allocVectors[mid*len+j]<<LM>>2;
+         if (bitsj > 0)
+            bitsj = IMAX(0, bitsj + trim_offset[j]);
+         bitsj += offsets[j];
+         if (bitsj >= thresh[j] || done)
+         {
+            done = 1;
+            /* Don't allocate more than we can actually use */
+            psum += IMIN(bitsj, cap[j]);
+         } else {
+            if (bitsj >= C<<BITRES)
+               psum += C<<BITRES;
+         }
+      }
+      if (psum > total)
+         hi = mid - 1;
+      else
+         lo = mid + 1;
+      /*printf ("lo = %d, hi = %d\n", lo, hi);*/
+   }
+   while (lo <= hi);
+   hi = lo--;
+   /*printf ("interp between %d and %d\n", lo, hi);*/
+   for (j=start;j<end;j++)
+   {
+      int bits1j, bits2j;
+      int N = m->eBands[j+1]-m->eBands[j];
+      bits1j = C*N*m->allocVectors[lo*len+j]<<LM>>2;
+      bits2j = hi>=m->nbAllocVectors ?
+            cap[j] : C*N*m->allocVectors[hi*len+j]<<LM>>2;
+      if (bits1j > 0)
+         bits1j = IMAX(0, bits1j + trim_offset[j]);
+      if (bits2j > 0)
+         bits2j = IMAX(0, bits2j + trim_offset[j]);
+      if (lo > 0)
+         bits1j += offsets[j];
+      bits2j += offsets[j];
+      if (offsets[j]>0)
+         skip_start = j;
+      bits2j = IMAX(0,bits2j-bits1j);
+      bits1[j] = bits1j;
+      bits2[j] = bits2j;
+   }
+   codedBands = interp_bits2pulses(m, start, end, skip_start, bits1, bits2, thresh, cap,
+         total, balance, skip_rsv, intensity, intensity_rsv, dual_stereo, dual_stereo_rsv,
+         pulses, ebits, fine_priority, C, LM, ec, encode, prev, signalBandwidth);
+   RESTORE_STACK;
+   return codedBands;
+}
+
diff --git a/opus/celt/rate.h b/opus/celt/rate.h
new file mode 100644 (file)
index 0000000..515f768
--- /dev/null
@@ -0,0 +1,101 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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 RATE_H
+#define RATE_H
+
+#define MAX_PSEUDO 40
+#define LOG_MAX_PSEUDO 6
+
+#define CELT_MAX_PULSES 128
+
+#define MAX_FINE_BITS 8
+
+#define FINE_OFFSET 21
+#define QTHETA_OFFSET 4
+#define QTHETA_OFFSET_TWOPHASE 16
+
+#include "cwrs.h"
+#include "modes.h"
+
+void compute_pulse_cache(CELTMode *m, int LM);
+
+static OPUS_INLINE int get_pulses(int i)
+{
+   return i<8 ? i : (8 + (i&7)) << ((i>>3)-1);
+}
+
+static OPUS_INLINE int bits2pulses(const CELTMode *m, int band, int LM, int bits)
+{
+   int i;
+   int lo, hi;
+   const unsigned char *cache;
+
+   LM++;
+   cache = m->cache.bits + m->cache.index[LM*m->nbEBands+band];
+
+   lo = 0;
+   hi = cache[0];
+   bits--;
+   for (i=0;i<LOG_MAX_PSEUDO;i++)
+   {
+      int mid = (lo+hi+1)>>1;
+      /* OPT: Make sure this is implemented with a conditional move */
+      if ((int)cache[mid] >= bits)
+         hi = mid;
+      else
+         lo = mid;
+   }
+   if (bits- (lo == 0 ? -1 : (int)cache[lo]) <= (int)cache[hi]-bits)
+      return lo;
+   else
+      return hi;
+}
+
+static OPUS_INLINE int pulses2bits(const CELTMode *m, int band, int LM, int pulses)
+{
+   const unsigned char *cache;
+
+   LM++;
+   cache = m->cache.bits + m->cache.index[LM*m->nbEBands+band];
+   return pulses == 0 ? 0 : cache[pulses]+1;
+}
+
+/** 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
+*/
+int compute_allocation(const CELTMode *m, int start, int end, const int *offsets, const int *cap, int alloc_trim, int *intensity, int *dual_stero,
+      opus_int32 total, opus_int32 *balance, int *pulses, int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev, int signalBandwidth);
+
+#endif
diff --git a/opus/celt/stack_alloc.h b/opus/celt/stack_alloc.h
new file mode 100644 (file)
index 0000000..2b51c8d
--- /dev/null
@@ -0,0 +1,184 @@
+/* Copyright (C) 2002-2003 Jean-Marc Valin
+   Copyright (C) 2007-2009 Xiph.Org Foundation */
+/**
+   @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.
+
+   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 STACK_ALLOC_H
+#define STACK_ALLOC_H
+
+#include "opus_types.h"
+#include "opus_defines.h"
+
+#if (!defined (VAR_ARRAYS) && !defined (USE_ALLOCA) && !defined (NONTHREADSAFE_PSEUDOSTACK))
+#error "Opus requires one of VAR_ARRAYS, USE_ALLOCA, or NONTHREADSAFE_PSEUDOSTACK be defined to select the temporary allocation mode."
+#endif
+
+#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
+/* C99 does not allow VLAs of size zero */
+#define ALLOC_NONE 1
+
+#elif defined(USE_ALLOCA)
+
+#define VARDECL(type, var) type *var
+
+# ifdef WIN32
+#  define ALLOC(var, size, type) var = ((type*)_alloca(sizeof(type)*(size)))
+# else
+#  define ALLOC(var, size, type) var = ((type*)alloca(sizeof(type)*(size)))
+# endif
+
+#define SAVE_STACK
+#define RESTORE_STACK
+#define ALLOC_STACK
+#define ALLOC_NONE 0
+
+#else
+
+#ifdef CELT_C
+char *scratch_ptr=0;
+char *global_stack=0;
+#else
+extern char *global_stack;
+extern char *scratch_ptr;
+#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 char *_saved_stack; ((global_stack = (global_stack==0) ? ((global_stack_top=opus_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)); _saved_stack = 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))))
+#if 0 /* Set this to 1 to instrument pseudostack usage */
+#define RESTORE_STACK (printf("%ld %s:%d\n", global_stack-scratch_ptr, __FILE__, __LINE__),global_stack = _saved_stack)
+#else
+#define RESTORE_STACK (global_stack = _saved_stack)
+#endif
+#define ALLOC_STACK char *_saved_stack; (global_stack = (global_stack==0) ? (scratch_ptr=opus_alloc_scratch(GLOBAL_STACK_SIZE)) : global_stack); _saved_stack = 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;
+#define ALLOC_NONE 0
+
+#endif /* VAR_ARRAYS */
+
+
+#ifdef ENABLE_VALGRIND
+
+#include <valgrind/memcheck.h>
+#define OPUS_CHECK_ARRAY(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr))
+#define OPUS_CHECK_VALUE(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value)
+#define OPUS_CHECK_ARRAY_COND(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr))
+#define OPUS_CHECK_VALUE_COND(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value)
+#define OPUS_PRINT_INT(value) do {fprintf(stderr, #value " = %d at %s:%d\n", value, __FILE__, __LINE__);}while(0)
+#define OPUS_FPRINTF fprintf
+
+#else
+
+static OPUS_INLINE int _opus_false(void) {return 0;}
+#define OPUS_CHECK_ARRAY(ptr, len) _opus_false()
+#define OPUS_CHECK_VALUE(value) _opus_false()
+#define OPUS_PRINT_INT(value) do{}while(0)
+#define OPUS_FPRINTF (void)
+
+#endif
+
+
+#endif /* STACK_ALLOC_H */
diff --git a/opus/celt/static_modes_fixed.h b/opus/celt/static_modes_fixed.h
new file mode 100644 (file)
index 0000000..8717d62
--- /dev/null
@@ -0,0 +1,892 @@
+/* The contents of this file was automatically generated by dump_modes.c
+   with arguments: 48000 960
+   It contains static definitions for some pre-defined modes. */
+#include "modes.h"
+#include "rate.h"
+
+#ifdef HAVE_ARM_NE10
+#define OVERRIDE_FFT 1
+#include "static_modes_fixed_arm_ne10.h"
+#endif
+
+#ifndef DEF_WINDOW120
+#define DEF_WINDOW120
+static const opus_val16 window120[120] = {
+2, 20, 55, 108, 178,
+266, 372, 494, 635, 792,
+966, 1157, 1365, 1590, 1831,
+2089, 2362, 2651, 2956, 3276,
+3611, 3961, 4325, 4703, 5094,
+5499, 5916, 6346, 6788, 7241,
+7705, 8179, 8663, 9156, 9657,
+10167, 10684, 11207, 11736, 12271,
+12810, 13353, 13899, 14447, 14997,
+15547, 16098, 16648, 17197, 17744,
+18287, 18827, 19363, 19893, 20418,
+20936, 21447, 21950, 22445, 22931,
+23407, 23874, 24330, 24774, 25208,
+25629, 26039, 26435, 26819, 27190,
+27548, 27893, 28224, 28541, 28845,
+29135, 29411, 29674, 29924, 30160,
+30384, 30594, 30792, 30977, 31151,
+31313, 31463, 31602, 31731, 31849,
+31958, 32057, 32148, 32229, 32303,
+32370, 32429, 32481, 32528, 32568,
+32604, 32634, 32661, 32683, 32701,
+32717, 32729, 32740, 32748, 32754,
+32758, 32762, 32764, 32766, 32767,
+32767, 32767, 32767, 32767, 32767,
+};
+#endif
+
+#ifndef DEF_LOGN400
+#define DEF_LOGN400
+static const opus_int16 logN400[21] = {
+0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, };
+#endif
+
+#ifndef DEF_PULSE_CACHE50
+#define DEF_PULSE_CACHE50
+static const opus_int16 cache_index50[105] = {
+-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41,
+82, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41,
+41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41,
+41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305,
+318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240,
+305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240,
+240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387,
+};
+static const unsigned char cache_bits50[392] = {
+40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28,
+31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50,
+51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65,
+66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61,
+64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92,
+94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123,
+124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94,
+97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, 129, 131, 135, 139,
+142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35,
+28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149,
+153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225,
+229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157,
+166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, 63,
+86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250,
+25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180,
+185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89,
+110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41,
+74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138,
+163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214,
+228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49,
+90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47,
+87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57,
+106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187,
+224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127,
+182, 234, };
+static const unsigned char cache_caps50[168] = {
+224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185,
+178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240,
+240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160,
+160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172,
+138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207,
+204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185,
+185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39,
+207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201,
+188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193,
+193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204,
+204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175,
+140, 66, 40, };
+#endif
+
+#ifndef FFT_TWIDDLES48000_960
+#define FFT_TWIDDLES48000_960
+static const kiss_twiddle_cpx fft_twiddles48000_960[480] = {
+{32767, 0}, {32766, -429},
+{32757, -858}, {32743, -1287},
+{32724, -1715}, {32698, -2143},
+{32667, -2570}, {32631, -2998},
+{32588, -3425}, {32541, -3851},
+{32488, -4277}, {32429, -4701},
+{32364, -5125}, {32295, -5548},
+{32219, -5971}, {32138, -6393},
+{32051, -6813}, {31960, -7231},
+{31863, -7650}, {31760, -8067},
+{31652, -8481}, {31539, -8895},
+{31419, -9306}, {31294, -9716},
+{31165, -10126}, {31030, -10532},
+{30889, -10937}, {30743, -11340},
+{30592, -11741}, {30436, -12141},
+{30274, -12540}, {30107, -12935},
+{29936, -13328}, {29758, -13718},
+{29577, -14107}, {29390, -14493},
+{29197, -14875}, {29000, -15257},
+{28797, -15635}, {28590, -16010},
+{28379, -16384}, {28162, -16753},
+{27940, -17119}, {27714, -17484},
+{27482, -17845}, {27246, -18205},
+{27006, -18560}, {26760, -18911},
+{26510, -19260}, {26257, -19606},
+{25997, -19947}, {25734, -20286},
+{25466, -20621}, {25194, -20952},
+{24918, -21281}, {24637, -21605},
+{24353, -21926}, {24063, -22242},
+{23770, -22555}, {23473, -22865},
+{23171, -23171}, {22866, -23472},
+{22557, -23769}, {22244, -24063},
+{21927, -24352}, {21606, -24636},
+{21282, -24917}, {20954, -25194},
+{20622, -25465}, {20288, -25733},
+{19949, -25997}, {19607, -26255},
+{19261, -26509}, {18914, -26760},
+{18561, -27004}, {18205, -27246},
+{17846, -27481}, {17485, -27713},
+{17122, -27940}, {16755, -28162},
+{16385, -28378}, {16012, -28590},
+{15636, -28797}, {15258, -28999},
+{14878, -29197}, {14494, -29389},
+{14108, -29576}, {13720, -29757},
+{13329, -29934}, {12937, -30107},
+{12540, -30274}, {12142, -30435},
+{11744, -30592}, {11342, -30743},
+{10939, -30889}, {10534, -31030},
+{10127, -31164}, {9718, -31294},
+{9307, -31418}, {8895, -31537},
+{8482, -31652}, {8067, -31759},
+{7650, -31862}, {7233, -31960},
+{6815, -32051}, {6393, -32138},
+{5973, -32219}, {5549, -32294},
+{5127, -32364}, {4703, -32429},
+{4278, -32487}, {3852, -32541},
+{3426, -32588}, {2999, -32630},
+{2572, -32667}, {2144, -32698},
+{1716, -32724}, {1287, -32742},
+{860, -32757}, {430, -32766},
+{0, -32767}, {-429, -32766},
+{-858, -32757}, {-1287, -32743},
+{-1715, -32724}, {-2143, -32698},
+{-2570, -32667}, {-2998, -32631},
+{-3425, -32588}, {-3851, -32541},
+{-4277, -32488}, {-4701, -32429},
+{-5125, -32364}, {-5548, -32295},
+{-5971, -32219}, {-6393, -32138},
+{-6813, -32051}, {-7231, -31960},
+{-7650, -31863}, {-8067, -31760},
+{-8481, -31652}, {-8895, -31539},
+{-9306, -31419}, {-9716, -31294},
+{-10126, -31165}, {-10532, -31030},
+{-10937, -30889}, {-11340, -30743},
+{-11741, -30592}, {-12141, -30436},
+{-12540, -30274}, {-12935, -30107},
+{-13328, -29936}, {-13718, -29758},
+{-14107, -29577}, {-14493, -29390},
+{-14875, -29197}, {-15257, -29000},
+{-15635, -28797}, {-16010, -28590},
+{-16384, -28379}, {-16753, -28162},
+{-17119, -27940}, {-17484, -27714},
+{-17845, -27482}, {-18205, -27246},
+{-18560, -27006}, {-18911, -26760},
+{-19260, -26510}, {-19606, -26257},
+{-19947, -25997}, {-20286, -25734},
+{-20621, -25466}, {-20952, -25194},
+{-21281, -24918}, {-21605, -24637},
+{-21926, -24353}, {-22242, -24063},
+{-22555, -23770}, {-22865, -23473},
+{-23171, -23171}, {-23472, -22866},
+{-23769, -22557}, {-24063, -22244},
+{-24352, -21927}, {-24636, -21606},
+{-24917, -21282}, {-25194, -20954},
+{-25465, -20622}, {-25733, -20288},
+{-25997, -19949}, {-26255, -19607},
+{-26509, -19261}, {-26760, -18914},
+{-27004, -18561}, {-27246, -18205},
+{-27481, -17846}, {-27713, -17485},
+{-27940, -17122}, {-28162, -16755},
+{-28378, -16385}, {-28590, -16012},
+{-28797, -15636}, {-28999, -15258},
+{-29197, -14878}, {-29389, -14494},
+{-29576, -14108}, {-29757, -13720},
+{-29934, -13329}, {-30107, -12937},
+{-30274, -12540}, {-30435, -12142},
+{-30592, -11744}, {-30743, -11342},
+{-30889, -10939}, {-31030, -10534},
+{-31164, -10127}, {-31294, -9718},
+{-31418, -9307}, {-31537, -8895},
+{-31652, -8482}, {-31759, -8067},
+{-31862, -7650}, {-31960, -7233},
+{-32051, -6815}, {-32138, -6393},
+{-32219, -5973}, {-32294, -5549},
+{-32364, -5127}, {-32429, -4703},
+{-32487, -4278}, {-32541, -3852},
+{-32588, -3426}, {-32630, -2999},
+{-32667, -2572}, {-32698, -2144},
+{-32724, -1716}, {-32742, -1287},
+{-32757, -860}, {-32766, -430},
+{-32767, 0}, {-32766, 429},
+{-32757, 858}, {-32743, 1287},
+{-32724, 1715}, {-32698, 2143},
+{-32667, 2570}, {-32631, 2998},
+{-32588, 3425}, {-32541, 3851},
+{-32488, 4277}, {-32429, 4701},
+{-32364, 5125}, {-32295, 5548},
+{-32219, 5971}, {-32138, 6393},
+{-32051, 6813}, {-31960, 7231},
+{-31863, 7650}, {-31760, 8067},
+{-31652, 8481}, {-31539, 8895},
+{-31419, 9306}, {-31294, 9716},
+{-31165, 10126}, {-31030, 10532},
+{-30889, 10937}, {-30743, 11340},
+{-30592, 11741}, {-30436, 12141},
+{-30274, 12540}, {-30107, 12935},
+{-29936, 13328}, {-29758, 13718},
+{-29577, 14107}, {-29390, 14493},
+{-29197, 14875}, {-29000, 15257},
+{-28797, 15635}, {-28590, 16010},
+{-28379, 16384}, {-28162, 16753},
+{-27940, 17119}, {-27714, 17484},
+{-27482, 17845}, {-27246, 18205},
+{-27006, 18560}, {-26760, 18911},
+{-26510, 19260}, {-26257, 19606},
+{-25997, 19947}, {-25734, 20286},
+{-25466, 20621}, {-25194, 20952},
+{-24918, 21281}, {-24637, 21605},
+{-24353, 21926}, {-24063, 22242},
+{-23770, 22555}, {-23473, 22865},
+{-23171, 23171}, {-22866, 23472},
+{-22557, 23769}, {-22244, 24063},
+{-21927, 24352}, {-21606, 24636},
+{-21282, 24917}, {-20954, 25194},
+{-20622, 25465}, {-20288, 25733},
+{-19949, 25997}, {-19607, 26255},
+{-19261, 26509}, {-18914, 26760},
+{-18561, 27004}, {-18205, 27246},
+{-17846, 27481}, {-17485, 27713},
+{-17122, 27940}, {-16755, 28162},
+{-16385, 28378}, {-16012, 28590},
+{-15636, 28797}, {-15258, 28999},
+{-14878, 29197}, {-14494, 29389},
+{-14108, 29576}, {-13720, 29757},
+{-13329, 29934}, {-12937, 30107},
+{-12540, 30274}, {-12142, 30435},
+{-11744, 30592}, {-11342, 30743},
+{-10939, 30889}, {-10534, 31030},
+{-10127, 31164}, {-9718, 31294},
+{-9307, 31418}, {-8895, 31537},
+{-8482, 31652}, {-8067, 31759},
+{-7650, 31862}, {-7233, 31960},
+{-6815, 32051}, {-6393, 32138},
+{-5973, 32219}, {-5549, 32294},
+{-5127, 32364}, {-4703, 32429},
+{-4278, 32487}, {-3852, 32541},
+{-3426, 32588}, {-2999, 32630},
+{-2572, 32667}, {-2144, 32698},
+{-1716, 32724}, {-1287, 32742},
+{-860, 32757}, {-430, 32766},
+{0, 32767}, {429, 32766},
+{858, 32757}, {1287, 32743},
+{1715, 32724}, {2143, 32698},
+{2570, 32667}, {2998, 32631},
+{3425, 32588}, {3851, 32541},
+{4277, 32488}, {4701, 32429},
+{5125, 32364}, {5548, 32295},
+{5971, 32219}, {6393, 32138},
+{6813, 32051}, {7231, 31960},
+{7650, 31863}, {8067, 31760},
+{8481, 31652}, {8895, 31539},
+{9306, 31419}, {9716, 31294},
+{10126, 31165}, {10532, 31030},
+{10937, 30889}, {11340, 30743},
+{11741, 30592}, {12141, 30436},
+{12540, 30274}, {12935, 30107},
+{13328, 29936}, {13718, 29758},
+{14107, 29577}, {14493, 29390},
+{14875, 29197}, {15257, 29000},
+{15635, 28797}, {16010, 28590},
+{16384, 28379}, {16753, 28162},
+{17119, 27940}, {17484, 27714},
+{17845, 27482}, {18205, 27246},
+{18560, 27006}, {18911, 26760},
+{19260, 26510}, {19606, 26257},
+{19947, 25997}, {20286, 25734},
+{20621, 25466}, {20952, 25194},
+{21281, 24918}, {21605, 24637},
+{21926, 24353}, {22242, 24063},
+{22555, 23770}, {22865, 23473},
+{23171, 23171}, {23472, 22866},
+{23769, 22557}, {24063, 22244},
+{24352, 21927}, {24636, 21606},
+{24917, 21282}, {25194, 20954},
+{25465, 20622}, {25733, 20288},
+{25997, 19949}, {26255, 19607},
+{26509, 19261}, {26760, 18914},
+{27004, 18561}, {27246, 18205},
+{27481, 17846}, {27713, 17485},
+{27940, 17122}, {28162, 16755},
+{28378, 16385}, {28590, 16012},
+{28797, 15636}, {28999, 15258},
+{29197, 14878}, {29389, 14494},
+{29576, 14108}, {29757, 13720},
+{29934, 13329}, {30107, 12937},
+{30274, 12540}, {30435, 12142},
+{30592, 11744}, {30743, 11342},
+{30889, 10939}, {31030, 10534},
+{31164, 10127}, {31294, 9718},
+{31418, 9307}, {31537, 8895},
+{31652, 8482}, {31759, 8067},
+{31862, 7650}, {31960, 7233},
+{32051, 6815}, {32138, 6393},
+{32219, 5973}, {32294, 5549},
+{32364, 5127}, {32429, 4703},
+{32487, 4278}, {32541, 3852},
+{32588, 3426}, {32630, 2999},
+{32667, 2572}, {32698, 2144},
+{32724, 1716}, {32742, 1287},
+{32757, 860}, {32766, 430},
+};
+#ifndef FFT_BITREV480
+#define FFT_BITREV480
+static const opus_int16 fft_bitrev480[480] = {
+0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448,
+8, 104, 200, 296, 392, 40, 136, 232, 328, 424, 72, 168, 264, 360, 456,
+16, 112, 208, 304, 400, 48, 144, 240, 336, 432, 80, 176, 272, 368, 464,
+24, 120, 216, 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472,
+4, 100, 196, 292, 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452,
+12, 108, 204, 300, 396, 44, 140, 236, 332, 428, 76, 172, 268, 364, 460,
+20, 116, 212, 308, 404, 52, 148, 244, 340, 436, 84, 180, 276, 372, 468,
+28, 124, 220, 316, 412, 60, 156, 252, 348, 444, 92, 188, 284, 380, 476,
+1, 97, 193, 289, 385, 33, 129, 225, 321, 417, 65, 161, 257, 353, 449,
+9, 105, 201, 297, 393, 41, 137, 233, 329, 425, 73, 169, 265, 361, 457,
+17, 113, 209, 305, 401, 49, 145, 241, 337, 433, 81, 177, 273, 369, 465,
+25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, 185, 281, 377, 473,
+5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, 261, 357, 453,
+13, 109, 205, 301, 397, 45, 141, 237, 333, 429, 77, 173, 269, 365, 461,
+21, 117, 213, 309, 405, 53, 149, 245, 341, 437, 85, 181, 277, 373, 469,
+29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477,
+2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450,
+10, 106, 202, 298, 394, 42, 138, 234, 330, 426, 74, 170, 266, 362, 458,
+18, 114, 210, 306, 402, 50, 146, 242, 338, 434, 82, 178, 274, 370, 466,
+26, 122, 218, 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474,
+6, 102, 198, 294, 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454,
+14, 110, 206, 302, 398, 46, 142, 238, 334, 430, 78, 174, 270, 366, 462,
+22, 118, 214, 310, 406, 54, 150, 246, 342, 438, 86, 182, 278, 374, 470,
+30, 126, 222, 318, 414, 62, 158, 254, 350, 446, 94, 190, 286, 382, 478,
+3, 99, 195, 291, 387, 35, 131, 227, 323, 419, 67, 163, 259, 355, 451,
+11, 107, 203, 299, 395, 43, 139, 235, 331, 427, 75, 171, 267, 363, 459,
+19, 115, 211, 307, 403, 51, 147, 243, 339, 435, 83, 179, 275, 371, 467,
+27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, 187, 283, 379, 475,
+7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, 263, 359, 455,
+15, 111, 207, 303, 399, 47, 143, 239, 335, 431, 79, 175, 271, 367, 463,
+23, 119, 215, 311, 407, 55, 151, 247, 343, 439, 87, 183, 279, 375, 471,
+31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479,
+};
+#endif
+
+#ifndef FFT_BITREV240
+#define FFT_BITREV240
+static const opus_int16 fft_bitrev240[240] = {
+0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224,
+4, 52, 100, 148, 196, 20, 68, 116, 164, 212, 36, 84, 132, 180, 228,
+8, 56, 104, 152, 200, 24, 72, 120, 168, 216, 40, 88, 136, 184, 232,
+12, 60, 108, 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236,
+1, 49, 97, 145, 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225,
+5, 53, 101, 149, 197, 21, 69, 117, 165, 213, 37, 85, 133, 181, 229,
+9, 57, 105, 153, 201, 25, 73, 121, 169, 217, 41, 89, 137, 185, 233,
+13, 61, 109, 157, 205, 29, 77, 125, 173, 221, 45, 93, 141, 189, 237,
+2, 50, 98, 146, 194, 18, 66, 114, 162, 210, 34, 82, 130, 178, 226,
+6, 54, 102, 150, 198, 22, 70, 118, 166, 214, 38, 86, 134, 182, 230,
+10, 58, 106, 154, 202, 26, 74, 122, 170, 218, 42, 90, 138, 186, 234,
+14, 62, 110, 158, 206, 30, 78, 126, 174, 222, 46, 94, 142, 190, 238,
+3, 51, 99, 147, 195, 19, 67, 115, 163, 211, 35, 83, 131, 179, 227,
+7, 55, 103, 151, 199, 23, 71, 119, 167, 215, 39, 87, 135, 183, 231,
+11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, 235,
+15, 63, 111, 159, 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239,
+};
+#endif
+
+#ifndef FFT_BITREV120
+#define FFT_BITREV120
+static const opus_int16 fft_bitrev120[120] = {
+0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112,
+4, 28, 52, 76, 100, 12, 36, 60, 84, 108, 20, 44, 68, 92, 116,
+1, 25, 49, 73, 97, 9, 33, 57, 81, 105, 17, 41, 65, 89, 113,
+5, 29, 53, 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117,
+2, 26, 50, 74, 98, 10, 34, 58, 82, 106, 18, 42, 66, 90, 114,
+6, 30, 54, 78, 102, 14, 38, 62, 86, 110, 22, 46, 70, 94, 118,
+3, 27, 51, 75, 99, 11, 35, 59, 83, 107, 19, 43, 67, 91, 115,
+7, 31, 55, 79, 103, 15, 39, 63, 87, 111, 23, 47, 71, 95, 119,
+};
+#endif
+
+#ifndef FFT_BITREV60
+#define FFT_BITREV60
+static const opus_int16 fft_bitrev60[60] = {
+0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56,
+1, 13, 25, 37, 49, 5, 17, 29, 41, 53, 9, 21, 33, 45, 57,
+2, 14, 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58,
+3, 15, 27, 39, 51, 7, 19, 31, 43, 55, 11, 23, 35, 47, 59,
+};
+#endif
+
+#ifndef FFT_STATE48000_960_0
+#define FFT_STATE48000_960_0
+static const kiss_fft_state fft_state48000_960_0 = {
+480,    /* nfft */
+17476,    /* scale */
+8,      /* scale_shift */
+-1,     /* shift */
+{5, 96, 3, 32, 4, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev480,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_480,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_1
+#define FFT_STATE48000_960_1
+static const kiss_fft_state fft_state48000_960_1 = {
+240,    /* nfft */
+17476,    /* scale */
+7,      /* scale_shift */
+1,      /* shift */
+{5, 48, 3, 16, 4, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev240,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_240,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_2
+#define FFT_STATE48000_960_2
+static const kiss_fft_state fft_state48000_960_2 = {
+120,    /* nfft */
+17476,    /* scale */
+6,      /* scale_shift */
+2,      /* shift */
+{5, 24, 3, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev120,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_120,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_3
+#define FFT_STATE48000_960_3
+static const kiss_fft_state fft_state48000_960_3 = {
+60,     /* nfft */
+17476,    /* scale */
+5,      /* scale_shift */
+3,      /* shift */
+{5, 12, 3, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev60,   /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_60,
+#else
+NULL,
+#endif
+};
+#endif
+
+#endif
+
+#ifndef MDCT_TWIDDLES960
+#define MDCT_TWIDDLES960
+static const opus_val16 mdct_twiddles960[1800] = {
+32767, 32767, 32767, 32766, 32765,
+32763, 32761, 32759, 32756, 32753,
+32750, 32746, 32742, 32738, 32733,
+32728, 32722, 32717, 32710, 32704,
+32697, 32690, 32682, 32674, 32666,
+32657, 32648, 32639, 32629, 32619,
+32609, 32598, 32587, 32576, 32564,
+32552, 32539, 32526, 32513, 32500,
+32486, 32472, 32457, 32442, 32427,
+32411, 32395, 32379, 32362, 32345,
+32328, 32310, 32292, 32274, 32255,
+32236, 32217, 32197, 32177, 32157,
+32136, 32115, 32093, 32071, 32049,
+32027, 32004, 31981, 31957, 31933,
+31909, 31884, 31859, 31834, 31809,
+31783, 31756, 31730, 31703, 31676,
+31648, 31620, 31592, 31563, 31534,
+31505, 31475, 31445, 31415, 31384,
+31353, 31322, 31290, 31258, 31226,
+31193, 31160, 31127, 31093, 31059,
+31025, 30990, 30955, 30920, 30884,
+30848, 30812, 30775, 30738, 30701,
+30663, 30625, 30587, 30548, 30509,
+30470, 30430, 30390, 30350, 30309,
+30269, 30227, 30186, 30144, 30102,
+30059, 30016, 29973, 29930, 29886,
+29842, 29797, 29752, 29707, 29662,
+29616, 29570, 29524, 29477, 29430,
+29383, 29335, 29287, 29239, 29190,
+29142, 29092, 29043, 28993, 28943,
+28892, 28842, 28791, 28739, 28688,
+28636, 28583, 28531, 28478, 28425,
+28371, 28317, 28263, 28209, 28154,
+28099, 28044, 27988, 27932, 27876,
+27820, 27763, 27706, 27648, 27591,
+27533, 27474, 27416, 27357, 27298,
+27238, 27178, 27118, 27058, 26997,
+26936, 26875, 26814, 26752, 26690,
+26628, 26565, 26502, 26439, 26375,
+26312, 26247, 26183, 26119, 26054,
+25988, 25923, 25857, 25791, 25725,
+25658, 25592, 25524, 25457, 25389,
+25322, 25253, 25185, 25116, 25047,
+24978, 24908, 24838, 24768, 24698,
+24627, 24557, 24485, 24414, 24342,
+24270, 24198, 24126, 24053, 23980,
+23907, 23834, 23760, 23686, 23612,
+23537, 23462, 23387, 23312, 23237,
+23161, 23085, 23009, 22932, 22856,
+22779, 22701, 22624, 22546, 22468,
+22390, 22312, 22233, 22154, 22075,
+21996, 21916, 21836, 21756, 21676,
+21595, 21515, 21434, 21352, 21271,
+21189, 21107, 21025, 20943, 20860,
+20777, 20694, 20611, 20528, 20444,
+20360, 20276, 20192, 20107, 20022,
+19937, 19852, 19767, 19681, 19595,
+19509, 19423, 19336, 19250, 19163,
+19076, 18988, 18901, 18813, 18725,
+18637, 18549, 18460, 18372, 18283,
+18194, 18104, 18015, 17925, 17835,
+17745, 17655, 17565, 17474, 17383,
+17292, 17201, 17110, 17018, 16927,
+16835, 16743, 16650, 16558, 16465,
+16372, 16279, 16186, 16093, 15999,
+15906, 15812, 15718, 15624, 15529,
+15435, 15340, 15245, 15150, 15055,
+14960, 14864, 14769, 14673, 14577,
+14481, 14385, 14288, 14192, 14095,
+13998, 13901, 13804, 13706, 13609,
+13511, 13414, 13316, 13218, 13119,
+13021, 12923, 12824, 12725, 12626,
+12527, 12428, 12329, 12230, 12130,
+12030, 11930, 11831, 11730, 11630,
+11530, 11430, 11329, 11228, 11128,
+11027, 10926, 10824, 10723, 10622,
+10520, 10419, 10317, 10215, 10113,
+10011, 9909, 9807, 9704, 9602,
+9499, 9397, 9294, 9191, 9088,
+8985, 8882, 8778, 8675, 8572,
+8468, 8364, 8261, 8157, 8053,
+7949, 7845, 7741, 7637, 7532,
+7428, 7323, 7219, 7114, 7009,
+6905, 6800, 6695, 6590, 6485,
+6380, 6274, 6169, 6064, 5958,
+5853, 5747, 5642, 5536, 5430,
+5325, 5219, 5113, 5007, 4901,
+4795, 4689, 4583, 4476, 4370,
+4264, 4157, 4051, 3945, 3838,
+3732, 3625, 3518, 3412, 3305,
+3198, 3092, 2985, 2878, 2771,
+2664, 2558, 2451, 2344, 2237,
+2130, 2023, 1916, 1809, 1702,
+1594, 1487, 1380, 1273, 1166,
+1059, 952, 844, 737, 630,
+523, 416, 308, 201, 94,
+-13, -121, -228, -335, -442,
+-550, -657, -764, -871, -978,
+-1086, -1193, -1300, -1407, -1514,
+-1621, -1728, -1835, -1942, -2049,
+-2157, -2263, -2370, -2477, -2584,
+-2691, -2798, -2905, -3012, -3118,
+-3225, -3332, -3439, -3545, -3652,
+-3758, -3865, -3971, -4078, -4184,
+-4290, -4397, -4503, -4609, -4715,
+-4821, -4927, -5033, -5139, -5245,
+-5351, -5457, -5562, -5668, -5774,
+-5879, -5985, -6090, -6195, -6301,
+-6406, -6511, -6616, -6721, -6826,
+-6931, -7036, -7140, -7245, -7349,
+-7454, -7558, -7663, -7767, -7871,
+-7975, -8079, -8183, -8287, -8390,
+-8494, -8597, -8701, -8804, -8907,
+-9011, -9114, -9217, -9319, -9422,
+-9525, -9627, -9730, -9832, -9934,
+-10037, -10139, -10241, -10342, -10444,
+-10546, -10647, -10748, -10850, -10951,
+-11052, -11153, -11253, -11354, -11455,
+-11555, -11655, -11756, -11856, -11955,
+-12055, -12155, -12254, -12354, -12453,
+-12552, -12651, -12750, -12849, -12947,
+-13046, -13144, -13242, -13340, -13438,
+-13536, -13633, -13731, -13828, -13925,
+-14022, -14119, -14216, -14312, -14409,
+-14505, -14601, -14697, -14793, -14888,
+-14984, -15079, -15174, -15269, -15364,
+-15459, -15553, -15647, -15741, -15835,
+-15929, -16023, -16116, -16210, -16303,
+-16396, -16488, -16581, -16673, -16766,
+-16858, -16949, -17041, -17133, -17224,
+-17315, -17406, -17497, -17587, -17678,
+-17768, -17858, -17948, -18037, -18127,
+-18216, -18305, -18394, -18483, -18571,
+-18659, -18747, -18835, -18923, -19010,
+-19098, -19185, -19271, -19358, -19444,
+-19531, -19617, -19702, -19788, -19873,
+-19959, -20043, -20128, -20213, -20297,
+-20381, -20465, -20549, -20632, -20715,
+-20798, -20881, -20963, -21046, -21128,
+-21210, -21291, -21373, -21454, -21535,
+-21616, -21696, -21776, -21856, -21936,
+-22016, -22095, -22174, -22253, -22331,
+-22410, -22488, -22566, -22643, -22721,
+-22798, -22875, -22951, -23028, -23104,
+-23180, -23256, -23331, -23406, -23481,
+-23556, -23630, -23704, -23778, -23852,
+-23925, -23998, -24071, -24144, -24216,
+-24288, -24360, -24432, -24503, -24574,
+-24645, -24716, -24786, -24856, -24926,
+-24995, -25064, -25133, -25202, -25270,
+-25339, -25406, -25474, -25541, -25608,
+-25675, -25742, -25808, -25874, -25939,
+-26005, -26070, -26135, -26199, -26264,
+-26327, -26391, -26455, -26518, -26581,
+-26643, -26705, -26767, -26829, -26891,
+-26952, -27013, -27073, -27133, -27193,
+-27253, -27312, -27372, -27430, -27489,
+-27547, -27605, -27663, -27720, -27777,
+-27834, -27890, -27946, -28002, -28058,
+-28113, -28168, -28223, -28277, -28331,
+-28385, -28438, -28491, -28544, -28596,
+-28649, -28701, -28752, -28803, -28854,
+-28905, -28955, -29006, -29055, -29105,
+-29154, -29203, -29251, -29299, -29347,
+-29395, -29442, -29489, -29535, -29582,
+-29628, -29673, -29719, -29764, -29808,
+-29853, -29897, -29941, -29984, -30027,
+-30070, -30112, -30154, -30196, -30238,
+-30279, -30320, -30360, -30400, -30440,
+-30480, -30519, -30558, -30596, -30635,
+-30672, -30710, -30747, -30784, -30821,
+-30857, -30893, -30929, -30964, -30999,
+-31033, -31068, -31102, -31135, -31168,
+-31201, -31234, -31266, -31298, -31330,
+-31361, -31392, -31422, -31453, -31483,
+-31512, -31541, -31570, -31599, -31627,
+-31655, -31682, -31710, -31737, -31763,
+-31789, -31815, -31841, -31866, -31891,
+-31915, -31939, -31963, -31986, -32010,
+-32032, -32055, -32077, -32099, -32120,
+-32141, -32162, -32182, -32202, -32222,
+-32241, -32260, -32279, -32297, -32315,
+-32333, -32350, -32367, -32383, -32399,
+-32415, -32431, -32446, -32461, -32475,
+-32489, -32503, -32517, -32530, -32542,
+-32555, -32567, -32579, -32590, -32601,
+-32612, -32622, -32632, -32641, -32651,
+-32659, -32668, -32676, -32684, -32692,
+-32699, -32706, -32712, -32718, -32724,
+-32729, -32734, -32739, -32743, -32747,
+-32751, -32754, -32757, -32760, -32762,
+-32764, -32765, -32767, -32767, -32767,
+32767, 32767, 32765, 32761, 32756,
+32750, 32742, 32732, 32722, 32710,
+32696, 32681, 32665, 32647, 32628,
+32608, 32586, 32562, 32538, 32512,
+32484, 32455, 32425, 32393, 32360,
+32326, 32290, 32253, 32214, 32174,
+32133, 32090, 32046, 32001, 31954,
+31906, 31856, 31805, 31753, 31700,
+31645, 31588, 31530, 31471, 31411,
+31349, 31286, 31222, 31156, 31089,
+31020, 30951, 30880, 30807, 30733,
+30658, 30582, 30504, 30425, 30345,
+30263, 30181, 30096, 30011, 29924,
+29836, 29747, 29656, 29564, 29471,
+29377, 29281, 29184, 29086, 28987,
+28886, 28784, 28681, 28577, 28471,
+28365, 28257, 28147, 28037, 27925,
+27812, 27698, 27583, 27467, 27349,
+27231, 27111, 26990, 26868, 26744,
+26620, 26494, 26367, 26239, 26110,
+25980, 25849, 25717, 25583, 25449,
+25313, 25176, 25038, 24900, 24760,
+24619, 24477, 24333, 24189, 24044,
+23898, 23751, 23602, 23453, 23303,
+23152, 22999, 22846, 22692, 22537,
+22380, 22223, 22065, 21906, 21746,
+21585, 21423, 21261, 21097, 20933,
+20767, 20601, 20434, 20265, 20096,
+19927, 19756, 19584, 19412, 19239,
+19065, 18890, 18714, 18538, 18361,
+18183, 18004, 17824, 17644, 17463,
+17281, 17098, 16915, 16731, 16546,
+16361, 16175, 15988, 15800, 15612,
+15423, 15234, 15043, 14852, 14661,
+14469, 14276, 14083, 13889, 13694,
+13499, 13303, 13107, 12910, 12713,
+12515, 12317, 12118, 11918, 11718,
+11517, 11316, 11115, 10913, 10710,
+10508, 10304, 10100, 9896, 9691,
+9486, 9281, 9075, 8869, 8662,
+8455, 8248, 8040, 7832, 7623,
+7415, 7206, 6996, 6787, 6577,
+6366, 6156, 5945, 5734, 5523,
+5311, 5100, 4888, 4675, 4463,
+4251, 4038, 3825, 3612, 3399,
+3185, 2972, 2758, 2544, 2330,
+2116, 1902, 1688, 1474, 1260,
+1045, 831, 617, 402, 188,
+-27, -241, -456, -670, -885,
+-1099, -1313, -1528, -1742, -1956,
+-2170, -2384, -2598, -2811, -3025,
+-3239, -3452, -3665, -3878, -4091,
+-4304, -4516, -4728, -4941, -5153,
+-5364, -5576, -5787, -5998, -6209,
+-6419, -6629, -6839, -7049, -7258,
+-7467, -7676, -7884, -8092, -8300,
+-8507, -8714, -8920, -9127, -9332,
+-9538, -9743, -9947, -10151, -10355,
+-10558, -10761, -10963, -11165, -11367,
+-11568, -11768, -11968, -12167, -12366,
+-12565, -12762, -12960, -13156, -13352,
+-13548, -13743, -13937, -14131, -14324,
+-14517, -14709, -14900, -15091, -15281,
+-15470, -15659, -15847, -16035, -16221,
+-16407, -16593, -16777, -16961, -17144,
+-17326, -17508, -17689, -17869, -18049,
+-18227, -18405, -18582, -18758, -18934,
+-19108, -19282, -19455, -19627, -19799,
+-19969, -20139, -20308, -20475, -20642,
+-20809, -20974, -21138, -21301, -21464,
+-21626, -21786, -21946, -22105, -22263,
+-22420, -22575, -22730, -22884, -23037,
+-23189, -23340, -23490, -23640, -23788,
+-23935, -24080, -24225, -24369, -24512,
+-24654, -24795, -24934, -25073, -25211,
+-25347, -25482, -25617, -25750, -25882,
+-26013, -26143, -26272, -26399, -26526,
+-26651, -26775, -26898, -27020, -27141,
+-27260, -27379, -27496, -27612, -27727,
+-27841, -27953, -28065, -28175, -28284,
+-28391, -28498, -28603, -28707, -28810,
+-28911, -29012, -29111, -29209, -29305,
+-29401, -29495, -29587, -29679, -29769,
+-29858, -29946, -30032, -30118, -30201,
+-30284, -30365, -30445, -30524, -30601,
+-30677, -30752, -30825, -30897, -30968,
+-31038, -31106, -31172, -31238, -31302,
+-31365, -31426, -31486, -31545, -31602,
+-31658, -31713, -31766, -31818, -31869,
+-31918, -31966, -32012, -32058, -32101,
+-32144, -32185, -32224, -32262, -32299,
+-32335, -32369, -32401, -32433, -32463,
+-32491, -32518, -32544, -32568, -32591,
+-32613, -32633, -32652, -32669, -32685,
+-32700, -32713, -32724, -32735, -32744,
+-32751, -32757, -32762, -32766, -32767,
+32767, 32764, 32755, 32741, 32720,
+32694, 32663, 32626, 32583, 32535,
+32481, 32421, 32356, 32286, 32209,
+32128, 32041, 31948, 31850, 31747,
+31638, 31523, 31403, 31278, 31148,
+31012, 30871, 30724, 30572, 30415,
+30253, 30086, 29913, 29736, 29553,
+29365, 29172, 28974, 28771, 28564,
+28351, 28134, 27911, 27684, 27452,
+27216, 26975, 26729, 26478, 26223,
+25964, 25700, 25432, 25159, 24882,
+24601, 24315, 24026, 23732, 23434,
+23133, 22827, 22517, 22204, 21886,
+21565, 21240, 20912, 20580, 20244,
+19905, 19563, 19217, 18868, 18516,
+18160, 17802, 17440, 17075, 16708,
+16338, 15964, 15588, 15210, 14829,
+14445, 14059, 13670, 13279, 12886,
+12490, 12093, 11693, 11291, 10888,
+10482, 10075, 9666, 9255, 8843,
+8429, 8014, 7597, 7180, 6760,
+6340, 5919, 5496, 5073, 4649,
+4224, 3798, 3372, 2945, 2517,
+2090, 1661, 1233, 804, 375,
+-54, -483, -911, -1340, -1768,
+-2197, -2624, -3052, -3479, -3905,
+-4330, -4755, -5179, -5602, -6024,
+-6445, -6865, -7284, -7702, -8118,
+-8533, -8946, -9358, -9768, -10177,
+-10584, -10989, -11392, -11793, -12192,
+-12589, -12984, -13377, -13767, -14155,
+-14541, -14924, -15305, -15683, -16058,
+-16430, -16800, -17167, -17531, -17892,
+-18249, -18604, -18956, -19304, -19649,
+-19990, -20329, -20663, -20994, -21322,
+-21646, -21966, -22282, -22595, -22904,
+-23208, -23509, -23806, -24099, -24387,
+-24672, -24952, -25228, -25499, -25766,
+-26029, -26288, -26541, -26791, -27035,
+-27275, -27511, -27741, -27967, -28188,
+-28405, -28616, -28823, -29024, -29221,
+-29412, -29599, -29780, -29957, -30128,
+-30294, -30455, -30611, -30761, -30906,
+-31046, -31181, -31310, -31434, -31552,
+-31665, -31773, -31875, -31972, -32063,
+-32149, -32229, -32304, -32373, -32437,
+-32495, -32547, -32594, -32635, -32671,
+-32701, -32726, -32745, -32758, -32766,
+32767, 32754, 32717, 32658, 32577,
+32473, 32348, 32200, 32029, 31837,
+31624, 31388, 31131, 30853, 30553,
+30232, 29891, 29530, 29148, 28746,
+28324, 27883, 27423, 26944, 26447,
+25931, 25398, 24847, 24279, 23695,
+23095, 22478, 21846, 21199, 20538,
+19863, 19174, 18472, 17757, 17030,
+16291, 15541, 14781, 14010, 13230,
+12441, 11643, 10837, 10024, 9204,
+8377, 7545, 6708, 5866, 5020,
+4171, 3319, 2464, 1608, 751,
+-107, -965, -1822, -2678, -3532,
+-4383, -5232, -6077, -6918, -7754,
+-8585, -9409, -10228, -11039, -11843,
+-12639, -13426, -14204, -14972, -15730,
+-16477, -17213, -17937, -18648, -19347,
+-20033, -20705, -21363, -22006, -22634,
+-23246, -23843, -24423, -24986, -25533,
+-26062, -26573, -27066, -27540, -27995,
+-28431, -28848, -29245, -29622, -29979,
+-30315, -30630, -30924, -31197, -31449,
+-31679, -31887, -32074, -32239, -32381,
+-32501, -32600, -32675, -32729, -32759,
+};
+#endif
+
+static const CELTMode mode48000_960_120 = {
+48000,  /* Fs */
+120,    /* overlap */
+21,     /* nbEBands */
+21,     /* effEBands */
+{27853, 0, 4096, 8192, },       /* preemph */
+eband5ms,       /* eBands */
+3,      /* maxLM */
+8,      /* nbShortMdcts */
+120,    /* shortMdctSize */
+11,     /* nbAllocVectors */
+band_allocation,        /* allocVectors */
+logN400,        /* logN */
+window120,      /* window */
+{1920, 3, {&fft_state48000_960_0, &fft_state48000_960_1, &fft_state48000_960_2, &fft_state48000_960_3, }, mdct_twiddles960},    /* mdct */
+{392, cache_index50, cache_bits50, cache_caps50},       /* cache */
+};
+
+/* List of all the available modes */
+#define TOTAL_MODES 1
+static const CELTMode * const static_mode_list[TOTAL_MODES] = {
+&mode48000_960_120,
+};
diff --git a/opus/celt/static_modes_fixed_arm_ne10.h b/opus/celt/static_modes_fixed_arm_ne10.h
new file mode 100644 (file)
index 0000000..7623092
--- /dev/null
@@ -0,0 +1,388 @@
+/* The contents of this file was automatically generated by
+ * dump_mode_arm_ne10.c with arguments: 48000 960
+ * It contains static definitions for some pre-defined modes. */
+#include <NE10_types.h>
+
+#ifndef NE10_FFT_PARAMS48000_960
+#define NE10_FFT_PARAMS48000_960
+static const ne10_int32_t ne10_factors_480[64] = {
+4, 40, 4, 30, 2, 15, 5, 3, 3, 1, 1, 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, 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, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_240[64] = {
+3, 20, 4, 15, 5, 3, 3, 1, 1, 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, 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, 0,
+0, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_120[64] = {
+3, 10, 2, 15, 5, 3, 3, 1, 1, 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, 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, 0,
+0, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_60[64] = {
+2, 5, 5, 3, 3, 1, 1, 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, 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, 0, 0, 0,
+0, 0, 0, 0, };
+static const ne10_fft_cpx_int32_t ne10_twiddles_480[480] = {
+{0,0}, {2147483647,0}, {2147483647,0},
+{2147483647,0}, {1961823921,-873460313}, {1436946998,-1595891394},
+{2147483647,0}, {1436946998,-1595891394}, {-224473265,-2135719496},
+{2147483647,0}, {663608871,-2042378339}, {-1737350854,-1262259096},
+{2147483647,0}, {-224473265,-2135719496}, {-2100555935,446487152},
+{2147483647,0}, {2100555974,-446486968}, {1961823921,-873460313},
+{1737350743,-1262259248}, {1436946998,-1595891394}, {1073741769,-1859775424},
+{663608871,-2042378339}, {224473078,-2135719516}, {-224473265,-2135719496},
+{-663609049,-2042378281}, {-1073741932,-1859775330}, {-1436947137,-1595891268},
+{-1737350854,-1262259096}, {-1961823997,-873460141}, {-2100556013,-446486785},
+{2147483647,0}, {2144540595,-112390613}, {2135719506,-224473172},
+{2121044558,-335940465}, {2100555974,-446486968}, {2074309912,-555809682},
+{2042378310,-663608960}, {2004848691,-769589332}, {1961823921,-873460313},
+{1913421927,-974937199}, {1859775377,-1073741851}, {1801031311,-1169603450},
+{1737350743,-1262259248}, {1668908218,-1351455280}, {1595891331,-1436947067},
+{1518500216,-1518500282}, {1436946998,-1595891394}, {1351455207,-1668908277},
+{1262259172,-1737350799}, {1169603371,-1801031362}, {1073741769,-1859775424},
+{974937230,-1913421912}, {873460227,-1961823959}, {769589125,-2004848771},
+{663608871,-2042378339}, {555809715,-2074309903}, {446486876,-2100555994},
+{335940246,-2121044593}, {224473078,-2135719516}, {112390647,-2144540593},
+{2147483647,0}, {2135719506,-224473172}, {2100555974,-446486968},
+{2042378310,-663608960}, {1961823921,-873460313}, {1859775377,-1073741851},
+{1737350743,-1262259248}, {1595891331,-1436947067}, {1436946998,-1595891394},
+{1262259172,-1737350799}, {1073741769,-1859775424}, {873460227,-1961823959},
+{663608871,-2042378339}, {446486876,-2100555994}, {224473078,-2135719516},
+{-94,-2147483647}, {-224473265,-2135719496}, {-446487060,-2100555955},
+{-663609049,-2042378281}, {-873460398,-1961823883}, {-1073741932,-1859775330},
+{-1262259116,-1737350839}, {-1436947137,-1595891268}, {-1595891628,-1436946738},
+{-1737350854,-1262259096}, {-1859775343,-1073741910}, {-1961823997,-873460141},
+{-2042378447,-663608538}, {-2100556013,-446486785}, {-2135719499,-224473240},
+{2147483647,0}, {2121044558,-335940465}, {2042378310,-663608960},
+{1913421927,-974937199}, {1737350743,-1262259248}, {1518500216,-1518500282},
+{1262259172,-1737350799}, {974937230,-1913421912}, {663608871,-2042378339},
+{335940246,-2121044593}, {-94,-2147483647}, {-335940431,-2121044564},
+{-663609049,-2042378281}, {-974937397,-1913421827}, {-1262259116,-1737350839},
+{-1518500258,-1518500240}, {-1737350854,-1262259096}, {-1913422071,-974936918},
+{-2042378447,-663608538}, {-2121044568,-335940406}, {-2147483647,188},
+{-2121044509,335940777}, {-2042378331,663608895}, {-1913421900,974937252},
+{-1737350633,1262259400}, {-1518499993,1518500506}, {-1262258813,1737351059},
+{-974936606,1913422229}, {-663609179,2042378239}, {-335940566,2121044542},
+{2147483647,0}, {2147299667,-28109693}, {2146747758,-56214570},
+{2145828015,-84309815}, {2144540595,-112390613}, {2142885719,-140452154},
+{2140863671,-168489630}, {2138474797,-196498235}, {2135719506,-224473172},
+{2132598271,-252409646}, {2129111626,-280302871}, {2125260168,-308148068},
+{2121044558,-335940465}, {2116465518,-363675300}, {2111523833,-391347822},
+{2106220349,-418953288}, {2100555974,-446486968}, {2094531681,-473944146},
+{2088148500,-501320115}, {2081407525,-528610186}, {2074309912,-555809682},
+{2066856885,-582913912}, {2059049696,-609918325}, {2050889698,-636818231},
+{2042378310,-663608960}, {2033516972,-690285983}, {2024307180,-716844791},
+{2014750533,-743280770}, {2004848691,-769589332}, {1994603329,-795766029},
+{1984016179,-821806435}, {1973089077,-847706028}, {1961823921,-873460313},
+{1950222618,-899064934}, {1938287127,-924515564}, {1926019520,-949807783},
+{1913421927,-974937199}, {1900496481,-999899565}, {1887245364,-1024690661},
+{1873670877,-1049306180}, {1859775377,-1073741851}, {1845561215,-1097993541},
+{1831030826,-1122057097}, {1816186632,-1145928502}, {1801031311,-1169603450},
+{1785567394,-1193077993}, {1769797456,-1216348214}, {1753724345,-1239409914},
+{1737350743,-1262259248}, {1720679456,-1284892300}, {1703713340,-1307305194},
+{1686455222,-1329494189}, {1668908218,-1351455280}, {1651075255,-1373184807},
+{1632959307,-1394679144}, {1614563642,-1415934412}, {1595891331,-1436947067},
+{1576945572,-1457713510}, {1557729613,-1478230181}, {1538246655,-1498493658},
+{1518500216,-1518500282}, {1498493590,-1538246721}, {1478230113,-1557729677},
+{1457713441,-1576945636}, {1436946998,-1595891394}, {1415934341,-1614563704},
+{1394679073,-1632959368}, {1373184735,-1651075315}, {1351455207,-1668908277},
+{1329494115,-1686455280}, {1307305120,-1703713397}, {1284892225,-1720679512},
+{1262259172,-1737350799}, {1239409837,-1753724400}, {1216348136,-1769797510},
+{1193077915,-1785567446}, {1169603371,-1801031362}, {1145928423,-1816186682},
+{1122057017,-1831030875}, {1097993571,-1845561197}, {1073741769,-1859775424},
+{1049305987,-1873670985}, {1024690635,-1887245378}, {999899482,-1900496524},
+{974937230,-1913421912}, {949807699,-1926019561}, {924515422,-1938287195},
+{899064965,-1950222603}, {873460227,-1961823959}, {847705824,-1973089164},
+{821806407,-1984016190}, {795765941,-1994603364}, {769589125,-2004848771},
+{743280682,-2014750566}, {716844642,-2024307233}, {690286016,-2033516961},
+{663608871,-2042378339}, {636818019,-2050889764}, {609918296,-2059049705},
+{582913822,-2066856911}, {555809715,-2074309903}, {528610126,-2081407540},
+{501319962,-2088148536}, {473944148,-2094531680}, {446486876,-2100555994},
+{418953102,-2106220386}, {391347792,-2111523838}, {363675176,-2116465540},
+{335940246,-2121044593}, {308148006,-2125260177}, {280302715,-2129111646},
+{252409648,-2132598271}, {224473078,-2135719516}, {196498046,-2138474814},
+{168489600,-2140863674}, {140452029,-2142885728}, {112390647,-2144540593},
+{84309753,-2145828017}, {56214412,-2146747762}, {28109695,-2147299667},
+{2147483647,0}, {2146747758,-56214570}, {2144540595,-112390613},
+{2140863671,-168489630}, {2135719506,-224473172}, {2129111626,-280302871},
+{2121044558,-335940465}, {2111523833,-391347822}, {2100555974,-446486968},
+{2088148500,-501320115}, {2074309912,-555809682}, {2059049696,-609918325},
+{2042378310,-663608960}, {2024307180,-716844791}, {2004848691,-769589332},
+{1984016179,-821806435}, {1961823921,-873460313}, {1938287127,-924515564},
+{1913421927,-974937199}, {1887245364,-1024690661}, {1859775377,-1073741851},
+{1831030826,-1122057097}, {1801031311,-1169603450}, {1769797456,-1216348214},
+{1737350743,-1262259248}, {1703713340,-1307305194}, {1668908218,-1351455280},
+{1632959307,-1394679144}, {1595891331,-1436947067}, {1557729613,-1478230181},
+{1518500216,-1518500282}, {1478230113,-1557729677}, {1436946998,-1595891394},
+{1394679073,-1632959368}, {1351455207,-1668908277}, {1307305120,-1703713397},
+{1262259172,-1737350799}, {1216348136,-1769797510}, {1169603371,-1801031362},
+{1122057017,-1831030875}, {1073741769,-1859775424}, {1024690635,-1887245378},
+{974937230,-1913421912}, {924515422,-1938287195}, {873460227,-1961823959},
+{821806407,-1984016190}, {769589125,-2004848771}, {716844642,-2024307233},
+{663608871,-2042378339}, {609918296,-2059049705}, {555809715,-2074309903},
+{501319962,-2088148536}, {446486876,-2100555994}, {391347792,-2111523838},
+{335940246,-2121044593}, {280302715,-2129111646}, {224473078,-2135719516},
+{168489600,-2140863674}, {112390647,-2144540593}, {56214412,-2146747762},
+{-94,-2147483647}, {-56214600,-2146747757}, {-112390835,-2144540584},
+{-168489787,-2140863659}, {-224473265,-2135719496}, {-280302901,-2129111622},
+{-335940431,-2121044564}, {-391347977,-2111523804}, {-446487060,-2100555955},
+{-501320144,-2088148493}, {-555809896,-2074309855}, {-609918476,-2059049651},
+{-663609049,-2042378281}, {-716844819,-2024307170}, {-769589300,-2004848703},
+{-821806581,-1984016118}, {-873460398,-1961823883}, {-924515591,-1938287114},
+{-974937397,-1913421827}, {-1024690575,-1887245411}, {-1073741932,-1859775330},
+{-1122057395,-1831030643}, {-1169603421,-1801031330}, {-1216348291,-1769797403},
+{-1262259116,-1737350839}, {-1307305268,-1703713283}, {-1351455453,-1668908078},
+{-1394679021,-1632959413}, {-1436947137,-1595891268}, {-1478230435,-1557729372},
+{-1518500258,-1518500240}, {-1557729742,-1478230045}, {-1595891628,-1436946738},
+{-1632959429,-1394679001}, {-1668908417,-1351455035}, {-1703713298,-1307305248},
+{-1737350854,-1262259096}, {-1769797708,-1216347848}, {-1801031344,-1169603400},
+{-1831030924,-1122056937}, {-1859775343,-1073741910}, {-1887245423,-1024690552},
+{-1913422071,-974936918}, {-1938287125,-924515568}, {-1961823997,-873460141},
+{-1984016324,-821806084}, {-2004848713,-769589276}, {-2024307264,-716844553},
+{-2042378447,-663608538}, {-2059049731,-609918206}, {-2074309994,-555809377},
+{-2088148499,-501320119}, {-2100556013,-446486785}, {-2111523902,-391347448},
+{-2121044568,-335940406}, {-2129111659,-280302621}, {-2135719499,-224473240},
+{-2140863681,-168489506}, {-2144540612,-112390298}, {-2146747758,-56214574},
+{2147483647,0}, {2145828015,-84309815}, {2140863671,-168489630},
+{2132598271,-252409646}, {2121044558,-335940465}, {2106220349,-418953288},
+{2088148500,-501320115}, {2066856885,-582913912}, {2042378310,-663608960},
+{2014750533,-743280770}, {1984016179,-821806435}, {1950222618,-899064934},
+{1913421927,-974937199}, {1873670877,-1049306180}, {1831030826,-1122057097},
+{1785567394,-1193077993}, {1737350743,-1262259248}, {1686455222,-1329494189},
+{1632959307,-1394679144}, {1576945572,-1457713510}, {1518500216,-1518500282},
+{1457713441,-1576945636}, {1394679073,-1632959368}, {1329494115,-1686455280},
+{1262259172,-1737350799}, {1193077915,-1785567446}, {1122057017,-1831030875},
+{1049305987,-1873670985}, {974937230,-1913421912}, {899064965,-1950222603},
+{821806407,-1984016190}, {743280682,-2014750566}, {663608871,-2042378339},
+{582913822,-2066856911}, {501319962,-2088148536}, {418953102,-2106220386},
+{335940246,-2121044593}, {252409648,-2132598271}, {168489600,-2140863674},
+{84309753,-2145828017}, {-94,-2147483647}, {-84309940,-2145828010},
+{-168489787,-2140863659}, {-252409834,-2132598249}, {-335940431,-2121044564},
+{-418953286,-2106220349}, {-501320144,-2088148493}, {-582914003,-2066856860},
+{-663609049,-2042378281}, {-743280858,-2014750501}, {-821806581,-1984016118},
+{-899065136,-1950222525}, {-974937397,-1913421827}, {-1049306374,-1873670768},
+{-1122057395,-1831030643}, {-1193078284,-1785567199}, {-1262259116,-1737350839},
+{-1329494061,-1686455323}, {-1394679021,-1632959413}, {-1457713485,-1576945595},
+{-1518500258,-1518500240}, {-1576945613,-1457713466}, {-1632959429,-1394679001},
+{-1686455338,-1329494041}, {-1737350854,-1262259096}, {-1785567498,-1193077837},
+{-1831030924,-1122056937}, {-1873671031,-1049305905}, {-1913422071,-974936918},
+{-1950222750,-899064648}, {-1984016324,-821806084}, {-2014750687,-743280354},
+{-2042378447,-663608538}, {-2066856867,-582913978}, {-2088148499,-501320119},
+{-2106220354,-418953261}, {-2121044568,-335940406}, {-2132598282,-252409555},
+{-2140863681,-168489506}, {-2145828021,-84309659}, {-2147483647,188},
+{-2145828006,84310034}, {-2140863651,168489881}, {-2132598237,252409928},
+{-2121044509,335940777}, {-2106220281,418953629}, {-2088148411,501320484},
+{-2066856765,582914339}, {-2042378331,663608895}, {-2014750557,743280706},
+{-1984016181,821806431}, {-1950222593,899064989}, {-1913421900,974937252},
+{-1873670848,1049306232}, {-1831030728,1122057257}, {-1785567289,1193078149},
+{-1737350633,1262259400}, {-1686455106,1329494336}, {-1632959185,1394679287},
+{-1576945358,1457713742}, {-1518499993,1518500506}, {-1457713209,1576945850},
+{-1394678735,1632959656}, {-1329493766,1686455555}, {-1262258813,1737351059},
+{-1193077546,1785567692}, {-1122056638,1831031107}, {-1049305599,1873671202},
+{-974936606,1913422229}, {-899064330,1950222896}, {-821805761,1984016458},
+{-743280025,2014750808}, {-663609179,2042378239}, {-582914134,2066856823},
+{-501320277,2088148461}, {-418953420,2106220322}, {-335940566,2121044542},
+{-252409716,2132598263}, {-168489668,2140863668}, {-84309821,2145828015},
+};
+static const ne10_fft_cpx_int32_t ne10_twiddles_240[240] = {
+{0,0}, {2147483647,0}, {2147483647,0},
+{2147483647,0}, {1961823921,-873460313}, {1436946998,-1595891394},
+{2147483647,0}, {1436946998,-1595891394}, {-224473265,-2135719496},
+{2147483647,0}, {663608871,-2042378339}, {-1737350854,-1262259096},
+{2147483647,0}, {-224473265,-2135719496}, {-2100555935,446487152},
+{2147483647,0}, {2135719506,-224473172}, {2100555974,-446486968},
+{2042378310,-663608960}, {1961823921,-873460313}, {1859775377,-1073741851},
+{1737350743,-1262259248}, {1595891331,-1436947067}, {1436946998,-1595891394},
+{1262259172,-1737350799}, {1073741769,-1859775424}, {873460227,-1961823959},
+{663608871,-2042378339}, {446486876,-2100555994}, {224473078,-2135719516},
+{2147483647,0}, {2100555974,-446486968}, {1961823921,-873460313},
+{1737350743,-1262259248}, {1436946998,-1595891394}, {1073741769,-1859775424},
+{663608871,-2042378339}, {224473078,-2135719516}, {-224473265,-2135719496},
+{-663609049,-2042378281}, {-1073741932,-1859775330}, {-1436947137,-1595891268},
+{-1737350854,-1262259096}, {-1961823997,-873460141}, {-2100556013,-446486785},
+{2147483647,0}, {2042378310,-663608960}, {1737350743,-1262259248},
+{1262259172,-1737350799}, {663608871,-2042378339}, {-94,-2147483647},
+{-663609049,-2042378281}, {-1262259116,-1737350839}, {-1737350854,-1262259096},
+{-2042378447,-663608538}, {-2147483647,188}, {-2042378331,663608895},
+{-1737350633,1262259400}, {-1262258813,1737351059}, {-663609179,2042378239},
+{2147483647,0}, {2146747758,-56214570}, {2144540595,-112390613},
+{2140863671,-168489630}, {2135719506,-224473172}, {2129111626,-280302871},
+{2121044558,-335940465}, {2111523833,-391347822}, {2100555974,-446486968},
+{2088148500,-501320115}, {2074309912,-555809682}, {2059049696,-609918325},
+{2042378310,-663608960}, {2024307180,-716844791}, {2004848691,-769589332},
+{1984016179,-821806435}, {1961823921,-873460313}, {1938287127,-924515564},
+{1913421927,-974937199}, {1887245364,-1024690661}, {1859775377,-1073741851},
+{1831030826,-1122057097}, {1801031311,-1169603450}, {1769797456,-1216348214},
+{1737350743,-1262259248}, {1703713340,-1307305194}, {1668908218,-1351455280},
+{1632959307,-1394679144}, {1595891331,-1436947067}, {1557729613,-1478230181},
+{1518500216,-1518500282}, {1478230113,-1557729677}, {1436946998,-1595891394},
+{1394679073,-1632959368}, {1351455207,-1668908277}, {1307305120,-1703713397},
+{1262259172,-1737350799}, {1216348136,-1769797510}, {1169603371,-1801031362},
+{1122057017,-1831030875}, {1073741769,-1859775424}, {1024690635,-1887245378},
+{974937230,-1913421912}, {924515422,-1938287195}, {873460227,-1961823959},
+{821806407,-1984016190}, {769589125,-2004848771}, {716844642,-2024307233},
+{663608871,-2042378339}, {609918296,-2059049705}, {555809715,-2074309903},
+{501319962,-2088148536}, {446486876,-2100555994}, {391347792,-2111523838},
+{335940246,-2121044593}, {280302715,-2129111646}, {224473078,-2135719516},
+{168489600,-2140863674}, {112390647,-2144540593}, {56214412,-2146747762},
+{2147483647,0}, {2144540595,-112390613}, {2135719506,-224473172},
+{2121044558,-335940465}, {2100555974,-446486968}, {2074309912,-555809682},
+{2042378310,-663608960}, {2004848691,-769589332}, {1961823921,-873460313},
+{1913421927,-974937199}, {1859775377,-1073741851}, {1801031311,-1169603450},
+{1737350743,-1262259248}, {1668908218,-1351455280}, {1595891331,-1436947067},
+{1518500216,-1518500282}, {1436946998,-1595891394}, {1351455207,-1668908277},
+{1262259172,-1737350799}, {1169603371,-1801031362}, {1073741769,-1859775424},
+{974937230,-1913421912}, {873460227,-1961823959}, {769589125,-2004848771},
+{663608871,-2042378339}, {555809715,-2074309903}, {446486876,-2100555994},
+{335940246,-2121044593}, {224473078,-2135719516}, {112390647,-2144540593},
+{-94,-2147483647}, {-112390835,-2144540584}, {-224473265,-2135719496},
+{-335940431,-2121044564}, {-446487060,-2100555955}, {-555809896,-2074309855},
+{-663609049,-2042378281}, {-769589300,-2004848703}, {-873460398,-1961823883},
+{-974937397,-1913421827}, {-1073741932,-1859775330}, {-1169603421,-1801031330},
+{-1262259116,-1737350839}, {-1351455453,-1668908078}, {-1436947137,-1595891268},
+{-1518500258,-1518500240}, {-1595891628,-1436946738}, {-1668908417,-1351455035},
+{-1737350854,-1262259096}, {-1801031344,-1169603400}, {-1859775343,-1073741910},
+{-1913422071,-974936918}, {-1961823997,-873460141}, {-2004848713,-769589276},
+{-2042378447,-663608538}, {-2074309994,-555809377}, {-2100556013,-446486785},
+{-2121044568,-335940406}, {-2135719499,-224473240}, {-2144540612,-112390298},
+{2147483647,0}, {2140863671,-168489630}, {2121044558,-335940465},
+{2088148500,-501320115}, {2042378310,-663608960}, {1984016179,-821806435},
+{1913421927,-974937199}, {1831030826,-1122057097}, {1737350743,-1262259248},
+{1632959307,-1394679144}, {1518500216,-1518500282}, {1394679073,-1632959368},
+{1262259172,-1737350799}, {1122057017,-1831030875}, {974937230,-1913421912},
+{821806407,-1984016190}, {663608871,-2042378339}, {501319962,-2088148536},
+{335940246,-2121044593}, {168489600,-2140863674}, {-94,-2147483647},
+{-168489787,-2140863659}, {-335940431,-2121044564}, {-501320144,-2088148493},
+{-663609049,-2042378281}, {-821806581,-1984016118}, {-974937397,-1913421827},
+{-1122057395,-1831030643}, {-1262259116,-1737350839}, {-1394679021,-1632959413},
+{-1518500258,-1518500240}, {-1632959429,-1394679001}, {-1737350854,-1262259096},
+{-1831030924,-1122056937}, {-1913422071,-974936918}, {-1984016324,-821806084},
+{-2042378447,-663608538}, {-2088148499,-501320119}, {-2121044568,-335940406},
+{-2140863681,-168489506}, {-2147483647,188}, {-2140863651,168489881},
+{-2121044509,335940777}, {-2088148411,501320484}, {-2042378331,663608895},
+{-1984016181,821806431}, {-1913421900,974937252}, {-1831030728,1122057257},
+{-1737350633,1262259400}, {-1632959185,1394679287}, {-1518499993,1518500506},
+{-1394678735,1632959656}, {-1262258813,1737351059}, {-1122056638,1831031107},
+{-974936606,1913422229}, {-821805761,1984016458}, {-663609179,2042378239},
+{-501320277,2088148461}, {-335940566,2121044542}, {-168489668,2140863668},
+};
+static const ne10_fft_cpx_int32_t ne10_twiddles_120[120] = {
+{0,0}, {2147483647,0}, {2147483647,0},
+{2147483647,0}, {1961823921,-873460313}, {1436946998,-1595891394},
+{2147483647,0}, {1436946998,-1595891394}, {-224473265,-2135719496},
+{2147483647,0}, {663608871,-2042378339}, {-1737350854,-1262259096},
+{2147483647,0}, {-224473265,-2135719496}, {-2100555935,446487152},
+{2147483647,0}, {2100555974,-446486968}, {1961823921,-873460313},
+{1737350743,-1262259248}, {1436946998,-1595891394}, {1073741769,-1859775424},
+{663608871,-2042378339}, {224473078,-2135719516}, {-224473265,-2135719496},
+{-663609049,-2042378281}, {-1073741932,-1859775330}, {-1436947137,-1595891268},
+{-1737350854,-1262259096}, {-1961823997,-873460141}, {-2100556013,-446486785},
+{2147483647,0}, {2144540595,-112390613}, {2135719506,-224473172},
+{2121044558,-335940465}, {2100555974,-446486968}, {2074309912,-555809682},
+{2042378310,-663608960}, {2004848691,-769589332}, {1961823921,-873460313},
+{1913421927,-974937199}, {1859775377,-1073741851}, {1801031311,-1169603450},
+{1737350743,-1262259248}, {1668908218,-1351455280}, {1595891331,-1436947067},
+{1518500216,-1518500282}, {1436946998,-1595891394}, {1351455207,-1668908277},
+{1262259172,-1737350799}, {1169603371,-1801031362}, {1073741769,-1859775424},
+{974937230,-1913421912}, {873460227,-1961823959}, {769589125,-2004848771},
+{663608871,-2042378339}, {555809715,-2074309903}, {446486876,-2100555994},
+{335940246,-2121044593}, {224473078,-2135719516}, {112390647,-2144540593},
+{2147483647,0}, {2135719506,-224473172}, {2100555974,-446486968},
+{2042378310,-663608960}, {1961823921,-873460313}, {1859775377,-1073741851},
+{1737350743,-1262259248}, {1595891331,-1436947067}, {1436946998,-1595891394},
+{1262259172,-1737350799}, {1073741769,-1859775424}, {873460227,-1961823959},
+{663608871,-2042378339}, {446486876,-2100555994}, {224473078,-2135719516},
+{-94,-2147483647}, {-224473265,-2135719496}, {-446487060,-2100555955},
+{-663609049,-2042378281}, {-873460398,-1961823883}, {-1073741932,-1859775330},
+{-1262259116,-1737350839}, {-1436947137,-1595891268}, {-1595891628,-1436946738},
+{-1737350854,-1262259096}, {-1859775343,-1073741910}, {-1961823997,-873460141},
+{-2042378447,-663608538}, {-2100556013,-446486785}, {-2135719499,-224473240},
+{2147483647,0}, {2121044558,-335940465}, {2042378310,-663608960},
+{1913421927,-974937199}, {1737350743,-1262259248}, {1518500216,-1518500282},
+{1262259172,-1737350799}, {974937230,-1913421912}, {663608871,-2042378339},
+{335940246,-2121044593}, {-94,-2147483647}, {-335940431,-2121044564},
+{-663609049,-2042378281}, {-974937397,-1913421827}, {-1262259116,-1737350839},
+{-1518500258,-1518500240}, {-1737350854,-1262259096}, {-1913422071,-974936918},
+{-2042378447,-663608538}, {-2121044568,-335940406}, {-2147483647,188},
+{-2121044509,335940777}, {-2042378331,663608895}, {-1913421900,974937252},
+{-1737350633,1262259400}, {-1518499993,1518500506}, {-1262258813,1737351059},
+{-974936606,1913422229}, {-663609179,2042378239}, {-335940566,2121044542},
+};
+static const ne10_fft_cpx_int32_t ne10_twiddles_60[60] = {
+{0,0}, {2147483647,0}, {2147483647,0},
+{2147483647,0}, {1961823921,-873460313}, {1436946998,-1595891394},
+{2147483647,0}, {1436946998,-1595891394}, {-224473265,-2135719496},
+{2147483647,0}, {663608871,-2042378339}, {-1737350854,-1262259096},
+{2147483647,0}, {-224473265,-2135719496}, {-2100555935,446487152},
+{2147483647,0}, {2135719506,-224473172}, {2100555974,-446486968},
+{2042378310,-663608960}, {1961823921,-873460313}, {1859775377,-1073741851},
+{1737350743,-1262259248}, {1595891331,-1436947067}, {1436946998,-1595891394},
+{1262259172,-1737350799}, {1073741769,-1859775424}, {873460227,-1961823959},
+{663608871,-2042378339}, {446486876,-2100555994}, {224473078,-2135719516},
+{2147483647,0}, {2100555974,-446486968}, {1961823921,-873460313},
+{1737350743,-1262259248}, {1436946998,-1595891394}, {1073741769,-1859775424},
+{663608871,-2042378339}, {224473078,-2135719516}, {-224473265,-2135719496},
+{-663609049,-2042378281}, {-1073741932,-1859775330}, {-1436947137,-1595891268},
+{-1737350854,-1262259096}, {-1961823997,-873460141}, {-2100556013,-446486785},
+{2147483647,0}, {2042378310,-663608960}, {1737350743,-1262259248},
+{1262259172,-1737350799}, {663608871,-2042378339}, {-94,-2147483647},
+{-663609049,-2042378281}, {-1262259116,-1737350839}, {-1737350854,-1262259096},
+{-2042378447,-663608538}, {-2147483647,188}, {-2042378331,663608895},
+{-1737350633,1262259400}, {-1262258813,1737351059}, {-663609179,2042378239},
+};
+static const ne10_fft_state_int32_t ne10_fft_state_int32_t_480 = {
+120,
+(ne10_int32_t *)ne10_factors_480,
+(ne10_fft_cpx_int32_t *)ne10_twiddles_480,
+NULL,
+(ne10_fft_cpx_int32_t *)&ne10_twiddles_480[120],
+};
+static const arch_fft_state cfg_arch_480 = {
+1,
+(void *)&ne10_fft_state_int32_t_480,
+};
+
+static const ne10_fft_state_int32_t ne10_fft_state_int32_t_240 = {
+60,
+(ne10_int32_t *)ne10_factors_240,
+(ne10_fft_cpx_int32_t *)ne10_twiddles_240,
+NULL,
+(ne10_fft_cpx_int32_t *)&ne10_twiddles_240[60],
+};
+static const arch_fft_state cfg_arch_240 = {
+1,
+(void *)&ne10_fft_state_int32_t_240,
+};
+
+static const ne10_fft_state_int32_t ne10_fft_state_int32_t_120 = {
+30,
+(ne10_int32_t *)ne10_factors_120,
+(ne10_fft_cpx_int32_t *)ne10_twiddles_120,
+NULL,
+(ne10_fft_cpx_int32_t *)&ne10_twiddles_120[30],
+};
+static const arch_fft_state cfg_arch_120 = {
+1,
+(void *)&ne10_fft_state_int32_t_120,
+};
+
+static const ne10_fft_state_int32_t ne10_fft_state_int32_t_60 = {
+15,
+(ne10_int32_t *)ne10_factors_60,
+(ne10_fft_cpx_int32_t *)ne10_twiddles_60,
+NULL,
+(ne10_fft_cpx_int32_t *)&ne10_twiddles_60[15],
+};
+static const arch_fft_state cfg_arch_60 = {
+1,
+(void *)&ne10_fft_state_int32_t_60,
+};
+
+#endif  /* end NE10_FFT_PARAMS48000_960 */
diff --git a/opus/celt/static_modes_float.h b/opus/celt/static_modes_float.h
new file mode 100644 (file)
index 0000000..e102a38
--- /dev/null
@@ -0,0 +1,888 @@
+/* The contents of this file was automatically generated by dump_modes.c
+   with arguments: 48000 960
+   It contains static definitions for some pre-defined modes. */
+#include "modes.h"
+#include "rate.h"
+
+#ifdef HAVE_ARM_NE10
+#define OVERRIDE_FFT 1
+#include "static_modes_float_arm_ne10.h"
+#endif
+
+#ifndef DEF_WINDOW120
+#define DEF_WINDOW120
+static const opus_val16 window120[120] = {
+6.7286966e-05f, 0.00060551348f, 0.0016815970f, 0.0032947962f, 0.0054439943f,
+0.0081276923f, 0.011344001f, 0.015090633f, 0.019364886f, 0.024163635f,
+0.029483315f, 0.035319905f, 0.041668911f, 0.048525347f, 0.055883718f,
+0.063737999f, 0.072081616f, 0.080907428f, 0.090207705f, 0.099974111f,
+0.11019769f, 0.12086883f, 0.13197729f, 0.14351214f, 0.15546177f,
+0.16781389f, 0.18055550f, 0.19367290f, 0.20715171f, 0.22097682f,
+0.23513243f, 0.24960208f, 0.26436860f, 0.27941419f, 0.29472040f,
+0.31026818f, 0.32603788f, 0.34200931f, 0.35816177f, 0.37447407f,
+0.39092462f, 0.40749142f, 0.42415215f, 0.44088423f, 0.45766484f,
+0.47447104f, 0.49127978f, 0.50806798f, 0.52481261f, 0.54149077f,
+0.55807973f, 0.57455701f, 0.59090049f, 0.60708841f, 0.62309951f,
+0.63891306f, 0.65450896f, 0.66986776f, 0.68497077f, 0.69980010f,
+0.71433873f, 0.72857055f, 0.74248043f, 0.75605424f, 0.76927895f,
+0.78214257f, 0.79463430f, 0.80674445f, 0.81846456f, 0.82978733f,
+0.84070669f, 0.85121779f, 0.86131698f, 0.87100183f, 0.88027111f,
+0.88912479f, 0.89756398f, 0.90559094f, 0.91320904f, 0.92042270f,
+0.92723738f, 0.93365955f, 0.93969656f, 0.94535671f, 0.95064907f,
+0.95558353f, 0.96017067f, 0.96442171f, 0.96834849f, 0.97196334f,
+0.97527906f, 0.97830883f, 0.98106616f, 0.98356480f, 0.98581869f,
+0.98784191f, 0.98964856f, 0.99125274f, 0.99266849f, 0.99390969f,
+0.99499004f, 0.99592297f, 0.99672162f, 0.99739874f, 0.99796667f,
+0.99843728f, 0.99882195f, 0.99913147f, 0.99937606f, 0.99956527f,
+0.99970802f, 0.99981248f, 0.99988613f, 0.99993565f, 0.99996697f,
+0.99998518f, 0.99999457f, 0.99999859f, 0.99999982f, 1.0000000f,
+};
+#endif
+
+#ifndef DEF_LOGN400
+#define DEF_LOGN400
+static const opus_int16 logN400[21] = {
+0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, };
+#endif
+
+#ifndef DEF_PULSE_CACHE50
+#define DEF_PULSE_CACHE50
+static const opus_int16 cache_index50[105] = {
+-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41,
+82, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41,
+41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41,
+41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305,
+318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240,
+305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240,
+240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387,
+};
+static const unsigned char cache_bits50[392] = {
+40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28,
+31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50,
+51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65,
+66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61,
+64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92,
+94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123,
+124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94,
+97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, 129, 131, 135, 139,
+142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35,
+28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149,
+153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225,
+229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157,
+166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, 63,
+86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250,
+25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180,
+185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89,
+110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41,
+74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138,
+163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214,
+228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49,
+90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47,
+87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57,
+106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187,
+224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127,
+182, 234, };
+static const unsigned char cache_caps50[168] = {
+224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185,
+178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240,
+240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160,
+160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172,
+138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207,
+204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185,
+185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39,
+207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201,
+188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193,
+193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204,
+204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175,
+140, 66, 40, };
+#endif
+
+#ifndef FFT_TWIDDLES48000_960
+#define FFT_TWIDDLES48000_960
+static const kiss_twiddle_cpx fft_twiddles48000_960[480] = {
+{1.0000000f, -0.0000000f}, {0.99991433f, -0.013089596f},
+{0.99965732f, -0.026176948f}, {0.99922904f, -0.039259816f},
+{0.99862953f, -0.052335956f}, {0.99785892f, -0.065403129f},
+{0.99691733f, -0.078459096f}, {0.99580493f, -0.091501619f},
+{0.99452190f, -0.10452846f}, {0.99306846f, -0.11753740f},
+{0.99144486f, -0.13052619f}, {0.98965139f, -0.14349262f},
+{0.98768834f, -0.15643447f}, {0.98555606f, -0.16934950f},
+{0.98325491f, -0.18223553f}, {0.98078528f, -0.19509032f},
+{0.97814760f, -0.20791169f}, {0.97534232f, -0.22069744f},
+{0.97236992f, -0.23344536f}, {0.96923091f, -0.24615329f},
+{0.96592583f, -0.25881905f}, {0.96245524f, -0.27144045f},
+{0.95881973f, -0.28401534f}, {0.95501994f, -0.29654157f},
+{0.95105652f, -0.30901699f}, {0.94693013f, -0.32143947f},
+{0.94264149f, -0.33380686f}, {0.93819134f, -0.34611706f},
+{0.93358043f, -0.35836795f}, {0.92880955f, -0.37055744f},
+{0.92387953f, -0.38268343f}, {0.91879121f, -0.39474386f},
+{0.91354546f, -0.40673664f}, {0.90814317f, -0.41865974f},
+{0.90258528f, -0.43051110f}, {0.89687274f, -0.44228869f},
+{0.89100652f, -0.45399050f}, {0.88498764f, -0.46561452f},
+{0.87881711f, -0.47715876f}, {0.87249601f, -0.48862124f},
+{0.86602540f, -0.50000000f}, {0.85940641f, -0.51129309f},
+{0.85264016f, -0.52249856f}, {0.84572782f, -0.53361452f},
+{0.83867057f, -0.54463904f}, {0.83146961f, -0.55557023f},
+{0.82412619f, -0.56640624f}, {0.81664156f, -0.57714519f},
+{0.80901699f, -0.58778525f}, {0.80125381f, -0.59832460f},
+{0.79335334f, -0.60876143f}, {0.78531693f, -0.61909395f},
+{0.77714596f, -0.62932039f}, {0.76884183f, -0.63943900f},
+{0.76040597f, -0.64944805f}, {0.75183981f, -0.65934582f},
+{0.74314483f, -0.66913061f}, {0.73432251f, -0.67880075f},
+{0.72537437f, -0.68835458f}, {0.71630194f, -0.69779046f},
+{0.70710678f, -0.70710678f}, {0.69779046f, -0.71630194f},
+{0.68835458f, -0.72537437f}, {0.67880075f, -0.73432251f},
+{0.66913061f, -0.74314483f}, {0.65934582f, -0.75183981f},
+{0.64944805f, -0.76040597f}, {0.63943900f, -0.76884183f},
+{0.62932039f, -0.77714596f}, {0.61909395f, -0.78531693f},
+{0.60876143f, -0.79335334f}, {0.59832460f, -0.80125381f},
+{0.58778525f, -0.80901699f}, {0.57714519f, -0.81664156f},
+{0.56640624f, -0.82412619f}, {0.55557023f, -0.83146961f},
+{0.54463904f, -0.83867057f}, {0.53361452f, -0.84572782f},
+{0.52249856f, -0.85264016f}, {0.51129309f, -0.85940641f},
+{0.50000000f, -0.86602540f}, {0.48862124f, -0.87249601f},
+{0.47715876f, -0.87881711f}, {0.46561452f, -0.88498764f},
+{0.45399050f, -0.89100652f}, {0.44228869f, -0.89687274f},
+{0.43051110f, -0.90258528f}, {0.41865974f, -0.90814317f},
+{0.40673664f, -0.91354546f}, {0.39474386f, -0.91879121f},
+{0.38268343f, -0.92387953f}, {0.37055744f, -0.92880955f},
+{0.35836795f, -0.93358043f}, {0.34611706f, -0.93819134f},
+{0.33380686f, -0.94264149f}, {0.32143947f, -0.94693013f},
+{0.30901699f, -0.95105652f}, {0.29654157f, -0.95501994f},
+{0.28401534f, -0.95881973f}, {0.27144045f, -0.96245524f},
+{0.25881905f, -0.96592583f}, {0.24615329f, -0.96923091f},
+{0.23344536f, -0.97236992f}, {0.22069744f, -0.97534232f},
+{0.20791169f, -0.97814760f}, {0.19509032f, -0.98078528f},
+{0.18223553f, -0.98325491f}, {0.16934950f, -0.98555606f},
+{0.15643447f, -0.98768834f}, {0.14349262f, -0.98965139f},
+{0.13052619f, -0.99144486f}, {0.11753740f, -0.99306846f},
+{0.10452846f, -0.99452190f}, {0.091501619f, -0.99580493f},
+{0.078459096f, -0.99691733f}, {0.065403129f, -0.99785892f},
+{0.052335956f, -0.99862953f}, {0.039259816f, -0.99922904f},
+{0.026176948f, -0.99965732f}, {0.013089596f, -0.99991433f},
+{6.1230318e-17f, -1.0000000f}, {-0.013089596f, -0.99991433f},
+{-0.026176948f, -0.99965732f}, {-0.039259816f, -0.99922904f},
+{-0.052335956f, -0.99862953f}, {-0.065403129f, -0.99785892f},
+{-0.078459096f, -0.99691733f}, {-0.091501619f, -0.99580493f},
+{-0.10452846f, -0.99452190f}, {-0.11753740f, -0.99306846f},
+{-0.13052619f, -0.99144486f}, {-0.14349262f, -0.98965139f},
+{-0.15643447f, -0.98768834f}, {-0.16934950f, -0.98555606f},
+{-0.18223553f, -0.98325491f}, {-0.19509032f, -0.98078528f},
+{-0.20791169f, -0.97814760f}, {-0.22069744f, -0.97534232f},
+{-0.23344536f, -0.97236992f}, {-0.24615329f, -0.96923091f},
+{-0.25881905f, -0.96592583f}, {-0.27144045f, -0.96245524f},
+{-0.28401534f, -0.95881973f}, {-0.29654157f, -0.95501994f},
+{-0.30901699f, -0.95105652f}, {-0.32143947f, -0.94693013f},
+{-0.33380686f, -0.94264149f}, {-0.34611706f, -0.93819134f},
+{-0.35836795f, -0.93358043f}, {-0.37055744f, -0.92880955f},
+{-0.38268343f, -0.92387953f}, {-0.39474386f, -0.91879121f},
+{-0.40673664f, -0.91354546f}, {-0.41865974f, -0.90814317f},
+{-0.43051110f, -0.90258528f}, {-0.44228869f, -0.89687274f},
+{-0.45399050f, -0.89100652f}, {-0.46561452f, -0.88498764f},
+{-0.47715876f, -0.87881711f}, {-0.48862124f, -0.87249601f},
+{-0.50000000f, -0.86602540f}, {-0.51129309f, -0.85940641f},
+{-0.52249856f, -0.85264016f}, {-0.53361452f, -0.84572782f},
+{-0.54463904f, -0.83867057f}, {-0.55557023f, -0.83146961f},
+{-0.56640624f, -0.82412619f}, {-0.57714519f, -0.81664156f},
+{-0.58778525f, -0.80901699f}, {-0.59832460f, -0.80125381f},
+{-0.60876143f, -0.79335334f}, {-0.61909395f, -0.78531693f},
+{-0.62932039f, -0.77714596f}, {-0.63943900f, -0.76884183f},
+{-0.64944805f, -0.76040597f}, {-0.65934582f, -0.75183981f},
+{-0.66913061f, -0.74314483f}, {-0.67880075f, -0.73432251f},
+{-0.68835458f, -0.72537437f}, {-0.69779046f, -0.71630194f},
+{-0.70710678f, -0.70710678f}, {-0.71630194f, -0.69779046f},
+{-0.72537437f, -0.68835458f}, {-0.73432251f, -0.67880075f},
+{-0.74314483f, -0.66913061f}, {-0.75183981f, -0.65934582f},
+{-0.76040597f, -0.64944805f}, {-0.76884183f, -0.63943900f},
+{-0.77714596f, -0.62932039f}, {-0.78531693f, -0.61909395f},
+{-0.79335334f, -0.60876143f}, {-0.80125381f, -0.59832460f},
+{-0.80901699f, -0.58778525f}, {-0.81664156f, -0.57714519f},
+{-0.82412619f, -0.56640624f}, {-0.83146961f, -0.55557023f},
+{-0.83867057f, -0.54463904f}, {-0.84572782f, -0.53361452f},
+{-0.85264016f, -0.52249856f}, {-0.85940641f, -0.51129309f},
+{-0.86602540f, -0.50000000f}, {-0.87249601f, -0.48862124f},
+{-0.87881711f, -0.47715876f}, {-0.88498764f, -0.46561452f},
+{-0.89100652f, -0.45399050f}, {-0.89687274f, -0.44228869f},
+{-0.90258528f, -0.43051110f}, {-0.90814317f, -0.41865974f},
+{-0.91354546f, -0.40673664f}, {-0.91879121f, -0.39474386f},
+{-0.92387953f, -0.38268343f}, {-0.92880955f, -0.37055744f},
+{-0.93358043f, -0.35836795f}, {-0.93819134f, -0.34611706f},
+{-0.94264149f, -0.33380686f}, {-0.94693013f, -0.32143947f},
+{-0.95105652f, -0.30901699f}, {-0.95501994f, -0.29654157f},
+{-0.95881973f, -0.28401534f}, {-0.96245524f, -0.27144045f},
+{-0.96592583f, -0.25881905f}, {-0.96923091f, -0.24615329f},
+{-0.97236992f, -0.23344536f}, {-0.97534232f, -0.22069744f},
+{-0.97814760f, -0.20791169f}, {-0.98078528f, -0.19509032f},
+{-0.98325491f, -0.18223553f}, {-0.98555606f, -0.16934950f},
+{-0.98768834f, -0.15643447f}, {-0.98965139f, -0.14349262f},
+{-0.99144486f, -0.13052619f}, {-0.99306846f, -0.11753740f},
+{-0.99452190f, -0.10452846f}, {-0.99580493f, -0.091501619f},
+{-0.99691733f, -0.078459096f}, {-0.99785892f, -0.065403129f},
+{-0.99862953f, -0.052335956f}, {-0.99922904f, -0.039259816f},
+{-0.99965732f, -0.026176948f}, {-0.99991433f, -0.013089596f},
+{-1.0000000f, -1.2246064e-16f}, {-0.99991433f, 0.013089596f},
+{-0.99965732f, 0.026176948f}, {-0.99922904f, 0.039259816f},
+{-0.99862953f, 0.052335956f}, {-0.99785892f, 0.065403129f},
+{-0.99691733f, 0.078459096f}, {-0.99580493f, 0.091501619f},
+{-0.99452190f, 0.10452846f}, {-0.99306846f, 0.11753740f},
+{-0.99144486f, 0.13052619f}, {-0.98965139f, 0.14349262f},
+{-0.98768834f, 0.15643447f}, {-0.98555606f, 0.16934950f},
+{-0.98325491f, 0.18223553f}, {-0.98078528f, 0.19509032f},
+{-0.97814760f, 0.20791169f}, {-0.97534232f, 0.22069744f},
+{-0.97236992f, 0.23344536f}, {-0.96923091f, 0.24615329f},
+{-0.96592583f, 0.25881905f}, {-0.96245524f, 0.27144045f},
+{-0.95881973f, 0.28401534f}, {-0.95501994f, 0.29654157f},
+{-0.95105652f, 0.30901699f}, {-0.94693013f, 0.32143947f},
+{-0.94264149f, 0.33380686f}, {-0.93819134f, 0.34611706f},
+{-0.93358043f, 0.35836795f}, {-0.92880955f, 0.37055744f},
+{-0.92387953f, 0.38268343f}, {-0.91879121f, 0.39474386f},
+{-0.91354546f, 0.40673664f}, {-0.90814317f, 0.41865974f},
+{-0.90258528f, 0.43051110f}, {-0.89687274f, 0.44228869f},
+{-0.89100652f, 0.45399050f}, {-0.88498764f, 0.46561452f},
+{-0.87881711f, 0.47715876f}, {-0.87249601f, 0.48862124f},
+{-0.86602540f, 0.50000000f}, {-0.85940641f, 0.51129309f},
+{-0.85264016f, 0.52249856f}, {-0.84572782f, 0.53361452f},
+{-0.83867057f, 0.54463904f}, {-0.83146961f, 0.55557023f},
+{-0.82412619f, 0.56640624f}, {-0.81664156f, 0.57714519f},
+{-0.80901699f, 0.58778525f}, {-0.80125381f, 0.59832460f},
+{-0.79335334f, 0.60876143f}, {-0.78531693f, 0.61909395f},
+{-0.77714596f, 0.62932039f}, {-0.76884183f, 0.63943900f},
+{-0.76040597f, 0.64944805f}, {-0.75183981f, 0.65934582f},
+{-0.74314483f, 0.66913061f}, {-0.73432251f, 0.67880075f},
+{-0.72537437f, 0.68835458f}, {-0.71630194f, 0.69779046f},
+{-0.70710678f, 0.70710678f}, {-0.69779046f, 0.71630194f},
+{-0.68835458f, 0.72537437f}, {-0.67880075f, 0.73432251f},
+{-0.66913061f, 0.74314483f}, {-0.65934582f, 0.75183981f},
+{-0.64944805f, 0.76040597f}, {-0.63943900f, 0.76884183f},
+{-0.62932039f, 0.77714596f}, {-0.61909395f, 0.78531693f},
+{-0.60876143f, 0.79335334f}, {-0.59832460f, 0.80125381f},
+{-0.58778525f, 0.80901699f}, {-0.57714519f, 0.81664156f},
+{-0.56640624f, 0.82412619f}, {-0.55557023f, 0.83146961f},
+{-0.54463904f, 0.83867057f}, {-0.53361452f, 0.84572782f},
+{-0.52249856f, 0.85264016f}, {-0.51129309f, 0.85940641f},
+{-0.50000000f, 0.86602540f}, {-0.48862124f, 0.87249601f},
+{-0.47715876f, 0.87881711f}, {-0.46561452f, 0.88498764f},
+{-0.45399050f, 0.89100652f}, {-0.44228869f, 0.89687274f},
+{-0.43051110f, 0.90258528f}, {-0.41865974f, 0.90814317f},
+{-0.40673664f, 0.91354546f}, {-0.39474386f, 0.91879121f},
+{-0.38268343f, 0.92387953f}, {-0.37055744f, 0.92880955f},
+{-0.35836795f, 0.93358043f}, {-0.34611706f, 0.93819134f},
+{-0.33380686f, 0.94264149f}, {-0.32143947f, 0.94693013f},
+{-0.30901699f, 0.95105652f}, {-0.29654157f, 0.95501994f},
+{-0.28401534f, 0.95881973f}, {-0.27144045f, 0.96245524f},
+{-0.25881905f, 0.96592583f}, {-0.24615329f, 0.96923091f},
+{-0.23344536f, 0.97236992f}, {-0.22069744f, 0.97534232f},
+{-0.20791169f, 0.97814760f}, {-0.19509032f, 0.98078528f},
+{-0.18223553f, 0.98325491f}, {-0.16934950f, 0.98555606f},
+{-0.15643447f, 0.98768834f}, {-0.14349262f, 0.98965139f},
+{-0.13052619f, 0.99144486f}, {-0.11753740f, 0.99306846f},
+{-0.10452846f, 0.99452190f}, {-0.091501619f, 0.99580493f},
+{-0.078459096f, 0.99691733f}, {-0.065403129f, 0.99785892f},
+{-0.052335956f, 0.99862953f}, {-0.039259816f, 0.99922904f},
+{-0.026176948f, 0.99965732f}, {-0.013089596f, 0.99991433f},
+{-1.8369095e-16f, 1.0000000f}, {0.013089596f, 0.99991433f},
+{0.026176948f, 0.99965732f}, {0.039259816f, 0.99922904f},
+{0.052335956f, 0.99862953f}, {0.065403129f, 0.99785892f},
+{0.078459096f, 0.99691733f}, {0.091501619f, 0.99580493f},
+{0.10452846f, 0.99452190f}, {0.11753740f, 0.99306846f},
+{0.13052619f, 0.99144486f}, {0.14349262f, 0.98965139f},
+{0.15643447f, 0.98768834f}, {0.16934950f, 0.98555606f},
+{0.18223553f, 0.98325491f}, {0.19509032f, 0.98078528f},
+{0.20791169f, 0.97814760f}, {0.22069744f, 0.97534232f},
+{0.23344536f, 0.97236992f}, {0.24615329f, 0.96923091f},
+{0.25881905f, 0.96592583f}, {0.27144045f, 0.96245524f},
+{0.28401534f, 0.95881973f}, {0.29654157f, 0.95501994f},
+{0.30901699f, 0.95105652f}, {0.32143947f, 0.94693013f},
+{0.33380686f, 0.94264149f}, {0.34611706f, 0.93819134f},
+{0.35836795f, 0.93358043f}, {0.37055744f, 0.92880955f},
+{0.38268343f, 0.92387953f}, {0.39474386f, 0.91879121f},
+{0.40673664f, 0.91354546f}, {0.41865974f, 0.90814317f},
+{0.43051110f, 0.90258528f}, {0.44228869f, 0.89687274f},
+{0.45399050f, 0.89100652f}, {0.46561452f, 0.88498764f},
+{0.47715876f, 0.87881711f}, {0.48862124f, 0.87249601f},
+{0.50000000f, 0.86602540f}, {0.51129309f, 0.85940641f},
+{0.52249856f, 0.85264016f}, {0.53361452f, 0.84572782f},
+{0.54463904f, 0.83867057f}, {0.55557023f, 0.83146961f},
+{0.56640624f, 0.82412619f}, {0.57714519f, 0.81664156f},
+{0.58778525f, 0.80901699f}, {0.59832460f, 0.80125381f},
+{0.60876143f, 0.79335334f}, {0.61909395f, 0.78531693f},
+{0.62932039f, 0.77714596f}, {0.63943900f, 0.76884183f},
+{0.64944805f, 0.76040597f}, {0.65934582f, 0.75183981f},
+{0.66913061f, 0.74314483f}, {0.67880075f, 0.73432251f},
+{0.68835458f, 0.72537437f}, {0.69779046f, 0.71630194f},
+{0.70710678f, 0.70710678f}, {0.71630194f, 0.69779046f},
+{0.72537437f, 0.68835458f}, {0.73432251f, 0.67880075f},
+{0.74314483f, 0.66913061f}, {0.75183981f, 0.65934582f},
+{0.76040597f, 0.64944805f}, {0.76884183f, 0.63943900f},
+{0.77714596f, 0.62932039f}, {0.78531693f, 0.61909395f},
+{0.79335334f, 0.60876143f}, {0.80125381f, 0.59832460f},
+{0.80901699f, 0.58778525f}, {0.81664156f, 0.57714519f},
+{0.82412619f, 0.56640624f}, {0.83146961f, 0.55557023f},
+{0.83867057f, 0.54463904f}, {0.84572782f, 0.53361452f},
+{0.85264016f, 0.52249856f}, {0.85940641f, 0.51129309f},
+{0.86602540f, 0.50000000f}, {0.87249601f, 0.48862124f},
+{0.87881711f, 0.47715876f}, {0.88498764f, 0.46561452f},
+{0.89100652f, 0.45399050f}, {0.89687274f, 0.44228869f},
+{0.90258528f, 0.43051110f}, {0.90814317f, 0.41865974f},
+{0.91354546f, 0.40673664f}, {0.91879121f, 0.39474386f},
+{0.92387953f, 0.38268343f}, {0.92880955f, 0.37055744f},
+{0.93358043f, 0.35836795f}, {0.93819134f, 0.34611706f},
+{0.94264149f, 0.33380686f}, {0.94693013f, 0.32143947f},
+{0.95105652f, 0.30901699f}, {0.95501994f, 0.29654157f},
+{0.95881973f, 0.28401534f}, {0.96245524f, 0.27144045f},
+{0.96592583f, 0.25881905f}, {0.96923091f, 0.24615329f},
+{0.97236992f, 0.23344536f}, {0.97534232f, 0.22069744f},
+{0.97814760f, 0.20791169f}, {0.98078528f, 0.19509032f},
+{0.98325491f, 0.18223553f}, {0.98555606f, 0.16934950f},
+{0.98768834f, 0.15643447f}, {0.98965139f, 0.14349262f},
+{0.99144486f, 0.13052619f}, {0.99306846f, 0.11753740f},
+{0.99452190f, 0.10452846f}, {0.99580493f, 0.091501619f},
+{0.99691733f, 0.078459096f}, {0.99785892f, 0.065403129f},
+{0.99862953f, 0.052335956f}, {0.99922904f, 0.039259816f},
+{0.99965732f, 0.026176948f}, {0.99991433f, 0.013089596f},
+};
+#ifndef FFT_BITREV480
+#define FFT_BITREV480
+static const opus_int16 fft_bitrev480[480] = {
+0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448,
+8, 104, 200, 296, 392, 40, 136, 232, 328, 424, 72, 168, 264, 360, 456,
+16, 112, 208, 304, 400, 48, 144, 240, 336, 432, 80, 176, 272, 368, 464,
+24, 120, 216, 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472,
+4, 100, 196, 292, 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452,
+12, 108, 204, 300, 396, 44, 140, 236, 332, 428, 76, 172, 268, 364, 460,
+20, 116, 212, 308, 404, 52, 148, 244, 340, 436, 84, 180, 276, 372, 468,
+28, 124, 220, 316, 412, 60, 156, 252, 348, 444, 92, 188, 284, 380, 476,
+1, 97, 193, 289, 385, 33, 129, 225, 321, 417, 65, 161, 257, 353, 449,
+9, 105, 201, 297, 393, 41, 137, 233, 329, 425, 73, 169, 265, 361, 457,
+17, 113, 209, 305, 401, 49, 145, 241, 337, 433, 81, 177, 273, 369, 465,
+25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, 185, 281, 377, 473,
+5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, 261, 357, 453,
+13, 109, 205, 301, 397, 45, 141, 237, 333, 429, 77, 173, 269, 365, 461,
+21, 117, 213, 309, 405, 53, 149, 245, 341, 437, 85, 181, 277, 373, 469,
+29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477,
+2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450,
+10, 106, 202, 298, 394, 42, 138, 234, 330, 426, 74, 170, 266, 362, 458,
+18, 114, 210, 306, 402, 50, 146, 242, 338, 434, 82, 178, 274, 370, 466,
+26, 122, 218, 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474,
+6, 102, 198, 294, 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454,
+14, 110, 206, 302, 398, 46, 142, 238, 334, 430, 78, 174, 270, 366, 462,
+22, 118, 214, 310, 406, 54, 150, 246, 342, 438, 86, 182, 278, 374, 470,
+30, 126, 222, 318, 414, 62, 158, 254, 350, 446, 94, 190, 286, 382, 478,
+3, 99, 195, 291, 387, 35, 131, 227, 323, 419, 67, 163, 259, 355, 451,
+11, 107, 203, 299, 395, 43, 139, 235, 331, 427, 75, 171, 267, 363, 459,
+19, 115, 211, 307, 403, 51, 147, 243, 339, 435, 83, 179, 275, 371, 467,
+27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, 187, 283, 379, 475,
+7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, 263, 359, 455,
+15, 111, 207, 303, 399, 47, 143, 239, 335, 431, 79, 175, 271, 367, 463,
+23, 119, 215, 311, 407, 55, 151, 247, 343, 439, 87, 183, 279, 375, 471,
+31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479,
+};
+#endif
+
+#ifndef FFT_BITREV240
+#define FFT_BITREV240
+static const opus_int16 fft_bitrev240[240] = {
+0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224,
+4, 52, 100, 148, 196, 20, 68, 116, 164, 212, 36, 84, 132, 180, 228,
+8, 56, 104, 152, 200, 24, 72, 120, 168, 216, 40, 88, 136, 184, 232,
+12, 60, 108, 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236,
+1, 49, 97, 145, 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225,
+5, 53, 101, 149, 197, 21, 69, 117, 165, 213, 37, 85, 133, 181, 229,
+9, 57, 105, 153, 201, 25, 73, 121, 169, 217, 41, 89, 137, 185, 233,
+13, 61, 109, 157, 205, 29, 77, 125, 173, 221, 45, 93, 141, 189, 237,
+2, 50, 98, 146, 194, 18, 66, 114, 162, 210, 34, 82, 130, 178, 226,
+6, 54, 102, 150, 198, 22, 70, 118, 166, 214, 38, 86, 134, 182, 230,
+10, 58, 106, 154, 202, 26, 74, 122, 170, 218, 42, 90, 138, 186, 234,
+14, 62, 110, 158, 206, 30, 78, 126, 174, 222, 46, 94, 142, 190, 238,
+3, 51, 99, 147, 195, 19, 67, 115, 163, 211, 35, 83, 131, 179, 227,
+7, 55, 103, 151, 199, 23, 71, 119, 167, 215, 39, 87, 135, 183, 231,
+11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, 235,
+15, 63, 111, 159, 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239,
+};
+#endif
+
+#ifndef FFT_BITREV120
+#define FFT_BITREV120
+static const opus_int16 fft_bitrev120[120] = {
+0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112,
+4, 28, 52, 76, 100, 12, 36, 60, 84, 108, 20, 44, 68, 92, 116,
+1, 25, 49, 73, 97, 9, 33, 57, 81, 105, 17, 41, 65, 89, 113,
+5, 29, 53, 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117,
+2, 26, 50, 74, 98, 10, 34, 58, 82, 106, 18, 42, 66, 90, 114,
+6, 30, 54, 78, 102, 14, 38, 62, 86, 110, 22, 46, 70, 94, 118,
+3, 27, 51, 75, 99, 11, 35, 59, 83, 107, 19, 43, 67, 91, 115,
+7, 31, 55, 79, 103, 15, 39, 63, 87, 111, 23, 47, 71, 95, 119,
+};
+#endif
+
+#ifndef FFT_BITREV60
+#define FFT_BITREV60
+static const opus_int16 fft_bitrev60[60] = {
+0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56,
+1, 13, 25, 37, 49, 5, 17, 29, 41, 53, 9, 21, 33, 45, 57,
+2, 14, 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58,
+3, 15, 27, 39, 51, 7, 19, 31, 43, 55, 11, 23, 35, 47, 59,
+};
+#endif
+
+#ifndef FFT_STATE48000_960_0
+#define FFT_STATE48000_960_0
+static const kiss_fft_state fft_state48000_960_0 = {
+480,    /* nfft */
+0.002083333f,   /* scale */
+-1,     /* shift */
+{5, 96, 3, 32, 4, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, },   /* factors */
+fft_bitrev480,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_480,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_1
+#define FFT_STATE48000_960_1
+static const kiss_fft_state fft_state48000_960_1 = {
+240,    /* nfft */
+0.004166667f,   /* scale */
+1,      /* shift */
+{5, 48, 3, 16, 4, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev240,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_240,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_2
+#define FFT_STATE48000_960_2
+static const kiss_fft_state fft_state48000_960_2 = {
+120,    /* nfft */
+0.008333333f,   /* scale */
+2,      /* shift */
+{5, 24, 3, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev120,  /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_120,
+#else
+NULL,
+#endif
+};
+#endif
+
+#ifndef FFT_STATE48000_960_3
+#define FFT_STATE48000_960_3
+static const kiss_fft_state fft_state48000_960_3 = {
+60,     /* nfft */
+0.016666667f,   /* scale */
+3,      /* shift */
+{5, 12, 3, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },    /* factors */
+fft_bitrev60,   /* bitrev */
+fft_twiddles48000_960,  /* bitrev */
+#ifdef OVERRIDE_FFT
+(arch_fft_state *)&cfg_arch_60,
+#else
+NULL,
+#endif
+};
+#endif
+
+#endif
+
+#ifndef MDCT_TWIDDLES960
+#define MDCT_TWIDDLES960
+static const opus_val16 mdct_twiddles960[1800] = {
+0.99999994f, 0.99999321f, 0.99997580f, 0.99994773f, 0.99990886f,
+0.99985933f, 0.99979913f, 0.99972820f, 0.99964654f, 0.99955416f,
+0.99945110f, 0.99933738f, 0.99921292f, 0.99907774f, 0.99893188f,
+0.99877530f, 0.99860805f, 0.99843007f, 0.99824142f, 0.99804211f,
+0.99783206f, 0.99761140f, 0.99737996f, 0.99713790f, 0.99688518f,
+0.99662173f, 0.99634761f, 0.99606287f, 0.99576741f, 0.99546129f,
+0.99514455f, 0.99481714f, 0.99447906f, 0.99413031f, 0.99377096f,
+0.99340093f, 0.99302030f, 0.99262899f, 0.99222708f, 0.99181455f,
+0.99139136f, 0.99095762f, 0.99051321f, 0.99005818f, 0.98959261f,
+0.98911643f, 0.98862964f, 0.98813224f, 0.98762429f, 0.98710573f,
+0.98657662f, 0.98603696f, 0.98548669f, 0.98492593f, 0.98435456f,
+0.98377270f, 0.98318028f, 0.98257732f, 0.98196387f, 0.98133987f,
+0.98070538f, 0.98006040f, 0.97940493f, 0.97873890f, 0.97806245f,
+0.97737551f, 0.97667813f, 0.97597027f, 0.97525197f, 0.97452319f,
+0.97378403f, 0.97303438f, 0.97227436f, 0.97150391f, 0.97072303f,
+0.96993178f, 0.96913016f, 0.96831810f, 0.96749574f, 0.96666300f,
+0.96581990f, 0.96496642f, 0.96410263f, 0.96322852f, 0.96234411f,
+0.96144938f, 0.96054435f, 0.95962906f, 0.95870346f, 0.95776761f,
+0.95682150f, 0.95586514f, 0.95489854f, 0.95392174f, 0.95293468f,
+0.95193744f, 0.95093000f, 0.94991243f, 0.94888461f, 0.94784665f,
+0.94679856f, 0.94574034f, 0.94467193f, 0.94359344f, 0.94250488f,
+0.94140619f, 0.94029742f, 0.93917859f, 0.93804967f, 0.93691075f,
+0.93576175f, 0.93460274f, 0.93343377f, 0.93225473f, 0.93106574f,
+0.92986679f, 0.92865789f, 0.92743903f, 0.92621022f, 0.92497152f,
+0.92372292f, 0.92246443f, 0.92119598f, 0.91991776f, 0.91862965f,
+0.91733170f, 0.91602397f, 0.91470635f, 0.91337901f, 0.91204184f,
+0.91069490f, 0.90933824f, 0.90797186f, 0.90659571f, 0.90520984f,
+0.90381432f, 0.90240908f, 0.90099424f, 0.89956969f, 0.89813554f,
+0.89669174f, 0.89523834f, 0.89377540f, 0.89230281f, 0.89082074f,
+0.88932908f, 0.88782793f, 0.88631725f, 0.88479710f, 0.88326746f,
+0.88172835f, 0.88017982f, 0.87862182f, 0.87705445f, 0.87547767f,
+0.87389153f, 0.87229604f, 0.87069118f, 0.86907703f, 0.86745358f,
+0.86582077f, 0.86417878f, 0.86252749f, 0.86086690f, 0.85919720f,
+0.85751826f, 0.85583007f, 0.85413277f, 0.85242635f, 0.85071075f,
+0.84898609f, 0.84725231f, 0.84550947f, 0.84375757f, 0.84199661f,
+0.84022665f, 0.83844769f, 0.83665979f, 0.83486289f, 0.83305705f,
+0.83124226f, 0.82941860f, 0.82758605f, 0.82574469f, 0.82389444f,
+0.82203537f, 0.82016748f, 0.81829083f, 0.81640542f, 0.81451124f,
+0.81260836f, 0.81069672f, 0.80877650f, 0.80684757f, 0.80490994f,
+0.80296379f, 0.80100900f, 0.79904562f, 0.79707366f, 0.79509324f,
+0.79310423f, 0.79110676f, 0.78910083f, 0.78708643f, 0.78506362f,
+0.78303236f, 0.78099275f, 0.77894479f, 0.77688843f, 0.77482378f,
+0.77275085f, 0.77066964f, 0.76858020f, 0.76648247f, 0.76437658f,
+0.76226246f, 0.76014024f, 0.75800985f, 0.75587130f, 0.75372469f,
+0.75157005f, 0.74940729f, 0.74723655f, 0.74505776f, 0.74287105f,
+0.74067634f, 0.73847371f, 0.73626316f, 0.73404479f, 0.73181850f,
+0.72958434f, 0.72734243f, 0.72509271f, 0.72283524f, 0.72057003f,
+0.71829706f, 0.71601641f, 0.71372813f, 0.71143216f, 0.70912862f,
+0.70681745f, 0.70449871f, 0.70217246f, 0.69983864f, 0.69749737f,
+0.69514859f, 0.69279242f, 0.69042879f, 0.68805778f, 0.68567938f,
+0.68329364f, 0.68090063f, 0.67850029f, 0.67609268f, 0.67367786f,
+0.67125577f, 0.66882652f, 0.66639012f, 0.66394657f, 0.66149592f,
+0.65903819f, 0.65657341f, 0.65410155f, 0.65162271f, 0.64913690f,
+0.64664418f, 0.64414448f, 0.64163786f, 0.63912445f, 0.63660413f,
+0.63407701f, 0.63154310f, 0.62900239f, 0.62645501f, 0.62390089f,
+0.62134010f, 0.61877263f, 0.61619854f, 0.61361790f, 0.61103064f,
+0.60843682f, 0.60583651f, 0.60322970f, 0.60061646f, 0.59799677f,
+0.59537065f, 0.59273821f, 0.59009939f, 0.58745426f, 0.58480281f,
+0.58214509f, 0.57948118f, 0.57681108f, 0.57413477f, 0.57145232f,
+0.56876373f, 0.56606907f, 0.56336832f, 0.56066155f, 0.55794877f,
+0.55523002f, 0.55250537f, 0.54977477f, 0.54703826f, 0.54429591f,
+0.54154772f, 0.53879374f, 0.53603399f, 0.53326851f, 0.53049731f,
+0.52772039f, 0.52493787f, 0.52214974f, 0.51935595f, 0.51655668f,
+0.51375180f, 0.51094145f, 0.50812566f, 0.50530440f, 0.50247771f,
+0.49964568f, 0.49680826f, 0.49396557f, 0.49111754f, 0.48826426f,
+0.48540577f, 0.48254207f, 0.47967321f, 0.47679919f, 0.47392011f,
+0.47103590f, 0.46814668f, 0.46525243f, 0.46235323f, 0.45944905f,
+0.45653993f, 0.45362595f, 0.45070711f, 0.44778344f, 0.44485497f,
+0.44192174f, 0.43898380f, 0.43604112f, 0.43309379f, 0.43014181f,
+0.42718524f, 0.42422408f, 0.42125839f, 0.41828820f, 0.41531351f,
+0.41233435f, 0.40935081f, 0.40636289f, 0.40337059f, 0.40037400f,
+0.39737311f, 0.39436796f, 0.39135858f, 0.38834500f, 0.38532731f,
+0.38230544f, 0.37927949f, 0.37624949f, 0.37321547f, 0.37017745f,
+0.36713544f, 0.36408952f, 0.36103970f, 0.35798600f, 0.35492846f,
+0.35186714f, 0.34880206f, 0.34573323f, 0.34266070f, 0.33958447f,
+0.33650464f, 0.33342120f, 0.33033419f, 0.32724363f, 0.32414958f,
+0.32105204f, 0.31795108f, 0.31484672f, 0.31173897f, 0.30862790f,
+0.30551350f, 0.30239585f, 0.29927495f, 0.29615086f, 0.29302359f,
+0.28989318f, 0.28675964f, 0.28362307f, 0.28048345f, 0.27734083f,
+0.27419522f, 0.27104670f, 0.26789525f, 0.26474094f, 0.26158381f,
+0.25842386f, 0.25526115f, 0.25209570f, 0.24892756f, 0.24575676f,
+0.24258332f, 0.23940729f, 0.23622867f, 0.23304754f, 0.22986393f,
+0.22667783f, 0.22348931f, 0.22029841f, 0.21710514f, 0.21390954f,
+0.21071166f, 0.20751151f, 0.20430915f, 0.20110460f, 0.19789790f,
+0.19468907f, 0.19147816f, 0.18826519f, 0.18505022f, 0.18183327f,
+0.17861435f, 0.17539354f, 0.17217083f, 0.16894630f, 0.16571994f,
+0.16249183f, 0.15926196f, 0.15603039f, 0.15279715f, 0.14956227f,
+0.14632578f, 0.14308774f, 0.13984816f, 0.13660708f, 0.13336454f,
+0.13012058f, 0.12687522f, 0.12362850f, 0.12038045f, 0.11713112f,
+0.11388054f, 0.11062872f, 0.10737573f, 0.10412160f, 0.10086634f,
+0.097609997f, 0.094352618f, 0.091094226f, 0.087834857f, 0.084574550f,
+0.081313334f, 0.078051247f, 0.074788325f, 0.071524605f, 0.068260118f,
+0.064994894f, 0.061728980f, 0.058462404f, 0.055195201f, 0.051927410f,
+0.048659060f, 0.045390189f, 0.042120833f, 0.038851023f, 0.035580799f,
+0.032310195f, 0.029039243f, 0.025767982f, 0.022496443f, 0.019224664f,
+0.015952680f, 0.012680525f, 0.0094082337f, 0.0061358409f, 0.0028633832f,
+-0.00040910527f, -0.0036815894f, -0.0069540343f, -0.010226404f, -0.013498665f,
+-0.016770782f, -0.020042717f, -0.023314439f, -0.026585912f, -0.029857099f,
+-0.033127967f, -0.036398482f, -0.039668605f, -0.042938303f, -0.046207540f,
+-0.049476285f, -0.052744497f, -0.056012146f, -0.059279196f, -0.062545612f,
+-0.065811358f, -0.069076397f, -0.072340697f, -0.075604223f, -0.078866936f,
+-0.082128808f, -0.085389800f, -0.088649876f, -0.091909006f, -0.095167145f,
+-0.098424271f, -0.10168034f, -0.10493532f, -0.10818918f, -0.11144188f,
+-0.11469338f, -0.11794366f, -0.12119267f, -0.12444039f, -0.12768677f,
+-0.13093179f, -0.13417540f, -0.13741758f, -0.14065829f, -0.14389749f,
+-0.14713514f, -0.15037122f, -0.15360570f, -0.15683852f, -0.16006967f,
+-0.16329910f, -0.16652679f, -0.16975269f, -0.17297678f, -0.17619900f,
+-0.17941935f, -0.18263777f, -0.18585424f, -0.18906870f, -0.19228116f,
+-0.19549155f, -0.19869985f, -0.20190603f, -0.20511003f, -0.20831184f,
+-0.21151142f, -0.21470875f, -0.21790376f, -0.22109644f, -0.22428675f,
+-0.22747467f, -0.23066014f, -0.23384315f, -0.23702365f, -0.24020162f,
+-0.24337701f, -0.24654980f, -0.24971995f, -0.25288740f, -0.25605217f,
+-0.25921419f, -0.26237345f, -0.26552987f, -0.26868346f, -0.27183419f,
+-0.27498198f, -0.27812684f, -0.28126872f, -0.28440759f, -0.28754342f,
+-0.29067615f, -0.29380578f, -0.29693225f, -0.30005556f, -0.30317566f,
+-0.30629250f, -0.30940607f, -0.31251630f, -0.31562322f, -0.31872672f,
+-0.32182685f, -0.32492352f, -0.32801670f, -0.33110636f, -0.33419248f,
+-0.33727503f, -0.34035397f, -0.34342924f, -0.34650084f, -0.34956875f,
+-0.35263291f, -0.35569328f, -0.35874987f, -0.36180258f, -0.36485144f,
+-0.36789638f, -0.37093741f, -0.37397444f, -0.37700745f, -0.38003644f,
+-0.38306138f, -0.38608220f, -0.38909888f, -0.39211139f, -0.39511973f,
+-0.39812380f, -0.40112361f, -0.40411916f, -0.40711036f, -0.41009718f,
+-0.41307965f, -0.41605768f, -0.41903123f, -0.42200032f, -0.42496487f,
+-0.42792490f, -0.43088034f, -0.43383113f, -0.43677729f, -0.43971881f,
+-0.44265559f, -0.44558764f, -0.44851488f, -0.45143735f, -0.45435500f,
+-0.45726776f, -0.46017563f, -0.46307856f, -0.46597654f, -0.46886954f,
+-0.47175750f, -0.47464043f, -0.47751826f, -0.48039100f, -0.48325855f,
+-0.48612097f, -0.48897815f, -0.49183011f, -0.49467680f, -0.49751821f,
+-0.50035429f, -0.50318497f, -0.50601029f, -0.50883019f, -0.51164466f,
+-0.51445359f, -0.51725709f, -0.52005500f, -0.52284735f, -0.52563411f,
+-0.52841520f, -0.53119069f, -0.53396046f, -0.53672451f, -0.53948283f,
+-0.54223537f, -0.54498214f, -0.54772300f, -0.55045801f, -0.55318713f,
+-0.55591035f, -0.55862761f, -0.56133890f, -0.56404412f, -0.56674337f,
+-0.56943649f, -0.57212353f, -0.57480448f, -0.57747924f, -0.58014780f,
+-0.58281022f, -0.58546633f, -0.58811617f, -0.59075975f, -0.59339696f,
+-0.59602785f, -0.59865236f, -0.60127044f, -0.60388207f, -0.60648727f,
+-0.60908598f, -0.61167812f, -0.61426371f, -0.61684275f, -0.61941516f,
+-0.62198097f, -0.62454009f, -0.62709254f, -0.62963831f, -0.63217729f,
+-0.63470948f, -0.63723493f, -0.63975352f, -0.64226526f, -0.64477009f,
+-0.64726806f, -0.64975911f, -0.65224314f, -0.65472025f, -0.65719032f,
+-0.65965337f, -0.66210932f, -0.66455823f, -0.66700000f, -0.66943461f,
+-0.67186207f, -0.67428231f, -0.67669535f, -0.67910111f, -0.68149966f,
+-0.68389088f, -0.68627477f, -0.68865126f, -0.69102043f, -0.69338220f,
+-0.69573659f, -0.69808346f, -0.70042288f, -0.70275480f, -0.70507920f,
+-0.70739603f, -0.70970529f, -0.71200693f, -0.71430099f, -0.71658736f,
+-0.71886611f, -0.72113711f, -0.72340041f, -0.72565591f, -0.72790372f,
+-0.73014367f, -0.73237586f, -0.73460019f, -0.73681659f, -0.73902518f,
+-0.74122584f, -0.74341851f, -0.74560326f, -0.74778003f, -0.74994880f,
+-0.75210953f, -0.75426215f, -0.75640678f, -0.75854325f, -0.76067162f,
+-0.76279181f, -0.76490390f, -0.76700771f, -0.76910341f, -0.77119076f,
+-0.77326995f, -0.77534080f, -0.77740335f, -0.77945763f, -0.78150350f,
+-0.78354102f, -0.78557014f, -0.78759086f, -0.78960317f, -0.79160696f,
+-0.79360235f, -0.79558921f, -0.79756755f, -0.79953730f, -0.80149853f,
+-0.80345118f, -0.80539525f, -0.80733067f, -0.80925739f, -0.81117553f,
+-0.81308490f, -0.81498563f, -0.81687760f, -0.81876087f, -0.82063532f,
+-0.82250100f, -0.82435787f, -0.82620591f, -0.82804507f, -0.82987541f,
+-0.83169687f, -0.83350939f, -0.83531296f, -0.83710766f, -0.83889335f,
+-0.84067005f, -0.84243774f, -0.84419644f, -0.84594607f, -0.84768665f,
+-0.84941816f, -0.85114056f, -0.85285389f, -0.85455805f, -0.85625303f,
+-0.85793889f, -0.85961550f, -0.86128294f, -0.86294121f, -0.86459017f,
+-0.86622989f, -0.86786032f, -0.86948150f, -0.87109333f, -0.87269586f,
+-0.87428904f, -0.87587279f, -0.87744725f, -0.87901229f, -0.88056785f,
+-0.88211405f, -0.88365078f, -0.88517809f, -0.88669586f, -0.88820416f,
+-0.88970292f, -0.89119220f, -0.89267188f, -0.89414203f, -0.89560264f,
+-0.89705360f, -0.89849502f, -0.89992678f, -0.90134889f, -0.90276134f,
+-0.90416414f, -0.90555727f, -0.90694070f, -0.90831441f, -0.90967834f,
+-0.91103262f, -0.91237706f, -0.91371179f, -0.91503674f, -0.91635185f,
+-0.91765714f, -0.91895264f, -0.92023826f, -0.92151409f, -0.92277998f,
+-0.92403603f, -0.92528218f, -0.92651838f, -0.92774469f, -0.92896110f,
+-0.93016750f, -0.93136400f, -0.93255049f, -0.93372697f, -0.93489349f,
+-0.93604994f, -0.93719643f, -0.93833286f, -0.93945926f, -0.94057560f,
+-0.94168180f, -0.94277799f, -0.94386405f, -0.94494003f, -0.94600588f,
+-0.94706154f, -0.94810712f, -0.94914252f, -0.95016778f, -0.95118284f,
+-0.95218778f, -0.95318246f, -0.95416695f, -0.95514119f, -0.95610523f,
+-0.95705903f, -0.95800257f, -0.95893586f, -0.95985889f, -0.96077162f,
+-0.96167403f, -0.96256620f, -0.96344805f, -0.96431959f, -0.96518075f,
+-0.96603161f, -0.96687216f, -0.96770233f, -0.96852213f, -0.96933156f,
+-0.97013056f, -0.97091925f, -0.97169751f, -0.97246534f, -0.97322279f,
+-0.97396982f, -0.97470641f, -0.97543252f, -0.97614825f, -0.97685349f,
+-0.97754824f, -0.97823256f, -0.97890645f, -0.97956979f, -0.98022264f,
+-0.98086500f, -0.98149687f, -0.98211825f, -0.98272908f, -0.98332942f,
+-0.98391914f, -0.98449844f, -0.98506713f, -0.98562527f, -0.98617285f,
+-0.98670989f, -0.98723638f, -0.98775226f, -0.98825759f, -0.98875231f,
+-0.98923647f, -0.98971003f, -0.99017298f, -0.99062532f, -0.99106705f,
+-0.99149817f, -0.99191868f, -0.99232858f, -0.99272782f, -0.99311644f,
+-0.99349445f, -0.99386179f, -0.99421853f, -0.99456459f, -0.99489999f,
+-0.99522477f, -0.99553883f, -0.99584228f, -0.99613506f, -0.99641716f,
+-0.99668860f, -0.99694937f, -0.99719942f, -0.99743885f, -0.99766755f,
+-0.99788558f, -0.99809295f, -0.99828959f, -0.99847561f, -0.99865085f,
+-0.99881548f, -0.99896932f, -0.99911255f, -0.99924499f, -0.99936682f,
+-0.99947786f, -0.99957830f, -0.99966794f, -0.99974692f, -0.99981517f,
+-0.99987274f, -0.99991959f, -0.99995571f, -0.99998116f, -0.99999589f,
+0.99999964f, 0.99997288f, 0.99990326f, 0.99979085f, 0.99963558f,
+0.99943751f, 0.99919659f, 0.99891287f, 0.99858636f, 0.99821711f,
+0.99780506f, 0.99735034f, 0.99685282f, 0.99631262f, 0.99572974f,
+0.99510419f, 0.99443603f, 0.99372530f, 0.99297196f, 0.99217612f,
+0.99133772f, 0.99045694f, 0.98953366f, 0.98856801f, 0.98756003f,
+0.98650974f, 0.98541719f, 0.98428243f, 0.98310548f, 0.98188645f,
+0.98062533f, 0.97932225f, 0.97797716f, 0.97659022f, 0.97516143f,
+0.97369087f, 0.97217858f, 0.97062469f, 0.96902919f, 0.96739221f,
+0.96571374f, 0.96399397f, 0.96223283f, 0.96043050f, 0.95858705f,
+0.95670253f, 0.95477700f, 0.95281059f, 0.95080340f, 0.94875544f,
+0.94666684f, 0.94453770f, 0.94236809f, 0.94015813f, 0.93790787f,
+0.93561745f, 0.93328691f, 0.93091643f, 0.92850608f, 0.92605597f,
+0.92356616f, 0.92103678f, 0.91846794f, 0.91585976f, 0.91321236f,
+0.91052586f, 0.90780038f, 0.90503591f, 0.90223277f, 0.89939094f,
+0.89651060f, 0.89359182f, 0.89063478f, 0.88763964f, 0.88460642f,
+0.88153529f, 0.87842643f, 0.87527996f, 0.87209594f, 0.86887461f,
+0.86561602f, 0.86232042f, 0.85898781f, 0.85561842f, 0.85221243f,
+0.84876984f, 0.84529096f, 0.84177583f, 0.83822471f, 0.83463764f,
+0.83101481f, 0.82735640f, 0.82366252f, 0.81993335f, 0.81616908f,
+0.81236988f, 0.80853581f, 0.80466717f, 0.80076402f, 0.79682660f,
+0.79285502f, 0.78884947f, 0.78481019f, 0.78073722f, 0.77663082f,
+0.77249116f, 0.76831841f, 0.76411277f, 0.75987434f, 0.75560343f,
+0.75130010f, 0.74696463f, 0.74259710f, 0.73819780f, 0.73376691f,
+0.72930455f, 0.72481096f, 0.72028631f, 0.71573079f, 0.71114463f,
+0.70652801f, 0.70188117f, 0.69720417f, 0.69249737f, 0.68776089f,
+0.68299496f, 0.67819971f, 0.67337549f, 0.66852236f, 0.66364062f,
+0.65873051f, 0.65379208f, 0.64882571f, 0.64383155f, 0.63880974f,
+0.63376063f, 0.62868434f, 0.62358117f, 0.61845124f, 0.61329484f,
+0.60811216f, 0.60290343f, 0.59766883f, 0.59240872f, 0.58712316f,
+0.58181250f, 0.57647687f, 0.57111657f, 0.56573176f, 0.56032276f,
+0.55488980f, 0.54943299f, 0.54395270f, 0.53844911f, 0.53292239f,
+0.52737290f, 0.52180082f, 0.51620632f, 0.51058978f, 0.50495136f,
+0.49929130f, 0.49360985f, 0.48790723f, 0.48218375f, 0.47643960f,
+0.47067502f, 0.46489030f, 0.45908567f, 0.45326138f, 0.44741765f,
+0.44155475f, 0.43567297f, 0.42977250f, 0.42385364f, 0.41791660f,
+0.41196167f, 0.40598908f, 0.39999911f, 0.39399201f, 0.38796803f,
+0.38192743f, 0.37587047f, 0.36979741f, 0.36370850f, 0.35760403f,
+0.35148421f, 0.34534934f, 0.33919969f, 0.33303553f, 0.32685706f,
+0.32066461f, 0.31445843f, 0.30823877f, 0.30200592f, 0.29576012f,
+0.28950164f, 0.28323078f, 0.27694780f, 0.27065292f, 0.26434645f,
+0.25802869f, 0.25169984f, 0.24536023f, 0.23901010f, 0.23264973f,
+0.22627939f, 0.21989937f, 0.21350993f, 0.20711134f, 0.20070387f,
+0.19428782f, 0.18786344f, 0.18143101f, 0.17499080f, 0.16854310f,
+0.16208819f, 0.15562633f, 0.14915779f, 0.14268288f, 0.13620184f,
+0.12971498f, 0.12322257f, 0.11672486f, 0.11022217f, 0.10371475f,
+0.097202882f, 0.090686858f, 0.084166944f, 0.077643424f, 0.071116582f,
+0.064586692f, 0.058054037f, 0.051518895f, 0.044981543f, 0.038442269f,
+0.031901345f, 0.025359053f, 0.018815678f, 0.012271495f, 0.0057267868f,
+-0.00081816671f, -0.0073630852f, -0.013907688f, -0.020451695f, -0.026994826f,
+-0.033536803f, -0.040077340f, -0.046616159f, -0.053152986f, -0.059687532f,
+-0.066219524f, -0.072748676f, -0.079274714f, -0.085797355f, -0.092316322f,
+-0.098831341f, -0.10534211f, -0.11184838f, -0.11834986f, -0.12484626f,
+-0.13133731f, -0.13782275f, -0.14430228f, -0.15077563f, -0.15724251f,
+-0.16370267f, -0.17015581f, -0.17660165f, -0.18303993f, -0.18947038f,
+-0.19589271f, -0.20230664f, -0.20871192f, -0.21510825f, -0.22149536f,
+-0.22787298f, -0.23424086f, -0.24059868f, -0.24694622f, -0.25328314f,
+-0.25960925f, -0.26592422f, -0.27222782f, -0.27851975f, -0.28479972f,
+-0.29106751f, -0.29732284f, -0.30356544f, -0.30979502f, -0.31601134f,
+-0.32221413f, -0.32840309f, -0.33457801f, -0.34073856f, -0.34688455f,
+-0.35301566f, -0.35913166f, -0.36523229f, -0.37131724f, -0.37738630f,
+-0.38343921f, -0.38947567f, -0.39549544f, -0.40149832f, -0.40748394f,
+-0.41345215f, -0.41940263f, -0.42533514f, -0.43124944f, -0.43714526f,
+-0.44302234f, -0.44888046f, -0.45471936f, -0.46053877f, -0.46633846f,
+-0.47211814f, -0.47787762f, -0.48361665f, -0.48933494f, -0.49503228f,
+-0.50070840f, -0.50636309f, -0.51199609f, -0.51760709f, -0.52319598f,
+-0.52876246f, -0.53430629f, -0.53982723f, -0.54532504f, -0.55079949f,
+-0.55625033f, -0.56167740f, -0.56708032f, -0.57245898f, -0.57781315f,
+-0.58314258f, -0.58844697f, -0.59372622f, -0.59897995f, -0.60420811f,
+-0.60941035f, -0.61458647f, -0.61973625f, -0.62485951f, -0.62995601f,
+-0.63502556f, -0.64006782f, -0.64508271f, -0.65007001f, -0.65502942f,
+-0.65996075f, -0.66486382f, -0.66973841f, -0.67458433f, -0.67940134f,
+-0.68418926f, -0.68894786f, -0.69367695f, -0.69837630f, -0.70304573f,
+-0.70768511f, -0.71229410f, -0.71687263f, -0.72142041f, -0.72593731f,
+-0.73042315f, -0.73487765f, -0.73930067f, -0.74369204f, -0.74805158f,
+-0.75237900f, -0.75667429f, -0.76093709f, -0.76516730f, -0.76936477f,
+-0.77352923f, -0.77766061f, -0.78175867f, -0.78582323f, -0.78985411f,
+-0.79385114f, -0.79781419f, -0.80174309f, -0.80563760f, -0.80949765f,
+-0.81332302f, -0.81711352f, -0.82086903f, -0.82458937f, -0.82827437f,
+-0.83192390f, -0.83553779f, -0.83911592f, -0.84265804f, -0.84616417f,
+-0.84963393f, -0.85306740f, -0.85646427f, -0.85982448f, -0.86314780f,
+-0.86643422f, -0.86968350f, -0.87289548f, -0.87607014f, -0.87920725f,
+-0.88230664f, -0.88536829f, -0.88839203f, -0.89137769f, -0.89432514f,
+-0.89723432f, -0.90010506f, -0.90293723f, -0.90573072f, -0.90848541f,
+-0.91120118f, -0.91387796f, -0.91651553f, -0.91911387f, -0.92167282f,
+-0.92419231f, -0.92667222f, -0.92911243f, -0.93151283f, -0.93387336f,
+-0.93619382f, -0.93847424f, -0.94071442f, -0.94291431f, -0.94507378f,
+-0.94719279f, -0.94927126f, -0.95130903f, -0.95330608f, -0.95526224f,
+-0.95717752f, -0.95905179f, -0.96088499f, -0.96267700f, -0.96442777f,
+-0.96613729f, -0.96780539f, -0.96943200f, -0.97101706f, -0.97256058f,
+-0.97406244f, -0.97552258f, -0.97694093f, -0.97831738f, -0.97965199f,
+-0.98094457f, -0.98219514f, -0.98340368f, -0.98457009f, -0.98569429f,
+-0.98677629f, -0.98781598f, -0.98881340f, -0.98976845f, -0.99068111f,
+-0.99155134f, -0.99237907f, -0.99316430f, -0.99390697f, -0.99460709f,
+-0.99526459f, -0.99587947f, -0.99645168f, -0.99698120f, -0.99746799f,
+-0.99791211f, -0.99831343f, -0.99867201f, -0.99898779f, -0.99926084f,
+-0.99949104f, -0.99967843f, -0.99982297f, -0.99992472f, -0.99998361f,
+0.99999869f, 0.99989158f, 0.99961317f, 0.99916345f, 0.99854255f,
+0.99775058f, 0.99678761f, 0.99565387f, 0.99434954f, 0.99287480f,
+0.99122995f, 0.98941529f, 0.98743105f, 0.98527765f, 0.98295540f,
+0.98046476f, 0.97780609f, 0.97497988f, 0.97198665f, 0.96882683f,
+0.96550101f, 0.96200979f, 0.95835376f, 0.95453346f, 0.95054960f,
+0.94640291f, 0.94209403f, 0.93762374f, 0.93299282f, 0.92820197f,
+0.92325211f, 0.91814411f, 0.91287869f, 0.90745693f, 0.90187967f,
+0.89614785f, 0.89026248f, 0.88422459f, 0.87803519f, 0.87169534f,
+0.86520612f, 0.85856867f, 0.85178405f, 0.84485358f, 0.83777827f,
+0.83055943f, 0.82319832f, 0.81569612f, 0.80805415f, 0.80027372f,
+0.79235619f, 0.78430289f, 0.77611518f, 0.76779449f, 0.75934225f,
+0.75075996f, 0.74204898f, 0.73321080f, 0.72424710f, 0.71515924f,
+0.70594883f, 0.69661748f, 0.68716675f, 0.67759830f, 0.66791373f,
+0.65811473f, 0.64820296f, 0.63818014f, 0.62804794f, 0.61780810f,
+0.60746247f, 0.59701276f, 0.58646071f, 0.57580817f, 0.56505698f,
+0.55420899f, 0.54326600f, 0.53222996f, 0.52110273f, 0.50988621f,
+0.49858227f, 0.48719296f, 0.47572014f, 0.46416581f, 0.45253196f,
+0.44082057f, 0.42903364f, 0.41717321f, 0.40524128f, 0.39323992f,
+0.38117120f, 0.36903715f, 0.35683987f, 0.34458145f, 0.33226398f,
+0.31988961f, 0.30746040f, 0.29497850f, 0.28244606f, 0.26986524f,
+0.25723818f, 0.24456702f, 0.23185398f, 0.21910121f, 0.20631088f,
+0.19348522f, 0.18062639f, 0.16773662f, 0.15481812f, 0.14187308f,
+0.12890373f, 0.11591230f, 0.10290100f, 0.089872077f, 0.076827750f,
+0.063770257f, 0.050701842f, 0.037624735f, 0.024541186f, 0.011453429f,
+-0.0016362892f, -0.014725727f, -0.027812643f, -0.040894791f, -0.053969935f,
+-0.067035832f, -0.080090240f, -0.093130924f, -0.10615565f, -0.11916219f,
+-0.13214831f, -0.14511178f, -0.15805040f, -0.17096193f, -0.18384418f,
+-0.19669491f, -0.20951195f, -0.22229309f, -0.23503613f, -0.24773891f,
+-0.26039925f, -0.27301496f, -0.28558388f, -0.29810387f, -0.31057280f,
+-0.32298848f, -0.33534884f, -0.34765175f, -0.35989508f, -0.37207675f,
+-0.38419467f, -0.39624676f, -0.40823093f, -0.42014518f, -0.43198743f,
+-0.44375566f, -0.45544785f, -0.46706200f, -0.47859612f, -0.49004826f,
+-0.50141639f, -0.51269865f, -0.52389306f, -0.53499764f, -0.54601061f,
+-0.55693001f, -0.56775403f, -0.57848072f, -0.58910829f, -0.59963489f,
+-0.61005878f, -0.62037814f, -0.63059121f, -0.64069623f, -0.65069145f,
+-0.66057515f, -0.67034572f, -0.68000144f, -0.68954057f, -0.69896162f,
+-0.70826286f, -0.71744281f, -0.72649974f, -0.73543227f, -0.74423873f,
+-0.75291771f, -0.76146764f, -0.76988715f, -0.77817470f, -0.78632891f,
+-0.79434842f, -0.80223179f, -0.80997771f, -0.81758487f, -0.82505190f,
+-0.83237761f, -0.83956063f, -0.84659988f, -0.85349399f, -0.86024189f,
+-0.86684239f, -0.87329435f, -0.87959671f, -0.88574833f, -0.89174819f,
+-0.89759529f, -0.90328854f, -0.90882701f, -0.91420978f, -0.91943592f,
+-0.92450452f, -0.92941469f, -0.93416560f, -0.93875647f, -0.94318646f,
+-0.94745487f, -0.95156091f, -0.95550388f, -0.95928317f, -0.96289814f,
+-0.96634805f, -0.96963239f, -0.97275060f, -0.97570217f, -0.97848648f,
+-0.98110318f, -0.98355180f, -0.98583186f, -0.98794299f, -0.98988485f,
+-0.99165714f, -0.99325943f, -0.99469161f, -0.99595332f, -0.99704438f,
+-0.99796462f, -0.99871385f, -0.99929196f, -0.99969882f, -0.99993443f,
+0.99999464f, 0.99956632f, 0.99845290f, 0.99665523f, 0.99417448f,
+0.99101239f, 0.98717111f, 0.98265326f, 0.97746199f, 0.97160077f,
+0.96507365f, 0.95788515f, 0.95004016f, 0.94154406f, 0.93240267f,
+0.92262226f, 0.91220951f, 0.90117162f, 0.88951606f, 0.87725091f,
+0.86438453f, 0.85092574f, 0.83688372f, 0.82226819f, 0.80708915f,
+0.79135692f, 0.77508235f, 0.75827658f, 0.74095112f, 0.72311783f,
+0.70478898f, 0.68597710f, 0.66669506f, 0.64695615f, 0.62677377f,
+0.60616189f, 0.58513457f, 0.56370622f, 0.54189157f, 0.51970547f,
+0.49716324f, 0.47428027f, 0.45107225f, 0.42755505f, 0.40374488f,
+0.37965798f, 0.35531086f, 0.33072025f, 0.30590299f, 0.28087607f,
+0.25565663f, 0.23026201f, 0.20470956f, 0.17901683f, 0.15320139f,
+0.12728097f, 0.10127331f, 0.075196236f, 0.049067631f, 0.022905400f,
+-0.0032725304f, -0.029448219f, -0.055603724f, -0.081721120f, -0.10778251f,
+-0.13377003f, -0.15966587f, -0.18545228f, -0.21111161f, -0.23662624f,
+-0.26197869f, -0.28715160f, -0.31212771f, -0.33688989f, -0.36142120f,
+-0.38570482f, -0.40972409f, -0.43346253f, -0.45690393f, -0.48003218f,
+-0.50283146f, -0.52528608f, -0.54738069f, -0.56910020f, -0.59042966f,
+-0.61135447f, -0.63186026f, -0.65193301f, -0.67155898f, -0.69072473f,
+-0.70941705f, -0.72762316f, -0.74533063f, -0.76252723f, -0.77920127f,
+-0.79534131f, -0.81093621f, -0.82597536f, -0.84044844f, -0.85434550f,
+-0.86765707f, -0.88037395f, -0.89248747f, -0.90398932f, -0.91487163f,
+-0.92512697f, -0.93474823f, -0.94372886f, -0.95206273f, -0.95974404f,
+-0.96676767f, -0.97312868f, -0.97882277f, -0.98384601f, -0.98819500f,
+-0.99186671f, -0.99485862f, -0.99716878f, -0.99879545f, -0.99973762f,
+};
+#endif
+
+static const CELTMode mode48000_960_120 = {
+48000,  /* Fs */
+120,    /* overlap */
+21,     /* nbEBands */
+21,     /* effEBands */
+{0.85000610f, 0.0000000f, 1.0000000f, 1.0000000f, },    /* preemph */
+eband5ms,       /* eBands */
+3,      /* maxLM */
+8,      /* nbShortMdcts */
+120,    /* shortMdctSize */
+11,     /* nbAllocVectors */
+band_allocation,        /* allocVectors */
+logN400,        /* logN */
+window120,      /* window */
+{1920, 3, {&fft_state48000_960_0, &fft_state48000_960_1, &fft_state48000_960_2, &fft_state48000_960_3, }, mdct_twiddles960},    /* mdct */
+{392, cache_index50, cache_bits50, cache_caps50},       /* cache */
+};
+
+/* List of all the available modes */
+#define TOTAL_MODES 1
+static const CELTMode * const static_mode_list[TOTAL_MODES] = {
+&mode48000_960_120,
+};
diff --git a/opus/celt/static_modes_float_arm_ne10.h b/opus/celt/static_modes_float_arm_ne10.h
new file mode 100644 (file)
index 0000000..66e1abb
--- /dev/null
@@ -0,0 +1,404 @@
+/* The contents of this file was automatically generated by
+ * dump_mode_arm_ne10.c with arguments: 48000 960
+ * It contains static definitions for some pre-defined modes. */
+#include <NE10_types.h>
+
+#ifndef NE10_FFT_PARAMS48000_960
+#define NE10_FFT_PARAMS48000_960
+static const ne10_int32_t ne10_factors_480[64] = {
+4, 40, 4, 30, 2, 15, 5, 3, 3, 1, 1, 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, 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, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_240[64] = {
+3, 20, 4, 15, 5, 3, 3, 1, 1, 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, 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, 0,
+0, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_120[64] = {
+3, 10, 2, 15, 5, 3, 3, 1, 1, 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, 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, 0,
+0, 0, 0, 0, };
+static const ne10_int32_t ne10_factors_60[64] = {
+2, 5, 5, 3, 3, 1, 1, 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, 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, 0, 0, 0,
+0, 0, 0, 0, };
+static const ne10_fft_cpx_float32_t ne10_twiddles_480[480] = {
+{1.0000000f,0.0000000f}, {1.0000000f,-0.0000000f}, {1.0000000f,-0.0000000f},
+{1.0000000f,-0.0000000f}, {0.91354543f,-0.40673664f}, {0.66913056f,-0.74314487f},
+{1.0000000f,-0.0000000f}, {0.66913056f,-0.74314487f}, {-0.10452851f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.30901697f,-0.95105654f}, {-0.80901700f,-0.58778518f},
+{1.0000000f,-0.0000000f}, {-0.10452851f,-0.99452192f}, {-0.97814757f,0.20791179f},
+{1.0000000f,-0.0000000f}, {0.97814763f,-0.20791170f}, {0.91354543f,-0.40673664f},
+{0.80901700f,-0.58778524f}, {0.66913056f,-0.74314487f}, {0.49999997f,-0.86602545f},
+{0.30901697f,-0.95105654f}, {0.10452842f,-0.99452192f}, {-0.10452851f,-0.99452192f},
+{-0.30901703f,-0.95105648f}, {-0.50000006f,-0.86602533f}, {-0.66913068f,-0.74314475f},
+{-0.80901700f,-0.58778518f}, {-0.91354549f,-0.40673658f}, {-0.97814763f,-0.20791161f},
+{1.0000000f,-0.0000000f}, {0.99862951f,-0.052335959f}, {0.99452192f,-0.10452846f},
+{0.98768836f,-0.15643448f}, {0.97814763f,-0.20791170f}, {0.96592581f,-0.25881904f},
+{0.95105648f,-0.30901700f}, {0.93358040f,-0.35836795f}, {0.91354543f,-0.40673664f},
+{0.89100653f,-0.45399052f}, {0.86602545f,-0.50000000f}, {0.83867055f,-0.54463905f},
+{0.80901700f,-0.58778524f}, {0.77714598f,-0.62932038f}, {0.74314475f,-0.66913062f},
+{0.70710677f,-0.70710683f}, {0.66913056f,-0.74314487f}, {0.62932038f,-0.77714598f},
+{0.58778524f,-0.80901700f}, {0.54463899f,-0.83867055f}, {0.49999997f,-0.86602545f},
+{0.45399052f,-0.89100653f}, {0.40673661f,-0.91354549f}, {0.35836786f,-0.93358046f},
+{0.30901697f,-0.95105654f}, {0.25881907f,-0.96592581f}, {0.20791166f,-0.97814763f},
+{0.15643437f,-0.98768836f}, {0.10452842f,-0.99452192f}, {0.052335974f,-0.99862951f},
+{1.0000000f,-0.0000000f}, {0.99452192f,-0.10452846f}, {0.97814763f,-0.20791170f},
+{0.95105648f,-0.30901700f}, {0.91354543f,-0.40673664f}, {0.86602545f,-0.50000000f},
+{0.80901700f,-0.58778524f}, {0.74314475f,-0.66913062f}, {0.66913056f,-0.74314487f},
+{0.58778524f,-0.80901700f}, {0.49999997f,-0.86602545f}, {0.40673661f,-0.91354549f},
+{0.30901697f,-0.95105654f}, {0.20791166f,-0.97814763f}, {0.10452842f,-0.99452192f},
+{-4.3711388e-08f,-1.0000000f}, {-0.10452851f,-0.99452192f}, {-0.20791174f,-0.97814757f},
+{-0.30901703f,-0.95105648f}, {-0.40673670f,-0.91354543f}, {-0.50000006f,-0.86602533f},
+{-0.58778518f,-0.80901700f}, {-0.66913068f,-0.74314475f}, {-0.74314493f,-0.66913044f},
+{-0.80901700f,-0.58778518f}, {-0.86602539f,-0.50000006f}, {-0.91354549f,-0.40673658f},
+{-0.95105654f,-0.30901679f}, {-0.97814763f,-0.20791161f}, {-0.99452192f,-0.10452849f},
+{1.0000000f,-0.0000000f}, {0.98768836f,-0.15643448f}, {0.95105648f,-0.30901700f},
+{0.89100653f,-0.45399052f}, {0.80901700f,-0.58778524f}, {0.70710677f,-0.70710683f},
+{0.58778524f,-0.80901700f}, {0.45399052f,-0.89100653f}, {0.30901697f,-0.95105654f},
+{0.15643437f,-0.98768836f}, {-4.3711388e-08f,-1.0000000f}, {-0.15643445f,-0.98768836f},
+{-0.30901703f,-0.95105648f}, {-0.45399061f,-0.89100647f}, {-0.58778518f,-0.80901700f},
+{-0.70710677f,-0.70710677f}, {-0.80901700f,-0.58778518f}, {-0.89100659f,-0.45399037f},
+{-0.95105654f,-0.30901679f}, {-0.98768836f,-0.15643445f}, {-1.0000000f,8.7422777e-08f},
+{-0.98768830f,0.15643461f}, {-0.95105654f,0.30901697f}, {-0.89100653f,0.45399055f},
+{-0.80901694f,0.58778536f}, {-0.70710665f,0.70710689f}, {-0.58778507f,0.80901712f},
+{-0.45399022f,0.89100665f}, {-0.30901709f,0.95105648f}, {-0.15643452f,0.98768830f},
+{1.0000000f,-0.0000000f}, {0.99991435f,-0.013089596f}, {0.99965733f,-0.026176950f},
+{0.99922901f,-0.039259817f}, {0.99862951f,-0.052335959f}, {0.99785894f,-0.065403134f},
+{0.99691731f,-0.078459099f}, {0.99580491f,-0.091501623f}, {0.99452192f,-0.10452846f},
+{0.99306846f,-0.11753740f}, {0.99144489f,-0.13052620f}, {0.98965138f,-0.14349262f},
+{0.98768836f,-0.15643448f}, {0.98555607f,-0.16934951f}, {0.98325491f,-0.18223552f},
+{0.98078525f,-0.19509032f}, {0.97814763f,-0.20791170f}, {0.97534233f,-0.22069745f},
+{0.97236991f,-0.23344538f}, {0.96923089f,-0.24615330f}, {0.96592581f,-0.25881904f},
+{0.96245521f,-0.27144045f}, {0.95881975f,-0.28401536f}, {0.95501995f,-0.29654160f},
+{0.95105648f,-0.30901700f}, {0.94693011f,-0.32143945f}, {0.94264150f,-0.33380687f},
+{0.93819129f,-0.34611708f}, {0.93358040f,-0.35836795f}, {0.92880952f,-0.37055743f},
+{0.92387956f,-0.38268346f}, {0.91879117f,-0.39474389f}, {0.91354543f,-0.40673664f},
+{0.90814316f,-0.41865975f}, {0.90258527f,-0.43051112f}, {0.89687270f,-0.44228873f},
+{0.89100653f,-0.45399052f}, {0.88498765f,-0.46561453f}, {0.87881708f,-0.47715878f},
+{0.87249601f,-0.48862126f}, {0.86602545f,-0.50000000f}, {0.85940641f,-0.51129311f},
+{0.85264015f,-0.52249855f}, {0.84572786f,-0.53361452f}, {0.83867055f,-0.54463905f},
+{0.83146960f,-0.55557024f}, {0.82412618f,-0.56640625f}, {0.81664151f,-0.57714522f},
+{0.80901700f,-0.58778524f}, {0.80125380f,-0.59832460f}, {0.79335332f,-0.60876143f},
+{0.78531694f,-0.61909395f}, {0.77714598f,-0.62932038f}, {0.76884180f,-0.63943899f},
+{0.76040596f,-0.64944810f}, {0.75183982f,-0.65934587f}, {0.74314475f,-0.66913062f},
+{0.73432249f,-0.67880076f}, {0.72537434f,-0.68835455f}, {0.71630192f,-0.69779050f},
+{0.70710677f,-0.70710683f}, {0.69779044f,-0.71630198f}, {0.68835455f,-0.72537440f},
+{0.67880070f,-0.73432255f}, {0.66913056f,-0.74314487f}, {0.65934581f,-0.75183982f},
+{0.64944804f,-0.76040596f}, {0.63943899f,-0.76884186f}, {0.62932038f,-0.77714598f},
+{0.61909395f,-0.78531694f}, {0.60876137f,-0.79335338f}, {0.59832460f,-0.80125386f},
+{0.58778524f,-0.80901700f}, {0.57714516f,-0.81664151f}, {0.56640625f,-0.82412618f},
+{0.55557019f,-0.83146960f}, {0.54463899f,-0.83867055f}, {0.53361452f,-0.84572786f},
+{0.52249849f,-0.85264015f}, {0.51129311f,-0.85940641f}, {0.49999997f,-0.86602545f},
+{0.48862118f,-0.87249601f}, {0.47715876f,-0.87881708f}, {0.46561447f,-0.88498765f},
+{0.45399052f,-0.89100653f}, {0.44228867f,-0.89687276f}, {0.43051103f,-0.90258533f},
+{0.41865975f,-0.90814316f}, {0.40673661f,-0.91354549f}, {0.39474380f,-0.91879129f},
+{0.38268343f,-0.92387956f}, {0.37055740f,-0.92880958f}, {0.35836786f,-0.93358046f},
+{0.34611705f,-0.93819135f}, {0.33380681f,-0.94264150f}, {0.32143947f,-0.94693011f},
+{0.30901697f,-0.95105654f}, {0.29654151f,-0.95501995f}, {0.28401533f,-0.95881975f},
+{0.27144039f,-0.96245527f}, {0.25881907f,-0.96592581f}, {0.24615327f,-0.96923089f},
+{0.23344530f,-0.97236991f}, {0.22069745f,-0.97534233f}, {0.20791166f,-0.97814763f},
+{0.19509023f,-0.98078531f}, {0.18223552f,-0.98325491f}, {0.16934945f,-0.98555607f},
+{0.15643437f,-0.98768836f}, {0.14349259f,-0.98965138f}, {0.13052613f,-0.99144489f},
+{0.11753740f,-0.99306846f}, {0.10452842f,-0.99452192f}, {0.091501534f,-0.99580491f},
+{0.078459084f,-0.99691731f}, {0.065403074f,-0.99785894f}, {0.052335974f,-0.99862951f},
+{0.039259788f,-0.99922901f}, {0.026176875f,-0.99965733f}, {0.013089597f,-0.99991435f},
+{1.0000000f,-0.0000000f}, {0.99965733f,-0.026176950f}, {0.99862951f,-0.052335959f},
+{0.99691731f,-0.078459099f}, {0.99452192f,-0.10452846f}, {0.99144489f,-0.13052620f},
+{0.98768836f,-0.15643448f}, {0.98325491f,-0.18223552f}, {0.97814763f,-0.20791170f},
+{0.97236991f,-0.23344538f}, {0.96592581f,-0.25881904f}, {0.95881975f,-0.28401536f},
+{0.95105648f,-0.30901700f}, {0.94264150f,-0.33380687f}, {0.93358040f,-0.35836795f},
+{0.92387956f,-0.38268346f}, {0.91354543f,-0.40673664f}, {0.90258527f,-0.43051112f},
+{0.89100653f,-0.45399052f}, {0.87881708f,-0.47715878f}, {0.86602545f,-0.50000000f},
+{0.85264015f,-0.52249855f}, {0.83867055f,-0.54463905f}, {0.82412618f,-0.56640625f},
+{0.80901700f,-0.58778524f}, {0.79335332f,-0.60876143f}, {0.77714598f,-0.62932038f},
+{0.76040596f,-0.64944810f}, {0.74314475f,-0.66913062f}, {0.72537434f,-0.68835455f},
+{0.70710677f,-0.70710683f}, {0.68835455f,-0.72537440f}, {0.66913056f,-0.74314487f},
+{0.64944804f,-0.76040596f}, {0.62932038f,-0.77714598f}, {0.60876137f,-0.79335338f},
+{0.58778524f,-0.80901700f}, {0.56640625f,-0.82412618f}, {0.54463899f,-0.83867055f},
+{0.52249849f,-0.85264015f}, {0.49999997f,-0.86602545f}, {0.47715876f,-0.87881708f},
+{0.45399052f,-0.89100653f}, {0.43051103f,-0.90258533f}, {0.40673661f,-0.91354549f},
+{0.38268343f,-0.92387956f}, {0.35836786f,-0.93358046f}, {0.33380681f,-0.94264150f},
+{0.30901697f,-0.95105654f}, {0.28401533f,-0.95881975f}, {0.25881907f,-0.96592581f},
+{0.23344530f,-0.97236991f}, {0.20791166f,-0.97814763f}, {0.18223552f,-0.98325491f},
+{0.15643437f,-0.98768836f}, {0.13052613f,-0.99144489f}, {0.10452842f,-0.99452192f},
+{0.078459084f,-0.99691731f}, {0.052335974f,-0.99862951f}, {0.026176875f,-0.99965733f},
+{-4.3711388e-08f,-1.0000000f}, {-0.026176963f,-0.99965733f}, {-0.052336060f,-0.99862951f},
+{-0.078459173f,-0.99691731f}, {-0.10452851f,-0.99452192f}, {-0.13052621f,-0.99144489f},
+{-0.15643445f,-0.98768836f}, {-0.18223560f,-0.98325491f}, {-0.20791174f,-0.97814757f},
+{-0.23344538f,-0.97236991f}, {-0.25881916f,-0.96592581f}, {-0.28401542f,-0.95881969f},
+{-0.30901703f,-0.95105648f}, {-0.33380687f,-0.94264150f}, {-0.35836795f,-0.93358040f},
+{-0.38268352f,-0.92387950f}, {-0.40673670f,-0.91354543f}, {-0.43051112f,-0.90258527f},
+{-0.45399061f,-0.89100647f}, {-0.47715873f,-0.87881708f}, {-0.50000006f,-0.86602533f},
+{-0.52249867f,-0.85264009f}, {-0.54463905f,-0.83867055f}, {-0.56640631f,-0.82412612f},
+{-0.58778518f,-0.80901700f}, {-0.60876143f,-0.79335332f}, {-0.62932050f,-0.77714586f},
+{-0.64944804f,-0.76040596f}, {-0.66913068f,-0.74314475f}, {-0.68835467f,-0.72537428f},
+{-0.70710677f,-0.70710677f}, {-0.72537446f,-0.68835449f}, {-0.74314493f,-0.66913044f},
+{-0.76040596f,-0.64944804f}, {-0.77714604f,-0.62932026f}, {-0.79335332f,-0.60876143f},
+{-0.80901700f,-0.58778518f}, {-0.82412624f,-0.56640613f}, {-0.83867055f,-0.54463899f},
+{-0.85264021f,-0.52249849f}, {-0.86602539f,-0.50000006f}, {-0.87881714f,-0.47715873f},
+{-0.89100659f,-0.45399037f}, {-0.90258527f,-0.43051112f}, {-0.91354549f,-0.40673658f},
+{-0.92387956f,-0.38268328f}, {-0.93358040f,-0.35836792f}, {-0.94264150f,-0.33380675f},
+{-0.95105654f,-0.30901679f}, {-0.95881975f,-0.28401530f}, {-0.96592587f,-0.25881892f},
+{-0.97236991f,-0.23344538f}, {-0.97814763f,-0.20791161f}, {-0.98325491f,-0.18223536f},
+{-0.98768836f,-0.15643445f}, {-0.99144489f,-0.13052608f}, {-0.99452192f,-0.10452849f},
+{-0.99691737f,-0.078459039f}, {-0.99862957f,-0.052335810f}, {-0.99965733f,-0.026176952f},
+{1.0000000f,-0.0000000f}, {0.99922901f,-0.039259817f}, {0.99691731f,-0.078459099f},
+{0.99306846f,-0.11753740f}, {0.98768836f,-0.15643448f}, {0.98078525f,-0.19509032f},
+{0.97236991f,-0.23344538f}, {0.96245521f,-0.27144045f}, {0.95105648f,-0.30901700f},
+{0.93819129f,-0.34611708f}, {0.92387956f,-0.38268346f}, {0.90814316f,-0.41865975f},
+{0.89100653f,-0.45399052f}, {0.87249601f,-0.48862126f}, {0.85264015f,-0.52249855f},
+{0.83146960f,-0.55557024f}, {0.80901700f,-0.58778524f}, {0.78531694f,-0.61909395f},
+{0.76040596f,-0.64944810f}, {0.73432249f,-0.67880076f}, {0.70710677f,-0.70710683f},
+{0.67880070f,-0.73432255f}, {0.64944804f,-0.76040596f}, {0.61909395f,-0.78531694f},
+{0.58778524f,-0.80901700f}, {0.55557019f,-0.83146960f}, {0.52249849f,-0.85264015f},
+{0.48862118f,-0.87249601f}, {0.45399052f,-0.89100653f}, {0.41865975f,-0.90814316f},
+{0.38268343f,-0.92387956f}, {0.34611705f,-0.93819135f}, {0.30901697f,-0.95105654f},
+{0.27144039f,-0.96245527f}, {0.23344530f,-0.97236991f}, {0.19509023f,-0.98078531f},
+{0.15643437f,-0.98768836f}, {0.11753740f,-0.99306846f}, {0.078459084f,-0.99691731f},
+{0.039259788f,-0.99922901f}, {-4.3711388e-08f,-1.0000000f}, {-0.039259877f,-0.99922901f},
+{-0.078459173f,-0.99691731f}, {-0.11753749f,-0.99306846f}, {-0.15643445f,-0.98768836f},
+{-0.19509032f,-0.98078525f}, {-0.23344538f,-0.97236991f}, {-0.27144048f,-0.96245521f},
+{-0.30901703f,-0.95105648f}, {-0.34611711f,-0.93819129f}, {-0.38268352f,-0.92387950f},
+{-0.41865984f,-0.90814310f}, {-0.45399061f,-0.89100647f}, {-0.48862135f,-0.87249595f},
+{-0.52249867f,-0.85264009f}, {-0.55557036f,-0.83146954f}, {-0.58778518f,-0.80901700f},
+{-0.61909389f,-0.78531694f}, {-0.64944804f,-0.76040596f}, {-0.67880076f,-0.73432249f},
+{-0.70710677f,-0.70710677f}, {-0.73432249f,-0.67880070f}, {-0.76040596f,-0.64944804f},
+{-0.78531694f,-0.61909389f}, {-0.80901700f,-0.58778518f}, {-0.83146966f,-0.55557019f},
+{-0.85264021f,-0.52249849f}, {-0.87249607f,-0.48862115f}, {-0.89100659f,-0.45399037f},
+{-0.90814322f,-0.41865960f}, {-0.92387956f,-0.38268328f}, {-0.93819135f,-0.34611690f},
+{-0.95105654f,-0.30901679f}, {-0.96245521f,-0.27144048f}, {-0.97236991f,-0.23344538f},
+{-0.98078531f,-0.19509031f}, {-0.98768836f,-0.15643445f}, {-0.99306846f,-0.11753736f},
+{-0.99691737f,-0.078459039f}, {-0.99922901f,-0.039259743f}, {-1.0000000f,8.7422777e-08f},
+{-0.99922901f,0.039259918f}, {-0.99691731f,0.078459218f}, {-0.99306846f,0.11753753f},
+{-0.98768830f,0.15643461f}, {-0.98078525f,0.19509049f}, {-0.97236985f,0.23344554f},
+{-0.96245515f,0.27144065f}, {-0.95105654f,0.30901697f}, {-0.93819135f,0.34611705f},
+{-0.92387956f,0.38268346f}, {-0.90814316f,0.41865975f}, {-0.89100653f,0.45399055f},
+{-0.87249601f,0.48862129f}, {-0.85264015f,0.52249861f}, {-0.83146960f,0.55557030f},
+{-0.80901694f,0.58778536f}, {-0.78531688f,0.61909401f}, {-0.76040590f,0.64944816f},
+{-0.73432243f,0.67880082f}, {-0.70710665f,0.70710689f}, {-0.67880058f,0.73432261f},
+{-0.64944792f,0.76040608f}, {-0.61909378f,0.78531706f}, {-0.58778507f,0.80901712f},
+{-0.55557001f,0.83146977f}, {-0.52249837f,0.85264033f}, {-0.48862100f,0.87249613f},
+{-0.45399022f,0.89100665f}, {-0.41865945f,0.90814328f}, {-0.38268313f,0.92387968f},
+{-0.34611672f,0.93819147f}, {-0.30901709f,0.95105648f}, {-0.27144054f,0.96245521f},
+{-0.23344545f,0.97236991f}, {-0.19509038f,0.98078525f}, {-0.15643452f,0.98768830f},
+{-0.11753743f,0.99306846f}, {-0.078459114f,0.99691731f}, {-0.039259821f,0.99922901f},
+};
+static const ne10_fft_cpx_float32_t ne10_twiddles_240[240] = {
+{1.0000000f,0.0000000f}, {1.0000000f,-0.0000000f}, {1.0000000f,-0.0000000f},
+{1.0000000f,-0.0000000f}, {0.91354543f,-0.40673664f}, {0.66913056f,-0.74314487f},
+{1.0000000f,-0.0000000f}, {0.66913056f,-0.74314487f}, {-0.10452851f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.30901697f,-0.95105654f}, {-0.80901700f,-0.58778518f},
+{1.0000000f,-0.0000000f}, {-0.10452851f,-0.99452192f}, {-0.97814757f,0.20791179f},
+{1.0000000f,-0.0000000f}, {0.99452192f,-0.10452846f}, {0.97814763f,-0.20791170f},
+{0.95105648f,-0.30901700f}, {0.91354543f,-0.40673664f}, {0.86602545f,-0.50000000f},
+{0.80901700f,-0.58778524f}, {0.74314475f,-0.66913062f}, {0.66913056f,-0.74314487f},
+{0.58778524f,-0.80901700f}, {0.49999997f,-0.86602545f}, {0.40673661f,-0.91354549f},
+{0.30901697f,-0.95105654f}, {0.20791166f,-0.97814763f}, {0.10452842f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.97814763f,-0.20791170f}, {0.91354543f,-0.40673664f},
+{0.80901700f,-0.58778524f}, {0.66913056f,-0.74314487f}, {0.49999997f,-0.86602545f},
+{0.30901697f,-0.95105654f}, {0.10452842f,-0.99452192f}, {-0.10452851f,-0.99452192f},
+{-0.30901703f,-0.95105648f}, {-0.50000006f,-0.86602533f}, {-0.66913068f,-0.74314475f},
+{-0.80901700f,-0.58778518f}, {-0.91354549f,-0.40673658f}, {-0.97814763f,-0.20791161f},
+{1.0000000f,-0.0000000f}, {0.95105648f,-0.30901700f}, {0.80901700f,-0.58778524f},
+{0.58778524f,-0.80901700f}, {0.30901697f,-0.95105654f}, {-4.3711388e-08f,-1.0000000f},
+{-0.30901703f,-0.95105648f}, {-0.58778518f,-0.80901700f}, {-0.80901700f,-0.58778518f},
+{-0.95105654f,-0.30901679f}, {-1.0000000f,8.7422777e-08f}, {-0.95105654f,0.30901697f},
+{-0.80901694f,0.58778536f}, {-0.58778507f,0.80901712f}, {-0.30901709f,0.95105648f},
+{1.0000000f,-0.0000000f}, {0.99965733f,-0.026176950f}, {0.99862951f,-0.052335959f},
+{0.99691731f,-0.078459099f}, {0.99452192f,-0.10452846f}, {0.99144489f,-0.13052620f},
+{0.98768836f,-0.15643448f}, {0.98325491f,-0.18223552f}, {0.97814763f,-0.20791170f},
+{0.97236991f,-0.23344538f}, {0.96592581f,-0.25881904f}, {0.95881975f,-0.28401536f},
+{0.95105648f,-0.30901700f}, {0.94264150f,-0.33380687f}, {0.93358040f,-0.35836795f},
+{0.92387956f,-0.38268346f}, {0.91354543f,-0.40673664f}, {0.90258527f,-0.43051112f},
+{0.89100653f,-0.45399052f}, {0.87881708f,-0.47715878f}, {0.86602545f,-0.50000000f},
+{0.85264015f,-0.52249855f}, {0.83867055f,-0.54463905f}, {0.82412618f,-0.56640625f},
+{0.80901700f,-0.58778524f}, {0.79335332f,-0.60876143f}, {0.77714598f,-0.62932038f},
+{0.76040596f,-0.64944810f}, {0.74314475f,-0.66913062f}, {0.72537434f,-0.68835455f},
+{0.70710677f,-0.70710683f}, {0.68835455f,-0.72537440f}, {0.66913056f,-0.74314487f},
+{0.64944804f,-0.76040596f}, {0.62932038f,-0.77714598f}, {0.60876137f,-0.79335338f},
+{0.58778524f,-0.80901700f}, {0.56640625f,-0.82412618f}, {0.54463899f,-0.83867055f},
+{0.52249849f,-0.85264015f}, {0.49999997f,-0.86602545f}, {0.47715876f,-0.87881708f},
+{0.45399052f,-0.89100653f}, {0.43051103f,-0.90258533f}, {0.40673661f,-0.91354549f},
+{0.38268343f,-0.92387956f}, {0.35836786f,-0.93358046f}, {0.33380681f,-0.94264150f},
+{0.30901697f,-0.95105654f}, {0.28401533f,-0.95881975f}, {0.25881907f,-0.96592581f},
+{0.23344530f,-0.97236991f}, {0.20791166f,-0.97814763f}, {0.18223552f,-0.98325491f},
+{0.15643437f,-0.98768836f}, {0.13052613f,-0.99144489f}, {0.10452842f,-0.99452192f},
+{0.078459084f,-0.99691731f}, {0.052335974f,-0.99862951f}, {0.026176875f,-0.99965733f},
+{1.0000000f,-0.0000000f}, {0.99862951f,-0.052335959f}, {0.99452192f,-0.10452846f},
+{0.98768836f,-0.15643448f}, {0.97814763f,-0.20791170f}, {0.96592581f,-0.25881904f},
+{0.95105648f,-0.30901700f}, {0.93358040f,-0.35836795f}, {0.91354543f,-0.40673664f},
+{0.89100653f,-0.45399052f}, {0.86602545f,-0.50000000f}, {0.83867055f,-0.54463905f},
+{0.80901700f,-0.58778524f}, {0.77714598f,-0.62932038f}, {0.74314475f,-0.66913062f},
+{0.70710677f,-0.70710683f}, {0.66913056f,-0.74314487f}, {0.62932038f,-0.77714598f},
+{0.58778524f,-0.80901700f}, {0.54463899f,-0.83867055f}, {0.49999997f,-0.86602545f},
+{0.45399052f,-0.89100653f}, {0.40673661f,-0.91354549f}, {0.35836786f,-0.93358046f},
+{0.30901697f,-0.95105654f}, {0.25881907f,-0.96592581f}, {0.20791166f,-0.97814763f},
+{0.15643437f,-0.98768836f}, {0.10452842f,-0.99452192f}, {0.052335974f,-0.99862951f},
+{-4.3711388e-08f,-1.0000000f}, {-0.052336060f,-0.99862951f}, {-0.10452851f,-0.99452192f},
+{-0.15643445f,-0.98768836f}, {-0.20791174f,-0.97814757f}, {-0.25881916f,-0.96592581f},
+{-0.30901703f,-0.95105648f}, {-0.35836795f,-0.93358040f}, {-0.40673670f,-0.91354543f},
+{-0.45399061f,-0.89100647f}, {-0.50000006f,-0.86602533f}, {-0.54463905f,-0.83867055f},
+{-0.58778518f,-0.80901700f}, {-0.62932050f,-0.77714586f}, {-0.66913068f,-0.74314475f},
+{-0.70710677f,-0.70710677f}, {-0.74314493f,-0.66913044f}, {-0.77714604f,-0.62932026f},
+{-0.80901700f,-0.58778518f}, {-0.83867055f,-0.54463899f}, {-0.86602539f,-0.50000006f},
+{-0.89100659f,-0.45399037f}, {-0.91354549f,-0.40673658f}, {-0.93358040f,-0.35836792f},
+{-0.95105654f,-0.30901679f}, {-0.96592587f,-0.25881892f}, {-0.97814763f,-0.20791161f},
+{-0.98768836f,-0.15643445f}, {-0.99452192f,-0.10452849f}, {-0.99862957f,-0.052335810f},
+{1.0000000f,-0.0000000f}, {0.99691731f,-0.078459099f}, {0.98768836f,-0.15643448f},
+{0.97236991f,-0.23344538f}, {0.95105648f,-0.30901700f}, {0.92387956f,-0.38268346f},
+{0.89100653f,-0.45399052f}, {0.85264015f,-0.52249855f}, {0.80901700f,-0.58778524f},
+{0.76040596f,-0.64944810f}, {0.70710677f,-0.70710683f}, {0.64944804f,-0.76040596f},
+{0.58778524f,-0.80901700f}, {0.52249849f,-0.85264015f}, {0.45399052f,-0.89100653f},
+{0.38268343f,-0.92387956f}, {0.30901697f,-0.95105654f}, {0.23344530f,-0.97236991f},
+{0.15643437f,-0.98768836f}, {0.078459084f,-0.99691731f}, {-4.3711388e-08f,-1.0000000f},
+{-0.078459173f,-0.99691731f}, {-0.15643445f,-0.98768836f}, {-0.23344538f,-0.97236991f},
+{-0.30901703f,-0.95105648f}, {-0.38268352f,-0.92387950f}, {-0.45399061f,-0.89100647f},
+{-0.52249867f,-0.85264009f}, {-0.58778518f,-0.80901700f}, {-0.64944804f,-0.76040596f},
+{-0.70710677f,-0.70710677f}, {-0.76040596f,-0.64944804f}, {-0.80901700f,-0.58778518f},
+{-0.85264021f,-0.52249849f}, {-0.89100659f,-0.45399037f}, {-0.92387956f,-0.38268328f},
+{-0.95105654f,-0.30901679f}, {-0.97236991f,-0.23344538f}, {-0.98768836f,-0.15643445f},
+{-0.99691737f,-0.078459039f}, {-1.0000000f,8.7422777e-08f}, {-0.99691731f,0.078459218f},
+{-0.98768830f,0.15643461f}, {-0.97236985f,0.23344554f}, {-0.95105654f,0.30901697f},
+{-0.92387956f,0.38268346f}, {-0.89100653f,0.45399055f}, {-0.85264015f,0.52249861f},
+{-0.80901694f,0.58778536f}, {-0.76040590f,0.64944816f}, {-0.70710665f,0.70710689f},
+{-0.64944792f,0.76040608f}, {-0.58778507f,0.80901712f}, {-0.52249837f,0.85264033f},
+{-0.45399022f,0.89100665f}, {-0.38268313f,0.92387968f}, {-0.30901709f,0.95105648f},
+{-0.23344545f,0.97236991f}, {-0.15643452f,0.98768830f}, {-0.078459114f,0.99691731f},
+};
+static const ne10_fft_cpx_float32_t ne10_twiddles_120[120] = {
+{1.0000000f,0.0000000f}, {1.0000000f,-0.0000000f}, {1.0000000f,-0.0000000f},
+{1.0000000f,-0.0000000f}, {0.91354543f,-0.40673664f}, {0.66913056f,-0.74314487f},
+{1.0000000f,-0.0000000f}, {0.66913056f,-0.74314487f}, {-0.10452851f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.30901697f,-0.95105654f}, {-0.80901700f,-0.58778518f},
+{1.0000000f,-0.0000000f}, {-0.10452851f,-0.99452192f}, {-0.97814757f,0.20791179f},
+{1.0000000f,-0.0000000f}, {0.97814763f,-0.20791170f}, {0.91354543f,-0.40673664f},
+{0.80901700f,-0.58778524f}, {0.66913056f,-0.74314487f}, {0.49999997f,-0.86602545f},
+{0.30901697f,-0.95105654f}, {0.10452842f,-0.99452192f}, {-0.10452851f,-0.99452192f},
+{-0.30901703f,-0.95105648f}, {-0.50000006f,-0.86602533f}, {-0.66913068f,-0.74314475f},
+{-0.80901700f,-0.58778518f}, {-0.91354549f,-0.40673658f}, {-0.97814763f,-0.20791161f},
+{1.0000000f,-0.0000000f}, {0.99862951f,-0.052335959f}, {0.99452192f,-0.10452846f},
+{0.98768836f,-0.15643448f}, {0.97814763f,-0.20791170f}, {0.96592581f,-0.25881904f},
+{0.95105648f,-0.30901700f}, {0.93358040f,-0.35836795f}, {0.91354543f,-0.40673664f},
+{0.89100653f,-0.45399052f}, {0.86602545f,-0.50000000f}, {0.83867055f,-0.54463905f},
+{0.80901700f,-0.58778524f}, {0.77714598f,-0.62932038f}, {0.74314475f,-0.66913062f},
+{0.70710677f,-0.70710683f}, {0.66913056f,-0.74314487f}, {0.62932038f,-0.77714598f},
+{0.58778524f,-0.80901700f}, {0.54463899f,-0.83867055f}, {0.49999997f,-0.86602545f},
+{0.45399052f,-0.89100653f}, {0.40673661f,-0.91354549f}, {0.35836786f,-0.93358046f},
+{0.30901697f,-0.95105654f}, {0.25881907f,-0.96592581f}, {0.20791166f,-0.97814763f},
+{0.15643437f,-0.98768836f}, {0.10452842f,-0.99452192f}, {0.052335974f,-0.99862951f},
+{1.0000000f,-0.0000000f}, {0.99452192f,-0.10452846f}, {0.97814763f,-0.20791170f},
+{0.95105648f,-0.30901700f}, {0.91354543f,-0.40673664f}, {0.86602545f,-0.50000000f},
+{0.80901700f,-0.58778524f}, {0.74314475f,-0.66913062f}, {0.66913056f,-0.74314487f},
+{0.58778524f,-0.80901700f}, {0.49999997f,-0.86602545f}, {0.40673661f,-0.91354549f},
+{0.30901697f,-0.95105654f}, {0.20791166f,-0.97814763f}, {0.10452842f,-0.99452192f},
+{-4.3711388e-08f,-1.0000000f}, {-0.10452851f,-0.99452192f}, {-0.20791174f,-0.97814757f},
+{-0.30901703f,-0.95105648f}, {-0.40673670f,-0.91354543f}, {-0.50000006f,-0.86602533f},
+{-0.58778518f,-0.80901700f}, {-0.66913068f,-0.74314475f}, {-0.74314493f,-0.66913044f},
+{-0.80901700f,-0.58778518f}, {-0.86602539f,-0.50000006f}, {-0.91354549f,-0.40673658f},
+{-0.95105654f,-0.30901679f}, {-0.97814763f,-0.20791161f}, {-0.99452192f,-0.10452849f},
+{1.0000000f,-0.0000000f}, {0.98768836f,-0.15643448f}, {0.95105648f,-0.30901700f},
+{0.89100653f,-0.45399052f}, {0.80901700f,-0.58778524f}, {0.70710677f,-0.70710683f},
+{0.58778524f,-0.80901700f}, {0.45399052f,-0.89100653f}, {0.30901697f,-0.95105654f},
+{0.15643437f,-0.98768836f}, {-4.3711388e-08f,-1.0000000f}, {-0.15643445f,-0.98768836f},
+{-0.30901703f,-0.95105648f}, {-0.45399061f,-0.89100647f}, {-0.58778518f,-0.80901700f},
+{-0.70710677f,-0.70710677f}, {-0.80901700f,-0.58778518f}, {-0.89100659f,-0.45399037f},
+{-0.95105654f,-0.30901679f}, {-0.98768836f,-0.15643445f}, {-1.0000000f,8.7422777e-08f},
+{-0.98768830f,0.15643461f}, {-0.95105654f,0.30901697f}, {-0.89100653f,0.45399055f},
+{-0.80901694f,0.58778536f}, {-0.70710665f,0.70710689f}, {-0.58778507f,0.80901712f},
+{-0.45399022f,0.89100665f}, {-0.30901709f,0.95105648f}, {-0.15643452f,0.98768830f},
+};
+static const ne10_fft_cpx_float32_t ne10_twiddles_60[60] = {
+{1.0000000f,0.0000000f}, {1.0000000f,-0.0000000f}, {1.0000000f,-0.0000000f},
+{1.0000000f,-0.0000000f}, {0.91354543f,-0.40673664f}, {0.66913056f,-0.74314487f},
+{1.0000000f,-0.0000000f}, {0.66913056f,-0.74314487f}, {-0.10452851f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.30901697f,-0.95105654f}, {-0.80901700f,-0.58778518f},
+{1.0000000f,-0.0000000f}, {-0.10452851f,-0.99452192f}, {-0.97814757f,0.20791179f},
+{1.0000000f,-0.0000000f}, {0.99452192f,-0.10452846f}, {0.97814763f,-0.20791170f},
+{0.95105648f,-0.30901700f}, {0.91354543f,-0.40673664f}, {0.86602545f,-0.50000000f},
+{0.80901700f,-0.58778524f}, {0.74314475f,-0.66913062f}, {0.66913056f,-0.74314487f},
+{0.58778524f,-0.80901700f}, {0.49999997f,-0.86602545f}, {0.40673661f,-0.91354549f},
+{0.30901697f,-0.95105654f}, {0.20791166f,-0.97814763f}, {0.10452842f,-0.99452192f},
+{1.0000000f,-0.0000000f}, {0.97814763f,-0.20791170f}, {0.91354543f,-0.40673664f},
+{0.80901700f,-0.58778524f}, {0.66913056f,-0.74314487f}, {0.49999997f,-0.86602545f},
+{0.30901697f,-0.95105654f}, {0.10452842f,-0.99452192f}, {-0.10452851f,-0.99452192f},
+{-0.30901703f,-0.95105648f}, {-0.50000006f,-0.86602533f}, {-0.66913068f,-0.74314475f},
+{-0.80901700f,-0.58778518f}, {-0.91354549f,-0.40673658f}, {-0.97814763f,-0.20791161f},
+{1.0000000f,-0.0000000f}, {0.95105648f,-0.30901700f}, {0.80901700f,-0.58778524f},
+{0.58778524f,-0.80901700f}, {0.30901697f,-0.95105654f}, {-4.3711388e-08f,-1.0000000f},
+{-0.30901703f,-0.95105648f}, {-0.58778518f,-0.80901700f}, {-0.80901700f,-0.58778518f},
+{-0.95105654f,-0.30901679f}, {-1.0000000f,8.7422777e-08f}, {-0.95105654f,0.30901697f},
+{-0.80901694f,0.58778536f}, {-0.58778507f,0.80901712f}, {-0.30901709f,0.95105648f},
+};
+static const ne10_fft_state_float32_t ne10_fft_state_float32_t_480 = {
+120,
+(ne10_int32_t *)ne10_factors_480,
+(ne10_fft_cpx_float32_t *)ne10_twiddles_480,
+NULL,
+(ne10_fft_cpx_float32_t *)&ne10_twiddles_480[120],
+/* is_forward_scaled = true */
+(ne10_int32_t) 1,
+/* is_backward_scaled = false */
+(ne10_int32_t) 0,
+};
+static const arch_fft_state cfg_arch_480 = {
+1,
+(void *)&ne10_fft_state_float32_t_480,
+};
+
+static const ne10_fft_state_float32_t ne10_fft_state_float32_t_240 = {
+60,
+(ne10_int32_t *)ne10_factors_240,
+(ne10_fft_cpx_float32_t *)ne10_twiddles_240,
+NULL,
+(ne10_fft_cpx_float32_t *)&ne10_twiddles_240[60],
+/* is_forward_scaled = true */
+(ne10_int32_t) 1,
+/* is_backward_scaled = false */
+(ne10_int32_t) 0,
+};
+static const arch_fft_state cfg_arch_240 = {
+1,
+(void *)&ne10_fft_state_float32_t_240,
+};
+
+static const ne10_fft_state_float32_t ne10_fft_state_float32_t_120 = {
+30,
+(ne10_int32_t *)ne10_factors_120,
+(ne10_fft_cpx_float32_t *)ne10_twiddles_120,
+NULL,
+(ne10_fft_cpx_float32_t *)&ne10_twiddles_120[30],
+/* is_forward_scaled = true */
+(ne10_int32_t) 1,
+/* is_backward_scaled = false */
+(ne10_int32_t) 0,
+};
+static const arch_fft_state cfg_arch_120 = {
+1,
+(void *)&ne10_fft_state_float32_t_120,
+};
+
+static const ne10_fft_state_float32_t ne10_fft_state_float32_t_60 = {
+15,
+(ne10_int32_t *)ne10_factors_60,
+(ne10_fft_cpx_float32_t *)ne10_twiddles_60,
+NULL,
+(ne10_fft_cpx_float32_t *)&ne10_twiddles_60[15],
+/* is_forward_scaled = true */
+(ne10_int32_t) 1,
+/* is_backward_scaled = false */
+(ne10_int32_t) 0,
+};
+static const arch_fft_state cfg_arch_60 = {
+1,
+(void *)&ne10_fft_state_float32_t_60,
+};
+
+#endif  /* end NE10_FFT_PARAMS48000_960 */
diff --git a/opus/celt/tests/test_unit_cwrs32.c b/opus/celt/tests/test_unit_cwrs32.c
new file mode 100644 (file)
index 0000000..36dd8af
--- /dev/null
@@ -0,0 +1,161 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation, Mozilla Corporation,
+                           Gregory Maxwell
+   Written by Jean-Marc Valin, Gregory Maxwell, and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#ifndef CUSTOM_MODES
+#define CUSTOM_MODES
+#else
+#define TEST_CUSTOM_MODES
+#endif
+
+#define CELT_C
+#include "stack_alloc.h"
+#include "entenc.c"
+#include "entdec.c"
+#include "entcode.c"
+#include "cwrs.c"
+#include "mathops.c"
+#include "rate.h"
+
+#define NMAX (240)
+#define KMAX (128)
+
+#ifdef TEST_CUSTOM_MODES
+
+#define NDIMS (44)
+static const int pn[NDIMS]={
+   2,   3,   4,   5,   6,   7,   8,   9,  10,
+  11,  12,  13,  14,  15,  16,  18,  20,  22,
+  24,  26,  28,  30,  32,  36,  40,  44,  48,
+  52,  56,  60,  64,  72,  80,  88,  96, 104,
+ 112, 120, 128, 144, 160, 176, 192, 208
+};
+static const int pkmax[NDIMS]={
+ 128, 128, 128, 128,  88,  52,  36,  26,  22,
+  18,  16,  15,  13,  12,  12,  11,  10,   9,
+   9,   8,   8,   7,   7,   7,   7,   6,   6,
+   6,   6,   6,   5,   5,   5,   5,   5,   5,
+   4,   4,   4,   4,   4,   4,   4,   4
+};
+
+#else /* TEST_CUSTOM_MODES */
+
+#define NDIMS (22)
+static const int pn[NDIMS]={
+   2,   3,   4,   6,   8,   9,  11,  12,  16,
+  18,  22,  24,  32,  36,  44,  48,  64,  72,
+  88,  96, 144, 176
+};
+static const int pkmax[NDIMS]={
+ 128, 128, 128,  88,  36,  26,  18,  16,  12,
+  11,   9,   9,   7,   7,   6,   6,   5,   5,
+   5,   5,   4,   4
+};
+
+#endif
+
+int main(void){
+  int t;
+  int n;
+  ALLOC_STACK;
+  for(t=0;t<NDIMS;t++){
+    int pseudo;
+    n=pn[t];
+    for(pseudo=1;pseudo<41;pseudo++)
+    {
+      int k;
+#if defined(SMALL_FOOTPRINT)
+      opus_uint32 uu[KMAX+2U];
+#endif
+      opus_uint32 inc;
+      opus_uint32 nc;
+      opus_uint32 i;
+      k=get_pulses(pseudo);
+      if (k>pkmax[t])break;
+      printf("Testing CWRS with N=%i, K=%i...\n",n,k);
+#if defined(SMALL_FOOTPRINT)
+      nc=ncwrs_urow(n,k,uu);
+#else
+      nc=CELT_PVQ_V(n,k);
+#endif
+      inc=nc/20000;
+      if(inc<1)inc=1;
+      for(i=0;i<nc;i+=inc){
+#if defined(SMALL_FOOTPRINT)
+        opus_uint32 u[KMAX+2U];
+#endif
+        int         y[NMAX];
+        int         sy;
+        opus_uint32 v;
+        opus_uint32 ii;
+        int         j;
+#if defined(SMALL_FOOTPRINT)
+        memcpy(u,uu,(k+2U)*sizeof(*u));
+        cwrsi(n,k,i,y,u);
+#else
+        cwrsi(n,k,i,y);
+#endif
+        sy=0;
+        for(j=0;j<n;j++)sy+=abs(y[j]);
+        if(sy!=k){
+          fprintf(stderr,"N=%d Pulse count mismatch in cwrsi (%d!=%d).\n",
+           n,sy,k);
+          return 99;
+        }
+        /*printf("%6u of %u:",i,nc);
+        for(j=0;j<n;j++)printf(" %+3i",y[j]);
+        printf(" ->");*/
+#if defined(SMALL_FOOTPRINT)
+        ii=icwrs(n,k,&v,y,u);
+#else
+        ii=icwrs(n,y);
+        v=CELT_PVQ_V(n,k);
+#endif
+        if(ii!=i){
+          fprintf(stderr,"Combination-index mismatch (%lu!=%lu).\n",
+           (long)ii,(long)i);
+          return 1;
+        }
+        if(v!=nc){
+          fprintf(stderr,"Combination count mismatch (%lu!=%lu).\n",
+           (long)v,(long)nc);
+          return 2;
+        }
+        /*printf(" %6u\n",i);*/
+      }
+      /*printf("\n");*/
+    }
+  }
+  return 0;
+}
diff --git a/opus/celt/tests/test_unit_dft.c b/opus/celt/tests/test_unit_dft.c
new file mode 100644 (file)
index 0000000..70f8f49
--- /dev/null
@@ -0,0 +1,179 @@
+/* Copyright (c) 2008 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+
+#include "stack_alloc.h"
+#include "kiss_fft.h"
+#include "mathops.h"
+#include "modes.h"
+
+#ifndef M_PI
+#define M_PI 3.141592653
+#endif
+
+int ret = 0;
+
+void check(kiss_fft_cpx  * in,kiss_fft_cpx  * out,int nfft,int isinverse)
+{
+    int bin,k;
+    double errpow=0,sigpow=0, snr;
+
+    for (bin=0;bin<nfft;++bin) {
+        double ansr = 0;
+        double ansi = 0;
+        double difr;
+        double difi;
+
+        for (k=0;k<nfft;++k) {
+            double phase = -2*M_PI*bin*k/nfft;
+            double re = cos(phase);
+            double im = sin(phase);
+            if (isinverse)
+                im = -im;
+
+            if (!isinverse)
+            {
+               re /= nfft;
+               im /= nfft;
+            }
+
+            ansr += in[k].r * re - in[k].i * im;
+            ansi += in[k].r * im + in[k].i * re;
+        }
+        /*printf ("%d %d ", (int)ansr, (int)ansi);*/
+        difr = ansr - out[bin].r;
+        difi = ansi - out[bin].i;
+        errpow += difr*difr + difi*difi;
+        sigpow += ansr*ansr+ansi*ansi;
+    }
+    snr = 10*log10(sigpow/errpow);
+    printf("nfft=%d inverse=%d,snr = %f\n",nfft,isinverse,snr );
+    if (snr<60) {
+       printf( "** poor snr: %f ** \n", snr);
+       ret = 1;
+    }
+}
+
+void test1d(int nfft,int isinverse,int arch)
+{
+    size_t buflen = sizeof(kiss_fft_cpx)*nfft;
+    kiss_fft_cpx *in;
+    kiss_fft_cpx *out;
+    int k;
+#ifdef CUSTOM_MODES
+    kiss_fft_state *cfg = opus_fft_alloc(nfft,0,0,arch);
+#else
+    int id;
+    const kiss_fft_state *cfg;
+    CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
+    if (nfft == 480) id = 0;
+    else if (nfft == 240) id = 1;
+    else if (nfft == 120) id = 2;
+    else if (nfft == 60) id = 3;
+    else return;
+    cfg = mode->mdct.kfft[id];
+#endif
+
+    in = (kiss_fft_cpx*)malloc(buflen);
+    out = (kiss_fft_cpx*)malloc(buflen);
+
+    for (k=0;k<nfft;++k) {
+        in[k].r = (rand() % 32767) - 16384;
+        in[k].i = (rand() % 32767) - 16384;
+    }
+
+    for (k=0;k<nfft;++k) {
+       in[k].r *= 32768;
+       in[k].i *= 32768;
+    }
+
+    if (isinverse)
+    {
+       for (k=0;k<nfft;++k) {
+          in[k].r /= nfft;
+          in[k].i /= nfft;
+       }
+    }
+
+    /*for (k=0;k<nfft;++k) printf("%d %d ", in[k].r, in[k].i);printf("\n");*/
+
+    if (isinverse)
+       opus_ifft(cfg,in,out, arch);
+    else
+       opus_fft(cfg,in,out, arch);
+
+    /*for (k=0;k<nfft;++k) printf("%d %d ", out[k].r, out[k].i);printf("\n");*/
+
+    check(in,out,nfft,isinverse);
+
+    free(in);
+    free(out);
+#ifdef CUSTOM_MODES
+    opus_fft_free(cfg, arch);
+#endif
+}
+
+int main(int argc,char ** argv)
+{
+    ALLOC_STACK;
+    int arch = opus_select_arch();
+
+    if (argc>1) {
+        int k;
+        for (k=1;k<argc;++k) {
+            test1d(atoi(argv[k]),0,arch);
+            test1d(atoi(argv[k]),1,arch);
+        }
+    }else{
+        test1d(32,0,arch);
+        test1d(32,1,arch);
+        test1d(128,0,arch);
+        test1d(128,1,arch);
+        test1d(256,0,arch);
+        test1d(256,1,arch);
+#ifndef RADIX_TWO_ONLY
+        test1d(36,0,arch);
+        test1d(36,1,arch);
+        test1d(50,0,arch);
+        test1d(50,1,arch);
+        test1d(60,0,arch);
+        test1d(60,1,arch);
+        test1d(120,0,arch);
+        test1d(120,1,arch);
+        test1d(240,0,arch);
+        test1d(240,1,arch);
+        test1d(480,0,arch);
+        test1d(480,1,arch);
+#endif
+    }
+    return ret;
+}
diff --git a/opus/celt/tests/test_unit_entropy.c b/opus/celt/tests/test_unit_entropy.c
new file mode 100644 (file)
index 0000000..ff92658
--- /dev/null
@@ -0,0 +1,382 @@
+/* Copyright (c) 2007-2011 Xiph.Org Foundation, Mozilla Corporation,
+                           Gregory Maxwell
+   Written by Jean-Marc Valin, Gregory Maxwell, and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+#include <time.h>
+#include "entcode.h"
+#include "entenc.h"
+#include "entdec.h"
+#include <string.h>
+
+#include "entenc.c"
+#include "entdec.c"
+#include "entcode.c"
+
+#ifndef M_LOG2E
+# define M_LOG2E    1.4426950408889634074
+#endif
+#define DATA_SIZE 10000000
+#define DATA_SIZE2 10000
+
+int main(int _argc,char **_argv){
+  ec_enc         enc;
+  ec_dec         dec;
+  long           nbits;
+  long           nbits2;
+  double         entropy;
+  int            ft;
+  int            ftb;
+  int            sz;
+  int            i;
+  int            ret;
+  unsigned int   sym;
+  unsigned int   seed;
+  unsigned char *ptr;
+  const char    *env_seed;
+  ret=0;
+  entropy=0;
+  if (_argc > 2) {
+    fprintf(stderr, "Usage: %s [<seed>]\n", _argv[0]);
+    return 1;
+  }
+  env_seed = getenv("SEED");
+  if (_argc > 1)
+    seed = atoi(_argv[1]);
+  else if (env_seed)
+    seed = atoi(env_seed);
+  else
+    seed = time(NULL);
+  /*Testing encoding of raw bit values.*/
+  ptr = (unsigned char *)malloc(DATA_SIZE);
+  ec_enc_init(&enc,ptr, DATA_SIZE);
+  for(ft=2;ft<1024;ft++){
+    for(i=0;i<ft;i++){
+      entropy+=log(ft)*M_LOG2E;
+      ec_enc_uint(&enc,i,ft);
+    }
+  }
+  /*Testing encoding of raw bit values.*/
+  for(ftb=1;ftb<16;ftb++){
+    for(i=0;i<(1<<ftb);i++){
+      entropy+=ftb;
+      nbits=ec_tell(&enc);
+      ec_enc_bits(&enc,i,ftb);
+      nbits2=ec_tell(&enc);
+      if(nbits2-nbits!=ftb){
+        fprintf(stderr,"Used %li bits to encode %i bits directly.\n",
+         nbits2-nbits,ftb);
+        ret=-1;
+      }
+    }
+  }
+  nbits=ec_tell_frac(&enc);
+  ec_enc_done(&enc);
+  fprintf(stderr,
+   "Encoded %0.2lf bits of entropy to %0.2lf bits (%0.3lf%% wasted).\n",
+   entropy,ldexp(nbits,-3),100*(nbits-ldexp(entropy,3))/nbits);
+  fprintf(stderr,"Packed to %li bytes.\n",(long)ec_range_bytes(&enc));
+  ec_dec_init(&dec,ptr,DATA_SIZE);
+  for(ft=2;ft<1024;ft++){
+    for(i=0;i<ft;i++){
+      sym=ec_dec_uint(&dec,ft);
+      if(sym!=(unsigned)i){
+        fprintf(stderr,"Decoded %i instead of %i with ft of %i.\n",sym,i,ft);
+        ret=-1;
+      }
+    }
+  }
+  for(ftb=1;ftb<16;ftb++){
+    for(i=0;i<(1<<ftb);i++){
+      sym=ec_dec_bits(&dec,ftb);
+      if(sym!=(unsigned)i){
+        fprintf(stderr,"Decoded %i instead of %i with ftb of %i.\n",sym,i,ftb);
+        ret=-1;
+      }
+    }
+  }
+  nbits2=ec_tell_frac(&dec);
+  if(nbits!=nbits2){
+    fprintf(stderr,
+     "Reported number of bits used was %0.2lf, should be %0.2lf.\n",
+     ldexp(nbits2,-3),ldexp(nbits,-3));
+    ret=-1;
+  }
+  /*Testing an encoder bust prefers range coder data over raw bits.
+    This isn't a general guarantee, will only work for data that is buffered in
+     the encoder state and not yet stored in the user buffer, and should never
+     get used in practice.
+    It's mostly here for code coverage completeness.*/
+  /*Start with a 16-bit buffer.*/
+  ec_enc_init(&enc,ptr,2);
+  /*Write 7 raw bits.*/
+  ec_enc_bits(&enc,0x55,7);
+  /*Write 12.3 bits of range coder data.*/
+  ec_enc_uint(&enc,1,2);
+  ec_enc_uint(&enc,1,3);
+  ec_enc_uint(&enc,1,4);
+  ec_enc_uint(&enc,1,5);
+  ec_enc_uint(&enc,2,6);
+  ec_enc_uint(&enc,6,7);
+  ec_enc_done(&enc);
+  ec_dec_init(&dec,ptr,2);
+  if(!enc.error
+   /*The raw bits should have been overwritten by the range coder data.*/
+   ||ec_dec_bits(&dec,7)!=0x05
+   /*And all the range coder data should have been encoded correctly.*/
+   ||ec_dec_uint(&dec,2)!=1
+   ||ec_dec_uint(&dec,3)!=1
+   ||ec_dec_uint(&dec,4)!=1
+   ||ec_dec_uint(&dec,5)!=1
+   ||ec_dec_uint(&dec,6)!=2
+   ||ec_dec_uint(&dec,7)!=6){
+    fprintf(stderr,"Encoder bust overwrote range coder data with raw bits.\n");
+    ret=-1;
+  }
+  srand(seed);
+  fprintf(stderr,"Testing random streams... Random seed: %u (%.4X)\n", seed, rand() % 65536);
+  for(i=0;i<409600;i++){
+    unsigned *data;
+    unsigned *tell;
+    unsigned tell_bits;
+    int       j;
+    int zeros;
+    ft=rand()/((RAND_MAX>>(rand()%11U))+1U)+10;
+    sz=rand()/((RAND_MAX>>(rand()%9U))+1U);
+    data=(unsigned *)malloc(sz*sizeof(*data));
+    tell=(unsigned *)malloc((sz+1)*sizeof(*tell));
+    ec_enc_init(&enc,ptr,DATA_SIZE2);
+    zeros = rand()%13==0;
+    tell[0]=ec_tell_frac(&enc);
+    for(j=0;j<sz;j++){
+      if (zeros)
+        data[j]=0;
+      else
+        data[j]=rand()%ft;
+      ec_enc_uint(&enc,data[j],ft);
+      tell[j+1]=ec_tell_frac(&enc);
+    }
+    if (rand()%2==0)
+      while(ec_tell(&enc)%8 != 0)
+        ec_enc_uint(&enc, rand()%2, 2);
+    tell_bits = ec_tell(&enc);
+    ec_enc_done(&enc);
+    if(tell_bits!=(unsigned)ec_tell(&enc)){
+      fprintf(stderr,"ec_tell() changed after ec_enc_done(): %i instead of %i (Random seed: %u)\n",
+       ec_tell(&enc),tell_bits,seed);
+      ret=-1;
+    }
+    if ((tell_bits+7)/8 < ec_range_bytes(&enc))
+    {
+      fprintf (stderr, "ec_tell() lied, there's %i bytes instead of %d (Random seed: %u)\n",
+               ec_range_bytes(&enc), (tell_bits+7)/8,seed);
+      ret=-1;
+    }
+    ec_dec_init(&dec,ptr,DATA_SIZE2);
+    if(ec_tell_frac(&dec)!=tell[0]){
+      fprintf(stderr,
+       "Tell mismatch between encoder and decoder at symbol %i: %i instead of %i (Random seed: %u).\n",
+       0,ec_tell_frac(&dec),tell[0],seed);
+    }
+    for(j=0;j<sz;j++){
+      sym=ec_dec_uint(&dec,ft);
+      if(sym!=data[j]){
+        fprintf(stderr,
+         "Decoded %i instead of %i with ft of %i at position %i of %i (Random seed: %u).\n",
+         sym,data[j],ft,j,sz,seed);
+        ret=-1;
+      }
+      if(ec_tell_frac(&dec)!=tell[j+1]){
+        fprintf(stderr,
+         "Tell mismatch between encoder and decoder at symbol %i: %i instead of %i (Random seed: %u).\n",
+         j+1,ec_tell_frac(&dec),tell[j+1],seed);
+      }
+    }
+    free(tell);
+    free(data);
+  }
+  /*Test compatibility between multiple different encode/decode routines.*/
+  for(i=0;i<409600;i++){
+    unsigned *logp1;
+    unsigned *data;
+    unsigned *tell;
+    unsigned *enc_method;
+    int       j;
+    sz=rand()/((RAND_MAX>>(rand()%9U))+1U);
+    logp1=(unsigned *)malloc(sz*sizeof(*logp1));
+    data=(unsigned *)malloc(sz*sizeof(*data));
+    tell=(unsigned *)malloc((sz+1)*sizeof(*tell));
+    enc_method=(unsigned *)malloc(sz*sizeof(*enc_method));
+    ec_enc_init(&enc,ptr,DATA_SIZE2);
+    tell[0]=ec_tell_frac(&enc);
+    for(j=0;j<sz;j++){
+      data[j]=rand()/((RAND_MAX>>1)+1);
+      logp1[j]=(rand()%15)+1;
+      enc_method[j]=rand()/((RAND_MAX>>2)+1);
+      switch(enc_method[j]){
+        case 0:{
+          ec_encode(&enc,data[j]?(1<<logp1[j])-1:0,
+           (1<<logp1[j])-(data[j]?0:1),1<<logp1[j]);
+        }break;
+        case 1:{
+          ec_encode_bin(&enc,data[j]?(1<<logp1[j])-1:0,
+           (1<<logp1[j])-(data[j]?0:1),logp1[j]);
+        }break;
+        case 2:{
+          ec_enc_bit_logp(&enc,data[j],logp1[j]);
+        }break;
+        case 3:{
+          unsigned char icdf[2];
+          icdf[0]=1;
+          icdf[1]=0;
+          ec_enc_icdf(&enc,data[j],icdf,logp1[j]);
+        }break;
+      }
+      tell[j+1]=ec_tell_frac(&enc);
+    }
+    ec_enc_done(&enc);
+    if((ec_tell(&enc)+7U)/8U<ec_range_bytes(&enc)){
+      fprintf(stderr,"tell() lied, there's %i bytes instead of %d (Random seed: %u)\n",
+       ec_range_bytes(&enc),(ec_tell(&enc)+7)/8,seed);
+      ret=-1;
+    }
+    ec_dec_init(&dec,ptr,DATA_SIZE2);
+    if(ec_tell_frac(&dec)!=tell[0]){
+      fprintf(stderr,
+       "Tell mismatch between encoder and decoder at symbol %i: %i instead of %i (Random seed: %u).\n",
+       0,ec_tell_frac(&dec),tell[0],seed);
+    }
+    for(j=0;j<sz;j++){
+      int fs;
+      int dec_method;
+      dec_method=rand()/((RAND_MAX>>2)+1);
+      switch(dec_method){
+        case 0:{
+          fs=ec_decode(&dec,1<<logp1[j]);
+          sym=fs>=(1<<logp1[j])-1;
+          ec_dec_update(&dec,sym?(1<<logp1[j])-1:0,
+           (1<<logp1[j])-(sym?0:1),1<<logp1[j]);
+        }break;
+        case 1:{
+          fs=ec_decode_bin(&dec,logp1[j]);
+          sym=fs>=(1<<logp1[j])-1;
+          ec_dec_update(&dec,sym?(1<<logp1[j])-1:0,
+           (1<<logp1[j])-(sym?0:1),1<<logp1[j]);
+        }break;
+        case 2:{
+          sym=ec_dec_bit_logp(&dec,logp1[j]);
+        }break;
+        case 3:{
+          unsigned char icdf[2];
+          icdf[0]=1;
+          icdf[1]=0;
+          sym=ec_dec_icdf(&dec,icdf,logp1[j]);
+        }break;
+      }
+      if(sym!=data[j]){
+        fprintf(stderr,
+         "Decoded %i instead of %i with logp1 of %i at position %i of %i (Random seed: %u).\n",
+         sym,data[j],logp1[j],j,sz,seed);
+        fprintf(stderr,"Encoding method: %i, decoding method: %i\n",
+         enc_method[j],dec_method);
+        ret=-1;
+      }
+      if(ec_tell_frac(&dec)!=tell[j+1]){
+        fprintf(stderr,
+         "Tell mismatch between encoder and decoder at symbol %i: %i instead of %i (Random seed: %u).\n",
+         j+1,ec_tell_frac(&dec),tell[j+1],seed);
+      }
+    }
+    free(enc_method);
+    free(tell);
+    free(data);
+    free(logp1);
+  }
+  ec_enc_init(&enc,ptr,DATA_SIZE2);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,0,2);
+  ec_enc_patch_initial_bits(&enc,3,2);
+  if(enc.error){
+    fprintf(stderr,"patch_initial_bits failed");
+    ret=-1;
+  }
+  ec_enc_patch_initial_bits(&enc,0,5);
+  if(!enc.error){
+    fprintf(stderr,"patch_initial_bits didn't fail when it should have");
+    ret=-1;
+  }
+  ec_enc_done(&enc);
+  if(ec_range_bytes(&enc)!=1||ptr[0]!=192){
+    fprintf(stderr,"Got %d when expecting 192 for patch_initial_bits",ptr[0]);
+    ret=-1;
+  }
+  ec_enc_init(&enc,ptr,DATA_SIZE2);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,0,1);
+  ec_enc_bit_logp(&enc,1,6);
+  ec_enc_bit_logp(&enc,0,2);
+  ec_enc_patch_initial_bits(&enc,0,2);
+  if(enc.error){
+    fprintf(stderr,"patch_initial_bits failed");
+    ret=-1;
+  }
+  ec_enc_done(&enc);
+  if(ec_range_bytes(&enc)!=2||ptr[0]!=63){
+    fprintf(stderr,"Got %d when expecting 63 for patch_initial_bits",ptr[0]);
+    ret=-1;
+  }
+  ec_enc_init(&enc,ptr,2);
+  ec_enc_bit_logp(&enc,0,2);
+  for(i=0;i<48;i++){
+    ec_enc_bits(&enc,0,1);
+  }
+  ec_enc_done(&enc);
+  if(!enc.error){
+    fprintf(stderr,"Raw bits overfill didn't fail when it should have");
+    ret=-1;
+  }
+  ec_enc_init(&enc,ptr,2);
+  for(i=0;i<17;i++){
+    ec_enc_bits(&enc,0,1);
+  }
+  ec_enc_done(&enc);
+  if(!enc.error){
+    fprintf(stderr,"17 raw bits encoded in two bytes");
+    ret=-1;
+  }
+  free(ptr);
+  return ret;
+}
diff --git a/opus/celt/tests/test_unit_laplace.c b/opus/celt/tests/test_unit_laplace.c
new file mode 100644 (file)
index 0000000..22951e2
--- /dev/null
@@ -0,0 +1,93 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation, Mozilla Corporation
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "laplace.h"
+#define CELT_C
+#include "stack_alloc.h"
+
+#include "entenc.c"
+#include "entdec.c"
+#include "entcode.c"
+#include "laplace.c"
+
+#define DATA_SIZE 40000
+
+int ec_laplace_get_start_freq(int decay)
+{
+   opus_uint32 ft = 32768 - LAPLACE_MINP*(2*LAPLACE_NMIN+1);
+   int fs = (ft*(16384-decay))/(16384+decay);
+   return fs+LAPLACE_MINP;
+}
+
+int main(void)
+{
+   int i;
+   int ret = 0;
+   ec_enc enc;
+   ec_dec dec;
+   unsigned char *ptr;
+   int val[10000], decay[10000];
+   ALLOC_STACK;
+   ptr = (unsigned char *)malloc(DATA_SIZE);
+   ec_enc_init(&enc,ptr,DATA_SIZE);
+
+   val[0] = 3; decay[0] = 6000;
+   val[1] = 0; decay[1] = 5800;
+   val[2] = -1; decay[2] = 5600;
+   for (i=3;i<10000;i++)
+   {
+      val[i] = rand()%15-7;
+      decay[i] = rand()%11000+5000;
+   }
+   for (i=0;i<10000;i++)
+      ec_laplace_encode(&enc, &val[i],
+            ec_laplace_get_start_freq(decay[i]), decay[i]);
+
+   ec_enc_done(&enc);
+
+   ec_dec_init(&dec,ec_get_buffer(&enc),ec_range_bytes(&enc));
+
+   for (i=0;i<10000;i++)
+   {
+      int d = ec_laplace_decode(&dec,
+            ec_laplace_get_start_freq(decay[i]), decay[i]);
+      if (d != val[i])
+      {
+         fprintf (stderr, "Got %d instead of %d\n", d, val[i]);
+         ret = 1;
+      }
+   }
+
+   free(ptr);
+   return ret;
+}
diff --git a/opus/celt/tests/test_unit_mathops.c b/opus/celt/tests/test_unit_mathops.c
new file mode 100644 (file)
index 0000000..874e9ad
--- /dev/null
@@ -0,0 +1,266 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation, Mozilla Corporation,
+                           Gregory Maxwell
+   Written by Jean-Marc Valin, Gregory Maxwell, and 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifndef CUSTOM_MODES
+#define CUSTOM_MODES
+#endif
+
+#include <stdio.h>
+#include <math.h>
+#include "mathops.h"
+#include "bands.h"
+
+#ifdef FIXED_POINT
+#define WORD "%d"
+#else
+#define WORD "%f"
+#endif
+
+int ret = 0;
+
+void testdiv(void)
+{
+   opus_int32 i;
+   for (i=1;i<=327670;i++)
+   {
+      double prod;
+      opus_val32 val;
+      val = celt_rcp(i);
+#ifdef FIXED_POINT
+      prod = (1./32768./65526.)*val*i;
+#else
+      prod = val*i;
+#endif
+      if (fabs(prod-1) > .00025)
+      {
+         fprintf (stderr, "div failed: 1/%d="WORD" (product = %f)\n", i, val, prod);
+         ret = 1;
+      }
+   }
+}
+
+void testsqrt(void)
+{
+   opus_int32 i;
+   for (i=1;i<=1000000000;i++)
+   {
+      double ratio;
+      opus_val16 val;
+      val = celt_sqrt(i);
+      ratio = val/sqrt(i);
+      if (fabs(ratio - 1) > .0005 && fabs(val-sqrt(i)) > 2)
+      {
+         fprintf (stderr, "sqrt failed: sqrt(%d)="WORD" (ratio = %f)\n", i, val, ratio);
+         ret = 1;
+      }
+      i+= i>>10;
+   }
+}
+
+void testbitexactcos(void)
+{
+   int i;
+   opus_int32 min_d,max_d,last,chk;
+   chk=max_d=0;
+   last=min_d=32767;
+   for(i=64;i<=16320;i++)
+   {
+      opus_int32 d;
+      opus_int32 q=bitexact_cos(i);
+      chk ^= q*i;
+      d = last - q;
+      if (d>max_d)max_d=d;
+      if (d<min_d)min_d=d;
+      last = q;
+   }
+   if ((chk!=89408644)||(max_d!=5)||(min_d!=0)||(bitexact_cos(64)!=32767)||
+       (bitexact_cos(16320)!=200)||(bitexact_cos(8192)!=23171))
+   {
+      fprintf (stderr, "bitexact_cos failed\n");
+      ret = 1;
+   }
+}
+
+void testbitexactlog2tan(void)
+{
+   int i,fail;
+   opus_int32 min_d,max_d,last,chk;
+   fail=chk=max_d=0;
+   last=min_d=15059;
+   for(i=64;i<8193;i++)
+   {
+      opus_int32 d;
+      opus_int32 mid=bitexact_cos(i);
+      opus_int32 side=bitexact_cos(16384-i);
+      opus_int32 q=bitexact_log2tan(mid,side);
+      chk ^= q*i;
+      d = last - q;
+      if (q!=-1*bitexact_log2tan(side,mid))
+        fail = 1;
+      if (d>max_d)max_d=d;
+      if (d<min_d)min_d=d;
+      last = q;
+   }
+   if ((chk!=15821257)||(max_d!=61)||(min_d!=-2)||fail||
+       (bitexact_log2tan(32767,200)!=15059)||(bitexact_log2tan(30274,12540)!=2611)||
+       (bitexact_log2tan(23171,23171)!=0))
+   {
+      fprintf (stderr, "bitexact_log2tan failed\n");
+      ret = 1;
+   }
+}
+
+#ifndef FIXED_POINT
+void testlog2(void)
+{
+   float x;
+   for (x=0.001;x<1677700.0;x+=(x/8.0))
+   {
+      float error = fabs((1.442695040888963387*log(x))-celt_log2(x));
+      if (error>0.0009)
+      {
+         fprintf (stderr, "celt_log2 failed: fabs((1.442695040888963387*log(x))-celt_log2(x))>0.001 (x = %f, error = %f)\n", x,error);
+         ret = 1;
+      }
+   }
+}
+
+void testexp2(void)
+{
+   float x;
+   for (x=-11.0;x<24.0;x+=0.0007)
+   {
+      float error = fabs(x-(1.442695040888963387*log(celt_exp2(x))));
+      if (error>0.0002)
+      {
+         fprintf (stderr, "celt_exp2 failed: fabs(x-(1.442695040888963387*log(celt_exp2(x))))>0.0005 (x = %f, error = %f)\n", x,error);
+         ret = 1;
+      }
+   }
+}
+
+void testexp2log2(void)
+{
+   float x;
+   for (x=-11.0;x<24.0;x+=0.0007)
+   {
+      float error = fabs(x-(celt_log2(celt_exp2(x))));
+      if (error>0.001)
+      {
+         fprintf (stderr, "celt_log2/celt_exp2 failed: fabs(x-(celt_log2(celt_exp2(x))))>0.001 (x = %f, error = %f)\n", x,error);
+         ret = 1;
+      }
+   }
+}
+#else
+void testlog2(void)
+{
+   opus_val32 x;
+   for (x=8;x<1073741824;x+=(x>>3))
+   {
+      float error = fabs((1.442695040888963387*log(x/16384.0))-celt_log2(x)/1024.0);
+      if (error>0.003)
+      {
+         fprintf (stderr, "celt_log2 failed: x = %ld, error = %f\n", (long)x,error);
+         ret = 1;
+      }
+   }
+}
+
+void testexp2(void)
+{
+   opus_val16 x;
+   for (x=-32768;x<15360;x++)
+   {
+      float error1 = fabs(x/1024.0-(1.442695040888963387*log(celt_exp2(x)/65536.0)));
+      float error2 = fabs(exp(0.6931471805599453094*x/1024.0)-celt_exp2(x)/65536.0);
+      if (error1>0.0002&&error2>0.00004)
+      {
+         fprintf (stderr, "celt_exp2 failed: x = "WORD", error1 = %f, error2 = %f\n", x,error1,error2);
+         ret = 1;
+      }
+   }
+}
+
+void testexp2log2(void)
+{
+   opus_val32 x;
+   for (x=8;x<65536;x+=(x>>3))
+   {
+      float error = fabs(x-0.25*celt_exp2(celt_log2(x)))/16384;
+      if (error>0.004)
+      {
+         fprintf (stderr, "celt_log2/celt_exp2 failed: fabs(x-(celt_exp2(celt_log2(x))))>0.001 (x = %ld, error = %f)\n", (long)x,error);
+         ret = 1;
+      }
+   }
+}
+
+void testilog2(void)
+{
+   opus_val32 x;
+   for (x=1;x<=268435455;x+=127)
+   {
+      opus_val32 lg;
+      opus_val32 y;
+
+      lg = celt_ilog2(x);
+      if (lg<0 || lg>=31)
+      {
+         printf("celt_ilog2 failed: 0<=celt_ilog2(x)<31 (x = %d, celt_ilog2(x) = %d)\n",x,lg);
+         ret = 1;
+      }
+      y = 1<<lg;
+
+      if (x<y || (x>>1)>=y)
+      {
+         printf("celt_ilog2 failed: 2**celt_ilog2(x)<=x<2**(celt_ilog2(x)+1) (x = %d, 2**celt_ilog2(x) = %d)\n",x,y);
+         ret = 1;
+      }
+   }
+}
+#endif
+
+int main(void)
+{
+   testbitexactcos();
+   testbitexactlog2tan();
+   testdiv();
+   testsqrt();
+   testlog2();
+   testexp2();
+   testexp2log2();
+#ifdef FIXED_POINT
+   testilog2();
+#endif
+   return ret;
+}
diff --git a/opus/celt/tests/test_unit_mdct.c b/opus/celt/tests/test_unit_mdct.c
new file mode 100644 (file)
index 0000000..4a563cc
--- /dev/null
@@ -0,0 +1,227 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+
+#include "mdct.h"
+#include "stack_alloc.h"
+#include "kiss_fft.h"
+#include "mdct.h"
+#include "modes.h"
+
+#ifndef M_PI
+#define M_PI 3.141592653
+#endif
+
+int ret = 0;
+void check(kiss_fft_scalar  * in,kiss_fft_scalar  * out,int nfft,int isinverse)
+{
+    int bin,k;
+    double errpow=0,sigpow=0;
+    double snr;
+    for (bin=0;bin<nfft/2;++bin) {
+        double ansr = 0;
+        double difr;
+
+        for (k=0;k<nfft;++k) {
+           double phase = 2*M_PI*(k+.5+.25*nfft)*(bin+.5)/nfft;
+           double re = cos(phase);
+
+           re /= nfft/4;
+
+           ansr += in[k] * re;
+        }
+        /*printf ("%f %f\n", ansr, out[bin]);*/
+        difr = ansr - out[bin];
+        errpow += difr*difr;
+        sigpow += ansr*ansr;
+    }
+    snr = 10*log10(sigpow/errpow);
+    printf("nfft=%d inverse=%d,snr = %f\n",nfft,isinverse,snr );
+    if (snr<60) {
+       printf( "** poor snr: %f **\n", snr);
+       ret = 1;
+    }
+}
+
+void check_inv(kiss_fft_scalar  * in,kiss_fft_scalar  * out,int nfft,int isinverse)
+{
+   int bin,k;
+   double errpow=0,sigpow=0;
+   double snr;
+   for (bin=0;bin<nfft;++bin) {
+      double ansr = 0;
+      double difr;
+
+      for (k=0;k<nfft/2;++k) {
+         double phase = 2*M_PI*(bin+.5+.25*nfft)*(k+.5)/nfft;
+         double re = cos(phase);
+
+         /*re *= 2;*/
+
+         ansr += in[k] * re;
+      }
+      /*printf ("%f %f\n", ansr, out[bin]);*/
+      difr = ansr - out[bin];
+      errpow += difr*difr;
+      sigpow += ansr*ansr;
+   }
+   snr = 10*log10(sigpow/errpow);
+   printf("nfft=%d inverse=%d,snr = %f\n",nfft,isinverse,snr );
+   if (snr<60) {
+      printf( "** poor snr: %f **\n", snr);
+      ret = 1;
+   }
+}
+
+
+void test1d(int nfft,int isinverse,int arch)
+{
+    size_t buflen = sizeof(kiss_fft_scalar)*nfft;
+    kiss_fft_scalar *in;
+    kiss_fft_scalar *in_copy;
+    kiss_fft_scalar *out;
+    opus_val16 *window;
+    int k;
+
+#ifdef CUSTOM_MODES
+    int shift = 0;
+    const mdct_lookup *cfg;
+    mdct_lookup _cfg;
+    clt_mdct_init(&_cfg, nfft, 0, arch);
+    cfg = &_cfg;
+#else
+    int shift;
+    const mdct_lookup *cfg;
+    CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
+    if (nfft == 1920) shift = 0;
+    else if (nfft == 960) shift = 1;
+    else if (nfft == 480) shift = 2;
+    else if (nfft == 240) shift = 3;
+    else return;
+    cfg = &mode->mdct;
+#endif
+
+    in = (kiss_fft_scalar*)malloc(buflen);
+    in_copy = (kiss_fft_scalar*)malloc(buflen);
+    out = (kiss_fft_scalar*)malloc(buflen);
+    window = (opus_val16*)malloc(sizeof(opus_val16)*nfft/2);
+
+    for (k=0;k<nfft;++k) {
+        in[k] = (rand() % 32768) - 16384;
+    }
+
+    for (k=0;k<nfft/2;++k) {
+       window[k] = Q15ONE;
+    }
+    for (k=0;k<nfft;++k) {
+       in[k] *= 32768;
+    }
+
+    if (isinverse)
+    {
+       for (k=0;k<nfft;++k) {
+          in[k] /= nfft;
+       }
+    }
+
+    for (k=0;k<nfft;++k)
+       in_copy[k] = in[k];
+    /*for (k=0;k<nfft;++k) printf("%d %d ", in[k].r, in[k].i);printf("\n");*/
+
+    if (isinverse)
+    {
+       for (k=0;k<nfft;++k)
+          out[k] = 0;
+       clt_mdct_backward(cfg,in,out, window, nfft/2, shift, 1, arch);
+       /* apply TDAC because clt_mdct_backward() no longer does that */
+       for (k=0;k<nfft/4;++k)
+          out[nfft-k-1] = out[nfft/2+k];
+       check_inv(in,out,nfft,isinverse);
+    } else {
+       clt_mdct_forward(cfg,in,out,window, nfft/2, shift, 1, arch);
+       check(in_copy,out,nfft,isinverse);
+    }
+    /*for (k=0;k<nfft;++k) printf("%d %d ", out[k].r, out[k].i);printf("\n");*/
+
+
+    free(in);
+    free(in_copy);
+    free(out);
+    free(window);
+#ifdef CUSTOM_MODES
+    clt_mdct_clear(&_cfg, arch);
+#endif
+}
+
+int main(int argc,char ** argv)
+{
+    ALLOC_STACK;
+    int arch = opus_select_arch();
+
+    if (argc>1) {
+        int k;
+        for (k=1;k<argc;++k) {
+            test1d(atoi(argv[k]),0,arch);
+            test1d(atoi(argv[k]),1,arch);
+        }
+    }else{
+        test1d(32,0,arch);
+        test1d(32,1,arch);
+        test1d(256,0,arch);
+        test1d(256,1,arch);
+        test1d(512,0,arch);
+        test1d(512,1,arch);
+        test1d(1024,0,arch);
+        test1d(1024,1,arch);
+        test1d(2048,0,arch);
+        test1d(2048,1,arch);
+#ifndef RADIX_TWO_ONLY
+        test1d(36,0,arch);
+        test1d(36,1,arch);
+        test1d(40,0,arch);
+        test1d(40,1,arch);
+        test1d(60,0,arch);
+        test1d(60,1,arch);
+        test1d(120,0,arch);
+        test1d(120,1,arch);
+        test1d(240,0,arch);
+        test1d(240,1,arch);
+        test1d(480,0,arch);
+        test1d(480,1,arch);
+        test1d(960,0,arch);
+        test1d(960,1,arch);
+        test1d(1920,0,arch);
+        test1d(1920,1,arch);
+#endif
+    }
+    return ret;
+}
diff --git a/opus/celt/tests/test_unit_rotation.c b/opus/celt/tests/test_unit_rotation.c
new file mode 100644 (file)
index 0000000..267b983
--- /dev/null
@@ -0,0 +1,88 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifndef CUSTOM_MODES
+#define CUSTOM_MODES
+#endif
+
+#define CELT_C
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "vq.h"
+#include "bands.h"
+#include "stack_alloc.h"
+#include <math.h>
+
+
+#define MAX_SIZE 100
+
+int ret=0;
+void test_rotation(int N, int K)
+{
+   int i;
+   double err = 0, ener = 0, snr, snr0;
+   opus_val16 x0[MAX_SIZE];
+   opus_val16 x1[MAX_SIZE];
+   for (i=0;i<N;i++)
+      x1[i] = x0[i] = rand()%32767-16384;
+   exp_rotation(x1, N, 1, 1, K, SPREAD_NORMAL);
+   for (i=0;i<N;i++)
+   {
+      err += (x0[i]-(double)x1[i])*(x0[i]-(double)x1[i]);
+      ener += x0[i]*(double)x0[i];
+   }
+   snr0 = 20*log10(ener/err);
+   err = ener = 0;
+   exp_rotation(x1, N, -1, 1, K, SPREAD_NORMAL);
+   for (i=0;i<N;i++)
+   {
+      err += (x0[i]-(double)x1[i])*(x0[i]-(double)x1[i]);
+      ener += x0[i]*(double)x0[i];
+   }
+   snr = 20*log10(ener/err);
+   printf ("SNR for size %d (%d pulses) is %f (was %f without inverse)\n", N, K, snr, snr0);
+   if (snr < 60 || snr0 > 20)
+   {
+      fprintf(stderr, "FAIL!\n");
+      ret = 1;
+   }
+}
+
+int main(void)
+{
+   ALLOC_STACK;
+   test_rotation(15, 3);
+   test_rotation(23, 5);
+   test_rotation(50, 3);
+   test_rotation(80, 1);
+   return ret;
+}
diff --git a/opus/celt/tests/test_unit_types.c b/opus/celt/tests/test_unit_types.c
new file mode 100644 (file)
index 0000000..67a0fb8
--- /dev/null
@@ -0,0 +1,50 @@
+/* Copyright (c) 2008-2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_types.h"
+#include <stdio.h>
+
+int main(void)
+{
+   opus_int16 i = 1;
+   i <<= 14;
+   if (i>>14 != 1)
+   {
+      fprintf(stderr, "opus_int16 isn't 16 bits\n");
+      return 1;
+   }
+   if (sizeof(opus_int16)*2 != sizeof(opus_int32))
+   {
+      fprintf(stderr, "16*2 != 32\n");
+      return 1;
+   }
+   return 0;
+}
diff --git a/opus/celt/vq.c b/opus/celt/vq.c
new file mode 100644 (file)
index 0000000..8ef80e5
--- /dev/null
@@ -0,0 +1,438 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "mathops.h"
+#include "cwrs.h"
+#include "vq.h"
+#include "arch.h"
+#include "os_support.h"
+#include "bands.h"
+#include "rate.h"
+#include "pitch.h"
+
+#ifndef OVERRIDE_vq_exp_rotation1
+static void exp_rotation1(celt_norm *X, int len, int stride, opus_val16 c, opus_val16 s)
+{
+   int i;
+   opus_val16 ms;
+   celt_norm *Xptr;
+   Xptr = X;
+   ms = NEG16(s);
+   for (i=0;i<len-stride;i++)
+   {
+      celt_norm x1, x2;
+      x1 = Xptr[0];
+      x2 = Xptr[stride];
+      Xptr[stride] = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x2),  s, x1), 15));
+      *Xptr++      = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x1), ms, x2), 15));
+   }
+   Xptr = &X[len-2*stride-1];
+   for (i=len-2*stride-1;i>=0;i--)
+   {
+      celt_norm x1, x2;
+      x1 = Xptr[0];
+      x2 = Xptr[stride];
+      Xptr[stride] = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x2),  s, x1), 15));
+      *Xptr--      = EXTRACT16(PSHR32(MAC16_16(MULT16_16(c, x1), ms, x2), 15));
+   }
+}
+#endif /* OVERRIDE_vq_exp_rotation1 */
+
+void exp_rotation(celt_norm *X, int len, int dir, int stride, int K, int spread)
+{
+   static const int SPREAD_FACTOR[3]={15,10,5};
+   int i;
+   opus_val16 c, s;
+   opus_val16 gain, theta;
+   int stride2=0;
+   int factor;
+
+   if (2*K>=len || spread==SPREAD_NONE)
+      return;
+   factor = SPREAD_FACTOR[spread-1];
+
+   gain = celt_div((opus_val32)MULT16_16(Q15_ONE,len),(opus_val32)(len+factor*K));
+   theta = HALF16(MULT16_16_Q15(gain,gain));
+
+   c = celt_cos_norm(EXTEND32(theta));
+   s = celt_cos_norm(EXTEND32(SUB16(Q15ONE,theta))); /*  sin(theta) */
+
+   if (len>=8*stride)
+   {
+      stride2 = 1;
+      /* This is just a simple (equivalent) way of computing sqrt(len/stride) with rounding.
+         It's basically incrementing long as (stride2+0.5)^2 < len/stride. */
+      while ((stride2*stride2+stride2)*stride + (stride>>2) < len)
+         stride2++;
+   }
+   /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
+      extract_collapse_mask().*/
+   len = celt_udiv(len, stride);
+   for (i=0;i<stride;i++)
+   {
+      if (dir < 0)
+      {
+         if (stride2)
+            exp_rotation1(X+i*len, len, stride2, s, c);
+         exp_rotation1(X+i*len, len, 1, c, s);
+      } else {
+         exp_rotation1(X+i*len, len, 1, c, -s);
+         if (stride2)
+            exp_rotation1(X+i*len, len, stride2, s, -c);
+      }
+   }
+}
+
+/** 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 normalise_residual(int * OPUS_RESTRICT iy, celt_norm * OPUS_RESTRICT X,
+      int N, opus_val32 Ryy, opus_val16 gain)
+{
+   int i;
+#ifdef FIXED_POINT
+   int k;
+#endif
+   opus_val32 t;
+   opus_val16 g;
+
+#ifdef FIXED_POINT
+   k = celt_ilog2(Ryy)>>1;
+#endif
+   t = VSHR32(Ryy, 2*(k-7));
+   g = MULT16_16_P15(celt_rsqrt_norm(t),gain);
+
+   i=0;
+   do
+      X[i] = EXTRACT16(PSHR32(MULT16_16(g, iy[i]), k+1));
+   while (++i < N);
+}
+
+static unsigned extract_collapse_mask(int *iy, int N, int B)
+{
+   unsigned collapse_mask;
+   int N0;
+   int i;
+   if (B<=1)
+      return 1;
+   /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
+      exp_rotation().*/
+   N0 = celt_udiv(N, B);
+   collapse_mask = 0;
+   i=0; do {
+      int j;
+      unsigned tmp=0;
+      j=0; do {
+         tmp |= iy[i*N0+j];
+      } while (++j<N0);
+      collapse_mask |= (tmp!=0)<<i;
+   } while (++i<B);
+   return collapse_mask;
+}
+
+opus_val16 op_pvq_search_c(celt_norm *X, int *iy, int K, int N, int arch)
+{
+   VARDECL(celt_norm, y);
+   VARDECL(int, signx);
+   int i, j;
+   int pulsesLeft;
+   opus_val32 sum;
+   opus_val32 xy;
+   opus_val16 yy;
+   SAVE_STACK;
+
+   (void)arch;
+   ALLOC(y, N, celt_norm);
+   ALLOC(signx, N, int);
+
+   /* Get rid of the sign */
+   sum = 0;
+   j=0; do {
+      signx[j] = X[j]<0;
+      /* OPT: Make sure the compiler doesn't use a branch on ABS16(). */
+      X[j] = ABS16(X[j]);
+      iy[j] = 0;
+      y[j] = 0;
+   } while (++j<N);
+
+   xy = yy = 0;
+
+   pulsesLeft = K;
+
+   /* Do a pre-search by projecting on the pyramid */
+   if (K > (N>>1))
+   {
+      opus_val16 rcp;
+      j=0; do {
+         sum += X[j];
+      }  while (++j<N);
+
+      /* If X is too small, just replace it with a pulse at 0 */
+#ifdef FIXED_POINT
+      if (sum <= K)
+#else
+      /* Prevents infinities and NaNs from causing too many pulses
+         to be allocated. 64 is an approximation of infinity here. */
+      if (!(sum > EPSILON && sum < 64))
+#endif
+      {
+         X[0] = QCONST16(1.f,14);
+         j=1; do
+            X[j]=0;
+         while (++j<N);
+         sum = QCONST16(1.f,14);
+      }
+#ifdef FIXED_POINT
+      rcp = EXTRACT16(MULT16_32_Q16(K, celt_rcp(sum)));
+#else
+      /* Using K+e with e < 1 guarantees we cannot get more than K pulses. */
+      rcp = EXTRACT16(MULT16_32_Q16(K+0.8f, celt_rcp(sum)));
+#endif
+      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] = (int)floor(rcp*X[j]);
+#endif
+         y[j] = (celt_norm)iy[j];
+         yy = MAC16_16(yy, y[j],y[j]);
+         xy = MAC16_16(xy, X[j],y[j]);
+         y[j] *= 2;
+         pulsesLeft -= iy[j];
+      }  while (++j<N);
+   }
+   celt_assert2(pulsesLeft>=0, "Allocated too many pulses in the quick pass");
+
+   /* This should never happen, but just in case it does (e.g. on silence)
+      we fill the first bin with pulses. */
+#ifdef FIXED_POINT_DEBUG
+   celt_assert2(pulsesLeft<=N+3, "Not enough pulses in the quick pass");
+#endif
+   if (pulsesLeft > N+3)
+   {
+      opus_val16 tmp = (opus_val16)pulsesLeft;
+      yy = MAC16_16(yy, tmp, tmp);
+      yy = MAC16_16(yy, tmp, y[0]);
+      iy[0] += pulsesLeft;
+      pulsesLeft=0;
+   }
+
+   for (i=0;i<pulsesLeft;i++)
+   {
+      opus_val16 Rxy, Ryy;
+      int best_id;
+      opus_val32 best_num;
+      opus_val16 best_den;
+#ifdef FIXED_POINT
+      int rshift;
+#endif
+#ifdef FIXED_POINT
+      rshift = 1+celt_ilog2(K-pulsesLeft+i+1);
+#endif
+      best_id = 0;
+      /* The squared magnitude term gets added anyway, so we might as well
+         add it outside the loop */
+      yy = ADD16(yy, 1);
+
+      /* Calculations for position 0 are out of the loop, in part to reduce
+         mispredicted branches (since the if condition is usually false)
+         in the loop. */
+      /* Temporary sums of the new pulse(s) */
+      Rxy = EXTRACT16(SHR32(ADD32(xy, EXTEND32(X[0])),rshift));
+      /* We're multiplying y[j] by two so we don't have to do it here */
+      Ryy = ADD16(yy, y[0]);
+
+      /* 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);
+      best_den = Ryy;
+      best_num = Rxy;
+      j=1;
+      do {
+         /* Temporary sums of the new pulse(s) */
+         Rxy = EXTRACT16(SHR32(ADD32(xy, EXTEND32(X[j])),rshift));
+         /* We're multiplying y[j] by two so we don't have to do it here */
+         Ryy = ADD16(yy, y[j]);
+
+         /* 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: It's not clear whether a cmov is faster than a branch here
+            since the condition is more often false than true and using
+            a cmov introduces data dependencies across iterations. The optimal
+            choice may be architecture-dependent. */
+         if (opus_unlikely(MULT16_16(best_den, Rxy) > MULT16_16(Ryy, best_num)))
+         {
+            best_den = Ryy;
+            best_num = Rxy;
+            best_id = j;
+         }
+      } while (++j<N);
+
+      /* Updating the sums of the new pulse(s) */
+      xy = ADD32(xy, EXTEND32(X[best_id]));
+      /* We're multiplying y[j] by two so we don't have to do it here */
+      yy = ADD16(yy, y[best_id]);
+
+      /* 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[best_id] += 2;
+      iy[best_id]++;
+   }
+
+   /* Put the original sign back */
+   j=0;
+   do {
+      /*iy[j] = signx[j] ? -iy[j] : iy[j];*/
+      /* OPT: The is more likely to be compiled without a branch than the code above
+         but has the same performance otherwise. */
+      iy[j] = (iy[j]^-signx[j]) + signx[j];
+   } while (++j<N);
+   RESTORE_STACK;
+   return yy;
+}
+
+unsigned alg_quant(celt_norm *X, int N, int K, int spread, int B, ec_enc *enc,
+      opus_val16 gain, int resynth, int arch)
+{
+   VARDECL(int, iy);
+   opus_val16 yy;
+   unsigned collapse_mask;
+   SAVE_STACK;
+
+   celt_assert2(K>0, "alg_quant() needs at least one pulse");
+   celt_assert2(N>1, "alg_quant() needs at least two dimensions");
+
+   /* Covers vectorization by up to 4. */
+   ALLOC(iy, N+3, int);
+
+   exp_rotation(X, N, 1, B, K, spread);
+
+   yy = op_pvq_search(X, iy, K, N, arch);
+
+   encode_pulses(iy, N, K, enc);
+
+   if (resynth)
+   {
+      normalise_residual(iy, X, N, yy, gain);
+      exp_rotation(X, N, -1, B, K, spread);
+   }
+
+   collapse_mask = extract_collapse_mask(iy, N, B);
+   RESTORE_STACK;
+   return collapse_mask;
+}
+
+/** Decode pulse vector and combine the result with the pitch vector to produce
+    the final normalised signal in the current band. */
+unsigned alg_unquant(celt_norm *X, int N, int K, int spread, int B,
+      ec_dec *dec, opus_val16 gain)
+{
+   opus_val32 Ryy;
+   unsigned collapse_mask;
+   VARDECL(int, iy);
+   SAVE_STACK;
+
+   celt_assert2(K>0, "alg_unquant() needs at least one pulse");
+   celt_assert2(N>1, "alg_unquant() needs at least two dimensions");
+   ALLOC(iy, N, int);
+   Ryy = decode_pulses(iy, N, K, dec);
+   normalise_residual(iy, X, N, Ryy, gain);
+   exp_rotation(X, N, -1, B, K, spread);
+   collapse_mask = extract_collapse_mask(iy, N, B);
+   RESTORE_STACK;
+   return collapse_mask;
+}
+
+#ifndef OVERRIDE_renormalise_vector
+void renormalise_vector(celt_norm *X, int N, opus_val16 gain, int arch)
+{
+   int i;
+#ifdef FIXED_POINT
+   int k;
+#endif
+   opus_val32 E;
+   opus_val16 g;
+   opus_val32 t;
+   celt_norm *xptr;
+   E = EPSILON + celt_inner_prod(X, X, N, arch);
+#ifdef FIXED_POINT
+   k = celt_ilog2(E)>>1;
+#endif
+   t = VSHR32(E, 2*(k-7));
+   g = MULT16_16_P15(celt_rsqrt_norm(t),gain);
+
+   xptr = X;
+   for (i=0;i<N;i++)
+   {
+      *xptr = EXTRACT16(PSHR32(MULT16_16(g, *xptr), k+1));
+      xptr++;
+   }
+   /*return celt_sqrt(E);*/
+}
+#endif /* OVERRIDE_renormalise_vector */
+
+int stereo_itheta(const celt_norm *X, const celt_norm *Y, int stereo, int N, int arch)
+{
+   int i;
+   int itheta;
+   opus_val16 mid, side;
+   opus_val32 Emid, Eside;
+
+   Emid = Eside = EPSILON;
+   if (stereo)
+   {
+      for (i=0;i<N;i++)
+      {
+         celt_norm m, s;
+         m = ADD16(SHR16(X[i],1),SHR16(Y[i],1));
+         s = SUB16(SHR16(X[i],1),SHR16(Y[i],1));
+         Emid = MAC16_16(Emid, m, m);
+         Eside = MAC16_16(Eside, s, s);
+      }
+   } else {
+      Emid += celt_inner_prod(X, X, N, arch);
+      Eside += celt_inner_prod(Y, Y, N, arch);
+   }
+   mid = celt_sqrt(Emid);
+   side = celt_sqrt(Eside);
+#ifdef FIXED_POINT
+   /* 0.63662 = 2/pi */
+   itheta = MULT16_16_Q15(QCONST16(0.63662f,15),celt_atan2p(side, mid));
+#else
+   itheta = (int)floor(.5f+16384*0.63662f*fast_atan2f(side,mid));
+#endif
+
+   return itheta;
+}
diff --git a/opus/celt/vq.h b/opus/celt/vq.h
new file mode 100644 (file)
index 0000000..0dfe6af
--- /dev/null
@@ -0,0 +1,83 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by Jean-Marc Valin */
+/**
+   @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.
+
+   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 VQ_H
+#define VQ_H
+
+#include "entenc.h"
+#include "entdec.h"
+#include "modes.h"
+
+#if (defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(FIXED_POINT))
+#include "x86/vq_sse.h"
+#endif
+
+#if defined(MIPSr1_ASM)
+#include "mips/vq_mipsr1.h"
+#endif
+
+void exp_rotation(celt_norm *X, int len, int dir, int stride, int K, int spread);
+
+opus_val16 op_pvq_search_c(celt_norm *X, int *iy, int K, int N, int arch);
+
+#if !defined(OVERRIDE_OP_PVQ_SEARCH)
+#define op_pvq_search(x, iy, K, N, arch) \
+    (op_pvq_search_c(x, iy, K, N, arch))
+#endif
+
+/** 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 N Number of samples to encode
+ * @param K Number of pulses to use
+ * @param enc Entropy encoder state
+ * @ret A mask indicating which blocks in the band received pulses
+*/
+unsigned alg_quant(celt_norm *X, int N, int K, int spread, int B, ec_enc *enc,
+      opus_val16 gain, int resynth, int arch);
+
+/** Algebraic pulse decoder
+ * @param X Decoded normalised spectrum (returned)
+ * @param N Number of samples to decode
+ * @param K Number of pulses to use
+ * @param dec Entropy decoder state
+ * @ret A mask indicating which blocks in the band received pulses
+ */
+unsigned alg_unquant(celt_norm *X, int N, int K, int spread, int B,
+      ec_dec *dec, opus_val16 gain);
+
+void renormalise_vector(celt_norm *X, int N, opus_val16 gain, int arch);
+
+int stereo_itheta(const celt_norm *X, const celt_norm *Y, int stereo, int N, int arch);
+
+#endif /* VQ_H */
diff --git a/opus/celt/x86/celt_lpc_sse.c b/opus/celt/x86/celt_lpc_sse.c
new file mode 100644 (file)
index 0000000..5478568
--- /dev/null
@@ -0,0 +1,89 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "pitch.h"
+#include "x86cpu.h"
+
+#if defined(FIXED_POINT)
+
+void celt_fir_sse4_1(const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         int ord,
+         int arch)
+{
+    int i,j;
+    VARDECL(opus_val16, rnum);
+
+    __m128i vecNoA;
+    opus_int32 noA ;
+    SAVE_STACK;
+
+   ALLOC(rnum, ord, opus_val16);
+   for(i=0;i<ord;i++)
+      rnum[i] = num[ord-i-1];
+   noA = EXTEND32(1) << SIG_SHIFT >> 1;
+   vecNoA = _mm_set_epi32(noA, noA, noA, noA);
+
+   for (i=0;i<N-3;i+=4)
+   {
+      opus_val32 sums[4] = {0};
+      __m128i vecSum, vecX;
+
+      xcorr_kernel(rnum, x+i-ord, sums, ord, arch);
+
+      vecSum = _mm_loadu_si128((__m128i *)sums);
+      vecSum = _mm_add_epi32(vecSum, vecNoA);
+      vecSum = _mm_srai_epi32(vecSum, SIG_SHIFT);
+      vecX = OP_CVTEPI16_EPI32_M64(x + i);
+      vecSum = _mm_add_epi32(vecSum, vecX);
+      vecSum = _mm_packs_epi32(vecSum, vecSum);
+      _mm_storel_epi64((__m128i *)(y + i), vecSum);
+   }
+   for (;i<N;i++)
+   {
+      opus_val32 sum = 0;
+      for (j=0;j<ord;j++)
+         sum = MAC16_16(sum, rnum[j], x[i+j-ord]);
+      y[i] = SATURATE16(ADD32(EXTEND32(x[i]), PSHR32(sum, SIG_SHIFT)));
+   }
+
+   RESTORE_STACK;
+}
+
+#endif
diff --git a/opus/celt/x86/celt_lpc_sse.h b/opus/celt/x86/celt_lpc_sse.h
new file mode 100644 (file)
index 0000000..7d1ecf7
--- /dev/null
@@ -0,0 +1,66 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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 CELT_LPC_SSE_H
+#define CELT_LPC_SSE_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1) && defined(FIXED_POINT)
+#define OVERRIDE_CELT_FIR
+
+void celt_fir_sse4_1(
+         const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         int ord,
+         int arch);
+
+#if defined(OPUS_X86_PRESUME_SSE4_1)
+#define celt_fir(x, num, y, N, ord, arch) \
+    ((void)arch, celt_fir_sse4_1(x, num, y, N, ord, arch))
+
+#else
+
+extern void (*const CELT_FIR_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16 *y,
+         int N,
+         int ord,
+         int arch);
+
+#  define celt_fir(x, num, y, N, ord, arch) \
+    ((*CELT_FIR_IMPL[(arch) & OPUS_ARCHMASK])(x, num, y, N, ord, arch))
+
+#endif
+#endif
+
+#endif
diff --git a/opus/celt/x86/pitch_sse.c b/opus/celt/x86/pitch_sse.c
new file mode 100644 (file)
index 0000000..20e7312
--- /dev/null
@@ -0,0 +1,185 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "macros.h"
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "pitch.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT)
+
+#include <xmmintrin.h>
+#include "arch.h"
+
+void xcorr_kernel_sse(const opus_val16 *x, const opus_val16 *y, opus_val32 sum[4], int len)
+{
+   int j;
+   __m128 xsum1, xsum2;
+   xsum1 = _mm_loadu_ps(sum);
+   xsum2 = _mm_setzero_ps();
+
+   for (j = 0; j < len-3; j += 4)
+   {
+      __m128 x0 = _mm_loadu_ps(x+j);
+      __m128 yj = _mm_loadu_ps(y+j);
+      __m128 y3 = _mm_loadu_ps(y+j+3);
+
+      xsum1 = _mm_add_ps(xsum1,_mm_mul_ps(_mm_shuffle_ps(x0,x0,0x00),yj));
+      xsum2 = _mm_add_ps(xsum2,_mm_mul_ps(_mm_shuffle_ps(x0,x0,0x55),
+                                          _mm_shuffle_ps(yj,y3,0x49)));
+      xsum1 = _mm_add_ps(xsum1,_mm_mul_ps(_mm_shuffle_ps(x0,x0,0xaa),
+                                          _mm_shuffle_ps(yj,y3,0x9e)));
+      xsum2 = _mm_add_ps(xsum2,_mm_mul_ps(_mm_shuffle_ps(x0,x0,0xff),y3));
+   }
+   if (j < len)
+   {
+      xsum1 = _mm_add_ps(xsum1,_mm_mul_ps(_mm_load1_ps(x+j),_mm_loadu_ps(y+j)));
+      if (++j < len)
+      {
+         xsum2 = _mm_add_ps(xsum2,_mm_mul_ps(_mm_load1_ps(x+j),_mm_loadu_ps(y+j)));
+         if (++j < len)
+         {
+            xsum1 = _mm_add_ps(xsum1,_mm_mul_ps(_mm_load1_ps(x+j),_mm_loadu_ps(y+j)));
+         }
+      }
+   }
+   _mm_storeu_ps(sum,_mm_add_ps(xsum1,xsum2));
+}
+
+
+void dual_inner_prod_sse(const opus_val16 *x, const opus_val16 *y01, const opus_val16 *y02,
+      int N, opus_val32 *xy1, opus_val32 *xy2)
+{
+   int i;
+   __m128 xsum1, xsum2;
+   xsum1 = _mm_setzero_ps();
+   xsum2 = _mm_setzero_ps();
+   for (i=0;i<N-3;i+=4)
+   {
+      __m128 xi = _mm_loadu_ps(x+i);
+      __m128 y1i = _mm_loadu_ps(y01+i);
+      __m128 y2i = _mm_loadu_ps(y02+i);
+      xsum1 = _mm_add_ps(xsum1,_mm_mul_ps(xi, y1i));
+      xsum2 = _mm_add_ps(xsum2,_mm_mul_ps(xi, y2i));
+   }
+   /* Horizontal sum */
+   xsum1 = _mm_add_ps(xsum1, _mm_movehl_ps(xsum1, xsum1));
+   xsum1 = _mm_add_ss(xsum1, _mm_shuffle_ps(xsum1, xsum1, 0x55));
+   _mm_store_ss(xy1, xsum1);
+   xsum2 = _mm_add_ps(xsum2, _mm_movehl_ps(xsum2, xsum2));
+   xsum2 = _mm_add_ss(xsum2, _mm_shuffle_ps(xsum2, xsum2, 0x55));
+   _mm_store_ss(xy2, xsum2);
+   for (;i<N;i++)
+   {
+      *xy1 = MAC16_16(*xy1, x[i], y01[i]);
+      *xy2 = MAC16_16(*xy2, x[i], y02[i]);
+   }
+}
+
+opus_val32 celt_inner_prod_sse(const opus_val16 *x, const opus_val16 *y,
+      int N)
+{
+   int i;
+   float xy;
+   __m128 sum;
+   sum = _mm_setzero_ps();
+   /* FIXME: We should probably go 8-way and use 2 sums. */
+   for (i=0;i<N-3;i+=4)
+   {
+      __m128 xi = _mm_loadu_ps(x+i);
+      __m128 yi = _mm_loadu_ps(y+i);
+      sum = _mm_add_ps(sum,_mm_mul_ps(xi, yi));
+   }
+   /* Horizontal sum */
+   sum = _mm_add_ps(sum, _mm_movehl_ps(sum, sum));
+   sum = _mm_add_ss(sum, _mm_shuffle_ps(sum, sum, 0x55));
+   _mm_store_ss(&xy, sum);
+   for (;i<N;i++)
+   {
+      xy = MAC16_16(xy, x[i], y[i]);
+   }
+   return xy;
+}
+
+void comb_filter_const_sse(opus_val32 *y, opus_val32 *x, int T, int N,
+      opus_val16 g10, opus_val16 g11, opus_val16 g12)
+{
+   int i;
+   __m128 x0v;
+   __m128 g10v, g11v, g12v;
+   g10v = _mm_load1_ps(&g10);
+   g11v = _mm_load1_ps(&g11);
+   g12v = _mm_load1_ps(&g12);
+   x0v = _mm_loadu_ps(&x[-T-2]);
+   for (i=0;i<N-3;i+=4)
+   {
+      __m128 yi, yi2, x1v, x2v, x3v, x4v;
+      const opus_val32 *xp = &x[i-T-2];
+      yi = _mm_loadu_ps(x+i);
+      x4v = _mm_loadu_ps(xp+4);
+#if 0
+      /* Slower version with all loads */
+      x1v = _mm_loadu_ps(xp+1);
+      x2v = _mm_loadu_ps(xp+2);
+      x3v = _mm_loadu_ps(xp+3);
+#else
+      x2v = _mm_shuffle_ps(x0v, x4v, 0x4e);
+      x1v = _mm_shuffle_ps(x0v, x2v, 0x99);
+      x3v = _mm_shuffle_ps(x2v, x4v, 0x99);
+#endif
+
+      yi = _mm_add_ps(yi, _mm_mul_ps(g10v,x2v));
+#if 0 /* Set to 1 to make it bit-exact with the non-SSE version */
+      yi = _mm_add_ps(yi, _mm_mul_ps(g11v,_mm_add_ps(x3v,x1v)));
+      yi = _mm_add_ps(yi, _mm_mul_ps(g12v,_mm_add_ps(x4v,x0v)));
+#else
+      /* Use partial sums */
+      yi2 = _mm_add_ps(_mm_mul_ps(g11v,_mm_add_ps(x3v,x1v)),
+                       _mm_mul_ps(g12v,_mm_add_ps(x4v,x0v)));
+      yi = _mm_add_ps(yi, yi2);
+#endif
+      x0v=x4v;
+      _mm_storeu_ps(y+i, yi);
+   }
+#ifdef CUSTOM_MODES
+   for (;i<N;i++)
+   {
+      y[i] = x[i]
+               + MULT16_32_Q15(g10,x[i-T])
+               + MULT16_32_Q15(g11,ADD32(x[i-T+1],x[i-T-1]))
+               + MULT16_32_Q15(g12,ADD32(x[i-T+2],x[i-T-2]));
+   }
+#endif
+}
+
+
+#endif
diff --git a/opus/celt/x86/pitch_sse.h b/opus/celt/x86/pitch_sse.h
new file mode 100644 (file)
index 0000000..e5f87ab
--- /dev/null
@@ -0,0 +1,192 @@
+/* Copyright (c) 2013 Jean-Marc Valin and John Ridges
+   Copyright (c) 2014, Cisco Systems, INC MingXiang WeiZhou MinPeng YanWang*/
+/**
+   @file pitch_sse.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.
+
+   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 PITCH_SSE_H
+#define PITCH_SSE_H
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1) && defined(FIXED_POINT)
+void xcorr_kernel_sse4_1(
+                    const opus_int16 *x,
+                    const opus_int16 *y,
+                    opus_val32       sum[4],
+                    int              len);
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT)
+void xcorr_kernel_sse(
+                    const opus_val16 *x,
+                    const opus_val16 *y,
+                    opus_val32       sum[4],
+                    int              len);
+#endif
+
+#if defined(OPUS_X86_PRESUME_SSE4_1) && defined(FIXED_POINT)
+#define OVERRIDE_XCORR_KERNEL
+#define xcorr_kernel(x, y, sum, len, arch) \
+    ((void)arch, xcorr_kernel_sse4_1(x, y, sum, len))
+
+#elif defined(OPUS_X86_PRESUME_SSE) && !defined(FIXED_POINT)
+#define OVERRIDE_XCORR_KERNEL
+#define xcorr_kernel(x, y, sum, len, arch) \
+    ((void)arch, xcorr_kernel_sse(x, y, sum, len))
+
+#elif (defined(OPUS_X86_MAY_HAVE_SSE4_1) && defined(FIXED_POINT)) || (defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT))
+
+extern void (*const XCORR_KERNEL_IMPL[OPUS_ARCHMASK + 1])(
+                    const opus_val16 *x,
+                    const opus_val16 *y,
+                    opus_val32       sum[4],
+                    int              len);
+
+#define OVERRIDE_XCORR_KERNEL
+#define xcorr_kernel(x, y, sum, len, arch) \
+    ((*XCORR_KERNEL_IMPL[(arch) & OPUS_ARCHMASK])(x, y, sum, len))
+
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1) && defined(FIXED_POINT)
+opus_val32 celt_inner_prod_sse4_1(
+    const opus_int16 *x,
+    const opus_int16 *y,
+    int               N);
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE2) && defined(FIXED_POINT)
+opus_val32 celt_inner_prod_sse2(
+    const opus_int16 *x,
+    const opus_int16 *y,
+    int               N);
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(FIXED_POINT)
+opus_val32 celt_inner_prod_sse(
+    const opus_val16 *x,
+    const opus_val16 *y,
+    int               N);
+#endif
+
+
+#if defined(OPUS_X86_PRESUME_SSE4_1) && defined(FIXED_POINT)
+#define OVERRIDE_CELT_INNER_PROD
+#define celt_inner_prod(x, y, N, arch) \
+    ((void)arch, celt_inner_prod_sse4_1(x, y, N))
+
+#elif defined(OPUS_X86_PRESUME_SSE2) && defined(FIXED_POINT) && !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#define OVERRIDE_CELT_INNER_PROD
+#define celt_inner_prod(x, y, N, arch) \
+    ((void)arch, celt_inner_prod_sse2(x, y, N))
+
+#elif defined(OPUS_X86_PRESUME_SSE) && !defined(FIXED_POINT)
+#define OVERRIDE_CELT_INNER_PROD
+#define celt_inner_prod(x, y, N, arch) \
+    ((void)arch, celt_inner_prod_sse(x, y, N))
+
+
+#elif ((defined(OPUS_X86_MAY_HAVE_SSE4_1) || defined(OPUS_X86_MAY_HAVE_SSE2)) && defined(FIXED_POINT)) || \
+    (defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT))
+
+extern opus_val32 (*const CELT_INNER_PROD_IMPL[OPUS_ARCHMASK + 1])(
+                    const opus_val16 *x,
+                    const opus_val16 *y,
+                    int               N);
+
+#define OVERRIDE_CELT_INNER_PROD
+#define celt_inner_prod(x, y, N, arch) \
+    ((*CELT_INNER_PROD_IMPL[(arch) & OPUS_ARCHMASK])(x, y, N))
+
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE) && !defined(FIXED_POINT)
+
+#define OVERRIDE_DUAL_INNER_PROD
+#define OVERRIDE_COMB_FILTER_CONST
+
+#undef dual_inner_prod
+#undef comb_filter_const
+
+void dual_inner_prod_sse(const opus_val16 *x,
+    const opus_val16 *y01,
+    const opus_val16 *y02,
+    int               N,
+    opus_val32       *xy1,
+    opus_val32       *xy2);
+
+void comb_filter_const_sse(opus_val32 *y,
+    opus_val32 *x,
+    int         T,
+    int         N,
+    opus_val16  g10,
+    opus_val16  g11,
+    opus_val16  g12);
+
+
+#if defined(OPUS_X86_PRESUME_SSE)
+# define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) \
+    ((void)(arch),dual_inner_prod_sse(x, y01, y02, N, xy1, xy2))
+
+# define comb_filter_const(y, x, T, N, g10, g11, g12, arch) \
+    ((void)(arch),comb_filter_const_sse(y, x, T, N, g10, g11, g12))
+#else
+
+extern void (*const DUAL_INNER_PROD_IMPL[OPUS_ARCHMASK + 1])(
+              const opus_val16 *x,
+              const opus_val16 *y01,
+              const opus_val16 *y02,
+              int               N,
+              opus_val32       *xy1,
+              opus_val32       *xy2);
+
+#define dual_inner_prod(x, y01, y02, N, xy1, xy2, arch) \
+    ((*DUAL_INNER_PROD_IMPL[(arch) & OPUS_ARCHMASK])(x, y01, y02, N, xy1, xy2))
+
+extern void (*const COMB_FILTER_CONST_IMPL[OPUS_ARCHMASK + 1])(
+              opus_val32 *y,
+              opus_val32 *x,
+              int         T,
+              int         N,
+              opus_val16  g10,
+              opus_val16  g11,
+              opus_val16  g12);
+
+#define comb_filter_const(y, x, T, N, g10, g11, g12, arch) \
+    ((*COMB_FILTER_CONST_IMPL[(arch) & OPUS_ARCHMASK])(y, x, T, N, g10, g11, g12))
+
+#define NON_STATIC_COMB_FILTER_CONST_C
+
+#endif
+#endif
+
+#endif
diff --git a/opus/celt/x86/pitch_sse2.c b/opus/celt/x86/pitch_sse2.c
new file mode 100644 (file)
index 0000000..a0e7d1b
--- /dev/null
@@ -0,0 +1,95 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+
+#include "macros.h"
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "pitch.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE2) && defined(FIXED_POINT)
+opus_val32 celt_inner_prod_sse2(const opus_val16 *x, const opus_val16 *y,
+      int N)
+{
+    opus_int  i, dataSize16;
+    opus_int32 sum;
+
+    __m128i inVec1_76543210, inVec1_FEDCBA98, acc1;
+    __m128i inVec2_76543210, inVec2_FEDCBA98, acc2;
+
+    sum = 0;
+    dataSize16 = N & ~15;
+
+    acc1 = _mm_setzero_si128();
+    acc2 = _mm_setzero_si128();
+
+    for (i=0;i<dataSize16;i+=16)
+    {
+        inVec1_76543210 = _mm_loadu_si128((__m128i *)(&x[i + 0]));
+        inVec2_76543210 = _mm_loadu_si128((__m128i *)(&y[i + 0]));
+
+        inVec1_FEDCBA98 = _mm_loadu_si128((__m128i *)(&x[i + 8]));
+        inVec2_FEDCBA98 = _mm_loadu_si128((__m128i *)(&y[i + 8]));
+
+        inVec1_76543210 = _mm_madd_epi16(inVec1_76543210, inVec2_76543210);
+        inVec1_FEDCBA98 = _mm_madd_epi16(inVec1_FEDCBA98, inVec2_FEDCBA98);
+
+        acc1 = _mm_add_epi32(acc1, inVec1_76543210);
+        acc2 = _mm_add_epi32(acc2, inVec1_FEDCBA98);
+    }
+
+    acc1 = _mm_add_epi32( acc1, acc2 );
+
+    if (N - i >= 8)
+    {
+        inVec1_76543210 = _mm_loadu_si128((__m128i *)(&x[i + 0]));
+        inVec2_76543210 = _mm_loadu_si128((__m128i *)(&y[i + 0]));
+
+        inVec1_76543210 = _mm_madd_epi16(inVec1_76543210, inVec2_76543210);
+
+        acc1 = _mm_add_epi32(acc1, inVec1_76543210);
+        i += 8;
+    }
+
+    acc1 = _mm_add_epi32(acc1, _mm_unpackhi_epi64( acc1, acc1));
+    acc1 = _mm_add_epi32(acc1, _mm_shufflelo_epi16( acc1, 0x0E));
+    sum += _mm_cvtsi128_si32(acc1);
+
+    for (;i<N;i++) {
+        sum = silk_SMLABB(sum, x[i], y[i]);
+    }
+
+    return sum;
+}
+#endif
diff --git a/opus/celt/x86/pitch_sse4_1.c b/opus/celt/x86/pitch_sse4_1.c
new file mode 100644 (file)
index 0000000..a092c68
--- /dev/null
@@ -0,0 +1,195 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+
+#include "macros.h"
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "pitch.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1) && defined(FIXED_POINT)
+#include <smmintrin.h>
+#include "x86cpu.h"
+
+opus_val32 celt_inner_prod_sse4_1(const opus_val16 *x, const opus_val16 *y,
+      int N)
+{
+    opus_int  i, dataSize16;
+    opus_int32 sum;
+    __m128i inVec1_76543210, inVec1_FEDCBA98, acc1;
+    __m128i inVec2_76543210, inVec2_FEDCBA98, acc2;
+    __m128i inVec1_3210, inVec2_3210;
+
+    sum = 0;
+    dataSize16 = N & ~15;
+
+    acc1 = _mm_setzero_si128();
+    acc2 = _mm_setzero_si128();
+
+    for (i=0;i<dataSize16;i+=16) {
+        inVec1_76543210 = _mm_loadu_si128((__m128i *)(&x[i + 0]));
+        inVec2_76543210 = _mm_loadu_si128((__m128i *)(&y[i + 0]));
+
+        inVec1_FEDCBA98 = _mm_loadu_si128((__m128i *)(&x[i + 8]));
+        inVec2_FEDCBA98 = _mm_loadu_si128((__m128i *)(&y[i + 8]));
+
+        inVec1_76543210 = _mm_madd_epi16(inVec1_76543210, inVec2_76543210);
+        inVec1_FEDCBA98 = _mm_madd_epi16(inVec1_FEDCBA98, inVec2_FEDCBA98);
+
+        acc1 = _mm_add_epi32(acc1, inVec1_76543210);
+        acc2 = _mm_add_epi32(acc2, inVec1_FEDCBA98);
+    }
+
+    acc1 = _mm_add_epi32(acc1, acc2);
+
+    if (N - i >= 8)
+    {
+        inVec1_76543210 = _mm_loadu_si128((__m128i *)(&x[i + 0]));
+        inVec2_76543210 = _mm_loadu_si128((__m128i *)(&y[i + 0]));
+
+        inVec1_76543210 = _mm_madd_epi16(inVec1_76543210, inVec2_76543210);
+
+        acc1 = _mm_add_epi32(acc1, inVec1_76543210);
+        i += 8;
+    }
+
+    if (N - i >= 4)
+    {
+        inVec1_3210 = OP_CVTEPI16_EPI32_M64(&x[i + 0]);
+        inVec2_3210 = OP_CVTEPI16_EPI32_M64(&y[i + 0]);
+
+        inVec1_3210 = _mm_mullo_epi32(inVec1_3210, inVec2_3210);
+
+        acc1 = _mm_add_epi32(acc1, inVec1_3210);
+        i += 4;
+    }
+
+    acc1 = _mm_add_epi32(acc1, _mm_unpackhi_epi64(acc1, acc1));
+    acc1 = _mm_add_epi32(acc1, _mm_shufflelo_epi16(acc1, 0x0E));
+
+    sum += _mm_cvtsi128_si32(acc1);
+
+    for (;i<N;i++)
+    {
+        sum = silk_SMLABB(sum, x[i], y[i]);
+    }
+
+    return sum;
+}
+
+void xcorr_kernel_sse4_1(const opus_val16 * x, const opus_val16 * y, opus_val32 sum[ 4 ], int len)
+{
+    int j;
+
+    __m128i vecX, vecX0, vecX1, vecX2, vecX3;
+    __m128i vecY0, vecY1, vecY2, vecY3;
+    __m128i sum0, sum1, sum2, sum3, vecSum;
+    __m128i initSum;
+
+    celt_assert(len >= 3);
+
+    sum0 = _mm_setzero_si128();
+    sum1 = _mm_setzero_si128();
+    sum2 = _mm_setzero_si128();
+    sum3 = _mm_setzero_si128();
+
+    for (j=0;j<(len-7);j+=8)
+    {
+        vecX = _mm_loadu_si128((__m128i *)(&x[j + 0]));
+        vecY0 = _mm_loadu_si128((__m128i *)(&y[j + 0]));
+        vecY1 = _mm_loadu_si128((__m128i *)(&y[j + 1]));
+        vecY2 = _mm_loadu_si128((__m128i *)(&y[j + 2]));
+        vecY3 = _mm_loadu_si128((__m128i *)(&y[j + 3]));
+
+        sum0 = _mm_add_epi32(sum0, _mm_madd_epi16(vecX, vecY0));
+        sum1 = _mm_add_epi32(sum1, _mm_madd_epi16(vecX, vecY1));
+        sum2 = _mm_add_epi32(sum2, _mm_madd_epi16(vecX, vecY2));
+        sum3 = _mm_add_epi32(sum3, _mm_madd_epi16(vecX, vecY3));
+    }
+
+    sum0 = _mm_add_epi32(sum0, _mm_unpackhi_epi64( sum0, sum0));
+    sum0 = _mm_add_epi32(sum0, _mm_shufflelo_epi16( sum0, 0x0E));
+
+    sum1 = _mm_add_epi32(sum1, _mm_unpackhi_epi64( sum1, sum1));
+    sum1 = _mm_add_epi32(sum1, _mm_shufflelo_epi16( sum1, 0x0E));
+
+    sum2 = _mm_add_epi32(sum2, _mm_unpackhi_epi64( sum2, sum2));
+    sum2 = _mm_add_epi32(sum2, _mm_shufflelo_epi16( sum2, 0x0E));
+
+    sum3 = _mm_add_epi32(sum3, _mm_unpackhi_epi64( sum3, sum3));
+    sum3 = _mm_add_epi32(sum3, _mm_shufflelo_epi16( sum3, 0x0E));
+
+    vecSum = _mm_unpacklo_epi64(_mm_unpacklo_epi32(sum0, sum1),
+          _mm_unpacklo_epi32(sum2, sum3));
+
+    for (;j<(len-3);j+=4)
+    {
+        vecX = OP_CVTEPI16_EPI32_M64(&x[j + 0]);
+        vecX0 = _mm_shuffle_epi32(vecX, 0x00);
+        vecX1 = _mm_shuffle_epi32(vecX, 0x55);
+        vecX2 = _mm_shuffle_epi32(vecX, 0xaa);
+        vecX3 = _mm_shuffle_epi32(vecX, 0xff);
+
+        vecY0 = OP_CVTEPI16_EPI32_M64(&y[j + 0]);
+        vecY1 = OP_CVTEPI16_EPI32_M64(&y[j + 1]);
+        vecY2 = OP_CVTEPI16_EPI32_M64(&y[j + 2]);
+        vecY3 = OP_CVTEPI16_EPI32_M64(&y[j + 3]);
+
+        sum0 = _mm_mullo_epi32(vecX0, vecY0);
+        sum1 = _mm_mullo_epi32(vecX1, vecY1);
+        sum2 = _mm_mullo_epi32(vecX2, vecY2);
+        sum3 = _mm_mullo_epi32(vecX3, vecY3);
+
+        sum0 = _mm_add_epi32(sum0, sum1);
+        sum2 = _mm_add_epi32(sum2, sum3);
+        vecSum = _mm_add_epi32(vecSum, sum0);
+        vecSum = _mm_add_epi32(vecSum, sum2);
+    }
+
+    for (;j<len;j++)
+    {
+        vecX = OP_CVTEPI16_EPI32_M64(&x[j + 0]);
+        vecX0 = _mm_shuffle_epi32(vecX, 0x00);
+
+        vecY0 = OP_CVTEPI16_EPI32_M64(&y[j + 0]);
+
+        sum0 = _mm_mullo_epi32(vecX0, vecY0);
+        vecSum = _mm_add_epi32(vecSum, sum0);
+    }
+
+    initSum = _mm_loadu_si128((__m128i *)(&sum[0]));
+    initSum = _mm_add_epi32(initSum, vecSum);
+    _mm_storeu_si128((__m128i *)sum, initSum);
+}
+#endif
diff --git a/opus/celt/x86/vq_sse.h b/opus/celt/x86/vq_sse.h
new file mode 100644 (file)
index 0000000..b4efe8f
--- /dev/null
@@ -0,0 +1,50 @@
+/* Copyright (c) 2016  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.
+
+   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 VQ_SSE_H
+#define VQ_SSE_H
+
+#if defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(FIXED_POINT)
+#define OVERRIDE_OP_PVQ_SEARCH
+
+opus_val16 op_pvq_search_sse2(celt_norm *_X, int *iy, int K, int N, int arch);
+
+#if defined(OPUS_X86_PRESUME_SSE2)
+#define op_pvq_search(x, iy, K, N, arch) \
+    (op_pvq_search_sse2(x, iy, K, N, arch))
+
+#else
+
+extern opus_val16 (*const OP_PVQ_SEARCH_IMPL[OPUS_ARCHMASK + 1])(
+      celt_norm *_X, int *iy, int K, int N, int arch);
+
+#  define op_pvq_search(X, iy, K, N, arch) \
+    ((*OP_PVQ_SEARCH_IMPL[(arch) & OPUS_ARCHMASK])(X, iy, K, N, arch))
+
+#endif
+#endif
+
+#endif
diff --git a/opus/celt/x86/vq_sse2.c b/opus/celt/x86/vq_sse2.c
new file mode 100644 (file)
index 0000000..6a31770
--- /dev/null
@@ -0,0 +1,217 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Copyright (c) 2007-2016 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include "celt_lpc.h"
+#include "stack_alloc.h"
+#include "mathops.h"
+#include "vq.h"
+#include "x86cpu.h"
+
+
+#ifndef FIXED_POINT
+
+opus_val16 op_pvq_search_sse2(celt_norm *_X, int *iy, int K, int N, int arch)
+{
+   int i, j;
+   int pulsesLeft;
+   float xy, yy;
+   VARDECL(celt_norm, y);
+   VARDECL(celt_norm, X);
+   VARDECL(float, signy);
+   __m128 signmask;
+   __m128 sums;
+   __m128i fours;
+   SAVE_STACK;
+
+   (void)arch;
+   /* All bits set to zero, except for the sign bit. */
+   signmask = _mm_set_ps1(-0.f);
+   fours = _mm_set_epi32(4, 4, 4, 4);
+   ALLOC(y, N+3, celt_norm);
+   ALLOC(X, N+3, celt_norm);
+   ALLOC(signy, N+3, float);
+
+   OPUS_COPY(X, _X, N);
+   X[N] = X[N+1] = X[N+2] = 0;
+   sums = _mm_setzero_ps();
+   for (j=0;j<N;j+=4)
+   {
+      __m128 x4, s4;
+      x4 = _mm_loadu_ps(&X[j]);
+      s4 = _mm_cmplt_ps(x4, _mm_setzero_ps());
+      /* Get rid of the sign */
+      x4 = _mm_andnot_ps(signmask, x4);
+      sums = _mm_add_ps(sums, x4);
+      /* Clear y and iy in case we don't do the projection. */
+      _mm_storeu_ps(&y[j], _mm_setzero_ps());
+      _mm_storeu_si128((__m128i*)&iy[j], _mm_setzero_si128());
+      _mm_storeu_ps(&X[j], x4);
+      _mm_storeu_ps(&signy[j], s4);
+   }
+   sums = _mm_add_ps(sums, _mm_shuffle_ps(sums, sums, _MM_SHUFFLE(1, 0, 3, 2)));
+   sums = _mm_add_ps(sums, _mm_shuffle_ps(sums, sums, _MM_SHUFFLE(2, 3, 0, 1)));
+
+   xy = yy = 0;
+
+   pulsesLeft = K;
+
+   /* Do a pre-search by projecting on the pyramid */
+   if (K > (N>>1))
+   {
+      __m128i pulses_sum;
+      __m128 yy4, xy4;
+      __m128 rcp4;
+      opus_val32 sum = _mm_cvtss_f32(sums);
+      /* If X is too small, just replace it with a pulse at 0 */
+      /* Prevents infinities and NaNs from causing too many pulses
+         to be allocated. 64 is an approximation of infinity here. */
+      if (!(sum > EPSILON && sum < 64))
+      {
+         X[0] = QCONST16(1.f,14);
+         j=1; do
+            X[j]=0;
+         while (++j<N);
+         sums = _mm_set_ps1(1.f);
+      }
+      /* Using K+e with e < 1 guarantees we cannot get more than K pulses. */
+      rcp4 = _mm_mul_ps(_mm_set_ps1((float)(K+.8)), _mm_rcp_ps(sums));
+      xy4 = yy4 = _mm_setzero_ps();
+      pulses_sum = _mm_setzero_si128();
+      for (j=0;j<N;j+=4)
+      {
+         __m128 rx4, x4, y4;
+         __m128i iy4;
+         x4 = _mm_loadu_ps(&X[j]);
+         rx4 = _mm_mul_ps(x4, rcp4);
+         iy4 = _mm_cvttps_epi32(rx4);
+         pulses_sum = _mm_add_epi32(pulses_sum, iy4);
+         _mm_storeu_si128((__m128i*)&iy[j], iy4);
+         y4 = _mm_cvtepi32_ps(iy4);
+         xy4 = _mm_add_ps(xy4, _mm_mul_ps(x4, y4));
+         yy4 = _mm_add_ps(yy4, _mm_mul_ps(y4, y4));
+         /* double the y[] vector so we don't have to do it in the search loop. */
+         _mm_storeu_ps(&y[j], _mm_add_ps(y4, y4));
+      }
+      pulses_sum = _mm_add_epi32(pulses_sum, _mm_shuffle_epi32(pulses_sum, _MM_SHUFFLE(1, 0, 3, 2)));
+      pulses_sum = _mm_add_epi32(pulses_sum, _mm_shuffle_epi32(pulses_sum, _MM_SHUFFLE(2, 3, 0, 1)));
+      pulsesLeft -= _mm_cvtsi128_si32(pulses_sum);
+      xy4 = _mm_add_ps(xy4, _mm_shuffle_ps(xy4, xy4, _MM_SHUFFLE(1, 0, 3, 2)));
+      xy4 = _mm_add_ps(xy4, _mm_shuffle_ps(xy4, xy4, _MM_SHUFFLE(2, 3, 0, 1)));
+      xy = _mm_cvtss_f32(xy4);
+      yy4 = _mm_add_ps(yy4, _mm_shuffle_ps(yy4, yy4, _MM_SHUFFLE(1, 0, 3, 2)));
+      yy4 = _mm_add_ps(yy4, _mm_shuffle_ps(yy4, yy4, _MM_SHUFFLE(2, 3, 0, 1)));
+      yy = _mm_cvtss_f32(yy4);
+   }
+   X[N] = X[N+1] = X[N+2] = -100;
+   y[N] = y[N+1] = y[N+2] = 100;
+   celt_assert2(pulsesLeft>=0, "Allocated too many pulses in the quick pass");
+
+   /* This should never happen, but just in case it does (e.g. on silence)
+      we fill the first bin with pulses. */
+   if (pulsesLeft > N+3)
+   {
+      opus_val16 tmp = (opus_val16)pulsesLeft;
+      yy = MAC16_16(yy, tmp, tmp);
+      yy = MAC16_16(yy, tmp, y[0]);
+      iy[0] += pulsesLeft;
+      pulsesLeft=0;
+   }
+
+   for (i=0;i<pulsesLeft;i++)
+   {
+      int best_id;
+      __m128 xy4, yy4;
+      __m128 max, max2;
+      __m128i count;
+      __m128i pos;
+      /* The squared magnitude term gets added anyway, so we might as well
+         add it outside the loop */
+      yy = ADD16(yy, 1);
+      xy4 = _mm_load1_ps(&xy);
+      yy4 = _mm_load1_ps(&yy);
+      max = _mm_setzero_ps();
+      pos = _mm_setzero_si128();
+      count = _mm_set_epi32(3, 2, 1, 0);
+      for (j=0;j<N;j+=4)
+      {
+         __m128 x4, y4, r4;
+         x4 = _mm_loadu_ps(&X[j]);
+         y4 = _mm_loadu_ps(&y[j]);
+         x4 = _mm_add_ps(x4, xy4);
+         y4 = _mm_add_ps(y4, yy4);
+         y4 = _mm_rsqrt_ps(y4);
+         r4 = _mm_mul_ps(x4, y4);
+         /* Update the index of the max. */
+         pos = _mm_max_epi16(pos, _mm_and_si128(count, _mm_castps_si128(_mm_cmpgt_ps(r4, max))));
+         /* Update the max. */
+         max = _mm_max_ps(max, r4);
+         /* Update the indices (+4) */
+         count = _mm_add_epi32(count, fours);
+      }
+      /* Horizontal max */
+      max2 = _mm_max_ps(max, _mm_shuffle_ps(max, max, _MM_SHUFFLE(1, 0, 3, 2)));
+      max2 = _mm_max_ps(max2, _mm_shuffle_ps(max2, max2, _MM_SHUFFLE(2, 3, 0, 1)));
+      /* Now that max2 contains the max at all positions, look at which value(s) of the
+         partial max is equal to the global max. */
+      pos = _mm_and_si128(pos, _mm_castps_si128(_mm_cmpeq_ps(max, max2)));
+      pos = _mm_max_epi16(pos, _mm_unpackhi_epi64(pos, pos));
+      pos = _mm_max_epi16(pos, _mm_shufflelo_epi16(pos, _MM_SHUFFLE(1, 0, 3, 2)));
+      best_id = _mm_cvtsi128_si32(pos);
+
+      /* Updating the sums of the new pulse(s) */
+      xy = ADD32(xy, EXTEND32(X[best_id]));
+      /* We're multiplying y[j] by two so we don't have to do it here */
+      yy = ADD16(yy, y[best_id]);
+
+      /* 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[best_id] += 2;
+      iy[best_id]++;
+   }
+
+   /* Put the original sign back */
+   for (j=0;j<N;j+=4)
+   {
+      __m128i y4;
+      __m128i s4;
+      y4 = _mm_loadu_si128((__m128i*)&iy[j]);
+      s4 = _mm_castps_si128(_mm_loadu_ps(&signy[j]));
+      y4 = _mm_xor_si128(_mm_add_epi32(y4, s4), s4);
+      _mm_storeu_si128((__m128i*)&iy[j], y4);
+   }
+   RESTORE_STACK;
+   return yy;
+}
+
+#endif
diff --git a/opus/celt/x86/x86_celt_map.c b/opus/celt/x86/x86_celt_map.c
new file mode 100644 (file)
index 0000000..d39d88e
--- /dev/null
@@ -0,0 +1,167 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#include "x86/x86cpu.h"
+#include "celt_lpc.h"
+#include "pitch.h"
+#include "pitch_sse.h"
+#include "vq.h"
+
+#if defined(OPUS_HAVE_RTCD)
+
+# if defined(FIXED_POINT)
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1) && !defined(OPUS_X86_PRESUME_SSE4_1)
+
+void (*const CELT_FIR_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *num,
+         opus_val16       *y,
+         int              N,
+         int              ord,
+         int              arch
+) = {
+  celt_fir_c,                /* non-sse */
+  celt_fir_c,
+  celt_fir_c,
+  MAY_HAVE_SSE4_1(celt_fir), /* sse4.1  */
+  MAY_HAVE_SSE4_1(celt_fir)  /* avx  */
+};
+
+void (*const XCORR_KERNEL_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *y,
+         opus_val32       sum[4],
+         int              len
+) = {
+  xcorr_kernel_c,                /* non-sse */
+  xcorr_kernel_c,
+  xcorr_kernel_c,
+  MAY_HAVE_SSE4_1(xcorr_kernel), /* sse4.1  */
+  MAY_HAVE_SSE4_1(xcorr_kernel)  /* avx  */
+};
+
+#endif
+
+#if (defined(OPUS_X86_MAY_HAVE_SSE4_1) && !defined(OPUS_X86_PRESUME_SSE4_1)) ||  \
+ (!defined(OPUS_X86_MAY_HAVE_SSE_4_1) && defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(OPUS_X86_PRESUME_SSE2))
+
+opus_val32 (*const CELT_INNER_PROD_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *y,
+         int              N
+) = {
+  celt_inner_prod_c,                /* non-sse */
+  celt_inner_prod_c,
+  MAY_HAVE_SSE2(celt_inner_prod),
+  MAY_HAVE_SSE4_1(celt_inner_prod), /* sse4.1  */
+  MAY_HAVE_SSE4_1(celt_inner_prod)  /* avx  */
+};
+
+#endif
+
+# else
+
+#if defined(OPUS_X86_MAY_HAVE_SSE) && !defined(OPUS_X86_PRESUME_SSE)
+
+void (*const XCORR_KERNEL_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *y,
+         opus_val32       sum[4],
+         int              len
+) = {
+  xcorr_kernel_c,                /* non-sse */
+  MAY_HAVE_SSE(xcorr_kernel),
+  MAY_HAVE_SSE(xcorr_kernel),
+  MAY_HAVE_SSE(xcorr_kernel),
+  MAY_HAVE_SSE(xcorr_kernel)
+};
+
+opus_val32 (*const CELT_INNER_PROD_IMPL[OPUS_ARCHMASK + 1])(
+         const opus_val16 *x,
+         const opus_val16 *y,
+         int              N
+) = {
+  celt_inner_prod_c,                /* non-sse */
+  MAY_HAVE_SSE(celt_inner_prod),
+  MAY_HAVE_SSE(celt_inner_prod),
+  MAY_HAVE_SSE(celt_inner_prod),
+  MAY_HAVE_SSE(celt_inner_prod)
+};
+
+void (*const DUAL_INNER_PROD_IMPL[OPUS_ARCHMASK + 1])(
+                    const opus_val16 *x,
+                    const opus_val16 *y01,
+                    const opus_val16 *y02,
+                    int               N,
+                    opus_val32       *xy1,
+                    opus_val32       *xy2
+) = {
+  dual_inner_prod_c,                /* non-sse */
+  MAY_HAVE_SSE(dual_inner_prod),
+  MAY_HAVE_SSE(dual_inner_prod),
+  MAY_HAVE_SSE(dual_inner_prod),
+  MAY_HAVE_SSE(dual_inner_prod)
+};
+
+void (*const COMB_FILTER_CONST_IMPL[OPUS_ARCHMASK + 1])(
+              opus_val32 *y,
+              opus_val32 *x,
+              int         T,
+              int         N,
+              opus_val16  g10,
+              opus_val16  g11,
+              opus_val16  g12
+) = {
+  comb_filter_const_c,                /* non-sse */
+  MAY_HAVE_SSE(comb_filter_const),
+  MAY_HAVE_SSE(comb_filter_const),
+  MAY_HAVE_SSE(comb_filter_const),
+  MAY_HAVE_SSE(comb_filter_const)
+};
+
+
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(OPUS_X86_PRESUME_SSE2)
+opus_val16 (*const OP_PVQ_SEARCH_IMPL[OPUS_ARCHMASK + 1])(
+      celt_norm *_X, int *iy, int K, int N, int arch
+) = {
+  op_pvq_search_c,                /* non-sse */
+  op_pvq_search_c,
+  MAY_HAVE_SSE2(op_pvq_search),
+  MAY_HAVE_SSE2(op_pvq_search),
+  MAY_HAVE_SSE2(op_pvq_search)
+};
+#endif
+
+#endif
+#endif
diff --git a/opus/celt/x86/x86cpu.c b/opus/celt/x86/x86cpu.c
new file mode 100644 (file)
index 0000000..080eb25
--- /dev/null
@@ -0,0 +1,157 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "cpu_support.h"
+#include "macros.h"
+#include "main.h"
+#include "pitch.h"
+#include "x86cpu.h"
+
+#if (defined(OPUS_X86_MAY_HAVE_SSE) && !defined(OPUS_X86_PRESUME_SSE)) || \
+  (defined(OPUS_X86_MAY_HAVE_SSE2) && !defined(OPUS_X86_PRESUME_SSE2)) || \
+  (defined(OPUS_X86_MAY_HAVE_SSE4_1) && !defined(OPUS_X86_PRESUME_SSE4_1)) || \
+  (defined(OPUS_X86_MAY_HAVE_AVX) && !defined(OPUS_X86_PRESUME_AVX))
+
+
+#if defined(_MSC_VER)
+
+#include <intrin.h>
+static _inline void cpuid(unsigned int CPUInfo[4], unsigned int InfoType)
+{
+    __cpuid((int*)CPUInfo, InfoType);
+}
+
+#else
+
+#if defined(CPU_INFO_BY_C)
+#include <cpuid.h>
+#endif
+
+static void cpuid(unsigned int CPUInfo[4], unsigned int InfoType)
+{
+#if defined(CPU_INFO_BY_ASM)
+#if defined(__i386__) && defined(__PIC__)
+/* %ebx is PIC register in 32-bit, so mustn't clobber it. */
+    __asm__ __volatile__ (
+        "xchg %%ebx, %1\n"
+        "cpuid\n"
+        "xchg %%ebx, %1\n":
+        "=a" (CPUInfo[0]),
+        "=r" (CPUInfo[1]),
+        "=c" (CPUInfo[2]),
+        "=d" (CPUInfo[3]) :
+        "0" (InfoType)
+    );
+#else
+    __asm__ __volatile__ (
+        "cpuid":
+        "=a" (CPUInfo[0]),
+        "=b" (CPUInfo[1]),
+        "=c" (CPUInfo[2]),
+        "=d" (CPUInfo[3]) :
+        "0" (InfoType)
+    );
+#endif
+#elif defined(CPU_INFO_BY_C)
+    __get_cpuid(InfoType, &(CPUInfo[0]), &(CPUInfo[1]), &(CPUInfo[2]), &(CPUInfo[3]));
+#endif
+}
+
+#endif
+
+typedef struct CPU_Feature{
+    /*  SIMD: 128-bit */
+    int HW_SSE;
+    int HW_SSE2;
+    int HW_SSE41;
+    /*  SIMD: 256-bit */
+    int HW_AVX;
+} CPU_Feature;
+
+static void opus_cpu_feature_check(CPU_Feature *cpu_feature)
+{
+    unsigned int info[4] = {0};
+    unsigned int nIds = 0;
+
+    cpuid(info, 0);
+    nIds = info[0];
+
+    if (nIds >= 1){
+        cpuid(info, 1);
+        cpu_feature->HW_SSE = (info[3] & (1 << 25)) != 0;
+        cpu_feature->HW_SSE2 = (info[3] & (1 << 26)) != 0;
+        cpu_feature->HW_SSE41 = (info[2] & (1 << 19)) != 0;
+        cpu_feature->HW_AVX = (info[2] & (1 << 28)) != 0;
+    }
+    else {
+        cpu_feature->HW_SSE = 0;
+        cpu_feature->HW_SSE2 = 0;
+        cpu_feature->HW_SSE41 = 0;
+        cpu_feature->HW_AVX = 0;
+    }
+}
+
+int opus_select_arch(void)
+{
+    CPU_Feature cpu_feature;
+    int arch;
+
+    opus_cpu_feature_check(&cpu_feature);
+
+    arch = 0;
+    if (!cpu_feature.HW_SSE)
+    {
+       return arch;
+    }
+    arch++;
+
+    if (!cpu_feature.HW_SSE2)
+    {
+       return arch;
+    }
+    arch++;
+
+    if (!cpu_feature.HW_SSE41)
+    {
+        return arch;
+    }
+    arch++;
+
+    if (!cpu_feature.HW_AVX)
+    {
+        return arch;
+    }
+    arch++;
+
+    return arch;
+}
+
+#endif
diff --git a/opus/celt/x86/x86cpu.h b/opus/celt/x86/x86cpu.h
new file mode 100644 (file)
index 0000000..04fd48a
--- /dev/null
@@ -0,0 +1,93 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#if !defined(X86CPU_H)
+# define X86CPU_H
+
+# if defined(OPUS_X86_MAY_HAVE_SSE)
+#  define MAY_HAVE_SSE(name) name ## _sse
+# else
+#  define MAY_HAVE_SSE(name) name ## _c
+# endif
+
+# if defined(OPUS_X86_MAY_HAVE_SSE2)
+#  define MAY_HAVE_SSE2(name) name ## _sse2
+# else
+#  define MAY_HAVE_SSE2(name) name ## _c
+# endif
+
+# if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#  define MAY_HAVE_SSE4_1(name) name ## _sse4_1
+# else
+#  define MAY_HAVE_SSE4_1(name) name ## _c
+# endif
+
+# if defined(OPUS_X86_MAY_HAVE_AVX)
+#  define MAY_HAVE_AVX(name) name ## _avx
+# else
+#  define MAY_HAVE_AVX(name) name ## _c
+# endif
+
+# if defined(OPUS_HAVE_RTCD)
+int opus_select_arch(void);
+# endif
+
+/*gcc appears to emit MOVDQA's to load the argument of an _mm_cvtepi8_epi32()
+  or _mm_cvtepi16_epi32() when optimizations are disabled, even though the
+  actual PMOVSXWD instruction takes an m32 or m64. Unlike a normal memory
+  reference, these require 16-byte alignment and load a full 16 bytes (instead
+  of 4 or 8), possibly reading out of bounds.
+
+  We can insert an explicit MOVD or MOVQ using _mm_cvtsi32_si128() or
+  _mm_loadl_epi64(), which should have the same semantics as an m32 or m64
+  reference in the PMOVSXWD instruction itself, but gcc is not smart enough to
+  optimize this out when optimizations ARE enabled.
+
+  Clang, in contrast, requires us to do this always for _mm_cvtepi8_epi32
+  (which is fair, since technically the compiler is always allowed to do the
+  dereference before invoking the function implementing the intrinsic).
+  However, it is smart enough to eliminate the extra MOVD instruction.
+  For _mm_cvtepi16_epi32, it does the right thing, though does *not* optimize out
+  the extra MOVQ if it's specified explicitly */
+
+# if defined(__clang__) || !defined(__OPTIMIZE__)
+#  define OP_CVTEPI8_EPI32_M32(x) \
+ (_mm_cvtepi8_epi32(_mm_cvtsi32_si128(*(int *)(x))))
+# else
+#  define OP_CVTEPI8_EPI32_M32(x) \
+ (_mm_cvtepi8_epi32(*(__m128i *)(x)))
+#endif
+
+# if !defined(__OPTIMIZE__)
+#  define OP_CVTEPI16_EPI32_M64(x) \
+ (_mm_cvtepi16_epi32(_mm_loadl_epi64((__m128i *)(x))))
+# else
+#  define OP_CVTEPI16_EPI32_M64(x) \
+ (_mm_cvtepi16_epi32(*(__m128i *)(x)))
+# endif
+
+#endif
similarity index 99%
rename from opus/opus.h
rename to opus/include/opus/opus.h
index 93a53a2..5be73dd 100644 (file)
@@ -142,7 +142,7 @@ extern "C" {
   *
   * opus_encode() and opus_encode_float() return the number of bytes actually written to the packet.
   * The return value <b>can be negative</b>, which indicates that an error has occurred. If the return value
-  * is 1 byte, then the packet does not need to be transmitted (DTX).
+  * is 2 bytes or less, then the packet does not need to be transmitted (DTX).
   *
   * Once the encoder state if no longer needed, it can be destroyed with
   *
@@ -616,7 +616,10 @@ OPUS_EXPORT void opus_pcm_soft_clip(float *pcm, int frame_size, int channels, fl
   * merged. Splitting valid Opus packets is always guaranteed to succeed,
   * whereas merging valid packets only succeeds if all frames have the same
   * mode, bandwidth, and frame size, and when the total duration of the merged
-  * packet is no more than 120 ms.
+  * packet is no more than 120 ms. The 120 ms limit comes from the
+  * specification and limits decoder memory requirements at a point where
+  * framing overhead becomes negligible.
+  *
   * The repacketizer currently only operates on elementary Opus
   * streams. It will not manipualte multistream packets successfully, except in
   * the degenerate case where they consist of data from a single stream.
similarity index 89%
rename from opus/opus_defines.h
rename to opus/include/opus/opus_defines.h
index 265089f..33c5acd 100644 (file)
@@ -46,7 +46,7 @@ extern "C" {
 #define OPUS_OK                0
 /** One or more invalid/out of range arguments @hideinitializer*/
 #define OPUS_BAD_ARG          -1
-/** The mode struct passed is invalid @hideinitializer*/
+/** Not enough bytes allocated in the buffer @hideinitializer*/
 #define OPUS_BUFFER_TOO_SMALL -2
 /** An internal error was detected @hideinitializer*/
 #define OPUS_INTERNAL_ERROR   -3
@@ -65,7 +65,7 @@ extern "C" {
 
 #ifndef OPUS_EXPORT
 # if defined(WIN32)
-#  ifdef OPUS_BUILD
+#  if defined(OPUS_BUILD) && defined(DLL_EXPORT)
 #   define OPUS_EXPORT __declspec(dllexport)
 #  else
 #   define OPUS_EXPORT
@@ -165,8 +165,9 @@ extern "C" {
 #define OPUS_GET_EXPERT_FRAME_DURATION_REQUEST 4041
 #define OPUS_SET_PREDICTION_DISABLED_REQUEST 4042
 #define OPUS_GET_PREDICTION_DISABLED_REQUEST 4043
-
 /* Don't use 4045, it's already taken by OPUS_GET_GAIN_REQUEST */
+#define OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST 4046
+#define OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST 4047
 
 /* Macros to trigger compilation errors when the wrong types are provided to a CTL */
 #define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x))
@@ -208,6 +209,9 @@ extern "C" {
 #define OPUS_FRAMESIZE_20_MS                 5004 /**< Use 20 ms frames */
 #define OPUS_FRAMESIZE_40_MS                 5005 /**< Use 40 ms frames */
 #define OPUS_FRAMESIZE_60_MS                 5006 /**< Use 60 ms frames */
+#define OPUS_FRAMESIZE_80_MS                 5007 /**< Use 80 ms frames */
+#define OPUS_FRAMESIZE_100_MS                5008 /**< Use 100 ms frames */
+#define OPUS_FRAMESIZE_120_MS                5009 /**< Use 120 ms frames */
 
 /**@}*/
 
@@ -274,7 +278,6 @@ extern "C" {
 /** Enables or disables variable bitrate (VBR) in the encoder.
   * The configured bitrate may not be met exactly because frames must
   * be an integer number of bytes in length.
-  * @warning Only the MDCT mode of Opus can provide hard CBR behavior.
   * @see OPUS_GET_VBR
   * @see OPUS_SET_VBR_CONSTRAINT
   * @param[in] x <tt>opus_int32</tt>: Allowed values:
@@ -454,14 +457,6 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_APPLICATION(x) OPUS_GET_APPLICATION_REQUEST, __opus_check_int_ptr(x)
 
-/** Gets the sampling rate the encoder or decoder was initialized with.
-  * This simply returns the <code>Fs</code> value passed to opus_encoder_init()
-  * or opus_decoder_init().
-  * @param[out] x <tt>opus_int32 *</tt>: Sampling rate of encoder or decoder.
-  * @hideinitializer
-  */
-#define OPUS_GET_SAMPLE_RATE(x) OPUS_GET_SAMPLE_RATE_REQUEST, __opus_check_int_ptr(x)
-
 /** Gets the total samples of delay added by the entire codec.
   * This can be queried by the encoder and then the provided number of samples can be
   * skipped on from the start of the decoder's output to provide time aligned input
@@ -498,9 +493,9 @@ extern "C" {
 #define OPUS_GET_INBAND_FEC(x) OPUS_GET_INBAND_FEC_REQUEST, __opus_check_int_ptr(x)
 
 /** Configures the encoder's expected packet loss percentage.
-  * Higher values with trigger progressively more loss resistant behavior in the encoder
-  * at the expense of quality at a given bitrate in the lossless case, but greater quality
-  * under loss.
+  * Higher values trigger progressively more loss resistant behavior in the encoder
+  * at the expense of quality at a given bitrate in the absence of packet loss, but
+  * greater quality under loss.
   * @see OPUS_GET_PACKET_LOSS_PERC
   * @param[in] x <tt>opus_int32</tt>:   Loss percentage in the range 0-100, inclusive (default: 0).
   * @hideinitializer */
@@ -532,7 +527,19 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_DTX(x) OPUS_GET_DTX_REQUEST, __opus_check_int_ptr(x)
 /** Configures the depth of signal being encoded.
+  *
   * This is a hint which helps the encoder identify silence and near-silence.
+  * It represents the number of significant bits of linear intensity below
+  * which the signal contains ignorable quantization or other noise.
+  *
+  * For example, OPUS_SET_LSB_DEPTH(14) would be an appropriate setting
+  * for G.711 u-law input. OPUS_SET_LSB_DEPTH(16) would be appropriate
+  * for 16-bit linear pcm input with opus_encode_float().
+  *
+  * When using opus_encode() instead of opus_encode_float(), or when libopus
+  * is compiled for fixed-point, the encoder uses the minimum of the value
+  * set here and the value 16.
+  *
   * @see OPUS_GET_LSB_DEPTH
   * @param[in] x <tt>opus_int32</tt>: Input precision in bits, between 8 and 24
   *                                   (default: 24).
@@ -545,11 +552,6 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_LSB_DEPTH(x) OPUS_GET_LSB_DEPTH_REQUEST, __opus_check_int_ptr(x)
 
-/** Gets the duration (in samples) of the last packet successfully decoded or concealed.
-  * @param[out] x <tt>opus_int32 *</tt>: Number of samples (at current sampling rate).
-  * @hideinitializer */
-#define OPUS_GET_LAST_PACKET_DURATION(x) OPUS_GET_LAST_PACKET_DURATION_REQUEST, __opus_check_int_ptr(x)
-
 /** Configures the encoder's use of variable duration frames.
   * When variable duration is enabled, the encoder is free to use a shorter frame
   * size than the one requested in the opus_encode*() call.
@@ -558,41 +560,57 @@ extern "C" {
   * packet. The part of the audio that was not encoded needs to be resent to the
   * encoder for the next call. Do not use this option unless you <b>really</b>
   * know what you are doing.
-  * @see OPUS_GET_EXPERT_VARIABLE_DURATION
+  * @see OPUS_GET_EXPERT_FRAME_DURATION
   * @param[in] x <tt>opus_int32</tt>: Allowed values:
   * <dl>
   * <dt>OPUS_FRAMESIZE_ARG</dt><dd>Select frame size from the argument (default).</dd>
   * <dt>OPUS_FRAMESIZE_2_5_MS</dt><dd>Use 2.5 ms frames.</dd>
-  * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 2.5 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 5 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_10_MS</dt><dd>Use 10 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_20_MS</dt><dd>Use 20 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_40_MS</dt><dd>Use 40 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_60_MS</dt><dd>Use 60 ms frames.</dd>
-  * <dt>OPUS_FRAMESIZE_VARIABLE</dt><dd>Optimize the frame size dynamically.</dd>
+  * <dt>OPUS_FRAMESIZE_80_MS</dt><dd>Use 80 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_100_MS</dt><dd>Use 100 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_120_MS</dt><dd>Use 120 ms frames.</dd>
   * </dl>
   * @hideinitializer */
 #define OPUS_SET_EXPERT_FRAME_DURATION(x) OPUS_SET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int(x)
 /** Gets the encoder's configured use of variable duration frames.
-  * @see OPUS_SET_EXPERT_VARIABLE_DURATION
+  * @see OPUS_SET_EXPERT_FRAME_DURATION
   * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
   * <dl>
   * <dt>OPUS_FRAMESIZE_ARG</dt><dd>Select frame size from the argument (default).</dd>
   * <dt>OPUS_FRAMESIZE_2_5_MS</dt><dd>Use 2.5 ms frames.</dd>
-  * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 2.5 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 5 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_10_MS</dt><dd>Use 10 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_20_MS</dt><dd>Use 20 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_40_MS</dt><dd>Use 40 ms frames.</dd>
   * <dt>OPUS_FRAMESIZE_60_MS</dt><dd>Use 60 ms frames.</dd>
-  * <dt>OPUS_FRAMESIZE_VARIABLE</dt><dd>Optimize the frame size dynamically.</dd>
+  * <dt>OPUS_FRAMESIZE_80_MS</dt><dd>Use 80 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_100_MS</dt><dd>Use 100 ms frames.</dd>
+  * <dt>OPUS_FRAMESIZE_120_MS</dt><dd>Use 120 ms frames.</dd>
   * </dl>
   * @hideinitializer */
 #define OPUS_GET_EXPERT_FRAME_DURATION(x) OPUS_GET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int_ptr(x)
 
 /** If set to 1, disables almost all use of prediction, making frames almost
-    completely independent. This reduces quality. (default : 0)
+  * completely independent. This reduces quality.
+  * @see OPUS_GET_PREDICTION_DISABLED
+  * @param[in] x <tt>opus_int32</tt>: Allowed values:
+  * <dl>
+  * <dt>0</dt><dd>Enable prediction (default).</dd>
+  * <dt>1</dt><dd>Disable prediction.</dd>
+  * </dl>
   * @hideinitializer */
 #define OPUS_SET_PREDICTION_DISABLED(x) OPUS_SET_PREDICTION_DISABLED_REQUEST, __opus_check_int(x)
 /** Gets the encoder's configured prediction status.
+  * @see OPUS_SET_PREDICTION_DISABLED
+  * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
+  * <dl>
+  * <dt>0</dt><dd>Prediction enabled (default).</dd>
+  * <dt>1</dt><dd>Prediction disabled.</dd>
+  * </dl>
   * @hideinitializer */
 #define OPUS_GET_PREDICTION_DISABLED(x) OPUS_GET_PREDICTION_DISABLED_REQUEST, __opus_check_int_ptr(x)
 
@@ -649,18 +667,6 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_FINAL_RANGE(x) OPUS_GET_FINAL_RANGE_REQUEST, __opus_check_uint_ptr(x)
 
-/** Gets the pitch of the last decoded frame, if available.
-  * This can be used for any post-processing algorithm requiring the use of pitch,
-  * e.g. time stretching/shortening. If the last frame was not voiced, or if the
-  * pitch was not coded in the frame, then zero is returned.
-  *
-  * This CTL is only implemented for decoder instances.
-  *
-  * @param[out] x <tt>opus_int32 *</tt>: pitch period at 48 kHz (or 0 if not available)
-  *
-  * @hideinitializer */
-#define OPUS_GET_PITCH(x) OPUS_GET_PITCH_REQUEST, __opus_check_int_ptr(x)
-
 /** Gets the encoder's configured bandpass or the decoder's last bandpass.
   * @see OPUS_SET_BANDWIDTH
   * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
@@ -675,6 +681,38 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_BANDWIDTH(x) OPUS_GET_BANDWIDTH_REQUEST, __opus_check_int_ptr(x)
 
+/** Gets the sampling rate the encoder or decoder was initialized with.
+  * This simply returns the <code>Fs</code> value passed to opus_encoder_init()
+  * or opus_decoder_init().
+  * @param[out] x <tt>opus_int32 *</tt>: Sampling rate of encoder or decoder.
+  * @hideinitializer
+  */
+#define OPUS_GET_SAMPLE_RATE(x) OPUS_GET_SAMPLE_RATE_REQUEST, __opus_check_int_ptr(x)
+
+/** If set to 1, disables the use of phase inversion for intensity stereo,
+  * improving the quality of mono downmixes, but slightly reducing normal
+  * stereo quality. Disabling phase inversion in the decoder does not comply
+  * with RFC 6716, although it does not cause any interoperability issue and
+  * is expected to become part of the Opus standard once RFC 6716 is updated
+  * by draft-ietf-codec-opus-update.
+  * @see OPUS_GET_PHASE_INVERSION_DISABLED
+  * @param[in] x <tt>opus_int32</tt>: Allowed values:
+  * <dl>
+  * <dt>0</dt><dd>Enable phase inversion (default).</dd>
+  * <dt>1</dt><dd>Disable phase inversion.</dd>
+  * </dl>
+  * @hideinitializer */
+#define OPUS_SET_PHASE_INVERSION_DISABLED(x) OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST, __opus_check_int(x)
+/** Gets the encoder's configured phase inversion status.
+  * @see OPUS_SET_PHASE_INVERSION_DISABLED
+  * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
+  * <dl>
+  * <dt>0</dt><dd>Stereo phase inversion enabled (default).</dd>
+  * <dt>1</dt><dd>Stereo phase inversion disabled.</dd>
+  * </dl>
+  * @hideinitializer */
+#define OPUS_GET_PHASE_INVERSION_DISABLED(x) OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST, __opus_check_int_ptr(x)
+
 /**@}*/
 
 /** @defgroup opus_decoderctls Decoder related CTLs
@@ -699,6 +737,23 @@ extern "C" {
   * @hideinitializer */
 #define OPUS_GET_GAIN(x) OPUS_GET_GAIN_REQUEST, __opus_check_int_ptr(x)
 
+/** Gets the duration (in samples) of the last packet successfully decoded or concealed.
+  * @param[out] x <tt>opus_int32 *</tt>: Number of samples (at current sampling rate).
+  * @hideinitializer */
+#define OPUS_GET_LAST_PACKET_DURATION(x) OPUS_GET_LAST_PACKET_DURATION_REQUEST, __opus_check_int_ptr(x)
+
+/** Gets the pitch of the last decoded frame, if available.
+  * This can be used for any post-processing algorithm requiring the use of pitch,
+  * e.g. time stretching/shortening. If the last frame was not voiced, or if the
+  * pitch was not coded in the frame, then zero is returned.
+  *
+  * This CTL is only implemented for decoder instances.
+  *
+  * @param[out] x <tt>opus_int32 *</tt>: pitch period at 48 kHz (or 0 if not available)
+  *
+  * @hideinitializer */
+#define OPUS_GET_PITCH(x) OPUS_GET_PITCH_REQUEST, __opus_check_int_ptr(x)
+
 /**@}*/
 
 /** @defgroup opus_libinfo Opus library information functions
@@ -714,6 +769,10 @@ OPUS_EXPORT const char *opus_strerror(int error);
 
 /** Gets the libopus version string.
   *
+  * Applications may look for the substring "-fixed" in the version string to
+  * determine whether they have a fixed-point or floating-point build at
+  * runtime.
+  *
   * @returns Version string
   */
 OPUS_EXPORT const char *opus_get_version_string(void);
similarity index 98%
rename from opus/opus_multistream.h
rename to opus/include/opus/opus_multistream.h
index ae59979..babcee6 100644 (file)
@@ -110,10 +110,10 @@ extern "C" {
   * packets produced by the encoder. Some basic information, such as packet
   * duration, can be computed without any special negotiation.
   *
-  * The format for multistream Opus packets is defined in the
-  * <a href="http://tools.ietf.org/html/draft-terriberry-oggopus">Ogg
-  * encapsulation specification</a> and is based on the self-delimited Opus
-  * framing described in Appendix B of <a href="http://tools.ietf.org/html/rfc6716">RFC 6716</a>.
+  * The format for multistream Opus packets is defined in
+  * <a href="https://tools.ietf.org/html/rfc7845">RFC 7845</a>
+  * and is based on the self-delimited Opus framing described in Appendix B of
+  * <a href="https://tools.ietf.org/html/rfc6716">RFC 6716</a>.
   * Normal Opus packets are just a degenerate case of multistream Opus packets,
   * and can be encoded or decoded with the multistream API by setting
   * <code>streams</code> to <code>1</code> when initializing the encoder or
@@ -140,7 +140,7 @@ extern "C" {
   *
   * The output channels specified by the encoder
   * should use the
-  * <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis
+  * <a href="https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-810004.3.9">Vorbis
   * channel ordering</a>. A decoder may wish to apply an additional permutation
   * to the mapping the encoder used to achieve a different output channel
   * order (e.g. for outputing in WAV order).
@@ -273,7 +273,7 @@ OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSEncoder *opus_multistream_surround_enc
       unsigned char *mapping,
       int application,
       int *error
-) OPUS_ARG_NONNULL(5);
+) OPUS_ARG_NONNULL(4) OPUS_ARG_NONNULL(5) OPUS_ARG_NONNULL(6);
 
 /** Initialize a previously allocated multistream encoder state.
   * The memory pointed to by \a st must be at least the size returned by
@@ -342,7 +342,7 @@ OPUS_EXPORT int opus_multistream_surround_encoder_init(
       int *coupled_streams,
       unsigned char *mapping,
       int application
-) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6);
+) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(5) OPUS_ARG_NONNULL(6) OPUS_ARG_NONNULL(7);
 
 /** Encodes a multistream Opus frame.
   * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.
similarity index 96%
rename from opus/opus_types.h
rename to opus/include/opus/opus_types.h
index b28e03a..7180826 100644 (file)
@@ -34,7 +34,7 @@
 #define OPUS_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))
+#if (defined(__STDC__) && __STDC__ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) || defined (HAVE_STDINT_H))
 #include <stdint.h>
 
    typedef int16_t opus_int16;
diff --git a/opus/silk/A2NLSF.c b/opus/silk/A2NLSF.c
new file mode 100644 (file)
index 0000000..b487686
--- /dev/null
@@ -0,0 +1,267 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+/* Conversion between prediction filter coefficients and NLSFs  */
+/* Requires the order to be an even number                      */
+/* A piecewise linear approximation maps LSF <-> cos(LSF)       */
+/* Therefore the result is not accurate NLSFs, but the two      */
+/* functions are accurate inverses of each other                */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "tables.h"
+
+/* Number of binary divisions, when not in low complexity mode */
+#define BIN_DIV_STEPS_A2NLSF_FIX      3 /* must be no higher than 16 - log2( LSF_COS_TAB_SZ_FIX ) */
+#define MAX_ITERATIONS_A2NLSF_FIX    16
+
+/* Helper function for A2NLSF(..)                    */
+/* Transforms polynomials from cos(n*f) to cos(f)^n  */
+static OPUS_INLINE void silk_A2NLSF_trans_poly(
+    opus_int32          *p,                     /* I/O    Polynomial                                */
+    const opus_int      dd                      /* I      Polynomial order (= filter order / 2 )    */
+)
+{
+    opus_int k, n;
+
+    for( k = 2; k <= dd; k++ ) {
+        for( n = dd; n > k; n-- ) {
+            p[ n - 2 ] -= p[ n ];
+        }
+        p[ k - 2 ] -= silk_LSHIFT( p[ k ], 1 );
+    }
+}
+/* Helper function for A2NLSF(..) */
+/* Polynomial evaluation          */
+static OPUS_INLINE opus_int32 silk_A2NLSF_eval_poly( /* return the polynomial evaluation, in Q16     */
+    opus_int32          *p,                     /* I    Polynomial, Q16                         */
+    const opus_int32    x,                      /* I    Evaluation point, Q12                   */
+    const opus_int      dd                      /* I    Order                                   */
+)
+{
+    opus_int   n;
+    opus_int32 x_Q16, y32;
+
+    y32 = p[ dd ];                                  /* Q16 */
+    x_Q16 = silk_LSHIFT( x, 4 );
+
+    if ( opus_likely( 8 == dd ) )
+    {
+        y32 = silk_SMLAWW( p[ 7 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 6 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 5 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 4 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 3 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 2 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 1 ], y32, x_Q16 );
+        y32 = silk_SMLAWW( p[ 0 ], y32, x_Q16 );
+    }
+    else
+    {
+        for( n = dd - 1; n >= 0; n-- ) {
+            y32 = silk_SMLAWW( p[ n ], y32, x_Q16 );    /* Q16 */
+        }
+    }
+    return y32;
+}
+
+static OPUS_INLINE void silk_A2NLSF_init(
+     const opus_int32    *a_Q16,
+     opus_int32          *P,
+     opus_int32          *Q,
+     const opus_int      dd
+)
+{
+    opus_int k;
+
+    /* Convert filter coefs to even and odd polynomials */
+    P[dd] = silk_LSHIFT( 1, 16 );
+    Q[dd] = silk_LSHIFT( 1, 16 );
+    for( k = 0; k < dd; k++ ) {
+        P[ k ] = -a_Q16[ dd - k - 1 ] - a_Q16[ dd + k ];    /* Q16 */
+        Q[ k ] = -a_Q16[ dd - k - 1 ] + a_Q16[ dd + k ];    /* Q16 */
+    }
+
+    /* Divide out zeros as we have that for even filter orders, */
+    /* z =  1 is always a root in Q, and                        */
+    /* z = -1 is always a root in P                             */
+    for( k = dd; k > 0; k-- ) {
+        P[ k - 1 ] -= P[ k ];
+        Q[ k - 1 ] += Q[ k ];
+    }
+
+    /* Transform polynomials from cos(n*f) to cos(f)^n */
+    silk_A2NLSF_trans_poly( P, dd );
+    silk_A2NLSF_trans_poly( Q, dd );
+}
+
+/* Compute Normalized Line Spectral Frequencies (NLSFs) from whitening filter coefficients      */
+/* If not all roots are found, the a_Q16 coefficients are bandwidth expanded until convergence. */
+void silk_A2NLSF(
+    opus_int16                  *NLSF,              /* O    Normalized Line Spectral Frequencies in Q15 (0..2^15-1) [d] */
+    opus_int32                  *a_Q16,             /* I/O  Monic whitening filter coefficients in Q16 [d]              */
+    const opus_int              d                   /* I    Filter order (must be even)                                 */
+)
+{
+    opus_int   i, k, m, dd, root_ix, ffrac;
+    opus_int32 xlo, xhi, xmid;
+    opus_int32 ylo, yhi, ymid, thr;
+    opus_int32 nom, den;
+    opus_int32 P[ SILK_MAX_ORDER_LPC / 2 + 1 ];
+    opus_int32 Q[ SILK_MAX_ORDER_LPC / 2 + 1 ];
+    opus_int32 *PQ[ 2 ];
+    opus_int32 *p;
+
+    /* Store pointers to array */
+    PQ[ 0 ] = P;
+    PQ[ 1 ] = Q;
+
+    dd = silk_RSHIFT( d, 1 );
+
+    silk_A2NLSF_init( a_Q16, P, Q, dd );
+
+    /* Find roots, alternating between P and Q */
+    p = P;                          /* Pointer to polynomial */
+
+    xlo = silk_LSFCosTab_FIX_Q12[ 0 ]; /* Q12*/
+    ylo = silk_A2NLSF_eval_poly( p, xlo, dd );
+
+    if( ylo < 0 ) {
+        /* Set the first NLSF to zero and move on to the next */
+        NLSF[ 0 ] = 0;
+        p = Q;                      /* Pointer to polynomial */
+        ylo = silk_A2NLSF_eval_poly( p, xlo, dd );
+        root_ix = 1;                /* Index of current root */
+    } else {
+        root_ix = 0;                /* Index of current root */
+    }
+    k = 1;                          /* Loop counter */
+    i = 0;                          /* Counter for bandwidth expansions applied */
+    thr = 0;
+    while( 1 ) {
+        /* Evaluate polynomial */
+        xhi = silk_LSFCosTab_FIX_Q12[ k ]; /* Q12 */
+        yhi = silk_A2NLSF_eval_poly( p, xhi, dd );
+
+        /* Detect zero crossing */
+        if( ( ylo <= 0 && yhi >= thr ) || ( ylo >= 0 && yhi <= -thr ) ) {
+            if( yhi == 0 ) {
+                /* If the root lies exactly at the end of the current       */
+                /* interval, look for the next root in the next interval    */
+                thr = 1;
+            } else {
+                thr = 0;
+            }
+            /* Binary division */
+            ffrac = -256;
+            for( m = 0; m < BIN_DIV_STEPS_A2NLSF_FIX; m++ ) {
+                /* Evaluate polynomial */
+                xmid = silk_RSHIFT_ROUND( xlo + xhi, 1 );
+                ymid = silk_A2NLSF_eval_poly( p, xmid, dd );
+
+                /* Detect zero crossing */
+                if( ( ylo <= 0 && ymid >= 0 ) || ( ylo >= 0 && ymid <= 0 ) ) {
+                    /* Reduce frequency */
+                    xhi = xmid;
+                    yhi = ymid;
+                } else {
+                    /* Increase frequency */
+                    xlo = xmid;
+                    ylo = ymid;
+                    ffrac = silk_ADD_RSHIFT( ffrac, 128, m );
+                }
+            }
+
+            /* Interpolate */
+            if( silk_abs( ylo ) < 65536 ) {
+                /* Avoid dividing by zero */
+                den = ylo - yhi;
+                nom = silk_LSHIFT( ylo, 8 - BIN_DIV_STEPS_A2NLSF_FIX ) + silk_RSHIFT( den, 1 );
+                if( den != 0 ) {
+                    ffrac += silk_DIV32( nom, den );
+                }
+            } else {
+                /* No risk of dividing by zero because abs(ylo - yhi) >= abs(ylo) >= 65536 */
+                ffrac += silk_DIV32( ylo, silk_RSHIFT( ylo - yhi, 8 - BIN_DIV_STEPS_A2NLSF_FIX ) );
+            }
+            NLSF[ root_ix ] = (opus_int16)silk_min_32( silk_LSHIFT( (opus_int32)k, 8 ) + ffrac, silk_int16_MAX );
+
+            silk_assert( NLSF[ root_ix ] >= 0 );
+
+            root_ix++;        /* Next root */
+            if( root_ix >= d ) {
+                /* Found all roots */
+                break;
+            }
+            /* Alternate pointer to polynomial */
+            p = PQ[ root_ix & 1 ];
+
+            /* Evaluate polynomial */
+            xlo = silk_LSFCosTab_FIX_Q12[ k - 1 ]; /* Q12*/
+            ylo = silk_LSHIFT( 1 - ( root_ix & 2 ), 12 );
+        } else {
+            /* Increment loop counter */
+            k++;
+            xlo = xhi;
+            ylo = yhi;
+            thr = 0;
+
+            if( k > LSF_COS_TAB_SZ_FIX ) {
+                i++;
+                if( i > MAX_ITERATIONS_A2NLSF_FIX ) {
+                    /* Set NLSFs to white spectrum and exit */
+                    NLSF[ 0 ] = (opus_int16)silk_DIV32_16( 1 << 15, d + 1 );
+                    for( k = 1; k < d; k++ ) {
+                        NLSF[ k ] = (opus_int16)silk_ADD16( NLSF[ k-1 ], NLSF[ 0 ] );
+                    }
+                    return;
+                }
+
+                /* Error: Apply progressively more bandwidth expansion and run again */
+                silk_bwexpander_32( a_Q16, d, 65536 - silk_LSHIFT( 1, i ) );
+
+                silk_A2NLSF_init( a_Q16, P, Q, dd );
+                p = P;                            /* Pointer to polynomial */
+                xlo = silk_LSFCosTab_FIX_Q12[ 0 ]; /* Q12*/
+                ylo = silk_A2NLSF_eval_poly( p, xlo, dd );
+                if( ylo < 0 ) {
+                    /* Set the first NLSF to zero and move on to the next */
+                    NLSF[ 0 ] = 0;
+                    p = Q;                        /* Pointer to polynomial */
+                    ylo = silk_A2NLSF_eval_poly( p, xlo, dd );
+                    root_ix = 1;                  /* Index of current root */
+                } else {
+                    root_ix = 0;                  /* Index of current root */
+                }
+                k = 1;                            /* Reset loop counter */
+            }
+        }
+    }
+}
diff --git a/opus/silk/API.h b/opus/silk/API.h
new file mode 100644 (file)
index 0000000..0131acb
--- /dev/null
@@ -0,0 +1,134 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_API_H
+#define SILK_API_H
+
+#include "control.h"
+#include "typedef.h"
+#include "errors.h"
+#include "entenc.h"
+#include "entdec.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define SILK_MAX_FRAMES_PER_PACKET  3
+
+/* Struct for TOC (Table of Contents) */
+typedef struct {
+    opus_int    VADFlag;                                /* Voice activity for packet                            */
+    opus_int    VADFlags[ SILK_MAX_FRAMES_PER_PACKET ]; /* Voice activity for each frame in packet              */
+    opus_int    inbandFECFlag;                          /* Flag indicating if packet contains in-band FEC       */
+} silk_TOC_struct;
+
+/****************************************/
+/* Encoder functions                    */
+/****************************************/
+
+/***********************************************/
+/* Get size in bytes of the Silk encoder state */
+/***********************************************/
+opus_int silk_Get_Encoder_Size(                         /* O    Returns error code                              */
+    opus_int                        *encSizeBytes       /* O    Number of bytes in SILK encoder state           */
+);
+
+/*************************/
+/* Init or reset encoder */
+/*************************/
+opus_int silk_InitEncoder(                              /* O    Returns error code                              */
+    void                            *encState,          /* I/O  State                                           */
+    int                              arch,              /* I    Run-time architecture                           */
+    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
+);
+
+/**************************/
+/* Encode frame with Silk */
+/**************************/
+/* Note: if prefillFlag is set, the input must contain 10 ms of audio, irrespective of what                     */
+/* encControl->payloadSize_ms is set to                                                                         */
+opus_int silk_Encode(                                   /* O    Returns error code                              */
+    void                            *encState,          /* I/O  State                                           */
+    silk_EncControlStruct           *encControl,        /* I    Control status                                  */
+    const opus_int16                *samplesIn,         /* I    Speech sample input vector                      */
+    opus_int                        nSamplesIn,         /* I    Number of samples in input vector               */
+    ec_enc                          *psRangeEnc,        /* I/O  Compressor data structure                       */
+    opus_int32                      *nBytesOut,         /* I/O  Number of bytes in payload (input: Max bytes)   */
+    const opus_int                  prefillFlag         /* I    Flag to indicate prefilling buffers no coding   */
+);
+
+/****************************************/
+/* Decoder functions                    */
+/****************************************/
+
+/***********************************************/
+/* Get size in bytes of the Silk decoder state */
+/***********************************************/
+opus_int silk_Get_Decoder_Size(                         /* O    Returns error code                              */
+    opus_int                        *decSizeBytes       /* O    Number of bytes in SILK decoder state           */
+);
+
+/*************************/
+/* Init or Reset decoder */
+/*************************/
+opus_int silk_InitDecoder(                              /* O    Returns error code                              */
+    void                            *decState           /* I/O  State                                           */
+);
+
+/******************/
+/* Decode a frame */
+/******************/
+opus_int silk_Decode(                                   /* O    Returns error code                              */
+    void*                           decState,           /* I/O  State                                           */
+    silk_DecControlStruct*          decControl,         /* I/O  Control Structure                               */
+    opus_int                        lostFlag,           /* I    0: no loss, 1 loss, 2 decode fec                */
+    opus_int                        newPacketFlag,      /* I    Indicates first decoder call for this packet    */
+    ec_dec                          *psRangeDec,        /* I/O  Compressor data structure                       */
+    opus_int16                      *samplesOut,        /* O    Decoded output speech vector                    */
+    opus_int32                      *nSamplesOut,       /* O    Number of samples decoded                       */
+    int                             arch                /* I    Run-time architecture                           */
+);
+
+#if 0
+/**************************************/
+/* Get table of contents for a packet */
+/**************************************/
+opus_int silk_get_TOC(
+    const opus_uint8                *payload,           /* I    Payload data                                */
+    const opus_int                  nBytesIn,           /* I    Number of input bytes                       */
+    const opus_int                  nFramesPerPayload,  /* I    Number of SILK frames per payload           */
+    silk_TOC_struct                 *Silk_TOC           /* O    Type of content                             */
+);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/CNG.c b/opus/silk/CNG.c
new file mode 100644 (file)
index 0000000..e6d9b86
--- /dev/null
@@ -0,0 +1,184 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/* Generates excitation for CNG LPC synthesis */
+static OPUS_INLINE void silk_CNG_exc(
+    opus_int32                       exc_Q14[],          /* O    CNG excitation signal Q10                   */
+    opus_int32                       exc_buf_Q14[],      /* I    Random samples buffer Q10                   */
+    opus_int                         length,             /* I    Length                                      */
+    opus_int32                       *rand_seed          /* I/O  Seed to random index generator              */
+)
+{
+    opus_int32 seed;
+    opus_int   i, idx, exc_mask;
+
+    exc_mask = CNG_BUF_MASK_MAX;
+    while( exc_mask > length ) {
+        exc_mask = silk_RSHIFT( exc_mask, 1 );
+    }
+
+    seed = *rand_seed;
+    for( i = 0; i < length; i++ ) {
+        seed = silk_RAND( seed );
+        idx = (opus_int)( silk_RSHIFT( seed, 24 ) & exc_mask );
+        silk_assert( idx >= 0 );
+        silk_assert( idx <= CNG_BUF_MASK_MAX );
+        exc_Q14[ i ] = exc_buf_Q14[ idx ];
+    }
+    *rand_seed = seed;
+}
+
+void silk_CNG_Reset(
+    silk_decoder_state          *psDec                          /* I/O  Decoder state                               */
+)
+{
+    opus_int i, NLSF_step_Q15, NLSF_acc_Q15;
+
+    NLSF_step_Q15 = silk_DIV32_16( silk_int16_MAX, psDec->LPC_order + 1 );
+    NLSF_acc_Q15 = 0;
+    for( i = 0; i < psDec->LPC_order; i++ ) {
+        NLSF_acc_Q15 += NLSF_step_Q15;
+        psDec->sCNG.CNG_smth_NLSF_Q15[ i ] = NLSF_acc_Q15;
+    }
+    psDec->sCNG.CNG_smth_Gain_Q16 = 0;
+    psDec->sCNG.rand_seed = 3176576;
+}
+
+/* Updates CNG estimate, and applies the CNG when packet was lost   */
+void silk_CNG(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state                               */
+    silk_decoder_control        *psDecCtrl,                     /* I/O  Decoder control                             */
+    opus_int16                  frame[],                        /* I/O  Signal                                      */
+    opus_int                    length                          /* I    Length of residual                          */
+)
+{
+    opus_int   i, subfr;
+    opus_int32 LPC_pred_Q10, max_Gain_Q16, gain_Q16, gain_Q10;
+    opus_int16 A_Q12[ MAX_LPC_ORDER ];
+    silk_CNG_struct *psCNG = &psDec->sCNG;
+    SAVE_STACK;
+
+    if( psDec->fs_kHz != psCNG->fs_kHz ) {
+        /* Reset state */
+        silk_CNG_Reset( psDec );
+
+        psCNG->fs_kHz = psDec->fs_kHz;
+    }
+    if( psDec->lossCnt == 0 && psDec->prevSignalType == TYPE_NO_VOICE_ACTIVITY ) {
+        /* Update CNG parameters */
+
+        /* Smoothing of LSF's  */
+        for( i = 0; i < psDec->LPC_order; i++ ) {
+            psCNG->CNG_smth_NLSF_Q15[ i ] += silk_SMULWB( (opus_int32)psDec->prevNLSF_Q15[ i ] - (opus_int32)psCNG->CNG_smth_NLSF_Q15[ i ], CNG_NLSF_SMTH_Q16 );
+        }
+        /* Find the subframe with the highest gain */
+        max_Gain_Q16 = 0;
+        subfr        = 0;
+        for( i = 0; i < psDec->nb_subfr; i++ ) {
+            if( psDecCtrl->Gains_Q16[ i ] > max_Gain_Q16 ) {
+                max_Gain_Q16 = psDecCtrl->Gains_Q16[ i ];
+                subfr        = i;
+            }
+        }
+        /* Update CNG excitation buffer with excitation from this subframe */
+        silk_memmove( &psCNG->CNG_exc_buf_Q14[ psDec->subfr_length ], psCNG->CNG_exc_buf_Q14, ( psDec->nb_subfr - 1 ) * psDec->subfr_length * sizeof( opus_int32 ) );
+        silk_memcpy(   psCNG->CNG_exc_buf_Q14, &psDec->exc_Q14[ subfr * psDec->subfr_length ], psDec->subfr_length * sizeof( opus_int32 ) );
+
+        /* Smooth gains */
+        for( i = 0; i < psDec->nb_subfr; i++ ) {
+            psCNG->CNG_smth_Gain_Q16 += silk_SMULWB( psDecCtrl->Gains_Q16[ i ] - psCNG->CNG_smth_Gain_Q16, CNG_GAIN_SMTH_Q16 );
+        }
+    }
+
+    /* Add CNG when packet is lost or during DTX */
+    if( psDec->lossCnt ) {
+        VARDECL( opus_int32, CNG_sig_Q14 );
+        ALLOC( CNG_sig_Q14, length + MAX_LPC_ORDER, opus_int32 );
+
+        /* Generate CNG excitation */
+        gain_Q16 = silk_SMULWW( psDec->sPLC.randScale_Q14, psDec->sPLC.prevGain_Q16[1] );
+        if( gain_Q16 >= (1 << 21) || psCNG->CNG_smth_Gain_Q16 > (1 << 23) ) {
+            gain_Q16 = silk_SMULTT( gain_Q16, gain_Q16 );
+            gain_Q16 = silk_SUB_LSHIFT32(silk_SMULTT( psCNG->CNG_smth_Gain_Q16, psCNG->CNG_smth_Gain_Q16 ), gain_Q16, 5 );
+            gain_Q16 = silk_LSHIFT32( silk_SQRT_APPROX( gain_Q16 ), 16 );
+        } else {
+            gain_Q16 = silk_SMULWW( gain_Q16, gain_Q16 );
+            gain_Q16 = silk_SUB_LSHIFT32(silk_SMULWW( psCNG->CNG_smth_Gain_Q16, psCNG->CNG_smth_Gain_Q16 ), gain_Q16, 5 );
+            gain_Q16 = silk_LSHIFT32( silk_SQRT_APPROX( gain_Q16 ), 8 );
+        }
+        gain_Q10 = silk_RSHIFT( gain_Q16, 6 );
+
+        silk_CNG_exc( CNG_sig_Q14 + MAX_LPC_ORDER, psCNG->CNG_exc_buf_Q14, length, &psCNG->rand_seed );
+
+        /* Convert CNG NLSF to filter representation */
+        silk_NLSF2A( A_Q12, psCNG->CNG_smth_NLSF_Q15, psDec->LPC_order, psDec->arch );
+
+        /* Generate CNG signal, by synthesis filtering */
+        silk_memcpy( CNG_sig_Q14, psCNG->CNG_synth_state, MAX_LPC_ORDER * sizeof( opus_int32 ) );
+        for( i = 0; i < length; i++ ) {
+            silk_assert( psDec->LPC_order == 10 || psDec->LPC_order == 16 );
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  1 ], A_Q12[ 0 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  2 ], A_Q12[ 1 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  3 ], A_Q12[ 2 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  4 ], A_Q12[ 3 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  5 ], A_Q12[ 4 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  6 ], A_Q12[ 5 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  7 ], A_Q12[ 6 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  8 ], A_Q12[ 7 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i -  9 ], A_Q12[ 8 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 10 ], A_Q12[ 9 ] );
+            if( psDec->LPC_order == 16 ) {
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 11 ], A_Q12[ 10 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 12 ], A_Q12[ 11 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 13 ], A_Q12[ 12 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 14 ], A_Q12[ 13 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 15 ], A_Q12[ 14 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, CNG_sig_Q14[ MAX_LPC_ORDER + i - 16 ], A_Q12[ 15 ] );
+            }
+
+            /* Update states */
+            CNG_sig_Q14[ MAX_LPC_ORDER + i ] = silk_ADD_SAT32( CNG_sig_Q14[ MAX_LPC_ORDER + i ], silk_LSHIFT_SAT32( LPC_pred_Q10, 4 ) );
+
+            /* Scale with Gain and add to input signal */
+            frame[ i ] = (opus_int16)silk_ADD_SAT16( frame[ i ], silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( CNG_sig_Q14[ MAX_LPC_ORDER + i ], gain_Q10 ), 8 ) ) );
+
+        }
+        silk_memcpy( psCNG->CNG_synth_state, &CNG_sig_Q14[ length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
+    } else {
+        silk_memset( psCNG->CNG_synth_state, 0, psDec->LPC_order *  sizeof( opus_int32 ) );
+    }
+    RESTORE_STACK;
+}
diff --git a/opus/silk/HP_variable_cutoff.c b/opus/silk/HP_variable_cutoff.c
new file mode 100644 (file)
index 0000000..bbe10f0
--- /dev/null
@@ -0,0 +1,77 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#ifdef FIXED_POINT
+#include "main_FIX.h"
+#else
+#include "main_FLP.h"
+#endif
+#include "tuning_parameters.h"
+
+/* High-pass filter with cutoff frequency adaptation based on pitch lag statistics */
+void silk_HP_variable_cutoff(
+    silk_encoder_state_Fxx          state_Fxx[]                         /* I/O  Encoder states                              */
+)
+{
+   opus_int   quality_Q15;
+   opus_int32 pitch_freq_Hz_Q16, pitch_freq_log_Q7, delta_freq_Q7;
+   silk_encoder_state *psEncC1 = &state_Fxx[ 0 ].sCmn;
+
+   /* Adaptive cutoff frequency: estimate low end of pitch frequency range */
+   if( psEncC1->prevSignalType == TYPE_VOICED ) {
+      /* difference, in log domain */
+      pitch_freq_Hz_Q16 = silk_DIV32_16( silk_LSHIFT( silk_MUL( psEncC1->fs_kHz, 1000 ), 16 ), psEncC1->prevLag );
+      pitch_freq_log_Q7 = silk_lin2log( pitch_freq_Hz_Q16 ) - ( 16 << 7 );
+
+      /* adjustment based on quality */
+      quality_Q15 = psEncC1->input_quality_bands_Q15[ 0 ];
+      pitch_freq_log_Q7 = silk_SMLAWB( pitch_freq_log_Q7, silk_SMULWB( silk_LSHIFT( -quality_Q15, 2 ), quality_Q15 ),
+            pitch_freq_log_Q7 - ( silk_lin2log( SILK_FIX_CONST( VARIABLE_HP_MIN_CUTOFF_HZ, 16 ) ) - ( 16 << 7 ) ) );
+
+      /* delta_freq = pitch_freq_log - psEnc->variable_HP_smth1; */
+      delta_freq_Q7 = pitch_freq_log_Q7 - silk_RSHIFT( psEncC1->variable_HP_smth1_Q15, 8 );
+      if( delta_freq_Q7 < 0 ) {
+         /* less smoothing for decreasing pitch frequency, to track something close to the minimum */
+         delta_freq_Q7 = silk_MUL( delta_freq_Q7, 3 );
+      }
+
+      /* limit delta, to reduce impact of outliers in pitch estimation */
+      delta_freq_Q7 = silk_LIMIT_32( delta_freq_Q7, -SILK_FIX_CONST( VARIABLE_HP_MAX_DELTA_FREQ, 7 ), SILK_FIX_CONST( VARIABLE_HP_MAX_DELTA_FREQ, 7 ) );
+
+      /* update smoother */
+      psEncC1->variable_HP_smth1_Q15 = silk_SMLAWB( psEncC1->variable_HP_smth1_Q15,
+            silk_SMULBB( psEncC1->speech_activity_Q8, delta_freq_Q7 ), SILK_FIX_CONST( VARIABLE_HP_SMTH_COEF1, 16 ) );
+
+      /* limit frequency range */
+      psEncC1->variable_HP_smth1_Q15 = silk_LIMIT_32( psEncC1->variable_HP_smth1_Q15,
+            silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 ),
+            silk_LSHIFT( silk_lin2log( VARIABLE_HP_MAX_CUTOFF_HZ ), 8 ) );
+   }
+}
diff --git a/opus/silk/Inlines.h b/opus/silk/Inlines.h
new file mode 100644 (file)
index 0000000..ec986cd
--- /dev/null
@@ -0,0 +1,188 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+/*! \file silk_Inlines.h
+ *  \brief silk_Inlines.h defines OPUS_INLINE signal processing functions.
+ */
+
+#ifndef SILK_FIX_INLINES_H
+#define SILK_FIX_INLINES_H
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+/* count leading zeros of opus_int64 */
+static OPUS_INLINE opus_int32 silk_CLZ64( opus_int64 in )
+{
+    opus_int32 in_upper;
+
+    in_upper = (opus_int32)silk_RSHIFT64(in, 32);
+    if (in_upper == 0) {
+        /* Search in the lower 32 bits */
+        return 32 + silk_CLZ32( (opus_int32) in );
+    } else {
+        /* Search in the upper 32 bits */
+        return silk_CLZ32( in_upper );
+    }
+}
+
+/* get number of leading zeros and fractional part (the bits right after the leading one */
+static OPUS_INLINE void silk_CLZ_FRAC(
+    opus_int32 in,            /* I  input                               */
+    opus_int32 *lz,           /* O  number of leading zeros             */
+    opus_int32 *frac_Q7       /* O  the 7 bits right after the leading one */
+)
+{
+    opus_int32 lzeros = silk_CLZ32(in);
+
+    * lz = lzeros;
+    * frac_Q7 = silk_ROR32(in, 24 - lzeros) & 0x7f;
+}
+
+/* Approximation of square root                                          */
+/* Accuracy: < +/- 10%  for output values > 15                           */
+/*           < +/- 2.5% for output values > 120                          */
+static OPUS_INLINE opus_int32 silk_SQRT_APPROX( opus_int32 x )
+{
+    opus_int32 y, lz, frac_Q7;
+
+    if( x <= 0 ) {
+        return 0;
+    }
+
+    silk_CLZ_FRAC(x, &lz, &frac_Q7);
+
+    if( lz & 1 ) {
+        y = 32768;
+    } else {
+        y = 46214;        /* 46214 = sqrt(2) * 32768 */
+    }
+
+    /* get scaling right */
+    y >>= silk_RSHIFT(lz, 1);
+
+    /* increment using fractional part of input */
+    y = silk_SMLAWB(y, y, silk_SMULBB(213, frac_Q7));
+
+    return y;
+}
+
+/* Divide two int32 values and return result as int32 in a given Q-domain */
+static OPUS_INLINE opus_int32 silk_DIV32_varQ(   /* O    returns a good approximation of "(a32 << Qres) / b32" */
+    const opus_int32     a32,               /* I    numerator (Q0)                  */
+    const opus_int32     b32,               /* I    denominator (Q0)                */
+    const opus_int       Qres               /* I    Q-domain of result (>= 0)       */
+)
+{
+    opus_int   a_headrm, b_headrm, lshift;
+    opus_int32 b32_inv, a32_nrm, b32_nrm, result;
+
+    silk_assert( b32 != 0 );
+    silk_assert( Qres >= 0 );
+
+    /* Compute number of bits head room and normalize inputs */
+    a_headrm = silk_CLZ32( silk_abs(a32) ) - 1;
+    a32_nrm = silk_LSHIFT(a32, a_headrm);                                       /* Q: a_headrm                  */
+    b_headrm = silk_CLZ32( silk_abs(b32) ) - 1;
+    b32_nrm = silk_LSHIFT(b32, b_headrm);                                       /* Q: b_headrm                  */
+
+    /* Inverse of b32, with 14 bits of precision */
+    b32_inv = silk_DIV32_16( silk_int32_MAX >> 2, silk_RSHIFT(b32_nrm, 16) );   /* Q: 29 + 16 - b_headrm        */
+
+    /* First approximation */
+    result = silk_SMULWB(a32_nrm, b32_inv);                                     /* Q: 29 + a_headrm - b_headrm  */
+
+    /* Compute residual by subtracting product of denominator and first approximation */
+    /* It's OK to overflow because the final value of a32_nrm should always be small */
+    a32_nrm = silk_SUB32_ovflw(a32_nrm, silk_LSHIFT_ovflw( silk_SMMUL(b32_nrm, result), 3 ));  /* Q: a_headrm   */
+
+    /* Refinement */
+    result = silk_SMLAWB(result, a32_nrm, b32_inv);                             /* Q: 29 + a_headrm - b_headrm  */
+
+    /* Convert to Qres domain */
+    lshift = 29 + a_headrm - b_headrm - Qres;
+    if( lshift < 0 ) {
+        return silk_LSHIFT_SAT32(result, -lshift);
+    } else {
+        if( lshift < 32){
+            return silk_RSHIFT(result, lshift);
+        } else {
+            /* Avoid undefined result */
+            return 0;
+        }
+    }
+}
+
+/* Invert int32 value and return result as int32 in a given Q-domain */
+static OPUS_INLINE opus_int32 silk_INVERSE32_varQ(   /* O    returns a good approximation of "(1 << Qres) / b32" */
+    const opus_int32     b32,                   /* I    denominator (Q0)                */
+    const opus_int       Qres                   /* I    Q-domain of result (> 0)        */
+)
+{
+    opus_int   b_headrm, lshift;
+    opus_int32 b32_inv, b32_nrm, err_Q32, result;
+
+    silk_assert( b32 != 0 );
+    silk_assert( Qres > 0 );
+
+    /* Compute number of bits head room and normalize input */
+    b_headrm = silk_CLZ32( silk_abs(b32) ) - 1;
+    b32_nrm = silk_LSHIFT(b32, b_headrm);                                       /* Q: b_headrm                */
+
+    /* Inverse of b32, with 14 bits of precision */
+    b32_inv = silk_DIV32_16( silk_int32_MAX >> 2, silk_RSHIFT(b32_nrm, 16) );   /* Q: 29 + 16 - b_headrm    */
+
+    /* First approximation */
+    result = silk_LSHIFT(b32_inv, 16);                                          /* Q: 61 - b_headrm            */
+
+    /* Compute residual by subtracting product of denominator and first approximation from one */
+    err_Q32 = silk_LSHIFT( ((opus_int32)1<<29) - silk_SMULWB(b32_nrm, b32_inv), 3 );        /* Q32                        */
+
+    /* Refinement */
+    result = silk_SMLAWW(result, err_Q32, b32_inv);                             /* Q: 61 - b_headrm            */
+
+    /* Convert to Qres domain */
+    lshift = 61 - b_headrm - Qres;
+    if( lshift <= 0 ) {
+        return silk_LSHIFT_SAT32(result, -lshift);
+    } else {
+        if( lshift < 32){
+            return silk_RSHIFT(result, lshift);
+        }else{
+            /* Avoid undefined result */
+            return 0;
+        }
+    }
+}
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif /* SILK_FIX_INLINES_H */
diff --git a/opus/silk/LPC_analysis_filter.c b/opus/silk/LPC_analysis_filter.c
new file mode 100644 (file)
index 0000000..7715f70
--- /dev/null
@@ -0,0 +1,111 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "celt_lpc.h"
+
+/*******************************************/
+/* LPC analysis filter                     */
+/* NB! State is kept internally and the    */
+/* filter always starts with zero state    */
+/* first d output samples are set to zero  */
+/*******************************************/
+
+/* OPT: Using celt_fir() for this function should be faster, but it may cause
+   integer overflows in intermediate values (not final results), which the
+   current implementation silences by casting to unsigned. Enabling
+   this should be safe in pretty much all cases, even though it is not technically
+   C89-compliant. */
+#define USE_CELT_FIR 0
+
+void silk_LPC_analysis_filter(
+    opus_int16                  *out,               /* O    Output signal                                               */
+    const opus_int16            *in,                /* I    Input signal                                                */
+    const opus_int16            *B,                 /* I    MA prediction coefficients, Q12 [order]                     */
+    const opus_int32            len,                /* I    Signal length                                               */
+    const opus_int32            d,                  /* I    Filter order                                                */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    opus_int   j;
+#if defined(FIXED_POINT) && USE_CELT_FIR
+    opus_int16 num[SILK_MAX_ORDER_LPC];
+#else
+    int ix;
+    opus_int32       out32_Q12, out32;
+    const opus_int16 *in_ptr;
+#endif
+
+    silk_assert( d >= 6 );
+    silk_assert( (d & 1) == 0 );
+    silk_assert( d <= len );
+
+#if defined(FIXED_POINT) && USE_CELT_FIR
+    silk_assert( d <= SILK_MAX_ORDER_LPC );
+    for ( j = 0; j < d; j++ ) {
+        num[ j ] = -B[ j ];
+    }
+    celt_fir( in + d, num, out + d, len - d, d, arch );
+    for ( j = 0; j < d; j++ ) {
+        out[ j ] = 0;
+    }
+#else
+    (void)arch;
+    for( ix = d; ix < len; ix++ ) {
+        in_ptr = &in[ ix - 1 ];
+
+        out32_Q12 = silk_SMULBB( in_ptr[  0 ], B[ 0 ] );
+        /* Allowing wrap around so that two wraps can cancel each other. The rare
+           cases where the result wraps around can only be triggered by invalid streams*/
+        out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -1 ], B[ 1 ] );
+        out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -2 ], B[ 2 ] );
+        out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -3 ], B[ 3 ] );
+        out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -4 ], B[ 4 ] );
+        out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -5 ], B[ 5 ] );
+        for( j = 6; j < d; j += 2 ) {
+            out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -j     ], B[ j     ] );
+            out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -j - 1 ], B[ j + 1 ] );
+        }
+
+        /* Subtract prediction */
+        out32_Q12 = silk_SUB32_ovflw( silk_LSHIFT( (opus_int32)in_ptr[ 1 ], 12 ), out32_Q12 );
+
+        /* Scale to Q0 */
+        out32 = silk_RSHIFT_ROUND( out32_Q12, 12 );
+
+        /* Saturate output */
+        out[ ix ] = (opus_int16)silk_SAT16( out32 );
+    }
+
+    /* Set first d output samples to zero */
+    silk_memset( out, 0, d * sizeof( opus_int16 ) );
+#endif
+}
diff --git a/opus/silk/LPC_fit.c b/opus/silk/LPC_fit.c
new file mode 100644 (file)
index 0000000..cdea4f3
--- /dev/null
@@ -0,0 +1,81 @@
+/***********************************************************************
+Copyright (c) 2013, Koen Vos. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Convert int32 coefficients to int16 coefs and make sure there's no wrap-around */
+void silk_LPC_fit(
+    opus_int16                  *a_QOUT,            /* O    Output signal                                               */
+    opus_int32                    *a_QIN,             /* I/O  Input signal                                                */
+    const opus_int              QOUT,               /* I    Input Q domain                                              */
+    const opus_int              QIN,                /* I    Input Q domain                                              */
+    const opus_int              d                   /* I    Filter order                                                */
+)
+{
+    opus_int    i, k, idx = 0;
+    opus_int32    maxabs, absval, chirp_Q16;
+
+    /* Limit the maximum absolute value of the prediction coefficients, so that they'll fit in int16 */
+    for( i = 0; i < 10; i++ ) {
+        /* Find maximum absolute value and its index */
+        maxabs = 0;
+        for( k = 0; k < d; k++ ) {
+            absval = silk_abs( a_QIN[k] );
+            if( absval > maxabs ) {
+                maxabs = absval;
+                idx    = k;
+            }
+        }
+        maxabs = silk_RSHIFT_ROUND( maxabs, QIN - QOUT );
+
+        if( maxabs > silk_int16_MAX ) {
+            /* Reduce magnitude of prediction coefficients */
+            maxabs = silk_min( maxabs, 163838 );  /* ( silk_int32_MAX >> 14 ) + silk_int16_MAX = 163838 */
+            chirp_Q16 = SILK_FIX_CONST( 0.999, 16 ) - silk_DIV32( silk_LSHIFT( maxabs - silk_int16_MAX, 14 ),
+                                        silk_RSHIFT32( silk_MUL( maxabs, idx + 1), 2 ) );
+            silk_bwexpander_32( a_QIN, d, chirp_Q16 );
+        } else {
+            break;
+        }
+    }
+
+    if( i == 10 ) {
+        /* Reached the last iteration, clip the coefficients */
+        for( k = 0; k < d; k++ ) {
+            a_QOUT[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( a_QIN[ k ], QIN - QOUT ) );
+            a_QIN[ k ] = silk_LSHIFT( (opus_int32)a_QOUT[ k ], QIN - QOUT );
+        }
+    } else {
+        for( k = 0; k < d; k++ ) {
+            a_QOUT[ k ] = (opus_int16)silk_RSHIFT_ROUND( a_QIN[ k ], QIN - QOUT );
+        }
+    }
+}
diff --git a/opus/silk/LPC_inv_pred_gain.c b/opus/silk/LPC_inv_pred_gain.c
new file mode 100644 (file)
index 0000000..a3746a6
--- /dev/null
@@ -0,0 +1,141 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "define.h"
+
+#define QA                          24
+#define A_LIMIT                     SILK_FIX_CONST( 0.99975, QA )
+
+#define MUL32_FRAC_Q(a32, b32, Q)   ((opus_int32)(silk_RSHIFT_ROUND64(silk_SMULL(a32, b32), Q)))
+
+/* Compute inverse of LPC prediction gain, and                          */
+/* test if LPC coefficients are stable (all poles within unit circle)   */
+static opus_int32 LPC_inverse_pred_gain_QA_c(               /* O   Returns inverse prediction gain in energy domain, Q30    */
+    opus_int32           A_QA[ SILK_MAX_ORDER_LPC ],        /* I   Prediction coefficients                                  */
+    const opus_int       order                              /* I   Prediction order                                         */
+)
+{
+    opus_int   k, n, mult2Q;
+    opus_int32 invGain_Q30, rc_Q31, rc_mult1_Q30, rc_mult2, tmp1, tmp2;
+
+    invGain_Q30 = SILK_FIX_CONST( 1, 30 );
+    for( k = order - 1; k > 0; k-- ) {
+        /* Check for stability */
+        if( ( A_QA[ k ] > A_LIMIT ) || ( A_QA[ k ] < -A_LIMIT ) ) {
+            return 0;
+        }
+
+        /* Set RC equal to negated AR coef */
+        rc_Q31 = -silk_LSHIFT( A_QA[ k ], 31 - QA );
+
+        /* rc_mult1_Q30 range: [ 1 : 2^30 ] */
+        rc_mult1_Q30 = silk_SUB32( SILK_FIX_CONST( 1, 30 ), silk_SMMUL( rc_Q31, rc_Q31 ) );
+        silk_assert( rc_mult1_Q30 > ( 1 << 15 ) );                   /* reduce A_LIMIT if fails */
+        silk_assert( rc_mult1_Q30 <= ( 1 << 30 ) );
+
+        /* Update inverse gain */
+        /* invGain_Q30 range: [ 0 : 2^30 ] */
+        invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
+        silk_assert( invGain_Q30 >= 0           );
+        silk_assert( invGain_Q30 <= ( 1 << 30 ) );
+        if( invGain_Q30 < SILK_FIX_CONST( 1.0f / MAX_PREDICTION_POWER_GAIN, 30 ) ) {
+            return 0;
+        }
+
+        /* rc_mult2 range: [ 2^30 : silk_int32_MAX ] */
+        mult2Q = 32 - silk_CLZ32( silk_abs( rc_mult1_Q30 ) );
+        rc_mult2 = silk_INVERSE32_varQ( rc_mult1_Q30, mult2Q + 30 );
+
+        /* Update AR coefficient */
+        for( n = 0; n < (k + 1) >> 1; n++ ) {
+            opus_int64 tmp64;
+            tmp1 = A_QA[ n ];
+            tmp2 = A_QA[ k - n - 1 ];
+            tmp64 = silk_RSHIFT_ROUND64( silk_SMULL( silk_SUB_SAT32(tmp1,
+                  MUL32_FRAC_Q( tmp2, rc_Q31, 31 ) ), rc_mult2 ), mult2Q);
+            if( tmp64 > silk_int32_MAX || tmp64 < silk_int32_MIN ) {
+               return 0;
+            }
+            A_QA[ n ] = ( opus_int32 )tmp64;
+            tmp64 = silk_RSHIFT_ROUND64( silk_SMULL( silk_SUB_SAT32(tmp2,
+                  MUL32_FRAC_Q( tmp1, rc_Q31, 31 ) ), rc_mult2), mult2Q);
+            if( tmp64 > silk_int32_MAX || tmp64 < silk_int32_MIN ) {
+               return 0;
+            }
+            A_QA[ k - n - 1 ] = ( opus_int32 )tmp64;
+        }
+    }
+
+    /* Check for stability */
+    if( ( A_QA[ k ] > A_LIMIT ) || ( A_QA[ k ] < -A_LIMIT ) ) {
+        return 0;
+    }
+
+    /* Set RC equal to negated AR coef */
+    rc_Q31 = -silk_LSHIFT( A_QA[ 0 ], 31 - QA );
+
+    /* Range: [ 1 : 2^30 ] */
+    rc_mult1_Q30 = silk_SUB32( SILK_FIX_CONST( 1, 30 ), silk_SMMUL( rc_Q31, rc_Q31 ) );
+
+    /* Update inverse gain */
+    /* Range: [ 0 : 2^30 ] */
+    invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
+    silk_assert( invGain_Q30 >= 0           );
+    silk_assert( invGain_Q30 <= ( 1 << 30 ) );
+    if( invGain_Q30 < SILK_FIX_CONST( 1.0f / MAX_PREDICTION_POWER_GAIN, 30 ) ) {
+        return 0;
+    }
+
+    return invGain_Q30;
+}
+
+/* For input in Q12 domain */
+opus_int32 silk_LPC_inverse_pred_gain_c(            /* O   Returns inverse prediction gain in energy domain, Q30        */
+    const opus_int16            *A_Q12,             /* I   Prediction coefficients, Q12 [order]                         */
+    const opus_int              order               /* I   Prediction order                                             */
+)
+{
+    opus_int   k;
+    opus_int32 Atmp_QA[ SILK_MAX_ORDER_LPC ];
+    opus_int32 DC_resp = 0;
+
+    /* Increase Q domain of the AR coefficients */
+    for( k = 0; k < order; k++ ) {
+        DC_resp += (opus_int32)A_Q12[ k ];
+        Atmp_QA[ k ] = silk_LSHIFT32( (opus_int32)A_Q12[ k ], QA - 12 );
+    }
+    /* If the DC is unstable, we don't even need to do the full calculations */
+    if( DC_resp >= 4096 ) {
+        return 0;
+    }
+    return LPC_inverse_pred_gain_QA_c( Atmp_QA, order );
+}
diff --git a/opus/silk/LP_variable_cutoff.c b/opus/silk/LP_variable_cutoff.c
new file mode 100644 (file)
index 0000000..79112ad
--- /dev/null
@@ -0,0 +1,135 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*
+    Elliptic/Cauer filters designed with 0.1 dB passband ripple,
+    80 dB minimum stopband attenuation, and
+    [0.95 : 0.15 : 0.35] normalized cut off frequencies.
+*/
+
+#include "main.h"
+
+/* Helper function, interpolates the filter taps */
+static OPUS_INLINE void silk_LP_interpolate_filter_taps(
+    opus_int32           B_Q28[ TRANSITION_NB ],
+    opus_int32           A_Q28[ TRANSITION_NA ],
+    const opus_int       ind,
+    const opus_int32     fac_Q16
+)
+{
+    opus_int nb, na;
+
+    if( ind < TRANSITION_INT_NUM - 1 ) {
+        if( fac_Q16 > 0 ) {
+            if( fac_Q16 < 32768 ) { /* fac_Q16 is in range of a 16-bit int */
+                /* Piece-wise linear interpolation of B and A */
+                for( nb = 0; nb < TRANSITION_NB; nb++ ) {
+                    B_Q28[ nb ] = silk_SMLAWB(
+                        silk_Transition_LP_B_Q28[ ind     ][ nb ],
+                        silk_Transition_LP_B_Q28[ ind + 1 ][ nb ] -
+                        silk_Transition_LP_B_Q28[ ind     ][ nb ],
+                        fac_Q16 );
+                }
+                for( na = 0; na < TRANSITION_NA; na++ ) {
+                    A_Q28[ na ] = silk_SMLAWB(
+                        silk_Transition_LP_A_Q28[ ind     ][ na ],
+                        silk_Transition_LP_A_Q28[ ind + 1 ][ na ] -
+                        silk_Transition_LP_A_Q28[ ind     ][ na ],
+                        fac_Q16 );
+                }
+            } else { /* ( fac_Q16 - ( 1 << 16 ) ) is in range of a 16-bit int */
+                silk_assert( fac_Q16 - ( 1 << 16 ) == silk_SAT16( fac_Q16 - ( 1 << 16 ) ) );
+                /* Piece-wise linear interpolation of B and A */
+                for( nb = 0; nb < TRANSITION_NB; nb++ ) {
+                    B_Q28[ nb ] = silk_SMLAWB(
+                        silk_Transition_LP_B_Q28[ ind + 1 ][ nb ],
+                        silk_Transition_LP_B_Q28[ ind + 1 ][ nb ] -
+                        silk_Transition_LP_B_Q28[ ind     ][ nb ],
+                        fac_Q16 - ( (opus_int32)1 << 16 ) );
+                }
+                for( na = 0; na < TRANSITION_NA; na++ ) {
+                    A_Q28[ na ] = silk_SMLAWB(
+                        silk_Transition_LP_A_Q28[ ind + 1 ][ na ],
+                        silk_Transition_LP_A_Q28[ ind + 1 ][ na ] -
+                        silk_Transition_LP_A_Q28[ ind     ][ na ],
+                        fac_Q16 - ( (opus_int32)1 << 16 ) );
+                }
+            }
+        } else {
+            silk_memcpy( B_Q28, silk_Transition_LP_B_Q28[ ind ], TRANSITION_NB * sizeof( opus_int32 ) );
+            silk_memcpy( A_Q28, silk_Transition_LP_A_Q28[ ind ], TRANSITION_NA * sizeof( opus_int32 ) );
+        }
+    } else {
+        silk_memcpy( B_Q28, silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM - 1 ], TRANSITION_NB * sizeof( opus_int32 ) );
+        silk_memcpy( A_Q28, silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM - 1 ], TRANSITION_NA * sizeof( opus_int32 ) );
+    }
+}
+
+/* Low-pass filter with variable cutoff frequency based on  */
+/* piece-wise linear interpolation between elliptic filters */
+/* Start by setting psEncC->mode <> 0;                      */
+/* Deactivate by setting psEncC->mode = 0;                  */
+void silk_LP_variable_cutoff(
+    silk_LP_state               *psLP,                          /* I/O  LP filter state                             */
+    opus_int16                  *frame,                         /* I/O  Low-pass filtered output signal             */
+    const opus_int              frame_length                    /* I    Frame length                                */
+)
+{
+    opus_int32   B_Q28[ TRANSITION_NB ], A_Q28[ TRANSITION_NA ], fac_Q16 = 0;
+    opus_int     ind = 0;
+
+    silk_assert( psLP->transition_frame_no >= 0 && psLP->transition_frame_no <= TRANSITION_FRAMES );
+
+    /* Run filter if needed */
+    if( psLP->mode != 0 ) {
+        /* Calculate index and interpolation factor for interpolation */
+#if( TRANSITION_INT_STEPS == 64 )
+        fac_Q16 = silk_LSHIFT( TRANSITION_FRAMES - psLP->transition_frame_no, 16 - 6 );
+#else
+        fac_Q16 = silk_DIV32_16( silk_LSHIFT( TRANSITION_FRAMES - psLP->transition_frame_no, 16 ), TRANSITION_FRAMES );
+#endif
+        ind      = silk_RSHIFT( fac_Q16, 16 );
+        fac_Q16 -= silk_LSHIFT( ind, 16 );
+
+        silk_assert( ind >= 0 );
+        silk_assert( ind < TRANSITION_INT_NUM );
+
+        /* Interpolate filter coefficients */
+        silk_LP_interpolate_filter_taps( B_Q28, A_Q28, ind, fac_Q16 );
+
+        /* Update transition frame number for next frame */
+        psLP->transition_frame_no = silk_LIMIT( psLP->transition_frame_no + psLP->mode, 0, TRANSITION_FRAMES );
+
+        /* ARMA low-pass filtering */
+        silk_assert( TRANSITION_NB == 3 && TRANSITION_NA == 2 );
+        silk_biquad_alt_stride1( frame, B_Q28, A_Q28, psLP->In_LP_State, frame, frame_length);
+    }
+}
diff --git a/opus/silk/MacroCount.h b/opus/silk/MacroCount.h
new file mode 100644 (file)
index 0000000..78100ff
--- /dev/null
@@ -0,0 +1,710 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SIGPROCFIX_API_MACROCOUNT_H
+#define SIGPROCFIX_API_MACROCOUNT_H
+#include <stdio.h>
+
+#ifdef    silk_MACRO_COUNT
+#define varDefine opus_int64 ops_count = 0;
+
+extern opus_int64 ops_count;
+
+static OPUS_INLINE opus_int64 silk_SaveCount(){
+    return(ops_count);
+}
+
+static OPUS_INLINE opus_int64 silk_SaveResetCount(){
+    opus_int64 ret;
+
+    ret = ops_count;
+    ops_count = 0;
+    return(ret);
+}
+
+static OPUS_INLINE silk_PrintCount(){
+    printf("ops_count = %d \n ", (opus_int32)ops_count);
+}
+
+#undef silk_MUL
+static OPUS_INLINE opus_int32 silk_MUL(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    ops_count += 4;
+    ret = a32 * b32;
+    return ret;
+}
+
+#undef silk_MUL_uint
+static OPUS_INLINE opus_uint32 silk_MUL_uint(opus_uint32 a32, opus_uint32 b32){
+    opus_uint32 ret;
+    ops_count += 4;
+    ret = a32 * b32;
+    return ret;
+}
+#undef silk_MLA
+static OPUS_INLINE opus_int32 silk_MLA(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 4;
+    ret = a32 + b32 * c32;
+    return ret;
+}
+
+#undef silk_MLA_uint
+static OPUS_INLINE opus_int32 silk_MLA_uint(opus_uint32 a32, opus_uint32 b32, opus_uint32 c32){
+    opus_uint32 ret;
+    ops_count += 4;
+    ret = a32 + b32 * c32;
+    return ret;
+}
+
+#undef silk_SMULWB
+static OPUS_INLINE opus_int32 silk_SMULWB(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    ops_count += 5;
+    ret = (a32 >> 16) * (opus_int32)((opus_int16)b32) + (((a32 & 0x0000FFFF) * (opus_int32)((opus_int16)b32)) >> 16);
+    return ret;
+}
+#undef    silk_SMLAWB
+static OPUS_INLINE opus_int32 silk_SMLAWB(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 5;
+    ret = ((a32) + ((((b32) >> 16) * (opus_int32)((opus_int16)(c32))) + ((((b32) & 0x0000FFFF) * (opus_int32)((opus_int16)(c32))) >> 16)));
+    return ret;
+}
+
+#undef silk_SMULWT
+static OPUS_INLINE opus_int32 silk_SMULWT(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    ops_count += 4;
+    ret = (a32 >> 16) * (b32 >> 16) + (((a32 & 0x0000FFFF) * (b32 >> 16)) >> 16);
+    return ret;
+}
+#undef silk_SMLAWT
+static OPUS_INLINE opus_int32 silk_SMLAWT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 4;
+    ret = a32 + ((b32 >> 16) * (c32 >> 16)) + (((b32 & 0x0000FFFF) * ((c32 >> 16)) >> 16));
+    return ret;
+}
+
+#undef silk_SMULBB
+static OPUS_INLINE opus_int32 silk_SMULBB(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = (opus_int32)((opus_int16)a32) * (opus_int32)((opus_int16)b32);
+    return ret;
+}
+#undef silk_SMLABB
+static OPUS_INLINE opus_int32 silk_SMLABB(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a32 + (opus_int32)((opus_int16)b32) * (opus_int32)((opus_int16)c32);
+    return ret;
+}
+
+#undef silk_SMULBT
+static OPUS_INLINE opus_int32 silk_SMULBT(opus_int32 a32, opus_int32 b32 ){
+    opus_int32 ret;
+    ops_count += 4;
+    ret = ((opus_int32)((opus_int16)a32)) * (b32 >> 16);
+    return ret;
+}
+
+#undef silk_SMLABT
+static OPUS_INLINE opus_int32 silk_SMLABT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a32 + ((opus_int32)((opus_int16)b32)) * (c32 >> 16);
+    return ret;
+}
+
+#undef silk_SMULTT
+static OPUS_INLINE opus_int32 silk_SMULTT(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = (a32 >> 16) * (b32 >> 16);
+    return ret;
+}
+
+#undef    silk_SMLATT
+static OPUS_INLINE opus_int32 silk_SMLATT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a32 + (b32 >> 16) * (c32 >> 16);
+    return ret;
+}
+
+
+/* multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode)*/
+#undef    silk_MLA_ovflw
+#define silk_MLA_ovflw silk_MLA
+
+#undef silk_SMLABB_ovflw
+#define silk_SMLABB_ovflw silk_SMLABB
+
+#undef silk_SMLABT_ovflw
+#define silk_SMLABT_ovflw silk_SMLABT
+
+#undef silk_SMLATT_ovflw
+#define silk_SMLATT_ovflw silk_SMLATT
+
+#undef silk_SMLAWB_ovflw
+#define silk_SMLAWB_ovflw silk_SMLAWB
+
+#undef silk_SMLAWT_ovflw
+#define silk_SMLAWT_ovflw silk_SMLAWT
+
+#undef silk_SMULL
+static OPUS_INLINE opus_int64 silk_SMULL(opus_int32 a32, opus_int32 b32){
+    opus_int64 ret;
+    ops_count += 8;
+    ret = ((opus_int64)(a32) * /*(opus_int64)*/(b32));
+    return ret;
+}
+
+#undef    silk_SMLAL
+static OPUS_INLINE opus_int64 silk_SMLAL(opus_int64 a64, opus_int32 b32, opus_int32 c32){
+    opus_int64 ret;
+    ops_count += 8;
+    ret = a64 + ((opus_int64)(b32) * /*(opus_int64)*/(c32));
+    return ret;
+}
+#undef    silk_SMLALBB
+static OPUS_INLINE opus_int64 silk_SMLALBB(opus_int64 a64, opus_int16 b16, opus_int16 c16){
+    opus_int64 ret;
+    ops_count += 4;
+    ret = a64 + ((opus_int64)(b16) * /*(opus_int64)*/(c16));
+    return ret;
+}
+
+#undef    SigProcFIX_CLZ16
+static OPUS_INLINE opus_int32 SigProcFIX_CLZ16(opus_int16 in16)
+{
+    opus_int32 out32 = 0;
+    ops_count += 10;
+    if( in16 == 0 ) {
+        return 16;
+    }
+    /* test nibbles */
+    if( in16 & 0xFF00 ) {
+        if( in16 & 0xF000 ) {
+            in16 >>= 12;
+        } else {
+            out32 += 4;
+            in16 >>= 8;
+        }
+    } else {
+        if( in16 & 0xFFF0 ) {
+            out32 += 8;
+            in16 >>= 4;
+        } else {
+            out32 += 12;
+        }
+    }
+    /* test bits and return */
+    if( in16 & 0xC ) {
+        if( in16 & 0x8 )
+            return out32 + 0;
+        else
+            return out32 + 1;
+    } else {
+        if( in16 & 0xE )
+            return out32 + 2;
+        else
+            return out32 + 3;
+    }
+}
+
+#undef SigProcFIX_CLZ32
+static OPUS_INLINE opus_int32 SigProcFIX_CLZ32(opus_int32 in32)
+{
+    /* test highest 16 bits and convert to opus_int16 */
+    ops_count += 2;
+    if( in32 & 0xFFFF0000 ) {
+        return SigProcFIX_CLZ16((opus_int16)(in32 >> 16));
+    } else {
+        return SigProcFIX_CLZ16((opus_int16)in32) + 16;
+    }
+}
+
+#undef silk_DIV32
+static OPUS_INLINE opus_int32 silk_DIV32(opus_int32 a32, opus_int32 b32){
+    ops_count += 64;
+    return a32 / b32;
+}
+
+#undef silk_DIV32_16
+static OPUS_INLINE opus_int32 silk_DIV32_16(opus_int32 a32, opus_int32 b32){
+    ops_count += 32;
+    return a32 / b32;
+}
+
+#undef silk_SAT8
+static OPUS_INLINE opus_int8 silk_SAT8(opus_int64 a){
+    opus_int8 tmp;
+    ops_count += 1;
+    tmp = (opus_int8)((a) > silk_int8_MAX ? silk_int8_MAX  : \
+                    ((a) < silk_int8_MIN ? silk_int8_MIN  : (a)));
+    return(tmp);
+}
+
+#undef silk_SAT16
+static OPUS_INLINE opus_int16 silk_SAT16(opus_int64 a){
+    opus_int16 tmp;
+    ops_count += 1;
+    tmp = (opus_int16)((a) > silk_int16_MAX ? silk_int16_MAX  : \
+                     ((a) < silk_int16_MIN ? silk_int16_MIN  : (a)));
+    return(tmp);
+}
+#undef silk_SAT32
+static OPUS_INLINE opus_int32 silk_SAT32(opus_int64 a){
+    opus_int32 tmp;
+    ops_count += 1;
+    tmp = (opus_int32)((a) > silk_int32_MAX ? silk_int32_MAX  : \
+                     ((a) < silk_int32_MIN ? silk_int32_MIN  : (a)));
+    return(tmp);
+}
+#undef silk_POS_SAT32
+static OPUS_INLINE opus_int32 silk_POS_SAT32(opus_int64 a){
+    opus_int32 tmp;
+    ops_count += 1;
+    tmp = (opus_int32)((a) > silk_int32_MAX ? silk_int32_MAX : (a));
+    return(tmp);
+}
+
+#undef silk_ADD_POS_SAT8
+static OPUS_INLINE opus_int8 silk_ADD_POS_SAT8(opus_int64 a, opus_int64 b){
+    opus_int8 tmp;
+    ops_count += 1;
+    tmp = (opus_int8)((((a)+(b)) & 0x80) ? silk_int8_MAX  : ((a)+(b)));
+    return(tmp);
+}
+#undef silk_ADD_POS_SAT16
+static OPUS_INLINE opus_int16 silk_ADD_POS_SAT16(opus_int64 a, opus_int64 b){
+    opus_int16 tmp;
+    ops_count += 1;
+    tmp = (opus_int16)((((a)+(b)) & 0x8000) ? silk_int16_MAX : ((a)+(b)));
+    return(tmp);
+}
+
+#undef silk_ADD_POS_SAT32
+static OPUS_INLINE opus_int32 silk_ADD_POS_SAT32(opus_int64 a, opus_int64 b){
+    opus_int32 tmp;
+    ops_count += 1;
+    tmp = (opus_int32)((((a)+(b)) & 0x80000000) ? silk_int32_MAX : ((a)+(b)));
+    return(tmp);
+}
+
+#undef    silk_LSHIFT8
+static OPUS_INLINE opus_int8 silk_LSHIFT8(opus_int8 a, opus_int32 shift){
+    opus_int8 ret;
+    ops_count += 1;
+    ret = a << shift;
+    return ret;
+}
+#undef    silk_LSHIFT16
+static OPUS_INLINE opus_int16 silk_LSHIFT16(opus_int16 a, opus_int32 shift){
+    opus_int16 ret;
+    ops_count += 1;
+    ret = a << shift;
+    return ret;
+}
+#undef    silk_LSHIFT32
+static OPUS_INLINE opus_int32 silk_LSHIFT32(opus_int32 a, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a << shift;
+    return ret;
+}
+#undef    silk_LSHIFT64
+static OPUS_INLINE opus_int64 silk_LSHIFT64(opus_int64 a, opus_int shift){
+    ops_count += 1;
+    return a << shift;
+}
+
+#undef    silk_LSHIFT_ovflw
+static OPUS_INLINE opus_int32 silk_LSHIFT_ovflw(opus_int32 a, opus_int32 shift){
+    ops_count += 1;
+    return a << shift;
+}
+
+#undef    silk_LSHIFT_uint
+static OPUS_INLINE opus_uint32 silk_LSHIFT_uint(opus_uint32 a, opus_int32 shift){
+    opus_uint32 ret;
+    ops_count += 1;
+    ret = a << shift;
+    return ret;
+}
+
+#undef    silk_RSHIFT8
+static OPUS_INLINE opus_int8 silk_RSHIFT8(opus_int8 a, opus_int32 shift){
+    ops_count += 1;
+    return a >> shift;
+}
+#undef    silk_RSHIFT16
+static OPUS_INLINE opus_int16 silk_RSHIFT16(opus_int16 a, opus_int32 shift){
+    ops_count += 1;
+    return a >> shift;
+}
+#undef    silk_RSHIFT32
+static OPUS_INLINE opus_int32 silk_RSHIFT32(opus_int32 a, opus_int32 shift){
+    ops_count += 1;
+    return a >> shift;
+}
+#undef    silk_RSHIFT64
+static OPUS_INLINE opus_int64 silk_RSHIFT64(opus_int64 a, opus_int64 shift){
+    ops_count += 1;
+    return a >> shift;
+}
+
+#undef    silk_RSHIFT_uint
+static OPUS_INLINE opus_uint32 silk_RSHIFT_uint(opus_uint32 a, opus_int32 shift){
+    ops_count += 1;
+    return a >> shift;
+}
+
+#undef    silk_ADD_LSHIFT
+static OPUS_INLINE opus_int32 silk_ADD_LSHIFT(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a + (b << shift);
+    return ret;                /* shift >= 0*/
+}
+#undef    silk_ADD_LSHIFT32
+static OPUS_INLINE opus_int32 silk_ADD_LSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a + (b << shift);
+    return ret;                /* shift >= 0*/
+}
+#undef    silk_ADD_LSHIFT_uint
+static OPUS_INLINE opus_uint32 silk_ADD_LSHIFT_uint(opus_uint32 a, opus_uint32 b, opus_int32 shift){
+    opus_uint32 ret;
+    ops_count += 1;
+    ret = a + (b << shift);
+    return ret;                /* shift >= 0*/
+}
+#undef    silk_ADD_RSHIFT
+static OPUS_INLINE opus_int32 silk_ADD_RSHIFT(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a + (b >> shift);
+    return ret;                /* shift  > 0*/
+}
+#undef    silk_ADD_RSHIFT32
+static OPUS_INLINE opus_int32 silk_ADD_RSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a + (b >> shift);
+    return ret;                /* shift  > 0*/
+}
+#undef    silk_ADD_RSHIFT_uint
+static OPUS_INLINE opus_uint32 silk_ADD_RSHIFT_uint(opus_uint32 a, opus_uint32 b, opus_int32 shift){
+    opus_uint32 ret;
+    ops_count += 1;
+    ret = a + (b >> shift);
+    return ret;                /* shift  > 0*/
+}
+#undef    silk_SUB_LSHIFT32
+static OPUS_INLINE opus_int32 silk_SUB_LSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a - (b << shift);
+    return ret;                /* shift >= 0*/
+}
+#undef    silk_SUB_RSHIFT32
+static OPUS_INLINE opus_int32 silk_SUB_RSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a - (b >> shift);
+    return ret;                /* shift  > 0*/
+}
+
+#undef    silk_RSHIFT_ROUND
+static OPUS_INLINE opus_int32 silk_RSHIFT_ROUND(opus_int32 a, opus_int32 shift){
+    opus_int32 ret;
+    ops_count += 3;
+    ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
+    return ret;
+}
+
+#undef    silk_RSHIFT_ROUND64
+static OPUS_INLINE opus_int64 silk_RSHIFT_ROUND64(opus_int64 a, opus_int32 shift){
+    opus_int64 ret;
+    ops_count += 6;
+    ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
+    return ret;
+}
+
+#undef    silk_abs_int64
+static OPUS_INLINE opus_int64 silk_abs_int64(opus_int64 a){
+    ops_count += 1;
+    return (((a) >  0)  ? (a) : -(a));            /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN*/
+}
+
+#undef    silk_abs_int32
+static OPUS_INLINE opus_int32 silk_abs_int32(opus_int32 a){
+    ops_count += 1;
+    return silk_abs(a);
+}
+
+
+#undef silk_min
+static silk_min(a, b){
+    ops_count += 1;
+    return (((a) < (b)) ? (a) :  (b));
+}
+#undef silk_max
+static silk_max(a, b){
+    ops_count += 1;
+    return (((a) > (b)) ? (a) :  (b));
+}
+#undef silk_sign
+static silk_sign(a){
+    ops_count += 1;
+    return ((a) > 0 ? 1 : ( (a) < 0 ? -1 : 0 ));
+}
+
+#undef    silk_ADD16
+static OPUS_INLINE opus_int16 silk_ADD16(opus_int16 a, opus_int16 b){
+    opus_int16 ret;
+    ops_count += 1;
+    ret = a + b;
+    return ret;
+}
+
+#undef    silk_ADD32
+static OPUS_INLINE opus_int32 silk_ADD32(opus_int32 a, opus_int32 b){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a + b;
+    return ret;
+}
+
+#undef    silk_ADD64
+static OPUS_INLINE opus_int64 silk_ADD64(opus_int64 a, opus_int64 b){
+    opus_int64 ret;
+    ops_count += 2;
+    ret = a + b;
+    return ret;
+}
+
+#undef    silk_SUB16
+static OPUS_INLINE opus_int16 silk_SUB16(opus_int16 a, opus_int16 b){
+    opus_int16 ret;
+    ops_count += 1;
+    ret = a - b;
+    return ret;
+}
+
+#undef    silk_SUB32
+static OPUS_INLINE opus_int32 silk_SUB32(opus_int32 a, opus_int32 b){
+    opus_int32 ret;
+    ops_count += 1;
+    ret = a - b;
+    return ret;
+}
+
+#undef    silk_SUB64
+static OPUS_INLINE opus_int64 silk_SUB64(opus_int64 a, opus_int64 b){
+    opus_int64 ret;
+    ops_count += 2;
+    ret = a - b;
+    return ret;
+}
+
+#undef silk_ADD_SAT16
+static OPUS_INLINE opus_int16 silk_ADD_SAT16( opus_int16 a16, opus_int16 b16 ) {
+    opus_int16 res;
+    /* Nb will be counted in AKP_add32 and silk_SAT16*/
+    res = (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a16), (b16) ) );
+    return res;
+}
+
+#undef silk_ADD_SAT32
+static OPUS_INLINE opus_int32 silk_ADD_SAT32(opus_int32 a32, opus_int32 b32){
+    opus_int32 res;
+    ops_count += 1;
+    res =    ((((a32) + (b32)) & 0x80000000) == 0 ?                                    \
+            ((((a32) & (b32)) & 0x80000000) != 0 ? silk_int32_MIN : (a32)+(b32)) :    \
+            ((((a32) | (b32)) & 0x80000000) == 0 ? silk_int32_MAX : (a32)+(b32)) );
+    return res;
+}
+
+#undef silk_ADD_SAT64
+static OPUS_INLINE opus_int64 silk_ADD_SAT64( opus_int64 a64, opus_int64 b64 ) {
+    opus_int64 res;
+    ops_count += 1;
+    res =    ((((a64) + (b64)) & 0x8000000000000000LL) == 0 ?                                \
+            ((((a64) & (b64)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a64)+(b64)) :    \
+            ((((a64) | (b64)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a64)+(b64)) );
+    return res;
+}
+
+#undef silk_SUB_SAT16
+static OPUS_INLINE opus_int16 silk_SUB_SAT16( opus_int16 a16, opus_int16 b16 ) {
+    opus_int16 res;
+    silk_assert(0);
+    /* Nb will be counted in sub-macros*/
+    res = (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a16), (b16) ) );
+    return res;
+}
+
+#undef silk_SUB_SAT32
+static OPUS_INLINE opus_int32 silk_SUB_SAT32( opus_int32 a32, opus_int32 b32 ) {
+    opus_int32 res;
+    ops_count += 1;
+    res =     ((((a32)-(b32)) & 0x80000000) == 0 ?                                            \
+            (( (a32) & ((b32)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a32)-(b32)) :    \
+            ((((a32)^0x80000000) & (b32)  & 0x80000000) ? silk_int32_MAX : (a32)-(b32)) );
+    return res;
+}
+
+#undef silk_SUB_SAT64
+static OPUS_INLINE opus_int64 silk_SUB_SAT64( opus_int64 a64, opus_int64 b64 ) {
+    opus_int64 res;
+    ops_count += 1;
+    res =    ((((a64)-(b64)) & 0x8000000000000000LL) == 0 ?                                                        \
+            (( (a64) & ((b64)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a64)-(b64)) :    \
+            ((((a64)^0x8000000000000000LL) & (b64)  & 0x8000000000000000LL) ? silk_int64_MAX : (a64)-(b64)) );
+
+    return res;
+}
+
+#undef    silk_SMULWW
+static OPUS_INLINE opus_int32 silk_SMULWW(opus_int32 a32, opus_int32 b32){
+    opus_int32 ret;
+    /* Nb will be counted in sub-macros*/
+    ret = silk_MLA(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16));
+    return ret;
+}
+
+#undef    silk_SMLAWW
+static OPUS_INLINE opus_int32 silk_SMLAWW(opus_int32 a32, opus_int32 b32, opus_int32 c32){
+    opus_int32 ret;
+    /* Nb will be counted in sub-macros*/
+    ret = silk_MLA(silk_SMLAWB((a32), (b32), (c32)), (b32), silk_RSHIFT_ROUND((c32), 16));
+    return ret;
+}
+
+#undef    silk_min_int
+static OPUS_INLINE opus_int silk_min_int(opus_int a, opus_int b)
+{
+    ops_count += 1;
+    return (((a) < (b)) ? (a) : (b));
+}
+
+#undef    silk_min_16
+static OPUS_INLINE opus_int16 silk_min_16(opus_int16 a, opus_int16 b)
+{
+    ops_count += 1;
+    return (((a) < (b)) ? (a) : (b));
+}
+#undef    silk_min_32
+static OPUS_INLINE opus_int32 silk_min_32(opus_int32 a, opus_int32 b)
+{
+    ops_count += 1;
+    return (((a) < (b)) ? (a) : (b));
+}
+#undef    silk_min_64
+static OPUS_INLINE opus_int64 silk_min_64(opus_int64 a, opus_int64 b)
+{
+    ops_count += 1;
+    return (((a) < (b)) ? (a) : (b));
+}
+
+/* silk_min() versions with typecast in the function call */
+#undef    silk_max_int
+static OPUS_INLINE opus_int silk_max_int(opus_int a, opus_int b)
+{
+    ops_count += 1;
+    return (((a) > (b)) ? (a) : (b));
+}
+#undef    silk_max_16
+static OPUS_INLINE opus_int16 silk_max_16(opus_int16 a, opus_int16 b)
+{
+    ops_count += 1;
+    return (((a) > (b)) ? (a) : (b));
+}
+#undef    silk_max_32
+static OPUS_INLINE opus_int32 silk_max_32(opus_int32 a, opus_int32 b)
+{
+    ops_count += 1;
+    return (((a) > (b)) ? (a) : (b));
+}
+
+#undef    silk_max_64
+static OPUS_INLINE opus_int64 silk_max_64(opus_int64 a, opus_int64 b)
+{
+    ops_count += 1;
+    return (((a) > (b)) ? (a) : (b));
+}
+
+
+#undef silk_LIMIT_int
+static OPUS_INLINE opus_int silk_LIMIT_int(opus_int a, opus_int limit1, opus_int limit2)
+{
+    opus_int ret;
+    ops_count += 6;
+
+    ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
+        : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
+
+    return(ret);
+}
+
+#undef silk_LIMIT_16
+static OPUS_INLINE opus_int16 silk_LIMIT_16(opus_int16 a, opus_int16 limit1, opus_int16 limit2)
+{
+    opus_int16 ret;
+    ops_count += 6;
+
+    ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
+        : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
+
+return(ret);
+}
+
+
+#undef silk_LIMIT_32
+static OPUS_INLINE opus_int32 silk_LIMIT_32(opus_int32 a, opus_int32 limit1, opus_int32 limit2)
+{
+    opus_int32 ret;
+    ops_count += 6;
+
+    ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
+        : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
+    return(ret);
+}
+
+#else
+#define varDefine
+#define silk_SaveCount()
+
+#endif
+#endif
+
diff --git a/opus/silk/MacroDebug.h b/opus/silk/MacroDebug.h
new file mode 100644 (file)
index 0000000..8dd4ce2
--- /dev/null
@@ -0,0 +1,951 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. All rights reserved.
+Copyright (C) 2012 Xiph.Org Foundation
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 MACRO_DEBUG_H
+#define MACRO_DEBUG_H
+
+/* Redefine macro functions with extensive assertion in DEBUG mode.
+   As functions can't be undefined, this file can't work with SigProcFIX_MacroCount.h */
+
+#if ( defined (FIXED_DEBUG) || ( 0 && defined (_DEBUG) ) ) && !defined (silk_MACRO_COUNT)
+
+#undef silk_ADD16
+#define silk_ADD16(a,b) silk_ADD16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_ADD16_(opus_int16 a, opus_int16 b, char *file, int line){
+    opus_int16 ret;
+
+    ret = a + b;
+    if ( ret != silk_ADD_SAT16( a, b ) )
+    {
+        fprintf (stderr, "silk_ADD16(%d, %d) in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_ADD32
+#define silk_ADD32(a,b) silk_ADD32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_ADD32_(opus_int32 a, opus_int32 b, char *file, int line){
+    opus_int32 ret;
+
+    ret = a + b;
+    if ( ret != silk_ADD_SAT32( a, b ) )
+    {
+        fprintf (stderr, "silk_ADD32(%d, %d) in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_ADD64
+#define silk_ADD64(a,b) silk_ADD64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_ADD64_(opus_int64 a, opus_int64 b, char *file, int line){
+    opus_int64 ret;
+
+    ret = a + b;
+    if ( ret != silk_ADD_SAT64( a, b ) )
+    {
+        fprintf (stderr, "silk_ADD64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SUB16
+#define silk_SUB16(a,b) silk_SUB16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_SUB16_(opus_int16 a, opus_int16 b, char *file, int line){
+    opus_int16 ret;
+
+    ret = a - b;
+    if ( ret != silk_SUB_SAT16( a, b ) )
+    {
+        fprintf (stderr, "silk_SUB16(%d, %d) in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SUB32
+#define silk_SUB32(a,b) silk_SUB32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SUB32_(opus_int32 a, opus_int32 b, char *file, int line){
+    opus_int32 ret;
+
+    ret = a - b;
+    if ( ret != silk_SUB_SAT32( a, b ) )
+    {
+        fprintf (stderr, "silk_SUB32(%d, %d) in %s: line %d\n", a, b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SUB64
+#define silk_SUB64(a,b) silk_SUB64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_SUB64_(opus_int64 a, opus_int64 b, char *file, int line){
+    opus_int64 ret;
+
+    ret = a - b;
+    if ( ret != silk_SUB_SAT64( a, b ) )
+    {
+        fprintf (stderr, "silk_SUB64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)b, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_ADD_SAT16
+#define silk_ADD_SAT16(a,b) silk_ADD_SAT16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_ADD_SAT16_( opus_int16 a16, opus_int16 b16, char *file, int line) {
+    opus_int16 res;
+    res = (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a16), (b16) ) );
+    if ( res != silk_SAT16( (opus_int32)a16 + (opus_int32)b16 ) )
+    {
+        fprintf (stderr, "silk_ADD_SAT16(%d, %d) in %s: line %d\n", a16, b16, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_ADD_SAT32
+#define silk_ADD_SAT32(a,b) silk_ADD_SAT32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_ADD_SAT32_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    opus_int32 res;
+    res =   ((((opus_uint32)(a32) + (opus_uint32)(b32)) & 0x80000000) == 0 ?       \
+            ((((a32) & (b32)) & 0x80000000) != 0 ? silk_int32_MIN : (a32)+(b32)) : \
+            ((((a32) | (b32)) & 0x80000000) == 0 ? silk_int32_MAX : (a32)+(b32)) );
+    if ( res != silk_SAT32( (opus_int64)a32 + (opus_int64)b32 ) )
+    {
+        fprintf (stderr, "silk_ADD_SAT32(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_ADD_SAT64
+#define silk_ADD_SAT64(a,b) silk_ADD_SAT64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_ADD_SAT64_( opus_int64 a64, opus_int64 b64, char *file, int line) {
+    opus_int64 res;
+    int        fail = 0;
+    res =   ((((a64) + (b64)) & 0x8000000000000000LL) == 0 ?                                 \
+            ((((a64) & (b64)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a64)+(b64)) : \
+            ((((a64) | (b64)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a64)+(b64)) );
+    if( res != a64 + b64 ) {
+        /* Check that we saturated to the correct extreme value */
+        if ( !(( res == silk_int64_MAX && ( ( a64 >> 1 ) + ( b64 >> 1 ) > ( silk_int64_MAX >> 3 ) ) ) ||
+               ( res == silk_int64_MIN && ( ( a64 >> 1 ) + ( b64 >> 1 ) < ( silk_int64_MIN >> 3 ) ) ) ) )
+        {
+            fail = 1;
+        }
+    } else {
+        /* Saturation not necessary */
+        fail = res != a64 + b64;
+    }
+    if ( fail )
+    {
+        fprintf (stderr, "silk_ADD_SAT64(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_SUB_SAT16
+#define silk_SUB_SAT16(a,b) silk_SUB_SAT16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_SUB_SAT16_( opus_int16 a16, opus_int16 b16, char *file, int line ) {
+    opus_int16 res;
+    res = (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a16), (b16) ) );
+    if ( res != silk_SAT16( (opus_int32)a16 - (opus_int32)b16 ) )
+    {
+        fprintf (stderr, "silk_SUB_SAT16(%d, %d) in %s: line %d\n", a16, b16, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_SUB_SAT32
+#define silk_SUB_SAT32(a,b) silk_SUB_SAT32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SUB_SAT32_( opus_int32 a32, opus_int32 b32, char *file, int line ) {
+    opus_int32 res;
+    res =   ((((opus_uint32)(a32)-(opus_uint32)(b32)) & 0x80000000) == 0 ?                \
+            (( (a32) & ((b32)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a32)-(b32)) : \
+            ((((a32)^0x80000000) & (b32)  & 0x80000000) ? silk_int32_MAX : (a32)-(b32)) );
+    if ( res != silk_SAT32( (opus_int64)a32 - (opus_int64)b32 ) )
+    {
+        fprintf (stderr, "silk_SUB_SAT32(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_SUB_SAT64
+#define silk_SUB_SAT64(a,b) silk_SUB_SAT64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_SUB_SAT64_( opus_int64 a64, opus_int64 b64, char *file, int line ) {
+    opus_int64 res;
+    int        fail = 0;
+    res =   ((((a64)-(b64)) & 0x8000000000000000LL) == 0 ?                                                    \
+            (( (a64) & ((b64)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a64)-(b64)) : \
+            ((((a64)^0x8000000000000000LL) & (b64)  & 0x8000000000000000LL) ? silk_int64_MAX : (a64)-(b64)) );
+    if( res != a64 - b64 ) {
+        /* Check that we saturated to the correct extreme value */
+        if( !(( res == silk_int64_MAX && ( ( a64 >> 1 ) + ( b64 >> 1 ) > ( silk_int64_MAX >> 3 ) ) ) ||
+              ( res == silk_int64_MIN && ( ( a64 >> 1 ) + ( b64 >> 1 ) < ( silk_int64_MIN >> 3 ) ) ) ))
+        {
+            fail = 1;
+        }
+    } else {
+        /* Saturation not necessary */
+        fail = res != a64 - b64;
+    }
+    if ( fail )
+    {
+        fprintf (stderr, "silk_SUB_SAT64(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return res;
+}
+
+#undef silk_MUL
+#define silk_MUL(a,b) silk_MUL_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_MUL_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    opus_int32 ret;
+    opus_int64 ret64;
+    ret = a32 * b32;
+    ret64 = (opus_int64)a32 * (opus_int64)b32;
+    if ( (opus_int64)ret != ret64 )
+    {
+        fprintf (stderr, "silk_MUL(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_MUL_uint
+#define silk_MUL_uint(a,b) silk_MUL_uint_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_uint32 silk_MUL_uint_(opus_uint32 a32, opus_uint32 b32, char *file, int line){
+    opus_uint32 ret;
+    ret = a32 * b32;
+    if ( (opus_uint64)ret != (opus_uint64)a32 * (opus_uint64)b32 )
+    {
+        fprintf (stderr, "silk_MUL_uint(%u, %u) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_MLA
+#define silk_MLA(a,b,c) silk_MLA_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_MLA_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = a32 + b32 * c32;
+    if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int64)c32 )
+    {
+        fprintf (stderr, "silk_MLA(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_MLA_uint
+#define silk_MLA_uint(a,b,c) silk_MLA_uint_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_MLA_uint_(opus_uint32 a32, opus_uint32 b32, opus_uint32 c32, char *file, int line){
+    opus_uint32 ret;
+    ret = a32 + b32 * c32;
+    if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int64)c32 )
+    {
+        fprintf (stderr, "silk_MLA_uint(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMULWB
+#define silk_SMULWB(a,b) silk_SMULWB_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMULWB_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    opus_int32 ret;
+    ret = (a32 >> 16) * (opus_int32)((opus_int16)b32) + (((a32 & 0x0000FFFF) * (opus_int32)((opus_int16)b32)) >> 16);
+    if ( (opus_int64)ret != ((opus_int64)a32 * (opus_int16)b32) >> 16 )
+    {
+        fprintf (stderr, "silk_SMULWB(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMLAWB
+#define silk_SMLAWB(a,b,c) silk_SMLAWB_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLAWB_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = silk_ADD32( a32, silk_SMULWB( b32, c32 ) );
+    if ( silk_ADD32( a32, silk_SMULWB( b32, c32 ) ) != silk_ADD_SAT32( a32, silk_SMULWB( b32, c32 ) ) )
+    {
+        fprintf (stderr, "silk_SMLAWB(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMULWT
+#define silk_SMULWT(a,b) silk_SMULWT_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMULWT_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    opus_int32 ret;
+    ret = (a32 >> 16) * (b32 >> 16) + (((a32 & 0x0000FFFF) * (b32 >> 16)) >> 16);
+    if ( (opus_int64)ret != ((opus_int64)a32 * (b32 >> 16)) >> 16 )
+    {
+        fprintf (stderr, "silk_SMULWT(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMLAWT
+#define silk_SMLAWT(a,b,c) silk_SMLAWT_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLAWT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = a32 + ((b32 >> 16) * (c32 >> 16)) + (((b32 & 0x0000FFFF) * ((c32 >> 16)) >> 16));
+    if ( (opus_int64)ret != (opus_int64)a32 + (((opus_int64)b32 * (c32 >> 16)) >> 16) )
+    {
+        fprintf (stderr, "silk_SMLAWT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMULL
+#define silk_SMULL(a,b) silk_SMULL_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_SMULL_(opus_int64 a64, opus_int64 b64, char *file, int line){
+    opus_int64 ret64;
+    int        fail = 0;
+    ret64 = a64 * b64;
+    if( b64 != 0 ) {
+        fail = a64 != (ret64 / b64);
+    } else if( a64 != 0 ) {
+        fail = b64 != (ret64 / a64);
+    }
+    if ( fail )
+    {
+        fprintf (stderr, "silk_SMULL(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret64;
+}
+
+/* no checking needed for silk_SMULBB */
+#undef silk_SMLABB
+#define silk_SMLABB(a,b,c) silk_SMLABB_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLABB_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = a32 + (opus_int32)((opus_int16)b32) * (opus_int32)((opus_int16)c32);
+    if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int16)c32 )
+    {
+        fprintf (stderr, "silk_SMLABB(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+/* no checking needed for silk_SMULBT */
+#undef silk_SMLABT
+#define silk_SMLABT(a,b,c) silk_SMLABT_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLABT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = a32 + ((opus_int32)((opus_int16)b32)) * (c32 >> 16);
+    if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (c32 >> 16) )
+    {
+        fprintf (stderr, "silk_SMLABT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+/* no checking needed for silk_SMULTT */
+#undef silk_SMLATT
+#define silk_SMLATT(a,b,c) silk_SMLATT_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLATT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret;
+    ret = a32 + (b32 >> 16) * (c32 >> 16);
+    if ( (opus_int64)ret != (opus_int64)a32 + (b32 >> 16) * (c32 >> 16) )
+    {
+        fprintf (stderr, "silk_SMLATT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_SMULWW
+#define silk_SMULWW(a,b) silk_SMULWW_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMULWW_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    opus_int32 ret, tmp1, tmp2;
+    opus_int64 ret64;
+    int        fail = 0;
+
+    ret  = silk_SMULWB( a32, b32 );
+    tmp1 = silk_RSHIFT_ROUND( b32, 16 );
+    tmp2 = silk_MUL( a32, tmp1 );
+
+    fail |= (opus_int64)tmp2 != (opus_int64) a32 * (opus_int64) tmp1;
+
+    tmp1 = ret;
+    ret  = silk_ADD32( tmp1, tmp2 );
+    fail |= silk_ADD32( tmp1, tmp2 ) != silk_ADD_SAT32( tmp1, tmp2 );
+
+    ret64 = silk_RSHIFT64( silk_SMULL( a32, b32 ), 16 );
+    fail |= (opus_int64)ret != ret64;
+
+    if ( fail )
+    {
+        fprintf (stderr, "silk_SMULWT(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+
+    return ret;
+}
+
+#undef silk_SMLAWW
+#define silk_SMLAWW(a,b,c) silk_SMLAWW_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SMLAWW_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
+    opus_int32 ret, tmp;
+
+    tmp = silk_SMULWW( b32, c32 );
+    ret = silk_ADD32( a32, tmp );
+    if ( ret != silk_ADD_SAT32( a32, tmp ) )
+    {
+        fprintf (stderr, "silk_SMLAWW(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+/* Multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode) */
+#undef  silk_MLA_ovflw
+#define silk_MLA_ovflw(a32, b32, c32)    ((a32) + ((b32) * (c32)))
+#undef  silk_SMLABB_ovflw
+#define silk_SMLABB_ovflw(a32, b32, c32)    ((a32) + ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32)))
+
+/* no checking needed for silk_SMULL
+   no checking needed for silk_SMLAL
+   no checking needed for silk_SMLALBB
+   no checking needed for SigProcFIX_CLZ16
+   no checking needed for SigProcFIX_CLZ32*/
+
+#undef silk_DIV32
+#define silk_DIV32(a,b) silk_DIV32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_DIV32_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    if ( b32 == 0 )
+    {
+        fprintf (stderr, "silk_DIV32(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a32 / b32;
+}
+
+#undef silk_DIV32_16
+#define silk_DIV32_16(a,b) silk_DIV32_16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_DIV32_16_(opus_int32 a32, opus_int32 b32, char *file, int line){
+    int fail = 0;
+    fail |= b32 == 0;
+    fail |= b32 > silk_int16_MAX;
+    fail |= b32 < silk_int16_MIN;
+    if ( fail )
+    {
+        fprintf (stderr, "silk_DIV32_16(%d, %d) in %s: line %d\n", a32, b32, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a32 / b32;
+}
+
+/* no checking needed for silk_SAT8
+   no checking needed for silk_SAT16
+   no checking needed for silk_SAT32
+   no checking needed for silk_POS_SAT32
+   no checking needed for silk_ADD_POS_SAT8
+   no checking needed for silk_ADD_POS_SAT16
+   no checking needed for silk_ADD_POS_SAT32 */
+
+#undef silk_LSHIFT8
+#define silk_LSHIFT8(a,b) silk_LSHIFT8_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int8 silk_LSHIFT8_(opus_int8 a, opus_int32 shift, char *file, int line){
+    opus_int8 ret;
+    int       fail = 0;
+    ret = a << shift;
+    fail |= shift < 0;
+    fail |= shift >= 8;
+    fail |= (opus_int64)ret != ((opus_int64)a) << shift;
+    if ( fail )
+    {
+        fprintf (stderr, "silk_LSHIFT8(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_LSHIFT16
+#define silk_LSHIFT16(a,b) silk_LSHIFT16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_LSHIFT16_(opus_int16 a, opus_int32 shift, char *file, int line){
+    opus_int16 ret;
+    int        fail = 0;
+    ret = a << shift;
+    fail |= shift < 0;
+    fail |= shift >= 16;
+    fail |= (opus_int64)ret != ((opus_int64)a) << shift;
+    if ( fail )
+    {
+        fprintf (stderr, "silk_LSHIFT16(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_LSHIFT32
+#define silk_LSHIFT32(a,b) silk_LSHIFT32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_LSHIFT32_(opus_int32 a, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    int        fail = 0;
+    ret = a << shift;
+    fail |= shift < 0;
+    fail |= shift >= 32;
+    fail |= (opus_int64)ret != ((opus_int64)a) << shift;
+    if ( fail )
+    {
+        fprintf (stderr, "silk_LSHIFT32(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_LSHIFT64
+#define silk_LSHIFT64(a,b) silk_LSHIFT64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_LSHIFT64_(opus_int64 a, opus_int shift, char *file, int line){
+    opus_int64 ret;
+    int        fail = 0;
+    ret = a << shift;
+    fail |= shift < 0;
+    fail |= shift >= 64;
+    fail |= (ret>>shift) != ((opus_int64)a);
+    if ( fail )
+    {
+        fprintf (stderr, "silk_LSHIFT64(%lld, %d) in %s: line %d\n", (long long)a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_LSHIFT_ovflw
+#define silk_LSHIFT_ovflw(a,b) silk_LSHIFT_ovflw_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_LSHIFT_ovflw_(opus_int32 a, opus_int32 shift, char *file, int line){
+    if ( (shift < 0) || (shift >= 32) ) /* no check for overflow */
+    {
+        fprintf (stderr, "silk_LSHIFT_ovflw(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a << shift;
+}
+
+#undef silk_LSHIFT_uint
+#define silk_LSHIFT_uint(a,b) silk_LSHIFT_uint_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_uint32 silk_LSHIFT_uint_(opus_uint32 a, opus_int32 shift, char *file, int line){
+    opus_uint32 ret;
+    ret = a << shift;
+    if ( (shift < 0) || ((opus_int64)ret != ((opus_int64)a) << shift))
+    {
+        fprintf (stderr, "silk_LSHIFT_uint(%u, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_RSHIFT8
+#define silk_RSHITF8(a,b) silk_RSHIFT8_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int8 silk_RSHIFT8_(opus_int8 a, opus_int32 shift, char *file, int line){
+    if ( (shift < 0) || (shift>=8) )
+    {
+        fprintf (stderr, "silk_RSHITF8(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a >> shift;
+}
+
+#undef silk_RSHIFT16
+#define silk_RSHITF16(a,b) silk_RSHIFT16_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_RSHIFT16_(opus_int16 a, opus_int32 shift, char *file, int line){
+    if ( (shift < 0) || (shift>=16) )
+    {
+        fprintf (stderr, "silk_RSHITF16(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a >> shift;
+}
+
+#undef silk_RSHIFT32
+#define silk_RSHIFT32(a,b) silk_RSHIFT32_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_RSHIFT32_(opus_int32 a, opus_int32 shift, char *file, int line){
+    if ( (shift < 0) || (shift>=32) )
+    {
+        fprintf (stderr, "silk_RSHITF32(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a >> shift;
+}
+
+#undef silk_RSHIFT64
+#define silk_RSHIFT64(a,b) silk_RSHIFT64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_RSHIFT64_(opus_int64 a, opus_int64 shift, char *file, int line){
+    if ( (shift < 0) || (shift>=64) )
+    {
+        fprintf (stderr, "silk_RSHITF64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a >> shift;
+}
+
+#undef silk_RSHIFT_uint
+#define silk_RSHIFT_uint(a,b) silk_RSHIFT_uint_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_uint32 silk_RSHIFT_uint_(opus_uint32 a, opus_int32 shift, char *file, int line){
+    if ( (shift < 0) || (shift>32) )
+    {
+        fprintf (stderr, "silk_RSHIFT_uint(%u, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return a >> shift;
+}
+
+#undef silk_ADD_LSHIFT
+#define silk_ADD_LSHIFT(a,b,c) silk_ADD_LSHIFT_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE int silk_ADD_LSHIFT_(int a, int b, int shift, char *file, int line){
+    opus_int16 ret;
+    ret = a + (b << shift);
+    if ( (shift < 0) || (shift>15) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
+    {
+        fprintf (stderr, "silk_ADD_LSHIFT(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift >= 0 */
+}
+
+#undef silk_ADD_LSHIFT32
+#define silk_ADD_LSHIFT32(a,b,c) silk_ADD_LSHIFT32_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_ADD_LSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    ret = a + (b << shift);
+    if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
+    {
+        fprintf (stderr, "silk_ADD_LSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift >= 0 */
+}
+
+#undef silk_ADD_LSHIFT_uint
+#define silk_ADD_LSHIFT_uint(a,b,c) silk_ADD_LSHIFT_uint_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_uint32 silk_ADD_LSHIFT_uint_(opus_uint32 a, opus_uint32 b, opus_int32 shift, char *file, int line){
+    opus_uint32 ret;
+    ret = a + (b << shift);
+    if ( (shift < 0) || (shift>32) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
+    {
+        fprintf (stderr, "silk_ADD_LSHIFT_uint(%u, %u, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift >= 0 */
+}
+
+#undef silk_ADD_RSHIFT
+#define silk_ADD_RSHIFT(a,b,c) silk_ADD_RSHIFT_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE int silk_ADD_RSHIFT_(int a, int b, int shift, char *file, int line){
+    opus_int16 ret;
+    ret = a + (b >> shift);
+    if ( (shift < 0) || (shift>15) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
+    {
+        fprintf (stderr, "silk_ADD_RSHIFT(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift  > 0 */
+}
+
+#undef silk_ADD_RSHIFT32
+#define silk_ADD_RSHIFT32(a,b,c) silk_ADD_RSHIFT32_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_ADD_RSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    ret = a + (b >> shift);
+    if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
+    {
+        fprintf (stderr, "silk_ADD_RSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift  > 0 */
+}
+
+#undef silk_ADD_RSHIFT_uint
+#define silk_ADD_RSHIFT_uint(a,b,c) silk_ADD_RSHIFT_uint_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_uint32 silk_ADD_RSHIFT_uint_(opus_uint32 a, opus_uint32 b, opus_int32 shift, char *file, int line){
+    opus_uint32 ret;
+    ret = a + (b >> shift);
+    if ( (shift < 0) || (shift>32) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
+    {
+        fprintf (stderr, "silk_ADD_RSHIFT_uint(%u, %u, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift  > 0 */
+}
+
+#undef silk_SUB_LSHIFT32
+#define silk_SUB_LSHIFT32(a,b,c) silk_SUB_LSHIFT32_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SUB_LSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    ret = a - (b << shift);
+    if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a - (((opus_int64)b) << shift)) )
+    {
+        fprintf (stderr, "silk_SUB_LSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift >= 0 */
+}
+
+#undef silk_SUB_RSHIFT32
+#define silk_SUB_RSHIFT32(a,b,c) silk_SUB_RSHIFT32_((a), (b), (c), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_SUB_RSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    ret = a - (b >> shift);
+    if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a - (((opus_int64)b) >> shift)) )
+    {
+        fprintf (stderr, "silk_SUB_RSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;                /* shift  > 0 */
+}
+
+#undef silk_RSHIFT_ROUND
+#define silk_RSHIFT_ROUND(a,b) silk_RSHIFT_ROUND_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_RSHIFT_ROUND_(opus_int32 a, opus_int32 shift, char *file, int line){
+    opus_int32 ret;
+    ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
+    /* the marco definition can't handle a shift of zero */
+    if ( (shift <= 0) || (shift>31) || ((opus_int64)ret != ((opus_int64)a + ((opus_int64)1 << (shift - 1))) >> shift) )
+    {
+        fprintf (stderr, "silk_RSHIFT_ROUND(%d, %d) in %s: line %d\n", a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return ret;
+}
+
+#undef silk_RSHIFT_ROUND64
+#define silk_RSHIFT_ROUND64(a,b) silk_RSHIFT_ROUND64_((a), (b), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_RSHIFT_ROUND64_(opus_int64 a, opus_int32 shift, char *file, int line){
+    opus_int64 ret;
+    /* the marco definition can't handle a shift of zero */
+    if ( (shift <= 0) || (shift>=64) )
+    {
+        fprintf (stderr, "silk_RSHIFT_ROUND64(%lld, %d) in %s: line %d\n", (long long)a, shift, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
+    return ret;
+}
+
+/* silk_abs is used on floats also, so doesn't work... */
+/*#undef silk_abs
+static OPUS_INLINE opus_int32 silk_abs(opus_int32 a){
+    silk_assert(a != 0x80000000);
+    return (((a) >  0)  ? (a) : -(a));            // Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN
+}*/
+
+#undef silk_abs_int64
+#define silk_abs_int64(a) silk_abs_int64_((a), __FILE__, __LINE__)
+static OPUS_INLINE opus_int64 silk_abs_int64_(opus_int64 a, char *file, int line){
+    if ( a == silk_int64_MIN )
+    {
+        fprintf (stderr, "silk_abs_int64(%lld) in %s: line %d\n", (long long)a, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return (((a) >  0)  ? (a) : -(a));            /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN */
+}
+
+#undef silk_abs_int32
+#define silk_abs_int32(a) silk_abs_int32_((a), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_abs_int32_(opus_int32 a, char *file, int line){
+    if ( a == silk_int32_MIN )
+    {
+        fprintf (stderr, "silk_abs_int32(%d) in %s: line %d\n", a, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return silk_abs(a);
+}
+
+#undef silk_CHECK_FIT8
+#define silk_CHECK_FIT8(a) silk_CHECK_FIT8_((a), __FILE__, __LINE__)
+static OPUS_INLINE opus_int8 silk_CHECK_FIT8_( opus_int64 a, char *file, int line ){
+    opus_int8 ret;
+    ret = (opus_int8)a;
+    if ( (opus_int64)ret != a )
+    {
+        fprintf (stderr, "silk_CHECK_FIT8(%lld) in %s: line %d\n", (long long)a, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return( ret );
+}
+
+#undef silk_CHECK_FIT16
+#define silk_CHECK_FIT16(a) silk_CHECK_FIT16_((a), __FILE__, __LINE__)
+static OPUS_INLINE opus_int16 silk_CHECK_FIT16_( opus_int64 a, char *file, int line ){
+    opus_int16 ret;
+    ret = (opus_int16)a;
+    if ( (opus_int64)ret != a )
+    {
+        fprintf (stderr, "silk_CHECK_FIT16(%lld) in %s: line %d\n", (long long)a, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return( ret );
+}
+
+#undef silk_CHECK_FIT32
+#define silk_CHECK_FIT32(a) silk_CHECK_FIT32_((a), __FILE__, __LINE__)
+static OPUS_INLINE opus_int32 silk_CHECK_FIT32_( opus_int64 a, char *file, int line ){
+    opus_int32 ret;
+    ret = (opus_int32)a;
+    if ( (opus_int64)ret != a )
+    {
+        fprintf (stderr, "silk_CHECK_FIT32(%lld) in %s: line %d\n", (long long)a, file, line);
+#ifdef FIXED_DEBUG_ASSERT
+        silk_assert( 0 );
+#endif
+    }
+    return( ret );
+}
+
+/* no checking for silk_NSHIFT_MUL_32_32
+   no checking for silk_NSHIFT_MUL_16_16
+   no checking needed for silk_min
+   no checking needed for silk_max
+   no checking needed for silk_sign
+*/
+
+#endif
+#endif /* MACRO_DEBUG_H */
diff --git a/opus/silk/NLSF2A.c b/opus/silk/NLSF2A.c
new file mode 100644 (file)
index 0000000..116b465
--- /dev/null
@@ -0,0 +1,141 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* conversion between prediction filter coefficients and LSFs   */
+/* order should be even                                         */
+/* a piecewise linear approximation maps LSF <-> cos(LSF)       */
+/* therefore the result is not accurate LSFs, but the two       */
+/* functions are accurate inverses of each other                */
+
+#include "SigProc_FIX.h"
+#include "tables.h"
+
+#define QA      16
+
+/* helper function for NLSF2A(..) */
+static OPUS_INLINE void silk_NLSF2A_find_poly(
+    opus_int32          *out,      /* O    intermediate polynomial, QA [dd+1]        */
+    const opus_int32    *cLSF,     /* I    vector of interleaved 2*cos(LSFs), QA [d] */
+    opus_int            dd         /* I    polynomial order (= 1/2 * filter order)   */
+)
+{
+    opus_int   k, n;
+    opus_int32 ftmp;
+
+    out[0] = silk_LSHIFT( 1, QA );
+    out[1] = -cLSF[0];
+    for( k = 1; k < dd; k++ ) {
+        ftmp = cLSF[2*k];            /* QA*/
+        out[k+1] = silk_LSHIFT( out[k-1], 1 ) - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[k] ), QA );
+        for( n = k; n > 1; n-- ) {
+            out[n] += out[n-2] - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[n-1] ), QA );
+        }
+        out[1] -= ftmp;
+    }
+}
+
+/* compute whitening filter coefficients from normalized line spectral frequencies */
+void silk_NLSF2A(
+    opus_int16                  *a_Q12,             /* O    monic whitening filter coefficients in Q12,  [ d ]          */
+    const opus_int16            *NLSF,              /* I    normalized line spectral frequencies in Q15, [ d ]          */
+    const opus_int              d,                  /* I    filter order (should be even)                               */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    /* This ordering was found to maximize quality. It improves numerical accuracy of
+       silk_NLSF2A_find_poly() compared to "standard" ordering. */
+    static const unsigned char ordering16[16] = {
+      0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1
+    };
+    static const unsigned char ordering10[10] = {
+      0, 9, 6, 3, 4, 5, 8, 1, 2, 7
+    };
+    const unsigned char *ordering;
+    opus_int   k, i, dd;
+    opus_int32 cos_LSF_QA[ SILK_MAX_ORDER_LPC ];
+    opus_int32 P[ SILK_MAX_ORDER_LPC / 2 + 1 ], Q[ SILK_MAX_ORDER_LPC / 2 + 1 ];
+    opus_int32 Ptmp, Qtmp, f_int, f_frac, cos_val, delta;
+    opus_int32 a32_QA1[ SILK_MAX_ORDER_LPC ];
+
+    silk_assert( LSF_COS_TAB_SZ_FIX == 128 );
+    silk_assert( d==10 || d==16 );
+
+    /* convert LSFs to 2*cos(LSF), using piecewise linear curve from table */
+    ordering = d == 16 ? ordering16 : ordering10;
+    for( k = 0; k < d; k++ ) {
+        silk_assert( NLSF[k] >= 0 );
+
+        /* f_int on a scale 0-127 (rounded down) */
+        f_int = silk_RSHIFT( NLSF[k], 15 - 7 );
+
+        /* f_frac, range: 0..255 */
+        f_frac = NLSF[k] - silk_LSHIFT( f_int, 15 - 7 );
+
+        silk_assert(f_int >= 0);
+        silk_assert(f_int < LSF_COS_TAB_SZ_FIX );
+
+        /* Read start and end value from table */
+        cos_val = silk_LSFCosTab_FIX_Q12[ f_int ];                /* Q12 */
+        delta   = silk_LSFCosTab_FIX_Q12[ f_int + 1 ] - cos_val;  /* Q12, with a range of 0..200 */
+
+        /* Linear interpolation */
+        cos_LSF_QA[ordering[k]] = silk_RSHIFT_ROUND( silk_LSHIFT( cos_val, 8 ) + silk_MUL( delta, f_frac ), 20 - QA ); /* QA */
+    }
+
+    dd = silk_RSHIFT( d, 1 );
+
+    /* generate even and odd polynomials using convolution */
+    silk_NLSF2A_find_poly( P, &cos_LSF_QA[ 0 ], dd );
+    silk_NLSF2A_find_poly( Q, &cos_LSF_QA[ 1 ], dd );
+
+    /* convert even and odd polynomials to opus_int32 Q12 filter coefs */
+    for( k = 0; k < dd; k++ ) {
+        Ptmp = P[ k+1 ] + P[ k ];
+        Qtmp = Q[ k+1 ] - Q[ k ];
+
+        /* the Ptmp and Qtmp values at this stage need to fit in int32 */
+        a32_QA1[ k ]     = -Qtmp - Ptmp;        /* QA+1 */
+        a32_QA1[ d-k-1 ] =  Qtmp - Ptmp;        /* QA+1 */
+    }
+
+    /* Convert int32 coefficients to Q12 int16 coefs */
+    silk_LPC_fit( a_Q12, a32_QA1, 12, QA + 1, d );
+
+    for( i = 0; silk_LPC_inverse_pred_gain( a_Q12, d, arch ) == 0 && i < MAX_LPC_STABILIZE_ITERATIONS; i++ ) {
+        /* Prediction coefficients are (too close to) unstable; apply bandwidth expansion   */
+        /* on the unscaled coefficients, convert to Q12 and measure again                   */
+        silk_bwexpander_32( a32_QA1, d, 65536 - silk_LSHIFT( 2, i ) );
+        for( k = 0; k < d; k++ ) {
+            a_Q12[ k ] = (opus_int16)silk_RSHIFT_ROUND( a32_QA1[ k ], QA + 1 - 12 );            /* QA+1 -> Q12 */
+        }
+    }
+}
+
diff --git a/opus/silk/NLSF_VQ.c b/opus/silk/NLSF_VQ.c
new file mode 100644 (file)
index 0000000..452f3dc
--- /dev/null
@@ -0,0 +1,76 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Compute quantization errors for an LPC_order element input vector for a VQ codebook */
+void silk_NLSF_VQ(
+    opus_int32                  err_Q24[],                      /* O    Quantization errors [K]                     */
+    const opus_int16            in_Q15[],                       /* I    Input vectors to be quantized [LPC_order]   */
+    const opus_uint8            pCB_Q8[],                       /* I    Codebook vectors [K*LPC_order]              */
+    const opus_int16            pWght_Q9[],                     /* I    Codebook weights [K*LPC_order]              */
+    const opus_int              K,                              /* I    Number of codebook vectors                  */
+    const opus_int              LPC_order                       /* I    Number of LPCs                              */
+)
+{
+    opus_int         i, m;
+    opus_int32       diff_Q15, diffw_Q24, sum_error_Q24, pred_Q24;
+    const opus_int16 *w_Q9_ptr;
+    const opus_uint8 *cb_Q8_ptr;
+
+    silk_assert( ( LPC_order & 1 ) == 0 );
+
+    /* Loop over codebook */
+    cb_Q8_ptr = pCB_Q8;
+    w_Q9_ptr = pWght_Q9;
+    for( i = 0; i < K; i++ ) {
+        sum_error_Q24 = 0;
+        pred_Q24 = 0;
+        for( m = LPC_order-2; m >= 0; m -= 2 ) {
+            /* Compute weighted absolute predictive quantization error for index m + 1 */
+            diff_Q15 = silk_SUB_LSHIFT32( in_Q15[ m + 1 ], (opus_int32)cb_Q8_ptr[ m + 1 ], 7 ); /* range: [ -32767 : 32767 ]*/
+            diffw_Q24 = silk_SMULBB( diff_Q15, w_Q9_ptr[ m + 1 ] );
+            sum_error_Q24 = silk_ADD32( sum_error_Q24, silk_abs( silk_SUB_RSHIFT32( diffw_Q24, pred_Q24, 1 ) ) );
+            pred_Q24 = diffw_Q24;
+
+            /* Compute weighted absolute predictive quantization error for index m */
+            diff_Q15 = silk_SUB_LSHIFT32( in_Q15[ m ], (opus_int32)cb_Q8_ptr[ m ], 7 ); /* range: [ -32767 : 32767 ]*/
+            diffw_Q24 = silk_SMULBB( diff_Q15, w_Q9_ptr[ m ] );
+            sum_error_Q24 = silk_ADD32( sum_error_Q24, silk_abs( silk_SUB_RSHIFT32( diffw_Q24, pred_Q24, 1 ) ) );
+            pred_Q24 = diffw_Q24;
+
+            silk_assert( sum_error_Q24 >= 0 );
+        }
+        err_Q24[ i ] = sum_error_Q24;
+        cb_Q8_ptr += LPC_order;
+        w_Q9_ptr += LPC_order;
+    }
+}
diff --git a/opus/silk/NLSF_VQ_weights_laroia.c b/opus/silk/NLSF_VQ_weights_laroia.c
new file mode 100644 (file)
index 0000000..04894c5
--- /dev/null
@@ -0,0 +1,80 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "define.h"
+#include "SigProc_FIX.h"
+
+/*
+R. Laroia, N. Phamdo and N. Farvardin, "Robust and Efficient Quantization of Speech LSP
+Parameters Using Structured Vector Quantization", Proc. IEEE Int. Conf. Acoust., Speech,
+Signal Processing, pp. 641-644, 1991.
+*/
+
+/* Laroia low complexity NLSF weights */
+void silk_NLSF_VQ_weights_laroia(
+    opus_int16                  *pNLSFW_Q_OUT,      /* O     Pointer to input vector weights [D]                        */
+    const opus_int16            *pNLSF_Q15,         /* I     Pointer to input vector         [D]                        */
+    const opus_int              D                   /* I     Input vector dimension (even)                              */
+)
+{
+    opus_int   k;
+    opus_int32 tmp1_int, tmp2_int;
+
+    silk_assert( D > 0 );
+    silk_assert( ( D & 1 ) == 0 );
+
+    /* First value */
+    tmp1_int = silk_max_int( pNLSF_Q15[ 0 ], 1 );
+    tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
+    tmp2_int = silk_max_int( pNLSF_Q15[ 1 ] - pNLSF_Q15[ 0 ], 1 );
+    tmp2_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp2_int );
+    pNLSFW_Q_OUT[ 0 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
+    silk_assert( pNLSFW_Q_OUT[ 0 ] > 0 );
+
+    /* Main loop */
+    for( k = 1; k < D - 1; k += 2 ) {
+        tmp1_int = silk_max_int( pNLSF_Q15[ k + 1 ] - pNLSF_Q15[ k ], 1 );
+        tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
+        pNLSFW_Q_OUT[ k ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
+        silk_assert( pNLSFW_Q_OUT[ k ] > 0 );
+
+        tmp2_int = silk_max_int( pNLSF_Q15[ k + 2 ] - pNLSF_Q15[ k + 1 ], 1 );
+        tmp2_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp2_int );
+        pNLSFW_Q_OUT[ k + 1 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
+        silk_assert( pNLSFW_Q_OUT[ k + 1 ] > 0 );
+    }
+
+    /* Last value */
+    tmp1_int = silk_max_int( ( 1 << 15 ) - pNLSF_Q15[ D - 1 ], 1 );
+    tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
+    pNLSFW_Q_OUT[ D - 1 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
+    silk_assert( pNLSFW_Q_OUT[ D - 1 ] > 0 );
+}
diff --git a/opus/silk/NLSF_decode.c b/opus/silk/NLSF_decode.c
new file mode 100644 (file)
index 0000000..eeb0ba8
--- /dev/null
@@ -0,0 +1,93 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Predictive dequantizer for NLSF residuals */
+static OPUS_INLINE void silk_NLSF_residual_dequant(          /* O    Returns RD value in Q30                     */
+          opus_int16         x_Q10[],                        /* O    Output [ order ]                            */
+    const opus_int8          indices[],                      /* I    Quantization indices [ order ]              */
+    const opus_uint8         pred_coef_Q8[],                 /* I    Backward predictor coefs [ order ]          */
+    const opus_int           quant_step_size_Q16,            /* I    Quantization step size                      */
+    const opus_int16         order                           /* I    Number of input values                      */
+)
+{
+    opus_int     i, out_Q10, pred_Q10;
+
+    out_Q10 = 0;
+    for( i = order-1; i >= 0; i-- ) {
+        pred_Q10 = silk_RSHIFT( silk_SMULBB( out_Q10, (opus_int16)pred_coef_Q8[ i ] ), 8 );
+        out_Q10  = silk_LSHIFT( indices[ i ], 10 );
+        if( out_Q10 > 0 ) {
+            out_Q10 = silk_SUB16( out_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        } else if( out_Q10 < 0 ) {
+            out_Q10 = silk_ADD16( out_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        }
+        out_Q10  = silk_SMLAWB( pred_Q10, (opus_int32)out_Q10, quant_step_size_Q16 );
+        x_Q10[ i ] = out_Q10;
+    }
+}
+
+
+/***********************/
+/* NLSF vector decoder */
+/***********************/
+void silk_NLSF_decode(
+          opus_int16            *pNLSF_Q15,                     /* O    Quantized NLSF vector [ LPC_ORDER ]         */
+          opus_int8             *NLSFIndices,                   /* I    Codebook path vector [ LPC_ORDER + 1 ]      */
+    const silk_NLSF_CB_struct   *psNLSF_CB                      /* I    Codebook object                             */
+)
+{
+    opus_int         i;
+    opus_uint8       pred_Q8[  MAX_LPC_ORDER ];
+    opus_int16       ec_ix[    MAX_LPC_ORDER ];
+    opus_int16       res_Q10[  MAX_LPC_ORDER ];
+    opus_int32       NLSF_Q15_tmp;
+    const opus_uint8 *pCB_element;
+    const opus_int16 *pCB_Wght_Q9;
+
+    /* Unpack entropy table indices and predictor for current CB1 index */
+    silk_NLSF_unpack( ec_ix, pred_Q8, psNLSF_CB, NLSFIndices[ 0 ] );
+
+    /* Predictive residual dequantizer */
+    silk_NLSF_residual_dequant( res_Q10, &NLSFIndices[ 1 ], pred_Q8, psNLSF_CB->quantStepSize_Q16, psNLSF_CB->order );
+
+    /* Apply inverse square-rooted weights to first stage and add to output */
+    pCB_element = &psNLSF_CB->CB1_NLSF_Q8[ NLSFIndices[ 0 ] * psNLSF_CB->order ];
+    pCB_Wght_Q9 = &psNLSF_CB->CB1_Wght_Q9[ NLSFIndices[ 0 ] * psNLSF_CB->order ];
+    for( i = 0; i < psNLSF_CB->order; i++ ) {
+        NLSF_Q15_tmp = silk_ADD_LSHIFT32( silk_DIV32_16( silk_LSHIFT( (opus_int32)res_Q10[ i ], 14 ), pCB_Wght_Q9[ i ] ), (opus_int16)pCB_element[ i ], 7 );
+        pNLSF_Q15[ i ] = (opus_int16)silk_LIMIT( NLSF_Q15_tmp, 0, 32767 );
+    }
+
+    /* NLSF stabilization */
+    silk_NLSF_stabilize( pNLSF_Q15, psNLSF_CB->deltaMin_Q15, psNLSF_CB->order );
+}
diff --git a/opus/silk/NLSF_del_dec_quant.c b/opus/silk/NLSF_del_dec_quant.c
new file mode 100644 (file)
index 0000000..44a16ac
--- /dev/null
@@ -0,0 +1,215 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Delayed-decision quantizer for NLSF residuals */
+opus_int32 silk_NLSF_del_dec_quant(                             /* O    Returns RD value in Q25                     */
+    opus_int8                   indices[],                      /* O    Quantization indices [ order ]              */
+    const opus_int16            x_Q10[],                        /* I    Input [ order ]                             */
+    const opus_int16            w_Q5[],                         /* I    Weights [ order ]                           */
+    const opus_uint8            pred_coef_Q8[],                 /* I    Backward predictor coefs [ order ]          */
+    const opus_int16            ec_ix[],                        /* I    Indices to entropy coding tables [ order ]  */
+    const opus_uint8            ec_rates_Q5[],                  /* I    Rates []                                    */
+    const opus_int              quant_step_size_Q16,            /* I    Quantization step size                      */
+    const opus_int16            inv_quant_step_size_Q6,         /* I    Inverse quantization step size              */
+    const opus_int32            mu_Q20,                         /* I    R/D tradeoff                                */
+    const opus_int16            order                           /* I    Number of input values                      */
+)
+{
+    opus_int         i, j, nStates, ind_tmp, ind_min_max, ind_max_min, in_Q10, res_Q10;
+    opus_int         pred_Q10, diff_Q10, rate0_Q5, rate1_Q5;
+    opus_int16       out0_Q10, out1_Q10;
+    opus_int32       RD_tmp_Q25, min_Q25, min_max_Q25, max_min_Q25;
+    opus_int         ind_sort[         NLSF_QUANT_DEL_DEC_STATES ];
+    opus_int8        ind[              NLSF_QUANT_DEL_DEC_STATES ][ MAX_LPC_ORDER ];
+    opus_int16       prev_out_Q10[ 2 * NLSF_QUANT_DEL_DEC_STATES ];
+    opus_int32       RD_Q25[       2 * NLSF_QUANT_DEL_DEC_STATES ];
+    opus_int32       RD_min_Q25[       NLSF_QUANT_DEL_DEC_STATES ];
+    opus_int32       RD_max_Q25[       NLSF_QUANT_DEL_DEC_STATES ];
+    const opus_uint8 *rates_Q5;
+
+    opus_int out0_Q10_table[2 * NLSF_QUANT_MAX_AMPLITUDE_EXT];
+    opus_int out1_Q10_table[2 * NLSF_QUANT_MAX_AMPLITUDE_EXT];
+
+    for (i = -NLSF_QUANT_MAX_AMPLITUDE_EXT; i <= NLSF_QUANT_MAX_AMPLITUDE_EXT-1; i++)
+    {
+        out0_Q10 = silk_LSHIFT( i, 10 );
+        out1_Q10 = silk_ADD16( out0_Q10, 1024 );
+        if( i > 0 ) {
+            out0_Q10 = silk_SUB16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+            out1_Q10 = silk_SUB16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        } else if( i == 0 ) {
+            out1_Q10 = silk_SUB16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        } else if( i == -1 ) {
+            out0_Q10 = silk_ADD16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        } else {
+            out0_Q10 = silk_ADD16( out0_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+            out1_Q10 = silk_ADD16( out1_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
+        }
+        out0_Q10_table[ i + NLSF_QUANT_MAX_AMPLITUDE_EXT ] = silk_RSHIFT( silk_SMULBB( out0_Q10, quant_step_size_Q16 ), 16 );
+        out1_Q10_table[ i + NLSF_QUANT_MAX_AMPLITUDE_EXT ] = silk_RSHIFT( silk_SMULBB( out1_Q10, quant_step_size_Q16 ), 16 );
+    }
+
+    silk_assert( (NLSF_QUANT_DEL_DEC_STATES & (NLSF_QUANT_DEL_DEC_STATES-1)) == 0 );     /* must be power of two */
+
+    nStates = 1;
+    RD_Q25[ 0 ] = 0;
+    prev_out_Q10[ 0 ] = 0;
+    for( i = order - 1; i >= 0; i-- ) {
+        rates_Q5 = &ec_rates_Q5[ ec_ix[ i ] ];
+        in_Q10 = x_Q10[ i ];
+        for( j = 0; j < nStates; j++ ) {
+            pred_Q10 = silk_RSHIFT( silk_SMULBB( (opus_int16)pred_coef_Q8[ i ], prev_out_Q10[ j ] ), 8 );
+            res_Q10  = silk_SUB16( in_Q10, pred_Q10 );
+            ind_tmp  = silk_RSHIFT( silk_SMULBB( inv_quant_step_size_Q6, res_Q10 ), 16 );
+            ind_tmp  = silk_LIMIT( ind_tmp, -NLSF_QUANT_MAX_AMPLITUDE_EXT, NLSF_QUANT_MAX_AMPLITUDE_EXT-1 );
+            ind[ j ][ i ] = (opus_int8)ind_tmp;
+
+            /* compute outputs for ind_tmp and ind_tmp + 1 */
+            out0_Q10 = out0_Q10_table[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE_EXT ];
+            out1_Q10 = out1_Q10_table[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE_EXT ];
+
+            out0_Q10  = silk_ADD16( out0_Q10, pred_Q10 );
+            out1_Q10  = silk_ADD16( out1_Q10, pred_Q10 );
+            prev_out_Q10[ j           ] = out0_Q10;
+            prev_out_Q10[ j + nStates ] = out1_Q10;
+
+            /* compute RD for ind_tmp and ind_tmp + 1 */
+            if( ind_tmp + 1 >= NLSF_QUANT_MAX_AMPLITUDE ) {
+                if( ind_tmp + 1 == NLSF_QUANT_MAX_AMPLITUDE ) {
+                    rate0_Q5 = rates_Q5[ ind_tmp + NLSF_QUANT_MAX_AMPLITUDE ];
+                    rate1_Q5 = 280;
+                } else {
+                    rate0_Q5 = silk_SMLABB( 280 - 43 * NLSF_QUANT_MAX_AMPLITUDE, 43, ind_tmp );
+                    rate1_Q5 = silk_ADD16( rate0_Q5, 43 );
+                }
+            } else if( ind_tmp <= -NLSF_QUANT_MAX_AMPLITUDE ) {
+                if( ind_tmp == -NLSF_QUANT_MAX_AMPLITUDE ) {
+                    rate0_Q5 = 280;
+                    rate1_Q5 = rates_Q5[ ind_tmp + 1 + NLSF_QUANT_MAX_AMPLITUDE ];
+                } else {
+                    rate0_Q5 = silk_SMLABB( 280 - 43 * NLSF_QUANT_MAX_AMPLITUDE, -43, ind_tmp );
+                    rate1_Q5 = silk_SUB16( rate0_Q5, 43 );
+                }
+            } else {
+                rate0_Q5 = rates_Q5[ ind_tmp +     NLSF_QUANT_MAX_AMPLITUDE ];
+                rate1_Q5 = rates_Q5[ ind_tmp + 1 + NLSF_QUANT_MAX_AMPLITUDE ];
+            }
+            RD_tmp_Q25            = RD_Q25[ j ];
+            diff_Q10              = silk_SUB16( in_Q10, out0_Q10 );
+            RD_Q25[ j ]           = silk_SMLABB( silk_MLA( RD_tmp_Q25, silk_SMULBB( diff_Q10, diff_Q10 ), w_Q5[ i ] ), mu_Q20, rate0_Q5 );
+            diff_Q10              = silk_SUB16( in_Q10, out1_Q10 );
+            RD_Q25[ j + nStates ] = silk_SMLABB( silk_MLA( RD_tmp_Q25, silk_SMULBB( diff_Q10, diff_Q10 ), w_Q5[ i ] ), mu_Q20, rate1_Q5 );
+        }
+
+        if( nStates <= NLSF_QUANT_DEL_DEC_STATES/2 ) {
+            /* double number of states and copy */
+            for( j = 0; j < nStates; j++ ) {
+                ind[ j + nStates ][ i ] = ind[ j ][ i ] + 1;
+            }
+            nStates = silk_LSHIFT( nStates, 1 );
+            for( j = nStates; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) {
+                ind[ j ][ i ] = ind[ j - nStates ][ i ];
+            }
+        } else {
+            /* sort lower and upper half of RD_Q25, pairwise */
+            for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) {
+                if( RD_Q25[ j ] > RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ] ) {
+                    RD_max_Q25[ j ]                         = RD_Q25[ j ];
+                    RD_min_Q25[ j ]                         = RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ];
+                    RD_Q25[ j ]                             = RD_min_Q25[ j ];
+                    RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ] = RD_max_Q25[ j ];
+                    /* swap prev_out values */
+                    out0_Q10 = prev_out_Q10[ j ];
+                    prev_out_Q10[ j ] = prev_out_Q10[ j + NLSF_QUANT_DEL_DEC_STATES ];
+                    prev_out_Q10[ j + NLSF_QUANT_DEL_DEC_STATES ] = out0_Q10;
+                    ind_sort[ j ] = j + NLSF_QUANT_DEL_DEC_STATES;
+                } else {
+                    RD_min_Q25[ j ] = RD_Q25[ j ];
+                    RD_max_Q25[ j ] = RD_Q25[ j + NLSF_QUANT_DEL_DEC_STATES ];
+                    ind_sort[ j ] = j;
+                }
+            }
+            /* compare the highest RD values of the winning half with the lowest one in the losing half, and copy if necessary */
+            /* afterwards ind_sort[] will contain the indices of the NLSF_QUANT_DEL_DEC_STATES winning RD values */
+            while( 1 ) {
+                min_max_Q25 = silk_int32_MAX;
+                max_min_Q25 = 0;
+                ind_min_max = 0;
+                ind_max_min = 0;
+                for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) {
+                    if( min_max_Q25 > RD_max_Q25[ j ] ) {
+                        min_max_Q25 = RD_max_Q25[ j ];
+                        ind_min_max = j;
+                    }
+                    if( max_min_Q25 < RD_min_Q25[ j ] ) {
+                        max_min_Q25 = RD_min_Q25[ j ];
+                        ind_max_min = j;
+                    }
+                }
+                if( min_max_Q25 >= max_min_Q25 ) {
+                    break;
+                }
+                /* copy ind_min_max to ind_max_min */
+                ind_sort[     ind_max_min ] = ind_sort[     ind_min_max ] ^ NLSF_QUANT_DEL_DEC_STATES;
+                RD_Q25[       ind_max_min ] = RD_Q25[       ind_min_max + NLSF_QUANT_DEL_DEC_STATES ];
+                prev_out_Q10[ ind_max_min ] = prev_out_Q10[ ind_min_max + NLSF_QUANT_DEL_DEC_STATES ];
+                RD_min_Q25[   ind_max_min ] = 0;
+                RD_max_Q25[   ind_min_max ] = silk_int32_MAX;
+                silk_memcpy( ind[ ind_max_min ], ind[ ind_min_max ], MAX_LPC_ORDER * sizeof( opus_int8 ) );
+            }
+            /* increment index if it comes from the upper half */
+            for( j = 0; j < NLSF_QUANT_DEL_DEC_STATES; j++ ) {
+                ind[ j ][ i ] += silk_RSHIFT( ind_sort[ j ], NLSF_QUANT_DEL_DEC_STATES_LOG2 );
+            }
+        }
+    }
+
+    /* last sample: find winner, copy indices and return RD value */
+    ind_tmp = 0;
+    min_Q25 = silk_int32_MAX;
+    for( j = 0; j < 2 * NLSF_QUANT_DEL_DEC_STATES; j++ ) {
+        if( min_Q25 > RD_Q25[ j ] ) {
+            min_Q25 = RD_Q25[ j ];
+            ind_tmp = j;
+        }
+    }
+    for( j = 0; j < order; j++ ) {
+        indices[ j ] = ind[ ind_tmp & ( NLSF_QUANT_DEL_DEC_STATES - 1 ) ][ j ];
+        silk_assert( indices[ j ] >= -NLSF_QUANT_MAX_AMPLITUDE_EXT );
+        silk_assert( indices[ j ] <=  NLSF_QUANT_MAX_AMPLITUDE_EXT );
+    }
+    indices[ 0 ] += silk_RSHIFT( ind_tmp, NLSF_QUANT_DEL_DEC_STATES_LOG2 );
+    silk_assert( indices[ 0 ] <= NLSF_QUANT_MAX_AMPLITUDE_EXT );
+    silk_assert( min_Q25 >= 0 );
+    return min_Q25;
+}
diff --git a/opus/silk/NLSF_encode.c b/opus/silk/NLSF_encode.c
new file mode 100644 (file)
index 0000000..268b9a1
--- /dev/null
@@ -0,0 +1,124 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/***********************/
+/* NLSF vector encoder */
+/***********************/
+opus_int32 silk_NLSF_encode(                                    /* O    Returns RD value in Q25                     */
+          opus_int8             *NLSFIndices,                   /* I    Codebook path vector [ LPC_ORDER + 1 ]      */
+          opus_int16            *pNLSF_Q15,                     /* I/O  (Un)quantized NLSF vector [ LPC_ORDER ]     */
+    const silk_NLSF_CB_struct   *psNLSF_CB,                     /* I    Codebook object                             */
+    const opus_int16            *pW_Q2,                         /* I    NLSF weight vector [ LPC_ORDER ]            */
+    const opus_int              NLSF_mu_Q20,                    /* I    Rate weight for the RD optimization         */
+    const opus_int              nSurvivors,                     /* I    Max survivors after first stage             */
+    const opus_int              signalType                      /* I    Signal type: 0/1/2                          */
+)
+{
+    opus_int         i, s, ind1, bestIndex, prob_Q8, bits_q7;
+    opus_int32       W_tmp_Q9, ret;
+    VARDECL( opus_int32, err_Q24 );
+    VARDECL( opus_int32, RD_Q25 );
+    VARDECL( opus_int, tempIndices1 );
+    VARDECL( opus_int8, tempIndices2 );
+    opus_int16       res_Q10[      MAX_LPC_ORDER ];
+    opus_int16       NLSF_tmp_Q15[ MAX_LPC_ORDER ];
+    opus_int16       W_adj_Q5[     MAX_LPC_ORDER ];
+    opus_uint8       pred_Q8[      MAX_LPC_ORDER ];
+    opus_int16       ec_ix[        MAX_LPC_ORDER ];
+    const opus_uint8 *pCB_element, *iCDF_ptr;
+    const opus_int16 *pCB_Wght_Q9;
+    SAVE_STACK;
+
+    silk_assert( signalType >= 0 && signalType <= 2 );
+    silk_assert( NLSF_mu_Q20 <= 32767 && NLSF_mu_Q20 >= 0 );
+
+    /* NLSF stabilization */
+    silk_NLSF_stabilize( pNLSF_Q15, psNLSF_CB->deltaMin_Q15, psNLSF_CB->order );
+
+    /* First stage: VQ */
+    ALLOC( err_Q24, psNLSF_CB->nVectors, opus_int32 );
+    silk_NLSF_VQ( err_Q24, pNLSF_Q15, psNLSF_CB->CB1_NLSF_Q8, psNLSF_CB->CB1_Wght_Q9, psNLSF_CB->nVectors, psNLSF_CB->order );
+
+    /* Sort the quantization errors */
+    ALLOC( tempIndices1, nSurvivors, opus_int );
+    silk_insertion_sort_increasing( err_Q24, tempIndices1, psNLSF_CB->nVectors, nSurvivors );
+
+    ALLOC( RD_Q25, nSurvivors, opus_int32 );
+    ALLOC( tempIndices2, nSurvivors * MAX_LPC_ORDER, opus_int8 );
+
+    /* Loop over survivors */
+    for( s = 0; s < nSurvivors; s++ ) {
+        ind1 = tempIndices1[ s ];
+
+        /* Residual after first stage */
+        pCB_element = &psNLSF_CB->CB1_NLSF_Q8[ ind1 * psNLSF_CB->order ];
+        pCB_Wght_Q9 = &psNLSF_CB->CB1_Wght_Q9[ ind1 * psNLSF_CB->order ];
+        for( i = 0; i < psNLSF_CB->order; i++ ) {
+            NLSF_tmp_Q15[ i ] = silk_LSHIFT16( (opus_int16)pCB_element[ i ], 7 );
+            W_tmp_Q9 = pCB_Wght_Q9[ i ];
+            res_Q10[ i ] = (opus_int16)silk_RSHIFT( silk_SMULBB( pNLSF_Q15[ i ] - NLSF_tmp_Q15[ i ], W_tmp_Q9 ), 14 );
+            W_adj_Q5[ i ] = silk_DIV32_varQ( (opus_int32)pW_Q2[ i ], silk_SMULBB( W_tmp_Q9, W_tmp_Q9 ), 21 );
+        }
+
+        /* Unpack entropy table indices and predictor for current CB1 index */
+        silk_NLSF_unpack( ec_ix, pred_Q8, psNLSF_CB, ind1 );
+
+        /* Trellis quantizer */
+        RD_Q25[ s ] = silk_NLSF_del_dec_quant( &tempIndices2[ s * MAX_LPC_ORDER ], res_Q10, W_adj_Q5, pred_Q8, ec_ix,
+            psNLSF_CB->ec_Rates_Q5, psNLSF_CB->quantStepSize_Q16, psNLSF_CB->invQuantStepSize_Q6, NLSF_mu_Q20, psNLSF_CB->order );
+
+        /* Add rate for first stage */
+        iCDF_ptr = &psNLSF_CB->CB1_iCDF[ ( signalType >> 1 ) * psNLSF_CB->nVectors ];
+        if( ind1 == 0 ) {
+            prob_Q8 = 256 - iCDF_ptr[ ind1 ];
+        } else {
+            prob_Q8 = iCDF_ptr[ ind1 - 1 ] - iCDF_ptr[ ind1 ];
+        }
+        bits_q7 = ( 8 << 7 ) - silk_lin2log( prob_Q8 );
+        RD_Q25[ s ] = silk_SMLABB( RD_Q25[ s ], bits_q7, silk_RSHIFT( NLSF_mu_Q20, 2 ) );
+    }
+
+    /* Find the lowest rate-distortion error */
+    silk_insertion_sort_increasing( RD_Q25, &bestIndex, nSurvivors, 1 );
+
+    NLSFIndices[ 0 ] = (opus_int8)tempIndices1[ bestIndex ];
+    silk_memcpy( &NLSFIndices[ 1 ], &tempIndices2[ bestIndex * MAX_LPC_ORDER ], psNLSF_CB->order * sizeof( opus_int8 ) );
+
+    /* Decode */
+    silk_NLSF_decode( pNLSF_Q15, NLSFIndices, psNLSF_CB );
+
+    ret = RD_Q25[ 0 ];
+    RESTORE_STACK;
+    return ret;
+}
diff --git a/opus/silk/NLSF_stabilize.c b/opus/silk/NLSF_stabilize.c
new file mode 100644 (file)
index 0000000..8f3426b
--- /dev/null
@@ -0,0 +1,142 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* NLSF stabilizer:                                         */
+/*                                                          */
+/* - Moves NLSFs further apart if they are too close        */
+/* - Moves NLSFs away from borders if they are too close    */
+/* - High effort to achieve a modification with minimum     */
+/*     Euclidean distance to input vector                   */
+/* - Output are sorted NLSF coefficients                    */
+/*                                                          */
+
+#include "SigProc_FIX.h"
+
+/* Constant Definitions */
+#define MAX_LOOPS        20
+
+/* NLSF stabilizer, for a single input data vector */
+void silk_NLSF_stabilize(
+          opus_int16            *NLSF_Q15,          /* I/O   Unstable/stabilized normalized LSF vector in Q15 [L]       */
+    const opus_int16            *NDeltaMin_Q15,     /* I     Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1]   */
+    const opus_int              L                   /* I     Number of NLSF parameters in the input vector              */
+)
+{
+    opus_int   i, I=0, k, loops;
+    opus_int16 center_freq_Q15;
+    opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15;
+
+    /* This is necessary to ensure an output within range of a opus_int16 */
+    silk_assert( NDeltaMin_Q15[L] >= 1 );
+
+    for( loops = 0; loops < MAX_LOOPS; loops++ ) {
+        /**************************/
+        /* Find smallest distance */
+        /**************************/
+        /* First element */
+        min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0];
+        I = 0;
+        /* Middle elements */
+        for( i = 1; i <= L-1; i++ ) {
+            diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] );
+            if( diff_Q15 < min_diff_Q15 ) {
+                min_diff_Q15 = diff_Q15;
+                I = i;
+            }
+        }
+        /* Last element */
+        diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] );
+        if( diff_Q15 < min_diff_Q15 ) {
+            min_diff_Q15 = diff_Q15;
+            I = L;
+        }
+
+        /***************************************************/
+        /* Now check if the smallest distance non-negative */
+        /***************************************************/
+        if( min_diff_Q15 >= 0 ) {
+            return;
+        }
+
+        if( I == 0 ) {
+            /* Move away from lower limit */
+            NLSF_Q15[0] = NDeltaMin_Q15[0];
+
+        } else if( I == L) {
+            /* Move away from higher limit */
+            NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L];
+
+        } else {
+            /* Find the lower extreme for the location of the current center frequency */
+            min_center_Q15 = 0;
+            for( k = 0; k < I; k++ ) {
+                min_center_Q15 += NDeltaMin_Q15[k];
+            }
+            min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 );
+
+            /* Find the upper extreme for the location of the current center frequency */
+            max_center_Q15 = 1 << 15;
+            for( k = L; k > I; k-- ) {
+                max_center_Q15 -= NDeltaMin_Q15[k];
+            }
+            max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 );
+
+            /* Move apart, sorted by value, keeping the same center frequency */
+            center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ),
+                min_center_Q15, max_center_Q15 );
+            NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 );
+            NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I];
+        }
+    }
+
+    /* Safe and simple fall back method, which is less ideal than the above */
+    if( loops == MAX_LOOPS )
+    {
+        /* Insertion sort (fast for already almost sorted arrays):   */
+        /* Best case:  O(n)   for an already sorted array            */
+        /* Worst case: O(n^2) for an inversely sorted array          */
+        silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L );
+
+        /* First NLSF should be no less than NDeltaMin[0] */
+        NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] );
+
+        /* Keep delta_min distance between the NLSFs */
+        for( i = 1; i < L; i++ )
+            NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], silk_ADD_SAT16( NLSF_Q15[i-1], NDeltaMin_Q15[i] ) );
+
+        /* Last NLSF should be no higher than 1 - NDeltaMin[L] */
+        NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] );
+
+        /* Keep NDeltaMin distance between the NLSFs */
+        for( i = L-2; i >= 0; i-- )
+            NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] );
+    }
+}
diff --git a/opus/silk/NLSF_unpack.c b/opus/silk/NLSF_unpack.c
new file mode 100644 (file)
index 0000000..17bd23f
--- /dev/null
@@ -0,0 +1,55 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Unpack predictor values and indices for entropy coding tables */
+void silk_NLSF_unpack(
+          opus_int16            ec_ix[],                        /* O    Indices to entropy tables [ LPC_ORDER ]     */
+          opus_uint8            pred_Q8[],                      /* O    LSF predictor [ LPC_ORDER ]                 */
+    const silk_NLSF_CB_struct   *psNLSF_CB,                     /* I    Codebook object                             */
+    const opus_int              CB1_index                       /* I    Index of vector in first LSF codebook       */
+)
+{
+    opus_int   i;
+    opus_uint8 entry;
+    const opus_uint8 *ec_sel_ptr;
+
+    ec_sel_ptr = &psNLSF_CB->ec_sel[ CB1_index * psNLSF_CB->order / 2 ];
+    for( i = 0; i < psNLSF_CB->order; i += 2 ) {
+        entry = *ec_sel_ptr++;
+        ec_ix  [ i     ] = silk_SMULBB( silk_RSHIFT( entry, 1 ) & 7, 2 * NLSF_QUANT_MAX_AMPLITUDE + 1 );
+        pred_Q8[ i     ] = psNLSF_CB->pred_Q8[ i + ( entry & 1 ) * ( psNLSF_CB->order - 1 ) ];
+        ec_ix  [ i + 1 ] = silk_SMULBB( silk_RSHIFT( entry, 5 ) & 7, 2 * NLSF_QUANT_MAX_AMPLITUDE + 1 );
+        pred_Q8[ i + 1 ] = psNLSF_CB->pred_Q8[ i + ( silk_RSHIFT( entry, 4 ) & 1 ) * ( psNLSF_CB->order - 1 ) + 1 ];
+    }
+}
+
diff --git a/opus/silk/NSQ.c b/opus/silk/NSQ.c
new file mode 100644 (file)
index 0000000..617a19f
--- /dev/null
@@ -0,0 +1,437 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+#include "NSQ.h"
+
+
+static OPUS_INLINE void silk_nsq_scale_states(
+    const silk_encoder_state *psEncC,           /* I    Encoder State                   */
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    const opus_int16    x16[],                  /* I    input                           */
+    opus_int32          x_sc_Q10[],             /* O    input scaled with 1/Gain        */
+    const opus_int16    sLTP[],                 /* I    re-whitened LTP state in Q0     */
+    opus_int32          sLTP_Q15[],             /* O    LTP state matching scaled input */
+    opus_int            subfr,                  /* I    subframe number                 */
+    const opus_int      LTP_scale_Q14,          /* I                                    */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ], /* I                                 */
+    const opus_int      pitchL[ MAX_NB_SUBFR ], /* I    Pitch lag                       */
+    const opus_int      signal_type             /* I    Signal type                     */
+);
+
+#if !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+static OPUS_INLINE void silk_noise_shape_quantizer(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    opus_int            signalType,             /* I    Signal type                     */
+    const opus_int32    x_sc_Q10[],             /* I                                    */
+    opus_int8           pulses[],               /* O                                    */
+    opus_int16          xq[],                   /* O                                    */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP state                       */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs     */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs      */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping AR coefs          */
+    opus_int            lag,                    /* I    Pitch lag                       */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                    */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                   */
+    opus_int32          LF_shp_Q14,             /* I                                    */
+    opus_int32          Gain_Q16,               /* I                                    */
+    opus_int            Lambda_Q10,             /* I                                    */
+    opus_int            offset_Q10,             /* I                                    */
+    opus_int            length,                 /* I    Input length                    */
+    opus_int            shapingLPCOrder,        /* I    Noise shaping AR filter order   */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order         */
+    int                 arch                    /* I    Architecture                    */
+);
+#endif
+
+void silk_NSQ_c
+(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int16            x16[],                                        /* I    Input                           */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs              */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+)
+{
+    opus_int            k, lag, start_idx, LSF_interpolation_flag;
+    const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
+    opus_int16          *pxq;
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
+    opus_int32          HarmShapeFIRPacked_Q14;
+    opus_int            offset_Q10;
+    VARDECL( opus_int32, x_sc_Q10 );
+    SAVE_STACK;
+
+    NSQ->rand_seed = psIndices->Seed;
+
+    /* Set unvoiced lag to the previous one, overwrite later for voiced */
+    lag = NSQ->lagPrev;
+
+    silk_assert( NSQ->prev_gain_Q16 != 0 );
+
+    offset_Q10 = silk_Quantization_Offsets_Q10[ psIndices->signalType >> 1 ][ psIndices->quantOffsetType ];
+
+    if( psIndices->NLSFInterpCoef_Q2 == 4 ) {
+        LSF_interpolation_flag = 0;
+    } else {
+        LSF_interpolation_flag = 1;
+    }
+
+    ALLOC( sLTP_Q15, psEncC->ltp_mem_length + psEncC->frame_length, opus_int32 );
+    ALLOC( sLTP, psEncC->ltp_mem_length + psEncC->frame_length, opus_int16 );
+    ALLOC( x_sc_Q10, psEncC->subfr_length, opus_int32 );
+    /* Set up pointers to start of sub frame */
+    NSQ->sLTP_shp_buf_idx = psEncC->ltp_mem_length;
+    NSQ->sLTP_buf_idx     = psEncC->ltp_mem_length;
+    pxq                   = &NSQ->xq[ psEncC->ltp_mem_length ];
+    for( k = 0; k < psEncC->nb_subfr; k++ ) {
+        A_Q12      = &PredCoef_Q12[ (( k >> 1 ) | ( 1 - LSF_interpolation_flag )) * MAX_LPC_ORDER ];
+        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER ];
+        AR_shp_Q13 = &AR_Q13[ k * MAX_SHAPE_LPC_ORDER ];
+
+        /* Noise shape parameters */
+        silk_assert( HarmShapeGain_Q14[ k ] >= 0 );
+        HarmShapeFIRPacked_Q14  =                          silk_RSHIFT( HarmShapeGain_Q14[ k ], 2 );
+        HarmShapeFIRPacked_Q14 |= silk_LSHIFT( (opus_int32)silk_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );
+
+        NSQ->rewhite_flag = 0;
+        if( psIndices->signalType == TYPE_VOICED ) {
+            /* Voiced */
+            lag = pitchL[ k ];
+
+            /* Re-whitening */
+            if( ( k & ( 3 - silk_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {
+                /* Rewhiten with new A coefs */
+                start_idx = psEncC->ltp_mem_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;
+                silk_assert( start_idx > 0 );
+
+                silk_LPC_analysis_filter( &sLTP[ start_idx ], &NSQ->xq[ start_idx + k * psEncC->subfr_length ],
+                    A_Q12, psEncC->ltp_mem_length - start_idx, psEncC->predictLPCOrder, psEncC->arch );
+
+                NSQ->rewhite_flag = 1;
+                NSQ->sLTP_buf_idx = psEncC->ltp_mem_length;
+            }
+        }
+
+        silk_nsq_scale_states( psEncC, NSQ, x16, x_sc_Q10, sLTP, sLTP_Q15, k, LTP_scale_Q14, Gains_Q16, pitchL, psIndices->signalType );
+
+        silk_noise_shape_quantizer( NSQ, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15, A_Q12, B_Q14,
+            AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ], Gains_Q16[ k ], Lambda_Q10,
+            offset_Q10, psEncC->subfr_length, psEncC->shapingLPCOrder, psEncC->predictLPCOrder, psEncC->arch );
+
+        x16    += psEncC->subfr_length;
+        pulses += psEncC->subfr_length;
+        pxq    += psEncC->subfr_length;
+    }
+
+    /* Update lagPrev for next frame */
+    NSQ->lagPrev = pitchL[ psEncC->nb_subfr - 1 ];
+
+    /* Save quantized speech and noise shaping signals */
+    silk_memmove( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int16 ) );
+    silk_memmove( NSQ->sLTP_shp_Q14, &NSQ->sLTP_shp_Q14[ psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
+
+/***********************************/
+/* silk_noise_shape_quantizer  */
+/***********************************/
+
+#if !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+static OPUS_INLINE
+#endif
+void silk_noise_shape_quantizer(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    opus_int            signalType,             /* I    Signal type                     */
+    const opus_int32    x_sc_Q10[],             /* I                                    */
+    opus_int8           pulses[],               /* O                                    */
+    opus_int16          xq[],                   /* O                                    */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP state                       */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs     */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs      */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping AR coefs          */
+    opus_int            lag,                    /* I    Pitch lag                       */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                    */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                   */
+    opus_int32          LF_shp_Q14,             /* I                                    */
+    opus_int32          Gain_Q16,               /* I                                    */
+    opus_int            Lambda_Q10,             /* I                                    */
+    opus_int            offset_Q10,             /* I                                    */
+    opus_int            length,                 /* I    Input length                    */
+    opus_int            shapingLPCOrder,        /* I    Noise shaping AR filter order   */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order         */
+    int                 arch                    /* I    Architecture                    */
+)
+{
+    opus_int     i;
+    opus_int32   LTP_pred_Q13, LPC_pred_Q10, n_AR_Q12, n_LTP_Q13;
+    opus_int32   n_LF_Q12, r_Q10, rr_Q10, q1_Q0, q1_Q10, q2_Q10, rd1_Q20, rd2_Q20;
+    opus_int32   exc_Q14, LPC_exc_Q14, xq_Q14, Gain_Q10;
+    opus_int32   tmp1, tmp2, sLF_AR_shp_Q14;
+    opus_int32   *psLPC_Q14, *shp_lag_ptr, *pred_lag_ptr;
+#ifdef silk_short_prediction_create_arch_coef
+    opus_int32   a_Q12_arch[MAX_LPC_ORDER];
+#endif
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+    /* Set up short term AR state */
+    psLPC_Q14 = &NSQ->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 ];
+
+#ifdef silk_short_prediction_create_arch_coef
+    silk_short_prediction_create_arch_coef(a_Q12_arch, a_Q12, predictLPCOrder);
+#endif
+
+    for( i = 0; i < length; i++ ) {
+        /* Generate dither */
+        NSQ->rand_seed = silk_RAND( NSQ->rand_seed );
+
+        /* Short-term prediction */
+        LPC_pred_Q10 = silk_noise_shape_quantizer_short_prediction(psLPC_Q14, a_Q12, a_Q12_arch, predictLPCOrder, arch);
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q13 = 2;
+            LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[  0 ], b_Q14[ 0 ] );
+            LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -1 ], b_Q14[ 1 ] );
+            LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -2 ], b_Q14[ 2 ] );
+            LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -3 ], b_Q14[ 3 ] );
+            LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );
+            pred_lag_ptr++;
+        } else {
+            LTP_pred_Q13 = 0;
+        }
+
+        /* Noise shape feedback */
+        silk_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */
+        n_AR_Q12 = silk_NSQ_noise_shape_feedback_loop(&NSQ->sDiff_shp_Q14, NSQ->sAR2_Q14, AR_shp_Q13, shapingLPCOrder, arch);
+
+        n_AR_Q12 = silk_SMLAWB( n_AR_Q12, NSQ->sLF_AR_shp_Q14, Tilt_Q14 );
+
+        n_LF_Q12 = silk_SMULWB( NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - 1 ], LF_shp_Q14 );
+        n_LF_Q12 = silk_SMLAWT( n_LF_Q12, NSQ->sLF_AR_shp_Q14, LF_shp_Q14 );
+
+        silk_assert( lag > 0 || signalType != TYPE_VOICED );
+
+        /* Combine prediction and noise shaping signals */
+        tmp1 = silk_SUB32( silk_LSHIFT32( LPC_pred_Q10, 2 ), n_AR_Q12 );        /* Q12 */
+        tmp1 = silk_SUB32( tmp1, n_LF_Q12 );                                    /* Q12 */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q13 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q13 = silk_SMLAWT( n_LTP_Q13, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q13 = silk_LSHIFT( n_LTP_Q13, 1 );
+            shp_lag_ptr++;
+
+            tmp2 = silk_SUB32( LTP_pred_Q13, n_LTP_Q13 );                       /* Q13 */
+            tmp1 = silk_ADD_LSHIFT32( tmp2, tmp1, 1 );                          /* Q13 */
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 3 );                                /* Q10 */
+        } else {
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 2 );                                /* Q10 */
+        }
+
+        r_Q10 = silk_SUB32( x_sc_Q10[ i ], tmp1 );                              /* residual error Q10 */
+
+        /* Flip sign depending on dither */
+        if( NSQ->rand_seed < 0 ) {
+            r_Q10 = -r_Q10;
+        }
+        r_Q10 = silk_LIMIT_32( r_Q10, -(31 << 10), 30 << 10 );
+
+        /* Find two quantization level candidates and measure their rate-distortion */
+        q1_Q10 = silk_SUB32( r_Q10, offset_Q10 );
+        q1_Q0 = silk_RSHIFT( q1_Q10, 10 );
+        if (Lambda_Q10 > 2048) {
+            /* For aggressive RDO, the bias becomes more than one pulse. */
+            int rdo_offset = Lambda_Q10/2 - 512;
+            if (q1_Q10 > rdo_offset) {
+                q1_Q0 = silk_RSHIFT( q1_Q10 - rdo_offset, 10 );
+            } else if (q1_Q10 < -rdo_offset) {
+                q1_Q0 = silk_RSHIFT( q1_Q10 + rdo_offset, 10 );
+            } else if (q1_Q10 < 0) {
+                q1_Q0 = -1;
+            } else {
+                q1_Q0 = 0;
+            }
+        }
+        if( q1_Q0 > 0 ) {
+            q1_Q10  = silk_SUB32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+            q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+            q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+            rd1_Q20 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+            rd2_Q20 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+        } else if( q1_Q0 == 0 ) {
+            q1_Q10  = offset_Q10;
+            q2_Q10  = silk_ADD32( q1_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+            rd1_Q20 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+            rd2_Q20 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+        } else if( q1_Q0 == -1 ) {
+            q2_Q10  = offset_Q10;
+            q1_Q10  = silk_SUB32( q2_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+            rd1_Q20 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+            rd2_Q20 = silk_SMULBB(  q2_Q10, Lambda_Q10 );
+        } else {            /* Q1_Q0 < -1 */
+            q1_Q10  = silk_ADD32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+            q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+            q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+            rd1_Q20 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+            rd2_Q20 = silk_SMULBB( -q2_Q10, Lambda_Q10 );
+        }
+        rr_Q10  = silk_SUB32( r_Q10, q1_Q10 );
+        rd1_Q20 = silk_SMLABB( rd1_Q20, rr_Q10, rr_Q10 );
+        rr_Q10  = silk_SUB32( r_Q10, q2_Q10 );
+        rd2_Q20 = silk_SMLABB( rd2_Q20, rr_Q10, rr_Q10 );
+
+        if( rd2_Q20 < rd1_Q20 ) {
+            q1_Q10 = q2_Q10;
+        }
+
+        pulses[ i ] = (opus_int8)silk_RSHIFT_ROUND( q1_Q10, 10 );
+
+        /* Excitation */
+        exc_Q14 = silk_LSHIFT( q1_Q10, 4 );
+        if ( NSQ->rand_seed < 0 ) {
+           exc_Q14 = -exc_Q14;
+        }
+
+        /* Add predictions */
+        LPC_exc_Q14 = silk_ADD_LSHIFT32( exc_Q14, LTP_pred_Q13, 1 );
+        xq_Q14      = silk_ADD_LSHIFT32( LPC_exc_Q14, LPC_pred_Q10, 4 );
+
+        /* Scale XQ back to normal level before saving */
+        xq[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( xq_Q14, Gain_Q10 ), 8 ) );
+
+        /* Update states */
+        psLPC_Q14++;
+        *psLPC_Q14 = xq_Q14;
+        NSQ->sDiff_shp_Q14 = silk_SUB_LSHIFT32( xq_Q14, x_sc_Q10[ i ], 4 );
+        sLF_AR_shp_Q14 = silk_SUB_LSHIFT32( NSQ->sDiff_shp_Q14, n_AR_Q12, 2 );
+        NSQ->sLF_AR_shp_Q14 = sLF_AR_shp_Q14;
+
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx ] = silk_SUB_LSHIFT32( sLF_AR_shp_Q14, n_LF_Q12, 2 );
+        sLTP_Q15[ NSQ->sLTP_buf_idx ] = silk_LSHIFT( LPC_exc_Q14, 1 );
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Make dither dependent on quantized signal */
+        NSQ->rand_seed = silk_ADD32_ovflw( NSQ->rand_seed, pulses[ i ] );
+    }
+
+    /* Update LPC synth buffer */
+    silk_memcpy( NSQ->sLPC_Q14, &NSQ->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+}
+
+static OPUS_INLINE void silk_nsq_scale_states(
+    const silk_encoder_state *psEncC,           /* I    Encoder State                   */
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    const opus_int16    x16[],                  /* I    input                           */
+    opus_int32          x_sc_Q10[],             /* O    input scaled with 1/Gain        */
+    const opus_int16    sLTP[],                 /* I    re-whitened LTP state in Q0     */
+    opus_int32          sLTP_Q15[],             /* O    LTP state matching scaled input */
+    opus_int            subfr,                  /* I    subframe number                 */
+    const opus_int      LTP_scale_Q14,          /* I                                    */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ], /* I                                 */
+    const opus_int      pitchL[ MAX_NB_SUBFR ], /* I    Pitch lag                       */
+    const opus_int      signal_type             /* I    Signal type                     */
+)
+{
+    opus_int   i, lag;
+    opus_int32 gain_adj_Q16, inv_gain_Q31, inv_gain_Q26;
+
+    lag          = pitchL[ subfr ];
+    inv_gain_Q31 = silk_INVERSE32_varQ( silk_max( Gains_Q16[ subfr ], 1 ), 47 );
+    silk_assert( inv_gain_Q31 != 0 );
+
+    /* Scale input */
+    inv_gain_Q26 = silk_RSHIFT_ROUND( inv_gain_Q31, 5 );
+    for( i = 0; i < psEncC->subfr_length; i++ ) {
+        x_sc_Q10[ i ] = silk_SMULWW( x16[ i ], inv_gain_Q26 );
+    }
+
+    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */
+    if( NSQ->rewhite_flag ) {
+        if( subfr == 0 ) {
+            /* Do LTP downscaling */
+            inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, LTP_scale_Q14 ), 2 );
+        }
+        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+            silk_assert( i < MAX_FRAME_LENGTH );
+            sLTP_Q15[ i ] = silk_SMULWB( inv_gain_Q31, sLTP[ i ] );
+        }
+    }
+
+    /* Adjust for changing gain */
+    if( Gains_Q16[ subfr ] != NSQ->prev_gain_Q16 ) {
+        gain_adj_Q16 =  silk_DIV32_varQ( NSQ->prev_gain_Q16, Gains_Q16[ subfr ], 16 );
+
+        /* Scale long-term shaping state */
+        for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+            NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+        }
+
+        /* Scale long-term prediction state */
+        if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+            for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+                sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+            }
+        }
+
+        NSQ->sLF_AR_shp_Q14 = silk_SMULWW( gain_adj_Q16, NSQ->sLF_AR_shp_Q14 );
+        NSQ->sDiff_shp_Q14 = silk_SMULWW( gain_adj_Q16, NSQ->sDiff_shp_Q14 );
+
+        /* Scale short-term prediction and shaping states */
+        for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+            NSQ->sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLPC_Q14[ i ] );
+        }
+        for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+            NSQ->sAR2_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sAR2_Q14[ i ] );
+        }
+
+        /* Save inverse gain */
+        NSQ->prev_gain_Q16 = Gains_Q16[ subfr ];
+    }
+}
diff --git a/opus/silk/NSQ.h b/opus/silk/NSQ.h
new file mode 100644 (file)
index 0000000..971832f
--- /dev/null
@@ -0,0 +1,101 @@
+/***********************************************************************
+Copyright (c) 2014 Vidyo.
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_NSQ_H
+#define SILK_NSQ_H
+
+#include "SigProc_FIX.h"
+
+#undef silk_short_prediction_create_arch_coef
+
+static OPUS_INLINE opus_int32 silk_noise_shape_quantizer_short_prediction_c(const opus_int32 *buf32, const opus_int16 *coef16, opus_int order)
+{
+    opus_int32 out;
+    silk_assert( order == 10 || order == 16 );
+
+    /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+    out = silk_RSHIFT( order, 1 );
+    out = silk_SMLAWB( out, buf32[  0 ], coef16[ 0 ] );
+    out = silk_SMLAWB( out, buf32[ -1 ], coef16[ 1 ] );
+    out = silk_SMLAWB( out, buf32[ -2 ], coef16[ 2 ] );
+    out = silk_SMLAWB( out, buf32[ -3 ], coef16[ 3 ] );
+    out = silk_SMLAWB( out, buf32[ -4 ], coef16[ 4 ] );
+    out = silk_SMLAWB( out, buf32[ -5 ], coef16[ 5 ] );
+    out = silk_SMLAWB( out, buf32[ -6 ], coef16[ 6 ] );
+    out = silk_SMLAWB( out, buf32[ -7 ], coef16[ 7 ] );
+    out = silk_SMLAWB( out, buf32[ -8 ], coef16[ 8 ] );
+    out = silk_SMLAWB( out, buf32[ -9 ], coef16[ 9 ] );
+
+    if( order == 16 )
+    {
+        out = silk_SMLAWB( out, buf32[ -10 ], coef16[ 10 ] );
+        out = silk_SMLAWB( out, buf32[ -11 ], coef16[ 11 ] );
+        out = silk_SMLAWB( out, buf32[ -12 ], coef16[ 12 ] );
+        out = silk_SMLAWB( out, buf32[ -13 ], coef16[ 13 ] );
+        out = silk_SMLAWB( out, buf32[ -14 ], coef16[ 14 ] );
+        out = silk_SMLAWB( out, buf32[ -15 ], coef16[ 15 ] );
+    }
+    return out;
+}
+
+#define silk_noise_shape_quantizer_short_prediction(in, coef, coefRev, order, arch)  ((void)arch,silk_noise_shape_quantizer_short_prediction_c(in, coef, order))
+
+static OPUS_INLINE opus_int32 silk_NSQ_noise_shape_feedback_loop_c(const opus_int32 *data0, opus_int32 *data1, const opus_int16 *coef, opus_int order)
+{
+    opus_int32 out;
+    opus_int32 tmp1, tmp2;
+    opus_int j;
+
+    tmp2 = data0[0];
+    tmp1 = data1[0];
+    data1[0] = tmp2;
+
+    out = silk_RSHIFT(order, 1);
+    out = silk_SMLAWB(out, tmp2, coef[0]);
+
+    for (j = 2; j < order; j += 2) {
+        tmp2 = data1[j - 1];
+        data1[j - 1] = tmp1;
+        out = silk_SMLAWB(out, tmp1, coef[j - 1]);
+        tmp1 = data1[j + 0];
+        data1[j + 0] = tmp2;
+        out = silk_SMLAWB(out, tmp2, coef[j]);
+    }
+    data1[order - 1] = tmp1;
+    out = silk_SMLAWB(out, tmp1, coef[order - 1]);
+    /* Q11 -> Q12 */
+    out = silk_LSHIFT32( out, 1 );
+    return out;
+}
+
+#define silk_NSQ_noise_shape_feedback_loop(data0, data1, coef, order, arch)  ((void)arch,silk_NSQ_noise_shape_feedback_loop_c(data0, data1, coef, order))
+
+#if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+#include "arm/NSQ_neon.h"
+#endif
+
+#endif /* SILK_NSQ_H */
diff --git a/opus/silk/NSQ_del_dec.c b/opus/silk/NSQ_del_dec.c
new file mode 100644 (file)
index 0000000..1cd29d9
--- /dev/null
@@ -0,0 +1,733 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+#include "NSQ.h"
+
+
+typedef struct {
+    opus_int32 sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ];
+    opus_int32 RandState[ DECISION_DELAY ];
+    opus_int32 Q_Q10[     DECISION_DELAY ];
+    opus_int32 Xq_Q14[    DECISION_DELAY ];
+    opus_int32 Pred_Q15[  DECISION_DELAY ];
+    opus_int32 Shape_Q14[ DECISION_DELAY ];
+    opus_int32 sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];
+    opus_int32 LF_AR_Q14;
+    opus_int32 Diff_Q14;
+    opus_int32 Seed;
+    opus_int32 SeedInit;
+    opus_int32 RD_Q10;
+} NSQ_del_dec_struct;
+
+typedef struct {
+    opus_int32 Q_Q10;
+    opus_int32 RD_Q10;
+    opus_int32 xq_Q14;
+    opus_int32 LF_AR_Q14;
+    opus_int32 Diff_Q14;
+    opus_int32 sLTP_shp_Q14;
+    opus_int32 LPC_exc_Q14;
+} NSQ_sample_struct;
+
+typedef NSQ_sample_struct  NSQ_sample_pair[ 2 ];
+
+#if defined(MIPSr1_ASM)
+#include "mips/NSQ_del_dec_mipsr1.h"
+#endif
+static OPUS_INLINE void silk_nsq_del_dec_scale_states(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int16    x16[],                      /* I    Input                               */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    opus_int            nStatesDelayedDecision,     /* I    Number of del dec states            */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+);
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay,          /* I                                        */
+    int                 arch                    /* I                                        */
+);
+
+void silk_NSQ_del_dec_c(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int16            x16[],                                        /* I    Input                           */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs              */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+)
+{
+    opus_int            i, k, lag, start_idx, LSF_interpolation_flag, Winner_ind, subfr;
+    opus_int            last_smple_idx, smpl_buf_idx, decisionDelay;
+    const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
+    opus_int16          *pxq;
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
+    opus_int32          HarmShapeFIRPacked_Q14;
+    opus_int            offset_Q10;
+    opus_int32          RDmin_Q10, Gain_Q10;
+    VARDECL( opus_int32, x_sc_Q10 );
+    VARDECL( opus_int32, delayedGain_Q10 );
+    VARDECL( NSQ_del_dec_struct, psDelDec );
+    NSQ_del_dec_struct  *psDD;
+    SAVE_STACK;
+
+    /* Set unvoiced lag to the previous one, overwrite later for voiced */
+    lag = NSQ->lagPrev;
+
+    silk_assert( NSQ->prev_gain_Q16 != 0 );
+
+    /* Initialize delayed decision states */
+    ALLOC( psDelDec, psEncC->nStatesDelayedDecision, NSQ_del_dec_struct );
+    silk_memset( psDelDec, 0, psEncC->nStatesDelayedDecision * sizeof( NSQ_del_dec_struct ) );
+    for( k = 0; k < psEncC->nStatesDelayedDecision; k++ ) {
+        psDD                 = &psDelDec[ k ];
+        psDD->Seed           = ( k + psIndices->Seed ) & 3;
+        psDD->SeedInit       = psDD->Seed;
+        psDD->RD_Q10         = 0;
+        psDD->LF_AR_Q14      = NSQ->sLF_AR_shp_Q14;
+        psDD->Diff_Q14       = NSQ->sDiff_shp_Q14;
+        psDD->Shape_Q14[ 0 ] = NSQ->sLTP_shp_Q14[ psEncC->ltp_mem_length - 1 ];
+        silk_memcpy( psDD->sLPC_Q14, NSQ->sLPC_Q14, NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+        silk_memcpy( psDD->sAR2_Q14, NSQ->sAR2_Q14, sizeof( NSQ->sAR2_Q14 ) );
+    }
+
+    offset_Q10   = silk_Quantization_Offsets_Q10[ psIndices->signalType >> 1 ][ psIndices->quantOffsetType ];
+    smpl_buf_idx = 0; /* index of oldest samples */
+
+    decisionDelay = silk_min_int( DECISION_DELAY, psEncC->subfr_length );
+
+    /* For voiced frames limit the decision delay to lower than the pitch lag */
+    if( psIndices->signalType == TYPE_VOICED ) {
+        for( k = 0; k < psEncC->nb_subfr; k++ ) {
+            decisionDelay = silk_min_int( decisionDelay, pitchL[ k ] - LTP_ORDER / 2 - 1 );
+        }
+    } else {
+        if( lag > 0 ) {
+            decisionDelay = silk_min_int( decisionDelay, lag - LTP_ORDER / 2 - 1 );
+        }
+    }
+
+    if( psIndices->NLSFInterpCoef_Q2 == 4 ) {
+        LSF_interpolation_flag = 0;
+    } else {
+        LSF_interpolation_flag = 1;
+    }
+
+    ALLOC( sLTP_Q15, psEncC->ltp_mem_length + psEncC->frame_length, opus_int32 );
+    ALLOC( sLTP, psEncC->ltp_mem_length + psEncC->frame_length, opus_int16 );
+    ALLOC( x_sc_Q10, psEncC->subfr_length, opus_int32 );
+    ALLOC( delayedGain_Q10, DECISION_DELAY, opus_int32 );
+    /* Set up pointers to start of sub frame */
+    pxq                   = &NSQ->xq[ psEncC->ltp_mem_length ];
+    NSQ->sLTP_shp_buf_idx = psEncC->ltp_mem_length;
+    NSQ->sLTP_buf_idx     = psEncC->ltp_mem_length;
+    subfr = 0;
+    for( k = 0; k < psEncC->nb_subfr; k++ ) {
+        A_Q12      = &PredCoef_Q12[ ( ( k >> 1 ) | ( 1 - LSF_interpolation_flag ) ) * MAX_LPC_ORDER ];
+        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER           ];
+        AR_shp_Q13 = &AR_Q13[     k * MAX_SHAPE_LPC_ORDER ];
+
+        /* Noise shape parameters */
+        silk_assert( HarmShapeGain_Q14[ k ] >= 0 );
+        HarmShapeFIRPacked_Q14  =                          silk_RSHIFT( HarmShapeGain_Q14[ k ], 2 );
+        HarmShapeFIRPacked_Q14 |= silk_LSHIFT( (opus_int32)silk_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );
+
+        NSQ->rewhite_flag = 0;
+        if( psIndices->signalType == TYPE_VOICED ) {
+            /* Voiced */
+            lag = pitchL[ k ];
+
+            /* Re-whitening */
+            if( ( k & ( 3 - silk_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {
+                if( k == 2 ) {
+                    /* RESET DELAYED DECISIONS */
+                    /* Find winner */
+                    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;
+                    Winner_ind = 0;
+                    for( i = 1; i < psEncC->nStatesDelayedDecision; i++ ) {
+                        if( psDelDec[ i ].RD_Q10 < RDmin_Q10 ) {
+                            RDmin_Q10 = psDelDec[ i ].RD_Q10;
+                            Winner_ind = i;
+                        }
+                    }
+                    for( i = 0; i < psEncC->nStatesDelayedDecision; i++ ) {
+                        if( i != Winner_ind ) {
+                            psDelDec[ i ].RD_Q10 += ( silk_int32_MAX >> 4 );
+                            silk_assert( psDelDec[ i ].RD_Q10 >= 0 );
+                        }
+                    }
+
+                    /* Copy final part of signals from winner state to output and long-term filter states */
+                    psDD = &psDelDec[ Winner_ind ];
+                    last_smple_idx = smpl_buf_idx + decisionDelay;
+                    for( i = 0; i < decisionDelay; i++ ) {
+                        last_smple_idx = ( last_smple_idx - 1 ) % DECISION_DELAY;
+                        if( last_smple_idx < 0 ) last_smple_idx += DECISION_DELAY;
+                        pulses[   i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+                        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                            silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], Gains_Q16[ 1 ] ), 14 ) );
+                        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q14[ last_smple_idx ];
+                    }
+
+                    subfr = 0;
+                }
+
+                /* Rewhiten with new A coefs */
+                start_idx = psEncC->ltp_mem_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;
+                silk_assert( start_idx > 0 );
+
+                silk_LPC_analysis_filter( &sLTP[ start_idx ], &NSQ->xq[ start_idx + k * psEncC->subfr_length ],
+                    A_Q12, psEncC->ltp_mem_length - start_idx, psEncC->predictLPCOrder, psEncC->arch );
+
+                NSQ->sLTP_buf_idx = psEncC->ltp_mem_length;
+                NSQ->rewhite_flag = 1;
+            }
+        }
+
+        silk_nsq_del_dec_scale_states( psEncC, NSQ, psDelDec, x16, x_sc_Q10, sLTP, sLTP_Q15, k,
+            psEncC->nStatesDelayedDecision, LTP_scale_Q14, Gains_Q16, pitchL, psIndices->signalType, decisionDelay );
+
+        silk_noise_shape_quantizer_del_dec( NSQ, psDelDec, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15,
+            delayedGain_Q10, A_Q12, B_Q14, AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ],
+            Gains_Q16[ k ], Lambda_Q10, offset_Q10, psEncC->subfr_length, subfr++, psEncC->shapingLPCOrder,
+            psEncC->predictLPCOrder, psEncC->warping_Q16, psEncC->nStatesDelayedDecision, &smpl_buf_idx, decisionDelay, psEncC->arch );
+
+        x16    += psEncC->subfr_length;
+        pulses += psEncC->subfr_length;
+        pxq    += psEncC->subfr_length;
+    }
+
+    /* Find winner */
+    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;
+    Winner_ind = 0;
+    for( k = 1; k < psEncC->nStatesDelayedDecision; k++ ) {
+        if( psDelDec[ k ].RD_Q10 < RDmin_Q10 ) {
+            RDmin_Q10 = psDelDec[ k ].RD_Q10;
+            Winner_ind = k;
+        }
+    }
+
+    /* Copy final part of signals from winner state to output and long-term filter states */
+    psDD = &psDelDec[ Winner_ind ];
+    psIndices->Seed = psDD->SeedInit;
+    last_smple_idx = smpl_buf_idx + decisionDelay;
+    Gain_Q10 = silk_RSHIFT32( Gains_Q16[ psEncC->nb_subfr - 1 ], 6 );
+    for( i = 0; i < decisionDelay; i++ ) {
+        last_smple_idx = ( last_smple_idx - 1 ) % DECISION_DELAY;
+        if( last_smple_idx < 0 ) last_smple_idx += DECISION_DELAY;
+
+        pulses[   i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+            silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], Gain_Q10 ), 8 ) );
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q14[ last_smple_idx ];
+    }
+    silk_memcpy( NSQ->sLPC_Q14, &psDD->sLPC_Q14[ psEncC->subfr_length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+    silk_memcpy( NSQ->sAR2_Q14, psDD->sAR2_Q14, sizeof( psDD->sAR2_Q14 ) );
+
+    /* Update states */
+    NSQ->sLF_AR_shp_Q14 = psDD->LF_AR_Q14;
+    NSQ->sDiff_shp_Q14  = psDD->Diff_Q14;
+    NSQ->lagPrev        = pitchL[ psEncC->nb_subfr - 1 ];
+
+    /* Save quantized speech signal */
+    silk_memmove( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int16 ) );
+    silk_memmove( NSQ->sLTP_shp_Q14, &NSQ->sLTP_shp_Q14[ psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+#ifndef OVERRIDE_silk_noise_shape_quantizer_del_dec
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay,          /* I                                        */
+    int                 arch                    /* I                                        */
+)
+{
+    opus_int     i, j, k, Winner_ind, RDmin_ind, RDmax_ind, last_smple_idx;
+    opus_int32   Winner_rand_state;
+    opus_int32   LTP_pred_Q14, LPC_pred_Q14, n_AR_Q14, n_LTP_Q14;
+    opus_int32   n_LF_Q14, r_Q10, rr_Q10, rd1_Q10, rd2_Q10, RDmin_Q10, RDmax_Q10;
+    opus_int32   q1_Q0, q1_Q10, q2_Q10, exc_Q14, LPC_exc_Q14, xq_Q14, Gain_Q10;
+    opus_int32   tmp1, tmp2, sLF_AR_shp_Q14;
+    opus_int32   *pred_lag_ptr, *shp_lag_ptr, *psLPC_Q14;
+#ifdef silk_short_prediction_create_arch_coef
+    opus_int32   a_Q12_arch[MAX_LPC_ORDER];
+#endif
+
+    VARDECL( NSQ_sample_pair, psSampleState );
+    NSQ_del_dec_struct *psDD;
+    NSQ_sample_struct  *psSS;
+    SAVE_STACK;
+
+    silk_assert( nStatesDelayedDecision > 0 );
+    ALLOC( psSampleState, nStatesDelayedDecision, NSQ_sample_pair );
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+#ifdef silk_short_prediction_create_arch_coef
+    silk_short_prediction_create_arch_coef(a_Q12_arch, a_Q12, predictLPCOrder);
+#endif
+
+    for( i = 0; i < length; i++ ) {
+        /* Perform common calculations used in all states */
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q14 = 2;
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[  0 ], b_Q14[ 0 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], b_Q14[ 1 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], b_Q14[ 2 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], b_Q14[ 3 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );
+            LTP_pred_Q14 = silk_LSHIFT( LTP_pred_Q14, 1 );                          /* Q13 -> Q14 */
+            pred_lag_ptr++;
+        } else {
+            LTP_pred_Q14 = 0;
+        }
+
+        /* Long-term shaping */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q14 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SUB_LSHIFT32( LTP_pred_Q14, n_LTP_Q14, 2 );            /* Q12 -> Q14 */
+            shp_lag_ptr++;
+        } else {
+            n_LTP_Q14 = 0;
+        }
+
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            /* Delayed decision state */
+            psDD = &psDelDec[ k ];
+
+            /* Sample state */
+            psSS = psSampleState[ k ];
+
+            /* Generate dither */
+            psDD->Seed = silk_RAND( psDD->Seed );
+
+            /* Pointer used in short term prediction and shaping */
+            psLPC_Q14 = &psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 + i ];
+            /* Short-term prediction */
+            LPC_pred_Q14 = silk_noise_shape_quantizer_short_prediction(psLPC_Q14, a_Q12, a_Q12_arch, predictLPCOrder, arch);
+            LPC_pred_Q14 = silk_LSHIFT( LPC_pred_Q14, 4 );                              /* Q10 -> Q14 */
+
+            /* Noise shape feedback */
+            silk_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */
+            /* Output of lowpass section */
+            tmp2 = silk_SMLAWB( psDD->Diff_Q14, psDD->sAR2_Q14[ 0 ], warping_Q16 );
+            /* Output of allpass section */
+            tmp1 = silk_SMLAWB( psDD->sAR2_Q14[ 0 ], psDD->sAR2_Q14[ 1 ] - tmp2, warping_Q16 );
+            psDD->sAR2_Q14[ 0 ] = tmp2;
+            n_AR_Q14 = silk_RSHIFT( shapingLPCOrder, 1 );
+            n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp2, AR_shp_Q13[ 0 ] );
+            /* Loop over allpass sections */
+            for( j = 2; j < shapingLPCOrder; j += 2 ) {
+                /* Output of allpass section */
+                tmp2 = silk_SMLAWB( psDD->sAR2_Q14[ j - 1 ], psDD->sAR2_Q14[ j + 0 ] - tmp1, warping_Q16 );
+                psDD->sAR2_Q14[ j - 1 ] = tmp1;
+                n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp1, AR_shp_Q13[ j - 1 ] );
+                /* Output of allpass section */
+                tmp1 = silk_SMLAWB( psDD->sAR2_Q14[ j + 0 ], psDD->sAR2_Q14[ j + 1 ] - tmp2, warping_Q16 );
+                psDD->sAR2_Q14[ j + 0 ] = tmp2;
+                n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp2, AR_shp_Q13[ j ] );
+            }
+            psDD->sAR2_Q14[ shapingLPCOrder - 1 ] = tmp1;
+            n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp1, AR_shp_Q13[ shapingLPCOrder - 1 ] );
+
+            n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 1 );                                      /* Q11 -> Q12 */
+            n_AR_Q14 = silk_SMLAWB( n_AR_Q14, psDD->LF_AR_Q14, Tilt_Q14 );              /* Q12 */
+            n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 2 );                                      /* Q12 -> Q14 */
+
+            n_LF_Q14 = silk_SMULWB( psDD->Shape_Q14[ *smpl_buf_idx ], LF_shp_Q14 );     /* Q12 */
+            n_LF_Q14 = silk_SMLAWT( n_LF_Q14, psDD->LF_AR_Q14, LF_shp_Q14 );            /* Q12 */
+            n_LF_Q14 = silk_LSHIFT( n_LF_Q14, 2 );                                      /* Q12 -> Q14 */
+
+            /* Input minus prediction plus noise feedback                       */
+            /* r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP  */
+            tmp1 = silk_ADD32( n_AR_Q14, n_LF_Q14 );                                    /* Q14 */
+            tmp2 = silk_ADD32( n_LTP_Q14, LPC_pred_Q14 );                               /* Q13 */
+            tmp1 = silk_SUB32( tmp2, tmp1 );                                            /* Q13 */
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 4 );                                        /* Q10 */
+
+            r_Q10 = silk_SUB32( x_Q10[ i ], tmp1 );                                     /* residual error Q10 */
+
+            /* Flip sign depending on dither */
+            if ( psDD->Seed < 0 ) {
+                r_Q10 = -r_Q10;
+            }
+            r_Q10 = silk_LIMIT_32( r_Q10, -(31 << 10), 30 << 10 );
+
+            /* Find two quantization level candidates and measure their rate-distortion */
+            q1_Q10 = silk_SUB32( r_Q10, offset_Q10 );
+            q1_Q0 = silk_RSHIFT( q1_Q10, 10 );
+            if (Lambda_Q10 > 2048) {
+                /* For aggressive RDO, the bias becomes more than one pulse. */
+                int rdo_offset = Lambda_Q10/2 - 512;
+                if (q1_Q10 > rdo_offset) {
+                    q1_Q0 = silk_RSHIFT( q1_Q10 - rdo_offset, 10 );
+                } else if (q1_Q10 < -rdo_offset) {
+                    q1_Q0 = silk_RSHIFT( q1_Q10 + rdo_offset, 10 );
+                } else if (q1_Q10 < 0) {
+                    q1_Q0 = -1;
+                } else {
+                    q1_Q0 = 0;
+                }
+            }
+            if( q1_Q0 > 0 ) {
+                q1_Q10  = silk_SUB32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+            } else if( q1_Q0 == 0 ) {
+                q1_Q10  = offset_Q10;
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+            } else if( q1_Q0 == -1 ) {
+                q2_Q10  = offset_Q10;
+                q1_Q10  = silk_SUB32( q2_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB(  q2_Q10, Lambda_Q10 );
+            } else {            /* q1_Q0 < -1 */
+                q1_Q10  = silk_ADD32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( -q2_Q10, Lambda_Q10 );
+            }
+            rr_Q10  = silk_SUB32( r_Q10, q1_Q10 );
+            rd1_Q10 = silk_RSHIFT( silk_SMLABB( rd1_Q10, rr_Q10, rr_Q10 ), 10 );
+            rr_Q10  = silk_SUB32( r_Q10, q2_Q10 );
+            rd2_Q10 = silk_RSHIFT( silk_SMLABB( rd2_Q10, rr_Q10, rr_Q10 ), 10 );
+
+            if( rd1_Q10 < rd2_Q10 ) {
+                psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                psSS[ 0 ].Q_Q10  = q1_Q10;
+                psSS[ 1 ].Q_Q10  = q2_Q10;
+            } else {
+                psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                psSS[ 0 ].Q_Q10  = q2_Q10;
+                psSS[ 1 ].Q_Q10  = q1_Q10;
+            }
+
+            /* Update states for best quantization */
+
+            /* Quantized excitation */
+            exc_Q14 = silk_LSHIFT32( psSS[ 0 ].Q_Q10, 4 );
+            if ( psDD->Seed < 0 ) {
+                exc_Q14 = -exc_Q14;
+            }
+
+            /* Add predictions */
+            LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+            xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+            /* Update states */
+            psSS[ 0 ].Diff_Q14     = silk_SUB_LSHIFT32( xq_Q14, x_Q10[ i ], 4 );
+            sLF_AR_shp_Q14         = silk_SUB32( psSS[ 0 ].Diff_Q14, n_AR_Q14 );
+            psSS[ 0 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+            psSS[ 0 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+            psSS[ 0 ].LPC_exc_Q14  = LPC_exc_Q14;
+            psSS[ 0 ].xq_Q14       = xq_Q14;
+
+            /* Update states for second best quantization */
+
+            /* Quantized excitation */
+            exc_Q14 = silk_LSHIFT32( psSS[ 1 ].Q_Q10, 4 );
+            if ( psDD->Seed < 0 ) {
+                exc_Q14 = -exc_Q14;
+            }
+
+            /* Add predictions */
+            LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+            xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+            /* Update states */
+            psSS[ 1 ].Diff_Q14     = silk_SUB_LSHIFT32( xq_Q14, x_Q10[ i ], 4 );
+            sLF_AR_shp_Q14         = silk_SUB32( psSS[ 1 ].Diff_Q14, n_AR_Q14 );
+            psSS[ 1 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+            psSS[ 1 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+            psSS[ 1 ].LPC_exc_Q14  = LPC_exc_Q14;
+            psSS[ 1 ].xq_Q14       = xq_Q14;
+        }
+
+        *smpl_buf_idx  = ( *smpl_buf_idx - 1 ) % DECISION_DELAY;
+        if( *smpl_buf_idx < 0 ) *smpl_buf_idx += DECISION_DELAY;
+        last_smple_idx = ( *smpl_buf_idx + decisionDelay ) % DECISION_DELAY;
+
+        /* Find winner */
+        RDmin_Q10 = psSampleState[ 0 ][ 0 ].RD_Q10;
+        Winner_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            if( psSampleState[ k ][ 0 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                Winner_ind = k;
+            }
+        }
+
+        /* Increase RD values of expired states */
+        Winner_rand_state = psDelDec[ Winner_ind ].RandState[ last_smple_idx ];
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            if( psDelDec[ k ].RandState[ last_smple_idx ] != Winner_rand_state ) {
+                psSampleState[ k ][ 0 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 0 ].RD_Q10, silk_int32_MAX >> 4 );
+                psSampleState[ k ][ 1 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 1 ].RD_Q10, silk_int32_MAX >> 4 );
+                silk_assert( psSampleState[ k ][ 0 ].RD_Q10 >= 0 );
+            }
+        }
+
+        /* Find worst in first set and best in second set */
+        RDmax_Q10  = psSampleState[ 0 ][ 0 ].RD_Q10;
+        RDmin_Q10  = psSampleState[ 0 ][ 1 ].RD_Q10;
+        RDmax_ind = 0;
+        RDmin_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            /* find worst in first set */
+            if( psSampleState[ k ][ 0 ].RD_Q10 > RDmax_Q10 ) {
+                RDmax_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                RDmax_ind = k;
+            }
+            /* find best in second set */
+            if( psSampleState[ k ][ 1 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 1 ].RD_Q10;
+                RDmin_ind = k;
+            }
+        }
+
+        /* Replace a state if best from second set outperforms worst in first set */
+        if( RDmin_Q10 < RDmax_Q10 ) {
+            silk_memcpy( ( (opus_int32 *)&psDelDec[ RDmax_ind ] ) + i,
+                         ( (opus_int32 *)&psDelDec[ RDmin_ind ] ) + i, sizeof( NSQ_del_dec_struct ) - i * sizeof( opus_int32) );
+            silk_memcpy( &psSampleState[ RDmax_ind ][ 0 ], &psSampleState[ RDmin_ind ][ 1 ], sizeof( NSQ_sample_struct ) );
+        }
+
+        /* Write samples from winner to output and long-term filter states */
+        psDD = &psDelDec[ Winner_ind ];
+        if( subfr > 0 || i >= decisionDelay ) {
+            pulses[  i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+            xq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], delayedGain_Q10[ last_smple_idx ] ), 8 ) );
+            NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay ] = psDD->Shape_Q14[ last_smple_idx ];
+            sLTP_Q15[          NSQ->sLTP_buf_idx     - decisionDelay ] = psDD->Pred_Q15[  last_smple_idx ];
+        }
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Update states */
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            psDD                                     = &psDelDec[ k ];
+            psSS                                     = &psSampleState[ k ][ 0 ];
+            psDD->LF_AR_Q14                          = psSS->LF_AR_Q14;
+            psDD->Diff_Q14                           = psSS->Diff_Q14;
+            psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH + i ] = psSS->xq_Q14;
+            psDD->Xq_Q14[    *smpl_buf_idx ]         = psSS->xq_Q14;
+            psDD->Q_Q10[     *smpl_buf_idx ]         = psSS->Q_Q10;
+            psDD->Pred_Q15[  *smpl_buf_idx ]         = silk_LSHIFT32( psSS->LPC_exc_Q14, 1 );
+            psDD->Shape_Q14[ *smpl_buf_idx ]         = psSS->sLTP_shp_Q14;
+            psDD->Seed                               = silk_ADD32_ovflw( psDD->Seed, silk_RSHIFT_ROUND( psSS->Q_Q10, 10 ) );
+            psDD->RandState[ *smpl_buf_idx ]         = psDD->Seed;
+            psDD->RD_Q10                             = psSS->RD_Q10;
+        }
+        delayedGain_Q10[     *smpl_buf_idx ]         = Gain_Q10;
+    }
+    /* Update LPC states */
+    for( k = 0; k < nStatesDelayedDecision; k++ ) {
+        psDD = &psDelDec[ k ];
+        silk_memcpy( psDD->sLPC_Q14, &psDD->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+    }
+    RESTORE_STACK;
+}
+#endif /* OVERRIDE_silk_noise_shape_quantizer_del_dec */
+
+static OPUS_INLINE void silk_nsq_del_dec_scale_states(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int16    x16[],                      /* I    Input                               */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    opus_int            nStatesDelayedDecision,     /* I    Number of del dec states            */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+)
+{
+    opus_int            i, k, lag;
+    opus_int32          gain_adj_Q16, inv_gain_Q31, inv_gain_Q26;
+    NSQ_del_dec_struct  *psDD;
+
+    lag          = pitchL[ subfr ];
+    inv_gain_Q31 = silk_INVERSE32_varQ( silk_max( Gains_Q16[ subfr ], 1 ), 47 );
+    silk_assert( inv_gain_Q31 != 0 );
+
+    /* Scale input */
+    inv_gain_Q26 = silk_RSHIFT_ROUND( inv_gain_Q31, 5 );
+    for( i = 0; i < psEncC->subfr_length; i++ ) {
+        x_sc_Q10[ i ] = silk_SMULWW( x16[ i ], inv_gain_Q26 );
+    }
+
+    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */
+    if( NSQ->rewhite_flag ) {
+        if( subfr == 0 ) {
+            /* Do LTP downscaling */
+            inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, LTP_scale_Q14 ), 2 );
+        }
+        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+            silk_assert( i < MAX_FRAME_LENGTH );
+            sLTP_Q15[ i ] = silk_SMULWB( inv_gain_Q31, sLTP[ i ] );
+        }
+    }
+
+    /* Adjust for changing gain */
+    if( Gains_Q16[ subfr ] != NSQ->prev_gain_Q16 ) {
+        gain_adj_Q16 =  silk_DIV32_varQ( NSQ->prev_gain_Q16, Gains_Q16[ subfr ], 16 );
+
+        /* Scale long-term shaping state */
+        for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+            NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+        }
+
+        /* Scale long-term prediction state */
+        if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+            for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx - decisionDelay; i++ ) {
+                sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+            }
+        }
+
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            psDD = &psDelDec[ k ];
+
+            /* Scale scalar states */
+            psDD->LF_AR_Q14 = silk_SMULWW( gain_adj_Q16, psDD->LF_AR_Q14 );
+            psDD->Diff_Q14 = silk_SMULWW( gain_adj_Q16, psDD->Diff_Q14 );
+
+            /* Scale short-term prediction and shaping states */
+            for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+                psDD->sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->sLPC_Q14[ i ] );
+            }
+            for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+                psDD->sAR2_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->sAR2_Q14[ i ] );
+            }
+            for( i = 0; i < DECISION_DELAY; i++ ) {
+                psDD->Pred_Q15[  i ] = silk_SMULWW( gain_adj_Q16, psDD->Pred_Q15[  i ] );
+                psDD->Shape_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->Shape_Q14[ i ] );
+            }
+        }
+
+        /* Save inverse gain */
+        NSQ->prev_gain_Q16 = Gains_Q16[ subfr ];
+    }
+}
diff --git a/opus/silk/PLC.c b/opus/silk/PLC.c
new file mode 100644 (file)
index 0000000..a3e55ea
--- /dev/null
@@ -0,0 +1,448 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+#include "PLC.h"
+
+#define NB_ATT 2
+static const opus_int16 HARM_ATT_Q15[NB_ATT]              = { 32440, 31130 }; /* 0.99, 0.95 */
+static const opus_int16 PLC_RAND_ATTENUATE_V_Q15[NB_ATT]  = { 31130, 26214 }; /* 0.95, 0.8 */
+static const opus_int16 PLC_RAND_ATTENUATE_UV_Q15[NB_ATT] = { 32440, 29491 }; /* 0.99, 0.9 */
+
+static OPUS_INLINE void silk_PLC_update(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl          /* I/O Decoder control      */
+);
+
+static OPUS_INLINE void silk_PLC_conceal(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl,         /* I/O Decoder control      */
+    opus_int16                          frame[],            /* O LPC residual signal    */
+    int                                 arch                /* I  Run-time architecture */
+);
+
+
+void silk_PLC_Reset(
+    silk_decoder_state                  *psDec              /* I/O Decoder state        */
+)
+{
+    psDec->sPLC.pitchL_Q8 = silk_LSHIFT( psDec->frame_length, 8 - 1 );
+    psDec->sPLC.prevGain_Q16[ 0 ] = SILK_FIX_CONST( 1, 16 );
+    psDec->sPLC.prevGain_Q16[ 1 ] = SILK_FIX_CONST( 1, 16 );
+    psDec->sPLC.subfr_length = 20;
+    psDec->sPLC.nb_subfr = 2;
+}
+
+void silk_PLC(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl,         /* I/O Decoder control      */
+    opus_int16                          frame[],            /* I/O  signal              */
+    opus_int                            lost,               /* I Loss flag              */
+    int                                 arch                /* I Run-time architecture  */
+)
+{
+    /* PLC control function */
+    if( psDec->fs_kHz != psDec->sPLC.fs_kHz ) {
+        silk_PLC_Reset( psDec );
+        psDec->sPLC.fs_kHz = psDec->fs_kHz;
+    }
+
+    if( lost ) {
+        /****************************/
+        /* Generate Signal          */
+        /****************************/
+        silk_PLC_conceal( psDec, psDecCtrl, frame, arch );
+
+        psDec->lossCnt++;
+    } else {
+        /****************************/
+        /* Update state             */
+        /****************************/
+        silk_PLC_update( psDec, psDecCtrl );
+    }
+}
+
+/**************************************************/
+/* Update state of PLC                            */
+/**************************************************/
+static OPUS_INLINE void silk_PLC_update(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl          /* I/O Decoder control      */
+)
+{
+    opus_int32 LTP_Gain_Q14, temp_LTP_Gain_Q14;
+    opus_int   i, j;
+    silk_PLC_struct *psPLC;
+
+    psPLC = &psDec->sPLC;
+
+    /* Update parameters used in case of packet loss */
+    psDec->prevSignalType = psDec->indices.signalType;
+    LTP_Gain_Q14 = 0;
+    if( psDec->indices.signalType == TYPE_VOICED ) {
+        /* Find the parameters for the last subframe which contains a pitch pulse */
+        for( j = 0; j * psDec->subfr_length < psDecCtrl->pitchL[ psDec->nb_subfr - 1 ]; j++ ) {
+            if( j == psDec->nb_subfr ) {
+                break;
+            }
+            temp_LTP_Gain_Q14 = 0;
+            for( i = 0; i < LTP_ORDER; i++ ) {
+                temp_LTP_Gain_Q14 += psDecCtrl->LTPCoef_Q14[ ( psDec->nb_subfr - 1 - j ) * LTP_ORDER  + i ];
+            }
+            if( temp_LTP_Gain_Q14 > LTP_Gain_Q14 ) {
+                LTP_Gain_Q14 = temp_LTP_Gain_Q14;
+                silk_memcpy( psPLC->LTPCoef_Q14,
+                    &psDecCtrl->LTPCoef_Q14[ silk_SMULBB( psDec->nb_subfr - 1 - j, LTP_ORDER ) ],
+                    LTP_ORDER * sizeof( opus_int16 ) );
+
+                psPLC->pitchL_Q8 = silk_LSHIFT( psDecCtrl->pitchL[ psDec->nb_subfr - 1 - j ], 8 );
+            }
+        }
+
+        silk_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( opus_int16 ) );
+        psPLC->LTPCoef_Q14[ LTP_ORDER / 2 ] = LTP_Gain_Q14;
+
+        /* Limit LT coefs */
+        if( LTP_Gain_Q14 < V_PITCH_GAIN_START_MIN_Q14 ) {
+            opus_int   scale_Q10;
+            opus_int32 tmp;
+
+            tmp = silk_LSHIFT( V_PITCH_GAIN_START_MIN_Q14, 10 );
+            scale_Q10 = silk_DIV32( tmp, silk_max( LTP_Gain_Q14, 1 ) );
+            for( i = 0; i < LTP_ORDER; i++ ) {
+                psPLC->LTPCoef_Q14[ i ] = silk_RSHIFT( silk_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q10 ), 10 );
+            }
+        } else if( LTP_Gain_Q14 > V_PITCH_GAIN_START_MAX_Q14 ) {
+            opus_int   scale_Q14;
+            opus_int32 tmp;
+
+            tmp = silk_LSHIFT( V_PITCH_GAIN_START_MAX_Q14, 14 );
+            scale_Q14 = silk_DIV32( tmp, silk_max( LTP_Gain_Q14, 1 ) );
+            for( i = 0; i < LTP_ORDER; i++ ) {
+                psPLC->LTPCoef_Q14[ i ] = silk_RSHIFT( silk_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q14 ), 14 );
+            }
+        }
+    } else {
+        psPLC->pitchL_Q8 = silk_LSHIFT( silk_SMULBB( psDec->fs_kHz, 18 ), 8 );
+        silk_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( opus_int16 ));
+    }
+
+    /* Save LPC coeficients */
+    silk_memcpy( psPLC->prevLPC_Q12, psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( opus_int16 ) );
+    psPLC->prevLTP_scale_Q14 = psDecCtrl->LTP_scale_Q14;
+
+    /* Save last two gains */
+    silk_memcpy( psPLC->prevGain_Q16, &psDecCtrl->Gains_Q16[ psDec->nb_subfr - 2 ], 2 * sizeof( opus_int32 ) );
+
+    psPLC->subfr_length = psDec->subfr_length;
+    psPLC->nb_subfr = psDec->nb_subfr;
+}
+
+static OPUS_INLINE void silk_PLC_energy(opus_int32 *energy1, opus_int *shift1, opus_int32 *energy2, opus_int *shift2,
+      const opus_int32 *exc_Q14, const opus_int32 *prevGain_Q10, int subfr_length, int nb_subfr)
+{
+    int i, k;
+    VARDECL( opus_int16, exc_buf );
+    opus_int16 *exc_buf_ptr;
+    SAVE_STACK;
+    ALLOC( exc_buf, 2*subfr_length, opus_int16 );
+    /* Find random noise component */
+    /* Scale previous excitation signal */
+    exc_buf_ptr = exc_buf;
+    for( k = 0; k < 2; k++ ) {
+        for( i = 0; i < subfr_length; i++ ) {
+            exc_buf_ptr[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT(
+                silk_SMULWW( exc_Q14[ i + ( k + nb_subfr - 2 ) * subfr_length ], prevGain_Q10[ k ] ), 8 ) );
+        }
+        exc_buf_ptr += subfr_length;
+    }
+    /* Find the subframe with lowest energy of the last two and use that as random noise generator */
+    silk_sum_sqr_shift( energy1, shift1, exc_buf,                  subfr_length );
+    silk_sum_sqr_shift( energy2, shift2, &exc_buf[ subfr_length ], subfr_length );
+    RESTORE_STACK;
+}
+
+static OPUS_INLINE void silk_PLC_conceal(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl,         /* I/O Decoder control      */
+    opus_int16                          frame[],            /* O LPC residual signal    */
+    int                                 arch                /* I Run-time architecture  */
+)
+{
+    opus_int   i, j, k;
+    opus_int   lag, idx, sLTP_buf_idx, shift1, shift2;
+    opus_int32 rand_seed, harm_Gain_Q15, rand_Gain_Q15, inv_gain_Q30;
+    opus_int32 energy1, energy2, *rand_ptr, *pred_lag_ptr;
+    opus_int32 LPC_pred_Q10, LTP_pred_Q12;
+    opus_int16 rand_scale_Q14;
+    opus_int16 *B_Q14;
+    opus_int32 *sLPC_Q14_ptr;
+    opus_int16 A_Q12[ MAX_LPC_ORDER ];
+#ifdef SMALL_FOOTPRINT
+    opus_int16 *sLTP;
+#else
+    VARDECL( opus_int16, sLTP );
+#endif
+    VARDECL( opus_int32, sLTP_Q14 );
+    silk_PLC_struct *psPLC = &psDec->sPLC;
+    opus_int32 prevGain_Q10[2];
+    SAVE_STACK;
+
+    ALLOC( sLTP_Q14, psDec->ltp_mem_length + psDec->frame_length, opus_int32 );
+#ifdef SMALL_FOOTPRINT
+    /* Ugly hack that breaks aliasing rules to save stack: put sLTP at the very end of sLTP_Q14. */
+    sLTP = ((opus_int16*)&sLTP_Q14[psDec->ltp_mem_length + psDec->frame_length])-psDec->ltp_mem_length;
+#else
+    ALLOC( sLTP, psDec->ltp_mem_length, opus_int16 );
+#endif
+
+    prevGain_Q10[0] = silk_RSHIFT( psPLC->prevGain_Q16[ 0 ], 6);
+    prevGain_Q10[1] = silk_RSHIFT( psPLC->prevGain_Q16[ 1 ], 6);
+
+    if( psDec->first_frame_after_reset ) {
+       silk_memset( psPLC->prevLPC_Q12, 0, sizeof( psPLC->prevLPC_Q12 ) );
+    }
+
+    silk_PLC_energy(&energy1, &shift1, &energy2, &shift2, psDec->exc_Q14, prevGain_Q10, psDec->subfr_length, psDec->nb_subfr);
+
+    if( silk_RSHIFT( energy1, shift2 ) < silk_RSHIFT( energy2, shift1 ) ) {
+        /* First sub-frame has lowest energy */
+        rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, ( psPLC->nb_subfr - 1 ) * psPLC->subfr_length - RAND_BUF_SIZE ) ];
+    } else {
+        /* Second sub-frame has lowest energy */
+        rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, psPLC->nb_subfr * psPLC->subfr_length - RAND_BUF_SIZE ) ];
+    }
+
+    /* Set up Gain to random noise component */
+    B_Q14          = psPLC->LTPCoef_Q14;
+    rand_scale_Q14 = psPLC->randScale_Q14;
+
+    /* Set up attenuation gains */
+    harm_Gain_Q15 = HARM_ATT_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
+    if( psDec->prevSignalType == TYPE_VOICED ) {
+        rand_Gain_Q15 = PLC_RAND_ATTENUATE_V_Q15[  silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
+    } else {
+        rand_Gain_Q15 = PLC_RAND_ATTENUATE_UV_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
+    }
+
+    /* LPC concealment. Apply BWE to previous LPC */
+    silk_bwexpander( psPLC->prevLPC_Q12, psDec->LPC_order, SILK_FIX_CONST( BWE_COEF, 16 ) );
+
+    /* Preload LPC coeficients to array on stack. Gives small performance gain */
+    silk_memcpy( A_Q12, psPLC->prevLPC_Q12, psDec->LPC_order * sizeof( opus_int16 ) );
+
+    /* First Lost frame */
+    if( psDec->lossCnt == 0 ) {
+        rand_scale_Q14 = 1 << 14;
+
+        /* Reduce random noise Gain for voiced frames */
+        if( psDec->prevSignalType == TYPE_VOICED ) {
+            for( i = 0; i < LTP_ORDER; i++ ) {
+                rand_scale_Q14 -= B_Q14[ i ];
+            }
+            rand_scale_Q14 = silk_max_16( 3277, rand_scale_Q14 ); /* 0.2 */
+            rand_scale_Q14 = (opus_int16)silk_RSHIFT( silk_SMULBB( rand_scale_Q14, psPLC->prevLTP_scale_Q14 ), 14 );
+        } else {
+            /* Reduce random noise for unvoiced frames with high LPC gain */
+            opus_int32 invGain_Q30, down_scale_Q30;
+
+            invGain_Q30 = silk_LPC_inverse_pred_gain( psPLC->prevLPC_Q12, psDec->LPC_order, arch );
+
+            down_scale_Q30 = silk_min_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_HIGH_THRES ), invGain_Q30 );
+            down_scale_Q30 = silk_max_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_LOW_THRES ), down_scale_Q30 );
+            down_scale_Q30 = silk_LSHIFT( down_scale_Q30, LOG2_INV_LPC_GAIN_HIGH_THRES );
+
+            rand_Gain_Q15 = silk_RSHIFT( silk_SMULWB( down_scale_Q30, rand_Gain_Q15 ), 14 );
+        }
+    }
+
+    rand_seed    = psPLC->rand_seed;
+    lag          = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
+    sLTP_buf_idx = psDec->ltp_mem_length;
+
+    /* Rewhiten LTP state */
+    idx = psDec->ltp_mem_length - lag - psDec->LPC_order - LTP_ORDER / 2;
+    silk_assert( idx > 0 );
+    silk_LPC_analysis_filter( &sLTP[ idx ], &psDec->outBuf[ idx ], A_Q12, psDec->ltp_mem_length - idx, psDec->LPC_order, arch );
+    /* Scale LTP state */
+    inv_gain_Q30 = silk_INVERSE32_varQ( psPLC->prevGain_Q16[ 1 ], 46 );
+    inv_gain_Q30 = silk_min( inv_gain_Q30, silk_int32_MAX >> 1 );
+    for( i = idx + psDec->LPC_order; i < psDec->ltp_mem_length; i++ ) {
+        sLTP_Q14[ i ] = silk_SMULWB( inv_gain_Q30, sLTP[ i ] );
+    }
+
+    /***************************/
+    /* LTP synthesis filtering */
+    /***************************/
+    for( k = 0; k < psDec->nb_subfr; k++ ) {
+        /* Set up pointer */
+        pred_lag_ptr = &sLTP_Q14[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+        for( i = 0; i < psDec->subfr_length; i++ ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q12 = 2;
+            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[  0 ], B_Q14[ 0 ] );
+            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );
+            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );
+            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );
+            LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );
+            pred_lag_ptr++;
+
+            /* Generate LPC excitation */
+            rand_seed = silk_RAND( rand_seed );
+            idx = silk_RSHIFT( rand_seed, 25 ) & RAND_BUF_MASK;
+            sLTP_Q14[ sLTP_buf_idx ] = silk_LSHIFT32( silk_SMLAWB( LTP_pred_Q12, rand_ptr[ idx ], rand_scale_Q14 ), 2 );
+            sLTP_buf_idx++;
+        }
+
+        /* Gradually reduce LTP gain */
+        for( j = 0; j < LTP_ORDER; j++ ) {
+            B_Q14[ j ] = silk_RSHIFT( silk_SMULBB( harm_Gain_Q15, B_Q14[ j ] ), 15 );
+        }
+        if ( psDec->indices.signalType != TYPE_NO_VOICE_ACTIVITY ) {
+            /* Gradually reduce excitation gain */
+            rand_scale_Q14 = silk_RSHIFT( silk_SMULBB( rand_scale_Q14, rand_Gain_Q15 ), 15 );
+        }
+
+        /* Slowly increase pitch lag */
+        psPLC->pitchL_Q8 = silk_SMLAWB( psPLC->pitchL_Q8, psPLC->pitchL_Q8, PITCH_DRIFT_FAC_Q16 );
+        psPLC->pitchL_Q8 = silk_min_32( psPLC->pitchL_Q8, silk_LSHIFT( silk_SMULBB( MAX_PITCH_LAG_MS, psDec->fs_kHz ), 8 ) );
+        lag = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
+    }
+
+    /***************************/
+    /* LPC synthesis filtering */
+    /***************************/
+    sLPC_Q14_ptr = &sLTP_Q14[ psDec->ltp_mem_length - MAX_LPC_ORDER ];
+
+    /* Copy LPC state */
+    silk_memcpy( sLPC_Q14_ptr, psDec->sLPC_Q14_buf, MAX_LPC_ORDER * sizeof( opus_int32 ) );
+
+    silk_assert( psDec->LPC_order >= 10 ); /* check that unrolling works */
+    for( i = 0; i < psDec->frame_length; i++ ) {
+        /* partly unrolled */
+        /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+        LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  1 ], A_Q12[ 0 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  2 ], A_Q12[ 1 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  3 ], A_Q12[ 2 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  4 ], A_Q12[ 3 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  5 ], A_Q12[ 4 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  6 ], A_Q12[ 5 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  7 ], A_Q12[ 6 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  8 ], A_Q12[ 7 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i -  9 ], A_Q12[ 8 ] );
+        LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 10 ], A_Q12[ 9 ] );
+        for( j = 10; j < psDec->LPC_order; j++ ) {
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - j - 1 ], A_Q12[ j ] );
+        }
+
+        /* Add prediction to LPC excitation */
+        sLPC_Q14_ptr[ MAX_LPC_ORDER + i ] = silk_ADD_SAT32( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ],
+                                            silk_LSHIFT_SAT32( LPC_pred_Q10, 4 ));
+
+        /* Scale with Gain */
+        frame[ i ] = (opus_int16)silk_SAT16( silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ], prevGain_Q10[ 1 ] ), 8 ) ) );
+    }
+
+    /* Save LPC state */
+    silk_memcpy( psDec->sLPC_Q14_buf, &sLPC_Q14_ptr[ psDec->frame_length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
+
+    /**************************************/
+    /* Update states                      */
+    /**************************************/
+    psPLC->rand_seed     = rand_seed;
+    psPLC->randScale_Q14 = rand_scale_Q14;
+    for( i = 0; i < MAX_NB_SUBFR; i++ ) {
+        psDecCtrl->pitchL[ i ] = lag;
+    }
+    RESTORE_STACK;
+}
+
+/* Glues concealed frames with new good received frames */
+void silk_PLC_glue_frames(
+    silk_decoder_state                  *psDec,             /* I/O decoder state        */
+    opus_int16                          frame[],            /* I/O signal               */
+    opus_int                            length              /* I length of signal       */
+)
+{
+    opus_int   i, energy_shift;
+    opus_int32 energy;
+    silk_PLC_struct *psPLC;
+    psPLC = &psDec->sPLC;
+
+    if( psDec->lossCnt ) {
+        /* Calculate energy in concealed residual */
+        silk_sum_sqr_shift( &psPLC->conc_energy, &psPLC->conc_energy_shift, frame, length );
+
+        psPLC->last_frame_lost = 1;
+    } else {
+        if( psDec->sPLC.last_frame_lost ) {
+            /* Calculate residual in decoded signal if last frame was lost */
+            silk_sum_sqr_shift( &energy, &energy_shift, frame, length );
+
+            /* Normalize energies */
+            if( energy_shift > psPLC->conc_energy_shift ) {
+                psPLC->conc_energy = silk_RSHIFT( psPLC->conc_energy, energy_shift - psPLC->conc_energy_shift );
+            } else if( energy_shift < psPLC->conc_energy_shift ) {
+                energy = silk_RSHIFT( energy, psPLC->conc_energy_shift - energy_shift );
+            }
+
+            /* Fade in the energy difference */
+            if( energy > psPLC->conc_energy ) {
+                opus_int32 frac_Q24, LZ;
+                opus_int32 gain_Q16, slope_Q16;
+
+                LZ = silk_CLZ32( psPLC->conc_energy );
+                LZ = LZ - 1;
+                psPLC->conc_energy = silk_LSHIFT( psPLC->conc_energy, LZ );
+                energy = silk_RSHIFT( energy, silk_max_32( 24 - LZ, 0 ) );
+
+                frac_Q24 = silk_DIV32( psPLC->conc_energy, silk_max( energy, 1 ) );
+
+                gain_Q16 = silk_LSHIFT( silk_SQRT_APPROX( frac_Q24 ), 4 );
+                slope_Q16 = silk_DIV32_16( ( (opus_int32)1 << 16 ) - gain_Q16, length );
+                /* Make slope 4x steeper to avoid missing onsets after DTX */
+                slope_Q16 = silk_LSHIFT( slope_Q16, 2 );
+
+                for( i = 0; i < length; i++ ) {
+                    frame[ i ] = silk_SMULWB( gain_Q16, frame[ i ] );
+                    gain_Q16 += slope_Q16;
+                    if( gain_Q16 > (opus_int32)1 << 16 ) {
+                        break;
+                    }
+                }
+            }
+        }
+        psPLC->last_frame_lost = 0;
+    }
+}
diff --git a/opus/silk/PLC.h b/opus/silk/PLC.h
new file mode 100644 (file)
index 0000000..6438f51
--- /dev/null
@@ -0,0 +1,62 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_PLC_H
+#define SILK_PLC_H
+
+#include "main.h"
+
+#define BWE_COEF                        0.99
+#define V_PITCH_GAIN_START_MIN_Q14      11469               /* 0.7 in Q14               */
+#define V_PITCH_GAIN_START_MAX_Q14      15565               /* 0.95 in Q14              */
+#define MAX_PITCH_LAG_MS                18
+#define RAND_BUF_SIZE                   128
+#define RAND_BUF_MASK                   ( RAND_BUF_SIZE - 1 )
+#define LOG2_INV_LPC_GAIN_HIGH_THRES    3                   /* 2^3 = 8 dB LPC gain      */
+#define LOG2_INV_LPC_GAIN_LOW_THRES     8                   /* 2^8 = 24 dB LPC gain     */
+#define PITCH_DRIFT_FAC_Q16             655                 /* 0.01 in Q16              */
+
+void silk_PLC_Reset(
+    silk_decoder_state                  *psDec              /* I/O Decoder state        */
+);
+
+void silk_PLC(
+    silk_decoder_state                  *psDec,             /* I/O Decoder state        */
+    silk_decoder_control                *psDecCtrl,         /* I/O Decoder control      */
+    opus_int16                          frame[],            /* I/O  signal              */
+    opus_int                            lost,               /* I Loss flag              */
+    int                                 arch                /* I Run-time architecture  */
+);
+
+void silk_PLC_glue_frames(
+    silk_decoder_state                  *psDec,             /* I/O decoder state        */
+    opus_int16                          frame[],            /* I/O signal               */
+    opus_int                            length              /* I length of signal       */
+);
+
+#endif
+
diff --git a/opus/silk/SigProc_FIX.h b/opus/silk/SigProc_FIX.h
new file mode 100644 (file)
index 0000000..f9ae326
--- /dev/null
@@ -0,0 +1,641 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_SIGPROC_FIX_H
+#define SILK_SIGPROC_FIX_H
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+/*#define silk_MACRO_COUNT */          /* Used to enable WMOPS counting */
+
+#define SILK_MAX_ORDER_LPC            24            /* max order of the LPC analysis in schur() and k2a() */
+
+#include <string.h>                                 /* for memset(), memcpy(), memmove() */
+#include "typedef.h"
+#include "resampler_structs.h"
+#include "macros.h"
+#include "cpu_support.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#include "x86/SigProc_FIX_sse.h"
+#endif
+
+#if (defined(OPUS_ARM_ASM) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR))
+#include "arm/biquad_alt_arm.h"
+#include "arm/LPC_inv_pred_gain_arm.h"
+#endif
+
+/********************************************************************/
+/*                    SIGNAL PROCESSING FUNCTIONS                   */
+/********************************************************************/
+
+/*!
+ * Initialize/reset the resampler state for a given pair of input/output sampling rates
+*/
+opus_int silk_resampler_init(
+    silk_resampler_state_struct *S,                 /* I/O  Resampler state                                             */
+    opus_int32                  Fs_Hz_in,           /* I    Input sampling rate (Hz)                                    */
+    opus_int32                  Fs_Hz_out,          /* I    Output sampling rate (Hz)                                   */
+    opus_int                    forEnc              /* I    If 1: encoder; if 0: decoder                                */
+);
+
+/*!
+ * Resampler: convert from one sampling rate to another
+ */
+opus_int silk_resampler(
+    silk_resampler_state_struct *S,                 /* I/O  Resampler state                                             */
+    opus_int16                  out[],              /* O    Output signal                                               */
+    const opus_int16            in[],               /* I    Input signal                                                */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+);
+
+/*!
+* Downsample 2x, mediocre quality
+*/
+void silk_resampler_down2(
+    opus_int32                  *S,                 /* I/O  State vector [ 2 ]                                          */
+    opus_int16                  *out,               /* O    Output signal [ len ]                                       */
+    const opus_int16            *in,                /* I    Input signal [ floor(len/2) ]                               */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+);
+
+/*!
+ * Downsample by a factor 2/3, low quality
+*/
+void silk_resampler_down2_3(
+    opus_int32                  *S,                 /* I/O  State vector [ 6 ]                                          */
+    opus_int16                  *out,               /* O    Output signal [ floor(2*inLen/3) ]                          */
+    const opus_int16            *in,                /* I    Input signal [ inLen ]                                      */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+);
+
+/*!
+ * second order ARMA filter;
+ * slower than biquad() but uses more precise coefficients
+ * can handle (slowly) varying coefficients
+ */
+void silk_biquad_alt_stride1(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [2]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+);
+
+void silk_biquad_alt_stride2_c(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+);
+
+/* Variable order MA prediction error filter. */
+void silk_LPC_analysis_filter(
+    opus_int16                  *out,               /* O    Output signal                                               */
+    const opus_int16            *in,                /* I    Input signal                                                */
+    const opus_int16            *B,                 /* I    MA prediction coefficients, Q12 [order]                     */
+    const opus_int32            len,                /* I    Signal length                                               */
+    const opus_int32            d,                  /* I    Filter order                                                */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+/* Chirp (bandwidth expand) LP AR filter */
+void silk_bwexpander(
+    opus_int16                  *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int              d,                  /* I    Length of ar                                                */
+    opus_int32                  chirp_Q16           /* I    Chirp factor (typically in the range 0 to 1)                */
+);
+
+/* Chirp (bandwidth expand) LP AR filter */
+void silk_bwexpander_32(
+    opus_int32                  *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int              d,                  /* I    Length of ar                                                */
+    opus_int32                  chirp_Q16           /* I    Chirp factor in Q16                                         */
+);
+
+/* Compute inverse of LPC prediction gain, and                           */
+/* test if LPC coefficients are stable (all poles within unit circle)    */
+opus_int32 silk_LPC_inverse_pred_gain_c(            /* O   Returns inverse prediction gain in energy domain, Q30        */
+    const opus_int16            *A_Q12,             /* I   Prediction coefficients, Q12 [order]                         */
+    const opus_int              order               /* I   Prediction order                                             */
+);
+
+/* Split signal in two decimated bands using first-order allpass filters */
+void silk_ana_filt_bank_1(
+    const opus_int16            *in,                /* I    Input signal [N]                                            */
+    opus_int32                  *S,                 /* I/O  State vector [2]                                            */
+    opus_int16                  *outL,              /* O    Low band [N/2]                                              */
+    opus_int16                  *outH,              /* O    High band [N/2]                                             */
+    const opus_int32            N                   /* I    Number of input samples                                     */
+);
+
+#if !defined(OVERRIDE_silk_biquad_alt_stride2)
+#define silk_biquad_alt_stride2(in, B_Q28, A_Q28, S, out, len, arch) ((void)(arch), silk_biquad_alt_stride2_c(in, B_Q28, A_Q28, S, out, len))
+#endif
+
+#if !defined(OVERRIDE_silk_LPC_inverse_pred_gain)
+#define silk_LPC_inverse_pred_gain(A_Q12, order, arch)     ((void)(arch), silk_LPC_inverse_pred_gain_c(A_Q12, order))
+#endif
+
+/********************************************************************/
+/*                        SCALAR FUNCTIONS                          */
+/********************************************************************/
+
+/* Approximation of 128 * log2() (exact inverse of approx 2^() below) */
+/* Convert input to a log scale    */
+opus_int32 silk_lin2log(
+    const opus_int32            inLin               /* I  input in linear scale                                         */
+);
+
+/* Approximation of a sigmoid function */
+opus_int silk_sigm_Q15(
+    opus_int                    in_Q5               /* I                                                                */
+);
+
+/* Approximation of 2^() (exact inverse of approx log2() above) */
+/* Convert input to a linear scale */
+opus_int32 silk_log2lin(
+    const opus_int32            inLog_Q7            /* I  input on log scale                                            */
+);
+
+/* Compute number of bits to right shift the sum of squares of a vector    */
+/* of int16s to make it fit in an int32                                    */
+void silk_sum_sqr_shift(
+    opus_int32                  *energy,            /* O   Energy of x, after shifting to the right                     */
+    opus_int                    *shift,             /* O   Number of bits right shift applied to energy                 */
+    const opus_int16            *x,                 /* I   Input vector                                                 */
+    opus_int                    len                 /* I   Length of input vector                                       */
+);
+
+/* Calculates the reflection coefficients from the correlation sequence    */
+/* Faster than schur64(), but much less accurate.                          */
+/* uses SMLAWB(), requiring armv5E and higher.                             */
+opus_int32 silk_schur(                              /* O    Returns residual energy                                     */
+    opus_int16                  *rc_Q15,            /* O    reflection coefficients [order] Q15                         */
+    const opus_int32            *c,                 /* I    correlations [order+1]                                      */
+    const opus_int32            order               /* I    prediction order                                            */
+);
+
+/* Calculates the reflection coefficients from the correlation sequence    */
+/* Slower than schur(), but more accurate.                                 */
+/* Uses SMULL(), available on armv4                                        */
+opus_int32 silk_schur64(                            /* O    returns residual energy                                     */
+    opus_int32                  rc_Q16[],           /* O    Reflection coefficients [order] Q16                         */
+    const opus_int32            c[],                /* I    Correlations [order+1]                                      */
+    opus_int32                  order               /* I    Prediction order                                            */
+);
+
+/* Step up function, converts reflection coefficients to prediction coefficients */
+void silk_k2a(
+    opus_int32                  *A_Q24,             /* O    Prediction coefficients [order] Q24                         */
+    const opus_int16            *rc_Q15,            /* I    Reflection coefficients [order] Q15                         */
+    const opus_int32            order               /* I    Prediction order                                            */
+);
+
+/* Step up function, converts reflection coefficients to prediction coefficients */
+void silk_k2a_Q16(
+    opus_int32                  *A_Q24,             /* O    Prediction coefficients [order] Q24                         */
+    const opus_int32            *rc_Q16,            /* I    Reflection coefficients [order] Q16                         */
+    const opus_int32            order               /* I    Prediction order                                            */
+);
+
+/* Apply sine window to signal vector.                              */
+/* Window types:                                                    */
+/*    1 -> sine window from 0 to pi/2                               */
+/*    2 -> sine window from pi/2 to pi                              */
+/* every other sample of window is linearly interpolated, for speed */
+void silk_apply_sine_window(
+    opus_int16                  px_win[],           /* O    Pointer to windowed signal                                  */
+    const opus_int16            px[],               /* I    Pointer to input signal                                     */
+    const opus_int              win_type,           /* I    Selects a window type                                       */
+    const opus_int              length              /* I    Window length, multiple of 4                                */
+);
+
+/* Compute autocorrelation */
+void silk_autocorr(
+    opus_int32                  *results,           /* O    Result (length correlationCount)                            */
+    opus_int                    *scale,             /* O    Scaling of the correlation vector                           */
+    const opus_int16            *inputData,         /* I    Input data to correlate                                     */
+    const opus_int              inputDataSize,      /* I    Length of input                                             */
+    const opus_int              correlationCount,   /* I    Number of correlation taps to compute                       */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+void silk_decode_pitch(
+    opus_int16                  lagIndex,           /* I                                                                */
+    opus_int8                   contourIndex,       /* O                                                                */
+    opus_int                    pitch_lags[],       /* O    4 pitch values                                              */
+    const opus_int              Fs_kHz,             /* I    sampling frequency (kHz)                                    */
+    const opus_int              nb_subfr            /* I    number of sub frames                                        */
+);
+
+opus_int silk_pitch_analysis_core(                  /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */
+    const opus_int16            *frame,             /* I    Signal of length PE_FRAME_LENGTH_MS*Fs_kHz                  */
+    opus_int                    *pitch_out,         /* O    4 pitch lag values                                          */
+    opus_int16                  *lagIndex,          /* O    Lag Index                                                   */
+    opus_int8                   *contourIndex,      /* O    Pitch contour Index                                         */
+    opus_int                    *LTPCorr_Q15,       /* I/O  Normalized correlation; input: value from previous frame    */
+    opus_int                    prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */
+    const opus_int32            search_thres1_Q16,  /* I    First stage threshold for lag candidates 0 - 1              */
+    const opus_int              search_thres2_Q13,  /* I    Final threshold for lag candidates 0 - 1                    */
+    const opus_int              Fs_kHz,             /* I    Sample frequency (kHz)                                      */
+    const opus_int              complexity,         /* I    Complexity setting, 0-2, where 2 is highest                 */
+    const opus_int              nb_subfr,           /* I    number of 5 ms subframes                                    */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+/* Compute Normalized Line Spectral Frequencies (NLSFs) from whitening filter coefficients      */
+/* If not all roots are found, the a_Q16 coefficients are bandwidth expanded until convergence. */
+void silk_A2NLSF(
+    opus_int16                  *NLSF,              /* O    Normalized Line Spectral Frequencies in Q15 (0..2^15-1) [d] */
+    opus_int32                  *a_Q16,             /* I/O  Monic whitening filter coefficients in Q16 [d]              */
+    const opus_int              d                   /* I    Filter order (must be even)                                 */
+);
+
+/* compute whitening filter coefficients from normalized line spectral frequencies */
+void silk_NLSF2A(
+    opus_int16                  *a_Q12,             /* O    monic whitening filter coefficients in Q12,  [ d ]          */
+    const opus_int16            *NLSF,              /* I    normalized line spectral frequencies in Q15, [ d ]          */
+    const opus_int              d,                  /* I    filter order (should be even)                               */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+/* Convert int32 coefficients to int16 coefs and make sure there's no wrap-around */
+void silk_LPC_fit(
+    opus_int16                  *a_QOUT,            /* O    Output signal                                               */
+    opus_int32                  *a_QIN,             /* I/O  Input signal                                                */
+    const opus_int              QOUT,               /* I    Input Q domain                                              */
+    const opus_int              QIN,                /* I    Input Q domain                                              */
+    const opus_int              d                   /* I    Filter order                                                */
+);
+
+void silk_insertion_sort_increasing(
+    opus_int32                  *a,                 /* I/O   Unsorted / Sorted vector                                   */
+    opus_int                    *idx,               /* O     Index vector for the sorted elements                       */
+    const opus_int              L,                  /* I     Vector length                                              */
+    const opus_int              K                   /* I     Number of correctly sorted positions                       */
+);
+
+void silk_insertion_sort_decreasing_int16(
+    opus_int16                  *a,                 /* I/O   Unsorted / Sorted vector                                   */
+    opus_int                    *idx,               /* O     Index vector for the sorted elements                       */
+    const opus_int              L,                  /* I     Vector length                                              */
+    const opus_int              K                   /* I     Number of correctly sorted positions                       */
+);
+
+void silk_insertion_sort_increasing_all_values_int16(
+     opus_int16                 *a,                 /* I/O   Unsorted / Sorted vector                                   */
+     const opus_int             L                   /* I     Vector length                                              */
+);
+
+/* NLSF stabilizer, for a single input data vector */
+void silk_NLSF_stabilize(
+          opus_int16            *NLSF_Q15,          /* I/O   Unstable/stabilized normalized LSF vector in Q15 [L]       */
+    const opus_int16            *NDeltaMin_Q15,     /* I     Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1]   */
+    const opus_int              L                   /* I     Number of NLSF parameters in the input vector              */
+);
+
+/* Laroia low complexity NLSF weights */
+void silk_NLSF_VQ_weights_laroia(
+    opus_int16                  *pNLSFW_Q_OUT,      /* O     Pointer to input vector weights [D]                        */
+    const opus_int16            *pNLSF_Q15,         /* I     Pointer to input vector         [D]                        */
+    const opus_int              D                   /* I     Input vector dimension (even)                              */
+);
+
+/* Compute reflection coefficients from input signal */
+void silk_burg_modified_c(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+/* Copy and multiply a vector by a constant */
+void silk_scale_copy_vector16(
+    opus_int16                  *data_out,
+    const opus_int16            *data_in,
+    opus_int32                  gain_Q16,           /* I    Gain in Q16                                                 */
+    const opus_int              dataSize            /* I    Length                                                      */
+);
+
+/* Some for the LTP related function requires Q26 to work.*/
+void silk_scale_vector32_Q26_lshift_18(
+    opus_int32                  *data1,             /* I/O  Q0/Q18                                                      */
+    opus_int32                  gain_Q26,           /* I    Q26                                                         */
+    opus_int                    dataSize            /* I    length                                                      */
+);
+
+/********************************************************************/
+/*                        INLINE ARM MATH                           */
+/********************************************************************/
+
+/*    return sum( inVec1[i] * inVec2[i] ) */
+
+opus_int32 silk_inner_prod_aligned(
+    const opus_int16 *const     inVec1,             /*    I input vector 1                                              */
+    const opus_int16 *const     inVec2,             /*    I input vector 2                                              */
+    const opus_int              len,                /*    I vector lengths                                              */
+    int                         arch                /*    I Run-time architecture                                       */
+);
+
+
+opus_int32 silk_inner_prod_aligned_scale(
+    const opus_int16 *const     inVec1,             /*    I input vector 1                                              */
+    const opus_int16 *const     inVec2,             /*    I input vector 2                                              */
+    const opus_int              scale,              /*    I number of bits to shift                                     */
+    const opus_int              len                 /*    I vector lengths                                              */
+);
+
+opus_int64 silk_inner_prod16_aligned_64_c(
+    const opus_int16            *inVec1,            /*    I input vector 1                                              */
+    const opus_int16            *inVec2,            /*    I input vector 2                                              */
+    const opus_int              len                 /*    I vector lengths                                              */
+);
+
+/********************************************************************/
+/*                                MACROS                            */
+/********************************************************************/
+
+/* Rotate a32 right by 'rot' bits. Negative rot values result in rotating
+   left. Output is 32bit int.
+   Note: contemporary compilers recognize the C expression below and
+   compile it into a 'ror' instruction if available. No need for OPUS_INLINE ASM! */
+static OPUS_INLINE opus_int32 silk_ROR32( opus_int32 a32, opus_int rot )
+{
+    opus_uint32 x = (opus_uint32) a32;
+    opus_uint32 r = (opus_uint32) rot;
+    opus_uint32 m = (opus_uint32) -rot;
+    if( rot == 0 ) {
+        return a32;
+    } else if( rot < 0 ) {
+        return (opus_int32) ((x << m) | (x >> (32 - m)));
+    } else {
+        return (opus_int32) ((x << (32 - r)) | (x >> r));
+    }
+}
+
+/* Allocate opus_int16 aligned to 4-byte memory address */
+#if EMBEDDED_ARM
+#define silk_DWORD_ALIGN __attribute__((aligned(4)))
+#else
+#define silk_DWORD_ALIGN
+#endif
+
+/* Useful Macros that can be adjusted to other platforms */
+#define silk_memcpy(dest, src, size)        memcpy((dest), (src), (size))
+#define silk_memset(dest, src, size)        memset((dest), (src), (size))
+#define silk_memmove(dest, src, size)       memmove((dest), (src), (size))
+
+/* Fixed point macros */
+
+/* (a32 * b32) output have to be 32bit int */
+#define silk_MUL(a32, b32)                  ((a32) * (b32))
+
+/* (a32 * b32) output have to be 32bit uint */
+#define silk_MUL_uint(a32, b32)             silk_MUL(a32, b32)
+
+/* a32 + (b32 * c32) output have to be 32bit int */
+#define silk_MLA(a32, b32, c32)             silk_ADD32((a32),((b32) * (c32)))
+
+/* a32 + (b32 * c32) output have to be 32bit uint */
+#define silk_MLA_uint(a32, b32, c32)        silk_MLA(a32, b32, c32)
+
+/* ((a32 >> 16)  * (b32 >> 16)) output have to be 32bit int */
+#define silk_SMULTT(a32, b32)               (((a32) >> 16) * ((b32) >> 16))
+
+/* a32 + ((a32 >> 16)  * (b32 >> 16)) output have to be 32bit int */
+#define silk_SMLATT(a32, b32, c32)          silk_ADD32((a32),((b32) >> 16) * ((c32) >> 16))
+
+#define silk_SMLALBB(a64, b16, c16)         silk_ADD64((a64),(opus_int64)((opus_int32)(b16) * (opus_int32)(c16)))
+
+/* (a32 * b32) */
+#define silk_SMULL(a32, b32)                ((opus_int64)(a32) * /*(opus_int64)*/(b32))
+
+/* Adds two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour
+   (just standard two's complement implementation-specific behaviour) */
+#define silk_ADD32_ovflw(a, b)              ((opus_int32)((opus_uint32)(a) + (opus_uint32)(b)))
+/* Subtractss two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour
+   (just standard two's complement implementation-specific behaviour) */
+#define silk_SUB32_ovflw(a, b)              ((opus_int32)((opus_uint32)(a) - (opus_uint32)(b)))
+
+/* Multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode) */
+#define silk_MLA_ovflw(a32, b32, c32)       silk_ADD32_ovflw((a32), (opus_uint32)(b32) * (opus_uint32)(c32))
+#define silk_SMLABB_ovflw(a32, b32, c32)    (silk_ADD32_ovflw((a32) , ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32))))
+
+#define silk_DIV32_16(a32, b16)             ((opus_int32)((a32) / (b16)))
+#define silk_DIV32(a32, b32)                ((opus_int32)((a32) / (b32)))
+
+/* These macros enables checking for overflow in silk_API_Debug.h*/
+#define silk_ADD16(a, b)                    ((a) + (b))
+#define silk_ADD32(a, b)                    ((a) + (b))
+#define silk_ADD64(a, b)                    ((a) + (b))
+
+#define silk_SUB16(a, b)                    ((a) - (b))
+#define silk_SUB32(a, b)                    ((a) - (b))
+#define silk_SUB64(a, b)                    ((a) - (b))
+
+#define silk_SAT8(a)                        ((a) > silk_int8_MAX ? silk_int8_MAX  :       \
+                                            ((a) < silk_int8_MIN ? silk_int8_MIN  : (a)))
+#define silk_SAT16(a)                       ((a) > silk_int16_MAX ? silk_int16_MAX :      \
+                                            ((a) < silk_int16_MIN ? silk_int16_MIN : (a)))
+#define silk_SAT32(a)                       ((a) > silk_int32_MAX ? silk_int32_MAX :      \
+                                            ((a) < silk_int32_MIN ? silk_int32_MIN : (a)))
+
+#define silk_CHECK_FIT8(a)                  (a)
+#define silk_CHECK_FIT16(a)                 (a)
+#define silk_CHECK_FIT32(a)                 (a)
+
+#define silk_ADD_SAT16(a, b)                (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a), (b) ) )
+#define silk_ADD_SAT64(a, b)                ((((a) + (b)) & 0x8000000000000000LL) == 0 ?                            \
+                                            ((((a) & (b)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a)+(b)) : \
+                                            ((((a) | (b)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a)+(b)) )
+
+#define silk_SUB_SAT16(a, b)                (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a), (b) ) )
+#define silk_SUB_SAT64(a, b)                ((((a)-(b)) & 0x8000000000000000LL) == 0 ?                                               \
+                                            (( (a) & ((b)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a)-(b)) : \
+                                            ((((a)^0x8000000000000000LL) & (b)  & 0x8000000000000000LL) ? silk_int64_MAX : (a)-(b)) )
+
+/* Saturation for positive input values */
+#define silk_POS_SAT32(a)                   ((a) > silk_int32_MAX ? silk_int32_MAX : (a))
+
+/* Add with saturation for positive input values */
+#define silk_ADD_POS_SAT8(a, b)             ((((a)+(b)) & 0x80)                 ? silk_int8_MAX  : ((a)+(b)))
+#define silk_ADD_POS_SAT16(a, b)            ((((a)+(b)) & 0x8000)               ? silk_int16_MAX : ((a)+(b)))
+#define silk_ADD_POS_SAT32(a, b)            ((((opus_uint32)(a)+(opus_uint32)(b)) & 0x80000000) ? silk_int32_MAX : ((a)+(b)))
+
+#define silk_LSHIFT8(a, shift)              ((opus_int8)((opus_uint8)(a)<<(shift)))         /* shift >= 0, shift < 8  */
+#define silk_LSHIFT16(a, shift)             ((opus_int16)((opus_uint16)(a)<<(shift)))       /* shift >= 0, shift < 16 */
+#define silk_LSHIFT32(a, shift)             ((opus_int32)((opus_uint32)(a)<<(shift)))       /* shift >= 0, shift < 32 */
+#define silk_LSHIFT64(a, shift)             ((opus_int64)((opus_uint64)(a)<<(shift)))       /* shift >= 0, shift < 64 */
+#define silk_LSHIFT(a, shift)               silk_LSHIFT32(a, shift)                         /* shift >= 0, shift < 32 */
+
+#define silk_RSHIFT8(a, shift)              ((a)>>(shift))                                  /* shift >= 0, shift < 8  */
+#define silk_RSHIFT16(a, shift)             ((a)>>(shift))                                  /* shift >= 0, shift < 16 */
+#define silk_RSHIFT32(a, shift)             ((a)>>(shift))                                  /* shift >= 0, shift < 32 */
+#define silk_RSHIFT64(a, shift)             ((a)>>(shift))                                  /* shift >= 0, shift < 64 */
+#define silk_RSHIFT(a, shift)               silk_RSHIFT32(a, shift)                         /* shift >= 0, shift < 32 */
+
+/* saturates before shifting */
+#define silk_LSHIFT_SAT32(a, shift)         (silk_LSHIFT32( silk_LIMIT( (a), silk_RSHIFT32( silk_int32_MIN, (shift) ), \
+                                                    silk_RSHIFT32( silk_int32_MAX, (shift) ) ), (shift) ))
+
+#define silk_LSHIFT_ovflw(a, shift)         ((opus_int32)((opus_uint32)(a) << (shift)))     /* shift >= 0, allowed to overflow */
+#define silk_LSHIFT_uint(a, shift)          ((a) << (shift))                                /* shift >= 0 */
+#define silk_RSHIFT_uint(a, shift)          ((a) >> (shift))                                /* shift >= 0 */
+
+#define silk_ADD_LSHIFT(a, b, shift)        ((a) + silk_LSHIFT((b), (shift)))               /* shift >= 0 */
+#define silk_ADD_LSHIFT32(a, b, shift)      silk_ADD32((a), silk_LSHIFT32((b), (shift)))    /* shift >= 0 */
+#define silk_ADD_LSHIFT_uint(a, b, shift)   ((a) + silk_LSHIFT_uint((b), (shift)))          /* shift >= 0 */
+#define silk_ADD_RSHIFT(a, b, shift)        ((a) + silk_RSHIFT((b), (shift)))               /* shift >= 0 */
+#define silk_ADD_RSHIFT32(a, b, shift)      silk_ADD32((a), silk_RSHIFT32((b), (shift)))    /* shift >= 0 */
+#define silk_ADD_RSHIFT_uint(a, b, shift)   ((a) + silk_RSHIFT_uint((b), (shift)))          /* shift >= 0 */
+#define silk_SUB_LSHIFT32(a, b, shift)      silk_SUB32((a), silk_LSHIFT32((b), (shift)))    /* shift >= 0 */
+#define silk_SUB_RSHIFT32(a, b, shift)      silk_SUB32((a), silk_RSHIFT32((b), (shift)))    /* shift >= 0 */
+
+/* Requires that shift > 0 */
+#define silk_RSHIFT_ROUND(a, shift)         ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)
+#define silk_RSHIFT_ROUND64(a, shift)       ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)
+
+/* Number of rightshift required to fit the multiplication */
+#define silk_NSHIFT_MUL_32_32(a, b)         ( -(31- (32-silk_CLZ32(silk_abs(a)) + (32-silk_CLZ32(silk_abs(b))))) )
+#define silk_NSHIFT_MUL_16_16(a, b)         ( -(15- (16-silk_CLZ16(silk_abs(a)) + (16-silk_CLZ16(silk_abs(b))))) )
+
+
+#define silk_min(a, b)                      (((a) < (b)) ? (a) : (b))
+#define silk_max(a, b)                      (((a) > (b)) ? (a) : (b))
+
+/* Macro to convert floating-point constants to fixed-point */
+#define SILK_FIX_CONST( C, Q )              ((opus_int32)((C) * ((opus_int64)1 << (Q)) + 0.5))
+
+/* silk_min() versions with typecast in the function call */
+static OPUS_INLINE opus_int silk_min_int(opus_int a, opus_int b)
+{
+    return (((a) < (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int16 silk_min_16(opus_int16 a, opus_int16 b)
+{
+    return (((a) < (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int32 silk_min_32(opus_int32 a, opus_int32 b)
+{
+    return (((a) < (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int64 silk_min_64(opus_int64 a, opus_int64 b)
+{
+    return (((a) < (b)) ? (a) : (b));
+}
+
+/* silk_min() versions with typecast in the function call */
+static OPUS_INLINE opus_int silk_max_int(opus_int a, opus_int b)
+{
+    return (((a) > (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int16 silk_max_16(opus_int16 a, opus_int16 b)
+{
+    return (((a) > (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int32 silk_max_32(opus_int32 a, opus_int32 b)
+{
+    return (((a) > (b)) ? (a) : (b));
+}
+static OPUS_INLINE opus_int64 silk_max_64(opus_int64 a, opus_int64 b)
+{
+    return (((a) > (b)) ? (a) : (b));
+}
+
+#define silk_LIMIT( a, limit1, limit2)      ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
+                                                                 : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))))
+
+#define silk_LIMIT_int                      silk_LIMIT
+#define silk_LIMIT_16                       silk_LIMIT
+#define silk_LIMIT_32                       silk_LIMIT
+
+#define silk_abs(a)                         (((a) >  0)  ? (a) : -(a))            /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN */
+#define silk_abs_int(a)                     (((a) ^ ((a) >> (8 * sizeof(a) - 1))) - ((a) >> (8 * sizeof(a) - 1)))
+#define silk_abs_int32(a)                   (((a) ^ ((a) >> 31)) - ((a) >> 31))
+#define silk_abs_int64(a)                   (((a) >  0)  ? (a) : -(a))
+
+#define silk_sign(a)                        ((a) > 0 ? 1 : ( (a) < 0 ? -1 : 0 ))
+
+/* PSEUDO-RANDOM GENERATOR                                                          */
+/* Make sure to store the result as the seed for the next call (also in between     */
+/* frames), otherwise result won't be random at all. When only using some of the    */
+/* bits, take the most significant bits by right-shifting.                          */
+#define RAND_MULTIPLIER                     196314165
+#define RAND_INCREMENT                      907633515
+#define silk_RAND(seed)                     (silk_MLA_ovflw((RAND_INCREMENT), (seed), (RAND_MULTIPLIER)))
+
+/*  Add some multiplication functions that can be easily mapped to ARM. */
+
+/*    silk_SMMUL: Signed top word multiply.
+          ARMv6        2 instruction cycles.
+          ARMv3M+      3 instruction cycles. use SMULL and ignore LSB registers.(except xM)*/
+/*#define silk_SMMUL(a32, b32)                (opus_int32)silk_RSHIFT(silk_SMLAL(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16)), 16)*/
+/* the following seems faster on x86 */
+#define silk_SMMUL(a32, b32)                (opus_int32)silk_RSHIFT64(silk_SMULL((a32), (b32)), 32)
+
+#if !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#define silk_burg_modified(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch) \
+    ((void)(arch), silk_burg_modified_c(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch))
+
+#define silk_inner_prod16_aligned_64(inVec1, inVec2, len, arch) \
+    ((void)(arch),silk_inner_prod16_aligned_64_c(inVec1, inVec2, len))
+#endif
+
+#include "Inlines.h"
+#include "MacroCount.h"
+#include "MacroDebug.h"
+
+#ifdef OPUS_ARM_INLINE_ASM
+#include "arm/SigProc_FIX_armv4.h"
+#endif
+
+#ifdef OPUS_ARM_INLINE_EDSP
+#include "arm/SigProc_FIX_armv5e.h"
+#endif
+
+#if defined(MIPSr1_ASM)
+#include "mips/sigproc_fix_mipsr1.h"
+#endif
+
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif /* SILK_SIGPROC_FIX_H */
diff --git a/opus/silk/VAD.c b/opus/silk/VAD.c
new file mode 100644 (file)
index 0000000..0a782af
--- /dev/null
@@ -0,0 +1,362 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/* Silk VAD noise level estimation */
+# if !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+static OPUS_INLINE void silk_VAD_GetNoiseLevels(
+    const opus_int32             pX[ VAD_N_BANDS ], /* I    subband energies                            */
+    silk_VAD_state              *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */
+);
+#endif
+
+/**********************************/
+/* Initialization of the Silk VAD */
+/**********************************/
+opus_int silk_VAD_Init(                                         /* O    Return value, 0 if success                  */
+    silk_VAD_state              *psSilk_VAD                     /* I/O  Pointer to Silk VAD state                   */
+)
+{
+    opus_int b, ret = 0;
+
+    /* reset state memory */
+    silk_memset( psSilk_VAD, 0, sizeof( silk_VAD_state ) );
+
+    /* init noise levels */
+    /* Initialize array with approx pink noise levels (psd proportional to inverse of frequency) */
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        psSilk_VAD->NoiseLevelBias[ b ] = silk_max_32( silk_DIV32_16( VAD_NOISE_LEVELS_BIAS, b + 1 ), 1 );
+    }
+
+    /* Initialize state */
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        psSilk_VAD->NL[ b ]     = silk_MUL( 100, psSilk_VAD->NoiseLevelBias[ b ] );
+        psSilk_VAD->inv_NL[ b ] = silk_DIV32( silk_int32_MAX, psSilk_VAD->NL[ b ] );
+    }
+    psSilk_VAD->counter = 15;
+
+    /* init smoothed energy-to-noise ratio*/
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        psSilk_VAD->NrgRatioSmth_Q8[ b ] = 100 * 256;       /* 100 * 256 --> 20 dB SNR */
+    }
+
+    return( ret );
+}
+
+/* Weighting factors for tilt measure */
+static const opus_int32 tiltWeights[ VAD_N_BANDS ] = { 30000, 6000, -12000, -12000 };
+
+/***************************************/
+/* Get the speech activity level in Q8 */
+/***************************************/
+opus_int silk_VAD_GetSA_Q8_c(                                   /* O    Return value, 0 if success                  */
+    silk_encoder_state          *psEncC,                        /* I/O  Encoder state                               */
+    const opus_int16            pIn[]                           /* I    PCM input                                   */
+)
+{
+    opus_int   SA_Q15, pSNR_dB_Q7, input_tilt;
+    opus_int   decimated_framelength1, decimated_framelength2;
+    opus_int   decimated_framelength;
+    opus_int   dec_subframe_length, dec_subframe_offset, SNR_Q7, i, b, s;
+    opus_int32 sumSquared, smooth_coef_Q16;
+    opus_int16 HPstateTmp;
+    VARDECL( opus_int16, X );
+    opus_int32 Xnrg[ VAD_N_BANDS ];
+    opus_int32 NrgToNoiseRatio_Q8[ VAD_N_BANDS ];
+    opus_int32 speech_nrg, x_tmp;
+    opus_int   X_offset[ VAD_N_BANDS ];
+    opus_int   ret = 0;
+    silk_VAD_state *psSilk_VAD = &psEncC->sVAD;
+    SAVE_STACK;
+
+    /* Safety checks */
+    silk_assert( VAD_N_BANDS == 4 );
+    silk_assert( MAX_FRAME_LENGTH >= psEncC->frame_length );
+    silk_assert( psEncC->frame_length <= 512 );
+    silk_assert( psEncC->frame_length == 8 * silk_RSHIFT( psEncC->frame_length, 3 ) );
+
+    /***********************/
+    /* Filter and Decimate */
+    /***********************/
+    decimated_framelength1 = silk_RSHIFT( psEncC->frame_length, 1 );
+    decimated_framelength2 = silk_RSHIFT( psEncC->frame_length, 2 );
+    decimated_framelength = silk_RSHIFT( psEncC->frame_length, 3 );
+    /* Decimate into 4 bands:
+       0       L      3L       L              3L                             5L
+               -      --       -              --                             --
+               8       8       2               4                              4
+
+       [0-1 kHz| temp. |1-2 kHz|    2-4 kHz    |            4-8 kHz           |
+
+       They're arranged to allow the minimal ( frame_length / 4 ) extra
+       scratch space during the downsampling process */
+    X_offset[ 0 ] = 0;
+    X_offset[ 1 ] = decimated_framelength + decimated_framelength2;
+    X_offset[ 2 ] = X_offset[ 1 ] + decimated_framelength;
+    X_offset[ 3 ] = X_offset[ 2 ] + decimated_framelength2;
+    ALLOC( X, X_offset[ 3 ] + decimated_framelength1, opus_int16 );
+
+    /* 0-8 kHz to 0-4 kHz and 4-8 kHz */
+    silk_ana_filt_bank_1( pIn, &psSilk_VAD->AnaState[  0 ],
+        X, &X[ X_offset[ 3 ] ], psEncC->frame_length );
+
+    /* 0-4 kHz to 0-2 kHz and 2-4 kHz */
+    silk_ana_filt_bank_1( X, &psSilk_VAD->AnaState1[ 0 ],
+        X, &X[ X_offset[ 2 ] ], decimated_framelength1 );
+
+    /* 0-2 kHz to 0-1 kHz and 1-2 kHz */
+    silk_ana_filt_bank_1( X, &psSilk_VAD->AnaState2[ 0 ],
+        X, &X[ X_offset[ 1 ] ], decimated_framelength2 );
+
+    /*********************************************/
+    /* HP filter on lowest band (differentiator) */
+    /*********************************************/
+    X[ decimated_framelength - 1 ] = silk_RSHIFT( X[ decimated_framelength - 1 ], 1 );
+    HPstateTmp = X[ decimated_framelength - 1 ];
+    for( i = decimated_framelength - 1; i > 0; i-- ) {
+        X[ i - 1 ]  = silk_RSHIFT( X[ i - 1 ], 1 );
+        X[ i ]     -= X[ i - 1 ];
+    }
+    X[ 0 ] -= psSilk_VAD->HPstate;
+    psSilk_VAD->HPstate = HPstateTmp;
+
+    /*************************************/
+    /* Calculate the energy in each band */
+    /*************************************/
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* Find the decimated framelength in the non-uniformly divided bands */
+        decimated_framelength = silk_RSHIFT( psEncC->frame_length, silk_min_int( VAD_N_BANDS - b, VAD_N_BANDS - 1 ) );
+
+        /* Split length into subframe lengths */
+        dec_subframe_length = silk_RSHIFT( decimated_framelength, VAD_INTERNAL_SUBFRAMES_LOG2 );
+        dec_subframe_offset = 0;
+
+        /* Compute energy per sub-frame */
+        /* initialize with summed energy of last subframe */
+        Xnrg[ b ] = psSilk_VAD->XnrgSubfr[ b ];
+        for( s = 0; s < VAD_INTERNAL_SUBFRAMES; s++ ) {
+            sumSquared = 0;
+            for( i = 0; i < dec_subframe_length; i++ ) {
+                /* The energy will be less than dec_subframe_length * ( silk_int16_MIN / 8 ) ^ 2.            */
+                /* Therefore we can accumulate with no risk of overflow (unless dec_subframe_length > 128)  */
+                x_tmp = silk_RSHIFT(
+                    X[ X_offset[ b ] + i + dec_subframe_offset ], 3 );
+                sumSquared = silk_SMLABB( sumSquared, x_tmp, x_tmp );
+
+                /* Safety check */
+                silk_assert( sumSquared >= 0 );
+            }
+
+            /* Add/saturate summed energy of current subframe */
+            if( s < VAD_INTERNAL_SUBFRAMES - 1 ) {
+                Xnrg[ b ] = silk_ADD_POS_SAT32( Xnrg[ b ], sumSquared );
+            } else {
+                /* Look-ahead subframe */
+                Xnrg[ b ] = silk_ADD_POS_SAT32( Xnrg[ b ], silk_RSHIFT( sumSquared, 1 ) );
+            }
+
+            dec_subframe_offset += dec_subframe_length;
+        }
+        psSilk_VAD->XnrgSubfr[ b ] = sumSquared;
+    }
+
+    /********************/
+    /* Noise estimation */
+    /********************/
+    silk_VAD_GetNoiseLevels( &Xnrg[ 0 ], psSilk_VAD );
+
+    /***********************************************/
+    /* Signal-plus-noise to noise ratio estimation */
+    /***********************************************/
+    sumSquared = 0;
+    input_tilt = 0;
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        speech_nrg = Xnrg[ b ] - psSilk_VAD->NL[ b ];
+        if( speech_nrg > 0 ) {
+            /* Divide, with sufficient resolution */
+            if( ( Xnrg[ b ] & 0xFF800000 ) == 0 ) {
+                NrgToNoiseRatio_Q8[ b ] = silk_DIV32( silk_LSHIFT( Xnrg[ b ], 8 ), psSilk_VAD->NL[ b ] + 1 );
+            } else {
+                NrgToNoiseRatio_Q8[ b ] = silk_DIV32( Xnrg[ b ], silk_RSHIFT( psSilk_VAD->NL[ b ], 8 ) + 1 );
+            }
+
+            /* Convert to log domain */
+            SNR_Q7 = silk_lin2log( NrgToNoiseRatio_Q8[ b ] ) - 8 * 128;
+
+            /* Sum-of-squares */
+            sumSquared = silk_SMLABB( sumSquared, SNR_Q7, SNR_Q7 );          /* Q14 */
+
+            /* Tilt measure */
+            if( speech_nrg < ( (opus_int32)1 << 20 ) ) {
+                /* Scale down SNR value for small subband speech energies */
+                SNR_Q7 = silk_SMULWB( silk_LSHIFT( silk_SQRT_APPROX( speech_nrg ), 6 ), SNR_Q7 );
+            }
+            input_tilt = silk_SMLAWB( input_tilt, tiltWeights[ b ], SNR_Q7 );
+        } else {
+            NrgToNoiseRatio_Q8[ b ] = 256;
+        }
+    }
+
+    /* Mean-of-squares */
+    sumSquared = silk_DIV32_16( sumSquared, VAD_N_BANDS ); /* Q14 */
+
+    /* Root-mean-square approximation, scale to dBs, and write to output pointer */
+    pSNR_dB_Q7 = (opus_int16)( 3 * silk_SQRT_APPROX( sumSquared ) ); /* Q7 */
+
+    /*********************************/
+    /* Speech Probability Estimation */
+    /*********************************/
+    SA_Q15 = silk_sigm_Q15( silk_SMULWB( VAD_SNR_FACTOR_Q16, pSNR_dB_Q7 ) - VAD_NEGATIVE_OFFSET_Q5 );
+
+    /**************************/
+    /* Frequency Tilt Measure */
+    /**************************/
+    psEncC->input_tilt_Q15 = silk_LSHIFT( silk_sigm_Q15( input_tilt ) - 16384, 1 );
+
+    /**************************************************/
+    /* Scale the sigmoid output based on power levels */
+    /**************************************************/
+    speech_nrg = 0;
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* Accumulate signal-without-noise energies, higher frequency bands have more weight */
+        speech_nrg += ( b + 1 ) * silk_RSHIFT( Xnrg[ b ] - psSilk_VAD->NL[ b ], 4 );
+    }
+
+    /* Power scaling */
+    if( speech_nrg <= 0 ) {
+        SA_Q15 = silk_RSHIFT( SA_Q15, 1 );
+    } else if( speech_nrg < 32768 ) {
+        if( psEncC->frame_length == 10 * psEncC->fs_kHz ) {
+            speech_nrg = silk_LSHIFT_SAT32( speech_nrg, 16 );
+        } else {
+            speech_nrg = silk_LSHIFT_SAT32( speech_nrg, 15 );
+        }
+
+        /* square-root */
+        speech_nrg = silk_SQRT_APPROX( speech_nrg );
+        SA_Q15 = silk_SMULWB( 32768 + speech_nrg, SA_Q15 );
+    }
+
+    /* Copy the resulting speech activity in Q8 */
+    psEncC->speech_activity_Q8 = silk_min_int( silk_RSHIFT( SA_Q15, 7 ), silk_uint8_MAX );
+
+    /***********************************/
+    /* Energy Level and SNR estimation */
+    /***********************************/
+    /* Smoothing coefficient */
+    smooth_coef_Q16 = silk_SMULWB( VAD_SNR_SMOOTH_COEF_Q18, silk_SMULWB( (opus_int32)SA_Q15, SA_Q15 ) );
+
+    if( psEncC->frame_length == 10 * psEncC->fs_kHz ) {
+        smooth_coef_Q16 >>= 1;
+    }
+
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* compute smoothed energy-to-noise ratio per band */
+        psSilk_VAD->NrgRatioSmth_Q8[ b ] = silk_SMLAWB( psSilk_VAD->NrgRatioSmth_Q8[ b ],
+            NrgToNoiseRatio_Q8[ b ] - psSilk_VAD->NrgRatioSmth_Q8[ b ], smooth_coef_Q16 );
+
+        /* signal to noise ratio in dB per band */
+        SNR_Q7 = 3 * ( silk_lin2log( psSilk_VAD->NrgRatioSmth_Q8[b] ) - 8 * 128 );
+        /* quality = sigmoid( 0.25 * ( SNR_dB - 16 ) ); */
+        psEncC->input_quality_bands_Q15[ b ] = silk_sigm_Q15( silk_RSHIFT( SNR_Q7 - 16 * 128, 4 ) );
+    }
+
+    RESTORE_STACK;
+    return( ret );
+}
+
+/**************************/
+/* Noise level estimation */
+/**************************/
+# if  !defined(OPUS_X86_MAY_HAVE_SSE4_1)
+static OPUS_INLINE
+#endif
+void silk_VAD_GetNoiseLevels(
+    const opus_int32            pX[ VAD_N_BANDS ],  /* I    subband energies                            */
+    silk_VAD_state              *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */
+)
+{
+    opus_int   k;
+    opus_int32 nl, nrg, inv_nrg;
+    opus_int   coef, min_coef;
+
+    /* Initially faster smoothing */
+    if( psSilk_VAD->counter < 1000 ) { /* 1000 = 20 sec */
+        min_coef = silk_DIV32_16( silk_int16_MAX, silk_RSHIFT( psSilk_VAD->counter, 4 ) + 1 );
+    } else {
+        min_coef = 0;
+    }
+
+    for( k = 0; k < VAD_N_BANDS; k++ ) {
+        /* Get old noise level estimate for current band */
+        nl = psSilk_VAD->NL[ k ];
+        silk_assert( nl >= 0 );
+
+        /* Add bias */
+        nrg = silk_ADD_POS_SAT32( pX[ k ], psSilk_VAD->NoiseLevelBias[ k ] );
+        silk_assert( nrg > 0 );
+
+        /* Invert energies */
+        inv_nrg = silk_DIV32( silk_int32_MAX, nrg );
+        silk_assert( inv_nrg >= 0 );
+
+        /* Less update when subband energy is high */
+        if( nrg > silk_LSHIFT( nl, 3 ) ) {
+            coef = VAD_NOISE_LEVEL_SMOOTH_COEF_Q16 >> 3;
+        } else if( nrg < nl ) {
+            coef = VAD_NOISE_LEVEL_SMOOTH_COEF_Q16;
+        } else {
+            coef = silk_SMULWB( silk_SMULWW( inv_nrg, nl ), VAD_NOISE_LEVEL_SMOOTH_COEF_Q16 << 1 );
+        }
+
+        /* Initially faster smoothing */
+        coef = silk_max_int( coef, min_coef );
+
+        /* Smooth inverse energies */
+        psSilk_VAD->inv_NL[ k ] = silk_SMLAWB( psSilk_VAD->inv_NL[ k ], inv_nrg - psSilk_VAD->inv_NL[ k ], coef );
+        silk_assert( psSilk_VAD->inv_NL[ k ] >= 0 );
+
+        /* Compute noise level by inverting again */
+        nl = silk_DIV32( silk_int32_MAX, psSilk_VAD->inv_NL[ k ] );
+        silk_assert( nl >= 0 );
+
+        /* Limit noise levels (guarantee 7 bits of head room) */
+        nl = silk_min( nl, 0x00FFFFFF );
+
+        /* Store as part of state */
+        psSilk_VAD->NL[ k ] = nl;
+    }
+
+    /* Increment frame counter */
+    psSilk_VAD->counter++;
+}
diff --git a/opus/silk/VQ_WMat_EC.c b/opus/silk/VQ_WMat_EC.c
new file mode 100644 (file)
index 0000000..0f3d545
--- /dev/null
@@ -0,0 +1,131 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Entropy constrained matrix-weighted VQ, hard-coded to 5-element vectors, for a single input data vector */
+void silk_VQ_WMat_EC_c(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *res_nrg_Q15,                   /* O    best residual energy                        */
+    opus_int32                  *rate_dist_Q8,                  /* O    best total bitrate                          */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int32            *XX_Q17,                        /* I    correlation matrix                          */
+    const opus_int32            *xX_Q17,                        /* I    correlation vector                          */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              subfr_len,                      /* I    number of samples per subframe              */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    const opus_int              L                               /* I    number of vectors in codebook               */
+)
+{
+    opus_int   k, gain_tmp_Q7;
+    const opus_int8 *cb_row_Q7;
+    opus_int32 neg_xX_Q24[ 5 ];
+    opus_int32 sum1_Q15, sum2_Q24;
+    opus_int32 bits_res_Q8, bits_tot_Q8;
+
+    /* Negate and convert to new Q domain */
+    neg_xX_Q24[ 0 ] = -silk_LSHIFT32( xX_Q17[ 0 ], 7 );
+    neg_xX_Q24[ 1 ] = -silk_LSHIFT32( xX_Q17[ 1 ], 7 );
+    neg_xX_Q24[ 2 ] = -silk_LSHIFT32( xX_Q17[ 2 ], 7 );
+    neg_xX_Q24[ 3 ] = -silk_LSHIFT32( xX_Q17[ 3 ], 7 );
+    neg_xX_Q24[ 4 ] = -silk_LSHIFT32( xX_Q17[ 4 ], 7 );
+
+    /* Loop over codebook */
+    *rate_dist_Q8 = silk_int32_MAX;
+    *res_nrg_Q15 = silk_int32_MAX;
+    cb_row_Q7 = cb_Q7;
+    /* In things go really bad, at least *ind is set to something safe. */
+    *ind = 0;
+    for( k = 0; k < L; k++ ) {
+        opus_int32 penalty;
+        gain_tmp_Q7 = cb_gain_Q7[k];
+        /* Weighted rate */
+        /* Quantization error: 1 - 2 * xX * cb + cb' * XX * cb */
+        sum1_Q15 = SILK_FIX_CONST( 1.001, 15 );
+
+        /* Penalty for too large gain */
+        penalty = silk_LSHIFT32( silk_max( silk_SUB32( gain_tmp_Q7, max_gain_Q7 ), 0 ), 11 );
+
+        /* first row of XX_Q17 */
+        sum2_Q24 = silk_MLA( neg_xX_Q24[ 0 ], XX_Q17[  1 ], cb_row_Q7[ 1 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  2 ], cb_row_Q7[ 2 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  3 ], cb_row_Q7[ 3 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  4 ], cb_row_Q7[ 4 ] );
+        sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  0 ], cb_row_Q7[ 0 ] );
+        sum1_Q15 = silk_SMLAWB( sum1_Q15,        sum2_Q24,  cb_row_Q7[ 0 ] );
+
+        /* second row of XX_Q17 */
+        sum2_Q24 = silk_MLA( neg_xX_Q24[ 1 ], XX_Q17[  7 ], cb_row_Q7[ 2 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  8 ], cb_row_Q7[ 3 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  9 ], cb_row_Q7[ 4 ] );
+        sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[  6 ], cb_row_Q7[ 1 ] );
+        sum1_Q15 = silk_SMLAWB( sum1_Q15,        sum2_Q24,  cb_row_Q7[ 1 ] );
+
+        /* third row of XX_Q17 */
+        sum2_Q24 = silk_MLA( neg_xX_Q24[ 2 ], XX_Q17[ 13 ], cb_row_Q7[ 3 ] );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[ 14 ], cb_row_Q7[ 4 ] );
+        sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[ 12 ], cb_row_Q7[ 2 ] );
+        sum1_Q15 = silk_SMLAWB( sum1_Q15,        sum2_Q24,  cb_row_Q7[ 2 ] );
+
+        /* fourth row of XX_Q17 */
+        sum2_Q24 = silk_MLA( neg_xX_Q24[ 3 ], XX_Q17[ 19 ], cb_row_Q7[ 4 ] );
+        sum2_Q24 = silk_LSHIFT32( sum2_Q24, 1 );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[ 18 ], cb_row_Q7[ 3 ] );
+        sum1_Q15 = silk_SMLAWB( sum1_Q15,        sum2_Q24,  cb_row_Q7[ 3 ] );
+
+        /* last row of XX_Q17 */
+        sum2_Q24 = silk_LSHIFT32( neg_xX_Q24[ 4 ], 1 );
+        sum2_Q24 = silk_MLA( sum2_Q24,        XX_Q17[ 24 ], cb_row_Q7[ 4 ] );
+        sum1_Q15 = silk_SMLAWB( sum1_Q15,        sum2_Q24,  cb_row_Q7[ 4 ] );
+
+        /* find best */
+        if( sum1_Q15 >= 0 ) {
+            /* Translate residual energy to bits using high-rate assumption (6 dB ==> 1 bit/sample) */
+            bits_res_Q8 = silk_SMULBB( subfr_len, silk_lin2log( sum1_Q15 + penalty) - (15 << 7) );
+            /* In the following line we reduce the codelength component by half ("-1"); seems to slghtly improve quality */
+            bits_tot_Q8 = silk_ADD_LSHIFT32( bits_res_Q8, cl_Q5[ k ], 3-1 );
+            if( bits_tot_Q8 <= *rate_dist_Q8 ) {
+                *rate_dist_Q8 = bits_tot_Q8;
+                *res_nrg_Q15 = sum1_Q15 + penalty;
+                *ind = (opus_int8)k;
+                *gain_Q7 = gain_tmp_Q7;
+            }
+        }
+
+        /* Go to next cbk vector */
+        cb_row_Q7 += LTP_ORDER;
+    }
+}
diff --git a/opus/silk/ana_filt_bank_1.c b/opus/silk/ana_filt_bank_1.c
new file mode 100644 (file)
index 0000000..24cfb03
--- /dev/null
@@ -0,0 +1,74 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Coefficients for 2-band filter bank based on first-order allpass filters */
+static opus_int16 A_fb1_20 = 5394 << 1;
+static opus_int16 A_fb1_21 = -24290; /* (opus_int16)(20623 << 1) */
+
+/* Split signal into two decimated bands using first-order allpass filters */
+void silk_ana_filt_bank_1(
+    const opus_int16            *in,                /* I    Input signal [N]                                            */
+    opus_int32                  *S,                 /* I/O  State vector [2]                                            */
+    opus_int16                  *outL,              /* O    Low band [N/2]                                              */
+    opus_int16                  *outH,              /* O    High band [N/2]                                             */
+    const opus_int32            N                   /* I    Number of input samples                                     */
+)
+{
+    opus_int      k, N2 = silk_RSHIFT( N, 1 );
+    opus_int32    in32, X, Y, out_1, out_2;
+
+    /* Internal variables and state are in Q10 format */
+    for( k = 0; k < N2; k++ ) {
+        /* Convert to Q10 */
+        in32 = silk_LSHIFT( (opus_int32)in[ 2 * k ], 10 );
+
+        /* All-pass section for even input sample */
+        Y      = silk_SUB32( in32, S[ 0 ] );
+        X      = silk_SMLAWB( Y, Y, A_fb1_21 );
+        out_1  = silk_ADD32( S[ 0 ], X );
+        S[ 0 ] = silk_ADD32( in32, X );
+
+        /* Convert to Q10 */
+        in32 = silk_LSHIFT( (opus_int32)in[ 2 * k + 1 ], 10 );
+
+        /* All-pass section for odd input sample, and add to output of previous section */
+        Y      = silk_SUB32( in32, S[ 1 ] );
+        X      = silk_SMULWB( Y, A_fb1_20 );
+        out_2  = silk_ADD32( S[ 1 ], X );
+        S[ 1 ] = silk_ADD32( in32, X );
+
+        /* Add/subtract, convert back to int16 and store to output */
+        outL[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_ADD32( out_2, out_1 ), 11 ) );
+        outH[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SUB32( out_2, out_1 ), 11 ) );
+    }
+}
diff --git a/opus/silk/arm/LPC_inv_pred_gain_arm.h b/opus/silk/arm/LPC_inv_pred_gain_arm.h
new file mode 100644 (file)
index 0000000..9895b55
--- /dev/null
@@ -0,0 +1,57 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_LPC_INV_PRED_GAIN_ARM_H
+# define SILK_LPC_INV_PRED_GAIN_ARM_H
+
+# include "celt/arm/armcpu.h"
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+opus_int32 silk_LPC_inverse_pred_gain_neon(         /* O   Returns inverse prediction gain in energy domain, Q30        */
+    const opus_int16            *A_Q12,             /* I   Prediction coefficients, Q12 [order]                         */
+    const opus_int              order               /* I   Prediction order                                             */
+);
+
+#  if !defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_PRESUME_NEON)
+#   define OVERRIDE_silk_LPC_inverse_pred_gain            (1)
+#   define silk_LPC_inverse_pred_gain(A_Q12, order, arch) ((void)(arch), PRESUME_NEON(silk_LPC_inverse_pred_gain)(A_Q12, order))
+#  endif
+# endif
+
+# if !defined(OVERRIDE_silk_LPC_inverse_pred_gain)
+/*Is run-time CPU detection enabled on this platform?*/
+#  if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern opus_int32 (*const SILK_LPC_INVERSE_PRED_GAIN_IMPL[OPUS_ARCHMASK+1])(const opus_int16 *A_Q12, const opus_int order);
+#   define OVERRIDE_silk_LPC_inverse_pred_gain            (1)
+#   define silk_LPC_inverse_pred_gain(A_Q12, order, arch) ((*SILK_LPC_INVERSE_PRED_GAIN_IMPL[(arch)&OPUS_ARCHMASK])(A_Q12, order))
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#   define OVERRIDE_silk_LPC_inverse_pred_gain            (1)
+#   define silk_LPC_inverse_pred_gain(A_Q12, order, arch) ((void)(arch), silk_LPC_inverse_pred_gain_neon(A_Q12, order))
+#  endif
+# endif
+
+#endif /* end SILK_LPC_INV_PRED_GAIN_ARM_H */
diff --git a/opus/silk/arm/LPC_inv_pred_gain_neon_intr.c b/opus/silk/arm/LPC_inv_pred_gain_neon_intr.c
new file mode 100644 (file)
index 0000000..27142f3
--- /dev/null
@@ -0,0 +1,280 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#include "SigProc_FIX.h"
+#include "define.h"
+
+#define QA                          24
+#define A_LIMIT                     SILK_FIX_CONST( 0.99975, QA )
+
+#define MUL32_FRAC_Q(a32, b32, Q)   ((opus_int32)(silk_RSHIFT_ROUND64(silk_SMULL(a32, b32), Q)))
+
+/* The difficulty is how to judge a 64-bit signed integer tmp64 is 32-bit overflowed,
+ * since NEON has no 64-bit min, max or comparison instructions.
+ * A failed idea is to compare the results of vmovn(tmp64) and vqmovn(tmp64) whether they are equal or not.
+ * However, this idea fails when the tmp64 is something like 0xFFFFFFF980000000.
+ * Here we know that mult2Q >= 1, so the highest bit (bit 63, sign bit) of tmp64 must equal to bit 62.
+ * tmp64 was shifted left by 1 and we got tmp64'. If high_half(tmp64') != 0 and high_half(tmp64') != -1,
+ * then we know that bit 31 to bit 63 of tmp64 can not all be the sign bit, and therefore tmp64 is 32-bit overflowed.
+ * That is, we judge if tmp64' > 0x00000000FFFFFFFF, or tmp64' <= 0xFFFFFFFF00000000.
+ * We use narrowing shift right 31 bits to tmp32' to save data bandwidth and instructions.
+ * That is, we judge if tmp32' > 0x00000000, or tmp32' <= 0xFFFFFFFF.
+ */
+
+/* Compute inverse of LPC prediction gain, and                          */
+/* test if LPC coefficients are stable (all poles within unit circle)   */
+static OPUS_INLINE opus_int32 LPC_inverse_pred_gain_QA_neon( /* O   Returns inverse prediction gain in energy domain, Q30    */
+    opus_int32           A_QA[ SILK_MAX_ORDER_LPC ],         /* I   Prediction coefficients                                  */
+    const opus_int       order                               /* I   Prediction order                                         */
+)
+{
+    opus_int   k, n, mult2Q;
+    opus_int32 invGain_Q30, rc_Q31, rc_mult1_Q30, rc_mult2, tmp1, tmp2;
+    opus_int32 max, min;
+    int32x4_t  max_s32x4, min_s32x4;
+    int32x2_t  max_s32x2, min_s32x2;
+
+    max_s32x4 = vdupq_n_s32( silk_int32_MIN );
+    min_s32x4 = vdupq_n_s32( silk_int32_MAX );
+    invGain_Q30 = SILK_FIX_CONST( 1, 30 );
+    for( k = order - 1; k > 0; k-- ) {
+        int32x2_t rc_Q31_s32x2, rc_mult2_s32x2;
+        int64x2_t mult2Q_s64x2;
+
+        /* Check for stability */
+        if( ( A_QA[ k ] > A_LIMIT ) || ( A_QA[ k ] < -A_LIMIT ) ) {
+            return 0;
+        }
+
+        /* Set RC equal to negated AR coef */
+        rc_Q31 = -silk_LSHIFT( A_QA[ k ], 31 - QA );
+
+        /* rc_mult1_Q30 range: [ 1 : 2^30 ] */
+        rc_mult1_Q30 = silk_SUB32( SILK_FIX_CONST( 1, 30 ), silk_SMMUL( rc_Q31, rc_Q31 ) );
+        silk_assert( rc_mult1_Q30 > ( 1 << 15 ) );                   /* reduce A_LIMIT if fails */
+        silk_assert( rc_mult1_Q30 <= ( 1 << 30 ) );
+
+        /* Update inverse gain */
+        /* invGain_Q30 range: [ 0 : 2^30 ] */
+        invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
+        silk_assert( invGain_Q30 >= 0           );
+        silk_assert( invGain_Q30 <= ( 1 << 30 ) );
+        if( invGain_Q30 < SILK_FIX_CONST( 1.0f / MAX_PREDICTION_POWER_GAIN, 30 ) ) {
+            return 0;
+        }
+
+        /* rc_mult2 range: [ 2^30 : silk_int32_MAX ] */
+        mult2Q = 32 - silk_CLZ32( silk_abs( rc_mult1_Q30 ) );
+        rc_mult2 = silk_INVERSE32_varQ( rc_mult1_Q30, mult2Q + 30 );
+
+        /* Update AR coefficient */
+        rc_Q31_s32x2   = vdup_n_s32( rc_Q31 );
+        mult2Q_s64x2   = vdupq_n_s64( -mult2Q );
+        rc_mult2_s32x2 = vdup_n_s32( rc_mult2 );
+
+        for( n = 0; n < ( ( k + 1 ) >> 1 ) - 3; n += 4 ) {
+            /* We always calculate extra elements of A_QA buffer when ( k % 4 ) != 0, to take the advantage of SIMD parallelization. */
+            int32x4_t tmp1_s32x4, tmp2_s32x4, t0_s32x4, t1_s32x4, s0_s32x4, s1_s32x4, t_QA0_s32x4, t_QA1_s32x4;
+            int64x2_t t0_s64x2, t1_s64x2, t2_s64x2, t3_s64x2;
+            tmp1_s32x4  = vld1q_s32( A_QA + n );
+            tmp2_s32x4  = vld1q_s32( A_QA + k - n - 4 );
+            tmp2_s32x4  = vrev64q_s32( tmp2_s32x4 );
+            tmp2_s32x4  = vcombine_s32( vget_high_s32( tmp2_s32x4 ), vget_low_s32( tmp2_s32x4 ) );
+            t0_s32x4    = vqrdmulhq_lane_s32( tmp2_s32x4, rc_Q31_s32x2, 0 );
+            t1_s32x4    = vqrdmulhq_lane_s32( tmp1_s32x4, rc_Q31_s32x2, 0 );
+            t_QA0_s32x4 = vqsubq_s32( tmp1_s32x4, t0_s32x4 );
+            t_QA1_s32x4 = vqsubq_s32( tmp2_s32x4, t1_s32x4 );
+            t0_s64x2    = vmull_s32( vget_low_s32 ( t_QA0_s32x4 ), rc_mult2_s32x2 );
+            t1_s64x2    = vmull_s32( vget_high_s32( t_QA0_s32x4 ), rc_mult2_s32x2 );
+            t2_s64x2    = vmull_s32( vget_low_s32 ( t_QA1_s32x4 ), rc_mult2_s32x2 );
+            t3_s64x2    = vmull_s32( vget_high_s32( t_QA1_s32x4 ), rc_mult2_s32x2 );
+            t0_s64x2    = vrshlq_s64( t0_s64x2, mult2Q_s64x2 );
+            t1_s64x2    = vrshlq_s64( t1_s64x2, mult2Q_s64x2 );
+            t2_s64x2    = vrshlq_s64( t2_s64x2, mult2Q_s64x2 );
+            t3_s64x2    = vrshlq_s64( t3_s64x2, mult2Q_s64x2 );
+            t0_s32x4    = vcombine_s32( vmovn_s64( t0_s64x2 ), vmovn_s64( t1_s64x2 ) );
+            t1_s32x4    = vcombine_s32( vmovn_s64( t2_s64x2 ), vmovn_s64( t3_s64x2 ) );
+            s0_s32x4    = vcombine_s32( vshrn_n_s64( t0_s64x2, 31 ), vshrn_n_s64( t1_s64x2, 31 ) );
+            s1_s32x4    = vcombine_s32( vshrn_n_s64( t2_s64x2, 31 ), vshrn_n_s64( t3_s64x2, 31 ) );
+            max_s32x4   = vmaxq_s32( max_s32x4, s0_s32x4 );
+            min_s32x4   = vminq_s32( min_s32x4, s0_s32x4 );
+            max_s32x4   = vmaxq_s32( max_s32x4, s1_s32x4 );
+            min_s32x4   = vminq_s32( min_s32x4, s1_s32x4 );
+            t1_s32x4    = vrev64q_s32( t1_s32x4 );
+            t1_s32x4    = vcombine_s32( vget_high_s32( t1_s32x4 ), vget_low_s32( t1_s32x4 ) );
+            vst1q_s32( A_QA + n,         t0_s32x4 );
+            vst1q_s32( A_QA + k - n - 4, t1_s32x4 );
+        }
+        for( ; n < (k + 1) >> 1; n++ ) {
+            opus_int64 tmp64;
+            tmp1 = A_QA[ n ];
+            tmp2 = A_QA[ k - n - 1 ];
+            tmp64 = silk_RSHIFT_ROUND64( silk_SMULL( silk_SUB_SAT32(tmp1,
+                  MUL32_FRAC_Q( tmp2, rc_Q31, 31 ) ), rc_mult2 ), mult2Q);
+            if( tmp64 > silk_int32_MAX || tmp64 < silk_int32_MIN ) {
+               return 0;
+            }
+            A_QA[ n ] = ( opus_int32 )tmp64;
+            tmp64 = silk_RSHIFT_ROUND64( silk_SMULL( silk_SUB_SAT32(tmp2,
+                  MUL32_FRAC_Q( tmp1, rc_Q31, 31 ) ), rc_mult2), mult2Q);
+            if( tmp64 > silk_int32_MAX || tmp64 < silk_int32_MIN ) {
+               return 0;
+            }
+            A_QA[ k - n - 1 ] = ( opus_int32 )tmp64;
+        }
+    }
+
+    /* Check for stability */
+    if( ( A_QA[ k ] > A_LIMIT ) || ( A_QA[ k ] < -A_LIMIT ) ) {
+        return 0;
+    }
+
+    max_s32x2 = vmax_s32( vget_low_s32( max_s32x4 ), vget_high_s32( max_s32x4 ) );
+    min_s32x2 = vmin_s32( vget_low_s32( min_s32x4 ), vget_high_s32( min_s32x4 ) );
+    max_s32x2 = vmax_s32( max_s32x2, vreinterpret_s32_s64( vshr_n_s64( vreinterpret_s64_s32( max_s32x2 ), 32 ) ) );
+    min_s32x2 = vmin_s32( min_s32x2, vreinterpret_s32_s64( vshr_n_s64( vreinterpret_s64_s32( min_s32x2 ), 32 ) ) );
+    max = vget_lane_s32( max_s32x2, 0 );
+    min = vget_lane_s32( min_s32x2, 0 );
+    if( ( max > 0 ) || ( min < -1 ) ) {
+        return 0;
+    }
+
+    /* Set RC equal to negated AR coef */
+    rc_Q31 = -silk_LSHIFT( A_QA[ 0 ], 31 - QA );
+
+    /* Range: [ 1 : 2^30 ] */
+    rc_mult1_Q30 = silk_SUB32( SILK_FIX_CONST( 1, 30 ), silk_SMMUL( rc_Q31, rc_Q31 ) );
+
+    /* Update inverse gain */
+    /* Range: [ 0 : 2^30 ] */
+    invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
+    silk_assert( invGain_Q30 >= 0           );
+    silk_assert( invGain_Q30 <= ( 1 << 30 ) );
+    if( invGain_Q30 < SILK_FIX_CONST( 1.0f / MAX_PREDICTION_POWER_GAIN, 30 ) ) {
+        return 0;
+    }
+
+    return invGain_Q30;
+}
+
+/* For input in Q12 domain */
+opus_int32 silk_LPC_inverse_pred_gain_neon(         /* O   Returns inverse prediction gain in energy domain, Q30        */
+    const opus_int16            *A_Q12,             /* I   Prediction coefficients, Q12 [order]                         */
+    const opus_int              order               /* I   Prediction order                                             */
+)
+{
+#ifdef OPUS_CHECK_ASM
+    const opus_int32 invGain_Q30_c = silk_LPC_inverse_pred_gain_c( A_Q12, order );
+#endif
+
+    opus_int32 invGain_Q30;
+    if( ( SILK_MAX_ORDER_LPC != 24 ) || ( order & 1 )) {
+        invGain_Q30 = silk_LPC_inverse_pred_gain_c( A_Q12, order );
+    }
+    else {
+        opus_int32 Atmp_QA[ SILK_MAX_ORDER_LPC ];
+        opus_int32 DC_resp;
+        int16x8_t  t0_s16x8, t1_s16x8, t2_s16x8;
+        int32x4_t  t0_s32x4;
+        const opus_int leftover = order & 7;
+
+        /* Increase Q domain of the AR coefficients */
+        t0_s16x8 = vld1q_s16( A_Q12 +  0 );
+        t1_s16x8 = vld1q_s16( A_Q12 +  8 );
+        t2_s16x8 = vld1q_s16( A_Q12 + 16 );
+        t0_s32x4 = vpaddlq_s16( t0_s16x8 );
+
+        switch( order - leftover )
+        {
+        case 24:
+            t0_s32x4 = vpadalq_s16( t0_s32x4, t2_s16x8 );
+            /* Intend to fall through */
+
+        case 16:
+            t0_s32x4 = vpadalq_s16( t0_s32x4, t1_s16x8 );
+            vst1q_s32( Atmp_QA + 16, vshll_n_s16( vget_low_s16 ( t2_s16x8 ), QA - 12 ) );
+            vst1q_s32( Atmp_QA + 20, vshll_n_s16( vget_high_s16( t2_s16x8 ), QA - 12 ) );
+            /* Intend to fall through */
+
+        case 8:
+        {
+            const int32x2_t t_s32x2 = vpadd_s32( vget_low_s32( t0_s32x4 ), vget_high_s32( t0_s32x4 ) );
+            const int64x1_t t_s64x1 = vpaddl_s32( t_s32x2 );
+            DC_resp = vget_lane_s32( vreinterpret_s32_s64( t_s64x1 ), 0 );
+            vst1q_s32( Atmp_QA +  8, vshll_n_s16( vget_low_s16 ( t1_s16x8 ), QA - 12 ) );
+            vst1q_s32( Atmp_QA + 12, vshll_n_s16( vget_high_s16( t1_s16x8 ), QA - 12 ) );
+        }
+        break;
+
+        default:
+            DC_resp = 0;
+            break;
+        }
+        A_Q12 += order - leftover;
+
+        switch( leftover )
+        {
+        case 6:
+            DC_resp += (opus_int32)A_Q12[ 5 ];
+            DC_resp += (opus_int32)A_Q12[ 4 ];
+            /* Intend to fall through */
+
+        case 4:
+            DC_resp += (opus_int32)A_Q12[ 3 ];
+            DC_resp += (opus_int32)A_Q12[ 2 ];
+            /* Intend to fall through */
+
+        case 2:
+            DC_resp += (opus_int32)A_Q12[ 1 ];
+            DC_resp += (opus_int32)A_Q12[ 0 ];
+            /* Intend to fall through */
+
+        default:
+            break;
+        }
+
+        /* If the DC is unstable, we don't even need to do the full calculations */
+        if( DC_resp >= 4096 ) {
+            invGain_Q30 = 0;
+        } else {
+            vst1q_s32( Atmp_QA + 0, vshll_n_s16( vget_low_s16 ( t0_s16x8 ), QA - 12 ) );
+            vst1q_s32( Atmp_QA + 4, vshll_n_s16( vget_high_s16( t0_s16x8 ), QA - 12 ) );
+            invGain_Q30 = LPC_inverse_pred_gain_QA_neon( Atmp_QA, order );
+        }
+    }
+
+#ifdef OPUS_CHECK_ASM
+    silk_assert( invGain_Q30_c == invGain_Q30 );
+#endif
+
+    return invGain_Q30;
+}
diff --git a/opus/silk/arm/NSQ_del_dec_arm.h b/opus/silk/arm/NSQ_del_dec_arm.h
new file mode 100644 (file)
index 0000000..9e76e16
--- /dev/null
@@ -0,0 +1,100 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_NSQ_DEL_DEC_ARM_H
+#define SILK_NSQ_DEL_DEC_ARM_H
+
+#include "celt/arm/armcpu.h"
+
+#if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+void silk_NSQ_del_dec_neon(
+    const silk_encoder_state *psEncC, silk_nsq_state *NSQ,
+    SideInfoIndices *psIndices, const opus_int16 x16[], opus_int8 pulses[],
+    const opus_int16 PredCoef_Q12[2 * MAX_LPC_ORDER],
+    const opus_int16 LTPCoef_Q14[LTP_ORDER * MAX_NB_SUBFR],
+    const opus_int16 AR_Q13[MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER],
+    const opus_int HarmShapeGain_Q14[MAX_NB_SUBFR],
+    const opus_int Tilt_Q14[MAX_NB_SUBFR],
+    const opus_int32 LF_shp_Q14[MAX_NB_SUBFR],
+    const opus_int32 Gains_Q16[MAX_NB_SUBFR],
+    const opus_int pitchL[MAX_NB_SUBFR], const opus_int Lambda_Q10,
+    const opus_int LTP_scale_Q14);
+
+#if !defined(OPUS_HAVE_RTCD)
+#define OVERRIDE_silk_NSQ_del_dec (1)
+#define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12,  \
+                         LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14, Tilt_Q14,   \
+                         LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10,          \
+                         LTP_scale_Q14, arch)                                \
+    ((void)(arch),                                                           \
+     PRESUME_NEON(silk_NSQ_del_dec)(                                         \
+         psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14,     \
+         AR_Q13, HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, \
+         Lambda_Q10, LTP_scale_Q14))
+#endif
+#endif
+
+#if !defined(OVERRIDE_silk_NSQ_del_dec)
+/*Is run-time CPU detection enabled on this platform?*/
+#if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && \
+                                !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern void (*const SILK_NSQ_DEL_DEC_IMPL[OPUS_ARCHMASK + 1])(
+    const silk_encoder_state *psEncC, silk_nsq_state *NSQ,
+    SideInfoIndices *psIndices, const opus_int16 x16[], opus_int8 pulses[],
+    const opus_int16 PredCoef_Q12[2 * MAX_LPC_ORDER],
+    const opus_int16 LTPCoef_Q14[LTP_ORDER * MAX_NB_SUBFR],
+    const opus_int16 AR_Q13[MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER],
+    const opus_int HarmShapeGain_Q14[MAX_NB_SUBFR],
+    const opus_int Tilt_Q14[MAX_NB_SUBFR],
+    const opus_int32 LF_shp_Q14[MAX_NB_SUBFR],
+    const opus_int32 Gains_Q16[MAX_NB_SUBFR],
+    const opus_int pitchL[MAX_NB_SUBFR], const opus_int Lambda_Q10,
+    const opus_int LTP_scale_Q14);
+#define OVERRIDE_silk_NSQ_del_dec (1)
+#define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, \
+                         LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14, Tilt_Q14,  \
+                         LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10,         \
+                         LTP_scale_Q14, arch)                               \
+    ((*SILK_NSQ_DEL_DEC_IMPL[(arch)&OPUS_ARCHMASK])(                        \
+        psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14,     \
+        AR_Q13, HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, \
+        Lambda_Q10, LTP_scale_Q14))
+#elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#define OVERRIDE_silk_NSQ_del_dec (1)
+#define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12,   \
+                         LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14, Tilt_Q14,    \
+                         LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10,           \
+                         LTP_scale_Q14, arch)                                 \
+    ((void)(arch),                                                            \
+     silk_NSQ_del_dec_neon(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, \
+                           LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14, Tilt_Q14,  \
+                           LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10,         \
+                           LTP_scale_Q14))
+#endif
+#endif
+
+#endif /* end SILK_NSQ_DEL_DEC_ARM_H */
diff --git a/opus/silk/arm/NSQ_del_dec_neon_intr.c b/opus/silk/arm/NSQ_del_dec_neon_intr.c
new file mode 100644 (file)
index 0000000..212410f
--- /dev/null
@@ -0,0 +1,1124 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#ifdef OPUS_CHECK_ASM
+# include <string.h>
+#endif
+#include "main.h"
+#include "stack_alloc.h"
+
+/* NEON intrinsics optimization now can only parallelize up to 4 delay decision states.    */
+/* If there are more states, C function is called, and this optimization must be expanded. */
+#define NEON_MAX_DEL_DEC_STATES 4
+
+typedef struct {
+    opus_int32 sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ][ NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 RandState[ DECISION_DELAY ][     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Q_Q10[     DECISION_DELAY ][     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Xq_Q14[    DECISION_DELAY ][     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Pred_Q15[  DECISION_DELAY ][     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Shape_Q14[ DECISION_DELAY ][     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 sAR2_Q14[ MAX_SHAPE_LPC_ORDER ][ NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 LF_AR_Q14[ NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Diff_Q14[  NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Seed[      NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 SeedInit[  NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 RD_Q10[    NEON_MAX_DEL_DEC_STATES ];
+} NSQ_del_decs_struct;
+
+typedef struct {
+    opus_int32 Q_Q10[        NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 RD_Q10[       NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 xq_Q14[       NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 LF_AR_Q14[    NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 Diff_Q14[     NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 sLTP_shp_Q14[ NEON_MAX_DEL_DEC_STATES ];
+    opus_int32 LPC_exc_Q14[  NEON_MAX_DEL_DEC_STATES ];
+} NSQ_samples_struct;
+
+static OPUS_INLINE void silk_nsq_del_dec_scale_states_neon(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_decs_struct psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int16    x16[],                      /* I    Input                               */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+);
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec_neon(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_decs_struct psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay           /* I                                        */
+);
+
+static OPUS_INLINE void copy_winner_state_kernel(
+    const NSQ_del_decs_struct *psDelDec,
+    const opus_int            offset,
+    const opus_int            last_smple_idx,
+    const opus_int            Winner_ind,
+    const int32x2_t           gain_lo_s32x2,
+    const int32x2_t           gain_hi_s32x2,
+    const int32x4_t           shift_s32x4,
+    int32x4_t                 t0_s32x4,
+    int32x4_t                 t1_s32x4,
+    opus_int8 *const          pulses,
+    opus_int16                *pxq,
+    silk_nsq_state            *NSQ
+)
+{
+    int16x8_t t_s16x8;
+    int32x4_t o0_s32x4, o1_s32x4;
+
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 0 ][ Winner_ind ], t0_s32x4, 0 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 1 ][ Winner_ind ], t0_s32x4, 1 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 2 ][ Winner_ind ], t0_s32x4, 2 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 3 ][ Winner_ind ], t0_s32x4, 3 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 4 ][ Winner_ind ], t1_s32x4, 0 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 5 ][ Winner_ind ], t1_s32x4, 1 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 6 ][ Winner_ind ], t1_s32x4, 2 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Q_Q10[ last_smple_idx - 7 ][ Winner_ind ], t1_s32x4, 3 );
+    t_s16x8 = vcombine_s16( vrshrn_n_s32( t0_s32x4, 10 ), vrshrn_n_s32( t1_s32x4, 10 ) );
+    vst1_s8( &pulses[ offset ], vmovn_s16( t_s16x8 ) );
+
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 0 ][ Winner_ind ], t0_s32x4, 0 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 1 ][ Winner_ind ], t0_s32x4, 1 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 2 ][ Winner_ind ], t0_s32x4, 2 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 3 ][ Winner_ind ], t0_s32x4, 3 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 4 ][ Winner_ind ], t1_s32x4, 0 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 5 ][ Winner_ind ], t1_s32x4, 1 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 6 ][ Winner_ind ], t1_s32x4, 2 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Xq_Q14[ last_smple_idx - 7 ][ Winner_ind ], t1_s32x4, 3 );
+    o0_s32x4 = vqdmulhq_lane_s32( t0_s32x4, gain_lo_s32x2, 0 );
+    o1_s32x4 = vqdmulhq_lane_s32( t1_s32x4, gain_lo_s32x2, 0 );
+    o0_s32x4 = vmlaq_lane_s32( o0_s32x4, t0_s32x4, gain_hi_s32x2, 0 );
+    o1_s32x4 = vmlaq_lane_s32( o1_s32x4, t1_s32x4, gain_hi_s32x2, 0 );
+    o0_s32x4 = vrshlq_s32( o0_s32x4, shift_s32x4 );
+    o1_s32x4 = vrshlq_s32( o1_s32x4, shift_s32x4 );
+    vst1_s16( &pxq[ offset + 0 ], vqmovn_s32( o0_s32x4 ) );
+    vst1_s16( &pxq[ offset + 4 ], vqmovn_s32( o1_s32x4 ) );
+
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 0 ][ Winner_ind ], t0_s32x4, 0 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 1 ][ Winner_ind ], t0_s32x4, 1 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 2 ][ Winner_ind ], t0_s32x4, 2 );
+    t0_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 3 ][ Winner_ind ], t0_s32x4, 3 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 4 ][ Winner_ind ], t1_s32x4, 0 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 5 ][ Winner_ind ], t1_s32x4, 1 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 6 ][ Winner_ind ], t1_s32x4, 2 );
+    t1_s32x4 = vld1q_lane_s32( &psDelDec->Shape_Q14[ last_smple_idx - 7 ][ Winner_ind ], t1_s32x4, 3 );
+    vst1q_s32( &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx + offset + 0 ], t0_s32x4 );
+    vst1q_s32( &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx + offset + 4 ], t1_s32x4 );
+}
+
+static OPUS_INLINE void copy_winner_state(
+    const NSQ_del_decs_struct *psDelDec,
+    const opus_int            decisionDelay,
+    const opus_int            smpl_buf_idx,
+    const opus_int            Winner_ind,
+    const opus_int32          gain,
+    const opus_int32          shift,
+    opus_int8 *const          pulses,
+    opus_int16                *pxq,
+    silk_nsq_state            *NSQ
+)
+{
+    opus_int        i, last_smple_idx;
+    const int32x2_t gain_lo_s32x2 = vdup_n_s32( silk_LSHIFT32( gain & 0x0000FFFF, 15 ) );
+    const int32x2_t gain_hi_s32x2 = vdup_n_s32( gain >> 16 );
+    const int32x4_t shift_s32x4 = vdupq_n_s32( -shift );
+    int32x4_t       t0_s32x4, t1_s32x4;
+
+    t0_s32x4 = t1_s32x4 = vdupq_n_s32( 0 ); /* initialization */
+    last_smple_idx = smpl_buf_idx + decisionDelay - 1 + DECISION_DELAY;
+    if( last_smple_idx >= DECISION_DELAY ) last_smple_idx -= DECISION_DELAY;
+    if( last_smple_idx >= DECISION_DELAY ) last_smple_idx -= DECISION_DELAY;
+
+    for( i = 0; ( i < ( decisionDelay - 7 ) ) && ( last_smple_idx >= 7 ); i += 8, last_smple_idx -= 8 ) {
+        copy_winner_state_kernel( psDelDec, i - decisionDelay, last_smple_idx, Winner_ind, gain_lo_s32x2, gain_hi_s32x2, shift_s32x4, t0_s32x4, t1_s32x4, pulses, pxq, NSQ );
+    }
+    for( ; ( i < decisionDelay ) && ( last_smple_idx >= 0 ); i++, last_smple_idx-- ) {
+        pulses[ i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDelDec->Q_Q10[ last_smple_idx ][ Winner_ind ], 10 );
+        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( psDelDec->Xq_Q14[ last_smple_idx ][ Winner_ind ], gain ), shift ) );
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDelDec->Shape_Q14[ last_smple_idx ][ Winner_ind ];
+    }
+
+    last_smple_idx += DECISION_DELAY;
+    for( ; i < ( decisionDelay - 7 ); i++, last_smple_idx-- ) {
+        copy_winner_state_kernel( psDelDec, i - decisionDelay, last_smple_idx, Winner_ind, gain_lo_s32x2, gain_hi_s32x2, shift_s32x4, t0_s32x4, t1_s32x4, pulses, pxq, NSQ );
+    }
+    for( ; i < decisionDelay; i++, last_smple_idx-- ) {
+        pulses[ i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDelDec->Q_Q10[ last_smple_idx ][ Winner_ind ], 10 );
+        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( psDelDec->Xq_Q14[ last_smple_idx ][ Winner_ind ], gain ), shift ) );
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDelDec->Shape_Q14[ last_smple_idx ][ Winner_ind ];
+    }
+}
+
+void silk_NSQ_del_dec_neon(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int16            x16[],                                      /* I    Input                           */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs              */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+)
+{
+#ifdef OPUS_CHECK_ASM
+    silk_nsq_state NSQ_c;
+    SideInfoIndices psIndices_c;
+    opus_int8 pulses_c[ MAX_FRAME_LENGTH ];
+    const opus_int8 *const pulses_a = pulses;
+
+    ( void )pulses_a;
+    silk_memcpy( &NSQ_c, NSQ, sizeof( NSQ_c ) );
+    silk_memcpy( &psIndices_c, psIndices, sizeof( psIndices_c ) );
+    silk_memcpy( pulses_c, pulses, sizeof( pulses_c ) );
+    silk_NSQ_del_dec_c( psEncC, &NSQ_c, &psIndices_c, x16, pulses_c, PredCoef_Q12, LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16,
+                       pitchL, Lambda_Q10, LTP_scale_Q14 );
+#endif
+
+    /* The optimization parallelizes the different delay decision states. */
+    if(( psEncC->nStatesDelayedDecision > NEON_MAX_DEL_DEC_STATES ) || ( psEncC->nStatesDelayedDecision <= 2 )) {
+        /* NEON intrinsics optimization now can only parallelize up to 4 delay decision states.    */
+        /* If there are more states, C function is called, and this optimization must be expanded. */
+        /* When the number of delay decision states is less than 3, there are penalties using this */
+        /* optimization, and C function is called.                                                 */
+        /* When the number of delay decision states is 2, it's better to specialize another        */
+        /* structure NSQ_del_dec2_struct and optimize with shorter NEON registers. (Low priority)  */
+        silk_NSQ_del_dec_c( psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14, AR_Q13, HarmShapeGain_Q14,
+            Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14 );
+    } else {
+        opus_int            i, k, lag, start_idx, LSF_interpolation_flag, Winner_ind, subfr;
+        opus_int            smpl_buf_idx, decisionDelay;
+        const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
+        opus_int16          *pxq;
+        VARDECL( opus_int32, sLTP_Q15 );
+        VARDECL( opus_int16, sLTP );
+        opus_int32          HarmShapeFIRPacked_Q14;
+        opus_int            offset_Q10;
+        opus_int32          RDmin_Q10, Gain_Q10;
+        VARDECL( opus_int32, x_sc_Q10 );
+        VARDECL( opus_int32, delayedGain_Q10 );
+        VARDECL( NSQ_del_decs_struct, psDelDec );
+        int32x4_t           t_s32x4;
+        SAVE_STACK;
+
+        /* Set unvoiced lag to the previous one, overwrite later for voiced */
+        lag = NSQ->lagPrev;
+
+        silk_assert( NSQ->prev_gain_Q16 != 0 );
+
+        /* Initialize delayed decision states */
+        ALLOC( psDelDec, 1, NSQ_del_decs_struct );
+        /* Only RandState and RD_Q10 need to be initialized to 0. */
+        silk_memset( psDelDec->RandState, 0, sizeof( psDelDec->RandState ) );
+        vst1q_s32( psDelDec->RD_Q10, vdupq_n_s32( 0 ) );
+
+        for( k = 0; k < psEncC->nStatesDelayedDecision; k++ ) {
+            psDelDec->SeedInit[ k ] = psDelDec->Seed[ k ] = ( k + psIndices->Seed ) & 3;
+        }
+        vst1q_s32( psDelDec->LF_AR_Q14, vld1q_dup_s32( &NSQ->sLF_AR_shp_Q14 ) );
+        vst1q_s32( psDelDec->Diff_Q14, vld1q_dup_s32( &NSQ->sDiff_shp_Q14 ) );
+        vst1q_s32( psDelDec->Shape_Q14[ 0 ], vld1q_dup_s32( &NSQ->sLTP_shp_Q14[ psEncC->ltp_mem_length - 1 ] ) );
+        for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+            vst1q_s32( psDelDec->sLPC_Q14[ i ], vld1q_dup_s32( &NSQ->sLPC_Q14[ i ] ) );
+        }
+        for( i = 0; i < (opus_int)( sizeof( NSQ->sAR2_Q14 ) / sizeof( NSQ->sAR2_Q14[ 0 ] ) ); i++ ) {
+            vst1q_s32( psDelDec->sAR2_Q14[ i ], vld1q_dup_s32( &NSQ->sAR2_Q14[ i ] ) );
+        }
+
+        offset_Q10   = silk_Quantization_Offsets_Q10[ psIndices->signalType >> 1 ][ psIndices->quantOffsetType ];
+        smpl_buf_idx = 0; /* index of oldest samples */
+
+        decisionDelay = silk_min_int( DECISION_DELAY, psEncC->subfr_length );
+
+        /* For voiced frames limit the decision delay to lower than the pitch lag */
+        if( psIndices->signalType == TYPE_VOICED ) {
+            opus_int pitch_min = pitchL[ 0 ];
+            for( k = 1; k < psEncC->nb_subfr; k++ ) {
+                pitch_min = silk_min_int( pitch_min, pitchL[ k ] );
+            }
+            decisionDelay = silk_min_int( decisionDelay, pitch_min - LTP_ORDER / 2 - 1 );
+        } else {
+            if( lag > 0 ) {
+                decisionDelay = silk_min_int( decisionDelay, lag - LTP_ORDER / 2 - 1 );
+            }
+        }
+
+        if( psIndices->NLSFInterpCoef_Q2 == 4 ) {
+            LSF_interpolation_flag = 0;
+        } else {
+            LSF_interpolation_flag = 1;
+        }
+
+        ALLOC( sLTP_Q15, psEncC->ltp_mem_length + psEncC->frame_length, opus_int32 );
+        ALLOC( sLTP, psEncC->ltp_mem_length + psEncC->frame_length, opus_int16 );
+        ALLOC( x_sc_Q10, psEncC->subfr_length, opus_int32 );
+        ALLOC( delayedGain_Q10, DECISION_DELAY, opus_int32 );
+        /* Set up pointers to start of sub frame */
+        pxq                   = &NSQ->xq[ psEncC->ltp_mem_length ];
+        NSQ->sLTP_shp_buf_idx = psEncC->ltp_mem_length;
+        NSQ->sLTP_buf_idx     = psEncC->ltp_mem_length;
+        subfr = 0;
+        for( k = 0; k < psEncC->nb_subfr; k++ ) {
+            A_Q12      = &PredCoef_Q12[ ( ( k >> 1 ) | ( 1 - LSF_interpolation_flag ) ) * MAX_LPC_ORDER ];
+            B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER           ];
+            AR_shp_Q13 = &AR_Q13[     k * MAX_SHAPE_LPC_ORDER ];
+
+            /* Noise shape parameters */
+            silk_assert( HarmShapeGain_Q14[ k ] >= 0 );
+            HarmShapeFIRPacked_Q14  =                          silk_RSHIFT( HarmShapeGain_Q14[ k ], 2 );
+            HarmShapeFIRPacked_Q14 |= silk_LSHIFT( (opus_int32)silk_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );
+
+            NSQ->rewhite_flag = 0;
+            if( psIndices->signalType == TYPE_VOICED ) {
+                /* Voiced */
+                lag = pitchL[ k ];
+
+                /* Re-whitening */
+                if( ( k & ( 3 - silk_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {
+                    if( k == 2 ) {
+                        /* RESET DELAYED DECISIONS */
+                        /* Find winner */
+                        int32x4_t RD_Q10_s32x4;
+                        RDmin_Q10 = psDelDec->RD_Q10[ 0 ];
+                        Winner_ind = 0;
+                        for( i = 1; i < psEncC->nStatesDelayedDecision; i++ ) {
+                            if( psDelDec->RD_Q10[ i ] < RDmin_Q10 ) {
+                                RDmin_Q10 = psDelDec->RD_Q10[ i ];
+                                Winner_ind = i;
+                            }
+                        }
+                        psDelDec->RD_Q10[ Winner_ind ] -= ( silk_int32_MAX >> 4 );
+                        RD_Q10_s32x4 = vld1q_s32( psDelDec->RD_Q10 );
+                        RD_Q10_s32x4 = vaddq_s32( RD_Q10_s32x4, vdupq_n_s32( silk_int32_MAX >> 4 ) );
+                        vst1q_s32( psDelDec->RD_Q10, RD_Q10_s32x4 );
+
+                        /* Copy final part of signals from winner state to output and long-term filter states */
+                        copy_winner_state( psDelDec, decisionDelay, smpl_buf_idx, Winner_ind, Gains_Q16[ 1 ], 14, pulses, pxq, NSQ );
+
+                        subfr = 0;
+                    }
+
+                    /* Rewhiten with new A coefs */
+                    start_idx = psEncC->ltp_mem_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;
+                    silk_assert( start_idx > 0 );
+
+                    silk_LPC_analysis_filter( &sLTP[ start_idx ], &NSQ->xq[ start_idx + k * psEncC->subfr_length ],
+                        A_Q12, psEncC->ltp_mem_length - start_idx, psEncC->predictLPCOrder, psEncC->arch );
+
+                    NSQ->sLTP_buf_idx = psEncC->ltp_mem_length;
+                    NSQ->rewhite_flag = 1;
+                }
+            }
+
+            silk_nsq_del_dec_scale_states_neon( psEncC, NSQ, psDelDec, x16, x_sc_Q10, sLTP, sLTP_Q15, k,
+                LTP_scale_Q14, Gains_Q16, pitchL, psIndices->signalType, decisionDelay );
+
+            silk_noise_shape_quantizer_del_dec_neon( NSQ, psDelDec, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15,
+                delayedGain_Q10, A_Q12, B_Q14, AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ],
+                Gains_Q16[ k ], Lambda_Q10, offset_Q10, psEncC->subfr_length, subfr++, psEncC->shapingLPCOrder,
+                psEncC->predictLPCOrder, psEncC->warping_Q16, psEncC->nStatesDelayedDecision, &smpl_buf_idx, decisionDelay );
+
+            x16    += psEncC->subfr_length;
+            pulses += psEncC->subfr_length;
+            pxq    += psEncC->subfr_length;
+        }
+
+        /* Find winner */
+        RDmin_Q10 = psDelDec->RD_Q10[ 0 ];
+        Winner_ind = 0;
+        for( k = 1; k < psEncC->nStatesDelayedDecision; k++ ) {
+            if( psDelDec->RD_Q10[ k ] < RDmin_Q10 ) {
+                RDmin_Q10 = psDelDec->RD_Q10[ k ];
+                Winner_ind = k;
+            }
+        }
+
+        /* Copy final part of signals from winner state to output and long-term filter states */
+        psIndices->Seed = psDelDec->SeedInit[ Winner_ind ];
+        Gain_Q10 = silk_RSHIFT32( Gains_Q16[ psEncC->nb_subfr - 1 ], 6 );
+        copy_winner_state( psDelDec, decisionDelay, smpl_buf_idx, Winner_ind, Gain_Q10, 8, pulses, pxq, NSQ );
+
+        t_s32x4 = vdupq_n_s32( 0 ); /* initialization */
+        for( i = 0; i < ( NSQ_LPC_BUF_LENGTH - 3 ); i += 4 ) {
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sLPC_Q14[ i + 0 ][ Winner_ind ], t_s32x4, 0 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sLPC_Q14[ i + 1 ][ Winner_ind ], t_s32x4, 1 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sLPC_Q14[ i + 2 ][ Winner_ind ], t_s32x4, 2 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sLPC_Q14[ i + 3 ][ Winner_ind ], t_s32x4, 3 );
+            vst1q_s32( &NSQ->sLPC_Q14[ i ], t_s32x4 );
+        }
+
+        for( ; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+          NSQ->sLPC_Q14[ i ] = psDelDec->sLPC_Q14[ i ][ Winner_ind ];
+        }
+
+        for( i = 0; i < (opus_int)( sizeof( NSQ->sAR2_Q14 ) / sizeof( NSQ->sAR2_Q14[ 0 ] ) - 3 ); i += 4 ) {
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sAR2_Q14[ i + 0 ][ Winner_ind ], t_s32x4, 0 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sAR2_Q14[ i + 1 ][ Winner_ind ], t_s32x4, 1 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sAR2_Q14[ i + 2 ][ Winner_ind ], t_s32x4, 2 );
+            t_s32x4 = vld1q_lane_s32( &psDelDec->sAR2_Q14[ i + 3 ][ Winner_ind ], t_s32x4, 3 );
+            vst1q_s32( &NSQ->sAR2_Q14[ i ], t_s32x4 );
+        }
+
+        for( ; i < (opus_int)( sizeof( NSQ->sAR2_Q14 ) / sizeof( NSQ->sAR2_Q14[ 0 ] ) ); i++ ) {
+          NSQ->sAR2_Q14[ i ] = psDelDec->sAR2_Q14[ i ][ Winner_ind ];
+        }
+
+        /* Update states */
+        NSQ->sLF_AR_shp_Q14 = psDelDec->LF_AR_Q14[ Winner_ind ];
+        NSQ->sDiff_shp_Q14  = psDelDec->Diff_Q14[ Winner_ind ];
+        NSQ->lagPrev        = pitchL[ psEncC->nb_subfr - 1 ];
+
+        /* Save quantized speech signal */
+        silk_memmove( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int16 ) );
+        silk_memmove( NSQ->sLTP_shp_Q14, &NSQ->sLTP_shp_Q14[ psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int32 ) );
+        RESTORE_STACK;
+    }
+
+#ifdef OPUS_CHECK_ASM
+    silk_assert( !memcmp( &NSQ_c, NSQ, sizeof( NSQ_c ) ) );
+    silk_assert( !memcmp( &psIndices_c, psIndices, sizeof( psIndices_c ) ) );
+    silk_assert( !memcmp( pulses_c, pulses_a, sizeof( pulses_c ) ) );
+#endif
+}
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+/* Note: Function silk_short_prediction_create_arch_coef_neon() defined in NSQ_neon.h is actually a hacking C function. */
+/*       Therefore here we append "_local" to the NEON function name to avoid confusion.                                */
+static OPUS_INLINE void silk_short_prediction_create_arch_coef_neon_local(opus_int32 *out, const opus_int16 *in, opus_int order)
+{
+  int16x8_t t_s16x8;
+  int32x4_t t0_s32x4, t1_s32x4, t2_s32x4, t3_s32x4;
+  silk_assert( order == 10 || order == 16 );
+
+  t_s16x8 = vld1q_s16( in + 0 );                                                   /* 7 6 5 4  3 2 1 0    */
+  t_s16x8 = vrev64q_s16( t_s16x8 );                                                /* 4 5 6 7  0 1 2 3    */
+  t2_s32x4 = vshll_n_s16( vget_high_s16( t_s16x8 ), 15 );                          /* 4 5 6 7             */
+  t3_s32x4 = vshll_n_s16( vget_low_s16(  t_s16x8 ), 15 );                          /* 0 1 2 3             */
+
+  if( order == 16 ) {
+      t_s16x8 = vld1q_s16( in + 8 );                                               /* F E D C  B A 9 8    */
+      t_s16x8 = vrev64q_s16( t_s16x8 );                                            /* C D E F  8 9 A B    */
+      t0_s32x4 = vshll_n_s16( vget_high_s16( t_s16x8 ), 15 );                      /* C D E F             */
+      t1_s32x4 = vshll_n_s16( vget_low_s16(  t_s16x8 ), 15 );                      /* 8 9 A B             */
+  } else {
+      int16x4_t t_s16x4;
+
+      t0_s32x4 = vdupq_n_s32( 0 );                                                 /* zero zero zero zero */
+      t_s16x4 = vld1_s16( in + 6 );                                                /* 9    8    7    6    */
+      t_s16x4 = vrev64_s16( t_s16x4 );                                             /* 6    7    8    9    */
+      t1_s32x4 = vshll_n_s16( t_s16x4, 15 );
+      t1_s32x4 = vcombine_s32( vget_low_s32(t0_s32x4), vget_low_s32( t1_s32x4 ) ); /* 8    9    zero zero */
+  }
+  vst1q_s32( out +  0, t0_s32x4 );
+  vst1q_s32( out +  4, t1_s32x4 );
+  vst1q_s32( out +  8, t2_s32x4 );
+  vst1q_s32( out + 12, t3_s32x4 );
+}
+
+static OPUS_INLINE int32x4_t silk_SMLAWB_lane0_neon(
+    const int32x4_t out_s32x4,
+    const int32x4_t in_s32x4,
+    const int32x2_t coef_s32x2
+)
+{
+    return vaddq_s32( out_s32x4, vqdmulhq_lane_s32( in_s32x4, coef_s32x2, 0 ) );
+}
+
+static OPUS_INLINE int32x4_t silk_SMLAWB_lane1_neon(
+    const int32x4_t out_s32x4,
+    const int32x4_t in_s32x4,
+    const int32x2_t coef_s32x2
+)
+{
+    return vaddq_s32( out_s32x4, vqdmulhq_lane_s32( in_s32x4, coef_s32x2, 1 ) );
+}
+
+/* Note: This function has different return value than silk_noise_shape_quantizer_short_prediction_neon(). */
+/*       Therefore here we append "_local" to the function name to avoid confusion.                        */
+static OPUS_INLINE int32x4_t silk_noise_shape_quantizer_short_prediction_neon_local(const opus_int32 *buf32, const opus_int32 *a_Q12_arch, opus_int order)
+{
+    const int32x4_t a_Q12_arch0_s32x4 = vld1q_s32( a_Q12_arch + 0 );
+    const int32x4_t a_Q12_arch1_s32x4 = vld1q_s32( a_Q12_arch + 4 );
+    const int32x4_t a_Q12_arch2_s32x4 = vld1q_s32( a_Q12_arch + 8 );
+    const int32x4_t a_Q12_arch3_s32x4 = vld1q_s32( a_Q12_arch + 12 );
+    int32x4_t LPC_pred_Q14_s32x4;
+
+    silk_assert( order == 10 || order == 16 );
+    /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+    LPC_pred_Q14_s32x4 = vdupq_n_s32( silk_RSHIFT( order, 1 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  0 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch0_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  1 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch0_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  2 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch0_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  3 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch0_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  4 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch1_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  5 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch1_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  6 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch1_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  7 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch1_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  8 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch2_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 +  9 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch2_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 10 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch2_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 11 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch2_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 12 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch3_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 13 * NEON_MAX_DEL_DEC_STATES ), vget_low_s32(  a_Q12_arch3_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane0_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 14 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch3_s32x4 ) );
+    LPC_pred_Q14_s32x4 = silk_SMLAWB_lane1_neon( LPC_pred_Q14_s32x4, vld1q_s32( buf32 + 15 * NEON_MAX_DEL_DEC_STATES ), vget_high_s32( a_Q12_arch3_s32x4 ) );
+
+    return LPC_pred_Q14_s32x4;
+}
+
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec_neon(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_decs_struct psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay           /* I                                        */
+)
+{
+    opus_int     i, j, k, Winner_ind, RDmin_ind, RDmax_ind, last_smple_idx;
+    opus_int32   Winner_rand_state;
+    opus_int32   LTP_pred_Q14, n_LTP_Q14;
+    opus_int32   RDmin_Q10, RDmax_Q10;
+    opus_int32   Gain_Q10;
+    opus_int32   *pred_lag_ptr, *shp_lag_ptr;
+    opus_int32   a_Q12_arch[MAX_LPC_ORDER];
+    const int32x2_t warping_Q16_s32x2 = vdup_n_s32( silk_LSHIFT32( warping_Q16, 16 ) >> 1 );
+    const opus_int32 LF_shp_Q29 = silk_LSHIFT32( LF_shp_Q14, 16 ) >> 1;
+    opus_int32 AR_shp_Q28[ MAX_SHAPE_LPC_ORDER ];
+    const uint32x4_t rand_multiplier_u32x4 = vdupq_n_u32( RAND_MULTIPLIER );
+    const uint32x4_t rand_increment_u32x4 = vdupq_n_u32( RAND_INCREMENT );
+
+    VARDECL( NSQ_samples_struct, psSampleState );
+    SAVE_STACK;
+
+    silk_assert( nStatesDelayedDecision > 0 );
+    silk_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */
+    ALLOC( psSampleState, 2, NSQ_samples_struct );
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+    for( i = 0; i < ( MAX_SHAPE_LPC_ORDER - 7 ); i += 8 ) {
+      const int16x8_t t_s16x8 = vld1q_s16( AR_shp_Q13 +  i );
+      vst1q_s32( AR_shp_Q28 + i + 0, vshll_n_s16( vget_low_s16(  t_s16x8 ), 15 ) );
+      vst1q_s32( AR_shp_Q28 + i + 4, vshll_n_s16( vget_high_s16( t_s16x8 ), 15 ) );
+    }
+
+    for( ; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+      AR_shp_Q28[i] = silk_LSHIFT32( AR_shp_Q13[i], 15 );
+    }
+
+    silk_short_prediction_create_arch_coef_neon_local( a_Q12_arch, a_Q12, predictLPCOrder );
+
+    for( i = 0; i < length; i++ ) {
+        int32x4_t Seed_s32x4, LPC_pred_Q14_s32x4;
+        int32x4_t sign_s32x4, tmp1_s32x4, tmp2_s32x4;
+        int32x4_t n_AR_Q14_s32x4, n_LF_Q14_s32x4;
+        int32x2_t AR_shp_Q28_s32x2;
+        int16x4_t r_Q10_s16x4, rr_Q10_s16x4;
+
+        /* Perform common calculations used in all states */
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q14 = 2;
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[  0 ], b_Q14[ 0 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], b_Q14[ 1 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], b_Q14[ 2 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], b_Q14[ 3 ] );
+            LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );
+            LTP_pred_Q14 = silk_LSHIFT( LTP_pred_Q14, 1 );                          /* Q13 -> Q14 */
+            pred_lag_ptr++;
+        } else {
+            LTP_pred_Q14 = 0;
+        }
+
+        /* Long-term shaping */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q14 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SUB_LSHIFT32( LTP_pred_Q14, n_LTP_Q14, 2 );            /* Q12 -> Q14 */
+            shp_lag_ptr++;
+        } else {
+            n_LTP_Q14 = 0;
+        }
+
+        /* Generate dither */
+        Seed_s32x4 = vld1q_s32( psDelDec->Seed );
+        Seed_s32x4 = vreinterpretq_s32_u32( vmlaq_u32( rand_increment_u32x4, vreinterpretq_u32_s32( Seed_s32x4 ), rand_multiplier_u32x4 ) );
+        vst1q_s32( psDelDec->Seed, Seed_s32x4 );
+
+        /* Short-term prediction */
+        LPC_pred_Q14_s32x4 = silk_noise_shape_quantizer_short_prediction_neon_local(psDelDec->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 16 + i ], a_Q12_arch, predictLPCOrder);
+        LPC_pred_Q14_s32x4 = vshlq_n_s32( LPC_pred_Q14_s32x4, 4 ); /* Q10 -> Q14 */
+
+        /* Noise shape feedback */
+        /* Output of lowpass section */
+        tmp2_s32x4 = silk_SMLAWB_lane0_neon( vld1q_s32( psDelDec->Diff_Q14 ), vld1q_s32( psDelDec->sAR2_Q14[ 0 ] ), warping_Q16_s32x2 );
+        /* Output of allpass section */
+        tmp1_s32x4 = vsubq_s32( vld1q_s32( psDelDec->sAR2_Q14[ 1 ] ), tmp2_s32x4 );
+        tmp1_s32x4 = silk_SMLAWB_lane0_neon( vld1q_s32( psDelDec->sAR2_Q14[ 0 ] ), tmp1_s32x4, warping_Q16_s32x2 );
+        vst1q_s32( psDelDec->sAR2_Q14[ 0 ], tmp2_s32x4 );
+        AR_shp_Q28_s32x2 = vld1_s32( AR_shp_Q28 );
+        n_AR_Q14_s32x4 = vaddq_s32( vdupq_n_s32( silk_RSHIFT( shapingLPCOrder, 1 ) ), vqdmulhq_lane_s32( tmp2_s32x4, AR_shp_Q28_s32x2, 0 ) );
+
+        /* Loop over allpass sections */
+        for( j = 2; j < shapingLPCOrder; j += 2 ) {
+            /* Output of allpass section */
+            tmp2_s32x4 = vsubq_s32( vld1q_s32( psDelDec->sAR2_Q14[ j + 0 ] ), tmp1_s32x4 );
+            tmp2_s32x4 = silk_SMLAWB_lane0_neon( vld1q_s32( psDelDec->sAR2_Q14[ j - 1 ] ), tmp2_s32x4, warping_Q16_s32x2 );
+            vst1q_s32( psDelDec->sAR2_Q14[ j - 1 ], tmp1_s32x4 );
+            n_AR_Q14_s32x4 = vaddq_s32( n_AR_Q14_s32x4, vqdmulhq_lane_s32( tmp1_s32x4, AR_shp_Q28_s32x2, 1 ) );
+            /* Output of allpass section */
+            tmp1_s32x4 = vsubq_s32( vld1q_s32( psDelDec->sAR2_Q14[ j + 1 ] ), tmp2_s32x4 );
+            tmp1_s32x4 = silk_SMLAWB_lane0_neon( vld1q_s32( psDelDec->sAR2_Q14[ j + 0 ] ), tmp1_s32x4, warping_Q16_s32x2 );
+            vst1q_s32( psDelDec->sAR2_Q14[ j + 0 ], tmp2_s32x4 );
+            AR_shp_Q28_s32x2 = vld1_s32( &AR_shp_Q28[ j ] );
+            n_AR_Q14_s32x4 = vaddq_s32( n_AR_Q14_s32x4, vqdmulhq_lane_s32( tmp2_s32x4, AR_shp_Q28_s32x2, 0 ) );
+        }
+        vst1q_s32( psDelDec->sAR2_Q14[ shapingLPCOrder - 1 ], tmp1_s32x4 );
+        n_AR_Q14_s32x4 = vaddq_s32( n_AR_Q14_s32x4, vqdmulhq_lane_s32( tmp1_s32x4, AR_shp_Q28_s32x2, 1 ) );
+        n_AR_Q14_s32x4 = vshlq_n_s32( n_AR_Q14_s32x4, 1 );                                                                                        /* Q11 -> Q12 */
+        n_AR_Q14_s32x4 = vaddq_s32( n_AR_Q14_s32x4, vqdmulhq_n_s32( vld1q_s32( psDelDec->LF_AR_Q14 ), silk_LSHIFT32( Tilt_Q14, 16 ) >> 1 ) );     /* Q12 */
+        n_AR_Q14_s32x4 = vshlq_n_s32( n_AR_Q14_s32x4, 2 );                                                                                        /* Q12 -> Q14 */
+        n_LF_Q14_s32x4 = vqdmulhq_n_s32( vld1q_s32( psDelDec->Shape_Q14[ *smpl_buf_idx ] ), LF_shp_Q29 );                                         /* Q12 */
+        n_LF_Q14_s32x4 = vaddq_s32( n_LF_Q14_s32x4, vqdmulhq_n_s32( vld1q_s32( psDelDec->LF_AR_Q14 ), silk_LSHIFT32( LF_shp_Q14 >> 16 , 15 ) ) ); /* Q12 */
+        n_LF_Q14_s32x4 = vshlq_n_s32( n_LF_Q14_s32x4, 2 );                                                                                        /* Q12 -> Q14 */
+
+        /* Input minus prediction plus noise feedback                       */
+        /* r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP  */
+        tmp1_s32x4 = vaddq_s32( n_AR_Q14_s32x4, n_LF_Q14_s32x4 );               /* Q14 */
+        tmp2_s32x4 = vaddq_s32( vdupq_n_s32( n_LTP_Q14 ), LPC_pred_Q14_s32x4 ); /* Q13 */
+        tmp1_s32x4 = vsubq_s32( tmp2_s32x4, tmp1_s32x4 );                       /* Q13 */
+        tmp1_s32x4 = vrshrq_n_s32( tmp1_s32x4, 4 );                             /* Q10 */
+        tmp1_s32x4 = vsubq_s32( vdupq_n_s32( x_Q10[ i ] ), tmp1_s32x4 );        /* residual error Q10 */
+
+        /* Flip sign depending on dither */
+        sign_s32x4 = vreinterpretq_s32_u32( vcltq_s32( Seed_s32x4, vdupq_n_s32( 0 ) ) );
+        tmp1_s32x4 = veorq_s32( tmp1_s32x4, sign_s32x4 );
+        tmp1_s32x4 = vsubq_s32( tmp1_s32x4, sign_s32x4 );
+        tmp1_s32x4 = vmaxq_s32( tmp1_s32x4, vdupq_n_s32( -( 31 << 10 ) ) );
+        tmp1_s32x4 = vminq_s32( tmp1_s32x4, vdupq_n_s32( 30 << 10 ) );
+        r_Q10_s16x4 = vmovn_s32( tmp1_s32x4 );
+
+        /* Find two quantization level candidates and measure their rate-distortion */
+        {
+            int16x4_t q1_Q10_s16x4 = vsub_s16( r_Q10_s16x4, vdup_n_s16( offset_Q10 ) );
+            int16x4_t q1_Q0_s16x4 = vshr_n_s16( q1_Q10_s16x4, 10 );
+            int16x4_t q2_Q10_s16x4;
+            int32x4_t rd1_Q10_s32x4, rd2_Q10_s32x4;
+            uint32x4_t t_u32x4;
+
+            if( Lambda_Q10 > 2048 ) {
+                /* For aggressive RDO, the bias becomes more than one pulse. */
+                const int rdo_offset = Lambda_Q10/2 - 512;
+                const uint16x4_t greaterThanRdo = vcgt_s16( q1_Q10_s16x4, vdup_n_s16( rdo_offset ) );
+                const uint16x4_t lessThanMinusRdo = vclt_s16( q1_Q10_s16x4, vdup_n_s16( -rdo_offset ) );
+                /* If Lambda_Q10 > 32767, then q1_Q0, q1_Q10 and q2_Q10 must change to 32-bit. */
+                silk_assert( Lambda_Q10 <= 32767 );
+
+                q1_Q0_s16x4 = vreinterpret_s16_u16( vclt_s16( q1_Q10_s16x4, vdup_n_s16( 0 ) ) );
+                q1_Q0_s16x4 = vbsl_s16( greaterThanRdo, vsub_s16( q1_Q10_s16x4, vdup_n_s16( rdo_offset ) ), q1_Q0_s16x4 );
+                q1_Q0_s16x4 = vbsl_s16( lessThanMinusRdo, vadd_s16( q1_Q10_s16x4, vdup_n_s16( rdo_offset ) ), q1_Q0_s16x4 );
+                q1_Q0_s16x4 = vshr_n_s16( q1_Q0_s16x4, 10 );
+            }
+            {
+                const uint16x4_t equal0_u16x4 = vceq_s16( q1_Q0_s16x4, vdup_n_s16( 0 ) );
+                const uint16x4_t equalMinus1_u16x4 = vceq_s16( q1_Q0_s16x4, vdup_n_s16( -1 ) );
+                const uint16x4_t lessThanMinus1_u16x4 = vclt_s16( q1_Q0_s16x4, vdup_n_s16( -1 ) );
+                int16x4_t tmp1_s16x4, tmp2_s16x4;
+
+                q1_Q10_s16x4 = vshl_n_s16( q1_Q0_s16x4, 10 );
+                tmp1_s16x4 = vadd_s16( q1_Q10_s16x4, vdup_n_s16( offset_Q10 - QUANT_LEVEL_ADJUST_Q10 ) );
+                q1_Q10_s16x4 = vadd_s16( q1_Q10_s16x4, vdup_n_s16( offset_Q10 + QUANT_LEVEL_ADJUST_Q10 ) );
+                q1_Q10_s16x4 = vbsl_s16( lessThanMinus1_u16x4, q1_Q10_s16x4, tmp1_s16x4 );
+                q1_Q10_s16x4 = vbsl_s16( equal0_u16x4, vdup_n_s16( offset_Q10 ), q1_Q10_s16x4 );
+                q1_Q10_s16x4 = vbsl_s16( equalMinus1_u16x4, vdup_n_s16( offset_Q10 - ( 1024 - QUANT_LEVEL_ADJUST_Q10 ) ), q1_Q10_s16x4 );
+                q2_Q10_s16x4 = vadd_s16( q1_Q10_s16x4, vdup_n_s16( 1024 ) );
+                q2_Q10_s16x4 = vbsl_s16( equal0_u16x4, vdup_n_s16( offset_Q10 + 1024 - QUANT_LEVEL_ADJUST_Q10 ), q2_Q10_s16x4 );
+                q2_Q10_s16x4 = vbsl_s16( equalMinus1_u16x4, vdup_n_s16( offset_Q10 ), q2_Q10_s16x4 );
+                tmp1_s16x4 = q1_Q10_s16x4;
+                tmp2_s16x4 = q2_Q10_s16x4;
+                tmp1_s16x4 = vbsl_s16( vorr_u16( equalMinus1_u16x4, lessThanMinus1_u16x4 ), vneg_s16( tmp1_s16x4 ), tmp1_s16x4 );
+                tmp2_s16x4 = vbsl_s16( lessThanMinus1_u16x4, vneg_s16( tmp2_s16x4 ), tmp2_s16x4 );
+                rd1_Q10_s32x4 = vmull_s16( tmp1_s16x4, vdup_n_s16( Lambda_Q10 ) );
+                rd2_Q10_s32x4 = vmull_s16( tmp2_s16x4, vdup_n_s16( Lambda_Q10 ) );
+            }
+
+            rr_Q10_s16x4 = vsub_s16( r_Q10_s16x4, q1_Q10_s16x4 );
+            rd1_Q10_s32x4 = vmlal_s16( rd1_Q10_s32x4, rr_Q10_s16x4, rr_Q10_s16x4 );
+            rd1_Q10_s32x4 = vshrq_n_s32( rd1_Q10_s32x4, 10 );
+
+            rr_Q10_s16x4 = vsub_s16( r_Q10_s16x4, q2_Q10_s16x4 );
+            rd2_Q10_s32x4 = vmlal_s16( rd2_Q10_s32x4, rr_Q10_s16x4, rr_Q10_s16x4 );
+            rd2_Q10_s32x4 = vshrq_n_s32( rd2_Q10_s32x4, 10 );
+
+            tmp2_s32x4 = vld1q_s32( psDelDec->RD_Q10 );
+            tmp1_s32x4 = vaddq_s32( tmp2_s32x4, vminq_s32( rd1_Q10_s32x4, rd2_Q10_s32x4 ) );
+            tmp2_s32x4 = vaddq_s32( tmp2_s32x4, vmaxq_s32( rd1_Q10_s32x4, rd2_Q10_s32x4 ) );
+            vst1q_s32( psSampleState[ 0 ].RD_Q10, tmp1_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].RD_Q10, tmp2_s32x4 );
+            t_u32x4 = vcltq_s32( rd1_Q10_s32x4, rd2_Q10_s32x4 );
+            tmp1_s32x4 = vbslq_s32( t_u32x4, vmovl_s16( q1_Q10_s16x4 ), vmovl_s16( q2_Q10_s16x4 ) );
+            tmp2_s32x4 = vbslq_s32( t_u32x4, vmovl_s16( q2_Q10_s16x4 ), vmovl_s16( q1_Q10_s16x4 ) );
+            vst1q_s32( psSampleState[ 0 ].Q_Q10, tmp1_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].Q_Q10, tmp2_s32x4 );
+        }
+
+        {
+            /* Update states for best quantization */
+            int32x4_t exc_Q14_s32x4, LPC_exc_Q14_s32x4, xq_Q14_s32x4, sLF_AR_shp_Q14_s32x4;
+
+            /* Quantized excitation */
+            exc_Q14_s32x4 = vshlq_n_s32( tmp1_s32x4, 4 );
+            exc_Q14_s32x4 = veorq_s32( exc_Q14_s32x4, sign_s32x4 );
+            exc_Q14_s32x4 = vsubq_s32( exc_Q14_s32x4, sign_s32x4 );
+
+            /* Add predictions */
+            LPC_exc_Q14_s32x4 = vaddq_s32( exc_Q14_s32x4, vdupq_n_s32( LTP_pred_Q14 ) );
+            xq_Q14_s32x4      = vaddq_s32( LPC_exc_Q14_s32x4, LPC_pred_Q14_s32x4 );
+
+            /* Update states */
+            tmp1_s32x4 = vsubq_s32( xq_Q14_s32x4, vshlq_n_s32( vdupq_n_s32( x_Q10[ i ] ), 4 ) );
+            vst1q_s32( psSampleState[ 0 ].Diff_Q14, tmp1_s32x4 );
+            sLF_AR_shp_Q14_s32x4 = vsubq_s32( tmp1_s32x4, n_AR_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 0 ].sLTP_shp_Q14, vsubq_s32( sLF_AR_shp_Q14_s32x4, n_LF_Q14_s32x4 ) );
+            vst1q_s32( psSampleState[ 0 ].LF_AR_Q14, sLF_AR_shp_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 0 ].LPC_exc_Q14, LPC_exc_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 0 ].xq_Q14, xq_Q14_s32x4 );
+
+            /* Quantized excitation */
+            exc_Q14_s32x4 = vshlq_n_s32( tmp2_s32x4, 4 );
+            exc_Q14_s32x4 = veorq_s32( exc_Q14_s32x4, sign_s32x4 );
+            exc_Q14_s32x4 = vsubq_s32( exc_Q14_s32x4, sign_s32x4 );
+
+            /* Add predictions */
+            LPC_exc_Q14_s32x4 = vaddq_s32( exc_Q14_s32x4, vdupq_n_s32( LTP_pred_Q14 ) );
+            xq_Q14_s32x4      = vaddq_s32( LPC_exc_Q14_s32x4, LPC_pred_Q14_s32x4 );
+
+            /* Update states */
+            tmp1_s32x4 = vsubq_s32( xq_Q14_s32x4, vshlq_n_s32( vdupq_n_s32( x_Q10[ i ] ), 4 ) );
+            vst1q_s32( psSampleState[ 1 ].Diff_Q14, tmp1_s32x4 );
+            sLF_AR_shp_Q14_s32x4 = vsubq_s32( tmp1_s32x4, n_AR_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].sLTP_shp_Q14, vsubq_s32( sLF_AR_shp_Q14_s32x4, n_LF_Q14_s32x4 ) );
+            vst1q_s32( psSampleState[ 1 ].LF_AR_Q14, sLF_AR_shp_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].LPC_exc_Q14, LPC_exc_Q14_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].xq_Q14, xq_Q14_s32x4 );
+        }
+
+        *smpl_buf_idx = *smpl_buf_idx ? ( *smpl_buf_idx - 1 ) : ( DECISION_DELAY - 1);
+        last_smple_idx = *smpl_buf_idx + decisionDelay + DECISION_DELAY;
+        if( last_smple_idx >= DECISION_DELAY ) last_smple_idx -= DECISION_DELAY;
+        if( last_smple_idx >= DECISION_DELAY ) last_smple_idx -= DECISION_DELAY;
+
+        /* Find winner */
+        RDmin_Q10 = psSampleState[ 0 ].RD_Q10[ 0 ];
+        Winner_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            if( psSampleState[ 0 ].RD_Q10[ k ] < RDmin_Q10 ) {
+                RDmin_Q10 = psSampleState[ 0 ].RD_Q10[ k ];
+                Winner_ind = k;
+            }
+        }
+
+        /* Increase RD values of expired states */
+        {
+            uint32x4_t t_u32x4;
+            Winner_rand_state = psDelDec->RandState[ last_smple_idx ][ Winner_ind ];
+            t_u32x4 = vceqq_s32( vld1q_s32( psDelDec->RandState[ last_smple_idx ] ), vdupq_n_s32( Winner_rand_state ) );
+            t_u32x4 = vmvnq_u32( t_u32x4 );
+            t_u32x4 = vshrq_n_u32( t_u32x4, 5 );
+            tmp1_s32x4 = vld1q_s32( psSampleState[ 0 ].RD_Q10 );
+            tmp2_s32x4 = vld1q_s32( psSampleState[ 1 ].RD_Q10 );
+            tmp1_s32x4 = vaddq_s32( tmp1_s32x4, vreinterpretq_s32_u32( t_u32x4 ) );
+            tmp2_s32x4 = vaddq_s32( tmp2_s32x4, vreinterpretq_s32_u32( t_u32x4 ) );
+            vst1q_s32( psSampleState[ 0 ].RD_Q10, tmp1_s32x4 );
+            vst1q_s32( psSampleState[ 1 ].RD_Q10, tmp2_s32x4 );
+
+            /* Find worst in first set and best in second set */
+            RDmax_Q10 = psSampleState[ 0 ].RD_Q10[ 0 ];
+            RDmin_Q10 = psSampleState[ 1 ].RD_Q10[ 0 ];
+            RDmax_ind = 0;
+            RDmin_ind = 0;
+            for( k = 1; k < nStatesDelayedDecision; k++ ) {
+                /* find worst in first set */
+                if( psSampleState[ 0 ].RD_Q10[ k ] > RDmax_Q10 ) {
+                    RDmax_Q10 = psSampleState[ 0 ].RD_Q10[ k ];
+                    RDmax_ind = k;
+                }
+                /* find best in second set */
+                if( psSampleState[ 1 ].RD_Q10[ k ] < RDmin_Q10 ) {
+                    RDmin_Q10 = psSampleState[ 1 ].RD_Q10[ k ];
+                    RDmin_ind = k;
+                }
+            }
+        }
+
+        /* Replace a state if best from second set outperforms worst in first set */
+        if( RDmin_Q10 < RDmax_Q10 ) {
+            opus_int32 (*ptr)[NEON_MAX_DEL_DEC_STATES] = psDelDec->RandState;
+            const int numOthers = (int)( ( sizeof( NSQ_del_decs_struct ) - sizeof( ( (NSQ_del_decs_struct *)0 )->sLPC_Q14 ) )
+                / ( NEON_MAX_DEL_DEC_STATES * sizeof( opus_int32 ) ) );
+            /* Only ( predictLPCOrder - 1 ) of sLPC_Q14 buffer need to be updated, though the first several     */
+            /* useless sLPC_Q14[] will be different comparing with C when predictLPCOrder < NSQ_LPC_BUF_LENGTH. */
+            /* Here just update constant ( NSQ_LPC_BUF_LENGTH - 1 ) for simplicity.                             */
+            for( j = i + 1; j < i + NSQ_LPC_BUF_LENGTH; j++ ) {
+                psDelDec->sLPC_Q14[ j ][ RDmax_ind ] = psDelDec->sLPC_Q14[ j ][ RDmin_ind ];
+            }
+            for( j = 0; j < numOthers; j++ ) {
+                ptr[ j ][ RDmax_ind ] = ptr[ j ][ RDmin_ind ];
+            }
+
+            psSampleState[ 0 ].Q_Q10[ RDmax_ind ] = psSampleState[ 1 ].Q_Q10[ RDmin_ind ];
+            psSampleState[ 0 ].RD_Q10[ RDmax_ind ] = psSampleState[ 1 ].RD_Q10[ RDmin_ind ];
+            psSampleState[ 0 ].xq_Q14[ RDmax_ind ] = psSampleState[ 1 ].xq_Q14[ RDmin_ind ];
+            psSampleState[ 0 ].LF_AR_Q14[ RDmax_ind ] = psSampleState[ 1 ].LF_AR_Q14[ RDmin_ind ];
+            psSampleState[ 0 ].Diff_Q14[ RDmax_ind ] = psSampleState[ 1 ].Diff_Q14[ RDmin_ind ];
+            psSampleState[ 0 ].sLTP_shp_Q14[ RDmax_ind ] = psSampleState[ 1 ].sLTP_shp_Q14[ RDmin_ind ];
+            psSampleState[ 0 ].LPC_exc_Q14[ RDmax_ind ] = psSampleState[ 1 ].LPC_exc_Q14[ RDmin_ind ];
+        }
+
+        /* Write samples from winner to output and long-term filter states */
+        if( subfr > 0 || i >= decisionDelay ) {
+            pulses[  i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDelDec->Q_Q10[ last_smple_idx ][ Winner_ind ], 10 );
+            xq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                silk_SMULWW( psDelDec->Xq_Q14[ last_smple_idx ][ Winner_ind ], delayedGain_Q10[ last_smple_idx ] ), 8 ) );
+            NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay ] = psDelDec->Shape_Q14[ last_smple_idx ][ Winner_ind ];
+            sLTP_Q15[          NSQ->sLTP_buf_idx     - decisionDelay ] = psDelDec->Pred_Q15[  last_smple_idx ][ Winner_ind ];
+        }
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Update states */
+        vst1q_s32( psDelDec->LF_AR_Q14, vld1q_s32( psSampleState[ 0 ].LF_AR_Q14 ) );
+        vst1q_s32( psDelDec->Diff_Q14, vld1q_s32( psSampleState[ 0 ].Diff_Q14 ) );
+        vst1q_s32( psDelDec->sLPC_Q14[ NSQ_LPC_BUF_LENGTH + i ], vld1q_s32( psSampleState[ 0 ].xq_Q14 ) );
+        vst1q_s32( psDelDec->Xq_Q14[ *smpl_buf_idx ], vld1q_s32( psSampleState[ 0 ].xq_Q14 ) );
+        tmp1_s32x4 = vld1q_s32( psSampleState[ 0 ].Q_Q10 );
+        vst1q_s32( psDelDec->Q_Q10[ *smpl_buf_idx ], tmp1_s32x4 );
+        vst1q_s32( psDelDec->Pred_Q15[ *smpl_buf_idx ], vshlq_n_s32( vld1q_s32( psSampleState[ 0 ].LPC_exc_Q14 ), 1 ) );
+        vst1q_s32( psDelDec->Shape_Q14[ *smpl_buf_idx ], vld1q_s32( psSampleState[ 0 ].sLTP_shp_Q14 ) );
+        tmp1_s32x4 = vrshrq_n_s32( tmp1_s32x4, 10 );
+        tmp1_s32x4 = vaddq_s32( vld1q_s32( psDelDec->Seed ), tmp1_s32x4 );
+        vst1q_s32( psDelDec->Seed, tmp1_s32x4 );
+        vst1q_s32( psDelDec->RandState[ *smpl_buf_idx ], tmp1_s32x4 );
+        vst1q_s32( psDelDec->RD_Q10, vld1q_s32( psSampleState[ 0 ].RD_Q10 ) );
+        delayedGain_Q10[ *smpl_buf_idx ] = Gain_Q10;
+    }
+    /* Update LPC states */
+    silk_memcpy( psDelDec->sLPC_Q14[ 0 ], psDelDec->sLPC_Q14[ length ], NEON_MAX_DEL_DEC_STATES * NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+
+    RESTORE_STACK;
+}
+
+static OPUS_INLINE void silk_SMULWB_8_neon(
+    const opus_int16 *a,
+    const int32x2_t  b,
+    opus_int32       *o
+)
+{
+    const int16x8_t a_s16x8 = vld1q_s16( a );
+    int32x4_t o0_s32x4, o1_s32x4;
+
+    o0_s32x4 = vshll_n_s16( vget_low_s16( a_s16x8 ), 15 );
+    o1_s32x4 = vshll_n_s16( vget_high_s16( a_s16x8 ), 15 );
+    o0_s32x4 = vqdmulhq_lane_s32( o0_s32x4, b, 0 );
+    o1_s32x4 = vqdmulhq_lane_s32( o1_s32x4, b, 0 );
+    vst1q_s32( o, o0_s32x4 );
+    vst1q_s32( o + 4, o1_s32x4 );
+}
+
+/* Only works when ( b >= -65536 ) && ( b < 65536 ). */
+static OPUS_INLINE void silk_SMULWW_small_b_4_neon(
+    opus_int32       *a,
+    const int32x2_t  b_s32x2)
+{
+    int32x4_t o_s32x4;
+
+    o_s32x4 = vld1q_s32( a );
+    o_s32x4 = vqdmulhq_lane_s32( o_s32x4, b_s32x2, 0 );
+    vst1q_s32( a, o_s32x4 );
+}
+
+/* Only works when ( b >= -65536 ) && ( b < 65536 ). */
+static OPUS_INLINE void silk_SMULWW_small_b_8_neon(
+    opus_int32       *a,
+    const int32x2_t  b_s32x2
+)
+{
+    int32x4_t o0_s32x4, o1_s32x4;
+
+    o0_s32x4 = vld1q_s32( a );
+    o1_s32x4 = vld1q_s32( a + 4 );
+    o0_s32x4 = vqdmulhq_lane_s32( o0_s32x4, b_s32x2, 0 );
+    o1_s32x4 = vqdmulhq_lane_s32( o1_s32x4, b_s32x2, 0 );
+    vst1q_s32( a, o0_s32x4 );
+    vst1q_s32( a + 4, o1_s32x4 );
+}
+
+static OPUS_INLINE void silk_SMULWW_4_neon(
+    opus_int32       *a,
+    const int32x2_t  b_s32x2)
+{
+    int32x4_t a_s32x4, o_s32x4;
+
+    a_s32x4 = vld1q_s32( a );
+    o_s32x4 = vqdmulhq_lane_s32( a_s32x4, b_s32x2, 0 );
+    o_s32x4 = vmlaq_lane_s32( o_s32x4, a_s32x4, b_s32x2, 1 );
+    vst1q_s32( a, o_s32x4 );
+}
+
+static OPUS_INLINE void silk_SMULWW_8_neon(
+    opus_int32       *a,
+    const int32x2_t  b_s32x2
+)
+{
+    int32x4_t a0_s32x4, a1_s32x4, o0_s32x4, o1_s32x4;
+
+    a0_s32x4 = vld1q_s32( a );
+    a1_s32x4 = vld1q_s32( a + 4 );
+    o0_s32x4 = vqdmulhq_lane_s32( a0_s32x4, b_s32x2, 0 );
+    o1_s32x4 = vqdmulhq_lane_s32( a1_s32x4, b_s32x2, 0 );
+    o0_s32x4 = vmlaq_lane_s32( o0_s32x4, a0_s32x4, b_s32x2, 1 );
+    o1_s32x4 = vmlaq_lane_s32( o1_s32x4, a1_s32x4, b_s32x2, 1 );
+    vst1q_s32( a, o0_s32x4 );
+    vst1q_s32( a + 4, o1_s32x4 );
+}
+
+static OPUS_INLINE void silk_SMULWW_loop_neon(
+    const opus_int16 *a,
+    const opus_int32 b,
+    opus_int32       *o,
+    const opus_int   loop_num
+)
+{
+    opus_int i;
+    int32x2_t b_s32x2;
+
+    b_s32x2 = vdup_n_s32( b );
+    for( i = 0; i < loop_num - 7; i += 8 ) {
+        silk_SMULWB_8_neon( a + i, b_s32x2, o + i );
+    }
+    for( ; i < loop_num; i++ ) {
+        o[ i ] = silk_SMULWW( a[ i ], b );
+    }
+}
+
+static OPUS_INLINE void silk_nsq_del_dec_scale_states_neon(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_decs_struct psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int16    x16[],                      /* I    Input                               */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+)
+{
+    opus_int            i, lag;
+    opus_int32          gain_adj_Q16, inv_gain_Q31, inv_gain_Q26;
+
+    lag          = pitchL[ subfr ];
+    inv_gain_Q31 = silk_INVERSE32_varQ( silk_max( Gains_Q16[ subfr ], 1 ), 47 );
+    silk_assert( inv_gain_Q31 != 0 );
+
+    /* Scale input */
+    inv_gain_Q26 = silk_RSHIFT_ROUND( inv_gain_Q31, 5 );
+    silk_SMULWW_loop_neon( x16, inv_gain_Q26, x_sc_Q10, psEncC->subfr_length );
+
+    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */
+    if( NSQ->rewhite_flag ) {
+        if( subfr == 0 ) {
+            /* Do LTP downscaling */
+            inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, LTP_scale_Q14 ), 2 );
+        }
+        silk_SMULWW_loop_neon( sLTP + NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2, inv_gain_Q31, sLTP_Q15 + NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2, lag + LTP_ORDER / 2 );
+    }
+
+    /* Adjust for changing gain */
+    if( Gains_Q16[ subfr ] != NSQ->prev_gain_Q16 ) {
+        int32x2_t gain_adj_Q16_s32x2;
+        gain_adj_Q16 = silk_DIV32_varQ( NSQ->prev_gain_Q16, Gains_Q16[ subfr ], 16 );
+
+        /* Scale long-term shaping state */
+        if( ( gain_adj_Q16 >= -65536 ) && ( gain_adj_Q16 < 65536 ) ) {
+            gain_adj_Q16_s32x2 = vdup_n_s32( silk_LSHIFT32( gain_adj_Q16, 15 ) );
+            for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx - 7; i += 8 ) {
+                silk_SMULWW_small_b_8_neon( NSQ->sLTP_shp_Q14 + i, gain_adj_Q16_s32x2 );
+            }
+            for( ; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+                NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+            }
+
+            /* Scale long-term prediction state */
+            if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+                for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx - decisionDelay - 7; i += 8 ) {
+                    silk_SMULWW_small_b_8_neon( sLTP_Q15 + i, gain_adj_Q16_s32x2 );
+                }
+                for( ; i < NSQ->sLTP_buf_idx - decisionDelay; i++ ) {
+                    sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+                }
+            }
+
+            /* Scale scalar states */
+            silk_SMULWW_small_b_4_neon( psDelDec->LF_AR_Q14, gain_adj_Q16_s32x2 );
+            silk_SMULWW_small_b_4_neon( psDelDec->Diff_Q14,  gain_adj_Q16_s32x2 );
+
+            /* Scale short-term prediction and shaping states */
+            for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+                silk_SMULWW_small_b_4_neon( psDelDec->sLPC_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+
+            for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+                silk_SMULWW_small_b_4_neon( psDelDec->sAR2_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+
+            for( i = 0; i < DECISION_DELAY; i++ ) {
+                silk_SMULWW_small_b_4_neon( psDelDec->Pred_Q15[  i ], gain_adj_Q16_s32x2 );
+                silk_SMULWW_small_b_4_neon( psDelDec->Shape_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+        } else {
+            gain_adj_Q16_s32x2 = vdup_n_s32( silk_LSHIFT32( gain_adj_Q16 & 0x0000FFFF, 15 ) );
+            gain_adj_Q16_s32x2 = vset_lane_s32( gain_adj_Q16 >> 16, gain_adj_Q16_s32x2, 1 );
+            for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx - 7; i += 8 ) {
+                silk_SMULWW_8_neon( NSQ->sLTP_shp_Q14 + i, gain_adj_Q16_s32x2 );
+            }
+            for( ; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+                NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+            }
+
+            /* Scale long-term prediction state */
+            if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+                for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx - decisionDelay - 7; i += 8 ) {
+                    silk_SMULWW_8_neon( sLTP_Q15 + i, gain_adj_Q16_s32x2 );
+                }
+                for( ; i < NSQ->sLTP_buf_idx - decisionDelay; i++ ) {
+                    sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+                }
+            }
+
+            /* Scale scalar states */
+            silk_SMULWW_4_neon( psDelDec->LF_AR_Q14, gain_adj_Q16_s32x2 );
+            silk_SMULWW_4_neon( psDelDec->Diff_Q14,  gain_adj_Q16_s32x2 );
+
+            /* Scale short-term prediction and shaping states */
+            for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+                silk_SMULWW_4_neon( psDelDec->sLPC_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+
+            for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+                silk_SMULWW_4_neon( psDelDec->sAR2_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+
+            for( i = 0; i < DECISION_DELAY; i++ ) {
+                silk_SMULWW_4_neon( psDelDec->Pred_Q15[  i ], gain_adj_Q16_s32x2 );
+                silk_SMULWW_4_neon( psDelDec->Shape_Q14[ i ], gain_adj_Q16_s32x2 );
+            }
+        }
+
+        /* Save inverse gain */
+        NSQ->prev_gain_Q16 = Gains_Q16[ subfr ];
+    }
+}
diff --git a/opus/silk/arm/NSQ_neon.c b/opus/silk/arm/NSQ_neon.c
new file mode 100644 (file)
index 0000000..9642529
--- /dev/null
@@ -0,0 +1,112 @@
+/***********************************************************************
+Copyright (C) 2014 Vidyo
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#include "main.h"
+#include "stack_alloc.h"
+#include "NSQ.h"
+#include "celt/cpu_support.h"
+#include "celt/arm/armcpu.h"
+
+opus_int32 silk_noise_shape_quantizer_short_prediction_neon(const opus_int32 *buf32, const opus_int32 *coef32, opus_int order)
+{
+    int32x4_t coef0 = vld1q_s32(coef32);
+    int32x4_t coef1 = vld1q_s32(coef32 + 4);
+    int32x4_t coef2 = vld1q_s32(coef32 + 8);
+    int32x4_t coef3 = vld1q_s32(coef32 + 12);
+
+    int32x4_t a0 = vld1q_s32(buf32 - 15);
+    int32x4_t a1 = vld1q_s32(buf32 - 11);
+    int32x4_t a2 = vld1q_s32(buf32 - 7);
+    int32x4_t a3 = vld1q_s32(buf32 - 3);
+
+    int32x4_t b0 = vqdmulhq_s32(coef0, a0);
+    int32x4_t b1 = vqdmulhq_s32(coef1, a1);
+    int32x4_t b2 = vqdmulhq_s32(coef2, a2);
+    int32x4_t b3 = vqdmulhq_s32(coef3, a3);
+
+    int32x4_t c0 = vaddq_s32(b0, b1);
+    int32x4_t c1 = vaddq_s32(b2, b3);
+
+    int32x4_t d = vaddq_s32(c0, c1);
+
+    int64x2_t e = vpaddlq_s32(d);
+
+    int64x1_t f = vadd_s64(vget_low_s64(e), vget_high_s64(e));
+
+    opus_int32 out = vget_lane_s32(vreinterpret_s32_s64(f), 0);
+
+    out += silk_RSHIFT( order, 1 );
+
+    return out;
+}
+
+
+opus_int32 silk_NSQ_noise_shape_feedback_loop_neon(const opus_int32 *data0, opus_int32 *data1, const opus_int16 *coef, opus_int order)
+{
+    opus_int32 out;
+    if (order == 8)
+    {
+        int32x4_t a00 = vdupq_n_s32(data0[0]);
+        int32x4_t a01 = vld1q_s32(data1);  /* data1[0] ... [3] */
+
+        int32x4_t a0 = vextq_s32 (a00, a01, 3); /* data0[0] data1[0] ...[2] */
+        int32x4_t a1 = vld1q_s32(data1 + 3);  /* data1[3] ... [6] */
+
+        /*TODO: Convert these once in advance instead of once per sample, like
+          silk_noise_shape_quantizer_short_prediction_neon() does.*/
+        int16x8_t coef16 = vld1q_s16(coef);
+        int32x4_t coef0 = vmovl_s16(vget_low_s16(coef16));
+        int32x4_t coef1 = vmovl_s16(vget_high_s16(coef16));
+
+        /*This is not bit-exact with the C version, since we do not drop the
+          lower 16 bits of each multiply, but wait until the end to truncate
+          precision. This is an encoder-specific calculation (and unlike
+          silk_noise_shape_quantizer_short_prediction_neon(), is not meant to
+          simulate what the decoder will do). We still could use vqdmulhq_s32()
+          like silk_noise_shape_quantizer_short_prediction_neon() and save
+          half the multiplies, but the speed difference is not large, since we
+          then need two extra adds.*/
+        int64x2_t b0 = vmull_s32(vget_low_s32(a0), vget_low_s32(coef0));
+        int64x2_t b1 = vmlal_s32(b0, vget_high_s32(a0), vget_high_s32(coef0));
+        int64x2_t b2 = vmlal_s32(b1, vget_low_s32(a1), vget_low_s32(coef1));
+        int64x2_t b3 = vmlal_s32(b2, vget_high_s32(a1), vget_high_s32(coef1));
+
+        int64x1_t c = vadd_s64(vget_low_s64(b3), vget_high_s64(b3));
+        int64x1_t cS = vrshr_n_s64(c, 15);
+        int32x2_t d = vreinterpret_s32_s64(cS);
+
+        out = vget_lane_s32(d, 0);
+        vst1q_s32(data1, a0);
+        vst1q_s32(data1 + 4, a1);
+        return out;
+    }
+    return silk_NSQ_noise_shape_feedback_loop_c(data0, data1, coef, order);
+}
diff --git a/opus/silk/arm/NSQ_neon.h b/opus/silk/arm/NSQ_neon.h
new file mode 100644 (file)
index 0000000..b31d944
--- /dev/null
@@ -0,0 +1,114 @@
+/***********************************************************************
+Copyright (C) 2014 Vidyo
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_NSQ_NEON_H
+#define SILK_NSQ_NEON_H
+
+#include "cpu_support.h"
+#include "SigProc_FIX.h"
+
+#undef silk_short_prediction_create_arch_coef
+/* For vectorized calc, reverse a_Q12 coefs, convert to 32-bit, and shift for vqdmulhq_s32. */
+static OPUS_INLINE void silk_short_prediction_create_arch_coef_neon(opus_int32 *out, const opus_int16 *in, opus_int order)
+{
+    out[15] = silk_LSHIFT32(in[0], 15);
+    out[14] = silk_LSHIFT32(in[1], 15);
+    out[13] = silk_LSHIFT32(in[2], 15);
+    out[12] = silk_LSHIFT32(in[3], 15);
+    out[11] = silk_LSHIFT32(in[4], 15);
+    out[10] = silk_LSHIFT32(in[5], 15);
+    out[9]  = silk_LSHIFT32(in[6], 15);
+    out[8]  = silk_LSHIFT32(in[7], 15);
+    out[7]  = silk_LSHIFT32(in[8], 15);
+    out[6]  = silk_LSHIFT32(in[9], 15);
+
+    if (order == 16)
+    {
+        out[5] = silk_LSHIFT32(in[10], 15);
+        out[4] = silk_LSHIFT32(in[11], 15);
+        out[3] = silk_LSHIFT32(in[12], 15);
+        out[2] = silk_LSHIFT32(in[13], 15);
+        out[1] = silk_LSHIFT32(in[14], 15);
+        out[0] = silk_LSHIFT32(in[15], 15);
+    }
+    else
+    {
+        out[5] = 0;
+        out[4] = 0;
+        out[3] = 0;
+        out[2] = 0;
+        out[1] = 0;
+        out[0] = 0;
+    }
+}
+
+#if defined(OPUS_ARM_PRESUME_NEON_INTR)
+
+#define silk_short_prediction_create_arch_coef(out, in, order) \
+    (silk_short_prediction_create_arch_coef_neon(out, in, order))
+
+#elif defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+
+#define silk_short_prediction_create_arch_coef(out, in, order) \
+    do { if (arch == OPUS_ARCH_ARM_NEON) { silk_short_prediction_create_arch_coef_neon(out, in, order); } } while (0)
+
+#endif
+
+opus_int32 silk_noise_shape_quantizer_short_prediction_neon(const opus_int32 *buf32, const opus_int32 *coef32, opus_int order);
+
+opus_int32 silk_NSQ_noise_shape_feedback_loop_neon(const opus_int32 *data0, opus_int32 *data1, const opus_int16 *coef, opus_int order);
+
+#if defined(OPUS_ARM_PRESUME_NEON_INTR)
+#undef silk_noise_shape_quantizer_short_prediction
+#define silk_noise_shape_quantizer_short_prediction(in, coef, coefRev, order, arch) \
+    ((void)arch,silk_noise_shape_quantizer_short_prediction_neon(in, coefRev, order))
+
+#undef silk_NSQ_noise_shape_feedback_loop
+#define silk_NSQ_noise_shape_feedback_loop(data0, data1, coef, order, arch)  ((void)arch,silk_NSQ_noise_shape_feedback_loop_neon(data0, data1, coef, order))
+
+#elif defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+
+/* silk_noise_shape_quantizer_short_prediction implementations take different parameters based on arch
+   (coef vs. coefRev) so can't use the usual IMPL table implementation */
+#undef silk_noise_shape_quantizer_short_prediction
+#define silk_noise_shape_quantizer_short_prediction(in, coef, coefRev, order, arch)  \
+    (arch == OPUS_ARCH_ARM_NEON ? \
+        silk_noise_shape_quantizer_short_prediction_neon(in, coefRev, order) : \
+        silk_noise_shape_quantizer_short_prediction_c(in, coef, order))
+
+extern opus_int32
+ (*const SILK_NSQ_NOISE_SHAPE_FEEDBACK_LOOP_IMPL[OPUS_ARCHMASK+1])(
+ const opus_int32 *data0, opus_int32 *data1, const opus_int16 *coef,
+ opus_int order);
+
+#undef silk_NSQ_noise_shape_feedback_loop
+#define silk_NSQ_noise_shape_feedback_loop(data0, data1, coef, order, arch) \
+ (SILK_NSQ_NOISE_SHAPE_FEEDBACK_LOOP_IMPL[(arch)&OPUS_ARCHMASK](data0, data1, \
+ coef, order))
+
+#endif
+
+#endif /* SILK_NSQ_NEON_H */
diff --git a/opus/silk/arm/SigProc_FIX_armv4.h b/opus/silk/arm/SigProc_FIX_armv4.h
new file mode 100644 (file)
index 0000000..ff62b1e
--- /dev/null
@@ -0,0 +1,47 @@
+/***********************************************************************
+Copyright (C) 2013 Xiph.Org Foundation and contributors
+Copyright (c) 2013       Parrot
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_SIGPROC_FIX_ARMv4_H
+#define SILK_SIGPROC_FIX_ARMv4_H
+
+#undef silk_MLA
+static OPUS_INLINE opus_int32 silk_MLA_armv4(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  opus_int32 res;
+  __asm__(
+      "#silk_MLA\n\t"
+      "mla %0, %1, %2, %3\n\t"
+      : "=&r"(res)
+      : "r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_MLA(a, b, c) (silk_MLA_armv4(a, b, c))
+
+#endif
diff --git a/opus/silk/arm/SigProc_FIX_armv5e.h b/opus/silk/arm/SigProc_FIX_armv5e.h
new file mode 100644 (file)
index 0000000..617a09c
--- /dev/null
@@ -0,0 +1,61 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. All rights reserved.
+Copyright (c) 2013       Parrot
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_SIGPROC_FIX_ARMv5E_H
+#define SILK_SIGPROC_FIX_ARMv5E_H
+
+#undef silk_SMULTT
+static OPUS_INLINE opus_int32 silk_SMULTT_armv5e(opus_int32 a, opus_int32 b)
+{
+  opus_int32 res;
+  __asm__(
+      "#silk_SMULTT\n\t"
+      "smultt %0, %1, %2\n\t"
+      : "=r"(res)
+      : "%r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SMULTT(a, b) (silk_SMULTT_armv5e(a, b))
+
+#undef silk_SMLATT
+static OPUS_INLINE opus_int32 silk_SMLATT_armv5e(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  opus_int32 res;
+  __asm__(
+      "#silk_SMLATT\n\t"
+      "smlatt %0, %1, %2, %3\n\t"
+      : "=r"(res)
+      : "%r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_SMLATT(a, b, c) (silk_SMLATT_armv5e(a, b, c))
+
+#endif
diff --git a/opus/silk/arm/arm_silk_map.c b/opus/silk/arm/arm_silk_map.c
new file mode 100644 (file)
index 0000000..0b9bfec
--- /dev/null
@@ -0,0 +1,123 @@
+/***********************************************************************
+Copyright (C) 2014 Vidyo
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "NSQ.h"
+#include "SigProc_FIX.h"
+
+#if defined(OPUS_HAVE_RTCD)
+
+# if (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && \
+ !defined(OPUS_ARM_PRESUME_NEON_INTR))
+
+void (*const SILK_BIQUAD_ALT_STRIDE2_IMPL[OPUS_ARCHMASK + 1])(
+        const opus_int16            *in,                /* I     input signal                                               */
+        const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+        const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+        opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+        opus_int16                  *out,               /* O     output signal                                              */
+        const opus_int32            len                 /* I     signal length (must be even)                               */
+) = {
+      silk_biquad_alt_stride2_c,    /* ARMv4 */
+      silk_biquad_alt_stride2_c,    /* EDSP */
+      silk_biquad_alt_stride2_c,    /* Media */
+      silk_biquad_alt_stride2_neon, /* Neon */
+};
+
+opus_int32 (*const SILK_LPC_INVERSE_PRED_GAIN_IMPL[OPUS_ARCHMASK + 1])( /* O   Returns inverse prediction gain in energy domain, Q30        */
+        const opus_int16            *A_Q12,                             /* I   Prediction coefficients, Q12 [order]                         */
+        const opus_int              order                               /* I   Prediction order                                             */
+) = {
+      silk_LPC_inverse_pred_gain_c,    /* ARMv4 */
+      silk_LPC_inverse_pred_gain_c,    /* EDSP */
+      silk_LPC_inverse_pred_gain_c,    /* Media */
+      silk_LPC_inverse_pred_gain_neon, /* Neon */
+};
+
+void  (*const SILK_NSQ_DEL_DEC_IMPL[OPUS_ARCHMASK + 1])(
+        const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+        silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+        SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+        const opus_int16            x16[],                                      /* I    Input                           */
+        opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+        const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+        const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+        const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs              */
+        const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+        const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+        const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+        const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+        const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+        const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+        const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+) = {
+      silk_NSQ_del_dec_c,    /* ARMv4 */
+      silk_NSQ_del_dec_c,    /* EDSP */
+      silk_NSQ_del_dec_c,    /* Media */
+      silk_NSQ_del_dec_neon, /* Neon */
+};
+
+/*There is no table for silk_noise_shape_quantizer_short_prediction because the
+   NEON version takes different parameters than the C version.
+  Instead RTCD is done via if statements at the call sites.
+  See NSQ_neon.h for details.*/
+
+opus_int32
+ (*const SILK_NSQ_NOISE_SHAPE_FEEDBACK_LOOP_IMPL[OPUS_ARCHMASK+1])(
+ const opus_int32 *data0, opus_int32 *data1, const opus_int16 *coef,
+ opus_int order) = {
+  silk_NSQ_noise_shape_feedback_loop_c,    /* ARMv4 */
+  silk_NSQ_noise_shape_feedback_loop_c,    /* EDSP */
+  silk_NSQ_noise_shape_feedback_loop_c,    /* Media */
+  silk_NSQ_noise_shape_feedback_loop_neon, /* NEON */
+};
+
+# endif
+
+# if defined(FIXED_POINT) && \
+ defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR)
+
+void (*const SILK_WARPED_AUTOCORRELATION_FIX_IMPL[OPUS_ARCHMASK + 1])(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order                                   /* I    Correlation order (even)                                                    */
+) = {
+      silk_warped_autocorrelation_FIX_c,    /* ARMv4 */
+      silk_warped_autocorrelation_FIX_c,    /* EDSP */
+      silk_warped_autocorrelation_FIX_c,    /* Media */
+      silk_warped_autocorrelation_FIX_neon, /* Neon */
+};
+
+# endif
+
+#endif /* OPUS_HAVE_RTCD */
diff --git a/opus/silk/arm/biquad_alt_arm.h b/opus/silk/arm/biquad_alt_arm.h
new file mode 100644 (file)
index 0000000..66ea9f4
--- /dev/null
@@ -0,0 +1,68 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_BIQUAD_ALT_ARM_H
+# define SILK_BIQUAD_ALT_ARM_H
+
+# include "celt/arm/armcpu.h"
+
+# if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+void silk_biquad_alt_stride2_neon(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+);
+
+#  if !defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_PRESUME_NEON)
+#   define OVERRIDE_silk_biquad_alt_stride2                   (1)
+#   define silk_biquad_alt_stride2(in, B_Q28, A_Q28, S, out, len, arch) ((void)(arch), PRESUME_NEON(silk_biquad_alt_stride2)(in, B_Q28, A_Q28, S, out, len))
+#  endif
+# endif
+
+# if !defined(OVERRIDE_silk_biquad_alt_stride2)
+/*Is run-time CPU detection enabled on this platform?*/
+#  if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern void (*const SILK_BIQUAD_ALT_STRIDE2_IMPL[OPUS_ARCHMASK+1])(
+        const opus_int16            *in,                /* I     input signal                                               */
+        const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+        const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+        opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+        opus_int16                  *out,               /* O     output signal                                              */
+        const opus_int32            len                 /* I     signal length (must be even)                               */
+    );
+#   define OVERRIDE_silk_biquad_alt_stride2                  (1)
+#   define silk_biquad_alt_stride2(in, B_Q28, A_Q28, S, out, len, arch) ((*SILK_BIQUAD_ALT_STRIDE2_IMPL[(arch)&OPUS_ARCHMASK])(in, B_Q28, A_Q28, S, out, len))
+#  elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#   define OVERRIDE_silk_biquad_alt_stride2                  (1)
+#   define silk_biquad_alt_stride2(in, B_Q28, A_Q28, S, out, len, arch) ((void)(arch), silk_biquad_alt_stride2_neon(in, B_Q28, A_Q28, S, out, len))
+#  endif
+# endif
+
+#endif /* end SILK_BIQUAD_ALT_ARM_H */
diff --git a/opus/silk/arm/biquad_alt_neon_intr.c b/opus/silk/arm/biquad_alt_neon_intr.c
new file mode 100644 (file)
index 0000000..9715733
--- /dev/null
@@ -0,0 +1,156 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#ifdef OPUS_CHECK_ASM
+# include <string.h>
+# include "stack_alloc.h"
+#endif
+#include "SigProc_FIX.h"
+
+static inline void silk_biquad_alt_stride2_kernel( const int32x4_t A_L_s32x4, const int32x4_t A_U_s32x4, const int32x4_t B_Q28_s32x4, const int32x2_t t_s32x2, const int32x4_t in_s32x4, int32x4_t *S_s32x4, int32x2_t *out32_Q14_s32x2 )
+{
+    int32x4_t t_s32x4, out32_Q14_s32x4;
+
+    *out32_Q14_s32x2 = vadd_s32( vget_low_s32( *S_s32x4 ), t_s32x2 );              /* silk_SMLAWB( S{0,1}, B_Q28[ 0 ], in{0,1} )                                      */
+    *S_s32x4         = vcombine_s32( vget_high_s32( *S_s32x4 ), vdup_n_s32( 0 ) ); /* S{0,1} = S{2,3}; S{2,3} = 0;                                                    */
+    *out32_Q14_s32x2 = vshl_n_s32( *out32_Q14_s32x2, 2 );                          /* out32_Q14_{0,1} = silk_LSHIFT( silk_SMLAWB( S{0,1}, B_Q28[ 0 ], in{0,1} ), 2 ); */
+    out32_Q14_s32x4  = vcombine_s32( *out32_Q14_s32x2, *out32_Q14_s32x2 );         /* out32_Q14_{0,1,0,1}                                                             */
+    t_s32x4          = vqdmulhq_s32( out32_Q14_s32x4, A_L_s32x4 );                 /* silk_SMULWB( out32_Q14_{0,1,0,1}, A{0,0,1,1}_L_Q28 )                            */
+    *S_s32x4         = vrsraq_n_s32( *S_s32x4, t_s32x4, 14 );                      /* S{0,1} = S{2,3} + silk_RSHIFT_ROUND();  S{2,3} = silk_RSHIFT_ROUND();           */
+    t_s32x4          = vqdmulhq_s32( out32_Q14_s32x4, A_U_s32x4 );                 /* silk_SMULWB( out32_Q14_{0,1,0,1}, A{0,0,1,1}_U_Q28 )                            */
+    *S_s32x4         = vaddq_s32( *S_s32x4, t_s32x4 );                             /* S0 = silk_SMLAWB( S{0,1,2,3}, out32_Q14_{0,1,0,1}, A{0,0,1,1}_U_Q28 );          */
+    t_s32x4          = vqdmulhq_s32( in_s32x4, B_Q28_s32x4 );                      /* silk_SMULWB( B_Q28[ {1,1,2,2} ], in{0,1,0,1} )                                  */
+    *S_s32x4         = vaddq_s32( *S_s32x4, t_s32x4 );                             /* S0 = silk_SMLAWB( S0, B_Q28[ {1,1,2,2} ], in{0,1,0,1} );                        */
+}
+
+void silk_biquad_alt_stride2_neon(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+)
+{
+    /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
+    opus_int        k            = 0;
+    const int32x2_t offset_s32x2 = vdup_n_s32( (1<<14) - 1 );
+    const int32x4_t offset_s32x4 = vcombine_s32( offset_s32x2, offset_s32x2 );
+    int16x4_t       in_s16x4  = vdup_n_s16( 0 );
+    int16x4_t       out_s16x4;
+    int32x2_t       A_Q28_s32x2, A_L_s32x2, A_U_s32x2, B_Q28_s32x2, t_s32x2;
+    int32x4_t       A_L_s32x4, A_U_s32x4, B_Q28_s32x4, S_s32x4, out32_Q14_s32x4;
+    int32x2x2_t     t0_s32x2x2, t1_s32x2x2, t2_s32x2x2, S_s32x2x2;
+
+#ifdef OPUS_CHECK_ASM
+    opus_int32 S_c[ 4 ];
+    VARDECL( opus_int16, out_c );
+    SAVE_STACK;
+    ALLOC( out_c, 2 * len, opus_int16 );
+
+    silk_memcpy( &S_c, S, sizeof( S_c ) );
+    silk_biquad_alt_stride2_c( in, B_Q28, A_Q28, S_c, out_c, len );
+#endif
+
+    /* Negate A_Q28 values and split in two parts */
+    A_Q28_s32x2 = vld1_s32( A_Q28 );
+    A_Q28_s32x2 = vneg_s32( A_Q28_s32x2 );
+    A_L_s32x2   = vshl_n_s32( A_Q28_s32x2, 18 );                                                        /* ( -A_Q28[] & 0x00003FFF ) << 18                                                     */
+    A_L_s32x2   = vreinterpret_s32_u32( vshr_n_u32( vreinterpret_u32_s32( A_L_s32x2 ), 3 ) );           /* ( -A_Q28[] & 0x00003FFF ) << 15                                                     */
+    A_U_s32x2   = vshr_n_s32( A_Q28_s32x2, 14 );                                                        /* silk_RSHIFT( -A_Q28[], 14 )                                                         */
+    A_U_s32x2   = vshl_n_s32( A_U_s32x2, 16 );                                                          /* silk_RSHIFT( -A_Q28[], 14 ) << 16 (Clip two leading bits to conform to C function.) */
+    A_U_s32x2   = vshr_n_s32( A_U_s32x2, 1 );                                                           /* silk_RSHIFT( -A_Q28[], 14 ) << 15                                                   */
+
+    B_Q28_s32x2  = vld1_s32( B_Q28 );
+    t_s32x2      = vld1_s32( B_Q28 + 1 );
+    t0_s32x2x2   = vzip_s32( A_L_s32x2, A_L_s32x2 );
+    t1_s32x2x2   = vzip_s32( A_U_s32x2, A_U_s32x2 );
+    t2_s32x2x2   = vzip_s32( t_s32x2, t_s32x2 );
+    A_L_s32x4    = vcombine_s32( t0_s32x2x2.val[ 0 ], t0_s32x2x2.val[ 1 ] );                            /* A{0,0,1,1}_L_Q28          */
+    A_U_s32x4    = vcombine_s32( t1_s32x2x2.val[ 0 ], t1_s32x2x2.val[ 1 ] );                            /* A{0,0,1,1}_U_Q28          */
+    B_Q28_s32x4  = vcombine_s32( t2_s32x2x2.val[ 0 ], t2_s32x2x2.val[ 1 ] );                            /* B_Q28[ {1,1,2,2} ]        */
+    S_s32x4      = vld1q_s32( S );                                                                      /* S0 = S[ 0 ]; S3 = S[ 3 ]; */
+    S_s32x2x2    = vtrn_s32( vget_low_s32( S_s32x4 ), vget_high_s32( S_s32x4 ) );                       /* S2 = S[ 1 ]; S1 = S[ 2 ]; */
+    S_s32x4      = vcombine_s32( S_s32x2x2.val[ 0 ], S_s32x2x2.val[ 1 ] );
+
+    for( ; k < len - 1; k += 2 ) {
+        int32x4_t in_s32x4[ 2 ], t_s32x4;
+        int32x2_t out32_Q14_s32x2[ 2 ];
+
+        /* S[ 2 * i + 0 ], S[ 2 * i + 1 ], S[ 2 * i + 2 ], S[ 2 * i + 3 ]: Q12 */
+        in_s16x4      = vld1_s16( &in[ 2 * k ] );                                                       /* in{0,1,2,3} = in[ 2 * k + {0,1,2,3} ]; */
+        in_s32x4[ 0 ] = vshll_n_s16( in_s16x4, 15 );                                                    /* in{0,1,2,3} << 15                      */
+        t_s32x4       = vqdmulhq_lane_s32( in_s32x4[ 0 ], B_Q28_s32x2, 0 );                             /* silk_SMULWB( B_Q28[ 0 ], in{0,1,2,3} ) */
+        in_s32x4[ 1 ] = vcombine_s32( vget_high_s32( in_s32x4[ 0 ] ), vget_high_s32( in_s32x4[ 0 ] ) ); /* in{2,3,2,3} << 15                      */
+        in_s32x4[ 0 ] = vcombine_s32( vget_low_s32 ( in_s32x4[ 0 ] ), vget_low_s32 ( in_s32x4[ 0 ] ) ); /* in{0,1,0,1} << 15                      */
+        silk_biquad_alt_stride2_kernel( A_L_s32x4, A_U_s32x4, B_Q28_s32x4, vget_low_s32 ( t_s32x4 ), in_s32x4[ 0 ], &S_s32x4, &out32_Q14_s32x2[ 0 ] );
+        silk_biquad_alt_stride2_kernel( A_L_s32x4, A_U_s32x4, B_Q28_s32x4, vget_high_s32( t_s32x4 ), in_s32x4[ 1 ], &S_s32x4, &out32_Q14_s32x2[ 1 ] );
+
+        /* Scale back to Q0 and saturate */
+        out32_Q14_s32x4 = vcombine_s32( out32_Q14_s32x2[ 0 ], out32_Q14_s32x2[ 1 ] );                   /* out32_Q14_{0,1,2,3}                                                                                        */
+        out32_Q14_s32x4 = vaddq_s32( out32_Q14_s32x4, offset_s32x4 );                                   /* out32_Q14_{0,1,2,3} + (1<<14) - 1                                                                          */
+        out_s16x4       = vqshrn_n_s32( out32_Q14_s32x4, 14 );                                          /* (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14_{0,1,2,3} + (1<<14) - 1, 14 ) )                             */
+        vst1_s16( &out[ 2 * k ], out_s16x4 );                                                           /* out[ 2 * k + {0,1,2,3} ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14_{0,1,2,3} + (1<<14) - 1, 14 ) ); */
+    }
+
+    /* Process leftover. */
+    if( k < len ) {
+        int32x4_t in_s32x4;
+        int32x2_t out32_Q14_s32x2;
+
+        /* S[ 2 * i + 0 ], S[ 2 * i + 1 ]: Q12 */
+        in_s16x4     = vld1_lane_s16( &in[ 2 * k + 0 ], in_s16x4, 0 );                                  /* in{0,1} = in[ 2 * k + {0,1} ];     */
+        in_s16x4     = vld1_lane_s16( &in[ 2 * k + 1 ], in_s16x4, 1 );                                  /* in{0,1} = in[ 2 * k + {0,1} ];     */
+        in_s32x4     = vshll_n_s16( in_s16x4, 15 );                                                     /* in{0,1} << 15                      */
+        t_s32x2      = vqdmulh_lane_s32( vget_low_s32( in_s32x4 ), B_Q28_s32x2, 0 );                    /* silk_SMULWB( B_Q28[ 0 ], in{0,1} ) */
+        in_s32x4     = vcombine_s32( vget_low_s32( in_s32x4 ), vget_low_s32( in_s32x4 ) );              /* in{0,1,0,1} << 15                  */
+        silk_biquad_alt_stride2_kernel( A_L_s32x4, A_U_s32x4, B_Q28_s32x4, t_s32x2, in_s32x4, &S_s32x4, &out32_Q14_s32x2 );
+
+        /* Scale back to Q0 and saturate */
+        out32_Q14_s32x2 = vadd_s32( out32_Q14_s32x2, offset_s32x2 );                                    /* out32_Q14_{0,1} + (1<<14) - 1                                                              */
+        out32_Q14_s32x4 = vcombine_s32( out32_Q14_s32x2, out32_Q14_s32x2 );                             /* out32_Q14_{0,1,0,1} + (1<<14) - 1                                                          */
+        out_s16x4       = vqshrn_n_s32( out32_Q14_s32x4, 14 );                                          /* (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14_{0,1,0,1} + (1<<14) - 1, 14 ) )             */
+        vst1_lane_s16( &out[ 2 * k + 0 ], out_s16x4, 0 );                                               /* out[ 2 * k + 0 ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14_0 + (1<<14) - 1, 14 ) ); */
+        vst1_lane_s16( &out[ 2 * k + 1 ], out_s16x4, 1 );                                               /* out[ 2 * k + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14_1 + (1<<14) - 1, 14 ) ); */
+    }
+
+    vst1q_lane_s32( &S[ 0 ], S_s32x4, 0 );                                                              /* S[ 0 ] = S0; */
+    vst1q_lane_s32( &S[ 1 ], S_s32x4, 2 );                                                              /* S[ 1 ] = S2; */
+    vst1q_lane_s32( &S[ 2 ], S_s32x4, 1 );                                                              /* S[ 2 ] = S1; */
+    vst1q_lane_s32( &S[ 3 ], S_s32x4, 3 );                                                              /* S[ 3 ] = S3; */
+
+#ifdef OPUS_CHECK_ASM
+    silk_assert( !memcmp( S_c, S, sizeof( S_c ) ) );
+    silk_assert( !memcmp( out_c, out, 2 * len * sizeof( opus_int16 ) ) );
+    RESTORE_STACK;
+#endif
+}
diff --git a/opus/silk/arm/macros_arm64.h b/opus/silk/arm/macros_arm64.h
new file mode 100644 (file)
index 0000000..ed03041
--- /dev/null
@@ -0,0 +1,39 @@
+/***********************************************************************
+Copyright (C) 2015 Vidyo
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MACROS_ARM64_H
+#define SILK_MACROS_ARM64_H
+
+#include <arm_neon.h>
+
+#undef silk_ADD_SAT32
+#define silk_ADD_SAT32(a, b) (vqadds_s32((a), (b)))
+
+#undef silk_SUB_SAT32
+#define silk_SUB_SAT32(a, b) (vqsubs_s32((a), (b)))
+
+#endif /* SILK_MACROS_ARM64_H */
diff --git a/opus/silk/arm/macros_armv4.h b/opus/silk/arm/macros_armv4.h
new file mode 100644 (file)
index 0000000..877eb18
--- /dev/null
@@ -0,0 +1,110 @@
+/***********************************************************************
+Copyright (C) 2013 Xiph.Org Foundation and contributors.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MACROS_ARMv4_H
+#define SILK_MACROS_ARMv4_H
+
+/* This macro only avoids the undefined behaviour from a left shift of
+   a negative value. It should only be used in macros that can't include
+   SigProc_FIX.h. In other cases, use silk_LSHIFT32(). */
+#define SAFE_SHL(a,b) ((opus_int32)((opus_uint32)(a) << (b)))
+
+/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
+#undef silk_SMULWB
+static OPUS_INLINE opus_int32 silk_SMULWB_armv4(opus_int32 a, opus_int16 b)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+      "#silk_SMULWB\n\t"
+      "smull %0, %1, %2, %3\n\t"
+      : "=&r"(rd_lo), "=&r"(rd_hi)
+      : "%r"(a), "r"(SAFE_SHL(b,16))
+  );
+  return rd_hi;
+}
+#define silk_SMULWB(a, b) (silk_SMULWB_armv4(a, b))
+
+/* a32 + (b32 * (opus_int32)((opus_int16)(c32))) >> 16 output have to be 32bit int */
+#undef silk_SMLAWB
+#define silk_SMLAWB(a, b, c) ((a) + silk_SMULWB(b, c))
+
+/* (a32 * (b32 >> 16)) >> 16 */
+#undef silk_SMULWT
+static OPUS_INLINE opus_int32 silk_SMULWT_armv4(opus_int32 a, opus_int32 b)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+      "#silk_SMULWT\n\t"
+      "smull %0, %1, %2, %3\n\t"
+      : "=&r"(rd_lo), "=&r"(rd_hi)
+      : "%r"(a), "r"(b&~0xFFFF)
+  );
+  return rd_hi;
+}
+#define silk_SMULWT(a, b) (silk_SMULWT_armv4(a, b))
+
+/* a32 + (b32 * (c32 >> 16)) >> 16 */
+#undef silk_SMLAWT
+#define silk_SMLAWT(a, b, c) ((a) + silk_SMULWT(b, c))
+
+/* (a32 * b32) >> 16 */
+#undef silk_SMULWW
+static OPUS_INLINE opus_int32 silk_SMULWW_armv4(opus_int32 a, opus_int32 b)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+    "#silk_SMULWW\n\t"
+    "smull %0, %1, %2, %3\n\t"
+    : "=&r"(rd_lo), "=&r"(rd_hi)
+    : "%r"(a), "r"(b)
+  );
+  return SAFE_SHL(rd_hi,16)+(rd_lo>>16);
+}
+#define silk_SMULWW(a, b) (silk_SMULWW_armv4(a, b))
+
+#undef silk_SMLAWW
+static OPUS_INLINE opus_int32 silk_SMLAWW_armv4(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  unsigned rd_lo;
+  int rd_hi;
+  __asm__(
+    "#silk_SMLAWW\n\t"
+    "smull %0, %1, %2, %3\n\t"
+    : "=&r"(rd_lo), "=&r"(rd_hi)
+    : "%r"(b), "r"(c)
+  );
+  return a+SAFE_SHL(rd_hi,16)+(rd_lo>>16);
+}
+#define silk_SMLAWW(a, b, c) (silk_SMLAWW_armv4(a, b, c))
+
+#undef SAFE_SHL
+
+#endif /* SILK_MACROS_ARMv4_H */
diff --git a/opus/silk/arm/macros_armv5e.h b/opus/silk/arm/macros_armv5e.h
new file mode 100644 (file)
index 0000000..b14ec65
--- /dev/null
@@ -0,0 +1,220 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. All rights reserved.
+Copyright (c) 2013       Parrot
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MACROS_ARMv5E_H
+#define SILK_MACROS_ARMv5E_H
+
+/* This macro only avoids the undefined behaviour from a left shift of
+   a negative value. It should only be used in macros that can't include
+   SigProc_FIX.h. In other cases, use silk_LSHIFT32(). */
+#define SAFE_SHL(a,b) ((opus_int32)((opus_uint32)(a) << (b)))
+
+/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
+#undef silk_SMULWB
+static OPUS_INLINE opus_int32 silk_SMULWB_armv5e(opus_int32 a, opus_int16 b)
+{
+  int res;
+  __asm__(
+      "#silk_SMULWB\n\t"
+      "smulwb %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SMULWB(a, b) (silk_SMULWB_armv5e(a, b))
+
+/* a32 + (b32 * (opus_int32)((opus_int16)(c32))) >> 16 output have to be 32bit int */
+#undef silk_SMLAWB
+static OPUS_INLINE opus_int32 silk_SMLAWB_armv5e(opus_int32 a, opus_int32 b,
+ opus_int16 c)
+{
+  int res;
+  __asm__(
+      "#silk_SMLAWB\n\t"
+      "smlawb %0, %1, %2, %3\n\t"
+      : "=r"(res)
+      : "r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_SMLAWB(a, b, c) (silk_SMLAWB_armv5e(a, b, c))
+
+/* (a32 * (b32 >> 16)) >> 16 */
+#undef silk_SMULWT
+static OPUS_INLINE opus_int32 silk_SMULWT_armv5e(opus_int32 a, opus_int32 b)
+{
+  int res;
+  __asm__(
+      "#silk_SMULWT\n\t"
+      "smulwt %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SMULWT(a, b) (silk_SMULWT_armv5e(a, b))
+
+/* a32 + (b32 * (c32 >> 16)) >> 16 */
+#undef silk_SMLAWT
+static OPUS_INLINE opus_int32 silk_SMLAWT_armv5e(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  int res;
+  __asm__(
+      "#silk_SMLAWT\n\t"
+      "smlawt %0, %1, %2, %3\n\t"
+      : "=r"(res)
+      : "r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_SMLAWT(a, b, c) (silk_SMLAWT_armv5e(a, b, c))
+
+/* (opus_int32)((opus_int16)(a3))) * (opus_int32)((opus_int16)(b32)) output have to be 32bit int */
+#undef silk_SMULBB
+static OPUS_INLINE opus_int32 silk_SMULBB_armv5e(opus_int32 a, opus_int32 b)
+{
+  int res;
+  __asm__(
+      "#silk_SMULBB\n\t"
+      "smulbb %0, %1, %2\n\t"
+      : "=r"(res)
+      : "%r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SMULBB(a, b) (silk_SMULBB_armv5e(a, b))
+
+/* a32 + (opus_int32)((opus_int16)(b32)) * (opus_int32)((opus_int16)(c32)) output have to be 32bit int */
+#undef silk_SMLABB
+static OPUS_INLINE opus_int32 silk_SMLABB_armv5e(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  int res;
+  __asm__(
+      "#silk_SMLABB\n\t"
+      "smlabb %0, %1, %2, %3\n\t"
+      : "=r"(res)
+      : "%r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_SMLABB(a, b, c) (silk_SMLABB_armv5e(a, b, c))
+
+/* (opus_int32)((opus_int16)(a32)) * (b32 >> 16) */
+#undef silk_SMULBT
+static OPUS_INLINE opus_int32 silk_SMULBT_armv5e(opus_int32 a, opus_int32 b)
+{
+  int res;
+  __asm__(
+      "#silk_SMULBT\n\t"
+      "smulbt %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SMULBT(a, b) (silk_SMULBT_armv5e(a, b))
+
+/* a32 + (opus_int32)((opus_int16)(b32)) * (c32 >> 16) */
+#undef silk_SMLABT
+static OPUS_INLINE opus_int32 silk_SMLABT_armv5e(opus_int32 a, opus_int32 b,
+ opus_int32 c)
+{
+  int res;
+  __asm__(
+      "#silk_SMLABT\n\t"
+      "smlabt %0, %1, %2, %3\n\t"
+      : "=r"(res)
+      : "r"(b), "r"(c), "r"(a)
+  );
+  return res;
+}
+#define silk_SMLABT(a, b, c) (silk_SMLABT_armv5e(a, b, c))
+
+/* add/subtract with output saturated */
+#undef silk_ADD_SAT32
+static OPUS_INLINE opus_int32 silk_ADD_SAT32_armv5e(opus_int32 a, opus_int32 b)
+{
+  int res;
+  __asm__(
+      "#silk_ADD_SAT32\n\t"
+      "qadd %0, %1, %2\n\t"
+      : "=r"(res)
+      : "%r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_ADD_SAT32(a, b) (silk_ADD_SAT32_armv5e(a, b))
+
+#undef silk_SUB_SAT32
+static OPUS_INLINE opus_int32 silk_SUB_SAT32_armv5e(opus_int32 a, opus_int32 b)
+{
+  int res;
+  __asm__(
+      "#silk_SUB_SAT32\n\t"
+      "qsub %0, %1, %2\n\t"
+      : "=r"(res)
+      : "r"(a), "r"(b)
+  );
+  return res;
+}
+#define silk_SUB_SAT32(a, b) (silk_SUB_SAT32_armv5e(a, b))
+
+#undef silk_CLZ16
+static OPUS_INLINE opus_int32 silk_CLZ16_armv5(opus_int16 in16)
+{
+  int res;
+  __asm__(
+      "#silk_CLZ16\n\t"
+      "clz %0, %1;\n"
+      : "=r"(res)
+      : "r"(SAFE_SHL(in16,16)|0x8000)
+  );
+  return res;
+}
+#define silk_CLZ16(in16) (silk_CLZ16_armv5(in16))
+
+#undef silk_CLZ32
+static OPUS_INLINE opus_int32 silk_CLZ32_armv5(opus_int32 in32)
+{
+  int res;
+  __asm__(
+      "#silk_CLZ32\n\t"
+      "clz %0, %1\n\t"
+      : "=r"(res)
+      : "r"(in32)
+  );
+  return res;
+}
+#define silk_CLZ32(in32) (silk_CLZ32_armv5(in32))
+
+#undef SAFE_SHL
+
+#endif /* SILK_MACROS_ARMv5E_H */
diff --git a/opus/silk/biquad_alt.c b/opus/silk/biquad_alt.c
new file mode 100644 (file)
index 0000000..54566a4
--- /dev/null
@@ -0,0 +1,121 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+/*                                                                      *
+ * silk_biquad_alt.c                                              *
+ *                                                                      *
+ * Second order ARMA filter                                             *
+ * Can handle slowly varying filter coefficients                        *
+ *                                                                      */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Second order ARMA filter, alternative implementation */
+void silk_biquad_alt_stride1(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [2]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+)
+{
+    /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
+    opus_int   k;
+    opus_int32 inval, A0_U_Q28, A0_L_Q28, A1_U_Q28, A1_L_Q28, out32_Q14;
+
+    /* Negate A_Q28 values and split in two parts */
+    A0_L_Q28 = ( -A_Q28[ 0 ] ) & 0x00003FFF;        /* lower part */
+    A0_U_Q28 = silk_RSHIFT( -A_Q28[ 0 ], 14 );      /* upper part */
+    A1_L_Q28 = ( -A_Q28[ 1 ] ) & 0x00003FFF;        /* lower part */
+    A1_U_Q28 = silk_RSHIFT( -A_Q28[ 1 ], 14 );      /* upper part */
+
+    for( k = 0; k < len; k++ ) {
+        /* S[ 0 ], S[ 1 ]: Q12 */
+        inval = in[ k ];
+        out32_Q14 = silk_LSHIFT( silk_SMLAWB( S[ 0 ], B_Q28[ 0 ], inval ), 2 );
+
+        S[ 0 ] = S[1] + silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14, A0_L_Q28 ), 14 );
+        S[ 0 ] = silk_SMLAWB( S[ 0 ], out32_Q14, A0_U_Q28 );
+        S[ 0 ] = silk_SMLAWB( S[ 0 ], B_Q28[ 1 ], inval);
+
+        S[ 1 ] = silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14, A1_L_Q28 ), 14 );
+        S[ 1 ] = silk_SMLAWB( S[ 1 ], out32_Q14, A1_U_Q28 );
+        S[ 1 ] = silk_SMLAWB( S[ 1 ], B_Q28[ 2 ], inval );
+
+        /* Scale back to Q0 and saturate */
+        out[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14 + (1<<14) - 1, 14 ) );
+    }
+}
+
+void silk_biquad_alt_stride2_c(
+    const opus_int16            *in,                /* I     input signal                                               */
+    const opus_int32            *B_Q28,             /* I     MA coefficients [3]                                        */
+    const opus_int32            *A_Q28,             /* I     AR coefficients [2]                                        */
+    opus_int32                  *S,                 /* I/O   State vector [4]                                           */
+    opus_int16                  *out,               /* O     output signal                                              */
+    const opus_int32            len                 /* I     signal length (must be even)                               */
+)
+{
+    /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
+    opus_int   k;
+    opus_int32 A0_U_Q28, A0_L_Q28, A1_U_Q28, A1_L_Q28, out32_Q14[ 2 ];
+
+    /* Negate A_Q28 values and split in two parts */
+    A0_L_Q28 = ( -A_Q28[ 0 ] ) & 0x00003FFF;        /* lower part */
+    A0_U_Q28 = silk_RSHIFT( -A_Q28[ 0 ], 14 );      /* upper part */
+    A1_L_Q28 = ( -A_Q28[ 1 ] ) & 0x00003FFF;        /* lower part */
+    A1_U_Q28 = silk_RSHIFT( -A_Q28[ 1 ], 14 );      /* upper part */
+
+    for( k = 0; k < len; k++ ) {
+        /* S[ 0 ], S[ 1 ], S[ 2 ], S[ 3 ]: Q12 */
+        out32_Q14[ 0 ] = silk_LSHIFT( silk_SMLAWB( S[ 0 ], B_Q28[ 0 ], in[ 2 * k + 0 ] ), 2 );
+        out32_Q14[ 1 ] = silk_LSHIFT( silk_SMLAWB( S[ 2 ], B_Q28[ 0 ], in[ 2 * k + 1 ] ), 2 );
+
+        S[ 0 ] = S[ 1 ] + silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14[ 0 ], A0_L_Q28 ), 14 );
+        S[ 2 ] = S[ 3 ] + silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14[ 1 ], A0_L_Q28 ), 14 );
+        S[ 0 ] = silk_SMLAWB( S[ 0 ], out32_Q14[ 0 ], A0_U_Q28 );
+        S[ 2 ] = silk_SMLAWB( S[ 2 ], out32_Q14[ 1 ], A0_U_Q28 );
+        S[ 0 ] = silk_SMLAWB( S[ 0 ], B_Q28[ 1 ], in[ 2 * k + 0 ] );
+        S[ 2 ] = silk_SMLAWB( S[ 2 ], B_Q28[ 1 ], in[ 2 * k + 1 ] );
+
+        S[ 1 ] = silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14[ 0 ], A1_L_Q28 ), 14 );
+        S[ 3 ] = silk_RSHIFT_ROUND( silk_SMULWB( out32_Q14[ 1 ], A1_L_Q28 ), 14 );
+        S[ 1 ] = silk_SMLAWB( S[ 1 ], out32_Q14[ 0 ], A1_U_Q28 );
+        S[ 3 ] = silk_SMLAWB( S[ 3 ], out32_Q14[ 1 ], A1_U_Q28 );
+        S[ 1 ] = silk_SMLAWB( S[ 1 ], B_Q28[ 2 ], in[ 2 * k + 0 ] );
+        S[ 3 ] = silk_SMLAWB( S[ 3 ], B_Q28[ 2 ], in[ 2 * k + 1 ] );
+
+        /* Scale back to Q0 and saturate */
+        out[ 2 * k + 0 ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14[ 0 ] + (1<<14) - 1, 14 ) );
+        out[ 2 * k + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT( out32_Q14[ 1 ] + (1<<14) - 1, 14 ) );
+    }
+}
diff --git a/opus/silk/bwexpander.c b/opus/silk/bwexpander.c
new file mode 100644 (file)
index 0000000..afa9790
--- /dev/null
@@ -0,0 +1,51 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Chirp (bandwidth expand) LP AR filter */
+void silk_bwexpander(
+    opus_int16                  *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int              d,                  /* I    Length of ar                                                */
+    opus_int32                  chirp_Q16           /* I    Chirp factor (typically in the range 0 to 1)                */
+)
+{
+    opus_int   i;
+    opus_int32 chirp_minus_one_Q16 = chirp_Q16 - 65536;
+
+    /* NB: Dont use silk_SMULWB, instead of silk_RSHIFT_ROUND( silk_MUL(), 16 ), below.  */
+    /* Bias in silk_SMULWB can lead to unstable filters                                */
+    for( i = 0; i < d - 1; i++ ) {
+        ar[ i ]    = (opus_int16)silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, ar[ i ]             ), 16 );
+        chirp_Q16 +=             silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, chirp_minus_one_Q16 ), 16 );
+    }
+    ar[ d - 1 ] = (opus_int16)silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, ar[ d - 1 ] ), 16 );
+}
diff --git a/opus/silk/bwexpander_32.c b/opus/silk/bwexpander_32.c
new file mode 100644 (file)
index 0000000..d0010f7
--- /dev/null
@@ -0,0 +1,50 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Chirp (bandwidth expand) LP AR filter */
+void silk_bwexpander_32(
+    opus_int32                  *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int              d,                  /* I    Length of ar                                                */
+    opus_int32                  chirp_Q16           /* I    Chirp factor in Q16                                         */
+)
+{
+    opus_int   i;
+    opus_int32 chirp_minus_one_Q16 = chirp_Q16 - 65536;
+
+    for( i = 0; i < d - 1; i++ ) {
+        ar[ i ]    = silk_SMULWW( chirp_Q16, ar[ i ] );
+        chirp_Q16 += silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, chirp_minus_one_Q16 ), 16 );
+    }
+    ar[ d - 1 ] = silk_SMULWW( chirp_Q16, ar[ d - 1 ] );
+}
+
diff --git a/opus/silk/check_control_input.c b/opus/silk/check_control_input.c
new file mode 100644 (file)
index 0000000..b5de9ce
--- /dev/null
@@ -0,0 +1,106 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "control.h"
+#include "errors.h"
+
+/* Check encoder control struct */
+opus_int check_control_input(
+    silk_EncControlStruct        *encControl                    /* I    Control structure                           */
+)
+{
+    silk_assert( encControl != NULL );
+
+    if( ( ( encControl->API_sampleRate            !=  8000 ) &&
+          ( encControl->API_sampleRate            != 12000 ) &&
+          ( encControl->API_sampleRate            != 16000 ) &&
+          ( encControl->API_sampleRate            != 24000 ) &&
+          ( encControl->API_sampleRate            != 32000 ) &&
+          ( encControl->API_sampleRate            != 44100 ) &&
+          ( encControl->API_sampleRate            != 48000 ) ) ||
+        ( ( encControl->desiredInternalSampleRate !=  8000 ) &&
+          ( encControl->desiredInternalSampleRate != 12000 ) &&
+          ( encControl->desiredInternalSampleRate != 16000 ) ) ||
+        ( ( encControl->maxInternalSampleRate     !=  8000 ) &&
+          ( encControl->maxInternalSampleRate     != 12000 ) &&
+          ( encControl->maxInternalSampleRate     != 16000 ) ) ||
+        ( ( encControl->minInternalSampleRate     !=  8000 ) &&
+          ( encControl->minInternalSampleRate     != 12000 ) &&
+          ( encControl->minInternalSampleRate     != 16000 ) ) ||
+          ( encControl->minInternalSampleRate > encControl->desiredInternalSampleRate ) ||
+          ( encControl->maxInternalSampleRate < encControl->desiredInternalSampleRate ) ||
+          ( encControl->minInternalSampleRate > encControl->maxInternalSampleRate ) ) {
+        silk_assert( 0 );
+        return SILK_ENC_FS_NOT_SUPPORTED;
+    }
+    if( encControl->payloadSize_ms != 10 &&
+        encControl->payloadSize_ms != 20 &&
+        encControl->payloadSize_ms != 40 &&
+        encControl->payloadSize_ms != 60 ) {
+        silk_assert( 0 );
+        return SILK_ENC_PACKET_SIZE_NOT_SUPPORTED;
+    }
+    if( encControl->packetLossPercentage < 0 || encControl->packetLossPercentage > 100 ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_LOSS_RATE;
+    }
+    if( encControl->useDTX < 0 || encControl->useDTX > 1 ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_DTX_SETTING;
+    }
+    if( encControl->useCBR < 0 || encControl->useCBR > 1 ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_CBR_SETTING;
+    }
+    if( encControl->useInBandFEC < 0 || encControl->useInBandFEC > 1 ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_INBAND_FEC_SETTING;
+    }
+    if( encControl->nChannelsAPI < 1 || encControl->nChannelsAPI > ENCODER_NUM_CHANNELS ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_NUMBER_OF_CHANNELS_ERROR;
+    }
+    if( encControl->nChannelsInternal < 1 || encControl->nChannelsInternal > ENCODER_NUM_CHANNELS ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_NUMBER_OF_CHANNELS_ERROR;
+    }
+    if( encControl->nChannelsInternal > encControl->nChannelsAPI ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_NUMBER_OF_CHANNELS_ERROR;
+    }
+    if( encControl->complexity < 0 || encControl->complexity > 10 ) {
+        silk_assert( 0 );
+        return SILK_ENC_INVALID_COMPLEXITY_SETTING;
+    }
+
+    return SILK_NO_ERROR;
+}
diff --git a/opus/silk/code_signs.c b/opus/silk/code_signs.c
new file mode 100644 (file)
index 0000000..dfd1dca
--- /dev/null
@@ -0,0 +1,115 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/*#define silk_enc_map(a)                ((a) > 0 ? 1 : 0)*/
+/*#define silk_dec_map(a)                ((a) > 0 ? 1 : -1)*/
+/* shifting avoids if-statement */
+#define silk_enc_map(a)                  ( silk_RSHIFT( (a), 15 ) + 1 )
+#define silk_dec_map(a)                  ( silk_LSHIFT( (a),  1 ) - 1 )
+
+/* Encodes signs of excitation */
+void silk_encode_signs(
+    ec_enc                      *psRangeEnc,                        /* I/O  Compressor data structure                   */
+    const opus_int8             pulses[],                           /* I    pulse signal                                */
+    opus_int                    length,                             /* I    length of input                             */
+    const opus_int              signalType,                         /* I    Signal type                                 */
+    const opus_int              quantOffsetType,                    /* I    Quantization offset type                    */
+    const opus_int              sum_pulses[ MAX_NB_SHELL_BLOCKS ]   /* I    Sum of absolute pulses per block            */
+)
+{
+    opus_int         i, j, p;
+    opus_uint8       icdf[ 2 ];
+    const opus_int8  *q_ptr;
+    const opus_uint8 *icdf_ptr;
+
+    icdf[ 1 ] = 0;
+    q_ptr = pulses;
+    i = silk_SMULBB( 7, silk_ADD_LSHIFT( quantOffsetType, signalType, 1 ) );
+    icdf_ptr = &silk_sign_iCDF[ i ];
+    length = silk_RSHIFT( length + SHELL_CODEC_FRAME_LENGTH/2, LOG2_SHELL_CODEC_FRAME_LENGTH );
+    for( i = 0; i < length; i++ ) {
+        p = sum_pulses[ i ];
+        if( p > 0 ) {
+            icdf[ 0 ] = icdf_ptr[ silk_min( p & 0x1F, 6 ) ];
+            for( j = 0; j < SHELL_CODEC_FRAME_LENGTH; j++ ) {
+                if( q_ptr[ j ] != 0 ) {
+                    ec_enc_icdf( psRangeEnc, silk_enc_map( q_ptr[ j ]), icdf, 8 );
+                }
+            }
+        }
+        q_ptr += SHELL_CODEC_FRAME_LENGTH;
+    }
+}
+
+/* Decodes signs of excitation */
+void silk_decode_signs(
+    ec_dec                      *psRangeDec,                        /* I/O  Compressor data structure                   */
+    opus_int16                  pulses[],                           /* I/O  pulse signal                                */
+    opus_int                    length,                             /* I    length of input                             */
+    const opus_int              signalType,                         /* I    Signal type                                 */
+    const opus_int              quantOffsetType,                    /* I    Quantization offset type                    */
+    const opus_int              sum_pulses[ MAX_NB_SHELL_BLOCKS ]   /* I    Sum of absolute pulses per block            */
+)
+{
+    opus_int         i, j, p;
+    opus_uint8       icdf[ 2 ];
+    opus_int16       *q_ptr;
+    const opus_uint8 *icdf_ptr;
+
+    icdf[ 1 ] = 0;
+    q_ptr = pulses;
+    i = silk_SMULBB( 7, silk_ADD_LSHIFT( quantOffsetType, signalType, 1 ) );
+    icdf_ptr = &silk_sign_iCDF[ i ];
+    length = silk_RSHIFT( length + SHELL_CODEC_FRAME_LENGTH/2, LOG2_SHELL_CODEC_FRAME_LENGTH );
+    for( i = 0; i < length; i++ ) {
+        p = sum_pulses[ i ];
+        if( p > 0 ) {
+            icdf[ 0 ] = icdf_ptr[ silk_min( p & 0x1F, 6 ) ];
+            for( j = 0; j < SHELL_CODEC_FRAME_LENGTH; j++ ) {
+                if( q_ptr[ j ] > 0 ) {
+                    /* attach sign */
+#if 0
+                    /* conditional implementation */
+                    if( ec_dec_icdf( psRangeDec, icdf, 8 ) == 0 ) {
+                        q_ptr[ j ] = -q_ptr[ j ];
+                    }
+#else
+                    /* implementation with shift, subtraction, multiplication */
+                    q_ptr[ j ] *= silk_dec_map( ec_dec_icdf( psRangeDec, icdf, 8 ) );
+#endif
+                }
+            }
+        }
+        q_ptr += SHELL_CODEC_FRAME_LENGTH;
+    }
+}
diff --git a/opus/silk/control.h b/opus/silk/control.h
new file mode 100644 (file)
index 0000000..b76ec33
--- /dev/null
@@ -0,0 +1,150 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_CONTROL_H
+#define SILK_CONTROL_H
+
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Decoder API flags */
+#define FLAG_DECODE_NORMAL                      0
+#define FLAG_PACKET_LOST                        1
+#define FLAG_DECODE_LBRR                        2
+
+/***********************************************/
+/* Structure for controlling encoder operation */
+/***********************************************/
+typedef struct {
+    /* I:   Number of channels; 1/2                                                         */
+    opus_int32 nChannelsAPI;
+
+    /* I:   Number of channels; 1/2                                                         */
+    opus_int32 nChannelsInternal;
+
+    /* I:   Input signal sampling rate in Hertz; 8000/12000/16000/24000/32000/44100/48000   */
+    opus_int32 API_sampleRate;
+
+    /* I:   Maximum internal sampling rate in Hertz; 8000/12000/16000                       */
+    opus_int32 maxInternalSampleRate;
+
+    /* I:   Minimum internal sampling rate in Hertz; 8000/12000/16000                       */
+    opus_int32 minInternalSampleRate;
+
+    /* I:   Soft request for internal sampling rate in Hertz; 8000/12000/16000              */
+    opus_int32 desiredInternalSampleRate;
+
+    /* I:   Number of samples per packet in milliseconds; 10/20/40/60                       */
+    opus_int payloadSize_ms;
+
+    /* I:   Bitrate during active speech in bits/second; internally limited                 */
+    opus_int32 bitRate;
+
+    /* I:   Uplink packet loss in percent (0-100)                                           */
+    opus_int packetLossPercentage;
+
+    /* I:   Complexity mode; 0 is lowest, 10 is highest complexity                          */
+    opus_int complexity;
+
+    /* I:   Flag to enable in-band Forward Error Correction (FEC); 0/1                      */
+    opus_int useInBandFEC;
+
+    /* I:   Flag to actually code in-band Forward Error Correction (FEC) in the current packet; 0/1 */
+    opus_int LBRR_coded;
+
+    /* I:   Flag to enable discontinuous transmission (DTX); 0/1                            */
+    opus_int useDTX;
+
+    /* I:   Flag to use constant bitrate                                                    */
+    opus_int useCBR;
+
+    /* I:   Maximum number of bits allowed for the frame                                    */
+    opus_int maxBits;
+
+    /* I:   Causes a smooth downmix to mono                                                 */
+    opus_int toMono;
+
+    /* I:   Opus encoder is allowing us to switch bandwidth                                 */
+    opus_int opusCanSwitch;
+
+    /* I: Make frames as independent as possible (but still use LPC)                        */
+    opus_int reducedDependency;
+
+    /* O:   Internal sampling rate used, in Hertz; 8000/12000/16000                         */
+    opus_int32 internalSampleRate;
+
+    /* O: Flag that bandwidth switching is allowed (because low voice activity)             */
+    opus_int allowBandwidthSwitch;
+
+    /* O:   Flag that SILK runs in WB mode without variable LP filter (use for switching between WB/SWB/FB) */
+    opus_int inWBmodeWithoutVariableLP;
+
+    /* O:   Stereo width */
+    opus_int stereoWidth_Q14;
+
+    /* O:   Tells the Opus encoder we're ready to switch                                    */
+    opus_int switchReady;
+
+    /* O: SILK Signal type */
+    opus_int signalType;
+
+    /* O: SILK offset (dithering) */
+    opus_int offset;
+} silk_EncControlStruct;
+
+/**************************************************************************/
+/* Structure for controlling decoder operation and reading decoder status */
+/**************************************************************************/
+typedef struct {
+    /* I:   Number of channels; 1/2                                                         */
+    opus_int32 nChannelsAPI;
+
+    /* I:   Number of channels; 1/2                                                         */
+    opus_int32 nChannelsInternal;
+
+    /* I:   Output signal sampling rate in Hertz; 8000/12000/16000/24000/32000/44100/48000  */
+    opus_int32 API_sampleRate;
+
+    /* I:   Internal sampling rate used, in Hertz; 8000/12000/16000                         */
+    opus_int32 internalSampleRate;
+
+    /* I:   Number of samples per packet in milliseconds; 10/20/40/60                       */
+    opus_int payloadSize_ms;
+
+    /* O:   Pitch lag of previous frame (0 if unvoiced), measured in samples at 48 kHz      */
+    opus_int prevPitchLag;
+} silk_DecControlStruct;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/control_SNR.c b/opus/silk/control_SNR.c
new file mode 100644 (file)
index 0000000..464c1ac
--- /dev/null
@@ -0,0 +1,75 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "tuning_parameters.h"
+
+/* Control SNR of redidual quantizer */
+opus_int silk_control_SNR(
+    silk_encoder_state          *psEncC,                        /* I/O  Pointer to Silk encoder state               */
+    opus_int32                  TargetRate_bps                  /* I    Target max bitrate (bps)                    */
+)
+{
+    opus_int k, ret = SILK_NO_ERROR;
+    opus_int32 frac_Q6;
+    const opus_int32 *rateTable;
+
+    /* Set bitrate/coding quality */
+    TargetRate_bps = silk_LIMIT( TargetRate_bps, MIN_TARGET_RATE_BPS, MAX_TARGET_RATE_BPS );
+    if( TargetRate_bps != psEncC->TargetRate_bps ) {
+        psEncC->TargetRate_bps = TargetRate_bps;
+
+        /* If new TargetRate_bps, translate to SNR_dB value */
+        if( psEncC->fs_kHz == 8 ) {
+            rateTable = silk_TargetRate_table_NB;
+        } else if( psEncC->fs_kHz == 12 ) {
+            rateTable = silk_TargetRate_table_MB;
+        } else {
+            rateTable = silk_TargetRate_table_WB;
+        }
+
+        /* Reduce bitrate for 10 ms modes in these calculations */
+        if( psEncC->nb_subfr == 2 ) {
+            TargetRate_bps -= REDUCE_BITRATE_10_MS_BPS;
+        }
+
+        /* Find bitrate interval in table and interpolate */
+        for( k = 1; k < TARGET_RATE_TAB_SZ; k++ ) {
+            if( TargetRate_bps <= rateTable[ k ] ) {
+                frac_Q6 = silk_DIV32( silk_LSHIFT( TargetRate_bps - rateTable[ k - 1 ], 6 ), rateTable[ k ] - rateTable[ k - 1 ] );
+                psEncC->SNR_dB_Q7 = silk_LSHIFT( silk_SNR_table_Q1[ k - 1 ], 6 ) + silk_MUL( frac_Q6, silk_SNR_table_Q1[ k ] - silk_SNR_table_Q1[ k - 1 ] );
+                break;
+            }
+        }
+    }
+
+    return ret;
+}
diff --git a/opus/silk/control_audio_bandwidth.c b/opus/silk/control_audio_bandwidth.c
new file mode 100644 (file)
index 0000000..4f9bc5c
--- /dev/null
@@ -0,0 +1,126 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "tuning_parameters.h"
+
+/* Control internal sampling rate */
+opus_int silk_control_audio_bandwidth(
+    silk_encoder_state          *psEncC,                        /* I/O  Pointer to Silk encoder state               */
+    silk_EncControlStruct       *encControl                     /* I    Control structure                           */
+)
+{
+    opus_int   fs_kHz;
+    opus_int32 fs_Hz;
+
+    fs_kHz = psEncC->fs_kHz;
+    fs_Hz = silk_SMULBB( fs_kHz, 1000 );
+    if( fs_Hz == 0 ) {
+        /* Encoder has just been initialized */
+        fs_Hz  = silk_min( psEncC->desiredInternal_fs_Hz, psEncC->API_fs_Hz );
+        fs_kHz = silk_DIV32_16( fs_Hz, 1000 );
+    } else if( fs_Hz > psEncC->API_fs_Hz || fs_Hz > psEncC->maxInternal_fs_Hz || fs_Hz < psEncC->minInternal_fs_Hz ) {
+        /* Make sure internal rate is not higher than external rate or maximum allowed, or lower than minimum allowed */
+        fs_Hz  = psEncC->API_fs_Hz;
+        fs_Hz  = silk_min( fs_Hz, psEncC->maxInternal_fs_Hz );
+        fs_Hz  = silk_max( fs_Hz, psEncC->minInternal_fs_Hz );
+        fs_kHz = silk_DIV32_16( fs_Hz, 1000 );
+    } else {
+        /* State machine for the internal sampling rate switching */
+        if( psEncC->sLP.transition_frame_no >= TRANSITION_FRAMES ) {
+            /* Stop transition phase */
+            psEncC->sLP.mode = 0;
+        }
+        if( psEncC->allow_bandwidth_switch || encControl->opusCanSwitch ) {
+            /* Check if we should switch down */
+            if( silk_SMULBB( psEncC->fs_kHz, 1000 ) > psEncC->desiredInternal_fs_Hz )
+            {
+                /* Switch down */
+                if( psEncC->sLP.mode == 0 ) {
+                    /* New transition */
+                    psEncC->sLP.transition_frame_no = TRANSITION_FRAMES;
+
+                    /* Reset transition filter state */
+                    silk_memset( psEncC->sLP.In_LP_State, 0, sizeof( psEncC->sLP.In_LP_State ) );
+                }
+                if( encControl->opusCanSwitch ) {
+                    /* Stop transition phase */
+                    psEncC->sLP.mode = 0;
+
+                    /* Switch to a lower sample frequency */
+                    fs_kHz = psEncC->fs_kHz == 16 ? 12 : 8;
+                } else {
+                   if( psEncC->sLP.transition_frame_no <= 0 ) {
+                       encControl->switchReady = 1;
+                       /* Make room for redundancy */
+                       encControl->maxBits -= encControl->maxBits * 5 / ( encControl->payloadSize_ms + 5 );
+                   } else {
+                       /* Direction: down (at double speed) */
+                       psEncC->sLP.mode = -2;
+                   }
+                }
+            }
+            else
+            /* Check if we should switch up */
+            if( silk_SMULBB( psEncC->fs_kHz, 1000 ) < psEncC->desiredInternal_fs_Hz )
+            {
+                /* Switch up */
+                if( encControl->opusCanSwitch ) {
+                    /* Switch to a higher sample frequency */
+                    fs_kHz = psEncC->fs_kHz == 8 ? 12 : 16;
+
+                    /* New transition */
+                    psEncC->sLP.transition_frame_no = 0;
+
+                    /* Reset transition filter state */
+                    silk_memset( psEncC->sLP.In_LP_State, 0, sizeof( psEncC->sLP.In_LP_State ) );
+
+                    /* Direction: up */
+                    psEncC->sLP.mode = 1;
+                } else {
+                   if( psEncC->sLP.mode == 0 ) {
+                       encControl->switchReady = 1;
+                       /* Make room for redundancy */
+                       encControl->maxBits -= encControl->maxBits * 5 / ( encControl->payloadSize_ms + 5 );
+                   } else {
+                       /* Direction: up */
+                       psEncC->sLP.mode = 1;
+                   }
+                }
+            } else {
+               if (psEncC->sLP.mode<0)
+                  psEncC->sLP.mode = 1;
+            }
+        }
+    }
+
+    return fs_kHz;
+}
diff --git a/opus/silk/control_codec.c b/opus/silk/control_codec.c
new file mode 100644 (file)
index 0000000..9350fd4
--- /dev/null
@@ -0,0 +1,423 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#ifdef FIXED_POINT
+#include "main_FIX.h"
+#define silk_encoder_state_Fxx      silk_encoder_state_FIX
+#else
+#include "main_FLP.h"
+#define silk_encoder_state_Fxx      silk_encoder_state_FLP
+#endif
+#include "stack_alloc.h"
+#include "tuning_parameters.h"
+#include "pitch_est_defines.h"
+
+static opus_int silk_setup_resamplers(
+    silk_encoder_state_Fxx          *psEnc,             /* I/O                      */
+    opus_int                        fs_kHz              /* I                        */
+);
+
+static opus_int silk_setup_fs(
+    silk_encoder_state_Fxx          *psEnc,             /* I/O                      */
+    opus_int                        fs_kHz,             /* I                        */
+    opus_int                        PacketSize_ms       /* I                        */
+);
+
+static opus_int silk_setup_complexity(
+    silk_encoder_state              *psEncC,            /* I/O                      */
+    opus_int                        Complexity          /* I                        */
+);
+
+static OPUS_INLINE opus_int silk_setup_LBRR(
+    silk_encoder_state              *psEncC,            /* I/O                      */
+    const silk_EncControlStruct     *encControl         /* I                        */
+);
+
+
+/* Control encoder */
+opus_int silk_control_encoder(
+    silk_encoder_state_Fxx          *psEnc,                                 /* I/O  Pointer to Silk encoder state                                               */
+    silk_EncControlStruct           *encControl,                            /* I    Control structure                                                           */
+    const opus_int                  allow_bw_switch,                        /* I    Flag to allow switching audio bandwidth                                     */
+    const opus_int                  channelNb,                              /* I    Channel number                                                              */
+    const opus_int                  force_fs_kHz
+)
+{
+    opus_int   fs_kHz, ret = 0;
+
+    psEnc->sCmn.useDTX                 = encControl->useDTX;
+    psEnc->sCmn.useCBR                 = encControl->useCBR;
+    psEnc->sCmn.API_fs_Hz              = encControl->API_sampleRate;
+    psEnc->sCmn.maxInternal_fs_Hz      = encControl->maxInternalSampleRate;
+    psEnc->sCmn.minInternal_fs_Hz      = encControl->minInternalSampleRate;
+    psEnc->sCmn.desiredInternal_fs_Hz  = encControl->desiredInternalSampleRate;
+    psEnc->sCmn.useInBandFEC           = encControl->useInBandFEC;
+    psEnc->sCmn.nChannelsAPI           = encControl->nChannelsAPI;
+    psEnc->sCmn.nChannelsInternal      = encControl->nChannelsInternal;
+    psEnc->sCmn.allow_bandwidth_switch = allow_bw_switch;
+    psEnc->sCmn.channelNb              = channelNb;
+
+    if( psEnc->sCmn.controlled_since_last_payload != 0 && psEnc->sCmn.prefillFlag == 0 ) {
+        if( psEnc->sCmn.API_fs_Hz != psEnc->sCmn.prev_API_fs_Hz && psEnc->sCmn.fs_kHz > 0 ) {
+            /* Change in API sampling rate in the middle of encoding a packet */
+            ret += silk_setup_resamplers( psEnc, psEnc->sCmn.fs_kHz );
+        }
+        return ret;
+    }
+
+    /* Beyond this point we know that there are no previously coded frames in the payload buffer */
+
+    /********************************************/
+    /* Determine internal sampling rate         */
+    /********************************************/
+    fs_kHz = silk_control_audio_bandwidth( &psEnc->sCmn, encControl );
+    if( force_fs_kHz ) {
+       fs_kHz = force_fs_kHz;
+    }
+    /********************************************/
+    /* Prepare resampler and buffered data      */
+    /********************************************/
+    ret += silk_setup_resamplers( psEnc, fs_kHz );
+
+    /********************************************/
+    /* Set internal sampling frequency          */
+    /********************************************/
+    ret += silk_setup_fs( psEnc, fs_kHz, encControl->payloadSize_ms );
+
+    /********************************************/
+    /* Set encoding complexity                  */
+    /********************************************/
+    ret += silk_setup_complexity( &psEnc->sCmn, encControl->complexity  );
+
+    /********************************************/
+    /* Set packet loss rate measured by farend  */
+    /********************************************/
+    psEnc->sCmn.PacketLoss_perc = encControl->packetLossPercentage;
+
+    /********************************************/
+    /* Set LBRR usage                           */
+    /********************************************/
+    ret += silk_setup_LBRR( &psEnc->sCmn, encControl );
+
+    psEnc->sCmn.controlled_since_last_payload = 1;
+
+    return ret;
+}
+
+static opus_int silk_setup_resamplers(
+    silk_encoder_state_Fxx          *psEnc,             /* I/O                      */
+    opus_int                         fs_kHz              /* I                        */
+)
+{
+    opus_int   ret = SILK_NO_ERROR;
+    SAVE_STACK;
+
+    if( psEnc->sCmn.fs_kHz != fs_kHz || psEnc->sCmn.prev_API_fs_Hz != psEnc->sCmn.API_fs_Hz )
+    {
+        if( psEnc->sCmn.fs_kHz == 0 ) {
+            /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */
+            ret += silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, fs_kHz * 1000, 1 );
+        } else {
+            VARDECL( opus_int16, x_buf_API_fs_Hz );
+            VARDECL( silk_resampler_state_struct, temp_resampler_state );
+#ifdef FIXED_POINT
+            opus_int16 *x_bufFIX = psEnc->x_buf;
+#else
+            VARDECL( opus_int16, x_bufFIX );
+            opus_int32 new_buf_samples;
+#endif
+            opus_int32 api_buf_samples;
+            opus_int32 old_buf_samples;
+            opus_int32 buf_length_ms;
+
+            buf_length_ms = silk_LSHIFT( psEnc->sCmn.nb_subfr * 5, 1 ) + LA_SHAPE_MS;
+            old_buf_samples = buf_length_ms * psEnc->sCmn.fs_kHz;
+
+#ifndef FIXED_POINT
+            new_buf_samples = buf_length_ms * fs_kHz;
+            ALLOC( x_bufFIX, silk_max( old_buf_samples, new_buf_samples ),
+                   opus_int16 );
+            silk_float2short_array( x_bufFIX, psEnc->x_buf, old_buf_samples );
+#endif
+
+            /* Initialize resampler for temporary resampling of x_buf data to API_fs_Hz */
+            ALLOC( temp_resampler_state, 1, silk_resampler_state_struct );
+            ret += silk_resampler_init( temp_resampler_state, silk_SMULBB( psEnc->sCmn.fs_kHz, 1000 ), psEnc->sCmn.API_fs_Hz, 0 );
+
+            /* Calculate number of samples to temporarily upsample */
+            api_buf_samples = buf_length_ms * silk_DIV32_16( psEnc->sCmn.API_fs_Hz, 1000 );
+
+            /* Temporary resampling of x_buf data to API_fs_Hz */
+            ALLOC( x_buf_API_fs_Hz, api_buf_samples, opus_int16 );
+            ret += silk_resampler( temp_resampler_state, x_buf_API_fs_Hz, x_bufFIX, old_buf_samples );
+
+            /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */
+            ret += silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, silk_SMULBB( fs_kHz, 1000 ), 1 );
+
+            /* Correct resampler state by resampling buffered data from API_fs_Hz to fs_kHz */
+            ret += silk_resampler( &psEnc->sCmn.resampler_state, x_bufFIX, x_buf_API_fs_Hz, api_buf_samples );
+
+#ifndef FIXED_POINT
+            silk_short2float_array( psEnc->x_buf, x_bufFIX, new_buf_samples);
+#endif
+        }
+    }
+
+    psEnc->sCmn.prev_API_fs_Hz = psEnc->sCmn.API_fs_Hz;
+
+    RESTORE_STACK;
+    return ret;
+}
+
+static opus_int silk_setup_fs(
+    silk_encoder_state_Fxx          *psEnc,             /* I/O                      */
+    opus_int                        fs_kHz,             /* I                        */
+    opus_int                        PacketSize_ms       /* I                        */
+)
+{
+    opus_int ret = SILK_NO_ERROR;
+
+    /* Set packet size */
+    if( PacketSize_ms != psEnc->sCmn.PacketSize_ms ) {
+        if( ( PacketSize_ms !=  10 ) &&
+            ( PacketSize_ms !=  20 ) &&
+            ( PacketSize_ms !=  40 ) &&
+            ( PacketSize_ms !=  60 ) ) {
+            ret = SILK_ENC_PACKET_SIZE_NOT_SUPPORTED;
+        }
+        if( PacketSize_ms <= 10 ) {
+            psEnc->sCmn.nFramesPerPacket = 1;
+            psEnc->sCmn.nb_subfr = PacketSize_ms == 10 ? 2 : 1;
+            psEnc->sCmn.frame_length = silk_SMULBB( PacketSize_ms, fs_kHz );
+            psEnc->sCmn.pitch_LPC_win_length = silk_SMULBB( FIND_PITCH_LPC_WIN_MS_2_SF, fs_kHz );
+            if( psEnc->sCmn.fs_kHz == 8 ) {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_10_ms_NB_iCDF;
+            } else {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_10_ms_iCDF;
+            }
+        } else {
+            psEnc->sCmn.nFramesPerPacket = silk_DIV32_16( PacketSize_ms, MAX_FRAME_LENGTH_MS );
+            psEnc->sCmn.nb_subfr = MAX_NB_SUBFR;
+            psEnc->sCmn.frame_length = silk_SMULBB( 20, fs_kHz );
+            psEnc->sCmn.pitch_LPC_win_length = silk_SMULBB( FIND_PITCH_LPC_WIN_MS, fs_kHz );
+            if( psEnc->sCmn.fs_kHz == 8 ) {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_NB_iCDF;
+            } else {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_iCDF;
+            }
+        }
+        psEnc->sCmn.PacketSize_ms  = PacketSize_ms;
+        psEnc->sCmn.TargetRate_bps = 0;         /* trigger new SNR computation */
+    }
+
+    /* Set internal sampling frequency */
+    silk_assert( fs_kHz == 8 || fs_kHz == 12 || fs_kHz == 16 );
+    silk_assert( psEnc->sCmn.nb_subfr == 2 || psEnc->sCmn.nb_subfr == 4 );
+    if( psEnc->sCmn.fs_kHz != fs_kHz ) {
+        /* reset part of the state */
+        silk_memset( &psEnc->sShape,               0, sizeof( psEnc->sShape ) );
+        silk_memset( &psEnc->sCmn.sNSQ,            0, sizeof( psEnc->sCmn.sNSQ ) );
+        silk_memset( psEnc->sCmn.prev_NLSFq_Q15,   0, sizeof( psEnc->sCmn.prev_NLSFq_Q15 ) );
+        silk_memset( &psEnc->sCmn.sLP.In_LP_State, 0, sizeof( psEnc->sCmn.sLP.In_LP_State ) );
+        psEnc->sCmn.inputBufIx                  = 0;
+        psEnc->sCmn.nFramesEncoded              = 0;
+        psEnc->sCmn.TargetRate_bps              = 0;     /* trigger new SNR computation */
+
+        /* Initialize non-zero parameters */
+        psEnc->sCmn.prevLag                     = 100;
+        psEnc->sCmn.first_frame_after_reset     = 1;
+        psEnc->sShape.LastGainIndex             = 10;
+        psEnc->sCmn.sNSQ.lagPrev                = 100;
+        psEnc->sCmn.sNSQ.prev_gain_Q16          = 65536;
+        psEnc->sCmn.prevSignalType              = TYPE_NO_VOICE_ACTIVITY;
+
+        psEnc->sCmn.fs_kHz = fs_kHz;
+        if( psEnc->sCmn.fs_kHz == 8 ) {
+            if( psEnc->sCmn.nb_subfr == MAX_NB_SUBFR ) {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_NB_iCDF;
+            } else {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_10_ms_NB_iCDF;
+            }
+        } else {
+            if( psEnc->sCmn.nb_subfr == MAX_NB_SUBFR ) {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_iCDF;
+            } else {
+                psEnc->sCmn.pitch_contour_iCDF = silk_pitch_contour_10_ms_iCDF;
+            }
+        }
+        if( psEnc->sCmn.fs_kHz == 8 || psEnc->sCmn.fs_kHz == 12 ) {
+            psEnc->sCmn.predictLPCOrder = MIN_LPC_ORDER;
+            psEnc->sCmn.psNLSF_CB  = &silk_NLSF_CB_NB_MB;
+        } else {
+            psEnc->sCmn.predictLPCOrder = MAX_LPC_ORDER;
+            psEnc->sCmn.psNLSF_CB  = &silk_NLSF_CB_WB;
+        }
+        psEnc->sCmn.subfr_length   = SUB_FRAME_LENGTH_MS * fs_kHz;
+        psEnc->sCmn.frame_length   = silk_SMULBB( psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr );
+        psEnc->sCmn.ltp_mem_length = silk_SMULBB( LTP_MEM_LENGTH_MS, fs_kHz );
+        psEnc->sCmn.la_pitch       = silk_SMULBB( LA_PITCH_MS, fs_kHz );
+        psEnc->sCmn.max_pitch_lag  = silk_SMULBB( 18, fs_kHz );
+        if( psEnc->sCmn.nb_subfr == MAX_NB_SUBFR ) {
+            psEnc->sCmn.pitch_LPC_win_length = silk_SMULBB( FIND_PITCH_LPC_WIN_MS, fs_kHz );
+        } else {
+            psEnc->sCmn.pitch_LPC_win_length = silk_SMULBB( FIND_PITCH_LPC_WIN_MS_2_SF, fs_kHz );
+        }
+        if( psEnc->sCmn.fs_kHz == 16 ) {
+            psEnc->sCmn.pitch_lag_low_bits_iCDF = silk_uniform8_iCDF;
+        } else if( psEnc->sCmn.fs_kHz == 12 ) {
+            psEnc->sCmn.pitch_lag_low_bits_iCDF = silk_uniform6_iCDF;
+        } else {
+            psEnc->sCmn.pitch_lag_low_bits_iCDF = silk_uniform4_iCDF;
+        }
+    }
+
+    /* Check that settings are valid */
+    silk_assert( ( psEnc->sCmn.subfr_length * psEnc->sCmn.nb_subfr ) == psEnc->sCmn.frame_length );
+
+    return ret;
+}
+
+static opus_int silk_setup_complexity(
+    silk_encoder_state              *psEncC,            /* I/O                      */
+    opus_int                        Complexity          /* I                        */
+)
+{
+    opus_int ret = 0;
+
+    /* Set encoding complexity */
+    silk_assert( Complexity >= 0 && Complexity <= 10 );
+    if( Complexity < 1 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MIN_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.8, 16 );
+        psEncC->pitchEstimationLPCOrder         = 6;
+        psEncC->shapingLPCOrder                 = 12;
+        psEncC->la_shape                        = 3 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 1;
+        psEncC->useInterpolatedNLSFs            = 0;
+        psEncC->NLSF_MSVQ_Survivors             = 2;
+        psEncC->warping_Q16                     = 0;
+    } else if( Complexity < 2 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MID_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.76, 16 );
+        psEncC->pitchEstimationLPCOrder         = 8;
+        psEncC->shapingLPCOrder                 = 14;
+        psEncC->la_shape                        = 5 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 1;
+        psEncC->useInterpolatedNLSFs            = 0;
+        psEncC->NLSF_MSVQ_Survivors             = 3;
+        psEncC->warping_Q16                     = 0;
+    } else if( Complexity < 3 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MIN_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.8, 16 );
+        psEncC->pitchEstimationLPCOrder         = 6;
+        psEncC->shapingLPCOrder                 = 12;
+        psEncC->la_shape                        = 3 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 2;
+        psEncC->useInterpolatedNLSFs            = 0;
+        psEncC->NLSF_MSVQ_Survivors             = 2;
+        psEncC->warping_Q16                     = 0;
+    } else if( Complexity < 4 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MID_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.76, 16 );
+        psEncC->pitchEstimationLPCOrder         = 8;
+        psEncC->shapingLPCOrder                 = 14;
+        psEncC->la_shape                        = 5 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 2;
+        psEncC->useInterpolatedNLSFs            = 0;
+        psEncC->NLSF_MSVQ_Survivors             = 4;
+        psEncC->warping_Q16                     = 0;
+    } else if( Complexity < 6 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MID_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.74, 16 );
+        psEncC->pitchEstimationLPCOrder         = 10;
+        psEncC->shapingLPCOrder                 = 16;
+        psEncC->la_shape                        = 5 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 2;
+        psEncC->useInterpolatedNLSFs            = 1;
+        psEncC->NLSF_MSVQ_Survivors             = 6;
+        psEncC->warping_Q16                     = psEncC->fs_kHz * SILK_FIX_CONST( WARPING_MULTIPLIER, 16 );
+    } else if( Complexity < 8 ) {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MID_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.72, 16 );
+        psEncC->pitchEstimationLPCOrder         = 12;
+        psEncC->shapingLPCOrder                 = 20;
+        psEncC->la_shape                        = 5 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = 3;
+        psEncC->useInterpolatedNLSFs            = 1;
+        psEncC->NLSF_MSVQ_Survivors             = 8;
+        psEncC->warping_Q16                     = psEncC->fs_kHz * SILK_FIX_CONST( WARPING_MULTIPLIER, 16 );
+    } else {
+        psEncC->pitchEstimationComplexity       = SILK_PE_MAX_COMPLEX;
+        psEncC->pitchEstimationThreshold_Q16    = SILK_FIX_CONST( 0.7, 16 );
+        psEncC->pitchEstimationLPCOrder         = 16;
+        psEncC->shapingLPCOrder                 = 24;
+        psEncC->la_shape                        = 5 * psEncC->fs_kHz;
+        psEncC->nStatesDelayedDecision          = MAX_DEL_DEC_STATES;
+        psEncC->useInterpolatedNLSFs            = 1;
+        psEncC->NLSF_MSVQ_Survivors             = 16;
+        psEncC->warping_Q16                     = psEncC->fs_kHz * SILK_FIX_CONST( WARPING_MULTIPLIER, 16 );
+    }
+
+    /* Do not allow higher pitch estimation LPC order than predict LPC order */
+    psEncC->pitchEstimationLPCOrder = silk_min_int( psEncC->pitchEstimationLPCOrder, psEncC->predictLPCOrder );
+    psEncC->shapeWinLength          = SUB_FRAME_LENGTH_MS * psEncC->fs_kHz + 2 * psEncC->la_shape;
+    psEncC->Complexity              = Complexity;
+
+    silk_assert( psEncC->pitchEstimationLPCOrder <= MAX_FIND_PITCH_LPC_ORDER );
+    silk_assert( psEncC->shapingLPCOrder         <= MAX_SHAPE_LPC_ORDER      );
+    silk_assert( psEncC->nStatesDelayedDecision  <= MAX_DEL_DEC_STATES       );
+    silk_assert( psEncC->warping_Q16             <= 32767                    );
+    silk_assert( psEncC->la_shape                <= LA_SHAPE_MAX             );
+    silk_assert( psEncC->shapeWinLength          <= SHAPE_LPC_WIN_MAX        );
+
+    return ret;
+}
+
+static OPUS_INLINE opus_int silk_setup_LBRR(
+    silk_encoder_state          *psEncC,            /* I/O                      */
+    const silk_EncControlStruct *encControl         /* I                        */
+)
+{
+    opus_int   LBRR_in_previous_packet, ret = SILK_NO_ERROR;
+
+    LBRR_in_previous_packet = psEncC->LBRR_enabled;
+    psEncC->LBRR_enabled = encControl->LBRR_coded;
+    if( psEncC->LBRR_enabled ) {
+        /* Set gain increase for coding LBRR excitation */
+        if( LBRR_in_previous_packet == 0 ) {
+            /* Previous packet did not have LBRR, and was therefore coded at a higher bitrate */
+            psEncC->LBRR_GainIncreases = 7;
+        } else {
+            psEncC->LBRR_GainIncreases = silk_max_int( 7 - silk_SMULWB( (opus_int32)psEncC->PacketLoss_perc, SILK_FIX_CONST( 0.4, 16 ) ), 2 );
+        }
+    }
+
+    return ret;
+}
diff --git a/opus/silk/debug.c b/opus/silk/debug.c
new file mode 100644 (file)
index 0000000..9253faf
--- /dev/null
@@ -0,0 +1,170 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "debug.h"
+#include "SigProc_FIX.h"
+
+#if SILK_TIC_TOC
+
+#ifdef _WIN32
+
+#if (defined(_WIN32) || defined(_WINCE))
+#include <windows.h>    /* timer */
+#else   /* Linux or Mac*/
+#include <sys/time.h>
+#endif
+
+unsigned long silk_GetHighResolutionTime(void) /* O  time in usec*/
+{
+    /* Returns a time counter in microsec   */
+    /* the resolution is platform dependent */
+    /* but is typically 1.62 us resolution  */
+    LARGE_INTEGER lpPerformanceCount;
+    LARGE_INTEGER lpFrequency;
+    QueryPerformanceCounter(&lpPerformanceCount);
+    QueryPerformanceFrequency(&lpFrequency);
+    return (unsigned long)((1000000*(lpPerformanceCount.QuadPart)) / lpFrequency.QuadPart);
+}
+#else   /* Linux or Mac*/
+unsigned long GetHighResolutionTime(void) /* O  time in usec*/
+{
+    struct timeval tv;
+    gettimeofday(&tv, 0);
+    return((tv.tv_sec*1000000)+(tv.tv_usec));
+}
+#endif
+
+int           silk_Timer_nTimers = 0;
+int           silk_Timer_depth_ctr = 0;
+char          silk_Timer_tags[silk_NUM_TIMERS_MAX][silk_NUM_TIMERS_MAX_TAG_LEN];
+#ifdef WIN32
+LARGE_INTEGER silk_Timer_start[silk_NUM_TIMERS_MAX];
+#else
+unsigned long silk_Timer_start[silk_NUM_TIMERS_MAX];
+#endif
+unsigned int  silk_Timer_cnt[silk_NUM_TIMERS_MAX];
+opus_int64     silk_Timer_min[silk_NUM_TIMERS_MAX];
+opus_int64     silk_Timer_sum[silk_NUM_TIMERS_MAX];
+opus_int64     silk_Timer_max[silk_NUM_TIMERS_MAX];
+opus_int64     silk_Timer_depth[silk_NUM_TIMERS_MAX];
+
+#ifdef WIN32
+void silk_TimerSave(char *file_name)
+{
+    if( silk_Timer_nTimers > 0 )
+    {
+        int k;
+        FILE *fp;
+        LARGE_INTEGER lpFrequency;
+        LARGE_INTEGER lpPerformanceCount1, lpPerformanceCount2;
+        int del = 0x7FFFFFFF;
+        double avg, sum_avg;
+        /* estimate overhead of calling performance counters */
+        for( k = 0; k < 1000; k++ ) {
+            QueryPerformanceCounter(&lpPerformanceCount1);
+            QueryPerformanceCounter(&lpPerformanceCount2);
+            lpPerformanceCount2.QuadPart -= lpPerformanceCount1.QuadPart;
+            if( (int)lpPerformanceCount2.LowPart < del )
+                del = lpPerformanceCount2.LowPart;
+        }
+        QueryPerformanceFrequency(&lpFrequency);
+        /* print results to file */
+        sum_avg = 0.0f;
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {
+            if (silk_Timer_depth[k] == 0) {
+                sum_avg += (1e6 * silk_Timer_sum[k] / silk_Timer_cnt[k] - del) / lpFrequency.QuadPart * silk_Timer_cnt[k];
+            }
+        }
+        fp = fopen(file_name, "w");
+        fprintf(fp, "                                min         avg     %%         max      count\n");
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {
+            if (silk_Timer_depth[k] == 0) {
+                fprintf(fp, "%-28s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 1) {
+                fprintf(fp, " %-27s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 2) {
+                fprintf(fp, "  %-26s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 3) {
+                fprintf(fp, "   %-25s", silk_Timer_tags[k]);
+            } else {
+                fprintf(fp, "    %-24s", silk_Timer_tags[k]);
+            }
+            avg = (1e6 * silk_Timer_sum[k] / silk_Timer_cnt[k] - del) / lpFrequency.QuadPart;
+            fprintf(fp, "%8.2f", (1e6 * (silk_max_64(silk_Timer_min[k] - del, 0))) / lpFrequency.QuadPart);
+            fprintf(fp, "%12.2f %6.2f", avg, 100.0 * avg / sum_avg * silk_Timer_cnt[k]);
+            fprintf(fp, "%12.2f", (1e6 * (silk_max_64(silk_Timer_max[k] - del, 0))) / lpFrequency.QuadPart);
+            fprintf(fp, "%10d\n", silk_Timer_cnt[k]);
+        }
+        fprintf(fp, "                                microseconds\n");
+        fclose(fp);
+    }
+}
+#else
+void silk_TimerSave(char *file_name)
+{
+    if( silk_Timer_nTimers > 0 )
+    {
+        int k;
+        FILE *fp;
+        /* print results to file */
+        fp = fopen(file_name, "w");
+        fprintf(fp, "                                min         avg         max      count\n");
+        for( k = 0; k < silk_Timer_nTimers; k++ )
+        {
+            if (silk_Timer_depth[k] == 0) {
+                fprintf(fp, "%-28s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 1) {
+                fprintf(fp, " %-27s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 2) {
+                fprintf(fp, "  %-26s", silk_Timer_tags[k]);
+            } else if (silk_Timer_depth[k] == 3) {
+                fprintf(fp, "   %-25s", silk_Timer_tags[k]);
+            } else {
+                fprintf(fp, "    %-24s", silk_Timer_tags[k]);
+            }
+            fprintf(fp, "%d ", silk_Timer_min[k]);
+            fprintf(fp, "%f ", (double)silk_Timer_sum[k] / (double)silk_Timer_cnt[k]);
+            fprintf(fp, "%d ", silk_Timer_max[k]);
+            fprintf(fp, "%10d\n", silk_Timer_cnt[k]);
+        }
+        fprintf(fp, "                                microseconds\n");
+        fclose(fp);
+    }
+}
+#endif
+
+#endif /* SILK_TIC_TOC */
+
+#if SILK_DEBUG
+FILE *silk_debug_store_fp[ silk_NUM_STORES_MAX ];
+int silk_debug_store_count = 0;
+#endif /* SILK_DEBUG */
+
diff --git a/opus/silk/debug.h b/opus/silk/debug.h
new file mode 100644 (file)
index 0000000..6f68c1c
--- /dev/null
@@ -0,0 +1,266 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_DEBUG_H
+#define SILK_DEBUG_H
+
+#include "typedef.h"
+#include <stdio.h>      /* file writing */
+#include <string.h>     /* strcpy, strcmp */
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+unsigned long GetHighResolutionTime(void); /* O  time in usec*/
+
+/* Set to 1 to enable DEBUG_STORE_DATA() macros for dumping
+ * intermediate signals from the codec.
+ */
+#define SILK_DEBUG 0
+
+/* Flag for using timers */
+#define SILK_TIC_TOC    0
+
+
+#if SILK_TIC_TOC
+
+#if (defined(_WIN32) || defined(_WINCE))
+#include <windows.h>    /* timer */
+#else   /* Linux or Mac*/
+#include <sys/time.h>
+#endif
+
+/*********************************/
+/* timer functions for profiling */
+/*********************************/
+/* example:                                                         */
+/*                                                                  */
+/* TIC(LPC)                                                         */
+/* do_LPC(in_vec, order, acoef);    // do LPC analysis              */
+/* TOC(LPC)                                                         */
+/*                                                                  */
+/* and call the following just before exiting (from main)           */
+/*                                                                  */
+/* silk_TimerSave("silk_TimingData.txt");                           */
+/*                                                                  */
+/* results are now in silk_TimingData.txt                           */
+
+void silk_TimerSave(char *file_name);
+
+/* max number of timers (in different locations) */
+#define silk_NUM_TIMERS_MAX                  50
+/* max length of name tags in TIC(..), TOC(..) */
+#define silk_NUM_TIMERS_MAX_TAG_LEN          30
+
+extern int           silk_Timer_nTimers;
+extern int           silk_Timer_depth_ctr;
+extern char          silk_Timer_tags[silk_NUM_TIMERS_MAX][silk_NUM_TIMERS_MAX_TAG_LEN];
+#ifdef _WIN32
+extern LARGE_INTEGER silk_Timer_start[silk_NUM_TIMERS_MAX];
+#else
+extern unsigned long silk_Timer_start[silk_NUM_TIMERS_MAX];
+#endif
+extern unsigned int  silk_Timer_cnt[silk_NUM_TIMERS_MAX];
+extern opus_int64    silk_Timer_sum[silk_NUM_TIMERS_MAX];
+extern opus_int64    silk_Timer_max[silk_NUM_TIMERS_MAX];
+extern opus_int64    silk_Timer_min[silk_NUM_TIMERS_MAX];
+extern opus_int64    silk_Timer_depth[silk_NUM_TIMERS_MAX];
+
+/* WARNING: TIC()/TOC can measure only up to 0.1 seconds at a time */
+#ifdef _WIN32
+#define TIC(TAG_NAME) {                                     \
+    static int init = 0;                                    \
+    static int ID = -1;                                     \
+    if( init == 0 )                                         \
+    {                                                       \
+        int k;                                              \
+        init = 1;                                           \
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {         \
+            if( strcmp(silk_Timer_tags[k], #TAG_NAME) == 0 ) { \
+                ID = k;                                     \
+                break;                                      \
+            }                                               \
+        }                                                   \
+        if (ID == -1) {                                     \
+            ID = silk_Timer_nTimers;                        \
+            silk_Timer_nTimers++;                           \
+            silk_Timer_depth[ID] = silk_Timer_depth_ctr;    \
+            strcpy(silk_Timer_tags[ID], #TAG_NAME);         \
+            silk_Timer_cnt[ID] = 0;                         \
+            silk_Timer_sum[ID] = 0;                         \
+            silk_Timer_min[ID] = 0xFFFFFFFF;                \
+            silk_Timer_max[ID] = 0;                         \
+        }                                                   \
+    }                                                       \
+    silk_Timer_depth_ctr++;                                 \
+    QueryPerformanceCounter(&silk_Timer_start[ID]);         \
+}
+#else
+#define TIC(TAG_NAME) {                                     \
+    static int init = 0;                                    \
+    static int ID = -1;                                     \
+    if( init == 0 )                                         \
+    {                                                       \
+        int k;                                              \
+        init = 1;                                           \
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {         \
+        if( strcmp(silk_Timer_tags[k], #TAG_NAME) == 0 ) {  \
+                ID = k;                                     \
+                break;                                      \
+            }                                               \
+        }                                                   \
+        if (ID == -1) {                                     \
+            ID = silk_Timer_nTimers;                        \
+            silk_Timer_nTimers++;                           \
+            silk_Timer_depth[ID] = silk_Timer_depth_ctr;    \
+            strcpy(silk_Timer_tags[ID], #TAG_NAME);         \
+            silk_Timer_cnt[ID] = 0;                         \
+            silk_Timer_sum[ID] = 0;                         \
+            silk_Timer_min[ID] = 0xFFFFFFFF;                \
+            silk_Timer_max[ID] = 0;                         \
+        }                                                   \
+    }                                                       \
+    silk_Timer_depth_ctr++;                                 \
+    silk_Timer_start[ID] = GetHighResolutionTime();         \
+}
+#endif
+
+#ifdef _WIN32
+#define TOC(TAG_NAME) {                                             \
+    LARGE_INTEGER lpPerformanceCount;                               \
+    static int init = 0;                                            \
+    static int ID = 0;                                              \
+    if( init == 0 )                                                 \
+    {                                                               \
+        int k;                                                      \
+        init = 1;                                                   \
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {                 \
+            if( strcmp(silk_Timer_tags[k], #TAG_NAME) == 0 ) {      \
+                ID = k;                                             \
+                break;                                              \
+            }                                                       \
+        }                                                           \
+    }                                                               \
+    QueryPerformanceCounter(&lpPerformanceCount);                   \
+    lpPerformanceCount.QuadPart -= silk_Timer_start[ID].QuadPart;   \
+    if((lpPerformanceCount.QuadPart < 100000000) &&                 \
+        (lpPerformanceCount.QuadPart >= 0)) {                       \
+        silk_Timer_cnt[ID]++;                                       \
+        silk_Timer_sum[ID] += lpPerformanceCount.QuadPart;          \
+        if( lpPerformanceCount.QuadPart > silk_Timer_max[ID] )      \
+            silk_Timer_max[ID] = lpPerformanceCount.QuadPart;       \
+        if( lpPerformanceCount.QuadPart < silk_Timer_min[ID] )      \
+            silk_Timer_min[ID] = lpPerformanceCount.QuadPart;       \
+    }                                                               \
+    silk_Timer_depth_ctr--;                                         \
+}
+#else
+#define TOC(TAG_NAME) {                                             \
+    unsigned long endTime;                                          \
+    static int init = 0;                                            \
+    static int ID = 0;                                              \
+    if( init == 0 )                                                 \
+    {                                                               \
+        int k;                                                      \
+        init = 1;                                                   \
+        for( k = 0; k < silk_Timer_nTimers; k++ ) {                 \
+            if( strcmp(silk_Timer_tags[k], #TAG_NAME) == 0 ) {      \
+                ID = k;                                             \
+                break;                                              \
+            }                                                       \
+        }                                                           \
+    }                                                               \
+    endTime = GetHighResolutionTime();                              \
+    endTime -= silk_Timer_start[ID];                                \
+    if((endTime < 100000000) &&                                     \
+        (endTime >= 0)) {                                           \
+        silk_Timer_cnt[ID]++;                                       \
+        silk_Timer_sum[ID] += endTime;                              \
+        if( endTime > silk_Timer_max[ID] )                          \
+            silk_Timer_max[ID] = endTime;                           \
+        if( endTime < silk_Timer_min[ID] )                          \
+            silk_Timer_min[ID] = endTime;                           \
+    }                                                               \
+        silk_Timer_depth_ctr--;                                     \
+}
+#endif
+
+#else /* SILK_TIC_TOC */
+
+/* define macros as empty strings */
+#define TIC(TAG_NAME)
+#define TOC(TAG_NAME)
+#define silk_TimerSave(FILE_NAME)
+
+#endif /* SILK_TIC_TOC */
+
+
+#if SILK_DEBUG
+/************************************/
+/* write data to file for debugging */
+/************************************/
+/* Example: DEBUG_STORE_DATA(testfile.pcm, &RIN[0], 160*sizeof(opus_int16)); */
+
+#define silk_NUM_STORES_MAX                                  100
+extern FILE *silk_debug_store_fp[ silk_NUM_STORES_MAX ];
+extern int silk_debug_store_count;
+
+/* Faster way of storing the data */
+#define DEBUG_STORE_DATA( FILE_NAME, DATA_PTR, N_BYTES ) {          \
+    static opus_int init = 0, cnt = 0;                              \
+    static FILE **fp;                                               \
+    if (init == 0) {                                                \
+        init = 1;                                                   \
+        cnt = silk_debug_store_count++;                             \
+        silk_debug_store_fp[ cnt ] = fopen(#FILE_NAME, "wb");       \
+    }                                                               \
+    fwrite((DATA_PTR), (N_BYTES), 1, silk_debug_store_fp[ cnt ]);   \
+}
+
+/* Call this at the end of main() */
+#define SILK_DEBUG_STORE_CLOSE_FILES {                              \
+    opus_int i;                                                     \
+    for( i = 0; i < silk_debug_store_count; i++ ) {                 \
+        fclose( silk_debug_store_fp[ i ] );                         \
+    }                                                               \
+}
+
+#else /* SILK_DEBUG */
+
+/* define macros as empty strings */
+#define DEBUG_STORE_DATA(FILE_NAME, DATA_PTR, N_BYTES)
+#define SILK_DEBUG_STORE_CLOSE_FILES
+
+#endif /* SILK_DEBUG */
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif /* SILK_DEBUG_H */
diff --git a/opus/silk/dec_API.c b/opus/silk/dec_API.c
new file mode 100644 (file)
index 0000000..b7d8ed4
--- /dev/null
@@ -0,0 +1,419 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#include "API.h"
+#include "main.h"
+#include "stack_alloc.h"
+#include "os_support.h"
+
+/************************/
+/* Decoder Super Struct */
+/************************/
+typedef struct {
+    silk_decoder_state          channel_state[ DECODER_NUM_CHANNELS ];
+    stereo_dec_state                sStereo;
+    opus_int                         nChannelsAPI;
+    opus_int                         nChannelsInternal;
+    opus_int                         prev_decode_only_middle;
+} silk_decoder;
+
+/*********************/
+/* Decoder functions */
+/*********************/
+
+opus_int silk_Get_Decoder_Size(                         /* O    Returns error code                              */
+    opus_int                        *decSizeBytes       /* O    Number of bytes in SILK decoder state           */
+)
+{
+    opus_int ret = SILK_NO_ERROR;
+
+    *decSizeBytes = sizeof( silk_decoder );
+
+    return ret;
+}
+
+/* Reset decoder state */
+opus_int silk_InitDecoder(                              /* O    Returns error code                              */
+    void                            *decState           /* I/O  State                                           */
+)
+{
+    opus_int n, ret = SILK_NO_ERROR;
+    silk_decoder_state *channel_state = ((silk_decoder *)decState)->channel_state;
+
+    for( n = 0; n < DECODER_NUM_CHANNELS; n++ ) {
+        ret  = silk_init_decoder( &channel_state[ n ] );
+    }
+    silk_memset(&((silk_decoder *)decState)->sStereo, 0, sizeof(((silk_decoder *)decState)->sStereo));
+    /* Not strictly needed, but it's cleaner that way */
+    ((silk_decoder *)decState)->prev_decode_only_middle = 0;
+
+    return ret;
+}
+
+/* Decode a frame */
+opus_int silk_Decode(                                   /* O    Returns error code                              */
+    void*                           decState,           /* I/O  State                                           */
+    silk_DecControlStruct*          decControl,         /* I/O  Control Structure                               */
+    opus_int                        lostFlag,           /* I    0: no loss, 1 loss, 2 decode fec                */
+    opus_int                        newPacketFlag,      /* I    Indicates first decoder call for this packet    */
+    ec_dec                          *psRangeDec,        /* I/O  Compressor data structure                       */
+    opus_int16                      *samplesOut,        /* O    Decoded output speech vector                    */
+    opus_int32                      *nSamplesOut,       /* O    Number of samples decoded                       */
+    int                             arch                /* I    Run-time architecture                           */
+)
+{
+    opus_int   i, n, decode_only_middle = 0, ret = SILK_NO_ERROR;
+    opus_int32 nSamplesOutDec, LBRR_symbol;
+    opus_int16 *samplesOut1_tmp[ 2 ];
+    VARDECL( opus_int16, samplesOut1_tmp_storage1 );
+    VARDECL( opus_int16, samplesOut1_tmp_storage2 );
+    VARDECL( opus_int16, samplesOut2_tmp );
+    opus_int32 MS_pred_Q13[ 2 ] = { 0 };
+    opus_int16 *resample_out_ptr;
+    silk_decoder *psDec = ( silk_decoder * )decState;
+    silk_decoder_state *channel_state = psDec->channel_state;
+    opus_int has_side;
+    opus_int stereo_to_mono;
+    int delay_stack_alloc;
+    SAVE_STACK;
+
+    silk_assert( decControl->nChannelsInternal == 1 || decControl->nChannelsInternal == 2 );
+
+    /**********************************/
+    /* Test if first frame in payload */
+    /**********************************/
+    if( newPacketFlag ) {
+        for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+            channel_state[ n ].nFramesDecoded = 0;  /* Used to count frames in packet */
+        }
+    }
+
+    /* If Mono -> Stereo transition in bitstream: init state of second channel */
+    if( decControl->nChannelsInternal > psDec->nChannelsInternal ) {
+        ret += silk_init_decoder( &channel_state[ 1 ] );
+    }
+
+    stereo_to_mono = decControl->nChannelsInternal == 1 && psDec->nChannelsInternal == 2 &&
+                     ( decControl->internalSampleRate == 1000*channel_state[ 0 ].fs_kHz );
+
+    if( channel_state[ 0 ].nFramesDecoded == 0 ) {
+        for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+            opus_int fs_kHz_dec;
+            if( decControl->payloadSize_ms == 0 ) {
+                /* Assuming packet loss, use 10 ms */
+                channel_state[ n ].nFramesPerPacket = 1;
+                channel_state[ n ].nb_subfr = 2;
+            } else if( decControl->payloadSize_ms == 10 ) {
+                channel_state[ n ].nFramesPerPacket = 1;
+                channel_state[ n ].nb_subfr = 2;
+            } else if( decControl->payloadSize_ms == 20 ) {
+                channel_state[ n ].nFramesPerPacket = 1;
+                channel_state[ n ].nb_subfr = 4;
+            } else if( decControl->payloadSize_ms == 40 ) {
+                channel_state[ n ].nFramesPerPacket = 2;
+                channel_state[ n ].nb_subfr = 4;
+            } else if( decControl->payloadSize_ms == 60 ) {
+                channel_state[ n ].nFramesPerPacket = 3;
+                channel_state[ n ].nb_subfr = 4;
+            } else {
+                silk_assert( 0 );
+                RESTORE_STACK;
+                return SILK_DEC_INVALID_FRAME_SIZE;
+            }
+            fs_kHz_dec = ( decControl->internalSampleRate >> 10 ) + 1;
+            if( fs_kHz_dec != 8 && fs_kHz_dec != 12 && fs_kHz_dec != 16 ) {
+                silk_assert( 0 );
+                RESTORE_STACK;
+                return SILK_DEC_INVALID_SAMPLING_FREQUENCY;
+            }
+            ret += silk_decoder_set_fs( &channel_state[ n ], fs_kHz_dec, decControl->API_sampleRate );
+        }
+    }
+
+    if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 2 && ( psDec->nChannelsAPI == 1 || psDec->nChannelsInternal == 1 ) ) {
+        silk_memset( psDec->sStereo.pred_prev_Q13, 0, sizeof( psDec->sStereo.pred_prev_Q13 ) );
+        silk_memset( psDec->sStereo.sSide, 0, sizeof( psDec->sStereo.sSide ) );
+        silk_memcpy( &channel_state[ 1 ].resampler_state, &channel_state[ 0 ].resampler_state, sizeof( silk_resampler_state_struct ) );
+    }
+    psDec->nChannelsAPI      = decControl->nChannelsAPI;
+    psDec->nChannelsInternal = decControl->nChannelsInternal;
+
+    if( decControl->API_sampleRate > (opus_int32)MAX_API_FS_KHZ * 1000 || decControl->API_sampleRate < 8000 ) {
+        ret = SILK_DEC_INVALID_SAMPLING_FREQUENCY;
+        RESTORE_STACK;
+        return( ret );
+    }
+
+    if( lostFlag != FLAG_PACKET_LOST && channel_state[ 0 ].nFramesDecoded == 0 ) {
+        /* First decoder call for this payload */
+        /* Decode VAD flags and LBRR flag */
+        for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+            for( i = 0; i < channel_state[ n ].nFramesPerPacket; i++ ) {
+                channel_state[ n ].VAD_flags[ i ] = ec_dec_bit_logp(psRangeDec, 1);
+            }
+            channel_state[ n ].LBRR_flag = ec_dec_bit_logp(psRangeDec, 1);
+        }
+        /* Decode LBRR flags */
+        for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+            silk_memset( channel_state[ n ].LBRR_flags, 0, sizeof( channel_state[ n ].LBRR_flags ) );
+            if( channel_state[ n ].LBRR_flag ) {
+                if( channel_state[ n ].nFramesPerPacket == 1 ) {
+                    channel_state[ n ].LBRR_flags[ 0 ] = 1;
+                } else {
+                    LBRR_symbol = ec_dec_icdf( psRangeDec, silk_LBRR_flags_iCDF_ptr[ channel_state[ n ].nFramesPerPacket - 2 ], 8 ) + 1;
+                    for( i = 0; i < channel_state[ n ].nFramesPerPacket; i++ ) {
+                        channel_state[ n ].LBRR_flags[ i ] = silk_RSHIFT( LBRR_symbol, i ) & 1;
+                    }
+                }
+            }
+        }
+
+        if( lostFlag == FLAG_DECODE_NORMAL ) {
+            /* Regular decoding: skip all LBRR data */
+            for( i = 0; i < channel_state[ 0 ].nFramesPerPacket; i++ ) {
+                for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+                    if( channel_state[ n ].LBRR_flags[ i ] ) {
+                        opus_int16 pulses[ MAX_FRAME_LENGTH ];
+                        opus_int condCoding;
+
+                        if( decControl->nChannelsInternal == 2 && n == 0 ) {
+                            silk_stereo_decode_pred( psRangeDec, MS_pred_Q13 );
+                            if( channel_state[ 1 ].LBRR_flags[ i ] == 0 ) {
+                                silk_stereo_decode_mid_only( psRangeDec, &decode_only_middle );
+                            }
+                        }
+                        /* Use conditional coding if previous frame available */
+                        if( i > 0 && channel_state[ n ].LBRR_flags[ i - 1 ] ) {
+                            condCoding = CODE_CONDITIONALLY;
+                        } else {
+                            condCoding = CODE_INDEPENDENTLY;
+                        }
+                        silk_decode_indices( &channel_state[ n ], psRangeDec, i, 1, condCoding );
+                        silk_decode_pulses( psRangeDec, pulses, channel_state[ n ].indices.signalType,
+                            channel_state[ n ].indices.quantOffsetType, channel_state[ n ].frame_length );
+                    }
+                }
+            }
+        }
+    }
+
+    /* Get MS predictor index */
+    if( decControl->nChannelsInternal == 2 ) {
+        if(   lostFlag == FLAG_DECODE_NORMAL ||
+            ( lostFlag == FLAG_DECODE_LBRR && channel_state[ 0 ].LBRR_flags[ channel_state[ 0 ].nFramesDecoded ] == 1 ) )
+        {
+            silk_stereo_decode_pred( psRangeDec, MS_pred_Q13 );
+            /* For LBRR data, decode mid-only flag only if side-channel's LBRR flag is false */
+            if( ( lostFlag == FLAG_DECODE_NORMAL && channel_state[ 1 ].VAD_flags[ channel_state[ 0 ].nFramesDecoded ] == 0 ) ||
+                ( lostFlag == FLAG_DECODE_LBRR && channel_state[ 1 ].LBRR_flags[ channel_state[ 0 ].nFramesDecoded ] == 0 ) )
+            {
+                silk_stereo_decode_mid_only( psRangeDec, &decode_only_middle );
+            } else {
+                decode_only_middle = 0;
+            }
+        } else {
+            for( n = 0; n < 2; n++ ) {
+                MS_pred_Q13[ n ] = psDec->sStereo.pred_prev_Q13[ n ];
+            }
+        }
+    }
+
+    /* Reset side channel decoder prediction memory for first frame with side coding */
+    if( decControl->nChannelsInternal == 2 && decode_only_middle == 0 && psDec->prev_decode_only_middle == 1 ) {
+        silk_memset( psDec->channel_state[ 1 ].outBuf, 0, sizeof(psDec->channel_state[ 1 ].outBuf) );
+        silk_memset( psDec->channel_state[ 1 ].sLPC_Q14_buf, 0, sizeof(psDec->channel_state[ 1 ].sLPC_Q14_buf) );
+        psDec->channel_state[ 1 ].lagPrev        = 100;
+        psDec->channel_state[ 1 ].LastGainIndex  = 10;
+        psDec->channel_state[ 1 ].prevSignalType = TYPE_NO_VOICE_ACTIVITY;
+        psDec->channel_state[ 1 ].first_frame_after_reset = 1;
+    }
+
+    /* Check if the temp buffer fits into the output PCM buffer. If it fits,
+       we can delay allocating the temp buffer until after the SILK peak stack
+       usage. We need to use a < and not a <= because of the two extra samples. */
+    delay_stack_alloc = decControl->internalSampleRate*decControl->nChannelsInternal
+          < decControl->API_sampleRate*decControl->nChannelsAPI;
+    ALLOC( samplesOut1_tmp_storage1, delay_stack_alloc ? ALLOC_NONE
+           : decControl->nChannelsInternal*(channel_state[ 0 ].frame_length + 2 ),
+           opus_int16 );
+    if ( delay_stack_alloc )
+    {
+       samplesOut1_tmp[ 0 ] = samplesOut;
+       samplesOut1_tmp[ 1 ] = samplesOut + channel_state[ 0 ].frame_length + 2;
+    } else {
+       samplesOut1_tmp[ 0 ] = samplesOut1_tmp_storage1;
+       samplesOut1_tmp[ 1 ] = samplesOut1_tmp_storage1 + channel_state[ 0 ].frame_length + 2;
+    }
+
+    if( lostFlag == FLAG_DECODE_NORMAL ) {
+        has_side = !decode_only_middle;
+    } else {
+        has_side = !psDec->prev_decode_only_middle
+              || (decControl->nChannelsInternal == 2 && lostFlag == FLAG_DECODE_LBRR && channel_state[1].LBRR_flags[ channel_state[1].nFramesDecoded ] == 1 );
+    }
+    /* Call decoder for one frame */
+    for( n = 0; n < decControl->nChannelsInternal; n++ ) {
+        if( n == 0 || has_side ) {
+            opus_int FrameIndex;
+            opus_int condCoding;
+
+            FrameIndex = channel_state[ 0 ].nFramesDecoded - n;
+            /* Use independent coding if no previous frame available */
+            if( FrameIndex <= 0 ) {
+                condCoding = CODE_INDEPENDENTLY;
+            } else if( lostFlag == FLAG_DECODE_LBRR ) {
+                condCoding = channel_state[ n ].LBRR_flags[ FrameIndex - 1 ] ? CODE_CONDITIONALLY : CODE_INDEPENDENTLY;
+            } else if( n > 0 && psDec->prev_decode_only_middle ) {
+                /* If we skipped a side frame in this packet, we don't
+                   need LTP scaling; the LTP state is well-defined. */
+                condCoding = CODE_INDEPENDENTLY_NO_LTP_SCALING;
+            } else {
+                condCoding = CODE_CONDITIONALLY;
+            }
+            ret += silk_decode_frame( &channel_state[ n ], psRangeDec, &samplesOut1_tmp[ n ][ 2 ], &nSamplesOutDec, lostFlag, condCoding, arch);
+        } else {
+            silk_memset( &samplesOut1_tmp[ n ][ 2 ], 0, nSamplesOutDec * sizeof( opus_int16 ) );
+        }
+        channel_state[ n ].nFramesDecoded++;
+    }
+
+    if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 2 ) {
+        /* Convert Mid/Side to Left/Right */
+        silk_stereo_MS_to_LR( &psDec->sStereo, samplesOut1_tmp[ 0 ], samplesOut1_tmp[ 1 ], MS_pred_Q13, channel_state[ 0 ].fs_kHz, nSamplesOutDec );
+    } else {
+        /* Buffering */
+        silk_memcpy( samplesOut1_tmp[ 0 ], psDec->sStereo.sMid, 2 * sizeof( opus_int16 ) );
+        silk_memcpy( psDec->sStereo.sMid, &samplesOut1_tmp[ 0 ][ nSamplesOutDec ], 2 * sizeof( opus_int16 ) );
+    }
+
+    /* Number of output samples */
+    *nSamplesOut = silk_DIV32( nSamplesOutDec * decControl->API_sampleRate, silk_SMULBB( channel_state[ 0 ].fs_kHz, 1000 ) );
+
+    /* Set up pointers to temp buffers */
+    ALLOC( samplesOut2_tmp,
+           decControl->nChannelsAPI == 2 ? *nSamplesOut : ALLOC_NONE, opus_int16 );
+    if( decControl->nChannelsAPI == 2 ) {
+        resample_out_ptr = samplesOut2_tmp;
+    } else {
+        resample_out_ptr = samplesOut;
+    }
+
+    ALLOC( samplesOut1_tmp_storage2, delay_stack_alloc
+           ? decControl->nChannelsInternal*(channel_state[ 0 ].frame_length + 2 )
+           : ALLOC_NONE,
+           opus_int16 );
+    if ( delay_stack_alloc ) {
+       OPUS_COPY(samplesOut1_tmp_storage2, samplesOut, decControl->nChannelsInternal*(channel_state[ 0 ].frame_length + 2));
+       samplesOut1_tmp[ 0 ] = samplesOut1_tmp_storage2;
+       samplesOut1_tmp[ 1 ] = samplesOut1_tmp_storage2 + channel_state[ 0 ].frame_length + 2;
+    }
+    for( n = 0; n < silk_min( decControl->nChannelsAPI, decControl->nChannelsInternal ); n++ ) {
+
+        /* Resample decoded signal to API_sampleRate */
+        ret += silk_resampler( &channel_state[ n ].resampler_state, resample_out_ptr, &samplesOut1_tmp[ n ][ 1 ], nSamplesOutDec );
+
+        /* Interleave if stereo output and stereo stream */
+        if( decControl->nChannelsAPI == 2 ) {
+            for( i = 0; i < *nSamplesOut; i++ ) {
+                samplesOut[ n + 2 * i ] = resample_out_ptr[ i ];
+            }
+        }
+    }
+
+    /* Create two channel output from mono stream */
+    if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 1 ) {
+        if ( stereo_to_mono ){
+            /* Resample right channel for newly collapsed stereo just in case
+               we weren't doing collapsing when switching to mono */
+            ret += silk_resampler( &channel_state[ 1 ].resampler_state, resample_out_ptr, &samplesOut1_tmp[ 0 ][ 1 ], nSamplesOutDec );
+
+            for( i = 0; i < *nSamplesOut; i++ ) {
+                samplesOut[ 1 + 2 * i ] = resample_out_ptr[ i ];
+            }
+        } else {
+            for( i = 0; i < *nSamplesOut; i++ ) {
+                samplesOut[ 1 + 2 * i ] = samplesOut[ 0 + 2 * i ];
+            }
+        }
+    }
+
+    /* Export pitch lag, measured at 48 kHz sampling rate */
+    if( channel_state[ 0 ].prevSignalType == TYPE_VOICED ) {
+        int mult_tab[ 3 ] = { 6, 4, 3 };
+        decControl->prevPitchLag = channel_state[ 0 ].lagPrev * mult_tab[ ( channel_state[ 0 ].fs_kHz - 8 ) >> 2 ];
+    } else {
+        decControl->prevPitchLag = 0;
+    }
+
+    if( lostFlag == FLAG_PACKET_LOST ) {
+       /* On packet loss, remove the gain clamping to prevent having the energy "bounce back"
+          if we lose packets when the energy is going down */
+       for ( i = 0; i < psDec->nChannelsInternal; i++ )
+          psDec->channel_state[ i ].LastGainIndex = 10;
+    } else {
+       psDec->prev_decode_only_middle = decode_only_middle;
+    }
+    RESTORE_STACK;
+    return ret;
+}
+
+#if 0
+/* Getting table of contents for a packet */
+opus_int silk_get_TOC(
+    const opus_uint8                *payload,           /* I    Payload data                                */
+    const opus_int                  nBytesIn,           /* I    Number of input bytes                       */
+    const opus_int                  nFramesPerPayload,  /* I    Number of SILK frames per payload           */
+    silk_TOC_struct                 *Silk_TOC           /* O    Type of content                             */
+)
+{
+    opus_int i, flags, ret = SILK_NO_ERROR;
+
+    if( nBytesIn < 1 ) {
+        return -1;
+    }
+    if( nFramesPerPayload < 0 || nFramesPerPayload > 3 ) {
+        return -1;
+    }
+
+    silk_memset( Silk_TOC, 0, sizeof( *Silk_TOC ) );
+
+    /* For stereo, extract the flags for the mid channel */
+    flags = silk_RSHIFT( payload[ 0 ], 7 - nFramesPerPayload ) & ( silk_LSHIFT( 1, nFramesPerPayload + 1 ) - 1 );
+
+    Silk_TOC->inbandFECFlag = flags & 1;
+    for( i = nFramesPerPayload - 1; i >= 0 ; i-- ) {
+        flags = silk_RSHIFT( flags, 1 );
+        Silk_TOC->VADFlags[ i ] = flags & 1;
+        Silk_TOC->VADFlag |= flags & 1;
+    }
+
+    return ret;
+}
+#endif
diff --git a/opus/silk/decode_core.c b/opus/silk/decode_core.c
new file mode 100644 (file)
index 0000000..fd4e857
--- /dev/null
@@ -0,0 +1,237 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/**********************************************************/
+/* Core decoder. Performs inverse NSQ operation LTP + LPC */
+/**********************************************************/
+void silk_decode_core(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state                               */
+    silk_decoder_control        *psDecCtrl,                     /* I    Decoder control                             */
+    opus_int16                  xq[],                           /* O    Decoded speech                              */
+    const opus_int16            pulses[ MAX_FRAME_LENGTH ],     /* I    Pulse signal                                */
+    int                         arch                            /* I    Run-time architecture                       */
+)
+{
+    opus_int   i, k, lag = 0, start_idx, sLTP_buf_idx, NLSF_interpolation_flag, signalType;
+    opus_int16 *A_Q12, *B_Q14, *pxq, A_Q12_tmp[ MAX_LPC_ORDER ];
+    VARDECL( opus_int16, sLTP );
+    VARDECL( opus_int32, sLTP_Q15 );
+    opus_int32 LTP_pred_Q13, LPC_pred_Q10, Gain_Q10, inv_gain_Q31, gain_adj_Q16, rand_seed, offset_Q10;
+    opus_int32 *pred_lag_ptr, *pexc_Q14, *pres_Q14;
+    VARDECL( opus_int32, res_Q14 );
+    VARDECL( opus_int32, sLPC_Q14 );
+    SAVE_STACK;
+
+    silk_assert( psDec->prev_gain_Q16 != 0 );
+
+    ALLOC( sLTP, psDec->ltp_mem_length, opus_int16 );
+    ALLOC( sLTP_Q15, psDec->ltp_mem_length + psDec->frame_length, opus_int32 );
+    ALLOC( res_Q14, psDec->subfr_length, opus_int32 );
+    ALLOC( sLPC_Q14, psDec->subfr_length + MAX_LPC_ORDER, opus_int32 );
+
+    offset_Q10 = silk_Quantization_Offsets_Q10[ psDec->indices.signalType >> 1 ][ psDec->indices.quantOffsetType ];
+
+    if( psDec->indices.NLSFInterpCoef_Q2 < 1 << 2 ) {
+        NLSF_interpolation_flag = 1;
+    } else {
+        NLSF_interpolation_flag = 0;
+    }
+
+    /* Decode excitation */
+    rand_seed = psDec->indices.Seed;
+    for( i = 0; i < psDec->frame_length; i++ ) {
+        rand_seed = silk_RAND( rand_seed );
+        psDec->exc_Q14[ i ] = silk_LSHIFT( (opus_int32)pulses[ i ], 14 );
+        if( psDec->exc_Q14[ i ] > 0 ) {
+            psDec->exc_Q14[ i ] -= QUANT_LEVEL_ADJUST_Q10 << 4;
+        } else
+        if( psDec->exc_Q14[ i ] < 0 ) {
+            psDec->exc_Q14[ i ] += QUANT_LEVEL_ADJUST_Q10 << 4;
+        }
+        psDec->exc_Q14[ i ] += offset_Q10 << 4;
+        if( rand_seed < 0 ) {
+           psDec->exc_Q14[ i ] = -psDec->exc_Q14[ i ];
+        }
+
+        rand_seed = silk_ADD32_ovflw( rand_seed, pulses[ i ] );
+    }
+
+    /* Copy LPC state */
+    silk_memcpy( sLPC_Q14, psDec->sLPC_Q14_buf, MAX_LPC_ORDER * sizeof( opus_int32 ) );
+
+    pexc_Q14 = psDec->exc_Q14;
+    pxq      = xq;
+    sLTP_buf_idx = psDec->ltp_mem_length;
+    /* Loop over subframes */
+    for( k = 0; k < psDec->nb_subfr; k++ ) {
+        pres_Q14 = res_Q14;
+        A_Q12 = psDecCtrl->PredCoef_Q12[ k >> 1 ];
+
+        /* Preload LPC coeficients to array on stack. Gives small performance gain */
+        silk_memcpy( A_Q12_tmp, A_Q12, psDec->LPC_order * sizeof( opus_int16 ) );
+        B_Q14        = &psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER ];
+        signalType   = psDec->indices.signalType;
+
+        Gain_Q10     = silk_RSHIFT( psDecCtrl->Gains_Q16[ k ], 6 );
+        inv_gain_Q31 = silk_INVERSE32_varQ( psDecCtrl->Gains_Q16[ k ], 47 );
+
+        /* Calculate gain adjustment factor */
+        if( psDecCtrl->Gains_Q16[ k ] != psDec->prev_gain_Q16 ) {
+            gain_adj_Q16 =  silk_DIV32_varQ( psDec->prev_gain_Q16, psDecCtrl->Gains_Q16[ k ], 16 );
+
+            /* Scale short term state */
+            for( i = 0; i < MAX_LPC_ORDER; i++ ) {
+                sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, sLPC_Q14[ i ] );
+            }
+        } else {
+            gain_adj_Q16 = (opus_int32)1 << 16;
+        }
+
+        /* Save inv_gain */
+        silk_assert( inv_gain_Q31 != 0 );
+        psDec->prev_gain_Q16 = psDecCtrl->Gains_Q16[ k ];
+
+        /* Avoid abrupt transition from voiced PLC to unvoiced normal decoding */
+        if( psDec->lossCnt && psDec->prevSignalType == TYPE_VOICED &&
+            psDec->indices.signalType != TYPE_VOICED && k < MAX_NB_SUBFR/2 ) {
+
+            silk_memset( B_Q14, 0, LTP_ORDER * sizeof( opus_int16 ) );
+            B_Q14[ LTP_ORDER/2 ] = SILK_FIX_CONST( 0.25, 14 );
+
+            signalType = TYPE_VOICED;
+            psDecCtrl->pitchL[ k ] = psDec->lagPrev;
+        }
+
+        if( signalType == TYPE_VOICED ) {
+            /* Voiced */
+            lag = psDecCtrl->pitchL[ k ];
+
+            /* Re-whitening */
+            if( k == 0 || ( k == 2 && NLSF_interpolation_flag ) ) {
+                /* Rewhiten with new A coefs */
+                start_idx = psDec->ltp_mem_length - lag - psDec->LPC_order - LTP_ORDER / 2;
+                silk_assert( start_idx > 0 );
+
+                if( k == 2 ) {
+                    silk_memcpy( &psDec->outBuf[ psDec->ltp_mem_length ], xq, 2 * psDec->subfr_length * sizeof( opus_int16 ) );
+                }
+
+                silk_LPC_analysis_filter( &sLTP[ start_idx ], &psDec->outBuf[ start_idx + k * psDec->subfr_length ],
+                    A_Q12, psDec->ltp_mem_length - start_idx, psDec->LPC_order, arch );
+
+                /* After rewhitening the LTP state is unscaled */
+                if( k == 0 ) {
+                    /* Do LTP downscaling to reduce inter-packet dependency */
+                    inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, psDecCtrl->LTP_scale_Q14 ), 2 );
+                }
+                for( i = 0; i < lag + LTP_ORDER/2; i++ ) {
+                    sLTP_Q15[ sLTP_buf_idx - i - 1 ] = silk_SMULWB( inv_gain_Q31, sLTP[ psDec->ltp_mem_length - i - 1 ] );
+                }
+            } else {
+                /* Update LTP state when Gain changes */
+                if( gain_adj_Q16 != (opus_int32)1 << 16 ) {
+                    for( i = 0; i < lag + LTP_ORDER/2; i++ ) {
+                        sLTP_Q15[ sLTP_buf_idx - i - 1 ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ sLTP_buf_idx - i - 1 ] );
+                    }
+                }
+            }
+        }
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Set up pointer */
+            pred_lag_ptr = &sLTP_Q15[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+            for( i = 0; i < psDec->subfr_length; i++ ) {
+                /* Unrolled loop */
+                /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+                LTP_pred_Q13 = 2;
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[  0 ], B_Q14[ 0 ] );
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );
+                pred_lag_ptr++;
+
+                /* Generate LPC excitation */
+                pres_Q14[ i ] = silk_ADD_LSHIFT32( pexc_Q14[ i ], LTP_pred_Q13, 1 );
+
+                /* Update states */
+                sLTP_Q15[ sLTP_buf_idx ] = silk_LSHIFT( pres_Q14[ i ], 1 );
+                sLTP_buf_idx++;
+            }
+        } else {
+            pres_Q14 = pexc_Q14;
+        }
+
+        for( i = 0; i < psDec->subfr_length; i++ ) {
+            /* Short-term prediction */
+            silk_assert( psDec->LPC_order == 10 || psDec->LPC_order == 16 );
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], A_Q12_tmp[ 0 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], A_Q12_tmp[ 1 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], A_Q12_tmp[ 2 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], A_Q12_tmp[ 3 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], A_Q12_tmp[ 4 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], A_Q12_tmp[ 5 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], A_Q12_tmp[ 6 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], A_Q12_tmp[ 7 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], A_Q12_tmp[ 8 ] );
+            LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], A_Q12_tmp[ 9 ] );
+            if( psDec->LPC_order == 16 ) {
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 11 ], A_Q12_tmp[ 10 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 12 ], A_Q12_tmp[ 11 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 13 ], A_Q12_tmp[ 12 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 14 ], A_Q12_tmp[ 13 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 15 ], A_Q12_tmp[ 14 ] );
+                LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 16 ], A_Q12_tmp[ 15 ] );
+            }
+
+            /* Add prediction to LPC excitation */
+            sLPC_Q14[ MAX_LPC_ORDER + i ] = silk_ADD_SAT32( pres_Q14[ i ], silk_LSHIFT_SAT32( LPC_pred_Q10, 4 ) );
+
+            /* Scale with gain */
+            pxq[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( sLPC_Q14[ MAX_LPC_ORDER + i ], Gain_Q10 ), 8 ) );
+        }
+
+        /* Update LPC filter state */
+        silk_memcpy( sLPC_Q14, &sLPC_Q14[ psDec->subfr_length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
+        pexc_Q14 += psDec->subfr_length;
+        pxq      += psDec->subfr_length;
+    }
+
+    /* Save LPC state */
+    silk_memcpy( psDec->sLPC_Q14_buf, sLPC_Q14, MAX_LPC_ORDER * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/decode_frame.c b/opus/silk/decode_frame.c
new file mode 100644 (file)
index 0000000..dfa73c4
--- /dev/null
@@ -0,0 +1,130 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+#include "PLC.h"
+
+/****************/
+/* Decode frame */
+/****************/
+opus_int silk_decode_frame(
+    silk_decoder_state          *psDec,                         /* I/O  Pointer to Silk decoder state               */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int16                  pOut[],                         /* O    Pointer to output speech frame              */
+    opus_int32                  *pN,                            /* O    Pointer to size of output frame             */
+    opus_int                    lostFlag,                       /* I    0: no loss, 1 loss, 2 decode fec            */
+    opus_int                    condCoding,                     /* I    The type of conditional coding to use       */
+    int                         arch                            /* I    Run-time architecture                       */
+)
+{
+    VARDECL( silk_decoder_control, psDecCtrl );
+    opus_int         L, mv_len, ret = 0;
+    SAVE_STACK;
+
+    L = psDec->frame_length;
+    ALLOC( psDecCtrl, 1, silk_decoder_control );
+    psDecCtrl->LTP_scale_Q14 = 0;
+
+    /* Safety checks */
+    silk_assert( L > 0 && L <= MAX_FRAME_LENGTH );
+
+    if(   lostFlag == FLAG_DECODE_NORMAL ||
+        ( lostFlag == FLAG_DECODE_LBRR && psDec->LBRR_flags[ psDec->nFramesDecoded ] == 1 ) )
+    {
+        VARDECL( opus_int16, pulses );
+        ALLOC( pulses, (L + SHELL_CODEC_FRAME_LENGTH - 1) &
+                       ~(SHELL_CODEC_FRAME_LENGTH - 1), opus_int16 );
+        /*********************************************/
+        /* Decode quantization indices of side info  */
+        /*********************************************/
+        silk_decode_indices( psDec, psRangeDec, psDec->nFramesDecoded, lostFlag, condCoding );
+
+        /*********************************************/
+        /* Decode quantization indices of excitation */
+        /*********************************************/
+        silk_decode_pulses( psRangeDec, pulses, psDec->indices.signalType,
+                psDec->indices.quantOffsetType, psDec->frame_length );
+
+        /********************************************/
+        /* Decode parameters and pulse signal       */
+        /********************************************/
+        silk_decode_parameters( psDec, psDecCtrl, condCoding );
+
+        /********************************************************/
+        /* Run inverse NSQ                                      */
+        /********************************************************/
+        silk_decode_core( psDec, psDecCtrl, pOut, pulses, arch );
+
+        /********************************************************/
+        /* Update PLC state                                     */
+        /********************************************************/
+        silk_PLC( psDec, psDecCtrl, pOut, 0, arch );
+
+        psDec->lossCnt = 0;
+        psDec->prevSignalType = psDec->indices.signalType;
+        silk_assert( psDec->prevSignalType >= 0 && psDec->prevSignalType <= 2 );
+
+        /* A frame has been decoded without errors */
+        psDec->first_frame_after_reset = 0;
+    } else {
+        /* Handle packet loss by extrapolation */
+        psDec->indices.signalType = psDec->prevSignalType;
+        silk_PLC( psDec, psDecCtrl, pOut, 1, arch );
+    }
+
+    /*************************/
+    /* Update output buffer. */
+    /*************************/
+    silk_assert( psDec->ltp_mem_length >= psDec->frame_length );
+    mv_len = psDec->ltp_mem_length - psDec->frame_length;
+    silk_memmove( psDec->outBuf, &psDec->outBuf[ psDec->frame_length ], mv_len * sizeof(opus_int16) );
+    silk_memcpy( &psDec->outBuf[ mv_len ], pOut, psDec->frame_length * sizeof( opus_int16 ) );
+
+    /************************************************/
+    /* Comfort noise generation / estimation        */
+    /************************************************/
+    silk_CNG( psDec, psDecCtrl, pOut, L );
+
+    /****************************************************************/
+    /* Ensure smooth connection of extrapolated and good frames     */
+    /****************************************************************/
+    silk_PLC_glue_frames( psDec, pOut, L );
+
+    /* Update some decoder state variables */
+    psDec->lagPrev = psDecCtrl->pitchL[ psDec->nb_subfr - 1 ];
+
+    /* Set output frame length */
+    *pN = L;
+
+    RESTORE_STACK;
+    return ret;
+}
diff --git a/opus/silk/decode_indices.c b/opus/silk/decode_indices.c
new file mode 100644 (file)
index 0000000..7afe5c2
--- /dev/null
@@ -0,0 +1,151 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Decode side-information parameters from payload */
+void silk_decode_indices(
+    silk_decoder_state          *psDec,                         /* I/O  State                                       */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int                    FrameIndex,                     /* I    Frame number                                */
+    opus_int                    decode_LBRR,                    /* I    Flag indicating LBRR data is being decoded  */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+)
+{
+    opus_int   i, k, Ix;
+    opus_int   decode_absolute_lagIndex, delta_lagIndex;
+    opus_int16 ec_ix[ MAX_LPC_ORDER ];
+    opus_uint8 pred_Q8[ MAX_LPC_ORDER ];
+
+    /*******************************************/
+    /* Decode signal type and quantizer offset */
+    /*******************************************/
+    if( decode_LBRR || psDec->VAD_flags[ FrameIndex ] ) {
+        Ix = ec_dec_icdf( psRangeDec, silk_type_offset_VAD_iCDF, 8 ) + 2;
+    } else {
+        Ix = ec_dec_icdf( psRangeDec, silk_type_offset_no_VAD_iCDF, 8 );
+    }
+    psDec->indices.signalType      = (opus_int8)silk_RSHIFT( Ix, 1 );
+    psDec->indices.quantOffsetType = (opus_int8)( Ix & 1 );
+
+    /****************/
+    /* Decode gains */
+    /****************/
+    /* First subframe */
+    if( condCoding == CODE_CONDITIONALLY ) {
+        /* Conditional coding */
+        psDec->indices.GainsIndices[ 0 ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_delta_gain_iCDF, 8 );
+    } else {
+        /* Independent coding, in two stages: MSB bits followed by 3 LSBs */
+        psDec->indices.GainsIndices[ 0 ]  = (opus_int8)silk_LSHIFT( ec_dec_icdf( psRangeDec, silk_gain_iCDF[ psDec->indices.signalType ], 8 ), 3 );
+        psDec->indices.GainsIndices[ 0 ] += (opus_int8)ec_dec_icdf( psRangeDec, silk_uniform8_iCDF, 8 );
+    }
+
+    /* Remaining subframes */
+    for( i = 1; i < psDec->nb_subfr; i++ ) {
+        psDec->indices.GainsIndices[ i ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_delta_gain_iCDF, 8 );
+    }
+
+    /**********************/
+    /* Decode LSF Indices */
+    /**********************/
+    psDec->indices.NLSFIndices[ 0 ] = (opus_int8)ec_dec_icdf( psRangeDec, &psDec->psNLSF_CB->CB1_iCDF[ ( psDec->indices.signalType >> 1 ) * psDec->psNLSF_CB->nVectors ], 8 );
+    silk_NLSF_unpack( ec_ix, pred_Q8, psDec->psNLSF_CB, psDec->indices.NLSFIndices[ 0 ] );
+    silk_assert( psDec->psNLSF_CB->order == psDec->LPC_order );
+    for( i = 0; i < psDec->psNLSF_CB->order; i++ ) {
+        Ix = ec_dec_icdf( psRangeDec, &psDec->psNLSF_CB->ec_iCDF[ ec_ix[ i ] ], 8 );
+        if( Ix == 0 ) {
+            Ix -= ec_dec_icdf( psRangeDec, silk_NLSF_EXT_iCDF, 8 );
+        } else if( Ix == 2 * NLSF_QUANT_MAX_AMPLITUDE ) {
+            Ix += ec_dec_icdf( psRangeDec, silk_NLSF_EXT_iCDF, 8 );
+        }
+        psDec->indices.NLSFIndices[ i+1 ] = (opus_int8)( Ix - NLSF_QUANT_MAX_AMPLITUDE );
+    }
+
+    /* Decode LSF interpolation factor */
+    if( psDec->nb_subfr == MAX_NB_SUBFR ) {
+        psDec->indices.NLSFInterpCoef_Q2 = (opus_int8)ec_dec_icdf( psRangeDec, silk_NLSF_interpolation_factor_iCDF, 8 );
+    } else {
+        psDec->indices.NLSFInterpCoef_Q2 = 4;
+    }
+
+    if( psDec->indices.signalType == TYPE_VOICED )
+    {
+        /*********************/
+        /* Decode pitch lags */
+        /*********************/
+        /* Get lag index */
+        decode_absolute_lagIndex = 1;
+        if( condCoding == CODE_CONDITIONALLY && psDec->ec_prevSignalType == TYPE_VOICED ) {
+            /* Decode Delta index */
+            delta_lagIndex = (opus_int16)ec_dec_icdf( psRangeDec, silk_pitch_delta_iCDF, 8 );
+            if( delta_lagIndex > 0 ) {
+                delta_lagIndex = delta_lagIndex - 9;
+                psDec->indices.lagIndex = (opus_int16)( psDec->ec_prevLagIndex + delta_lagIndex );
+                decode_absolute_lagIndex = 0;
+            }
+        }
+        if( decode_absolute_lagIndex ) {
+            /* Absolute decoding */
+            psDec->indices.lagIndex  = (opus_int16)ec_dec_icdf( psRangeDec, silk_pitch_lag_iCDF, 8 ) * silk_RSHIFT( psDec->fs_kHz, 1 );
+            psDec->indices.lagIndex += (opus_int16)ec_dec_icdf( psRangeDec, psDec->pitch_lag_low_bits_iCDF, 8 );
+        }
+        psDec->ec_prevLagIndex = psDec->indices.lagIndex;
+
+        /* Get countour index */
+        psDec->indices.contourIndex = (opus_int8)ec_dec_icdf( psRangeDec, psDec->pitch_contour_iCDF, 8 );
+
+        /********************/
+        /* Decode LTP gains */
+        /********************/
+        /* Decode PERIndex value */
+        psDec->indices.PERIndex = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTP_per_index_iCDF, 8 );
+
+        for( k = 0; k < psDec->nb_subfr; k++ ) {
+            psDec->indices.LTPIndex[ k ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTP_gain_iCDF_ptrs[ psDec->indices.PERIndex ], 8 );
+        }
+
+        /**********************/
+        /* Decode LTP scaling */
+        /**********************/
+        if( condCoding == CODE_INDEPENDENTLY ) {
+            psDec->indices.LTP_scaleIndex = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTPscale_iCDF, 8 );
+        } else {
+            psDec->indices.LTP_scaleIndex = 0;
+        }
+    }
+    psDec->ec_prevSignalType = psDec->indices.signalType;
+
+    /***************/
+    /* Decode seed */
+    /***************/
+    psDec->indices.Seed = (opus_int8)ec_dec_icdf( psRangeDec, silk_uniform4_iCDF, 8 );
+}
diff --git a/opus/silk/decode_parameters.c b/opus/silk/decode_parameters.c
new file mode 100644 (file)
index 0000000..a56a409
--- /dev/null
@@ -0,0 +1,115 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Decode parameters from payload */
+void silk_decode_parameters(
+    silk_decoder_state          *psDec,                         /* I/O  State                                       */
+    silk_decoder_control        *psDecCtrl,                     /* I/O  Decoder control                             */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+)
+{
+    opus_int   i, k, Ix;
+    opus_int16 pNLSF_Q15[ MAX_LPC_ORDER ], pNLSF0_Q15[ MAX_LPC_ORDER ];
+    const opus_int8 *cbk_ptr_Q7;
+
+    /* Dequant Gains */
+    silk_gains_dequant( psDecCtrl->Gains_Q16, psDec->indices.GainsIndices,
+        &psDec->LastGainIndex, condCoding == CODE_CONDITIONALLY, psDec->nb_subfr );
+
+    /****************/
+    /* Decode NLSFs */
+    /****************/
+    silk_NLSF_decode( pNLSF_Q15, psDec->indices.NLSFIndices, psDec->psNLSF_CB );
+
+    /* Convert NLSF parameters to AR prediction filter coefficients */
+    silk_NLSF2A( psDecCtrl->PredCoef_Q12[ 1 ], pNLSF_Q15, psDec->LPC_order, psDec->arch );
+
+    /* If just reset, e.g., because internal Fs changed, do not allow interpolation */
+    /* improves the case of packet loss in the first frame after a switch           */
+    if( psDec->first_frame_after_reset == 1 ) {
+        psDec->indices.NLSFInterpCoef_Q2 = 4;
+    }
+
+    if( psDec->indices.NLSFInterpCoef_Q2 < 4 ) {
+        /* Calculation of the interpolated NLSF0 vector from the interpolation factor, */
+        /* the previous NLSF1, and the current NLSF1                                   */
+        for( i = 0; i < psDec->LPC_order; i++ ) {
+            pNLSF0_Q15[ i ] = psDec->prevNLSF_Q15[ i ] + silk_RSHIFT( silk_MUL( psDec->indices.NLSFInterpCoef_Q2,
+                pNLSF_Q15[ i ] - psDec->prevNLSF_Q15[ i ] ), 2 );
+        }
+
+        /* Convert NLSF parameters to AR prediction filter coefficients */
+        silk_NLSF2A( psDecCtrl->PredCoef_Q12[ 0 ], pNLSF0_Q15, psDec->LPC_order, psDec->arch );
+    } else {
+        /* Copy LPC coefficients for first half from second half */
+        silk_memcpy( psDecCtrl->PredCoef_Q12[ 0 ], psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( opus_int16 ) );
+    }
+
+    silk_memcpy( psDec->prevNLSF_Q15, pNLSF_Q15, psDec->LPC_order * sizeof( opus_int16 ) );
+
+    /* After a packet loss do BWE of LPC coefs */
+    if( psDec->lossCnt ) {
+        silk_bwexpander( psDecCtrl->PredCoef_Q12[ 0 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );
+        silk_bwexpander( psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );
+    }
+
+    if( psDec->indices.signalType == TYPE_VOICED ) {
+        /*********************/
+        /* Decode pitch lags */
+        /*********************/
+
+        /* Decode pitch values */
+        silk_decode_pitch( psDec->indices.lagIndex, psDec->indices.contourIndex, psDecCtrl->pitchL, psDec->fs_kHz, psDec->nb_subfr );
+
+        /* Decode Codebook Index */
+        cbk_ptr_Q7 = silk_LTP_vq_ptrs_Q7[ psDec->indices.PERIndex ]; /* set pointer to start of codebook */
+
+        for( k = 0; k < psDec->nb_subfr; k++ ) {
+            Ix = psDec->indices.LTPIndex[ k ];
+            for( i = 0; i < LTP_ORDER; i++ ) {
+                psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER + i ] = silk_LSHIFT( cbk_ptr_Q7[ Ix * LTP_ORDER + i ], 7 );
+            }
+        }
+
+        /**********************/
+        /* Decode LTP scaling */
+        /**********************/
+        Ix = psDec->indices.LTP_scaleIndex;
+        psDecCtrl->LTP_scale_Q14 = silk_LTPScales_table_Q14[ Ix ];
+    } else {
+        silk_memset( psDecCtrl->pitchL,      0,             psDec->nb_subfr * sizeof( opus_int   ) );
+        silk_memset( psDecCtrl->LTPCoef_Q14, 0, LTP_ORDER * psDec->nb_subfr * sizeof( opus_int16 ) );
+        psDec->indices.PERIndex  = 0;
+        psDecCtrl->LTP_scale_Q14 = 0;
+    }
+}
diff --git a/opus/silk/decode_pitch.c b/opus/silk/decode_pitch.c
new file mode 100644 (file)
index 0000000..fedbc6a
--- /dev/null
@@ -0,0 +1,77 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/***********************************************************
+* Pitch analyser function
+********************************************************** */
+#include "SigProc_FIX.h"
+#include "pitch_est_defines.h"
+
+void silk_decode_pitch(
+    opus_int16                  lagIndex,           /* I                                                                */
+    opus_int8                   contourIndex,       /* O                                                                */
+    opus_int                    pitch_lags[],       /* O    4 pitch values                                              */
+    const opus_int              Fs_kHz,             /* I    sampling frequency (kHz)                                    */
+    const opus_int              nb_subfr            /* I    number of sub frames                                        */
+)
+{
+    opus_int   lag, k, min_lag, max_lag, cbk_size;
+    const opus_int8 *Lag_CB_ptr;
+
+    if( Fs_kHz == 8 ) {
+        if( nb_subfr == PE_MAX_NB_SUBFR ) {
+            Lag_CB_ptr = &silk_CB_lags_stage2[ 0 ][ 0 ];
+            cbk_size   = PE_NB_CBKS_STAGE2_EXT;
+        } else {
+            silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1 );
+            Lag_CB_ptr = &silk_CB_lags_stage2_10_ms[ 0 ][ 0 ];
+            cbk_size   = PE_NB_CBKS_STAGE2_10MS;
+        }
+    } else {
+        if( nb_subfr == PE_MAX_NB_SUBFR ) {
+            Lag_CB_ptr = &silk_CB_lags_stage3[ 0 ][ 0 ];
+            cbk_size   = PE_NB_CBKS_STAGE3_MAX;
+        } else {
+            silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1 );
+            Lag_CB_ptr = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+            cbk_size   = PE_NB_CBKS_STAGE3_10MS;
+        }
+    }
+
+    min_lag = silk_SMULBB( PE_MIN_LAG_MS, Fs_kHz );
+    max_lag = silk_SMULBB( PE_MAX_LAG_MS, Fs_kHz );
+    lag = min_lag + lagIndex;
+
+    for( k = 0; k < nb_subfr; k++ ) {
+        pitch_lags[ k ] = lag + matrix_ptr( Lag_CB_ptr, k, contourIndex, cbk_size );
+        pitch_lags[ k ] = silk_LIMIT( pitch_lags[ k ], min_lag, max_lag );
+    }
+}
diff --git a/opus/silk/decode_pulses.c b/opus/silk/decode_pulses.c
new file mode 100644 (file)
index 0000000..d6bbec9
--- /dev/null
@@ -0,0 +1,115 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/*********************************************/
+/* Decode quantization indices of excitation */
+/*********************************************/
+void silk_decode_pulses(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int16                  pulses[],                       /* O    Excitation signal                           */
+    const opus_int              signalType,                     /* I    Sigtype                                     */
+    const opus_int              quantOffsetType,                /* I    quantOffsetType                             */
+    const opus_int              frame_length                    /* I    Frame length                                */
+)
+{
+    opus_int   i, j, k, iter, abs_q, nLS, RateLevelIndex;
+    opus_int   sum_pulses[ MAX_NB_SHELL_BLOCKS ], nLshifts[ MAX_NB_SHELL_BLOCKS ];
+    opus_int16 *pulses_ptr;
+    const opus_uint8 *cdf_ptr;
+
+    /*********************/
+    /* Decode rate level */
+    /*********************/
+    RateLevelIndex = ec_dec_icdf( psRangeDec, silk_rate_levels_iCDF[ signalType >> 1 ], 8 );
+
+    /* Calculate number of shell blocks */
+    silk_assert( 1 << LOG2_SHELL_CODEC_FRAME_LENGTH == SHELL_CODEC_FRAME_LENGTH );
+    iter = silk_RSHIFT( frame_length, LOG2_SHELL_CODEC_FRAME_LENGTH );
+    if( iter * SHELL_CODEC_FRAME_LENGTH < frame_length ) {
+        silk_assert( frame_length == 12 * 10 ); /* Make sure only happens for 10 ms @ 12 kHz */
+        iter++;
+    }
+
+    /***************************************************/
+    /* Sum-Weighted-Pulses Decoding                    */
+    /***************************************************/
+    cdf_ptr = silk_pulses_per_block_iCDF[ RateLevelIndex ];
+    for( i = 0; i < iter; i++ ) {
+        nLshifts[ i ] = 0;
+        sum_pulses[ i ] = ec_dec_icdf( psRangeDec, cdf_ptr, 8 );
+
+        /* LSB indication */
+        while( sum_pulses[ i ] == SILK_MAX_PULSES + 1 ) {
+            nLshifts[ i ]++;
+            /* When we've already got 10 LSBs, we shift the table to not allow (SILK_MAX_PULSES + 1) */
+            sum_pulses[ i ] = ec_dec_icdf( psRangeDec,
+                    silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1] + ( nLshifts[ i ] == 10 ), 8 );
+        }
+    }
+
+    /***************************************************/
+    /* Shell decoding                                  */
+    /***************************************************/
+    for( i = 0; i < iter; i++ ) {
+        if( sum_pulses[ i ] > 0 ) {
+            silk_shell_decoder( &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], psRangeDec, sum_pulses[ i ] );
+        } else {
+            silk_memset( &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], 0, SHELL_CODEC_FRAME_LENGTH * sizeof( pulses[0] ) );
+        }
+    }
+
+    /***************************************************/
+    /* LSB Decoding                                    */
+    /***************************************************/
+    for( i = 0; i < iter; i++ ) {
+        if( nLshifts[ i ] > 0 ) {
+            nLS = nLshifts[ i ];
+            pulses_ptr = &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ];
+            for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
+                abs_q = pulses_ptr[ k ];
+                for( j = 0; j < nLS; j++ ) {
+                    abs_q = silk_LSHIFT( abs_q, 1 );
+                    abs_q += ec_dec_icdf( psRangeDec, silk_lsb_iCDF, 8 );
+                }
+                pulses_ptr[ k ] = abs_q;
+            }
+            /* Mark the number of pulses non-zero for sign decoding. */
+            sum_pulses[ i ] |= nLS << 5;
+        }
+    }
+
+    /****************************************/
+    /* Decode and add signs to pulse signal */
+    /****************************************/
+    silk_decode_signs( psRangeDec, pulses, frame_length, signalType, quantOffsetType, sum_pulses );
+}
diff --git a/opus/silk/decoder_set_fs.c b/opus/silk/decoder_set_fs.c
new file mode 100644 (file)
index 0000000..eef0fd2
--- /dev/null
@@ -0,0 +1,108 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Set decoder sampling rate */
+opus_int silk_decoder_set_fs(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state pointer                       */
+    opus_int                    fs_kHz,                         /* I    Sampling frequency (kHz)                    */
+    opus_int32                  fs_API_Hz                       /* I    API Sampling frequency (Hz)                 */
+)
+{
+    opus_int frame_length, ret = 0;
+
+    silk_assert( fs_kHz == 8 || fs_kHz == 12 || fs_kHz == 16 );
+    silk_assert( psDec->nb_subfr == MAX_NB_SUBFR || psDec->nb_subfr == MAX_NB_SUBFR/2 );
+
+    /* New (sub)frame length */
+    psDec->subfr_length = silk_SMULBB( SUB_FRAME_LENGTH_MS, fs_kHz );
+    frame_length = silk_SMULBB( psDec->nb_subfr, psDec->subfr_length );
+
+    /* Initialize resampler when switching internal or external sampling frequency */
+    if( psDec->fs_kHz != fs_kHz || psDec->fs_API_hz != fs_API_Hz ) {
+        /* Initialize the resampler for dec_API.c preparing resampling from fs_kHz to API_fs_Hz */
+        ret += silk_resampler_init( &psDec->resampler_state, silk_SMULBB( fs_kHz, 1000 ), fs_API_Hz, 0 );
+
+        psDec->fs_API_hz = fs_API_Hz;
+    }
+
+    if( psDec->fs_kHz != fs_kHz || frame_length != psDec->frame_length ) {
+        if( fs_kHz == 8 ) {
+            if( psDec->nb_subfr == MAX_NB_SUBFR ) {
+                psDec->pitch_contour_iCDF = silk_pitch_contour_NB_iCDF;
+            } else {
+                psDec->pitch_contour_iCDF = silk_pitch_contour_10_ms_NB_iCDF;
+            }
+        } else {
+            if( psDec->nb_subfr == MAX_NB_SUBFR ) {
+                psDec->pitch_contour_iCDF = silk_pitch_contour_iCDF;
+            } else {
+                psDec->pitch_contour_iCDF = silk_pitch_contour_10_ms_iCDF;
+            }
+        }
+        if( psDec->fs_kHz != fs_kHz ) {
+            psDec->ltp_mem_length = silk_SMULBB( LTP_MEM_LENGTH_MS, fs_kHz );
+            if( fs_kHz == 8 || fs_kHz == 12 ) {
+                psDec->LPC_order = MIN_LPC_ORDER;
+                psDec->psNLSF_CB = &silk_NLSF_CB_NB_MB;
+            } else {
+                psDec->LPC_order = MAX_LPC_ORDER;
+                psDec->psNLSF_CB = &silk_NLSF_CB_WB;
+            }
+            if( fs_kHz == 16 ) {
+                psDec->pitch_lag_low_bits_iCDF = silk_uniform8_iCDF;
+            } else if( fs_kHz == 12 ) {
+                psDec->pitch_lag_low_bits_iCDF = silk_uniform6_iCDF;
+            } else if( fs_kHz == 8 ) {
+                psDec->pitch_lag_low_bits_iCDF = silk_uniform4_iCDF;
+            } else {
+                /* unsupported sampling rate */
+                silk_assert( 0 );
+            }
+            psDec->first_frame_after_reset = 1;
+            psDec->lagPrev                 = 100;
+            psDec->LastGainIndex           = 10;
+            psDec->prevSignalType          = TYPE_NO_VOICE_ACTIVITY;
+            silk_memset( psDec->outBuf, 0, sizeof(psDec->outBuf));
+            silk_memset( psDec->sLPC_Q14_buf, 0, sizeof(psDec->sLPC_Q14_buf) );
+        }
+
+        psDec->fs_kHz       = fs_kHz;
+        psDec->frame_length = frame_length;
+    }
+
+    /* Check that settings are valid */
+    silk_assert( psDec->frame_length > 0 && psDec->frame_length <= MAX_FRAME_LENGTH );
+
+    return ret;
+}
+
diff --git a/opus/silk/define.h b/opus/silk/define.h
new file mode 100644 (file)
index 0000000..1286048
--- /dev/null
@@ -0,0 +1,230 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_DEFINE_H
+#define SILK_DEFINE_H
+
+#include "errors.h"
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Max number of encoder channels (1/2) */
+#define ENCODER_NUM_CHANNELS                    2
+/* Number of decoder channels (1/2) */
+#define DECODER_NUM_CHANNELS                    2
+
+#define MAX_FRAMES_PER_PACKET                   3
+
+/* Limits on bitrate */
+#define MIN_TARGET_RATE_BPS                     5000
+#define MAX_TARGET_RATE_BPS                     80000
+#define TARGET_RATE_TAB_SZ                      8
+
+/* LBRR thresholds */
+#define LBRR_NB_MIN_RATE_BPS                    12000
+#define LBRR_MB_MIN_RATE_BPS                    14000
+#define LBRR_WB_MIN_RATE_BPS                    16000
+
+/* DTX settings */
+#define NB_SPEECH_FRAMES_BEFORE_DTX             10      /* eq 200 ms */
+#define MAX_CONSECUTIVE_DTX                     20      /* eq 400 ms */
+#define DTX_ACTIVITY_THRESHOLD                  0.1f
+
+/* Maximum sampling frequency */
+#define MAX_FS_KHZ                              16
+#define MAX_API_FS_KHZ                          48
+
+/* Signal types */
+#define TYPE_NO_VOICE_ACTIVITY                  0
+#define TYPE_UNVOICED                           1
+#define TYPE_VOICED                             2
+
+/* Conditional coding types */
+#define CODE_INDEPENDENTLY                      0
+#define CODE_INDEPENDENTLY_NO_LTP_SCALING       1
+#define CODE_CONDITIONALLY                      2
+
+/* Settings for stereo processing */
+#define STEREO_QUANT_TAB_SIZE                   16
+#define STEREO_QUANT_SUB_STEPS                  5
+#define STEREO_INTERP_LEN_MS                    8       /* must be even */
+#define STEREO_RATIO_SMOOTH_COEF                0.01    /* smoothing coef for signal norms and stereo width */
+
+/* Range of pitch lag estimates */
+#define PITCH_EST_MIN_LAG_MS                    2       /* 2 ms -> 500 Hz */
+#define PITCH_EST_MAX_LAG_MS                    18      /* 18 ms -> 56 Hz */
+
+/* Maximum number of subframes */
+#define MAX_NB_SUBFR                            4
+
+/* Number of samples per frame */
+#define LTP_MEM_LENGTH_MS                       20
+#define SUB_FRAME_LENGTH_MS                     5
+#define MAX_SUB_FRAME_LENGTH                    ( SUB_FRAME_LENGTH_MS * MAX_FS_KHZ )
+#define MAX_FRAME_LENGTH_MS                     ( SUB_FRAME_LENGTH_MS * MAX_NB_SUBFR )
+#define MAX_FRAME_LENGTH                        ( MAX_FRAME_LENGTH_MS * MAX_FS_KHZ )
+
+/* Milliseconds of lookahead for pitch analysis */
+#define LA_PITCH_MS                             2
+#define LA_PITCH_MAX                            ( LA_PITCH_MS * MAX_FS_KHZ )
+
+/* Order of LPC used in find pitch */
+#define MAX_FIND_PITCH_LPC_ORDER                16
+
+/* Length of LPC window used in find pitch */
+#define FIND_PITCH_LPC_WIN_MS                   ( 20 + (LA_PITCH_MS << 1) )
+#define FIND_PITCH_LPC_WIN_MS_2_SF              ( 10 + (LA_PITCH_MS << 1) )
+#define FIND_PITCH_LPC_WIN_MAX                  ( FIND_PITCH_LPC_WIN_MS * MAX_FS_KHZ )
+
+/* Milliseconds of lookahead for noise shape analysis */
+#define LA_SHAPE_MS                             5
+#define LA_SHAPE_MAX                            ( LA_SHAPE_MS * MAX_FS_KHZ )
+
+/* Maximum length of LPC window used in noise shape analysis */
+#define SHAPE_LPC_WIN_MAX                       ( 15 * MAX_FS_KHZ )
+
+/* dB level of lowest gain quantization level */
+#define MIN_QGAIN_DB                            2
+/* dB level of highest gain quantization level */
+#define MAX_QGAIN_DB                            88
+/* Number of gain quantization levels */
+#define N_LEVELS_QGAIN                          64
+/* Max increase in gain quantization index */
+#define MAX_DELTA_GAIN_QUANT                    36
+/* Max decrease in gain quantization index */
+#define MIN_DELTA_GAIN_QUANT                    -4
+
+/* Quantization offsets (multiples of 4) */
+#define OFFSET_VL_Q10                           32
+#define OFFSET_VH_Q10                           100
+#define OFFSET_UVL_Q10                          100
+#define OFFSET_UVH_Q10                          240
+
+#define QUANT_LEVEL_ADJUST_Q10                  80
+
+/* Maximum numbers of iterations used to stabilize an LPC vector */
+#define MAX_LPC_STABILIZE_ITERATIONS            16
+#define MAX_PREDICTION_POWER_GAIN               1e4f
+#define MAX_PREDICTION_POWER_GAIN_AFTER_RESET   1e2f
+
+#define MAX_LPC_ORDER                           16
+#define MIN_LPC_ORDER                           10
+
+/* Find Pred Coef defines */
+#define LTP_ORDER                               5
+
+/* LTP quantization settings */
+#define NB_LTP_CBKS                             3
+
+/* Flag to use harmonic noise shaping */
+#define USE_HARM_SHAPING                        1
+
+/* Max LPC order of noise shaping filters */
+#define MAX_SHAPE_LPC_ORDER                     24
+
+#define HARM_SHAPE_FIR_TAPS                     3
+
+/* Maximum number of delayed decision states */
+#define MAX_DEL_DEC_STATES                      4
+
+#define LTP_BUF_LENGTH                          512
+#define LTP_MASK                                ( LTP_BUF_LENGTH - 1 )
+
+#define DECISION_DELAY                          40
+
+/* Number of subframes for excitation entropy coding */
+#define SHELL_CODEC_FRAME_LENGTH                16
+#define LOG2_SHELL_CODEC_FRAME_LENGTH           4
+#define MAX_NB_SHELL_BLOCKS                     ( MAX_FRAME_LENGTH / SHELL_CODEC_FRAME_LENGTH )
+
+/* Number of rate levels, for entropy coding of excitation */
+#define N_RATE_LEVELS                           10
+
+/* Maximum sum of pulses per shell coding frame */
+#define SILK_MAX_PULSES                         16
+
+#define MAX_MATRIX_SIZE                         MAX_LPC_ORDER /* Max of LPC Order and LTP order */
+
+# define NSQ_LPC_BUF_LENGTH                     MAX_LPC_ORDER
+
+/***************************/
+/* Voice activity detector */
+/***************************/
+#define VAD_N_BANDS                             4
+
+#define VAD_INTERNAL_SUBFRAMES_LOG2             2
+#define VAD_INTERNAL_SUBFRAMES                  ( 1 << VAD_INTERNAL_SUBFRAMES_LOG2 )
+
+#define VAD_NOISE_LEVEL_SMOOTH_COEF_Q16         1024    /* Must be <  4096 */
+#define VAD_NOISE_LEVELS_BIAS                   50
+
+/* Sigmoid settings */
+#define VAD_NEGATIVE_OFFSET_Q5                  128     /* sigmoid is 0 at -128 */
+#define VAD_SNR_FACTOR_Q16                      45000
+
+/* smoothing for SNR measurement */
+#define VAD_SNR_SMOOTH_COEF_Q18                 4096
+
+/* Size of the piecewise linear cosine approximation table for the LSFs */
+#define LSF_COS_TAB_SZ_FIX                      128
+
+/******************/
+/* NLSF quantizer */
+/******************/
+#define NLSF_W_Q                                2
+#define NLSF_VQ_MAX_VECTORS                     32
+#define NLSF_QUANT_MAX_AMPLITUDE                4
+#define NLSF_QUANT_MAX_AMPLITUDE_EXT            10
+#define NLSF_QUANT_LEVEL_ADJ                    0.1
+#define NLSF_QUANT_DEL_DEC_STATES_LOG2          2
+#define NLSF_QUANT_DEL_DEC_STATES               ( 1 << NLSF_QUANT_DEL_DEC_STATES_LOG2 )
+
+/* Transition filtering for mode switching */
+#define TRANSITION_TIME_MS                      5120    /* 5120 = 64 * FRAME_LENGTH_MS * ( TRANSITION_INT_NUM - 1 ) = 64*(20*4)*/
+#define TRANSITION_NB                           3       /* Hardcoded in tables */
+#define TRANSITION_NA                           2       /* Hardcoded in tables */
+#define TRANSITION_INT_NUM                      5       /* Hardcoded in tables */
+#define TRANSITION_FRAMES                       ( TRANSITION_TIME_MS / MAX_FRAME_LENGTH_MS )
+#define TRANSITION_INT_STEPS                    ( TRANSITION_FRAMES  / ( TRANSITION_INT_NUM - 1 ) )
+
+/* BWE factors to apply after packet loss */
+#define BWE_AFTER_LOSS_Q16                      63570
+
+/* Defines for CN generation */
+#define CNG_BUF_MASK_MAX                        255     /* 2^floor(log2(MAX_FRAME_LENGTH))-1    */
+#define CNG_GAIN_SMTH_Q16                       4634    /* 0.25^(1/4)                           */
+#define CNG_NLSF_SMTH_Q16                       16348   /* 0.25                                 */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/enc_API.c b/opus/silk/enc_API.c
new file mode 100644 (file)
index 0000000..701c290
--- /dev/null
@@ -0,0 +1,565 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#include "define.h"
+#include "API.h"
+#include "control.h"
+#include "typedef.h"
+#include "stack_alloc.h"
+#include "structs.h"
+#include "tuning_parameters.h"
+#ifdef FIXED_POINT
+#include "main_FIX.h"
+#else
+#include "main_FLP.h"
+#endif
+
+/***************************************/
+/* Read control structure from encoder */
+/***************************************/
+static opus_int silk_QueryEncoder(                      /* O    Returns error code                              */
+    const void                      *encState,          /* I    State                                           */
+    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
+);
+
+/****************************************/
+/* Encoder functions                    */
+/****************************************/
+
+opus_int silk_Get_Encoder_Size(                         /* O    Returns error code                              */
+    opus_int                        *encSizeBytes       /* O    Number of bytes in SILK encoder state           */
+)
+{
+    opus_int ret = SILK_NO_ERROR;
+
+    *encSizeBytes = sizeof( silk_encoder );
+
+    return ret;
+}
+
+/*************************/
+/* Init or Reset encoder */
+/*************************/
+opus_int silk_InitEncoder(                              /* O    Returns error code                              */
+    void                            *encState,          /* I/O  State                                           */
+    int                              arch,              /* I    Run-time architecture                           */
+    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
+)
+{
+    silk_encoder *psEnc;
+    opus_int n, ret = SILK_NO_ERROR;
+
+    psEnc = (silk_encoder *)encState;
+
+    /* Reset encoder */
+    silk_memset( psEnc, 0, sizeof( silk_encoder ) );
+    for( n = 0; n < ENCODER_NUM_CHANNELS; n++ ) {
+        if( ret += silk_init_encoder( &psEnc->state_Fxx[ n ], arch ) ) {
+            silk_assert( 0 );
+        }
+    }
+
+    psEnc->nChannelsAPI = 1;
+    psEnc->nChannelsInternal = 1;
+
+    /* Read control structure */
+    if( ret += silk_QueryEncoder( encState, encStatus ) ) {
+        silk_assert( 0 );
+    }
+
+    return ret;
+}
+
+/***************************************/
+/* Read control structure from encoder */
+/***************************************/
+static opus_int silk_QueryEncoder(                      /* O    Returns error code                              */
+    const void                      *encState,          /* I    State                                           */
+    silk_EncControlStruct           *encStatus          /* O    Encoder Status                                  */
+)
+{
+    opus_int ret = SILK_NO_ERROR;
+    silk_encoder_state_Fxx *state_Fxx;
+    silk_encoder *psEnc = (silk_encoder *)encState;
+
+    state_Fxx = psEnc->state_Fxx;
+
+    encStatus->nChannelsAPI              = psEnc->nChannelsAPI;
+    encStatus->nChannelsInternal         = psEnc->nChannelsInternal;
+    encStatus->API_sampleRate            = state_Fxx[ 0 ].sCmn.API_fs_Hz;
+    encStatus->maxInternalSampleRate     = state_Fxx[ 0 ].sCmn.maxInternal_fs_Hz;
+    encStatus->minInternalSampleRate     = state_Fxx[ 0 ].sCmn.minInternal_fs_Hz;
+    encStatus->desiredInternalSampleRate = state_Fxx[ 0 ].sCmn.desiredInternal_fs_Hz;
+    encStatus->payloadSize_ms            = state_Fxx[ 0 ].sCmn.PacketSize_ms;
+    encStatus->bitRate                   = state_Fxx[ 0 ].sCmn.TargetRate_bps;
+    encStatus->packetLossPercentage      = state_Fxx[ 0 ].sCmn.PacketLoss_perc;
+    encStatus->complexity                = state_Fxx[ 0 ].sCmn.Complexity;
+    encStatus->useInBandFEC              = state_Fxx[ 0 ].sCmn.useInBandFEC;
+    encStatus->useDTX                    = state_Fxx[ 0 ].sCmn.useDTX;
+    encStatus->useCBR                    = state_Fxx[ 0 ].sCmn.useCBR;
+    encStatus->internalSampleRate        = silk_SMULBB( state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
+    encStatus->allowBandwidthSwitch      = state_Fxx[ 0 ].sCmn.allow_bandwidth_switch;
+    encStatus->inWBmodeWithoutVariableLP = state_Fxx[ 0 ].sCmn.fs_kHz == 16 && state_Fxx[ 0 ].sCmn.sLP.mode == 0;
+
+    return ret;
+}
+
+
+/**************************/
+/* Encode frame with Silk */
+/**************************/
+/* Note: if prefillFlag is set, the input must contain 10 ms of audio, irrespective of what                     */
+/* encControl->payloadSize_ms is set to                                                                         */
+opus_int silk_Encode(                                   /* O    Returns error code                              */
+    void                            *encState,          /* I/O  State                                           */
+    silk_EncControlStruct           *encControl,        /* I    Control status                                  */
+    const opus_int16                *samplesIn,         /* I    Speech sample input vector                      */
+    opus_int                        nSamplesIn,         /* I    Number of samples in input vector               */
+    ec_enc                          *psRangeEnc,        /* I/O  Compressor data structure                       */
+    opus_int32                      *nBytesOut,         /* I/O  Number of bytes in payload (input: Max bytes)   */
+    const opus_int                  prefillFlag         /* I    Flag to indicate prefilling buffers no coding   */
+)
+{
+    opus_int   n, i, nBits, flags, tmp_payloadSize_ms = 0, tmp_complexity = 0, ret = 0;
+    opus_int   nSamplesToBuffer, nSamplesToBufferMax, nBlocksOf10ms;
+    opus_int   nSamplesFromInput = 0, nSamplesFromInputMax;
+    opus_int   speech_act_thr_for_switch_Q8;
+    opus_int32 TargetRate_bps, MStargetRates_bps[ 2 ], channelRate_bps, LBRR_symbol, sum;
+    silk_encoder *psEnc = ( silk_encoder * )encState;
+    VARDECL( opus_int16, buf );
+    opus_int transition, curr_block, tot_blocks;
+    SAVE_STACK;
+
+    if (encControl->reducedDependency)
+    {
+       psEnc->state_Fxx[0].sCmn.first_frame_after_reset = 1;
+       psEnc->state_Fxx[1].sCmn.first_frame_after_reset = 1;
+    }
+    psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded = psEnc->state_Fxx[ 1 ].sCmn.nFramesEncoded = 0;
+
+    /* Check values in encoder control structure */
+    if( ( ret = check_control_input( encControl ) ) != 0 ) {
+        silk_assert( 0 );
+        RESTORE_STACK;
+        return ret;
+    }
+
+    encControl->switchReady = 0;
+
+    if( encControl->nChannelsInternal > psEnc->nChannelsInternal ) {
+        /* Mono -> Stereo transition: init state of second channel and stereo state */
+        ret += silk_init_encoder( &psEnc->state_Fxx[ 1 ], psEnc->state_Fxx[ 0 ].sCmn.arch );
+        silk_memset( psEnc->sStereo.pred_prev_Q13, 0, sizeof( psEnc->sStereo.pred_prev_Q13 ) );
+        silk_memset( psEnc->sStereo.sSide, 0, sizeof( psEnc->sStereo.sSide ) );
+        psEnc->sStereo.mid_side_amp_Q0[ 0 ] = 0;
+        psEnc->sStereo.mid_side_amp_Q0[ 1 ] = 1;
+        psEnc->sStereo.mid_side_amp_Q0[ 2 ] = 0;
+        psEnc->sStereo.mid_side_amp_Q0[ 3 ] = 1;
+        psEnc->sStereo.width_prev_Q14 = 0;
+        psEnc->sStereo.smth_width_Q14 = SILK_FIX_CONST( 1, 14 );
+        if( psEnc->nChannelsAPI == 2 ) {
+            silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof( silk_resampler_state_struct ) );
+            silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.In_HP_State,     &psEnc->state_Fxx[ 0 ].sCmn.In_HP_State,     sizeof( psEnc->state_Fxx[ 1 ].sCmn.In_HP_State ) );
+        }
+    }
+
+    transition = (encControl->payloadSize_ms != psEnc->state_Fxx[ 0 ].sCmn.PacketSize_ms) || (psEnc->nChannelsInternal != encControl->nChannelsInternal);
+
+    psEnc->nChannelsAPI = encControl->nChannelsAPI;
+    psEnc->nChannelsInternal = encControl->nChannelsInternal;
+
+    nBlocksOf10ms = silk_DIV32( 100 * nSamplesIn, encControl->API_sampleRate );
+    tot_blocks = ( nBlocksOf10ms > 1 ) ? nBlocksOf10ms >> 1 : 1;
+    curr_block = 0;
+    if( prefillFlag ) {
+        /* Only accept input length of 10 ms */
+        if( nBlocksOf10ms != 1 ) {
+            silk_assert( 0 );
+            RESTORE_STACK;
+            return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
+        }
+        /* Reset Encoder */
+        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+            ret = silk_init_encoder( &psEnc->state_Fxx[ n ], psEnc->state_Fxx[ n ].sCmn.arch );
+            silk_assert( !ret );
+        }
+        tmp_payloadSize_ms = encControl->payloadSize_ms;
+        encControl->payloadSize_ms = 10;
+        tmp_complexity = encControl->complexity;
+        encControl->complexity = 0;
+        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+            psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
+            psEnc->state_Fxx[ n ].sCmn.prefillFlag = 1;
+        }
+    } else {
+        /* Only accept input lengths that are a multiple of 10 ms */
+        if( nBlocksOf10ms * encControl->API_sampleRate != 100 * nSamplesIn || nSamplesIn < 0 ) {
+            silk_assert( 0 );
+            RESTORE_STACK;
+            return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
+        }
+        /* Make sure no more than one packet can be produced */
+        if( 1000 * (opus_int32)nSamplesIn > encControl->payloadSize_ms * encControl->API_sampleRate ) {
+            silk_assert( 0 );
+            RESTORE_STACK;
+            return SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;
+        }
+    }
+
+    for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+        /* Force the side channel to the same rate as the mid */
+        opus_int force_fs_kHz = (n==1) ? psEnc->state_Fxx[0].sCmn.fs_kHz : 0;
+        if( ( ret = silk_control_encoder( &psEnc->state_Fxx[ n ], encControl, psEnc->allowBandwidthSwitch, n, force_fs_kHz ) ) != 0 ) {
+            silk_assert( 0 );
+            RESTORE_STACK;
+            return ret;
+        }
+        if( psEnc->state_Fxx[n].sCmn.first_frame_after_reset || transition ) {
+            for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
+                psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] = 0;
+            }
+        }
+        psEnc->state_Fxx[ n ].sCmn.inDTX = psEnc->state_Fxx[ n ].sCmn.useDTX;
+    }
+    silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );
+
+    /* Input buffering/resampling and encoding */
+    nSamplesToBufferMax =
+        10 * nBlocksOf10ms * psEnc->state_Fxx[ 0 ].sCmn.fs_kHz;
+    nSamplesFromInputMax =
+        silk_DIV32_16( nSamplesToBufferMax *
+                           psEnc->state_Fxx[ 0 ].sCmn.API_fs_Hz,
+                       psEnc->state_Fxx[ 0 ].sCmn.fs_kHz * 1000 );
+    ALLOC( buf, nSamplesFromInputMax, opus_int16 );
+    while( 1 ) {
+        nSamplesToBuffer  = psEnc->state_Fxx[ 0 ].sCmn.frame_length - psEnc->state_Fxx[ 0 ].sCmn.inputBufIx;
+        nSamplesToBuffer  = silk_min( nSamplesToBuffer, nSamplesToBufferMax );
+        nSamplesFromInput = silk_DIV32_16( nSamplesToBuffer * psEnc->state_Fxx[ 0 ].sCmn.API_fs_Hz, psEnc->state_Fxx[ 0 ].sCmn.fs_kHz * 1000 );
+        /* Resample and write to buffer */
+        if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 2 ) {
+            opus_int id = psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded;
+            for( n = 0; n < nSamplesFromInput; n++ ) {
+                buf[ n ] = samplesIn[ 2 * n ];
+            }
+            /* Making sure to start both resamplers from the same state when switching from mono to stereo */
+            if( psEnc->nPrevChannelsInternal == 1 && id==0 ) {
+               silk_memcpy( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state, &psEnc->state_Fxx[ 0 ].sCmn.resampler_state, sizeof(psEnc->state_Fxx[ 1 ].sCmn.resampler_state));
+            }
+
+            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
+                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
+            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
+
+            nSamplesToBuffer  = psEnc->state_Fxx[ 1 ].sCmn.frame_length - psEnc->state_Fxx[ 1 ].sCmn.inputBufIx;
+            nSamplesToBuffer  = silk_min( nSamplesToBuffer, 10 * nBlocksOf10ms * psEnc->state_Fxx[ 1 ].sCmn.fs_kHz );
+            for( n = 0; n < nSamplesFromInput; n++ ) {
+                buf[ n ] = samplesIn[ 2 * n + 1 ];
+            }
+            ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
+                &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
+
+            psEnc->state_Fxx[ 1 ].sCmn.inputBufIx += nSamplesToBuffer;
+        } else if( encControl->nChannelsAPI == 2 && encControl->nChannelsInternal == 1 ) {
+            /* Combine left and right channels before resampling */
+            for( n = 0; n < nSamplesFromInput; n++ ) {
+                sum = samplesIn[ 2 * n ] + samplesIn[ 2 * n + 1 ];
+                buf[ n ] = (opus_int16)silk_RSHIFT_ROUND( sum,  1 );
+            }
+            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
+                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
+            /* On the first mono frame, average the results for the two resampler states  */
+            if( psEnc->nPrevChannelsInternal == 2 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 ) {
+               ret += silk_resampler( &psEnc->state_Fxx[ 1 ].sCmn.resampler_state,
+                   &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
+               for( n = 0; n < psEnc->state_Fxx[ 0 ].sCmn.frame_length; n++ ) {
+                  psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ] =
+                        silk_RSHIFT(psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx+n+2 ]
+                                  + psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ psEnc->state_Fxx[ 1 ].sCmn.inputBufIx+n+2 ], 1);
+               }
+            }
+            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
+        } else {
+            silk_assert( encControl->nChannelsAPI == 1 && encControl->nChannelsInternal == 1 );
+            silk_memcpy(buf, samplesIn, nSamplesFromInput*sizeof(opus_int16));
+            ret += silk_resampler( &psEnc->state_Fxx[ 0 ].sCmn.resampler_state,
+                &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.inputBufIx + 2 ], buf, nSamplesFromInput );
+            psEnc->state_Fxx[ 0 ].sCmn.inputBufIx += nSamplesToBuffer;
+        }
+
+        samplesIn  += nSamplesFromInput * encControl->nChannelsAPI;
+        nSamplesIn -= nSamplesFromInput;
+
+        /* Default */
+        psEnc->allowBandwidthSwitch = 0;
+
+        /* Silk encoder */
+        if( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx >= psEnc->state_Fxx[ 0 ].sCmn.frame_length ) {
+            /* Enough data in input buffer, so encode */
+            silk_assert( psEnc->state_Fxx[ 0 ].sCmn.inputBufIx == psEnc->state_Fxx[ 0 ].sCmn.frame_length );
+            silk_assert( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inputBufIx == psEnc->state_Fxx[ 1 ].sCmn.frame_length );
+
+            /* Deal with LBRR data */
+            if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == 0 && !prefillFlag ) {
+                /* Create space at start of payload for VAD and FEC flags */
+                opus_uint8 iCDF[ 2 ] = { 0, 0 };
+                iCDF[ 0 ] = 256 - silk_RSHIFT( 256, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
+                ec_enc_icdf( psRangeEnc, 0, iCDF, 8 );
+
+                /* Encode any LBRR data from previous packet */
+                /* Encode LBRR flags */
+                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+                    LBRR_symbol = 0;
+                    for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
+                        LBRR_symbol |= silk_LSHIFT( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ], i );
+                    }
+                    psEnc->state_Fxx[ n ].sCmn.LBRR_flag = LBRR_symbol > 0 ? 1 : 0;
+                    if( LBRR_symbol && psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket > 1 ) {
+                        ec_enc_icdf( psRangeEnc, LBRR_symbol - 1, silk_LBRR_flags_iCDF_ptr[ psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket - 2 ], 8 );
+                    }
+                }
+
+                /* Code LBRR indices and excitation signals */
+                for( i = 0; i < psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket; i++ ) {
+                    for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+                        if( psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i ] ) {
+                            opus_int condCoding;
+
+                            if( encControl->nChannelsInternal == 2 && n == 0 ) {
+                                silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ i ] );
+                                /* For LBRR data there's no need to code the mid-only flag if the side-channel LBRR flag is set */
+                                if( psEnc->state_Fxx[ 1 ].sCmn.LBRR_flags[ i ] == 0 ) {
+                                    silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ i ] );
+                                }
+                            }
+                            /* Use conditional coding if previous frame available */
+                            if( i > 0 && psEnc->state_Fxx[ n ].sCmn.LBRR_flags[ i - 1 ] ) {
+                                condCoding = CODE_CONDITIONALLY;
+                            } else {
+                                condCoding = CODE_INDEPENDENTLY;
+                            }
+                            silk_encode_indices( &psEnc->state_Fxx[ n ].sCmn, psRangeEnc, i, 1, condCoding );
+                            silk_encode_pulses( psRangeEnc, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].signalType, psEnc->state_Fxx[ n ].sCmn.indices_LBRR[i].quantOffsetType,
+                                psEnc->state_Fxx[ n ].sCmn.pulses_LBRR[ i ], psEnc->state_Fxx[ n ].sCmn.frame_length );
+                        }
+                    }
+                }
+
+                /* Reset LBRR flags */
+                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+                    silk_memset( psEnc->state_Fxx[ n ].sCmn.LBRR_flags, 0, sizeof( psEnc->state_Fxx[ n ].sCmn.LBRR_flags ) );
+                }
+
+                psEnc->nBitsUsedLBRR = ec_tell( psRangeEnc );
+            }
+
+            silk_HP_variable_cutoff( psEnc->state_Fxx );
+
+            /* Total target bits for packet */
+            nBits = silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
+            /* Subtract bits used for LBRR */
+            if( !prefillFlag ) {
+                nBits -= psEnc->nBitsUsedLBRR;
+            }
+            /* Divide by number of uncoded frames left in packet */
+            nBits = silk_DIV32_16( nBits, psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket );
+            /* Convert to bits/second */
+            if( encControl->payloadSize_ms == 10 ) {
+                TargetRate_bps = silk_SMULBB( nBits, 100 );
+            } else {
+                TargetRate_bps = silk_SMULBB( nBits, 50 );
+            }
+            /* Subtract fraction of bits in excess of target in previous frames and packets */
+            TargetRate_bps -= silk_DIV32_16( silk_MUL( psEnc->nBitsExceeded, 1000 ), BITRESERVOIR_DECAY_TIME_MS );
+            if( !prefillFlag && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded > 0 ) {
+                /* Compare actual vs target bits so far in this packet */
+                opus_int32 bitsBalance = ec_tell( psRangeEnc ) - psEnc->nBitsUsedLBRR - nBits * psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded;
+                TargetRate_bps -= silk_DIV32_16( silk_MUL( bitsBalance, 1000 ), BITRESERVOIR_DECAY_TIME_MS );
+            }
+            /* Never exceed input bitrate */
+            TargetRate_bps = silk_LIMIT( TargetRate_bps, encControl->bitRate, 5000 );
+
+            /* Convert Left/Right to Mid/Side */
+            if( encControl->nChannelsInternal == 2 ) {
+                silk_stereo_LR_to_MS( &psEnc->sStereo, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ 2 ], &psEnc->state_Fxx[ 1 ].sCmn.inputBuf[ 2 ],
+                    psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ], &psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ],
+                    MStargetRates_bps, TargetRate_bps, psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8, encControl->toMono,
+                    psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, psEnc->state_Fxx[ 0 ].sCmn.frame_length );
+                if( psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
+                    /* Reset side channel encoder memory for first frame with side coding */
+                    if( psEnc->prev_decode_only_middle == 1 ) {
+                        silk_memset( &psEnc->state_Fxx[ 1 ].sShape,               0, sizeof( psEnc->state_Fxx[ 1 ].sShape ) );
+                        silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sNSQ,            0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sNSQ ) );
+                        silk_memset( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15,   0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.prev_NLSFq_Q15 ) );
+                        silk_memset( &psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State, 0, sizeof( psEnc->state_Fxx[ 1 ].sCmn.sLP.In_LP_State ) );
+                        psEnc->state_Fxx[ 1 ].sCmn.prevLag                 = 100;
+                        psEnc->state_Fxx[ 1 ].sCmn.sNSQ.lagPrev            = 100;
+                        psEnc->state_Fxx[ 1 ].sShape.LastGainIndex         = 10;
+                        psEnc->state_Fxx[ 1 ].sCmn.prevSignalType          = TYPE_NO_VOICE_ACTIVITY;
+                        psEnc->state_Fxx[ 1 ].sCmn.sNSQ.prev_gain_Q16      = 65536;
+                        psEnc->state_Fxx[ 1 ].sCmn.first_frame_after_reset = 1;
+                    }
+                    silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 1 ] );
+                } else {
+                    psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] = 0;
+                }
+                if( !prefillFlag ) {
+                    silk_stereo_encode_pred( psRangeEnc, psEnc->sStereo.predIx[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
+                    if( psEnc->state_Fxx[ 1 ].sCmn.VAD_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] == 0 ) {
+                        silk_stereo_encode_mid_only( psRangeEnc, psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded ] );
+                    }
+                }
+            } else {
+                /* Buffering */
+                silk_memcpy( psEnc->state_Fxx[ 0 ].sCmn.inputBuf, psEnc->sStereo.sMid, 2 * sizeof( opus_int16 ) );
+                silk_memcpy( psEnc->sStereo.sMid, &psEnc->state_Fxx[ 0 ].sCmn.inputBuf[ psEnc->state_Fxx[ 0 ].sCmn.frame_length ], 2 * sizeof( opus_int16 ) );
+            }
+            silk_encode_do_VAD_Fxx( &psEnc->state_Fxx[ 0 ] );
+
+            /* Encode */
+            for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+                opus_int maxBits, useCBR;
+
+                /* Handling rate constraints */
+                maxBits = encControl->maxBits;
+                if( tot_blocks == 2 && curr_block == 0 ) {
+                    maxBits = maxBits * 3 / 5;
+                } else if( tot_blocks == 3 ) {
+                    if( curr_block == 0 ) {
+                        maxBits = maxBits * 2 / 5;
+                    } else if( curr_block == 1 ) {
+                        maxBits = maxBits * 3 / 4;
+                    }
+                }
+                useCBR = encControl->useCBR && curr_block == tot_blocks - 1;
+
+                if( encControl->nChannelsInternal == 1 ) {
+                    channelRate_bps = TargetRate_bps;
+                } else {
+                    channelRate_bps = MStargetRates_bps[ n ];
+                    if( n == 0 && MStargetRates_bps[ 1 ] > 0 ) {
+                        useCBR = 0;
+                        /* Give mid up to 1/2 of the max bits for that frame */
+                        maxBits -= encControl->maxBits / ( tot_blocks * 2 );
+                    }
+                }
+
+                if( channelRate_bps > 0 ) {
+                    opus_int condCoding;
+
+                    silk_control_SNR( &psEnc->state_Fxx[ n ].sCmn, channelRate_bps );
+
+                    /* Use independent coding if no previous frame available */
+                    if( psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - n <= 0 ) {
+                        condCoding = CODE_INDEPENDENTLY;
+                    } else if( n > 0 && psEnc->prev_decode_only_middle ) {
+                        /* If we skipped a side frame in this packet, we don't
+                           need LTP scaling; the LTP state is well-defined. */
+                        condCoding = CODE_INDEPENDENTLY_NO_LTP_SCALING;
+                    } else {
+                        condCoding = CODE_CONDITIONALLY;
+                    }
+                    if( ( ret = silk_encode_frame_Fxx( &psEnc->state_Fxx[ n ], nBytesOut, psRangeEnc, condCoding, maxBits, useCBR ) ) != 0 ) {
+                        silk_assert( 0 );
+                    }
+                }
+                psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
+                psEnc->state_Fxx[ n ].sCmn.inputBufIx = 0;
+                psEnc->state_Fxx[ n ].sCmn.nFramesEncoded++;
+            }
+            psEnc->prev_decode_only_middle = psEnc->sStereo.mid_only_flags[ psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded - 1 ];
+
+            /* Insert VAD and FEC flags at beginning of bitstream */
+            if( *nBytesOut > 0 && psEnc->state_Fxx[ 0 ].sCmn.nFramesEncoded == psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket) {
+                flags = 0;
+                for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+                    for( i = 0; i < psEnc->state_Fxx[ n ].sCmn.nFramesPerPacket; i++ ) {
+                        flags  = silk_LSHIFT( flags, 1 );
+                        flags |= psEnc->state_Fxx[ n ].sCmn.VAD_flags[ i ];
+                    }
+                    flags  = silk_LSHIFT( flags, 1 );
+                    flags |= psEnc->state_Fxx[ n ].sCmn.LBRR_flag;
+                }
+                if( !prefillFlag ) {
+                    ec_enc_patch_initial_bits( psRangeEnc, flags, ( psEnc->state_Fxx[ 0 ].sCmn.nFramesPerPacket + 1 ) * encControl->nChannelsInternal );
+                }
+
+                /* Return zero bytes if all channels DTXed */
+                if( psEnc->state_Fxx[ 0 ].sCmn.inDTX && ( encControl->nChannelsInternal == 1 || psEnc->state_Fxx[ 1 ].sCmn.inDTX ) ) {
+                    *nBytesOut = 0;
+                }
+
+                psEnc->nBitsExceeded += *nBytesOut * 8;
+                psEnc->nBitsExceeded -= silk_DIV32_16( silk_MUL( encControl->bitRate, encControl->payloadSize_ms ), 1000 );
+                psEnc->nBitsExceeded  = silk_LIMIT( psEnc->nBitsExceeded, 0, 10000 );
+
+                /* Update flag indicating if bandwidth switching is allowed */
+                speech_act_thr_for_switch_Q8 = silk_SMLAWB( SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ),
+                    SILK_FIX_CONST( ( 1 - SPEECH_ACTIVITY_DTX_THRES ) / MAX_BANDWIDTH_SWITCH_DELAY_MS, 16 + 8 ), psEnc->timeSinceSwitchAllowed_ms );
+                if( psEnc->state_Fxx[ 0 ].sCmn.speech_activity_Q8 < speech_act_thr_for_switch_Q8 ) {
+                    psEnc->allowBandwidthSwitch = 1;
+                    psEnc->timeSinceSwitchAllowed_ms = 0;
+                } else {
+                    psEnc->allowBandwidthSwitch = 0;
+                    psEnc->timeSinceSwitchAllowed_ms += encControl->payloadSize_ms;
+                }
+            }
+
+            if( nSamplesIn == 0 ) {
+                break;
+            }
+        } else {
+            break;
+        }
+        curr_block++;
+    }
+
+    psEnc->nPrevChannelsInternal = encControl->nChannelsInternal;
+
+    encControl->allowBandwidthSwitch = psEnc->allowBandwidthSwitch;
+    encControl->inWBmodeWithoutVariableLP = psEnc->state_Fxx[ 0 ].sCmn.fs_kHz == 16 && psEnc->state_Fxx[ 0 ].sCmn.sLP.mode == 0;
+    encControl->internalSampleRate = silk_SMULBB( psEnc->state_Fxx[ 0 ].sCmn.fs_kHz, 1000 );
+    encControl->stereoWidth_Q14 = encControl->toMono ? 0 : psEnc->sStereo.smth_width_Q14;
+    if( prefillFlag ) {
+        encControl->payloadSize_ms = tmp_payloadSize_ms;
+        encControl->complexity = tmp_complexity;
+        for( n = 0; n < encControl->nChannelsInternal; n++ ) {
+            psEnc->state_Fxx[ n ].sCmn.controlled_since_last_payload = 0;
+            psEnc->state_Fxx[ n ].sCmn.prefillFlag = 0;
+        }
+    }
+
+    encControl->signalType = psEnc->state_Fxx[0].sCmn.indices.signalType;
+    encControl->offset = silk_Quantization_Offsets_Q10
+                         [ psEnc->state_Fxx[0].sCmn.indices.signalType >> 1 ]
+                         [ psEnc->state_Fxx[0].sCmn.indices.quantOffsetType ];
+    RESTORE_STACK;
+    return ret;
+}
+
diff --git a/opus/silk/encode_indices.c b/opus/silk/encode_indices.c
new file mode 100644 (file)
index 0000000..666c8c0
--- /dev/null
@@ -0,0 +1,181 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Encode side-information parameters to payload */
+void silk_encode_indices(
+    silk_encoder_state          *psEncC,                        /* I/O  Encoder state                               */
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int                    FrameIndex,                     /* I    Frame number                                */
+    opus_int                    encode_LBRR,                    /* I    Flag indicating LBRR data is being encoded  */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+)
+{
+    opus_int   i, k, typeOffset;
+    opus_int   encode_absolute_lagIndex, delta_lagIndex;
+    opus_int16 ec_ix[ MAX_LPC_ORDER ];
+    opus_uint8 pred_Q8[ MAX_LPC_ORDER ];
+    const SideInfoIndices *psIndices;
+
+    if( encode_LBRR ) {
+         psIndices = &psEncC->indices_LBRR[ FrameIndex ];
+    } else {
+         psIndices = &psEncC->indices;
+    }
+
+    /*******************************************/
+    /* Encode signal type and quantizer offset */
+    /*******************************************/
+    typeOffset = 2 * psIndices->signalType + psIndices->quantOffsetType;
+    silk_assert( typeOffset >= 0 && typeOffset < 6 );
+    silk_assert( encode_LBRR == 0 || typeOffset >= 2 );
+    if( encode_LBRR || typeOffset >= 2 ) {
+        ec_enc_icdf( psRangeEnc, typeOffset - 2, silk_type_offset_VAD_iCDF, 8 );
+    } else {
+        ec_enc_icdf( psRangeEnc, typeOffset, silk_type_offset_no_VAD_iCDF, 8 );
+    }
+
+    /****************/
+    /* Encode gains */
+    /****************/
+    /* first subframe */
+    if( condCoding == CODE_CONDITIONALLY ) {
+        /* conditional coding */
+        silk_assert( psIndices->GainsIndices[ 0 ] >= 0 && psIndices->GainsIndices[ 0 ] < MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 );
+        ec_enc_icdf( psRangeEnc, psIndices->GainsIndices[ 0 ], silk_delta_gain_iCDF, 8 );
+    } else {
+        /* independent coding, in two stages: MSB bits followed by 3 LSBs */
+        silk_assert( psIndices->GainsIndices[ 0 ] >= 0 && psIndices->GainsIndices[ 0 ] < N_LEVELS_QGAIN );
+        ec_enc_icdf( psRangeEnc, silk_RSHIFT( psIndices->GainsIndices[ 0 ], 3 ), silk_gain_iCDF[ psIndices->signalType ], 8 );
+        ec_enc_icdf( psRangeEnc, psIndices->GainsIndices[ 0 ] & 7, silk_uniform8_iCDF, 8 );
+    }
+
+    /* remaining subframes */
+    for( i = 1; i < psEncC->nb_subfr; i++ ) {
+        silk_assert( psIndices->GainsIndices[ i ] >= 0 && psIndices->GainsIndices[ i ] < MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 );
+        ec_enc_icdf( psRangeEnc, psIndices->GainsIndices[ i ], silk_delta_gain_iCDF, 8 );
+    }
+
+    /****************/
+    /* Encode NLSFs */
+    /****************/
+    ec_enc_icdf( psRangeEnc, psIndices->NLSFIndices[ 0 ], &psEncC->psNLSF_CB->CB1_iCDF[ ( psIndices->signalType >> 1 ) * psEncC->psNLSF_CB->nVectors ], 8 );
+    silk_NLSF_unpack( ec_ix, pred_Q8, psEncC->psNLSF_CB, psIndices->NLSFIndices[ 0 ] );
+    silk_assert( psEncC->psNLSF_CB->order == psEncC->predictLPCOrder );
+    for( i = 0; i < psEncC->psNLSF_CB->order; i++ ) {
+        if( psIndices->NLSFIndices[ i+1 ] >= NLSF_QUANT_MAX_AMPLITUDE ) {
+            ec_enc_icdf( psRangeEnc, 2 * NLSF_QUANT_MAX_AMPLITUDE, &psEncC->psNLSF_CB->ec_iCDF[ ec_ix[ i ] ], 8 );
+            ec_enc_icdf( psRangeEnc, psIndices->NLSFIndices[ i+1 ] - NLSF_QUANT_MAX_AMPLITUDE, silk_NLSF_EXT_iCDF, 8 );
+        } else if( psIndices->NLSFIndices[ i+1 ] <= -NLSF_QUANT_MAX_AMPLITUDE ) {
+            ec_enc_icdf( psRangeEnc, 0, &psEncC->psNLSF_CB->ec_iCDF[ ec_ix[ i ] ], 8 );
+            ec_enc_icdf( psRangeEnc, -psIndices->NLSFIndices[ i+1 ] - NLSF_QUANT_MAX_AMPLITUDE, silk_NLSF_EXT_iCDF, 8 );
+        } else {
+            ec_enc_icdf( psRangeEnc, psIndices->NLSFIndices[ i+1 ] + NLSF_QUANT_MAX_AMPLITUDE, &psEncC->psNLSF_CB->ec_iCDF[ ec_ix[ i ] ], 8 );
+        }
+    }
+
+    /* Encode NLSF interpolation factor */
+    if( psEncC->nb_subfr == MAX_NB_SUBFR ) {
+        silk_assert( psIndices->NLSFInterpCoef_Q2 >= 0 && psIndices->NLSFInterpCoef_Q2 < 5 );
+        ec_enc_icdf( psRangeEnc, psIndices->NLSFInterpCoef_Q2, silk_NLSF_interpolation_factor_iCDF, 8 );
+    }
+
+    if( psIndices->signalType == TYPE_VOICED )
+    {
+        /*********************/
+        /* Encode pitch lags */
+        /*********************/
+        /* lag index */
+        encode_absolute_lagIndex = 1;
+        if( condCoding == CODE_CONDITIONALLY && psEncC->ec_prevSignalType == TYPE_VOICED ) {
+            /* Delta Encoding */
+            delta_lagIndex = psIndices->lagIndex - psEncC->ec_prevLagIndex;
+            if( delta_lagIndex < -8 || delta_lagIndex > 11 ) {
+                delta_lagIndex = 0;
+            } else {
+                delta_lagIndex = delta_lagIndex + 9;
+                encode_absolute_lagIndex = 0; /* Only use delta */
+            }
+            silk_assert( delta_lagIndex >= 0 && delta_lagIndex < 21 );
+            ec_enc_icdf( psRangeEnc, delta_lagIndex, silk_pitch_delta_iCDF, 8 );
+        }
+        if( encode_absolute_lagIndex ) {
+            /* Absolute encoding */
+            opus_int32 pitch_high_bits, pitch_low_bits;
+            pitch_high_bits = silk_DIV32_16( psIndices->lagIndex, silk_RSHIFT( psEncC->fs_kHz, 1 ) );
+            pitch_low_bits = psIndices->lagIndex - silk_SMULBB( pitch_high_bits, silk_RSHIFT( psEncC->fs_kHz, 1 ) );
+            silk_assert( pitch_low_bits < psEncC->fs_kHz / 2 );
+            silk_assert( pitch_high_bits < 32 );
+            ec_enc_icdf( psRangeEnc, pitch_high_bits, silk_pitch_lag_iCDF, 8 );
+            ec_enc_icdf( psRangeEnc, pitch_low_bits, psEncC->pitch_lag_low_bits_iCDF, 8 );
+        }
+        psEncC->ec_prevLagIndex = psIndices->lagIndex;
+
+        /* Countour index */
+        silk_assert(   psIndices->contourIndex  >= 0 );
+        silk_assert( ( psIndices->contourIndex < 34 && psEncC->fs_kHz  > 8 && psEncC->nb_subfr == 4 ) ||
+                    ( psIndices->contourIndex < 11 && psEncC->fs_kHz == 8 && psEncC->nb_subfr == 4 ) ||
+                    ( psIndices->contourIndex < 12 && psEncC->fs_kHz  > 8 && psEncC->nb_subfr == 2 ) ||
+                    ( psIndices->contourIndex <  3 && psEncC->fs_kHz == 8 && psEncC->nb_subfr == 2 ) );
+        ec_enc_icdf( psRangeEnc, psIndices->contourIndex, psEncC->pitch_contour_iCDF, 8 );
+
+        /********************/
+        /* Encode LTP gains */
+        /********************/
+        /* PERIndex value */
+        silk_assert( psIndices->PERIndex >= 0 && psIndices->PERIndex < 3 );
+        ec_enc_icdf( psRangeEnc, psIndices->PERIndex, silk_LTP_per_index_iCDF, 8 );
+
+        /* Codebook Indices */
+        for( k = 0; k < psEncC->nb_subfr; k++ ) {
+            silk_assert( psIndices->LTPIndex[ k ] >= 0 && psIndices->LTPIndex[ k ] < ( 8 << psIndices->PERIndex ) );
+            ec_enc_icdf( psRangeEnc, psIndices->LTPIndex[ k ], silk_LTP_gain_iCDF_ptrs[ psIndices->PERIndex ], 8 );
+        }
+
+        /**********************/
+        /* Encode LTP scaling */
+        /**********************/
+        if( condCoding == CODE_INDEPENDENTLY ) {
+            silk_assert( psIndices->LTP_scaleIndex >= 0 && psIndices->LTP_scaleIndex < 3 );
+            ec_enc_icdf( psRangeEnc, psIndices->LTP_scaleIndex, silk_LTPscale_iCDF, 8 );
+        }
+        silk_assert( !condCoding || psIndices->LTP_scaleIndex == 0 );
+    }
+
+    psEncC->ec_prevSignalType = psIndices->signalType;
+
+    /***************/
+    /* Encode seed */
+    /***************/
+    silk_assert( psIndices->Seed >= 0 && psIndices->Seed < 4 );
+    ec_enc_icdf( psRangeEnc, psIndices->Seed, silk_uniform4_iCDF, 8 );
+}
diff --git a/opus/silk/encode_pulses.c b/opus/silk/encode_pulses.c
new file mode 100644 (file)
index 0000000..ab00264
--- /dev/null
@@ -0,0 +1,206 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/*********************************************/
+/* Encode quantization indices of excitation */
+/*********************************************/
+
+static OPUS_INLINE opus_int combine_and_check(    /* return ok                           */
+    opus_int         *pulses_comb,           /* O                                   */
+    const opus_int   *pulses_in,             /* I                                   */
+    opus_int         max_pulses,             /* I    max value for sum of pulses    */
+    opus_int         len                     /* I    number of output values        */
+)
+{
+    opus_int k, sum;
+
+    for( k = 0; k < len; k++ ) {
+        sum = pulses_in[ 2 * k ] + pulses_in[ 2 * k + 1 ];
+        if( sum > max_pulses ) {
+            return 1;
+        }
+        pulses_comb[ k ] = sum;
+    }
+
+    return 0;
+}
+
+/* Encode quantization indices of excitation */
+void silk_encode_pulses(
+    ec_enc                      *psRangeEnc,                    /* I/O  compressor data structure                   */
+    const opus_int              signalType,                     /* I    Signal type                                 */
+    const opus_int              quantOffsetType,                /* I    quantOffsetType                             */
+    opus_int8                   pulses[],                       /* I    quantization indices                        */
+    const opus_int              frame_length                    /* I    Frame length                                */
+)
+{
+    opus_int   i, k, j, iter, bit, nLS, scale_down, RateLevelIndex = 0;
+    opus_int32 abs_q, minSumBits_Q5, sumBits_Q5;
+    VARDECL( opus_int, abs_pulses );
+    VARDECL( opus_int, sum_pulses );
+    VARDECL( opus_int, nRshifts );
+    opus_int   pulses_comb[ 8 ];
+    opus_int   *abs_pulses_ptr;
+    const opus_int8 *pulses_ptr;
+    const opus_uint8 *cdf_ptr;
+    const opus_uint8 *nBits_ptr;
+    SAVE_STACK;
+
+    silk_memset( pulses_comb, 0, 8 * sizeof( opus_int ) ); /* Fixing Valgrind reported problem*/
+
+    /****************************/
+    /* Prepare for shell coding */
+    /****************************/
+    /* Calculate number of shell blocks */
+    silk_assert( 1 << LOG2_SHELL_CODEC_FRAME_LENGTH == SHELL_CODEC_FRAME_LENGTH );
+    iter = silk_RSHIFT( frame_length, LOG2_SHELL_CODEC_FRAME_LENGTH );
+    if( iter * SHELL_CODEC_FRAME_LENGTH < frame_length ) {
+        silk_assert( frame_length == 12 * 10 ); /* Make sure only happens for 10 ms @ 12 kHz */
+        iter++;
+        silk_memset( &pulses[ frame_length ], 0, SHELL_CODEC_FRAME_LENGTH * sizeof(opus_int8));
+    }
+
+    /* Take the absolute value of the pulses */
+    ALLOC( abs_pulses, iter * SHELL_CODEC_FRAME_LENGTH, opus_int );
+    silk_assert( !( SHELL_CODEC_FRAME_LENGTH & 3 ) );
+    for( i = 0; i < iter * SHELL_CODEC_FRAME_LENGTH; i+=4 ) {
+        abs_pulses[i+0] = ( opus_int )silk_abs( pulses[ i + 0 ] );
+        abs_pulses[i+1] = ( opus_int )silk_abs( pulses[ i + 1 ] );
+        abs_pulses[i+2] = ( opus_int )silk_abs( pulses[ i + 2 ] );
+        abs_pulses[i+3] = ( opus_int )silk_abs( pulses[ i + 3 ] );
+    }
+
+    /* Calc sum pulses per shell code frame */
+    ALLOC( sum_pulses, iter, opus_int );
+    ALLOC( nRshifts, iter, opus_int );
+    abs_pulses_ptr = abs_pulses;
+    for( i = 0; i < iter; i++ ) {
+        nRshifts[ i ] = 0;
+
+        while( 1 ) {
+            /* 1+1 -> 2 */
+            scale_down = combine_and_check( pulses_comb, abs_pulses_ptr, silk_max_pulses_table[ 0 ], 8 );
+            /* 2+2 -> 4 */
+            scale_down += combine_and_check( pulses_comb, pulses_comb, silk_max_pulses_table[ 1 ], 4 );
+            /* 4+4 -> 8 */
+            scale_down += combine_and_check( pulses_comb, pulses_comb, silk_max_pulses_table[ 2 ], 2 );
+            /* 8+8 -> 16 */
+            scale_down += combine_and_check( &sum_pulses[ i ], pulses_comb, silk_max_pulses_table[ 3 ], 1 );
+
+            if( scale_down ) {
+                /* We need to downscale the quantization signal */
+                nRshifts[ i ]++;
+                for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
+                    abs_pulses_ptr[ k ] = silk_RSHIFT( abs_pulses_ptr[ k ], 1 );
+                }
+            } else {
+                /* Jump out of while(1) loop and go to next shell coding frame */
+                break;
+            }
+        }
+        abs_pulses_ptr += SHELL_CODEC_FRAME_LENGTH;
+    }
+
+    /**************/
+    /* Rate level */
+    /**************/
+    /* find rate level that leads to fewest bits for coding of pulses per block info */
+    minSumBits_Q5 = silk_int32_MAX;
+    for( k = 0; k < N_RATE_LEVELS - 1; k++ ) {
+        nBits_ptr  = silk_pulses_per_block_BITS_Q5[ k ];
+        sumBits_Q5 = silk_rate_levels_BITS_Q5[ signalType >> 1 ][ k ];
+        for( i = 0; i < iter; i++ ) {
+            if( nRshifts[ i ] > 0 ) {
+                sumBits_Q5 += nBits_ptr[ SILK_MAX_PULSES + 1 ];
+            } else {
+                sumBits_Q5 += nBits_ptr[ sum_pulses[ i ] ];
+            }
+        }
+        if( sumBits_Q5 < minSumBits_Q5 ) {
+            minSumBits_Q5 = sumBits_Q5;
+            RateLevelIndex = k;
+        }
+    }
+    ec_enc_icdf( psRangeEnc, RateLevelIndex, silk_rate_levels_iCDF[ signalType >> 1 ], 8 );
+
+    /***************************************************/
+    /* Sum-Weighted-Pulses Encoding                    */
+    /***************************************************/
+    cdf_ptr = silk_pulses_per_block_iCDF[ RateLevelIndex ];
+    for( i = 0; i < iter; i++ ) {
+        if( nRshifts[ i ] == 0 ) {
+            ec_enc_icdf( psRangeEnc, sum_pulses[ i ], cdf_ptr, 8 );
+        } else {
+            ec_enc_icdf( psRangeEnc, SILK_MAX_PULSES + 1, cdf_ptr, 8 );
+            for( k = 0; k < nRshifts[ i ] - 1; k++ ) {
+                ec_enc_icdf( psRangeEnc, SILK_MAX_PULSES + 1, silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1 ], 8 );
+            }
+            ec_enc_icdf( psRangeEnc, sum_pulses[ i ], silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1 ], 8 );
+        }
+    }
+
+    /******************/
+    /* Shell Encoding */
+    /******************/
+    for( i = 0; i < iter; i++ ) {
+        if( sum_pulses[ i ] > 0 ) {
+            silk_shell_encoder( psRangeEnc, &abs_pulses[ i * SHELL_CODEC_FRAME_LENGTH ] );
+        }
+    }
+
+    /****************/
+    /* LSB Encoding */
+    /****************/
+    for( i = 0; i < iter; i++ ) {
+        if( nRshifts[ i ] > 0 ) {
+            pulses_ptr = &pulses[ i * SHELL_CODEC_FRAME_LENGTH ];
+            nLS = nRshifts[ i ] - 1;
+            for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
+                abs_q = (opus_int8)silk_abs( pulses_ptr[ k ] );
+                for( j = nLS; j > 0; j-- ) {
+                    bit = silk_RSHIFT( abs_q, j ) & 1;
+                    ec_enc_icdf( psRangeEnc, bit, silk_lsb_iCDF, 8 );
+                }
+                bit = abs_q & 1;
+                ec_enc_icdf( psRangeEnc, bit, silk_lsb_iCDF, 8 );
+            }
+        }
+    }
+
+    /****************/
+    /* Encode signs */
+    /****************/
+    silk_encode_signs( psRangeEnc, pulses, frame_length, signalType, quantOffsetType, sum_pulses );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/errors.h b/opus/silk/errors.h
new file mode 100644 (file)
index 0000000..4507080
--- /dev/null
@@ -0,0 +1,98 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_ERRORS_H
+#define SILK_ERRORS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/******************/
+/* Error messages */
+/******************/
+#define SILK_NO_ERROR                               0
+
+/**************************/
+/* Encoder error messages */
+/**************************/
+
+/* Input length is not a multiple of 10 ms, or length is longer than the packet length */
+#define SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES        -101
+
+/* Sampling frequency not 8000, 12000 or 16000 Hertz */
+#define SILK_ENC_FS_NOT_SUPPORTED                   -102
+
+/* Packet size not 10, 20, 40, or 60 ms */
+#define SILK_ENC_PACKET_SIZE_NOT_SUPPORTED          -103
+
+/* Allocated payload buffer too short */
+#define SILK_ENC_PAYLOAD_BUF_TOO_SHORT              -104
+
+/* Loss rate not between 0 and 100 percent */
+#define SILK_ENC_INVALID_LOSS_RATE                  -105
+
+/* Complexity setting not valid, use 0...10 */
+#define SILK_ENC_INVALID_COMPLEXITY_SETTING         -106
+
+/* Inband FEC setting not valid, use 0 or 1 */
+#define SILK_ENC_INVALID_INBAND_FEC_SETTING         -107
+
+/* DTX setting not valid, use 0 or 1 */
+#define SILK_ENC_INVALID_DTX_SETTING                -108
+
+/* CBR setting not valid, use 0 or 1 */
+#define SILK_ENC_INVALID_CBR_SETTING                -109
+
+/* Internal encoder error */
+#define SILK_ENC_INTERNAL_ERROR                     -110
+
+/* Internal encoder error */
+#define SILK_ENC_INVALID_NUMBER_OF_CHANNELS_ERROR   -111
+
+/**************************/
+/* Decoder error messages */
+/**************************/
+
+/* Output sampling frequency lower than internal decoded sampling frequency */
+#define SILK_DEC_INVALID_SAMPLING_FREQUENCY         -200
+
+/* Payload size exceeded the maximum allowed 1024 bytes */
+#define SILK_DEC_PAYLOAD_TOO_LARGE                  -201
+
+/* Payload has bit errors */
+#define SILK_DEC_PAYLOAD_ERROR                      -202
+
+/* Payload has bit errors */
+#define SILK_DEC_INVALID_FRAME_SIZE                 -203
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/fixed/LTP_analysis_filter_FIX.c b/opus/silk/fixed/LTP_analysis_filter_FIX.c
new file mode 100644 (file)
index 0000000..5574e70
--- /dev/null
@@ -0,0 +1,90 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+void silk_LTP_analysis_filter_FIX(
+    opus_int16                      *LTP_res,                               /* O    LTP residual signal of length MAX_NB_SUBFR * ( pre_length + subfr_length )  */
+    const opus_int16                *x,                                     /* I    Pointer to input signal with at least max( pitchL ) preceding samples       */
+    const opus_int16                LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],/* I    LTP_ORDER LTP coefficients for each MAX_NB_SUBFR subframe                   */
+    const opus_int                  pitchL[ MAX_NB_SUBFR ],                 /* I    Pitch lag, one for each subframe                                            */
+    const opus_int32                invGains_Q16[ MAX_NB_SUBFR ],           /* I    Inverse quantization gains, one for each subframe                           */
+    const opus_int                  subfr_length,                           /* I    Length of each subframe                                                     */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    const opus_int                  pre_length                              /* I    Length of the preceding samples starting at &x[0] for each subframe         */
+)
+{
+    const opus_int16 *x_ptr, *x_lag_ptr;
+    opus_int16   Btmp_Q14[ LTP_ORDER ];
+    opus_int16   *LTP_res_ptr;
+    opus_int     k, i;
+    opus_int32   LTP_est;
+
+    x_ptr = x;
+    LTP_res_ptr = LTP_res;
+    for( k = 0; k < nb_subfr; k++ ) {
+
+        x_lag_ptr = x_ptr - pitchL[ k ];
+
+        Btmp_Q14[ 0 ] = LTPCoef_Q14[ k * LTP_ORDER ];
+        Btmp_Q14[ 1 ] = LTPCoef_Q14[ k * LTP_ORDER + 1 ];
+        Btmp_Q14[ 2 ] = LTPCoef_Q14[ k * LTP_ORDER + 2 ];
+        Btmp_Q14[ 3 ] = LTPCoef_Q14[ k * LTP_ORDER + 3 ];
+        Btmp_Q14[ 4 ] = LTPCoef_Q14[ k * LTP_ORDER + 4 ];
+
+        /* LTP analysis FIR filter */
+        for( i = 0; i < subfr_length + pre_length; i++ ) {
+            LTP_res_ptr[ i ] = x_ptr[ i ];
+
+            /* Long-term prediction */
+            LTP_est = silk_SMULBB( x_lag_ptr[ LTP_ORDER / 2 ], Btmp_Q14[ 0 ] );
+            LTP_est = silk_SMLABB_ovflw( LTP_est, x_lag_ptr[ 1 ], Btmp_Q14[ 1 ] );
+            LTP_est = silk_SMLABB_ovflw( LTP_est, x_lag_ptr[ 0 ], Btmp_Q14[ 2 ] );
+            LTP_est = silk_SMLABB_ovflw( LTP_est, x_lag_ptr[ -1 ], Btmp_Q14[ 3 ] );
+            LTP_est = silk_SMLABB_ovflw( LTP_est, x_lag_ptr[ -2 ], Btmp_Q14[ 4 ] );
+
+            LTP_est = silk_RSHIFT_ROUND( LTP_est, 14 ); /* round and -> Q0*/
+
+            /* Subtract long-term prediction */
+            LTP_res_ptr[ i ] = (opus_int16)silk_SAT16( (opus_int32)x_ptr[ i ] - LTP_est );
+
+            /* Scale residual */
+            LTP_res_ptr[ i ] = silk_SMULWB( invGains_Q16[ k ], LTP_res_ptr[ i ] );
+
+            x_lag_ptr++;
+        }
+
+        /* Update pointers */
+        LTP_res_ptr += subfr_length + pre_length;
+        x_ptr       += subfr_length;
+    }
+}
+
diff --git a/opus/silk/fixed/LTP_scale_ctrl_FIX.c b/opus/silk/fixed/LTP_scale_ctrl_FIX.c
new file mode 100644 (file)
index 0000000..3dcedef
--- /dev/null
@@ -0,0 +1,53 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+/* Calculation of LTP state scaling */
+void silk_LTP_scale_ctrl_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+)
+{
+    opus_int round_loss;
+
+    if( condCoding == CODE_INDEPENDENTLY ) {
+        /* Only scale if first frame in packet */
+        round_loss = psEnc->sCmn.PacketLoss_perc + psEnc->sCmn.nFramesPerPacket;
+        psEnc->sCmn.indices.LTP_scaleIndex = (opus_int8)silk_LIMIT(
+            silk_SMULWB( silk_SMULBB( round_loss, psEncCtrl->LTPredCodGain_Q7 ), SILK_FIX_CONST( 0.1, 9 ) ), 0, 2 );
+    } else {
+        /* Default is minimum scaling */
+        psEnc->sCmn.indices.LTP_scaleIndex = 0;
+    }
+    psEncCtrl->LTP_scale_Q14 = silk_LTPScales_table_Q14[ psEnc->sCmn.indices.LTP_scaleIndex ];
+}
diff --git a/opus/silk/fixed/apply_sine_window_FIX.c b/opus/silk/fixed/apply_sine_window_FIX.c
new file mode 100644 (file)
index 0000000..4502b71
--- /dev/null
@@ -0,0 +1,101 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Apply sine window to signal vector.                                      */
+/* Window types:                                                            */
+/*    1 -> sine window from 0 to pi/2                                       */
+/*    2 -> sine window from pi/2 to pi                                      */
+/* Every other sample is linearly interpolated, for speed.                  */
+/* Window length must be between 16 and 120 (incl) and a multiple of 4.     */
+
+/* Matlab code for table:
+   for k=16:9*4:16+2*9*4, fprintf(' %7.d,', -round(65536*pi ./ (k:4:k+8*4))); fprintf('\n'); end
+*/
+static const opus_int16 freq_table_Q16[ 27 ] = {
+   12111,    9804,    8235,    7100,    6239,    5565,    5022,    4575,    4202,
+    3885,    3612,    3375,    3167,    2984,    2820,    2674,    2542,    2422,
+    2313,    2214,    2123,    2038,    1961,    1889,    1822,    1760,    1702,
+};
+
+void silk_apply_sine_window(
+    opus_int16                  px_win[],           /* O    Pointer to windowed signal                                  */
+    const opus_int16            px[],               /* I    Pointer to input signal                                     */
+    const opus_int              win_type,           /* I    Selects a window type                                       */
+    const opus_int              length              /* I    Window length, multiple of 4                                */
+)
+{
+    opus_int   k, f_Q16, c_Q16;
+    opus_int32 S0_Q16, S1_Q16;
+
+    silk_assert( win_type == 1 || win_type == 2 );
+
+    /* Length must be in a range from 16 to 120 and a multiple of 4 */
+    silk_assert( length >= 16 && length <= 120 );
+    silk_assert( ( length & 3 ) == 0 );
+
+    /* Frequency */
+    k = ( length >> 2 ) - 4;
+    silk_assert( k >= 0 && k <= 26 );
+    f_Q16 = (opus_int)freq_table_Q16[ k ];
+
+    /* Factor used for cosine approximation */
+    c_Q16 = silk_SMULWB( (opus_int32)f_Q16, -f_Q16 );
+    silk_assert( c_Q16 >= -32768 );
+
+    /* initialize state */
+    if( win_type == 1 ) {
+        /* start from 0 */
+        S0_Q16 = 0;
+        /* approximation of sin(f) */
+        S1_Q16 = f_Q16 + silk_RSHIFT( length, 3 );
+    } else {
+        /* start from 1 */
+        S0_Q16 = ( (opus_int32)1 << 16 );
+        /* approximation of cos(f) */
+        S1_Q16 = ( (opus_int32)1 << 16 ) + silk_RSHIFT( c_Q16, 1 ) + silk_RSHIFT( length, 4 );
+    }
+
+    /* Uses the recursive equation:   sin(n*f) = 2 * cos(f) * sin((n-1)*f) - sin((n-2)*f)    */
+    /* 4 samples at a time */
+    for( k = 0; k < length; k += 4 ) {
+        px_win[ k ]     = (opus_int16)silk_SMULWB( silk_RSHIFT( S0_Q16 + S1_Q16, 1 ), px[ k ] );
+        px_win[ k + 1 ] = (opus_int16)silk_SMULWB( S1_Q16, px[ k + 1] );
+        S0_Q16 = silk_SMULWB( S1_Q16, c_Q16 ) + silk_LSHIFT( S1_Q16, 1 ) - S0_Q16 + 1;
+        S0_Q16 = silk_min( S0_Q16, ( (opus_int32)1 << 16 ) );
+
+        px_win[ k + 2 ] = (opus_int16)silk_SMULWB( silk_RSHIFT( S0_Q16 + S1_Q16, 1 ), px[ k + 2] );
+        px_win[ k + 3 ] = (opus_int16)silk_SMULWB( S0_Q16, px[ k + 3 ] );
+        S1_Q16 = silk_SMULWB( S0_Q16, c_Q16 ) + silk_LSHIFT( S0_Q16, 1 ) - S1_Q16;
+        S1_Q16 = silk_min( S1_Q16, ( (opus_int32)1 << 16 ) );
+    }
+}
diff --git a/opus/silk/fixed/arm/warped_autocorrelation_FIX_arm.h b/opus/silk/fixed/arm/warped_autocorrelation_FIX_arm.h
new file mode 100644 (file)
index 0000000..1992e43
--- /dev/null
@@ -0,0 +1,68 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc.
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_WARPED_AUTOCORRELATION_FIX_ARM_H
+# define SILK_WARPED_AUTOCORRELATION_FIX_ARM_H
+
+# include "celt/arm/armcpu.h"
+
+# if defined(FIXED_POINT)
+
+#  if defined(OPUS_ARM_MAY_HAVE_NEON_INTR)
+void silk_warped_autocorrelation_FIX_neon(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order                                   /* I    Correlation order (even)                                                    */
+);
+
+#  if !defined(OPUS_HAVE_RTCD) && defined(OPUS_ARM_PRESUME_NEON)
+#   define OVERRIDE_silk_warped_autocorrelation_FIX (1)
+#   define silk_warped_autocorrelation_FIX(corr, scale, input, warping_Q16, length, order, arch) \
+    ((void)(arch), PRESUME_NEON(silk_warped_autocorrelation_FIX)(corr, scale, input, warping_Q16, length, order))
+#  endif
+#  endif
+
+#  if !defined(OVERRIDE_silk_warped_autocorrelation_FIX)
+/*Is run-time CPU detection enabled on this platform?*/
+#   if defined(OPUS_HAVE_RTCD) && (defined(OPUS_ARM_MAY_HAVE_NEON_INTR) && !defined(OPUS_ARM_PRESUME_NEON_INTR))
+extern void (*const SILK_WARPED_AUTOCORRELATION_FIX_IMPL[OPUS_ARCHMASK+1])(opus_int32*, opus_int*, const opus_int16*, const opus_int, const opus_int, const opus_int);
+#    define OVERRIDE_silk_warped_autocorrelation_FIX (1)
+#    define silk_warped_autocorrelation_FIX(corr, scale, input, warping_Q16, length, order, arch) \
+    ((*SILK_WARPED_AUTOCORRELATION_FIX_IMPL[(arch)&OPUS_ARCHMASK])(corr, scale, input, warping_Q16, length, order))
+#   elif defined(OPUS_ARM_PRESUME_NEON_INTR)
+#    define OVERRIDE_silk_warped_autocorrelation_FIX (1)
+#    define silk_warped_autocorrelation_FIX(corr, scale, input, warping_Q16, length, order, arch) \
+    ((void)(arch), silk_warped_autocorrelation_FIX_neon(corr, scale, input, warping_Q16, length, order))
+#   endif
+#  endif
+
+# endif /* end FIXED_POINT */
+
+#endif /* end SILK_WARPED_AUTOCORRELATION_FIX_ARM_H */
diff --git a/opus/silk/fixed/arm/warped_autocorrelation_FIX_neon_intr.c b/opus/silk/fixed/arm/warped_autocorrelation_FIX_neon_intr.c
new file mode 100644 (file)
index 0000000..00a70cb
--- /dev/null
@@ -0,0 +1,260 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc., 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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <arm_neon.h>
+#ifdef OPUS_CHECK_ASM
+# include <string.h>
+#endif
+#include "stack_alloc.h"
+#include "main_FIX.h"
+
+static OPUS_INLINE void calc_corr( const opus_int32 *const input_QS, opus_int64 *const corr_QC, const opus_int offset, const int32x4_t state_QS_s32x4 )
+{
+    int64x2_t corr_QC_s64x2[ 2 ], t_s64x2[ 2 ];
+    const int32x4_t input_QS_s32x4 = vld1q_s32( input_QS + offset );
+    corr_QC_s64x2[ 0 ] = vld1q_s64( corr_QC + offset + 0 );
+    corr_QC_s64x2[ 1 ] = vld1q_s64( corr_QC + offset + 2 );
+    t_s64x2[ 0 ] = vmull_s32( vget_low_s32( state_QS_s32x4 ), vget_low_s32( input_QS_s32x4 ) );
+    t_s64x2[ 1 ] = vmull_s32( vget_high_s32( state_QS_s32x4 ), vget_high_s32( input_QS_s32x4 ) );
+    corr_QC_s64x2[ 0 ] = vsraq_n_s64( corr_QC_s64x2[ 0 ], t_s64x2[ 0 ], 2 * QS - QC );
+    corr_QC_s64x2[ 1 ] = vsraq_n_s64( corr_QC_s64x2[ 1 ], t_s64x2[ 1 ], 2 * QS - QC );
+    vst1q_s64( corr_QC + offset + 0, corr_QC_s64x2[ 0 ] );
+    vst1q_s64( corr_QC + offset + 2, corr_QC_s64x2[ 1 ] );
+}
+
+static OPUS_INLINE int32x4_t calc_state( const int32x4_t state_QS0_s32x4, const int32x4_t state_QS0_1_s32x4, const int32x4_t state_QS1_1_s32x4, const int32x4_t warping_Q16_s32x4 )
+{
+    int32x4_t t_s32x4 = vsubq_s32( state_QS0_s32x4, state_QS0_1_s32x4 );
+    t_s32x4 = vqdmulhq_s32( t_s32x4, warping_Q16_s32x4 );
+    return vaddq_s32( state_QS1_1_s32x4, t_s32x4 );
+}
+
+void silk_warped_autocorrelation_FIX_neon(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order                                   /* I    Correlation order (even)                                                    */
+)
+{
+    if( ( MAX_SHAPE_LPC_ORDER > 24 ) || ( order < 6 ) ) {
+        silk_warped_autocorrelation_FIX_c( corr, scale, input, warping_Q16, length, order );
+    } else {
+        opus_int       n, i, lsh;
+        opus_int64     corr_QC[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 }; /* In reverse order */
+        opus_int64     corr_QC_orderT;
+        int64x2_t      lsh_s64x2;
+        const opus_int orderT = ( order + 3 ) & ~3;
+        opus_int64     *corr_QCT;
+        opus_int32     *input_QS;
+        VARDECL( opus_int32, input_QST );
+        VARDECL( opus_int32, state );
+        SAVE_STACK;
+
+        /* Order must be even */
+        silk_assert( ( order & 1 ) == 0 );
+        silk_assert( 2 * QS - QC >= 0 );
+
+        ALLOC( input_QST, length + 2 * MAX_SHAPE_LPC_ORDER, opus_int32 );
+
+        input_QS = input_QST;
+        /* input_QS has zero paddings in the beginning and end. */
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+
+        /* Loop over samples */
+        for( n = 0; n < length - 7; n += 8, input_QS += 8 ) {
+            const int16x8_t t0_s16x4 = vld1q_s16( input + n );
+            vst1q_s32( input_QS + 0, vshll_n_s16( vget_low_s16( t0_s16x4 ), QS ) );
+            vst1q_s32( input_QS + 4, vshll_n_s16( vget_high_s16( t0_s16x4 ), QS ) );
+        }
+        for( ; n < length; n++, input_QS++ ) {
+            input_QS[ 0 ] = silk_LSHIFT32( (opus_int32)input[ n ], QS );
+        }
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS += 4;
+        vst1q_s32( input_QS, vdupq_n_s32( 0 ) );
+        input_QS = input_QST + MAX_SHAPE_LPC_ORDER - orderT;
+
+        /* The following loop runs ( length + order ) times, with ( order ) extra epilogues.                  */
+        /* The zero paddings in input_QS guarantee corr_QC's correctness even with the extra epilogues.       */
+        /* The values of state_QS will be polluted by the extra epilogues, however they are temporary values. */
+
+        /* Keep the C code here to help understand the intrinsics optimization. */
+        /*
+        {
+            opus_int32 state_QS[ 2 ][ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
+            opus_int32 *state_QST[ 3 ];
+            state_QST[ 0 ] = state_QS[ 0 ];
+            state_QST[ 1 ] = state_QS[ 1 ];
+            for( n = 0; n < length + order; n++, input_QS++ ) {
+                state_QST[ 0 ][ orderT ] = input_QS[ orderT ];
+                for( i = 0; i < orderT; i++ ) {
+                    corr_QC[ i ] += silk_RSHIFT64( silk_SMULL( state_QST[ 0 ][ i ], input_QS[ i ] ), 2 * QS - QC );
+                    state_QST[ 1 ][ i ] = silk_SMLAWB( state_QST[ 1 ][ i + 1 ], state_QST[ 0 ][ i ] - state_QST[ 0 ][ i + 1 ], warping_Q16 );
+                }
+                state_QST[ 2 ] = state_QST[ 0 ];
+                state_QST[ 0 ] = state_QST[ 1 ];
+                state_QST[ 1 ] = state_QST[ 2 ];
+            }
+        }
+        */
+
+        {
+            const int32x4_t warping_Q16_s32x4 = vdupq_n_s32( warping_Q16 << 15 );
+            const opus_int32 *in = input_QS + orderT;
+            opus_int o = orderT;
+            int32x4_t state_QS_s32x4[ 3 ][ 2 ];
+
+            ALLOC( state, length + orderT, opus_int32 );
+            state_QS_s32x4[ 2 ][ 1 ] = vdupq_n_s32( 0 );
+
+            /* Calculate 8 taps of all inputs in each loop. */
+            do {
+                state_QS_s32x4[ 0 ][ 0 ] = state_QS_s32x4[ 0 ][ 1 ] =
+                state_QS_s32x4[ 1 ][ 0 ] = state_QS_s32x4[ 1 ][ 1 ] = vdupq_n_s32( 0 );
+                n = 0;
+                do {
+                    calc_corr( input_QS + n, corr_QC, o - 8, state_QS_s32x4[ 0 ][ 0 ] );
+                    calc_corr( input_QS + n, corr_QC, o - 4, state_QS_s32x4[ 0 ][ 1 ] );
+                    state_QS_s32x4[ 2 ][ 1 ] = vld1q_s32( in + n );
+                    vst1q_lane_s32( state + n, state_QS_s32x4[ 0 ][ 0 ], 0 );
+                    state_QS_s32x4[ 2 ][ 0 ] = vextq_s32( state_QS_s32x4[ 0 ][ 0 ], state_QS_s32x4[ 0 ][ 1 ], 1 );
+                    state_QS_s32x4[ 2 ][ 1 ] = vextq_s32( state_QS_s32x4[ 0 ][ 1 ], state_QS_s32x4[ 2 ][ 1 ], 1 );
+                    state_QS_s32x4[ 0 ][ 0 ] = calc_state( state_QS_s32x4[ 0 ][ 0 ], state_QS_s32x4[ 2 ][ 0 ], state_QS_s32x4[ 1 ][ 0 ], warping_Q16_s32x4 );
+                    state_QS_s32x4[ 0 ][ 1 ] = calc_state( state_QS_s32x4[ 0 ][ 1 ], state_QS_s32x4[ 2 ][ 1 ], state_QS_s32x4[ 1 ][ 1 ], warping_Q16_s32x4 );
+                    state_QS_s32x4[ 1 ][ 0 ] = state_QS_s32x4[ 2 ][ 0 ];
+                    state_QS_s32x4[ 1 ][ 1 ] = state_QS_s32x4[ 2 ][ 1 ];
+                } while( ++n < ( length + order ) );
+                in = state;
+                o -= 8;
+            } while( o > 4 );
+
+            if( o ) {
+                /* Calculate the last 4 taps of all inputs. */
+                opus_int32 *stateT = state;
+                silk_assert( o == 4 );
+                state_QS_s32x4[ 0 ][ 0 ] = state_QS_s32x4[ 1 ][ 0 ] = vdupq_n_s32( 0 );
+                n = length + order;
+                do {
+                    calc_corr( input_QS, corr_QC, 0, state_QS_s32x4[ 0 ][ 0 ] );
+                    state_QS_s32x4[ 2 ][ 0 ] = vld1q_s32( stateT );
+                    vst1q_lane_s32( stateT, state_QS_s32x4[ 0 ][ 0 ], 0 );
+                    state_QS_s32x4[ 2 ][ 0 ] = vextq_s32( state_QS_s32x4[ 0 ][ 0 ], state_QS_s32x4[ 2 ][ 0 ], 1 );
+                    state_QS_s32x4[ 0 ][ 0 ] = calc_state( state_QS_s32x4[ 0 ][ 0 ], state_QS_s32x4[ 2 ][ 0 ], state_QS_s32x4[ 1 ][ 0 ], warping_Q16_s32x4 );
+                    state_QS_s32x4[ 1 ][ 0 ] = state_QS_s32x4[ 2 ][ 0 ];
+                    input_QS++;
+                    stateT++;
+                } while( --n );
+            }
+        }
+
+        {
+            const opus_int16 *inputT = input;
+            int32x4_t t_s32x4;
+            int64x1_t t_s64x1;
+            int64x2_t t_s64x2 = vdupq_n_s64( 0 );
+            for( n = 0; n <= length - 8; n += 8 ) {
+                int16x8_t input_s16x8 = vld1q_s16( inputT );
+                t_s32x4 = vmull_s16( vget_low_s16( input_s16x8 ), vget_low_s16( input_s16x8 ) );
+                t_s32x4 = vmlal_s16( t_s32x4, vget_high_s16( input_s16x8 ), vget_high_s16( input_s16x8 ) );
+                t_s64x2 = vaddw_s32( t_s64x2, vget_low_s32( t_s32x4 ) );
+                t_s64x2 = vaddw_s32( t_s64x2, vget_high_s32( t_s32x4 ) );
+                inputT += 8;
+            }
+            t_s64x1 = vadd_s64( vget_low_s64( t_s64x2 ), vget_high_s64( t_s64x2 ) );
+            corr_QC_orderT = vget_lane_s64( t_s64x1, 0 );
+            for( ; n < length; n++ ) {
+                corr_QC_orderT += silk_SMULL( input[ n ], input[ n ] );
+            }
+            corr_QC_orderT = silk_LSHIFT64( corr_QC_orderT, QC );
+            corr_QC[ orderT ] = corr_QC_orderT;
+        }
+
+        corr_QCT = corr_QC + orderT - order;
+        lsh = silk_CLZ64( corr_QC_orderT ) - 35;
+        lsh = silk_LIMIT( lsh, -12 - QC, 30 - QC );
+        *scale = -( QC + lsh );
+        silk_assert( *scale >= -30 && *scale <= 12 );
+        lsh_s64x2 = vdupq_n_s64( lsh );
+        for( i = 0; i <= order - 3; i += 4 ) {
+            int32x4_t corr_s32x4;
+            int64x2_t corr_QC0_s64x2, corr_QC1_s64x2;
+            corr_QC0_s64x2 = vld1q_s64( corr_QCT + i );
+            corr_QC1_s64x2 = vld1q_s64( corr_QCT + i + 2 );
+            corr_QC0_s64x2 = vshlq_s64( corr_QC0_s64x2, lsh_s64x2 );
+            corr_QC1_s64x2 = vshlq_s64( corr_QC1_s64x2, lsh_s64x2 );
+            corr_s32x4     = vcombine_s32( vmovn_s64( corr_QC1_s64x2 ), vmovn_s64( corr_QC0_s64x2 ) );
+            corr_s32x4     = vrev64q_s32( corr_s32x4 );
+            vst1q_s32( corr + order - i - 3, corr_s32x4 );
+        }
+        if( lsh >= 0 ) {
+            for( ; i < order + 1; i++ ) {
+                corr[ order - i ] = (opus_int32)silk_CHECK_FIT32( silk_LSHIFT64( corr_QCT[ i ], lsh ) );
+            }
+        } else {
+            for( ; i < order + 1; i++ ) {
+                corr[ order - i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( corr_QCT[ i ], -lsh ) );
+            }
+        }
+        silk_assert( corr_QCT[ order ] >= 0 ); /* If breaking, decrease QC*/
+        RESTORE_STACK;
+    }
+
+#ifdef OPUS_CHECK_ASM
+    {
+        opus_int32 corr_c[ MAX_SHAPE_LPC_ORDER + 1 ];
+        opus_int   scale_c;
+        silk_warped_autocorrelation_FIX_c( corr_c, &scale_c, input, warping_Q16, length, order );
+        silk_assert( !memcmp( corr_c, corr, sizeof( corr_c[ 0 ] ) * ( order + 1 ) ) );
+        silk_assert( scale_c == *scale );
+    }
+#endif
+}
diff --git a/opus/silk/fixed/autocorr_FIX.c b/opus/silk/fixed/autocorr_FIX.c
new file mode 100644 (file)
index 0000000..de95c98
--- /dev/null
@@ -0,0 +1,48 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "celt_lpc.h"
+
+/* Compute autocorrelation */
+void silk_autocorr(
+    opus_int32                  *results,           /* O    Result (length correlationCount)                            */
+    opus_int                    *scale,             /* O    Scaling of the correlation vector                           */
+    const opus_int16            *inputData,         /* I    Input data to correlate                                     */
+    const opus_int              inputDataSize,      /* I    Length of input                                             */
+    const opus_int              correlationCount,   /* I    Number of correlation taps to compute                       */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    opus_int   corrCount;
+    corrCount = silk_min_int( inputDataSize, correlationCount );
+    *scale = _celt_autocorr(inputData, results, NULL, 0, corrCount-1, inputDataSize, arch);
+}
diff --git a/opus/silk/fixed/burg_modified_FIX.c b/opus/silk/fixed/burg_modified_FIX.c
new file mode 100644 (file)
index 0000000..80edbdf
--- /dev/null
@@ -0,0 +1,280 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "define.h"
+#include "tuning_parameters.h"
+#include "pitch.h"
+
+#define MAX_FRAME_SIZE              384             /* subfr_length * nb_subfr = ( 0.005 * 16000 + 16 ) * 4 = 384 */
+
+#define QA                          25
+#define N_BITS_HEAD_ROOM            3
+#define MIN_RSHIFTS                 -16
+#define MAX_RSHIFTS                 (32 - QA)
+
+/* Compute reflection coefficients from input signal */
+void silk_burg_modified_c(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    opus_int         k, n, s, lz, rshifts, reached_max_gain;
+    opus_int32       C0, num, nrg, rc_Q31, invGain_Q30, Atmp_QA, Atmp1, tmp1, tmp2, x1, x2;
+    const opus_int16 *x_ptr;
+    opus_int32       C_first_row[ SILK_MAX_ORDER_LPC ];
+    opus_int32       C_last_row[  SILK_MAX_ORDER_LPC ];
+    opus_int32       Af_QA[       SILK_MAX_ORDER_LPC ];
+    opus_int32       CAf[ SILK_MAX_ORDER_LPC + 1 ];
+    opus_int32       CAb[ SILK_MAX_ORDER_LPC + 1 ];
+    opus_int32       xcorr[ SILK_MAX_ORDER_LPC ];
+    opus_int64       C0_64;
+
+    silk_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE );
+
+    /* Compute autocorrelations, added over subframes */
+    C0_64 = silk_inner_prod16_aligned_64( x, x, subfr_length*nb_subfr, arch );
+    lz = silk_CLZ64(C0_64);
+    rshifts = 32 + 1 + N_BITS_HEAD_ROOM - lz;
+    if (rshifts > MAX_RSHIFTS) rshifts = MAX_RSHIFTS;
+    if (rshifts < MIN_RSHIFTS) rshifts = MIN_RSHIFTS;
+
+    if (rshifts > 0) {
+        C0 = (opus_int32)silk_RSHIFT64(C0_64, rshifts );
+    } else {
+        C0 = silk_LSHIFT32((opus_int32)C0_64, -rshifts );
+    }
+
+    CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1;                                /* Q(-rshifts) */
+    silk_memset( C_first_row, 0, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) );
+    if( rshifts > 0 ) {
+        for( s = 0; s < nb_subfr; s++ ) {
+            x_ptr = x + s * subfr_length;
+            for( n = 1; n < D + 1; n++ ) {
+                C_first_row[ n - 1 ] += (opus_int32)silk_RSHIFT64(
+                    silk_inner_prod16_aligned_64( x_ptr, x_ptr + n, subfr_length - n, arch ), rshifts );
+            }
+        }
+    } else {
+        for( s = 0; s < nb_subfr; s++ ) {
+            int i;
+            opus_int32 d;
+            x_ptr = x + s * subfr_length;
+            celt_pitch_xcorr(x_ptr, x_ptr + 1, xcorr, subfr_length - D, D, arch );
+            for( n = 1; n < D + 1; n++ ) {
+               for ( i = n + subfr_length - D, d = 0; i < subfr_length; i++ )
+                  d = MAC16_16( d, x_ptr[ i ], x_ptr[ i - n ] );
+               xcorr[ n - 1 ] += d;
+            }
+            for( n = 1; n < D + 1; n++ ) {
+                C_first_row[ n - 1 ] += silk_LSHIFT32( xcorr[ n - 1 ], -rshifts );
+            }
+        }
+    }
+    silk_memcpy( C_last_row, C_first_row, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) );
+
+    /* Initialize */
+    CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1;                                /* Q(-rshifts) */
+
+    invGain_Q30 = (opus_int32)1 << 30;
+    reached_max_gain = 0;
+    for( n = 0; n < D; n++ ) {
+        /* Update first row of correlation matrix (without first element) */
+        /* Update last row of correlation matrix (without last element, stored in reversed order) */
+        /* Update C * Af */
+        /* Update C * flipud(Af) (stored in reversed order) */
+        if( rshifts > -2 ) {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                x1  = -silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    16 - rshifts );        /* Q(16-rshifts) */
+                x2  = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 16 - rshifts );        /* Q(16-rshifts) */
+                tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    QA - 16 );             /* Q(QA-16) */
+                tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], QA - 16 );             /* Q(QA-16) */
+                for( k = 0; k < n; k++ ) {
+                    C_first_row[ k ] = silk_SMLAWB( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); /* Q( -rshifts ) */
+                    C_last_row[ k ]  = silk_SMLAWB( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */
+                    Atmp_QA = Af_QA[ k ];
+                    tmp1 = silk_SMLAWB( tmp1, Atmp_QA, x_ptr[ n - k - 1 ]            );                 /* Q(QA-16) */
+                    tmp2 = silk_SMLAWB( tmp2, Atmp_QA, x_ptr[ subfr_length - n + k ] );                 /* Q(QA-16) */
+                }
+                tmp1 = silk_LSHIFT32( -tmp1, 32 - QA - rshifts );                                       /* Q(16-rshifts) */
+                tmp2 = silk_LSHIFT32( -tmp2, 32 - QA - rshifts );                                       /* Q(16-rshifts) */
+                for( k = 0; k <= n; k++ ) {
+                    CAf[ k ] = silk_SMLAWB( CAf[ k ], tmp1, x_ptr[ n - k ]                    );        /* Q( -rshift ) */
+                    CAb[ k ] = silk_SMLAWB( CAb[ k ], tmp2, x_ptr[ subfr_length - n + k - 1 ] );        /* Q( -rshift ) */
+                }
+            }
+        } else {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                x1  = -silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    -rshifts );            /* Q( -rshifts ) */
+                x2  = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], -rshifts );            /* Q( -rshifts ) */
+                tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    17 );                  /* Q17 */
+                tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 17 );                  /* Q17 */
+                for( k = 0; k < n; k++ ) {
+                    C_first_row[ k ] = silk_MLA( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); /* Q( -rshifts ) */
+                    C_last_row[ k ]  = silk_MLA( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */
+                    Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 17 );                                   /* Q17 */
+                    /* We sometimes have get overflows in the multiplications (even beyond +/- 2^32),
+                       but they cancel each other and the real result seems to always fit in a 32-bit
+                       signed integer. This was determined experimentally, not theoretically (unfortunately). */
+                    tmp1 = silk_MLA_ovflw( tmp1, x_ptr[ n - k - 1 ],            Atmp1 );                      /* Q17 */
+                    tmp2 = silk_MLA_ovflw( tmp2, x_ptr[ subfr_length - n + k ], Atmp1 );                      /* Q17 */
+                }
+                tmp1 = -tmp1;                                                                           /* Q17 */
+                tmp2 = -tmp2;                                                                           /* Q17 */
+                for( k = 0; k <= n; k++ ) {
+                    CAf[ k ] = silk_SMLAWW( CAf[ k ], tmp1,
+                        silk_LSHIFT32( (opus_int32)x_ptr[ n - k ], -rshifts - 1 ) );                    /* Q( -rshift ) */
+                    CAb[ k ] = silk_SMLAWW( CAb[ k ], tmp2,
+                        silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n + k - 1 ], -rshifts - 1 ) ); /* Q( -rshift ) */
+                }
+            }
+        }
+
+        /* Calculate nominator and denominator for the next order reflection (parcor) coefficient */
+        tmp1 = C_first_row[ n ];                                                                        /* Q( -rshifts ) */
+        tmp2 = C_last_row[ n ];                                                                         /* Q( -rshifts ) */
+        num  = 0;                                                                                       /* Q( -rshifts ) */
+        nrg  = silk_ADD32( CAb[ 0 ], CAf[ 0 ] );                                                        /* Q( 1-rshifts ) */
+        for( k = 0; k < n; k++ ) {
+            Atmp_QA = Af_QA[ k ];
+            lz = silk_CLZ32( silk_abs( Atmp_QA ) ) - 1;
+            lz = silk_min( 32 - QA, lz );
+            Atmp1 = silk_LSHIFT32( Atmp_QA, lz );                                                       /* Q( QA + lz ) */
+
+            tmp1 = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( C_last_row[  n - k - 1 ], Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            tmp2 = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( C_first_row[ n - k - 1 ], Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            num  = silk_ADD_LSHIFT32( num,  silk_SMMUL( CAb[ n - k ],             Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            nrg  = silk_ADD_LSHIFT32( nrg,  silk_SMMUL( silk_ADD32( CAb[ k + 1 ], CAf[ k + 1 ] ),
+                                                                                Atmp1 ), 32 - QA - lz );    /* Q( 1-rshifts ) */
+        }
+        CAf[ n + 1 ] = tmp1;                                                                            /* Q( -rshifts ) */
+        CAb[ n + 1 ] = tmp2;                                                                            /* Q( -rshifts ) */
+        num = silk_ADD32( num, tmp2 );                                                                  /* Q( -rshifts ) */
+        num = silk_LSHIFT32( -num, 1 );                                                                 /* Q( 1-rshifts ) */
+
+        /* Calculate the next order reflection (parcor) coefficient */
+        if( silk_abs( num ) < nrg ) {
+            rc_Q31 = silk_DIV32_varQ( num, nrg, 31 );
+        } else {
+            rc_Q31 = ( num > 0 ) ? silk_int32_MAX : silk_int32_MIN;
+        }
+
+        /* Update inverse prediction gain */
+        tmp1 = ( (opus_int32)1 << 30 ) - silk_SMMUL( rc_Q31, rc_Q31 );
+        tmp1 = silk_LSHIFT( silk_SMMUL( invGain_Q30, tmp1 ), 2 );
+        if( tmp1 <= minInvGain_Q30 ) {
+            /* Max prediction gain exceeded; set reflection coefficient such that max prediction gain is exactly hit */
+            tmp2 = ( (opus_int32)1 << 30 ) - silk_DIV32_varQ( minInvGain_Q30, invGain_Q30, 30 );            /* Q30 */
+            rc_Q31 = silk_SQRT_APPROX( tmp2 );                                                  /* Q15 */
+            if( rc_Q31 > 0 ) {
+                /* Newton-Raphson iteration */
+                rc_Q31 = silk_RSHIFT32( rc_Q31 + silk_DIV32( tmp2, rc_Q31 ), 1 );                       /* Q15 */
+                rc_Q31 = silk_LSHIFT32( rc_Q31, 16 );                                                   /* Q31 */
+                if( num < 0 ) {
+                    /* Ensure adjusted reflection coefficients has the original sign */
+                    rc_Q31 = -rc_Q31;
+                }
+            }
+            invGain_Q30 = minInvGain_Q30;
+            reached_max_gain = 1;
+        } else {
+            invGain_Q30 = tmp1;
+        }
+
+        /* Update the AR coefficients */
+        for( k = 0; k < (n + 1) >> 1; k++ ) {
+            tmp1 = Af_QA[ k ];                                                                  /* QA */
+            tmp2 = Af_QA[ n - k - 1 ];                                                          /* QA */
+            Af_QA[ k ]         = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 );      /* QA */
+            Af_QA[ n - k - 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 );      /* QA */
+        }
+        Af_QA[ n ] = silk_RSHIFT32( rc_Q31, 31 - QA );                                          /* QA */
+
+        if( reached_max_gain ) {
+            /* Reached max prediction gain; set remaining coefficients to zero and exit loop */
+            for( k = n + 1; k < D; k++ ) {
+                Af_QA[ k ] = 0;
+            }
+            break;
+        }
+
+        /* Update C * Af and C * Ab */
+        for( k = 0; k <= n + 1; k++ ) {
+            tmp1 = CAf[ k ];                                                                    /* Q( -rshifts ) */
+            tmp2 = CAb[ n - k + 1 ];                                                            /* Q( -rshifts ) */
+            CAf[ k ]         = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 );        /* Q( -rshifts ) */
+            CAb[ n - k + 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 );        /* Q( -rshifts ) */
+        }
+    }
+
+    if( reached_max_gain ) {
+        for( k = 0; k < D; k++ ) {
+            /* Scale coefficients */
+            A_Q16[ k ] = -silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 );
+        }
+        /* Subtract energy of preceding samples from C0 */
+        if( rshifts > 0 ) {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                C0 -= (opus_int32)silk_RSHIFT64( silk_inner_prod16_aligned_64( x_ptr, x_ptr, D, arch ), rshifts );
+            }
+        } else {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                C0 -= silk_LSHIFT32( silk_inner_prod_aligned( x_ptr, x_ptr, D, arch), -rshifts);
+            }
+        }
+        /* Approximate residual energy */
+        *res_nrg = silk_LSHIFT( silk_SMMUL( invGain_Q30, C0 ), 2 );
+        *res_nrg_Q = -rshifts;
+    } else {
+        /* Return residual energy */
+        nrg  = CAf[ 0 ];                                                                            /* Q( -rshifts ) */
+        tmp1 = (opus_int32)1 << 16;                                                                             /* Q16 */
+        for( k = 0; k < D; k++ ) {
+            Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 );                                       /* Q16 */
+            nrg  = silk_SMLAWW( nrg, CAf[ k + 1 ], Atmp1 );                                         /* Q( -rshifts ) */
+            tmp1 = silk_SMLAWW( tmp1, Atmp1, Atmp1 );                                               /* Q16 */
+            A_Q16[ k ] = -Atmp1;
+        }
+        *res_nrg = silk_SMLAWW( nrg, silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ), -tmp1 );/* Q( -rshifts ) */
+        *res_nrg_Q = -rshifts;
+    }
+}
diff --git a/opus/silk/fixed/corrMatrix_FIX.c b/opus/silk/fixed/corrMatrix_FIX.c
new file mode 100644 (file)
index 0000000..1b4a29c
--- /dev/null
@@ -0,0 +1,150 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/**********************************************************************
+ * Correlation Matrix Computations for LS estimate.
+ **********************************************************************/
+
+#include "main_FIX.h"
+
+/* Calculates correlation vector X'*t */
+void silk_corrVector_FIX(
+    const opus_int16                *x,                                     /* I    x vector [L + order - 1] used to form data matrix X                         */
+    const opus_int16                *t,                                     /* I    Target vector [L]                                                           */
+    const opus_int                  L,                                      /* I    Length of vectors                                                           */
+    const opus_int                  order,                                  /* I    Max lag for correlation                                                     */
+    opus_int32                      *Xt,                                    /* O    Pointer to X'*t correlation vector [order]                                  */
+    const opus_int                  rshifts,                                /* I    Right shifts of correlations                                                */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int         lag, i;
+    const opus_int16 *ptr1, *ptr2;
+    opus_int32       inner_prod;
+
+    ptr1 = &x[ order - 1 ]; /* Points to first sample of column 0 of X: X[:,0] */
+    ptr2 = t;
+    /* Calculate X'*t */
+    if( rshifts > 0 ) {
+        /* Right shifting used */
+        for( lag = 0; lag < order; lag++ ) {
+            inner_prod = 0;
+            for( i = 0; i < L; i++ ) {
+                inner_prod = silk_ADD_RSHIFT32( inner_prod, silk_SMULBB( ptr1[ i ], ptr2[i] ), rshifts );
+            }
+            Xt[ lag ] = inner_prod; /* X[:,lag]'*t */
+            ptr1--; /* Go to next column of X */
+        }
+    } else {
+        silk_assert( rshifts == 0 );
+        for( lag = 0; lag < order; lag++ ) {
+            Xt[ lag ] = silk_inner_prod_aligned( ptr1, ptr2, L, arch ); /* X[:,lag]'*t */
+            ptr1--; /* Go to next column of X */
+        }
+    }
+}
+
+/* Calculates correlation matrix X'*X */
+void silk_corrMatrix_FIX(
+    const opus_int16                *x,                                     /* I    x vector [L + order - 1] used to form data matrix X                         */
+    const opus_int                  L,                                      /* I    Length of vectors                                                           */
+    const opus_int                  order,                                  /* I    Max lag for correlation                                                     */
+    opus_int32                      *XX,                                    /* O    Pointer to X'*X correlation matrix [ order x order ]                        */
+    opus_int32                      *nrg,                                    /* O    Energy of x vector                                                            */
+    opus_int                        *rshifts,                               /* O    Right shifts of correlations and energy                                     */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int         i, j, lag;
+    opus_int32       energy;
+    const opus_int16 *ptr1, *ptr2;
+
+    /* Calculate energy to find shift used to fit in 32 bits */
+    silk_sum_sqr_shift( nrg, rshifts, x, L + order - 1 );
+    energy = *nrg;
+
+    /* Calculate energy of first column (0) of X: X[:,0]'*X[:,0] */
+    /* Remove contribution of first order - 1 samples */
+    for( i = 0; i < order - 1; i++ ) {
+        energy -= silk_RSHIFT32( silk_SMULBB( x[ i ], x[ i ] ), *rshifts );
+    }
+
+    /* Calculate energy of remaining columns of X: X[:,j]'*X[:,j] */
+    /* Fill out the diagonal of the correlation matrix */
+    matrix_ptr( XX, 0, 0, order ) = energy;
+    silk_assert( energy >= 0 );
+    ptr1 = &x[ order - 1 ]; /* First sample of column 0 of X */
+    for( j = 1; j < order; j++ ) {
+        energy = silk_SUB32( energy, silk_RSHIFT32( silk_SMULBB( ptr1[ L - j ], ptr1[ L - j ] ), *rshifts ) );
+        energy = silk_ADD32( energy, silk_RSHIFT32( silk_SMULBB( ptr1[ -j ], ptr1[ -j ] ), *rshifts ) );
+        matrix_ptr( XX, j, j, order ) = energy;
+        silk_assert( energy >= 0 );
+    }
+
+    ptr2 = &x[ order - 2 ]; /* First sample of column 1 of X */
+    /* Calculate the remaining elements of the correlation matrix */
+    if( *rshifts > 0 ) {
+        /* Right shifting used */
+        for( lag = 1; lag < order; lag++ ) {
+            /* Inner product of column 0 and column lag: X[:,0]'*X[:,lag] */
+            energy = 0;
+            for( i = 0; i < L; i++ ) {
+                energy += silk_RSHIFT32( silk_SMULBB( ptr1[ i ], ptr2[i] ), *rshifts );
+            }
+            /* Calculate remaining off diagonal: X[:,j]'*X[:,j + lag] */
+            matrix_ptr( XX, lag, 0, order ) = energy;
+            matrix_ptr( XX, 0, lag, order ) = energy;
+            for( j = 1; j < ( order - lag ); j++ ) {
+                energy = silk_SUB32( energy, silk_RSHIFT32( silk_SMULBB( ptr1[ L - j ], ptr2[ L - j ] ), *rshifts ) );
+                energy = silk_ADD32( energy, silk_RSHIFT32( silk_SMULBB( ptr1[ -j ], ptr2[ -j ] ), *rshifts ) );
+                matrix_ptr( XX, lag + j, j, order ) = energy;
+                matrix_ptr( XX, j, lag + j, order ) = energy;
+            }
+            ptr2--; /* Update pointer to first sample of next column (lag) in X */
+        }
+    } else {
+        for( lag = 1; lag < order; lag++ ) {
+            /* Inner product of column 0 and column lag: X[:,0]'*X[:,lag] */
+            energy = silk_inner_prod_aligned( ptr1, ptr2, L, arch );
+            matrix_ptr( XX, lag, 0, order ) = energy;
+            matrix_ptr( XX, 0, lag, order ) = energy;
+            /* Calculate remaining off diagonal: X[:,j]'*X[:,j + lag] */
+            for( j = 1; j < ( order - lag ); j++ ) {
+                energy = silk_SUB32( energy, silk_SMULBB( ptr1[ L - j ], ptr2[ L - j ] ) );
+                energy = silk_SMLABB( energy, ptr1[ -j ], ptr2[ -j ] );
+                matrix_ptr( XX, lag + j, j, order ) = energy;
+                matrix_ptr( XX, j, lag + j, order ) = energy;
+            }
+            ptr2--;/* Update pointer to first sample of next column (lag) in X */
+        }
+    }
+}
+
diff --git a/opus/silk/fixed/encode_frame_FIX.c b/opus/silk/fixed/encode_frame_FIX.c
new file mode 100644 (file)
index 0000000..4f9e086
--- /dev/null
@@ -0,0 +1,441 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include "main_FIX.h"
+#include "stack_alloc.h"
+#include "tuning_parameters.h"
+
+/* Low Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode with lower bitrate           */
+static OPUS_INLINE void silk_LBRR_encode_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Pointer to Silk FIX encoder control struct                                  */
+    const opus_int16                x16[],                                  /* I    Input signal                                                                */
+    opus_int                        condCoding                              /* I    The type of conditional coding used so far for this frame                   */
+);
+
+void silk_encode_do_VAD_FIX(
+    silk_encoder_state_FIX          *psEnc                                  /* I/O  Pointer to Silk FIX encoder state                                           */
+)
+{
+    /****************************/
+    /* Voice Activity Detection */
+    /****************************/
+    silk_VAD_GetSA_Q8( &psEnc->sCmn, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.arch );
+
+    /**************************************************/
+    /* Convert speech activity into VAD and DTX flags */
+    /**************************************************/
+    if( psEnc->sCmn.speech_activity_Q8 < SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ) ) {
+        psEnc->sCmn.indices.signalType = TYPE_NO_VOICE_ACTIVITY;
+        psEnc->sCmn.noSpeechCounter++;
+        if( psEnc->sCmn.noSpeechCounter < NB_SPEECH_FRAMES_BEFORE_DTX ) {
+            psEnc->sCmn.inDTX = 0;
+        } else if( psEnc->sCmn.noSpeechCounter > MAX_CONSECUTIVE_DTX + NB_SPEECH_FRAMES_BEFORE_DTX ) {
+            psEnc->sCmn.noSpeechCounter = NB_SPEECH_FRAMES_BEFORE_DTX;
+            psEnc->sCmn.inDTX           = 0;
+        }
+        psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 0;
+    } else {
+        psEnc->sCmn.noSpeechCounter    = 0;
+        psEnc->sCmn.inDTX              = 0;
+        psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
+        psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
+    }
+}
+
+/****************/
+/* Encode frame */
+/****************/
+opus_int silk_encode_frame_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    opus_int32                      *pnBytesOut,                            /* O    Pointer to number of payload bytes;                                         */
+    ec_enc                          *psRangeEnc,                            /* I/O  compressor data structure                                                   */
+    opus_int                        condCoding,                             /* I    The type of conditional coding to use                                       */
+    opus_int                        maxBits,                                /* I    If > 0: maximum number of output bits                                       */
+    opus_int                        useCBR                                  /* I    Flag to force constant-bitrate operation                                    */
+)
+{
+    silk_encoder_control_FIX sEncCtrl;
+    opus_int     i, iter, maxIter, found_upper, found_lower, ret = 0;
+    opus_int16   *x_frame;
+    ec_enc       sRangeEnc_copy, sRangeEnc_copy2;
+    silk_nsq_state sNSQ_copy, sNSQ_copy2;
+    opus_int32   seed_copy, nBits, nBits_lower, nBits_upper, gainMult_lower, gainMult_upper;
+    opus_int32   gainsID, gainsID_lower, gainsID_upper;
+    opus_int16   gainMult_Q8;
+    opus_int16   ec_prevLagIndex_copy;
+    opus_int     ec_prevSignalType_copy;
+    opus_int8    LastGainIndex_copy2;
+    opus_int     gain_lock[ MAX_NB_SUBFR ] = {0};
+    opus_int16   best_gain_mult[ MAX_NB_SUBFR ];
+    opus_int     best_sum[ MAX_NB_SUBFR ];
+    SAVE_STACK;
+
+    /* This is totally unnecessary but many compilers (including gcc) are too dumb to realise it */
+    LastGainIndex_copy2 = nBits_lower = nBits_upper = gainMult_lower = gainMult_upper = 0;
+
+    psEnc->sCmn.indices.Seed = psEnc->sCmn.frameCounter++ & 3;
+
+    /**************************************************************/
+    /* Set up Input Pointers, and insert frame in input buffer   */
+    /*************************************************************/
+    /* start of frame to encode */
+    x_frame = psEnc->x_buf + psEnc->sCmn.ltp_mem_length;
+
+    /***************************************/
+    /* Ensure smooth bandwidth transitions */
+    /***************************************/
+    silk_LP_variable_cutoff( &psEnc->sCmn.sLP, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length );
+
+    /*******************************************/
+    /* Copy new frame to front of input buffer */
+    /*******************************************/
+    silk_memcpy( x_frame + LA_SHAPE_MS * psEnc->sCmn.fs_kHz, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length * sizeof( opus_int16 ) );
+
+    if( !psEnc->sCmn.prefillFlag ) {
+        VARDECL( opus_int16, res_pitch );
+        VARDECL( opus_uint8, ec_buf_copy );
+        opus_int16 *res_pitch_frame;
+
+        ALLOC( res_pitch,
+               psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length
+                   + psEnc->sCmn.ltp_mem_length, opus_int16 );
+        /* start of pitch LPC residual frame */
+        res_pitch_frame = res_pitch + psEnc->sCmn.ltp_mem_length;
+
+        /*****************************************/
+        /* Find pitch lags, initial LPC analysis */
+        /*****************************************/
+        silk_find_pitch_lags_FIX( psEnc, &sEncCtrl, res_pitch, x_frame - psEnc->sCmn.ltp_mem_length, psEnc->sCmn.arch );
+
+        /************************/
+        /* Noise shape analysis */
+        /************************/
+        silk_noise_shape_analysis_FIX( psEnc, &sEncCtrl, res_pitch_frame, x_frame, psEnc->sCmn.arch );
+
+        /***************************************************/
+        /* Find linear prediction coefficients (LPC + LTP) */
+        /***************************************************/
+        silk_find_pred_coefs_FIX( psEnc, &sEncCtrl, res_pitch_frame, x_frame, condCoding );
+
+        /****************************************/
+        /* Process gains                        */
+        /****************************************/
+        silk_process_gains_FIX( psEnc, &sEncCtrl, condCoding );
+
+        /****************************************/
+        /* Low Bitrate Redundant Encoding       */
+        /****************************************/
+        silk_LBRR_encode_FIX( psEnc, &sEncCtrl, x_frame, condCoding );
+
+        /* Loop over quantizer and entropy coding to control bitrate */
+        maxIter = 6;
+        gainMult_Q8 = SILK_FIX_CONST( 1, 8 );
+        found_lower = 0;
+        found_upper = 0;
+        gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
+        gainsID_lower = -1;
+        gainsID_upper = -1;
+        /* Copy part of the input state */
+        silk_memcpy( &sRangeEnc_copy, psRangeEnc, sizeof( ec_enc ) );
+        silk_memcpy( &sNSQ_copy, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+        seed_copy = psEnc->sCmn.indices.Seed;
+        ec_prevLagIndex_copy = psEnc->sCmn.ec_prevLagIndex;
+        ec_prevSignalType_copy = psEnc->sCmn.ec_prevSignalType;
+        ALLOC( ec_buf_copy, 1275, opus_uint8 );
+        for( iter = 0; ; iter++ ) {
+            if( gainsID == gainsID_lower ) {
+                nBits = nBits_lower;
+            } else if( gainsID == gainsID_upper ) {
+                nBits = nBits_upper;
+            } else {
+                /* Restore part of the input state */
+                if( iter > 0 ) {
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy, sizeof( ec_enc ) );
+                    silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy, sizeof( silk_nsq_state ) );
+                    psEnc->sCmn.indices.Seed = seed_copy;
+                    psEnc->sCmn.ec_prevLagIndex = ec_prevLagIndex_copy;
+                    psEnc->sCmn.ec_prevSignalType = ec_prevSignalType_copy;
+                }
+
+                /*****************************************/
+                /* Noise shaping quantization            */
+                /*****************************************/
+                if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {
+                    silk_NSQ_del_dec( &psEnc->sCmn, &psEnc->sCmn.sNSQ, &psEnc->sCmn.indices, x_frame, psEnc->sCmn.pulses,
+                           sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR_Q13, sEncCtrl.HarmShapeGain_Q14,
+                           sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.pitchL, sEncCtrl.Lambda_Q10, sEncCtrl.LTP_scale_Q14,
+                           psEnc->sCmn.arch );
+                } else {
+                    silk_NSQ( &psEnc->sCmn, &psEnc->sCmn.sNSQ, &psEnc->sCmn.indices, x_frame, psEnc->sCmn.pulses,
+                            sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR_Q13, sEncCtrl.HarmShapeGain_Q14,
+                            sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.pitchL, sEncCtrl.Lambda_Q10, sEncCtrl.LTP_scale_Q14,
+                            psEnc->sCmn.arch);
+                }
+
+                if ( iter == maxIter && !found_lower ) {
+                    silk_memcpy( &sRangeEnc_copy2, psRangeEnc, sizeof( ec_enc ) );
+                }
+
+                /****************************************/
+                /* Encode Parameters                    */
+                /****************************************/
+                silk_encode_indices( &psEnc->sCmn, psRangeEnc, psEnc->sCmn.nFramesEncoded, 0, condCoding );
+
+                /****************************************/
+                /* Encode Excitation Signal             */
+                /****************************************/
+                silk_encode_pulses( psRangeEnc, psEnc->sCmn.indices.signalType, psEnc->sCmn.indices.quantOffsetType,
+                    psEnc->sCmn.pulses, psEnc->sCmn.frame_length );
+
+                nBits = ec_tell( psRangeEnc );
+
+                /* If we still bust after the last iteration, do some damage control. */
+                if ( iter == maxIter && !found_lower && nBits > maxBits ) {
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy2, sizeof( ec_enc ) );
+
+                    /* Keep gains the same as the last frame. */
+                    psEnc->sShape.LastGainIndex = sEncCtrl.lastGainIndexPrev;
+                    for ( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                        psEnc->sCmn.indices.GainsIndices[ i ] = 4;
+                    }
+                    if (condCoding != CODE_CONDITIONALLY) {
+                       psEnc->sCmn.indices.GainsIndices[ 0 ] = sEncCtrl.lastGainIndexPrev;
+                    }
+                    psEnc->sCmn.ec_prevLagIndex = ec_prevLagIndex_copy;
+                    psEnc->sCmn.ec_prevSignalType = ec_prevSignalType_copy;
+                    /* Clear all pulses. */
+                    for ( i = 0; i < psEnc->sCmn.frame_length; i++ ) {
+                        psEnc->sCmn.pulses[ i ] = 0;
+                    }
+
+                    silk_encode_indices( &psEnc->sCmn, psRangeEnc, psEnc->sCmn.nFramesEncoded, 0, condCoding );
+
+                    silk_encode_pulses( psRangeEnc, psEnc->sCmn.indices.signalType, psEnc->sCmn.indices.quantOffsetType,
+                        psEnc->sCmn.pulses, psEnc->sCmn.frame_length );
+
+                    nBits = ec_tell( psRangeEnc );
+                }
+
+                if( useCBR == 0 && iter == 0 && nBits <= maxBits ) {
+                    break;
+                }
+            }
+
+            if( iter == maxIter ) {
+                if( found_lower && ( gainsID == gainsID_lower || nBits > maxBits ) ) {
+                    /* Restore output state from earlier iteration that did meet the bitrate budget */
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy2, sizeof( ec_enc ) );
+                    silk_assert( sRangeEnc_copy2.offs <= 1275 );
+                    silk_memcpy( psRangeEnc->buf, ec_buf_copy, sRangeEnc_copy2.offs );
+                    silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy2, sizeof( silk_nsq_state ) );
+                    psEnc->sShape.LastGainIndex = LastGainIndex_copy2;
+                }
+                break;
+            }
+
+            if( nBits > maxBits ) {
+                if( found_lower == 0 && iter >= 2 ) {
+                    /* Adjust the quantizer's rate/distortion tradeoff and discard previous "upper" results */
+                    sEncCtrl.Lambda_Q10 = silk_ADD_RSHIFT32( sEncCtrl.Lambda_Q10, sEncCtrl.Lambda_Q10, 1 );
+                    found_upper = 0;
+                    gainsID_upper = -1;
+                } else {
+                    found_upper = 1;
+                    nBits_upper = nBits;
+                    gainMult_upper = gainMult_Q8;
+                    gainsID_upper = gainsID;
+                }
+            } else if( nBits < maxBits - 5 ) {
+                found_lower = 1;
+                nBits_lower = nBits;
+                gainMult_lower = gainMult_Q8;
+                if( gainsID != gainsID_lower ) {
+                    gainsID_lower = gainsID;
+                    /* Copy part of the output state */
+                    silk_memcpy( &sRangeEnc_copy2, psRangeEnc, sizeof( ec_enc ) );
+                    silk_assert( psRangeEnc->offs <= 1275 );
+                    silk_memcpy( ec_buf_copy, psRangeEnc->buf, psRangeEnc->offs );
+                    silk_memcpy( &sNSQ_copy2, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+                    LastGainIndex_copy2 = psEnc->sShape.LastGainIndex;
+                }
+            } else {
+                /* Within 5 bits of budget: close enough */
+                break;
+            }
+
+            if ( !found_lower && nBits > maxBits ) {
+                int j;
+                for ( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                    int sum=0;
+                    for ( j = i*psEnc->sCmn.subfr_length; j < (i+1)*psEnc->sCmn.subfr_length; j++ ) {
+                        sum += abs( psEnc->sCmn.pulses[j] );
+                    }
+                    if ( iter == 0 || (sum < best_sum[i] && !gain_lock[i]) ) {
+                        best_sum[i] = sum;
+                        best_gain_mult[i] = gainMult_Q8;
+                    } else {
+                        gain_lock[i] = 1;
+                    }
+                }
+            }
+            if( ( found_lower & found_upper ) == 0 ) {
+                /* Adjust gain according to high-rate rate/distortion curve */
+                if( nBits > maxBits ) {
+                    if (gainMult_Q8 < 16384) {
+                        gainMult_Q8 *= 2;
+                    } else {
+                        gainMult_Q8 = 32767;
+                    }
+                } else {
+                    opus_int32 gain_factor_Q16;
+                    gain_factor_Q16 = silk_log2lin( silk_LSHIFT( nBits - maxBits, 7 ) / psEnc->sCmn.frame_length + SILK_FIX_CONST( 16, 7 ) );
+                    gainMult_Q8 = silk_SMULWB( gain_factor_Q16, gainMult_Q8 );
+                }
+
+            } else {
+                /* Adjust gain by interpolating */
+                gainMult_Q8 = gainMult_lower + silk_DIV32_16( silk_MUL( gainMult_upper - gainMult_lower, maxBits - nBits_lower ), nBits_upper - nBits_lower );
+                /* New gain multplier must be between 25% and 75% of old range (note that gainMult_upper < gainMult_lower) */
+                if( gainMult_Q8 > silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 ) ) {
+                    gainMult_Q8 = silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 );
+                } else
+                if( gainMult_Q8 < silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 ) ) {
+                    gainMult_Q8 = silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 );
+                }
+            }
+
+            for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                opus_int16 tmp;
+                if ( gain_lock[i] ) {
+                    tmp = best_gain_mult[i];
+                } else {
+                    tmp = gainMult_Q8;
+                }
+                sEncCtrl.Gains_Q16[ i ] = silk_LSHIFT_SAT32( silk_SMULWB( sEncCtrl.GainsUnq_Q16[ i ], tmp ), 8 );
+            }
+
+            /* Quantize gains */
+            psEnc->sShape.LastGainIndex = sEncCtrl.lastGainIndexPrev;
+            silk_gains_quant( psEnc->sCmn.indices.GainsIndices, sEncCtrl.Gains_Q16,
+                  &psEnc->sShape.LastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+            /* Unique identifier of gains vector */
+            gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
+        }
+    }
+
+    /* Update input buffer */
+    silk_memmove( psEnc->x_buf, &psEnc->x_buf[ psEnc->sCmn.frame_length ],
+        ( psEnc->sCmn.ltp_mem_length + LA_SHAPE_MS * psEnc->sCmn.fs_kHz ) * sizeof( opus_int16 ) );
+
+    /* Exit without entropy coding */
+    if( psEnc->sCmn.prefillFlag ) {
+        /* No payload */
+        *pnBytesOut = 0;
+        RESTORE_STACK;
+        return ret;
+    }
+
+    /* Parameters needed for next frame */
+    psEnc->sCmn.prevLag        = sEncCtrl.pitchL[ psEnc->sCmn.nb_subfr - 1 ];
+    psEnc->sCmn.prevSignalType = psEnc->sCmn.indices.signalType;
+
+    /****************************************/
+    /* Finalize payload                     */
+    /****************************************/
+    psEnc->sCmn.first_frame_after_reset = 0;
+    /* Payload size */
+    *pnBytesOut = silk_RSHIFT( ec_tell( psRangeEnc ) + 7, 3 );
+
+    RESTORE_STACK;
+    return ret;
+}
+
+/* Low-Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode excitation at lower bitrate  */
+static OPUS_INLINE void silk_LBRR_encode_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Pointer to Silk FIX encoder control struct                                  */
+    const opus_int16                x16[],                                  /* I    Input signal                                                                */
+    opus_int                        condCoding                              /* I    The type of conditional coding used so far for this frame                   */
+)
+{
+    opus_int32   TempGains_Q16[ MAX_NB_SUBFR ];
+    SideInfoIndices *psIndices_LBRR = &psEnc->sCmn.indices_LBRR[ psEnc->sCmn.nFramesEncoded ];
+    silk_nsq_state sNSQ_LBRR;
+
+    /*******************************************/
+    /* Control use of inband LBRR              */
+    /*******************************************/
+    if( psEnc->sCmn.LBRR_enabled && psEnc->sCmn.speech_activity_Q8 > SILK_FIX_CONST( LBRR_SPEECH_ACTIVITY_THRES, 8 ) ) {
+        psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
+
+        /* Copy noise shaping quantizer state and quantization indices from regular encoding */
+        silk_memcpy( &sNSQ_LBRR, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+        silk_memcpy( psIndices_LBRR, &psEnc->sCmn.indices, sizeof( SideInfoIndices ) );
+
+        /* Save original gains */
+        silk_memcpy( TempGains_Q16, psEncCtrl->Gains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
+
+        if( psEnc->sCmn.nFramesEncoded == 0 || psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded - 1 ] == 0 ) {
+            /* First frame in packet or previous frame not LBRR coded */
+            psEnc->sCmn.LBRRprevLastGainIndex = psEnc->sShape.LastGainIndex;
+
+            /* Increase Gains to get target LBRR rate */
+            psIndices_LBRR->GainsIndices[ 0 ] = psIndices_LBRR->GainsIndices[ 0 ] + psEnc->sCmn.LBRR_GainIncreases;
+            psIndices_LBRR->GainsIndices[ 0 ] = silk_min_int( psIndices_LBRR->GainsIndices[ 0 ], N_LEVELS_QGAIN - 1 );
+        }
+
+        /* Decode to get gains in sync with decoder         */
+        /* Overwrite unquantized gains with quantized gains */
+        silk_gains_dequant( psEncCtrl->Gains_Q16, psIndices_LBRR->GainsIndices,
+            &psEnc->sCmn.LBRRprevLastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+        /*****************************************/
+        /* Noise shaping quantization            */
+        /*****************************************/
+        if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {
+            silk_NSQ_del_dec( &psEnc->sCmn, &sNSQ_LBRR, psIndices_LBRR, x16,
+                psEnc->sCmn.pulses_LBRR[ psEnc->sCmn.nFramesEncoded ], psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14,
+                psEncCtrl->AR_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14,
+                psEncCtrl->Gains_Q16, psEncCtrl->pitchL, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14, psEnc->sCmn.arch );
+        } else {
+            silk_NSQ( &psEnc->sCmn, &sNSQ_LBRR, psIndices_LBRR, x16,
+                psEnc->sCmn.pulses_LBRR[ psEnc->sCmn.nFramesEncoded ], psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14,
+                psEncCtrl->AR_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14,
+                psEncCtrl->Gains_Q16, psEncCtrl->pitchL, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14, psEnc->sCmn.arch );
+        }
+
+        /* Restore original gains */
+        silk_memcpy( psEncCtrl->Gains_Q16, TempGains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
+    }
+}
diff --git a/opus/silk/fixed/find_LPC_FIX.c b/opus/silk/fixed/find_LPC_FIX.c
new file mode 100644 (file)
index 0000000..e55b63a
--- /dev/null
@@ -0,0 +1,151 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "stack_alloc.h"
+#include "tuning_parameters.h"
+
+/* Finds LPC vector from correlations, and converts to NLSF */
+void silk_find_LPC_FIX(
+    silk_encoder_state              *psEncC,                                /* I/O  Encoder state                                                               */
+    opus_int16                      NLSF_Q15[],                             /* O    NLSFs                                                                       */
+    const opus_int16                x[],                                    /* I    Input signal                                                                */
+    const opus_int32                minInvGain_Q30                          /* I    Inverse of max prediction gain                                              */
+)
+{
+    opus_int     k, subfr_length;
+    opus_int32   a_Q16[ MAX_LPC_ORDER ];
+    opus_int     isInterpLower, shift;
+    opus_int32   res_nrg0, res_nrg1;
+    opus_int     rshift0, rshift1;
+
+    /* Used only for LSF interpolation */
+    opus_int32   a_tmp_Q16[ MAX_LPC_ORDER ], res_nrg_interp, res_nrg, res_tmp_nrg;
+    opus_int     res_nrg_interp_Q, res_nrg_Q, res_tmp_nrg_Q;
+    opus_int16   a_tmp_Q12[ MAX_LPC_ORDER ];
+    opus_int16   NLSF0_Q15[ MAX_LPC_ORDER ];
+    SAVE_STACK;
+
+    subfr_length = psEncC->subfr_length + psEncC->predictLPCOrder;
+
+    /* Default: no interpolation */
+    psEncC->indices.NLSFInterpCoef_Q2 = 4;
+
+    /* Burg AR analysis for the full frame */
+    silk_burg_modified( &res_nrg, &res_nrg_Q, a_Q16, x, minInvGain_Q30, subfr_length, psEncC->nb_subfr, psEncC->predictLPCOrder, psEncC->arch );
+
+    if( psEncC->useInterpolatedNLSFs && !psEncC->first_frame_after_reset && psEncC->nb_subfr == MAX_NB_SUBFR ) {
+        VARDECL( opus_int16, LPC_res );
+
+        /* Optimal solution for last 10 ms */
+        silk_burg_modified( &res_tmp_nrg, &res_tmp_nrg_Q, a_tmp_Q16, x + 2 * subfr_length, minInvGain_Q30, subfr_length, 2, psEncC->predictLPCOrder, psEncC->arch );
+
+        /* subtract residual energy here, as that's easier than adding it to the    */
+        /* residual energy of the first 10 ms in each iteration of the search below */
+        shift = res_tmp_nrg_Q - res_nrg_Q;
+        if( shift >= 0 ) {
+            if( shift < 32 ) {
+                res_nrg = res_nrg - silk_RSHIFT( res_tmp_nrg, shift );
+            }
+        } else {
+            silk_assert( shift > -32 );
+            res_nrg   = silk_RSHIFT( res_nrg, -shift ) - res_tmp_nrg;
+            res_nrg_Q = res_tmp_nrg_Q;
+        }
+
+        /* Convert to NLSFs */
+        silk_A2NLSF( NLSF_Q15, a_tmp_Q16, psEncC->predictLPCOrder );
+
+        ALLOC( LPC_res, 2 * subfr_length, opus_int16 );
+
+        /* Search over interpolation indices to find the one with lowest residual energy */
+        for( k = 3; k >= 0; k-- ) {
+            /* Interpolate NLSFs for first half */
+            silk_interpolate( NLSF0_Q15, psEncC->prev_NLSFq_Q15, NLSF_Q15, k, psEncC->predictLPCOrder );
+
+            /* Convert to LPC for residual energy evaluation */
+            silk_NLSF2A( a_tmp_Q12, NLSF0_Q15, psEncC->predictLPCOrder, psEncC->arch );
+
+            /* Calculate residual energy with NLSF interpolation */
+            silk_LPC_analysis_filter( LPC_res, x, a_tmp_Q12, 2 * subfr_length, psEncC->predictLPCOrder, psEncC->arch );
+
+            silk_sum_sqr_shift( &res_nrg0, &rshift0, LPC_res + psEncC->predictLPCOrder,                subfr_length - psEncC->predictLPCOrder );
+            silk_sum_sqr_shift( &res_nrg1, &rshift1, LPC_res + psEncC->predictLPCOrder + subfr_length, subfr_length - psEncC->predictLPCOrder );
+
+            /* Add subframe energies from first half frame */
+            shift = rshift0 - rshift1;
+            if( shift >= 0 ) {
+                res_nrg1         = silk_RSHIFT( res_nrg1, shift );
+                res_nrg_interp_Q = -rshift0;
+            } else {
+                res_nrg0         = silk_RSHIFT( res_nrg0, -shift );
+                res_nrg_interp_Q = -rshift1;
+            }
+            res_nrg_interp = silk_ADD32( res_nrg0, res_nrg1 );
+
+            /* Compare with first half energy without NLSF interpolation, or best interpolated value so far */
+            shift = res_nrg_interp_Q - res_nrg_Q;
+            if( shift >= 0 ) {
+                if( silk_RSHIFT( res_nrg_interp, shift ) < res_nrg ) {
+                    isInterpLower = silk_TRUE;
+                } else {
+                    isInterpLower = silk_FALSE;
+                }
+            } else {
+                if( -shift < 32 ) {
+                    if( res_nrg_interp < silk_RSHIFT( res_nrg, -shift ) ) {
+                        isInterpLower = silk_TRUE;
+                    } else {
+                        isInterpLower = silk_FALSE;
+                    }
+                } else {
+                    isInterpLower = silk_FALSE;
+                }
+            }
+
+            /* Determine whether current interpolated NLSFs are best so far */
+            if( isInterpLower == silk_TRUE ) {
+                /* Interpolation has lower residual energy */
+                res_nrg   = res_nrg_interp;
+                res_nrg_Q = res_nrg_interp_Q;
+                psEncC->indices.NLSFInterpCoef_Q2 = (opus_int8)k;
+            }
+        }
+    }
+
+    if( psEncC->indices.NLSFInterpCoef_Q2 == 4 ) {
+        /* NLSF interpolation is currently inactive, calculate NLSFs from full frame AR coefficients */
+        silk_A2NLSF( NLSF_Q15, a_Q16, psEncC->predictLPCOrder );
+    }
+
+    silk_assert( psEncC->indices.NLSFInterpCoef_Q2 == 4 || ( psEncC->useInterpolatedNLSFs && !psEncC->first_frame_after_reset && psEncC->nb_subfr == MAX_NB_SUBFR ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/find_LTP_FIX.c b/opus/silk/fixed/find_LTP_FIX.c
new file mode 100644 (file)
index 0000000..62d4afb
--- /dev/null
@@ -0,0 +1,99 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "tuning_parameters.h"
+
+void silk_find_LTP_FIX(
+    opus_int32                      XXLTP_Q17[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* O    Correlation matrix                                               */
+    opus_int32                      xXLTP_Q17[ MAX_NB_SUBFR * LTP_ORDER ],  /* O    Correlation vector                                                          */
+    const opus_int16                r_ptr[],                                /* I    Residual signal after LPC                                                   */
+    const opus_int                  lag[ MAX_NB_SUBFR ],                    /* I    LTP lags                                                                    */
+    const opus_int                  subfr_length,                           /* I    Subframe length                                                             */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int   i, k, extra_shifts;
+    opus_int   xx_shifts, xX_shifts, XX_shifts;
+    const opus_int16 *lag_ptr;
+    opus_int32 *XXLTP_Q17_ptr, *xXLTP_Q17_ptr;
+    opus_int32 xx, nrg, temp;
+
+    xXLTP_Q17_ptr = xXLTP_Q17;
+    XXLTP_Q17_ptr = XXLTP_Q17;
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_ptr = r_ptr - ( lag[ k ] + LTP_ORDER / 2 );
+
+        silk_sum_sqr_shift( &xx, &xx_shifts, r_ptr, subfr_length + LTP_ORDER );                            /* xx in Q( -xx_shifts ) */
+        silk_corrMatrix_FIX( lag_ptr, subfr_length, LTP_ORDER, XXLTP_Q17_ptr, &nrg, &XX_shifts, arch );    /* XXLTP_Q17_ptr and nrg in Q( -XX_shifts ) */
+        extra_shifts = xx_shifts - XX_shifts;
+        if( extra_shifts > 0 ) {
+            /* Shift XX */
+            xX_shifts = xx_shifts;
+            for( i = 0; i < LTP_ORDER * LTP_ORDER; i++ ) {
+                XXLTP_Q17_ptr[ i ] = silk_RSHIFT32( XXLTP_Q17_ptr[ i ], extra_shifts );              /* Q( -xX_shifts ) */
+            }
+            nrg = silk_RSHIFT32( nrg, extra_shifts );                                                /* Q( -xX_shifts ) */
+        } else if( extra_shifts < 0 ) {
+            /* Shift xx */
+            xX_shifts = XX_shifts;
+            xx = silk_RSHIFT32( xx, -extra_shifts );                                                 /* Q( -xX_shifts ) */
+        } else {
+            xX_shifts = xx_shifts;
+        }
+        silk_corrVector_FIX( lag_ptr, r_ptr, subfr_length, LTP_ORDER, xXLTP_Q17_ptr, xX_shifts, arch );    /* xXLTP_Q17_ptr in Q( -xX_shifts ) */
+
+        /* At this point all correlations are in Q(-xX_shifts) */
+        temp = silk_SMLAWB( 1, nrg, SILK_FIX_CONST( LTP_CORR_INV_MAX, 16 ) );
+        temp = silk_max( temp, xx );
+TIC(div)
+#if 0
+        for( i = 0; i < LTP_ORDER * LTP_ORDER; i++ ) {
+            XXLTP_Q17_ptr[ i ] = silk_DIV32_varQ( XXLTP_Q17_ptr[ i ], temp, 17 );
+        }
+        for( i = 0; i < LTP_ORDER; i++ ) {
+            xXLTP_Q17_ptr[ i ] = silk_DIV32_varQ( xXLTP_Q17_ptr[ i ], temp, 17 );
+        }
+#else
+        for( i = 0; i < LTP_ORDER * LTP_ORDER; i++ ) {
+            XXLTP_Q17_ptr[ i ] = (opus_int32)( silk_LSHIFT64( (opus_int64)XXLTP_Q17_ptr[ i ], 17 ) / temp );
+        }
+        for( i = 0; i < LTP_ORDER; i++ ) {
+            xXLTP_Q17_ptr[ i ] = (opus_int32)( silk_LSHIFT64( (opus_int64)xXLTP_Q17_ptr[ i ], 17 ) / temp );
+        }
+#endif
+TOC(div)
+        r_ptr         += subfr_length;
+        XXLTP_Q17_ptr += LTP_ORDER * LTP_ORDER;
+        xXLTP_Q17_ptr += LTP_ORDER;
+    }
+}
diff --git a/opus/silk/fixed/find_pitch_lags_FIX.c b/opus/silk/fixed/find_pitch_lags_FIX.c
new file mode 100644 (file)
index 0000000..9303e9d
--- /dev/null
@@ -0,0 +1,143 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "stack_alloc.h"
+#include "tuning_parameters.h"
+
+/* Find pitch lags */
+void silk_find_pitch_lags_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    opus_int16                      res[],                                  /* O    residual                                                                    */
+    const opus_int16                x[],                                    /* I    Speech signal                                                               */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int   buf_len, i, scale;
+    opus_int32 thrhld_Q13, res_nrg;
+    const opus_int16 *x_ptr;
+    VARDECL( opus_int16, Wsig );
+    opus_int16 *Wsig_ptr;
+    opus_int32 auto_corr[ MAX_FIND_PITCH_LPC_ORDER + 1 ];
+    opus_int16 rc_Q15[    MAX_FIND_PITCH_LPC_ORDER ];
+    opus_int32 A_Q24[     MAX_FIND_PITCH_LPC_ORDER ];
+    opus_int16 A_Q12[     MAX_FIND_PITCH_LPC_ORDER ];
+    SAVE_STACK;
+
+    /******************************************/
+    /* Set up buffer lengths etc based on Fs  */
+    /******************************************/
+    buf_len = psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length + psEnc->sCmn.ltp_mem_length;
+
+    /* Safety check */
+    silk_assert( buf_len >= psEnc->sCmn.pitch_LPC_win_length );
+
+    /*************************************/
+    /* Estimate LPC AR coefficients      */
+    /*************************************/
+
+    /* Calculate windowed signal */
+
+    ALLOC( Wsig, psEnc->sCmn.pitch_LPC_win_length, opus_int16 );
+
+    /* First LA_LTP samples */
+    x_ptr = x + buf_len - psEnc->sCmn.pitch_LPC_win_length;
+    Wsig_ptr  = Wsig;
+    silk_apply_sine_window( Wsig_ptr, x_ptr, 1, psEnc->sCmn.la_pitch );
+
+    /* Middle un - windowed samples */
+    Wsig_ptr  += psEnc->sCmn.la_pitch;
+    x_ptr += psEnc->sCmn.la_pitch;
+    silk_memcpy( Wsig_ptr, x_ptr, ( psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 ) ) * sizeof( opus_int16 ) );
+
+    /* Last LA_LTP samples */
+    Wsig_ptr  += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 );
+    x_ptr += psEnc->sCmn.pitch_LPC_win_length - silk_LSHIFT( psEnc->sCmn.la_pitch, 1 );
+    silk_apply_sine_window( Wsig_ptr, x_ptr, 2, psEnc->sCmn.la_pitch );
+
+    /* Calculate autocorrelation sequence */
+    silk_autocorr( auto_corr, &scale, Wsig, psEnc->sCmn.pitch_LPC_win_length, psEnc->sCmn.pitchEstimationLPCOrder + 1, arch );
+
+    /* Add white noise, as fraction of energy */
+    auto_corr[ 0 ] = silk_SMLAWB( auto_corr[ 0 ], auto_corr[ 0 ], SILK_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) ) + 1;
+
+    /* Calculate the reflection coefficients using schur */
+    res_nrg = silk_schur( rc_Q15, auto_corr, psEnc->sCmn.pitchEstimationLPCOrder );
+
+    /* Prediction gain */
+    psEncCtrl->predGain_Q16 = silk_DIV32_varQ( auto_corr[ 0 ], silk_max_int( res_nrg, 1 ), 16 );
+
+    /* Convert reflection coefficients to prediction coefficients */
+    silk_k2a( A_Q24, rc_Q15, psEnc->sCmn.pitchEstimationLPCOrder );
+
+    /* Convert From 32 bit Q24 to 16 bit Q12 coefs */
+    for( i = 0; i < psEnc->sCmn.pitchEstimationLPCOrder; i++ ) {
+        A_Q12[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT( A_Q24[ i ], 12 ) );
+    }
+
+    /* Do BWE */
+    silk_bwexpander( A_Q12, psEnc->sCmn.pitchEstimationLPCOrder, SILK_FIX_CONST( FIND_PITCH_BANDWIDTH_EXPANSION, 16 ) );
+
+    /*****************************************/
+    /* LPC analysis filtering                */
+    /*****************************************/
+    silk_LPC_analysis_filter( res, x, A_Q12, buf_len, psEnc->sCmn.pitchEstimationLPCOrder, psEnc->sCmn.arch );
+
+    if( psEnc->sCmn.indices.signalType != TYPE_NO_VOICE_ACTIVITY && psEnc->sCmn.first_frame_after_reset == 0 ) {
+        /* Threshold for pitch estimator */
+        thrhld_Q13 = SILK_FIX_CONST( 0.6, 13 );
+        thrhld_Q13 = silk_SMLABB( thrhld_Q13, SILK_FIX_CONST( -0.004, 13 ), psEnc->sCmn.pitchEstimationLPCOrder );
+        thrhld_Q13 = silk_SMLAWB( thrhld_Q13, SILK_FIX_CONST( -0.1,   21  ), psEnc->sCmn.speech_activity_Q8 );
+        thrhld_Q13 = silk_SMLABB( thrhld_Q13, SILK_FIX_CONST( -0.15,  13 ), silk_RSHIFT( psEnc->sCmn.prevSignalType, 1 ) );
+        thrhld_Q13 = silk_SMLAWB( thrhld_Q13, SILK_FIX_CONST( -0.1,   14 ), psEnc->sCmn.input_tilt_Q15 );
+        thrhld_Q13 = silk_SAT16(  thrhld_Q13 );
+
+        /*****************************************/
+        /* Call pitch estimator                  */
+        /*****************************************/
+        if( silk_pitch_analysis_core( res, psEncCtrl->pitchL, &psEnc->sCmn.indices.lagIndex, &psEnc->sCmn.indices.contourIndex,
+                &psEnc->LTPCorr_Q15, psEnc->sCmn.prevLag, psEnc->sCmn.pitchEstimationThreshold_Q16,
+                (opus_int)thrhld_Q13, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr,
+                psEnc->sCmn.arch) == 0 )
+        {
+            psEnc->sCmn.indices.signalType = TYPE_VOICED;
+        } else {
+            psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
+        }
+    } else {
+        silk_memset( psEncCtrl->pitchL, 0, sizeof( psEncCtrl->pitchL ) );
+        psEnc->sCmn.indices.lagIndex = 0;
+        psEnc->sCmn.indices.contourIndex = 0;
+        psEnc->LTPCorr_Q15 = 0;
+    }
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/find_pred_coefs_FIX.c b/opus/silk/fixed/find_pred_coefs_FIX.c
new file mode 100644 (file)
index 0000000..24c6aab
--- /dev/null
@@ -0,0 +1,145 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "stack_alloc.h"
+
+void silk_find_pred_coefs_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    const opus_int16                res_pitch[],                            /* I    Residual from pitch analysis                                                */
+    const opus_int16                x[],                                    /* I    Speech signal                                                               */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+)
+{
+    opus_int         i;
+    opus_int32       invGains_Q16[ MAX_NB_SUBFR ], local_gains[ MAX_NB_SUBFR ];
+    opus_int16       NLSF_Q15[ MAX_LPC_ORDER ];
+    const opus_int16 *x_ptr;
+    opus_int16       *x_pre_ptr;
+    VARDECL( opus_int16, LPC_in_pre );
+    opus_int32       min_gain_Q16, minInvGain_Q30;
+    SAVE_STACK;
+
+    /* weighting for weighted least squares */
+    min_gain_Q16 = silk_int32_MAX >> 6;
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        min_gain_Q16 = silk_min( min_gain_Q16, psEncCtrl->Gains_Q16[ i ] );
+    }
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        /* Divide to Q16 */
+        silk_assert( psEncCtrl->Gains_Q16[ i ] > 0 );
+        /* Invert and normalize gains, and ensure that maximum invGains_Q16 is within range of a 16 bit int */
+        invGains_Q16[ i ] = silk_DIV32_varQ( min_gain_Q16, psEncCtrl->Gains_Q16[ i ], 16 - 2 );
+
+        /* Limit inverse */
+        invGains_Q16[ i ] = silk_max( invGains_Q16[ i ], 100 );
+
+        /* Square the inverted gains */
+        silk_assert( invGains_Q16[ i ] == silk_SAT16( invGains_Q16[ i ] ) );
+
+        /* Invert the inverted and normalized gains */
+        local_gains[ i ] = silk_DIV32( ( (opus_int32)1 << 16 ), invGains_Q16[ i ] );
+    }
+
+    ALLOC( LPC_in_pre,
+           psEnc->sCmn.nb_subfr * psEnc->sCmn.predictLPCOrder
+               + psEnc->sCmn.frame_length, opus_int16 );
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        VARDECL( opus_int32, xXLTP_Q17 );
+        VARDECL( opus_int32, XXLTP_Q17 );
+
+        /**********/
+        /* VOICED */
+        /**********/
+        silk_assert( psEnc->sCmn.ltp_mem_length - psEnc->sCmn.predictLPCOrder >= psEncCtrl->pitchL[ 0 ] + LTP_ORDER / 2 );
+
+        ALLOC( xXLTP_Q17, psEnc->sCmn.nb_subfr * LTP_ORDER, opus_int32 );
+        ALLOC( XXLTP_Q17, psEnc->sCmn.nb_subfr * LTP_ORDER * LTP_ORDER, opus_int32 );
+
+        /* LTP analysis */
+        silk_find_LTP_FIX( XXLTP_Q17, xXLTP_Q17, res_pitch,
+            psEncCtrl->pitchL, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.arch );
+
+        /* Quantize LTP gain parameters */
+        silk_quant_LTP_gains( psEncCtrl->LTPCoef_Q14, psEnc->sCmn.indices.LTPIndex, &psEnc->sCmn.indices.PERIndex,
+            &psEnc->sCmn.sum_log_gain_Q7, &psEncCtrl->LTPredCodGain_Q7, XXLTP_Q17, xXLTP_Q17, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.arch );
+
+        /* Control LTP scaling */
+        silk_LTP_scale_ctrl_FIX( psEnc, psEncCtrl, condCoding );
+
+        /* Create LTP residual */
+        silk_LTP_analysis_filter_FIX( LPC_in_pre, x - psEnc->sCmn.predictLPCOrder, psEncCtrl->LTPCoef_Q14,
+            psEncCtrl->pitchL, invGains_Q16, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.predictLPCOrder );
+
+    } else {
+        /************/
+        /* UNVOICED */
+        /************/
+        /* Create signal with prepended subframes, scaled by inverse gains */
+        x_ptr     = x - psEnc->sCmn.predictLPCOrder;
+        x_pre_ptr = LPC_in_pre;
+        for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+            silk_scale_copy_vector16( x_pre_ptr, x_ptr, invGains_Q16[ i ],
+                psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder );
+            x_pre_ptr += psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder;
+            x_ptr     += psEnc->sCmn.subfr_length;
+        }
+
+        silk_memset( psEncCtrl->LTPCoef_Q14, 0, psEnc->sCmn.nb_subfr * LTP_ORDER * sizeof( opus_int16 ) );
+        psEncCtrl->LTPredCodGain_Q7 = 0;
+        psEnc->sCmn.sum_log_gain_Q7 = 0;
+    }
+
+    /* Limit on total predictive coding gain */
+    if( psEnc->sCmn.first_frame_after_reset ) {
+        minInvGain_Q30 = SILK_FIX_CONST( 1.0f / MAX_PREDICTION_POWER_GAIN_AFTER_RESET, 30 );
+    } else {
+        minInvGain_Q30 = silk_log2lin( silk_SMLAWB( 16 << 7, (opus_int32)psEncCtrl->LTPredCodGain_Q7, SILK_FIX_CONST( 1.0 / 3, 16 ) ) );      /* Q16 */
+        minInvGain_Q30 = silk_DIV32_varQ( minInvGain_Q30,
+            silk_SMULWW( SILK_FIX_CONST( MAX_PREDICTION_POWER_GAIN, 0 ),
+                silk_SMLAWB( SILK_FIX_CONST( 0.25, 18 ), SILK_FIX_CONST( 0.75, 18 ), psEncCtrl->coding_quality_Q14 ) ), 14 );
+    }
+
+    /* LPC_in_pre contains the LTP-filtered input for voiced, and the unfiltered input for unvoiced */
+    silk_find_LPC_FIX( &psEnc->sCmn, NLSF_Q15, LPC_in_pre, minInvGain_Q30 );
+
+    /* Quantize LSFs */
+    silk_process_NLSFs( &psEnc->sCmn, psEncCtrl->PredCoef_Q12, NLSF_Q15, psEnc->sCmn.prev_NLSFq_Q15 );
+
+    /* Calculate residual energy using quantized LPC coefficients */
+    silk_residual_energy_FIX( psEncCtrl->ResNrg, psEncCtrl->ResNrgQ, LPC_in_pre, psEncCtrl->PredCoef_Q12, local_gains,
+        psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.predictLPCOrder, psEnc->sCmn.arch );
+
+    /* Copy to prediction struct for use in next frame for interpolation */
+    silk_memcpy( psEnc->sCmn.prev_NLSFq_Q15, NLSF_Q15, sizeof( psEnc->sCmn.prev_NLSFq_Q15 ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/k2a_FIX.c b/opus/silk/fixed/k2a_FIX.c
new file mode 100644 (file)
index 0000000..549f6ea
--- /dev/null
@@ -0,0 +1,54 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Step up function, converts reflection coefficients to prediction coefficients */
+void silk_k2a(
+    opus_int32                  *A_Q24,             /* O    Prediction coefficients [order] Q24                         */
+    const opus_int16            *rc_Q15,            /* I    Reflection coefficients [order] Q15                         */
+    const opus_int32            order               /* I    Prediction order                                            */
+)
+{
+    opus_int   k, n;
+    opus_int32 rc, tmp1, tmp2;
+
+    for( k = 0; k < order; k++ ) {
+        rc = rc_Q15[ k ];
+        for( n = 0; n < (k + 1) >> 1; n++ ) {
+            tmp1 = A_Q24[ n ];
+            tmp2 = A_Q24[ k - n - 1 ];
+            A_Q24[ n ]         = silk_SMLAWB( tmp1, silk_LSHIFT( tmp2, 1 ), rc );
+            A_Q24[ k - n - 1 ] = silk_SMLAWB( tmp2, silk_LSHIFT( tmp1, 1 ), rc );
+        }
+        A_Q24[ k ] = -silk_LSHIFT( (opus_int32)rc_Q15[ k ], 9 );
+    }
+}
diff --git a/opus/silk/fixed/k2a_Q16_FIX.c b/opus/silk/fixed/k2a_Q16_FIX.c
new file mode 100644 (file)
index 0000000..1595aa6
--- /dev/null
@@ -0,0 +1,54 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Step up function, converts reflection coefficients to prediction coefficients */
+void silk_k2a_Q16(
+    opus_int32                  *A_Q24,             /* O    Prediction coefficients [order] Q24                         */
+    const opus_int32            *rc_Q16,            /* I    Reflection coefficients [order] Q16                         */
+    const opus_int32            order               /* I    Prediction order                                            */
+)
+{
+    opus_int   k, n;
+    opus_int32 rc, tmp1, tmp2;
+
+    for( k = 0; k < order; k++ ) {
+        rc = rc_Q16[ k ];
+        for( n = 0; n < (k + 1) >> 1; n++ ) {
+            tmp1 = A_Q24[ n ];
+            tmp2 = A_Q24[ k - n - 1 ];
+            A_Q24[ n ]         = silk_SMLAWW( tmp1, tmp2, rc );
+            A_Q24[ k - n - 1 ] = silk_SMLAWW( tmp2, tmp1, rc );
+        }
+        A_Q24[ k ] = -silk_LSHIFT( rc, 8 );
+    }
+}
diff --git a/opus/silk/fixed/main_FIX.h b/opus/silk/fixed/main_FIX.h
new file mode 100644 (file)
index 0000000..780afa3
--- /dev/null
@@ -0,0 +1,243 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MAIN_FIX_H
+#define SILK_MAIN_FIX_H
+
+#include "SigProc_FIX.h"
+#include "structs_FIX.h"
+#include "control.h"
+#include "main.h"
+#include "PLC.h"
+#include "debug.h"
+#include "entenc.h"
+
+#if ((defined(OPUS_ARM_ASM) && defined(FIXED_POINT)) \
+   || defined(OPUS_ARM_MAY_HAVE_NEON_INTR))
+#include "fixed/arm/warped_autocorrelation_FIX_arm.h"
+#endif
+
+#ifndef FORCE_CPP_BUILD
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+#endif
+
+#define silk_encoder_state_Fxx      silk_encoder_state_FIX
+#define silk_encode_do_VAD_Fxx      silk_encode_do_VAD_FIX
+#define silk_encode_frame_Fxx       silk_encode_frame_FIX
+
+#define QC  10
+#define QS  13
+
+/*********************/
+/* Encoder Functions */
+/*********************/
+
+/* High-pass filter with cutoff frequency adaptation based on pitch lag statistics */
+void silk_HP_variable_cutoff(
+    silk_encoder_state_Fxx          state_Fxx[]                             /* I/O  Encoder states                                                              */
+);
+
+/* Encoder main function */
+void silk_encode_do_VAD_FIX(
+    silk_encoder_state_FIX          *psEnc                                  /* I/O  Pointer to Silk FIX encoder state                                           */
+);
+
+/* Encoder main function */
+opus_int silk_encode_frame_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    opus_int32                      *pnBytesOut,                            /* O    Pointer to number of payload bytes;                                         */
+    ec_enc                          *psRangeEnc,                            /* I/O  compressor data structure                                                   */
+    opus_int                        condCoding,                             /* I    The type of conditional coding to use                                       */
+    opus_int                        maxBits,                                /* I    If > 0: maximum number of output bits                                       */
+    opus_int                        useCBR                                  /* I    Flag to force constant-bitrate operation                                    */
+);
+
+/* Initializes the Silk encoder state */
+opus_int silk_init_encoder(
+    silk_encoder_state_Fxx          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+);
+
+/* Control the Silk encoder */
+opus_int silk_control_encoder(
+    silk_encoder_state_Fxx          *psEnc,                                 /* I/O  Pointer to Silk encoder state                                               */
+    silk_EncControlStruct           *encControl,                            /* I    Control structure                                                           */
+    const opus_int                  allow_bw_switch,                        /* I    Flag to allow switching audio bandwidth                                     */
+    const opus_int                  channelNb,                              /* I    Channel number                                                              */
+    const opus_int                  force_fs_kHz
+);
+
+/**************************/
+/* Noise shaping analysis */
+/**************************/
+/* Compute noise shaping coefficients and initial gain values */
+void silk_noise_shape_analysis_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Encoder state FIX                                                           */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Encoder control FIX                                                         */
+    const opus_int16                *pitch_res,                             /* I    LPC residual from pitch analysis                                            */
+    const opus_int16                *x,                                     /* I    Input signal [ frame_length + la_shape ]                                    */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+);
+
+/* Autocorrelations for a warped frequency axis */
+void silk_warped_autocorrelation_FIX_c(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order                                   /* I    Correlation order (even)                                                    */
+);
+
+#if !defined(OVERRIDE_silk_warped_autocorrelation_FIX)
+#define silk_warped_autocorrelation_FIX(corr, scale, input, warping_Q16, length, order, arch) \
+        ((void)(arch), silk_warped_autocorrelation_FIX_c(corr, scale, input, warping_Q16, length, order))
+#endif
+
+/* Calculation of LTP state scaling */
+void silk_LTP_scale_ctrl_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+);
+
+/**********************************************/
+/* Prediction Analysis                        */
+/**********************************************/
+/* Find pitch lags */
+void silk_find_pitch_lags_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    opus_int16                      res[],                                  /* O    residual                                                                    */
+    const opus_int16                x[],                                    /* I    Speech signal                                                               */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+);
+
+/* Find LPC and LTP coefficients */
+void silk_find_pred_coefs_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  encoder control                                                             */
+    const opus_int16                res_pitch[],                            /* I    Residual from pitch analysis                                                */
+    const opus_int16                x[],                                    /* I    Speech signal                                                               */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+);
+
+/* LPC analysis */
+void silk_find_LPC_FIX(
+    silk_encoder_state              *psEncC,                                /* I/O  Encoder state                                                               */
+    opus_int16                      NLSF_Q15[],                             /* O    NLSFs                                                                       */
+    const opus_int16                x[],                                    /* I    Input signal                                                                */
+    const opus_int32                minInvGain_Q30                          /* I    Inverse of max prediction gain                                              */
+);
+
+/* LTP analysis */
+void silk_find_LTP_FIX(
+    opus_int32                      XXLTP_Q17[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* O    Correlation matrix                                               */
+    opus_int32                      xXLTP_Q17[ MAX_NB_SUBFR * LTP_ORDER ],  /* O    Correlation vector                                                          */
+    const opus_int16                r_lpc[],                                /* I    Residual signal after LPC                                                   */
+    const opus_int                  lag[ MAX_NB_SUBFR ],                    /* I    LTP lags                                                                    */
+    const opus_int                  subfr_length,                           /* I    Subframe length                                                             */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+);
+
+void silk_LTP_analysis_filter_FIX(
+    opus_int16                      *LTP_res,                               /* O    LTP residual signal of length MAX_NB_SUBFR * ( pre_length + subfr_length )  */
+    const opus_int16                *x,                                     /* I    Pointer to input signal with at least max( pitchL ) preceding samples       */
+    const opus_int16                LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],/* I    LTP_ORDER LTP coefficients for each MAX_NB_SUBFR subframe                   */
+    const opus_int                  pitchL[ MAX_NB_SUBFR ],                 /* I    Pitch lag, one for each subframe                                            */
+    const opus_int32                invGains_Q16[ MAX_NB_SUBFR ],           /* I    Inverse quantization gains, one for each subframe                           */
+    const opus_int                  subfr_length,                           /* I    Length of each subframe                                                     */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    const opus_int                  pre_length                              /* I    Length of the preceding samples starting at &x[0] for each subframe         */
+);
+
+/* Calculates residual energies of input subframes where all subframes have LPC_order   */
+/* of preceding samples                                                                 */
+void silk_residual_energy_FIX(
+          opus_int32                nrgs[ MAX_NB_SUBFR ],                   /* O    Residual energy per subframe                                                */
+          opus_int                  nrgsQ[ MAX_NB_SUBFR ],                  /* O    Q value per subframe                                                        */
+    const opus_int16                x[],                                    /* I    Input signal                                                                */
+          opus_int16                a_Q12[ 2 ][ MAX_LPC_ORDER ],            /* I    AR coefs for each frame half                                                */
+    const opus_int32                gains[ MAX_NB_SUBFR ],                  /* I    Quantization gains                                                          */
+    const opus_int                  subfr_length,                           /* I    Subframe length                                                             */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    const opus_int                  LPC_order,                              /* I    LPC order                                                                   */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+);
+
+/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */
+opus_int32 silk_residual_energy16_covar_FIX(
+    const opus_int16                *c,                                     /* I    Prediction vector                                                           */
+    const opus_int32                *wXX,                                   /* I    Correlation matrix                                                          */
+    const opus_int32                *wXx,                                   /* I    Correlation vector                                                          */
+    opus_int32                      wxx,                                    /* I    Signal energy                                                               */
+    opus_int                        D,                                      /* I    Dimension                                                                   */
+    opus_int                        cQ                                      /* I    Q value for c vector 0 - 15                                                 */
+);
+
+/* Processing of gains */
+void silk_process_gains_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Encoder control                                                             */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+);
+
+/******************/
+/* Linear Algebra */
+/******************/
+/* Calculates correlation matrix X'*X */
+void silk_corrMatrix_FIX(
+    const opus_int16                *x,                                     /* I    x vector [L + order - 1] used to form data matrix X                         */
+    const opus_int                  L,                                      /* I    Length of vectors                                                           */
+    const opus_int                  order,                                  /* I    Max lag for correlation                                                     */
+    opus_int32                      *XX,                                    /* O    Pointer to X'*X correlation matrix [ order x order ]                        */
+    opus_int32                      *nrg,                                   /* O    Energy of x vector                                                          */
+    opus_int                        *rshifts,                               /* O    Right shifts of correlations                                                */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+);
+
+/* Calculates correlation vector X'*t */
+void silk_corrVector_FIX(
+    const opus_int16                *x,                                     /* I    x vector [L + order - 1] used to form data matrix X                         */
+    const opus_int16                *t,                                     /* I    Target vector [L]                                                           */
+    const opus_int                  L,                                      /* I    Length of vectors                                                           */
+    const opus_int                  order,                                  /* I    Max lag for correlation                                                     */
+    opus_int32                      *Xt,                                    /* O    Pointer to X'*t correlation vector [order]                                  */
+    const opus_int                  rshifts,                                /* I    Right shifts of correlations                                                */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+);
+
+#ifndef FORCE_CPP_BUILD
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* FORCE_CPP_BUILD */
+#endif /* SILK_MAIN_FIX_H */
diff --git a/opus/silk/fixed/mips/noise_shape_analysis_FIX_mipsr1.h b/opus/silk/fixed/mips/noise_shape_analysis_FIX_mipsr1.h
new file mode 100644 (file)
index 0000000..3999b5b
--- /dev/null
@@ -0,0 +1,336 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+
+/**************************************************************/
+/* Compute noise shaping coefficients and initial gain values */
+/**************************************************************/
+#define OVERRIDE_silk_noise_shape_analysis_FIX
+
+void silk_noise_shape_analysis_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Encoder state FIX                                                           */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Encoder control FIX                                                         */
+    const opus_int16                *pitch_res,                             /* I    LPC residual from pitch analysis                                            */
+    const opus_int16                *x,                                     /* I    Input signal [ frame_length + la_shape ]                                    */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+)
+{
+    silk_shape_state_FIX *psShapeSt = &psEnc->sShape;
+    opus_int     k, i, nSamples, Qnrg, b_Q14, warping_Q16, scale = 0;
+    opus_int32   SNR_adj_dB_Q7, HarmBoost_Q16, HarmShapeGain_Q16, Tilt_Q16, tmp32;
+    opus_int32   nrg, pre_nrg_Q30, log_energy_Q7, log_energy_prev_Q7, energy_variation_Q7;
+    opus_int32   delta_Q16, BWExp1_Q16, BWExp2_Q16, gain_mult_Q16, gain_add_Q16, strength_Q16, b_Q8;
+    opus_int32   auto_corr[     MAX_SHAPE_LPC_ORDER + 1 ];
+    opus_int32   refl_coef_Q16[ MAX_SHAPE_LPC_ORDER ];
+    opus_int32   AR1_Q24[       MAX_SHAPE_LPC_ORDER ];
+    opus_int32   AR2_Q24[       MAX_SHAPE_LPC_ORDER ];
+    VARDECL( opus_int16, x_windowed );
+    const opus_int16 *x_ptr, *pitch_res_ptr;
+    SAVE_STACK;
+
+    /* Point to start of first LPC analysis block */
+    x_ptr = x - psEnc->sCmn.la_shape;
+
+    /****************/
+    /* GAIN CONTROL */
+    /****************/
+    SNR_adj_dB_Q7 = psEnc->sCmn.SNR_dB_Q7;
+
+    /* Input quality is the average of the quality in the lowest two VAD bands */
+    psEncCtrl->input_quality_Q14 = ( opus_int )silk_RSHIFT( (opus_int32)psEnc->sCmn.input_quality_bands_Q15[ 0 ]
+        + psEnc->sCmn.input_quality_bands_Q15[ 1 ], 2 );
+
+    /* Coding quality level, between 0.0_Q0 and 1.0_Q0, but in Q14 */
+    psEncCtrl->coding_quality_Q14 = silk_RSHIFT( silk_sigm_Q15( silk_RSHIFT_ROUND( SNR_adj_dB_Q7 -
+        SILK_FIX_CONST( 20.0, 7 ), 4 ) ), 1 );
+
+    /* Reduce coding SNR during low speech activity */
+    if( psEnc->sCmn.useCBR == 0 ) {
+        b_Q8 = SILK_FIX_CONST( 1.0, 8 ) - psEnc->sCmn.speech_activity_Q8;
+        b_Q8 = silk_SMULWB( silk_LSHIFT( b_Q8, 8 ), b_Q8 );
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7,
+            silk_SMULBB( SILK_FIX_CONST( -BG_SNR_DECR_dB, 7 ) >> ( 4 + 1 ), b_Q8 ),                                       /* Q11*/
+            silk_SMULWB( SILK_FIX_CONST( 1.0, 14 ) + psEncCtrl->input_quality_Q14, psEncCtrl->coding_quality_Q14 ) );     /* Q12*/
+    }
+
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce gains for periodic signals */
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7, SILK_FIX_CONST( HARM_SNR_INCR_dB, 8 ), psEnc->LTPCorr_Q15 );
+    } else {
+        /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7,
+            silk_SMLAWB( SILK_FIX_CONST( 6.0, 9 ), -SILK_FIX_CONST( 0.4, 18 ), psEnc->sCmn.SNR_dB_Q7 ),
+            SILK_FIX_CONST( 1.0, 14 ) - psEncCtrl->input_quality_Q14 );
+    }
+
+    /*************************/
+    /* SPARSENESS PROCESSING */
+    /*************************/
+    /* Set quantizer offset */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Initially set to 0; may be overruled in process_gains(..) */
+        psEnc->sCmn.indices.quantOffsetType = 0;
+        psEncCtrl->sparseness_Q8 = 0;
+    } else {
+        /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */
+        nSamples = silk_LSHIFT( psEnc->sCmn.fs_kHz, 1 );
+        energy_variation_Q7 = 0;
+        log_energy_prev_Q7  = 0;
+        pitch_res_ptr = pitch_res;
+        for( k = 0; k < silk_SMULBB( SUB_FRAME_LENGTH_MS, psEnc->sCmn.nb_subfr ) / 2; k++ ) {
+            silk_sum_sqr_shift( &nrg, &scale, pitch_res_ptr, nSamples );
+            nrg += silk_RSHIFT( nSamples, scale );           /* Q(-scale)*/
+
+            log_energy_Q7 = silk_lin2log( nrg );
+            if( k > 0 ) {
+                energy_variation_Q7 += silk_abs( log_energy_Q7 - log_energy_prev_Q7 );
+            }
+            log_energy_prev_Q7 = log_energy_Q7;
+            pitch_res_ptr += nSamples;
+        }
+
+        psEncCtrl->sparseness_Q8 = silk_RSHIFT( silk_sigm_Q15( silk_SMULWB( energy_variation_Q7 -
+            SILK_FIX_CONST( 5.0, 7 ), SILK_FIX_CONST( 0.1, 16 ) ) ), 7 );
+
+        /* Set quantization offset depending on sparseness measure */
+        if( psEncCtrl->sparseness_Q8 > SILK_FIX_CONST( SPARSENESS_THRESHOLD_QNT_OFFSET, 8 ) ) {
+            psEnc->sCmn.indices.quantOffsetType = 0;
+        } else {
+            psEnc->sCmn.indices.quantOffsetType = 1;
+        }
+
+        /* Increase coding SNR for sparse signals */
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7, SILK_FIX_CONST( SPARSE_SNR_INCR_dB, 15 ), psEncCtrl->sparseness_Q8 - SILK_FIX_CONST( 0.5, 8 ) );
+    }
+
+    /*******************************/
+    /* Control bandwidth expansion */
+    /*******************************/
+    /* More BWE for signals with high prediction gain */
+    strength_Q16 = silk_SMULWB( psEncCtrl->predGain_Q16, SILK_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) );
+    BWExp1_Q16 = BWExp2_Q16 = silk_DIV32_varQ( SILK_FIX_CONST( BANDWIDTH_EXPANSION, 16 ),
+        silk_SMLAWW( SILK_FIX_CONST( 1.0, 16 ), strength_Q16, strength_Q16 ), 16 );
+    delta_Q16  = silk_SMULWB( SILK_FIX_CONST( 1.0, 16 ) - silk_SMULBB( 3, psEncCtrl->coding_quality_Q14 ),
+        SILK_FIX_CONST( LOW_RATE_BANDWIDTH_EXPANSION_DELTA, 16 ) );
+    BWExp1_Q16 = silk_SUB32( BWExp1_Q16, delta_Q16 );
+    BWExp2_Q16 = silk_ADD32( BWExp2_Q16, delta_Q16 );
+    /* BWExp1 will be applied after BWExp2, so make it relative */
+    BWExp1_Q16 = silk_DIV32_16( silk_LSHIFT( BWExp1_Q16, 14 ), silk_RSHIFT( BWExp2_Q16, 2 ) );
+
+    if( psEnc->sCmn.warping_Q16 > 0 ) {
+        /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */
+        warping_Q16 = silk_SMLAWB( psEnc->sCmn.warping_Q16, (opus_int32)psEncCtrl->coding_quality_Q14, SILK_FIX_CONST( 0.01, 18 ) );
+    } else {
+        warping_Q16 = 0;
+    }
+
+    /********************************************/
+    /* Compute noise shaping AR coefs and gains */
+    /********************************************/
+    ALLOC( x_windowed, psEnc->sCmn.shapeWinLength, opus_int16 );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        /* Apply window: sine slope followed by flat part followed by cosine slope */
+        opus_int shift, slope_part, flat_part;
+        flat_part = psEnc->sCmn.fs_kHz * 3;
+        slope_part = silk_RSHIFT( psEnc->sCmn.shapeWinLength - flat_part, 1 );
+
+        silk_apply_sine_window( x_windowed, x_ptr, 1, slope_part );
+        shift = slope_part;
+        silk_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(opus_int16) );
+        shift += flat_part;
+        silk_apply_sine_window( x_windowed + shift, x_ptr + shift, 2, slope_part );
+
+        /* Update pointer: next LPC analysis block */
+        x_ptr += psEnc->sCmn.subfr_length;
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Calculate warped auto correlation */
+            silk_warped_autocorrelation_FIX( auto_corr, &scale, x_windowed, warping_Q16, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder, arch );
+        } else {
+            /* Calculate regular auto correlation */
+            silk_autocorr( auto_corr, &scale, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1, arch );
+        }
+
+        /* Add white noise, as a fraction of energy */
+        auto_corr[0] = silk_ADD32( auto_corr[0], silk_max_32( silk_SMULWB( silk_RSHIFT( auto_corr[ 0 ], 4 ),
+            SILK_FIX_CONST( SHAPE_WHITE_NOISE_FRACTION, 20 ) ), 1 ) );
+
+        /* Calculate the reflection coefficients using schur */
+        nrg = silk_schur64( refl_coef_Q16, auto_corr, psEnc->sCmn.shapingLPCOrder );
+        silk_assert( nrg >= 0 );
+
+        /* Convert reflection coefficients to prediction coefficients */
+        silk_k2a_Q16( AR2_Q24, refl_coef_Q16, psEnc->sCmn.shapingLPCOrder );
+
+        Qnrg = -scale;          /* range: -12...30*/
+        silk_assert( Qnrg >= -12 );
+        silk_assert( Qnrg <=  30 );
+
+        /* Make sure that Qnrg is an even number */
+        if( Qnrg & 1 ) {
+            Qnrg -= 1;
+            nrg >>= 1;
+        }
+
+        tmp32 = silk_SQRT_APPROX( nrg );
+        Qnrg >>= 1;             /* range: -6...15*/
+
+        psEncCtrl->Gains_Q16[ k ] = (silk_LSHIFT32( silk_LIMIT( (tmp32), silk_RSHIFT32( silk_int32_MIN, (16 - Qnrg) ), \
+                            silk_RSHIFT32( silk_int32_MAX, (16 - Qnrg) ) ), (16 - Qnrg) ));
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Adjust gain for warping */
+            gain_mult_Q16 = warped_gain( AR2_Q24, warping_Q16, psEnc->sCmn.shapingLPCOrder );
+            silk_assert( psEncCtrl->Gains_Q16[ k ] >= 0 );
+            if ( silk_SMULWW( silk_RSHIFT_ROUND( psEncCtrl->Gains_Q16[ k ], 1 ), gain_mult_Q16 ) >= ( silk_int32_MAX >> 1 ) ) {
+               psEncCtrl->Gains_Q16[ k ] = silk_int32_MAX;
+            } else {
+               psEncCtrl->Gains_Q16[ k ] = silk_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );
+            }
+        }
+
+        /* Bandwidth expansion for synthesis filter shaping */
+        silk_bwexpander_32( AR2_Q24, psEnc->sCmn.shapingLPCOrder, BWExp2_Q16 );
+
+        /* Compute noise shaping filter coefficients */
+        silk_memcpy( AR1_Q24, AR2_Q24, psEnc->sCmn.shapingLPCOrder * sizeof( opus_int32 ) );
+
+        /* Bandwidth expansion for analysis filter shaping */
+        silk_assert( BWExp1_Q16 <= SILK_FIX_CONST( 1.0, 16 ) );
+        silk_bwexpander_32( AR1_Q24, psEnc->sCmn.shapingLPCOrder, BWExp1_Q16 );
+
+        /* Ratio of prediction gains, in energy domain */
+        pre_nrg_Q30 = silk_LPC_inverse_pred_gain_Q24( AR2_Q24, psEnc->sCmn.shapingLPCOrder, arch );
+        nrg         = silk_LPC_inverse_pred_gain_Q24( AR1_Q24, psEnc->sCmn.shapingLPCOrder, arch );
+
+        /*psEncCtrl->GainsPre[ k ] = 1.0f - 0.7f * ( 1.0f - pre_nrg / nrg ) = 0.3f + 0.7f * pre_nrg / nrg;*/
+        pre_nrg_Q30 = silk_LSHIFT32( silk_SMULWB( pre_nrg_Q30, SILK_FIX_CONST( 0.7, 15 ) ), 1 );
+        psEncCtrl->GainsPre_Q14[ k ] = ( opus_int ) SILK_FIX_CONST( 0.3, 14 ) + silk_DIV32_varQ( pre_nrg_Q30, nrg, 14 );
+
+        /* Convert to monic warped prediction coefficients and limit absolute values */
+        limit_warped_coefs( AR2_Q24, AR1_Q24, warping_Q16, SILK_FIX_CONST( 3.999, 24 ), psEnc->sCmn.shapingLPCOrder );
+
+        /* Convert from Q24 to Q13 and store in int16 */
+        for( i = 0; i < psEnc->sCmn.shapingLPCOrder; i++ ) {
+            psEncCtrl->AR1_Q13[ k * MAX_SHAPE_LPC_ORDER + i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( AR1_Q24[ i ], 11 ) );
+            psEncCtrl->AR2_Q13[ k * MAX_SHAPE_LPC_ORDER + i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( AR2_Q24[ i ], 11 ) );
+        }
+    }
+
+    /*****************/
+    /* Gain tweaking */
+    /*****************/
+    /* Increase gains during low speech activity and put lower limit on gains */
+    gain_mult_Q16 = silk_log2lin( -silk_SMLAWB( -SILK_FIX_CONST( 16.0, 7 ), SNR_adj_dB_Q7, SILK_FIX_CONST( 0.16, 16 ) ) );
+    gain_add_Q16  = silk_log2lin(  silk_SMLAWB(  SILK_FIX_CONST( 16.0, 7 ), SILK_FIX_CONST( MIN_QGAIN_DB, 7 ), SILK_FIX_CONST( 0.16, 16 ) ) );
+    silk_assert( gain_mult_Q16 > 0 );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psEncCtrl->Gains_Q16[ k ] = silk_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );
+        silk_assert( psEncCtrl->Gains_Q16[ k ] >= 0 );
+        psEncCtrl->Gains_Q16[ k ] = silk_ADD_POS_SAT32( psEncCtrl->Gains_Q16[ k ], gain_add_Q16 );
+    }
+
+    gain_mult_Q16 = SILK_FIX_CONST( 1.0, 16 ) + silk_RSHIFT_ROUND( silk_MLA( SILK_FIX_CONST( INPUT_TILT, 26 ),
+        psEncCtrl->coding_quality_Q14, SILK_FIX_CONST( HIGH_RATE_INPUT_TILT, 12 ) ), 10 );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psEncCtrl->GainsPre_Q14[ k ] = silk_SMULWB( gain_mult_Q16, psEncCtrl->GainsPre_Q14[ k ] );
+    }
+
+    /************************************************/
+    /* Control low-frequency shaping and noise tilt */
+    /************************************************/
+    /* Less low frequency shaping for noisy inputs */
+    strength_Q16 = silk_MUL( SILK_FIX_CONST( LOW_FREQ_SHAPING, 4 ), silk_SMLAWB( SILK_FIX_CONST( 1.0, 12 ),
+        SILK_FIX_CONST( LOW_QUALITY_LOW_FREQ_SHAPING_DECR, 13 ), psEnc->sCmn.input_quality_bands_Q15[ 0 ] - SILK_FIX_CONST( 1.0, 15 ) ) );
+    strength_Q16 = silk_RSHIFT( silk_MUL( strength_Q16, psEnc->sCmn.speech_activity_Q8 ), 8 );
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */
+        /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/
+        opus_int fs_kHz_inv = silk_DIV32_16( SILK_FIX_CONST( 0.2, 14 ), psEnc->sCmn.fs_kHz );
+        for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+            b_Q14 = fs_kHz_inv + silk_DIV32_16( SILK_FIX_CONST( 3.0, 14 ), psEncCtrl->pitchL[ k ] );
+            /* Pack two coefficients in one int32 */
+            psEncCtrl->LF_shp_Q14[ k ]  = silk_LSHIFT( SILK_FIX_CONST( 1.0, 14 ) - b_Q14 - silk_SMULWB( strength_Q16, b_Q14 ), 16 );
+            psEncCtrl->LF_shp_Q14[ k ] |= (opus_uint16)( b_Q14 - SILK_FIX_CONST( 1.0, 14 ) );
+        }
+        silk_assert( SILK_FIX_CONST( HARM_HP_NOISE_COEF, 24 ) < SILK_FIX_CONST( 0.5, 24 ) ); /* Guarantees that second argument to SMULWB() is within range of an opus_int16*/
+        Tilt_Q16 = - SILK_FIX_CONST( HP_NOISE_COEF, 16 ) -
+            silk_SMULWB( SILK_FIX_CONST( 1.0, 16 ) - SILK_FIX_CONST( HP_NOISE_COEF, 16 ),
+                silk_SMULWB( SILK_FIX_CONST( HARM_HP_NOISE_COEF, 24 ), psEnc->sCmn.speech_activity_Q8 ) );
+    } else {
+        b_Q14 = silk_DIV32_16( 21299, psEnc->sCmn.fs_kHz ); /* 1.3_Q0 = 21299_Q14*/
+        /* Pack two coefficients in one int32 */
+        psEncCtrl->LF_shp_Q14[ 0 ]  = silk_LSHIFT( SILK_FIX_CONST( 1.0, 14 ) - b_Q14 -
+            silk_SMULWB( strength_Q16, silk_SMULWB( SILK_FIX_CONST( 0.6, 16 ), b_Q14 ) ), 16 );
+        psEncCtrl->LF_shp_Q14[ 0 ] |= (opus_uint16)( b_Q14 - SILK_FIX_CONST( 1.0, 14 ) );
+        for( k = 1; k < psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->LF_shp_Q14[ k ] = psEncCtrl->LF_shp_Q14[ 0 ];
+        }
+        Tilt_Q16 = -SILK_FIX_CONST( HP_NOISE_COEF, 16 );
+    }
+
+    /****************************/
+    /* HARMONIC SHAPING CONTROL */
+    /****************************/
+    /* Control boosting of harmonic frequencies */
+    HarmBoost_Q16 = silk_SMULWB( silk_SMULWB( SILK_FIX_CONST( 1.0, 17 ) - silk_LSHIFT( psEncCtrl->coding_quality_Q14, 3 ),
+        psEnc->LTPCorr_Q15 ), SILK_FIX_CONST( LOW_RATE_HARMONIC_BOOST, 16 ) );
+
+    /* More harmonic boost for noisy input signals */
+    HarmBoost_Q16 = silk_SMLAWB( HarmBoost_Q16,
+        SILK_FIX_CONST( 1.0, 16 ) - silk_LSHIFT( psEncCtrl->input_quality_Q14, 2 ), SILK_FIX_CONST( LOW_INPUT_QUALITY_HARMONIC_BOOST, 16 ) );
+
+    if( USE_HARM_SHAPING && psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* More harmonic noise shaping for high bitrates or noisy input */
+        HarmShapeGain_Q16 = silk_SMLAWB( SILK_FIX_CONST( HARMONIC_SHAPING, 16 ),
+                SILK_FIX_CONST( 1.0, 16 ) - silk_SMULWB( SILK_FIX_CONST( 1.0, 18 ) - silk_LSHIFT( psEncCtrl->coding_quality_Q14, 4 ),
+                psEncCtrl->input_quality_Q14 ), SILK_FIX_CONST( HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING, 16 ) );
+
+        /* Less harmonic noise shaping for less periodic signals */
+        HarmShapeGain_Q16 = silk_SMULWB( silk_LSHIFT( HarmShapeGain_Q16, 1 ),
+            silk_SQRT_APPROX( silk_LSHIFT( psEnc->LTPCorr_Q15, 15 ) ) );
+    } else {
+        HarmShapeGain_Q16 = 0;
+    }
+
+    /*************************/
+    /* Smooth over subframes */
+    /*************************/
+    for( k = 0; k < MAX_NB_SUBFR; k++ ) {
+        psShapeSt->HarmBoost_smth_Q16 =
+            silk_SMLAWB( psShapeSt->HarmBoost_smth_Q16,     HarmBoost_Q16     - psShapeSt->HarmBoost_smth_Q16,     SILK_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );
+        psShapeSt->HarmShapeGain_smth_Q16 =
+            silk_SMLAWB( psShapeSt->HarmShapeGain_smth_Q16, HarmShapeGain_Q16 - psShapeSt->HarmShapeGain_smth_Q16, SILK_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );
+        psShapeSt->Tilt_smth_Q16 =
+            silk_SMLAWB( psShapeSt->Tilt_smth_Q16,          Tilt_Q16          - psShapeSt->Tilt_smth_Q16,          SILK_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );
+
+        psEncCtrl->HarmBoost_Q14[ k ]     = ( opus_int )silk_RSHIFT_ROUND( psShapeSt->HarmBoost_smth_Q16,     2 );
+        psEncCtrl->HarmShapeGain_Q14[ k ] = ( opus_int )silk_RSHIFT_ROUND( psShapeSt->HarmShapeGain_smth_Q16, 2 );
+        psEncCtrl->Tilt_Q14[ k ]          = ( opus_int )silk_RSHIFT_ROUND( psShapeSt->Tilt_smth_Q16,          2 );
+    }
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/mips/warped_autocorrelation_FIX_mipsr1.h b/opus/silk/fixed/mips/warped_autocorrelation_FIX_mipsr1.h
new file mode 100644 (file)
index 0000000..fcbd96c
--- /dev/null
@@ -0,0 +1,166 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 __WARPED_AUTOCORRELATION_FIX_MIPSR1_H__
+#define __WARPED_AUTOCORRELATION_FIX_MIPSR1_H__
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+#undef QC
+#define QC  10
+
+#undef QS
+#define QS  14
+
+/* Autocorrelations for a warped frequency axis */
+#define OVERRIDE_silk_warped_autocorrelation_FIX
+void silk_warped_autocorrelation_FIX(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order,                                  /* I    Correlation order (even)                                                    */
+    int                             arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int   n, i, lsh;
+    opus_int32 tmp1_QS=0, tmp2_QS=0, tmp3_QS=0, tmp4_QS=0, tmp5_QS=0, tmp6_QS=0, tmp7_QS=0, tmp8_QS=0, start_1=0, start_2=0, start_3=0;
+    opus_int32 state_QS[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
+    opus_int64 corr_QC[  MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
+    opus_int64 temp64;
+
+    opus_int32 val;
+    val = 2 * QS - QC;
+
+    /* Order must be even */
+    silk_assert( ( order & 1 ) == 0 );
+    silk_assert( 2 * QS - QC >= 0 );
+
+    /* Loop over samples */
+    for( n = 0; n < length; n=n+4 ) {
+
+        tmp1_QS = silk_LSHIFT32( (opus_int32)input[ n ], QS );
+        start_1 = tmp1_QS;
+        tmp3_QS = silk_LSHIFT32( (opus_int32)input[ n+1], QS );
+        start_2 = tmp3_QS;
+        tmp5_QS = silk_LSHIFT32( (opus_int32)input[ n+2], QS );
+        start_3 = tmp5_QS;
+        tmp7_QS = silk_LSHIFT32( (opus_int32)input[ n+3], QS );
+
+        /* Loop over allpass sections */
+        for( i = 0; i < order; i += 2 ) {
+            /* Output of allpass section */
+            tmp2_QS = silk_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );
+            corr_QC[  i ] = __builtin_mips_madd( corr_QC[  i ], tmp1_QS,  start_1);
+
+            tmp4_QS = silk_SMLAWB( tmp1_QS, tmp2_QS - tmp3_QS, warping_Q16 );
+            corr_QC[  i ] = __builtin_mips_madd( corr_QC[  i ], tmp3_QS,  start_2);
+
+            tmp6_QS = silk_SMLAWB( tmp3_QS, tmp4_QS - tmp5_QS, warping_Q16 );
+            corr_QC[  i ] = __builtin_mips_madd( corr_QC[  i ], tmp5_QS,  start_3);
+
+            tmp8_QS = silk_SMLAWB( tmp5_QS, tmp6_QS - tmp7_QS, warping_Q16 );
+            state_QS[ i ]  = tmp7_QS;
+            corr_QC[  i ] = __builtin_mips_madd( corr_QC[  i ], tmp7_QS, state_QS[0]);
+
+            /* Output of allpass section */
+            tmp1_QS = silk_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );
+            corr_QC[  i+1 ] = __builtin_mips_madd( corr_QC[  i+1 ], tmp2_QS,  start_1);
+
+            tmp3_QS = silk_SMLAWB( tmp2_QS, tmp1_QS - tmp4_QS, warping_Q16 );
+            corr_QC[  i+1 ] = __builtin_mips_madd( corr_QC[  i+1 ], tmp4_QS,  start_2);
+
+            tmp5_QS = silk_SMLAWB( tmp4_QS, tmp3_QS - tmp6_QS, warping_Q16 );
+            corr_QC[  i+1 ] = __builtin_mips_madd( corr_QC[  i+1 ], tmp6_QS,  start_3);
+
+            tmp7_QS = silk_SMLAWB( tmp6_QS, tmp5_QS - tmp8_QS, warping_Q16 );
+            state_QS[ i + 1 ]  = tmp8_QS;
+            corr_QC[  i+1 ] = __builtin_mips_madd( corr_QC[  i+1 ], tmp8_QS,  state_QS[ 0 ]);
+
+        }
+        state_QS[ order ] = tmp7_QS;
+
+        corr_QC[  order ] = __builtin_mips_madd( corr_QC[  order ], tmp1_QS,  start_1);
+        corr_QC[  order ] = __builtin_mips_madd( corr_QC[  order ], tmp3_QS,  start_2);
+        corr_QC[  order ] = __builtin_mips_madd( corr_QC[  order ], tmp5_QS,  start_3);
+        corr_QC[  order ] = __builtin_mips_madd( corr_QC[  order ], tmp7_QS,  state_QS[ 0 ]);
+    }
+
+    for(;n< length; n++ ) {
+
+        tmp1_QS = silk_LSHIFT32( (opus_int32)input[ n ], QS );
+
+        /* Loop over allpass sections */
+        for( i = 0; i < order; i += 2 ) {
+
+            /* Output of allpass section */
+            tmp2_QS = silk_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );
+            state_QS[ i ] = tmp1_QS;
+            corr_QC[  i ] = __builtin_mips_madd( corr_QC[  i ], tmp1_QS,   state_QS[ 0 ]);
+
+            /* Output of allpass section */
+            tmp1_QS = silk_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );
+            state_QS[ i + 1 ]  = tmp2_QS;
+            corr_QC[  i+1 ] = __builtin_mips_madd( corr_QC[  i+1 ], tmp2_QS,   state_QS[ 0 ]);
+        }
+        state_QS[ order ] = tmp1_QS;
+        corr_QC[  order ] = __builtin_mips_madd( corr_QC[  order ], tmp1_QS,   state_QS[ 0 ]);
+    }
+
+    temp64 =  corr_QC[ 0 ];
+    temp64 = __builtin_mips_shilo(temp64, val);
+
+    lsh = silk_CLZ64( temp64 ) - 35;
+    lsh = silk_LIMIT( lsh, -12 - QC, 30 - QC );
+    *scale = -( QC + lsh );
+    silk_assert( *scale >= -30 && *scale <= 12 );
+    if( lsh >= 0 ) {
+        for( i = 0; i < order + 1; i++ ) {
+            temp64 = corr_QC[ i ];
+            //temp64 = __builtin_mips_shilo(temp64, val);
+            temp64 = (val >= 0) ? (temp64 >> val) : (temp64 << -val);
+            corr[ i ] = (opus_int32)silk_CHECK_FIT32( __builtin_mips_shilo( temp64, -lsh ) );
+        }
+    } else {
+        for( i = 0; i < order + 1; i++ ) {
+            temp64 = corr_QC[ i ];
+            //temp64 = __builtin_mips_shilo(temp64, val);
+            temp64 = (val >= 0) ? (temp64 >> val) : (temp64 << -val);
+            corr[ i ] = (opus_int32)silk_CHECK_FIT32( __builtin_mips_shilo( temp64, -lsh ) );
+        }
+    }
+
+     corr_QC[ 0 ] = __builtin_mips_shilo(corr_QC[ 0 ], val);
+
+     silk_assert( corr_QC[ 0 ] >= 0 ); /* If breaking, decrease QC*/
+}
+#endif /* __WARPED_AUTOCORRELATION_FIX_MIPSR1_H__ */
diff --git a/opus/silk/fixed/noise_shape_analysis_FIX.c b/opus/silk/fixed/noise_shape_analysis_FIX.c
new file mode 100644 (file)
index 0000000..85fea0b
--- /dev/null
@@ -0,0 +1,407 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "stack_alloc.h"
+#include "tuning_parameters.h"
+
+/* Compute gain to make warped filter coefficients have a zero mean log frequency response on a   */
+/* non-warped frequency scale. (So that it can be implemented with a minimum-phase monic filter.) */
+/* Note: A monic filter is one with the first coefficient equal to 1.0. In Silk we omit the first */
+/* coefficient in an array of coefficients, for monic filters.                                    */
+static OPUS_INLINE opus_int32 warped_gain( /* gain in Q16*/
+    const opus_int32     *coefs_Q24,
+    opus_int             lambda_Q16,
+    opus_int             order
+) {
+    opus_int   i;
+    opus_int32 gain_Q24;
+
+    lambda_Q16 = -lambda_Q16;
+    gain_Q24 = coefs_Q24[ order - 1 ];
+    for( i = order - 2; i >= 0; i-- ) {
+        gain_Q24 = silk_SMLAWB( coefs_Q24[ i ], gain_Q24, lambda_Q16 );
+    }
+    gain_Q24  = silk_SMLAWB( SILK_FIX_CONST( 1.0, 24 ), gain_Q24, -lambda_Q16 );
+    return silk_INVERSE32_varQ( gain_Q24, 40 );
+}
+
+/* Convert warped filter coefficients to monic pseudo-warped coefficients and limit maximum     */
+/* amplitude of monic warped coefficients by using bandwidth expansion on the true coefficients */
+static OPUS_INLINE void limit_warped_coefs(
+    opus_int32           *coefs_Q24,
+    opus_int             lambda_Q16,
+    opus_int32           limit_Q24,
+    opus_int             order
+) {
+    opus_int   i, iter, ind = 0;
+    opus_int32 tmp, maxabs_Q24, chirp_Q16, gain_Q16;
+    opus_int32 nom_Q16, den_Q24;
+    opus_int32 limit_Q20, maxabs_Q20;
+
+    /* Convert to monic coefficients */
+    lambda_Q16 = -lambda_Q16;
+    for( i = order - 1; i > 0; i-- ) {
+        coefs_Q24[ i - 1 ] = silk_SMLAWB( coefs_Q24[ i - 1 ], coefs_Q24[ i ], lambda_Q16 );
+    }
+    lambda_Q16 = -lambda_Q16;
+    nom_Q16  = silk_SMLAWB( SILK_FIX_CONST( 1.0, 16 ), -(opus_int32)lambda_Q16, lambda_Q16 );
+    den_Q24  = silk_SMLAWB( SILK_FIX_CONST( 1.0, 24 ), coefs_Q24[ 0 ], lambda_Q16 );
+    gain_Q16 = silk_DIV32_varQ( nom_Q16, den_Q24, 24 );
+    for( i = 0; i < order; i++ ) {
+        coefs_Q24[ i ] = silk_SMULWW( gain_Q16, coefs_Q24[ i ] );
+    }
+    limit_Q20 = silk_RSHIFT(limit_Q24, 4);
+    for( iter = 0; iter < 10; iter++ ) {
+        /* Find maximum absolute value */
+        maxabs_Q24 = -1;
+        for( i = 0; i < order; i++ ) {
+            tmp = silk_abs_int32( coefs_Q24[ i ] );
+            if( tmp > maxabs_Q24 ) {
+                maxabs_Q24 = tmp;
+                ind = i;
+            }
+        }
+        /* Use Q20 to avoid any overflow when multiplying by (ind + 1) later. */
+        maxabs_Q20 = silk_RSHIFT(maxabs_Q24, 4);
+        if( maxabs_Q20 <= limit_Q20 ) {
+            /* Coefficients are within range - done */
+            return;
+        }
+
+        /* Convert back to true warped coefficients */
+        for( i = 1; i < order; i++ ) {
+            coefs_Q24[ i - 1 ] = silk_SMLAWB( coefs_Q24[ i - 1 ], coefs_Q24[ i ], lambda_Q16 );
+        }
+        gain_Q16 = silk_INVERSE32_varQ( gain_Q16, 32 );
+        for( i = 0; i < order; i++ ) {
+            coefs_Q24[ i ] = silk_SMULWW( gain_Q16, coefs_Q24[ i ] );
+        }
+
+        /* Apply bandwidth expansion */
+        chirp_Q16 = SILK_FIX_CONST( 0.99, 16 ) - silk_DIV32_varQ(
+            silk_SMULWB( maxabs_Q20 - limit_Q20, silk_SMLABB( SILK_FIX_CONST( 0.8, 10 ), SILK_FIX_CONST( 0.1, 10 ), iter ) ),
+            silk_MUL( maxabs_Q20, ind + 1 ), 22 );
+        silk_bwexpander_32( coefs_Q24, order, chirp_Q16 );
+
+        /* Convert to monic warped coefficients */
+        lambda_Q16 = -lambda_Q16;
+        for( i = order - 1; i > 0; i-- ) {
+            coefs_Q24[ i - 1 ] = silk_SMLAWB( coefs_Q24[ i - 1 ], coefs_Q24[ i ], lambda_Q16 );
+        }
+        lambda_Q16 = -lambda_Q16;
+        nom_Q16  = silk_SMLAWB( SILK_FIX_CONST( 1.0, 16 ), -(opus_int32)lambda_Q16,        lambda_Q16 );
+        den_Q24  = silk_SMLAWB( SILK_FIX_CONST( 1.0, 24 ), coefs_Q24[ 0 ], lambda_Q16 );
+        gain_Q16 = silk_DIV32_varQ( nom_Q16, den_Q24, 24 );
+        for( i = 0; i < order; i++ ) {
+            coefs_Q24[ i ] = silk_SMULWW( gain_Q16, coefs_Q24[ i ] );
+        }
+    }
+    silk_assert( 0 );
+}
+
+/* Disable MIPS version until it's updated. */
+#if 0 && defined(MIPSr1_ASM)
+#include "mips/noise_shape_analysis_FIX_mipsr1.h"
+#endif
+
+/**************************************************************/
+/* Compute noise shaping coefficients and initial gain values */
+/**************************************************************/
+#ifndef OVERRIDE_silk_noise_shape_analysis_FIX
+void silk_noise_shape_analysis_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Encoder state FIX                                                           */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Encoder control FIX                                                         */
+    const opus_int16                *pitch_res,                             /* I    LPC residual from pitch analysis                                            */
+    const opus_int16                *x,                                     /* I    Input signal [ frame_length + la_shape ]                                    */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+)
+{
+    silk_shape_state_FIX *psShapeSt = &psEnc->sShape;
+    opus_int     k, i, nSamples, nSegs, Qnrg, b_Q14, warping_Q16, scale = 0;
+    opus_int32   SNR_adj_dB_Q7, HarmShapeGain_Q16, Tilt_Q16, tmp32;
+    opus_int32   nrg, log_energy_Q7, log_energy_prev_Q7, energy_variation_Q7;
+    opus_int32   BWExp_Q16, gain_mult_Q16, gain_add_Q16, strength_Q16, b_Q8;
+    opus_int32   auto_corr[     MAX_SHAPE_LPC_ORDER + 1 ];
+    opus_int32   refl_coef_Q16[ MAX_SHAPE_LPC_ORDER ];
+    opus_int32   AR_Q24[       MAX_SHAPE_LPC_ORDER ];
+    VARDECL( opus_int16, x_windowed );
+    const opus_int16 *x_ptr, *pitch_res_ptr;
+    SAVE_STACK;
+
+    /* Point to start of first LPC analysis block */
+    x_ptr = x - psEnc->sCmn.la_shape;
+
+    /****************/
+    /* GAIN CONTROL */
+    /****************/
+    SNR_adj_dB_Q7 = psEnc->sCmn.SNR_dB_Q7;
+
+    /* Input quality is the average of the quality in the lowest two VAD bands */
+    psEncCtrl->input_quality_Q14 = ( opus_int )silk_RSHIFT( (opus_int32)psEnc->sCmn.input_quality_bands_Q15[ 0 ]
+        + psEnc->sCmn.input_quality_bands_Q15[ 1 ], 2 );
+
+    /* Coding quality level, between 0.0_Q0 and 1.0_Q0, but in Q14 */
+    psEncCtrl->coding_quality_Q14 = silk_RSHIFT( silk_sigm_Q15( silk_RSHIFT_ROUND( SNR_adj_dB_Q7 -
+        SILK_FIX_CONST( 20.0, 7 ), 4 ) ), 1 );
+
+    /* Reduce coding SNR during low speech activity */
+    if( psEnc->sCmn.useCBR == 0 ) {
+        b_Q8 = SILK_FIX_CONST( 1.0, 8 ) - psEnc->sCmn.speech_activity_Q8;
+        b_Q8 = silk_SMULWB( silk_LSHIFT( b_Q8, 8 ), b_Q8 );
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7,
+            silk_SMULBB( SILK_FIX_CONST( -BG_SNR_DECR_dB, 7 ) >> ( 4 + 1 ), b_Q8 ),                                       /* Q11*/
+            silk_SMULWB( SILK_FIX_CONST( 1.0, 14 ) + psEncCtrl->input_quality_Q14, psEncCtrl->coding_quality_Q14 ) );     /* Q12*/
+    }
+
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce gains for periodic signals */
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7, SILK_FIX_CONST( HARM_SNR_INCR_dB, 8 ), psEnc->LTPCorr_Q15 );
+    } else {
+        /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */
+        SNR_adj_dB_Q7 = silk_SMLAWB( SNR_adj_dB_Q7,
+            silk_SMLAWB( SILK_FIX_CONST( 6.0, 9 ), -SILK_FIX_CONST( 0.4, 18 ), psEnc->sCmn.SNR_dB_Q7 ),
+            SILK_FIX_CONST( 1.0, 14 ) - psEncCtrl->input_quality_Q14 );
+    }
+
+    /*************************/
+    /* SPARSENESS PROCESSING */
+    /*************************/
+    /* Set quantizer offset */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Initially set to 0; may be overruled in process_gains(..) */
+        psEnc->sCmn.indices.quantOffsetType = 0;
+    } else {
+        /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */
+        nSamples = silk_LSHIFT( psEnc->sCmn.fs_kHz, 1 );
+        energy_variation_Q7 = 0;
+        log_energy_prev_Q7  = 0;
+        pitch_res_ptr = pitch_res;
+        nSegs = silk_SMULBB( SUB_FRAME_LENGTH_MS, psEnc->sCmn.nb_subfr ) / 2;
+        for( k = 0; k < nSegs; k++ ) {
+            silk_sum_sqr_shift( &nrg, &scale, pitch_res_ptr, nSamples );
+            nrg += silk_RSHIFT( nSamples, scale );           /* Q(-scale)*/
+
+            log_energy_Q7 = silk_lin2log( nrg );
+            if( k > 0 ) {
+                energy_variation_Q7 += silk_abs( log_energy_Q7 - log_energy_prev_Q7 );
+            }
+            log_energy_prev_Q7 = log_energy_Q7;
+            pitch_res_ptr += nSamples;
+        }
+
+        /* Set quantization offset depending on sparseness measure */
+        if( energy_variation_Q7 > SILK_FIX_CONST( ENERGY_VARIATION_THRESHOLD_QNT_OFFSET, 7 ) * (nSegs-1) ) {
+            psEnc->sCmn.indices.quantOffsetType = 0;
+        } else {
+            psEnc->sCmn.indices.quantOffsetType = 1;
+        }
+    }
+
+    /*******************************/
+    /* Control bandwidth expansion */
+    /*******************************/
+    /* More BWE for signals with high prediction gain */
+    strength_Q16 = silk_SMULWB( psEncCtrl->predGain_Q16, SILK_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) );
+    BWExp_Q16 = silk_DIV32_varQ( SILK_FIX_CONST( BANDWIDTH_EXPANSION, 16 ),
+        silk_SMLAWW( SILK_FIX_CONST( 1.0, 16 ), strength_Q16, strength_Q16 ), 16 );
+
+    if( psEnc->sCmn.warping_Q16 > 0 ) {
+        /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */
+        warping_Q16 = silk_SMLAWB( psEnc->sCmn.warping_Q16, (opus_int32)psEncCtrl->coding_quality_Q14, SILK_FIX_CONST( 0.01, 18 ) );
+    } else {
+        warping_Q16 = 0;
+    }
+
+    /********************************************/
+    /* Compute noise shaping AR coefs and gains */
+    /********************************************/
+    ALLOC( x_windowed, psEnc->sCmn.shapeWinLength, opus_int16 );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        /* Apply window: sine slope followed by flat part followed by cosine slope */
+        opus_int shift, slope_part, flat_part;
+        flat_part = psEnc->sCmn.fs_kHz * 3;
+        slope_part = silk_RSHIFT( psEnc->sCmn.shapeWinLength - flat_part, 1 );
+
+        silk_apply_sine_window( x_windowed, x_ptr, 1, slope_part );
+        shift = slope_part;
+        silk_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(opus_int16) );
+        shift += flat_part;
+        silk_apply_sine_window( x_windowed + shift, x_ptr + shift, 2, slope_part );
+
+        /* Update pointer: next LPC analysis block */
+        x_ptr += psEnc->sCmn.subfr_length;
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Calculate warped auto correlation */
+            silk_warped_autocorrelation_FIX( auto_corr, &scale, x_windowed, warping_Q16, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder, arch );
+        } else {
+            /* Calculate regular auto correlation */
+            silk_autocorr( auto_corr, &scale, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1, arch );
+        }
+
+        /* Add white noise, as a fraction of energy */
+        auto_corr[0] = silk_ADD32( auto_corr[0], silk_max_32( silk_SMULWB( silk_RSHIFT( auto_corr[ 0 ], 4 ),
+            SILK_FIX_CONST( SHAPE_WHITE_NOISE_FRACTION, 20 ) ), 1 ) );
+
+        /* Calculate the reflection coefficients using schur */
+        nrg = silk_schur64( refl_coef_Q16, auto_corr, psEnc->sCmn.shapingLPCOrder );
+        silk_assert( nrg >= 0 );
+
+        /* Convert reflection coefficients to prediction coefficients */
+        silk_k2a_Q16( AR_Q24, refl_coef_Q16, psEnc->sCmn.shapingLPCOrder );
+
+        Qnrg = -scale;          /* range: -12...30*/
+        silk_assert( Qnrg >= -12 );
+        silk_assert( Qnrg <=  30 );
+
+        /* Make sure that Qnrg is an even number */
+        if( Qnrg & 1 ) {
+            Qnrg -= 1;
+            nrg >>= 1;
+        }
+
+        tmp32 = silk_SQRT_APPROX( nrg );
+        Qnrg >>= 1;             /* range: -6...15*/
+
+        psEncCtrl->Gains_Q16[ k ] = silk_LSHIFT_SAT32( tmp32, 16 - Qnrg );
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Adjust gain for warping */
+            gain_mult_Q16 = warped_gain( AR_Q24, warping_Q16, psEnc->sCmn.shapingLPCOrder );
+            silk_assert( psEncCtrl->Gains_Q16[ k ] > 0 );
+            if( psEncCtrl->Gains_Q16[ k ] < SILK_FIX_CONST( 0.25, 16 ) ) {
+                psEncCtrl->Gains_Q16[ k ] = silk_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );
+            } else {
+                psEncCtrl->Gains_Q16[ k ] = silk_SMULWW( silk_RSHIFT_ROUND( psEncCtrl->Gains_Q16[ k ], 1 ), gain_mult_Q16 );
+                if ( psEncCtrl->Gains_Q16[ k ] >= ( silk_int32_MAX >> 1 ) ) {
+                    psEncCtrl->Gains_Q16[ k ] = silk_int32_MAX;
+                } else {
+                    psEncCtrl->Gains_Q16[ k ] = silk_LSHIFT32( psEncCtrl->Gains_Q16[ k ], 1 );
+                }
+            }
+            silk_assert( psEncCtrl->Gains_Q16[ k ] > 0 );
+        }
+
+        /* Bandwidth expansion */
+        silk_bwexpander_32( AR_Q24, psEnc->sCmn.shapingLPCOrder, BWExp_Q16 );
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Convert to monic warped prediction coefficients and limit absolute values */
+            limit_warped_coefs( AR_Q24, warping_Q16, SILK_FIX_CONST( 3.999, 24 ), psEnc->sCmn.shapingLPCOrder );
+
+            /* Convert from Q24 to Q13 and store in int16 */
+            for( i = 0; i < psEnc->sCmn.shapingLPCOrder; i++ ) {
+                psEncCtrl->AR_Q13[ k * MAX_SHAPE_LPC_ORDER + i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( AR_Q24[ i ], 11 ) );
+            }
+        } else {
+            silk_LPC_fit( &psEncCtrl->AR_Q13[ k * MAX_SHAPE_LPC_ORDER ], AR_Q24, 13, 24, psEnc->sCmn.shapingLPCOrder );
+        }
+    }
+
+    /*****************/
+    /* Gain tweaking */
+    /*****************/
+    /* Increase gains during low speech activity and put lower limit on gains */
+    gain_mult_Q16 = silk_log2lin( -silk_SMLAWB( -SILK_FIX_CONST( 16.0, 7 ), SNR_adj_dB_Q7, SILK_FIX_CONST( 0.16, 16 ) ) );
+    gain_add_Q16  = silk_log2lin(  silk_SMLAWB(  SILK_FIX_CONST( 16.0, 7 ), SILK_FIX_CONST( MIN_QGAIN_DB, 7 ), SILK_FIX_CONST( 0.16, 16 ) ) );
+    silk_assert( gain_mult_Q16 > 0 );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psEncCtrl->Gains_Q16[ k ] = silk_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );
+        silk_assert( psEncCtrl->Gains_Q16[ k ] >= 0 );
+        psEncCtrl->Gains_Q16[ k ] = silk_ADD_POS_SAT32( psEncCtrl->Gains_Q16[ k ], gain_add_Q16 );
+    }
+
+
+    /************************************************/
+    /* Control low-frequency shaping and noise tilt */
+    /************************************************/
+    /* Less low frequency shaping for noisy inputs */
+    strength_Q16 = silk_MUL( SILK_FIX_CONST( LOW_FREQ_SHAPING, 4 ), silk_SMLAWB( SILK_FIX_CONST( 1.0, 12 ),
+        SILK_FIX_CONST( LOW_QUALITY_LOW_FREQ_SHAPING_DECR, 13 ), psEnc->sCmn.input_quality_bands_Q15[ 0 ] - SILK_FIX_CONST( 1.0, 15 ) ) );
+    strength_Q16 = silk_RSHIFT( silk_MUL( strength_Q16, psEnc->sCmn.speech_activity_Q8 ), 8 );
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */
+        /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/
+        opus_int fs_kHz_inv = silk_DIV32_16( SILK_FIX_CONST( 0.2, 14 ), psEnc->sCmn.fs_kHz );
+        for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+            b_Q14 = fs_kHz_inv + silk_DIV32_16( SILK_FIX_CONST( 3.0, 14 ), psEncCtrl->pitchL[ k ] );
+            /* Pack two coefficients in one int32 */
+            psEncCtrl->LF_shp_Q14[ k ]  = silk_LSHIFT( SILK_FIX_CONST( 1.0, 14 ) - b_Q14 - silk_SMULWB( strength_Q16, b_Q14 ), 16 );
+            psEncCtrl->LF_shp_Q14[ k ] |= (opus_uint16)( b_Q14 - SILK_FIX_CONST( 1.0, 14 ) );
+        }
+        silk_assert( SILK_FIX_CONST( HARM_HP_NOISE_COEF, 24 ) < SILK_FIX_CONST( 0.5, 24 ) ); /* Guarantees that second argument to SMULWB() is within range of an opus_int16*/
+        Tilt_Q16 = - SILK_FIX_CONST( HP_NOISE_COEF, 16 ) -
+            silk_SMULWB( SILK_FIX_CONST( 1.0, 16 ) - SILK_FIX_CONST( HP_NOISE_COEF, 16 ),
+                silk_SMULWB( SILK_FIX_CONST( HARM_HP_NOISE_COEF, 24 ), psEnc->sCmn.speech_activity_Q8 ) );
+    } else {
+        b_Q14 = silk_DIV32_16( 21299, psEnc->sCmn.fs_kHz ); /* 1.3_Q0 = 21299_Q14*/
+        /* Pack two coefficients in one int32 */
+        psEncCtrl->LF_shp_Q14[ 0 ]  = silk_LSHIFT( SILK_FIX_CONST( 1.0, 14 ) - b_Q14 -
+            silk_SMULWB( strength_Q16, silk_SMULWB( SILK_FIX_CONST( 0.6, 16 ), b_Q14 ) ), 16 );
+        psEncCtrl->LF_shp_Q14[ 0 ] |= (opus_uint16)( b_Q14 - SILK_FIX_CONST( 1.0, 14 ) );
+        for( k = 1; k < psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->LF_shp_Q14[ k ] = psEncCtrl->LF_shp_Q14[ 0 ];
+        }
+        Tilt_Q16 = -SILK_FIX_CONST( HP_NOISE_COEF, 16 );
+    }
+
+    /****************************/
+    /* HARMONIC SHAPING CONTROL */
+    /****************************/
+    if( USE_HARM_SHAPING && psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* More harmonic noise shaping for high bitrates or noisy input */
+        HarmShapeGain_Q16 = silk_SMLAWB( SILK_FIX_CONST( HARMONIC_SHAPING, 16 ),
+                SILK_FIX_CONST( 1.0, 16 ) - silk_SMULWB( SILK_FIX_CONST( 1.0, 18 ) - silk_LSHIFT( psEncCtrl->coding_quality_Q14, 4 ),
+                psEncCtrl->input_quality_Q14 ), SILK_FIX_CONST( HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING, 16 ) );
+
+        /* Less harmonic noise shaping for less periodic signals */
+        HarmShapeGain_Q16 = silk_SMULWB( silk_LSHIFT( HarmShapeGain_Q16, 1 ),
+            silk_SQRT_APPROX( silk_LSHIFT( psEnc->LTPCorr_Q15, 15 ) ) );
+    } else {
+        HarmShapeGain_Q16 = 0;
+    }
+
+    /*************************/
+    /* Smooth over subframes */
+    /*************************/
+    for( k = 0; k < MAX_NB_SUBFR; k++ ) {
+        psShapeSt->HarmShapeGain_smth_Q16 =
+            silk_SMLAWB( psShapeSt->HarmShapeGain_smth_Q16, HarmShapeGain_Q16 - psShapeSt->HarmShapeGain_smth_Q16, SILK_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );
+        psShapeSt->Tilt_smth_Q16 =
+            silk_SMLAWB( psShapeSt->Tilt_smth_Q16,          Tilt_Q16          - psShapeSt->Tilt_smth_Q16,          SILK_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );
+
+        psEncCtrl->HarmShapeGain_Q14[ k ] = ( opus_int )silk_RSHIFT_ROUND( psShapeSt->HarmShapeGain_smth_Q16, 2 );
+        psEncCtrl->Tilt_Q14[ k ]          = ( opus_int )silk_RSHIFT_ROUND( psShapeSt->Tilt_smth_Q16,          2 );
+    }
+    RESTORE_STACK;
+}
+#endif /* OVERRIDE_silk_noise_shape_analysis_FIX */
diff --git a/opus/silk/fixed/pitch_analysis_core_FIX.c b/opus/silk/fixed/pitch_analysis_core_FIX.c
new file mode 100644 (file)
index 0000000..8df109e
--- /dev/null
@@ -0,0 +1,721 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/***********************************************************
+* Pitch analyser function
+********************************************************** */
+#include "SigProc_FIX.h"
+#include "pitch_est_defines.h"
+#include "stack_alloc.h"
+#include "debug.h"
+#include "pitch.h"
+
+#define SCRATCH_SIZE    22
+#define SF_LENGTH_4KHZ  ( PE_SUBFR_LENGTH_MS * 4 )
+#define SF_LENGTH_8KHZ  ( PE_SUBFR_LENGTH_MS * 8 )
+#define MIN_LAG_4KHZ    ( PE_MIN_LAG_MS * 4 )
+#define MIN_LAG_8KHZ    ( PE_MIN_LAG_MS * 8 )
+#define MAX_LAG_4KHZ    ( PE_MAX_LAG_MS * 4 )
+#define MAX_LAG_8KHZ    ( PE_MAX_LAG_MS * 8 - 1 )
+#define CSTRIDE_4KHZ    ( MAX_LAG_4KHZ + 1 - MIN_LAG_4KHZ )
+#define CSTRIDE_8KHZ    ( MAX_LAG_8KHZ + 3 - ( MIN_LAG_8KHZ - 2 ) )
+#define D_COMP_MIN      ( MIN_LAG_8KHZ - 3 )
+#define D_COMP_MAX      ( MAX_LAG_8KHZ + 4 )
+#define D_COMP_STRIDE   ( D_COMP_MAX - D_COMP_MIN )
+
+typedef opus_int32 silk_pe_stage3_vals[ PE_NB_STAGE3_LAGS ];
+
+/************************************************************/
+/* Internally used functions                                */
+/************************************************************/
+static void silk_P_Ana_calc_corr_st3(
+    silk_pe_stage3_vals cross_corr_st3[],              /* O 3 DIM correlation array */
+    const opus_int16  frame[],                         /* I vector to correlate         */
+    opus_int          start_lag,                       /* I lag offset to search around */
+    opus_int          sf_length,                       /* I length of a 5 ms subframe   */
+    opus_int          nb_subfr,                        /* I number of subframes         */
+    opus_int          complexity,                      /* I Complexity setting          */
+    int               arch                             /* I Run-time architecture       */
+);
+
+static void silk_P_Ana_calc_energy_st3(
+    silk_pe_stage3_vals energies_st3[],                /* O 3 DIM energy array */
+    const opus_int16  frame[],                         /* I vector to calc energy in    */
+    opus_int          start_lag,                       /* I lag offset to search around */
+    opus_int          sf_length,                       /* I length of one 5 ms subframe */
+    opus_int          nb_subfr,                        /* I number of subframes         */
+    opus_int          complexity,                      /* I Complexity setting          */
+    int               arch                             /* I Run-time architecture       */
+);
+
+/*************************************************************/
+/*      FIXED POINT CORE PITCH ANALYSIS FUNCTION             */
+/*************************************************************/
+opus_int silk_pitch_analysis_core(                  /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */
+    const opus_int16            *frame_unscaled,    /* I    Signal of length PE_FRAME_LENGTH_MS*Fs_kHz                  */
+    opus_int                    *pitch_out,         /* O    4 pitch lag values                                          */
+    opus_int16                  *lagIndex,          /* O    Lag Index                                                   */
+    opus_int8                   *contourIndex,      /* O    Pitch contour Index                                         */
+    opus_int                    *LTPCorr_Q15,       /* I/O  Normalized correlation; input: value from previous frame    */
+    opus_int                    prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */
+    const opus_int32            search_thres1_Q16,  /* I    First stage threshold for lag candidates 0 - 1              */
+    const opus_int              search_thres2_Q13,  /* I    Final threshold for lag candidates 0 - 1                    */
+    const opus_int              Fs_kHz,             /* I    Sample frequency (kHz)                                      */
+    const opus_int              complexity,         /* I    Complexity setting, 0-2, where 2 is highest                 */
+    const opus_int              nb_subfr,           /* I    number of 5 ms subframes                                    */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    VARDECL( opus_int16, frame_8kHz_buf );
+    VARDECL( opus_int16, frame_4kHz );
+    VARDECL( opus_int16, frame_scaled );
+    opus_int32 filt_state[ 6 ];
+    const opus_int16 *frame, *frame_8kHz;
+    opus_int   i, k, d, j;
+    VARDECL( opus_int16, C );
+    VARDECL( opus_int32, xcorr32 );
+    const opus_int16 *target_ptr, *basis_ptr;
+    opus_int32 cross_corr, normalizer, energy, energy_basis, energy_target;
+    opus_int   d_srch[ PE_D_SRCH_LENGTH ], Cmax, length_d_srch, length_d_comp, shift;
+    VARDECL( opus_int16, d_comp );
+    opus_int32 sum, threshold, lag_counter;
+    opus_int   CBimax, CBimax_new, CBimax_old, lag, start_lag, end_lag, lag_new;
+    opus_int32 CC[ PE_NB_CBKS_STAGE2_EXT ], CCmax, CCmax_b, CCmax_new_b, CCmax_new;
+    VARDECL( silk_pe_stage3_vals, energies_st3 );
+    VARDECL( silk_pe_stage3_vals, cross_corr_st3 );
+    opus_int   frame_length, frame_length_8kHz, frame_length_4kHz;
+    opus_int   sf_length;
+    opus_int   min_lag;
+    opus_int   max_lag;
+    opus_int32 contour_bias_Q15, diff;
+    opus_int   nb_cbk_search, cbk_size;
+    opus_int32 delta_lag_log2_sqr_Q7, lag_log2_Q7, prevLag_log2_Q7, prev_lag_bias_Q13;
+    const opus_int8 *Lag_CB_ptr;
+    SAVE_STACK;
+
+    /* Check for valid sampling frequency */
+    silk_assert( Fs_kHz == 8 || Fs_kHz == 12 || Fs_kHz == 16 );
+
+    /* Check for valid complexity setting */
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    silk_assert( search_thres1_Q16 >= 0 && search_thres1_Q16 <= (1<<16) );
+    silk_assert( search_thres2_Q13 >= 0 && search_thres2_Q13 <= (1<<13) );
+
+    /* Set up frame lengths max / min lag for the sampling frequency */
+    frame_length      = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * Fs_kHz;
+    frame_length_4kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 4;
+    frame_length_8kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 8;
+    sf_length         = PE_SUBFR_LENGTH_MS * Fs_kHz;
+    min_lag           = PE_MIN_LAG_MS * Fs_kHz;
+    max_lag           = PE_MAX_LAG_MS * Fs_kHz - 1;
+
+    /* Downscale input if necessary */
+    silk_sum_sqr_shift( &energy, &shift, frame_unscaled, frame_length );
+    shift += 3 - silk_CLZ32( energy );        /* at least two bits headroom */
+    ALLOC( frame_scaled, frame_length, opus_int16 );
+    if( shift > 0 ) {
+        shift = silk_RSHIFT( shift + 1, 1 );
+        for( i = 0; i < frame_length; i++ ) {
+            frame_scaled[ i ] = silk_RSHIFT( frame_unscaled[ i ], shift );
+        }
+        frame = frame_scaled;
+    } else {
+        frame = frame_unscaled;
+    }
+
+    ALLOC( frame_8kHz_buf, ( Fs_kHz == 8 ) ? 1 : frame_length_8kHz, opus_int16 );
+    /* Resample from input sampled at Fs_kHz to 8 kHz */
+    if( Fs_kHz == 16 ) {
+        silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) );
+        silk_resampler_down2( filt_state, frame_8kHz_buf, frame, frame_length );
+        frame_8kHz = frame_8kHz_buf;
+    } else if( Fs_kHz == 12 ) {
+        silk_memset( filt_state, 0, 6 * sizeof( opus_int32 ) );
+        silk_resampler_down2_3( filt_state, frame_8kHz_buf, frame, frame_length );
+        frame_8kHz = frame_8kHz_buf;
+    } else {
+        silk_assert( Fs_kHz == 8 );
+        frame_8kHz = frame;
+    }
+
+    /* Decimate again to 4 kHz */
+    silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) );/* Set state to zero */
+    ALLOC( frame_4kHz, frame_length_4kHz, opus_int16 );
+    silk_resampler_down2( filt_state, frame_4kHz, frame_8kHz, frame_length_8kHz );
+
+    /* Low-pass filter */
+    for( i = frame_length_4kHz - 1; i > 0; i-- ) {
+        frame_4kHz[ i ] = silk_ADD_SAT16( frame_4kHz[ i ], frame_4kHz[ i - 1 ] );
+    }
+
+
+    /******************************************************************************
+    * FIRST STAGE, operating in 4 khz
+    ******************************************************************************/
+    ALLOC( C, nb_subfr * CSTRIDE_8KHZ, opus_int16 );
+    ALLOC( xcorr32, MAX_LAG_4KHZ-MIN_LAG_4KHZ+1, opus_int32 );
+    silk_memset( C, 0, (nb_subfr >> 1) * CSTRIDE_4KHZ * sizeof( opus_int16 ) );
+    target_ptr = &frame_4kHz[ silk_LSHIFT( SF_LENGTH_4KHZ, 2 ) ];
+    for( k = 0; k < nb_subfr >> 1; k++ ) {
+        /* Check that we are within range of the array */
+        silk_assert( target_ptr >= frame_4kHz );
+        silk_assert( target_ptr + SF_LENGTH_8KHZ <= frame_4kHz + frame_length_4kHz );
+
+        basis_ptr = target_ptr - MIN_LAG_4KHZ;
+
+        /* Check that we are within range of the array */
+        silk_assert( basis_ptr >= frame_4kHz );
+        silk_assert( basis_ptr + SF_LENGTH_8KHZ <= frame_4kHz + frame_length_4kHz );
+
+        celt_pitch_xcorr( target_ptr, target_ptr - MAX_LAG_4KHZ, xcorr32, SF_LENGTH_8KHZ, MAX_LAG_4KHZ - MIN_LAG_4KHZ + 1, arch );
+
+        /* Calculate first vector products before loop */
+        cross_corr = xcorr32[ MAX_LAG_4KHZ - MIN_LAG_4KHZ ];
+        normalizer = silk_inner_prod_aligned( target_ptr, target_ptr, SF_LENGTH_8KHZ, arch );
+        normalizer = silk_ADD32( normalizer, silk_inner_prod_aligned( basis_ptr,  basis_ptr, SF_LENGTH_8KHZ, arch ) );
+        normalizer = silk_ADD32( normalizer, silk_SMULBB( SF_LENGTH_8KHZ, 4000 ) );
+
+        matrix_ptr( C, k, 0, CSTRIDE_4KHZ ) =
+            (opus_int16)silk_DIV32_varQ( cross_corr, normalizer, 13 + 1 );                      /* Q13 */
+
+        /* From now on normalizer is computed recursively */
+        for( d = MIN_LAG_4KHZ + 1; d <= MAX_LAG_4KHZ; d++ ) {
+            basis_ptr--;
+
+            /* Check that we are within range of the array */
+            silk_assert( basis_ptr >= frame_4kHz );
+            silk_assert( basis_ptr + SF_LENGTH_8KHZ <= frame_4kHz + frame_length_4kHz );
+
+            cross_corr = xcorr32[ MAX_LAG_4KHZ - d ];
+
+            /* Add contribution of new sample and remove contribution from oldest sample */
+            normalizer = silk_ADD32( normalizer,
+                silk_SMULBB( basis_ptr[ 0 ], basis_ptr[ 0 ] ) -
+                silk_SMULBB( basis_ptr[ SF_LENGTH_8KHZ ], basis_ptr[ SF_LENGTH_8KHZ ] ) );
+
+            matrix_ptr( C, k, d - MIN_LAG_4KHZ, CSTRIDE_4KHZ) =
+                (opus_int16)silk_DIV32_varQ( cross_corr, normalizer, 13 + 1 );                  /* Q13 */
+        }
+        /* Update target pointer */
+        target_ptr += SF_LENGTH_8KHZ;
+    }
+
+    /* Combine two subframes into single correlation measure and apply short-lag bias */
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        for( i = MAX_LAG_4KHZ; i >= MIN_LAG_4KHZ; i-- ) {
+            sum = (opus_int32)matrix_ptr( C, 0, i - MIN_LAG_4KHZ, CSTRIDE_4KHZ )
+                + (opus_int32)matrix_ptr( C, 1, i - MIN_LAG_4KHZ, CSTRIDE_4KHZ );               /* Q14 */
+            sum = silk_SMLAWB( sum, sum, silk_LSHIFT( -i, 4 ) );                                /* Q14 */
+            C[ i - MIN_LAG_4KHZ ] = (opus_int16)sum;                                            /* Q14 */
+        }
+    } else {
+        /* Only short-lag bias */
+        for( i = MAX_LAG_4KHZ; i >= MIN_LAG_4KHZ; i-- ) {
+            sum = silk_LSHIFT( (opus_int32)C[ i - MIN_LAG_4KHZ ], 1 );                          /* Q14 */
+            sum = silk_SMLAWB( sum, sum, silk_LSHIFT( -i, 4 ) );                                /* Q14 */
+            C[ i - MIN_LAG_4KHZ ] = (opus_int16)sum;                                            /* Q14 */
+        }
+    }
+
+    /* Sort */
+    length_d_srch = silk_ADD_LSHIFT32( 4, complexity, 1 );
+    silk_assert( 3 * length_d_srch <= PE_D_SRCH_LENGTH );
+    silk_insertion_sort_decreasing_int16( C, d_srch, CSTRIDE_4KHZ,
+                                          length_d_srch );
+
+    /* Escape if correlation is very low already here */
+    Cmax = (opus_int)C[ 0 ];                                                    /* Q14 */
+    if( Cmax < SILK_FIX_CONST( 0.2, 14 ) ) {
+        silk_memset( pitch_out, 0, nb_subfr * sizeof( opus_int ) );
+        *LTPCorr_Q15  = 0;
+        *lagIndex     = 0;
+        *contourIndex = 0;
+        RESTORE_STACK;
+        return 1;
+    }
+
+    threshold = silk_SMULWB( search_thres1_Q16, Cmax );
+    for( i = 0; i < length_d_srch; i++ ) {
+        /* Convert to 8 kHz indices for the sorted correlation that exceeds the threshold */
+        if( C[ i ] > threshold ) {
+            d_srch[ i ] = silk_LSHIFT( d_srch[ i ] + MIN_LAG_4KHZ, 1 );
+        } else {
+            length_d_srch = i;
+            break;
+        }
+    }
+    silk_assert( length_d_srch > 0 );
+
+    ALLOC( d_comp, D_COMP_STRIDE, opus_int16 );
+    for( i = D_COMP_MIN; i < D_COMP_MAX; i++ ) {
+        d_comp[ i - D_COMP_MIN ] = 0;
+    }
+    for( i = 0; i < length_d_srch; i++ ) {
+        d_comp[ d_srch[ i ] - D_COMP_MIN ] = 1;
+    }
+
+    /* Convolution */
+    for( i = D_COMP_MAX - 1; i >= MIN_LAG_8KHZ; i-- ) {
+        d_comp[ i - D_COMP_MIN ] +=
+            d_comp[ i - 1 - D_COMP_MIN ] + d_comp[ i - 2 - D_COMP_MIN ];
+    }
+
+    length_d_srch = 0;
+    for( i = MIN_LAG_8KHZ; i < MAX_LAG_8KHZ + 1; i++ ) {
+        if( d_comp[ i + 1 - D_COMP_MIN ] > 0 ) {
+            d_srch[ length_d_srch ] = i;
+            length_d_srch++;
+        }
+    }
+
+    /* Convolution */
+    for( i = D_COMP_MAX - 1; i >= MIN_LAG_8KHZ; i-- ) {
+        d_comp[ i - D_COMP_MIN ] += d_comp[ i - 1 - D_COMP_MIN ]
+            + d_comp[ i - 2 - D_COMP_MIN ] + d_comp[ i - 3 - D_COMP_MIN ];
+    }
+
+    length_d_comp = 0;
+    for( i = MIN_LAG_8KHZ; i < D_COMP_MAX; i++ ) {
+        if( d_comp[ i - D_COMP_MIN ] > 0 ) {
+            d_comp[ length_d_comp ] = i - 2;
+            length_d_comp++;
+        }
+    }
+
+    /**********************************************************************************
+    ** SECOND STAGE, operating at 8 kHz, on lag sections with high correlation
+    *************************************************************************************/
+
+    /*********************************************************************************
+    * Find energy of each subframe projected onto its history, for a range of delays
+    *********************************************************************************/
+    silk_memset( C, 0, nb_subfr * CSTRIDE_8KHZ * sizeof( opus_int16 ) );
+
+    target_ptr = &frame_8kHz[ PE_LTP_MEM_LENGTH_MS * 8 ];
+    for( k = 0; k < nb_subfr; k++ ) {
+
+        /* Check that we are within range of the array */
+        silk_assert( target_ptr >= frame_8kHz );
+        silk_assert( target_ptr + SF_LENGTH_8KHZ <= frame_8kHz + frame_length_8kHz );
+
+        energy_target = silk_ADD32( silk_inner_prod_aligned( target_ptr, target_ptr, SF_LENGTH_8KHZ, arch ), 1 );
+        for( j = 0; j < length_d_comp; j++ ) {
+            d = d_comp[ j ];
+            basis_ptr = target_ptr - d;
+
+            /* Check that we are within range of the array */
+            silk_assert( basis_ptr >= frame_8kHz );
+            silk_assert( basis_ptr + SF_LENGTH_8KHZ <= frame_8kHz + frame_length_8kHz );
+
+            cross_corr = silk_inner_prod_aligned( target_ptr, basis_ptr, SF_LENGTH_8KHZ, arch );
+            if( cross_corr > 0 ) {
+                energy_basis = silk_inner_prod_aligned( basis_ptr, basis_ptr, SF_LENGTH_8KHZ, arch );
+                matrix_ptr( C, k, d - ( MIN_LAG_8KHZ - 2 ), CSTRIDE_8KHZ ) =
+                    (opus_int16)silk_DIV32_varQ( cross_corr,
+                                                 silk_ADD32( energy_target,
+                                                             energy_basis ),
+                                                 13 + 1 );                                      /* Q13 */
+            } else {
+                matrix_ptr( C, k, d - ( MIN_LAG_8KHZ - 2 ), CSTRIDE_8KHZ ) = 0;
+            }
+        }
+        target_ptr += SF_LENGTH_8KHZ;
+    }
+
+    /* search over lag range and lags codebook */
+    /* scale factor for lag codebook, as a function of center lag */
+
+    CCmax   = silk_int32_MIN;
+    CCmax_b = silk_int32_MIN;
+
+    CBimax = 0; /* To avoid returning undefined lag values */
+    lag = -1;   /* To check if lag with strong enough correlation has been found */
+
+    if( prevLag > 0 ) {
+        if( Fs_kHz == 12 ) {
+            prevLag = silk_DIV32_16( silk_LSHIFT( prevLag, 1 ), 3 );
+        } else if( Fs_kHz == 16 ) {
+            prevLag = silk_RSHIFT( prevLag, 1 );
+        }
+        prevLag_log2_Q7 = silk_lin2log( (opus_int32)prevLag );
+    } else {
+        prevLag_log2_Q7 = 0;
+    }
+    silk_assert( search_thres2_Q13 == silk_SAT16( search_thres2_Q13 ) );
+    /* Set up stage 2 codebook based on number of subframes */
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        cbk_size   = PE_NB_CBKS_STAGE2_EXT;
+        Lag_CB_ptr = &silk_CB_lags_stage2[ 0 ][ 0 ];
+        if( Fs_kHz == 8 && complexity > SILK_PE_MIN_COMPLEX ) {
+            /* If input is 8 khz use a larger codebook here because it is last stage */
+            nb_cbk_search = PE_NB_CBKS_STAGE2_EXT;
+        } else {
+            nb_cbk_search = PE_NB_CBKS_STAGE2;
+        }
+    } else {
+        cbk_size       = PE_NB_CBKS_STAGE2_10MS;
+        Lag_CB_ptr     = &silk_CB_lags_stage2_10_ms[ 0 ][ 0 ];
+        nb_cbk_search  = PE_NB_CBKS_STAGE2_10MS;
+    }
+
+    for( k = 0; k < length_d_srch; k++ ) {
+        d = d_srch[ k ];
+        for( j = 0; j < nb_cbk_search; j++ ) {
+            CC[ j ] = 0;
+            for( i = 0; i < nb_subfr; i++ ) {
+                opus_int d_subfr;
+                /* Try all codebooks */
+                d_subfr = d + matrix_ptr( Lag_CB_ptr, i, j, cbk_size );
+                CC[ j ] = CC[ j ]
+                    + (opus_int32)matrix_ptr( C, i,
+                                              d_subfr - ( MIN_LAG_8KHZ - 2 ),
+                                              CSTRIDE_8KHZ );
+            }
+        }
+        /* Find best codebook */
+        CCmax_new = silk_int32_MIN;
+        CBimax_new = 0;
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            if( CC[ i ] > CCmax_new ) {
+                CCmax_new = CC[ i ];
+                CBimax_new = i;
+            }
+        }
+
+        /* Bias towards shorter lags */
+        lag_log2_Q7 = silk_lin2log( d ); /* Q7 */
+        silk_assert( lag_log2_Q7 == silk_SAT16( lag_log2_Q7 ) );
+        silk_assert( nb_subfr * SILK_FIX_CONST( PE_SHORTLAG_BIAS, 13 ) == silk_SAT16( nb_subfr * SILK_FIX_CONST( PE_SHORTLAG_BIAS, 13 ) ) );
+        CCmax_new_b = CCmax_new - silk_RSHIFT( silk_SMULBB( nb_subfr * SILK_FIX_CONST( PE_SHORTLAG_BIAS, 13 ), lag_log2_Q7 ), 7 ); /* Q13 */
+
+        /* Bias towards previous lag */
+        silk_assert( nb_subfr * SILK_FIX_CONST( PE_PREVLAG_BIAS, 13 ) == silk_SAT16( nb_subfr * SILK_FIX_CONST( PE_PREVLAG_BIAS, 13 ) ) );
+        if( prevLag > 0 ) {
+            delta_lag_log2_sqr_Q7 = lag_log2_Q7 - prevLag_log2_Q7;
+            silk_assert( delta_lag_log2_sqr_Q7 == silk_SAT16( delta_lag_log2_sqr_Q7 ) );
+            delta_lag_log2_sqr_Q7 = silk_RSHIFT( silk_SMULBB( delta_lag_log2_sqr_Q7, delta_lag_log2_sqr_Q7 ), 7 );
+            prev_lag_bias_Q13 = silk_RSHIFT( silk_SMULBB( nb_subfr * SILK_FIX_CONST( PE_PREVLAG_BIAS, 13 ), *LTPCorr_Q15 ), 15 ); /* Q13 */
+            prev_lag_bias_Q13 = silk_DIV32( silk_MUL( prev_lag_bias_Q13, delta_lag_log2_sqr_Q7 ), delta_lag_log2_sqr_Q7 + SILK_FIX_CONST( 0.5, 7 ) );
+            CCmax_new_b -= prev_lag_bias_Q13; /* Q13 */
+        }
+
+        if( CCmax_new_b > CCmax_b                                   &&  /* Find maximum biased correlation                  */
+            CCmax_new > silk_SMULBB( nb_subfr, search_thres2_Q13 )  &&  /* Correlation needs to be high enough to be voiced */
+            silk_CB_lags_stage2[ 0 ][ CBimax_new ] <= MIN_LAG_8KHZ      /* Lag must be in range                             */
+         ) {
+            CCmax_b = CCmax_new_b;
+            CCmax   = CCmax_new;
+            lag     = d;
+            CBimax  = CBimax_new;
+        }
+    }
+
+    if( lag == -1 ) {
+        /* No suitable candidate found */
+        silk_memset( pitch_out, 0, nb_subfr * sizeof( opus_int ) );
+        *LTPCorr_Q15  = 0;
+        *lagIndex     = 0;
+        *contourIndex = 0;
+        RESTORE_STACK;
+        return 1;
+    }
+
+    /* Output normalized correlation */
+    *LTPCorr_Q15 = (opus_int)silk_LSHIFT( silk_DIV32_16( CCmax, nb_subfr ), 2 );
+    silk_assert( *LTPCorr_Q15 >= 0 );
+
+    if( Fs_kHz > 8 ) {
+        /* Search in original signal */
+
+        CBimax_old = CBimax;
+        /* Compensate for decimation */
+        silk_assert( lag == silk_SAT16( lag ) );
+        if( Fs_kHz == 12 ) {
+            lag = silk_RSHIFT( silk_SMULBB( lag, 3 ), 1 );
+        } else if( Fs_kHz == 16 ) {
+            lag = silk_LSHIFT( lag, 1 );
+        } else {
+            lag = silk_SMULBB( lag, 3 );
+        }
+
+        lag = silk_LIMIT_int( lag, min_lag, max_lag );
+        start_lag = silk_max_int( lag - 2, min_lag );
+        end_lag   = silk_min_int( lag + 2, max_lag );
+        lag_new   = lag;                                    /* to avoid undefined lag */
+        CBimax    = 0;                                      /* to avoid undefined lag */
+
+        CCmax = silk_int32_MIN;
+        /* pitch lags according to second stage */
+        for( k = 0; k < nb_subfr; k++ ) {
+            pitch_out[ k ] = lag + 2 * silk_CB_lags_stage2[ k ][ CBimax_old ];
+        }
+
+        /* Set up codebook parameters according to complexity setting and frame length */
+        if( nb_subfr == PE_MAX_NB_SUBFR ) {
+            nb_cbk_search   = (opus_int)silk_nb_cbk_searchs_stage3[ complexity ];
+            cbk_size        = PE_NB_CBKS_STAGE3_MAX;
+            Lag_CB_ptr      = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        } else {
+            nb_cbk_search   = PE_NB_CBKS_STAGE3_10MS;
+            cbk_size        = PE_NB_CBKS_STAGE3_10MS;
+            Lag_CB_ptr      = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        }
+
+        /* Calculate the correlations and energies needed in stage 3 */
+        ALLOC( energies_st3, nb_subfr * nb_cbk_search, silk_pe_stage3_vals );
+        ALLOC( cross_corr_st3, nb_subfr * nb_cbk_search, silk_pe_stage3_vals );
+        silk_P_Ana_calc_corr_st3(  cross_corr_st3, frame, start_lag, sf_length, nb_subfr, complexity, arch );
+        silk_P_Ana_calc_energy_st3( energies_st3, frame, start_lag, sf_length, nb_subfr, complexity, arch );
+
+        lag_counter = 0;
+        silk_assert( lag == silk_SAT16( lag ) );
+        contour_bias_Q15 = silk_DIV32_16( SILK_FIX_CONST( PE_FLATCONTOUR_BIAS, 15 ), lag );
+
+        target_ptr = &frame[ PE_LTP_MEM_LENGTH_MS * Fs_kHz ];
+        energy_target = silk_ADD32( silk_inner_prod_aligned( target_ptr, target_ptr, nb_subfr * sf_length, arch ), 1 );
+        for( d = start_lag; d <= end_lag; d++ ) {
+            for( j = 0; j < nb_cbk_search; j++ ) {
+                cross_corr = 0;
+                energy     = energy_target;
+                for( k = 0; k < nb_subfr; k++ ) {
+                    cross_corr = silk_ADD32( cross_corr,
+                        matrix_ptr( cross_corr_st3, k, j,
+                                    nb_cbk_search )[ lag_counter ] );
+                    energy     = silk_ADD32( energy,
+                        matrix_ptr( energies_st3, k, j,
+                                    nb_cbk_search )[ lag_counter ] );
+                    silk_assert( energy >= 0 );
+                }
+                if( cross_corr > 0 ) {
+                    CCmax_new = silk_DIV32_varQ( cross_corr, energy, 13 + 1 );          /* Q13 */
+                    /* Reduce depending on flatness of contour */
+                    diff = silk_int16_MAX - silk_MUL( contour_bias_Q15, j );            /* Q15 */
+                    silk_assert( diff == silk_SAT16( diff ) );
+                    CCmax_new = silk_SMULWB( CCmax_new, diff );                         /* Q14 */
+                } else {
+                    CCmax_new = 0;
+                }
+
+                if( CCmax_new > CCmax && ( d + silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag ) {
+                    CCmax   = CCmax_new;
+                    lag_new = d;
+                    CBimax  = j;
+                }
+            }
+            lag_counter++;
+        }
+
+        for( k = 0; k < nb_subfr; k++ ) {
+            pitch_out[ k ] = lag_new + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size );
+            pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], min_lag, PE_MAX_LAG_MS * Fs_kHz );
+        }
+        *lagIndex = (opus_int16)( lag_new - min_lag);
+        *contourIndex = (opus_int8)CBimax;
+    } else {        /* Fs_kHz == 8 */
+        /* Save Lags */
+        for( k = 0; k < nb_subfr; k++ ) {
+            pitch_out[ k ] = lag + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size );
+            pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], MIN_LAG_8KHZ, PE_MAX_LAG_MS * 8 );
+        }
+        *lagIndex = (opus_int16)( lag - MIN_LAG_8KHZ );
+        *contourIndex = (opus_int8)CBimax;
+    }
+    silk_assert( *lagIndex >= 0 );
+    /* return as voiced */
+    RESTORE_STACK;
+    return 0;
+}
+
+/***********************************************************************
+ * Calculates the correlations used in stage 3 search. In order to cover
+ * the whole lag codebook for all the searched offset lags (lag +- 2),
+ * the following correlations are needed in each sub frame:
+ *
+ * sf1: lag range [-8,...,7] total 16 correlations
+ * sf2: lag range [-4,...,4] total 9 correlations
+ * sf3: lag range [-3,....4] total 8 correltions
+ * sf4: lag range [-6,....8] total 15 correlations
+ *
+ * In total 48 correlations. The direct implementation computed in worst
+ * case 4*12*5 = 240 correlations, but more likely around 120.
+ ***********************************************************************/
+static void silk_P_Ana_calc_corr_st3(
+    silk_pe_stage3_vals cross_corr_st3[],              /* O 3 DIM correlation array */
+    const opus_int16  frame[],                         /* I vector to correlate         */
+    opus_int          start_lag,                       /* I lag offset to search around */
+    opus_int          sf_length,                       /* I length of a 5 ms subframe   */
+    opus_int          nb_subfr,                        /* I number of subframes         */
+    opus_int          complexity,                      /* I Complexity setting          */
+    int               arch                             /* I Run-time architecture       */
+)
+{
+    const opus_int16 *target_ptr;
+    opus_int   i, j, k, lag_counter, lag_low, lag_high;
+    opus_int   nb_cbk_search, delta, idx, cbk_size;
+    VARDECL( opus_int32, scratch_mem );
+    VARDECL( opus_int32, xcorr32 );
+    const opus_int8 *Lag_range_ptr, *Lag_CB_ptr;
+    SAVE_STACK;
+
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ];
+        cbk_size      = PE_NB_CBKS_STAGE3_MAX;
+    } else {
+        silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1);
+        Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        nb_cbk_search = PE_NB_CBKS_STAGE3_10MS;
+        cbk_size      = PE_NB_CBKS_STAGE3_10MS;
+    }
+    ALLOC( scratch_mem, SCRATCH_SIZE, opus_int32 );
+    ALLOC( xcorr32, SCRATCH_SIZE, opus_int32 );
+
+    target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ]; /* Pointer to middle of frame */
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_counter = 0;
+
+        /* Calculate the correlations for each subframe */
+        lag_low  = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        lag_high = matrix_ptr( Lag_range_ptr, k, 1, 2 );
+        silk_assert(lag_high-lag_low+1 <= SCRATCH_SIZE);
+        celt_pitch_xcorr( target_ptr, target_ptr - start_lag - lag_high, xcorr32, sf_length, lag_high - lag_low + 1, arch );
+        for( j = lag_low; j <= lag_high; j++ ) {
+            silk_assert( lag_counter < SCRATCH_SIZE );
+            scratch_mem[ lag_counter ] = xcorr32[ lag_high - j ];
+            lag_counter++;
+        }
+
+        delta = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            /* Fill out the 3 dim array that stores the correlations for */
+            /* each code_book vector for each start lag */
+            idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta;
+            for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) {
+                silk_assert( idx + j < SCRATCH_SIZE );
+                silk_assert( idx + j < lag_counter );
+                matrix_ptr( cross_corr_st3, k, i, nb_cbk_search )[ j ] =
+                    scratch_mem[ idx + j ];
+            }
+        }
+        target_ptr += sf_length;
+    }
+    RESTORE_STACK;
+}
+
+/********************************************************************/
+/* Calculate the energies for first two subframes. The energies are */
+/* calculated recursively.                                          */
+/********************************************************************/
+static void silk_P_Ana_calc_energy_st3(
+    silk_pe_stage3_vals energies_st3[],                 /* O 3 DIM energy array */
+    const opus_int16  frame[],                          /* I vector to calc energy in    */
+    opus_int          start_lag,                        /* I lag offset to search around */
+    opus_int          sf_length,                        /* I length of one 5 ms subframe */
+    opus_int          nb_subfr,                         /* I number of subframes         */
+    opus_int          complexity,                       /* I Complexity setting          */
+    int               arch                              /* I Run-time architecture       */
+)
+{
+    const opus_int16 *target_ptr, *basis_ptr;
+    opus_int32 energy;
+    opus_int   k, i, j, lag_counter;
+    opus_int   nb_cbk_search, delta, idx, cbk_size, lag_diff;
+    VARDECL( opus_int32, scratch_mem );
+    const opus_int8 *Lag_range_ptr, *Lag_CB_ptr;
+    SAVE_STACK;
+
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ];
+        cbk_size      = PE_NB_CBKS_STAGE3_MAX;
+    } else {
+        silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1);
+        Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        nb_cbk_search = PE_NB_CBKS_STAGE3_10MS;
+        cbk_size      = PE_NB_CBKS_STAGE3_10MS;
+    }
+    ALLOC( scratch_mem, SCRATCH_SIZE, opus_int32 );
+
+    target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ];
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_counter = 0;
+
+        /* Calculate the energy for first lag */
+        basis_ptr = target_ptr - ( start_lag + matrix_ptr( Lag_range_ptr, k, 0, 2 ) );
+        energy = silk_inner_prod_aligned( basis_ptr, basis_ptr, sf_length, arch );
+        silk_assert( energy >= 0 );
+        scratch_mem[ lag_counter ] = energy;
+        lag_counter++;
+
+        lag_diff = ( matrix_ptr( Lag_range_ptr, k, 1, 2 ) -  matrix_ptr( Lag_range_ptr, k, 0, 2 ) + 1 );
+        for( i = 1; i < lag_diff; i++ ) {
+            /* remove part outside new window */
+            energy -= silk_SMULBB( basis_ptr[ sf_length - i ], basis_ptr[ sf_length - i ] );
+            silk_assert( energy >= 0 );
+
+            /* add part that comes into window */
+            energy = silk_ADD_SAT32( energy, silk_SMULBB( basis_ptr[ -i ], basis_ptr[ -i ] ) );
+            silk_assert( energy >= 0 );
+            silk_assert( lag_counter < SCRATCH_SIZE );
+            scratch_mem[ lag_counter ] = energy;
+            lag_counter++;
+        }
+
+        delta = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            /* Fill out the 3 dim array that stores the correlations for    */
+            /* each code_book vector for each start lag                     */
+            idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta;
+            for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) {
+                silk_assert( idx + j < SCRATCH_SIZE );
+                silk_assert( idx + j < lag_counter );
+                matrix_ptr( energies_st3, k, i, nb_cbk_search )[ j ] =
+                    scratch_mem[ idx + j ];
+                silk_assert(
+                    matrix_ptr( energies_st3, k, i, nb_cbk_search )[ j ] >= 0 );
+            }
+        }
+        target_ptr += sf_length;
+    }
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/process_gains_FIX.c b/opus/silk/fixed/process_gains_FIX.c
new file mode 100644 (file)
index 0000000..05aba31
--- /dev/null
@@ -0,0 +1,117 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "tuning_parameters.h"
+
+/* Processing of gains */
+void silk_process_gains_FIX(
+    silk_encoder_state_FIX          *psEnc,                                 /* I/O  Encoder state                                                               */
+    silk_encoder_control_FIX        *psEncCtrl,                             /* I/O  Encoder control                                                             */
+    opus_int                        condCoding                              /* I    The type of conditional coding to use                                       */
+)
+{
+    silk_shape_state_FIX *psShapeSt = &psEnc->sShape;
+    opus_int     k;
+    opus_int32   s_Q16, InvMaxSqrVal_Q16, gain, gain_squared, ResNrg, ResNrgPart, quant_offset_Q10;
+
+    /* Gain reduction when LTP coding gain is high */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /*s = -0.5f * silk_sigmoid( 0.25f * ( psEncCtrl->LTPredCodGain - 12.0f ) ); */
+        s_Q16 = -silk_sigm_Q15( silk_RSHIFT_ROUND( psEncCtrl->LTPredCodGain_Q7 - SILK_FIX_CONST( 12.0, 7 ), 4 ) );
+        for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->Gains_Q16[ k ] = silk_SMLAWB( psEncCtrl->Gains_Q16[ k ], psEncCtrl->Gains_Q16[ k ], s_Q16 );
+        }
+    }
+
+    /* Limit the quantized signal */
+    /* InvMaxSqrVal = pow( 2.0f, 0.33f * ( 21.0f - SNR_dB ) ) / subfr_length; */
+    InvMaxSqrVal_Q16 = silk_DIV32_16( silk_log2lin(
+        silk_SMULWB( SILK_FIX_CONST( 21 + 16 / 0.33, 7 ) - psEnc->sCmn.SNR_dB_Q7, SILK_FIX_CONST( 0.33, 16 ) ) ), psEnc->sCmn.subfr_length );
+
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        /* Soft limit on ratio residual energy and squared gains */
+        ResNrg     = psEncCtrl->ResNrg[ k ];
+        ResNrgPart = silk_SMULWW( ResNrg, InvMaxSqrVal_Q16 );
+        if( psEncCtrl->ResNrgQ[ k ] > 0 ) {
+            ResNrgPart = silk_RSHIFT_ROUND( ResNrgPart, psEncCtrl->ResNrgQ[ k ] );
+        } else {
+            if( ResNrgPart >= silk_RSHIFT( silk_int32_MAX, -psEncCtrl->ResNrgQ[ k ] ) ) {
+                ResNrgPart = silk_int32_MAX;
+            } else {
+                ResNrgPart = silk_LSHIFT( ResNrgPart, -psEncCtrl->ResNrgQ[ k ] );
+            }
+        }
+        gain = psEncCtrl->Gains_Q16[ k ];
+        gain_squared = silk_ADD_SAT32( ResNrgPart, silk_SMMUL( gain, gain ) );
+        if( gain_squared < silk_int16_MAX ) {
+            /* recalculate with higher precision */
+            gain_squared = silk_SMLAWW( silk_LSHIFT( ResNrgPart, 16 ), gain, gain );
+            silk_assert( gain_squared > 0 );
+            gain = silk_SQRT_APPROX( gain_squared );                    /* Q8   */
+            gain = silk_min( gain, silk_int32_MAX >> 8 );
+            psEncCtrl->Gains_Q16[ k ] = silk_LSHIFT_SAT32( gain, 8 );   /* Q16  */
+        } else {
+            gain = silk_SQRT_APPROX( gain_squared );                    /* Q0   */
+            gain = silk_min( gain, silk_int32_MAX >> 16 );
+            psEncCtrl->Gains_Q16[ k ] = silk_LSHIFT_SAT32( gain, 16 );  /* Q16  */
+        }
+    }
+
+    /* Save unquantized gains and gain Index */
+    silk_memcpy( psEncCtrl->GainsUnq_Q16, psEncCtrl->Gains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
+    psEncCtrl->lastGainIndexPrev = psShapeSt->LastGainIndex;
+
+    /* Quantize gains */
+    silk_gains_quant( psEnc->sCmn.indices.GainsIndices, psEncCtrl->Gains_Q16,
+        &psShapeSt->LastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+    /* Set quantizer offset for voiced signals. Larger offset when LTP coding gain is low or tilt is high (ie low-pass) */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        if( psEncCtrl->LTPredCodGain_Q7 + silk_RSHIFT( psEnc->sCmn.input_tilt_Q15, 8 ) > SILK_FIX_CONST( 1.0, 7 ) ) {
+            psEnc->sCmn.indices.quantOffsetType = 0;
+        } else {
+            psEnc->sCmn.indices.quantOffsetType = 1;
+        }
+    }
+
+    /* Quantizer boundary adjustment */
+    quant_offset_Q10 = silk_Quantization_Offsets_Q10[ psEnc->sCmn.indices.signalType >> 1 ][ psEnc->sCmn.indices.quantOffsetType ];
+    psEncCtrl->Lambda_Q10 = SILK_FIX_CONST( LAMBDA_OFFSET, 10 )
+                          + silk_SMULBB( SILK_FIX_CONST( LAMBDA_DELAYED_DECISIONS, 10 ), psEnc->sCmn.nStatesDelayedDecision )
+                          + silk_SMULWB( SILK_FIX_CONST( LAMBDA_SPEECH_ACT,        18 ), psEnc->sCmn.speech_activity_Q8     )
+                          + silk_SMULWB( SILK_FIX_CONST( LAMBDA_INPUT_QUALITY,     12 ), psEncCtrl->input_quality_Q14       )
+                          + silk_SMULWB( SILK_FIX_CONST( LAMBDA_CODING_QUALITY,    12 ), psEncCtrl->coding_quality_Q14      )
+                          + silk_SMULWB( SILK_FIX_CONST( LAMBDA_QUANT_OFFSET,      16 ), quant_offset_Q10                   );
+
+    silk_assert( psEncCtrl->Lambda_Q10 > 0 );
+    silk_assert( psEncCtrl->Lambda_Q10 < SILK_FIX_CONST( 2, 10 ) );
+}
diff --git a/opus/silk/fixed/regularize_correlations_FIX.c b/opus/silk/fixed/regularize_correlations_FIX.c
new file mode 100644 (file)
index 0000000..a2836b0
--- /dev/null
@@ -0,0 +1,47 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+/* Add noise to matrix diagonal */
+void silk_regularize_correlations_FIX(
+    opus_int32                      *XX,                                    /* I/O  Correlation matrices                                                        */
+    opus_int32                      *xx,                                    /* I/O  Correlation values                                                          */
+    opus_int32                      noise,                                  /* I    Noise to add                                                                */
+    opus_int                        D                                       /* I    Dimension of XX                                                             */
+)
+{
+    opus_int i;
+    for( i = 0; i < D; i++ ) {
+        matrix_ptr( &XX[ 0 ], i, i, D ) = silk_ADD32( matrix_ptr( &XX[ 0 ], i, i, D ), noise );
+    }
+    xx[ 0 ] += noise;
+}
diff --git a/opus/silk/fixed/residual_energy16_FIX.c b/opus/silk/fixed/residual_energy16_FIX.c
new file mode 100644 (file)
index 0000000..ebffb2a
--- /dev/null
@@ -0,0 +1,103 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */
+opus_int32 silk_residual_energy16_covar_FIX(
+    const opus_int16                *c,                                     /* I    Prediction vector                                                           */
+    const opus_int32                *wXX,                                   /* I    Correlation matrix                                                          */
+    const opus_int32                *wXx,                                   /* I    Correlation vector                                                          */
+    opus_int32                      wxx,                                    /* I    Signal energy                                                               */
+    opus_int                        D,                                      /* I    Dimension                                                                   */
+    opus_int                        cQ                                      /* I    Q value for c vector 0 - 15                                                 */
+)
+{
+    opus_int   i, j, lshifts, Qxtra;
+    opus_int32 c_max, w_max, tmp, tmp2, nrg;
+    opus_int   cn[ MAX_MATRIX_SIZE ];
+    const opus_int32 *pRow;
+
+    /* Safety checks */
+    silk_assert( D >=  0 );
+    silk_assert( D <= 16 );
+    silk_assert( cQ >  0 );
+    silk_assert( cQ < 16 );
+
+    lshifts = 16 - cQ;
+    Qxtra = lshifts;
+
+    c_max = 0;
+    for( i = 0; i < D; i++ ) {
+        c_max = silk_max_32( c_max, silk_abs( (opus_int32)c[ i ] ) );
+    }
+    Qxtra = silk_min_int( Qxtra, silk_CLZ32( c_max ) - 17 );
+
+    w_max = silk_max_32( wXX[ 0 ], wXX[ D * D - 1 ] );
+    Qxtra = silk_min_int( Qxtra, silk_CLZ32( silk_MUL( D, silk_RSHIFT( silk_SMULWB( w_max, c_max ), 4 ) ) ) - 5 );
+    Qxtra = silk_max_int( Qxtra, 0 );
+    for( i = 0; i < D; i++ ) {
+        cn[ i ] = silk_LSHIFT( ( opus_int )c[ i ], Qxtra );
+        silk_assert( silk_abs(cn[i]) <= ( silk_int16_MAX + 1 ) ); /* Check that silk_SMLAWB can be used */
+    }
+    lshifts -= Qxtra;
+
+    /* Compute wxx - 2 * wXx * c */
+    tmp = 0;
+    for( i = 0; i < D; i++ ) {
+        tmp = silk_SMLAWB( tmp, wXx[ i ], cn[ i ] );
+    }
+    nrg = silk_RSHIFT( wxx, 1 + lshifts ) - tmp;                         /* Q: -lshifts - 1 */
+
+    /* Add c' * wXX * c, assuming wXX is symmetric */
+    tmp2 = 0;
+    for( i = 0; i < D; i++ ) {
+        tmp = 0;
+        pRow = &wXX[ i * D ];
+        for( j = i + 1; j < D; j++ ) {
+            tmp = silk_SMLAWB( tmp, pRow[ j ], cn[ j ] );
+        }
+        tmp  = silk_SMLAWB( tmp,  silk_RSHIFT( pRow[ i ], 1 ), cn[ i ] );
+        tmp2 = silk_SMLAWB( tmp2, tmp,                        cn[ i ] );
+    }
+    nrg = silk_ADD_LSHIFT32( nrg, tmp2, lshifts );                       /* Q: -lshifts - 1 */
+
+    /* Keep one bit free always, because we add them for LSF interpolation */
+    if( nrg < 1 ) {
+        nrg = 1;
+    } else if( nrg > silk_RSHIFT( silk_int32_MAX, lshifts + 2 ) ) {
+        nrg = silk_int32_MAX >> 1;
+    } else {
+        nrg = silk_LSHIFT( nrg, lshifts + 1 );                           /* Q0 */
+    }
+    return nrg;
+
+}
diff --git a/opus/silk/fixed/residual_energy_FIX.c b/opus/silk/fixed/residual_energy_FIX.c
new file mode 100644 (file)
index 0000000..41f7477
--- /dev/null
@@ -0,0 +1,98 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+#include "stack_alloc.h"
+
+/* Calculates residual energies of input subframes where all subframes have LPC_order   */
+/* of preceding samples                                                                 */
+void silk_residual_energy_FIX(
+          opus_int32                nrgs[ MAX_NB_SUBFR ],                   /* O    Residual energy per subframe                                                */
+          opus_int                  nrgsQ[ MAX_NB_SUBFR ],                  /* O    Q value per subframe                                                        */
+    const opus_int16                x[],                                    /* I    Input signal                                                                */
+          opus_int16                a_Q12[ 2 ][ MAX_LPC_ORDER ],            /* I    AR coefs for each frame half                                                */
+    const opus_int32                gains[ MAX_NB_SUBFR ],                  /* I    Quantization gains                                                          */
+    const opus_int                  subfr_length,                           /* I    Subframe length                                                             */
+    const opus_int                  nb_subfr,                               /* I    Number of subframes                                                         */
+    const opus_int                  LPC_order,                              /* I    LPC order                                                                   */
+          int                       arch                                    /* I    Run-time architecture                                                       */
+)
+{
+    opus_int         offset, i, j, rshift, lz1, lz2;
+    opus_int16       *LPC_res_ptr;
+    VARDECL( opus_int16, LPC_res );
+    const opus_int16 *x_ptr;
+    opus_int32       tmp32;
+    SAVE_STACK;
+
+    x_ptr  = x;
+    offset = LPC_order + subfr_length;
+
+    /* Filter input to create the LPC residual for each frame half, and measure subframe energies */
+    ALLOC( LPC_res, ( MAX_NB_SUBFR >> 1 ) * offset, opus_int16 );
+    silk_assert( ( nb_subfr >> 1 ) * ( MAX_NB_SUBFR >> 1 ) == nb_subfr );
+    for( i = 0; i < nb_subfr >> 1; i++ ) {
+        /* Calculate half frame LPC residual signal including preceding samples */
+        silk_LPC_analysis_filter( LPC_res, x_ptr, a_Q12[ i ], ( MAX_NB_SUBFR >> 1 ) * offset, LPC_order, arch );
+
+        /* Point to first subframe of the just calculated LPC residual signal */
+        LPC_res_ptr = LPC_res + LPC_order;
+        for( j = 0; j < ( MAX_NB_SUBFR >> 1 ); j++ ) {
+            /* Measure subframe energy */
+            silk_sum_sqr_shift( &nrgs[ i * ( MAX_NB_SUBFR >> 1 ) + j ], &rshift, LPC_res_ptr, subfr_length );
+
+            /* Set Q values for the measured energy */
+            nrgsQ[ i * ( MAX_NB_SUBFR >> 1 ) + j ] = -rshift;
+
+            /* Move to next subframe */
+            LPC_res_ptr += offset;
+        }
+        /* Move to next frame half */
+        x_ptr += ( MAX_NB_SUBFR >> 1 ) * offset;
+    }
+
+    /* Apply the squared subframe gains */
+    for( i = 0; i < nb_subfr; i++ ) {
+        /* Fully upscale gains and energies */
+        lz1 = silk_CLZ32( nrgs[  i ] ) - 1;
+        lz2 = silk_CLZ32( gains[ i ] ) - 1;
+
+        tmp32 = silk_LSHIFT32( gains[ i ], lz2 );
+
+        /* Find squared gains */
+        tmp32 = silk_SMMUL( tmp32, tmp32 ); /* Q( 2 * lz2 - 32 )*/
+
+        /* Scale energies */
+        nrgs[ i ] = silk_SMMUL( tmp32, silk_LSHIFT32( nrgs[ i ], lz1 ) ); /* Q( nrgsQ[ i ] + lz1 + 2 * lz2 - 32 - 32 )*/
+        nrgsQ[ i ] += lz1 + 2 * lz2 - 32 - 32;
+    }
+    RESTORE_STACK;
+}
diff --git a/opus/silk/fixed/schur64_FIX.c b/opus/silk/fixed/schur64_FIX.c
new file mode 100644 (file)
index 0000000..b2cb12d
--- /dev/null
@@ -0,0 +1,93 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Slower than schur(), but more accurate.                              */
+/* Uses SMULL(), available on armv4                                     */
+opus_int32 silk_schur64(                            /* O    returns residual energy                                     */
+    opus_int32                  rc_Q16[],           /* O    Reflection coefficients [order] Q16                         */
+    const opus_int32            c[],                /* I    Correlations [order+1]                                      */
+    opus_int32                  order               /* I    Prediction order                                            */
+)
+{
+    opus_int   k, n;
+    opus_int32 C[ SILK_MAX_ORDER_LPC + 1 ][ 2 ];
+    opus_int32 Ctmp1_Q30, Ctmp2_Q30, rc_tmp_Q31;
+
+    silk_assert( order >= 0 && order <= SILK_MAX_ORDER_LPC );
+
+    /* Check for invalid input */
+    if( c[ 0 ] <= 0 ) {
+        silk_memset( rc_Q16, 0, order * sizeof( opus_int32 ) );
+        return 0;
+    }
+
+    k = 0;
+    do {
+        C[ k ][ 0 ] = C[ k ][ 1 ] = c[ k ];
+    } while( ++k <= order );
+
+    for( k = 0; k < order; k++ ) {
+        /* Check that we won't be getting an unstable rc, otherwise stop here. */
+        if (silk_abs_int32(C[ k + 1 ][ 0 ]) >= C[ 0 ][ 1 ]) {
+           if ( C[ k + 1 ][ 0 ] > 0 ) {
+              rc_Q16[ k ] = -SILK_FIX_CONST( .99f, 16 );
+           } else {
+              rc_Q16[ k ] = SILK_FIX_CONST( .99f, 16 );
+           }
+           k++;
+           break;
+        }
+
+        /* Get reflection coefficient: divide two Q30 values and get result in Q31 */
+        rc_tmp_Q31 = silk_DIV32_varQ( -C[ k + 1 ][ 0 ], C[ 0 ][ 1 ], 31 );
+
+        /* Save the output */
+        rc_Q16[ k ] = silk_RSHIFT_ROUND( rc_tmp_Q31, 15 );
+
+        /* Update correlations */
+        for( n = 0; n < order - k; n++ ) {
+            Ctmp1_Q30 = C[ n + k + 1 ][ 0 ];
+            Ctmp2_Q30 = C[ n ][ 1 ];
+
+            /* Multiply and add the highest int32 */
+            C[ n + k + 1 ][ 0 ] = Ctmp1_Q30 + silk_SMMUL( silk_LSHIFT( Ctmp2_Q30, 1 ), rc_tmp_Q31 );
+            C[ n ][ 1 ]         = Ctmp2_Q30 + silk_SMMUL( silk_LSHIFT( Ctmp1_Q30, 1 ), rc_tmp_Q31 );
+        }
+    }
+
+    for(; k < order; k++ ) {
+       rc_Q16[ k ] = 0;
+    }
+
+    return silk_max_32( 1, C[ 0 ][ 1 ] );
+}
diff --git a/opus/silk/fixed/schur_FIX.c b/opus/silk/fixed/schur_FIX.c
new file mode 100644 (file)
index 0000000..59d44a6
--- /dev/null
@@ -0,0 +1,107 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Faster than schur64(), but much less accurate.                       */
+/* uses SMLAWB(), requiring armv5E and higher.                          */
+opus_int32 silk_schur(                              /* O    Returns residual energy                                     */
+    opus_int16                  *rc_Q15,            /* O    reflection coefficients [order] Q15                         */
+    const opus_int32            *c,                 /* I    correlations [order+1]                                      */
+    const opus_int32            order               /* I    prediction order                                            */
+)
+{
+    opus_int        k, n, lz;
+    opus_int32    C[ SILK_MAX_ORDER_LPC + 1 ][ 2 ];
+    opus_int32    Ctmp1, Ctmp2, rc_tmp_Q15;
+
+    silk_assert( order >= 0 && order <= SILK_MAX_ORDER_LPC );
+
+    /* Get number of leading zeros */
+    lz = silk_CLZ32( c[ 0 ] );
+
+    /* Copy correlations and adjust level to Q30 */
+    k = 0;
+    if( lz < 2 ) {
+        /* lz must be 1, so shift one to the right */
+        do {
+            C[ k ][ 0 ] = C[ k ][ 1 ] = silk_RSHIFT( c[ k ], 1 );
+        } while( ++k <= order );
+    } else if( lz > 2 ) {
+        /* Shift to the left */
+        lz -= 2;
+        do {
+            C[ k ][ 0 ] = C[ k ][ 1 ] = silk_LSHIFT( c[ k ], lz );
+        } while( ++k <= order );
+    } else {
+        /* No need to shift */
+        do {
+            C[ k ][ 0 ] = C[ k ][ 1 ] = c[ k ];
+        } while( ++k <= order );
+    }
+
+    for( k = 0; k < order; k++ ) {
+        /* Check that we won't be getting an unstable rc, otherwise stop here. */
+        if (silk_abs_int32(C[ k + 1 ][ 0 ]) >= C[ 0 ][ 1 ]) {
+           if ( C[ k + 1 ][ 0 ] > 0 ) {
+              rc_Q15[ k ] = -SILK_FIX_CONST( .99f, 15 );
+           } else {
+              rc_Q15[ k ] = SILK_FIX_CONST( .99f, 15 );
+           }
+           k++;
+           break;
+        }
+
+        /* Get reflection coefficient */
+        rc_tmp_Q15 = -silk_DIV32_16( C[ k + 1 ][ 0 ], silk_max_32( silk_RSHIFT( C[ 0 ][ 1 ], 15 ), 1 ) );
+
+        /* Clip (shouldn't happen for properly conditioned inputs) */
+        rc_tmp_Q15 = silk_SAT16( rc_tmp_Q15 );
+
+        /* Store */
+        rc_Q15[ k ] = (opus_int16)rc_tmp_Q15;
+
+        /* Update correlations */
+        for( n = 0; n < order - k; n++ ) {
+            Ctmp1 = C[ n + k + 1 ][ 0 ];
+            Ctmp2 = C[ n ][ 1 ];
+            C[ n + k + 1 ][ 0 ] = silk_SMLAWB( Ctmp1, silk_LSHIFT( Ctmp2, 1 ), rc_tmp_Q15 );
+            C[ n ][ 1 ]         = silk_SMLAWB( Ctmp2, silk_LSHIFT( Ctmp1, 1 ), rc_tmp_Q15 );
+        }
+    }
+
+    for(; k < order; k++ ) {
+       rc_Q15[ k ] = 0;
+    }
+
+    /* return residual energy */
+    return silk_max_32( 1, C[ 0 ][ 1 ] );
+}
diff --git a/opus/silk/fixed/structs_FIX.h b/opus/silk/fixed/structs_FIX.h
new file mode 100644 (file)
index 0000000..2774a97
--- /dev/null
@@ -0,0 +1,116 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_STRUCTS_FIX_H
+#define SILK_STRUCTS_FIX_H
+
+#include "typedef.h"
+#include "main.h"
+#include "structs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/********************************/
+/* Noise shaping analysis state */
+/********************************/
+typedef struct {
+    opus_int8                   LastGainIndex;
+    opus_int32                  HarmBoost_smth_Q16;
+    opus_int32                  HarmShapeGain_smth_Q16;
+    opus_int32                  Tilt_smth_Q16;
+} silk_shape_state_FIX;
+
+/********************************/
+/* Encoder state FIX            */
+/********************************/
+typedef struct {
+    silk_encoder_state          sCmn;                                   /* Common struct, shared with floating-point code       */
+    silk_shape_state_FIX        sShape;                                 /* Shape state                                          */
+
+    /* Buffer for find pitch and noise shape analysis */
+    silk_DWORD_ALIGN opus_int16 x_buf[ 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ];/* Buffer for find pitch and noise shape analysis  */
+    opus_int                    LTPCorr_Q15;                            /* Normalized correlation from pitch lag estimator      */
+    opus_int32                    resNrgSmth;
+} silk_encoder_state_FIX;
+
+/************************/
+/* Encoder control FIX  */
+/************************/
+typedef struct {
+    /* Prediction and coding parameters */
+    opus_int32                  Gains_Q16[ MAX_NB_SUBFR ];
+    silk_DWORD_ALIGN opus_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];
+    opus_int16                  LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ];
+    opus_int                    LTP_scale_Q14;
+    opus_int                    pitchL[ MAX_NB_SUBFR ];
+
+    /* Noise shaping parameters */
+    /* Testing */
+    silk_DWORD_ALIGN opus_int16 AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ];
+    opus_int32                  LF_shp_Q14[        MAX_NB_SUBFR ];      /* Packs two int16 coefficients per int32 value         */
+    opus_int                    Tilt_Q14[          MAX_NB_SUBFR ];
+    opus_int                    HarmShapeGain_Q14[ MAX_NB_SUBFR ];
+    opus_int                    Lambda_Q10;
+    opus_int                    input_quality_Q14;
+    opus_int                    coding_quality_Q14;
+
+    /* measures */
+    opus_int32                  predGain_Q16;
+    opus_int                    LTPredCodGain_Q7;
+    opus_int32                  ResNrg[ MAX_NB_SUBFR ];                 /* Residual energy per subframe                         */
+    opus_int                    ResNrgQ[ MAX_NB_SUBFR ];                /* Q domain for the residual energy > 0                 */
+
+    /* Parameters for CBR mode */
+    opus_int32                  GainsUnq_Q16[ MAX_NB_SUBFR ];
+    opus_int8                   lastGainIndexPrev;
+} silk_encoder_control_FIX;
+
+/************************/
+/* Encoder Super Struct */
+/************************/
+typedef struct {
+    silk_encoder_state_FIX      state_Fxx[ ENCODER_NUM_CHANNELS ];
+    stereo_enc_state            sStereo;
+    opus_int32                  nBitsUsedLBRR;
+    opus_int32                  nBitsExceeded;
+    opus_int                    nChannelsAPI;
+    opus_int                    nChannelsInternal;
+    opus_int                    nPrevChannelsInternal;
+    opus_int                    timeSinceSwitchAllowed_ms;
+    opus_int                    allowBandwidthSwitch;
+    opus_int                    prev_decode_only_middle;
+} silk_encoder;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/fixed/vector_ops_FIX.c b/opus/silk/fixed/vector_ops_FIX.c
new file mode 100644 (file)
index 0000000..d949800
--- /dev/null
@@ -0,0 +1,102 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "pitch.h"
+
+/* Copy and multiply a vector by a constant */
+void silk_scale_copy_vector16(
+    opus_int16                  *data_out,
+    const opus_int16            *data_in,
+    opus_int32                  gain_Q16,           /* I    Gain in Q16                                                 */
+    const opus_int              dataSize            /* I    Length                                                      */
+)
+{
+    opus_int  i;
+    opus_int32 tmp32;
+
+    for( i = 0; i < dataSize; i++ ) {
+        tmp32 = silk_SMULWB( gain_Q16, data_in[ i ] );
+        data_out[ i ] = (opus_int16)silk_CHECK_FIT16( tmp32 );
+    }
+}
+
+/* Multiply a vector by a constant */
+void silk_scale_vector32_Q26_lshift_18(
+    opus_int32                  *data1,             /* I/O  Q0/Q18                                                      */
+    opus_int32                  gain_Q26,           /* I    Q26                                                         */
+    opus_int                    dataSize            /* I    length                                                      */
+)
+{
+    opus_int  i;
+
+    for( i = 0; i < dataSize; i++ ) {
+        data1[ i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( silk_SMULL( data1[ i ], gain_Q26 ), 8 ) );    /* OUTPUT: Q18 */
+    }
+}
+
+/* sum = for(i=0;i<len;i++)inVec1[i]*inVec2[i];      ---        inner product   */
+/* Note for ARM asm:                                                            */
+/*        * inVec1 and inVec2 should be at least 2 byte aligned.                */
+/*        * len should be positive 16bit integer.                               */
+/*        * only when len>6, memory access can be reduced by half.              */
+opus_int32 silk_inner_prod_aligned(
+    const opus_int16 *const     inVec1,             /*    I input vector 1                                              */
+    const opus_int16 *const     inVec2,             /*    I input vector 2                                              */
+    const opus_int              len,                /*    I vector lengths                                              */
+    int                         arch                /*    I Run-time architecture                                       */
+)
+{
+#ifdef FIXED_POINT
+   return celt_inner_prod(inVec1, inVec2, len, arch);
+#else
+    opus_int   i;
+    opus_int32 sum = 0;
+    for( i = 0; i < len; i++ ) {
+        sum = silk_SMLABB( sum, inVec1[ i ], inVec2[ i ] );
+    }
+    return sum;
+#endif
+}
+
+opus_int64 silk_inner_prod16_aligned_64_c(
+    const opus_int16            *inVec1,            /*    I input vector 1                                              */
+    const opus_int16            *inVec2,            /*    I input vector 2                                              */
+    const opus_int              len                 /*    I vector lengths                                              */
+)
+{
+    opus_int   i;
+    opus_int64 sum = 0;
+    for( i = 0; i < len; i++ ) {
+        sum = silk_SMLALBB( sum, inVec1[ i ], inVec2[ i ] );
+    }
+    return sum;
+}
diff --git a/opus/silk/fixed/warped_autocorrelation_FIX.c b/opus/silk/fixed/warped_autocorrelation_FIX.c
new file mode 100644 (file)
index 0000000..994c299
--- /dev/null
@@ -0,0 +1,90 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FIX.h"
+
+#if defined(MIPSr1_ASM)
+#include "mips/warped_autocorrelation_FIX_mipsr1.h"
+#endif
+
+
+/* Autocorrelations for a warped frequency axis */
+void silk_warped_autocorrelation_FIX_c(
+          opus_int32                *corr,                                  /* O    Result [order + 1]                                                          */
+          opus_int                  *scale,                                 /* O    Scaling of the correlation vector                                           */
+    const opus_int16                *input,                                 /* I    Input data to correlate                                                     */
+    const opus_int                  warping_Q16,                            /* I    Warping coefficient                                                         */
+    const opus_int                  length,                                 /* I    Length of input                                                             */
+    const opus_int                  order                                   /* I    Correlation order (even)                                                    */
+)
+{
+    opus_int   n, i, lsh;
+    opus_int32 tmp1_QS, tmp2_QS;
+    opus_int32 state_QS[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
+    opus_int64 corr_QC[  MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };
+
+    /* Order must be even */
+    silk_assert( ( order & 1 ) == 0 );
+    silk_assert( 2 * QS - QC >= 0 );
+
+    /* Loop over samples */
+    for( n = 0; n < length; n++ ) {
+        tmp1_QS = silk_LSHIFT32( (opus_int32)input[ n ], QS );
+        /* Loop over allpass sections */
+        for( i = 0; i < order; i += 2 ) {
+            /* Output of allpass section */
+            tmp2_QS = silk_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );
+            state_QS[ i ]  = tmp1_QS;
+            corr_QC[  i ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
+            /* Output of allpass section */
+            tmp1_QS = silk_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );
+            state_QS[ i + 1 ]  = tmp2_QS;
+            corr_QC[  i + 1 ] += silk_RSHIFT64( silk_SMULL( tmp2_QS, state_QS[ 0 ] ), 2 * QS - QC );
+        }
+        state_QS[ order ] = tmp1_QS;
+        corr_QC[  order ] += silk_RSHIFT64( silk_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );
+    }
+
+    lsh = silk_CLZ64( corr_QC[ 0 ] ) - 35;
+    lsh = silk_LIMIT( lsh, -12 - QC, 30 - QC );
+    *scale = -( QC + lsh );
+    silk_assert( *scale >= -30 && *scale <= 12 );
+    if( lsh >= 0 ) {
+        for( i = 0; i < order + 1; i++ ) {
+            corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_LSHIFT64( corr_QC[ i ], lsh ) );
+        }
+    } else {
+        for( i = 0; i < order + 1; i++ ) {
+            corr[ i ] = (opus_int32)silk_CHECK_FIT32( silk_RSHIFT64( corr_QC[ i ], -lsh ) );
+        }
+    }
+    silk_assert( corr_QC[ 0 ] >= 0 ); /* If breaking, decrease QC*/
+}
diff --git a/opus/silk/fixed/x86/burg_modified_FIX_sse.c b/opus/silk/fixed/x86/burg_modified_FIX_sse.c
new file mode 100644 (file)
index 0000000..3c3583c
--- /dev/null
@@ -0,0 +1,377 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+
+#include "SigProc_FIX.h"
+#include "define.h"
+#include "tuning_parameters.h"
+#include "pitch.h"
+#include "celt/x86/x86cpu.h"
+
+#define MAX_FRAME_SIZE              384             /* subfr_length * nb_subfr = ( 0.005 * 16000 + 16 ) * 4 = 384 */
+
+#define QA                          25
+#define N_BITS_HEAD_ROOM            2
+#define MIN_RSHIFTS                 -16
+#define MAX_RSHIFTS                 (32 - QA)
+
+/* Compute reflection coefficients from input signal */
+void silk_burg_modified_sse4_1(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */
+)
+{
+    opus_int         k, n, s, lz, rshifts, rshifts_extra, reached_max_gain;
+    opus_int32       C0, num, nrg, rc_Q31, invGain_Q30, Atmp_QA, Atmp1, tmp1, tmp2, x1, x2;
+    const opus_int16 *x_ptr;
+    opus_int32       C_first_row[ SILK_MAX_ORDER_LPC ];
+    opus_int32       C_last_row[  SILK_MAX_ORDER_LPC ];
+    opus_int32       Af_QA[       SILK_MAX_ORDER_LPC ];
+    opus_int32       CAf[ SILK_MAX_ORDER_LPC + 1 ];
+    opus_int32       CAb[ SILK_MAX_ORDER_LPC + 1 ];
+    opus_int32       xcorr[ SILK_MAX_ORDER_LPC ];
+
+    __m128i FIRST_3210, LAST_3210, ATMP_3210, TMP1_3210, TMP2_3210, T1_3210, T2_3210, PTR_3210, SUBFR_3210, X1_3210, X2_3210;
+    __m128i CONST1 = _mm_set1_epi32(1);
+
+    silk_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE );
+
+    /* Compute autocorrelations, added over subframes */
+    silk_sum_sqr_shift( &C0, &rshifts, x, nb_subfr * subfr_length );
+    if( rshifts > MAX_RSHIFTS ) {
+        C0 = silk_LSHIFT32( C0, rshifts - MAX_RSHIFTS );
+        silk_assert( C0 > 0 );
+        rshifts = MAX_RSHIFTS;
+    } else {
+        lz = silk_CLZ32( C0 ) - 1;
+        rshifts_extra = N_BITS_HEAD_ROOM - lz;
+        if( rshifts_extra > 0 ) {
+            rshifts_extra = silk_min( rshifts_extra, MAX_RSHIFTS - rshifts );
+            C0 = silk_RSHIFT32( C0, rshifts_extra );
+        } else {
+            rshifts_extra = silk_max( rshifts_extra, MIN_RSHIFTS - rshifts );
+            C0 = silk_LSHIFT32( C0, -rshifts_extra );
+        }
+        rshifts += rshifts_extra;
+    }
+    CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1;                                /* Q(-rshifts) */
+    silk_memset( C_first_row, 0, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) );
+    if( rshifts > 0 ) {
+        for( s = 0; s < nb_subfr; s++ ) {
+            x_ptr = x + s * subfr_length;
+            for( n = 1; n < D + 1; n++ ) {
+                C_first_row[ n - 1 ] += (opus_int32)silk_RSHIFT64(
+                    silk_inner_prod16_aligned_64( x_ptr, x_ptr + n, subfr_length - n, arch ), rshifts );
+            }
+        }
+    } else {
+        for( s = 0; s < nb_subfr; s++ ) {
+            int i;
+            opus_int32 d;
+            x_ptr = x + s * subfr_length;
+            celt_pitch_xcorr(x_ptr, x_ptr + 1, xcorr, subfr_length - D, D, arch );
+            for( n = 1; n < D + 1; n++ ) {
+               for ( i = n + subfr_length - D, d = 0; i < subfr_length; i++ )
+                  d = MAC16_16( d, x_ptr[ i ], x_ptr[ i - n ] );
+               xcorr[ n - 1 ] += d;
+            }
+            for( n = 1; n < D + 1; n++ ) {
+                C_first_row[ n - 1 ] += silk_LSHIFT32( xcorr[ n - 1 ], -rshifts );
+            }
+        }
+    }
+    silk_memcpy( C_last_row, C_first_row, SILK_MAX_ORDER_LPC * sizeof( opus_int32 ) );
+
+    /* Initialize */
+    CAb[ 0 ] = CAf[ 0 ] = C0 + silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ) + 1;                                /* Q(-rshifts) */
+
+    invGain_Q30 = (opus_int32)1 << 30;
+    reached_max_gain = 0;
+    for( n = 0; n < D; n++ ) {
+        /* Update first row of correlation matrix (without first element) */
+        /* Update last row of correlation matrix (without last element, stored in reversed order) */
+        /* Update C * Af */
+        /* Update C * flipud(Af) (stored in reversed order) */
+        if( rshifts > -2 ) {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                x1  = -silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    16 - rshifts );        /* Q(16-rshifts) */
+                x2  = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 16 - rshifts );        /* Q(16-rshifts) */
+                tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    QA - 16 );             /* Q(QA-16) */
+                tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], QA - 16 );             /* Q(QA-16) */
+                for( k = 0; k < n; k++ ) {
+                    C_first_row[ k ] = silk_SMLAWB( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); /* Q( -rshifts ) */
+                    C_last_row[ k ]  = silk_SMLAWB( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */
+                    Atmp_QA = Af_QA[ k ];
+                    tmp1 = silk_SMLAWB( tmp1, Atmp_QA, x_ptr[ n - k - 1 ]            );                 /* Q(QA-16) */
+                    tmp2 = silk_SMLAWB( tmp2, Atmp_QA, x_ptr[ subfr_length - n + k ] );                 /* Q(QA-16) */
+                }
+                tmp1 = silk_LSHIFT32( -tmp1, 32 - QA - rshifts );                                       /* Q(16-rshifts) */
+                tmp2 = silk_LSHIFT32( -tmp2, 32 - QA - rshifts );                                       /* Q(16-rshifts) */
+                for( k = 0; k <= n; k++ ) {
+                    CAf[ k ] = silk_SMLAWB( CAf[ k ], tmp1, x_ptr[ n - k ]                    );        /* Q( -rshift ) */
+                    CAb[ k ] = silk_SMLAWB( CAb[ k ], tmp2, x_ptr[ subfr_length - n + k - 1 ] );        /* Q( -rshift ) */
+                }
+            }
+        } else {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                x1  = -silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    -rshifts );            /* Q( -rshifts ) */
+                x2  = -silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], -rshifts );            /* Q( -rshifts ) */
+                tmp1 = silk_LSHIFT32( (opus_int32)x_ptr[ n ],                    17 );                  /* Q17 */
+                tmp2 = silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n - 1 ], 17 );                  /* Q17 */
+
+                X1_3210 = _mm_set1_epi32( x1 );
+                X2_3210 = _mm_set1_epi32( x2 );
+                TMP1_3210 = _mm_setzero_si128();
+                TMP2_3210 = _mm_setzero_si128();
+                for( k = 0; k < n - 3; k += 4 ) {
+                    PTR_3210   = OP_CVTEPI16_EPI32_M64( &x_ptr[ n - k - 1 - 3 ] );
+                    SUBFR_3210 = OP_CVTEPI16_EPI32_M64( &x_ptr[ subfr_length - n + k ] );
+                    FIRST_3210 = _mm_loadu_si128( (__m128i *)&C_first_row[ k ] );
+                    PTR_3210   = _mm_shuffle_epi32( PTR_3210,  _MM_SHUFFLE( 0, 1, 2, 3 ) );
+                    LAST_3210  = _mm_loadu_si128( (__m128i *)&C_last_row[ k ] );
+                    ATMP_3210  = _mm_loadu_si128( (__m128i *)&Af_QA[ k ] );
+
+                    T1_3210 = _mm_mullo_epi32( PTR_3210, X1_3210 );
+                    T2_3210 = _mm_mullo_epi32( SUBFR_3210, X2_3210 );
+
+                    ATMP_3210 = _mm_srai_epi32( ATMP_3210, 7 );
+                    ATMP_3210 = _mm_add_epi32( ATMP_3210, CONST1 );
+                    ATMP_3210 = _mm_srai_epi32( ATMP_3210, 1 );
+
+                    FIRST_3210 = _mm_add_epi32( FIRST_3210, T1_3210 );
+                    LAST_3210 = _mm_add_epi32( LAST_3210, T2_3210 );
+
+                    PTR_3210   = _mm_mullo_epi32( ATMP_3210, PTR_3210 );
+                    SUBFR_3210   = _mm_mullo_epi32( ATMP_3210, SUBFR_3210 );
+
+                    _mm_storeu_si128( (__m128i *)&C_first_row[ k ], FIRST_3210 );
+                    _mm_storeu_si128( (__m128i *)&C_last_row[ k ], LAST_3210 );
+
+                    TMP1_3210 = _mm_add_epi32( TMP1_3210, PTR_3210 );
+                    TMP2_3210 = _mm_add_epi32( TMP2_3210, SUBFR_3210 );
+                }
+
+                TMP1_3210 = _mm_add_epi32( TMP1_3210, _mm_unpackhi_epi64(TMP1_3210, TMP1_3210 ) );
+                TMP2_3210 = _mm_add_epi32( TMP2_3210, _mm_unpackhi_epi64(TMP2_3210, TMP2_3210 ) );
+                TMP1_3210 = _mm_add_epi32( TMP1_3210, _mm_shufflelo_epi16(TMP1_3210, 0x0E ) );
+                TMP2_3210 = _mm_add_epi32( TMP2_3210, _mm_shufflelo_epi16(TMP2_3210, 0x0E ) );
+
+                tmp1 += _mm_cvtsi128_si32( TMP1_3210 );
+                tmp2 += _mm_cvtsi128_si32( TMP2_3210 );
+
+                for( ; k < n; k++ ) {
+                    C_first_row[ k ] = silk_MLA( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); /* Q( -rshifts ) */
+                    C_last_row[ k ]  = silk_MLA( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); /* Q( -rshifts ) */
+                    Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 17 );                                   /* Q17 */
+                    tmp1 = silk_MLA( tmp1, x_ptr[ n - k - 1 ],            Atmp1 );                      /* Q17 */
+                    tmp2 = silk_MLA( tmp2, x_ptr[ subfr_length - n + k ], Atmp1 );                      /* Q17 */
+                }
+
+                tmp1 = -tmp1;                /* Q17 */
+                tmp2 = -tmp2;                /* Q17 */
+
+                {
+                    __m128i xmm_tmp1, xmm_tmp2;
+                    __m128i xmm_x_ptr_n_k_x2x0, xmm_x_ptr_n_k_x3x1;
+                    __m128i xmm_x_ptr_sub_x2x0, xmm_x_ptr_sub_x3x1;
+
+                    xmm_tmp1 = _mm_set1_epi32( tmp1 );
+                    xmm_tmp2 = _mm_set1_epi32( tmp2 );
+
+                    for( k = 0; k <= n - 3; k += 4 ) {
+                        xmm_x_ptr_n_k_x2x0 = OP_CVTEPI16_EPI32_M64( &x_ptr[ n - k - 3 ] );
+                        xmm_x_ptr_sub_x2x0 = OP_CVTEPI16_EPI32_M64( &x_ptr[ subfr_length - n + k - 1 ] );
+
+                        xmm_x_ptr_n_k_x2x0 = _mm_shuffle_epi32( xmm_x_ptr_n_k_x2x0, _MM_SHUFFLE( 0, 1, 2, 3 ) );
+
+                        xmm_x_ptr_n_k_x2x0 = _mm_slli_epi32( xmm_x_ptr_n_k_x2x0, -rshifts - 1 );
+                        xmm_x_ptr_sub_x2x0 = _mm_slli_epi32( xmm_x_ptr_sub_x2x0, -rshifts - 1 );
+
+                        /* equal shift right 4 bytes, xmm_x_ptr_n_k_x3x1 = _mm_srli_si128(xmm_x_ptr_n_k_x2x0, 4)*/
+                        xmm_x_ptr_n_k_x3x1 = _mm_shuffle_epi32( xmm_x_ptr_n_k_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+                        xmm_x_ptr_sub_x3x1 = _mm_shuffle_epi32( xmm_x_ptr_sub_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+                        xmm_x_ptr_n_k_x2x0 = _mm_mul_epi32( xmm_x_ptr_n_k_x2x0, xmm_tmp1 );
+                        xmm_x_ptr_n_k_x3x1 = _mm_mul_epi32( xmm_x_ptr_n_k_x3x1, xmm_tmp1 );
+                        xmm_x_ptr_sub_x2x0 = _mm_mul_epi32( xmm_x_ptr_sub_x2x0, xmm_tmp2 );
+                        xmm_x_ptr_sub_x3x1 = _mm_mul_epi32( xmm_x_ptr_sub_x3x1, xmm_tmp2 );
+
+                        xmm_x_ptr_n_k_x2x0 = _mm_srli_epi64( xmm_x_ptr_n_k_x2x0, 16 );
+                        xmm_x_ptr_n_k_x3x1 = _mm_slli_epi64( xmm_x_ptr_n_k_x3x1, 16 );
+                        xmm_x_ptr_sub_x2x0 = _mm_srli_epi64( xmm_x_ptr_sub_x2x0, 16 );
+                        xmm_x_ptr_sub_x3x1 = _mm_slli_epi64( xmm_x_ptr_sub_x3x1, 16 );
+
+                        xmm_x_ptr_n_k_x2x0 = _mm_blend_epi16( xmm_x_ptr_n_k_x2x0, xmm_x_ptr_n_k_x3x1, 0xCC );
+                        xmm_x_ptr_sub_x2x0 = _mm_blend_epi16( xmm_x_ptr_sub_x2x0, xmm_x_ptr_sub_x3x1, 0xCC );
+
+                        X1_3210  = _mm_loadu_si128( (__m128i *)&CAf[ k ] );
+                        PTR_3210 = _mm_loadu_si128( (__m128i *)&CAb[ k ] );
+
+                        X1_3210  = _mm_add_epi32( X1_3210, xmm_x_ptr_n_k_x2x0 );
+                        PTR_3210 = _mm_add_epi32( PTR_3210, xmm_x_ptr_sub_x2x0 );
+
+                        _mm_storeu_si128( (__m128i *)&CAf[ k ], X1_3210 );
+                        _mm_storeu_si128( (__m128i *)&CAb[ k ], PTR_3210 );
+                    }
+
+                    for( ; k <= n; k++ ) {
+                        CAf[ k ] = silk_SMLAWW( CAf[ k ], tmp1,
+                            silk_LSHIFT32( (opus_int32)x_ptr[ n - k ], -rshifts - 1 ) );                    /* Q( -rshift ) */
+                        CAb[ k ] = silk_SMLAWW( CAb[ k ], tmp2,
+                            silk_LSHIFT32( (opus_int32)x_ptr[ subfr_length - n + k - 1 ], -rshifts - 1 ) ); /* Q( -rshift ) */
+                    }
+                }
+            }
+        }
+
+        /* Calculate nominator and denominator for the next order reflection (parcor) coefficient */
+        tmp1 = C_first_row[ n ];                                                                        /* Q( -rshifts ) */
+        tmp2 = C_last_row[ n ];                                                                         /* Q( -rshifts ) */
+        num  = 0;                                                                                       /* Q( -rshifts ) */
+        nrg  = silk_ADD32( CAb[ 0 ], CAf[ 0 ] );                                                        /* Q( 1-rshifts ) */
+        for( k = 0; k < n; k++ ) {
+            Atmp_QA = Af_QA[ k ];
+            lz = silk_CLZ32( silk_abs( Atmp_QA ) ) - 1;
+            lz = silk_min( 32 - QA, lz );
+            Atmp1 = silk_LSHIFT32( Atmp_QA, lz );                                                       /* Q( QA + lz ) */
+
+            tmp1 = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( C_last_row[  n - k - 1 ], Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            tmp2 = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( C_first_row[ n - k - 1 ], Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            num  = silk_ADD_LSHIFT32( num,  silk_SMMUL( CAb[ n - k ],             Atmp1 ), 32 - QA - lz );  /* Q( -rshifts ) */
+            nrg  = silk_ADD_LSHIFT32( nrg,  silk_SMMUL( silk_ADD32( CAb[ k + 1 ], CAf[ k + 1 ] ),
+                                                                                Atmp1 ), 32 - QA - lz );    /* Q( 1-rshifts ) */
+        }
+        CAf[ n + 1 ] = tmp1;                                                                            /* Q( -rshifts ) */
+        CAb[ n + 1 ] = tmp2;                                                                            /* Q( -rshifts ) */
+        num = silk_ADD32( num, tmp2 );                                                                  /* Q( -rshifts ) */
+        num = silk_LSHIFT32( -num, 1 );                                                                 /* Q( 1-rshifts ) */
+
+        /* Calculate the next order reflection (parcor) coefficient */
+        if( silk_abs( num ) < nrg ) {
+            rc_Q31 = silk_DIV32_varQ( num, nrg, 31 );
+        } else {
+            rc_Q31 = ( num > 0 ) ? silk_int32_MAX : silk_int32_MIN;
+        }
+
+        /* Update inverse prediction gain */
+        tmp1 = ( (opus_int32)1 << 30 ) - silk_SMMUL( rc_Q31, rc_Q31 );
+        tmp1 = silk_LSHIFT( silk_SMMUL( invGain_Q30, tmp1 ), 2 );
+        if( tmp1 <= minInvGain_Q30 ) {
+            /* Max prediction gain exceeded; set reflection coefficient such that max prediction gain is exactly hit */
+            tmp2 = ( (opus_int32)1 << 30 ) - silk_DIV32_varQ( minInvGain_Q30, invGain_Q30, 30 );            /* Q30 */
+            rc_Q31 = silk_SQRT_APPROX( tmp2 );                                                  /* Q15 */
+            if( rc_Q31 > 0 ) {
+                 /* Newton-Raphson iteration */
+                rc_Q31 = silk_RSHIFT32( rc_Q31 + silk_DIV32( tmp2, rc_Q31 ), 1 );                   /* Q15 */
+                rc_Q31 = silk_LSHIFT32( rc_Q31, 16 );                                               /* Q31 */
+                if( num < 0 ) {
+                    /* Ensure adjusted reflection coefficients has the original sign */
+                    rc_Q31 = -rc_Q31;
+                }
+            }
+            invGain_Q30 = minInvGain_Q30;
+            reached_max_gain = 1;
+        } else {
+            invGain_Q30 = tmp1;
+        }
+
+        /* Update the AR coefficients */
+        for( k = 0; k < (n + 1) >> 1; k++ ) {
+            tmp1 = Af_QA[ k ];                                                                  /* QA */
+            tmp2 = Af_QA[ n - k - 1 ];                                                          /* QA */
+            Af_QA[ k ]         = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 );      /* QA */
+            Af_QA[ n - k - 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 );      /* QA */
+        }
+        Af_QA[ n ] = silk_RSHIFT32( rc_Q31, 31 - QA );                                          /* QA */
+
+        if( reached_max_gain ) {
+            /* Reached max prediction gain; set remaining coefficients to zero and exit loop */
+            for( k = n + 1; k < D; k++ ) {
+                Af_QA[ k ] = 0;
+            }
+            break;
+        }
+
+        /* Update C * Af and C * Ab */
+        for( k = 0; k <= n + 1; k++ ) {
+            tmp1 = CAf[ k ];                                                                    /* Q( -rshifts ) */
+            tmp2 = CAb[ n - k + 1 ];                                                            /* Q( -rshifts ) */
+            CAf[ k ]         = silk_ADD_LSHIFT32( tmp1, silk_SMMUL( tmp2, rc_Q31 ), 1 );        /* Q( -rshifts ) */
+            CAb[ n - k + 1 ] = silk_ADD_LSHIFT32( tmp2, silk_SMMUL( tmp1, rc_Q31 ), 1 );        /* Q( -rshifts ) */
+        }
+    }
+
+    if( reached_max_gain ) {
+        for( k = 0; k < D; k++ ) {
+            /* Scale coefficients */
+            A_Q16[ k ] = -silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 );
+        }
+        /* Subtract energy of preceding samples from C0 */
+        if( rshifts > 0 ) {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                C0 -= (opus_int32)silk_RSHIFT64( silk_inner_prod16_aligned_64( x_ptr, x_ptr, D, arch ), rshifts );
+            }
+        } else {
+            for( s = 0; s < nb_subfr; s++ ) {
+                x_ptr = x + s * subfr_length;
+                C0 -= silk_LSHIFT32( silk_inner_prod_aligned( x_ptr, x_ptr, D, arch ), -rshifts );
+            }
+        }
+        /* Approximate residual energy */
+        *res_nrg = silk_LSHIFT( silk_SMMUL( invGain_Q30, C0 ), 2 );
+        *res_nrg_Q = -rshifts;
+    } else {
+        /* Return residual energy */
+        nrg  = CAf[ 0 ];                                                                            /* Q( -rshifts ) */
+        tmp1 = (opus_int32)1 << 16;                                                                             /* Q16 */
+        for( k = 0; k < D; k++ ) {
+            Atmp1 = silk_RSHIFT_ROUND( Af_QA[ k ], QA - 16 );                                       /* Q16 */
+            nrg  = silk_SMLAWW( nrg, CAf[ k + 1 ], Atmp1 );                                         /* Q( -rshifts ) */
+            tmp1 = silk_SMLAWW( tmp1, Atmp1, Atmp1 );                                               /* Q16 */
+            A_Q16[ k ] = -Atmp1;
+        }
+        *res_nrg = silk_SMLAWW( nrg, silk_SMMUL( SILK_FIX_CONST( FIND_LPC_COND_FAC, 32 ), C0 ), -tmp1 );/* Q( -rshifts ) */
+        *res_nrg_Q = -rshifts;
+    }
+}
diff --git a/opus/silk/fixed/x86/vector_ops_FIX_sse.c b/opus/silk/fixed/x86/vector_ops_FIX_sse.c
new file mode 100644 (file)
index 0000000..c1e9056
--- /dev/null
@@ -0,0 +1,88 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+#include "main.h"
+
+#include "SigProc_FIX.h"
+#include "pitch.h"
+
+opus_int64 silk_inner_prod16_aligned_64_sse4_1(
+    const opus_int16            *inVec1,            /*    I input vector 1                                              */
+    const opus_int16            *inVec2,            /*    I input vector 2                                              */
+    const opus_int              len                 /*    I vector lengths                                              */
+)
+{
+    opus_int  i, dataSize8;
+    opus_int64 sum;
+
+    __m128i xmm_tempa;
+    __m128i inVec1_76543210, acc1;
+    __m128i inVec2_76543210, acc2;
+
+    sum = 0;
+    dataSize8 = len & ~7;
+
+    acc1 = _mm_setzero_si128();
+    acc2 = _mm_setzero_si128();
+
+    for( i = 0; i < dataSize8; i += 8 ) {
+        inVec1_76543210 = _mm_loadu_si128( (__m128i *)(&inVec1[i + 0] ) );
+        inVec2_76543210 = _mm_loadu_si128( (__m128i *)(&inVec2[i + 0] ) );
+
+        /* only when all 4 operands are -32768 (0x8000), this results in wrap around */
+        inVec1_76543210 = _mm_madd_epi16( inVec1_76543210, inVec2_76543210 );
+
+        xmm_tempa       = _mm_cvtepi32_epi64( inVec1_76543210 );
+        /* equal shift right 8 bytes */
+        inVec1_76543210 = _mm_shuffle_epi32( inVec1_76543210, _MM_SHUFFLE( 0, 0, 3, 2 ) );
+        inVec1_76543210 = _mm_cvtepi32_epi64( inVec1_76543210 );
+
+        acc1 = _mm_add_epi64( acc1, xmm_tempa );
+        acc2 = _mm_add_epi64( acc2, inVec1_76543210 );
+    }
+
+    acc1 = _mm_add_epi64( acc1, acc2 );
+
+    /* equal shift right 8 bytes */
+    acc2 = _mm_shuffle_epi32( acc1, _MM_SHUFFLE( 0, 0, 3, 2 ) );
+    acc1 = _mm_add_epi64( acc1, acc2 );
+
+    _mm_storel_epi64( (__m128i *)&sum, acc1 );
+
+    for( ; i < len; i++ ) {
+        sum = silk_SMLABB( sum, inVec1[ i ], inVec2[ i ] );
+    }
+
+    return sum;
+}
diff --git a/opus/silk/float/LPC_analysis_filter_FLP.c b/opus/silk/float/LPC_analysis_filter_FLP.c
new file mode 100644 (file)
index 0000000..cae89a0
--- /dev/null
@@ -0,0 +1,249 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include "main_FLP.h"
+
+/************************************************/
+/* LPC analysis filter                          */
+/* NB! State is kept internally and the         */
+/* filter always starts with zero state         */
+/* first Order output samples are set to zero   */
+/************************************************/
+
+/* 16th order LPC analysis filter, does not write first 16 samples */
+static OPUS_INLINE void silk_LPC_analysis_filter16_FLP(
+          silk_float                 r_LPC[],            /* O    LPC residual signal                     */
+    const silk_float                 PredCoef[],         /* I    LPC coefficients                        */
+    const silk_float                 s[],                /* I    Input signal                            */
+    const opus_int                   length              /* I    Length of input signal                  */
+)
+{
+    opus_int   ix;
+    silk_float LPC_pred;
+    const silk_float *s_ptr;
+
+    for( ix = 16; ix < length; ix++ ) {
+        s_ptr = &s[ix - 1];
+
+        /* short-term prediction */
+        LPC_pred = s_ptr[  0 ]  * PredCoef[ 0 ]  +
+                   s_ptr[ -1 ]  * PredCoef[ 1 ]  +
+                   s_ptr[ -2 ]  * PredCoef[ 2 ]  +
+                   s_ptr[ -3 ]  * PredCoef[ 3 ]  +
+                   s_ptr[ -4 ]  * PredCoef[ 4 ]  +
+                   s_ptr[ -5 ]  * PredCoef[ 5 ]  +
+                   s_ptr[ -6 ]  * PredCoef[ 6 ]  +
+                   s_ptr[ -7 ]  * PredCoef[ 7 ]  +
+                   s_ptr[ -8 ]  * PredCoef[ 8 ]  +
+                   s_ptr[ -9 ]  * PredCoef[ 9 ]  +
+                   s_ptr[ -10 ] * PredCoef[ 10 ] +
+                   s_ptr[ -11 ] * PredCoef[ 11 ] +
+                   s_ptr[ -12 ] * PredCoef[ 12 ] +
+                   s_ptr[ -13 ] * PredCoef[ 13 ] +
+                   s_ptr[ -14 ] * PredCoef[ 14 ] +
+                   s_ptr[ -15 ] * PredCoef[ 15 ];
+
+        /* prediction error */
+        r_LPC[ix] = s_ptr[ 1 ] - LPC_pred;
+    }
+}
+
+/* 12th order LPC analysis filter, does not write first 12 samples */
+static OPUS_INLINE void silk_LPC_analysis_filter12_FLP(
+          silk_float                 r_LPC[],            /* O    LPC residual signal                     */
+    const silk_float                 PredCoef[],         /* I    LPC coefficients                        */
+    const silk_float                 s[],                /* I    Input signal                            */
+    const opus_int                   length              /* I    Length of input signal                  */
+)
+{
+    opus_int   ix;
+    silk_float LPC_pred;
+    const silk_float *s_ptr;
+
+    for( ix = 12; ix < length; ix++ ) {
+        s_ptr = &s[ix - 1];
+
+        /* short-term prediction */
+        LPC_pred = s_ptr[  0 ]  * PredCoef[ 0 ]  +
+                   s_ptr[ -1 ]  * PredCoef[ 1 ]  +
+                   s_ptr[ -2 ]  * PredCoef[ 2 ]  +
+                   s_ptr[ -3 ]  * PredCoef[ 3 ]  +
+                   s_ptr[ -4 ]  * PredCoef[ 4 ]  +
+                   s_ptr[ -5 ]  * PredCoef[ 5 ]  +
+                   s_ptr[ -6 ]  * PredCoef[ 6 ]  +
+                   s_ptr[ -7 ]  * PredCoef[ 7 ]  +
+                   s_ptr[ -8 ]  * PredCoef[ 8 ]  +
+                   s_ptr[ -9 ]  * PredCoef[ 9 ]  +
+                   s_ptr[ -10 ] * PredCoef[ 10 ] +
+                   s_ptr[ -11 ] * PredCoef[ 11 ];
+
+        /* prediction error */
+        r_LPC[ix] = s_ptr[ 1 ] - LPC_pred;
+    }
+}
+
+/* 10th order LPC analysis filter, does not write first 10 samples */
+static OPUS_INLINE void silk_LPC_analysis_filter10_FLP(
+          silk_float                 r_LPC[],            /* O    LPC residual signal                     */
+    const silk_float                 PredCoef[],         /* I    LPC coefficients                        */
+    const silk_float                 s[],                /* I    Input signal                            */
+    const opus_int                   length              /* I    Length of input signal                  */
+)
+{
+    opus_int   ix;
+    silk_float LPC_pred;
+    const silk_float *s_ptr;
+
+    for( ix = 10; ix < length; ix++ ) {
+        s_ptr = &s[ix - 1];
+
+        /* short-term prediction */
+        LPC_pred = s_ptr[  0 ] * PredCoef[ 0 ]  +
+                   s_ptr[ -1 ] * PredCoef[ 1 ]  +
+                   s_ptr[ -2 ] * PredCoef[ 2 ]  +
+                   s_ptr[ -3 ] * PredCoef[ 3 ]  +
+                   s_ptr[ -4 ] * PredCoef[ 4 ]  +
+                   s_ptr[ -5 ] * PredCoef[ 5 ]  +
+                   s_ptr[ -6 ] * PredCoef[ 6 ]  +
+                   s_ptr[ -7 ] * PredCoef[ 7 ]  +
+                   s_ptr[ -8 ] * PredCoef[ 8 ]  +
+                   s_ptr[ -9 ] * PredCoef[ 9 ];
+
+        /* prediction error */
+        r_LPC[ix] = s_ptr[ 1 ] - LPC_pred;
+    }
+}
+
+/* 8th order LPC analysis filter, does not write first 8 samples */
+static OPUS_INLINE void silk_LPC_analysis_filter8_FLP(
+          silk_float                 r_LPC[],            /* O    LPC residual signal                     */
+    const silk_float                 PredCoef[],         /* I    LPC coefficients                        */
+    const silk_float                 s[],                /* I    Input signal                            */
+    const opus_int                   length              /* I    Length of input signal                  */
+)
+{
+    opus_int   ix;
+    silk_float LPC_pred;
+    const silk_float *s_ptr;
+
+    for( ix = 8; ix < length; ix++ ) {
+        s_ptr = &s[ix - 1];
+
+        /* short-term prediction */
+        LPC_pred = s_ptr[  0 ] * PredCoef[ 0 ]  +
+                   s_ptr[ -1 ] * PredCoef[ 1 ]  +
+                   s_ptr[ -2 ] * PredCoef[ 2 ]  +
+                   s_ptr[ -3 ] * PredCoef[ 3 ]  +
+                   s_ptr[ -4 ] * PredCoef[ 4 ]  +
+                   s_ptr[ -5 ] * PredCoef[ 5 ]  +
+                   s_ptr[ -6 ] * PredCoef[ 6 ]  +
+                   s_ptr[ -7 ] * PredCoef[ 7 ];
+
+        /* prediction error */
+        r_LPC[ix] = s_ptr[ 1 ] - LPC_pred;
+    }
+}
+
+/* 6th order LPC analysis filter, does not write first 6 samples */
+static OPUS_INLINE void silk_LPC_analysis_filter6_FLP(
+          silk_float                 r_LPC[],            /* O    LPC residual signal                     */
+    const silk_float                 PredCoef[],         /* I    LPC coefficients                        */
+    const silk_float                 s[],                /* I    Input signal                            */
+    const opus_int                   length              /* I    Length of input signal                  */
+)
+{
+    opus_int   ix;
+    silk_float LPC_pred;
+    const silk_float *s_ptr;
+
+    for( ix = 6; ix < length; ix++ ) {
+        s_ptr = &s[ix - 1];
+
+        /* short-term prediction */
+        LPC_pred = s_ptr[  0 ] * PredCoef[ 0 ]  +
+                   s_ptr[ -1 ] * PredCoef[ 1 ]  +
+                   s_ptr[ -2 ] * PredCoef[ 2 ]  +
+                   s_ptr[ -3 ] * PredCoef[ 3 ]  +
+                   s_ptr[ -4 ] * PredCoef[ 4 ]  +
+                   s_ptr[ -5 ] * PredCoef[ 5 ];
+
+        /* prediction error */
+        r_LPC[ix] = s_ptr[ 1 ] - LPC_pred;
+    }
+}
+
+/************************************************/
+/* LPC analysis filter                          */
+/* NB! State is kept internally and the         */
+/* filter always starts with zero state         */
+/* first Order output samples are set to zero   */
+/************************************************/
+void silk_LPC_analysis_filter_FLP(
+    silk_float                      r_LPC[],                            /* O    LPC residual signal                         */
+    const silk_float                PredCoef[],                         /* I    LPC coefficients                            */
+    const silk_float                s[],                                /* I    Input signal                                */
+    const opus_int                  length,                             /* I    Length of input signal                      */
+    const opus_int                  Order                               /* I    LPC order                                   */
+)
+{
+    silk_assert( Order <= length );
+
+    switch( Order ) {
+        case 6:
+            silk_LPC_analysis_filter6_FLP(  r_LPC, PredCoef, s, length );
+        break;
+
+        case 8:
+            silk_LPC_analysis_filter8_FLP(  r_LPC, PredCoef, s, length );
+        break;
+
+        case 10:
+            silk_LPC_analysis_filter10_FLP( r_LPC, PredCoef, s, length );
+        break;
+
+        case 12:
+            silk_LPC_analysis_filter12_FLP( r_LPC, PredCoef, s, length );
+        break;
+
+        case 16:
+            silk_LPC_analysis_filter16_FLP( r_LPC, PredCoef, s, length );
+        break;
+
+        default:
+            silk_assert( 0 );
+        break;
+    }
+
+    /* Set first Order output samples to zero */
+    silk_memset( r_LPC, 0, Order * sizeof( silk_float ) );
+}
+
diff --git a/opus/silk/float/LPC_inv_pred_gain_FLP.c b/opus/silk/float/LPC_inv_pred_gain_FLP.c
new file mode 100644 (file)
index 0000000..2be2122
--- /dev/null
@@ -0,0 +1,73 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "SigProc_FLP.h"
+#include "define.h"
+
+/* compute inverse of LPC prediction gain, and                          */
+/* test if LPC coefficients are stable (all poles within unit circle)   */
+/* this code is based on silk_a2k_FLP()                                 */
+silk_float silk_LPC_inverse_pred_gain_FLP(  /* O    return inverse prediction gain, energy domain               */
+    const silk_float    *A,                 /* I    prediction coefficients [order]                             */
+    opus_int32          order               /* I    prediction order                                            */
+)
+{
+    opus_int   k, n;
+    double     invGain, rc, rc_mult1, rc_mult2, tmp1, tmp2;
+    silk_float Atmp[ SILK_MAX_ORDER_LPC ];
+
+    silk_memcpy( Atmp, A, order * sizeof(silk_float) );
+
+    invGain = 1.0;
+    for( k = order - 1; k > 0; k-- ) {
+        rc = -Atmp[ k ];
+        rc_mult1 = 1.0f - rc * rc;
+        invGain *= rc_mult1;
+        if( invGain * MAX_PREDICTION_POWER_GAIN < 1.0f ) {
+            return 0.0f;
+        }
+        rc_mult2 = 1.0f / rc_mult1;
+        for( n = 0; n < (k + 1) >> 1; n++ ) {
+            tmp1 = Atmp[ n ];
+            tmp2 = Atmp[ k - n - 1 ];
+            Atmp[ n ]         = (silk_float)( ( tmp1 - tmp2 * rc ) * rc_mult2 );
+            Atmp[ k - n - 1 ] = (silk_float)( ( tmp2 - tmp1 * rc ) * rc_mult2 );
+        }
+    }
+    rc = -Atmp[ 0 ];
+    rc_mult1 = 1.0f - rc * rc;
+    invGain *= rc_mult1;
+    if( invGain * MAX_PREDICTION_POWER_GAIN < 1.0f ) {
+        return 0.0f;
+    }
+    return (silk_float)invGain;
+}
diff --git a/opus/silk/float/LTP_analysis_filter_FLP.c b/opus/silk/float/LTP_analysis_filter_FLP.c
new file mode 100644 (file)
index 0000000..849b7c1
--- /dev/null
@@ -0,0 +1,75 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+void silk_LTP_analysis_filter_FLP(
+    silk_float                      *LTP_res,                           /* O    LTP res MAX_NB_SUBFR*(pre_lgth+subfr_lngth) */
+    const silk_float                *x,                                 /* I    Input signal, with preceding samples        */
+    const silk_float                B[ LTP_ORDER * MAX_NB_SUBFR ],      /* I    LTP coefficients for each subframe          */
+    const opus_int                  pitchL[   MAX_NB_SUBFR ],           /* I    Pitch lags                                  */
+    const silk_float                invGains[ MAX_NB_SUBFR ],           /* I    Inverse quantization gains                  */
+    const opus_int                  subfr_length,                       /* I    Length of each subframe                     */
+    const opus_int                  nb_subfr,                           /* I    number of subframes                         */
+    const opus_int                  pre_length                          /* I    Preceding samples for each subframe         */
+)
+{
+    const silk_float *x_ptr, *x_lag_ptr;
+    silk_float   Btmp[ LTP_ORDER ];
+    silk_float   *LTP_res_ptr;
+    silk_float   inv_gain;
+    opus_int     k, i, j;
+
+    x_ptr = x;
+    LTP_res_ptr = LTP_res;
+    for( k = 0; k < nb_subfr; k++ ) {
+        x_lag_ptr = x_ptr - pitchL[ k ];
+        inv_gain = invGains[ k ];
+        for( i = 0; i < LTP_ORDER; i++ ) {
+            Btmp[ i ] = B[ k * LTP_ORDER + i ];
+        }
+
+        /* LTP analysis FIR filter */
+        for( i = 0; i < subfr_length + pre_length; i++ ) {
+            LTP_res_ptr[ i ] = x_ptr[ i ];
+            /* Subtract long-term prediction */
+            for( j = 0; j < LTP_ORDER; j++ ) {
+                LTP_res_ptr[ i ] -= Btmp[ j ] * x_lag_ptr[ LTP_ORDER / 2 - j ];
+            }
+            LTP_res_ptr[ i ] *= inv_gain;
+            x_lag_ptr++;
+        }
+
+        /* Update pointers */
+        LTP_res_ptr += subfr_length + pre_length;
+        x_ptr       += subfr_length;
+    }
+}
diff --git a/opus/silk/float/LTP_scale_ctrl_FLP.c b/opus/silk/float/LTP_scale_ctrl_FLP.c
new file mode 100644 (file)
index 0000000..8dbe29d
--- /dev/null
@@ -0,0 +1,52 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+void silk_LTP_scale_ctrl_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+)
+{
+    opus_int   round_loss;
+
+    if( condCoding == CODE_INDEPENDENTLY ) {
+        /* Only scale if first frame in packet */
+        round_loss = psEnc->sCmn.PacketLoss_perc + psEnc->sCmn.nFramesPerPacket;
+        psEnc->sCmn.indices.LTP_scaleIndex = (opus_int8)silk_LIMIT( round_loss * psEncCtrl->LTPredCodGain * 0.1f, 0.0f, 2.0f );
+    } else {
+        /* Default is minimum scaling */
+        psEnc->sCmn.indices.LTP_scaleIndex = 0;
+    }
+
+    psEncCtrl->LTP_scale = (silk_float)silk_LTPScales_table_Q14[ psEnc->sCmn.indices.LTP_scaleIndex ] / 16384.0f;
+}
diff --git a/opus/silk/float/SigProc_FLP.h b/opus/silk/float/SigProc_FLP.h
new file mode 100644 (file)
index 0000000..953de8b
--- /dev/null
@@ -0,0 +1,197 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_SIGPROC_FLP_H
+#define SILK_SIGPROC_FLP_H
+
+#include "SigProc_FIX.h"
+#include "float_cast.h"
+#include <math.h>
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+/********************************************************************/
+/*                    SIGNAL PROCESSING FUNCTIONS                   */
+/********************************************************************/
+
+/* Chirp (bw expand) LP AR filter */
+void silk_bwexpander_FLP(
+    silk_float          *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int      d,                  /* I    length of ar                                                */
+    const silk_float    chirp               /* I    chirp factor (typically in range (0..1) )                   */
+);
+
+/* compute inverse of LPC prediction gain, and                          */
+/* test if LPC coefficients are stable (all poles within unit circle)   */
+/* this code is based on silk_FLP_a2k()                                 */
+silk_float silk_LPC_inverse_pred_gain_FLP(  /* O    return inverse prediction gain, energy domain               */
+    const silk_float    *A,                 /* I    prediction coefficients [order]                             */
+    opus_int32          order               /* I    prediction order                                            */
+);
+
+silk_float silk_schur_FLP(                  /* O    returns residual energy                                     */
+    silk_float          refl_coef[],        /* O    reflection coefficients (length order)                      */
+    const silk_float    auto_corr[],        /* I    autocorrelation sequence (length order+1)                   */
+    opus_int            order               /* I    order                                                       */
+);
+
+void silk_k2a_FLP(
+    silk_float          *A,                 /* O     prediction coefficients [order]                            */
+    const silk_float    *rc,                /* I     reflection coefficients [order]                            */
+    opus_int32          order               /* I     prediction order                                           */
+);
+
+/* compute autocorrelation */
+void silk_autocorrelation_FLP(
+    silk_float          *results,           /* O    result (length correlationCount)                            */
+    const silk_float    *inputData,         /* I    input data to correlate                                     */
+    opus_int            inputDataSize,      /* I    length of input                                             */
+    opus_int            correlationCount    /* I    number of correlation taps to compute                       */
+);
+
+opus_int silk_pitch_analysis_core_FLP(      /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */
+    const silk_float    *frame,             /* I    Signal of length PE_FRAME_LENGTH_MS*Fs_kHz                  */
+    opus_int            *pitch_out,         /* O    Pitch lag values [nb_subfr]                                 */
+    opus_int16          *lagIndex,          /* O    Lag Index                                                   */
+    opus_int8           *contourIndex,      /* O    Pitch contour Index                                         */
+    silk_float          *LTPCorr,           /* I/O  Normalized correlation; input: value from previous frame    */
+    opus_int            prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */
+    const silk_float    search_thres1,      /* I    First stage threshold for lag candidates 0 - 1              */
+    const silk_float    search_thres2,      /* I    Final threshold for lag candidates 0 - 1                    */
+    const opus_int      Fs_kHz,             /* I    sample frequency (kHz)                                      */
+    const opus_int      complexity,         /* I    Complexity setting, 0-2, where 2 is highest                 */
+    const opus_int      nb_subfr,           /* I    Number of 5 ms subframes                                    */
+    int                 arch                /* I    Run-time architecture                                       */
+);
+
+void silk_insertion_sort_decreasing_FLP(
+    silk_float          *a,                 /* I/O  Unsorted / Sorted vector                                    */
+    opus_int            *idx,               /* O    Index vector for the sorted elements                        */
+    const opus_int      L,                  /* I    Vector length                                               */
+    const opus_int      K                   /* I    Number of correctly sorted positions                        */
+);
+
+/* Compute reflection coefficients from input signal */
+silk_float silk_burg_modified_FLP(          /* O    returns residual energy                                     */
+    silk_float          A[],                /* O    prediction coefficients (length order)                      */
+    const silk_float    x[],                /* I    input signal, length: nb_subfr*(D+L_sub)                    */
+    const silk_float    minInvGain,         /* I    minimum inverse prediction gain                             */
+    const opus_int      subfr_length,       /* I    input signal subframe length (incl. D preceding samples)    */
+    const opus_int      nb_subfr,           /* I    number of subframes stacked in x                            */
+    const opus_int      D                   /* I    order                                                       */
+);
+
+/* multiply a vector by a constant */
+void silk_scale_vector_FLP(
+    silk_float          *data1,
+    silk_float          gain,
+    opus_int            dataSize
+);
+
+/* copy and multiply a vector by a constant */
+void silk_scale_copy_vector_FLP(
+    silk_float          *data_out,
+    const silk_float    *data_in,
+    silk_float          gain,
+    opus_int            dataSize
+);
+
+/* inner product of two silk_float arrays, with result as double */
+double silk_inner_product_FLP(
+    const silk_float    *data1,
+    const silk_float    *data2,
+    opus_int            dataSize
+);
+
+/* sum of squares of a silk_float array, with result as double */
+double silk_energy_FLP(
+    const silk_float    *data,
+    opus_int            dataSize
+);
+
+/********************************************************************/
+/*                                MACROS                            */
+/********************************************************************/
+
+#define PI              (3.1415926536f)
+
+#define silk_min_float( a, b )                  (((a) < (b)) ? (a) :  (b))
+#define silk_max_float( a, b )                  (((a) > (b)) ? (a) :  (b))
+#define silk_abs_float( a )                     ((silk_float)fabs(a))
+
+/* sigmoid function */
+static OPUS_INLINE silk_float silk_sigmoid( silk_float x )
+{
+    return (silk_float)(1.0 / (1.0 + exp(-x)));
+}
+
+/* floating-point to integer conversion (rounding) */
+static OPUS_INLINE opus_int32 silk_float2int( silk_float x )
+{
+    return (opus_int32)float2int( x );
+}
+
+/* floating-point to integer conversion (rounding) */
+static OPUS_INLINE void silk_float2short_array(
+    opus_int16       *out,
+    const silk_float *in,
+    opus_int32       length
+)
+{
+    opus_int32 k;
+    for( k = length - 1; k >= 0; k-- ) {
+        out[k] = silk_SAT16( (opus_int32)float2int( in[k] ) );
+    }
+}
+
+/* integer to floating-point conversion */
+static OPUS_INLINE void silk_short2float_array(
+    silk_float       *out,
+    const opus_int16 *in,
+    opus_int32       length
+)
+{
+    opus_int32 k;
+    for( k = length - 1; k >= 0; k-- ) {
+        out[k] = (silk_float)in[k];
+    }
+}
+
+/* using log2() helps the fixed-point conversion */
+static OPUS_INLINE silk_float silk_log2( double x )
+{
+    return ( silk_float )( 3.32192809488736 * log10( x ) );
+}
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif /* SILK_SIGPROC_FLP_H */
diff --git a/opus/silk/float/apply_sine_window_FLP.c b/opus/silk/float/apply_sine_window_FLP.c
new file mode 100644 (file)
index 0000000..6aae57c
--- /dev/null
@@ -0,0 +1,81 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+/* Apply sine window to signal vector   */
+/* Window types:                        */
+/*  1 -> sine window from 0 to pi/2     */
+/*  2 -> sine window from pi/2 to pi    */
+void silk_apply_sine_window_FLP(
+    silk_float                      px_win[],                           /* O    Pointer to windowed signal                  */
+    const silk_float                px[],                               /* I    Pointer to input signal                     */
+    const opus_int                  win_type,                           /* I    Selects a window type                       */
+    const opus_int                  length                              /* I    Window length, multiple of 4                */
+)
+{
+    opus_int   k;
+    silk_float freq, c, S0, S1;
+
+    silk_assert( win_type == 1 || win_type == 2 );
+
+    /* Length must be multiple of 4 */
+    silk_assert( ( length & 3 ) == 0 );
+
+    freq = PI / ( length + 1 );
+
+    /* Approximation of 2 * cos(f) */
+    c = 2.0f - freq * freq;
+
+    /* Initialize state */
+    if( win_type < 2 ) {
+        /* Start from 0 */
+        S0 = 0.0f;
+        /* Approximation of sin(f) */
+        S1 = freq;
+    } else {
+        /* Start from 1 */
+        S0 = 1.0f;
+        /* Approximation of cos(f) */
+        S1 = 0.5f * c;
+    }
+
+    /* Uses the recursive equation:   sin(n*f) = 2 * cos(f) * sin((n-1)*f) - sin((n-2)*f)   */
+    /* 4 samples at a time */
+    for( k = 0; k < length; k += 4 ) {
+        px_win[ k + 0 ] = px[ k + 0 ] * 0.5f * ( S0 + S1 );
+        px_win[ k + 1 ] = px[ k + 1 ] * S1;
+        S0 = c * S1 - S0;
+        px_win[ k + 2 ] = px[ k + 2 ] * 0.5f * ( S1 + S0 );
+        px_win[ k + 3 ] = px[ k + 3 ] * S0;
+        S1 = c * S0 - S1;
+    }
+}
diff --git a/opus/silk/float/autocorrelation_FLP.c b/opus/silk/float/autocorrelation_FLP.c
new file mode 100644 (file)
index 0000000..8b8a9e6
--- /dev/null
@@ -0,0 +1,52 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "typedef.h"
+#include "SigProc_FLP.h"
+
+/* compute autocorrelation */
+void silk_autocorrelation_FLP(
+    silk_float          *results,           /* O    result (length correlationCount)                            */
+    const silk_float    *inputData,         /* I    input data to correlate                                     */
+    opus_int            inputDataSize,      /* I    length of input                                             */
+    opus_int            correlationCount    /* I    number of correlation taps to compute                       */
+)
+{
+    opus_int i;
+
+    if( correlationCount > inputDataSize ) {
+        correlationCount = inputDataSize;
+    }
+
+    for( i = 0; i < correlationCount; i++ ) {
+        results[ i ] =  (silk_float)silk_inner_product_FLP( inputData, inputData + i, inputDataSize - i );
+    }
+}
diff --git a/opus/silk/float/burg_modified_FLP.c b/opus/silk/float/burg_modified_FLP.c
new file mode 100644 (file)
index 0000000..ea5dc25
--- /dev/null
@@ -0,0 +1,186 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+#include "tuning_parameters.h"
+#include "define.h"
+
+#define MAX_FRAME_SIZE              384 /* subfr_length * nb_subfr = ( 0.005 * 16000 + 16 ) * 4 = 384*/
+
+/* Compute reflection coefficients from input signal */
+silk_float silk_burg_modified_FLP(          /* O    returns residual energy                                     */
+    silk_float          A[],                /* O    prediction coefficients (length order)                      */
+    const silk_float    x[],                /* I    input signal, length: nb_subfr*(D+L_sub)                    */
+    const silk_float    minInvGain,         /* I    minimum inverse prediction gain                             */
+    const opus_int      subfr_length,       /* I    input signal subframe length (incl. D preceding samples)    */
+    const opus_int      nb_subfr,           /* I    number of subframes stacked in x                            */
+    const opus_int      D                   /* I    order                                                       */
+)
+{
+    opus_int         k, n, s, reached_max_gain;
+    double           C0, invGain, num, nrg_f, nrg_b, rc, Atmp, tmp1, tmp2;
+    const silk_float *x_ptr;
+    double           C_first_row[ SILK_MAX_ORDER_LPC ], C_last_row[ SILK_MAX_ORDER_LPC ];
+    double           CAf[ SILK_MAX_ORDER_LPC + 1 ], CAb[ SILK_MAX_ORDER_LPC + 1 ];
+    double           Af[ SILK_MAX_ORDER_LPC ];
+
+    silk_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE );
+
+    /* Compute autocorrelations, added over subframes */
+    C0 = silk_energy_FLP( x, nb_subfr * subfr_length );
+    silk_memset( C_first_row, 0, SILK_MAX_ORDER_LPC * sizeof( double ) );
+    for( s = 0; s < nb_subfr; s++ ) {
+        x_ptr = x + s * subfr_length;
+        for( n = 1; n < D + 1; n++ ) {
+            C_first_row[ n - 1 ] += silk_inner_product_FLP( x_ptr, x_ptr + n, subfr_length - n );
+        }
+    }
+    silk_memcpy( C_last_row, C_first_row, SILK_MAX_ORDER_LPC * sizeof( double ) );
+
+    /* Initialize */
+    CAb[ 0 ] = CAf[ 0 ] = C0 + FIND_LPC_COND_FAC * C0 + 1e-9f;
+    invGain = 1.0f;
+    reached_max_gain = 0;
+    for( n = 0; n < D; n++ ) {
+        /* Update first row of correlation matrix (without first element) */
+        /* Update last row of correlation matrix (without last element, stored in reversed order) */
+        /* Update C * Af */
+        /* Update C * flipud(Af) (stored in reversed order) */
+        for( s = 0; s < nb_subfr; s++ ) {
+            x_ptr = x + s * subfr_length;
+            tmp1 = x_ptr[ n ];
+            tmp2 = x_ptr[ subfr_length - n - 1 ];
+            for( k = 0; k < n; k++ ) {
+                C_first_row[ k ] -= x_ptr[ n ] * x_ptr[ n - k - 1 ];
+                C_last_row[ k ]  -= x_ptr[ subfr_length - n - 1 ] * x_ptr[ subfr_length - n + k ];
+                Atmp = Af[ k ];
+                tmp1 += x_ptr[ n - k - 1 ] * Atmp;
+                tmp2 += x_ptr[ subfr_length - n + k ] * Atmp;
+            }
+            for( k = 0; k <= n; k++ ) {
+                CAf[ k ] -= tmp1 * x_ptr[ n - k ];
+                CAb[ k ] -= tmp2 * x_ptr[ subfr_length - n + k - 1 ];
+            }
+        }
+        tmp1 = C_first_row[ n ];
+        tmp2 = C_last_row[ n ];
+        for( k = 0; k < n; k++ ) {
+            Atmp = Af[ k ];
+            tmp1 += C_last_row[  n - k - 1 ] * Atmp;
+            tmp2 += C_first_row[ n - k - 1 ] * Atmp;
+        }
+        CAf[ n + 1 ] = tmp1;
+        CAb[ n + 1 ] = tmp2;
+
+        /* Calculate nominator and denominator for the next order reflection (parcor) coefficient */
+        num = CAb[ n + 1 ];
+        nrg_b = CAb[ 0 ];
+        nrg_f = CAf[ 0 ];
+        for( k = 0; k < n; k++ ) {
+            Atmp = Af[ k ];
+            num   += CAb[ n - k ] * Atmp;
+            nrg_b += CAb[ k + 1 ] * Atmp;
+            nrg_f += CAf[ k + 1 ] * Atmp;
+        }
+        silk_assert( nrg_f > 0.0 );
+        silk_assert( nrg_b > 0.0 );
+
+        /* Calculate the next order reflection (parcor) coefficient */
+        rc = -2.0 * num / ( nrg_f + nrg_b );
+        silk_assert( rc > -1.0 && rc < 1.0 );
+
+        /* Update inverse prediction gain */
+        tmp1 = invGain * ( 1.0 - rc * rc );
+        if( tmp1 <= minInvGain ) {
+            /* Max prediction gain exceeded; set reflection coefficient such that max prediction gain is exactly hit */
+            rc = sqrt( 1.0 - minInvGain / invGain );
+            if( num > 0 ) {
+                /* Ensure adjusted reflection coefficients has the original sign */
+                rc = -rc;
+            }
+            invGain = minInvGain;
+            reached_max_gain = 1;
+        } else {
+            invGain = tmp1;
+        }
+
+        /* Update the AR coefficients */
+        for( k = 0; k < (n + 1) >> 1; k++ ) {
+            tmp1 = Af[ k ];
+            tmp2 = Af[ n - k - 1 ];
+            Af[ k ]         = tmp1 + rc * tmp2;
+            Af[ n - k - 1 ] = tmp2 + rc * tmp1;
+        }
+        Af[ n ] = rc;
+
+        if( reached_max_gain ) {
+            /* Reached max prediction gain; set remaining coefficients to zero and exit loop */
+            for( k = n + 1; k < D; k++ ) {
+                Af[ k ] = 0.0;
+            }
+            break;
+        }
+
+        /* Update C * Af and C * Ab */
+        for( k = 0; k <= n + 1; k++ ) {
+            tmp1 = CAf[ k ];
+            CAf[ k ]          += rc * CAb[ n - k + 1 ];
+            CAb[ n - k + 1  ] += rc * tmp1;
+        }
+    }
+
+    if( reached_max_gain ) {
+        /* Convert to silk_float */
+        for( k = 0; k < D; k++ ) {
+            A[ k ] = (silk_float)( -Af[ k ] );
+        }
+        /* Subtract energy of preceding samples from C0 */
+        for( s = 0; s < nb_subfr; s++ ) {
+            C0 -= silk_energy_FLP( x + s * subfr_length, D );
+        }
+        /* Approximate residual energy */
+        nrg_f = C0 * invGain;
+    } else {
+        /* Compute residual energy and store coefficients as silk_float */
+        nrg_f = CAf[ 0 ];
+        tmp1 = 1.0;
+        for( k = 0; k < D; k++ ) {
+            Atmp = Af[ k ];
+            nrg_f += CAf[ k + 1 ] * Atmp;
+            tmp1  += Atmp * Atmp;
+            A[ k ] = (silk_float)(-Atmp);
+        }
+        nrg_f -= FIND_LPC_COND_FAC * C0 * tmp1;
+    }
+
+    /* Return residual energy */
+    return (silk_float)nrg_f;
+}
diff --git a/opus/silk/float/bwexpander_FLP.c b/opus/silk/float/bwexpander_FLP.c
new file mode 100644 (file)
index 0000000..d55a4d7
--- /dev/null
@@ -0,0 +1,49 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* Chirp (bw expand) LP AR filter */
+void silk_bwexpander_FLP(
+    silk_float          *ar,                /* I/O  AR filter to be expanded (without leading 1)                */
+    const opus_int      d,                  /* I    length of ar                                                */
+    const silk_float    chirp               /* I    chirp factor (typically in range (0..1) )                   */
+)
+{
+    opus_int   i;
+    silk_float cfac = chirp;
+
+    for( i = 0; i < d - 1; i++ ) {
+        ar[ i ] *=  cfac;
+        cfac    *=  chirp;
+    }
+    ar[ d - 1 ] *=  cfac;
+}
diff --git a/opus/silk/float/corrMatrix_FLP.c b/opus/silk/float/corrMatrix_FLP.c
new file mode 100644 (file)
index 0000000..eae6a1c
--- /dev/null
@@ -0,0 +1,93 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/**********************************************************************
+ * Correlation matrix computations for LS estimate.
+ **********************************************************************/
+
+#include "main_FLP.h"
+
+/* Calculates correlation vector X'*t */
+void silk_corrVector_FLP(
+    const silk_float                *x,                                 /* I    x vector [L+order-1] used to create X       */
+    const silk_float                *t,                                 /* I    Target vector [L]                           */
+    const opus_int                  L,                                  /* I    Length of vecors                            */
+    const opus_int                  Order,                              /* I    Max lag for correlation                     */
+    silk_float                      *Xt                                 /* O    X'*t correlation vector [order]             */
+)
+{
+    opus_int lag;
+    const silk_float *ptr1;
+
+    ptr1 = &x[ Order - 1 ];                     /* Points to first sample of column 0 of X: X[:,0] */
+    for( lag = 0; lag < Order; lag++ ) {
+        /* Calculate X[:,lag]'*t */
+        Xt[ lag ] = (silk_float)silk_inner_product_FLP( ptr1, t, L );
+        ptr1--;                                 /* Next column of X */
+    }
+}
+
+/* Calculates correlation matrix X'*X */
+void silk_corrMatrix_FLP(
+    const silk_float                *x,                                 /* I    x vector [ L+order-1 ] used to create X     */
+    const opus_int                  L,                                  /* I    Length of vectors                           */
+    const opus_int                  Order,                              /* I    Max lag for correlation                     */
+    silk_float                      *XX                                 /* O    X'*X correlation matrix [order x order]     */
+)
+{
+    opus_int j, lag;
+    double  energy;
+    const silk_float *ptr1, *ptr2;
+
+    ptr1 = &x[ Order - 1 ];                     /* First sample of column 0 of X */
+    energy = silk_energy_FLP( ptr1, L );  /* X[:,0]'*X[:,0] */
+    matrix_ptr( XX, 0, 0, Order ) = ( silk_float )energy;
+    for( j = 1; j < Order; j++ ) {
+        /* Calculate X[:,j]'*X[:,j] */
+        energy += ptr1[ -j ] * ptr1[ -j ] - ptr1[ L - j ] * ptr1[ L - j ];
+        matrix_ptr( XX, j, j, Order ) = ( silk_float )energy;
+    }
+
+    ptr2 = &x[ Order - 2 ];                     /* First sample of column 1 of X */
+    for( lag = 1; lag < Order; lag++ ) {
+        /* Calculate X[:,0]'*X[:,lag] */
+        energy = silk_inner_product_FLP( ptr1, ptr2, L );
+        matrix_ptr( XX, lag, 0, Order ) = ( silk_float )energy;
+        matrix_ptr( XX, 0, lag, Order ) = ( silk_float )energy;
+        /* Calculate X[:,j]'*X[:,j + lag] */
+        for( j = 1; j < ( Order - lag ); j++ ) {
+            energy += ptr1[ -j ] * ptr2[ -j ] - ptr1[ L - j ] * ptr2[ L - j ];
+            matrix_ptr( XX, lag + j, j, Order ) = ( silk_float )energy;
+            matrix_ptr( XX, j, lag + j, Order ) = ( silk_float )energy;
+        }
+        ptr2--;                                 /* Next column of X */
+    }
+}
diff --git a/opus/silk/float/encode_frame_FLP.c b/opus/silk/float/encode_frame_FLP.c
new file mode 100644 (file)
index 0000000..c3ad50a
--- /dev/null
@@ -0,0 +1,428 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+/* Low Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode with lower bitrate */
+static OPUS_INLINE void silk_LBRR_encode_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                xfw[],                              /* I    Input signal                                */
+    opus_int                        condCoding                          /* I    The type of conditional coding used so far for this frame */
+);
+
+void silk_encode_do_VAD_FLP(
+    silk_encoder_state_FLP          *psEnc                              /* I/O  Encoder state FLP                           */
+)
+{
+    /****************************/
+    /* Voice Activity Detection */
+    /****************************/
+    silk_VAD_GetSA_Q8( &psEnc->sCmn, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.arch );
+
+    /**************************************************/
+    /* Convert speech activity into VAD and DTX flags */
+    /**************************************************/
+    if( psEnc->sCmn.speech_activity_Q8 < SILK_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ) ) {
+        psEnc->sCmn.indices.signalType = TYPE_NO_VOICE_ACTIVITY;
+        psEnc->sCmn.noSpeechCounter++;
+        if( psEnc->sCmn.noSpeechCounter < NB_SPEECH_FRAMES_BEFORE_DTX ) {
+            psEnc->sCmn.inDTX = 0;
+        } else if( psEnc->sCmn.noSpeechCounter > MAX_CONSECUTIVE_DTX + NB_SPEECH_FRAMES_BEFORE_DTX ) {
+            psEnc->sCmn.noSpeechCounter = NB_SPEECH_FRAMES_BEFORE_DTX;
+            psEnc->sCmn.inDTX           = 0;
+        }
+        psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 0;
+    } else {
+        psEnc->sCmn.noSpeechCounter    = 0;
+        psEnc->sCmn.inDTX              = 0;
+        psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
+        psEnc->sCmn.VAD_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
+    }
+}
+
+/****************/
+/* Encode frame */
+/****************/
+opus_int silk_encode_frame_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    opus_int32                      *pnBytesOut,                        /* O    Number of payload bytes;                    */
+    ec_enc                          *psRangeEnc,                        /* I/O  compressor data structure                   */
+    opus_int                        condCoding,                         /* I    The type of conditional coding to use       */
+    opus_int                        maxBits,                            /* I    If > 0: maximum number of output bits       */
+    opus_int                        useCBR                              /* I    Flag to force constant-bitrate operation    */
+)
+{
+    silk_encoder_control_FLP sEncCtrl;
+    opus_int     i, iter, maxIter, found_upper, found_lower, ret = 0;
+    silk_float   *x_frame, *res_pitch_frame;
+    silk_float   res_pitch[ 2 * MAX_FRAME_LENGTH + LA_PITCH_MAX ];
+    ec_enc       sRangeEnc_copy, sRangeEnc_copy2;
+    silk_nsq_state sNSQ_copy, sNSQ_copy2;
+    opus_int32   seed_copy, nBits, nBits_lower, nBits_upper, gainMult_lower, gainMult_upper;
+    opus_int32   gainsID, gainsID_lower, gainsID_upper;
+    opus_int16   gainMult_Q8;
+    opus_int16   ec_prevLagIndex_copy;
+    opus_int     ec_prevSignalType_copy;
+    opus_int8    LastGainIndex_copy2;
+    opus_int32   pGains_Q16[ MAX_NB_SUBFR ];
+    opus_uint8   ec_buf_copy[ 1275 ];
+    opus_int     gain_lock[ MAX_NB_SUBFR ] = {0};
+    opus_int16   best_gain_mult[ MAX_NB_SUBFR ];
+    opus_int     best_sum[ MAX_NB_SUBFR ];
+
+    /* This is totally unnecessary but many compilers (including gcc) are too dumb to realise it */
+    LastGainIndex_copy2 = nBits_lower = nBits_upper = gainMult_lower = gainMult_upper = 0;
+
+    psEnc->sCmn.indices.Seed = psEnc->sCmn.frameCounter++ & 3;
+
+    /**************************************************************/
+    /* Set up Input Pointers, and insert frame in input buffer    */
+    /**************************************************************/
+    /* pointers aligned with start of frame to encode */
+    x_frame         = psEnc->x_buf + psEnc->sCmn.ltp_mem_length;    /* start of frame to encode */
+    res_pitch_frame = res_pitch    + psEnc->sCmn.ltp_mem_length;    /* start of pitch LPC residual frame */
+
+    /***************************************/
+    /* Ensure smooth bandwidth transitions */
+    /***************************************/
+    silk_LP_variable_cutoff( &psEnc->sCmn.sLP, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length );
+
+    /*******************************************/
+    /* Copy new frame to front of input buffer */
+    /*******************************************/
+    silk_short2float_array( x_frame + LA_SHAPE_MS * psEnc->sCmn.fs_kHz, psEnc->sCmn.inputBuf + 1, psEnc->sCmn.frame_length );
+
+    /* Add tiny signal to avoid high CPU load from denormalized floating point numbers */
+    for( i = 0; i < 8; i++ ) {
+        x_frame[ LA_SHAPE_MS * psEnc->sCmn.fs_kHz + i * ( psEnc->sCmn.frame_length >> 3 ) ] += ( 1 - ( i & 2 ) ) * 1e-6f;
+    }
+
+    if( !psEnc->sCmn.prefillFlag ) {
+        /*****************************************/
+        /* Find pitch lags, initial LPC analysis */
+        /*****************************************/
+        silk_find_pitch_lags_FLP( psEnc, &sEncCtrl, res_pitch, x_frame, psEnc->sCmn.arch );
+
+        /************************/
+        /* Noise shape analysis */
+        /************************/
+        silk_noise_shape_analysis_FLP( psEnc, &sEncCtrl, res_pitch_frame, x_frame );
+
+        /***************************************************/
+        /* Find linear prediction coefficients (LPC + LTP) */
+        /***************************************************/
+        silk_find_pred_coefs_FLP( psEnc, &sEncCtrl, res_pitch_frame, x_frame, condCoding );
+
+        /****************************************/
+        /* Process gains                        */
+        /****************************************/
+        silk_process_gains_FLP( psEnc, &sEncCtrl, condCoding );
+
+        /****************************************/
+        /* Low Bitrate Redundant Encoding       */
+        /****************************************/
+        silk_LBRR_encode_FLP( psEnc, &sEncCtrl, x_frame, condCoding );
+
+        /* Loop over quantizer and entroy coding to control bitrate */
+        maxIter = 6;
+        gainMult_Q8 = SILK_FIX_CONST( 1, 8 );
+        found_lower = 0;
+        found_upper = 0;
+        gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
+        gainsID_lower = -1;
+        gainsID_upper = -1;
+        /* Copy part of the input state */
+        silk_memcpy( &sRangeEnc_copy, psRangeEnc, sizeof( ec_enc ) );
+        silk_memcpy( &sNSQ_copy, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+        seed_copy = psEnc->sCmn.indices.Seed;
+        ec_prevLagIndex_copy = psEnc->sCmn.ec_prevLagIndex;
+        ec_prevSignalType_copy = psEnc->sCmn.ec_prevSignalType;
+        for( iter = 0; ; iter++ ) {
+            if( gainsID == gainsID_lower ) {
+                nBits = nBits_lower;
+            } else if( gainsID == gainsID_upper ) {
+                nBits = nBits_upper;
+            } else {
+                /* Restore part of the input state */
+                if( iter > 0 ) {
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy, sizeof( ec_enc ) );
+                    silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy, sizeof( silk_nsq_state ) );
+                    psEnc->sCmn.indices.Seed = seed_copy;
+                    psEnc->sCmn.ec_prevLagIndex = ec_prevLagIndex_copy;
+                    psEnc->sCmn.ec_prevSignalType = ec_prevSignalType_copy;
+                }
+
+                /*****************************************/
+                /* Noise shaping quantization            */
+                /*****************************************/
+                silk_NSQ_wrapper_FLP( psEnc, &sEncCtrl, &psEnc->sCmn.indices, &psEnc->sCmn.sNSQ, psEnc->sCmn.pulses, x_frame );
+
+                if ( iter == maxIter && !found_lower ) {
+                    silk_memcpy( &sRangeEnc_copy2, psRangeEnc, sizeof( ec_enc ) );
+                }
+
+                /****************************************/
+                /* Encode Parameters                    */
+                /****************************************/
+                silk_encode_indices( &psEnc->sCmn, psRangeEnc, psEnc->sCmn.nFramesEncoded, 0, condCoding );
+
+                /****************************************/
+                /* Encode Excitation Signal             */
+                /****************************************/
+                silk_encode_pulses( psRangeEnc, psEnc->sCmn.indices.signalType, psEnc->sCmn.indices.quantOffsetType,
+                      psEnc->sCmn.pulses, psEnc->sCmn.frame_length );
+
+                nBits = ec_tell( psRangeEnc );
+
+                /* If we still bust after the last iteration, do some damage control. */
+                if ( iter == maxIter && !found_lower && nBits > maxBits ) {
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy2, sizeof( ec_enc ) );
+
+                    /* Keep gains the same as the last frame. */
+                    psEnc->sShape.LastGainIndex = sEncCtrl.lastGainIndexPrev;
+                    for ( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                        psEnc->sCmn.indices.GainsIndices[ i ] = 4;
+                    }
+                    if (condCoding != CODE_CONDITIONALLY) {
+                       psEnc->sCmn.indices.GainsIndices[ 0 ] = sEncCtrl.lastGainIndexPrev;
+                    }
+                    psEnc->sCmn.ec_prevLagIndex = ec_prevLagIndex_copy;
+                    psEnc->sCmn.ec_prevSignalType = ec_prevSignalType_copy;
+                    /* Clear all pulses. */
+                    for ( i = 0; i < psEnc->sCmn.frame_length; i++ ) {
+                        psEnc->sCmn.pulses[ i ] = 0;
+                    }
+
+                    silk_encode_indices( &psEnc->sCmn, psRangeEnc, psEnc->sCmn.nFramesEncoded, 0, condCoding );
+
+                    silk_encode_pulses( psRangeEnc, psEnc->sCmn.indices.signalType, psEnc->sCmn.indices.quantOffsetType,
+                        psEnc->sCmn.pulses, psEnc->sCmn.frame_length );
+
+                    nBits = ec_tell( psRangeEnc );
+                }
+
+                if( useCBR == 0 && iter == 0 && nBits <= maxBits ) {
+                    break;
+                }
+            }
+
+            if( iter == maxIter ) {
+                if( found_lower && ( gainsID == gainsID_lower || nBits > maxBits ) ) {
+                    /* Restore output state from earlier iteration that did meet the bitrate budget */
+                    silk_memcpy( psRangeEnc, &sRangeEnc_copy2, sizeof( ec_enc ) );
+                    silk_assert( sRangeEnc_copy2.offs <= 1275 );
+                    silk_memcpy( psRangeEnc->buf, ec_buf_copy, sRangeEnc_copy2.offs );
+                    silk_memcpy( &psEnc->sCmn.sNSQ, &sNSQ_copy2, sizeof( silk_nsq_state ) );
+                    psEnc->sShape.LastGainIndex = LastGainIndex_copy2;
+                }
+                break;
+            }
+
+            if( nBits > maxBits ) {
+                if( found_lower == 0 && iter >= 2 ) {
+                    /* Adjust the quantizer's rate/distortion tradeoff and discard previous "upper" results */
+                    sEncCtrl.Lambda = silk_max_float(sEncCtrl.Lambda*1.5f, 1.5f);
+                    /* Reducing dithering can help us hit the target. */
+                    psEnc->sCmn.indices.quantOffsetType = 0;
+                    found_upper = 0;
+                    gainsID_upper = -1;
+                } else {
+                    found_upper = 1;
+                    nBits_upper = nBits;
+                    gainMult_upper = gainMult_Q8;
+                    gainsID_upper = gainsID;
+                }
+            } else if( nBits < maxBits - 5 ) {
+                found_lower = 1;
+                nBits_lower = nBits;
+                gainMult_lower = gainMult_Q8;
+                if( gainsID != gainsID_lower ) {
+                    gainsID_lower = gainsID;
+                    /* Copy part of the output state */
+                    silk_memcpy( &sRangeEnc_copy2, psRangeEnc, sizeof( ec_enc ) );
+                    silk_assert( psRangeEnc->offs <= 1275 );
+                    silk_memcpy( ec_buf_copy, psRangeEnc->buf, psRangeEnc->offs );
+                    silk_memcpy( &sNSQ_copy2, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+                    LastGainIndex_copy2 = psEnc->sShape.LastGainIndex;
+                }
+            } else {
+                /* Within 5 bits of budget: close enough */
+                break;
+            }
+
+            if ( !found_lower && nBits > maxBits ) {
+                int j;
+                for ( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                    int sum=0;
+                    for ( j = i*psEnc->sCmn.subfr_length; j < (i+1)*psEnc->sCmn.subfr_length; j++ ) {
+                        sum += abs( psEnc->sCmn.pulses[j] );
+                    }
+                    if ( iter == 0 || (sum < best_sum[i] && !gain_lock[i]) ) {
+                        best_sum[i] = sum;
+                        best_gain_mult[i] = gainMult_Q8;
+                    } else {
+                        gain_lock[i] = 1;
+                    }
+                }
+            }
+            if( ( found_lower & found_upper ) == 0 ) {
+                /* Adjust gain according to high-rate rate/distortion curve */
+                if( nBits > maxBits ) {
+                    if (gainMult_Q8 < 16384) {
+                        gainMult_Q8 *= 2;
+                    } else {
+                        gainMult_Q8 = 32767;
+                    }
+                } else {
+                    opus_int32 gain_factor_Q16;
+                    gain_factor_Q16 = silk_log2lin( silk_LSHIFT( nBits - maxBits, 7 ) / psEnc->sCmn.frame_length + SILK_FIX_CONST( 16, 7 ) );
+                    gainMult_Q8 = silk_SMULWB( gain_factor_Q16, gainMult_Q8 );
+                }
+            } else {
+                /* Adjust gain by interpolating */
+                gainMult_Q8 = gainMult_lower + ( ( gainMult_upper - gainMult_lower ) * ( maxBits - nBits_lower ) ) / ( nBits_upper - nBits_lower );
+                /* New gain multplier must be between 25% and 75% of old range (note that gainMult_upper < gainMult_lower) */
+                if( gainMult_Q8 > silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 ) ) {
+                    gainMult_Q8 = silk_ADD_RSHIFT32( gainMult_lower, gainMult_upper - gainMult_lower, 2 );
+                } else
+                if( gainMult_Q8 < silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 ) ) {
+                    gainMult_Q8 = silk_SUB_RSHIFT32( gainMult_upper, gainMult_upper - gainMult_lower, 2 );
+                }
+            }
+
+            for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                opus_int16 tmp;
+                if ( gain_lock[i] ) {
+                    tmp = best_gain_mult[i];
+                } else {
+                    tmp = gainMult_Q8;
+                }
+                pGains_Q16[ i ] = silk_LSHIFT_SAT32( silk_SMULWB( sEncCtrl.GainsUnq_Q16[ i ], tmp ), 8 );
+            }
+
+            /* Quantize gains */
+            psEnc->sShape.LastGainIndex = sEncCtrl.lastGainIndexPrev;
+            silk_gains_quant( psEnc->sCmn.indices.GainsIndices, pGains_Q16,
+                  &psEnc->sShape.LastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+            /* Unique identifier of gains vector */
+            gainsID = silk_gains_ID( psEnc->sCmn.indices.GainsIndices, psEnc->sCmn.nb_subfr );
+
+            /* Overwrite unquantized gains with quantized gains and convert back to Q0 from Q16 */
+            for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+                sEncCtrl.Gains[ i ] = pGains_Q16[ i ] / 65536.0f;
+            }
+        }
+    }
+
+    /* Update input buffer */
+    silk_memmove( psEnc->x_buf, &psEnc->x_buf[ psEnc->sCmn.frame_length ],
+        ( psEnc->sCmn.ltp_mem_length + LA_SHAPE_MS * psEnc->sCmn.fs_kHz ) * sizeof( silk_float ) );
+
+    /* Exit without entropy coding */
+    if( psEnc->sCmn.prefillFlag ) {
+        /* No payload */
+        *pnBytesOut = 0;
+        return ret;
+    }
+
+    /* Parameters needed for next frame */
+    psEnc->sCmn.prevLag        = sEncCtrl.pitchL[ psEnc->sCmn.nb_subfr - 1 ];
+    psEnc->sCmn.prevSignalType = psEnc->sCmn.indices.signalType;
+
+    /****************************************/
+    /* Finalize payload                     */
+    /****************************************/
+    psEnc->sCmn.first_frame_after_reset = 0;
+    /* Payload size */
+    *pnBytesOut = silk_RSHIFT( ec_tell( psRangeEnc ) + 7, 3 );
+
+    return ret;
+}
+
+/* Low-Bitrate Redundancy (LBRR) encoding. Reuse all parameters but encode excitation at lower bitrate  */
+static OPUS_INLINE void silk_LBRR_encode_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                xfw[],                              /* I    Input signal                                */
+    opus_int                        condCoding                          /* I    The type of conditional coding used so far for this frame */
+)
+{
+    opus_int     k;
+    opus_int32   Gains_Q16[ MAX_NB_SUBFR ];
+    silk_float   TempGains[ MAX_NB_SUBFR ];
+    SideInfoIndices *psIndices_LBRR = &psEnc->sCmn.indices_LBRR[ psEnc->sCmn.nFramesEncoded ];
+    silk_nsq_state sNSQ_LBRR;
+
+    /*******************************************/
+    /* Control use of inband LBRR              */
+    /*******************************************/
+    if( psEnc->sCmn.LBRR_enabled && psEnc->sCmn.speech_activity_Q8 > SILK_FIX_CONST( LBRR_SPEECH_ACTIVITY_THRES, 8 ) ) {
+        psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded ] = 1;
+
+        /* Copy noise shaping quantizer state and quantization indices from regular encoding */
+        silk_memcpy( &sNSQ_LBRR, &psEnc->sCmn.sNSQ, sizeof( silk_nsq_state ) );
+        silk_memcpy( psIndices_LBRR, &psEnc->sCmn.indices, sizeof( SideInfoIndices ) );
+
+        /* Save original gains */
+        silk_memcpy( TempGains, psEncCtrl->Gains, psEnc->sCmn.nb_subfr * sizeof( silk_float ) );
+
+        if( psEnc->sCmn.nFramesEncoded == 0 || psEnc->sCmn.LBRR_flags[ psEnc->sCmn.nFramesEncoded - 1 ] == 0 ) {
+            /* First frame in packet or previous frame not LBRR coded */
+            psEnc->sCmn.LBRRprevLastGainIndex = psEnc->sShape.LastGainIndex;
+
+            /* Increase Gains to get target LBRR rate */
+            psIndices_LBRR->GainsIndices[ 0 ] += psEnc->sCmn.LBRR_GainIncreases;
+            psIndices_LBRR->GainsIndices[ 0 ] = silk_min_int( psIndices_LBRR->GainsIndices[ 0 ], N_LEVELS_QGAIN - 1 );
+        }
+
+        /* Decode to get gains in sync with decoder */
+        silk_gains_dequant( Gains_Q16, psIndices_LBRR->GainsIndices,
+            &psEnc->sCmn.LBRRprevLastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+        /* Overwrite unquantized gains with quantized gains and convert back to Q0 from Q16 */
+        for( k = 0; k <  psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->Gains[ k ] = Gains_Q16[ k ] * ( 1.0f / 65536.0f );
+        }
+
+        /*****************************************/
+        /* Noise shaping quantization            */
+        /*****************************************/
+        silk_NSQ_wrapper_FLP( psEnc, psEncCtrl, psIndices_LBRR, &sNSQ_LBRR,
+            psEnc->sCmn.pulses_LBRR[ psEnc->sCmn.nFramesEncoded ], xfw );
+
+        /* Restore original gains */
+        silk_memcpy( psEncCtrl->Gains, TempGains, psEnc->sCmn.nb_subfr * sizeof( silk_float ) );
+    }
+}
diff --git a/opus/silk/float/energy_FLP.c b/opus/silk/float/energy_FLP.c
new file mode 100644 (file)
index 0000000..7bc7173
--- /dev/null
@@ -0,0 +1,59 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* sum of squares of a silk_float array, with result as double */
+double silk_energy_FLP(
+    const silk_float    *data,
+    opus_int            dataSize
+)
+{
+    opus_int i;
+    double   result;
+
+    /* 4x unrolled loop */
+    result = 0.0;
+    for( i = 0; i < dataSize - 3; i += 4 ) {
+        result += data[ i + 0 ] * (double)data[ i + 0 ] +
+                  data[ i + 1 ] * (double)data[ i + 1 ] +
+                  data[ i + 2 ] * (double)data[ i + 2 ] +
+                  data[ i + 3 ] * (double)data[ i + 3 ];
+    }
+
+    /* add any remaining products */
+    for( ; i < dataSize; i++ ) {
+        result += data[ i ] * (double)data[ i ];
+    }
+
+    silk_assert( result >= 0.0 );
+    return result;
+}
diff --git a/opus/silk/float/find_LPC_FLP.c b/opus/silk/float/find_LPC_FLP.c
new file mode 100644 (file)
index 0000000..4d63964
--- /dev/null
@@ -0,0 +1,104 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "define.h"
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+/* LPC analysis */
+void silk_find_LPC_FLP(
+    silk_encoder_state              *psEncC,                            /* I/O  Encoder state                               */
+    opus_int16                      NLSF_Q15[],                         /* O    NLSFs                                       */
+    const silk_float                x[],                                /* I    Input signal                                */
+    const silk_float                minInvGain                          /* I    Inverse of max prediction gain              */
+)
+{
+    opus_int    k, subfr_length;
+    silk_float  a[ MAX_LPC_ORDER ];
+
+    /* Used only for NLSF interpolation */
+    silk_float  res_nrg, res_nrg_2nd, res_nrg_interp;
+    opus_int16  NLSF0_Q15[ MAX_LPC_ORDER ];
+    silk_float  a_tmp[ MAX_LPC_ORDER ];
+    silk_float  LPC_res[ MAX_FRAME_LENGTH + MAX_NB_SUBFR * MAX_LPC_ORDER ];
+
+    subfr_length = psEncC->subfr_length + psEncC->predictLPCOrder;
+
+    /* Default: No interpolation */
+    psEncC->indices.NLSFInterpCoef_Q2 = 4;
+
+    /* Burg AR analysis for the full frame */
+    res_nrg = silk_burg_modified_FLP( a, x, minInvGain, subfr_length, psEncC->nb_subfr, psEncC->predictLPCOrder );
+
+    if( psEncC->useInterpolatedNLSFs && !psEncC->first_frame_after_reset && psEncC->nb_subfr == MAX_NB_SUBFR ) {
+        /* Optimal solution for last 10 ms; subtract residual energy here, as that's easier than        */
+        /* adding it to the residual energy of the first 10 ms in each iteration of the search below    */
+        res_nrg -= silk_burg_modified_FLP( a_tmp, x + ( MAX_NB_SUBFR / 2 ) * subfr_length, minInvGain, subfr_length, MAX_NB_SUBFR / 2, psEncC->predictLPCOrder );
+
+        /* Convert to NLSFs */
+        silk_A2NLSF_FLP( NLSF_Q15, a_tmp, psEncC->predictLPCOrder );
+
+        /* Search over interpolation indices to find the one with lowest residual energy */
+        res_nrg_2nd = silk_float_MAX;
+        for( k = 3; k >= 0; k-- ) {
+            /* Interpolate NLSFs for first half */
+            silk_interpolate( NLSF0_Q15, psEncC->prev_NLSFq_Q15, NLSF_Q15, k, psEncC->predictLPCOrder );
+
+            /* Convert to LPC for residual energy evaluation */
+            silk_NLSF2A_FLP( a_tmp, NLSF0_Q15, psEncC->predictLPCOrder, psEncC->arch );
+
+            /* Calculate residual energy with LSF interpolation */
+            silk_LPC_analysis_filter_FLP( LPC_res, a_tmp, x, 2 * subfr_length, psEncC->predictLPCOrder );
+            res_nrg_interp = (silk_float)(
+                silk_energy_FLP( LPC_res + psEncC->predictLPCOrder,                subfr_length - psEncC->predictLPCOrder ) +
+                silk_energy_FLP( LPC_res + psEncC->predictLPCOrder + subfr_length, subfr_length - psEncC->predictLPCOrder ) );
+
+            /* Determine whether current interpolated NLSFs are best so far */
+            if( res_nrg_interp < res_nrg ) {
+                /* Interpolation has lower residual energy */
+                res_nrg = res_nrg_interp;
+                psEncC->indices.NLSFInterpCoef_Q2 = (opus_int8)k;
+            } else if( res_nrg_interp > res_nrg_2nd ) {
+                /* No reason to continue iterating - residual energies will continue to climb */
+                break;
+            }
+            res_nrg_2nd = res_nrg_interp;
+        }
+    }
+
+    if( psEncC->indices.NLSFInterpCoef_Q2 == 4 ) {
+        /* NLSF interpolation is currently inactive, calculate NLSFs from full frame AR coefficients */
+        silk_A2NLSF_FLP( NLSF_Q15, a, psEncC->predictLPCOrder );
+    }
+
+    silk_assert( psEncC->indices.NLSFInterpCoef_Q2 == 4 ||
+        ( psEncC->useInterpolatedNLSFs && !psEncC->first_frame_after_reset && psEncC->nb_subfr == MAX_NB_SUBFR ) );
+}
diff --git a/opus/silk/float/find_LTP_FLP.c b/opus/silk/float/find_LTP_FLP.c
new file mode 100644 (file)
index 0000000..f970649
--- /dev/null
@@ -0,0 +1,64 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+void silk_find_LTP_FLP(
+    silk_float                      XX[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* O    Weight for LTP quantization         */
+    silk_float                      xX[ MAX_NB_SUBFR * LTP_ORDER ],     /* O    Weight for LTP quantization                 */
+    const silk_float                r_ptr[],                            /* I    LPC residual                                */
+    const opus_int                  lag[ MAX_NB_SUBFR ],                /* I    LTP lags                                    */
+    const opus_int                  subfr_length,                       /* I    Subframe length                             */
+    const opus_int                  nb_subfr                            /* I    number of subframes                         */
+)
+{
+    opus_int   k;
+    silk_float *xX_ptr, *XX_ptr;
+    const silk_float *lag_ptr;
+    silk_float xx, temp;
+
+    xX_ptr = xX;
+    XX_ptr = XX;
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_ptr = r_ptr - ( lag[ k ] + LTP_ORDER / 2 );
+        silk_corrMatrix_FLP( lag_ptr, subfr_length, LTP_ORDER, XX_ptr );
+        silk_corrVector_FLP( lag_ptr, r_ptr, subfr_length, LTP_ORDER, xX_ptr );
+        xx = ( silk_float )silk_energy_FLP( r_ptr, subfr_length + LTP_ORDER );
+        temp = 1.0f / silk_max( xx, LTP_CORR_INV_MAX * 0.5f * ( XX_ptr[ 0 ] + XX_ptr[ 24 ] ) + 1.0f );
+        silk_scale_vector_FLP( XX_ptr, temp, LTP_ORDER * LTP_ORDER );
+        silk_scale_vector_FLP( xX_ptr, temp, LTP_ORDER );
+
+        r_ptr  += subfr_length;
+        XX_ptr += LTP_ORDER * LTP_ORDER;
+        xX_ptr += LTP_ORDER;
+    }
+}
diff --git a/opus/silk/float/find_pitch_lags_FLP.c b/opus/silk/float/find_pitch_lags_FLP.c
new file mode 100644 (file)
index 0000000..f3b22d2
--- /dev/null
@@ -0,0 +1,132 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+void silk_find_pitch_lags_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    silk_float                      res[],                              /* O    Residual                                    */
+    const silk_float                x[],                                /* I    Speech signal                               */
+    int                             arch                                /* I    Run-time architecture                       */
+)
+{
+    opus_int   buf_len;
+    silk_float thrhld, res_nrg;
+    const silk_float *x_buf_ptr, *x_buf;
+    silk_float auto_corr[ MAX_FIND_PITCH_LPC_ORDER + 1 ];
+    silk_float A[         MAX_FIND_PITCH_LPC_ORDER ];
+    silk_float refl_coef[ MAX_FIND_PITCH_LPC_ORDER ];
+    silk_float Wsig[      FIND_PITCH_LPC_WIN_MAX ];
+    silk_float *Wsig_ptr;
+
+    /******************************************/
+    /* Set up buffer lengths etc based on Fs  */
+    /******************************************/
+    buf_len = psEnc->sCmn.la_pitch + psEnc->sCmn.frame_length + psEnc->sCmn.ltp_mem_length;
+
+    /* Safety check */
+    silk_assert( buf_len >= psEnc->sCmn.pitch_LPC_win_length );
+
+    x_buf = x - psEnc->sCmn.ltp_mem_length;
+
+    /******************************************/
+    /* Estimate LPC AR coeficients            */
+    /******************************************/
+
+    /* Calculate windowed signal */
+
+    /* First LA_LTP samples */
+    x_buf_ptr = x_buf + buf_len - psEnc->sCmn.pitch_LPC_win_length;
+    Wsig_ptr  = Wsig;
+    silk_apply_sine_window_FLP( Wsig_ptr, x_buf_ptr, 1, psEnc->sCmn.la_pitch );
+
+    /* Middle non-windowed samples */
+    Wsig_ptr  += psEnc->sCmn.la_pitch;
+    x_buf_ptr += psEnc->sCmn.la_pitch;
+    silk_memcpy( Wsig_ptr, x_buf_ptr, ( psEnc->sCmn.pitch_LPC_win_length - ( psEnc->sCmn.la_pitch << 1 ) ) * sizeof( silk_float ) );
+
+    /* Last LA_LTP samples */
+    Wsig_ptr  += psEnc->sCmn.pitch_LPC_win_length - ( psEnc->sCmn.la_pitch << 1 );
+    x_buf_ptr += psEnc->sCmn.pitch_LPC_win_length - ( psEnc->sCmn.la_pitch << 1 );
+    silk_apply_sine_window_FLP( Wsig_ptr, x_buf_ptr, 2, psEnc->sCmn.la_pitch );
+
+    /* Calculate autocorrelation sequence */
+    silk_autocorrelation_FLP( auto_corr, Wsig, psEnc->sCmn.pitch_LPC_win_length, psEnc->sCmn.pitchEstimationLPCOrder + 1 );
+
+    /* Add white noise, as a fraction of the energy */
+    auto_corr[ 0 ] += auto_corr[ 0 ] * FIND_PITCH_WHITE_NOISE_FRACTION + 1;
+
+    /* Calculate the reflection coefficients using Schur */
+    res_nrg = silk_schur_FLP( refl_coef, auto_corr, psEnc->sCmn.pitchEstimationLPCOrder );
+
+    /* Prediction gain */
+    psEncCtrl->predGain = auto_corr[ 0 ] / silk_max_float( res_nrg, 1.0f );
+
+    /* Convert reflection coefficients to prediction coefficients */
+    silk_k2a_FLP( A, refl_coef, psEnc->sCmn.pitchEstimationLPCOrder );
+
+    /* Bandwidth expansion */
+    silk_bwexpander_FLP( A, psEnc->sCmn.pitchEstimationLPCOrder, FIND_PITCH_BANDWIDTH_EXPANSION );
+
+    /*****************************************/
+    /* LPC analysis filtering                */
+    /*****************************************/
+    silk_LPC_analysis_filter_FLP( res, A, x_buf, buf_len, psEnc->sCmn.pitchEstimationLPCOrder );
+
+    if( psEnc->sCmn.indices.signalType != TYPE_NO_VOICE_ACTIVITY && psEnc->sCmn.first_frame_after_reset == 0 ) {
+        /* Threshold for pitch estimator */
+        thrhld  = 0.6f;
+        thrhld -= 0.004f * psEnc->sCmn.pitchEstimationLPCOrder;
+        thrhld -= 0.1f   * psEnc->sCmn.speech_activity_Q8 * ( 1.0f /  256.0f );
+        thrhld -= 0.15f  * (psEnc->sCmn.prevSignalType >> 1);
+        thrhld -= 0.1f   * psEnc->sCmn.input_tilt_Q15 * ( 1.0f / 32768.0f );
+
+        /*****************************************/
+        /* Call Pitch estimator                  */
+        /*****************************************/
+        if( silk_pitch_analysis_core_FLP( res, psEncCtrl->pitchL, &psEnc->sCmn.indices.lagIndex,
+            &psEnc->sCmn.indices.contourIndex, &psEnc->LTPCorr, psEnc->sCmn.prevLag, psEnc->sCmn.pitchEstimationThreshold_Q16 / 65536.0f,
+            thrhld, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, psEnc->sCmn.nb_subfr, arch ) == 0 )
+        {
+            psEnc->sCmn.indices.signalType = TYPE_VOICED;
+        } else {
+            psEnc->sCmn.indices.signalType = TYPE_UNVOICED;
+        }
+    } else {
+        silk_memset( psEncCtrl->pitchL, 0, sizeof( psEncCtrl->pitchL ) );
+        psEnc->sCmn.indices.lagIndex = 0;
+        psEnc->sCmn.indices.contourIndex = 0;
+        psEnc->LTPCorr = 0;
+    }
+}
diff --git a/opus/silk/float/find_pred_coefs_FLP.c b/opus/silk/float/find_pred_coefs_FLP.c
new file mode 100644 (file)
index 0000000..cb2e763
--- /dev/null
@@ -0,0 +1,116 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+/* Find LPC and LTP coefficients */
+void silk_find_pred_coefs_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                res_pitch[],                        /* I    Residual from pitch analysis                */
+    const silk_float                x[],                                /* I    Speech signal                               */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+)
+{
+    opus_int         i;
+    silk_float       XXLTP[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ];
+    silk_float       xXLTP[ MAX_NB_SUBFR * LTP_ORDER ];
+    silk_float       invGains[ MAX_NB_SUBFR ];
+    opus_int16       NLSF_Q15[ MAX_LPC_ORDER ];
+    const silk_float *x_ptr;
+    silk_float       *x_pre_ptr, LPC_in_pre[ MAX_NB_SUBFR * MAX_LPC_ORDER + MAX_FRAME_LENGTH ];
+    silk_float       minInvGain;
+
+    /* Weighting for weighted least squares */
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        silk_assert( psEncCtrl->Gains[ i ] > 0.0f );
+        invGains[ i ] = 1.0f / psEncCtrl->Gains[ i ];
+    }
+
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /**********/
+        /* VOICED */
+        /**********/
+        silk_assert( psEnc->sCmn.ltp_mem_length - psEnc->sCmn.predictLPCOrder >= psEncCtrl->pitchL[ 0 ] + LTP_ORDER / 2 );
+
+        /* LTP analysis */
+        silk_find_LTP_FLP( XXLTP, xXLTP, res_pitch, psEncCtrl->pitchL, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr );
+
+        /* Quantize LTP gain parameters */
+        silk_quant_LTP_gains_FLP( psEncCtrl->LTPCoef, psEnc->sCmn.indices.LTPIndex, &psEnc->sCmn.indices.PERIndex,
+            &psEnc->sCmn.sum_log_gain_Q7, &psEncCtrl->LTPredCodGain, XXLTP, xXLTP, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.arch );
+
+        /* Control LTP scaling */
+        silk_LTP_scale_ctrl_FLP( psEnc, psEncCtrl, condCoding );
+
+        /* Create LTP residual */
+        silk_LTP_analysis_filter_FLP( LPC_in_pre, x - psEnc->sCmn.predictLPCOrder, psEncCtrl->LTPCoef,
+            psEncCtrl->pitchL, invGains, psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.predictLPCOrder );
+    } else {
+        /************/
+        /* UNVOICED */
+        /************/
+        /* Create signal with prepended subframes, scaled by inverse gains */
+        x_ptr     = x - psEnc->sCmn.predictLPCOrder;
+        x_pre_ptr = LPC_in_pre;
+        for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+            silk_scale_copy_vector_FLP( x_pre_ptr, x_ptr, invGains[ i ],
+                psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder );
+            x_pre_ptr += psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder;
+            x_ptr     += psEnc->sCmn.subfr_length;
+        }
+        silk_memset( psEncCtrl->LTPCoef, 0, psEnc->sCmn.nb_subfr * LTP_ORDER * sizeof( silk_float ) );
+        psEncCtrl->LTPredCodGain = 0.0f;
+        psEnc->sCmn.sum_log_gain_Q7 = 0;
+    }
+
+    /* Limit on total predictive coding gain */
+    if( psEnc->sCmn.first_frame_after_reset ) {
+        minInvGain = 1.0f / MAX_PREDICTION_POWER_GAIN_AFTER_RESET;
+    } else {
+        minInvGain = (silk_float)pow( 2, psEncCtrl->LTPredCodGain / 3 ) /  MAX_PREDICTION_POWER_GAIN;
+        minInvGain /= 0.25f + 0.75f * psEncCtrl->coding_quality;
+    }
+
+    /* LPC_in_pre contains the LTP-filtered input for voiced, and the unfiltered input for unvoiced */
+    silk_find_LPC_FLP( &psEnc->sCmn, NLSF_Q15, LPC_in_pre, minInvGain );
+
+    /* Quantize LSFs */
+    silk_process_NLSFs_FLP( &psEnc->sCmn, psEncCtrl->PredCoef, NLSF_Q15, psEnc->sCmn.prev_NLSFq_Q15 );
+
+    /* Calculate residual energy using quantized LPC coefficients */
+    silk_residual_energy_FLP( psEncCtrl->ResNrg, LPC_in_pre, psEncCtrl->PredCoef, psEncCtrl->Gains,
+        psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr, psEnc->sCmn.predictLPCOrder );
+
+    /* Copy to prediction struct for use in next frame for interpolation */
+    silk_memcpy( psEnc->sCmn.prev_NLSFq_Q15, NLSF_Q15, sizeof( psEnc->sCmn.prev_NLSFq_Q15 ) );
+}
+
diff --git a/opus/silk/float/inner_product_FLP.c b/opus/silk/float/inner_product_FLP.c
new file mode 100644 (file)
index 0000000..cdd39d2
--- /dev/null
@@ -0,0 +1,59 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* inner product of two silk_float arrays, with result as double */
+double silk_inner_product_FLP(
+    const silk_float    *data1,
+    const silk_float    *data2,
+    opus_int            dataSize
+)
+{
+    opus_int i;
+    double   result;
+
+    /* 4x unrolled loop */
+    result = 0.0;
+    for( i = 0; i < dataSize - 3; i += 4 ) {
+        result += data1[ i + 0 ] * (double)data2[ i + 0 ] +
+                  data1[ i + 1 ] * (double)data2[ i + 1 ] +
+                  data1[ i + 2 ] * (double)data2[ i + 2 ] +
+                  data1[ i + 3 ] * (double)data2[ i + 3 ];
+    }
+
+    /* add any remaining products */
+    for( ; i < dataSize; i++ ) {
+        result += data1[ i ] * (double)data2[ i ];
+    }
+
+    return result;
+}
diff --git a/opus/silk/float/k2a_FLP.c b/opus/silk/float/k2a_FLP.c
new file mode 100644 (file)
index 0000000..1448008
--- /dev/null
@@ -0,0 +1,54 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* step up function, converts reflection coefficients to prediction coefficients */
+void silk_k2a_FLP(
+    silk_float          *A,                 /* O     prediction coefficients [order]                            */
+    const silk_float    *rc,                /* I     reflection coefficients [order]                            */
+    opus_int32          order               /* I     prediction order                                           */
+)
+{
+    opus_int   k, n;
+    silk_float rck, tmp1, tmp2;
+
+    for( k = 0; k < order; k++ ) {
+        rck = rc[ k ];
+        for( n = 0; n < (k + 1) >> 1; n++ ) {
+            tmp1 = A[ n ];
+            tmp2 = A[ k - n - 1 ];
+            A[ n ]         = tmp1 + tmp2 * rck;
+            A[ k - n - 1 ] = tmp2 + tmp1 * rck;
+        }
+        A[ k ] = -rck;
+    }
+}
diff --git a/opus/silk/float/main_FLP.h b/opus/silk/float/main_FLP.h
new file mode 100644 (file)
index 0000000..f47fc93
--- /dev/null
@@ -0,0 +1,285 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MAIN_FLP_H
+#define SILK_MAIN_FLP_H
+
+#include "SigProc_FLP.h"
+#include "SigProc_FIX.h"
+#include "structs_FLP.h"
+#include "main.h"
+#include "define.h"
+#include "debug.h"
+#include "entenc.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define silk_encoder_state_Fxx      silk_encoder_state_FLP
+#define silk_encode_do_VAD_Fxx      silk_encode_do_VAD_FLP
+#define silk_encode_frame_Fxx       silk_encode_frame_FLP
+
+/*********************/
+/* Encoder Functions */
+/*********************/
+
+/* High-pass filter with cutoff frequency adaptation based on pitch lag statistics */
+void silk_HP_variable_cutoff(
+    silk_encoder_state_Fxx          state_Fxx[]                         /* I/O  Encoder states                              */
+);
+
+/* Encoder main function */
+void silk_encode_do_VAD_FLP(
+    silk_encoder_state_FLP          *psEnc                              /* I/O  Encoder state FLP                           */
+);
+
+/* Encoder main function */
+opus_int silk_encode_frame_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    opus_int32                      *pnBytesOut,                        /* O    Number of payload bytes;                    */
+    ec_enc                          *psRangeEnc,                        /* I/O  compressor data structure                   */
+    opus_int                        condCoding,                         /* I    The type of conditional coding to use       */
+    opus_int                        maxBits,                            /* I    If > 0: maximum number of output bits       */
+    opus_int                        useCBR                              /* I    Flag to force constant-bitrate operation    */
+);
+
+/* Initializes the Silk encoder state */
+opus_int silk_init_encoder(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    int                              arch                               /* I    Run-tim architecture                        */
+);
+
+/* Control the Silk encoder */
+opus_int silk_control_encoder(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Pointer to Silk encoder state FLP           */
+    silk_EncControlStruct           *encControl,                        /* I    Control structure                           */
+    const opus_int                  allow_bw_switch,                    /* I    Flag to allow switching audio bandwidth     */
+    const opus_int                  channelNb,                          /* I    Channel number                              */
+    const opus_int                  force_fs_kHz
+);
+
+/**************************/
+/* Noise shaping analysis */
+/**************************/
+/* Compute noise shaping coefficients and initial gain values */
+void silk_noise_shape_analysis_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                *pitch_res,                         /* I    LPC residual from pitch analysis            */
+    const silk_float                *x                                  /* I    Input signal [frame_length + la_shape]      */
+);
+
+/* Autocorrelations for a warped frequency axis */
+void silk_warped_autocorrelation_FLP(
+    silk_float                      *corr,                              /* O    Result [order + 1]                          */
+    const silk_float                *input,                             /* I    Input data to correlate                     */
+    const silk_float                warping,                            /* I    Warping coefficient                         */
+    const opus_int                  length,                             /* I    Length of input                             */
+    const opus_int                  order                               /* I    Correlation order (even)                    */
+);
+
+/* Calculation of LTP state scaling */
+void silk_LTP_scale_ctrl_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+);
+
+/**********************************************/
+/* Prediction Analysis                        */
+/**********************************************/
+/* Find pitch lags */
+void silk_find_pitch_lags_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    silk_float                      res[],                              /* O    Residual                                    */
+    const silk_float                x[],                                /* I    Speech signal                               */
+    int                             arch                                /* I    Run-time architecture                       */
+);
+
+/* Find LPC and LTP coefficients */
+void silk_find_pred_coefs_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                res_pitch[],                        /* I    Residual from pitch analysis                */
+    const silk_float                x[],                                /* I    Speech signal                               */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+);
+
+/* LPC analysis */
+void silk_find_LPC_FLP(
+    silk_encoder_state              *psEncC,                            /* I/O  Encoder state                               */
+    opus_int16                      NLSF_Q15[],                         /* O    NLSFs                                       */
+    const silk_float                x[],                                /* I    Input signal                                */
+    const silk_float                minInvGain                          /* I    Prediction gain from LTP (dB)               */
+);
+
+/* LTP analysis */
+void silk_find_LTP_FLP(
+    silk_float                      XX[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* O    Weight for LTP quantization         */
+    silk_float                      xX[ MAX_NB_SUBFR * LTP_ORDER ],     /* O    Weight for LTP quantization                 */
+    const silk_float                r_ptr[],                            /* I    LPC residual                                */
+    const opus_int                  lag[  MAX_NB_SUBFR ],               /* I    LTP lags                                    */
+    const opus_int                  subfr_length,                       /* I    Subframe length                             */
+    const opus_int                  nb_subfr                            /* I    number of subframes                         */
+);
+
+void silk_LTP_analysis_filter_FLP(
+    silk_float                      *LTP_res,                           /* O    LTP res MAX_NB_SUBFR*(pre_lgth+subfr_lngth) */
+    const silk_float                *x,                                 /* I    Input signal, with preceding samples        */
+    const silk_float                B[ LTP_ORDER * MAX_NB_SUBFR ],      /* I    LTP coefficients for each subframe          */
+    const opus_int                  pitchL[   MAX_NB_SUBFR ],           /* I    Pitch lags                                  */
+    const silk_float                invGains[ MAX_NB_SUBFR ],           /* I    Inverse quantization gains                  */
+    const opus_int                  subfr_length,                       /* I    Length of each subframe                     */
+    const opus_int                  nb_subfr,                           /* I    number of subframes                         */
+    const opus_int                  pre_length                          /* I    Preceding samples for each subframe         */
+);
+
+/* Calculates residual energies of input subframes where all subframes have LPC_order   */
+/* of preceding samples                                                                 */
+void silk_residual_energy_FLP(
+    silk_float                      nrgs[ MAX_NB_SUBFR ],               /* O    Residual energy per subframe                */
+    const silk_float                x[],                                /* I    Input signal                                */
+    silk_float                      a[ 2 ][ MAX_LPC_ORDER ],            /* I    AR coefs for each frame half                */
+    const silk_float                gains[],                            /* I    Quantization gains                          */
+    const opus_int                  subfr_length,                       /* I    Subframe length                             */
+    const opus_int                  nb_subfr,                           /* I    number of subframes                         */
+    const opus_int                  LPC_order                           /* I    LPC order                                   */
+);
+
+/* 16th order LPC analysis filter */
+void silk_LPC_analysis_filter_FLP(
+    silk_float                      r_LPC[],                            /* O    LPC residual signal                         */
+    const silk_float                PredCoef[],                         /* I    LPC coefficients                            */
+    const silk_float                s[],                                /* I    Input signal                                */
+    const opus_int                  length,                             /* I    Length of input signal                      */
+    const opus_int                  Order                               /* I    LPC order                                   */
+);
+
+/* LTP tap quantizer */
+void silk_quant_LTP_gains_FLP(
+    silk_float                      B[ MAX_NB_SUBFR * LTP_ORDER ],      /* O    Quantized LTP gains                         */
+    opus_int8                       cbk_index[ MAX_NB_SUBFR ],          /* O    Codebook index                              */
+    opus_int8                       *periodicity_index,                 /* O    Periodicity index                           */
+    opus_int32                      *sum_log_gain_Q7,                   /* I/O  Cumulative max prediction gain  */
+    silk_float                      *pred_gain_dB,                      /* O    LTP prediction gain                         */
+    const silk_float                XX[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* I    Correlation matrix                  */
+    const silk_float                xX[ MAX_NB_SUBFR * LTP_ORDER ],     /* I    Correlation vector                          */
+    const opus_int                  subfr_len,                          /* I    Number of samples per subframe              */
+    const opus_int                  nb_subfr,                           /* I    Number of subframes                         */
+    int                             arch                                /* I    Run-time architecture                       */
+);
+
+/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */
+silk_float silk_residual_energy_covar_FLP(                              /* O    Weighted residual energy                    */
+    const silk_float                *c,                                 /* I    Filter coefficients                         */
+    silk_float                      *wXX,                               /* I/O  Weighted correlation matrix, reg. out       */
+    const silk_float                *wXx,                               /* I    Weighted correlation vector                 */
+    const silk_float                wxx,                                /* I    Weighted correlation value                  */
+    const opus_int                  D                                   /* I    Dimension                                   */
+);
+
+/* Processing of gains */
+void silk_process_gains_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+);
+
+/******************/
+/* Linear Algebra */
+/******************/
+/* Calculates correlation matrix X'*X */
+void silk_corrMatrix_FLP(
+    const silk_float                *x,                                 /* I    x vector [ L+order-1 ] used to create X     */
+    const opus_int                  L,                                  /* I    Length of vectors                           */
+    const opus_int                  Order,                              /* I    Max lag for correlation                     */
+    silk_float                      *XX                                 /* O    X'*X correlation matrix [order x order]     */
+);
+
+/* Calculates correlation vector X'*t */
+void silk_corrVector_FLP(
+    const silk_float                *x,                                 /* I    x vector [L+order-1] used to create X       */
+    const silk_float                *t,                                 /* I    Target vector [L]                           */
+    const opus_int                  L,                                  /* I    Length of vecors                            */
+    const opus_int                  Order,                              /* I    Max lag for correlation                     */
+    silk_float                      *Xt                                 /* O    X'*t correlation vector [order]             */
+);
+
+/* Apply sine window to signal vector.  */
+/* Window types:                        */
+/*  1 -> sine window from 0 to pi/2     */
+/*  2 -> sine window from pi/2 to pi    */
+void silk_apply_sine_window_FLP(
+    silk_float                      px_win[],                           /* O    Pointer to windowed signal                  */
+    const silk_float                px[],                               /* I    Pointer to input signal                     */
+    const opus_int                  win_type,                           /* I    Selects a window type                       */
+    const opus_int                  length                              /* I    Window length, multiple of 4                */
+);
+
+/* Wrapper functions. Call flp / fix code */
+
+/* Convert AR filter coefficients to NLSF parameters */
+void silk_A2NLSF_FLP(
+    opus_int16                      *NLSF_Q15,                          /* O    NLSF vector      [ LPC_order ]              */
+    const silk_float                *pAR,                               /* I    LPC coefficients [ LPC_order ]              */
+    const opus_int                  LPC_order                           /* I    LPC order                                   */
+);
+
+/* Convert NLSF parameters to AR prediction filter coefficients */
+void silk_NLSF2A_FLP(
+    silk_float                      *pAR,                               /* O    LPC coefficients [ LPC_order ]              */
+    const opus_int16                *NLSF_Q15,                          /* I    NLSF vector      [ LPC_order ]              */
+    const opus_int                  LPC_order,                          /* I    LPC order                                   */
+    int                             arch                                /* I    Run-time architecture                       */
+);
+
+/* Limit, stabilize, and quantize NLSFs */
+void silk_process_NLSFs_FLP(
+    silk_encoder_state              *psEncC,                            /* I/O  Encoder state                               */
+    silk_float                      PredCoef[ 2 ][ MAX_LPC_ORDER ],     /* O    Prediction coefficients                     */
+    opus_int16                      NLSF_Q15[      MAX_LPC_ORDER ],     /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */
+    const opus_int16                prev_NLSF_Q15[ MAX_LPC_ORDER ]      /* I    Previous Normalized LSFs (0 - (2^15-1))     */
+);
+
+/* Floating-point Silk NSQ wrapper      */
+void silk_NSQ_wrapper_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    SideInfoIndices                 *psIndices,                         /* I/O  Quantization indices                        */
+    silk_nsq_state                  *psNSQ,                             /* I/O  Noise Shaping Quantzation state             */
+    opus_int8                       pulses[],                           /* O    Quantized pulse signal                      */
+    const silk_float                x[]                                 /* I    Prefiltered input signal                    */
+);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/float/noise_shape_analysis_FLP.c b/opus/silk/float/noise_shape_analysis_FLP.c
new file mode 100644 (file)
index 0000000..cb3d8a5
--- /dev/null
@@ -0,0 +1,350 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+/* Compute gain to make warped filter coefficients have a zero mean log frequency response on a   */
+/* non-warped frequency scale. (So that it can be implemented with a minimum-phase monic filter.) */
+/* Note: A monic filter is one with the first coefficient equal to 1.0. In Silk we omit the first */
+/* coefficient in an array of coefficients, for monic filters.                                    */
+static OPUS_INLINE silk_float warped_gain(
+    const silk_float     *coefs,
+    silk_float           lambda,
+    opus_int             order
+) {
+    opus_int   i;
+    silk_float gain;
+
+    lambda = -lambda;
+    gain = coefs[ order - 1 ];
+    for( i = order - 2; i >= 0; i-- ) {
+        gain = lambda * gain + coefs[ i ];
+    }
+    return (silk_float)( 1.0f / ( 1.0f - lambda * gain ) );
+}
+
+/* Convert warped filter coefficients to monic pseudo-warped coefficients and limit maximum     */
+/* amplitude of monic warped coefficients by using bandwidth expansion on the true coefficients */
+static OPUS_INLINE void warped_true2monic_coefs(
+    silk_float           *coefs,
+    silk_float           lambda,
+    silk_float           limit,
+    opus_int             order
+) {
+    opus_int   i, iter, ind = 0;
+    silk_float tmp, maxabs, chirp, gain;
+
+    /* Convert to monic coefficients */
+    for( i = order - 1; i > 0; i-- ) {
+        coefs[ i - 1 ] -= lambda * coefs[ i ];
+    }
+    gain = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs[ 0 ] );
+    for( i = 0; i < order; i++ ) {
+        coefs[ i ] *= gain;
+    }
+
+    /* Limit */
+    for( iter = 0; iter < 10; iter++ ) {
+        /* Find maximum absolute value */
+        maxabs = -1.0f;
+        for( i = 0; i < order; i++ ) {
+            tmp = silk_abs_float( coefs[ i ] );
+            if( tmp > maxabs ) {
+                maxabs = tmp;
+                ind = i;
+            }
+        }
+        if( maxabs <= limit ) {
+            /* Coefficients are within range - done */
+            return;
+        }
+
+        /* Convert back to true warped coefficients */
+        for( i = 1; i < order; i++ ) {
+            coefs[ i - 1 ] += lambda * coefs[ i ];
+        }
+        gain = 1.0f / gain;
+        for( i = 0; i < order; i++ ) {
+            coefs[ i ] *= gain;
+        }
+
+        /* Apply bandwidth expansion */
+        chirp = 0.99f - ( 0.8f + 0.1f * iter ) * ( maxabs - limit ) / ( maxabs * ( ind + 1 ) );
+        silk_bwexpander_FLP( coefs, order, chirp );
+
+        /* Convert to monic warped coefficients */
+        for( i = order - 1; i > 0; i-- ) {
+            coefs[ i - 1 ] -= lambda * coefs[ i ];
+        }
+        gain = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs[ 0 ] );
+        for( i = 0; i < order; i++ ) {
+            coefs[ i ] *= gain;
+        }
+    }
+    silk_assert( 0 );
+}
+
+static OPUS_INLINE void limit_coefs(
+    silk_float           *coefs,
+    silk_float           limit,
+    opus_int             order
+) {
+    opus_int   i, iter, ind = 0;
+    silk_float tmp, maxabs, chirp;
+
+    for( iter = 0; iter < 10; iter++ ) {
+        /* Find maximum absolute value */
+        maxabs = -1.0f;
+        for( i = 0; i < order; i++ ) {
+            tmp = silk_abs_float( coefs[ i ] );
+            if( tmp > maxabs ) {
+                maxabs = tmp;
+                ind = i;
+            }
+        }
+        if( maxabs <= limit ) {
+            /* Coefficients are within range - done */
+            return;
+        }
+
+        /* Apply bandwidth expansion */
+        chirp = 0.99f - ( 0.8f + 0.1f * iter ) * ( maxabs - limit ) / ( maxabs * ( ind + 1 ) );
+        silk_bwexpander_FLP( coefs, order, chirp );
+    }
+    silk_assert( 0 );
+}
+
+/* Compute noise shaping coefficients and initial gain values */
+void silk_noise_shape_analysis_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    const silk_float                *pitch_res,                         /* I    LPC residual from pitch analysis            */
+    const silk_float                *x                                  /* I    Input signal [frame_length + la_shape]      */
+)
+{
+    silk_shape_state_FLP *psShapeSt = &psEnc->sShape;
+    opus_int     k, nSamples, nSegs;
+    silk_float   SNR_adj_dB, HarmShapeGain, Tilt;
+    silk_float   nrg, log_energy, log_energy_prev, energy_variation;
+    silk_float   BWExp, gain_mult, gain_add, strength, b, warping;
+    silk_float   x_windowed[ SHAPE_LPC_WIN_MAX ];
+    silk_float   auto_corr[ MAX_SHAPE_LPC_ORDER + 1 ];
+    silk_float   rc[ MAX_SHAPE_LPC_ORDER + 1 ];
+    const silk_float *x_ptr, *pitch_res_ptr;
+
+    /* Point to start of first LPC analysis block */
+    x_ptr = x - psEnc->sCmn.la_shape;
+
+    /****************/
+    /* GAIN CONTROL */
+    /****************/
+    SNR_adj_dB = psEnc->sCmn.SNR_dB_Q7 * ( 1 / 128.0f );
+
+    /* Input quality is the average of the quality in the lowest two VAD bands */
+    psEncCtrl->input_quality = 0.5f * ( psEnc->sCmn.input_quality_bands_Q15[ 0 ] + psEnc->sCmn.input_quality_bands_Q15[ 1 ] ) * ( 1.0f / 32768.0f );
+
+    /* Coding quality level, between 0.0 and 1.0 */
+    psEncCtrl->coding_quality = silk_sigmoid( 0.25f * ( SNR_adj_dB - 20.0f ) );
+
+    if( psEnc->sCmn.useCBR == 0 ) {
+        /* Reduce coding SNR during low speech activity */
+        b = 1.0f - psEnc->sCmn.speech_activity_Q8 * ( 1.0f /  256.0f );
+        SNR_adj_dB -= BG_SNR_DECR_dB * psEncCtrl->coding_quality * ( 0.5f + 0.5f * psEncCtrl->input_quality ) * b * b;
+    }
+
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce gains for periodic signals */
+        SNR_adj_dB += HARM_SNR_INCR_dB * psEnc->LTPCorr;
+    } else {
+        /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */
+        SNR_adj_dB += ( -0.4f * psEnc->sCmn.SNR_dB_Q7 * ( 1 / 128.0f ) + 6.0f ) * ( 1.0f - psEncCtrl->input_quality );
+    }
+
+    /*************************/
+    /* SPARSENESS PROCESSING */
+    /*************************/
+    /* Set quantizer offset */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Initially set to 0; may be overruled in process_gains(..) */
+        psEnc->sCmn.indices.quantOffsetType = 0;
+    } else {
+        /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */
+        nSamples = 2 * psEnc->sCmn.fs_kHz;
+        energy_variation = 0.0f;
+        log_energy_prev  = 0.0f;
+        pitch_res_ptr = pitch_res;
+        nSegs = silk_SMULBB( SUB_FRAME_LENGTH_MS, psEnc->sCmn.nb_subfr ) / 2;
+        for( k = 0; k < nSegs; k++ ) {
+            nrg = ( silk_float )nSamples + ( silk_float )silk_energy_FLP( pitch_res_ptr, nSamples );
+            log_energy = silk_log2( nrg );
+            if( k > 0 ) {
+                energy_variation += silk_abs_float( log_energy - log_energy_prev );
+            }
+            log_energy_prev = log_energy;
+            pitch_res_ptr += nSamples;
+        }
+
+        /* Set quantization offset depending on sparseness measure */
+        if( energy_variation > ENERGY_VARIATION_THRESHOLD_QNT_OFFSET * (nSegs-1) ) {
+            psEnc->sCmn.indices.quantOffsetType = 0;
+        } else {
+            psEnc->sCmn.indices.quantOffsetType = 1;
+        }
+    }
+
+    /*******************************/
+    /* Control bandwidth expansion */
+    /*******************************/
+    /* More BWE for signals with high prediction gain */
+    strength = FIND_PITCH_WHITE_NOISE_FRACTION * psEncCtrl->predGain;           /* between 0.0 and 1.0 */
+    BWExp = BANDWIDTH_EXPANSION / ( 1.0f + strength * strength );
+
+    /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */
+    warping = (silk_float)psEnc->sCmn.warping_Q16 / 65536.0f + 0.01f * psEncCtrl->coding_quality;
+
+    /********************************************/
+    /* Compute noise shaping AR coefs and gains */
+    /********************************************/
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        /* Apply window: sine slope followed by flat part followed by cosine slope */
+        opus_int shift, slope_part, flat_part;
+        flat_part = psEnc->sCmn.fs_kHz * 3;
+        slope_part = ( psEnc->sCmn.shapeWinLength - flat_part ) / 2;
+
+        silk_apply_sine_window_FLP( x_windowed, x_ptr, 1, slope_part );
+        shift = slope_part;
+        silk_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(silk_float) );
+        shift += flat_part;
+        silk_apply_sine_window_FLP( x_windowed + shift, x_ptr + shift, 2, slope_part );
+
+        /* Update pointer: next LPC analysis block */
+        x_ptr += psEnc->sCmn.subfr_length;
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Calculate warped auto correlation */
+            silk_warped_autocorrelation_FLP( auto_corr, x_windowed, warping,
+                psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder );
+        } else {
+            /* Calculate regular auto correlation */
+            silk_autocorrelation_FLP( auto_corr, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1 );
+        }
+
+        /* Add white noise, as a fraction of energy */
+        auto_corr[ 0 ] += auto_corr[ 0 ] * SHAPE_WHITE_NOISE_FRACTION + 1.0f;
+
+        /* Convert correlations to prediction coefficients, and compute residual energy */
+        nrg = silk_schur_FLP( rc, auto_corr, psEnc->sCmn.shapingLPCOrder );
+        silk_k2a_FLP( &psEncCtrl->AR[ k * MAX_SHAPE_LPC_ORDER ], rc, psEnc->sCmn.shapingLPCOrder );
+        psEncCtrl->Gains[ k ] = ( silk_float )sqrt( nrg );
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Adjust gain for warping */
+            psEncCtrl->Gains[ k ] *= warped_gain( &psEncCtrl->AR[ k * MAX_SHAPE_LPC_ORDER ], warping, psEnc->sCmn.shapingLPCOrder );
+        }
+
+        /* Bandwidth expansion for synthesis filter shaping */
+        silk_bwexpander_FLP( &psEncCtrl->AR[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder, BWExp );
+
+        if( psEnc->sCmn.warping_Q16 > 0 ) {
+            /* Convert to monic warped prediction coefficients and limit absolute values */
+            warped_true2monic_coefs( &psEncCtrl->AR[ k * MAX_SHAPE_LPC_ORDER ], warping, 3.999f, psEnc->sCmn.shapingLPCOrder );
+        } else {
+            /* Limit absolute values */
+            limit_coefs( &psEncCtrl->AR[ k * MAX_SHAPE_LPC_ORDER ], 3.999f, psEnc->sCmn.shapingLPCOrder );
+        }
+    }
+
+    /*****************/
+    /* Gain tweaking */
+    /*****************/
+    /* Increase gains during low speech activity */
+    gain_mult = (silk_float)pow( 2.0f, -0.16f * SNR_adj_dB );
+    gain_add  = (silk_float)pow( 2.0f,  0.16f * MIN_QGAIN_DB );
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psEncCtrl->Gains[ k ] *= gain_mult;
+        psEncCtrl->Gains[ k ] += gain_add;
+    }
+
+    /************************************************/
+    /* Control low-frequency shaping and noise tilt */
+    /************************************************/
+    /* Less low frequency shaping for noisy inputs */
+    strength = LOW_FREQ_SHAPING * ( 1.0f + LOW_QUALITY_LOW_FREQ_SHAPING_DECR * ( psEnc->sCmn.input_quality_bands_Q15[ 0 ] * ( 1.0f / 32768.0f ) - 1.0f ) );
+    strength *= psEnc->sCmn.speech_activity_Q8 * ( 1.0f /  256.0f );
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */
+        /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/
+        for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+            b = 0.2f / psEnc->sCmn.fs_kHz + 3.0f / psEncCtrl->pitchL[ k ];
+            psEncCtrl->LF_MA_shp[ k ] = -1.0f + b;
+            psEncCtrl->LF_AR_shp[ k ] =  1.0f - b - b * strength;
+        }
+        Tilt = - HP_NOISE_COEF -
+            (1 - HP_NOISE_COEF) * HARM_HP_NOISE_COEF * psEnc->sCmn.speech_activity_Q8 * ( 1.0f /  256.0f );
+    } else {
+        b = 1.3f / psEnc->sCmn.fs_kHz;
+        psEncCtrl->LF_MA_shp[ 0 ] = -1.0f + b;
+        psEncCtrl->LF_AR_shp[ 0 ] =  1.0f - b - b * strength * 0.6f;
+        for( k = 1; k < psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->LF_MA_shp[ k ] = psEncCtrl->LF_MA_shp[ 0 ];
+            psEncCtrl->LF_AR_shp[ k ] = psEncCtrl->LF_AR_shp[ 0 ];
+        }
+        Tilt = -HP_NOISE_COEF;
+    }
+
+    /****************************/
+    /* HARMONIC SHAPING CONTROL */
+    /****************************/
+    if( USE_HARM_SHAPING && psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        /* Harmonic noise shaping */
+        HarmShapeGain = HARMONIC_SHAPING;
+
+        /* More harmonic noise shaping for high bitrates or noisy input */
+        HarmShapeGain += HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING *
+            ( 1.0f - ( 1.0f - psEncCtrl->coding_quality ) * psEncCtrl->input_quality );
+
+        /* Less harmonic noise shaping for less periodic signals */
+        HarmShapeGain *= ( silk_float )sqrt( psEnc->LTPCorr );
+    } else {
+        HarmShapeGain = 0.0f;
+    }
+
+    /*************************/
+    /* Smooth over subframes */
+    /*************************/
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psShapeSt->HarmShapeGain_smth += SUBFR_SMTH_COEF * ( HarmShapeGain - psShapeSt->HarmShapeGain_smth );
+        psEncCtrl->HarmShapeGain[ k ]  = psShapeSt->HarmShapeGain_smth;
+        psShapeSt->Tilt_smth          += SUBFR_SMTH_COEF * ( Tilt - psShapeSt->Tilt_smth );
+        psEncCtrl->Tilt[ k ]           = psShapeSt->Tilt_smth;
+    }
+}
diff --git a/opus/silk/float/pitch_analysis_core_FLP.c b/opus/silk/float/pitch_analysis_core_FLP.c
new file mode 100644 (file)
index 0000000..b371693
--- /dev/null
@@ -0,0 +1,630 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*****************************************************************************
+* Pitch analyser function
+******************************************************************************/
+#include "SigProc_FLP.h"
+#include "SigProc_FIX.h"
+#include "pitch_est_defines.h"
+#include "pitch.h"
+
+#define SCRATCH_SIZE        22
+
+/************************************************************/
+/* Internally used functions                                */
+/************************************************************/
+static void silk_P_Ana_calc_corr_st3(
+    silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */
+    const silk_float    frame[],            /* I vector to correlate                                            */
+    opus_int            start_lag,          /* I start lag                                                      */
+    opus_int            sf_length,          /* I sub frame length                                               */
+    opus_int            nb_subfr,           /* I number of subframes                                            */
+    opus_int            complexity,         /* I Complexity setting                                             */
+    int                 arch                /* I Run-time architecture                                          */
+);
+
+static void silk_P_Ana_calc_energy_st3(
+    silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */
+    const silk_float    frame[],            /* I vector to correlate                                            */
+    opus_int            start_lag,          /* I start lag                                                      */
+    opus_int            sf_length,          /* I sub frame length                                               */
+    opus_int            nb_subfr,           /* I number of subframes                                            */
+    opus_int            complexity          /* I Complexity setting                                             */
+);
+
+/************************************************************/
+/* CORE PITCH ANALYSIS FUNCTION                             */
+/************************************************************/
+opus_int silk_pitch_analysis_core_FLP(      /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */
+    const silk_float    *frame,             /* I    Signal of length PE_FRAME_LENGTH_MS*Fs_kHz                  */
+    opus_int            *pitch_out,         /* O    Pitch lag values [nb_subfr]                                 */
+    opus_int16          *lagIndex,          /* O    Lag Index                                                   */
+    opus_int8           *contourIndex,      /* O    Pitch contour Index                                         */
+    silk_float          *LTPCorr,           /* I/O  Normalized correlation; input: value from previous frame    */
+    opus_int            prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */
+    const silk_float    search_thres1,      /* I    First stage threshold for lag candidates 0 - 1              */
+    const silk_float    search_thres2,      /* I    Final threshold for lag candidates 0 - 1                    */
+    const opus_int      Fs_kHz,             /* I    sample frequency (kHz)                                      */
+    const opus_int      complexity,         /* I    Complexity setting, 0-2, where 2 is highest                 */
+    const opus_int      nb_subfr,           /* I    Number of 5 ms subframes                                    */
+    int                 arch                /* I    Run-time architecture                                       */
+)
+{
+    opus_int   i, k, d, j;
+    silk_float frame_8kHz[  PE_MAX_FRAME_LENGTH_MS * 8 ];
+    silk_float frame_4kHz[  PE_MAX_FRAME_LENGTH_MS * 4 ];
+    opus_int16 frame_8_FIX[ PE_MAX_FRAME_LENGTH_MS * 8 ];
+    opus_int16 frame_4_FIX[ PE_MAX_FRAME_LENGTH_MS * 4 ];
+    opus_int32 filt_state[ 6 ];
+    silk_float threshold, contour_bias;
+    silk_float C[ PE_MAX_NB_SUBFR][ (PE_MAX_LAG >> 1) + 5 ];
+    opus_val32 xcorr[ PE_MAX_LAG_MS * 4 - PE_MIN_LAG_MS * 4 + 1 ];
+    silk_float CC[ PE_NB_CBKS_STAGE2_EXT ];
+    const silk_float *target_ptr, *basis_ptr;
+    double    cross_corr, normalizer, energy, energy_tmp;
+    opus_int   d_srch[ PE_D_SRCH_LENGTH ];
+    opus_int16 d_comp[ (PE_MAX_LAG >> 1) + 5 ];
+    opus_int   length_d_srch, length_d_comp;
+    silk_float Cmax, CCmax, CCmax_b, CCmax_new_b, CCmax_new;
+    opus_int   CBimax, CBimax_new, lag, start_lag, end_lag, lag_new;
+    opus_int   cbk_size;
+    silk_float lag_log2, prevLag_log2, delta_lag_log2_sqr;
+    silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ];
+    silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ];
+    opus_int   lag_counter;
+    opus_int   frame_length, frame_length_8kHz, frame_length_4kHz;
+    opus_int   sf_length, sf_length_8kHz, sf_length_4kHz;
+    opus_int   min_lag, min_lag_8kHz, min_lag_4kHz;
+    opus_int   max_lag, max_lag_8kHz, max_lag_4kHz;
+    opus_int   nb_cbk_search;
+    const opus_int8 *Lag_CB_ptr;
+
+    /* Check for valid sampling frequency */
+    silk_assert( Fs_kHz == 8 || Fs_kHz == 12 || Fs_kHz == 16 );
+
+    /* Check for valid complexity setting */
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    silk_assert( search_thres1 >= 0.0f && search_thres1 <= 1.0f );
+    silk_assert( search_thres2 >= 0.0f && search_thres2 <= 1.0f );
+
+    /* Set up frame lengths max / min lag for the sampling frequency */
+    frame_length      = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * Fs_kHz;
+    frame_length_4kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 4;
+    frame_length_8kHz = ( PE_LTP_MEM_LENGTH_MS + nb_subfr * PE_SUBFR_LENGTH_MS ) * 8;
+    sf_length         = PE_SUBFR_LENGTH_MS * Fs_kHz;
+    sf_length_4kHz    = PE_SUBFR_LENGTH_MS * 4;
+    sf_length_8kHz    = PE_SUBFR_LENGTH_MS * 8;
+    min_lag           = PE_MIN_LAG_MS * Fs_kHz;
+    min_lag_4kHz      = PE_MIN_LAG_MS * 4;
+    min_lag_8kHz      = PE_MIN_LAG_MS * 8;
+    max_lag           = PE_MAX_LAG_MS * Fs_kHz - 1;
+    max_lag_4kHz      = PE_MAX_LAG_MS * 4;
+    max_lag_8kHz      = PE_MAX_LAG_MS * 8 - 1;
+
+    /* Resample from input sampled at Fs_kHz to 8 kHz */
+    if( Fs_kHz == 16 ) {
+        /* Resample to 16 -> 8 khz */
+        opus_int16 frame_16_FIX[ 16 * PE_MAX_FRAME_LENGTH_MS ];
+        silk_float2short_array( frame_16_FIX, frame, frame_length );
+        silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) );
+        silk_resampler_down2( filt_state, frame_8_FIX, frame_16_FIX, frame_length );
+        silk_short2float_array( frame_8kHz, frame_8_FIX, frame_length_8kHz );
+    } else if( Fs_kHz == 12 ) {
+        /* Resample to 12 -> 8 khz */
+        opus_int16 frame_12_FIX[ 12 * PE_MAX_FRAME_LENGTH_MS ];
+        silk_float2short_array( frame_12_FIX, frame, frame_length );
+        silk_memset( filt_state, 0, 6 * sizeof( opus_int32 ) );
+        silk_resampler_down2_3( filt_state, frame_8_FIX, frame_12_FIX, frame_length );
+        silk_short2float_array( frame_8kHz, frame_8_FIX, frame_length_8kHz );
+    } else {
+        silk_assert( Fs_kHz == 8 );
+        silk_float2short_array( frame_8_FIX, frame, frame_length_8kHz );
+    }
+
+    /* Decimate again to 4 kHz */
+    silk_memset( filt_state, 0, 2 * sizeof( opus_int32 ) );
+    silk_resampler_down2( filt_state, frame_4_FIX, frame_8_FIX, frame_length_8kHz );
+    silk_short2float_array( frame_4kHz, frame_4_FIX, frame_length_4kHz );
+
+    /* Low-pass filter */
+    for( i = frame_length_4kHz - 1; i > 0; i-- ) {
+        frame_4kHz[ i ] = silk_ADD_SAT16( frame_4kHz[ i ], frame_4kHz[ i - 1 ] );
+    }
+
+    /******************************************************************************
+    * FIRST STAGE, operating in 4 khz
+    ******************************************************************************/
+    silk_memset(C, 0, sizeof(silk_float) * nb_subfr * ((PE_MAX_LAG >> 1) + 5));
+    target_ptr = &frame_4kHz[ silk_LSHIFT( sf_length_4kHz, 2 ) ];
+    for( k = 0; k < nb_subfr >> 1; k++ ) {
+        /* Check that we are within range of the array */
+        silk_assert( target_ptr >= frame_4kHz );
+        silk_assert( target_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz );
+
+        basis_ptr = target_ptr - min_lag_4kHz;
+
+        /* Check that we are within range of the array */
+        silk_assert( basis_ptr >= frame_4kHz );
+        silk_assert( basis_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz );
+
+        celt_pitch_xcorr( target_ptr, target_ptr-max_lag_4kHz, xcorr, sf_length_8kHz, max_lag_4kHz - min_lag_4kHz + 1, arch );
+
+        /* Calculate first vector products before loop */
+        cross_corr = xcorr[ max_lag_4kHz - min_lag_4kHz ];
+        normalizer = silk_energy_FLP( target_ptr, sf_length_8kHz ) +
+                     silk_energy_FLP( basis_ptr,  sf_length_8kHz ) +
+                     sf_length_8kHz * 4000.0f;
+
+        C[ 0 ][ min_lag_4kHz ] += (silk_float)( 2 * cross_corr / normalizer );
+
+        /* From now on normalizer is computed recursively */
+        for( d = min_lag_4kHz + 1; d <= max_lag_4kHz; d++ ) {
+            basis_ptr--;
+
+            /* Check that we are within range of the array */
+            silk_assert( basis_ptr >= frame_4kHz );
+            silk_assert( basis_ptr + sf_length_8kHz <= frame_4kHz + frame_length_4kHz );
+
+            cross_corr = xcorr[ max_lag_4kHz - d ];
+
+            /* Add contribution of new sample and remove contribution from oldest sample */
+            normalizer +=
+                basis_ptr[ 0 ] * (double)basis_ptr[ 0 ] -
+                basis_ptr[ sf_length_8kHz ] * (double)basis_ptr[ sf_length_8kHz ];
+            C[ 0 ][ d ] += (silk_float)( 2 * cross_corr / normalizer );
+        }
+        /* Update target pointer */
+        target_ptr += sf_length_8kHz;
+    }
+
+    /* Apply short-lag bias */
+    for( i = max_lag_4kHz; i >= min_lag_4kHz; i-- ) {
+        C[ 0 ][ i ] -= C[ 0 ][ i ] * i / 4096.0f;
+    }
+
+    /* Sort */
+    length_d_srch = 4 + 2 * complexity;
+    silk_assert( 3 * length_d_srch <= PE_D_SRCH_LENGTH );
+    silk_insertion_sort_decreasing_FLP( &C[ 0 ][ min_lag_4kHz ], d_srch, max_lag_4kHz - min_lag_4kHz + 1, length_d_srch );
+
+    /* Escape if correlation is very low already here */
+    Cmax = C[ 0 ][ min_lag_4kHz ];
+    if( Cmax < 0.2f ) {
+        silk_memset( pitch_out, 0, nb_subfr * sizeof( opus_int ) );
+        *LTPCorr      = 0.0f;
+        *lagIndex     = 0;
+        *contourIndex = 0;
+        return 1;
+    }
+
+    threshold = search_thres1 * Cmax;
+    for( i = 0; i < length_d_srch; i++ ) {
+        /* Convert to 8 kHz indices for the sorted correlation that exceeds the threshold */
+        if( C[ 0 ][ min_lag_4kHz + i ] > threshold ) {
+            d_srch[ i ] = silk_LSHIFT( d_srch[ i ] + min_lag_4kHz, 1 );
+        } else {
+            length_d_srch = i;
+            break;
+        }
+    }
+    silk_assert( length_d_srch > 0 );
+
+    for( i = min_lag_8kHz - 5; i < max_lag_8kHz + 5; i++ ) {
+        d_comp[ i ] = 0;
+    }
+    for( i = 0; i < length_d_srch; i++ ) {
+        d_comp[ d_srch[ i ] ] = 1;
+    }
+
+    /* Convolution */
+    for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {
+        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ];
+    }
+
+    length_d_srch = 0;
+    for( i = min_lag_8kHz; i < max_lag_8kHz + 1; i++ ) {
+        if( d_comp[ i + 1 ] > 0 ) {
+            d_srch[ length_d_srch ] = i;
+            length_d_srch++;
+        }
+    }
+
+    /* Convolution */
+    for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {
+        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ] + d_comp[ i - 3 ];
+    }
+
+    length_d_comp = 0;
+    for( i = min_lag_8kHz; i < max_lag_8kHz + 4; i++ ) {
+        if( d_comp[ i ] > 0 ) {
+            d_comp[ length_d_comp ] = (opus_int16)( i - 2 );
+            length_d_comp++;
+        }
+    }
+
+    /**********************************************************************************
+    ** SECOND STAGE, operating at 8 kHz, on lag sections with high correlation
+    *************************************************************************************/
+    /*********************************************************************************
+    * Find energy of each subframe projected onto its history, for a range of delays
+    *********************************************************************************/
+    silk_memset( C, 0, PE_MAX_NB_SUBFR*((PE_MAX_LAG >> 1) + 5) * sizeof(silk_float));
+
+    if( Fs_kHz == 8 ) {
+        target_ptr = &frame[ PE_LTP_MEM_LENGTH_MS * 8 ];
+    } else {
+        target_ptr = &frame_8kHz[ PE_LTP_MEM_LENGTH_MS * 8 ];
+    }
+    for( k = 0; k < nb_subfr; k++ ) {
+        energy_tmp = silk_energy_FLP( target_ptr, sf_length_8kHz ) + 1.0;
+        for( j = 0; j < length_d_comp; j++ ) {
+            d = d_comp[ j ];
+            basis_ptr = target_ptr - d;
+            cross_corr = silk_inner_product_FLP( basis_ptr, target_ptr, sf_length_8kHz );
+            if( cross_corr > 0.0f ) {
+                energy = silk_energy_FLP( basis_ptr, sf_length_8kHz );
+                C[ k ][ d ] = (silk_float)( 2 * cross_corr / ( energy + energy_tmp ) );
+            } else {
+                C[ k ][ d ] = 0.0f;
+            }
+        }
+        target_ptr += sf_length_8kHz;
+    }
+
+    /* search over lag range and lags codebook */
+    /* scale factor for lag codebook, as a function of center lag */
+
+    CCmax   = 0.0f; /* This value doesn't matter */
+    CCmax_b = -1000.0f;
+
+    CBimax = 0; /* To avoid returning undefined lag values */
+    lag = -1;   /* To check if lag with strong enough correlation has been found */
+
+    if( prevLag > 0 ) {
+        if( Fs_kHz == 12 ) {
+            prevLag = silk_LSHIFT( prevLag, 1 ) / 3;
+        } else if( Fs_kHz == 16 ) {
+            prevLag = silk_RSHIFT( prevLag, 1 );
+        }
+        prevLag_log2 = silk_log2( (silk_float)prevLag );
+    } else {
+        prevLag_log2 = 0;
+    }
+
+    /* Set up stage 2 codebook based on number of subframes */
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        cbk_size   = PE_NB_CBKS_STAGE2_EXT;
+        Lag_CB_ptr = &silk_CB_lags_stage2[ 0 ][ 0 ];
+        if( Fs_kHz == 8 && complexity > SILK_PE_MIN_COMPLEX ) {
+            /* If input is 8 khz use a larger codebook here because it is last stage */
+            nb_cbk_search = PE_NB_CBKS_STAGE2_EXT;
+        } else {
+            nb_cbk_search = PE_NB_CBKS_STAGE2;
+        }
+    } else {
+        cbk_size       = PE_NB_CBKS_STAGE2_10MS;
+        Lag_CB_ptr     = &silk_CB_lags_stage2_10_ms[ 0 ][ 0 ];
+        nb_cbk_search  = PE_NB_CBKS_STAGE2_10MS;
+    }
+
+    for( k = 0; k < length_d_srch; k++ ) {
+        d = d_srch[ k ];
+        for( j = 0; j < nb_cbk_search; j++ ) {
+            CC[j] = 0.0f;
+            for( i = 0; i < nb_subfr; i++ ) {
+                /* Try all codebooks */
+                CC[ j ] += C[ i ][ d + matrix_ptr( Lag_CB_ptr, i, j, cbk_size )];
+            }
+        }
+        /* Find best codebook */
+        CCmax_new  = -1000.0f;
+        CBimax_new = 0;
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            if( CC[ i ] > CCmax_new ) {
+                CCmax_new = CC[ i ];
+                CBimax_new = i;
+            }
+        }
+
+        /* Bias towards shorter lags */
+        lag_log2 = silk_log2( (silk_float)d );
+        CCmax_new_b = CCmax_new - PE_SHORTLAG_BIAS * nb_subfr * lag_log2;
+
+        /* Bias towards previous lag */
+        if( prevLag > 0 ) {
+            delta_lag_log2_sqr = lag_log2 - prevLag_log2;
+            delta_lag_log2_sqr *= delta_lag_log2_sqr;
+            CCmax_new_b -= PE_PREVLAG_BIAS * nb_subfr * (*LTPCorr) * delta_lag_log2_sqr / ( delta_lag_log2_sqr + 0.5f );
+        }
+
+        if( CCmax_new_b > CCmax_b &&                /* Find maximum biased correlation                  */
+            CCmax_new > nb_subfr * search_thres2    /* Correlation needs to be high enough to be voiced */
+        ) {
+            CCmax_b = CCmax_new_b;
+            CCmax   = CCmax_new;
+            lag     = d;
+            CBimax  = CBimax_new;
+        }
+    }
+
+    if( lag == -1 ) {
+        /* No suitable candidate found */
+        silk_memset( pitch_out, 0, PE_MAX_NB_SUBFR * sizeof(opus_int) );
+        *LTPCorr      = 0.0f;
+        *lagIndex     = 0;
+        *contourIndex = 0;
+        return 1;
+    }
+
+    /* Output normalized correlation */
+    *LTPCorr = (silk_float)( CCmax / nb_subfr );
+    silk_assert( *LTPCorr >= 0.0f );
+
+    if( Fs_kHz > 8 ) {
+        /* Search in original signal */
+
+        /* Compensate for decimation */
+        silk_assert( lag == silk_SAT16( lag ) );
+        if( Fs_kHz == 12 ) {
+            lag = silk_RSHIFT_ROUND( silk_SMULBB( lag, 3 ), 1 );
+        } else { /* Fs_kHz == 16 */
+            lag = silk_LSHIFT( lag, 1 );
+        }
+
+        lag = silk_LIMIT_int( lag, min_lag, max_lag );
+        start_lag = silk_max_int( lag - 2, min_lag );
+        end_lag   = silk_min_int( lag + 2, max_lag );
+        lag_new   = lag;                                    /* to avoid undefined lag */
+        CBimax    = 0;                                      /* to avoid undefined lag */
+
+        CCmax = -1000.0f;
+
+        /* Calculate the correlations and energies needed in stage 3 */
+        silk_P_Ana_calc_corr_st3( cross_corr_st3, frame, start_lag, sf_length, nb_subfr, complexity, arch );
+        silk_P_Ana_calc_energy_st3( energies_st3, frame, start_lag, sf_length, nb_subfr, complexity );
+
+        lag_counter = 0;
+        silk_assert( lag == silk_SAT16( lag ) );
+        contour_bias = PE_FLATCONTOUR_BIAS / lag;
+
+        /* Set up cbk parameters according to complexity setting and frame length */
+        if( nb_subfr == PE_MAX_NB_SUBFR ) {
+            nb_cbk_search = (opus_int)silk_nb_cbk_searchs_stage3[ complexity ];
+            cbk_size      = PE_NB_CBKS_STAGE3_MAX;
+            Lag_CB_ptr    = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        } else {
+            nb_cbk_search = PE_NB_CBKS_STAGE3_10MS;
+            cbk_size      = PE_NB_CBKS_STAGE3_10MS;
+            Lag_CB_ptr    = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        }
+
+        target_ptr = &frame[ PE_LTP_MEM_LENGTH_MS * Fs_kHz ];
+        energy_tmp = silk_energy_FLP( target_ptr, nb_subfr * sf_length ) + 1.0;
+        for( d = start_lag; d <= end_lag; d++ ) {
+            for( j = 0; j < nb_cbk_search; j++ ) {
+                cross_corr = 0.0;
+                energy = energy_tmp;
+                for( k = 0; k < nb_subfr; k++ ) {
+                    cross_corr += cross_corr_st3[ k ][ j ][ lag_counter ];
+                    energy     +=   energies_st3[ k ][ j ][ lag_counter ];
+                }
+                if( cross_corr > 0.0 ) {
+                    CCmax_new = (silk_float)( 2 * cross_corr / energy );
+                    /* Reduce depending on flatness of contour */
+                    CCmax_new *= 1.0f - contour_bias * j;
+                } else {
+                    CCmax_new = 0.0f;
+                }
+
+                if( CCmax_new > CCmax && ( d + (opus_int)silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag ) {
+                    CCmax   = CCmax_new;
+                    lag_new = d;
+                    CBimax  = j;
+                }
+            }
+            lag_counter++;
+        }
+
+        for( k = 0; k < nb_subfr; k++ ) {
+            pitch_out[ k ] = lag_new + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size );
+            pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], min_lag, PE_MAX_LAG_MS * Fs_kHz );
+        }
+        *lagIndex = (opus_int16)( lag_new - min_lag );
+        *contourIndex = (opus_int8)CBimax;
+    } else {        /* Fs_kHz == 8 */
+        /* Save Lags */
+        for( k = 0; k < nb_subfr; k++ ) {
+            pitch_out[ k ] = lag + matrix_ptr( Lag_CB_ptr, k, CBimax, cbk_size );
+            pitch_out[ k ] = silk_LIMIT( pitch_out[ k ], min_lag_8kHz, PE_MAX_LAG_MS * 8 );
+        }
+        *lagIndex = (opus_int16)( lag - min_lag_8kHz );
+        *contourIndex = (opus_int8)CBimax;
+    }
+    silk_assert( *lagIndex >= 0 );
+    /* return as voiced */
+    return 0;
+}
+
+/***********************************************************************
+ * Calculates the correlations used in stage 3 search. In order to cover
+ * the whole lag codebook for all the searched offset lags (lag +- 2),
+ * the following correlations are needed in each sub frame:
+ *
+ * sf1: lag range [-8,...,7] total 16 correlations
+ * sf2: lag range [-4,...,4] total 9 correlations
+ * sf3: lag range [-3,....4] total 8 correltions
+ * sf4: lag range [-6,....8] total 15 correlations
+ *
+ * In total 48 correlations. The direct implementation computed in worst
+ * case 4*12*5 = 240 correlations, but more likely around 120.
+ ***********************************************************************/
+static void silk_P_Ana_calc_corr_st3(
+    silk_float cross_corr_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */
+    const silk_float    frame[],            /* I vector to correlate                                            */
+    opus_int            start_lag,          /* I start lag                                                      */
+    opus_int            sf_length,          /* I sub frame length                                               */
+    opus_int            nb_subfr,           /* I number of subframes                                            */
+    opus_int            complexity,         /* I Complexity setting                                             */
+    int                 arch                /* I Run-time architecture                                          */
+)
+{
+    const silk_float *target_ptr;
+    opus_int   i, j, k, lag_counter, lag_low, lag_high;
+    opus_int   nb_cbk_search, delta, idx, cbk_size;
+    silk_float scratch_mem[ SCRATCH_SIZE ];
+    opus_val32 xcorr[ SCRATCH_SIZE ];
+    const opus_int8 *Lag_range_ptr, *Lag_CB_ptr;
+
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ];
+        cbk_size      = PE_NB_CBKS_STAGE3_MAX;
+    } else {
+        silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1);
+        Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        nb_cbk_search = PE_NB_CBKS_STAGE3_10MS;
+        cbk_size      = PE_NB_CBKS_STAGE3_10MS;
+    }
+
+    target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ]; /* Pointer to middle of frame */
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_counter = 0;
+
+        /* Calculate the correlations for each subframe */
+        lag_low  = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        lag_high = matrix_ptr( Lag_range_ptr, k, 1, 2 );
+        silk_assert(lag_high-lag_low+1 <= SCRATCH_SIZE);
+        celt_pitch_xcorr( target_ptr, target_ptr - start_lag - lag_high, xcorr, sf_length, lag_high - lag_low + 1, arch );
+        for( j = lag_low; j <= lag_high; j++ ) {
+            silk_assert( lag_counter < SCRATCH_SIZE );
+            scratch_mem[ lag_counter ] = xcorr[ lag_high - j ];
+            lag_counter++;
+        }
+
+        delta = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            /* Fill out the 3 dim array that stores the correlations for */
+            /* each code_book vector for each start lag */
+            idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta;
+            for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) {
+                silk_assert( idx + j < SCRATCH_SIZE );
+                silk_assert( idx + j < lag_counter );
+                cross_corr_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ];
+            }
+        }
+        target_ptr += sf_length;
+    }
+}
+
+/********************************************************************/
+/* Calculate the energies for first two subframes. The energies are */
+/* calculated recursively.                                          */
+/********************************************************************/
+static void silk_P_Ana_calc_energy_st3(
+    silk_float energies_st3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ][ PE_NB_STAGE3_LAGS ], /* O 3 DIM correlation array */
+    const silk_float    frame[],            /* I vector to correlate                                            */
+    opus_int            start_lag,          /* I start lag                                                      */
+    opus_int            sf_length,          /* I sub frame length                                               */
+    opus_int            nb_subfr,           /* I number of subframes                                            */
+    opus_int            complexity          /* I Complexity setting                                             */
+)
+{
+    const silk_float *target_ptr, *basis_ptr;
+    double    energy;
+    opus_int   k, i, j, lag_counter;
+    opus_int   nb_cbk_search, delta, idx, cbk_size, lag_diff;
+    silk_float scratch_mem[ SCRATCH_SIZE ];
+    const opus_int8 *Lag_range_ptr, *Lag_CB_ptr;
+
+    silk_assert( complexity >= SILK_PE_MIN_COMPLEX );
+    silk_assert( complexity <= SILK_PE_MAX_COMPLEX );
+
+    if( nb_subfr == PE_MAX_NB_SUBFR ) {
+        Lag_range_ptr = &silk_Lag_range_stage3[ complexity ][ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3[ 0 ][ 0 ];
+        nb_cbk_search = silk_nb_cbk_searchs_stage3[ complexity ];
+        cbk_size      = PE_NB_CBKS_STAGE3_MAX;
+    } else {
+        silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1);
+        Lag_range_ptr = &silk_Lag_range_stage3_10_ms[ 0 ][ 0 ];
+        Lag_CB_ptr    = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
+        nb_cbk_search = PE_NB_CBKS_STAGE3_10MS;
+        cbk_size      = PE_NB_CBKS_STAGE3_10MS;
+    }
+
+    target_ptr = &frame[ silk_LSHIFT( sf_length, 2 ) ];
+    for( k = 0; k < nb_subfr; k++ ) {
+        lag_counter = 0;
+
+        /* Calculate the energy for first lag */
+        basis_ptr = target_ptr - ( start_lag + matrix_ptr( Lag_range_ptr, k, 0, 2 ) );
+        energy = silk_energy_FLP( basis_ptr, sf_length ) + 1e-3;
+        silk_assert( energy >= 0.0 );
+        scratch_mem[lag_counter] = (silk_float)energy;
+        lag_counter++;
+
+        lag_diff = ( matrix_ptr( Lag_range_ptr, k, 1, 2 ) -  matrix_ptr( Lag_range_ptr, k, 0, 2 ) + 1 );
+        for( i = 1; i < lag_diff; i++ ) {
+            /* remove part outside new window */
+            energy -= basis_ptr[sf_length - i] * (double)basis_ptr[sf_length - i];
+            silk_assert( energy >= 0.0 );
+
+            /* add part that comes into window */
+            energy += basis_ptr[ -i ] * (double)basis_ptr[ -i ];
+            silk_assert( energy >= 0.0 );
+            silk_assert( lag_counter < SCRATCH_SIZE );
+            scratch_mem[lag_counter] = (silk_float)energy;
+            lag_counter++;
+        }
+
+        delta = matrix_ptr( Lag_range_ptr, k, 0, 2 );
+        for( i = 0; i < nb_cbk_search; i++ ) {
+            /* Fill out the 3 dim array that stores the correlations for    */
+            /* each code_book vector for each start lag                     */
+            idx = matrix_ptr( Lag_CB_ptr, k, i, cbk_size ) - delta;
+            for( j = 0; j < PE_NB_STAGE3_LAGS; j++ ) {
+                silk_assert( idx + j < SCRATCH_SIZE );
+                silk_assert( idx + j < lag_counter );
+                energies_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ];
+                silk_assert( energies_st3[ k ][ i ][ j ] >= 0.0f );
+            }
+        }
+        target_ptr += sf_length;
+    }
+}
diff --git a/opus/silk/float/process_gains_FLP.c b/opus/silk/float/process_gains_FLP.c
new file mode 100644 (file)
index 0000000..c0da0da
--- /dev/null
@@ -0,0 +1,103 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+#include "tuning_parameters.h"
+
+/* Processing of gains */
+void silk_process_gains_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    opus_int                        condCoding                          /* I    The type of conditional coding to use       */
+)
+{
+    silk_shape_state_FLP *psShapeSt = &psEnc->sShape;
+    opus_int     k;
+    opus_int32   pGains_Q16[ MAX_NB_SUBFR ];
+    silk_float   s, InvMaxSqrVal, gain, quant_offset;
+
+    /* Gain reduction when LTP coding gain is high */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        s = 1.0f - 0.5f * silk_sigmoid( 0.25f * ( psEncCtrl->LTPredCodGain - 12.0f ) );
+        for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+            psEncCtrl->Gains[ k ] *= s;
+        }
+    }
+
+    /* Limit the quantized signal */
+    InvMaxSqrVal = ( silk_float )( pow( 2.0f, 0.33f * ( 21.0f - psEnc->sCmn.SNR_dB_Q7 * ( 1 / 128.0f ) ) ) / psEnc->sCmn.subfr_length );
+
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        /* Soft limit on ratio residual energy and squared gains */
+        gain = psEncCtrl->Gains[ k ];
+        gain = ( silk_float )sqrt( gain * gain + psEncCtrl->ResNrg[ k ] * InvMaxSqrVal );
+        psEncCtrl->Gains[ k ] = silk_min_float( gain, 32767.0f );
+    }
+
+    /* Prepare gains for noise shaping quantization */
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        pGains_Q16[ k ] = (opus_int32)( psEncCtrl->Gains[ k ] * 65536.0f );
+    }
+
+    /* Save unquantized gains and gain Index */
+    silk_memcpy( psEncCtrl->GainsUnq_Q16, pGains_Q16, psEnc->sCmn.nb_subfr * sizeof( opus_int32 ) );
+    psEncCtrl->lastGainIndexPrev = psShapeSt->LastGainIndex;
+
+    /* Quantize gains */
+    silk_gains_quant( psEnc->sCmn.indices.GainsIndices, pGains_Q16,
+            &psShapeSt->LastGainIndex, condCoding == CODE_CONDITIONALLY, psEnc->sCmn.nb_subfr );
+
+    /* Overwrite unquantized gains with quantized gains and convert back to Q0 from Q16 */
+    for( k = 0; k < psEnc->sCmn.nb_subfr; k++ ) {
+        psEncCtrl->Gains[ k ] = pGains_Q16[ k ] / 65536.0f;
+    }
+
+    /* Set quantizer offset for voiced signals. Larger offset when LTP coding gain is low or tilt is high (ie low-pass) */
+    if( psEnc->sCmn.indices.signalType == TYPE_VOICED ) {
+        if( psEncCtrl->LTPredCodGain + psEnc->sCmn.input_tilt_Q15 * ( 1.0f / 32768.0f ) > 1.0f ) {
+            psEnc->sCmn.indices.quantOffsetType = 0;
+        } else {
+            psEnc->sCmn.indices.quantOffsetType = 1;
+        }
+    }
+
+    /* Quantizer boundary adjustment */
+    quant_offset = silk_Quantization_Offsets_Q10[ psEnc->sCmn.indices.signalType >> 1 ][ psEnc->sCmn.indices.quantOffsetType ] / 1024.0f;
+    psEncCtrl->Lambda = LAMBDA_OFFSET
+                      + LAMBDA_DELAYED_DECISIONS * psEnc->sCmn.nStatesDelayedDecision
+                      + LAMBDA_SPEECH_ACT        * psEnc->sCmn.speech_activity_Q8 * ( 1.0f /  256.0f )
+                      + LAMBDA_INPUT_QUALITY     * psEncCtrl->input_quality
+                      + LAMBDA_CODING_QUALITY    * psEncCtrl->coding_quality
+                      + LAMBDA_QUANT_OFFSET      * quant_offset;
+
+    silk_assert( psEncCtrl->Lambda > 0.0f );
+    silk_assert( psEncCtrl->Lambda < 2.0f );
+}
diff --git a/opus/silk/float/regularize_correlations_FLP.c b/opus/silk/float/regularize_correlations_FLP.c
new file mode 100644 (file)
index 0000000..df46126
--- /dev/null
@@ -0,0 +1,48 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+/* Add noise to matrix diagonal */
+void silk_regularize_correlations_FLP(
+    silk_float                      *XX,                                /* I/O  Correlation matrices                        */
+    silk_float                      *xx,                                /* I/O  Correlation values                          */
+    const silk_float                noise,                              /* I    Noise energy to add                         */
+    const opus_int                  D                                   /* I    Dimension of XX                             */
+)
+{
+    opus_int i;
+
+    for( i = 0; i < D; i++ ) {
+        matrix_ptr( &XX[ 0 ], i, i, D ) += noise;
+    }
+    xx[ 0 ] += noise;
+}
diff --git a/opus/silk/float/residual_energy_FLP.c b/opus/silk/float/residual_energy_FLP.c
new file mode 100644 (file)
index 0000000..b2e03a8
--- /dev/null
@@ -0,0 +1,117 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+#define MAX_ITERATIONS_RESIDUAL_NRG         10
+#define REGULARIZATION_FACTOR               1e-8f
+
+/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */
+silk_float silk_residual_energy_covar_FLP(                              /* O    Weighted residual energy                    */
+    const silk_float                *c,                                 /* I    Filter coefficients                         */
+    silk_float                      *wXX,                               /* I/O  Weighted correlation matrix, reg. out       */
+    const silk_float                *wXx,                               /* I    Weighted correlation vector                 */
+    const silk_float                wxx,                                /* I    Weighted correlation value                  */
+    const opus_int                  D                                   /* I    Dimension                                   */
+)
+{
+    opus_int   i, j, k;
+    silk_float tmp, nrg = 0.0f, regularization;
+
+    /* Safety checks */
+    silk_assert( D >= 0 );
+
+    regularization = REGULARIZATION_FACTOR * ( wXX[ 0 ] + wXX[ D * D - 1 ] );
+    for( k = 0; k < MAX_ITERATIONS_RESIDUAL_NRG; k++ ) {
+        nrg = wxx;
+
+        tmp = 0.0f;
+        for( i = 0; i < D; i++ ) {
+            tmp += wXx[ i ] * c[ i ];
+        }
+        nrg -= 2.0f * tmp;
+
+        /* compute c' * wXX * c, assuming wXX is symmetric */
+        for( i = 0; i < D; i++ ) {
+            tmp = 0.0f;
+            for( j = i + 1; j < D; j++ ) {
+                tmp += matrix_c_ptr( wXX, i, j, D ) * c[ j ];
+            }
+            nrg += c[ i ] * ( 2.0f * tmp + matrix_c_ptr( wXX, i, i, D ) * c[ i ] );
+        }
+        if( nrg > 0 ) {
+            break;
+        } else {
+            /* Add white noise */
+            for( i = 0; i < D; i++ ) {
+                matrix_c_ptr( wXX, i, i, D ) +=  regularization;
+            }
+            /* Increase noise for next run */
+            regularization *= 2.0f;
+        }
+    }
+    if( k == MAX_ITERATIONS_RESIDUAL_NRG ) {
+        silk_assert( nrg == 0 );
+        nrg = 1.0f;
+    }
+
+    return nrg;
+}
+
+/* Calculates residual energies of input subframes where all subframes have LPC_order   */
+/* of preceding samples                                                                 */
+void silk_residual_energy_FLP(
+    silk_float                      nrgs[ MAX_NB_SUBFR ],               /* O    Residual energy per subframe                */
+    const silk_float                x[],                                /* I    Input signal                                */
+    silk_float                      a[ 2 ][ MAX_LPC_ORDER ],            /* I    AR coefs for each frame half                */
+    const silk_float                gains[],                            /* I    Quantization gains                          */
+    const opus_int                  subfr_length,                       /* I    Subframe length                             */
+    const opus_int                  nb_subfr,                           /* I    number of subframes                         */
+    const opus_int                  LPC_order                           /* I    LPC order                                   */
+)
+{
+    opus_int     shift;
+    silk_float   *LPC_res_ptr, LPC_res[ ( MAX_FRAME_LENGTH + MAX_NB_SUBFR * MAX_LPC_ORDER ) / 2 ];
+
+    LPC_res_ptr = LPC_res + LPC_order;
+    shift = LPC_order + subfr_length;
+
+    /* Filter input to create the LPC residual for each frame half, and measure subframe energies */
+    silk_LPC_analysis_filter_FLP( LPC_res, a[ 0 ], x + 0 * shift, 2 * shift, LPC_order );
+    nrgs[ 0 ] = ( silk_float )( gains[ 0 ] * gains[ 0 ] * silk_energy_FLP( LPC_res_ptr + 0 * shift, subfr_length ) );
+    nrgs[ 1 ] = ( silk_float )( gains[ 1 ] * gains[ 1 ] * silk_energy_FLP( LPC_res_ptr + 1 * shift, subfr_length ) );
+
+    if( nb_subfr == MAX_NB_SUBFR ) {
+        silk_LPC_analysis_filter_FLP( LPC_res, a[ 1 ], x + 2 * shift, 2 * shift, LPC_order );
+        nrgs[ 2 ] = ( silk_float )( gains[ 2 ] * gains[ 2 ] * silk_energy_FLP( LPC_res_ptr + 0 * shift, subfr_length ) );
+        nrgs[ 3 ] = ( silk_float )( gains[ 3 ] * gains[ 3 ] * silk_energy_FLP( LPC_res_ptr + 1 * shift, subfr_length ) );
+    }
+}
diff --git a/opus/silk/float/scale_copy_vector_FLP.c b/opus/silk/float/scale_copy_vector_FLP.c
new file mode 100644 (file)
index 0000000..20db32b
--- /dev/null
@@ -0,0 +1,57 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* copy and multiply a vector by a constant */
+void silk_scale_copy_vector_FLP(
+    silk_float          *data_out,
+    const silk_float    *data_in,
+    silk_float          gain,
+    opus_int            dataSize
+)
+{
+    opus_int  i, dataSize4;
+
+    /* 4x unrolled loop */
+    dataSize4 = dataSize & 0xFFFC;
+    for( i = 0; i < dataSize4; i += 4 ) {
+        data_out[ i + 0 ] = gain * data_in[ i + 0 ];
+        data_out[ i + 1 ] = gain * data_in[ i + 1 ];
+        data_out[ i + 2 ] = gain * data_in[ i + 2 ];
+        data_out[ i + 3 ] = gain * data_in[ i + 3 ];
+    }
+
+    /* any remaining elements */
+    for( ; i < dataSize; i++ ) {
+        data_out[ i ] = gain * data_in[ i ];
+    }
+}
diff --git a/opus/silk/float/scale_vector_FLP.c b/opus/silk/float/scale_vector_FLP.c
new file mode 100644 (file)
index 0000000..108fdcb
--- /dev/null
@@ -0,0 +1,56 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+/* multiply a vector by a constant */
+void silk_scale_vector_FLP(
+    silk_float          *data1,
+    silk_float          gain,
+    opus_int            dataSize
+)
+{
+    opus_int  i, dataSize4;
+
+    /* 4x unrolled loop */
+    dataSize4 = dataSize & 0xFFFC;
+    for( i = 0; i < dataSize4; i += 4 ) {
+        data1[ i + 0 ] *= gain;
+        data1[ i + 1 ] *= gain;
+        data1[ i + 2 ] *= gain;
+        data1[ i + 3 ] *= gain;
+    }
+
+    /* any remaining elements */
+    for( ; i < dataSize; i++ ) {
+        data1[ i ] *= gain;
+    }
+}
diff --git a/opus/silk/float/schur_FLP.c b/opus/silk/float/schur_FLP.c
new file mode 100644 (file)
index 0000000..c1e0bbb
--- /dev/null
@@ -0,0 +1,70 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FLP.h"
+
+silk_float silk_schur_FLP(                  /* O    returns residual energy                                     */
+    silk_float          refl_coef[],        /* O    reflection coefficients (length order)                      */
+    const silk_float    auto_corr[],        /* I    autocorrelation sequence (length order+1)                   */
+    opus_int            order               /* I    order                                                       */
+)
+{
+    opus_int   k, n;
+    double C[ SILK_MAX_ORDER_LPC + 1 ][ 2 ];
+    double Ctmp1, Ctmp2, rc_tmp;
+
+    silk_assert( order >= 0 && order <= SILK_MAX_ORDER_LPC );
+
+    /* Copy correlations */
+    k = 0;
+    do {
+        C[ k ][ 0 ] = C[ k ][ 1 ] = auto_corr[ k ];
+    } while( ++k <= order );
+
+    for( k = 0; k < order; k++ ) {
+        /* Get reflection coefficient */
+        rc_tmp = -C[ k + 1 ][ 0 ] / silk_max_float( C[ 0 ][ 1 ], 1e-9f );
+
+        /* Save the output */
+        refl_coef[ k ] = (silk_float)rc_tmp;
+
+        /* Update correlations */
+        for( n = 0; n < order - k; n++ ) {
+            Ctmp1 = C[ n + k + 1 ][ 0 ];
+            Ctmp2 = C[ n ][ 1 ];
+            C[ n + k + 1 ][ 0 ] = Ctmp1 + Ctmp2 * rc_tmp;
+            C[ n ][ 1 ]         = Ctmp2 + Ctmp1 * rc_tmp;
+        }
+    }
+
+    /* Return residual energy */
+    return (silk_float)C[ 0 ][ 1 ];
+}
diff --git a/opus/silk/float/sort_FLP.c b/opus/silk/float/sort_FLP.c
new file mode 100644 (file)
index 0000000..f08d759
--- /dev/null
@@ -0,0 +1,83 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* Insertion sort (fast for already almost sorted arrays):  */
+/* Best case:  O(n)   for an already sorted array           */
+/* Worst case: O(n^2) for an inversely sorted array         */
+
+#include "typedef.h"
+#include "SigProc_FLP.h"
+
+void silk_insertion_sort_decreasing_FLP(
+    silk_float          *a,                 /* I/O  Unsorted / Sorted vector                                    */
+    opus_int            *idx,               /* O    Index vector for the sorted elements                        */
+    const opus_int      L,                  /* I    Vector length                                               */
+    const opus_int      K                   /* I    Number of correctly sorted positions                        */
+)
+{
+    silk_float value;
+    opus_int   i, j;
+
+    /* Safety checks */
+    silk_assert( K >  0 );
+    silk_assert( L >  0 );
+    silk_assert( L >= K );
+
+    /* Write start indices in index vector */
+    for( i = 0; i < K; i++ ) {
+        idx[ i ] = i;
+    }
+
+    /* Sort vector elements by value, decreasing order */
+    for( i = 1; i < K; i++ ) {
+        value = a[ i ];
+        for( j = i - 1; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
+            a[ j + 1 ]   = a[ j ];      /* Shift value */
+            idx[ j + 1 ] = idx[ j ];    /* Shift index */
+        }
+        a[ j + 1 ]   = value;   /* Write value */
+        idx[ j + 1 ] = i;       /* Write index */
+    }
+
+    /* If less than L values are asked check the remaining values,      */
+    /* but only spend CPU to ensure that the K first values are correct */
+    for( i = K; i < L; i++ ) {
+        value = a[ i ];
+        if( value > a[ K - 1 ] ) {
+            for( j = K - 2; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
+                a[ j + 1 ]   = a[ j ];      /* Shift value */
+                idx[ j + 1 ] = idx[ j ];    /* Shift index */
+            }
+            a[ j + 1 ]   = value;   /* Write value */
+            idx[ j + 1 ] = i;       /* Write index */
+        }
+    }
+}
diff --git a/opus/silk/float/structs_FLP.h b/opus/silk/float/structs_FLP.h
new file mode 100644 (file)
index 0000000..3150b38
--- /dev/null
@@ -0,0 +1,112 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_STRUCTS_FLP_H
+#define SILK_STRUCTS_FLP_H
+
+#include "typedef.h"
+#include "main.h"
+#include "structs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/********************************/
+/* Noise shaping analysis state */
+/********************************/
+typedef struct {
+    opus_int8                   LastGainIndex;
+    silk_float                  HarmShapeGain_smth;
+    silk_float                  Tilt_smth;
+} silk_shape_state_FLP;
+
+/********************************/
+/* Encoder state FLP            */
+/********************************/
+typedef struct {
+    silk_encoder_state          sCmn;                               /* Common struct, shared with fixed-point code */
+    silk_shape_state_FLP        sShape;                             /* Noise shaping state */
+
+    /* Buffer for find pitch and noise shape analysis */
+    silk_float                  x_buf[ 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ];/* Buffer for find pitch and noise shape analysis */
+    silk_float                  LTPCorr;                            /* Normalized correlation from pitch lag estimator */
+} silk_encoder_state_FLP;
+
+/************************/
+/* Encoder control FLP  */
+/************************/
+typedef struct {
+    /* Prediction and coding parameters */
+    silk_float                  Gains[ MAX_NB_SUBFR ];
+    silk_float                  PredCoef[ 2 ][ MAX_LPC_ORDER ];     /* holds interpolated and final coefficients */
+    silk_float                  LTPCoef[LTP_ORDER * MAX_NB_SUBFR];
+    silk_float                  LTP_scale;
+    opus_int                    pitchL[ MAX_NB_SUBFR ];
+
+    /* Noise shaping parameters */
+    silk_float                  AR[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ];
+    silk_float                  LF_MA_shp[     MAX_NB_SUBFR ];
+    silk_float                  LF_AR_shp[     MAX_NB_SUBFR ];
+    silk_float                  Tilt[          MAX_NB_SUBFR ];
+    silk_float                  HarmShapeGain[ MAX_NB_SUBFR ];
+    silk_float                  Lambda;
+    silk_float                  input_quality;
+    silk_float                  coding_quality;
+
+    /* Measures */
+    silk_float                  predGain;
+    silk_float                  LTPredCodGain;
+    silk_float                  ResNrg[ MAX_NB_SUBFR ];             /* Residual energy per subframe */
+
+    /* Parameters for CBR mode */
+    opus_int32                  GainsUnq_Q16[ MAX_NB_SUBFR ];
+    opus_int8                   lastGainIndexPrev;
+} silk_encoder_control_FLP;
+
+/************************/
+/* Encoder Super Struct */
+/************************/
+typedef struct {
+    silk_encoder_state_FLP      state_Fxx[ ENCODER_NUM_CHANNELS ];
+    stereo_enc_state            sStereo;
+    opus_int32                  nBitsUsedLBRR;
+    opus_int32                  nBitsExceeded;
+    opus_int                    nChannelsAPI;
+    opus_int                    nChannelsInternal;
+    opus_int                    nPrevChannelsInternal;
+    opus_int                    timeSinceSwitchAllowed_ms;
+    opus_int                    allowBandwidthSwitch;
+    opus_int                    prev_decode_only_middle;
+} silk_encoder;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/float/warped_autocorrelation_FLP.c b/opus/silk/float/warped_autocorrelation_FLP.c
new file mode 100644 (file)
index 0000000..542414f
--- /dev/null
@@ -0,0 +1,73 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+/* Autocorrelations for a warped frequency axis */
+void silk_warped_autocorrelation_FLP(
+    silk_float                      *corr,                              /* O    Result [order + 1]                          */
+    const silk_float                *input,                             /* I    Input data to correlate                     */
+    const silk_float                warping,                            /* I    Warping coefficient                         */
+    const opus_int                  length,                             /* I    Length of input                             */
+    const opus_int                  order                               /* I    Correlation order (even)                    */
+)
+{
+    opus_int    n, i;
+    double      tmp1, tmp2;
+    double      state[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
+    double      C[     MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
+
+    /* Order must be even */
+    silk_assert( ( order & 1 ) == 0 );
+
+    /* Loop over samples */
+    for( n = 0; n < length; n++ ) {
+        tmp1 = input[ n ];
+        /* Loop over allpass sections */
+        for( i = 0; i < order; i += 2 ) {
+            /* Output of allpass section */
+            tmp2 = state[ i ] + warping * ( state[ i + 1 ] - tmp1 );
+            state[ i ] = tmp1;
+            C[ i ] += state[ 0 ] * tmp1;
+            /* Output of allpass section */
+            tmp1 = state[ i + 1 ] + warping * ( state[ i + 2 ] - tmp2 );
+            state[ i + 1 ] = tmp2;
+            C[ i + 1 ] += state[ 0 ] * tmp2;
+        }
+        state[ order ] = tmp1;
+        C[ order ] += state[ 0 ] * tmp1;
+    }
+
+    /* Copy correlations in silk_float output format */
+    for( i = 0; i < order + 1; i++ ) {
+        corr[ i ] = ( silk_float )C[ i ];
+    }
+}
diff --git a/opus/silk/float/wrappers_FLP.c b/opus/silk/float/wrappers_FLP.c
new file mode 100644 (file)
index 0000000..ad90b87
--- /dev/null
@@ -0,0 +1,207 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main_FLP.h"
+
+/* Wrappers. Calls flp / fix code */
+
+/* Convert AR filter coefficients to NLSF parameters */
+void silk_A2NLSF_FLP(
+    opus_int16                      *NLSF_Q15,                          /* O    NLSF vector      [ LPC_order ]              */
+    const silk_float                *pAR,                               /* I    LPC coefficients [ LPC_order ]              */
+    const opus_int                  LPC_order                           /* I    LPC order                                   */
+)
+{
+    opus_int   i;
+    opus_int32 a_fix_Q16[ MAX_LPC_ORDER ];
+
+    for( i = 0; i < LPC_order; i++ ) {
+        a_fix_Q16[ i ] = silk_float2int( pAR[ i ] * 65536.0f );
+    }
+
+    silk_A2NLSF( NLSF_Q15, a_fix_Q16, LPC_order );
+}
+
+/* Convert LSF parameters to AR prediction filter coefficients */
+void silk_NLSF2A_FLP(
+    silk_float                      *pAR,                               /* O    LPC coefficients [ LPC_order ]              */
+    const opus_int16                *NLSF_Q15,                          /* I    NLSF vector      [ LPC_order ]              */
+    const opus_int                  LPC_order,                          /* I    LPC order                                   */
+    int                             arch                                /* I    Run-time architecture                       */
+)
+{
+    opus_int   i;
+    opus_int16 a_fix_Q12[ MAX_LPC_ORDER ];
+
+    silk_NLSF2A( a_fix_Q12, NLSF_Q15, LPC_order, arch );
+
+    for( i = 0; i < LPC_order; i++ ) {
+        pAR[ i ] = ( silk_float )a_fix_Q12[ i ] * ( 1.0f / 4096.0f );
+    }
+}
+
+/******************************************/
+/* Floating-point NLSF processing wrapper */
+/******************************************/
+void silk_process_NLSFs_FLP(
+    silk_encoder_state              *psEncC,                            /* I/O  Encoder state                               */
+    silk_float                      PredCoef[ 2 ][ MAX_LPC_ORDER ],     /* O    Prediction coefficients                     */
+    opus_int16                      NLSF_Q15[      MAX_LPC_ORDER ],     /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */
+    const opus_int16                prev_NLSF_Q15[ MAX_LPC_ORDER ]      /* I    Previous Normalized LSFs (0 - (2^15-1))     */
+)
+{
+    opus_int     i, j;
+    opus_int16   PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];
+
+    silk_process_NLSFs( psEncC, PredCoef_Q12, NLSF_Q15, prev_NLSF_Q15);
+
+    for( j = 0; j < 2; j++ ) {
+        for( i = 0; i < psEncC->predictLPCOrder; i++ ) {
+            PredCoef[ j ][ i ] = ( silk_float )PredCoef_Q12[ j ][ i ] * ( 1.0f / 4096.0f );
+        }
+    }
+}
+
+/****************************************/
+/* Floating-point Silk NSQ wrapper      */
+/****************************************/
+void silk_NSQ_wrapper_FLP(
+    silk_encoder_state_FLP          *psEnc,                             /* I/O  Encoder state FLP                           */
+    silk_encoder_control_FLP        *psEncCtrl,                         /* I/O  Encoder control FLP                         */
+    SideInfoIndices                 *psIndices,                         /* I/O  Quantization indices                        */
+    silk_nsq_state                  *psNSQ,                             /* I/O  Noise Shaping Quantzation state             */
+    opus_int8                       pulses[],                           /* O    Quantized pulse signal                      */
+    const silk_float                x[]                                 /* I    Prefiltered input signal                    */
+)
+{
+    opus_int     i, j;
+    opus_int16   x16[ MAX_FRAME_LENGTH ];
+    opus_int32   Gains_Q16[ MAX_NB_SUBFR ];
+    silk_DWORD_ALIGN opus_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];
+    opus_int16   LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ];
+    opus_int     LTP_scale_Q14;
+
+    /* Noise shaping parameters */
+    opus_int16   AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ];
+    opus_int32   LF_shp_Q14[ MAX_NB_SUBFR ];         /* Packs two int16 coefficients per int32 value             */
+    opus_int     Lambda_Q10;
+    opus_int     Tilt_Q14[ MAX_NB_SUBFR ];
+    opus_int     HarmShapeGain_Q14[ MAX_NB_SUBFR ];
+
+    /* Convert control struct to fix control struct */
+    /* Noise shape parameters */
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        for( j = 0; j < psEnc->sCmn.shapingLPCOrder; j++ ) {
+            AR_Q13[ i * MAX_SHAPE_LPC_ORDER + j ] = silk_float2int( psEncCtrl->AR[ i * MAX_SHAPE_LPC_ORDER + j ] * 8192.0f );
+        }
+    }
+
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        LF_shp_Q14[ i ] =   silk_LSHIFT32( silk_float2int( psEncCtrl->LF_AR_shp[ i ]     * 16384.0f ), 16 ) |
+                              (opus_uint16)silk_float2int( psEncCtrl->LF_MA_shp[ i ]     * 16384.0f );
+        Tilt_Q14[ i ]   =        (opus_int)silk_float2int( psEncCtrl->Tilt[ i ]          * 16384.0f );
+        HarmShapeGain_Q14[ i ] = (opus_int)silk_float2int( psEncCtrl->HarmShapeGain[ i ] * 16384.0f );
+    }
+    Lambda_Q10 = ( opus_int )silk_float2int( psEncCtrl->Lambda * 1024.0f );
+
+    /* prediction and coding parameters */
+    for( i = 0; i < psEnc->sCmn.nb_subfr * LTP_ORDER; i++ ) {
+        LTPCoef_Q14[ i ] = (opus_int16)silk_float2int( psEncCtrl->LTPCoef[ i ] * 16384.0f );
+    }
+
+    for( j = 0; j < 2; j++ ) {
+        for( i = 0; i < psEnc->sCmn.predictLPCOrder; i++ ) {
+            PredCoef_Q12[ j ][ i ] = (opus_int16)silk_float2int( psEncCtrl->PredCoef[ j ][ i ] * 4096.0f );
+        }
+    }
+
+    for( i = 0; i < psEnc->sCmn.nb_subfr; i++ ) {
+        Gains_Q16[ i ] = silk_float2int( psEncCtrl->Gains[ i ] * 65536.0f );
+        silk_assert( Gains_Q16[ i ] > 0 );
+    }
+
+    if( psIndices->signalType == TYPE_VOICED ) {
+        LTP_scale_Q14 = silk_LTPScales_table_Q14[ psIndices->LTP_scaleIndex ];
+    } else {
+        LTP_scale_Q14 = 0;
+    }
+
+    /* Convert input to fix */
+    for( i = 0; i < psEnc->sCmn.frame_length; i++ ) {
+        x16[ i ] = silk_float2int( x[ i ] );
+    }
+
+    /* Call NSQ */
+    if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {
+        silk_NSQ_del_dec( &psEnc->sCmn, psNSQ, psIndices, x16, pulses, PredCoef_Q12[ 0 ], LTPCoef_Q14,
+            AR_Q13, HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, psEncCtrl->pitchL, Lambda_Q10, LTP_scale_Q14, psEnc->sCmn.arch );
+    } else {
+        silk_NSQ( &psEnc->sCmn, psNSQ, psIndices, x16, pulses, PredCoef_Q12[ 0 ], LTPCoef_Q14,
+            AR_Q13, HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, psEncCtrl->pitchL, Lambda_Q10, LTP_scale_Q14, psEnc->sCmn.arch );
+    }
+}
+
+/***********************************************/
+/* Floating-point Silk LTP quantiation wrapper */
+/***********************************************/
+void silk_quant_LTP_gains_FLP(
+    silk_float                      B[ MAX_NB_SUBFR * LTP_ORDER ],      /* O    Quantized LTP gains                            */
+    opus_int8                       cbk_index[ MAX_NB_SUBFR ],          /* O    Codebook index                              */
+    opus_int8                       *periodicity_index,                 /* O    Periodicity index                           */
+    opus_int32                      *sum_log_gain_Q7,                   /* I/O  Cumulative max prediction gain  */
+    silk_float                      *pred_gain_dB,                        /* O    LTP prediction gain                            */
+    const silk_float                XX[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ], /* I    Correlation matrix                    */
+    const silk_float                xX[ MAX_NB_SUBFR * LTP_ORDER ],        /* I    Correlation vector                            */
+    const opus_int                    subfr_len,                            /* I    Number of samples per subframe                */
+    const opus_int                    nb_subfr,                           /* I    Number of subframes                            */
+    int                             arch                                /* I    Run-time architecture                       */
+)
+{
+    opus_int   i, pred_gain_dB_Q7;
+    opus_int16 B_Q14[ MAX_NB_SUBFR * LTP_ORDER ];
+    opus_int32 XX_Q17[ MAX_NB_SUBFR * LTP_ORDER * LTP_ORDER ];
+    opus_int32 xX_Q17[ MAX_NB_SUBFR * LTP_ORDER ];
+
+    for( i = 0; i < nb_subfr * LTP_ORDER * LTP_ORDER; i++ ) {
+        XX_Q17[ i ] = (opus_int32)silk_float2int( XX[ i ] * 131072.0f );
+    }
+    for( i = 0; i < nb_subfr * LTP_ORDER; i++ ) {
+        xX_Q17[ i ] = (opus_int32)silk_float2int( xX[ i ] * 131072.0f );
+    }
+
+    silk_quant_LTP_gains( B_Q14, cbk_index, periodicity_index, sum_log_gain_Q7, &pred_gain_dB_Q7, XX_Q17, xX_Q17, subfr_len, nb_subfr, arch );
+
+    for( i = 0; i < nb_subfr * LTP_ORDER; i++ ) {
+        B[ i ] = (silk_float)B_Q14[ i ] * ( 1.0f / 16384.0f );
+    }
+
+    *pred_gain_dB = (silk_float)pred_gain_dB_Q7 * ( 1.0f / 128.0f );
+}
diff --git a/opus/silk/gain_quant.c b/opus/silk/gain_quant.c
new file mode 100644 (file)
index 0000000..ee65245
--- /dev/null
@@ -0,0 +1,142 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+#define OFFSET                  ( ( MIN_QGAIN_DB * 128 ) / 6 + 16 * 128 )
+#define SCALE_Q16               ( ( 65536 * ( N_LEVELS_QGAIN - 1 ) ) / ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) )
+#define INV_SCALE_Q16           ( ( 65536 * ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) ) / ( N_LEVELS_QGAIN - 1 ) )
+
+/* Gain scalar quantization with hysteresis, uniform on log scale */
+void silk_gains_quant(
+    opus_int8                   ind[ MAX_NB_SUBFR ],            /* O    gain indices                                */
+    opus_int32                  gain_Q16[ MAX_NB_SUBFR ],       /* I/O  gains (quantized out)                       */
+    opus_int8                   *prev_ind,                      /* I/O  last index in previous frame                */
+    const opus_int              conditional,                    /* I    first gain is delta coded if 1              */
+    const opus_int              nb_subfr                        /* I    number of subframes                         */
+)
+{
+    opus_int k, double_step_size_threshold;
+
+    for( k = 0; k < nb_subfr; k++ ) {
+        /* Convert to log scale, scale, floor() */
+        ind[ k ] = silk_SMULWB( SCALE_Q16, silk_lin2log( gain_Q16[ k ] ) - OFFSET );
+
+        /* Round towards previous quantized gain (hysteresis) */
+        if( ind[ k ] < *prev_ind ) {
+            ind[ k ]++;
+        }
+        ind[ k ] = silk_LIMIT_int( ind[ k ], 0, N_LEVELS_QGAIN - 1 );
+
+        /* Compute delta indices and limit */
+        if( k == 0 && conditional == 0 ) {
+            /* Full index */
+            ind[ k ] = silk_LIMIT_int( ind[ k ], *prev_ind + MIN_DELTA_GAIN_QUANT, N_LEVELS_QGAIN - 1 );
+            *prev_ind = ind[ k ];
+        } else {
+            /* Delta index */
+            ind[ k ] = ind[ k ] - *prev_ind;
+
+            /* Double the quantization step size for large gain increases, so that the max gain level can be reached */
+            double_step_size_threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
+            if( ind[ k ] > double_step_size_threshold ) {
+                ind[ k ] = double_step_size_threshold + silk_RSHIFT( ind[ k ] - double_step_size_threshold + 1, 1 );
+            }
+
+            ind[ k ] = silk_LIMIT_int( ind[ k ], MIN_DELTA_GAIN_QUANT, MAX_DELTA_GAIN_QUANT );
+
+            /* Accumulate deltas */
+            if( ind[ k ] > double_step_size_threshold ) {
+                *prev_ind += silk_LSHIFT( ind[ k ], 1 ) - double_step_size_threshold;
+                *prev_ind = silk_min_int( *prev_ind, N_LEVELS_QGAIN - 1 );
+            } else {
+                *prev_ind += ind[ k ];
+            }
+
+            /* Shift to make non-negative */
+            ind[ k ] -= MIN_DELTA_GAIN_QUANT;
+        }
+
+        /* Scale and convert to linear scale */
+        gain_Q16[ k ] = silk_log2lin( silk_min_32( silk_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3967 = 31 in Q7 */
+    }
+}
+
+/* Gains scalar dequantization, uniform on log scale */
+void silk_gains_dequant(
+    opus_int32                  gain_Q16[ MAX_NB_SUBFR ],       /* O    quantized gains                             */
+    const opus_int8             ind[ MAX_NB_SUBFR ],            /* I    gain indices                                */
+    opus_int8                   *prev_ind,                      /* I/O  last index in previous frame                */
+    const opus_int              conditional,                    /* I    first gain is delta coded if 1              */
+    const opus_int              nb_subfr                        /* I    number of subframes                          */
+)
+{
+    opus_int   k, ind_tmp, double_step_size_threshold;
+
+    for( k = 0; k < nb_subfr; k++ ) {
+        if( k == 0 && conditional == 0 ) {
+            /* Gain index is not allowed to go down more than 16 steps (~21.8 dB) */
+            *prev_ind = silk_max_int( ind[ k ], *prev_ind - 16 );
+        } else {
+            /* Delta index */
+            ind_tmp = ind[ k ] + MIN_DELTA_GAIN_QUANT;
+
+            /* Accumulate deltas */
+            double_step_size_threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
+            if( ind_tmp > double_step_size_threshold ) {
+                *prev_ind += silk_LSHIFT( ind_tmp, 1 ) - double_step_size_threshold;
+            } else {
+                *prev_ind += ind_tmp;
+            }
+        }
+        *prev_ind = silk_LIMIT_int( *prev_ind, 0, N_LEVELS_QGAIN - 1 );
+
+        /* Scale and convert to linear scale */
+        gain_Q16[ k ] = silk_log2lin( silk_min_32( silk_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3967 = 31 in Q7 */
+    }
+}
+
+/* Compute unique identifier of gain indices vector */
+opus_int32 silk_gains_ID(                                       /* O    returns unique identifier of gains          */
+    const opus_int8             ind[ MAX_NB_SUBFR ],            /* I    gain indices                                */
+    const opus_int              nb_subfr                        /* I    number of subframes                         */
+)
+{
+    opus_int   k;
+    opus_int32 gainsID;
+
+    gainsID = 0;
+    for( k = 0; k < nb_subfr; k++ ) {
+        gainsID = silk_ADD_LSHIFT32( ind[ k ], gainsID, 8 );
+    }
+
+    return gainsID;
+}
diff --git a/opus/silk/init_decoder.c b/opus/silk/init_decoder.c
new file mode 100644 (file)
index 0000000..16c03dc
--- /dev/null
@@ -0,0 +1,57 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/************************/
+/* Init Decoder State   */
+/************************/
+opus_int silk_init_decoder(
+    silk_decoder_state          *psDec                          /* I/O  Decoder state pointer                       */
+)
+{
+    /* Clear the entire encoder state, except anything copied */
+    silk_memset( psDec, 0, sizeof( silk_decoder_state ) );
+
+    /* Used to deactivate LSF interpolation */
+    psDec->first_frame_after_reset = 1;
+    psDec->prev_gain_Q16 = 65536;
+    psDec->arch = opus_select_arch();
+
+    /* Reset CNG state */
+    silk_CNG_Reset( psDec );
+
+    /* Reset PLC state */
+    silk_PLC_Reset( psDec );
+
+    return(0);
+}
+
diff --git a/opus/silk/init_encoder.c b/opus/silk/init_encoder.c
new file mode 100644 (file)
index 0000000..65995c3
--- /dev/null
@@ -0,0 +1,64 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#ifdef FIXED_POINT
+#include "main_FIX.h"
+#else
+#include "main_FLP.h"
+#endif
+#include "tuning_parameters.h"
+#include "cpu_support.h"
+
+/*********************************/
+/* Initialize Silk Encoder state */
+/*********************************/
+opus_int silk_init_encoder(
+    silk_encoder_state_Fxx          *psEnc,                                 /* I/O  Pointer to Silk FIX encoder state                                           */
+    int                              arch                                   /* I    Run-time architecture                                                       */
+)
+{
+    opus_int ret = 0;
+
+    /* Clear the entire encoder state */
+    silk_memset( psEnc, 0, sizeof( silk_encoder_state_Fxx ) );
+
+    psEnc->sCmn.arch = arch;
+
+    psEnc->sCmn.variable_HP_smth1_Q15 = silk_LSHIFT( silk_lin2log( SILK_FIX_CONST( VARIABLE_HP_MIN_CUTOFF_HZ, 16 ) ) - ( 16 << 7 ), 8 );
+    psEnc->sCmn.variable_HP_smth2_Q15 = psEnc->sCmn.variable_HP_smth1_Q15;
+
+    /* Used to deactivate LSF interpolation, pitch prediction */
+    psEnc->sCmn.first_frame_after_reset = 1;
+
+    /* Initialize Silk VAD */
+    ret += silk_VAD_Init( &psEnc->sCmn.sVAD );
+
+    return  ret;
+}
diff --git a/opus/silk/inner_prod_aligned.c b/opus/silk/inner_prod_aligned.c
new file mode 100644 (file)
index 0000000..257ae9e
--- /dev/null
@@ -0,0 +1,47 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+opus_int32 silk_inner_prod_aligned_scale(
+    const opus_int16 *const     inVec1,             /*    I input vector 1                                              */
+    const opus_int16 *const     inVec2,             /*    I input vector 2                                              */
+    const opus_int              scale,              /*    I number of bits to shift                                     */
+    const opus_int              len                 /*    I vector lengths                                              */
+)
+{
+    opus_int   i;
+    opus_int32 sum = 0;
+    for( i = 0; i < len; i++ ) {
+        sum = silk_ADD_RSHIFT32( sum, silk_SMULBB( inVec1[ i ], inVec2[ i ] ), scale );
+    }
+    return sum;
+}
diff --git a/opus/silk/interpolate.c b/opus/silk/interpolate.c
new file mode 100644 (file)
index 0000000..1bd8ca4
--- /dev/null
@@ -0,0 +1,51 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Interpolate two vectors */
+void silk_interpolate(
+    opus_int16                  xi[ MAX_LPC_ORDER ],            /* O    interpolated vector                         */
+    const opus_int16            x0[ MAX_LPC_ORDER ],            /* I    first vector                                */
+    const opus_int16            x1[ MAX_LPC_ORDER ],            /* I    second vector                               */
+    const opus_int              ifact_Q2,                       /* I    interp. factor, weight on 2nd vector        */
+    const opus_int              d                               /* I    number of parameters                        */
+)
+{
+    opus_int i;
+
+    silk_assert( ifact_Q2 >= 0 );
+    silk_assert( ifact_Q2 <= 4 );
+
+    for( i = 0; i < d; i++ ) {
+        xi[ i ] = (opus_int16)silk_ADD_RSHIFT( x0[ i ], silk_SMULBB( x1[ i ] - x0[ i ], ifact_Q2 ), 2 );
+    }
+}
diff --git a/opus/silk/lin2log.c b/opus/silk/lin2log.c
new file mode 100644 (file)
index 0000000..0d5155a
--- /dev/null
@@ -0,0 +1,46 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+/* Approximation of 128 * log2() (very close inverse of silk_log2lin()) */
+/* Convert input to a log scale    */
+opus_int32 silk_lin2log(
+    const opus_int32            inLin               /* I  input in linear scale                                         */
+)
+{
+    opus_int32 lz, frac_Q7;
+
+    silk_CLZ_FRAC( inLin, &lz, &frac_Q7 );
+
+    /* Piece-wise parabolic approximation */
+    return silk_ADD_LSHIFT32( silk_SMLAWB( frac_Q7, silk_MUL( frac_Q7, 128 - frac_Q7 ), 179 ), 31 - lz, 7 );
+}
+
diff --git a/opus/silk/log2lin.c b/opus/silk/log2lin.c
new file mode 100644 (file)
index 0000000..b7c48e4
--- /dev/null
@@ -0,0 +1,58 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Approximation of 2^() (very close inverse of silk_lin2log()) */
+/* Convert input to a linear scale    */
+opus_int32 silk_log2lin(
+    const opus_int32            inLog_Q7            /* I  input on log scale                                            */
+)
+{
+    opus_int32 out, frac_Q7;
+
+    if( inLog_Q7 < 0 ) {
+        return 0;
+    } else if ( inLog_Q7 >= 3967 ) {
+        return silk_int32_MAX;
+    }
+
+    out = silk_LSHIFT( 1, silk_RSHIFT( inLog_Q7, 7 ) );
+    frac_Q7 = inLog_Q7 & 0x7F;
+    if( inLog_Q7 < 2048 ) {
+        /* Piece-wise parabolic approximation */
+        out = silk_ADD_RSHIFT32( out, silk_MUL( out, silk_SMLAWB( frac_Q7, silk_SMULBB( frac_Q7, 128 - frac_Q7 ), -174 ) ), 7 );
+    } else {
+        /* Piece-wise parabolic approximation */
+        out = silk_MLA( out, silk_RSHIFT( out, 7 ), silk_SMLAWB( frac_Q7, silk_SMULBB( frac_Q7, 128 - frac_Q7 ), -174 ) );
+    }
+    return out;
+}
diff --git a/opus/silk/macros.h b/opus/silk/macros.h
new file mode 100644 (file)
index 0000000..3c67b6e
--- /dev/null
@@ -0,0 +1,151 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MACROS_H
+#define SILK_MACROS_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_types.h"
+#include "opus_defines.h"
+#include "arch.h"
+
+/* This is an OPUS_INLINE header file for general platform. */
+
+/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
+#if OPUS_FAST_INT64
+#define silk_SMULWB(a32, b32)            ((opus_int32)(((a32) * (opus_int64)((opus_int16)(b32))) >> 16))
+#else
+#define silk_SMULWB(a32, b32)            ((((a32) >> 16) * (opus_int32)((opus_int16)(b32))) + ((((a32) & 0x0000FFFF) * (opus_int32)((opus_int16)(b32))) >> 16))
+#endif
+
+/* a32 + (b32 * (opus_int32)((opus_int16)(c32))) >> 16 output have to be 32bit int */
+#if OPUS_FAST_INT64
+#define silk_SMLAWB(a32, b32, c32)       ((opus_int32)((a32) + (((b32) * (opus_int64)((opus_int16)(c32))) >> 16)))
+#else
+#define silk_SMLAWB(a32, b32, c32)       ((a32) + ((((b32) >> 16) * (opus_int32)((opus_int16)(c32))) + ((((b32) & 0x0000FFFF) * (opus_int32)((opus_int16)(c32))) >> 16)))
+#endif
+
+/* (a32 * (b32 >> 16)) >> 16 */
+#if OPUS_FAST_INT64
+#define silk_SMULWT(a32, b32)            ((opus_int32)(((a32) * (opus_int64)((b32) >> 16)) >> 16))
+#else
+#define silk_SMULWT(a32, b32)            (((a32) >> 16) * ((b32) >> 16) + ((((a32) & 0x0000FFFF) * ((b32) >> 16)) >> 16))
+#endif
+
+/* a32 + (b32 * (c32 >> 16)) >> 16 */
+#if OPUS_FAST_INT64
+#define silk_SMLAWT(a32, b32, c32)       ((opus_int32)((a32) + (((b32) * ((opus_int64)(c32) >> 16)) >> 16)))
+#else
+#define silk_SMLAWT(a32, b32, c32)       ((a32) + (((b32) >> 16) * ((c32) >> 16)) + ((((b32) & 0x0000FFFF) * ((c32) >> 16)) >> 16))
+#endif
+
+/* (opus_int32)((opus_int16)(a3))) * (opus_int32)((opus_int16)(b32)) output have to be 32bit int */
+#define silk_SMULBB(a32, b32)            ((opus_int32)((opus_int16)(a32)) * (opus_int32)((opus_int16)(b32)))
+
+/* a32 + (opus_int32)((opus_int16)(b32)) * (opus_int32)((opus_int16)(c32)) output have to be 32bit int */
+#define silk_SMLABB(a32, b32, c32)       ((a32) + ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32)))
+
+/* (opus_int32)((opus_int16)(a32)) * (b32 >> 16) */
+#define silk_SMULBT(a32, b32)            ((opus_int32)((opus_int16)(a32)) * ((b32) >> 16))
+
+/* a32 + (opus_int32)((opus_int16)(b32)) * (c32 >> 16) */
+#define silk_SMLABT(a32, b32, c32)       ((a32) + ((opus_int32)((opus_int16)(b32))) * ((c32) >> 16))
+
+/* a64 + (b32 * c32) */
+#define silk_SMLAL(a64, b32, c32)        (silk_ADD64((a64), ((opus_int64)(b32) * (opus_int64)(c32))))
+
+/* (a32 * b32) >> 16 */
+#if OPUS_FAST_INT64
+#define silk_SMULWW(a32, b32)            ((opus_int32)(((opus_int64)(a32) * (b32)) >> 16))
+#else
+#define silk_SMULWW(a32, b32)            silk_MLA(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16))
+#endif
+
+/* a32 + ((b32 * c32) >> 16) */
+#if OPUS_FAST_INT64
+#define silk_SMLAWW(a32, b32, c32)       ((opus_int32)((a32) + (((opus_int64)(b32) * (c32)) >> 16)))
+#else
+#define silk_SMLAWW(a32, b32, c32)       silk_MLA(silk_SMLAWB((a32), (b32), (c32)), (b32), silk_RSHIFT_ROUND((c32), 16))
+#endif
+
+/* add/subtract with output saturated */
+#define silk_ADD_SAT32(a, b)             ((((opus_uint32)(a) + (opus_uint32)(b)) & 0x80000000) == 0 ?                              \
+                                        ((((a) & (b)) & 0x80000000) != 0 ? silk_int32_MIN : (a)+(b)) :   \
+                                        ((((a) | (b)) & 0x80000000) == 0 ? silk_int32_MAX : (a)+(b)) )
+
+#define silk_SUB_SAT32(a, b)             ((((opus_uint32)(a)-(opus_uint32)(b)) & 0x80000000) == 0 ?                                        \
+                                        (( (a) & ((b)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a)-(b)) :    \
+                                        ((((a)^0x80000000) & (b)  & 0x80000000) ? silk_int32_MAX : (a)-(b)) )
+
+#if defined(MIPSr1_ASM)
+#include "mips/macros_mipsr1.h"
+#endif
+
+#include "ecintrin.h"
+#ifndef OVERRIDE_silk_CLZ16
+static OPUS_INLINE opus_int32 silk_CLZ16(opus_int16 in16)
+{
+    return 32 - EC_ILOG(in16<<16|0x8000);
+}
+#endif
+
+#ifndef OVERRIDE_silk_CLZ32
+static OPUS_INLINE opus_int32 silk_CLZ32(opus_int32 in32)
+{
+    return in32 ? 32 - EC_ILOG(in32) : 32;
+}
+#endif
+
+/* Row based */
+#define matrix_ptr(Matrix_base_adr, row, column, N) \
+    (*((Matrix_base_adr) + ((row)*(N)+(column))))
+#define matrix_adr(Matrix_base_adr, row, column, N) \
+      ((Matrix_base_adr) + ((row)*(N)+(column)))
+
+/* Column based */
+#ifndef matrix_c_ptr
+#   define matrix_c_ptr(Matrix_base_adr, row, column, M) \
+    (*((Matrix_base_adr) + ((row)+(M)*(column))))
+#endif
+
+#ifdef OPUS_ARM_INLINE_ASM
+#include "arm/macros_armv4.h"
+#endif
+
+#ifdef OPUS_ARM_INLINE_EDSP
+#include "arm/macros_armv5e.h"
+#endif
+
+#ifdef OPUS_ARM_PRESUME_AARCH64_NEON_INTR
+#include "arm/macros_arm64.h"
+#endif
+
+#endif /* SILK_MACROS_H */
+
diff --git a/opus/silk/main.h b/opus/silk/main.h
new file mode 100644 (file)
index 0000000..1a33eed
--- /dev/null
@@ -0,0 +1,476 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_MAIN_H
+#define SILK_MAIN_H
+
+#include "SigProc_FIX.h"
+#include "define.h"
+#include "structs.h"
+#include "tables.h"
+#include "PLC.h"
+#include "control.h"
+#include "debug.h"
+#include "entenc.h"
+#include "entdec.h"
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+#include "x86/main_sse.h"
+#endif
+
+#if (defined(OPUS_ARM_ASM) || defined(OPUS_ARM_MAY_HAVE_NEON_INTR))
+#include "arm/NSQ_del_dec_arm.h"
+#endif
+
+/* Convert Left/Right stereo signal to adaptive Mid/Side representation */
+void silk_stereo_LR_to_MS(
+    stereo_enc_state            *state,                         /* I/O  State                                       */
+    opus_int16                  x1[],                           /* I/O  Left input signal, becomes mid signal       */
+    opus_int16                  x2[],                           /* I/O  Right input signal, becomes side signal     */
+    opus_int8                   ix[ 2 ][ 3 ],                   /* O    Quantization indices                        */
+    opus_int8                   *mid_only_flag,                 /* O    Flag: only mid signal coded                 */
+    opus_int32                  mid_side_rates_bps[],           /* O    Bitrates for mid and side signals           */
+    opus_int32                  total_rate_bps,                 /* I    Total bitrate                               */
+    opus_int                    prev_speech_act_Q8,             /* I    Speech activity level in previous frame     */
+    opus_int                    toMono,                         /* I    Last frame before a stereo->mono transition */
+    opus_int                    fs_kHz,                         /* I    Sample rate (kHz)                           */
+    opus_int                    frame_length                    /* I    Number of samples                           */
+);
+
+/* Convert adaptive Mid/Side representation to Left/Right stereo signal */
+void silk_stereo_MS_to_LR(
+    stereo_dec_state            *state,                         /* I/O  State                                       */
+    opus_int16                  x1[],                           /* I/O  Left input signal, becomes mid signal       */
+    opus_int16                  x2[],                           /* I/O  Right input signal, becomes side signal     */
+    const opus_int32            pred_Q13[],                     /* I    Predictors                                  */
+    opus_int                    fs_kHz,                         /* I    Samples rate (kHz)                          */
+    opus_int                    frame_length                    /* I    Number of samples                           */
+);
+
+/* Find least-squares prediction gain for one signal based on another and quantize it */
+opus_int32 silk_stereo_find_predictor(                          /* O    Returns predictor in Q13                    */
+    opus_int32                  *ratio_Q14,                     /* O    Ratio of residual and mid energies          */
+    const opus_int16            x[],                            /* I    Basis signal                                */
+    const opus_int16            y[],                            /* I    Target signal                               */
+    opus_int32                  mid_res_amp_Q0[],               /* I/O  Smoothed mid, residual norms                */
+    opus_int                    length,                         /* I    Number of samples                           */
+    opus_int                    smooth_coef_Q16                 /* I    Smoothing coefficient                       */
+);
+
+/* Quantize mid/side predictors */
+void silk_stereo_quant_pred(
+    opus_int32                  pred_Q13[],                     /* I/O  Predictors (out: quantized)                 */
+    opus_int8                   ix[ 2 ][ 3 ]                    /* O    Quantization indices                        */
+);
+
+/* Entropy code the mid/side quantization indices */
+void silk_stereo_encode_pred(
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int8                   ix[ 2 ][ 3 ]                    /* I    Quantization indices                        */
+);
+
+/* Entropy code the mid-only flag */
+void silk_stereo_encode_mid_only(
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int8                   mid_only_flag
+);
+
+/* Decode mid/side predictors */
+void silk_stereo_decode_pred(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int32                  pred_Q13[]                      /* O    Predictors                                  */
+);
+
+/* Decode mid-only flag */
+void silk_stereo_decode_mid_only(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int                    *decode_only_mid                /* O    Flag that only mid channel has been coded   */
+);
+
+/* Encodes signs of excitation */
+void silk_encode_signs(
+    ec_enc                      *psRangeEnc,                        /* I/O  Compressor data structure               */
+    const opus_int8             pulses[],                           /* I    pulse signal                            */
+    opus_int                    length,                             /* I    length of input                         */
+    const opus_int              signalType,                         /* I    Signal type                             */
+    const opus_int              quantOffsetType,                    /* I    Quantization offset type                */
+    const opus_int              sum_pulses[ MAX_NB_SHELL_BLOCKS ]   /* I    Sum of absolute pulses per block        */
+);
+
+/* Decodes signs of excitation */
+void silk_decode_signs(
+    ec_dec                      *psRangeDec,                        /* I/O  Compressor data structure               */
+    opus_int16                  pulses[],                           /* I/O  pulse signal                            */
+    opus_int                    length,                             /* I    length of input                         */
+    const opus_int              signalType,                         /* I    Signal type                             */
+    const opus_int              quantOffsetType,                    /* I    Quantization offset type                */
+    const opus_int              sum_pulses[ MAX_NB_SHELL_BLOCKS ]   /* I    Sum of absolute pulses per block        */
+);
+
+/* Check encoder control struct */
+opus_int check_control_input(
+    silk_EncControlStruct        *encControl                    /* I    Control structure                           */
+);
+
+/* Control internal sampling rate */
+opus_int silk_control_audio_bandwidth(
+    silk_encoder_state          *psEncC,                        /* I/O  Pointer to Silk encoder state               */
+    silk_EncControlStruct       *encControl                     /* I    Control structure                           */
+);
+
+/* Control SNR of redidual quantizer */
+opus_int silk_control_SNR(
+    silk_encoder_state          *psEncC,                        /* I/O  Pointer to Silk encoder state               */
+    opus_int32                  TargetRate_bps                  /* I    Target max bitrate (bps)                    */
+);
+
+/***************/
+/* Shell coder */
+/***************/
+
+/* Encode quantization indices of excitation */
+void silk_encode_pulses(
+    ec_enc                      *psRangeEnc,                    /* I/O  compressor data structure                   */
+    const opus_int              signalType,                     /* I    Signal type                                 */
+    const opus_int              quantOffsetType,                /* I    quantOffsetType                             */
+    opus_int8                   pulses[],                       /* I    quantization indices                        */
+    const opus_int              frame_length                    /* I    Frame length                                */
+);
+
+/* Shell encoder, operates on one shell code frame of 16 pulses */
+void silk_shell_encoder(
+    ec_enc                      *psRangeEnc,                    /* I/O  compressor data structure                   */
+    const opus_int              *pulses0                        /* I    data: nonnegative pulse amplitudes          */
+);
+
+/* Shell decoder, operates on one shell code frame of 16 pulses */
+void silk_shell_decoder(
+    opus_int16                  *pulses0,                       /* O    data: nonnegative pulse amplitudes          */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    const opus_int              pulses4                         /* I    number of pulses per pulse-subframe         */
+);
+
+/* Gain scalar quantization with hysteresis, uniform on log scale */
+void silk_gains_quant(
+    opus_int8                   ind[ MAX_NB_SUBFR ],            /* O    gain indices                                */
+    opus_int32                  gain_Q16[ MAX_NB_SUBFR ],       /* I/O  gains (quantized out)                       */
+    opus_int8                   *prev_ind,                      /* I/O  last index in previous frame                */
+    const opus_int              conditional,                    /* I    first gain is delta coded if 1              */
+    const opus_int              nb_subfr                        /* I    number of subframes                         */
+);
+
+/* Gains scalar dequantization, uniform on log scale */
+void silk_gains_dequant(
+    opus_int32                  gain_Q16[ MAX_NB_SUBFR ],       /* O    quantized gains                             */
+    const opus_int8             ind[ MAX_NB_SUBFR ],            /* I    gain indices                                */
+    opus_int8                   *prev_ind,                      /* I/O  last index in previous frame                */
+    const opus_int              conditional,                    /* I    first gain is delta coded if 1              */
+    const opus_int              nb_subfr                        /* I    number of subframes                          */
+);
+
+/* Compute unique identifier of gain indices vector */
+opus_int32 silk_gains_ID(                                       /* O    returns unique identifier of gains          */
+    const opus_int8             ind[ MAX_NB_SUBFR ],            /* I    gain indices                                */
+    const opus_int              nb_subfr                        /* I    number of subframes                         */
+);
+
+/* Interpolate two vectors */
+void silk_interpolate(
+    opus_int16                  xi[ MAX_LPC_ORDER ],            /* O    interpolated vector                         */
+    const opus_int16            x0[ MAX_LPC_ORDER ],            /* I    first vector                                */
+    const opus_int16            x1[ MAX_LPC_ORDER ],            /* I    second vector                               */
+    const opus_int              ifact_Q2,                       /* I    interp. factor, weight on 2nd vector        */
+    const opus_int              d                               /* I    number of parameters                        */
+);
+
+/* LTP tap quantizer */
+void silk_quant_LTP_gains(
+    opus_int16                  B_Q14[ MAX_NB_SUBFR * LTP_ORDER ],          /* O    Quantized LTP gains             */
+    opus_int8                   cbk_index[ MAX_NB_SUBFR ],                  /* O    Codebook Index                  */
+    opus_int8                   *periodicity_index,                         /* O    Periodicity Index               */
+    opus_int32                  *sum_gain_dB_Q7,                            /* I/O  Cumulative max prediction gain  */
+    opus_int                    *pred_gain_dB_Q7,                           /* O    LTP prediction gain             */
+    const opus_int32            XX_Q17[ MAX_NB_SUBFR*LTP_ORDER*LTP_ORDER ], /* I    Correlation matrix in Q18       */
+    const opus_int32            xX_Q17[ MAX_NB_SUBFR*LTP_ORDER ],           /* I    Correlation vector in Q18       */
+    const opus_int              subfr_len,                                  /* I    Number of samples per subframe  */
+    const opus_int              nb_subfr,                                   /* I    Number of subframes             */
+    int                         arch                                        /* I    Run-time architecture           */
+);
+
+/* Entropy constrained matrix-weighted VQ, for a single input data vector */
+void silk_VQ_WMat_EC_c(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *res_nrg_Q15,                   /* O    best residual energy                        */
+    opus_int32                  *rate_dist_Q8,                  /* O    best total bitrate                          */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int32            *XX_Q17,                        /* I    correlation matrix                          */
+    const opus_int32            *xX_Q17,                        /* I    correlation vector                          */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              subfr_len,                      /* I    number of samples per subframe              */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    const opus_int              L                               /* I    number of vectors in codebook               */
+);
+
+#if !defined(OVERRIDE_silk_VQ_WMat_EC)
+#define silk_VQ_WMat_EC(ind, res_nrg_Q15, rate_dist_Q8, gain_Q7, XX_Q17, xX_Q17, cb_Q7, cb_gain_Q7, cl_Q5, subfr_len, max_gain_Q7, L, arch) \
+    ((void)(arch),silk_VQ_WMat_EC_c(ind, res_nrg_Q15, rate_dist_Q8, gain_Q7, XX_Q17, xX_Q17, cb_Q7, cb_gain_Q7, cl_Q5, subfr_len, max_gain_Q7, L))
+#endif
+
+/************************************/
+/* Noise shaping quantization (NSQ) */
+/************************************/
+
+void silk_NSQ_c(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int16            x16[],                                      /* I    Input                           */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I  Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#if !defined(OVERRIDE_silk_NSQ)
+#define silk_NSQ(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14, AR_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((void)(arch),silk_NSQ_c(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14, AR_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+#endif
+
+/* Noise shaping using delayed decision */
+void silk_NSQ_del_dec_c(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int16            x16[],                                      /* I    Input                           */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I  Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#if !defined(OVERRIDE_silk_NSQ_del_dec)
+#define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14, AR_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((void)(arch),silk_NSQ_del_dec_c(psEncC, NSQ, psIndices, x16, pulses, PredCoef_Q12, LTPCoef_Q14, AR_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+#endif
+
+/************/
+/* Silk VAD */
+/************/
+/* Initialize the Silk VAD */
+opus_int silk_VAD_Init(                                         /* O    Return value, 0 if success                  */
+    silk_VAD_state              *psSilk_VAD                     /* I/O  Pointer to Silk VAD state                   */
+);
+
+/* Get speech activity level in Q8 */
+opus_int silk_VAD_GetSA_Q8_c(                                   /* O    Return value, 0 if success                  */
+    silk_encoder_state          *psEncC,                        /* I/O  Encoder state                               */
+    const opus_int16            pIn[]                           /* I    PCM input                                   */
+);
+
+#if !defined(OVERRIDE_silk_VAD_GetSA_Q8)
+#define silk_VAD_GetSA_Q8(psEnC, pIn, arch) ((void)(arch),silk_VAD_GetSA_Q8_c(psEnC, pIn))
+#endif
+
+/* Low-pass filter with variable cutoff frequency based on  */
+/* piece-wise linear interpolation between elliptic filters */
+/* Start by setting transition_frame_no = 1;                */
+void silk_LP_variable_cutoff(
+    silk_LP_state               *psLP,                          /* I/O  LP filter state                             */
+    opus_int16                  *frame,                         /* I/O  Low-pass filtered output signal             */
+    const opus_int              frame_length                    /* I    Frame length                                */
+);
+
+/******************/
+/* NLSF Quantizer */
+/******************/
+/* Limit, stabilize, convert and quantize NLSFs */
+void silk_process_NLSFs(
+    silk_encoder_state          *psEncC,                            /* I/O  Encoder state                               */
+    opus_int16                  PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ], /* O    Prediction coefficients                     */
+    opus_int16                  pNLSF_Q15[         MAX_LPC_ORDER ], /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */
+    const opus_int16            prev_NLSFq_Q15[    MAX_LPC_ORDER ]  /* I    Previous Normalized LSFs (0 - (2^15-1))     */
+);
+
+opus_int32 silk_NLSF_encode(                                    /* O    Returns RD value in Q25                     */
+          opus_int8             *NLSFIndices,                   /* I    Codebook path vector [ LPC_ORDER + 1 ]      */
+          opus_int16            *pNLSF_Q15,                     /* I/O  Quantized NLSF vector [ LPC_ORDER ]         */
+    const silk_NLSF_CB_struct   *psNLSF_CB,                     /* I    Codebook object                             */
+    const opus_int16            *pW_QW,                         /* I    NLSF weight vector [ LPC_ORDER ]            */
+    const opus_int              NLSF_mu_Q20,                    /* I    Rate weight for the RD optimization         */
+    const opus_int              nSurvivors,                     /* I    Max survivors after first stage             */
+    const opus_int              signalType                      /* I    Signal type: 0/1/2                          */
+);
+
+/* Compute quantization errors for an LPC_order element input vector for a VQ codebook */
+void silk_NLSF_VQ(
+    opus_int32                  err_Q26[],                      /* O    Quantization errors [K]                     */
+    const opus_int16            in_Q15[],                       /* I    Input vectors to be quantized [LPC_order]   */
+    const opus_uint8            pCB_Q8[],                       /* I    Codebook vectors [K*LPC_order]              */
+    const opus_int16            pWght_Q9[],                     /* I    Codebook weights [K*LPC_order]              */
+    const opus_int              K,                              /* I    Number of codebook vectors                  */
+    const opus_int              LPC_order                       /* I    Number of LPCs                              */
+);
+
+/* Delayed-decision quantizer for NLSF residuals */
+opus_int32 silk_NLSF_del_dec_quant(                             /* O    Returns RD value in Q25                     */
+    opus_int8                   indices[],                      /* O    Quantization indices [ order ]              */
+    const opus_int16            x_Q10[],                        /* I    Input [ order ]                             */
+    const opus_int16            w_Q5[],                         /* I    Weights [ order ]                           */
+    const opus_uint8            pred_coef_Q8[],                 /* I    Backward predictor coefs [ order ]          */
+    const opus_int16            ec_ix[],                        /* I    Indices to entropy coding tables [ order ]  */
+    const opus_uint8            ec_rates_Q5[],                  /* I    Rates []                                    */
+    const opus_int              quant_step_size_Q16,            /* I    Quantization step size                      */
+    const opus_int16            inv_quant_step_size_Q6,         /* I    Inverse quantization step size              */
+    const opus_int32            mu_Q20,                         /* I    R/D tradeoff                                */
+    const opus_int16            order                           /* I    Number of input values                      */
+);
+
+/* Unpack predictor values and indices for entropy coding tables */
+void silk_NLSF_unpack(
+          opus_int16            ec_ix[],                        /* O    Indices to entropy tables [ LPC_ORDER ]     */
+          opus_uint8            pred_Q8[],                      /* O    LSF predictor [ LPC_ORDER ]                 */
+    const silk_NLSF_CB_struct   *psNLSF_CB,                     /* I    Codebook object                             */
+    const opus_int              CB1_index                       /* I    Index of vector in first LSF codebook       */
+);
+
+/***********************/
+/* NLSF vector decoder */
+/***********************/
+void silk_NLSF_decode(
+          opus_int16            *pNLSF_Q15,                     /* O    Quantized NLSF vector [ LPC_ORDER ]         */
+          opus_int8             *NLSFIndices,                   /* I    Codebook path vector [ LPC_ORDER + 1 ]      */
+    const silk_NLSF_CB_struct   *psNLSF_CB                      /* I    Codebook object                             */
+);
+
+/****************************************************/
+/* Decoder Functions                                */
+/****************************************************/
+opus_int silk_init_decoder(
+    silk_decoder_state          *psDec                          /* I/O  Decoder state pointer                       */
+);
+
+/* Set decoder sampling rate */
+opus_int silk_decoder_set_fs(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state pointer                       */
+    opus_int                    fs_kHz,                         /* I    Sampling frequency (kHz)                    */
+    opus_int32                  fs_API_Hz                       /* I    API Sampling frequency (Hz)                 */
+);
+
+/****************/
+/* Decode frame */
+/****************/
+opus_int silk_decode_frame(
+    silk_decoder_state          *psDec,                         /* I/O  Pointer to Silk decoder state               */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int16                  pOut[],                         /* O    Pointer to output speech frame              */
+    opus_int32                  *pN,                            /* O    Pointer to size of output frame             */
+    opus_int                    lostFlag,                       /* I    0: no loss, 1 loss, 2 decode fec            */
+    opus_int                    condCoding,                     /* I    The type of conditional coding to use       */
+    int                         arch                            /* I    Run-time architecture                       */
+);
+
+/* Decode indices from bitstream */
+void silk_decode_indices(
+    silk_decoder_state          *psDec,                         /* I/O  State                                       */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int                    FrameIndex,                     /* I    Frame number                                */
+    opus_int                    decode_LBRR,                    /* I    Flag indicating LBRR data is being decoded  */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+);
+
+/* Decode parameters from payload */
+void silk_decode_parameters(
+    silk_decoder_state          *psDec,                         /* I/O  State                                       */
+    silk_decoder_control        *psDecCtrl,                     /* I/O  Decoder control                             */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+);
+
+/* Core decoder. Performs inverse NSQ operation LTP + LPC */
+void silk_decode_core(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state                               */
+    silk_decoder_control        *psDecCtrl,                     /* I    Decoder control                             */
+    opus_int16                  xq[],                           /* O    Decoded speech                              */
+    const opus_int16            pulses[ MAX_FRAME_LENGTH ],     /* I    Pulse signal                                */
+    int                         arch                            /* I    Run-time architecture                       */
+);
+
+/* Decode quantization indices of excitation (Shell coding) */
+void silk_decode_pulses(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int16                  pulses[],                       /* O    Excitation signal                           */
+    const opus_int              signalType,                     /* I    Sigtype                                     */
+    const opus_int              quantOffsetType,                /* I    quantOffsetType                             */
+    const opus_int              frame_length                    /* I    Frame length                                */
+);
+
+/******************/
+/* CNG */
+/******************/
+
+/* Reset CNG */
+void silk_CNG_Reset(
+    silk_decoder_state          *psDec                          /* I/O  Decoder state                               */
+);
+
+/* Updates CNG estimate, and applies the CNG when packet was lost */
+void silk_CNG(
+    silk_decoder_state          *psDec,                         /* I/O  Decoder state                               */
+    silk_decoder_control        *psDecCtrl,                     /* I/O  Decoder control                             */
+    opus_int16                  frame[],                        /* I/O  Signal                                      */
+    opus_int                    length                          /* I    Length of residual                          */
+);
+
+/* Encoding of various parameters */
+void silk_encode_indices(
+    silk_encoder_state          *psEncC,                        /* I/O  Encoder state                               */
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int                    FrameIndex,                     /* I    Frame number                                */
+    opus_int                    encode_LBRR,                    /* I    Flag indicating LBRR data is being encoded  */
+    opus_int                    condCoding                      /* I    The type of conditional coding to use       */
+);
+
+#endif
diff --git a/opus/silk/mips/NSQ_del_dec_mipsr1.h b/opus/silk/mips/NSQ_del_dec_mipsr1.h
new file mode 100644 (file)
index 0000000..cd70713
--- /dev/null
@@ -0,0 +1,410 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 __NSQ_DEL_DEC_MIPSR1_H__
+#define __NSQ_DEL_DEC_MIPSR1_H__
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+#define OVERRIDE_silk_noise_shape_quantizer_del_dec
+static inline void silk_noise_shape_quantizer_del_dec(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay,          /* I                                        */
+    int                 arch                    /* I                                        */
+)
+{
+    opus_int     i, j, k, Winner_ind, RDmin_ind, RDmax_ind, last_smple_idx;
+    opus_int32   Winner_rand_state;
+    opus_int32   LTP_pred_Q14, LPC_pred_Q14, n_AR_Q14, n_LTP_Q14;
+    opus_int32   n_LF_Q14, r_Q10, rr_Q10, rd1_Q10, rd2_Q10, RDmin_Q10, RDmax_Q10;
+    opus_int32   q1_Q0, q1_Q10, q2_Q10, exc_Q14, LPC_exc_Q14, xq_Q14, Gain_Q10;
+    opus_int32   tmp1, tmp2, sLF_AR_shp_Q14;
+    opus_int32   *pred_lag_ptr, *shp_lag_ptr, *psLPC_Q14;
+    NSQ_sample_struct  psSampleState[ MAX_DEL_DEC_STATES ][ 2 ];
+    NSQ_del_dec_struct *psDD;
+    NSQ_sample_struct  *psSS;
+    opus_int16 b_Q14_0, b_Q14_1, b_Q14_2, b_Q14_3, b_Q14_4;
+    opus_int16 a_Q12_0, a_Q12_1, a_Q12_2, a_Q12_3, a_Q12_4, a_Q12_5, a_Q12_6;
+    opus_int16 a_Q12_7, a_Q12_8, a_Q12_9, a_Q12_10, a_Q12_11, a_Q12_12, a_Q12_13;
+    opus_int16 a_Q12_14, a_Q12_15;
+
+    opus_int32 cur, prev, next;
+
+    /*Unused.*/
+    (void)arch;
+
+    //Intialize b_Q14 variables
+    b_Q14_0 = b_Q14[ 0 ];
+    b_Q14_1 = b_Q14[ 1 ];
+    b_Q14_2 = b_Q14[ 2 ];
+    b_Q14_3 = b_Q14[ 3 ];
+    b_Q14_4 = b_Q14[ 4 ];
+
+    //Intialize a_Q12 variables
+    a_Q12_0 = a_Q12[0];
+    a_Q12_1 = a_Q12[1];
+    a_Q12_2 = a_Q12[2];
+    a_Q12_3 = a_Q12[3];
+    a_Q12_4 = a_Q12[4];
+    a_Q12_5 = a_Q12[5];
+    a_Q12_6 = a_Q12[6];
+    a_Q12_7 = a_Q12[7];
+    a_Q12_8 = a_Q12[8];
+    a_Q12_9 = a_Q12[9];
+    a_Q12_10 = a_Q12[10];
+    a_Q12_11 = a_Q12[11];
+    a_Q12_12 = a_Q12[12];
+    a_Q12_13 = a_Q12[13];
+    a_Q12_14 = a_Q12[14];
+    a_Q12_15 = a_Q12[15];
+
+    long long temp64;
+
+    silk_assert( nStatesDelayedDecision > 0 );
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+    for( i = 0; i < length; i++ ) {
+        /* Perform common calculations used in all states */
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            temp64 = __builtin_mips_mult(pred_lag_ptr[ 0 ], b_Q14_0 );
+            temp64 = __builtin_mips_madd( temp64, pred_lag_ptr[ -1 ], b_Q14_1 );
+            temp64 = __builtin_mips_madd( temp64, pred_lag_ptr[ -2 ], b_Q14_2 );
+            temp64 = __builtin_mips_madd( temp64, pred_lag_ptr[ -3 ], b_Q14_3 );
+            temp64 = __builtin_mips_madd( temp64, pred_lag_ptr[ -4 ], b_Q14_4 );
+            temp64 += 32768;
+            LTP_pred_Q14 = __builtin_mips_extr_w(temp64, 16);
+            LTP_pred_Q14 = silk_LSHIFT( LTP_pred_Q14, 1 );                          /* Q13 -> Q14 */
+            pred_lag_ptr++;
+        } else {
+            LTP_pred_Q14 = 0;
+        }
+
+        /* Long-term shaping */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q14 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SUB_LSHIFT32( LTP_pred_Q14, n_LTP_Q14, 2 );            /* Q12 -> Q14 */
+            shp_lag_ptr++;
+        } else {
+            n_LTP_Q14 = 0;
+        }
+
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            /* Delayed decision state */
+            psDD = &psDelDec[ k ];
+
+            /* Sample state */
+            psSS = psSampleState[ k ];
+
+            /* Generate dither */
+            psDD->Seed = silk_RAND( psDD->Seed );
+
+            /* Pointer used in short term prediction and shaping */
+            psLPC_Q14 = &psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 + i ];
+            /* Short-term prediction */
+            silk_assert( predictLPCOrder == 10 || predictLPCOrder == 16 );
+            temp64 = __builtin_mips_mult(psLPC_Q14[  0 ], a_Q12_0 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -1 ], a_Q12_1 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -2 ], a_Q12_2 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -3 ], a_Q12_3 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -4 ], a_Q12_4 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -5 ], a_Q12_5 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -6 ], a_Q12_6 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -7 ], a_Q12_7 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -8 ], a_Q12_8 );
+            temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -9 ], a_Q12_9 );
+            if( predictLPCOrder == 16 ) {
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -10 ], a_Q12_10 );
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -11 ], a_Q12_11 );
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -12 ], a_Q12_12 );
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -13 ], a_Q12_13 );
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -14 ], a_Q12_14 );
+                temp64 = __builtin_mips_madd( temp64, psLPC_Q14[ -15 ], a_Q12_15 );
+            }
+            temp64 += 32768;
+            LPC_pred_Q14 = __builtin_mips_extr_w(temp64, 16);
+
+            LPC_pred_Q14 = silk_LSHIFT( LPC_pred_Q14, 4 );                              /* Q10 -> Q14 */
+
+            /* Noise shape feedback */
+            silk_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */
+            /* Output of lowpass section */
+            tmp2 = silk_SMLAWB( psLPC_Q14[ 0 ], psDD->sAR2_Q14[ 0 ], warping_Q16 );
+            /* Output of allpass section */
+            tmp1 = silk_SMLAWB( psDD->sAR2_Q14[ 0 ], psDD->sAR2_Q14[ 1 ] - tmp2, warping_Q16 );
+            psDD->sAR2_Q14[ 0 ] = tmp2;
+
+            temp64 = __builtin_mips_mult(tmp2, AR_shp_Q13[ 0 ] );
+
+            prev = psDD->sAR2_Q14[ 1 ];
+
+            /* Loop over allpass sections */
+            for( j = 2; j < shapingLPCOrder; j += 2 ) {
+                cur = psDD->sAR2_Q14[ j ];
+                next = psDD->sAR2_Q14[ j+1 ];
+                /* Output of allpass section */
+                tmp2 = silk_SMLAWB( prev, cur - tmp1, warping_Q16 );
+                psDD->sAR2_Q14[ j - 1 ] = tmp1;
+                temp64 = __builtin_mips_madd( temp64, tmp1, AR_shp_Q13[ j - 1 ] );
+                temp64 = __builtin_mips_madd( temp64, tmp2, AR_shp_Q13[ j ] );
+                /* Output of allpass section */
+                tmp1 = silk_SMLAWB( cur, next - tmp2, warping_Q16 );
+                psDD->sAR2_Q14[ j + 0 ] = tmp2;
+                prev = next;
+            }
+            psDD->sAR2_Q14[ shapingLPCOrder - 1 ] = tmp1;
+            temp64 = __builtin_mips_madd( temp64, tmp1, AR_shp_Q13[ shapingLPCOrder - 1 ] );
+            temp64 += 32768;
+            n_AR_Q14 = __builtin_mips_extr_w(temp64, 16);
+            n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 1 );                                      /* Q11 -> Q12 */
+            n_AR_Q14 = silk_SMLAWB( n_AR_Q14, psDD->LF_AR_Q14, Tilt_Q14 );              /* Q12 */
+            n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 2 );                                      /* Q12 -> Q14 */
+
+            n_LF_Q14 = silk_SMULWB( psDD->Shape_Q14[ *smpl_buf_idx ], LF_shp_Q14 );     /* Q12 */
+            n_LF_Q14 = silk_SMLAWT( n_LF_Q14, psDD->LF_AR_Q14, LF_shp_Q14 );            /* Q12 */
+            n_LF_Q14 = silk_LSHIFT( n_LF_Q14, 2 );                                      /* Q12 -> Q14 */
+
+            /* Input minus prediction plus noise feedback                       */
+            /* r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP  */
+            tmp1 = silk_ADD32( n_AR_Q14, n_LF_Q14 );                                    /* Q14 */
+            tmp2 = silk_ADD32( n_LTP_Q14, LPC_pred_Q14 );                               /* Q13 */
+            tmp1 = silk_SUB32( tmp2, tmp1 );                                            /* Q13 */
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 4 );                                        /* Q10 */
+
+            r_Q10 = silk_SUB32( x_Q10[ i ], tmp1 );                                     /* residual error Q10 */
+
+            /* Flip sign depending on dither */
+            if ( psDD->Seed < 0 ) {
+                r_Q10 = -r_Q10;
+            }
+            r_Q10 = silk_LIMIT_32( r_Q10, -(31 << 10), 30 << 10 );
+
+            /* Find two quantization level candidates and measure their rate-distortion */
+            q1_Q10 = silk_SUB32( r_Q10, offset_Q10 );
+            q1_Q0 = silk_RSHIFT( q1_Q10, 10 );
+            if( q1_Q0 > 0 ) {
+                q1_Q10  = silk_SUB32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+            } else if( q1_Q0 == 0 ) {
+                q1_Q10  = offset_Q10;
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+            } else if( q1_Q0 == -1 ) {
+                q2_Q10  = offset_Q10;
+                q1_Q10  = silk_SUB32( q2_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB(  q2_Q10, Lambda_Q10 );
+            } else {            /* q1_Q0 < -1 */
+                q1_Q10  = silk_ADD32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                rd2_Q10 = silk_SMULBB( -q2_Q10, Lambda_Q10 );
+            }
+            rr_Q10  = silk_SUB32( r_Q10, q1_Q10 );
+            rd1_Q10 = silk_RSHIFT( silk_SMLABB( rd1_Q10, rr_Q10, rr_Q10 ), 10 );
+            rr_Q10  = silk_SUB32( r_Q10, q2_Q10 );
+            rd2_Q10 = silk_RSHIFT( silk_SMLABB( rd2_Q10, rr_Q10, rr_Q10 ), 10 );
+
+            if( rd1_Q10 < rd2_Q10 ) {
+                psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                psSS[ 0 ].Q_Q10  = q1_Q10;
+                psSS[ 1 ].Q_Q10  = q2_Q10;
+            } else {
+                psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                psSS[ 0 ].Q_Q10  = q2_Q10;
+                psSS[ 1 ].Q_Q10  = q1_Q10;
+            }
+
+            /* Update states for best quantization */
+
+            /* Quantized excitation */
+            exc_Q14 = silk_LSHIFT32( psSS[ 0 ].Q_Q10, 4 );
+            if ( psDD->Seed < 0 ) {
+                exc_Q14 = -exc_Q14;
+            }
+
+            /* Add predictions */
+            LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+            xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+            /* Update states */
+            sLF_AR_shp_Q14         = silk_SUB32( xq_Q14, n_AR_Q14 );
+            psSS[ 0 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+            psSS[ 0 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+            psSS[ 0 ].LPC_exc_Q14  = LPC_exc_Q14;
+            psSS[ 0 ].xq_Q14       = xq_Q14;
+
+            /* Update states for second best quantization */
+
+            /* Quantized excitation */
+            exc_Q14 = silk_LSHIFT32( psSS[ 1 ].Q_Q10, 4 );
+            if ( psDD->Seed < 0 ) {
+                exc_Q14 = -exc_Q14;
+            }
+
+
+            /* Add predictions */
+            LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+            xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+            /* Update states */
+            sLF_AR_shp_Q14         = silk_SUB32( xq_Q14, n_AR_Q14 );
+            psSS[ 1 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+            psSS[ 1 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+            psSS[ 1 ].LPC_exc_Q14  = LPC_exc_Q14;
+            psSS[ 1 ].xq_Q14       = xq_Q14;
+        }
+
+        *smpl_buf_idx  = ( *smpl_buf_idx - 1 ) % DECISION_DELAY;
+        if( *smpl_buf_idx < 0 ) *smpl_buf_idx += DECISION_DELAY;
+        last_smple_idx = ( *smpl_buf_idx + decisionDelay ) % DECISION_DELAY;
+
+        /* Find winner */
+        RDmin_Q10 = psSampleState[ 0 ][ 0 ].RD_Q10;
+        Winner_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            if( psSampleState[ k ][ 0 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                Winner_ind = k;
+            }
+        }
+
+        /* Increase RD values of expired states */
+        Winner_rand_state = psDelDec[ Winner_ind ].RandState[ last_smple_idx ];
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            if( psDelDec[ k ].RandState[ last_smple_idx ] != Winner_rand_state ) {
+                psSampleState[ k ][ 0 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 0 ].RD_Q10, silk_int32_MAX >> 4 );
+                psSampleState[ k ][ 1 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 1 ].RD_Q10, silk_int32_MAX >> 4 );
+                silk_assert( psSampleState[ k ][ 0 ].RD_Q10 >= 0 );
+            }
+        }
+
+        /* Find worst in first set and best in second set */
+        RDmax_Q10  = psSampleState[ 0 ][ 0 ].RD_Q10;
+        RDmin_Q10  = psSampleState[ 0 ][ 1 ].RD_Q10;
+        RDmax_ind = 0;
+        RDmin_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            /* find worst in first set */
+            if( psSampleState[ k ][ 0 ].RD_Q10 > RDmax_Q10 ) {
+                RDmax_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                RDmax_ind = k;
+            }
+            /* find best in second set */
+            if( psSampleState[ k ][ 1 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 1 ].RD_Q10;
+                RDmin_ind = k;
+            }
+        }
+
+        /* Replace a state if best from second set outperforms worst in first set */
+        if( RDmin_Q10 < RDmax_Q10 ) {
+            silk_memcpy( ( (opus_int32 *)&psDelDec[ RDmax_ind ] ) + i,
+                         ( (opus_int32 *)&psDelDec[ RDmin_ind ] ) + i, sizeof( NSQ_del_dec_struct ) - i * sizeof( opus_int32) );
+            silk_memcpy( &psSampleState[ RDmax_ind ][ 0 ], &psSampleState[ RDmin_ind ][ 1 ], sizeof( NSQ_sample_struct ) );
+        }
+
+        /* Write samples from winner to output and long-term filter states */
+        psDD = &psDelDec[ Winner_ind ];
+        if( subfr > 0 || i >= decisionDelay ) {
+            pulses[  i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+            xq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], delayedGain_Q10[ last_smple_idx ] ), 8 ) );
+            NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay ] = psDD->Shape_Q14[ last_smple_idx ];
+            sLTP_Q15[          NSQ->sLTP_buf_idx     - decisionDelay ] = psDD->Pred_Q15[  last_smple_idx ];
+        }
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Update states */
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            psDD                                     = &psDelDec[ k ];
+            psSS                                     = &psSampleState[ k ][ 0 ];
+            psDD->LF_AR_Q14                          = psSS->LF_AR_Q14;
+            psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH + i ] = psSS->xq_Q14;
+            psDD->Xq_Q14[    *smpl_buf_idx ]         = psSS->xq_Q14;
+            psDD->Q_Q10[     *smpl_buf_idx ]         = psSS->Q_Q10;
+            psDD->Pred_Q15[  *smpl_buf_idx ]         = silk_LSHIFT32( psSS->LPC_exc_Q14, 1 );
+            psDD->Shape_Q14[ *smpl_buf_idx ]         = psSS->sLTP_shp_Q14;
+            psDD->Seed                               = silk_ADD32_ovflw( psDD->Seed, silk_RSHIFT_ROUND( psSS->Q_Q10, 10 ) );
+            psDD->RandState[ *smpl_buf_idx ]         = psDD->Seed;
+            psDD->RD_Q10                             = psSS->RD_Q10;
+        }
+        delayedGain_Q10[     *smpl_buf_idx ]         = Gain_Q10;
+    }
+    /* Update LPC states */
+    for( k = 0; k < nStatesDelayedDecision; k++ ) {
+        psDD = &psDelDec[ k ];
+        silk_memcpy( psDD->sLPC_Q14, &psDD->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+    }
+}
+
+#endif /* __NSQ_DEL_DEC_MIPSR1_H__ */
diff --git a/opus/silk/mips/macros_mipsr1.h b/opus/silk/mips/macros_mipsr1.h
new file mode 100644 (file)
index 0000000..12ed981
--- /dev/null
@@ -0,0 +1,92 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 __SILK_MACROS_MIPSR1_H__
+#define __SILK_MACROS_MIPSR1_H__
+
+#define mips_clz(x) __builtin_clz(x)
+
+#undef silk_SMULWB
+static inline int silk_SMULWB(int a, int b)
+{
+    long long ac;
+    int c;
+
+    ac = __builtin_mips_mult(a, (opus_int32)(opus_int16)b);
+    c = __builtin_mips_extr_w(ac, 16);
+
+    return c;
+}
+
+#undef silk_SMLAWB
+#define silk_SMLAWB(a32, b32, c32)       ((a32) + silk_SMULWB(b32, c32))
+
+#undef silk_SMULWW
+static inline int silk_SMULWW(int a, int b)
+{
+    long long ac;
+    int c;
+
+    ac = __builtin_mips_mult(a, b);
+    c = __builtin_mips_extr_w(ac, 16);
+
+    return c;
+}
+
+#undef silk_SMLAWW
+static inline int silk_SMLAWW(int a, int b, int c)
+{
+    long long ac;
+    int res;
+
+    ac = __builtin_mips_mult(b, c);
+    res = __builtin_mips_extr_w(ac, 16);
+    res += a;
+
+    return res;
+}
+
+#define OVERRIDE_silk_CLZ16
+static inline opus_int32 silk_CLZ16(opus_int16 in16)
+{
+    int re32;
+    opus_int32 in32 = (opus_int32 )in16;
+    re32 = mips_clz(in32);
+    re32-=16;
+    return re32;
+}
+
+#define OVERRIDE_silk_CLZ32
+static inline opus_int32 silk_CLZ32(opus_int32 in32)
+{
+    int re32;
+    re32 = mips_clz(in32);
+    return re32;
+}
+
+#endif /* __SILK_MACROS_MIPSR1_H__ */
diff --git a/opus/silk/mips/sigproc_fix_mipsr1.h b/opus/silk/mips/sigproc_fix_mipsr1.h
new file mode 100644 (file)
index 0000000..51520c0
--- /dev/null
@@ -0,0 +1,60 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_SIGPROC_FIX_MIPSR1_H
+#define SILK_SIGPROC_FIX_MIPSR1_H
+
+#undef silk_SAT16
+static inline short int silk_SAT16(int a)
+{
+    int c;
+    c = __builtin_mips_shll_s_w(a, 16);
+    c = c>>16;
+
+    return c;
+}
+
+#undef silk_LSHIFT_SAT32
+static inline int silk_LSHIFT_SAT32(int a, int shift)
+{
+    int r;
+
+    r = __builtin_mips_shll_s_w(a, shift);
+
+    return r;
+}
+
+#undef silk_RSHIFT_ROUND
+static inline int silk_RSHIFT_ROUND(int a, int shift)
+{
+    int r;
+
+    r = __builtin_mips_shra_r_w(a, shift);
+    return r;
+}
+
+#endif /* SILK_SIGPROC_FIX_MIPSR1_H */
diff --git a/opus/silk/pitch_est_defines.h b/opus/silk/pitch_est_defines.h
new file mode 100644 (file)
index 0000000..e1e4b5d
--- /dev/null
@@ -0,0 +1,88 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_PE_DEFINES_H
+#define SILK_PE_DEFINES_H
+
+#include "SigProc_FIX.h"
+
+/********************************************************/
+/* Definitions for pitch estimator                      */
+/********************************************************/
+
+#define PE_MAX_FS_KHZ               16 /* Maximum sampling frequency used */
+
+#define PE_MAX_NB_SUBFR             4
+#define PE_SUBFR_LENGTH_MS          5   /* 5 ms */
+
+#define PE_LTP_MEM_LENGTH_MS        ( 4 * PE_SUBFR_LENGTH_MS )
+
+#define PE_MAX_FRAME_LENGTH_MS      ( PE_LTP_MEM_LENGTH_MS + PE_MAX_NB_SUBFR * PE_SUBFR_LENGTH_MS )
+#define PE_MAX_FRAME_LENGTH         ( PE_MAX_FRAME_LENGTH_MS * PE_MAX_FS_KHZ )
+#define PE_MAX_FRAME_LENGTH_ST_1    ( PE_MAX_FRAME_LENGTH >> 2 )
+#define PE_MAX_FRAME_LENGTH_ST_2    ( PE_MAX_FRAME_LENGTH >> 1 )
+
+#define PE_MAX_LAG_MS               18           /* 18 ms -> 56 Hz */
+#define PE_MIN_LAG_MS               2            /* 2 ms -> 500 Hz */
+#define PE_MAX_LAG                  ( PE_MAX_LAG_MS * PE_MAX_FS_KHZ )
+#define PE_MIN_LAG                  ( PE_MIN_LAG_MS * PE_MAX_FS_KHZ )
+
+#define PE_D_SRCH_LENGTH            24
+
+#define PE_NB_STAGE3_LAGS           5
+
+#define PE_NB_CBKS_STAGE2           3
+#define PE_NB_CBKS_STAGE2_EXT       11
+
+#define PE_NB_CBKS_STAGE3_MAX       34
+#define PE_NB_CBKS_STAGE3_MID       24
+#define PE_NB_CBKS_STAGE3_MIN       16
+
+#define PE_NB_CBKS_STAGE3_10MS      12
+#define PE_NB_CBKS_STAGE2_10MS      3
+
+#define PE_SHORTLAG_BIAS            0.2f    /* for logarithmic weighting    */
+#define PE_PREVLAG_BIAS             0.2f    /* for logarithmic weighting    */
+#define PE_FLATCONTOUR_BIAS         0.05f
+
+#define SILK_PE_MIN_COMPLEX         0
+#define SILK_PE_MID_COMPLEX         1
+#define SILK_PE_MAX_COMPLEX         2
+
+/* Tables for 20 ms frames */
+extern const opus_int8 silk_CB_lags_stage2[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE2_EXT ];
+extern const opus_int8 silk_CB_lags_stage3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ];
+extern const opus_int8 silk_Lag_range_stage3[ SILK_PE_MAX_COMPLEX + 1 ] [ PE_MAX_NB_SUBFR ][ 2 ];
+extern const opus_int8 silk_nb_cbk_searchs_stage3[ SILK_PE_MAX_COMPLEX + 1 ];
+
+/* Tables for 10 ms frames */
+extern const opus_int8 silk_CB_lags_stage2_10_ms[ PE_MAX_NB_SUBFR >> 1][ 3 ];
+extern const opus_int8 silk_CB_lags_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 12 ];
+extern const opus_int8 silk_Lag_range_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 2 ];
+
+#endif
+
diff --git a/opus/silk/pitch_est_tables.c b/opus/silk/pitch_est_tables.c
new file mode 100644 (file)
index 0000000..81a8bac
--- /dev/null
@@ -0,0 +1,99 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "typedef.h"
+#include "pitch_est_defines.h"
+
+const opus_int8 silk_CB_lags_stage2_10_ms[ PE_MAX_NB_SUBFR >> 1][ PE_NB_CBKS_STAGE2_10MS ] =
+{
+    {0, 1, 0},
+    {0, 0, 1}
+};
+
+const opus_int8 silk_CB_lags_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ PE_NB_CBKS_STAGE3_10MS ] =
+{
+    { 0, 0, 1,-1, 1,-1, 2,-2, 2,-2, 3,-3},
+    { 0, 1, 0, 1,-1, 2,-1, 2,-2, 3,-2, 3}
+};
+
+const opus_int8 silk_Lag_range_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 2 ] =
+{
+    {-3, 7},
+    {-2, 7}
+};
+
+const opus_int8 silk_CB_lags_stage2[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE2_EXT ] =
+{
+    {0, 2,-1,-1,-1, 0, 0, 1, 1, 0, 1},
+    {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0},
+    {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0},
+    {0,-1, 2, 1, 0, 1, 1, 0, 0,-1,-1}
+};
+
+const opus_int8 silk_CB_lags_stage3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ] =
+{
+    {0, 0, 1,-1, 0, 1,-1, 0,-1, 1,-2, 2,-2,-2, 2,-3, 2, 3,-3,-4, 3,-4, 4, 4,-5, 5,-6,-5, 6,-7, 6, 5, 8,-9},
+    {0, 0, 1, 0, 0, 0, 0, 0, 0, 0,-1, 1, 0, 0, 1,-1, 0, 1,-1,-1, 1,-1, 2, 1,-1, 2,-2,-2, 2,-2, 2, 2, 3,-3},
+    {0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1,-1, 1, 0, 0, 2, 1,-1, 2,-1,-1, 2,-1, 2, 2,-1, 3,-2,-2,-2, 3},
+    {0, 1, 0, 0, 1, 0, 1,-1, 2,-1, 2,-1, 2, 3,-2, 3,-2,-2, 4, 4,-3, 5,-3,-4, 6,-4, 6, 5,-5, 8,-6,-5,-7, 9}
+};
+
+const opus_int8 silk_Lag_range_stage3[ SILK_PE_MAX_COMPLEX + 1 ] [ PE_MAX_NB_SUBFR ][ 2 ] =
+{
+    /* Lags to search for low number of stage3 cbks */
+    {
+        {-5,8},
+        {-1,6},
+        {-1,6},
+        {-4,10}
+    },
+    /* Lags to search for middle number of stage3 cbks */
+    {
+        {-6,10},
+        {-2,6},
+        {-1,6},
+        {-5,10}
+    },
+    /* Lags to search for max number of stage3 cbks */
+    {
+        {-9,12},
+        {-3,7},
+        {-2,7},
+        {-7,13}
+    }
+};
+
+const opus_int8 silk_nb_cbk_searchs_stage3[ SILK_PE_MAX_COMPLEX + 1 ] =
+{
+    PE_NB_CBKS_STAGE3_MIN,
+    PE_NB_CBKS_STAGE3_MID,
+    PE_NB_CBKS_STAGE3_MAX
+};
diff --git a/opus/silk/process_NLSFs.c b/opus/silk/process_NLSFs.c
new file mode 100644 (file)
index 0000000..2f10f8d
--- /dev/null
@@ -0,0 +1,107 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Limit, stabilize, convert and quantize NLSFs */
+void silk_process_NLSFs(
+    silk_encoder_state          *psEncC,                            /* I/O  Encoder state                               */
+    opus_int16                  PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ], /* O    Prediction coefficients                     */
+    opus_int16                  pNLSF_Q15[         MAX_LPC_ORDER ], /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */
+    const opus_int16            prev_NLSFq_Q15[    MAX_LPC_ORDER ]  /* I    Previous Normalized LSFs (0 - (2^15-1))     */
+)
+{
+    opus_int     i, doInterpolate;
+    opus_int     NLSF_mu_Q20;
+    opus_int16   i_sqr_Q15;
+    opus_int16   pNLSF0_temp_Q15[ MAX_LPC_ORDER ];
+    opus_int16   pNLSFW_QW[ MAX_LPC_ORDER ];
+    opus_int16   pNLSFW0_temp_QW[ MAX_LPC_ORDER ];
+
+    silk_assert( psEncC->speech_activity_Q8 >=   0 );
+    silk_assert( psEncC->speech_activity_Q8 <= SILK_FIX_CONST( 1.0, 8 ) );
+    silk_assert( psEncC->useInterpolatedNLSFs == 1 || psEncC->indices.NLSFInterpCoef_Q2 == ( 1 << 2 ) );
+
+    /***********************/
+    /* Calculate mu values */
+    /***********************/
+    /* NLSF_mu  = 0.003 - 0.0015 * psEnc->speech_activity; */
+    NLSF_mu_Q20 = silk_SMLAWB( SILK_FIX_CONST( 0.003, 20 ), SILK_FIX_CONST( -0.001, 28 ), psEncC->speech_activity_Q8 );
+    if( psEncC->nb_subfr == 2 ) {
+        /* Multiply by 1.5 for 10 ms packets */
+        NLSF_mu_Q20 = silk_ADD_RSHIFT( NLSF_mu_Q20, NLSF_mu_Q20, 1 );
+    }
+
+    silk_assert( NLSF_mu_Q20 >  0 );
+    silk_assert( NLSF_mu_Q20 <= SILK_FIX_CONST( 0.005, 20 ) );
+
+    /* Calculate NLSF weights */
+    silk_NLSF_VQ_weights_laroia( pNLSFW_QW, pNLSF_Q15, psEncC->predictLPCOrder );
+
+    /* Update NLSF weights for interpolated NLSFs */
+    doInterpolate = ( psEncC->useInterpolatedNLSFs == 1 ) && ( psEncC->indices.NLSFInterpCoef_Q2 < 4 );
+    if( doInterpolate ) {
+        /* Calculate the interpolated NLSF vector for the first half */
+        silk_interpolate( pNLSF0_temp_Q15, prev_NLSFq_Q15, pNLSF_Q15,
+            psEncC->indices.NLSFInterpCoef_Q2, psEncC->predictLPCOrder );
+
+        /* Calculate first half NLSF weights for the interpolated NLSFs */
+        silk_NLSF_VQ_weights_laroia( pNLSFW0_temp_QW, pNLSF0_temp_Q15, psEncC->predictLPCOrder );
+
+        /* Update NLSF weights with contribution from first half */
+        i_sqr_Q15 = silk_LSHIFT( silk_SMULBB( psEncC->indices.NLSFInterpCoef_Q2, psEncC->indices.NLSFInterpCoef_Q2 ), 11 );
+        for( i = 0; i < psEncC->predictLPCOrder; i++ ) {
+            pNLSFW_QW[ i ] = silk_ADD16( silk_RSHIFT( pNLSFW_QW[ i ], 1 ), silk_RSHIFT(
+                  silk_SMULBB( pNLSFW0_temp_QW[ i ], i_sqr_Q15 ), 16) );
+            silk_assert( pNLSFW_QW[ i ] >= 1 );
+        }
+    }
+
+    silk_NLSF_encode( psEncC->indices.NLSFIndices, pNLSF_Q15, psEncC->psNLSF_CB, pNLSFW_QW,
+        NLSF_mu_Q20, psEncC->NLSF_MSVQ_Survivors, psEncC->indices.signalType );
+
+    /* Convert quantized NLSFs back to LPC coefficients */
+    silk_NLSF2A( PredCoef_Q12[ 1 ], pNLSF_Q15, psEncC->predictLPCOrder, psEncC->arch );
+
+    if( doInterpolate ) {
+        /* Calculate the interpolated, quantized LSF vector for the first half */
+        silk_interpolate( pNLSF0_temp_Q15, prev_NLSFq_Q15, pNLSF_Q15,
+            psEncC->indices.NLSFInterpCoef_Q2, psEncC->predictLPCOrder );
+
+        /* Convert back to LPC coefficients */
+        silk_NLSF2A( PredCoef_Q12[ 0 ], pNLSF0_temp_Q15, psEncC->predictLPCOrder, psEncC->arch );
+
+    } else {
+        /* Copy LPC coefficients for first half from second half */
+        silk_assert( psEncC->predictLPCOrder <= MAX_LPC_ORDER );
+        silk_memcpy( PredCoef_Q12[ 0 ], PredCoef_Q12[ 1 ], psEncC->predictLPCOrder * sizeof( opus_int16 ) );
+    }
+}
diff --git a/opus/silk/quant_LTP_gains.c b/opus/silk/quant_LTP_gains.c
new file mode 100644 (file)
index 0000000..d6b8eff
--- /dev/null
@@ -0,0 +1,132 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "tuning_parameters.h"
+
+void silk_quant_LTP_gains(
+    opus_int16                  B_Q14[ MAX_NB_SUBFR * LTP_ORDER ],          /* O    Quantized LTP gains             */
+    opus_int8                   cbk_index[ MAX_NB_SUBFR ],                  /* O    Codebook Index                  */
+    opus_int8                   *periodicity_index,                         /* O    Periodicity Index               */
+    opus_int32                  *sum_log_gain_Q7,                           /* I/O  Cumulative max prediction gain  */
+    opus_int                    *pred_gain_dB_Q7,                           /* O    LTP prediction gain             */
+    const opus_int32            XX_Q17[ MAX_NB_SUBFR*LTP_ORDER*LTP_ORDER ], /* I    Correlation matrix in Q18       */
+    const opus_int32            xX_Q17[ MAX_NB_SUBFR*LTP_ORDER ],           /* I    Correlation vector in Q18       */
+    const opus_int              subfr_len,                                  /* I    Number of samples per subframe  */
+    const opus_int              nb_subfr,                                   /* I    Number of subframes             */
+    int                         arch                                        /* I    Run-time architecture           */
+)
+{
+    opus_int             j, k, cbk_size;
+    opus_int8            temp_idx[ MAX_NB_SUBFR ];
+    const opus_uint8     *cl_ptr_Q5;
+    const opus_int8      *cbk_ptr_Q7;
+    const opus_uint8     *cbk_gain_ptr_Q7;
+    const opus_int32     *XX_Q17_ptr, *xX_Q17_ptr;
+    opus_int32           res_nrg_Q15_subfr, res_nrg_Q15, rate_dist_Q7_subfr, rate_dist_Q7, min_rate_dist_Q7;
+    opus_int32           sum_log_gain_tmp_Q7, best_sum_log_gain_Q7, max_gain_Q7;
+    opus_int             gain_Q7;
+
+    /***************************************************/
+    /* iterate over different codebooks with different */
+    /* rates/distortions, and choose best */
+    /***************************************************/
+    min_rate_dist_Q7 = silk_int32_MAX;
+    best_sum_log_gain_Q7 = 0;
+    for( k = 0; k < 3; k++ ) {
+        /* Safety margin for pitch gain control, to take into account factors
+           such as state rescaling/rewhitening. */
+        opus_int32 gain_safety = SILK_FIX_CONST( 0.4, 7 );
+
+        cl_ptr_Q5  = silk_LTP_gain_BITS_Q5_ptrs[ k ];
+        cbk_ptr_Q7 = silk_LTP_vq_ptrs_Q7[        k ];
+        cbk_gain_ptr_Q7 = silk_LTP_vq_gain_ptrs_Q7[ k ];
+        cbk_size   = silk_LTP_vq_sizes[          k ];
+
+        /* Set up pointers to first subframe */
+        XX_Q17_ptr = XX_Q17;
+        xX_Q17_ptr = xX_Q17;
+
+        res_nrg_Q15 = 0;
+        rate_dist_Q7 = 0;
+        sum_log_gain_tmp_Q7 = *sum_log_gain_Q7;
+        for( j = 0; j < nb_subfr; j++ ) {
+            max_gain_Q7 = silk_log2lin( ( SILK_FIX_CONST( MAX_SUM_LOG_GAIN_DB / 6.0, 7 ) - sum_log_gain_tmp_Q7 )
+                                        + SILK_FIX_CONST( 7, 7 ) ) - gain_safety;
+            silk_VQ_WMat_EC(
+                &temp_idx[ j ],         /* O    index of best codebook vector                           */
+                &res_nrg_Q15_subfr,     /* O    residual energy                                         */
+                &rate_dist_Q7_subfr,    /* O    best weighted quantization error + mu * rate            */
+                &gain_Q7,               /* O    sum of absolute LTP coefficients                        */
+                XX_Q17_ptr,             /* I    correlation matrix                                      */
+                xX_Q17_ptr,             /* I    correlation vector                                      */
+                cbk_ptr_Q7,             /* I    codebook                                                */
+                cbk_gain_ptr_Q7,        /* I    codebook effective gains                                */
+                cl_ptr_Q5,              /* I    code length for each codebook vector                    */
+                subfr_len,              /* I    number of samples per subframe                          */
+                max_gain_Q7,            /* I    maximum sum of absolute LTP coefficients                */
+                cbk_size,               /* I    number of vectors in codebook                           */
+                arch                    /* I    Run-time architecture                                   */
+            );
+
+            res_nrg_Q15  = silk_ADD_POS_SAT32( res_nrg_Q15, res_nrg_Q15_subfr );
+            rate_dist_Q7 = silk_ADD_POS_SAT32( rate_dist_Q7, rate_dist_Q7_subfr );
+            sum_log_gain_tmp_Q7 = silk_max(0, sum_log_gain_tmp_Q7
+                                + silk_lin2log( gain_safety + gain_Q7 ) - SILK_FIX_CONST( 7, 7 ));
+
+            XX_Q17_ptr += LTP_ORDER * LTP_ORDER;
+            xX_Q17_ptr += LTP_ORDER;
+        }
+
+        if( rate_dist_Q7 <= min_rate_dist_Q7 ) {
+            min_rate_dist_Q7 = rate_dist_Q7;
+            *periodicity_index = (opus_int8)k;
+            silk_memcpy( cbk_index, temp_idx, nb_subfr * sizeof( opus_int8 ) );
+            best_sum_log_gain_Q7 = sum_log_gain_tmp_Q7;
+        }
+    }
+
+    cbk_ptr_Q7 = silk_LTP_vq_ptrs_Q7[ *periodicity_index ];
+    for( j = 0; j < nb_subfr; j++ ) {
+        for( k = 0; k < LTP_ORDER; k++ ) {
+            B_Q14[ j * LTP_ORDER + k ] = silk_LSHIFT( cbk_ptr_Q7[ cbk_index[ j ] * LTP_ORDER + k ], 7 );
+        }
+    }
+
+    if( nb_subfr == 2 ) {
+        res_nrg_Q15 = silk_RSHIFT32( res_nrg_Q15, 1 );
+    } else {
+        res_nrg_Q15 = silk_RSHIFT32( res_nrg_Q15, 2 );
+    }
+
+    *sum_log_gain_Q7 = best_sum_log_gain_Q7;
+    *pred_gain_dB_Q7 = (opus_int)silk_SMULBB( -3, silk_lin2log( res_nrg_Q15 ) - ( 15 << 7 ) );
+}
diff --git a/opus/silk/resampler.c b/opus/silk/resampler.c
new file mode 100644 (file)
index 0000000..374fbb3
--- /dev/null
@@ -0,0 +1,215 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*
+ * Matrix of resampling methods used:
+ *                                 Fs_out (kHz)
+ *                        8      12     16     24     48
+ *
+ *               8        C      UF     U      UF     UF
+ *              12        AF     C      UF     U      UF
+ * Fs_in (kHz)  16        D      AF     C      UF     UF
+ *              24        AF     D      AF     C      U
+ *              48        AF     AF     AF     D      C
+ *
+ * C   -> Copy (no resampling)
+ * D   -> Allpass-based 2x downsampling
+ * U   -> Allpass-based 2x upsampling
+ * UF  -> Allpass-based 2x upsampling followed by FIR interpolation
+ * AF  -> AR2 filter followed by FIR interpolation
+ */
+
+#include "resampler_private.h"
+
+/* Tables with delay compensation values to equalize total delay for different modes */
+static const opus_int8 delay_matrix_enc[ 5 ][ 3 ] = {
+/* in  \ out  8  12  16 */
+/*  8 */   {  6,  0,  3 },
+/* 12 */   {  0,  7,  3 },
+/* 16 */   {  0,  1, 10 },
+/* 24 */   {  0,  2,  6 },
+/* 48 */   { 18, 10, 12 }
+};
+
+static const opus_int8 delay_matrix_dec[ 3 ][ 5 ] = {
+/* in  \ out  8  12  16  24  48 */
+/*  8 */   {  4,  0,  2,  0,  0 },
+/* 12 */   {  0,  9,  4,  7,  4 },
+/* 16 */   {  0,  3, 12,  7,  7 }
+};
+
+/* Simple way to make [8000, 12000, 16000, 24000, 48000] to [0, 1, 2, 3, 4] */
+#define rateID(R) ( ( ( ((R)>>12) - ((R)>16000) ) >> ((R)>24000) ) - 1 )
+
+#define USE_silk_resampler_copy                     (0)
+#define USE_silk_resampler_private_up2_HQ_wrapper   (1)
+#define USE_silk_resampler_private_IIR_FIR          (2)
+#define USE_silk_resampler_private_down_FIR         (3)
+
+/* Initialize/reset the resampler state for a given pair of input/output sampling rates */
+opus_int silk_resampler_init(
+    silk_resampler_state_struct *S,                 /* I/O  Resampler state                                             */
+    opus_int32                  Fs_Hz_in,           /* I    Input sampling rate (Hz)                                    */
+    opus_int32                  Fs_Hz_out,          /* I    Output sampling rate (Hz)                                   */
+    opus_int                    forEnc              /* I    If 1: encoder; if 0: decoder                                */
+)
+{
+    opus_int up2x;
+
+    /* Clear state */
+    silk_memset( S, 0, sizeof( silk_resampler_state_struct ) );
+
+    /* Input checking */
+    if( forEnc ) {
+        if( ( Fs_Hz_in  != 8000 && Fs_Hz_in  != 12000 && Fs_Hz_in  != 16000 && Fs_Hz_in  != 24000 && Fs_Hz_in  != 48000 ) ||
+            ( Fs_Hz_out != 8000 && Fs_Hz_out != 12000 && Fs_Hz_out != 16000 ) ) {
+            silk_assert( 0 );
+            return -1;
+        }
+        S->inputDelay = delay_matrix_enc[ rateID( Fs_Hz_in ) ][ rateID( Fs_Hz_out ) ];
+    } else {
+        if( ( Fs_Hz_in  != 8000 && Fs_Hz_in  != 12000 && Fs_Hz_in  != 16000 ) ||
+            ( Fs_Hz_out != 8000 && Fs_Hz_out != 12000 && Fs_Hz_out != 16000 && Fs_Hz_out != 24000 && Fs_Hz_out != 48000 ) ) {
+            silk_assert( 0 );
+            return -1;
+        }
+        S->inputDelay = delay_matrix_dec[ rateID( Fs_Hz_in ) ][ rateID( Fs_Hz_out ) ];
+    }
+
+    S->Fs_in_kHz  = silk_DIV32_16( Fs_Hz_in,  1000 );
+    S->Fs_out_kHz = silk_DIV32_16( Fs_Hz_out, 1000 );
+
+    /* Number of samples processed per batch */
+    S->batchSize = S->Fs_in_kHz * RESAMPLER_MAX_BATCH_SIZE_MS;
+
+    /* Find resampler with the right sampling ratio */
+    up2x = 0;
+    if( Fs_Hz_out > Fs_Hz_in ) {
+        /* Upsample */
+        if( Fs_Hz_out == silk_MUL( Fs_Hz_in, 2 ) ) {                            /* Fs_out : Fs_in = 2 : 1 */
+            /* Special case: directly use 2x upsampler */
+            S->resampler_function = USE_silk_resampler_private_up2_HQ_wrapper;
+        } else {
+            /* Default resampler */
+            S->resampler_function = USE_silk_resampler_private_IIR_FIR;
+            up2x = 1;
+        }
+    } else if ( Fs_Hz_out < Fs_Hz_in ) {
+        /* Downsample */
+         S->resampler_function = USE_silk_resampler_private_down_FIR;
+        if( silk_MUL( Fs_Hz_out, 4 ) == silk_MUL( Fs_Hz_in, 3 ) ) {             /* Fs_out : Fs_in = 3 : 4 */
+            S->FIR_Fracs = 3;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR0;
+            S->Coefs = silk_Resampler_3_4_COEFS;
+        } else if( silk_MUL( Fs_Hz_out, 3 ) == silk_MUL( Fs_Hz_in, 2 ) ) {      /* Fs_out : Fs_in = 2 : 3 */
+            S->FIR_Fracs = 2;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR0;
+            S->Coefs = silk_Resampler_2_3_COEFS;
+        } else if( silk_MUL( Fs_Hz_out, 2 ) == Fs_Hz_in ) {                     /* Fs_out : Fs_in = 1 : 2 */
+            S->FIR_Fracs = 1;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR1;
+            S->Coefs = silk_Resampler_1_2_COEFS;
+        } else if( silk_MUL( Fs_Hz_out, 3 ) == Fs_Hz_in ) {                     /* Fs_out : Fs_in = 1 : 3 */
+            S->FIR_Fracs = 1;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
+            S->Coefs = silk_Resampler_1_3_COEFS;
+        } else if( silk_MUL( Fs_Hz_out, 4 ) == Fs_Hz_in ) {                     /* Fs_out : Fs_in = 1 : 4 */
+            S->FIR_Fracs = 1;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
+            S->Coefs = silk_Resampler_1_4_COEFS;
+        } else if( silk_MUL( Fs_Hz_out, 6 ) == Fs_Hz_in ) {                     /* Fs_out : Fs_in = 1 : 6 */
+            S->FIR_Fracs = 1;
+            S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
+            S->Coefs = silk_Resampler_1_6_COEFS;
+        } else {
+            /* None available */
+            silk_assert( 0 );
+            return -1;
+        }
+    } else {
+        /* Input and output sampling rates are equal: copy */
+        S->resampler_function = USE_silk_resampler_copy;
+    }
+
+    /* Ratio of input/output samples */
+    S->invRatio_Q16 = silk_LSHIFT32( silk_DIV32( silk_LSHIFT32( Fs_Hz_in, 14 + up2x ), Fs_Hz_out ), 2 );
+    /* Make sure the ratio is rounded up */
+    while( silk_SMULWW( S->invRatio_Q16, Fs_Hz_out ) < silk_LSHIFT32( Fs_Hz_in, up2x ) ) {
+        S->invRatio_Q16++;
+    }
+
+    return 0;
+}
+
+/* Resampler: convert from one sampling rate to another */
+/* Input and output sampling rate are at most 48000 Hz  */
+opus_int silk_resampler(
+    silk_resampler_state_struct *S,                 /* I/O  Resampler state                                             */
+    opus_int16                  out[],              /* O    Output signal                                               */
+    const opus_int16            in[],               /* I    Input signal                                                */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+)
+{
+    opus_int nSamples;
+
+    /* Need at least 1 ms of input data */
+    silk_assert( inLen >= S->Fs_in_kHz );
+    /* Delay can't exceed the 1 ms of buffering */
+    silk_assert( S->inputDelay <= S->Fs_in_kHz );
+
+    nSamples = S->Fs_in_kHz - S->inputDelay;
+
+    /* Copy to delay buffer */
+    silk_memcpy( &S->delayBuf[ S->inputDelay ], in, nSamples * sizeof( opus_int16 ) );
+
+    switch( S->resampler_function ) {
+        case USE_silk_resampler_private_up2_HQ_wrapper:
+            silk_resampler_private_up2_HQ_wrapper( S, out, S->delayBuf, S->Fs_in_kHz );
+            silk_resampler_private_up2_HQ_wrapper( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
+            break;
+        case USE_silk_resampler_private_IIR_FIR:
+            silk_resampler_private_IIR_FIR( S, out, S->delayBuf, S->Fs_in_kHz );
+            silk_resampler_private_IIR_FIR( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
+            break;
+        case USE_silk_resampler_private_down_FIR:
+            silk_resampler_private_down_FIR( S, out, S->delayBuf, S->Fs_in_kHz );
+            silk_resampler_private_down_FIR( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
+            break;
+        default:
+            silk_memcpy( out, S->delayBuf, S->Fs_in_kHz * sizeof( opus_int16 ) );
+            silk_memcpy( &out[ S->Fs_out_kHz ], &in[ nSamples ], ( inLen - S->Fs_in_kHz ) * sizeof( opus_int16 ) );
+    }
+
+    /* Copy to delay buffer */
+    silk_memcpy( S->delayBuf, &in[ inLen - S->inputDelay ], S->inputDelay * sizeof( opus_int16 ) );
+
+    return 0;
+}
diff --git a/opus/silk/resampler_down2.c b/opus/silk/resampler_down2.c
new file mode 100644 (file)
index 0000000..cec3634
--- /dev/null
@@ -0,0 +1,74 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_rom.h"
+
+/* Downsample by a factor 2 */
+void silk_resampler_down2(
+    opus_int32                  *S,                 /* I/O  State vector [ 2 ]                                          */
+    opus_int16                  *out,               /* O    Output signal [ floor(len/2) ]                              */
+    const opus_int16            *in,                /* I    Input signal [ len ]                                        */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+)
+{
+    opus_int32 k, len2 = silk_RSHIFT32( inLen, 1 );
+    opus_int32 in32, out32, Y, X;
+
+    silk_assert( silk_resampler_down2_0 > 0 );
+    silk_assert( silk_resampler_down2_1 < 0 );
+
+    /* Internal variables and state are in Q10 format */
+    for( k = 0; k < len2; k++ ) {
+        /* Convert to Q10 */
+        in32 = silk_LSHIFT( (opus_int32)in[ 2 * k ], 10 );
+
+        /* All-pass section for even input sample */
+        Y      = silk_SUB32( in32, S[ 0 ] );
+        X      = silk_SMLAWB( Y, Y, silk_resampler_down2_1 );
+        out32  = silk_ADD32( S[ 0 ], X );
+        S[ 0 ] = silk_ADD32( in32, X );
+
+        /* Convert to Q10 */
+        in32 = silk_LSHIFT( (opus_int32)in[ 2 * k + 1 ], 10 );
+
+        /* All-pass section for odd input sample, and add to output of previous section */
+        Y      = silk_SUB32( in32, S[ 1 ] );
+        X      = silk_SMULWB( Y, silk_resampler_down2_0 );
+        out32  = silk_ADD32( out32, S[ 1 ] );
+        out32  = silk_ADD32( out32, X );
+        S[ 1 ] = silk_ADD32( in32, X );
+
+        /* Add, convert back to int16 and store to output */
+        out[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( out32, 11 ) );
+    }
+}
+
diff --git a/opus/silk/resampler_down2_3.c b/opus/silk/resampler_down2_3.c
new file mode 100644 (file)
index 0000000..4342614
--- /dev/null
@@ -0,0 +1,103 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_private.h"
+#include "stack_alloc.h"
+
+#define ORDER_FIR                   4
+
+/* Downsample by a factor 2/3, low quality */
+void silk_resampler_down2_3(
+    opus_int32                  *S,                 /* I/O  State vector [ 6 ]                                          */
+    opus_int16                  *out,               /* O    Output signal [ floor(2*inLen/3) ]                          */
+    const opus_int16            *in,                /* I    Input signal [ inLen ]                                      */
+    opus_int32                  inLen               /* I    Number of input samples                                     */
+)
+{
+    opus_int32 nSamplesIn, counter, res_Q6;
+    VARDECL( opus_int32, buf );
+    opus_int32 *buf_ptr;
+    SAVE_STACK;
+
+    ALLOC( buf, RESAMPLER_MAX_BATCH_SIZE_IN + ORDER_FIR, opus_int32 );
+
+    /* Copy buffered samples to start of buffer */
+    silk_memcpy( buf, S, ORDER_FIR * sizeof( opus_int32 ) );
+
+    /* Iterate over blocks of frameSizeIn input samples */
+    while( 1 ) {
+        nSamplesIn = silk_min( inLen, RESAMPLER_MAX_BATCH_SIZE_IN );
+
+        /* Second-order AR filter (output in Q8) */
+        silk_resampler_private_AR2( &S[ ORDER_FIR ], &buf[ ORDER_FIR ], in,
+            silk_Resampler_2_3_COEFS_LQ, nSamplesIn );
+
+        /* Interpolate filtered signal */
+        buf_ptr = buf;
+        counter = nSamplesIn;
+        while( counter > 2 ) {
+            /* Inner product */
+            res_Q6 = silk_SMULWB(         buf_ptr[ 0 ], silk_Resampler_2_3_COEFS_LQ[ 2 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 1 ], silk_Resampler_2_3_COEFS_LQ[ 3 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], silk_Resampler_2_3_COEFS_LQ[ 5 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], silk_Resampler_2_3_COEFS_LQ[ 4 ] );
+
+            /* Scale down, saturate and store in output array */
+            *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
+
+            res_Q6 = silk_SMULWB(         buf_ptr[ 1 ], silk_Resampler_2_3_COEFS_LQ[ 4 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], silk_Resampler_2_3_COEFS_LQ[ 5 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], silk_Resampler_2_3_COEFS_LQ[ 3 ] );
+            res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 4 ], silk_Resampler_2_3_COEFS_LQ[ 2 ] );
+
+            /* Scale down, saturate and store in output array */
+            *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
+
+            buf_ptr += 3;
+            counter -= 3;
+        }
+
+        in += nSamplesIn;
+        inLen -= nSamplesIn;
+
+        if( inLen > 0 ) {
+            /* More iterations to do; copy last part of filtered signal to beginning of buffer */
+            silk_memcpy( buf, &buf[ nSamplesIn ], ORDER_FIR * sizeof( opus_int32 ) );
+        } else {
+            break;
+        }
+    }
+
+    /* Copy last part of filtered signal to the state for the next call */
+    silk_memcpy( S, &buf[ nSamplesIn ], ORDER_FIR * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/resampler_private.h b/opus/silk/resampler_private.h
new file mode 100644 (file)
index 0000000..422a7d9
--- /dev/null
@@ -0,0 +1,88 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_RESAMPLER_PRIVATE_H
+#define SILK_RESAMPLER_PRIVATE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_structs.h"
+#include "resampler_rom.h"
+
+/* Number of input samples to process in the inner loop */
+#define RESAMPLER_MAX_BATCH_SIZE_MS             10
+#define RESAMPLER_MAX_FS_KHZ                    48
+#define RESAMPLER_MAX_BATCH_SIZE_IN             ( RESAMPLER_MAX_BATCH_SIZE_MS * RESAMPLER_MAX_FS_KHZ )
+
+/* Description: Hybrid IIR/FIR polyphase implementation of resampling */
+void silk_resampler_private_IIR_FIR(
+    void                            *SS,            /* I/O  Resampler state             */
+    opus_int16                      out[],          /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    opus_int32                      inLen           /* I    Number of input samples     */
+);
+
+/* Description: Hybrid IIR/FIR polyphase implementation of resampling */
+void silk_resampler_private_down_FIR(
+    void                            *SS,            /* I/O  Resampler state             */
+    opus_int16                      out[],          /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    opus_int32                      inLen           /* I    Number of input samples     */
+);
+
+/* Upsample by a factor 2, high quality */
+void silk_resampler_private_up2_HQ_wrapper(
+    void                            *SS,            /* I/O  Resampler state (unused)    */
+    opus_int16                      *out,           /* O    Output signal [ 2 * len ]   */
+    const opus_int16                *in,            /* I    Input signal [ len ]        */
+    opus_int32                      len             /* I    Number of input samples     */
+);
+
+/* Upsample by a factor 2, high quality */
+void silk_resampler_private_up2_HQ(
+    opus_int32                      *S,             /* I/O  Resampler state [ 6 ]       */
+    opus_int16                      *out,           /* O    Output signal [ 2 * len ]   */
+    const opus_int16                *in,            /* I    Input signal [ len ]        */
+    opus_int32                      len             /* I    Number of input samples     */
+);
+
+/* Second order AR filter */
+void silk_resampler_private_AR2(
+    opus_int32                      S[],            /* I/O  State vector [ 2 ]          */
+    opus_int32                      out_Q8[],       /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    const opus_int16                A_Q14[],        /* I    AR coefficients, Q14        */
+    opus_int32                      len             /* I    Signal length               */
+);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* SILK_RESAMPLER_PRIVATE_H */
diff --git a/opus/silk/resampler_private_AR2.c b/opus/silk/resampler_private_AR2.c
new file mode 100644 (file)
index 0000000..5fff237
--- /dev/null
@@ -0,0 +1,55 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_private.h"
+
+/* Second order AR filter with single delay elements */
+void silk_resampler_private_AR2(
+    opus_int32                      S[],            /* I/O  State vector [ 2 ]          */
+    opus_int32                      out_Q8[],       /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    const opus_int16                A_Q14[],        /* I    AR coefficients, Q14        */
+    opus_int32                      len             /* I    Signal length               */
+)
+{
+    opus_int32    k;
+    opus_int32    out32;
+
+    for( k = 0; k < len; k++ ) {
+        out32       = silk_ADD_LSHIFT32( S[ 0 ], (opus_int32)in[ k ], 8 );
+        out_Q8[ k ] = out32;
+        out32       = silk_LSHIFT( out32, 2 );
+        S[ 0 ]      = silk_SMLAWB( S[ 1 ], out32, A_Q14[ 0 ] );
+        S[ 1 ]      = silk_SMULWB( out32, A_Q14[ 1 ] );
+    }
+}
+
diff --git a/opus/silk/resampler_private_IIR_FIR.c b/opus/silk/resampler_private_IIR_FIR.c
new file mode 100644 (file)
index 0000000..6b2b3a2
--- /dev/null
@@ -0,0 +1,107 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_private.h"
+#include "stack_alloc.h"
+
+static OPUS_INLINE opus_int16 *silk_resampler_private_IIR_FIR_INTERPOL(
+    opus_int16  *out,
+    opus_int16  *buf,
+    opus_int32  max_index_Q16,
+    opus_int32  index_increment_Q16
+)
+{
+    opus_int32 index_Q16, res_Q15;
+    opus_int16 *buf_ptr;
+    opus_int32 table_index;
+
+    /* Interpolate upsampled signal and store in output array */
+    for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
+        table_index = silk_SMULWB( index_Q16 & 0xFFFF, 12 );
+        buf_ptr = &buf[ index_Q16 >> 16 ];
+
+        res_Q15 = silk_SMULBB(          buf_ptr[ 0 ], silk_resampler_frac_FIR_12[      table_index ][ 0 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 1 ], silk_resampler_frac_FIR_12[      table_index ][ 1 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 2 ], silk_resampler_frac_FIR_12[      table_index ][ 2 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 3 ], silk_resampler_frac_FIR_12[      table_index ][ 3 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 4 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 3 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 5 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 2 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 6 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 1 ] );
+        res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 7 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 0 ] );
+        *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q15, 15 ) );
+    }
+    return out;
+}
+/* Upsample using a combination of allpass-based 2x upsampling and FIR interpolation */
+void silk_resampler_private_IIR_FIR(
+    void                            *SS,            /* I/O  Resampler state             */
+    opus_int16                      out[],          /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    opus_int32                      inLen           /* I    Number of input samples     */
+)
+{
+    silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
+    opus_int32 nSamplesIn;
+    opus_int32 max_index_Q16, index_increment_Q16;
+    VARDECL( opus_int16, buf );
+    SAVE_STACK;
+
+    ALLOC( buf, 2 * S->batchSize + RESAMPLER_ORDER_FIR_12, opus_int16 );
+
+    /* Copy buffered samples to start of buffer */
+    silk_memcpy( buf, S->sFIR.i16, RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
+
+    /* Iterate over blocks of frameSizeIn input samples */
+    index_increment_Q16 = S->invRatio_Q16;
+    while( 1 ) {
+        nSamplesIn = silk_min( inLen, S->batchSize );
+
+        /* Upsample 2x */
+        silk_resampler_private_up2_HQ( S->sIIR, &buf[ RESAMPLER_ORDER_FIR_12 ], in, nSamplesIn );
+
+        max_index_Q16 = silk_LSHIFT32( nSamplesIn, 16 + 1 );         /* + 1 because 2x upsampling */
+        out = silk_resampler_private_IIR_FIR_INTERPOL( out, buf, max_index_Q16, index_increment_Q16 );
+        in += nSamplesIn;
+        inLen -= nSamplesIn;
+
+        if( inLen > 0 ) {
+            /* More iterations to do; copy last part of filtered signal to beginning of buffer */
+            silk_memcpy( buf, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
+        } else {
+            break;
+        }
+    }
+
+    /* Copy last part of filtered signal to the state for the next call */
+    silk_memcpy( S->sFIR.i16, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/resampler_private_down_FIR.c b/opus/silk/resampler_private_down_FIR.c
new file mode 100644 (file)
index 0000000..783e42b
--- /dev/null
@@ -0,0 +1,194 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_private.h"
+#include "stack_alloc.h"
+
+static OPUS_INLINE opus_int16 *silk_resampler_private_down_FIR_INTERPOL(
+    opus_int16          *out,
+    opus_int32          *buf,
+    const opus_int16    *FIR_Coefs,
+    opus_int            FIR_Order,
+    opus_int            FIR_Fracs,
+    opus_int32          max_index_Q16,
+    opus_int32          index_increment_Q16
+)
+{
+    opus_int32 index_Q16, res_Q6;
+    opus_int32 *buf_ptr;
+    opus_int32 interpol_ind;
+    const opus_int16 *interpol_ptr;
+
+    switch( FIR_Order ) {
+        case RESAMPLER_DOWN_ORDER_FIR0:
+            for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
+                /* Integer part gives pointer to buffered input */
+                buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
+
+                /* Fractional part gives interpolation coefficients */
+                interpol_ind = silk_SMULWB( index_Q16 & 0xFFFF, FIR_Fracs );
+
+                /* Inner product */
+                interpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR0 / 2 * interpol_ind ];
+                res_Q6 = silk_SMULWB(         buf_ptr[ 0 ], interpol_ptr[ 0 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 1 ], interpol_ptr[ 1 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], interpol_ptr[ 2 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], interpol_ptr[ 3 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 4 ], interpol_ptr[ 4 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 5 ], interpol_ptr[ 5 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 6 ], interpol_ptr[ 6 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 7 ], interpol_ptr[ 7 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 8 ], interpol_ptr[ 8 ] );
+                interpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR0 / 2 * ( FIR_Fracs - 1 - interpol_ind ) ];
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 17 ], interpol_ptr[ 0 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 16 ], interpol_ptr[ 1 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 15 ], interpol_ptr[ 2 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 14 ], interpol_ptr[ 3 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 13 ], interpol_ptr[ 4 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 12 ], interpol_ptr[ 5 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 11 ], interpol_ptr[ 6 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 10 ], interpol_ptr[ 7 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[  9 ], interpol_ptr[ 8 ] );
+
+                /* Scale down, saturate and store in output array */
+                *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
+            }
+            break;
+        case RESAMPLER_DOWN_ORDER_FIR1:
+            for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
+                /* Integer part gives pointer to buffered input */
+                buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
+
+                /* Inner product */
+                res_Q6 = silk_SMULWB(         silk_ADD32( buf_ptr[  0 ], buf_ptr[ 23 ] ), FIR_Coefs[  0 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  1 ], buf_ptr[ 22 ] ), FIR_Coefs[  1 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  2 ], buf_ptr[ 21 ] ), FIR_Coefs[  2 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  3 ], buf_ptr[ 20 ] ), FIR_Coefs[  3 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  4 ], buf_ptr[ 19 ] ), FIR_Coefs[  4 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  5 ], buf_ptr[ 18 ] ), FIR_Coefs[  5 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  6 ], buf_ptr[ 17 ] ), FIR_Coefs[  6 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  7 ], buf_ptr[ 16 ] ), FIR_Coefs[  7 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  8 ], buf_ptr[ 15 ] ), FIR_Coefs[  8 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  9 ], buf_ptr[ 14 ] ), FIR_Coefs[  9 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 10 ], buf_ptr[ 13 ] ), FIR_Coefs[ 10 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 11 ], buf_ptr[ 12 ] ), FIR_Coefs[ 11 ] );
+
+                /* Scale down, saturate and store in output array */
+                *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
+            }
+            break;
+        case RESAMPLER_DOWN_ORDER_FIR2:
+            for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
+                /* Integer part gives pointer to buffered input */
+                buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
+
+                /* Inner product */
+                res_Q6 = silk_SMULWB(         silk_ADD32( buf_ptr[  0 ], buf_ptr[ 35 ] ), FIR_Coefs[  0 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  1 ], buf_ptr[ 34 ] ), FIR_Coefs[  1 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  2 ], buf_ptr[ 33 ] ), FIR_Coefs[  2 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  3 ], buf_ptr[ 32 ] ), FIR_Coefs[  3 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  4 ], buf_ptr[ 31 ] ), FIR_Coefs[  4 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  5 ], buf_ptr[ 30 ] ), FIR_Coefs[  5 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  6 ], buf_ptr[ 29 ] ), FIR_Coefs[  6 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  7 ], buf_ptr[ 28 ] ), FIR_Coefs[  7 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  8 ], buf_ptr[ 27 ] ), FIR_Coefs[  8 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[  9 ], buf_ptr[ 26 ] ), FIR_Coefs[  9 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 10 ], buf_ptr[ 25 ] ), FIR_Coefs[ 10 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 11 ], buf_ptr[ 24 ] ), FIR_Coefs[ 11 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 12 ], buf_ptr[ 23 ] ), FIR_Coefs[ 12 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 13 ], buf_ptr[ 22 ] ), FIR_Coefs[ 13 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 14 ], buf_ptr[ 21 ] ), FIR_Coefs[ 14 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 15 ], buf_ptr[ 20 ] ), FIR_Coefs[ 15 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 16 ], buf_ptr[ 19 ] ), FIR_Coefs[ 16 ] );
+                res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 17 ], buf_ptr[ 18 ] ), FIR_Coefs[ 17 ] );
+
+                /* Scale down, saturate and store in output array */
+                *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
+            }
+            break;
+        default:
+            silk_assert( 0 );
+    }
+    return out;
+}
+
+/* Resample with a 2nd order AR filter followed by FIR interpolation */
+void silk_resampler_private_down_FIR(
+    void                            *SS,            /* I/O  Resampler state             */
+    opus_int16                      out[],          /* O    Output signal               */
+    const opus_int16                in[],           /* I    Input signal                */
+    opus_int32                      inLen           /* I    Number of input samples     */
+)
+{
+    silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
+    opus_int32 nSamplesIn;
+    opus_int32 max_index_Q16, index_increment_Q16;
+    VARDECL( opus_int32, buf );
+    const opus_int16 *FIR_Coefs;
+    SAVE_STACK;
+
+    ALLOC( buf, S->batchSize + S->FIR_Order, opus_int32 );
+
+    /* Copy buffered samples to start of buffer */
+    silk_memcpy( buf, S->sFIR.i32, S->FIR_Order * sizeof( opus_int32 ) );
+
+    FIR_Coefs = &S->Coefs[ 2 ];
+
+    /* Iterate over blocks of frameSizeIn input samples */
+    index_increment_Q16 = S->invRatio_Q16;
+    while( 1 ) {
+        nSamplesIn = silk_min( inLen, S->batchSize );
+
+        /* Second-order AR filter (output in Q8) */
+        silk_resampler_private_AR2( S->sIIR, &buf[ S->FIR_Order ], in, S->Coefs, nSamplesIn );
+
+        max_index_Q16 = silk_LSHIFT32( nSamplesIn, 16 );
+
+        /* Interpolate filtered signal */
+        out = silk_resampler_private_down_FIR_INTERPOL( out, buf, FIR_Coefs, S->FIR_Order,
+            S->FIR_Fracs, max_index_Q16, index_increment_Q16 );
+
+        in += nSamplesIn;
+        inLen -= nSamplesIn;
+
+        if( inLen > 1 ) {
+            /* More iterations to do; copy last part of filtered signal to beginning of buffer */
+            silk_memcpy( buf, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
+        } else {
+            break;
+        }
+    }
+
+    /* Copy last part of filtered signal to the state for the next call */
+    silk_memcpy( S->sFIR.i32, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
diff --git a/opus/silk/resampler_private_up2_HQ.c b/opus/silk/resampler_private_up2_HQ.c
new file mode 100644 (file)
index 0000000..c7ec8de
--- /dev/null
@@ -0,0 +1,113 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+#include "resampler_private.h"
+
+/* Upsample by a factor 2, high quality */
+/* Uses 2nd order allpass filters for the 2x upsampling, followed by a      */
+/* notch filter just above Nyquist.                                         */
+void silk_resampler_private_up2_HQ(
+    opus_int32                      *S,             /* I/O  Resampler state [ 6 ]       */
+    opus_int16                      *out,           /* O    Output signal [ 2 * len ]   */
+    const opus_int16                *in,            /* I    Input signal [ len ]        */
+    opus_int32                      len             /* I    Number of input samples     */
+)
+{
+    opus_int32 k;
+    opus_int32 in32, out32_1, out32_2, Y, X;
+
+    silk_assert( silk_resampler_up2_hq_0[ 0 ] > 0 );
+    silk_assert( silk_resampler_up2_hq_0[ 1 ] > 0 );
+    silk_assert( silk_resampler_up2_hq_0[ 2 ] < 0 );
+    silk_assert( silk_resampler_up2_hq_1[ 0 ] > 0 );
+    silk_assert( silk_resampler_up2_hq_1[ 1 ] > 0 );
+    silk_assert( silk_resampler_up2_hq_1[ 2 ] < 0 );
+
+    /* Internal variables and state are in Q10 format */
+    for( k = 0; k < len; k++ ) {
+        /* Convert to Q10 */
+        in32 = silk_LSHIFT( (opus_int32)in[ k ], 10 );
+
+        /* First all-pass section for even output sample */
+        Y       = silk_SUB32( in32, S[ 0 ] );
+        X       = silk_SMULWB( Y, silk_resampler_up2_hq_0[ 0 ] );
+        out32_1 = silk_ADD32( S[ 0 ], X );
+        S[ 0 ]  = silk_ADD32( in32, X );
+
+        /* Second all-pass section for even output sample */
+        Y       = silk_SUB32( out32_1, S[ 1 ] );
+        X       = silk_SMULWB( Y, silk_resampler_up2_hq_0[ 1 ] );
+        out32_2 = silk_ADD32( S[ 1 ], X );
+        S[ 1 ]  = silk_ADD32( out32_1, X );
+
+        /* Third all-pass section for even output sample */
+        Y       = silk_SUB32( out32_2, S[ 2 ] );
+        X       = silk_SMLAWB( Y, Y, silk_resampler_up2_hq_0[ 2 ] );
+        out32_1 = silk_ADD32( S[ 2 ], X );
+        S[ 2 ]  = silk_ADD32( out32_2, X );
+
+        /* Apply gain in Q15, convert back to int16 and store to output */
+        out[ 2 * k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( out32_1, 10 ) );
+
+        /* First all-pass section for odd output sample */
+        Y       = silk_SUB32( in32, S[ 3 ] );
+        X       = silk_SMULWB( Y, silk_resampler_up2_hq_1[ 0 ] );
+        out32_1 = silk_ADD32( S[ 3 ], X );
+        S[ 3 ]  = silk_ADD32( in32, X );
+
+        /* Second all-pass section for odd output sample */
+        Y       = silk_SUB32( out32_1, S[ 4 ] );
+        X       = silk_SMULWB( Y, silk_resampler_up2_hq_1[ 1 ] );
+        out32_2 = silk_ADD32( S[ 4 ], X );
+        S[ 4 ]  = silk_ADD32( out32_1, X );
+
+        /* Third all-pass section for odd output sample */
+        Y       = silk_SUB32( out32_2, S[ 5 ] );
+        X       = silk_SMLAWB( Y, Y, silk_resampler_up2_hq_1[ 2 ] );
+        out32_1 = silk_ADD32( S[ 5 ], X );
+        S[ 5 ]  = silk_ADD32( out32_2, X );
+
+        /* Apply gain in Q15, convert back to int16 and store to output */
+        out[ 2 * k + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( out32_1, 10 ) );
+    }
+}
+
+void silk_resampler_private_up2_HQ_wrapper(
+    void                            *SS,            /* I/O  Resampler state (unused)    */
+    opus_int16                      *out,           /* O    Output signal [ 2 * len ]   */
+    const opus_int16                *in,            /* I    Input signal [ len ]        */
+    opus_int32                      len             /* I    Number of input samples     */
+)
+{
+    silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
+    silk_resampler_private_up2_HQ( S->sIIR, out, in, len );
+}
diff --git a/opus/silk/resampler_rom.c b/opus/silk/resampler_rom.c
new file mode 100644 (file)
index 0000000..5e6b044
--- /dev/null
@@ -0,0 +1,96 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* Filter coefficients for IIR/FIR polyphase resampling     *
+ * Total size: 179 Words (358 Bytes)                        */
+
+#include "resampler_private.h"
+
+/* Matlab code for the notch filter coefficients: */
+/* B = [1, 0.147, 1];  A = [1, 0.107, 0.89]; G = 0.93; freqz(G * B, A, 2^14, 16e3); axis([0, 8000, -10, 1]) */
+/* fprintf('\t%6d, %6d, %6d, %6d\n', round(B(2)*2^16), round(-A(2)*2^16), round((1-A(3))*2^16), round(G*2^15)) */
+/* const opus_int16 silk_resampler_up2_hq_notch[ 4 ] = { 9634,  -7012,   7209,  30474 }; */
+
+/* Tables with IIR and FIR coefficients for fractional downsamplers (123 Words) */
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ] = {
+    -20694, -13867,
+       -49,     64,     17,   -157,    353,   -496,    163,  11047,  22205,
+       -39,      6,     91,   -170,    186,     23,   -896,   6336,  19928,
+       -19,    -36,    102,    -89,    -24,    328,   -951,   2568,  15909,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ] = {
+    -14457, -14019,
+        64,    128,   -122,     36,    310,   -768,    584,   9267,  17733,
+        12,    128,     18,   -142,    288,   -117,   -865,   4123,  14459,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_2_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR1 / 2 ] = {
+       616, -14323,
+       -10,     39,     58,    -46,    -84,    120,    184,   -315,   -541,   1284,   5380,   9024,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_3_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
+     16102, -15162,
+       -13,      0,     20,     26,      5,    -31,    -43,     -4,     65,     90,      7,   -157,   -248,    -44,    593,   1583,   2612,   3271,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_4_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
+     22500, -15099,
+         3,    -14,    -20,    -15,      2,     25,     37,     25,    -16,    -71,   -107,    -79,     50,    292,    623,    982,   1288,   1464,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_6_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
+     27540, -15257,
+        17,     12,      8,      1,    -10,    -22,    -30,    -32,    -22,      3,     44,    100,    168,    243,    317,    381,    429,    455,
+};
+
+silk_DWORD_ALIGN const opus_int16 silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ] = {
+     -2797,  -6507,
+      4697,  10739,
+      1567,   8276,
+};
+
+/* Table with interplation fractions of 1/24, 3/24, 5/24, ... , 23/24 : 23/24 (46 Words) */
+silk_DWORD_ALIGN const opus_int16 silk_resampler_frac_FIR_12[ 12 ][ RESAMPLER_ORDER_FIR_12 / 2 ] = {
+    {  189,  -600,   617, 30567 },
+    {  117,  -159, -1070, 29704 },
+    {   52,   221, -2392, 28276 },
+    {   -4,   529, -3350, 26341 },
+    {  -48,   758, -3956, 23973 },
+    {  -80,   905, -4235, 21254 },
+    {  -99,   972, -4222, 18278 },
+    { -107,   967, -3957, 15143 },
+    { -103,   896, -3487, 11950 },
+    {  -91,   773, -2865,  8798 },
+    {  -71,   611, -2143,  5784 },
+    {  -46,   425, -1375,  2996 },
+};
diff --git a/opus/silk/resampler_rom.h b/opus/silk/resampler_rom.h
new file mode 100644 (file)
index 0000000..490b338
--- /dev/null
@@ -0,0 +1,68 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_FIX_RESAMPLER_ROM_H
+#define SILK_FIX_RESAMPLER_ROM_H
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+#include "typedef.h"
+#include "resampler_structs.h"
+
+#define RESAMPLER_DOWN_ORDER_FIR0               18
+#define RESAMPLER_DOWN_ORDER_FIR1               24
+#define RESAMPLER_DOWN_ORDER_FIR2               36
+#define RESAMPLER_ORDER_FIR_12                  8
+
+/* Tables for 2x downsampler */
+static const opus_int16 silk_resampler_down2_0 = 9872;
+static const opus_int16 silk_resampler_down2_1 = 39809 - 65536;
+
+/* Tables for 2x upsampler, high quality */
+static const opus_int16 silk_resampler_up2_hq_0[ 3 ] = { 1746, 14986, 39083 - 65536 };
+static const opus_int16 silk_resampler_up2_hq_1[ 3 ] = { 6854, 25769, 55542 - 65536 };
+
+/* Tables with IIR and FIR coefficients for fractional downsamplers */
+extern const opus_int16 silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ];
+extern const opus_int16 silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ];
+extern const opus_int16 silk_Resampler_1_2_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR1 / 2 ];
+extern const opus_int16 silk_Resampler_1_3_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
+extern const opus_int16 silk_Resampler_1_4_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
+extern const opus_int16 silk_Resampler_1_6_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
+extern const opus_int16 silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ];
+
+/* Table with interplation fractions of 1/24, 3/24, ..., 23/24 */
+extern const opus_int16 silk_resampler_frac_FIR_12[ 12 ][ RESAMPLER_ORDER_FIR_12 / 2 ];
+
+#ifdef  __cplusplus
+}
+#endif
+
+#endif /* SILK_FIX_RESAMPLER_ROM_H */
diff --git a/opus/silk/resampler_structs.h b/opus/silk/resampler_structs.h
new file mode 100644 (file)
index 0000000..9e9457d
--- /dev/null
@@ -0,0 +1,60 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_RESAMPLER_STRUCTS_H
+#define SILK_RESAMPLER_STRUCTS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define SILK_RESAMPLER_MAX_FIR_ORDER                 36
+#define SILK_RESAMPLER_MAX_IIR_ORDER                 6
+
+typedef struct _silk_resampler_state_struct{
+    opus_int32       sIIR[ SILK_RESAMPLER_MAX_IIR_ORDER ]; /* this must be the first element of this struct */
+    union{
+        opus_int32   i32[ SILK_RESAMPLER_MAX_FIR_ORDER ];
+        opus_int16   i16[ SILK_RESAMPLER_MAX_FIR_ORDER ];
+    }                sFIR;
+    opus_int16       delayBuf[ 48 ];
+    opus_int         resampler_function;
+    opus_int         batchSize;
+    opus_int32       invRatio_Q16;
+    opus_int         FIR_Order;
+    opus_int         FIR_Fracs;
+    opus_int         Fs_in_kHz;
+    opus_int         Fs_out_kHz;
+    opus_int         inputDelay;
+    const opus_int16 *Coefs;
+} silk_resampler_state_struct;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* SILK_RESAMPLER_STRUCTS_H */
+
diff --git a/opus/silk/shell_coder.c b/opus/silk/shell_coder.c
new file mode 100644 (file)
index 0000000..4af3414
--- /dev/null
@@ -0,0 +1,151 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* shell coder; pulse-subframe length is hardcoded */
+
+static OPUS_INLINE void combine_pulses(
+    opus_int         *out,   /* O    combined pulses vector [len] */
+    const opus_int   *in,    /* I    input vector       [2 * len] */
+    const opus_int   len     /* I    number of OUTPUT samples     */
+)
+{
+    opus_int k;
+    for( k = 0; k < len; k++ ) {
+        out[ k ] = in[ 2 * k ] + in[ 2 * k + 1 ];
+    }
+}
+
+static OPUS_INLINE void encode_split(
+    ec_enc                      *psRangeEnc,    /* I/O  compressor data structure                   */
+    const opus_int              p_child1,       /* I    pulse amplitude of first child subframe     */
+    const opus_int              p,              /* I    pulse amplitude of current subframe         */
+    const opus_uint8            *shell_table    /* I    table of shell cdfs                         */
+)
+{
+    if( p > 0 ) {
+        ec_enc_icdf( psRangeEnc, p_child1, &shell_table[ silk_shell_code_table_offsets[ p ] ], 8 );
+    }
+}
+
+static OPUS_INLINE void decode_split(
+    opus_int16                  *p_child1,      /* O    pulse amplitude of first child subframe     */
+    opus_int16                  *p_child2,      /* O    pulse amplitude of second child subframe    */
+    ec_dec                      *psRangeDec,    /* I/O  Compressor data structure                   */
+    const opus_int              p,              /* I    pulse amplitude of current subframe         */
+    const opus_uint8            *shell_table    /* I    table of shell cdfs                         */
+)
+{
+    if( p > 0 ) {
+        p_child1[ 0 ] = ec_dec_icdf( psRangeDec, &shell_table[ silk_shell_code_table_offsets[ p ] ], 8 );
+        p_child2[ 0 ] = p - p_child1[ 0 ];
+    } else {
+        p_child1[ 0 ] = 0;
+        p_child2[ 0 ] = 0;
+    }
+}
+
+/* Shell encoder, operates on one shell code frame of 16 pulses */
+void silk_shell_encoder(
+    ec_enc                      *psRangeEnc,                    /* I/O  compressor data structure                   */
+    const opus_int              *pulses0                        /* I    data: nonnegative pulse amplitudes          */
+)
+{
+    opus_int pulses1[ 8 ], pulses2[ 4 ], pulses3[ 2 ], pulses4[ 1 ];
+
+    /* this function operates on one shell code frame of 16 pulses */
+    silk_assert( SHELL_CODEC_FRAME_LENGTH == 16 );
+
+    /* tree representation per pulse-subframe */
+    combine_pulses( pulses1, pulses0, 8 );
+    combine_pulses( pulses2, pulses1, 4 );
+    combine_pulses( pulses3, pulses2, 2 );
+    combine_pulses( pulses4, pulses3, 1 );
+
+    encode_split( psRangeEnc, pulses3[  0 ], pulses4[ 0 ], silk_shell_code_table3 );
+
+    encode_split( psRangeEnc, pulses2[  0 ], pulses3[ 0 ], silk_shell_code_table2 );
+
+    encode_split( psRangeEnc, pulses1[  0 ], pulses2[ 0 ], silk_shell_code_table1 );
+    encode_split( psRangeEnc, pulses0[  0 ], pulses1[ 0 ], silk_shell_code_table0 );
+    encode_split( psRangeEnc, pulses0[  2 ], pulses1[ 1 ], silk_shell_code_table0 );
+
+    encode_split( psRangeEnc, pulses1[  2 ], pulses2[ 1 ], silk_shell_code_table1 );
+    encode_split( psRangeEnc, pulses0[  4 ], pulses1[ 2 ], silk_shell_code_table0 );
+    encode_split( psRangeEnc, pulses0[  6 ], pulses1[ 3 ], silk_shell_code_table0 );
+
+    encode_split( psRangeEnc, pulses2[  2 ], pulses3[ 1 ], silk_shell_code_table2 );
+
+    encode_split( psRangeEnc, pulses1[  4 ], pulses2[ 2 ], silk_shell_code_table1 );
+    encode_split( psRangeEnc, pulses0[  8 ], pulses1[ 4 ], silk_shell_code_table0 );
+    encode_split( psRangeEnc, pulses0[ 10 ], pulses1[ 5 ], silk_shell_code_table0 );
+
+    encode_split( psRangeEnc, pulses1[  6 ], pulses2[ 3 ], silk_shell_code_table1 );
+    encode_split( psRangeEnc, pulses0[ 12 ], pulses1[ 6 ], silk_shell_code_table0 );
+    encode_split( psRangeEnc, pulses0[ 14 ], pulses1[ 7 ], silk_shell_code_table0 );
+}
+
+
+/* Shell decoder, operates on one shell code frame of 16 pulses */
+void silk_shell_decoder(
+    opus_int16                  *pulses0,                       /* O    data: nonnegative pulse amplitudes          */
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    const opus_int              pulses4                         /* I    number of pulses per pulse-subframe         */
+)
+{
+    opus_int16 pulses3[ 2 ], pulses2[ 4 ], pulses1[ 8 ];
+
+    /* this function operates on one shell code frame of 16 pulses */
+    silk_assert( SHELL_CODEC_FRAME_LENGTH == 16 );
+
+    decode_split( &pulses3[  0 ], &pulses3[  1 ], psRangeDec, pulses4,      silk_shell_code_table3 );
+
+    decode_split( &pulses2[  0 ], &pulses2[  1 ], psRangeDec, pulses3[ 0 ], silk_shell_code_table2 );
+
+    decode_split( &pulses1[  0 ], &pulses1[  1 ], psRangeDec, pulses2[ 0 ], silk_shell_code_table1 );
+    decode_split( &pulses0[  0 ], &pulses0[  1 ], psRangeDec, pulses1[ 0 ], silk_shell_code_table0 );
+    decode_split( &pulses0[  2 ], &pulses0[  3 ], psRangeDec, pulses1[ 1 ], silk_shell_code_table0 );
+
+    decode_split( &pulses1[  2 ], &pulses1[  3 ], psRangeDec, pulses2[ 1 ], silk_shell_code_table1 );
+    decode_split( &pulses0[  4 ], &pulses0[  5 ], psRangeDec, pulses1[ 2 ], silk_shell_code_table0 );
+    decode_split( &pulses0[  6 ], &pulses0[  7 ], psRangeDec, pulses1[ 3 ], silk_shell_code_table0 );
+
+    decode_split( &pulses2[  2 ], &pulses2[  3 ], psRangeDec, pulses3[ 1 ], silk_shell_code_table2 );
+
+    decode_split( &pulses1[  4 ], &pulses1[  5 ], psRangeDec, pulses2[ 2 ], silk_shell_code_table1 );
+    decode_split( &pulses0[  8 ], &pulses0[  9 ], psRangeDec, pulses1[ 4 ], silk_shell_code_table0 );
+    decode_split( &pulses0[ 10 ], &pulses0[ 11 ], psRangeDec, pulses1[ 5 ], silk_shell_code_table0 );
+
+    decode_split( &pulses1[  6 ], &pulses1[  7 ], psRangeDec, pulses2[ 3 ], silk_shell_code_table1 );
+    decode_split( &pulses0[ 12 ], &pulses0[ 13 ], psRangeDec, pulses1[ 6 ], silk_shell_code_table0 );
+    decode_split( &pulses0[ 14 ], &pulses0[ 15 ], psRangeDec, pulses1[ 7 ], silk_shell_code_table0 );
+}
diff --git a/opus/silk/sigm_Q15.c b/opus/silk/sigm_Q15.c
new file mode 100644 (file)
index 0000000..3c507d2
--- /dev/null
@@ -0,0 +1,76 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* Approximate sigmoid function */
+
+#include "SigProc_FIX.h"
+
+/* fprintf(1, '%d, ', round(1024 * ([1 ./ (1 + exp(-(1:5))), 1] - 1 ./ (1 + exp(-(0:5)))))); */
+static const opus_int32 sigm_LUT_slope_Q10[ 6 ] = {
+    237, 153, 73, 30, 12, 7
+};
+/* fprintf(1, '%d, ', round(32767 * 1 ./ (1 + exp(-(0:5))))); */
+static const opus_int32 sigm_LUT_pos_Q15[ 6 ] = {
+    16384, 23955, 28861, 31213, 32178, 32548
+};
+/* fprintf(1, '%d, ', round(32767 * 1 ./ (1 + exp((0:5))))); */
+static const opus_int32 sigm_LUT_neg_Q15[ 6 ] = {
+    16384, 8812, 3906, 1554, 589, 219
+};
+
+opus_int silk_sigm_Q15(
+    opus_int                    in_Q5               /* I                                                                */
+)
+{
+    opus_int ind;
+
+    if( in_Q5 < 0 ) {
+        /* Negative input */
+        in_Q5 = -in_Q5;
+        if( in_Q5 >= 6 * 32 ) {
+            return 0;        /* Clip */
+        } else {
+            /* Linear interpolation of look up table */
+            ind = silk_RSHIFT( in_Q5, 5 );
+            return( sigm_LUT_neg_Q15[ ind ] - silk_SMULBB( sigm_LUT_slope_Q10[ ind ], in_Q5 & 0x1F ) );
+        }
+    } else {
+        /* Positive input */
+        if( in_Q5 >= 6 * 32 ) {
+            return 32767;        /* clip */
+        } else {
+            /* Linear interpolation of look up table */
+            ind = silk_RSHIFT( in_Q5, 5 );
+            return( sigm_LUT_pos_Q15[ ind ] + silk_SMULBB( sigm_LUT_slope_Q10[ ind ], in_Q5 & 0x1F ) );
+        }
+    }
+}
+
diff --git a/opus/silk/sort.c b/opus/silk/sort.c
new file mode 100644 (file)
index 0000000..7187c9e
--- /dev/null
@@ -0,0 +1,154 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* Insertion sort (fast for already almost sorted arrays):   */
+/* Best case:  O(n)   for an already sorted array            */
+/* Worst case: O(n^2) for an inversely sorted array          */
+/*                                                           */
+/* Shell short:    https://en.wikipedia.org/wiki/Shell_sort  */
+
+#include "SigProc_FIX.h"
+
+void silk_insertion_sort_increasing(
+    opus_int32           *a,             /* I/O   Unsorted / Sorted vector               */
+    opus_int             *idx,           /* O     Index vector for the sorted elements   */
+    const opus_int       L,              /* I     Vector length                          */
+    const opus_int       K               /* I     Number of correctly sorted positions   */
+)
+{
+    opus_int32    value;
+    opus_int        i, j;
+
+    /* Safety checks */
+    silk_assert( K >  0 );
+    silk_assert( L >  0 );
+    silk_assert( L >= K );
+
+    /* Write start indices in index vector */
+    for( i = 0; i < K; i++ ) {
+        idx[ i ] = i;
+    }
+
+    /* Sort vector elements by value, increasing order */
+    for( i = 1; i < K; i++ ) {
+        value = a[ i ];
+        for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
+            a[ j + 1 ]   = a[ j ];       /* Shift value */
+            idx[ j + 1 ] = idx[ j ];     /* Shift index */
+        }
+        a[ j + 1 ]   = value;   /* Write value */
+        idx[ j + 1 ] = i;       /* Write index */
+    }
+
+    /* If less than L values are asked for, check the remaining values, */
+    /* but only spend CPU to ensure that the K first values are correct */
+    for( i = K; i < L; i++ ) {
+        value = a[ i ];
+        if( value < a[ K - 1 ] ) {
+            for( j = K - 2; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
+                a[ j + 1 ]   = a[ j ];       /* Shift value */
+                idx[ j + 1 ] = idx[ j ];     /* Shift index */
+            }
+            a[ j + 1 ]   = value;   /* Write value */
+            idx[ j + 1 ] = i;       /* Write index */
+        }
+    }
+}
+
+#ifdef FIXED_POINT
+/* This function is only used by the fixed-point build */
+void silk_insertion_sort_decreasing_int16(
+    opus_int16                  *a,                 /* I/O   Unsorted / Sorted vector                                   */
+    opus_int                    *idx,               /* O     Index vector for the sorted elements                       */
+    const opus_int              L,                  /* I     Vector length                                              */
+    const opus_int              K                   /* I     Number of correctly sorted positions                       */
+)
+{
+    opus_int i, j;
+    opus_int value;
+
+    /* Safety checks */
+    silk_assert( K >  0 );
+    silk_assert( L >  0 );
+    silk_assert( L >= K );
+
+    /* Write start indices in index vector */
+    for( i = 0; i < K; i++ ) {
+        idx[ i ] = i;
+    }
+
+    /* Sort vector elements by value, decreasing order */
+    for( i = 1; i < K; i++ ) {
+        value = a[ i ];
+        for( j = i - 1; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
+            a[ j + 1 ]   = a[ j ];     /* Shift value */
+            idx[ j + 1 ] = idx[ j ];   /* Shift index */
+        }
+        a[ j + 1 ]   = value;   /* Write value */
+        idx[ j + 1 ] = i;       /* Write index */
+    }
+
+    /* If less than L values are asked for, check the remaining values, */
+    /* but only spend CPU to ensure that the K first values are correct */
+    for( i = K; i < L; i++ ) {
+        value = a[ i ];
+        if( value > a[ K - 1 ] ) {
+            for( j = K - 2; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
+                a[ j + 1 ]   = a[ j ];     /* Shift value */
+                idx[ j + 1 ] = idx[ j ];   /* Shift index */
+            }
+            a[ j + 1 ]   = value;   /* Write value */
+            idx[ j + 1 ] = i;       /* Write index */
+        }
+    }
+}
+#endif
+
+void silk_insertion_sort_increasing_all_values_int16(
+     opus_int16                 *a,                 /* I/O   Unsorted / Sorted vector                                   */
+     const opus_int             L                   /* I     Vector length                                              */
+)
+{
+    opus_int    value;
+    opus_int    i, j;
+
+    /* Safety checks */
+    silk_assert( L >  0 );
+
+    /* Sort vector elements by value, increasing order */
+    for( i = 1; i < L; i++ ) {
+        value = a[ i ];
+        for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
+            a[ j + 1 ] = a[ j ]; /* Shift value */
+        }
+        a[ j + 1 ] = value; /* Write value */
+    }
+}
diff --git a/opus/silk/stereo_LR_to_MS.c b/opus/silk/stereo_LR_to_MS.c
new file mode 100644 (file)
index 0000000..dda0298
--- /dev/null
@@ -0,0 +1,229 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/* Convert Left/Right stereo signal to adaptive Mid/Side representation */
+void silk_stereo_LR_to_MS(
+    stereo_enc_state            *state,                         /* I/O  State                                       */
+    opus_int16                  x1[],                           /* I/O  Left input signal, becomes mid signal       */
+    opus_int16                  x2[],                           /* I/O  Right input signal, becomes side signal     */
+    opus_int8                   ix[ 2 ][ 3 ],                   /* O    Quantization indices                        */
+    opus_int8                   *mid_only_flag,                 /* O    Flag: only mid signal coded                 */
+    opus_int32                  mid_side_rates_bps[],           /* O    Bitrates for mid and side signals           */
+    opus_int32                  total_rate_bps,                 /* I    Total bitrate                               */
+    opus_int                    prev_speech_act_Q8,             /* I    Speech activity level in previous frame     */
+    opus_int                    toMono,                         /* I    Last frame before a stereo->mono transition */
+    opus_int                    fs_kHz,                         /* I    Sample rate (kHz)                           */
+    opus_int                    frame_length                    /* I    Number of samples                           */
+)
+{
+    opus_int   n, is10msFrame, denom_Q16, delta0_Q13, delta1_Q13;
+    opus_int32 sum, diff, smooth_coef_Q16, pred_Q13[ 2 ], pred0_Q13, pred1_Q13;
+    opus_int32 LP_ratio_Q14, HP_ratio_Q14, frac_Q16, frac_3_Q16, min_mid_rate_bps, width_Q14, w_Q24, deltaw_Q24;
+    VARDECL( opus_int16, side );
+    VARDECL( opus_int16, LP_mid );
+    VARDECL( opus_int16, HP_mid );
+    VARDECL( opus_int16, LP_side );
+    VARDECL( opus_int16, HP_side );
+    opus_int16 *mid = &x1[ -2 ];
+    SAVE_STACK;
+
+    ALLOC( side, frame_length + 2, opus_int16 );
+    /* Convert to basic mid/side signals */
+    for( n = 0; n < frame_length + 2; n++ ) {
+        sum  = x1[ n - 2 ] + (opus_int32)x2[ n - 2 ];
+        diff = x1[ n - 2 ] - (opus_int32)x2[ n - 2 ];
+        mid[  n ] = (opus_int16)silk_RSHIFT_ROUND( sum, 1 );
+        side[ n ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( diff, 1 ) );
+    }
+
+    /* Buffering */
+    silk_memcpy( mid,  state->sMid,  2 * sizeof( opus_int16 ) );
+    silk_memcpy( side, state->sSide, 2 * sizeof( opus_int16 ) );
+    silk_memcpy( state->sMid,  &mid[  frame_length ], 2 * sizeof( opus_int16 ) );
+    silk_memcpy( state->sSide, &side[ frame_length ], 2 * sizeof( opus_int16 ) );
+
+    /* LP and HP filter mid signal */
+    ALLOC( LP_mid, frame_length, opus_int16 );
+    ALLOC( HP_mid, frame_length, opus_int16 );
+    for( n = 0; n < frame_length; n++ ) {
+        sum = silk_RSHIFT_ROUND( silk_ADD_LSHIFT( mid[ n ] + (opus_int32)mid[ n + 2 ], mid[ n + 1 ], 1 ), 2 );
+        LP_mid[ n ] = sum;
+        HP_mid[ n ] = mid[ n + 1 ] - sum;
+    }
+
+    /* LP and HP filter side signal */
+    ALLOC( LP_side, frame_length, opus_int16 );
+    ALLOC( HP_side, frame_length, opus_int16 );
+    for( n = 0; n < frame_length; n++ ) {
+        sum = silk_RSHIFT_ROUND( silk_ADD_LSHIFT( side[ n ] + (opus_int32)side[ n + 2 ], side[ n + 1 ], 1 ), 2 );
+        LP_side[ n ] = sum;
+        HP_side[ n ] = side[ n + 1 ] - sum;
+    }
+
+    /* Find energies and predictors */
+    is10msFrame = frame_length == 10 * fs_kHz;
+    smooth_coef_Q16 = is10msFrame ?
+        SILK_FIX_CONST( STEREO_RATIO_SMOOTH_COEF / 2, 16 ) :
+        SILK_FIX_CONST( STEREO_RATIO_SMOOTH_COEF,     16 );
+    smooth_coef_Q16 = silk_SMULWB( silk_SMULBB( prev_speech_act_Q8, prev_speech_act_Q8 ), smooth_coef_Q16 );
+
+    pred_Q13[ 0 ] = silk_stereo_find_predictor( &LP_ratio_Q14, LP_mid, LP_side, &state->mid_side_amp_Q0[ 0 ], frame_length, smooth_coef_Q16 );
+    pred_Q13[ 1 ] = silk_stereo_find_predictor( &HP_ratio_Q14, HP_mid, HP_side, &state->mid_side_amp_Q0[ 2 ], frame_length, smooth_coef_Q16 );
+    /* Ratio of the norms of residual and mid signals */
+    frac_Q16 = silk_SMLABB( HP_ratio_Q14, LP_ratio_Q14, 3 );
+    frac_Q16 = silk_min( frac_Q16, SILK_FIX_CONST( 1, 16 ) );
+
+    /* Determine bitrate distribution between mid and side, and possibly reduce stereo width */
+    total_rate_bps -= is10msFrame ? 1200 : 600;      /* Subtract approximate bitrate for coding stereo parameters */
+    if( total_rate_bps < 1 ) {
+        total_rate_bps = 1;
+    }
+    min_mid_rate_bps = silk_SMLABB( 2000, fs_kHz, 900 );
+    silk_assert( min_mid_rate_bps < 32767 );
+    /* Default bitrate distribution: 8 parts for Mid and (5+3*frac) parts for Side. so: mid_rate = ( 8 / ( 13 + 3 * frac ) ) * total_ rate */
+    frac_3_Q16 = silk_MUL( 3, frac_Q16 );
+    mid_side_rates_bps[ 0 ] = silk_DIV32_varQ( total_rate_bps, SILK_FIX_CONST( 8 + 5, 16 ) + frac_3_Q16, 16+3 );
+    /* If Mid bitrate below minimum, reduce stereo width */
+    if( mid_side_rates_bps[ 0 ] < min_mid_rate_bps ) {
+        mid_side_rates_bps[ 0 ] = min_mid_rate_bps;
+        mid_side_rates_bps[ 1 ] = total_rate_bps - mid_side_rates_bps[ 0 ];
+        /* width = 4 * ( 2 * side_rate - min_rate ) / ( ( 1 + 3 * frac ) * min_rate ) */
+        width_Q14 = silk_DIV32_varQ( silk_LSHIFT( mid_side_rates_bps[ 1 ], 1 ) - min_mid_rate_bps,
+            silk_SMULWB( SILK_FIX_CONST( 1, 16 ) + frac_3_Q16, min_mid_rate_bps ), 14+2 );
+        width_Q14 = silk_LIMIT( width_Q14, 0, SILK_FIX_CONST( 1, 14 ) );
+    } else {
+        mid_side_rates_bps[ 1 ] = total_rate_bps - mid_side_rates_bps[ 0 ];
+        width_Q14 = SILK_FIX_CONST( 1, 14 );
+    }
+
+    /* Smoother */
+    state->smth_width_Q14 = (opus_int16)silk_SMLAWB( state->smth_width_Q14, width_Q14 - state->smth_width_Q14, smooth_coef_Q16 );
+
+    /* At very low bitrates or for inputs that are nearly amplitude panned, switch to panned-mono coding */
+    *mid_only_flag = 0;
+    if( toMono ) {
+        /* Last frame before stereo->mono transition; collapse stereo width */
+        width_Q14 = 0;
+        pred_Q13[ 0 ] = 0;
+        pred_Q13[ 1 ] = 0;
+        silk_stereo_quant_pred( pred_Q13, ix );
+    } else if( state->width_prev_Q14 == 0 &&
+        ( 8 * total_rate_bps < 13 * min_mid_rate_bps || silk_SMULWB( frac_Q16, state->smth_width_Q14 ) < SILK_FIX_CONST( 0.05, 14 ) ) )
+    {
+        /* Code as panned-mono; previous frame already had zero width */
+        /* Scale down and quantize predictors */
+        pred_Q13[ 0 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 0 ] ), 14 );
+        pred_Q13[ 1 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 1 ] ), 14 );
+        silk_stereo_quant_pred( pred_Q13, ix );
+        /* Collapse stereo width */
+        width_Q14 = 0;
+        pred_Q13[ 0 ] = 0;
+        pred_Q13[ 1 ] = 0;
+        mid_side_rates_bps[ 0 ] = total_rate_bps;
+        mid_side_rates_bps[ 1 ] = 0;
+        *mid_only_flag = 1;
+    } else if( state->width_prev_Q14 != 0 &&
+        ( 8 * total_rate_bps < 11 * min_mid_rate_bps || silk_SMULWB( frac_Q16, state->smth_width_Q14 ) < SILK_FIX_CONST( 0.02, 14 ) ) )
+    {
+        /* Transition to zero-width stereo */
+        /* Scale down and quantize predictors */
+        pred_Q13[ 0 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 0 ] ), 14 );
+        pred_Q13[ 1 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 1 ] ), 14 );
+        silk_stereo_quant_pred( pred_Q13, ix );
+        /* Collapse stereo width */
+        width_Q14 = 0;
+        pred_Q13[ 0 ] = 0;
+        pred_Q13[ 1 ] = 0;
+    } else if( state->smth_width_Q14 > SILK_FIX_CONST( 0.95, 14 ) ) {
+        /* Full-width stereo coding */
+        silk_stereo_quant_pred( pred_Q13, ix );
+        width_Q14 = SILK_FIX_CONST( 1, 14 );
+    } else {
+        /* Reduced-width stereo coding; scale down and quantize predictors */
+        pred_Q13[ 0 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 0 ] ), 14 );
+        pred_Q13[ 1 ] = silk_RSHIFT( silk_SMULBB( state->smth_width_Q14, pred_Q13[ 1 ] ), 14 );
+        silk_stereo_quant_pred( pred_Q13, ix );
+        width_Q14 = state->smth_width_Q14;
+    }
+
+    /* Make sure to keep on encoding until the tapered output has been transmitted */
+    if( *mid_only_flag == 1 ) {
+        state->silent_side_len += frame_length - STEREO_INTERP_LEN_MS * fs_kHz;
+        if( state->silent_side_len < LA_SHAPE_MS * fs_kHz ) {
+            *mid_only_flag = 0;
+        } else {
+            /* Limit to avoid wrapping around */
+            state->silent_side_len = 10000;
+        }
+    } else {
+        state->silent_side_len = 0;
+    }
+
+    if( *mid_only_flag == 0 && mid_side_rates_bps[ 1 ] < 1 ) {
+        mid_side_rates_bps[ 1 ] = 1;
+        mid_side_rates_bps[ 0 ] = silk_max_int( 1, total_rate_bps - mid_side_rates_bps[ 1 ]);
+    }
+
+    /* Interpolate predictors and subtract prediction from side channel */
+    pred0_Q13  = -state->pred_prev_Q13[ 0 ];
+    pred1_Q13  = -state->pred_prev_Q13[ 1 ];
+    w_Q24      =  silk_LSHIFT( state->width_prev_Q14, 10 );
+    denom_Q16  = silk_DIV32_16( (opus_int32)1 << 16, STEREO_INTERP_LEN_MS * fs_kHz );
+    delta0_Q13 = -silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 0 ] - state->pred_prev_Q13[ 0 ], denom_Q16 ), 16 );
+    delta1_Q13 = -silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 1 ] - state->pred_prev_Q13[ 1 ], denom_Q16 ), 16 );
+    deltaw_Q24 =  silk_LSHIFT( silk_SMULWB( width_Q14 - state->width_prev_Q14, denom_Q16 ), 10 );
+    for( n = 0; n < STEREO_INTERP_LEN_MS * fs_kHz; n++ ) {
+        pred0_Q13 += delta0_Q13;
+        pred1_Q13 += delta1_Q13;
+        w_Q24   += deltaw_Q24;
+        sum = silk_LSHIFT( silk_ADD_LSHIFT( mid[ n ] + (opus_int32)mid[ n + 2 ], mid[ n + 1 ], 1 ), 9 );    /* Q11 */
+        sum = silk_SMLAWB( silk_SMULWB( w_Q24, side[ n + 1 ] ), sum, pred0_Q13 );               /* Q8  */
+        sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)mid[ n + 1 ], 11 ), pred1_Q13 );       /* Q8  */
+        x2[ n - 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
+    }
+
+    pred0_Q13 = -pred_Q13[ 0 ];
+    pred1_Q13 = -pred_Q13[ 1 ];
+    w_Q24     =  silk_LSHIFT( width_Q14, 10 );
+    for( n = STEREO_INTERP_LEN_MS * fs_kHz; n < frame_length; n++ ) {
+        sum = silk_LSHIFT( silk_ADD_LSHIFT( mid[ n ] + (opus_int32)mid[ n + 2 ], mid[ n + 1 ], 1 ), 9 );    /* Q11 */
+        sum = silk_SMLAWB( silk_SMULWB( w_Q24, side[ n + 1 ] ), sum, pred0_Q13 );               /* Q8  */
+        sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)mid[ n + 1 ], 11 ), pred1_Q13 );       /* Q8  */
+        x2[ n - 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
+    }
+    state->pred_prev_Q13[ 0 ] = (opus_int16)pred_Q13[ 0 ];
+    state->pred_prev_Q13[ 1 ] = (opus_int16)pred_Q13[ 1 ];
+    state->width_prev_Q14     = (opus_int16)width_Q14;
+    RESTORE_STACK;
+}
diff --git a/opus/silk/stereo_MS_to_LR.c b/opus/silk/stereo_MS_to_LR.c
new file mode 100644 (file)
index 0000000..62521a4
--- /dev/null
@@ -0,0 +1,85 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Convert adaptive Mid/Side representation to Left/Right stereo signal */
+void silk_stereo_MS_to_LR(
+    stereo_dec_state            *state,                         /* I/O  State                                       */
+    opus_int16                  x1[],                           /* I/O  Left input signal, becomes mid signal       */
+    opus_int16                  x2[],                           /* I/O  Right input signal, becomes side signal     */
+    const opus_int32            pred_Q13[],                     /* I    Predictors                                  */
+    opus_int                    fs_kHz,                         /* I    Samples rate (kHz)                          */
+    opus_int                    frame_length                    /* I    Number of samples                           */
+)
+{
+    opus_int   n, denom_Q16, delta0_Q13, delta1_Q13;
+    opus_int32 sum, diff, pred0_Q13, pred1_Q13;
+
+    /* Buffering */
+    silk_memcpy( x1, state->sMid,  2 * sizeof( opus_int16 ) );
+    silk_memcpy( x2, state->sSide, 2 * sizeof( opus_int16 ) );
+    silk_memcpy( state->sMid,  &x1[ frame_length ], 2 * sizeof( opus_int16 ) );
+    silk_memcpy( state->sSide, &x2[ frame_length ], 2 * sizeof( opus_int16 ) );
+
+    /* Interpolate predictors and add prediction to side channel */
+    pred0_Q13  = state->pred_prev_Q13[ 0 ];
+    pred1_Q13  = state->pred_prev_Q13[ 1 ];
+    denom_Q16  = silk_DIV32_16( (opus_int32)1 << 16, STEREO_INTERP_LEN_MS * fs_kHz );
+    delta0_Q13 = silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 0 ] - state->pred_prev_Q13[ 0 ], denom_Q16 ), 16 );
+    delta1_Q13 = silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 1 ] - state->pred_prev_Q13[ 1 ], denom_Q16 ), 16 );
+    for( n = 0; n < STEREO_INTERP_LEN_MS * fs_kHz; n++ ) {
+        pred0_Q13 += delta0_Q13;
+        pred1_Q13 += delta1_Q13;
+        sum = silk_LSHIFT( silk_ADD_LSHIFT( x1[ n ] + x1[ n + 2 ], x1[ n + 1 ], 1 ), 9 );       /* Q11 */
+        sum = silk_SMLAWB( silk_LSHIFT( (opus_int32)x2[ n + 1 ], 8 ), sum, pred0_Q13 );         /* Q8  */
+        sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)x1[ n + 1 ], 11 ), pred1_Q13 );        /* Q8  */
+        x2[ n + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
+    }
+    pred0_Q13 = pred_Q13[ 0 ];
+    pred1_Q13 = pred_Q13[ 1 ];
+    for( n = STEREO_INTERP_LEN_MS * fs_kHz; n < frame_length; n++ ) {
+        sum = silk_LSHIFT( silk_ADD_LSHIFT( x1[ n ] + x1[ n + 2 ], x1[ n + 1 ], 1 ), 9 );       /* Q11 */
+        sum = silk_SMLAWB( silk_LSHIFT( (opus_int32)x2[ n + 1 ], 8 ), sum, pred0_Q13 );         /* Q8  */
+        sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)x1[ n + 1 ], 11 ), pred1_Q13 );        /* Q8  */
+        x2[ n + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
+    }
+    state->pred_prev_Q13[ 0 ] = pred_Q13[ 0 ];
+    state->pred_prev_Q13[ 1 ] = pred_Q13[ 1 ];
+
+    /* Convert to left/right signals */
+    for( n = 0; n < frame_length; n++ ) {
+        sum  = x1[ n + 1 ] + (opus_int32)x2[ n + 1 ];
+        diff = x1[ n + 1 ] - (opus_int32)x2[ n + 1 ];
+        x1[ n + 1 ] = (opus_int16)silk_SAT16( sum );
+        x2[ n + 1 ] = (opus_int16)silk_SAT16( diff );
+    }
+}
diff --git a/opus/silk/stereo_decode_pred.c b/opus/silk/stereo_decode_pred.c
new file mode 100644 (file)
index 0000000..56ba392
--- /dev/null
@@ -0,0 +1,73 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Decode mid/side predictors */
+void silk_stereo_decode_pred(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int32                  pred_Q13[]                      /* O    Predictors                                  */
+)
+{
+    opus_int   n, ix[ 2 ][ 3 ];
+    opus_int32 low_Q13, step_Q13;
+
+    /* Entropy decoding */
+    n = ec_dec_icdf( psRangeDec, silk_stereo_pred_joint_iCDF, 8 );
+    ix[ 0 ][ 2 ] = silk_DIV32_16( n, 5 );
+    ix[ 1 ][ 2 ] = n - 5 * ix[ 0 ][ 2 ];
+    for( n = 0; n < 2; n++ ) {
+        ix[ n ][ 0 ] = ec_dec_icdf( psRangeDec, silk_uniform3_iCDF, 8 );
+        ix[ n ][ 1 ] = ec_dec_icdf( psRangeDec, silk_uniform5_iCDF, 8 );
+    }
+
+    /* Dequantize */
+    for( n = 0; n < 2; n++ ) {
+        ix[ n ][ 0 ] += 3 * ix[ n ][ 2 ];
+        low_Q13 = silk_stereo_pred_quant_Q13[ ix[ n ][ 0 ] ];
+        step_Q13 = silk_SMULWB( silk_stereo_pred_quant_Q13[ ix[ n ][ 0 ] + 1 ] - low_Q13,
+            SILK_FIX_CONST( 0.5 / STEREO_QUANT_SUB_STEPS, 16 ) );
+        pred_Q13[ n ] = silk_SMLABB( low_Q13, step_Q13, 2 * ix[ n ][ 1 ] + 1 );
+    }
+
+    /* Subtract second from first predictor (helps when actually applying these) */
+    pred_Q13[ 0 ] -= pred_Q13[ 1 ];
+}
+
+/* Decode mid-only flag */
+void silk_stereo_decode_mid_only(
+    ec_dec                      *psRangeDec,                    /* I/O  Compressor data structure                   */
+    opus_int                    *decode_only_mid                /* O    Flag that only mid channel has been coded   */
+)
+{
+    /* Decode flag that only mid channel is coded */
+    *decode_only_mid = ec_dec_icdf( psRangeDec, silk_stereo_only_code_mid_iCDF, 8 );
+}
diff --git a/opus/silk/stereo_encode_pred.c b/opus/silk/stereo_encode_pred.c
new file mode 100644 (file)
index 0000000..e6dd195
--- /dev/null
@@ -0,0 +1,62 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Entropy code the mid/side quantization indices */
+void silk_stereo_encode_pred(
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int8                   ix[ 2 ][ 3 ]                    /* I    Quantization indices                        */
+)
+{
+    opus_int   n;
+
+    /* Entropy coding */
+    n = 5 * ix[ 0 ][ 2 ] + ix[ 1 ][ 2 ];
+    silk_assert( n < 25 );
+    ec_enc_icdf( psRangeEnc, n, silk_stereo_pred_joint_iCDF, 8 );
+    for( n = 0; n < 2; n++ ) {
+        silk_assert( ix[ n ][ 0 ] < 3 );
+        silk_assert( ix[ n ][ 1 ] < STEREO_QUANT_SUB_STEPS );
+        ec_enc_icdf( psRangeEnc, ix[ n ][ 0 ], silk_uniform3_iCDF, 8 );
+        ec_enc_icdf( psRangeEnc, ix[ n ][ 1 ], silk_uniform5_iCDF, 8 );
+    }
+}
+
+/* Entropy code the mid-only flag */
+void silk_stereo_encode_mid_only(
+    ec_enc                      *psRangeEnc,                    /* I/O  Compressor data structure                   */
+    opus_int8                   mid_only_flag
+)
+{
+    /* Encode flag that only mid channel is coded */
+    ec_enc_icdf( psRangeEnc, mid_only_flag, silk_stereo_only_code_mid_iCDF, 8 );
+}
diff --git a/opus/silk/stereo_find_predictor.c b/opus/silk/stereo_find_predictor.c
new file mode 100644 (file)
index 0000000..e30e90b
--- /dev/null
@@ -0,0 +1,79 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Find least-squares prediction gain for one signal based on another and quantize it */
+opus_int32 silk_stereo_find_predictor(                          /* O    Returns predictor in Q13                    */
+    opus_int32                  *ratio_Q14,                     /* O    Ratio of residual and mid energies          */
+    const opus_int16            x[],                            /* I    Basis signal                                */
+    const opus_int16            y[],                            /* I    Target signal                               */
+    opus_int32                  mid_res_amp_Q0[],               /* I/O  Smoothed mid, residual norms                */
+    opus_int                    length,                         /* I    Number of samples                           */
+    opus_int                    smooth_coef_Q16                 /* I    Smoothing coefficient                       */
+)
+{
+    opus_int   scale, scale1, scale2;
+    opus_int32 nrgx, nrgy, corr, pred_Q13, pred2_Q10;
+
+    /* Find  predictor */
+    silk_sum_sqr_shift( &nrgx, &scale1, x, length );
+    silk_sum_sqr_shift( &nrgy, &scale2, y, length );
+    scale = silk_max_int( scale1, scale2 );
+    scale = scale + ( scale & 1 );          /* make even */
+    nrgy = silk_RSHIFT32( nrgy, scale - scale2 );
+    nrgx = silk_RSHIFT32( nrgx, scale - scale1 );
+    nrgx = silk_max_int( nrgx, 1 );
+    corr = silk_inner_prod_aligned_scale( x, y, scale, length );
+    pred_Q13 = silk_DIV32_varQ( corr, nrgx, 13 );
+    pred_Q13 = silk_LIMIT( pred_Q13, -(1 << 14), 1 << 14 );
+    pred2_Q10 = silk_SMULWB( pred_Q13, pred_Q13 );
+
+    /* Faster update for signals with large prediction parameters */
+    smooth_coef_Q16 = (opus_int)silk_max_int( smooth_coef_Q16, silk_abs( pred2_Q10 ) );
+
+    /* Smoothed mid and residual norms */
+    silk_assert( smooth_coef_Q16 < 32768 );
+    scale = silk_RSHIFT( scale, 1 );
+    mid_res_amp_Q0[ 0 ] = silk_SMLAWB( mid_res_amp_Q0[ 0 ], silk_LSHIFT( silk_SQRT_APPROX( nrgx ), scale ) - mid_res_amp_Q0[ 0 ],
+        smooth_coef_Q16 );
+    /* Residual energy = nrgy - 2 * pred * corr + pred^2 * nrgx */
+    nrgy = silk_SUB_LSHIFT32( nrgy, silk_SMULWB( corr, pred_Q13 ), 3 + 1 );
+    nrgy = silk_ADD_LSHIFT32( nrgy, silk_SMULWB( nrgx, pred2_Q10 ), 6 );
+    mid_res_amp_Q0[ 1 ] = silk_SMLAWB( mid_res_amp_Q0[ 1 ], silk_LSHIFT( silk_SQRT_APPROX( nrgy ), scale ) - mid_res_amp_Q0[ 1 ],
+        smooth_coef_Q16 );
+
+    /* Ratio of smoothed residual and mid norms */
+    *ratio_Q14 = silk_DIV32_varQ( mid_res_amp_Q0[ 1 ], silk_max( mid_res_amp_Q0[ 0 ], 1 ), 14 );
+    *ratio_Q14 = silk_LIMIT( *ratio_Q14, 0, 32767 );
+
+    return pred_Q13;
+}
diff --git a/opus/silk/stereo_quant_pred.c b/opus/silk/stereo_quant_pred.c
new file mode 100644 (file)
index 0000000..d4ced6c
--- /dev/null
@@ -0,0 +1,73 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "main.h"
+
+/* Quantize mid/side predictors */
+void silk_stereo_quant_pred(
+    opus_int32                  pred_Q13[],                     /* I/O  Predictors (out: quantized)                 */
+    opus_int8                   ix[ 2 ][ 3 ]                    /* O    Quantization indices                        */
+)
+{
+    opus_int   i, j, n;
+    opus_int32 low_Q13, step_Q13, lvl_Q13, err_min_Q13, err_Q13, quant_pred_Q13 = 0;
+
+    /* Quantize */
+    for( n = 0; n < 2; n++ ) {
+        /* Brute-force search over quantization levels */
+        err_min_Q13 = silk_int32_MAX;
+        for( i = 0; i < STEREO_QUANT_TAB_SIZE - 1; i++ ) {
+            low_Q13 = silk_stereo_pred_quant_Q13[ i ];
+            step_Q13 = silk_SMULWB( silk_stereo_pred_quant_Q13[ i + 1 ] - low_Q13,
+                SILK_FIX_CONST( 0.5 / STEREO_QUANT_SUB_STEPS, 16 ) );
+            for( j = 0; j < STEREO_QUANT_SUB_STEPS; j++ ) {
+                lvl_Q13 = silk_SMLABB( low_Q13, step_Q13, 2 * j + 1 );
+                err_Q13 = silk_abs( pred_Q13[ n ] - lvl_Q13 );
+                if( err_Q13 < err_min_Q13 ) {
+                    err_min_Q13 = err_Q13;
+                    quant_pred_Q13 = lvl_Q13;
+                    ix[ n ][ 0 ] = i;
+                    ix[ n ][ 1 ] = j;
+                } else {
+                    /* Error increasing, so we're past the optimum */
+                    goto done;
+                }
+            }
+        }
+        done:
+        ix[ n ][ 2 ]  = silk_DIV32_16( ix[ n ][ 0 ], 3 );
+        ix[ n ][ 0 ] -= ix[ n ][ 2 ] * 3;
+        pred_Q13[ n ] = quant_pred_Q13;
+    }
+
+    /* Subtract second from first predictor (helps when actually applying these) */
+    pred_Q13[ 0 ] -= pred_Q13[ 1 ];
+}
diff --git a/opus/silk/structs.h b/opus/silk/structs.h
new file mode 100644 (file)
index 0000000..4ff590b
--- /dev/null
@@ -0,0 +1,328 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_STRUCTS_H
+#define SILK_STRUCTS_H
+
+#include "typedef.h"
+#include "SigProc_FIX.h"
+#include "define.h"
+#include "entenc.h"
+#include "entdec.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/************************************/
+/* Noise shaping quantization state */
+/************************************/
+typedef struct {
+    opus_int16                  xq[           2 * MAX_FRAME_LENGTH ]; /* Buffer for quantized output signal                             */
+    opus_int32                  sLTP_shp_Q14[ 2 * MAX_FRAME_LENGTH ];
+    opus_int32                  sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ];
+    opus_int32                  sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];
+    opus_int32                  sLF_AR_shp_Q14;
+    opus_int32                  sDiff_shp_Q14;
+    opus_int                    lagPrev;
+    opus_int                    sLTP_buf_idx;
+    opus_int                    sLTP_shp_buf_idx;
+    opus_int32                  rand_seed;
+    opus_int32                  prev_gain_Q16;
+    opus_int                    rewhite_flag;
+} silk_nsq_state;
+
+/********************************/
+/* VAD state                    */
+/********************************/
+typedef struct {
+    opus_int32                  AnaState[ 2 ];                  /* Analysis filterbank state: 0-8 kHz                                   */
+    opus_int32                  AnaState1[ 2 ];                 /* Analysis filterbank state: 0-4 kHz                                   */
+    opus_int32                  AnaState2[ 2 ];                 /* Analysis filterbank state: 0-2 kHz                                   */
+    opus_int32                  XnrgSubfr[ VAD_N_BANDS ];       /* Subframe energies                                                    */
+    opus_int32                  NrgRatioSmth_Q8[ VAD_N_BANDS ]; /* Smoothed energy level in each band                                   */
+    opus_int16                  HPstate;                        /* State of differentiator in the lowest band                           */
+    opus_int32                  NL[ VAD_N_BANDS ];              /* Noise energy level in each band                                      */
+    opus_int32                  inv_NL[ VAD_N_BANDS ];          /* Inverse noise energy level in each band                              */
+    opus_int32                  NoiseLevelBias[ VAD_N_BANDS ];  /* Noise level estimator bias/offset                                    */
+    opus_int32                  counter;                        /* Frame counter used in the initial phase                              */
+} silk_VAD_state;
+
+/* Variable cut-off low-pass filter state */
+typedef struct {
+    opus_int32                   In_LP_State[ 2 ];           /* Low pass filter state */
+    opus_int32                   transition_frame_no;        /* Counter which is mapped to a cut-off frequency */
+    opus_int                     mode;                       /* Operating mode, <0: switch down, >0: switch up; 0: do nothing           */
+} silk_LP_state;
+
+/* Structure containing NLSF codebook */
+typedef struct {
+    const opus_int16             nVectors;
+    const opus_int16             order;
+    const opus_int16             quantStepSize_Q16;
+    const opus_int16             invQuantStepSize_Q6;
+    const opus_uint8             *CB1_NLSF_Q8;
+    const opus_int16             *CB1_Wght_Q9;
+    const opus_uint8             *CB1_iCDF;
+    const opus_uint8             *pred_Q8;
+    const opus_uint8             *ec_sel;
+    const opus_uint8             *ec_iCDF;
+    const opus_uint8             *ec_Rates_Q5;
+    const opus_int16             *deltaMin_Q15;
+} silk_NLSF_CB_struct;
+
+typedef struct {
+    opus_int16                   pred_prev_Q13[ 2 ];
+    opus_int16                   sMid[ 2 ];
+    opus_int16                   sSide[ 2 ];
+    opus_int32                   mid_side_amp_Q0[ 4 ];
+    opus_int16                   smth_width_Q14;
+    opus_int16                   width_prev_Q14;
+    opus_int16                   silent_side_len;
+    opus_int8                    predIx[ MAX_FRAMES_PER_PACKET ][ 2 ][ 3 ];
+    opus_int8                    mid_only_flags[ MAX_FRAMES_PER_PACKET ];
+} stereo_enc_state;
+
+typedef struct {
+    opus_int16                   pred_prev_Q13[ 2 ];
+    opus_int16                   sMid[ 2 ];
+    opus_int16                   sSide[ 2 ];
+} stereo_dec_state;
+
+typedef struct {
+    opus_int8                    GainsIndices[ MAX_NB_SUBFR ];
+    opus_int8                    LTPIndex[ MAX_NB_SUBFR ];
+    opus_int8                    NLSFIndices[ MAX_LPC_ORDER + 1 ];
+    opus_int16                   lagIndex;
+    opus_int8                    contourIndex;
+    opus_int8                    signalType;
+    opus_int8                    quantOffsetType;
+    opus_int8                    NLSFInterpCoef_Q2;
+    opus_int8                    PERIndex;
+    opus_int8                    LTP_scaleIndex;
+    opus_int8                    Seed;
+} SideInfoIndices;
+
+/********************************/
+/* Encoder state                */
+/********************************/
+typedef struct {
+    opus_int32                   In_HP_State[ 2 ];                  /* High pass filter state                                           */
+    opus_int32                   variable_HP_smth1_Q15;             /* State of first smoother                                          */
+    opus_int32                   variable_HP_smth2_Q15;             /* State of second smoother                                         */
+    silk_LP_state                sLP;                               /* Low pass filter state                                            */
+    silk_VAD_state               sVAD;                              /* Voice activity detector state                                    */
+    silk_nsq_state               sNSQ;                              /* Noise Shape Quantizer State                                      */
+    opus_int16                   prev_NLSFq_Q15[ MAX_LPC_ORDER ];   /* Previously quantized NLSF vector                                 */
+    opus_int                     speech_activity_Q8;                /* Speech activity                                                  */
+    opus_int                     allow_bandwidth_switch;            /* Flag indicating that switching of internal bandwidth is allowed  */
+    opus_int8                    LBRRprevLastGainIndex;
+    opus_int8                    prevSignalType;
+    opus_int                     prevLag;
+    opus_int                     pitch_LPC_win_length;
+    opus_int                     max_pitch_lag;                     /* Highest possible pitch lag (samples)                             */
+    opus_int32                   API_fs_Hz;                         /* API sampling frequency (Hz)                                      */
+    opus_int32                   prev_API_fs_Hz;                    /* Previous API sampling frequency (Hz)                             */
+    opus_int                     maxInternal_fs_Hz;                 /* Maximum internal sampling frequency (Hz)                         */
+    opus_int                     minInternal_fs_Hz;                 /* Minimum internal sampling frequency (Hz)                         */
+    opus_int                     desiredInternal_fs_Hz;             /* Soft request for internal sampling frequency (Hz)                */
+    opus_int                     fs_kHz;                            /* Internal sampling frequency (kHz)                                */
+    opus_int                     nb_subfr;                          /* Number of 5 ms subframes in a frame                              */
+    opus_int                     frame_length;                      /* Frame length (samples)                                           */
+    opus_int                     subfr_length;                      /* Subframe length (samples)                                        */
+    opus_int                     ltp_mem_length;                    /* Length of LTP memory                                             */
+    opus_int                     la_pitch;                          /* Look-ahead for pitch analysis (samples)                          */
+    opus_int                     la_shape;                          /* Look-ahead for noise shape analysis (samples)                    */
+    opus_int                     shapeWinLength;                    /* Window length for noise shape analysis (samples)                 */
+    opus_int32                   TargetRate_bps;                    /* Target bitrate (bps)                                             */
+    opus_int                     PacketSize_ms;                     /* Number of milliseconds to put in each packet                     */
+    opus_int                     PacketLoss_perc;                   /* Packet loss rate measured by farend                              */
+    opus_int32                   frameCounter;
+    opus_int                     Complexity;                        /* Complexity setting                                               */
+    opus_int                     nStatesDelayedDecision;            /* Number of states in delayed decision quantization                */
+    opus_int                     useInterpolatedNLSFs;              /* Flag for using NLSF interpolation                                */
+    opus_int                     shapingLPCOrder;                   /* Filter order for noise shaping filters                           */
+    opus_int                     predictLPCOrder;                   /* Filter order for prediction filters                              */
+    opus_int                     pitchEstimationComplexity;         /* Complexity level for pitch estimator                             */
+    opus_int                     pitchEstimationLPCOrder;           /* Whitening filter order for pitch estimator                       */
+    opus_int32                   pitchEstimationThreshold_Q16;      /* Threshold for pitch estimator                                    */
+    opus_int32                   sum_log_gain_Q7;                   /* Cumulative max prediction gain                                   */
+    opus_int                     NLSF_MSVQ_Survivors;               /* Number of survivors in NLSF MSVQ                                 */
+    opus_int                     first_frame_after_reset;           /* Flag for deactivating NLSF interpolation, pitch prediction       */
+    opus_int                     controlled_since_last_payload;     /* Flag for ensuring codec_control only runs once per packet        */
+    opus_int                     warping_Q16;                       /* Warping parameter for warped noise shaping                       */
+    opus_int                     useCBR;                            /* Flag to enable constant bitrate                                  */
+    opus_int                     prefillFlag;                       /* Flag to indicate that only buffers are prefilled, no coding      */
+    const opus_uint8             *pitch_lag_low_bits_iCDF;          /* Pointer to iCDF table for low bits of pitch lag index            */
+    const opus_uint8             *pitch_contour_iCDF;               /* Pointer to iCDF table for pitch contour index                    */
+    const silk_NLSF_CB_struct    *psNLSF_CB;                        /* Pointer to NLSF codebook                                         */
+    opus_int                     input_quality_bands_Q15[ VAD_N_BANDS ];
+    opus_int                     input_tilt_Q15;
+    opus_int                     SNR_dB_Q7;                         /* Quality setting                                                  */
+
+    opus_int8                    VAD_flags[ MAX_FRAMES_PER_PACKET ];
+    opus_int8                    LBRR_flag;
+    opus_int                     LBRR_flags[ MAX_FRAMES_PER_PACKET ];
+
+    SideInfoIndices              indices;
+    opus_int8                    pulses[ MAX_FRAME_LENGTH ];
+
+    int                          arch;
+
+    /* Input/output buffering */
+    opus_int16                   inputBuf[ MAX_FRAME_LENGTH + 2 ];  /* Buffer containing input signal                                   */
+    opus_int                     inputBufIx;
+    opus_int                     nFramesPerPacket;
+    opus_int                     nFramesEncoded;                    /* Number of frames analyzed in current packet                      */
+
+    opus_int                     nChannelsAPI;
+    opus_int                     nChannelsInternal;
+    opus_int                     channelNb;
+
+    /* Parameters For LTP scaling Control */
+    opus_int                     frames_since_onset;
+
+    /* Specifically for entropy coding */
+    opus_int                     ec_prevSignalType;
+    opus_int16                   ec_prevLagIndex;
+
+    silk_resampler_state_struct resampler_state;
+
+    /* DTX */
+    opus_int                     useDTX;                            /* Flag to enable DTX                                               */
+    opus_int                     inDTX;                             /* Flag to signal DTX period                                        */
+    opus_int                     noSpeechCounter;                   /* Counts concecutive nonactive frames, used by DTX                 */
+
+    /* Inband Low Bitrate Redundancy (LBRR) data */
+    opus_int                     useInBandFEC;                      /* Saves the API setting for query                                  */
+    opus_int                     LBRR_enabled;                      /* Depends on useInBandFRC, bitrate and packet loss rate            */
+    opus_int                     LBRR_GainIncreases;                /* Gains increment for coding LBRR frames                           */
+    SideInfoIndices              indices_LBRR[ MAX_FRAMES_PER_PACKET ];
+    opus_int8                    pulses_LBRR[ MAX_FRAMES_PER_PACKET ][ MAX_FRAME_LENGTH ];
+} silk_encoder_state;
+
+
+/* Struct for Packet Loss Concealment */
+typedef struct {
+    opus_int32                  pitchL_Q8;                          /* Pitch lag to use for voiced concealment                          */
+    opus_int16                  LTPCoef_Q14[ LTP_ORDER ];           /* LTP coeficients to use for voiced concealment                    */
+    opus_int16                  prevLPC_Q12[ MAX_LPC_ORDER ];
+    opus_int                    last_frame_lost;                    /* Was previous frame lost                                          */
+    opus_int32                  rand_seed;                          /* Seed for unvoiced signal generation                              */
+    opus_int16                  randScale_Q14;                      /* Scaling of unvoiced random signal                                */
+    opus_int32                  conc_energy;
+    opus_int                    conc_energy_shift;
+    opus_int16                  prevLTP_scale_Q14;
+    opus_int32                  prevGain_Q16[ 2 ];
+    opus_int                    fs_kHz;
+    opus_int                    nb_subfr;
+    opus_int                    subfr_length;
+} silk_PLC_struct;
+
+/* Struct for CNG */
+typedef struct {
+    opus_int32                  CNG_exc_buf_Q14[ MAX_FRAME_LENGTH ];
+    opus_int16                  CNG_smth_NLSF_Q15[ MAX_LPC_ORDER ];
+    opus_int32                  CNG_synth_state[ MAX_LPC_ORDER ];
+    opus_int32                  CNG_smth_Gain_Q16;
+    opus_int32                  rand_seed;
+    opus_int                    fs_kHz;
+} silk_CNG_struct;
+
+/********************************/
+/* Decoder state                */
+/********************************/
+typedef struct {
+    opus_int32                  prev_gain_Q16;
+    opus_int32                  exc_Q14[ MAX_FRAME_LENGTH ];
+    opus_int32                  sLPC_Q14_buf[ MAX_LPC_ORDER ];
+    opus_int16                  outBuf[ MAX_FRAME_LENGTH + 2 * MAX_SUB_FRAME_LENGTH ];  /* Buffer for output signal                     */
+    opus_int                    lagPrev;                            /* Previous Lag                                                     */
+    opus_int8                   LastGainIndex;                      /* Previous gain index                                              */
+    opus_int                    fs_kHz;                             /* Sampling frequency in kHz                                        */
+    opus_int32                  fs_API_hz;                          /* API sample frequency (Hz)                                        */
+    opus_int                    nb_subfr;                           /* Number of 5 ms subframes in a frame                              */
+    opus_int                    frame_length;                       /* Frame length (samples)                                           */
+    opus_int                    subfr_length;                       /* Subframe length (samples)                                        */
+    opus_int                    ltp_mem_length;                     /* Length of LTP memory                                             */
+    opus_int                    LPC_order;                          /* LPC order                                                        */
+    opus_int16                  prevNLSF_Q15[ MAX_LPC_ORDER ];      /* Used to interpolate LSFs                                         */
+    opus_int                    first_frame_after_reset;            /* Flag for deactivating NLSF interpolation                         */
+    const opus_uint8            *pitch_lag_low_bits_iCDF;           /* Pointer to iCDF table for low bits of pitch lag index            */
+    const opus_uint8            *pitch_contour_iCDF;                /* Pointer to iCDF table for pitch contour index                    */
+
+    /* For buffering payload in case of more frames per packet */
+    opus_int                    nFramesDecoded;
+    opus_int                    nFramesPerPacket;
+
+    /* Specifically for entropy coding */
+    opus_int                    ec_prevSignalType;
+    opus_int16                  ec_prevLagIndex;
+
+    opus_int                    VAD_flags[ MAX_FRAMES_PER_PACKET ];
+    opus_int                    LBRR_flag;
+    opus_int                    LBRR_flags[ MAX_FRAMES_PER_PACKET ];
+
+    silk_resampler_state_struct resampler_state;
+
+    const silk_NLSF_CB_struct   *psNLSF_CB;                         /* Pointer to NLSF codebook                                         */
+
+    /* Quantization indices */
+    SideInfoIndices             indices;
+
+    /* CNG state */
+    silk_CNG_struct             sCNG;
+
+    /* Stuff used for PLC */
+    opus_int                    lossCnt;
+    opus_int                    prevSignalType;
+    int                         arch;
+
+    silk_PLC_struct sPLC;
+
+} silk_decoder_state;
+
+/************************/
+/* Decoder control      */
+/************************/
+typedef struct {
+    /* Prediction and coding parameters */
+    opus_int                    pitchL[ MAX_NB_SUBFR ];
+    opus_int32                  Gains_Q16[ MAX_NB_SUBFR ];
+    /* Holds interpolated and final coefficients, 4-byte aligned */
+    silk_DWORD_ALIGN opus_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];
+    opus_int16                  LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ];
+    opus_int                    LTP_scale_Q14;
+} silk_decoder_control;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/sum_sqr_shift.c b/opus/silk/sum_sqr_shift.c
new file mode 100644 (file)
index 0000000..4fd0c3d
--- /dev/null
@@ -0,0 +1,83 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "SigProc_FIX.h"
+
+/* Compute number of bits to right shift the sum of squares of a vector */
+/* of int16s to make it fit in an int32                                 */
+void silk_sum_sqr_shift(
+    opus_int32                  *energy,            /* O   Energy of x, after shifting to the right                     */
+    opus_int                    *shift,             /* O   Number of bits right shift applied to energy                 */
+    const opus_int16            *x,                 /* I   Input vector                                                 */
+    opus_int                    len                 /* I   Length of input vector                                       */
+)
+{
+    opus_int   i, shft;
+    opus_uint32 nrg_tmp;
+    opus_int32 nrg;
+
+    /* Do a first run with the maximum shift we could have. */
+    shft = 31-silk_CLZ32(len);
+    /* Let's be conservative with rounding and start with nrg=len. */
+    nrg  = len;
+    for( i = 0; i < len - 1; i += 2 ) {
+        nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
+        nrg_tmp = silk_SMLABB_ovflw( nrg_tmp, x[ i + 1 ], x[ i + 1 ] );
+        nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );
+    }
+    if( i < len ) {
+        /* One sample left to process */
+        nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
+        nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );
+    }
+    silk_assert( nrg >= 0 );
+    /* Make sure the result will fit in a 32-bit signed integer with two bits
+       of headroom. */
+    shft = silk_max_32(0, shft+3 - silk_CLZ32(nrg));
+    nrg = 0;
+    for( i = 0 ; i < len - 1; i += 2 ) {
+        nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
+        nrg_tmp = silk_SMLABB_ovflw( nrg_tmp, x[ i + 1 ], x[ i + 1 ] );
+        nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );
+    }
+    if( i < len ) {
+        /* One sample left to process */
+        nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
+        nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );
+    }
+
+    silk_assert( nrg >= 0 );
+
+    /* Output arguments */
+    *shift  = shft;
+    *energy = nrg;
+}
+
diff --git a/opus/silk/table_LSF_cos.c b/opus/silk/table_LSF_cos.c
new file mode 100644 (file)
index 0000000..ec9dc63
--- /dev/null
@@ -0,0 +1,70 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+/* Cosine approximation table for LSF conversion */
+/* Q12 values (even) */
+const opus_int16 silk_LSFCosTab_FIX_Q12[ LSF_COS_TAB_SZ_FIX + 1 ] = {
+            8192,             8190,             8182,             8170,
+            8152,             8130,             8104,             8072,
+            8034,             7994,             7946,             7896,
+            7840,             7778,             7714,             7644,
+            7568,             7490,             7406,             7318,
+            7226,             7128,             7026,             6922,
+            6812,             6698,             6580,             6458,
+            6332,             6204,             6070,             5934,
+            5792,             5648,             5502,             5352,
+            5198,             5040,             4880,             4718,
+            4552,             4382,             4212,             4038,
+            3862,             3684,             3502,             3320,
+            3136,             2948,             2760,             2570,
+            2378,             2186,             1990,             1794,
+            1598,             1400,             1202,             1002,
+             802,              602,              402,              202,
+               0,             -202,             -402,             -602,
+            -802,            -1002,            -1202,            -1400,
+           -1598,            -1794,            -1990,            -2186,
+           -2378,            -2570,            -2760,            -2948,
+           -3136,            -3320,            -3502,            -3684,
+           -3862,            -4038,            -4212,            -4382,
+           -4552,            -4718,            -4880,            -5040,
+           -5198,            -5352,            -5502,            -5648,
+           -5792,            -5934,            -6070,            -6204,
+           -6332,            -6458,            -6580,            -6698,
+           -6812,            -6922,            -7026,            -7128,
+           -7226,            -7318,            -7406,            -7490,
+           -7568,            -7644,            -7714,            -7778,
+           -7840,            -7896,            -7946,            -7994,
+           -8034,            -8072,            -8104,            -8130,
+           -8152,            -8170,            -8182,            -8190,
+           -8192
+};
diff --git a/opus/silk/tables.h b/opus/silk/tables.h
new file mode 100644 (file)
index 0000000..8b0380e
--- /dev/null
@@ -0,0 +1,120 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_TABLES_H
+#define SILK_TABLES_H
+
+#include "define.h"
+#include "structs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Entropy coding tables (with size in bytes indicated) */
+extern const opus_uint8  silk_gain_iCDF[ 3 ][ N_LEVELS_QGAIN / 8 ];                                 /* 24 */
+extern const opus_uint8  silk_delta_gain_iCDF[ MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 ];   /* 41 */
+
+extern const opus_uint8  silk_pitch_lag_iCDF[ 2 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) ];/* 32 */
+extern const opus_uint8  silk_pitch_delta_iCDF[ 21 ];                                               /*  21 */
+extern const opus_uint8  silk_pitch_contour_iCDF[ 34 ];                                             /*  34 */
+extern const opus_uint8  silk_pitch_contour_NB_iCDF[ 11 ];                                          /*  11 */
+extern const opus_uint8  silk_pitch_contour_10_ms_iCDF[ 12 ];                                       /*  12 */
+extern const opus_uint8  silk_pitch_contour_10_ms_NB_iCDF[ 3 ];                                     /*   3 */
+
+extern const opus_uint8  silk_pulses_per_block_iCDF[ N_RATE_LEVELS ][ SILK_MAX_PULSES + 2 ];        /* 180 */
+extern const opus_uint8  silk_pulses_per_block_BITS_Q5[ N_RATE_LEVELS - 1 ][ SILK_MAX_PULSES + 2 ]; /* 162 */
+
+extern const opus_uint8  silk_rate_levels_iCDF[ 2 ][ N_RATE_LEVELS - 1 ];                           /*  18 */
+extern const opus_uint8  silk_rate_levels_BITS_Q5[ 2 ][ N_RATE_LEVELS - 1 ];                        /*  18 */
+
+extern const opus_uint8  silk_max_pulses_table[ 4 ];                                                /*   4 */
+
+extern const opus_uint8  silk_shell_code_table0[ 152 ];                                             /* 152 */
+extern const opus_uint8  silk_shell_code_table1[ 152 ];                                             /* 152 */
+extern const opus_uint8  silk_shell_code_table2[ 152 ];                                             /* 152 */
+extern const opus_uint8  silk_shell_code_table3[ 152 ];                                             /* 152 */
+extern const opus_uint8  silk_shell_code_table_offsets[ SILK_MAX_PULSES + 1 ];                      /*  17 */
+
+extern const opus_uint8  silk_lsb_iCDF[ 2 ];                                                        /*   2 */
+
+extern const opus_uint8  silk_sign_iCDF[ 42 ];                                                      /*  42 */
+
+extern const opus_uint8  silk_uniform3_iCDF[ 3 ];                                                   /*   3 */
+extern const opus_uint8  silk_uniform4_iCDF[ 4 ];                                                   /*   4 */
+extern const opus_uint8  silk_uniform5_iCDF[ 5 ];                                                   /*   5 */
+extern const opus_uint8  silk_uniform6_iCDF[ 6 ];                                                   /*   6 */
+extern const opus_uint8  silk_uniform8_iCDF[ 8 ];                                                   /*   8 */
+
+extern const opus_uint8  silk_NLSF_EXT_iCDF[ 7 ];                                                   /*   7 */
+
+extern const opus_uint8  silk_LTP_per_index_iCDF[ 3 ];                                              /*   3 */
+extern const opus_uint8  * const silk_LTP_gain_iCDF_ptrs[ NB_LTP_CBKS ];                            /*   3 */
+extern const opus_uint8  * const silk_LTP_gain_BITS_Q5_ptrs[ NB_LTP_CBKS ];                         /*   3 */
+extern const opus_int8   * const silk_LTP_vq_ptrs_Q7[ NB_LTP_CBKS ];                                /* 168 */
+extern const opus_uint8  * const silk_LTP_vq_gain_ptrs_Q7[NB_LTP_CBKS];
+extern const opus_int8   silk_LTP_vq_sizes[ NB_LTP_CBKS ];                                          /*   3 */
+
+extern const opus_uint8  silk_LTPscale_iCDF[ 3 ];                                                   /*   4 */
+extern const opus_int16  silk_LTPScales_table_Q14[ 3 ];                                             /*   6 */
+
+extern const opus_uint8  silk_type_offset_VAD_iCDF[ 4 ];                                            /*   4 */
+extern const opus_uint8  silk_type_offset_no_VAD_iCDF[ 2 ];                                         /*   2 */
+
+extern const opus_int16  silk_stereo_pred_quant_Q13[ STEREO_QUANT_TAB_SIZE ];                       /*  32 */
+extern const opus_uint8  silk_stereo_pred_joint_iCDF[ 25 ];                                         /*  25 */
+extern const opus_uint8  silk_stereo_only_code_mid_iCDF[ 2 ];                                       /*   2 */
+
+extern const opus_uint8  * const silk_LBRR_flags_iCDF_ptr[ 2 ];                                     /*  10 */
+
+extern const opus_uint8  silk_NLSF_interpolation_factor_iCDF[ 5 ];                                  /*   5 */
+
+extern const silk_NLSF_CB_struct silk_NLSF_CB_WB;                                                   /* 1040 */
+extern const silk_NLSF_CB_struct silk_NLSF_CB_NB_MB;                                                /* 728 */
+
+/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */
+extern const opus_int32  silk_TargetRate_table_NB[  TARGET_RATE_TAB_SZ ];                           /*  32 */
+extern const opus_int32  silk_TargetRate_table_MB[  TARGET_RATE_TAB_SZ ];                           /*  32 */
+extern const opus_int32  silk_TargetRate_table_WB[  TARGET_RATE_TAB_SZ ];                           /*  32 */
+extern const opus_int16  silk_SNR_table_Q1[         TARGET_RATE_TAB_SZ ];                           /*  32 */
+
+/* Quantization offsets */
+extern const opus_int16  silk_Quantization_Offsets_Q10[ 2 ][ 2 ];                                   /*   8 */
+
+/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
+extern const opus_int32  silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ];           /*  60 */
+extern const opus_int32  silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ];           /*  60 */
+
+/* Rom table with cosine values */
+extern const opus_int16  silk_LSFCosTab_FIX_Q12[ LSF_COS_TAB_SZ_FIX + 1 ];                          /* 258 */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/opus/silk/tables_LTP.c b/opus/silk/tables_LTP.c
new file mode 100644 (file)
index 0000000..5e12c86
--- /dev/null
@@ -0,0 +1,294 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+const opus_uint8 silk_LTP_per_index_iCDF[3] = {
+       179,     99,      0
+};
+
+static const opus_uint8 silk_LTP_gain_iCDF_0[8] = {
+        71,     56,     43,     30,     21,     12,      6,      0
+};
+
+static const opus_uint8 silk_LTP_gain_iCDF_1[16] = {
+       199,    165,    144,    124,    109,     96,     84,     71,
+        61,     51,     42,     32,     23,     15,      8,      0
+};
+
+static const opus_uint8 silk_LTP_gain_iCDF_2[32] = {
+       241,    225,    211,    199,    187,    175,    164,    153,
+       142,    132,    123,    114,    105,     96,     88,     80,
+        72,     64,     57,     50,     44,     38,     33,     29,
+        24,     20,     16,     12,      9,      5,      2,      0
+};
+
+static const opus_uint8 silk_LTP_gain_BITS_Q5_0[8] = {
+        15,    131,    138,    138,    155,    155,    173,    173
+};
+
+static const opus_uint8 silk_LTP_gain_BITS_Q5_1[16] = {
+        69,     93,    115,    118,    131,    138,    141,    138,
+       150,    150,    155,    150,    155,    160,    166,    160
+};
+
+static const opus_uint8 silk_LTP_gain_BITS_Q5_2[32] = {
+       131,    128,    134,    141,    141,    141,    145,    145,
+       145,    150,    155,    155,    155,    155,    160,    160,
+       160,    160,    166,    166,    173,    173,    182,    192,
+       182,    192,    192,    192,    205,    192,    205,    224
+};
+
+const opus_uint8 * const silk_LTP_gain_iCDF_ptrs[NB_LTP_CBKS] = {
+    silk_LTP_gain_iCDF_0,
+    silk_LTP_gain_iCDF_1,
+    silk_LTP_gain_iCDF_2
+};
+
+const opus_uint8 * const silk_LTP_gain_BITS_Q5_ptrs[NB_LTP_CBKS] = {
+    silk_LTP_gain_BITS_Q5_0,
+    silk_LTP_gain_BITS_Q5_1,
+    silk_LTP_gain_BITS_Q5_2
+};
+
+static const opus_int8 silk_LTP_gain_vq_0[8][5] =
+{
+{
+         4,      6,     24,      7,      5
+},
+{
+         0,      0,      2,      0,      0
+},
+{
+        12,     28,     41,     13,     -4
+},
+{
+        -9,     15,     42,     25,     14
+},
+{
+         1,     -2,     62,     41,     -9
+},
+{
+       -10,     37,     65,     -4,      3
+},
+{
+        -6,      4,     66,      7,     -8
+},
+{
+        16,     14,     38,     -3,     33
+}
+};
+
+static const opus_int8 silk_LTP_gain_vq_1[16][5] =
+{
+{
+        13,     22,     39,     23,     12
+},
+{
+        -1,     36,     64,     27,     -6
+},
+{
+        -7,     10,     55,     43,     17
+},
+{
+         1,      1,      8,      1,      1
+},
+{
+         6,    -11,     74,     53,     -9
+},
+{
+       -12,     55,     76,    -12,      8
+},
+{
+        -3,      3,     93,     27,     -4
+},
+{
+        26,     39,     59,      3,     -8
+},
+{
+         2,      0,     77,     11,      9
+},
+{
+        -8,     22,     44,     -6,      7
+},
+{
+        40,      9,     26,      3,      9
+},
+{
+        -7,     20,    101,     -7,      4
+},
+{
+         3,     -8,     42,     26,      0
+},
+{
+       -15,     33,     68,      2,     23
+},
+{
+        -2,     55,     46,     -2,     15
+},
+{
+         3,     -1,     21,     16,     41
+}
+};
+
+static const opus_int8 silk_LTP_gain_vq_2[32][5] =
+{
+{
+        -6,     27,     61,     39,      5
+},
+{
+       -11,     42,     88,      4,      1
+},
+{
+        -2,     60,     65,      6,     -4
+},
+{
+        -1,     -5,     73,     56,      1
+},
+{
+        -9,     19,     94,     29,     -9
+},
+{
+         0,     12,     99,      6,      4
+},
+{
+         8,    -19,    102,     46,    -13
+},
+{
+         3,      2,     13,      3,      2
+},
+{
+         9,    -21,     84,     72,    -18
+},
+{
+       -11,     46,    104,    -22,      8
+},
+{
+        18,     38,     48,     23,      0
+},
+{
+       -16,     70,     83,    -21,     11
+},
+{
+         5,    -11,    117,     22,     -8
+},
+{
+        -6,     23,    117,    -12,      3
+},
+{
+         3,     -8,     95,     28,      4
+},
+{
+       -10,     15,     77,     60,    -15
+},
+{
+        -1,      4,    124,      2,     -4
+},
+{
+         3,     38,     84,     24,    -25
+},
+{
+         2,     13,     42,     13,     31
+},
+{
+        21,     -4,     56,     46,     -1
+},
+{
+        -1,     35,     79,    -13,     19
+},
+{
+        -7,     65,     88,     -9,    -14
+},
+{
+        20,      4,     81,     49,    -29
+},
+{
+        20,      0,     75,      3,    -17
+},
+{
+         5,     -9,     44,     92,     -8
+},
+{
+         1,     -3,     22,     69,     31
+},
+{
+        -6,     95,     41,    -12,      5
+},
+{
+        39,     67,     16,     -4,      1
+},
+{
+         0,     -6,    120,     55,    -36
+},
+{
+       -13,     44,    122,      4,    -24
+},
+{
+        81,      5,     11,      3,      7
+},
+{
+         2,      0,      9,     10,     88
+}
+};
+
+const opus_int8 * const silk_LTP_vq_ptrs_Q7[NB_LTP_CBKS] = {
+    (opus_int8 *)&silk_LTP_gain_vq_0[0][0],
+    (opus_int8 *)&silk_LTP_gain_vq_1[0][0],
+    (opus_int8 *)&silk_LTP_gain_vq_2[0][0]
+};
+
+/* Maximum frequency-dependent response of the pitch taps above,
+   computed as max(abs(freqz(taps))) */
+static const opus_uint8 silk_LTP_gain_vq_0_gain[8] = {
+      46,      2,     90,     87,     93,     91,     82,     98
+};
+
+static const opus_uint8 silk_LTP_gain_vq_1_gain[16] = {
+     109,    120,    118,     12,    113,    115,    117,    119,
+      99,     59,     87,    111,     63,    111,    112,     80
+};
+
+static const opus_uint8 silk_LTP_gain_vq_2_gain[32] = {
+     126,    124,    125,    124,    129,    121,    126,     23,
+     132,    127,    127,    127,    126,    127,    122,    133,
+     130,    134,    101,    118,    119,    145,    126,     86,
+     124,    120,    123,    119,    170,    173,    107,    109
+};
+
+const opus_uint8 * const silk_LTP_vq_gain_ptrs_Q7[NB_LTP_CBKS] = {
+    &silk_LTP_gain_vq_0_gain[0],
+    &silk_LTP_gain_vq_1_gain[0],
+    &silk_LTP_gain_vq_2_gain[0]
+};
+
+const opus_int8 silk_LTP_vq_sizes[NB_LTP_CBKS] = {
+    8, 16, 32
+};
diff --git a/opus/silk/tables_NLSF_CB_NB_MB.c b/opus/silk/tables_NLSF_CB_NB_MB.c
new file mode 100644 (file)
index 0000000..195d5b9
--- /dev/null
@@ -0,0 +1,195 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+static const opus_uint8 silk_NLSF_CB1_NB_MB_Q8[ 320 ] = {
+        12,     35,     60,     83,    108,    132,    157,    180,
+       206,    228,     15,     32,     55,     77,    101,    125,
+       151,    175,    201,    225,     19,     42,     66,     89,
+       114,    137,    162,    184,    209,    230,     12,     25,
+        50,     72,     97,    120,    147,    172,    200,    223,
+        26,     44,     69,     90,    114,    135,    159,    180,
+       205,    225,     13,     22,     53,     80,    106,    130,
+       156,    180,    205,    228,     15,     25,     44,     64,
+        90,    115,    142,    168,    196,    222,     19,     24,
+        62,     82,    100,    120,    145,    168,    190,    214,
+        22,     31,     50,     79,    103,    120,    151,    170,
+       203,    227,     21,     29,     45,     65,    106,    124,
+       150,    171,    196,    224,     30,     49,     75,     97,
+       121,    142,    165,    186,    209,    229,     19,     25,
+        52,     70,     93,    116,    143,    166,    192,    219,
+        26,     34,     62,     75,     97,    118,    145,    167,
+       194,    217,     25,     33,     56,     70,     91,    113,
+       143,    165,    196,    223,     21,     34,     51,     72,
+        97,    117,    145,    171,    196,    222,     20,     29,
+        50,     67,     90,    117,    144,    168,    197,    221,
+        22,     31,     48,     66,     95,    117,    146,    168,
+       196,    222,     24,     33,     51,     77,    116,    134,
+       158,    180,    200,    224,     21,     28,     70,     87,
+       106,    124,    149,    170,    194,    217,     26,     33,
+        53,     64,     83,    117,    152,    173,    204,    225,
+        27,     34,     65,     95,    108,    129,    155,    174,
+       210,    225,     20,     26,     72,     99,    113,    131,
+       154,    176,    200,    219,     34,     43,     61,     78,
+        93,    114,    155,    177,    205,    229,     23,     29,
+        54,     97,    124,    138,    163,    179,    209,    229,
+        30,     38,     56,     89,    118,    129,    158,    178,
+       200,    231,     21,     29,     49,     63,     85,    111,
+       142,    163,    193,    222,     27,     48,     77,    103,
+       133,    158,    179,    196,    215,    232,     29,     47,
+        74,     99,    124,    151,    176,    198,    220,    237,
+        33,     42,     61,     76,     93,    121,    155,    174,
+       207,    225,     29,     53,     87,    112,    136,    154,
+       170,    188,    208,    227,     24,     30,     52,     84,
+       131,    150,    166,    186,    203,    229,     37,     48,
+        64,     84,    104,    118,    156,    177,    201,    230
+};
+
+static const opus_int16 silk_NLSF_CB1_Wght_Q9[ 320 ] = {
+     2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287,
+     2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194,
+     2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354,
+     3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194,
+     2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314,
+     3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261,
+     3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114,
+     4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074,
+     3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221,
+     3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101,
+     2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367,
+     3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048,
+     3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127,
+     3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101,
+     2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114,
+     3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141,
+     3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114,
+     3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181,
+     3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127,
+     3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274,
+     3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540,
+     3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261,
+     3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247,
+     3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367,
+     3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167,
+     3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061,
+     2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553,
+     2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700,
+     3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380,
+     2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367,
+     3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207,
+     2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181
+};
+
+static const opus_uint8 silk_NLSF_CB1_iCDF_NB_MB[ 64 ] = {
+       212,    178,    148,    129,    108,     96,     85,     82,
+        79,     77,     61,     59,     57,     56,     51,     49,
+        48,     45,     42,     41,     40,     38,     36,     34,
+        31,     30,     21,     12,     10,      3,      1,      0,
+       255,    245,    244,    236,    233,    225,    217,    203,
+       190,    176,    175,    161,    149,    136,    125,    114,
+       102,     91,     81,     71,     60,     52,     43,     35,
+        28,     20,     19,     18,     12,     11,      5,      0
+};
+
+static const opus_uint8 silk_NLSF_CB2_SELECT_NB_MB[ 160 ] = {
+        16,      0,      0,      0,      0,     99,     66,     36,
+        36,     34,     36,     34,     34,     34,     34,     83,
+        69,     36,     52,     34,    116,    102,     70,     68,
+        68,    176,    102,     68,     68,     34,     65,     85,
+        68,     84,     36,    116,    141,    152,    139,    170,
+       132,    187,    184,    216,    137,    132,    249,    168,
+       185,    139,    104,    102,    100,     68,     68,    178,
+       218,    185,    185,    170,    244,    216,    187,    187,
+       170,    244,    187,    187,    219,    138,    103,    155,
+       184,    185,    137,    116,    183,    155,    152,    136,
+       132,    217,    184,    184,    170,    164,    217,    171,
+       155,    139,    244,    169,    184,    185,    170,    164,
+       216,    223,    218,    138,    214,    143,    188,    218,
+       168,    244,    141,    136,    155,    170,    168,    138,
+       220,    219,    139,    164,    219,    202,    216,    137,
+       168,    186,    246,    185,    139,    116,    185,    219,
+       185,    138,    100,    100,    134,    100,    102,     34,
+        68,     68,    100,     68,    168,    203,    221,    218,
+       168,    167,    154,    136,    104,     70,    164,    246,
+       171,    137,    139,    137,    155,    218,    219,    139
+};
+
+static const opus_uint8 silk_NLSF_CB2_iCDF_NB_MB[ 72 ] = {
+       255,    254,    253,    238,     14,      3,      2,      1,
+         0,    255,    254,    252,    218,     35,      3,      2,
+         1,      0,    255,    254,    250,    208,     59,      4,
+         2,      1,      0,    255,    254,    246,    194,     71,
+        10,      2,      1,      0,    255,    252,    236,    183,
+        82,      8,      2,      1,      0,    255,    252,    235,
+       180,     90,     17,      2,      1,      0,    255,    248,
+       224,    171,     97,     30,      4,      1,      0,    255,
+       254,    236,    173,     95,     37,      7,      1,      0
+};
+
+static const opus_uint8 silk_NLSF_CB2_BITS_NB_MB_Q5[ 72 ] = {
+       255,    255,    255,    131,      6,    145,    255,    255,
+       255,    255,    255,    236,     93,     15,     96,    255,
+       255,    255,    255,    255,    194,     83,     25,     71,
+       221,    255,    255,    255,    255,    162,     73,     34,
+        66,    162,    255,    255,    255,    210,    126,     73,
+        43,     57,    173,    255,    255,    255,    201,    125,
+        71,     48,     58,    130,    255,    255,    255,    166,
+       110,     73,     57,     62,    104,    210,    255,    255,
+       251,    123,     65,     55,     68,    100,    171,    255
+};
+
+static const opus_uint8 silk_NLSF_PRED_NB_MB_Q8[ 18 ] = {
+       179,    138,    140,    148,    151,    149,    153,    151,
+       163,    116,     67,     82,     59,     92,     72,    100,
+        89,     92
+};
+
+static const opus_int16 silk_NLSF_DELTA_MIN_NB_MB_Q15[ 11 ] = {
+       250,      3,      6,      3,      3,      3,      4,      3,
+         3,      3,    461
+};
+
+const silk_NLSF_CB_struct silk_NLSF_CB_NB_MB =
+{
+    32,
+    10,
+    SILK_FIX_CONST( 0.18, 16 ),
+    SILK_FIX_CONST( 1.0 / 0.18, 6 ),
+    silk_NLSF_CB1_NB_MB_Q8,
+    silk_NLSF_CB1_Wght_Q9,
+    silk_NLSF_CB1_iCDF_NB_MB,
+    silk_NLSF_PRED_NB_MB_Q8,
+    silk_NLSF_CB2_SELECT_NB_MB,
+    silk_NLSF_CB2_iCDF_NB_MB,
+    silk_NLSF_CB2_BITS_NB_MB_Q5,
+    silk_NLSF_DELTA_MIN_NB_MB_Q15,
+};
diff --git a/opus/silk/tables_NLSF_CB_WB.c b/opus/silk/tables_NLSF_CB_WB.c
new file mode 100644 (file)
index 0000000..5cc9f57
--- /dev/null
@@ -0,0 +1,234 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+static const opus_uint8 silk_NLSF_CB1_WB_Q8[ 512 ] = {
+         7,     23,     38,     54,     69,     85,    100,    116,
+       131,    147,    162,    178,    193,    208,    223,    239,
+        13,     25,     41,     55,     69,     83,     98,    112,
+       127,    142,    157,    171,    187,    203,    220,    236,
+        15,     21,     34,     51,     61,     78,     92,    106,
+       126,    136,    152,    167,    185,    205,    225,    240,
+        10,     21,     36,     50,     63,     79,     95,    110,
+       126,    141,    157,    173,    189,    205,    221,    237,
+        17,     20,     37,     51,     59,     78,     89,    107,
+       123,    134,    150,    164,    184,    205,    224,    240,
+        10,     15,     32,     51,     67,     81,     96,    112,
+       129,    142,    158,    173,    189,    204,    220,    236,
+         8,     21,     37,     51,     65,     79,     98,    113,
+       126,    138,    155,    168,    179,    192,    209,    218,
+        12,     15,     34,     55,     63,     78,     87,    108,
+       118,    131,    148,    167,    185,    203,    219,    236,
+        16,     19,     32,     36,     56,     79,     91,    108,
+       118,    136,    154,    171,    186,    204,    220,    237,
+        11,     28,     43,     58,     74,     89,    105,    120,
+       135,    150,    165,    180,    196,    211,    226,    241,
+         6,     16,     33,     46,     60,     75,     92,    107,
+       123,    137,    156,    169,    185,    199,    214,    225,
+        11,     19,     30,     44,     57,     74,     89,    105,
+       121,    135,    152,    169,    186,    202,    218,    234,
+        12,     19,     29,     46,     57,     71,     88,    100,
+       120,    132,    148,    165,    182,    199,    216,    233,
+        17,     23,     35,     46,     56,     77,     92,    106,
+       123,    134,    152,    167,    185,    204,    222,    237,
+        14,     17,     45,     53,     63,     75,     89,    107,
+       115,    132,    151,    171,    188,    206,    221,    240,
+         9,     16,     29,     40,     56,     71,     88,    103,
+       119,    137,    154,    171,    189,    205,    222,    237,
+        16,     19,     36,     48,     57,     76,     87,    105,
+       118,    132,    150,    167,    185,    202,    218,    236,
+        12,     17,     29,     54,     71,     81,     94,    104,
+       126,    136,    149,    164,    182,    201,    221,    237,
+        15,     28,     47,     62,     79,     97,    115,    129,
+       142,    155,    168,    180,    194,    208,    223,    238,
+         8,     14,     30,     45,     62,     78,     94,    111,
+       127,    143,    159,    175,    192,    207,    223,    239,
+        17,     30,     49,     62,     79,     92,    107,    119,
+       132,    145,    160,    174,    190,    204,    220,    235,
+        14,     19,     36,     45,     61,     76,     91,    108,
+       121,    138,    154,    172,    189,    205,    222,    238,
+        12,     18,     31,     45,     60,     76,     91,    107,
+       123,    138,    154,    171,    187,    204,    221,    236,
+        13,     17,     31,     43,     53,     70,     83,    103,
+       114,    131,    149,    167,    185,    203,    220,    237,
+        17,     22,     35,     42,     58,     78,     93,    110,
+       125,    139,    155,    170,    188,    206,    224,    240,
+         8,     15,     34,     50,     67,     83,     99,    115,
+       131,    146,    162,    178,    193,    209,    224,    239,
+        13,     16,     41,     66,     73,     86,     95,    111,
+       128,    137,    150,    163,    183,    206,    225,    241,
+        17,     25,     37,     52,     63,     75,     92,    102,
+       119,    132,    144,    160,    175,    191,    212,    231,
+        19,     31,     49,     65,     83,    100,    117,    133,
+       147,    161,    174,    187,    200,    213,    227,    242,
+        18,     31,     52,     68,     88,    103,    117,    126,
+       138,    149,    163,    177,    192,    207,    223,    239,
+        16,     29,     47,     61,     76,     90,    106,    119,
+       133,    147,    161,    176,    193,    209,    224,    240,
+        15,     21,     35,     50,     61,     73,     86,     97,
+       110,    119,    129,    141,    175,    198,    218,    237
+};
+
+static const opus_int16 silk_NLSF_CB1_WB_Wght_Q9[ 512 ] = {
+     3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846,
+     3216, 3085, 2972, 3056, 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726,
+     3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925,
+     3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, 2888, 2888, 2888, 2753,
+     5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888,
+     4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726,
+     3620, 3019, 2972, 3056, 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991,
+     5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673,
+     5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, 2846, 2793, 2846, 2700,
+     3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963,
+     4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873,
+     3760, 3760, 3244, 3103, 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660,
+     3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580,
+     3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, 2647, 2647, 2846, 2806,
+     5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753,
+     4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806,
+     5081, 5054, 3047, 3545, 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620,
+     4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753,
+     3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, 3056, 3010, 2963, 2846,
+     4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846,
+     2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740,
+     4229, 4149, 3310, 3347, 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793,
+     4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780,
+     4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, 2687, 2740, 2793, 2700,
+     4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888,
+     4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888,
+     5174, 4921, 2261, 3432, 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925,
+     3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434,
+     2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, 3150, 3103, 3010, 3010,
+     2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846,
+     3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888,
+     3920, 3967, 3010, 3197, 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607
+};
+
+static const opus_uint8 silk_NLSF_CB1_iCDF_WB[ 64 ] = {
+       225,    204,    201,    184,    183,    175,    158,    154,
+       153,    135,    119,    115,    113,    110,    109,     99,
+        98,     95,     79,     68,     52,     50,     48,     45,
+        43,     32,     31,     27,     18,     10,      3,      0,
+       255,    251,    235,    230,    212,    201,    196,    182,
+       167,    166,    163,    151,    138,    124,    110,    104,
+        90,     78,     76,     70,     69,     57,     45,     34,
+        24,     21,     11,      6,      5,      4,      3,      0
+};
+
+static const opus_uint8 silk_NLSF_CB2_SELECT_WB[ 256 ] = {
+         0,      0,      0,      0,      0,      0,      0,      1,
+       100,    102,    102,     68,     68,     36,     34,     96,
+       164,    107,    158,    185,    180,    185,    139,    102,
+        64,     66,     36,     34,     34,      0,      1,     32,
+       208,    139,    141,    191,    152,    185,    155,    104,
+        96,    171,    104,    166,    102,    102,    102,    132,
+         1,      0,      0,      0,      0,     16,     16,      0,
+        80,    109,     78,    107,    185,    139,    103,    101,
+       208,    212,    141,    139,    173,    153,    123,    103,
+        36,      0,      0,      0,      0,      0,      0,      1,
+        48,      0,      0,      0,      0,      0,      0,     32,
+        68,    135,    123,    119,    119,    103,     69,     98,
+        68,    103,    120,    118,    118,    102,     71,     98,
+       134,    136,    157,    184,    182,    153,    139,    134,
+       208,    168,    248,     75,    189,    143,    121,    107,
+        32,     49,     34,     34,     34,      0,     17,      2,
+       210,    235,    139,    123,    185,    137,    105,    134,
+        98,    135,    104,    182,    100,    183,    171,    134,
+       100,     70,     68,     70,     66,     66,     34,    131,
+        64,    166,    102,     68,     36,      2,      1,      0,
+       134,    166,    102,     68,     34,     34,     66,    132,
+       212,    246,    158,    139,    107,    107,     87,    102,
+       100,    219,    125,    122,    137,    118,    103,    132,
+       114,    135,    137,    105,    171,    106,     50,     34,
+       164,    214,    141,    143,    185,    151,    121,    103,
+       192,     34,      0,      0,      0,      0,      0,      1,
+       208,    109,     74,    187,    134,    249,    159,    137,
+       102,    110,    154,    118,     87,    101,    119,    101,
+         0,      2,      0,     36,     36,     66,     68,     35,
+        96,    164,    102,    100,     36,      0,      2,     33,
+       167,    138,    174,    102,    100,     84,      2,      2,
+       100,    107,    120,    119,     36,    197,     24,      0
+};
+
+static const opus_uint8 silk_NLSF_CB2_iCDF_WB[ 72 ] = {
+       255,    254,    253,    244,     12,      3,      2,      1,
+         0,    255,    254,    252,    224,     38,      3,      2,
+         1,      0,    255,    254,    251,    209,     57,      4,
+         2,      1,      0,    255,    254,    244,    195,     69,
+         4,      2,      1,      0,    255,    251,    232,    184,
+        84,      7,      2,      1,      0,    255,    254,    240,
+       186,     86,     14,      2,      1,      0,    255,    254,
+       239,    178,     91,     30,      5,      1,      0,    255,
+       248,    227,    177,    100,     19,      2,      1,      0
+};
+
+static const opus_uint8 silk_NLSF_CB2_BITS_WB_Q5[ 72 ] = {
+       255,    255,    255,    156,      4,    154,    255,    255,
+       255,    255,    255,    227,    102,     15,     92,    255,
+       255,    255,    255,    255,    213,     83,     24,     72,
+       236,    255,    255,    255,    255,    150,     76,     33,
+        63,    214,    255,    255,    255,    190,    121,     77,
+        43,     55,    185,    255,    255,    255,    245,    137,
+        71,     43,     59,    139,    255,    255,    255,    255,
+       131,     66,     50,     66,    107,    194,    255,    255,
+       166,    116,     76,     55,     53,    125,    255,    255
+};
+
+static const opus_uint8 silk_NLSF_PRED_WB_Q8[ 30 ] = {
+       175,    148,    160,    176,    178,    173,    174,    164,
+       177,    174,    196,    182,    198,    192,    182,     68,
+        62,     66,     60,     72,    117,     85,     90,    118,
+       136,    151,    142,    160,    142,    155
+};
+
+static const opus_int16 silk_NLSF_DELTA_MIN_WB_Q15[ 17 ] = {
+       100,      3,     40,      3,      3,      3,      5,     14,
+        14,     10,     11,      3,      8,      9,      7,      3,
+       347
+};
+
+const silk_NLSF_CB_struct silk_NLSF_CB_WB =
+{
+    32,
+    16,
+    SILK_FIX_CONST( 0.15, 16 ),
+    SILK_FIX_CONST( 1.0 / 0.15, 6 ),
+    silk_NLSF_CB1_WB_Q8,
+    silk_NLSF_CB1_WB_Wght_Q9,
+    silk_NLSF_CB1_iCDF_WB,
+    silk_NLSF_PRED_WB_Q8,
+    silk_NLSF_CB2_SELECT_WB,
+    silk_NLSF_CB2_iCDF_WB,
+    silk_NLSF_CB2_BITS_WB_Q5,
+    silk_NLSF_DELTA_MIN_WB_Q15,
+};
+
diff --git a/opus/silk/tables_gain.c b/opus/silk/tables_gain.c
new file mode 100644 (file)
index 0000000..37e41d8
--- /dev/null
@@ -0,0 +1,63 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+const opus_uint8 silk_gain_iCDF[ 3 ][ N_LEVELS_QGAIN / 8 ] =
+{
+{
+       224,    112,     44,     15,      3,      2,      1,      0
+},
+{
+       254,    237,    192,    132,     70,     23,      4,      0
+},
+{
+       255,    252,    226,    155,     61,     11,      2,      0
+}
+};
+
+const opus_uint8 silk_delta_gain_iCDF[ MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 ] = {
+       250,    245,    234,    203,     71,     50,     42,     38,
+        35,     33,     31,     29,     28,     27,     26,     25,
+        24,     23,     22,     21,     20,     19,     18,     17,
+        16,     15,     14,     13,     12,     11,     10,      9,
+         8,      7,      6,      5,      4,      3,      2,      1,
+         0
+};
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/opus/silk/tables_other.c b/opus/silk/tables_other.c
new file mode 100644 (file)
index 0000000..398686b
--- /dev/null
@@ -0,0 +1,138 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "structs.h"
+#include "define.h"
+#include "tables.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */
+const opus_int32 silk_TargetRate_table_NB[ TARGET_RATE_TAB_SZ ] = {
+    0,      8000,   9400,   11500,  13500,  17500,  25000,  MAX_TARGET_RATE_BPS
+};
+const opus_int32 silk_TargetRate_table_MB[ TARGET_RATE_TAB_SZ ] = {
+    0,      9000,   12000,  14500,  18500,  24500,  35500,  MAX_TARGET_RATE_BPS
+};
+const opus_int32 silk_TargetRate_table_WB[ TARGET_RATE_TAB_SZ ] = {
+    0,      10500,  14000,  17000,  21500,  28500,  42000,  MAX_TARGET_RATE_BPS
+};
+const opus_int16 silk_SNR_table_Q1[ TARGET_RATE_TAB_SZ ] = {
+    18,     29,     38,     40,     46,     52,     62,     84
+};
+
+/* Tables for stereo predictor coding */
+const opus_int16 silk_stereo_pred_quant_Q13[ STEREO_QUANT_TAB_SIZE ] = {
+    -13732, -10050, -8266, -7526, -6500, -5000, -2950,  -820,
+       820,   2950,  5000,  6500,  7526,  8266, 10050, 13732
+};
+const opus_uint8  silk_stereo_pred_joint_iCDF[ 25 ] = {
+    249, 247, 246, 245, 244,
+    234, 210, 202, 201, 200,
+    197, 174,  82,  59,  56,
+     55,  54,  46,  22,  12,
+     11,  10,   9,   7,   0
+};
+const opus_uint8  silk_stereo_only_code_mid_iCDF[ 2 ] = { 64, 0 };
+
+/* Tables for LBRR flags */
+static const opus_uint8 silk_LBRR_flags_2_iCDF[ 3 ] = { 203, 150, 0 };
+static const opus_uint8 silk_LBRR_flags_3_iCDF[ 7 ] = { 215, 195, 166, 125, 110, 82, 0 };
+const opus_uint8 * const silk_LBRR_flags_iCDF_ptr[ 2 ] = {
+    silk_LBRR_flags_2_iCDF,
+    silk_LBRR_flags_3_iCDF
+};
+
+/* Table for LSB coding */
+const opus_uint8 silk_lsb_iCDF[ 2 ] = { 120, 0 };
+
+/* Tables for LTPScale */
+const opus_uint8 silk_LTPscale_iCDF[ 3 ] = { 128, 64, 0 };
+
+/* Tables for signal type and offset coding */
+const opus_uint8 silk_type_offset_VAD_iCDF[ 4 ] = {
+       232,    158,    10,      0
+};
+const opus_uint8 silk_type_offset_no_VAD_iCDF[ 2 ] = {
+       230,      0
+};
+
+/* Tables for NLSF interpolation factor */
+const opus_uint8 silk_NLSF_interpolation_factor_iCDF[ 5 ] = { 243, 221, 192, 181, 0 };
+
+/* Quantization offsets */
+const opus_int16  silk_Quantization_Offsets_Q10[ 2 ][ 2 ] = {
+    { OFFSET_UVL_Q10, OFFSET_UVH_Q10 }, { OFFSET_VL_Q10, OFFSET_VH_Q10 }
+};
+
+/* Table for LTPScale */
+const opus_int16 silk_LTPScales_table_Q14[ 3 ] = { 15565, 12288, 8192 };
+
+/* Uniform entropy tables */
+const opus_uint8 silk_uniform3_iCDF[ 3 ] = { 171, 85, 0 };
+const opus_uint8 silk_uniform4_iCDF[ 4 ] = { 192, 128, 64, 0 };
+const opus_uint8 silk_uniform5_iCDF[ 5 ] = { 205, 154, 102, 51, 0 };
+const opus_uint8 silk_uniform6_iCDF[ 6 ] = { 213, 171, 128, 85, 43, 0 };
+const opus_uint8 silk_uniform8_iCDF[ 8 ] = { 224, 192, 160, 128, 96, 64, 32, 0 };
+
+const opus_uint8 silk_NLSF_EXT_iCDF[ 7 ] = { 100, 40, 16, 7, 3, 1, 0 };
+
+/*  Elliptic/Cauer filters designed with 0.1 dB passband ripple,
+        80 dB minimum stopband attenuation, and
+        [0.95 : 0.15 : 0.35] normalized cut off frequencies. */
+
+/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
+const opus_int32 silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ] =
+{
+{    250767114,  501534038,  250767114  },
+{    209867381,  419732057,  209867381  },
+{    170987846,  341967853,  170987846  },
+{    131531482,  263046905,  131531482  },
+{     89306658,  178584282,   89306658  }
+};
+
+/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
+const opus_int32 silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ] =
+{
+{    506393414,  239854379  },
+{    411067935,  169683996  },
+{    306733530,  116694253  },
+{    185807084,   77959395  },
+{     35497197,   57401098  }
+};
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/opus/silk/tables_pitch_lag.c b/opus/silk/tables_pitch_lag.c
new file mode 100644 (file)
index 0000000..e80cc59
--- /dev/null
@@ -0,0 +1,69 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+const opus_uint8 silk_pitch_lag_iCDF[ 2 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) ] = {
+       253,    250,    244,    233,    212,    182,    150,    131,
+       120,    110,     98,     85,     72,     60,     49,     40,
+        32,     25,     19,     15,     13,     11,      9,      8,
+         7,      6,      5,      4,      3,      2,      1,      0
+};
+
+const opus_uint8 silk_pitch_delta_iCDF[21] = {
+       210,    208,    206,    203,    199,    193,    183,    168,
+       142,    104,     74,     52,     37,     27,     20,     14,
+        10,      6,      4,      2,      0
+};
+
+const opus_uint8 silk_pitch_contour_iCDF[34] = {
+       223,    201,    183,    167,    152,    138,    124,    111,
+        98,     88,     79,     70,     62,     56,     50,     44,
+        39,     35,     31,     27,     24,     21,     18,     16,
+        14,     12,     10,      8,      6,      4,      3,      2,
+         1,      0
+};
+
+const opus_uint8 silk_pitch_contour_NB_iCDF[11] = {
+       188,    176,    155,    138,    119,     97,     67,     43,
+        26,     10,      0
+};
+
+const opus_uint8 silk_pitch_contour_10_ms_iCDF[12] = {
+       165,    119,     80,     61,     47,     35,     27,     20,
+        14,      9,      4,      0
+};
+
+const opus_uint8 silk_pitch_contour_10_ms_NB_iCDF[3] = {
+       113,     63,      0
+};
+
+
diff --git a/opus/silk/tables_pulses_per_block.c b/opus/silk/tables_pulses_per_block.c
new file mode 100644 (file)
index 0000000..c7c01c8
--- /dev/null
@@ -0,0 +1,264 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "tables.h"
+
+const opus_uint8 silk_max_pulses_table[ 4 ] = {
+         8,     10,     12,     16
+};
+
+const opus_uint8 silk_pulses_per_block_iCDF[ 10 ][ 18 ] = {
+{
+       125,     51,     26,     18,     15,     12,     11,     10,
+         9,      8,      7,      6,      5,      4,      3,      2,
+         1,      0
+},
+{
+       198,    105,     45,     22,     15,     12,     11,     10,
+         9,      8,      7,      6,      5,      4,      3,      2,
+         1,      0
+},
+{
+       213,    162,    116,     83,     59,     43,     32,     24,
+        18,     15,     12,      9,      7,      6,      5,      3,
+         2,      0
+},
+{
+       239,    187,    116,     59,     28,     16,     11,     10,
+         9,      8,      7,      6,      5,      4,      3,      2,
+         1,      0
+},
+{
+       250,    229,    188,    135,     86,     51,     30,     19,
+        13,     10,      8,      6,      5,      4,      3,      2,
+         1,      0
+},
+{
+       249,    235,    213,    185,    156,    128,    103,     83,
+        66,     53,     42,     33,     26,     21,     17,     13,
+        10,      0
+},
+{
+       254,    249,    235,    206,    164,    118,     77,     46,
+        27,     16,     10,      7,      5,      4,      3,      2,
+         1,      0
+},
+{
+       255,    253,    249,    239,    220,    191,    156,    119,
+        85,     57,     37,     23,     15,     10,      6,      4,
+         2,      0
+},
+{
+       255,    253,    251,    246,    237,    223,    203,    179,
+       152,    124,     98,     75,     55,     40,     29,     21,
+        15,      0
+},
+{
+       255,    254,    253,    247,    220,    162,    106,     67,
+        42,     28,     18,     12,      9,      6,      4,      3,
+         2,      0
+}
+};
+
+const opus_uint8 silk_pulses_per_block_BITS_Q5[ 9 ][ 18 ] = {
+{
+        31,     57,    107,    160,    205,    205,    255,    255,
+       255,    255,    255,    255,    255,    255,    255,    255,
+       255,    255
+},
+{
+        69,     47,     67,    111,    166,    205,    255,    255,
+       255,    255,    255,    255,    255,    255,    255,    255,
+       255,    255
+},
+{
+        82,     74,     79,     95,    109,    128,    145,    160,
+       173,    205,    205,    205,    224,    255,    255,    224,
+       255,    224
+},
+{
+       125,     74,     59,     69,     97,    141,    182,    255,
+       255,    255,    255,    255,    255,    255,    255,    255,
+       255,    255
+},
+{
+       173,    115,     85,     73,     76,     92,    115,    145,
+       173,    205,    224,    224,    255,    255,    255,    255,
+       255,    255
+},
+{
+       166,    134,    113,    102,    101,    102,    107,    118,
+       125,    138,    145,    155,    166,    182,    192,    192,
+       205,    150
+},
+{
+       224,    182,    134,    101,     83,     79,     85,     97,
+       120,    145,    173,    205,    224,    255,    255,    255,
+       255,    255
+},
+{
+       255,    224,    192,    150,    120,    101,     92,     89,
+        93,    102,    118,    134,    160,    182,    192,    224,
+       224,    224
+},
+{
+       255,    224,    224,    182,    155,    134,    118,    109,
+       104,    102,    106,    111,    118,    131,    145,    160,
+       173,    131
+}
+};
+
+const opus_uint8 silk_rate_levels_iCDF[ 2 ][ 9 ] =
+{
+{
+       241,    190,    178,    132,     87,     74,     41,     14,
+         0
+},
+{
+       223,    193,    157,    140,    106,     57,     39,     18,
+         0
+}
+};
+
+const opus_uint8 silk_rate_levels_BITS_Q5[ 2 ][ 9 ] =
+{
+{
+       131,     74,    141,     79,     80,    138,     95,    104,
+       134
+},
+{
+        95,     99,     91,    125,     93,     76,    123,    115,
+       123
+}
+};
+
+const opus_uint8 silk_shell_code_table0[ 152 ] = {
+       128,      0,    214,     42,      0,    235,    128,     21,
+         0,    244,    184,     72,     11,      0,    248,    214,
+       128,     42,      7,      0,    248,    225,    170,     80,
+        25,      5,      0,    251,    236,    198,    126,     54,
+        18,      3,      0,    250,    238,    211,    159,     82,
+        35,     15,      5,      0,    250,    231,    203,    168,
+       128,     88,     53,     25,      6,      0,    252,    238,
+       216,    185,    148,    108,     71,     40,     18,      4,
+         0,    253,    243,    225,    199,    166,    128,     90,
+        57,     31,     13,      3,      0,    254,    246,    233,
+       212,    183,    147,    109,     73,     44,     23,     10,
+         2,      0,    255,    250,    240,    223,    198,    166,
+       128,     90,     58,     33,     16,      6,      1,      0,
+       255,    251,    244,    231,    210,    181,    146,    110,
+        75,     46,     25,     12,      5,      1,      0,    255,
+       253,    248,    238,    221,    196,    164,    128,     92,
+        60,     35,     18,      8,      3,      1,      0,    255,
+       253,    249,    242,    229,    208,    180,    146,    110,
+        76,     48,     27,     14,      7,      3,      1,      0
+};
+
+const opus_uint8 silk_shell_code_table1[ 152 ] = {
+       129,      0,    207,     50,      0,    236,    129,     20,
+         0,    245,    185,     72,     10,      0,    249,    213,
+       129,     42,      6,      0,    250,    226,    169,     87,
+        27,      4,      0,    251,    233,    194,    130,     62,
+        20,      4,      0,    250,    236,    207,    160,     99,
+        47,     17,      3,      0,    255,    240,    217,    182,
+       131,     81,     41,     11,      1,      0,    255,    254,
+       233,    201,    159,    107,     61,     20,      2,      1,
+         0,    255,    249,    233,    206,    170,    128,     86,
+        50,     23,      7,      1,      0,    255,    250,    238,
+       217,    186,    148,    108,     70,     39,     18,      6,
+         1,      0,    255,    252,    243,    226,    200,    166,
+       128,     90,     56,     30,     13,      4,      1,      0,
+       255,    252,    245,    231,    209,    180,    146,    110,
+        76,     47,     25,     11,      4,      1,      0,    255,
+       253,    248,    237,    219,    194,    163,    128,     93,
+        62,     37,     19,      8,      3,      1,      0,    255,
+       254,    250,    241,    226,    205,    177,    145,    111,
+        79,     51,     30,     15,      6,      2,      1,      0
+};
+
+const opus_uint8 silk_shell_code_table2[ 152 ] = {
+       129,      0,    203,     54,      0,    234,    129,     23,
+         0,    245,    184,     73,     10,      0,    250,    215,
+       129,     41,      5,      0,    252,    232,    173,     86,
+        24,      3,      0,    253,    240,    200,    129,     56,
+        15,      2,      0,    253,    244,    217,    164,     94,
+        38,     10,      1,      0,    253,    245,    226,    189,
+       132,     71,     27,      7,      1,      0,    253,    246,
+       231,    203,    159,    105,     56,     23,      6,      1,
+         0,    255,    248,    235,    213,    179,    133,     85,
+        47,     19,      5,      1,      0,    255,    254,    243,
+       221,    194,    159,    117,     70,     37,     12,      2,
+         1,      0,    255,    254,    248,    234,    208,    171,
+       128,     85,     48,     22,      8,      2,      1,      0,
+       255,    254,    250,    240,    220,    189,    149,    107,
+        67,     36,     16,      6,      2,      1,      0,    255,
+       254,    251,    243,    227,    201,    166,    128,     90,
+        55,     29,     13,      5,      2,      1,      0,    255,
+       254,    252,    246,    234,    213,    183,    147,    109,
+        73,     43,     22,     10,      4,      2,      1,      0
+};
+
+const opus_uint8 silk_shell_code_table3[ 152 ] = {
+       130,      0,    200,     58,      0,    231,    130,     26,
+         0,    244,    184,     76,     12,      0,    249,    214,
+       130,     43,      6,      0,    252,    232,    173,     87,
+        24,      3,      0,    253,    241,    203,    131,     56,
+        14,      2,      0,    254,    246,    221,    167,     94,
+        35,      8,      1,      0,    254,    249,    232,    193,
+       130,     65,     23,      5,      1,      0,    255,    251,
+       239,    211,    162,     99,     45,     15,      4,      1,
+         0,    255,    251,    243,    223,    186,    131,     74,
+        33,     11,      3,      1,      0,    255,    252,    245,
+       230,    202,    158,    105,     57,     24,      8,      2,
+         1,      0,    255,    253,    247,    235,    214,    179,
+       132,     84,     44,     19,      7,      2,      1,      0,
+       255,    254,    250,    240,    223,    196,    159,    112,
+        69,     36,     15,      6,      2,      1,      0,    255,
+       254,    253,    245,    231,    209,    176,    136,     93,
+        55,     27,     11,      3,      2,      1,      0,    255,
+       254,    253,    252,    239,    221,    194,    158,    117,
+        76,     42,     18,      4,      3,      2,      1,      0
+};
+
+const opus_uint8 silk_shell_code_table_offsets[ 17 ] = {
+         0,      0,      2,      5,      9,     14,     20,     27,
+        35,     44,     54,     65,     77,     90,    104,    119,
+       135
+};
+
+const opus_uint8 silk_sign_iCDF[ 42 ] = {
+       254,     49,     67,     77,     82,     93,     99,
+       198,     11,     18,     24,     31,     36,     45,
+       255,     46,     66,     78,     87,     94,    104,
+       208,     14,     21,     32,     42,     51,     66,
+       255,     94,    104,    109,    112,    115,    118,
+       248,     53,     69,     80,     88,     95,    102
+};
diff --git a/opus/silk/tests/test_unit_LPC_inv_pred_gain.c b/opus/silk/tests/test_unit_LPC_inv_pred_gain.c
new file mode 100644 (file)
index 0000000..67067ce
--- /dev/null
@@ -0,0 +1,129 @@
+/***********************************************************************
+Copyright (c) 2017 Google Inc., 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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+***********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "celt/stack_alloc.h"
+#include "cpu_support.h"
+#include "SigProc_FIX.h"
+
+/* Computes the impulse response of the filter so we
+   can catch filters that are definitely unstable. Some
+   unstable filters may be classified as stable, but not
+   the other way around. */
+int check_stability(opus_int16 *A_Q12, int order) {
+    int i;
+    int j;
+    int sum_a, sum_abs_a;
+    sum_a = sum_abs_a = 0;
+    for( j = 0; j < order; j++ ) {
+        sum_a += A_Q12[ j ];
+        sum_abs_a += silk_abs( A_Q12[ j ] );
+    }
+    /* Check DC stability. */
+    if( sum_a >= 4096 ) {
+        return 0;
+    }
+    /* If the sum of absolute values is less than 1, the filter
+       has to be stable. */
+    if( sum_abs_a < 4096 ) {
+        return 1;
+    }
+    double y[SILK_MAX_ORDER_LPC] = {0};
+    y[0] = 1;
+    for( i = 0; i < 10000; i++ ) {
+        double sum = 0;
+        for( j = 0; j < order; j++ ) {
+            sum += y[ j ]*A_Q12[ j ];
+        }
+        for( j = order - 1; j > 0; j-- ) {
+            y[ j ] = y[ j - 1 ];
+        }
+        y[ 0 ] = sum*(1./4096);
+        /* If impulse response reaches +/- 10000, the filter
+           is definitely unstable. */
+        if( !(y[ 0 ] < 10000 && y[ 0 ] > -10000) ) {
+            return 0;
+        }
+        /* Test every 8 sample for low amplitude. */
+        if( ( i & 0x7 ) == 0 ) {
+            double amp = 0;
+            for( j = 0; j < order; j++ ) {
+                amp += fabs(y[j]);
+            }
+            if( amp < 0.00001 ) {
+                return 1;
+            }
+        }
+    }
+    return 1;
+}
+
+int main(void) {
+    const int arch = opus_select_arch();
+    /* Set to 10000 so all branches in C function are triggered */
+    const int loop_num = 10000;
+    int count = 0;
+    ALLOC_STACK;
+
+    /* FIXME: Make the seed random (with option to set it explicitly)
+       so we get wider coverage. */
+    srand(0);
+
+    printf("Testing silk_LPC_inverse_pred_gain() optimization ...\n");
+    for( count = 0; count < loop_num; count++ ) {
+        unsigned int i;
+        opus_int     order;
+        unsigned int shift;
+        opus_int16   A_Q12[ SILK_MAX_ORDER_LPC ];
+        opus_int32 gain;
+
+        for( order = 2; order <= SILK_MAX_ORDER_LPC; order += 2 ) { /* order must be even. */
+            for( shift = 0; shift < 16; shift++ ) { /* Different dynamic range. */
+                for( i = 0; i < SILK_MAX_ORDER_LPC; i++ ) {
+                    A_Q12[i] = ((opus_int16)rand()) >> shift;
+                }
+                gain = silk_LPC_inverse_pred_gain(A_Q12, order, arch);
+                /* Look for filters that silk_LPC_inverse_pred_gain() thinks are
+                   stable but definitely aren't. */
+                if( gain != 0 && !check_stability(A_Q12, order) ) {
+                    fprintf(stderr, "**Loop %4d failed!**\n", count);
+                    return 1;
+                }
+            }
+        }
+        if( !(count % 500) ) {
+            printf("Loop %4d passed\n", count);
+        }
+    }
+    printf("silk_LPC_inverse_pred_gain() optimization passed\n");
+    return 0;
+}
diff --git a/opus/silk/tuning_parameters.h b/opus/silk/tuning_parameters.h
new file mode 100644 (file)
index 0000000..d70275f
--- /dev/null
@@ -0,0 +1,155 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_TUNING_PARAMETERS_H
+#define SILK_TUNING_PARAMETERS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Decay time for bitreservoir */
+#define BITRESERVOIR_DECAY_TIME_MS                      500
+
+/*******************/
+/* Pitch estimator */
+/*******************/
+
+/* Level of noise floor for whitening filter LPC analysis in pitch analysis */
+#define FIND_PITCH_WHITE_NOISE_FRACTION                 1e-3f
+
+/* Bandwidth expansion for whitening filter in pitch analysis */
+#define FIND_PITCH_BANDWIDTH_EXPANSION                  0.99f
+
+/*********************/
+/* Linear prediction */
+/*********************/
+
+/* LPC analysis regularization */
+#define FIND_LPC_COND_FAC                               1e-5f
+
+/* Max cumulative LTP gain */
+#define MAX_SUM_LOG_GAIN_DB                             250.0f
+
+/* LTP analysis defines */
+#define LTP_CORR_INV_MAX                                0.03f
+
+/***********************/
+/* High pass filtering */
+/***********************/
+
+/* Smoothing parameters for low end of pitch frequency range estimation */
+#define VARIABLE_HP_SMTH_COEF1                          0.1f
+#define VARIABLE_HP_SMTH_COEF2                          0.015f
+#define VARIABLE_HP_MAX_DELTA_FREQ                      0.4f
+
+/* Min and max cut-off frequency values (-3 dB points) */
+#define VARIABLE_HP_MIN_CUTOFF_HZ                       60
+#define VARIABLE_HP_MAX_CUTOFF_HZ                       100
+
+/***********/
+/* Various */
+/***********/
+
+/* VAD threshold */
+#define SPEECH_ACTIVITY_DTX_THRES                       0.05f
+
+/* Speech Activity LBRR enable threshold */
+#define LBRR_SPEECH_ACTIVITY_THRES                      0.3f
+
+/*************************/
+/* Perceptual parameters */
+/*************************/
+
+/* reduction in coding SNR during low speech activity */
+#define BG_SNR_DECR_dB                                  2.0f
+
+/* factor for reducing quantization noise during voiced speech */
+#define HARM_SNR_INCR_dB                                2.0f
+
+/* factor for reducing quantization noise for unvoiced sparse signals */
+#define SPARSE_SNR_INCR_dB                              2.0f
+
+/* threshold for sparseness measure above which to use lower quantization offset during unvoiced */
+#define ENERGY_VARIATION_THRESHOLD_QNT_OFFSET           0.6f
+
+/* warping control */
+#define WARPING_MULTIPLIER                              0.015f
+
+/* fraction added to first autocorrelation value */
+#define SHAPE_WHITE_NOISE_FRACTION                      3e-5f
+
+/* noise shaping filter chirp factor */
+#define BANDWIDTH_EXPANSION                             0.94f
+
+/* harmonic noise shaping */
+#define HARMONIC_SHAPING                                0.3f
+
+/* extra harmonic noise shaping for high bitrates or noisy input */
+#define HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING       0.2f
+
+/* parameter for shaping noise towards higher frequencies */
+#define HP_NOISE_COEF                                   0.25f
+
+/* parameter for shaping noise even more towards higher frequencies during voiced speech */
+#define HARM_HP_NOISE_COEF                              0.35f
+
+/* parameter for applying a high-pass tilt to the input signal */
+#define INPUT_TILT                                      0.05f
+
+/* parameter for extra high-pass tilt to the input signal at high rates */
+#define HIGH_RATE_INPUT_TILT                            0.1f
+
+/* parameter for reducing noise at the very low frequencies */
+#define LOW_FREQ_SHAPING                                4.0f
+
+/* less reduction of noise at the very low frequencies for signals with low SNR at low frequencies */
+#define LOW_QUALITY_LOW_FREQ_SHAPING_DECR               0.5f
+
+/* subframe smoothing coefficient for HarmBoost, HarmShapeGain, Tilt (lower -> more smoothing) */
+#define SUBFR_SMTH_COEF                                 0.4f
+
+/* parameters defining the R/D tradeoff in the residual quantizer */
+#define LAMBDA_OFFSET                                   1.2f
+#define LAMBDA_SPEECH_ACT                               -0.2f
+#define LAMBDA_DELAYED_DECISIONS                        -0.05f
+#define LAMBDA_INPUT_QUALITY                            -0.1f
+#define LAMBDA_CODING_QUALITY                           -0.2f
+#define LAMBDA_QUANT_OFFSET                             0.8f
+
+/* Compensation in bitrate calculations for 10 ms modes */
+#define REDUCE_BITRATE_10_MS_BPS                        2200
+
+/* Maximum time before allowing a bandwidth transition */
+#define MAX_BANDWIDTH_SWITCH_DELAY_MS                   5000
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SILK_TUNING_PARAMETERS_H */
diff --git a/opus/silk/typedef.h b/opus/silk/typedef.h
new file mode 100644 (file)
index 0000000..97b7e70
--- /dev/null
@@ -0,0 +1,78 @@
+/***********************************************************************
+Copyright (c) 2006-2011, Skype Limited. 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 name of Internet Society, IETF or IETF Trust, nor the
+names of specific 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 SILK_TYPEDEF_H
+#define SILK_TYPEDEF_H
+
+#include "opus_types.h"
+#include "opus_defines.h"
+
+#ifndef FIXED_POINT
+# include <float.h>
+# define silk_float      float
+# define silk_float_MAX  FLT_MAX
+#endif
+
+#define silk_int64_MAX   ((opus_int64)0x7FFFFFFFFFFFFFFFLL)   /*  2^63 - 1 */
+#define silk_int64_MIN   ((opus_int64)0x8000000000000000LL)   /* -2^63 */
+#define silk_int32_MAX   0x7FFFFFFF                           /*  2^31 - 1 =  2147483647 */
+#define silk_int32_MIN   ((opus_int32)0x80000000)             /* -2^31     = -2147483648 */
+#define silk_int16_MAX   0x7FFF                               /*  2^15 - 1 =  32767 */
+#define silk_int16_MIN   ((opus_int16)0x8000)                 /* -2^15     = -32768 */
+#define silk_int8_MAX    0x7F                                 /*  2^7 - 1  =  127 */
+#define silk_int8_MIN    ((opus_int8)0x80)                    /* -2^7      = -128 */
+#define silk_uint8_MAX   0xFF                                 /*  2^8 - 1 = 255 */
+
+#define silk_TRUE        1
+#define silk_FALSE       0
+
+/* assertions */
+#if (defined _WIN32 && !defined _WINCE && !defined(__GNUC__) && !defined(NO_ASSERTS))
+# ifndef silk_assert
+#  include <crtdbg.h>      /* ASSERTE() */
+#  define silk_assert(COND)   _ASSERTE(COND)
+# endif
+#else
+# ifdef ENABLE_ASSERTIONS
+#  include <stdio.h>
+#  include <stdlib.h>
+#define silk_fatal(str) _silk_fatal(str, __FILE__, __LINE__);
+#ifdef __GNUC__
+__attribute__((noreturn))
+#endif
+static OPUS_INLINE void _silk_fatal(const char *str, const char *file, int line)
+{
+   fprintf (stderr, "Fatal (internal) error in %s, line %d: %s\n", file, line, str);
+   abort();
+}
+#  define silk_assert(COND) {if (!(COND)) {silk_fatal("assertion failed: " #COND);}}
+# else
+#  define silk_assert(COND)
+# endif
+#endif
+
+#endif /* SILK_TYPEDEF_H */
diff --git a/opus/silk/x86/NSQ_del_dec_sse.c b/opus/silk/x86/NSQ_del_dec_sse.c
new file mode 100644 (file)
index 0000000..c5212be
--- /dev/null
@@ -0,0 +1,859 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+#include "main.h"
+#include "celt/x86/x86cpu.h"
+
+#include "stack_alloc.h"
+
+typedef struct {
+    opus_int32 sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ];
+    opus_int32 RandState[ DECISION_DELAY ];
+    opus_int32 Q_Q10[     DECISION_DELAY ];
+    opus_int32 Xq_Q14[    DECISION_DELAY ];
+    opus_int32 Pred_Q15[  DECISION_DELAY ];
+    opus_int32 Shape_Q14[ DECISION_DELAY ];
+    opus_int32 sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];
+    opus_int32 LF_AR_Q14;
+    opus_int32 Seed;
+    opus_int32 SeedInit;
+    opus_int32 RD_Q10;
+} NSQ_del_dec_struct;
+
+typedef struct {
+    opus_int32 Q_Q10;
+    opus_int32 RD_Q10;
+    opus_int32 xq_Q14;
+    opus_int32 LF_AR_Q14;
+    opus_int32 sLTP_shp_Q14;
+    opus_int32 LPC_exc_Q14;
+} NSQ_sample_struct;
+
+typedef NSQ_sample_struct  NSQ_sample_pair[ 2 ];
+
+static OPUS_INLINE void silk_nsq_del_dec_scale_states_sse4_1(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int32    x_Q3[],                     /* I    Input in Q3                         */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    opus_int            nStatesDelayedDecision,     /* I    Number of del dec states            */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+);
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec_sse4_1(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay           /* I                                        */
+);
+
+void silk_NSQ_del_dec_sse4_1(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+)
+{
+    opus_int            i, k, lag, start_idx, LSF_interpolation_flag, Winner_ind, subfr;
+    opus_int            last_smple_idx, smpl_buf_idx, decisionDelay;
+    const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
+    opus_int16          *pxq;
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
+    opus_int32          HarmShapeFIRPacked_Q14;
+    opus_int            offset_Q10;
+    opus_int32          RDmin_Q10, Gain_Q10;
+    VARDECL( opus_int32, x_sc_Q10 );
+    VARDECL( opus_int32, delayedGain_Q10 );
+    VARDECL( NSQ_del_dec_struct, psDelDec );
+    NSQ_del_dec_struct  *psDD;
+    SAVE_STACK;
+
+    /* Set unvoiced lag to the previous one, overwrite later for voiced */
+    lag = NSQ->lagPrev;
+
+    silk_assert( NSQ->prev_gain_Q16 != 0 );
+
+    /* Initialize delayed decision states */
+    ALLOC( psDelDec, psEncC->nStatesDelayedDecision, NSQ_del_dec_struct );
+    silk_memset( psDelDec, 0, psEncC->nStatesDelayedDecision * sizeof( NSQ_del_dec_struct ) );
+    for( k = 0; k < psEncC->nStatesDelayedDecision; k++ ) {
+        psDD                 = &psDelDec[ k ];
+        psDD->Seed           = ( k + psIndices->Seed ) & 3;
+        psDD->SeedInit       = psDD->Seed;
+        psDD->RD_Q10         = 0;
+        psDD->LF_AR_Q14      = NSQ->sLF_AR_shp_Q14;
+        psDD->Shape_Q14[ 0 ] = NSQ->sLTP_shp_Q14[ psEncC->ltp_mem_length - 1 ];
+        silk_memcpy( psDD->sLPC_Q14, NSQ->sLPC_Q14, NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+        silk_memcpy( psDD->sAR2_Q14, NSQ->sAR2_Q14, sizeof( NSQ->sAR2_Q14 ) );
+    }
+
+    offset_Q10   = silk_Quantization_Offsets_Q10[ psIndices->signalType >> 1 ][ psIndices->quantOffsetType ];
+    smpl_buf_idx = 0; /* index of oldest samples */
+
+    decisionDelay = silk_min_int( DECISION_DELAY, psEncC->subfr_length );
+
+    /* For voiced frames limit the decision delay to lower than the pitch lag */
+    if( psIndices->signalType == TYPE_VOICED ) {
+        for( k = 0; k < psEncC->nb_subfr; k++ ) {
+            decisionDelay = silk_min_int( decisionDelay, pitchL[ k ] - LTP_ORDER / 2 - 1 );
+        }
+    } else {
+        if( lag > 0 ) {
+            decisionDelay = silk_min_int( decisionDelay, lag - LTP_ORDER / 2 - 1 );
+        }
+    }
+
+    if( psIndices->NLSFInterpCoef_Q2 == 4 ) {
+        LSF_interpolation_flag = 0;
+    } else {
+        LSF_interpolation_flag = 1;
+    }
+
+    ALLOC( sLTP_Q15,
+           psEncC->ltp_mem_length + psEncC->frame_length, opus_int32 );
+    ALLOC( sLTP, psEncC->ltp_mem_length + psEncC->frame_length, opus_int16 );
+    ALLOC( x_sc_Q10, psEncC->subfr_length, opus_int32 );
+    ALLOC( delayedGain_Q10, DECISION_DELAY, opus_int32 );
+    /* Set up pointers to start of sub frame */
+    pxq                   = &NSQ->xq[ psEncC->ltp_mem_length ];
+    NSQ->sLTP_shp_buf_idx = psEncC->ltp_mem_length;
+    NSQ->sLTP_buf_idx     = psEncC->ltp_mem_length;
+    subfr = 0;
+    for( k = 0; k < psEncC->nb_subfr; k++ ) {
+        A_Q12      = &PredCoef_Q12[ ( ( k >> 1 ) | ( 1 - LSF_interpolation_flag ) ) * MAX_LPC_ORDER ];
+        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER           ];
+        AR_shp_Q13 = &AR2_Q13[     k * MAX_SHAPE_LPC_ORDER ];
+
+        /* Noise shape parameters */
+        silk_assert( HarmShapeGain_Q14[ k ] >= 0 );
+        HarmShapeFIRPacked_Q14  =                          silk_RSHIFT( HarmShapeGain_Q14[ k ], 2 );
+        HarmShapeFIRPacked_Q14 |= silk_LSHIFT( (opus_int32)silk_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );
+
+        NSQ->rewhite_flag = 0;
+        if( psIndices->signalType == TYPE_VOICED ) {
+            /* Voiced */
+            lag = pitchL[ k ];
+
+            /* Re-whitening */
+            if( ( k & ( 3 - silk_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {
+                if( k == 2 ) {
+                    /* RESET DELAYED DECISIONS */
+                    /* Find winner */
+                    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;
+                    Winner_ind = 0;
+                    for( i = 1; i < psEncC->nStatesDelayedDecision; i++ ) {
+                        if( psDelDec[ i ].RD_Q10 < RDmin_Q10 ) {
+                            RDmin_Q10 = psDelDec[ i ].RD_Q10;
+                            Winner_ind = i;
+                        }
+                    }
+                    for( i = 0; i < psEncC->nStatesDelayedDecision; i++ ) {
+                        if( i != Winner_ind ) {
+                            psDelDec[ i ].RD_Q10 += ( silk_int32_MAX >> 4 );
+                            silk_assert( psDelDec[ i ].RD_Q10 >= 0 );
+                        }
+                    }
+
+                    /* Copy final part of signals from winner state to output and long-term filter states */
+                    psDD = &psDelDec[ Winner_ind ];
+                    last_smple_idx = smpl_buf_idx + decisionDelay;
+                    for( i = 0; i < decisionDelay; i++ ) {
+                        last_smple_idx = ( last_smple_idx - 1 ) % DECISION_DELAY;
+                        if( last_smple_idx < 0 ) last_smple_idx += DECISION_DELAY;
+                        pulses[   i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+                        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                            silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], Gains_Q16[ 1 ] ), 14 ) );
+                        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q14[ last_smple_idx ];
+                    }
+
+                    subfr = 0;
+                }
+
+                /* Rewhiten with new A coefs */
+                start_idx = psEncC->ltp_mem_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;
+                silk_assert( start_idx > 0 );
+
+                silk_LPC_analysis_filter( &sLTP[ start_idx ], &NSQ->xq[ start_idx + k * psEncC->subfr_length ],
+                    A_Q12, psEncC->ltp_mem_length - start_idx, psEncC->predictLPCOrder, psEncC->arch );
+
+                NSQ->sLTP_buf_idx = psEncC->ltp_mem_length;
+                NSQ->rewhite_flag = 1;
+            }
+        }
+
+        silk_nsq_del_dec_scale_states_sse4_1( psEncC, NSQ, psDelDec, x_Q3, x_sc_Q10, sLTP, sLTP_Q15, k,
+            psEncC->nStatesDelayedDecision, LTP_scale_Q14, Gains_Q16, pitchL, psIndices->signalType, decisionDelay );
+
+        silk_noise_shape_quantizer_del_dec_sse4_1( NSQ, psDelDec, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15,
+            delayedGain_Q10, A_Q12, B_Q14, AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ],
+            Gains_Q16[ k ], Lambda_Q10, offset_Q10, psEncC->subfr_length, subfr++, psEncC->shapingLPCOrder,
+            psEncC->predictLPCOrder, psEncC->warping_Q16, psEncC->nStatesDelayedDecision, &smpl_buf_idx, decisionDelay );
+
+        x_Q3   += psEncC->subfr_length;
+        pulses += psEncC->subfr_length;
+        pxq    += psEncC->subfr_length;
+    }
+
+    /* Find winner */
+    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;
+    Winner_ind = 0;
+    for( k = 1; k < psEncC->nStatesDelayedDecision; k++ ) {
+        if( psDelDec[ k ].RD_Q10 < RDmin_Q10 ) {
+            RDmin_Q10 = psDelDec[ k ].RD_Q10;
+            Winner_ind = k;
+        }
+    }
+
+    /* Copy final part of signals from winner state to output and long-term filter states */
+    psDD = &psDelDec[ Winner_ind ];
+    psIndices->Seed = psDD->SeedInit;
+    last_smple_idx = smpl_buf_idx + decisionDelay;
+    Gain_Q10 = silk_RSHIFT32( Gains_Q16[ psEncC->nb_subfr - 1 ], 6 );
+    for( i = 0; i < decisionDelay; i++ ) {
+        last_smple_idx = ( last_smple_idx - 1 ) % DECISION_DELAY;
+        if( last_smple_idx < 0 ) last_smple_idx += DECISION_DELAY;
+        pulses[   i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+        pxq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+            silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], Gain_Q10 ), 8 ) );
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q14[ last_smple_idx ];
+    }
+    silk_memcpy( NSQ->sLPC_Q14, &psDD->sLPC_Q14[ psEncC->subfr_length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+    silk_memcpy( NSQ->sAR2_Q14, psDD->sAR2_Q14, sizeof( psDD->sAR2_Q14 ) );
+
+    /* Update states */
+    NSQ->sLF_AR_shp_Q14 = psDD->LF_AR_Q14;
+    NSQ->lagPrev        = pitchL[ psEncC->nb_subfr - 1 ];
+
+    /* Save quantized speech signal */
+    silk_memmove( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int16 ) );
+    silk_memmove( NSQ->sLTP_shp_Q14, &NSQ->sLTP_shp_Q14[ psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
+
+/******************************************/
+/* Noise shape quantizer for one subframe */
+/******************************************/
+static OPUS_INLINE void silk_noise_shape_quantizer_del_dec_sse4_1(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */
+    opus_int            signalType,             /* I    Signal type                         */
+    const opus_int32    x_Q10[],                /* I                                        */
+    opus_int8           pulses[],               /* O                                        */
+    opus_int16          xq[],                   /* O                                        */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP filter state                    */
+    opus_int32          delayedGain_Q10[],      /* I/O  Gain delay buffer                   */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs         */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs          */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping coefs                 */
+    opus_int            lag,                    /* I    Pitch lag                           */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                        */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                       */
+    opus_int32          LF_shp_Q14,             /* I                                        */
+    opus_int32          Gain_Q16,               /* I                                        */
+    opus_int            Lambda_Q10,             /* I                                        */
+    opus_int            offset_Q10,             /* I                                        */
+    opus_int            length,                 /* I    Input length                        */
+    opus_int            subfr,                  /* I    Subframe number                     */
+    opus_int            shapingLPCOrder,        /* I    Shaping LPC filter order            */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order             */
+    opus_int            warping_Q16,            /* I                                        */
+    opus_int            nStatesDelayedDecision, /* I    Number of states in decision tree   */
+    opus_int            *smpl_buf_idx,          /* I/O  Index to newest samples in buffers  */
+    opus_int            decisionDelay           /* I                                        */
+)
+{
+    opus_int     i, j, k, Winner_ind, RDmin_ind, RDmax_ind, last_smple_idx;
+    opus_int32   Winner_rand_state;
+    opus_int32   LTP_pred_Q14, LPC_pred_Q14, n_AR_Q14, n_LTP_Q14;
+    opus_int32   n_LF_Q14, r_Q10, rr_Q10, rd1_Q10, rd2_Q10, RDmin_Q10, RDmax_Q10;
+    opus_int32   q1_Q0, q1_Q10, q2_Q10, exc_Q14, LPC_exc_Q14, xq_Q14, Gain_Q10;
+    opus_int32   tmp1, tmp2, sLF_AR_shp_Q14;
+    opus_int32   *pred_lag_ptr, *shp_lag_ptr, *psLPC_Q14;
+    VARDECL( NSQ_sample_pair, psSampleState );
+    NSQ_del_dec_struct *psDD;
+    NSQ_sample_struct  *psSS;
+
+    __m128i a_Q12_0123, a_Q12_4567, a_Q12_89AB, a_Q12_CDEF;
+    __m128i b_Q12_0123, b_sr_Q12_0123;
+    SAVE_STACK;
+
+    silk_assert( nStatesDelayedDecision > 0 );
+    ALLOC( psSampleState, nStatesDelayedDecision, NSQ_sample_pair );
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+    a_Q12_0123 = OP_CVTEPI16_EPI32_M64( a_Q12 );
+    a_Q12_4567 = OP_CVTEPI16_EPI32_M64( a_Q12 + 4 );
+
+    if( opus_likely( predictLPCOrder == 16 ) ) {
+        a_Q12_89AB = OP_CVTEPI16_EPI32_M64( a_Q12 + 8 );
+        a_Q12_CDEF = OP_CVTEPI16_EPI32_M64( a_Q12 + 12 );
+    }
+
+    if( signalType == TYPE_VOICED ){
+        b_Q12_0123 = OP_CVTEPI16_EPI32_M64( b_Q14 );
+        b_sr_Q12_0123 = _mm_shuffle_epi32( b_Q12_0123, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+    }
+    for( i = 0; i < length; i++ ) {
+        /* Perform common calculations used in all states */
+
+        /* Long-term prediction */
+        if( signalType == TYPE_VOICED ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q14 = 2;
+            {
+                __m128i tmpa, tmpb, pred_lag_ptr_tmp;
+                pred_lag_ptr_tmp    = _mm_loadu_si128( (__m128i *)(&pred_lag_ptr[ -3 ] ) );
+                pred_lag_ptr_tmp    = _mm_shuffle_epi32( pred_lag_ptr_tmp, 0x1B );
+                tmpa                = _mm_mul_epi32( pred_lag_ptr_tmp, b_Q12_0123 );
+                tmpa                = _mm_srli_si128( tmpa, 2 );
+
+                pred_lag_ptr_tmp = _mm_shuffle_epi32( pred_lag_ptr_tmp, _MM_SHUFFLE( 0, 3, 2, 1 ) );/* equal shift right 4 bytes */
+                pred_lag_ptr_tmp    = _mm_mul_epi32( pred_lag_ptr_tmp, b_sr_Q12_0123 );
+                pred_lag_ptr_tmp    = _mm_srli_si128( pred_lag_ptr_tmp, 2 );
+                pred_lag_ptr_tmp    = _mm_add_epi32( pred_lag_ptr_tmp, tmpa );
+
+                tmpb = _mm_shuffle_epi32( pred_lag_ptr_tmp, _MM_SHUFFLE( 0, 0, 3, 2 ) );/* equal shift right 8 bytes */
+                pred_lag_ptr_tmp    = _mm_add_epi32( pred_lag_ptr_tmp, tmpb );
+                LTP_pred_Q14        += _mm_cvtsi128_si32( pred_lag_ptr_tmp );
+
+                LTP_pred_Q14 = silk_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );
+                LTP_pred_Q14 = silk_LSHIFT( LTP_pred_Q14, 1 );                          /* Q13 -> Q14 */
+                pred_lag_ptr++;
+            }
+        } else {
+            LTP_pred_Q14 = 0;
+        }
+
+        /* Long-term shaping */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q14 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q14 = silk_SUB_LSHIFT32( LTP_pred_Q14, n_LTP_Q14, 2 );            /* Q12 -> Q14 */
+            shp_lag_ptr++;
+        } else {
+            n_LTP_Q14 = 0;
+        }
+        {
+            __m128i tmpa, tmpb, psLPC_Q14_tmp, a_Q12_tmp;
+
+            for( k = 0; k < nStatesDelayedDecision; k++ ) {
+                /* Delayed decision state */
+                psDD = &psDelDec[ k ];
+
+                /* Sample state */
+                psSS = psSampleState[ k ];
+
+                /* Generate dither */
+                psDD->Seed = silk_RAND( psDD->Seed );
+
+                /* Pointer used in short term prediction and shaping */
+                psLPC_Q14 = &psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 + i ];
+                /* Short-term prediction */
+                silk_assert( predictLPCOrder == 10 || predictLPCOrder == 16 );
+                /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+                LPC_pred_Q14 = silk_RSHIFT( predictLPCOrder, 1 );
+
+                tmpb = _mm_setzero_si128();
+
+                /* step 1 */
+                psLPC_Q14_tmp   = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -3 ] ) ); /* -3, -2 , -1, 0 */
+                psLPC_Q14_tmp   = _mm_shuffle_epi32( psLPC_Q14_tmp, 0x1B );      /* 0, -1, -2, -3 */
+                tmpa            = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_0123 );    /* 0, -1, -2, -3 * 0123 -> 0*0, 2*-2 */
+
+                tmpa            = _mm_srli_epi64( tmpa, 16 );
+                tmpb            = _mm_add_epi32( tmpb, tmpa );
+
+                psLPC_Q14_tmp = _mm_shuffle_epi32( psLPC_Q14_tmp, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                a_Q12_tmp = _mm_shuffle_epi32( a_Q12_0123, _MM_SHUFFLE(0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                psLPC_Q14_tmp   = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_tmp ); /* 1*-1, 3*-3 */
+                psLPC_Q14_tmp   = _mm_srli_epi64( psLPC_Q14_tmp, 16 );
+                tmpb            = _mm_add_epi32( tmpb, psLPC_Q14_tmp );
+
+                /* step 2 */
+                psLPC_Q14_tmp   = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -7 ] ) );
+                psLPC_Q14_tmp   = _mm_shuffle_epi32( psLPC_Q14_tmp, 0x1B );
+                tmpa            = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_4567 );
+                tmpa            = _mm_srli_epi64( tmpa, 16 );
+                tmpb            = _mm_add_epi32( tmpb, tmpa );
+
+                psLPC_Q14_tmp = _mm_shuffle_epi32( psLPC_Q14_tmp, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                a_Q12_tmp = _mm_shuffle_epi32( a_Q12_4567, _MM_SHUFFLE(0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                psLPC_Q14_tmp   = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_tmp );
+                psLPC_Q14_tmp   = _mm_srli_epi64( psLPC_Q14_tmp, 16 );
+                tmpb            = _mm_add_epi32( tmpb, psLPC_Q14_tmp );
+
+                if ( opus_likely( predictLPCOrder == 16 ) )
+                {
+                    /* step 3 */
+                    psLPC_Q14_tmp   = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -11 ] ) );
+                    psLPC_Q14_tmp   = _mm_shuffle_epi32( psLPC_Q14_tmp, 0x1B );
+                    tmpa            = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_89AB );
+                    tmpa            = _mm_srli_epi64( tmpa, 16 );
+                    tmpb            = _mm_add_epi32( tmpb, tmpa );
+
+                    psLPC_Q14_tmp = _mm_shuffle_epi32( psLPC_Q14_tmp, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                    a_Q12_tmp = _mm_shuffle_epi32( a_Q12_89AB, _MM_SHUFFLE(0, 3, 2, 1 ) );/* equal shift right 4 bytes */
+                    psLPC_Q14_tmp   = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_tmp );
+                    psLPC_Q14_tmp   = _mm_srli_epi64( psLPC_Q14_tmp, 16 );
+                    tmpb            = _mm_add_epi32( tmpb, psLPC_Q14_tmp );
+
+                    /* setp 4 */
+                    psLPC_Q14_tmp   = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -15 ] ) );
+                    psLPC_Q14_tmp   = _mm_shuffle_epi32( psLPC_Q14_tmp, 0x1B );
+                    tmpa            = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_CDEF );
+                    tmpa            = _mm_srli_epi64( tmpa, 16 );
+                    tmpb            = _mm_add_epi32( tmpb, tmpa );
+
+                    psLPC_Q14_tmp = _mm_shuffle_epi32( psLPC_Q14_tmp, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                    a_Q12_tmp = _mm_shuffle_epi32( a_Q12_CDEF, _MM_SHUFFLE(0, 3, 2, 1 ) ); /* equal shift right 4 bytes */
+                    psLPC_Q14_tmp   = _mm_mul_epi32( psLPC_Q14_tmp, a_Q12_tmp );
+                    psLPC_Q14_tmp   = _mm_srli_epi64( psLPC_Q14_tmp, 16 );
+                    tmpb            = _mm_add_epi32( tmpb, psLPC_Q14_tmp );
+
+                    /* add at last */
+                    /* equal shift right 8 bytes*/
+                    tmpa            = _mm_shuffle_epi32( tmpb, _MM_SHUFFLE( 0, 0, 3, 2 ) );
+                    tmpb            = _mm_add_epi32( tmpb, tmpa );
+                    LPC_pred_Q14    += _mm_cvtsi128_si32( tmpb );
+                }
+                else
+                {
+                    /* add at last */
+                    tmpa            = _mm_shuffle_epi32( tmpb, _MM_SHUFFLE( 0, 0, 3, 2 ) ); /* equal shift right 8 bytes*/
+                    tmpb            = _mm_add_epi32( tmpb, tmpa );
+                    LPC_pred_Q14    += _mm_cvtsi128_si32( tmpb );
+
+                    LPC_pred_Q14 = silk_SMLAWB( LPC_pred_Q14, psLPC_Q14[ -8 ], a_Q12[ 8 ] );
+                    LPC_pred_Q14 = silk_SMLAWB( LPC_pred_Q14, psLPC_Q14[ -9 ], a_Q12[ 9 ] );
+                }
+
+                LPC_pred_Q14 = silk_LSHIFT( LPC_pred_Q14, 4 ); /* Q10 -> Q14 */
+
+                /* Noise shape feedback */
+                silk_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */
+                /* Output of lowpass section */
+                tmp2 = silk_SMLAWB( psLPC_Q14[ 0 ], psDD->sAR2_Q14[ 0 ], warping_Q16 );
+                /* Output of allpass section */
+                tmp1 = silk_SMLAWB( psDD->sAR2_Q14[ 0 ], psDD->sAR2_Q14[ 1 ] - tmp2, warping_Q16 );
+                psDD->sAR2_Q14[ 0 ] = tmp2;
+                n_AR_Q14 = silk_RSHIFT( shapingLPCOrder, 1 );
+                n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp2, AR_shp_Q13[ 0 ] );
+                /* Loop over allpass sections */
+                for( j = 2; j < shapingLPCOrder; j += 2 ) {
+                    /* Output of allpass section */
+                    tmp2 = silk_SMLAWB( psDD->sAR2_Q14[ j - 1 ], psDD->sAR2_Q14[ j + 0 ] - tmp1, warping_Q16 );
+                    psDD->sAR2_Q14[ j - 1 ] = tmp1;
+                    n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp1, AR_shp_Q13[ j - 1 ] );
+                    /* Output of allpass section */
+                    tmp1 = silk_SMLAWB( psDD->sAR2_Q14[ j + 0 ], psDD->sAR2_Q14[ j + 1 ] - tmp2, warping_Q16 );
+                    psDD->sAR2_Q14[ j + 0 ] = tmp2;
+                    n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp2, AR_shp_Q13[ j ] );
+                }
+                psDD->sAR2_Q14[ shapingLPCOrder - 1 ] = tmp1;
+                n_AR_Q14 = silk_SMLAWB( n_AR_Q14, tmp1, AR_shp_Q13[ shapingLPCOrder - 1 ] );
+
+                n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 1 );                                      /* Q11 -> Q12 */
+                n_AR_Q14 = silk_SMLAWB( n_AR_Q14, psDD->LF_AR_Q14, Tilt_Q14 );              /* Q12 */
+                n_AR_Q14 = silk_LSHIFT( n_AR_Q14, 2 );                                      /* Q12 -> Q14 */
+
+                n_LF_Q14 = silk_SMULWB( psDD->Shape_Q14[ *smpl_buf_idx ], LF_shp_Q14 );     /* Q12 */
+                n_LF_Q14 = silk_SMLAWT( n_LF_Q14, psDD->LF_AR_Q14, LF_shp_Q14 );            /* Q12 */
+                n_LF_Q14 = silk_LSHIFT( n_LF_Q14, 2 );                                      /* Q12 -> Q14 */
+
+                /* Input minus prediction plus noise feedback                       */
+                /* r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP  */
+                tmp1 = silk_ADD32( n_AR_Q14, n_LF_Q14 );                                    /* Q14 */
+                tmp2 = silk_ADD32( n_LTP_Q14, LPC_pred_Q14 );                               /* Q13 */
+                tmp1 = silk_SUB32( tmp2, tmp1 );                                            /* Q13 */
+                tmp1 = silk_RSHIFT_ROUND( tmp1, 4 );                                        /* Q10 */
+
+                r_Q10 = silk_SUB32( x_Q10[ i ], tmp1 );                                     /* residual error Q10 */
+
+                /* Flip sign depending on dither */
+                if ( psDD->Seed < 0 ) {
+                    r_Q10 = -r_Q10;
+                }
+                r_Q10 = silk_LIMIT_32( r_Q10, -(31 << 10), 30 << 10 );
+
+                /* Find two quantization level candidates and measure their rate-distortion */
+                q1_Q10 = silk_SUB32( r_Q10, offset_Q10 );
+                q1_Q0 = silk_RSHIFT( q1_Q10, 10 );
+                if( q1_Q0 > 0 ) {
+                    q1_Q10  = silk_SUB32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                    q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                    q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                    rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                    rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+                } else if( q1_Q0 == 0 ) {
+                    q1_Q10  = offset_Q10;
+                    q2_Q10  = silk_ADD32( q1_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                    rd1_Q10 = silk_SMULBB( q1_Q10, Lambda_Q10 );
+                    rd2_Q10 = silk_SMULBB( q2_Q10, Lambda_Q10 );
+                } else if( q1_Q0 == -1 ) {
+                    q2_Q10  = offset_Q10;
+                    q1_Q10  = silk_SUB32( q2_Q10, 1024 - QUANT_LEVEL_ADJUST_Q10 );
+                    rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                    rd2_Q10 = silk_SMULBB(  q2_Q10, Lambda_Q10 );
+                } else {            /* q1_Q0 < -1 */
+                    q1_Q10  = silk_ADD32( silk_LSHIFT( q1_Q0, 10 ), QUANT_LEVEL_ADJUST_Q10 );
+                    q1_Q10  = silk_ADD32( q1_Q10, offset_Q10 );
+                    q2_Q10  = silk_ADD32( q1_Q10, 1024 );
+                    rd1_Q10 = silk_SMULBB( -q1_Q10, Lambda_Q10 );
+                    rd2_Q10 = silk_SMULBB( -q2_Q10, Lambda_Q10 );
+                }
+                rr_Q10  = silk_SUB32( r_Q10, q1_Q10 );
+                rd1_Q10 = silk_RSHIFT( silk_SMLABB( rd1_Q10, rr_Q10, rr_Q10 ), 10 );
+                rr_Q10  = silk_SUB32( r_Q10, q2_Q10 );
+                rd2_Q10 = silk_RSHIFT( silk_SMLABB( rd2_Q10, rr_Q10, rr_Q10 ), 10 );
+
+                if( rd1_Q10 < rd2_Q10 ) {
+                    psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                    psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                    psSS[ 0 ].Q_Q10  = q1_Q10;
+                    psSS[ 1 ].Q_Q10  = q2_Q10;
+                } else {
+                    psSS[ 0 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd2_Q10 );
+                    psSS[ 1 ].RD_Q10 = silk_ADD32( psDD->RD_Q10, rd1_Q10 );
+                    psSS[ 0 ].Q_Q10  = q2_Q10;
+                    psSS[ 1 ].Q_Q10  = q1_Q10;
+                }
+
+                /* Update states for best quantization */
+
+                /* Quantized excitation */
+                exc_Q14 = silk_LSHIFT32( psSS[ 0 ].Q_Q10, 4 );
+                if ( psDD->Seed < 0 ) {
+                    exc_Q14 = -exc_Q14;
+                }
+
+                /* Add predictions */
+                LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+                xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+                /* Update states */
+                sLF_AR_shp_Q14         = silk_SUB32( xq_Q14, n_AR_Q14 );
+                psSS[ 0 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+                psSS[ 0 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+                psSS[ 0 ].LPC_exc_Q14  = LPC_exc_Q14;
+                psSS[ 0 ].xq_Q14       = xq_Q14;
+
+                /* Update states for second best quantization */
+
+                /* Quantized excitation */
+                exc_Q14 = silk_LSHIFT32( psSS[ 1 ].Q_Q10, 4 );
+                if ( psDD->Seed < 0 ) {
+                    exc_Q14 = -exc_Q14;
+                }
+
+
+                /* Add predictions */
+                LPC_exc_Q14 = silk_ADD32( exc_Q14, LTP_pred_Q14 );
+                xq_Q14      = silk_ADD32( LPC_exc_Q14, LPC_pred_Q14 );
+
+                /* Update states */
+                sLF_AR_shp_Q14         = silk_SUB32( xq_Q14, n_AR_Q14 );
+                psSS[ 1 ].sLTP_shp_Q14 = silk_SUB32( sLF_AR_shp_Q14, n_LF_Q14 );
+                psSS[ 1 ].LF_AR_Q14    = sLF_AR_shp_Q14;
+                psSS[ 1 ].LPC_exc_Q14  = LPC_exc_Q14;
+                psSS[ 1 ].xq_Q14       = xq_Q14;
+            }
+        }
+        *smpl_buf_idx  = ( *smpl_buf_idx - 1 ) % DECISION_DELAY;
+        if( *smpl_buf_idx < 0 ) *smpl_buf_idx += DECISION_DELAY;
+        last_smple_idx = ( *smpl_buf_idx + decisionDelay ) % DECISION_DELAY;
+
+        /* Find winner */
+        RDmin_Q10 = psSampleState[ 0 ][ 0 ].RD_Q10;
+        Winner_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            if( psSampleState[ k ][ 0 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                Winner_ind = k;
+            }
+        }
+
+        /* Increase RD values of expired states */
+        Winner_rand_state = psDelDec[ Winner_ind ].RandState[ last_smple_idx ];
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            if( psDelDec[ k ].RandState[ last_smple_idx ] != Winner_rand_state ) {
+                psSampleState[ k ][ 0 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 0 ].RD_Q10, silk_int32_MAX >> 4 );
+                psSampleState[ k ][ 1 ].RD_Q10 = silk_ADD32( psSampleState[ k ][ 1 ].RD_Q10, silk_int32_MAX >> 4 );
+                silk_assert( psSampleState[ k ][ 0 ].RD_Q10 >= 0 );
+            }
+        }
+
+        /* Find worst in first set and best in second set */
+        RDmax_Q10  = psSampleState[ 0 ][ 0 ].RD_Q10;
+        RDmin_Q10  = psSampleState[ 0 ][ 1 ].RD_Q10;
+        RDmax_ind = 0;
+        RDmin_ind = 0;
+        for( k = 1; k < nStatesDelayedDecision; k++ ) {
+            /* find worst in first set */
+            if( psSampleState[ k ][ 0 ].RD_Q10 > RDmax_Q10 ) {
+                RDmax_Q10  = psSampleState[ k ][ 0 ].RD_Q10;
+                RDmax_ind = k;
+            }
+            /* find best in second set */
+            if( psSampleState[ k ][ 1 ].RD_Q10 < RDmin_Q10 ) {
+                RDmin_Q10  = psSampleState[ k ][ 1 ].RD_Q10;
+                RDmin_ind = k;
+            }
+        }
+
+        /* Replace a state if best from second set outperforms worst in first set */
+        if( RDmin_Q10 < RDmax_Q10 ) {
+            silk_memcpy( ( (opus_int32 *)&psDelDec[ RDmax_ind ] ) + i,
+                         ( (opus_int32 *)&psDelDec[ RDmin_ind ] ) + i, sizeof( NSQ_del_dec_struct ) - i * sizeof( opus_int32) );
+            silk_memcpy( &psSampleState[ RDmax_ind ][ 0 ], &psSampleState[ RDmin_ind ][ 1 ], sizeof( NSQ_sample_struct ) );
+        }
+
+        /* Write samples from winner to output and long-term filter states */
+        psDD = &psDelDec[ Winner_ind ];
+        if( subfr > 0 || i >= decisionDelay ) {
+            pulses[  i - decisionDelay ] = (opus_int8)silk_RSHIFT_ROUND( psDD->Q_Q10[ last_smple_idx ], 10 );
+            xq[ i - decisionDelay ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND(
+                silk_SMULWW( psDD->Xq_Q14[ last_smple_idx ], delayedGain_Q10[ last_smple_idx ] ), 8 ) );
+            NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - decisionDelay ] = psDD->Shape_Q14[ last_smple_idx ];
+            sLTP_Q15[          NSQ->sLTP_buf_idx     - decisionDelay ] = psDD->Pred_Q15[  last_smple_idx ];
+        }
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Update states */
+        for( k = 0; k < nStatesDelayedDecision; k++ ) {
+            psDD                                     = &psDelDec[ k ];
+            psSS                                     = &psSampleState[ k ][ 0 ];
+            psDD->LF_AR_Q14                          = psSS->LF_AR_Q14;
+            psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH + i ] = psSS->xq_Q14;
+            psDD->Xq_Q14[    *smpl_buf_idx ]         = psSS->xq_Q14;
+            psDD->Q_Q10[     *smpl_buf_idx ]         = psSS->Q_Q10;
+            psDD->Pred_Q15[  *smpl_buf_idx ]         = silk_LSHIFT32( psSS->LPC_exc_Q14, 1 );
+            psDD->Shape_Q14[ *smpl_buf_idx ]         = psSS->sLTP_shp_Q14;
+            psDD->Seed                               = silk_ADD32_ovflw( psDD->Seed, silk_RSHIFT_ROUND( psSS->Q_Q10, 10 ) );
+            psDD->RandState[ *smpl_buf_idx ]         = psDD->Seed;
+            psDD->RD_Q10                             = psSS->RD_Q10;
+        }
+        delayedGain_Q10[     *smpl_buf_idx ]         = Gain_Q10;
+    }
+    /* Update LPC states */
+    for( k = 0; k < nStatesDelayedDecision; k++ ) {
+        psDD = &psDelDec[ k ];
+        silk_memcpy( psDD->sLPC_Q14, &psDD->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+    }
+    RESTORE_STACK;
+}
+
+static OPUS_INLINE void silk_nsq_del_dec_scale_states_sse4_1(
+    const silk_encoder_state *psEncC,               /* I    Encoder State                       */
+    silk_nsq_state      *NSQ,                       /* I/O  NSQ state                           */
+    NSQ_del_dec_struct  psDelDec[],                 /* I/O  Delayed decision states             */
+    const opus_int32    x_Q3[],                     /* I    Input in Q3                         */
+    opus_int32          x_sc_Q10[],                 /* O    Input scaled with 1/Gain in Q10     */
+    const opus_int16    sLTP[],                     /* I    Re-whitened LTP state in Q0         */
+    opus_int32          sLTP_Q15[],                 /* O    LTP state matching scaled input     */
+    opus_int            subfr,                      /* I    Subframe number                     */
+    opus_int            nStatesDelayedDecision,     /* I    Number of del dec states            */
+    const opus_int      LTP_scale_Q14,              /* I    LTP state scaling                   */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ],  /* I                                        */
+    const opus_int      pitchL[ MAX_NB_SUBFR ],     /* I    Pitch lag                           */
+    const opus_int      signal_type,                /* I    Signal type                         */
+    const opus_int      decisionDelay               /* I    Decision delay                      */
+)
+{
+    opus_int            i, k, lag;
+    opus_int32          gain_adj_Q16, inv_gain_Q31, inv_gain_Q23;
+    NSQ_del_dec_struct  *psDD;
+    __m128i xmm_inv_gain_Q23, xmm_x_Q3_x2x0, xmm_x_Q3_x3x1;
+
+    lag          = pitchL[ subfr ];
+    inv_gain_Q31 = silk_INVERSE32_varQ( silk_max( Gains_Q16[ subfr ], 1 ), 47 );
+
+    silk_assert( inv_gain_Q31 != 0 );
+
+    /* Calculate gain adjustment factor */
+    if( Gains_Q16[ subfr ] != NSQ->prev_gain_Q16 ) {
+        gain_adj_Q16 =  silk_DIV32_varQ( NSQ->prev_gain_Q16, Gains_Q16[ subfr ], 16 );
+    } else {
+        gain_adj_Q16 = (opus_int32)1 << 16;
+    }
+
+    /* Scale input */
+    inv_gain_Q23 = silk_RSHIFT_ROUND( inv_gain_Q31, 8 );
+
+    /* prepare inv_gain_Q23 in packed 4 32-bits */
+    xmm_inv_gain_Q23 = _mm_set1_epi32(inv_gain_Q23);
+
+    for( i = 0; i < psEncC->subfr_length - 3; i += 4 ) {
+        xmm_x_Q3_x2x0 = _mm_loadu_si128( (__m128i *)(&(x_Q3[ i ] ) ) );
+        /* equal shift right 4 bytes*/
+        xmm_x_Q3_x3x1 = _mm_shuffle_epi32( xmm_x_Q3_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+        xmm_x_Q3_x2x0 = _mm_mul_epi32( xmm_x_Q3_x2x0, xmm_inv_gain_Q23 );
+        xmm_x_Q3_x3x1 = _mm_mul_epi32( xmm_x_Q3_x3x1, xmm_inv_gain_Q23 );
+
+        xmm_x_Q3_x2x0 = _mm_srli_epi64( xmm_x_Q3_x2x0, 16 );
+        xmm_x_Q3_x3x1 = _mm_slli_epi64( xmm_x_Q3_x3x1, 16 );
+
+        xmm_x_Q3_x2x0 = _mm_blend_epi16( xmm_x_Q3_x2x0, xmm_x_Q3_x3x1, 0xCC );
+
+        _mm_storeu_si128( (__m128i *)(&(x_sc_Q10[ i ])), xmm_x_Q3_x2x0 );
+    }
+
+    for( ; i < psEncC->subfr_length; i++ ) {
+        x_sc_Q10[ i ] = silk_SMULWW( x_Q3[ i ], inv_gain_Q23 );
+    }
+
+    /* Save inverse gain */
+    NSQ->prev_gain_Q16 = Gains_Q16[ subfr ];
+
+    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */
+    if( NSQ->rewhite_flag ) {
+        if( subfr == 0 ) {
+            /* Do LTP downscaling */
+            inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, LTP_scale_Q14 ), 2 );
+        }
+        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+            silk_assert( i < MAX_FRAME_LENGTH );
+            sLTP_Q15[ i ] = silk_SMULWB( inv_gain_Q31, sLTP[ i ] );
+        }
+    }
+
+    /* Adjust for changing gain */
+    if( gain_adj_Q16 != (opus_int32)1 << 16 ) {
+        /* Scale long-term shaping state */
+        {
+            __m128i xmm_gain_adj_Q16, xmm_sLTP_shp_Q14_x2x0, xmm_sLTP_shp_Q14_x3x1;
+
+            /* prepare gain_adj_Q16 in packed 4 32-bits */
+            xmm_gain_adj_Q16 = _mm_set1_epi32( gain_adj_Q16 );
+
+            for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx - 3; i += 4 )
+            {
+                xmm_sLTP_shp_Q14_x2x0 = _mm_loadu_si128( (__m128i *)(&(NSQ->sLTP_shp_Q14[ i ] ) ) );
+                /* equal shift right 4 bytes*/
+                xmm_sLTP_shp_Q14_x3x1 = _mm_shuffle_epi32( xmm_sLTP_shp_Q14_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+                xmm_sLTP_shp_Q14_x2x0 = _mm_mul_epi32( xmm_sLTP_shp_Q14_x2x0, xmm_gain_adj_Q16 );
+                xmm_sLTP_shp_Q14_x3x1 = _mm_mul_epi32( xmm_sLTP_shp_Q14_x3x1, xmm_gain_adj_Q16 );
+
+                xmm_sLTP_shp_Q14_x2x0 = _mm_srli_epi64( xmm_sLTP_shp_Q14_x2x0, 16 );
+                xmm_sLTP_shp_Q14_x3x1 = _mm_slli_epi64( xmm_sLTP_shp_Q14_x3x1, 16 );
+
+                xmm_sLTP_shp_Q14_x2x0 = _mm_blend_epi16( xmm_sLTP_shp_Q14_x2x0, xmm_sLTP_shp_Q14_x3x1, 0xCC );
+
+                _mm_storeu_si128( (__m128i *)(&(NSQ->sLTP_shp_Q14[ i ] ) ), xmm_sLTP_shp_Q14_x2x0 );
+            }
+
+            for( ; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+                NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+            }
+
+            /* Scale long-term prediction state */
+            if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+                for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx - decisionDelay; i++ ) {
+                    sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+                }
+            }
+
+            for( k = 0; k < nStatesDelayedDecision; k++ ) {
+                psDD = &psDelDec[ k ];
+
+                /* Scale scalar states */
+                psDD->LF_AR_Q14 = silk_SMULWW( gain_adj_Q16, psDD->LF_AR_Q14 );
+
+                /* Scale short-term prediction and shaping states */
+                for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+                    psDD->sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->sLPC_Q14[ i ] );
+                }
+                for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+                    psDD->sAR2_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->sAR2_Q14[ i ] );
+                }
+                for( i = 0; i < DECISION_DELAY; i++ ) {
+                    psDD->Pred_Q15[  i ] = silk_SMULWW( gain_adj_Q16, psDD->Pred_Q15[  i ] );
+                    psDD->Shape_Q14[ i ] = silk_SMULWW( gain_adj_Q16, psDD->Shape_Q14[ i ] );
+                }
+            }
+        }
+    }
+}
diff --git a/opus/silk/x86/NSQ_sse.c b/opus/silk/x86/NSQ_sse.c
new file mode 100644 (file)
index 0000000..6a9e6e9
--- /dev/null
@@ -0,0 +1,719 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+#include "main.h"
+#include "celt/x86/x86cpu.h"
+#include "stack_alloc.h"
+
+static OPUS_INLINE void silk_nsq_scale_states_sse4_1(
+    const silk_encoder_state *psEncC,           /* I    Encoder State                   */
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    const opus_int32    x_Q3[],                 /* I    input in Q3                     */
+    opus_int32          x_sc_Q10[],             /* O    input scaled with 1/Gain        */
+    const opus_int16    sLTP[],                 /* I    re-whitened LTP state in Q0     */
+    opus_int32          sLTP_Q15[],             /* O    LTP state matching scaled input */
+    opus_int            subfr,                  /* I    subframe number                 */
+    const opus_int      LTP_scale_Q14,          /* I                                    */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ], /* I                                 */
+    const opus_int      pitchL[ MAX_NB_SUBFR ], /* I    Pitch lag                       */
+    const opus_int      signal_type             /* I    Signal type                     */
+);
+
+static OPUS_INLINE void silk_noise_shape_quantizer_10_16_sse4_1(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    opus_int            signalType,             /* I    Signal type                     */
+    const opus_int32    x_sc_Q10[],             /* I                                    */
+    opus_int8           pulses[],               /* O                                    */
+    opus_int16          xq[],                   /* O                                    */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP state                       */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs     */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs      */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping AR coefs          */
+    opus_int            lag,                    /* I    Pitch lag                       */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                    */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                   */
+    opus_int32          LF_shp_Q14,             /* I                                    */
+    opus_int32          Gain_Q16,               /* I                                    */
+    opus_int            offset_Q10,             /* I                                    */
+    opus_int            length,                 /* I    Input length                    */
+    opus_int32          table[][4]              /* I                                    */
+);
+
+void silk_NSQ_sse4_1(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+)
+{
+    opus_int            k, lag, start_idx, LSF_interpolation_flag;
+    const opus_int16    *A_Q12, *B_Q14, *AR_shp_Q13;
+    opus_int16          *pxq;
+    VARDECL( opus_int32, sLTP_Q15 );
+    VARDECL( opus_int16, sLTP );
+    opus_int32          HarmShapeFIRPacked_Q14;
+    opus_int            offset_Q10;
+    VARDECL( opus_int32, x_sc_Q10 );
+
+    opus_int32   table[ 64 ][ 4 ];
+    opus_int32   tmp1;
+    opus_int32   q1_Q10, q2_Q10, rd1_Q20, rd2_Q20;
+
+    SAVE_STACK;
+
+    NSQ->rand_seed = psIndices->Seed;
+
+    /* Set unvoiced lag to the previous one, overwrite later for voiced */
+    lag = NSQ->lagPrev;
+
+    silk_assert( NSQ->prev_gain_Q16 != 0 );
+
+    offset_Q10 = silk_Quantization_Offsets_Q10[ psIndices->signalType >> 1 ][ psIndices->quantOffsetType ];
+
+    /* 0 */
+    q1_Q10  = offset_Q10;
+    q2_Q10  = offset_Q10 + ( 1024 - QUANT_LEVEL_ADJUST_Q10 );
+    rd1_Q20 = q1_Q10 * Lambda_Q10;
+    rd2_Q20 = q2_Q10 * Lambda_Q10;
+
+    table[ 32 ][ 0 ] = q1_Q10;
+    table[ 32 ][ 1 ] = q2_Q10;
+    table[ 32 ][ 2 ] = 2 * (q1_Q10 - q2_Q10);
+    table[ 32 ][ 3 ] = (rd1_Q20 - rd2_Q20) + (q1_Q10 * q1_Q10 - q2_Q10 * q2_Q10);
+
+    /* -1 */
+    q1_Q10  = offset_Q10 - ( 1024 - QUANT_LEVEL_ADJUST_Q10 );
+    q2_Q10  = offset_Q10;
+    rd1_Q20 = - q1_Q10 * Lambda_Q10;
+    rd2_Q20 = q2_Q10 * Lambda_Q10;
+
+    table[ 31 ][ 0 ] = q1_Q10;
+    table[ 31 ][ 1 ] = q2_Q10;
+    table[ 31 ][ 2 ] = 2 * (q1_Q10 - q2_Q10);
+    table[ 31 ][ 3 ] = (rd1_Q20 - rd2_Q20) + (q1_Q10 * q1_Q10 - q2_Q10 * q2_Q10);
+
+    /* > 0 */
+    for (k = 1; k <= 31; k++)
+    {
+        tmp1 = offset_Q10 + silk_LSHIFT( k, 10 );
+
+        q1_Q10  = tmp1 - QUANT_LEVEL_ADJUST_Q10;
+        q2_Q10  = tmp1 - QUANT_LEVEL_ADJUST_Q10 + 1024;
+        rd1_Q20 = q1_Q10 * Lambda_Q10;
+        rd2_Q20 = q2_Q10 * Lambda_Q10;
+
+        table[ 32 + k ][ 0 ] = q1_Q10;
+        table[ 32 + k ][ 1 ] = q2_Q10;
+        table[ 32 + k ][ 2 ] = 2 * (q1_Q10 - q2_Q10);
+        table[ 32 + k ][ 3 ] = (rd1_Q20 - rd2_Q20) + (q1_Q10 * q1_Q10 - q2_Q10 * q2_Q10);
+    }
+
+    /* < -1 */
+    for (k = -32; k <= -2; k++)
+    {
+        tmp1 = offset_Q10 + silk_LSHIFT( k, 10 );
+
+        q1_Q10  = tmp1 + QUANT_LEVEL_ADJUST_Q10;
+        q2_Q10  = tmp1 + QUANT_LEVEL_ADJUST_Q10 + 1024;
+        rd1_Q20 = - q1_Q10 * Lambda_Q10;
+        rd2_Q20 = - q2_Q10 * Lambda_Q10;
+
+        table[ 32 + k ][ 0 ] = q1_Q10;
+        table[ 32 + k ][ 1 ] = q2_Q10;
+        table[ 32 + k ][ 2 ] = 2 * (q1_Q10 - q2_Q10);
+        table[ 32 + k ][ 3 ] = (rd1_Q20 - rd2_Q20) + (q1_Q10 * q1_Q10 - q2_Q10 * q2_Q10);
+    }
+
+    if( psIndices->NLSFInterpCoef_Q2 == 4 ) {
+        LSF_interpolation_flag = 0;
+    } else {
+        LSF_interpolation_flag = 1;
+    }
+
+    ALLOC( sLTP_Q15,
+           psEncC->ltp_mem_length + psEncC->frame_length, opus_int32 );
+    ALLOC( sLTP, psEncC->ltp_mem_length + psEncC->frame_length, opus_int16 );
+    ALLOC( x_sc_Q10, psEncC->subfr_length, opus_int32 );
+    /* Set up pointers to start of sub frame */
+    NSQ->sLTP_shp_buf_idx = psEncC->ltp_mem_length;
+    NSQ->sLTP_buf_idx     = psEncC->ltp_mem_length;
+    pxq                   = &NSQ->xq[ psEncC->ltp_mem_length ];
+    for( k = 0; k < psEncC->nb_subfr; k++ ) {
+        A_Q12      = &PredCoef_Q12[ (( k >> 1 ) | ( 1 - LSF_interpolation_flag )) * MAX_LPC_ORDER ];
+        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER ];
+        AR_shp_Q13 = &AR2_Q13[     k * MAX_SHAPE_LPC_ORDER ];
+
+        /* Noise shape parameters */
+        silk_assert( HarmShapeGain_Q14[ k ] >= 0 );
+        HarmShapeFIRPacked_Q14  =                          silk_RSHIFT( HarmShapeGain_Q14[ k ], 2 );
+        HarmShapeFIRPacked_Q14 |= silk_LSHIFT( (opus_int32)silk_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );
+
+        NSQ->rewhite_flag = 0;
+        if( psIndices->signalType == TYPE_VOICED ) {
+            /* Voiced */
+            lag = pitchL[ k ];
+
+            /* Re-whitening */
+            if( ( k & ( 3 - silk_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {
+                /* Rewhiten with new A coefs */
+                start_idx = psEncC->ltp_mem_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;
+                silk_assert( start_idx > 0 );
+
+                silk_LPC_analysis_filter( &sLTP[ start_idx ], &NSQ->xq[ start_idx + k * psEncC->subfr_length ],
+                    A_Q12, psEncC->ltp_mem_length - start_idx, psEncC->predictLPCOrder, psEncC->arch );
+
+                NSQ->rewhite_flag = 1;
+                NSQ->sLTP_buf_idx = psEncC->ltp_mem_length;
+            }
+        }
+
+        silk_nsq_scale_states_sse4_1( psEncC, NSQ, x_Q3, x_sc_Q10, sLTP, sLTP_Q15, k, LTP_scale_Q14, Gains_Q16, pitchL, psIndices->signalType );
+
+        if ( opus_likely( ( 10 == psEncC->shapingLPCOrder ) && ( 16 == psEncC->predictLPCOrder) ) )
+        {
+            silk_noise_shape_quantizer_10_16_sse4_1( NSQ, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15, A_Q12, B_Q14,
+                AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ], Gains_Q16[ k ],
+                offset_Q10, psEncC->subfr_length, &(table[32]) );
+        }
+        else
+        {
+            silk_noise_shape_quantizer( NSQ, psIndices->signalType, x_sc_Q10, pulses, pxq, sLTP_Q15, A_Q12, B_Q14,
+                AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ], Gains_Q16[ k ], Lambda_Q10,
+                offset_Q10, psEncC->subfr_length, psEncC->shapingLPCOrder, psEncC->predictLPCOrder, psEncC->arch );
+        }
+
+        x_Q3   += psEncC->subfr_length;
+        pulses += psEncC->subfr_length;
+        pxq    += psEncC->subfr_length;
+    }
+
+    /* Update lagPrev for next frame */
+    NSQ->lagPrev = pitchL[ psEncC->nb_subfr - 1 ];
+
+    /* Save quantized speech and noise shaping signals */
+    silk_memmove( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int16 ) );
+    silk_memmove( NSQ->sLTP_shp_Q14, &NSQ->sLTP_shp_Q14[ psEncC->frame_length ], psEncC->ltp_mem_length * sizeof( opus_int32 ) );
+    RESTORE_STACK;
+}
+
+/***********************************/
+/* silk_noise_shape_quantizer_10_16  */
+/***********************************/
+static OPUS_INLINE void silk_noise_shape_quantizer_10_16_sse4_1(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    opus_int            signalType,             /* I    Signal type                     */
+    const opus_int32    x_sc_Q10[],             /* I                                    */
+    opus_int8           pulses[],               /* O                                    */
+    opus_int16          xq[],                   /* O                                    */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP state                       */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs     */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs      */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping AR coefs          */
+    opus_int            lag,                    /* I    Pitch lag                       */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                    */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                   */
+    opus_int32          LF_shp_Q14,             /* I                                    */
+    opus_int32          Gain_Q16,               /* I                                    */
+    opus_int            offset_Q10,             /* I                                    */
+    opus_int            length,                 /* I    Input length                    */
+    opus_int32          table[][4]              /* I                                    */
+)
+{
+    opus_int     i;
+    opus_int32   LTP_pred_Q13, LPC_pred_Q10, n_AR_Q12, n_LTP_Q13;
+    opus_int32   n_LF_Q12, r_Q10, q1_Q0, q1_Q10, q2_Q10;
+    opus_int32   exc_Q14, LPC_exc_Q14, xq_Q14, Gain_Q10;
+    opus_int32   tmp1, tmp2, sLF_AR_shp_Q14;
+    opus_int32   *psLPC_Q14, *shp_lag_ptr, *pred_lag_ptr;
+
+    __m128i xmm_tempa, xmm_tempb;
+
+    __m128i xmm_one;
+
+    __m128i psLPC_Q14_hi_01234567, psLPC_Q14_hi_89ABCDEF;
+    __m128i psLPC_Q14_lo_01234567, psLPC_Q14_lo_89ABCDEF;
+    __m128i a_Q12_01234567,        a_Q12_89ABCDEF;
+
+    __m128i sAR2_Q14_hi_76543210, sAR2_Q14_lo_76543210;
+    __m128i AR_shp_Q13_76543210;
+
+    shp_lag_ptr  = &NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];
+    pred_lag_ptr = &sLTP_Q15[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];
+    Gain_Q10     = silk_RSHIFT( Gain_Q16, 6 );
+
+    /* Set up short term AR state */
+    psLPC_Q14 = &NSQ->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 ];
+
+    sLF_AR_shp_Q14 = NSQ->sLF_AR_shp_Q14;
+    xq_Q14         = psLPC_Q14[ 0 ];
+    LTP_pred_Q13   = 0;
+
+    /* load a_Q12 */
+    xmm_one = _mm_set_epi8( 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 );
+
+    /* load a_Q12[0] - a_Q12[7] */
+    a_Q12_01234567 = _mm_loadu_si128( (__m128i *)(&a_Q12[ 0 ] ) );
+    /* load a_Q12[ 8 ] - a_Q12[ 15 ] */
+    a_Q12_89ABCDEF = _mm_loadu_si128( (__m128i *)(&a_Q12[ 8 ] ) );
+
+    a_Q12_01234567 = _mm_shuffle_epi8( a_Q12_01234567, xmm_one );
+    a_Q12_89ABCDEF = _mm_shuffle_epi8( a_Q12_89ABCDEF, xmm_one );
+
+    /* load AR_shp_Q13 */
+    AR_shp_Q13_76543210 = _mm_loadu_si128( (__m128i *)(&AR_shp_Q13[0] ) );
+
+    /* load psLPC_Q14 */
+    xmm_one = _mm_set_epi8(15, 14, 11, 10, 7, 6, 3, 2, 13, 12, 9, 8, 5, 4, 1, 0 );
+
+    xmm_tempa = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[-16]) );
+    xmm_tempb = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[-12]) );
+
+    xmm_tempa = _mm_shuffle_epi8( xmm_tempa, xmm_one );
+    xmm_tempb = _mm_shuffle_epi8( xmm_tempb, xmm_one );
+
+    psLPC_Q14_hi_89ABCDEF = _mm_unpackhi_epi64( xmm_tempa, xmm_tempb );
+    psLPC_Q14_lo_89ABCDEF = _mm_unpacklo_epi64( xmm_tempa, xmm_tempb );
+
+    xmm_tempa = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -8 ]) );
+    xmm_tempb = _mm_loadu_si128( (__m128i *)(&psLPC_Q14[ -4 ]) );
+
+    xmm_tempa = _mm_shuffle_epi8( xmm_tempa, xmm_one );
+    xmm_tempb = _mm_shuffle_epi8( xmm_tempb, xmm_one );
+
+    psLPC_Q14_hi_01234567 = _mm_unpackhi_epi64( xmm_tempa, xmm_tempb );
+    psLPC_Q14_lo_01234567 = _mm_unpacklo_epi64( xmm_tempa, xmm_tempb );
+
+    /* load sAR2_Q14 */
+    xmm_tempa = _mm_loadu_si128( (__m128i *)(&(NSQ->sAR2_Q14[ 0 ]) ) );
+    xmm_tempb = _mm_loadu_si128( (__m128i *)(&(NSQ->sAR2_Q14[ 4 ]) ) );
+
+    xmm_tempa = _mm_shuffle_epi8( xmm_tempa, xmm_one );
+    xmm_tempb = _mm_shuffle_epi8( xmm_tempb, xmm_one );
+
+    sAR2_Q14_hi_76543210 = _mm_unpackhi_epi64( xmm_tempa, xmm_tempb );
+    sAR2_Q14_lo_76543210 = _mm_unpacklo_epi64( xmm_tempa, xmm_tempb );
+
+    /* prepare 1 in 8 * 16bit */
+    xmm_one = _mm_set1_epi16(1);
+
+    for( i = 0; i < length; i++ )
+    {
+        /* Short-term prediction */
+        __m128i xmm_hi_07, xmm_hi_8F, xmm_lo_07, xmm_lo_8F;
+
+        /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+        LPC_pred_Q10 = 8; /* silk_RSHIFT( predictLPCOrder, 1 ); */
+
+        /* shift psLPC_Q14 */
+        psLPC_Q14_hi_89ABCDEF = _mm_alignr_epi8( psLPC_Q14_hi_01234567, psLPC_Q14_hi_89ABCDEF, 2 );
+        psLPC_Q14_lo_89ABCDEF = _mm_alignr_epi8( psLPC_Q14_lo_01234567, psLPC_Q14_lo_89ABCDEF, 2 );
+
+        psLPC_Q14_hi_01234567 = _mm_srli_si128( psLPC_Q14_hi_01234567, 2 );
+        psLPC_Q14_lo_01234567 = _mm_srli_si128( psLPC_Q14_lo_01234567, 2 );
+
+        psLPC_Q14_hi_01234567 = _mm_insert_epi16( psLPC_Q14_hi_01234567, (xq_Q14 >> 16), 7 );
+        psLPC_Q14_lo_01234567 = _mm_insert_epi16( psLPC_Q14_lo_01234567, (xq_Q14),       7 );
+
+        /* high part, use pmaddwd, results in 4 32-bit */
+        xmm_hi_07 = _mm_madd_epi16( psLPC_Q14_hi_01234567, a_Q12_01234567 );
+        xmm_hi_8F = _mm_madd_epi16( psLPC_Q14_hi_89ABCDEF, a_Q12_89ABCDEF );
+
+        /* low part, use pmulhw, results in 8 16-bit, note we need simulate unsigned * signed, _mm_srai_epi16(psLPC_Q14_lo_01234567, 15) */
+        xmm_tempa = _mm_cmpgt_epi16( _mm_setzero_si128(), psLPC_Q14_lo_01234567 );
+        xmm_tempb = _mm_cmpgt_epi16( _mm_setzero_si128(), psLPC_Q14_lo_89ABCDEF );
+
+        xmm_tempa = _mm_and_si128( xmm_tempa, a_Q12_01234567 );
+        xmm_tempb = _mm_and_si128( xmm_tempb, a_Q12_89ABCDEF );
+
+        xmm_lo_07 = _mm_mulhi_epi16( psLPC_Q14_lo_01234567, a_Q12_01234567 );
+        xmm_lo_8F = _mm_mulhi_epi16( psLPC_Q14_lo_89ABCDEF, a_Q12_89ABCDEF );
+
+        xmm_lo_07 = _mm_add_epi16( xmm_lo_07, xmm_tempa );
+        xmm_lo_8F = _mm_add_epi16( xmm_lo_8F, xmm_tempb );
+
+        xmm_lo_07 = _mm_madd_epi16( xmm_lo_07, xmm_one );
+        xmm_lo_8F = _mm_madd_epi16( xmm_lo_8F, xmm_one );
+
+        /* accumulate */
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, xmm_hi_8F );
+        xmm_lo_07 = _mm_add_epi32( xmm_lo_07, xmm_lo_8F );
+
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, xmm_lo_07 );
+
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, _mm_unpackhi_epi64(xmm_hi_07, xmm_hi_07 ) );
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, _mm_shufflelo_epi16(xmm_hi_07, 0x0E ) );
+
+        LPC_pred_Q10 += _mm_cvtsi128_si32( xmm_hi_07 );
+
+        /* Long-term prediction */
+        if ( opus_likely( signalType == TYPE_VOICED ) ) {
+            /* Unrolled loop */
+            /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
+            LTP_pred_Q13 = 2;
+            {
+                __m128i b_Q14_3210, b_Q14_0123, pred_lag_ptr_0123;
+
+                b_Q14_3210 = OP_CVTEPI16_EPI32_M64( b_Q14 );
+                b_Q14_0123 = _mm_shuffle_epi32( b_Q14_3210, 0x1B );
+
+                /* loaded: [0] [-1] [-2] [-3] */
+                pred_lag_ptr_0123 = _mm_loadu_si128( (__m128i *)(&pred_lag_ptr[ -3 ] ) );
+                /* shuffle to [-3] [-2] [-1] [0] and to new xmm */
+                xmm_tempa = _mm_shuffle_epi32( pred_lag_ptr_0123, 0x1B );
+                /*64-bit multiply, a[2] * b[-2], a[0] * b[0] */
+                xmm_tempa = _mm_mul_epi32( xmm_tempa, b_Q14_3210 );
+                /* right shift 2 bytes (16 bits), zero extended */
+                xmm_tempa = _mm_srli_si128( xmm_tempa, 2 );
+
+                /* a[1] * b[-1], a[3] * b[-3] */
+                pred_lag_ptr_0123 = _mm_mul_epi32( pred_lag_ptr_0123, b_Q14_0123 );
+                pred_lag_ptr_0123 = _mm_srli_si128( pred_lag_ptr_0123, 2 );
+
+                pred_lag_ptr_0123 = _mm_add_epi32( pred_lag_ptr_0123, xmm_tempa );
+                /* equal shift right 8 bytes*/
+                xmm_tempa = _mm_shuffle_epi32( pred_lag_ptr_0123, _MM_SHUFFLE( 0, 0, 3, 2 ) );
+                xmm_tempa = _mm_add_epi32( xmm_tempa, pred_lag_ptr_0123 );
+
+                LTP_pred_Q13 += _mm_cvtsi128_si32( xmm_tempa );
+
+                LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );
+                pred_lag_ptr++;
+            }
+        }
+
+        /* Noise shape feedback */
+        NSQ->sAR2_Q14[ 9 ] = NSQ->sAR2_Q14[ 8 ];
+        NSQ->sAR2_Q14[ 8 ] = _mm_cvtsi128_si32( _mm_srli_si128(_mm_unpackhi_epi16( sAR2_Q14_lo_76543210, sAR2_Q14_hi_76543210 ), 12 ) );
+
+        sAR2_Q14_hi_76543210 = _mm_slli_si128( sAR2_Q14_hi_76543210, 2 );
+        sAR2_Q14_lo_76543210 = _mm_slli_si128( sAR2_Q14_lo_76543210, 2 );
+
+        sAR2_Q14_hi_76543210 = _mm_insert_epi16( sAR2_Q14_hi_76543210, (xq_Q14 >> 16), 0 );
+        sAR2_Q14_lo_76543210 = _mm_insert_epi16( sAR2_Q14_lo_76543210, (xq_Q14),       0 );
+
+        /* high part, use pmaddwd, results in 4 32-bit */
+        xmm_hi_07 = _mm_madd_epi16( sAR2_Q14_hi_76543210, AR_shp_Q13_76543210 );
+
+        /* low part, use pmulhw, results in 8 16-bit, note we need simulate unsigned * signed,_mm_srai_epi16(sAR2_Q14_lo_76543210, 15) */
+        xmm_tempa = _mm_cmpgt_epi16( _mm_setzero_si128(), sAR2_Q14_lo_76543210 );
+        xmm_tempa = _mm_and_si128( xmm_tempa, AR_shp_Q13_76543210 );
+
+        xmm_lo_07 = _mm_mulhi_epi16( sAR2_Q14_lo_76543210, AR_shp_Q13_76543210 );
+        xmm_lo_07 = _mm_add_epi16( xmm_lo_07, xmm_tempa );
+
+        xmm_lo_07 = _mm_madd_epi16( xmm_lo_07, xmm_one );
+
+        /* accumulate */
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, xmm_lo_07 );
+
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, _mm_unpackhi_epi64(xmm_hi_07, xmm_hi_07 ) );
+        xmm_hi_07 = _mm_add_epi32( xmm_hi_07, _mm_shufflelo_epi16(xmm_hi_07, 0x0E ) );
+
+        n_AR_Q12 = 5 + _mm_cvtsi128_si32( xmm_hi_07 );
+
+        n_AR_Q12 = silk_SMLAWB( n_AR_Q12, NSQ->sAR2_Q14[ 8 ], AR_shp_Q13[ 8 ] );
+        n_AR_Q12 = silk_SMLAWB( n_AR_Q12, NSQ->sAR2_Q14[ 9 ], AR_shp_Q13[ 9 ] );
+
+        n_AR_Q12 = silk_LSHIFT32( n_AR_Q12, 1 );                                /* Q11 -> Q12 */
+        n_AR_Q12 = silk_SMLAWB( n_AR_Q12, sLF_AR_shp_Q14, Tilt_Q14 );
+
+        n_LF_Q12 = silk_SMULWB( NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx - 1 ], LF_shp_Q14 );
+        n_LF_Q12 = silk_SMLAWT( n_LF_Q12, sLF_AR_shp_Q14, LF_shp_Q14 );
+
+        silk_assert( lag > 0 || signalType != TYPE_VOICED );
+
+        /* Combine prediction and noise shaping signals */
+        tmp1 = silk_SUB32( silk_LSHIFT32( LPC_pred_Q10, 2 ), n_AR_Q12 );        /* Q12 */
+        tmp1 = silk_SUB32( tmp1, n_LF_Q12 );                                    /* Q12 */
+        if( lag > 0 ) {
+            /* Symmetric, packed FIR coefficients */
+            n_LTP_Q13 = silk_SMULWB( silk_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );
+            n_LTP_Q13 = silk_SMLAWT( n_LTP_Q13, shp_lag_ptr[ -1 ],                      HarmShapeFIRPacked_Q14 );
+            n_LTP_Q13 = silk_LSHIFT( n_LTP_Q13, 1 );
+            shp_lag_ptr++;
+
+            tmp2 = silk_SUB32( LTP_pred_Q13, n_LTP_Q13 );                       /* Q13 */
+            tmp1 = silk_ADD_LSHIFT32( tmp2, tmp1, 1 );                          /* Q13 */
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 3 );                                /* Q10 */
+        } else {
+            tmp1 = silk_RSHIFT_ROUND( tmp1, 2 );                                /* Q10 */
+        }
+
+        r_Q10 = silk_SUB32( x_sc_Q10[ i ], tmp1 );                              /* residual error Q10 */
+
+        /* Generate dither */
+        NSQ->rand_seed = silk_RAND( NSQ->rand_seed );
+
+        /* Flip sign depending on dither */
+        tmp2 = -r_Q10;
+        if ( NSQ->rand_seed < 0 ) r_Q10 = tmp2;
+
+        r_Q10 = silk_LIMIT_32( r_Q10, -(31 << 10), 30 << 10 );
+
+        /* Find two quantization level candidates and measure their rate-distortion */
+        q1_Q10 = silk_SUB32( r_Q10, offset_Q10 );
+        q1_Q0 = silk_RSHIFT( q1_Q10, 10 );
+
+        q1_Q10 = table[q1_Q0][0];
+        q2_Q10 = table[q1_Q0][1];
+
+        if (r_Q10 * table[q1_Q0][2] - table[q1_Q0][3] < 0)
+        {
+            q1_Q10 = q2_Q10;
+        }
+
+        pulses[ i ] = (opus_int8)silk_RSHIFT_ROUND( q1_Q10, 10 );
+
+        /* Excitation */
+        exc_Q14 = silk_LSHIFT( q1_Q10, 4 );
+
+        tmp2 = -exc_Q14;
+        if ( NSQ->rand_seed < 0 ) exc_Q14 = tmp2;
+
+        /* Add predictions */
+        LPC_exc_Q14 = silk_ADD_LSHIFT32( exc_Q14, LTP_pred_Q13, 1 );
+        xq_Q14      = silk_ADD_LSHIFT32( LPC_exc_Q14, LPC_pred_Q10, 4 );
+
+        /* Update states */
+        psLPC_Q14++;
+        *psLPC_Q14 = xq_Q14;
+        sLF_AR_shp_Q14 = silk_SUB_LSHIFT32( xq_Q14, n_AR_Q12, 2 );
+
+        NSQ->sLTP_shp_Q14[ NSQ->sLTP_shp_buf_idx ] = silk_SUB_LSHIFT32( sLF_AR_shp_Q14, n_LF_Q12, 2 );
+        sLTP_Q15[ NSQ->sLTP_buf_idx ] = silk_LSHIFT( LPC_exc_Q14, 1 );
+        NSQ->sLTP_shp_buf_idx++;
+        NSQ->sLTP_buf_idx++;
+
+        /* Make dither dependent on quantized signal */
+        NSQ->rand_seed = silk_ADD32_ovflw( NSQ->rand_seed, pulses[ i ] );
+    }
+
+    NSQ->sLF_AR_shp_Q14 = sLF_AR_shp_Q14;
+
+    /* Scale XQ back to normal level before saving */
+    psLPC_Q14 = &NSQ->sLPC_Q14[ NSQ_LPC_BUF_LENGTH ];
+
+    /* write back sAR2_Q14 */
+    xmm_tempa = _mm_unpackhi_epi16( sAR2_Q14_lo_76543210, sAR2_Q14_hi_76543210 );
+    xmm_tempb = _mm_unpacklo_epi16( sAR2_Q14_lo_76543210, sAR2_Q14_hi_76543210 );
+    _mm_storeu_si128( (__m128i *)(&NSQ->sAR2_Q14[ 4 ]), xmm_tempa );
+    _mm_storeu_si128( (__m128i *)(&NSQ->sAR2_Q14[ 0 ]), xmm_tempb );
+
+    /* xq[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( psLPC_Q14[ i ], Gain_Q10 ), 8 ) ); */
+    {
+        __m128i xmm_Gain_Q10;
+        __m128i xmm_xq_Q14_3210, xmm_xq_Q14_x3x1, xmm_xq_Q14_7654, xmm_xq_Q14_x7x5;
+
+        /* prepare (1 << 7) in packed 4 32-bits */
+        xmm_tempa = _mm_set1_epi32( (1 << 7) );
+
+        /* prepare Gain_Q10 in packed 4 32-bits */
+        xmm_Gain_Q10 = _mm_set1_epi32( Gain_Q10 );
+
+        /* process xq */
+        for (i = 0; i < length - 7; i += 8)
+        {
+            xmm_xq_Q14_3210 = _mm_loadu_si128( (__m128i *)(&(psLPC_Q14[ i + 0 ] ) ) );
+            xmm_xq_Q14_7654 = _mm_loadu_si128( (__m128i *)(&(psLPC_Q14[ i + 4 ] ) ) );
+
+            /* equal shift right 4 bytes*/
+            xmm_xq_Q14_x3x1 = _mm_shuffle_epi32( xmm_xq_Q14_3210, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+            /* equal shift right 4 bytes*/
+            xmm_xq_Q14_x7x5 = _mm_shuffle_epi32( xmm_xq_Q14_7654, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+            xmm_xq_Q14_3210 = _mm_mul_epi32( xmm_xq_Q14_3210, xmm_Gain_Q10 );
+            xmm_xq_Q14_x3x1 = _mm_mul_epi32( xmm_xq_Q14_x3x1, xmm_Gain_Q10 );
+            xmm_xq_Q14_7654 = _mm_mul_epi32( xmm_xq_Q14_7654, xmm_Gain_Q10 );
+            xmm_xq_Q14_x7x5 = _mm_mul_epi32( xmm_xq_Q14_x7x5, xmm_Gain_Q10 );
+
+            xmm_xq_Q14_3210 = _mm_srli_epi64( xmm_xq_Q14_3210, 16 );
+            xmm_xq_Q14_x3x1 = _mm_slli_epi64( xmm_xq_Q14_x3x1, 16 );
+            xmm_xq_Q14_7654 = _mm_srli_epi64( xmm_xq_Q14_7654, 16 );
+            xmm_xq_Q14_x7x5 = _mm_slli_epi64( xmm_xq_Q14_x7x5, 16 );
+
+            xmm_xq_Q14_3210 = _mm_blend_epi16( xmm_xq_Q14_3210, xmm_xq_Q14_x3x1, 0xCC );
+            xmm_xq_Q14_7654 = _mm_blend_epi16( xmm_xq_Q14_7654, xmm_xq_Q14_x7x5, 0xCC );
+
+            /* silk_RSHIFT_ROUND(xq, 8) */
+            xmm_xq_Q14_3210 = _mm_add_epi32( xmm_xq_Q14_3210, xmm_tempa );
+            xmm_xq_Q14_7654 = _mm_add_epi32( xmm_xq_Q14_7654, xmm_tempa );
+
+            xmm_xq_Q14_3210 = _mm_srai_epi32( xmm_xq_Q14_3210, 8 );
+            xmm_xq_Q14_7654 = _mm_srai_epi32( xmm_xq_Q14_7654, 8 );
+
+            /* silk_SAT16 */
+            xmm_xq_Q14_3210 = _mm_packs_epi32( xmm_xq_Q14_3210, xmm_xq_Q14_7654 );
+
+            /* save to xq */
+            _mm_storeu_si128( (__m128i *)(&xq[ i ] ), xmm_xq_Q14_3210 );
+        }
+    }
+    for ( ; i < length; i++)
+    {
+        xq[i] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( psLPC_Q14[ i ], Gain_Q10 ), 8 ) );
+    }
+
+    /* Update LPC synth buffer */
+    silk_memcpy( NSQ->sLPC_Q14, &NSQ->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( opus_int32 ) );
+}
+
+static OPUS_INLINE void silk_nsq_scale_states_sse4_1(
+    const silk_encoder_state *psEncC,           /* I    Encoder State                   */
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    const opus_int32    x_Q3[],                 /* I    input in Q3                     */
+    opus_int32          x_sc_Q10[],             /* O    input scaled with 1/Gain        */
+    const opus_int16    sLTP[],                 /* I    re-whitened LTP state in Q0     */
+    opus_int32          sLTP_Q15[],             /* O    LTP state matching scaled input */
+    opus_int            subfr,                  /* I    subframe number                 */
+    const opus_int      LTP_scale_Q14,          /* I                                    */
+    const opus_int32    Gains_Q16[ MAX_NB_SUBFR ], /* I                                 */
+    const opus_int      pitchL[ MAX_NB_SUBFR ], /* I    Pitch lag                       */
+    const opus_int      signal_type             /* I    Signal type                     */
+)
+{
+    opus_int   i, lag;
+    opus_int32 gain_adj_Q16, inv_gain_Q31, inv_gain_Q23;
+    __m128i xmm_inv_gain_Q23, xmm_x_Q3_x2x0, xmm_x_Q3_x3x1;
+
+    lag          = pitchL[ subfr ];
+    inv_gain_Q31 = silk_INVERSE32_varQ( silk_max( Gains_Q16[ subfr ], 1 ), 47 );
+    silk_assert( inv_gain_Q31 != 0 );
+
+    /* Calculate gain adjustment factor */
+    if( Gains_Q16[ subfr ] != NSQ->prev_gain_Q16 ) {
+        gain_adj_Q16 =  silk_DIV32_varQ( NSQ->prev_gain_Q16, Gains_Q16[ subfr ], 16 );
+    } else {
+        gain_adj_Q16 = (opus_int32)1 << 16;
+    }
+
+    /* Scale input */
+    inv_gain_Q23 = silk_RSHIFT_ROUND( inv_gain_Q31, 8 );
+
+    /* prepare inv_gain_Q23 in packed 4 32-bits */
+    xmm_inv_gain_Q23 = _mm_set1_epi32(inv_gain_Q23);
+
+    for( i = 0; i < psEncC->subfr_length - 3; i += 4 ) {
+        xmm_x_Q3_x2x0 = _mm_loadu_si128( (__m128i *)(&(x_Q3[ i ] ) ) );
+
+        /* equal shift right 4 bytes*/
+        xmm_x_Q3_x3x1 = _mm_shuffle_epi32( xmm_x_Q3_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+        xmm_x_Q3_x2x0 = _mm_mul_epi32( xmm_x_Q3_x2x0, xmm_inv_gain_Q23 );
+        xmm_x_Q3_x3x1 = _mm_mul_epi32( xmm_x_Q3_x3x1, xmm_inv_gain_Q23 );
+
+        xmm_x_Q3_x2x0 = _mm_srli_epi64( xmm_x_Q3_x2x0, 16 );
+        xmm_x_Q3_x3x1 = _mm_slli_epi64( xmm_x_Q3_x3x1, 16 );
+
+        xmm_x_Q3_x2x0 = _mm_blend_epi16( xmm_x_Q3_x2x0, xmm_x_Q3_x3x1, 0xCC );
+
+        _mm_storeu_si128( (__m128i *)(&(x_sc_Q10[ i ] ) ), xmm_x_Q3_x2x0 );
+    }
+
+    for( ; i < psEncC->subfr_length; i++ ) {
+        x_sc_Q10[ i ] = silk_SMULWW( x_Q3[ i ], inv_gain_Q23 );
+    }
+
+    /* Save inverse gain */
+    NSQ->prev_gain_Q16 = Gains_Q16[ subfr ];
+
+    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */
+    if( NSQ->rewhite_flag ) {
+        if( subfr == 0 ) {
+            /* Do LTP downscaling */
+            inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, LTP_scale_Q14 ), 2 );
+        }
+        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+            silk_assert( i < MAX_FRAME_LENGTH );
+            sLTP_Q15[ i ] = silk_SMULWB( inv_gain_Q31, sLTP[ i ] );
+        }
+    }
+
+    /* Adjust for changing gain */
+    if( gain_adj_Q16 != (opus_int32)1 << 16 ) {
+        /* Scale long-term shaping state */
+        __m128i xmm_gain_adj_Q16, xmm_sLTP_shp_Q14_x2x0, xmm_sLTP_shp_Q14_x3x1;
+
+        /* prepare gain_adj_Q16 in packed 4 32-bits */
+        xmm_gain_adj_Q16 = _mm_set1_epi32(gain_adj_Q16);
+
+        for( i = NSQ->sLTP_shp_buf_idx - psEncC->ltp_mem_length; i < NSQ->sLTP_shp_buf_idx - 3; i += 4 )
+        {
+            xmm_sLTP_shp_Q14_x2x0 = _mm_loadu_si128( (__m128i *)(&(NSQ->sLTP_shp_Q14[ i ] ) ) );
+            /* equal shift right 4 bytes*/
+            xmm_sLTP_shp_Q14_x3x1 = _mm_shuffle_epi32( xmm_sLTP_shp_Q14_x2x0, _MM_SHUFFLE( 0, 3, 2, 1 ) );
+
+            xmm_sLTP_shp_Q14_x2x0 = _mm_mul_epi32( xmm_sLTP_shp_Q14_x2x0, xmm_gain_adj_Q16 );
+            xmm_sLTP_shp_Q14_x3x1 = _mm_mul_epi32( xmm_sLTP_shp_Q14_x3x1, xmm_gain_adj_Q16 );
+
+            xmm_sLTP_shp_Q14_x2x0 = _mm_srli_epi64( xmm_sLTP_shp_Q14_x2x0, 16 );
+            xmm_sLTP_shp_Q14_x3x1 = _mm_slli_epi64( xmm_sLTP_shp_Q14_x3x1, 16 );
+
+            xmm_sLTP_shp_Q14_x2x0 = _mm_blend_epi16( xmm_sLTP_shp_Q14_x2x0, xmm_sLTP_shp_Q14_x3x1, 0xCC );
+
+            _mm_storeu_si128( (__m128i *)(&(NSQ->sLTP_shp_Q14[ i ] ) ), xmm_sLTP_shp_Q14_x2x0 );
+        }
+
+        for( ; i < NSQ->sLTP_shp_buf_idx; i++ ) {
+            NSQ->sLTP_shp_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q14[ i ] );
+        }
+
+        /* Scale long-term prediction state */
+        if( signal_type == TYPE_VOICED && NSQ->rewhite_flag == 0 ) {
+            for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {
+                sLTP_Q15[ i ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ i ] );
+            }
+        }
+
+        NSQ->sLF_AR_shp_Q14 = silk_SMULWW( gain_adj_Q16, NSQ->sLF_AR_shp_Q14 );
+
+        /* Scale short-term prediction and shaping states */
+        for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {
+            NSQ->sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sLPC_Q14[ i ] );
+        }
+        for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {
+            NSQ->sAR2_Q14[ i ] = silk_SMULWW( gain_adj_Q16, NSQ->sAR2_Q14[ i ] );
+        }
+    }
+}
diff --git a/opus/silk/x86/SigProc_FIX_sse.h b/opus/silk/x86/SigProc_FIX_sse.h
new file mode 100644 (file)
index 0000000..61efa8d
--- /dev/null
@@ -0,0 +1,94 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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 SIGPROC_FIX_SSE_H
+#define SIGPROC_FIX_SSE_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+void silk_burg_modified_sse4_1(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */
+);
+
+#if defined(OPUS_X86_PRESUME_SSE4_1)
+#define silk_burg_modified(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch) \
+    ((void)(arch), silk_burg_modified_sse4_1(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch))
+
+#else
+
+extern void (*const SILK_BURG_MODIFIED_IMPL[OPUS_ARCHMASK + 1])(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */);
+
+#  define silk_burg_modified(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch) \
+    ((*SILK_BURG_MODIFIED_IMPL[(arch) & OPUS_ARCHMASK])(res_nrg, res_nrg_Q, A_Q16, x, minInvGain_Q30, subfr_length, nb_subfr, D, arch))
+
+#endif
+
+opus_int64 silk_inner_prod16_aligned_64_sse4_1(
+    const opus_int16 *inVec1,
+    const opus_int16 *inVec2,
+    const opus_int   len
+);
+
+
+#if defined(OPUS_X86_PRESUME_SSE4_1)
+
+#define silk_inner_prod16_aligned_64(inVec1, inVec2, len, arch) \
+    ((void)(arch),silk_inner_prod16_aligned_64_sse4_1(inVec1, inVec2, len))
+
+#else
+
+extern opus_int64 (*const SILK_INNER_PROD16_ALIGNED_64_IMPL[OPUS_ARCHMASK + 1])(
+                    const opus_int16 *inVec1,
+                    const opus_int16 *inVec2,
+                    const opus_int   len);
+
+#  define silk_inner_prod16_aligned_64(inVec1, inVec2, len, arch) \
+    ((*SILK_INNER_PROD16_ALIGNED_64_IMPL[(arch) & OPUS_ARCHMASK])(inVec1, inVec2, len))
+
+#endif
+#endif
+#endif
diff --git a/opus/silk/x86/VAD_sse.c b/opus/silk/x86/VAD_sse.c
new file mode 100644 (file)
index 0000000..4e90f44
--- /dev/null
@@ -0,0 +1,277 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+
+#include "main.h"
+#include "stack_alloc.h"
+
+/* Weighting factors for tilt measure */
+static const opus_int32 tiltWeights[ VAD_N_BANDS ] = { 30000, 6000, -12000, -12000 };
+
+/***************************************/
+/* Get the speech activity level in Q8 */
+/***************************************/
+opus_int silk_VAD_GetSA_Q8_sse4_1(                  /* O    Return value, 0 if success                  */
+    silk_encoder_state          *psEncC,            /* I/O  Encoder state                               */
+    const opus_int16            pIn[]               /* I    PCM input                                   */
+)
+{
+    opus_int   SA_Q15, pSNR_dB_Q7, input_tilt;
+    opus_int   decimated_framelength1, decimated_framelength2;
+    opus_int   decimated_framelength;
+    opus_int   dec_subframe_length, dec_subframe_offset, SNR_Q7, i, b, s;
+    opus_int32 sumSquared, smooth_coef_Q16;
+    opus_int16 HPstateTmp;
+    VARDECL( opus_int16, X );
+    opus_int32 Xnrg[ VAD_N_BANDS ];
+    opus_int32 NrgToNoiseRatio_Q8[ VAD_N_BANDS ];
+    opus_int32 speech_nrg, x_tmp;
+    opus_int   X_offset[ VAD_N_BANDS ];
+    opus_int   ret = 0;
+    silk_VAD_state *psSilk_VAD = &psEncC->sVAD;
+
+    SAVE_STACK;
+
+    /* Safety checks */
+    silk_assert( VAD_N_BANDS == 4 );
+    silk_assert( MAX_FRAME_LENGTH >= psEncC->frame_length );
+    silk_assert( psEncC->frame_length <= 512 );
+    silk_assert( psEncC->frame_length == 8 * silk_RSHIFT( psEncC->frame_length, 3 ) );
+
+    /***********************/
+    /* Filter and Decimate */
+    /***********************/
+    decimated_framelength1 = silk_RSHIFT( psEncC->frame_length, 1 );
+    decimated_framelength2 = silk_RSHIFT( psEncC->frame_length, 2 );
+    decimated_framelength = silk_RSHIFT( psEncC->frame_length, 3 );
+    /* Decimate into 4 bands:
+       0       L      3L       L              3L                             5L
+               -      --       -              --                             --
+               8       8       2               4                              4
+
+       [0-1 kHz| temp. |1-2 kHz|    2-4 kHz    |            4-8 kHz           |
+
+       They're arranged to allow the minimal ( frame_length / 4 ) extra
+       scratch space during the downsampling process */
+    X_offset[ 0 ] = 0;
+    X_offset[ 1 ] = decimated_framelength + decimated_framelength2;
+    X_offset[ 2 ] = X_offset[ 1 ] + decimated_framelength;
+    X_offset[ 3 ] = X_offset[ 2 ] + decimated_framelength2;
+    ALLOC( X, X_offset[ 3 ] + decimated_framelength1, opus_int16 );
+
+    /* 0-8 kHz to 0-4 kHz and 4-8 kHz */
+    silk_ana_filt_bank_1( pIn, &psSilk_VAD->AnaState[  0 ],
+        X, &X[ X_offset[ 3 ] ], psEncC->frame_length );
+
+    /* 0-4 kHz to 0-2 kHz and 2-4 kHz */
+    silk_ana_filt_bank_1( X, &psSilk_VAD->AnaState1[ 0 ],
+        X, &X[ X_offset[ 2 ] ], decimated_framelength1 );
+
+    /* 0-2 kHz to 0-1 kHz and 1-2 kHz */
+    silk_ana_filt_bank_1( X, &psSilk_VAD->AnaState2[ 0 ],
+        X, &X[ X_offset[ 1 ] ], decimated_framelength2 );
+
+    /*********************************************/
+    /* HP filter on lowest band (differentiator) */
+    /*********************************************/
+    X[ decimated_framelength - 1 ] = silk_RSHIFT( X[ decimated_framelength - 1 ], 1 );
+    HPstateTmp = X[ decimated_framelength - 1 ];
+    for( i = decimated_framelength - 1; i > 0; i-- ) {
+        X[ i - 1 ]  = silk_RSHIFT( X[ i - 1 ], 1 );
+        X[ i ]     -= X[ i - 1 ];
+    }
+    X[ 0 ] -= psSilk_VAD->HPstate;
+    psSilk_VAD->HPstate = HPstateTmp;
+
+    /*************************************/
+    /* Calculate the energy in each band */
+    /*************************************/
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* Find the decimated framelength in the non-uniformly divided bands */
+        decimated_framelength = silk_RSHIFT( psEncC->frame_length, silk_min_int( VAD_N_BANDS - b, VAD_N_BANDS - 1 ) );
+
+        /* Split length into subframe lengths */
+        dec_subframe_length = silk_RSHIFT( decimated_framelength, VAD_INTERNAL_SUBFRAMES_LOG2 );
+        dec_subframe_offset = 0;
+
+        /* Compute energy per sub-frame */
+        /* initialize with summed energy of last subframe */
+        Xnrg[ b ] = psSilk_VAD->XnrgSubfr[ b ];
+        for( s = 0; s < VAD_INTERNAL_SUBFRAMES; s++ ) {
+            __m128i xmm_X, xmm_acc;
+            sumSquared = 0;
+
+            xmm_acc = _mm_setzero_si128();
+
+            for( i = 0; i < dec_subframe_length - 7; i += 8 )
+            {
+                xmm_X   = _mm_loadu_si128( (__m128i *)&(X[ X_offset[ b ] + i + dec_subframe_offset ] ) );
+                xmm_X   = _mm_srai_epi16( xmm_X, 3 );
+                xmm_X   = _mm_madd_epi16( xmm_X, xmm_X );
+                xmm_acc = _mm_add_epi32( xmm_acc, xmm_X );
+            }
+
+            xmm_acc = _mm_add_epi32( xmm_acc, _mm_unpackhi_epi64( xmm_acc, xmm_acc ) );
+            xmm_acc = _mm_add_epi32( xmm_acc, _mm_shufflelo_epi16( xmm_acc, 0x0E ) );
+
+            sumSquared += _mm_cvtsi128_si32( xmm_acc );
+
+            for( ; i < dec_subframe_length; i++ ) {
+                /* The energy will be less than dec_subframe_length * ( silk_int16_MIN / 8 ) ^ 2.            */
+                /* Therefore we can accumulate with no risk of overflow (unless dec_subframe_length > 128)  */
+                x_tmp = silk_RSHIFT(
+                    X[ X_offset[ b ] + i + dec_subframe_offset ], 3 );
+                sumSquared = silk_SMLABB( sumSquared, x_tmp, x_tmp );
+
+                /* Safety check */
+                silk_assert( sumSquared >= 0 );
+            }
+
+            /* Add/saturate summed energy of current subframe */
+            if( s < VAD_INTERNAL_SUBFRAMES - 1 ) {
+                Xnrg[ b ] = silk_ADD_POS_SAT32( Xnrg[ b ], sumSquared );
+            } else {
+                /* Look-ahead subframe */
+                Xnrg[ b ] = silk_ADD_POS_SAT32( Xnrg[ b ], silk_RSHIFT( sumSquared, 1 ) );
+            }
+
+            dec_subframe_offset += dec_subframe_length;
+        }
+        psSilk_VAD->XnrgSubfr[ b ] = sumSquared;
+    }
+
+    /********************/
+    /* Noise estimation */
+    /********************/
+    silk_VAD_GetNoiseLevels( &Xnrg[ 0 ], psSilk_VAD );
+
+    /***********************************************/
+    /* Signal-plus-noise to noise ratio estimation */
+    /***********************************************/
+    sumSquared = 0;
+    input_tilt = 0;
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        speech_nrg = Xnrg[ b ] - psSilk_VAD->NL[ b ];
+        if( speech_nrg > 0 ) {
+            /* Divide, with sufficient resolution */
+            if( ( Xnrg[ b ] & 0xFF800000 ) == 0 ) {
+                NrgToNoiseRatio_Q8[ b ] = silk_DIV32( silk_LSHIFT( Xnrg[ b ], 8 ), psSilk_VAD->NL[ b ] + 1 );
+            } else {
+                NrgToNoiseRatio_Q8[ b ] = silk_DIV32( Xnrg[ b ], silk_RSHIFT( psSilk_VAD->NL[ b ], 8 ) + 1 );
+            }
+
+            /* Convert to log domain */
+            SNR_Q7 = silk_lin2log( NrgToNoiseRatio_Q8[ b ] ) - 8 * 128;
+
+            /* Sum-of-squares */
+            sumSquared = silk_SMLABB( sumSquared, SNR_Q7, SNR_Q7 );          /* Q14 */
+
+            /* Tilt measure */
+            if( speech_nrg < ( (opus_int32)1 << 20 ) ) {
+                /* Scale down SNR value for small subband speech energies */
+                SNR_Q7 = silk_SMULWB( silk_LSHIFT( silk_SQRT_APPROX( speech_nrg ), 6 ), SNR_Q7 );
+            }
+            input_tilt = silk_SMLAWB( input_tilt, tiltWeights[ b ], SNR_Q7 );
+        } else {
+            NrgToNoiseRatio_Q8[ b ] = 256;
+        }
+    }
+
+    /* Mean-of-squares */
+    sumSquared = silk_DIV32_16( sumSquared, VAD_N_BANDS ); /* Q14 */
+
+    /* Root-mean-square approximation, scale to dBs, and write to output pointer */
+    pSNR_dB_Q7 = (opus_int16)( 3 * silk_SQRT_APPROX( sumSquared ) ); /* Q7 */
+
+    /*********************************/
+    /* Speech Probability Estimation */
+    /*********************************/
+    SA_Q15 = silk_sigm_Q15( silk_SMULWB( VAD_SNR_FACTOR_Q16, pSNR_dB_Q7 ) - VAD_NEGATIVE_OFFSET_Q5 );
+
+    /**************************/
+    /* Frequency Tilt Measure */
+    /**************************/
+    psEncC->input_tilt_Q15 = silk_LSHIFT( silk_sigm_Q15( input_tilt ) - 16384, 1 );
+
+    /**************************************************/
+    /* Scale the sigmoid output based on power levels */
+    /**************************************************/
+    speech_nrg = 0;
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* Accumulate signal-without-noise energies, higher frequency bands have more weight */
+        speech_nrg += ( b + 1 ) * silk_RSHIFT( Xnrg[ b ] - psSilk_VAD->NL[ b ], 4 );
+    }
+
+    /* Power scaling */
+    if( speech_nrg <= 0 ) {
+        SA_Q15 = silk_RSHIFT( SA_Q15, 1 );
+    } else if( speech_nrg < 32768 ) {
+        if( psEncC->frame_length == 10 * psEncC->fs_kHz ) {
+            speech_nrg = silk_LSHIFT_SAT32( speech_nrg, 16 );
+        } else {
+            speech_nrg = silk_LSHIFT_SAT32( speech_nrg, 15 );
+        }
+
+        /* square-root */
+        speech_nrg = silk_SQRT_APPROX( speech_nrg );
+        SA_Q15 = silk_SMULWB( 32768 + speech_nrg, SA_Q15 );
+    }
+
+    /* Copy the resulting speech activity in Q8 */
+    psEncC->speech_activity_Q8 = silk_min_int( silk_RSHIFT( SA_Q15, 7 ), silk_uint8_MAX );
+
+    /***********************************/
+    /* Energy Level and SNR estimation */
+    /***********************************/
+    /* Smoothing coefficient */
+    smooth_coef_Q16 = silk_SMULWB( VAD_SNR_SMOOTH_COEF_Q18, silk_SMULWB( (opus_int32)SA_Q15, SA_Q15 ) );
+
+    if( psEncC->frame_length == 10 * psEncC->fs_kHz ) {
+        smooth_coef_Q16 >>= 1;
+    }
+
+    for( b = 0; b < VAD_N_BANDS; b++ ) {
+        /* compute smoothed energy-to-noise ratio per band */
+        psSilk_VAD->NrgRatioSmth_Q8[ b ] = silk_SMLAWB( psSilk_VAD->NrgRatioSmth_Q8[ b ],
+            NrgToNoiseRatio_Q8[ b ] - psSilk_VAD->NrgRatioSmth_Q8[ b ], smooth_coef_Q16 );
+
+        /* signal to noise ratio in dB per band */
+        SNR_Q7 = 3 * ( silk_lin2log( psSilk_VAD->NrgRatioSmth_Q8[b] ) - 8 * 128 );
+        /* quality = sigmoid( 0.25 * ( SNR_dB - 16 ) ); */
+        psEncC->input_quality_bands_Q15[ b ] = silk_sigm_Q15( silk_RSHIFT( SNR_Q7 - 16 * 128, 4 ) );
+    }
+
+    RESTORE_STACK;
+    return( ret );
+}
diff --git a/opus/silk/x86/VQ_WMat_EC_sse.c b/opus/silk/x86/VQ_WMat_EC_sse.c
new file mode 100644 (file)
index 0000000..74d6c6d
--- /dev/null
@@ -0,0 +1,142 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <xmmintrin.h>
+#include <emmintrin.h>
+#include <smmintrin.h>
+#include "main.h"
+#include "celt/x86/x86cpu.h"
+
+/* Entropy constrained matrix-weighted VQ, hard-coded to 5-element vectors, for a single input data vector */
+void silk_VQ_WMat_EC_sse4_1(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *rate_dist_Q14,                 /* O    best weighted quant error + mu * rate       */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int16            *in_Q14,                        /* I    input vector to be quantized                */
+    const opus_int32            *W_Q18,                         /* I    weighting matrix                            */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              mu_Q9,                          /* I    tradeoff betw. weighted error and rate      */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    opus_int                    L                               /* I    number of vectors in codebook               */
+)
+{
+    opus_int   k, gain_tmp_Q7;
+    const opus_int8 *cb_row_Q7;
+    opus_int16 diff_Q14[ 5 ];
+    opus_int32 sum1_Q14, sum2_Q16;
+
+    __m128i C_tmp1, C_tmp2, C_tmp3, C_tmp4, C_tmp5;
+    /* Loop over codebook */
+    *rate_dist_Q14 = silk_int32_MAX;
+    cb_row_Q7 = cb_Q7;
+    for( k = 0; k < L; k++ ) {
+        gain_tmp_Q7 = cb_gain_Q7[k];
+
+        diff_Q14[ 0 ] = in_Q14[ 0 ] - silk_LSHIFT( cb_row_Q7[ 0 ], 7 );
+
+        C_tmp1 = OP_CVTEPI16_EPI32_M64( &in_Q14[ 1 ] );
+        C_tmp2 = OP_CVTEPI8_EPI32_M32( &cb_row_Q7[ 1 ] );
+        C_tmp2 = _mm_slli_epi32( C_tmp2, 7 );
+        C_tmp1 = _mm_sub_epi32( C_tmp1, C_tmp2 );
+
+        diff_Q14[ 1 ] = _mm_extract_epi16( C_tmp1, 0 );
+        diff_Q14[ 2 ] = _mm_extract_epi16( C_tmp1, 2 );
+        diff_Q14[ 3 ] = _mm_extract_epi16( C_tmp1, 4 );
+        diff_Q14[ 4 ] = _mm_extract_epi16( C_tmp1, 6 );
+
+        /* Weighted rate */
+        sum1_Q14 = silk_SMULBB( mu_Q9, cl_Q5[ k ] );
+
+        /* Penalty for too large gain */
+        sum1_Q14 = silk_ADD_LSHIFT32( sum1_Q14, silk_max( silk_SUB32( gain_tmp_Q7, max_gain_Q7 ), 0 ), 10 );
+
+        silk_assert( sum1_Q14 >= 0 );
+
+        /* first row of W_Q18 */
+        C_tmp3 = _mm_loadu_si128( (__m128i *)(&W_Q18[ 1 ] ) );
+        C_tmp4 = _mm_mul_epi32( C_tmp3, C_tmp1 );
+        C_tmp4 = _mm_srli_si128( C_tmp4, 2 );
+
+        C_tmp1 = _mm_shuffle_epi32( C_tmp1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* shift right 4 bytes */
+        C_tmp3 = _mm_shuffle_epi32( C_tmp3, _MM_SHUFFLE( 0, 3, 2, 1 ) ); /* shift right 4 bytes */
+
+        C_tmp5 = _mm_mul_epi32( C_tmp3, C_tmp1 );
+        C_tmp5 = _mm_srli_si128( C_tmp5, 2 );
+
+        C_tmp5 = _mm_add_epi32( C_tmp4, C_tmp5 );
+        C_tmp5 = _mm_slli_epi32( C_tmp5, 1 );
+
+        C_tmp5 = _mm_add_epi32( C_tmp5, _mm_shuffle_epi32( C_tmp5, _MM_SHUFFLE( 0, 0, 0, 2 ) ) );
+        sum2_Q16 = _mm_cvtsi128_si32( C_tmp5 );
+
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[  0 ], diff_Q14[ 0 ] );
+        sum1_Q14 = silk_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 0 ] );
+
+        /* second row of W_Q18 */
+        sum2_Q16 = silk_SMULWB(           W_Q18[  7 ], diff_Q14[ 2 ] );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[  8 ], diff_Q14[ 3 ] );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[  9 ], diff_Q14[ 4 ] );
+        sum2_Q16 = silk_LSHIFT( sum2_Q16, 1 );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[  6 ], diff_Q14[ 1 ] );
+        sum1_Q14 = silk_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 1 ] );
+
+        /* third row of W_Q18 */
+        sum2_Q16 = silk_SMULWB(           W_Q18[ 13 ], diff_Q14[ 3 ] );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[ 14 ], diff_Q14[ 4 ] );
+        sum2_Q16 = silk_LSHIFT( sum2_Q16, 1 );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[ 12 ], diff_Q14[ 2 ] );
+        sum1_Q14 = silk_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 2 ] );
+
+        /* fourth row of W_Q18 */
+        sum2_Q16 = silk_SMULWB(           W_Q18[ 19 ], diff_Q14[ 4 ] );
+        sum2_Q16 = silk_LSHIFT( sum2_Q16, 1 );
+        sum2_Q16 = silk_SMLAWB( sum2_Q16, W_Q18[ 18 ], diff_Q14[ 3 ] );
+        sum1_Q14 = silk_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 3 ] );
+
+        /* last row of W_Q18 */
+        sum2_Q16 = silk_SMULWB(           W_Q18[ 24 ], diff_Q14[ 4 ] );
+        sum1_Q14 = silk_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 4 ] );
+
+        silk_assert( sum1_Q14 >= 0 );
+
+        /* find best */
+        if( sum1_Q14 < *rate_dist_Q14 ) {
+            *rate_dist_Q14 = sum1_Q14;
+            *ind = (opus_int8)k;
+            *gain_Q7 = gain_tmp_Q7;
+        }
+
+        /* Go to next cbk vector */
+        cb_row_Q7 += LTP_ORDER;
+    }
+}
diff --git a/opus/silk/x86/main_sse.h b/opus/silk/x86/main_sse.h
new file mode 100644 (file)
index 0000000..2f15d44
--- /dev/null
@@ -0,0 +1,248 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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 MAIN_SSE_H
+#define MAIN_SSE_H
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+# if defined(OPUS_X86_MAY_HAVE_SSE4_1)
+
+#if 0 /* FIXME: SSE disabled until silk_VQ_WMat_EC_sse4_1() gets updated. */
+#  define OVERRIDE_silk_VQ_WMat_EC
+
+void silk_VQ_WMat_EC_sse4_1(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *rate_dist_Q14,                 /* O    best weighted quant error + mu * rate       */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int16            *in_Q14,                        /* I    input vector to be quantized                */
+    const opus_int32            *W_Q18,                         /* I    weighting matrix                            */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              mu_Q9,                          /* I    tradeoff betw. weighted error and rate      */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    opus_int                    L                               /* I    number of vectors in codebook               */
+);
+
+#if defined OPUS_X86_PRESUME_SSE4_1
+
+#define silk_VQ_WMat_EC(ind, rate_dist_Q14, gain_Q7, in_Q14, W_Q18, cb_Q7, cb_gain_Q7, cl_Q5, \
+                          mu_Q9, max_gain_Q7, L, arch) \
+    ((void)(arch),silk_VQ_WMat_EC_sse4_1(ind, rate_dist_Q14, gain_Q7, in_Q14, W_Q18, cb_Q7, cb_gain_Q7, cl_Q5, \
+                          mu_Q9, max_gain_Q7, L))
+
+#else
+
+extern void (*const SILK_VQ_WMAT_EC_IMPL[OPUS_ARCHMASK + 1])(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *rate_dist_Q14,                 /* O    best weighted quant error + mu * rate       */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int16            *in_Q14,                        /* I    input vector to be quantized                */
+    const opus_int32            *W_Q18,                         /* I    weighting matrix                            */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              mu_Q9,                          /* I    tradeoff betw. weighted error and rate      */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    opus_int                    L                               /* I    number of vectors in codebook               */
+);
+
+#  define silk_VQ_WMat_EC(ind, rate_dist_Q14, gain_Q7, in_Q14, W_Q18, cb_Q7, cb_gain_Q7, cl_Q5, \
+                          mu_Q9, max_gain_Q7, L, arch) \
+    ((*SILK_VQ_WMAT_EC_IMPL[(arch) & OPUS_ARCHMASK])(ind, rate_dist_Q14, gain_Q7, in_Q14, W_Q18, cb_Q7, cb_gain_Q7, cl_Q5, \
+                          mu_Q9, max_gain_Q7, L))
+
+#endif
+#endif
+
+#if 0 /* FIXME: SSE disabled until the NSQ code gets updated. */
+#  define OVERRIDE_silk_NSQ
+
+void silk_NSQ_sse4_1(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#if defined OPUS_X86_PRESUME_SSE4_1
+
+#define silk_NSQ(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((void)(arch),silk_NSQ_sse4_1(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+
+#else
+
+extern void (*const SILK_NSQ_IMPL[OPUS_ARCHMASK + 1])(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#  define silk_NSQ(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((*SILK_NSQ_IMPL[(arch) & OPUS_ARCHMASK])(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                   HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+
+#endif
+
+#  define OVERRIDE_silk_NSQ_del_dec
+
+void silk_NSQ_del_dec_sse4_1(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#if defined OPUS_X86_PRESUME_SSE4_1
+
+#define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((void)(arch),silk_NSQ_del_dec_sse4_1(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+
+#else
+
+extern void (*const SILK_NSQ_DEL_DEC_IMPL[OPUS_ARCHMASK + 1])(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+);
+
+#  define silk_NSQ_del_dec(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14, arch) \
+    ((*SILK_NSQ_DEL_DEC_IMPL[(arch) & OPUS_ARCHMASK])(psEncC, NSQ, psIndices, x_Q3, pulses, PredCoef_Q12, LTPCoef_Q14, AR2_Q13, \
+                           HarmShapeGain_Q14, Tilt_Q14, LF_shp_Q14, Gains_Q16, pitchL, Lambda_Q10, LTP_scale_Q14))
+
+#endif
+#endif
+
+void silk_noise_shape_quantizer(
+    silk_nsq_state      *NSQ,                   /* I/O  NSQ state                       */
+    opus_int            signalType,             /* I    Signal type                     */
+    const opus_int32    x_sc_Q10[],             /* I                                    */
+    opus_int8           pulses[],               /* O                                    */
+    opus_int16          xq[],                   /* O                                    */
+    opus_int32          sLTP_Q15[],             /* I/O  LTP state                       */
+    const opus_int16    a_Q12[],                /* I    Short term prediction coefs     */
+    const opus_int16    b_Q14[],                /* I    Long term prediction coefs      */
+    const opus_int16    AR_shp_Q13[],           /* I    Noise shaping AR coefs          */
+    opus_int            lag,                    /* I    Pitch lag                       */
+    opus_int32          HarmShapeFIRPacked_Q14, /* I                                    */
+    opus_int            Tilt_Q14,               /* I    Spectral tilt                   */
+    opus_int32          LF_shp_Q14,             /* I                                    */
+    opus_int32          Gain_Q16,               /* I                                    */
+    opus_int            Lambda_Q10,             /* I                                    */
+    opus_int            offset_Q10,             /* I                                    */
+    opus_int            length,                 /* I    Input length                    */
+    opus_int            shapingLPCOrder,        /* I    Noise shaping AR filter order   */
+    opus_int            predictLPCOrder,        /* I    Prediction filter order         */
+    int                 arch                    /* I    Architecture                    */
+);
+
+/**************************/
+/* Noise level estimation */
+/**************************/
+void silk_VAD_GetNoiseLevels(
+    const opus_int32            pX[ VAD_N_BANDS ],  /* I    subband energies                            */
+    silk_VAD_state              *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */
+);
+
+#  define OVERRIDE_silk_VAD_GetSA_Q8
+
+opus_int silk_VAD_GetSA_Q8_sse4_1(
+    silk_encoder_state *psEnC,
+    const opus_int16   pIn[]
+);
+
+#if defined(OPUS_X86_PRESUME_SSE4_1)
+#define silk_VAD_GetSA_Q8(psEnC, pIn, arch) ((void)(arch),silk_VAD_GetSA_Q8_sse4_1(psEnC, pIn))
+
+#else
+
+#  define silk_VAD_GetSA_Q8(psEnC, pIn, arch) \
+     ((*SILK_VAD_GETSA_Q8_IMPL[(arch) & OPUS_ARCHMASK])(psEnC, pIn))
+
+extern opus_int (*const SILK_VAD_GETSA_Q8_IMPL[OPUS_ARCHMASK + 1])(
+     silk_encoder_state *psEnC,
+     const opus_int16   pIn[]);
+
+#endif
+
+# endif
+#endif
diff --git a/opus/silk/x86/x86_silk_map.c b/opus/silk/x86/x86_silk_map.c
new file mode 100644 (file)
index 0000000..32dcc3c
--- /dev/null
@@ -0,0 +1,164 @@
+/* Copyright (c) 2014, Cisco Systems, INC
+   Written by XiangMingZhu WeiZhou MinPeng YanWang
+
+   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.
+
+   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.
+*/
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#include "celt/x86/x86cpu.h"
+#include "structs.h"
+#include "SigProc_FIX.h"
+#include "pitch.h"
+#include "main.h"
+
+#if !defined(OPUS_X86_PRESUME_SSE4_1)
+
+#if defined(FIXED_POINT)
+
+#include "fixed/main_FIX.h"
+
+opus_int64 (*const SILK_INNER_PROD16_ALIGNED_64_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    const opus_int16 *inVec1,
+    const opus_int16 *inVec2,
+    const opus_int   len
+) = {
+  silk_inner_prod16_aligned_64_c,                  /* non-sse */
+  silk_inner_prod16_aligned_64_c,
+  silk_inner_prod16_aligned_64_c,
+  MAY_HAVE_SSE4_1( silk_inner_prod16_aligned_64 ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_inner_prod16_aligned_64 )  /* avx */
+};
+
+#endif
+
+opus_int (*const SILK_VAD_GETSA_Q8_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    silk_encoder_state *psEncC,
+    const opus_int16   pIn[]
+) = {
+  silk_VAD_GetSA_Q8_c,                  /* non-sse */
+  silk_VAD_GetSA_Q8_c,
+  silk_VAD_GetSA_Q8_c,
+  MAY_HAVE_SSE4_1( silk_VAD_GetSA_Q8 ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_VAD_GetSA_Q8 )  /* avx */
+};
+
+#if 0 /* FIXME: SSE disabled until the NSQ code gets updated. */
+void (*const SILK_NSQ_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+) = {
+  silk_NSQ_c,                  /* non-sse */
+  silk_NSQ_c,
+  silk_NSQ_c,
+  MAY_HAVE_SSE4_1( silk_NSQ ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_NSQ )  /* avx */
+};
+#endif
+
+#if 0 /* FIXME: SSE disabled until silk_VQ_WMat_EC_sse4_1() gets updated. */
+void (*const SILK_VQ_WMAT_EC_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    opus_int8                   *ind,                           /* O    index of best codebook vector               */
+    opus_int32                  *rate_dist_Q14,                 /* O    best weighted quant error + mu * rate       */
+    opus_int                    *gain_Q7,                       /* O    sum of absolute LTP coefficients            */
+    const opus_int16            *in_Q14,                        /* I    input vector to be quantized                */
+    const opus_int32            *W_Q18,                         /* I    weighting matrix                            */
+    const opus_int8             *cb_Q7,                         /* I    codebook                                    */
+    const opus_uint8            *cb_gain_Q7,                    /* I    codebook effective gain                     */
+    const opus_uint8            *cl_Q5,                         /* I    code length for each codebook vector        */
+    const opus_int              mu_Q9,                          /* I    tradeoff betw. weighted error and rate      */
+    const opus_int32            max_gain_Q7,                    /* I    maximum sum of absolute LTP coefficients    */
+    opus_int                    L                               /* I    number of vectors in codebook               */
+) = {
+  silk_VQ_WMat_EC_c,                  /* non-sse */
+  silk_VQ_WMat_EC_c,
+  silk_VQ_WMat_EC_c,
+  MAY_HAVE_SSE4_1( silk_VQ_WMat_EC ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_VQ_WMat_EC )  /* avx */
+};
+#endif
+
+#if 0 /* FIXME: SSE disabled until the NSQ code gets updated. */
+void (*const SILK_NSQ_DEL_DEC_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    const silk_encoder_state    *psEncC,                                    /* I    Encoder State                   */
+    silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                       */
+    SideInfoIndices             *psIndices,                                 /* I/O  Quantization Indices            */
+    const opus_int32            x_Q3[],                                     /* I    Prefiltered input signal        */
+    opus_int8                   pulses[],                                   /* O    Quantized pulse signal          */
+    const opus_int16            PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefs     */
+    const opus_int16            LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ],    /* I    Long term prediction coefs      */
+    const opus_int16            AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs             */
+    const opus_int              HarmShapeGain_Q14[ MAX_NB_SUBFR ],          /* I    Long term shaping coefs         */
+    const opus_int              Tilt_Q14[ MAX_NB_SUBFR ],                   /* I    Spectral tilt                   */
+    const opus_int32            LF_shp_Q14[ MAX_NB_SUBFR ],                 /* I    Low frequency shaping coefs     */
+    const opus_int32            Gains_Q16[ MAX_NB_SUBFR ],                  /* I    Quantization step sizes         */
+    const opus_int              pitchL[ MAX_NB_SUBFR ],                     /* I    Pitch lags                      */
+    const opus_int              Lambda_Q10,                                 /* I    Rate/distortion tradeoff        */
+    const opus_int              LTP_scale_Q14                               /* I    LTP state scaling               */
+) = {
+  silk_NSQ_del_dec_c,                  /* non-sse */
+  silk_NSQ_del_dec_c,
+  silk_NSQ_del_dec_c,
+  MAY_HAVE_SSE4_1( silk_NSQ_del_dec ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_NSQ_del_dec )  /* avx */
+};
+#endif
+
+#if defined(FIXED_POINT)
+
+void (*const SILK_BURG_MODIFIED_IMPL[ OPUS_ARCHMASK + 1 ] )(
+    opus_int32                  *res_nrg,           /* O    Residual energy                                             */
+    opus_int                    *res_nrg_Q,         /* O    Residual energy Q value                                     */
+    opus_int32                  A_Q16[],            /* O    Prediction coefficients (length order)                      */
+    const opus_int16            x[],                /* I    Input signal, length: nb_subfr * ( D + subfr_length )       */
+    const opus_int32            minInvGain_Q30,     /* I    Inverse of max prediction gain                              */
+    const opus_int              subfr_length,       /* I    Input signal subframe length (incl. D preceding samples)    */
+    const opus_int              nb_subfr,           /* I    Number of subframes stacked in x                            */
+    const opus_int              D,                  /* I    Order                                                       */
+    int                         arch                /* I    Run-time architecture                                       */
+) = {
+  silk_burg_modified_c,                  /* non-sse */
+  silk_burg_modified_c,
+  silk_burg_modified_c,
+  MAY_HAVE_SSE4_1( silk_burg_modified ), /* sse4.1 */
+  MAY_HAVE_SSE4_1( silk_burg_modified )  /* avx */
+};
+
+#endif
+#endif
diff --git a/opus/src/analysis.c b/opus/src/analysis.c
new file mode 100644 (file)
index 0000000..f4160e4
--- /dev/null
@@ -0,0 +1,940 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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
+
+#define ANALYSIS_C
+
+#include <stdio.h>
+
+#include "mathops.h"
+#include "kiss_fft.h"
+#include "celt.h"
+#include "modes.h"
+#include "arch.h"
+#include "quant_bands.h"
+#include "analysis.h"
+#include "mlp.h"
+#include "stack_alloc.h"
+#include "float_cast.h"
+
+#ifndef M_PI
+#define M_PI 3.141592653
+#endif
+
+#ifndef DISABLE_FLOAT_API
+
+static const float dct_table[128] = {
+        0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f,
+        0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f, 0.250000f,
+        0.351851f, 0.338330f, 0.311806f, 0.273300f, 0.224292f, 0.166664f, 0.102631f, 0.034654f,
+       -0.034654f,-0.102631f,-0.166664f,-0.224292f,-0.273300f,-0.311806f,-0.338330f,-0.351851f,
+        0.346760f, 0.293969f, 0.196424f, 0.068975f,-0.068975f,-0.196424f,-0.293969f,-0.346760f,
+       -0.346760f,-0.293969f,-0.196424f,-0.068975f, 0.068975f, 0.196424f, 0.293969f, 0.346760f,
+        0.338330f, 0.224292f, 0.034654f,-0.166664f,-0.311806f,-0.351851f,-0.273300f,-0.102631f,
+        0.102631f, 0.273300f, 0.351851f, 0.311806f, 0.166664f,-0.034654f,-0.224292f,-0.338330f,
+        0.326641f, 0.135299f,-0.135299f,-0.326641f,-0.326641f,-0.135299f, 0.135299f, 0.326641f,
+        0.326641f, 0.135299f,-0.135299f,-0.326641f,-0.326641f,-0.135299f, 0.135299f, 0.326641f,
+        0.311806f, 0.034654f,-0.273300f,-0.338330f,-0.102631f, 0.224292f, 0.351851f, 0.166664f,
+       -0.166664f,-0.351851f,-0.224292f, 0.102631f, 0.338330f, 0.273300f,-0.034654f,-0.311806f,
+        0.293969f,-0.068975f,-0.346760f,-0.196424f, 0.196424f, 0.346760f, 0.068975f,-0.293969f,
+       -0.293969f, 0.068975f, 0.346760f, 0.196424f,-0.196424f,-0.346760f,-0.068975f, 0.293969f,
+        0.273300f,-0.166664f,-0.338330f, 0.034654f, 0.351851f, 0.102631f,-0.311806f,-0.224292f,
+        0.224292f, 0.311806f,-0.102631f,-0.351851f,-0.034654f, 0.338330f, 0.166664f,-0.273300f,
+};
+
+static const float analysis_window[240] = {
+      0.000043f, 0.000171f, 0.000385f, 0.000685f, 0.001071f, 0.001541f, 0.002098f, 0.002739f,
+      0.003466f, 0.004278f, 0.005174f, 0.006156f, 0.007222f, 0.008373f, 0.009607f, 0.010926f,
+      0.012329f, 0.013815f, 0.015385f, 0.017037f, 0.018772f, 0.020590f, 0.022490f, 0.024472f,
+      0.026535f, 0.028679f, 0.030904f, 0.033210f, 0.035595f, 0.038060f, 0.040604f, 0.043227f,
+      0.045928f, 0.048707f, 0.051564f, 0.054497f, 0.057506f, 0.060591f, 0.063752f, 0.066987f,
+      0.070297f, 0.073680f, 0.077136f, 0.080665f, 0.084265f, 0.087937f, 0.091679f, 0.095492f,
+      0.099373f, 0.103323f, 0.107342f, 0.111427f, 0.115579f, 0.119797f, 0.124080f, 0.128428f,
+      0.132839f, 0.137313f, 0.141849f, 0.146447f, 0.151105f, 0.155823f, 0.160600f, 0.165435f,
+      0.170327f, 0.175276f, 0.180280f, 0.185340f, 0.190453f, 0.195619f, 0.200838f, 0.206107f,
+      0.211427f, 0.216797f, 0.222215f, 0.227680f, 0.233193f, 0.238751f, 0.244353f, 0.250000f,
+      0.255689f, 0.261421f, 0.267193f, 0.273005f, 0.278856f, 0.284744f, 0.290670f, 0.296632f,
+      0.302628f, 0.308658f, 0.314721f, 0.320816f, 0.326941f, 0.333097f, 0.339280f, 0.345492f,
+      0.351729f, 0.357992f, 0.364280f, 0.370590f, 0.376923f, 0.383277f, 0.389651f, 0.396044f,
+      0.402455f, 0.408882f, 0.415325f, 0.421783f, 0.428254f, 0.434737f, 0.441231f, 0.447736f,
+      0.454249f, 0.460770f, 0.467298f, 0.473832f, 0.480370f, 0.486912f, 0.493455f, 0.500000f,
+      0.506545f, 0.513088f, 0.519630f, 0.526168f, 0.532702f, 0.539230f, 0.545751f, 0.552264f,
+      0.558769f, 0.565263f, 0.571746f, 0.578217f, 0.584675f, 0.591118f, 0.597545f, 0.603956f,
+      0.610349f, 0.616723f, 0.623077f, 0.629410f, 0.635720f, 0.642008f, 0.648271f, 0.654508f,
+      0.660720f, 0.666903f, 0.673059f, 0.679184f, 0.685279f, 0.691342f, 0.697372f, 0.703368f,
+      0.709330f, 0.715256f, 0.721144f, 0.726995f, 0.732807f, 0.738579f, 0.744311f, 0.750000f,
+      0.755647f, 0.761249f, 0.766807f, 0.772320f, 0.777785f, 0.783203f, 0.788573f, 0.793893f,
+      0.799162f, 0.804381f, 0.809547f, 0.814660f, 0.819720f, 0.824724f, 0.829673f, 0.834565f,
+      0.839400f, 0.844177f, 0.848895f, 0.853553f, 0.858151f, 0.862687f, 0.867161f, 0.871572f,
+      0.875920f, 0.880203f, 0.884421f, 0.888573f, 0.892658f, 0.896677f, 0.900627f, 0.904508f,
+      0.908321f, 0.912063f, 0.915735f, 0.919335f, 0.922864f, 0.926320f, 0.929703f, 0.933013f,
+      0.936248f, 0.939409f, 0.942494f, 0.945503f, 0.948436f, 0.951293f, 0.954072f, 0.956773f,
+      0.959396f, 0.961940f, 0.964405f, 0.966790f, 0.969096f, 0.971321f, 0.973465f, 0.975528f,
+      0.977510f, 0.979410f, 0.981228f, 0.982963f, 0.984615f, 0.986185f, 0.987671f, 0.989074f,
+      0.990393f, 0.991627f, 0.992778f, 0.993844f, 0.994826f, 0.995722f, 0.996534f, 0.997261f,
+      0.997902f, 0.998459f, 0.998929f, 0.999315f, 0.999615f, 0.999829f, 0.999957f, 1.000000f,
+};
+
+static const int tbands[NB_TBANDS+1] = {
+      4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 136, 160, 192, 240
+};
+
+#define NB_TONAL_SKIP_BANDS 9
+
+static opus_val32 silk_resampler_down2_hp(
+    opus_val32                  *S,                 /* I/O  State vector [ 2 ]                                          */
+    opus_val32                  *out,               /* O    Output signal [ floor(len/2) ]                              */
+    const opus_val32            *in,                /* I    Input signal [ len ]                                        */
+    int                         inLen               /* I    Number of input samples                                     */
+)
+{
+    int k, len2 = inLen/2;
+    opus_val32 in32, out32, out32_hp, Y, X;
+    opus_val64 hp_ener = 0;
+    /* Internal variables and state are in Q10 format */
+    for( k = 0; k < len2; k++ ) {
+        /* Convert to Q10 */
+        in32 = in[ 2 * k ];
+
+        /* All-pass section for even input sample */
+        Y      = SUB32( in32, S[ 0 ] );
+        X      = MULT16_32_Q15(QCONST16(0.6074371f, 15), Y);
+        out32  = ADD32( S[ 0 ], X );
+        S[ 0 ] = ADD32( in32, X );
+        out32_hp = out32;
+        /* Convert to Q10 */
+        in32 = in[ 2 * k + 1 ];
+
+        /* All-pass section for odd input sample, and add to output of previous section */
+        Y      = SUB32( in32, S[ 1 ] );
+        X      = MULT16_32_Q15(QCONST16(0.15063f, 15), Y);
+        out32  = ADD32( out32, S[ 1 ] );
+        out32  = ADD32( out32, X );
+        S[ 1 ] = ADD32( in32, X );
+
+        Y      = SUB32( -in32, S[ 2 ] );
+        X      = MULT16_32_Q15(QCONST16(0.15063f, 15), Y);
+        out32_hp  = ADD32( out32_hp, S[ 2 ] );
+        out32_hp  = ADD32( out32_hp, X );
+        S[ 2 ] = ADD32( -in32, X );
+
+        hp_ener += out32_hp*(opus_val64)out32_hp;
+        /* Add, convert back to int16 and store to output */
+        out[ k ] = HALF32(out32);
+    }
+#ifdef FIXED_POINT
+    /* len2 can be up to 480, so we shift by 8 more to make it fit. */
+    hp_ener = hp_ener >> (2*SIG_SHIFT + 8);
+#endif
+    return (opus_val32)hp_ener;
+}
+
+static opus_val32 downmix_and_resample(downmix_func downmix, const void *_x, opus_val32 *y, opus_val32 S[3], int subframe, int offset, int c1, int c2, int C, int Fs)
+{
+   VARDECL(opus_val32, tmp);
+   opus_val32 scale;
+   int j;
+   opus_val32 ret = 0;
+   SAVE_STACK;
+
+   if (subframe==0) return 0;
+   if (Fs == 48000)
+   {
+      subframe *= 2;
+      offset *= 2;
+   } else if (Fs == 16000) {
+      subframe = subframe*2/3;
+      offset = offset*2/3;
+   }
+   ALLOC(tmp, subframe, opus_val32);
+
+   downmix(_x, tmp, subframe, offset, c1, c2, C);
+#ifdef FIXED_POINT
+   scale = (1<<SIG_SHIFT);
+#else
+   scale = 1.f/32768;
+#endif
+   if (c2==-2)
+      scale /= C;
+   else if (c2>-1)
+      scale /= 2;
+   for (j=0;j<subframe;j++)
+      tmp[j] *= scale;
+   if (Fs == 48000)
+   {
+      ret = silk_resampler_down2_hp(S, y, tmp, subframe);
+   } else if (Fs == 24000) {
+      OPUS_COPY(y, tmp, subframe);
+   } else if (Fs == 16000) {
+      VARDECL(opus_val32, tmp3x);
+      ALLOC(tmp3x, 3*subframe, opus_val32);
+      /* Don't do this at home! This resampler is horrible and it's only (barely)
+         usable for the purpose of the analysis because we don't care about all
+         the aliasing between 8 kHz and 12 kHz. */
+      for (j=0;j<subframe;j++)
+      {
+         tmp3x[3*j] = tmp[j];
+         tmp3x[3*j+1] = tmp[j];
+         tmp3x[3*j+2] = tmp[j];
+      }
+      silk_resampler_down2_hp(S, y, tmp3x, 3*subframe);
+   }
+   RESTORE_STACK;
+   return ret;
+}
+
+void tonality_analysis_init(TonalityAnalysisState *tonal, opus_int32 Fs)
+{
+  /* Initialize reusable fields. */
+  tonal->arch = opus_select_arch();
+  tonal->Fs = Fs;
+  /* Clear remaining fields. */
+  tonality_analysis_reset(tonal);
+}
+
+void tonality_analysis_reset(TonalityAnalysisState *tonal)
+{
+  /* Clear non-reusable fields. */
+  char *start = (char*)&tonal->TONALITY_ANALYSIS_RESET_START;
+  OPUS_CLEAR(start, sizeof(TonalityAnalysisState) - (start - (char*)tonal));
+  tonal->music_confidence = .9f;
+  tonal->speech_confidence = .1f;
+}
+
+void tonality_get_info(TonalityAnalysisState *tonal, AnalysisInfo *info_out, int len)
+{
+   int pos;
+   int curr_lookahead;
+   float psum;
+   float tonality_max;
+   float tonality_avg;
+   int tonality_count;
+   int i;
+
+   pos = tonal->read_pos;
+   curr_lookahead = tonal->write_pos-tonal->read_pos;
+   if (curr_lookahead<0)
+      curr_lookahead += DETECT_SIZE;
+
+   /* On long frames, look at the second analysis window rather than the first. */
+   if (len > tonal->Fs/50 && pos != tonal->write_pos)
+   {
+      pos++;
+      if (pos==DETECT_SIZE)
+         pos=0;
+   }
+   if (pos == tonal->write_pos)
+      pos--;
+   if (pos<0)
+      pos = DETECT_SIZE-1;
+   OPUS_COPY(info_out, &tonal->info[pos], 1);
+   tonality_max = tonality_avg = info_out->tonality;
+   tonality_count = 1;
+   /* If possible, look ahead for a tone to compensate for the delay in the tone detector. */
+   for (i=0;i<3;i++)
+   {
+      pos++;
+      if (pos==DETECT_SIZE)
+         pos = 0;
+      if (pos == tonal->write_pos)
+         break;
+      tonality_max = MAX32(tonality_max, tonal->info[pos].tonality);
+      tonality_avg += tonal->info[pos].tonality;
+      tonality_count++;
+   }
+   info_out->tonality = MAX32(tonality_avg/tonality_count, tonality_max-.2f);
+   tonal->read_subframe += len/(tonal->Fs/400);
+   while (tonal->read_subframe>=8)
+   {
+      tonal->read_subframe -= 8;
+      tonal->read_pos++;
+   }
+   if (tonal->read_pos>=DETECT_SIZE)
+      tonal->read_pos-=DETECT_SIZE;
+
+   /* The -1 is to compensate for the delay in the features themselves. */
+   curr_lookahead = IMAX(curr_lookahead-1, 0);
+
+   psum=0;
+   /* Summing the probability of transition patterns that involve music at
+      time (DETECT_SIZE-curr_lookahead-1) */
+   for (i=0;i<DETECT_SIZE-curr_lookahead;i++)
+      psum += tonal->pmusic[i];
+   for (;i<DETECT_SIZE;i++)
+      psum += tonal->pspeech[i];
+   psum = psum*tonal->music_confidence + (1-psum)*tonal->speech_confidence;
+   /*printf("%f %f %f %f %f\n", psum, info_out->music_prob, info_out->vad_prob, info_out->activity_probability, info_out->tonality);*/
+
+   info_out->music_prob = psum;
+}
+
+static const float std_feature_bias[9] = {
+      5.684947f, 3.475288f, 1.770634f, 1.599784f, 3.773215f,
+      2.163313f, 1.260756f, 1.116868f, 1.918795f
+};
+
+#define LEAKAGE_OFFSET 2.5f
+#define LEAKAGE_SLOPE 2.f
+
+#ifdef FIXED_POINT
+/* For fixed-point, the input is +/-2^15 shifted up by SIG_SHIFT, so we need to
+   compensate for that in the energy. */
+#define SCALE_COMPENS (1.f/((opus_int32)1<<(15+SIG_SHIFT)))
+#define SCALE_ENER(e) ((SCALE_COMPENS*SCALE_COMPENS)*(e))
+#else
+#define SCALE_ENER(e) (e)
+#endif
+
+static void tonality_analysis(TonalityAnalysisState *tonal, const CELTMode *celt_mode, const void *x, int len, int offset, int c1, int c2, int C, int lsb_depth, downmix_func downmix)
+{
+    int i, b;
+    const kiss_fft_state *kfft;
+    VARDECL(kiss_fft_cpx, in);
+    VARDECL(kiss_fft_cpx, out);
+    int N = 480, N2=240;
+    float * OPUS_RESTRICT A = tonal->angle;
+    float * OPUS_RESTRICT dA = tonal->d_angle;
+    float * OPUS_RESTRICT d2A = tonal->d2_angle;
+    VARDECL(float, tonality);
+    VARDECL(float, noisiness);
+    float band_tonality[NB_TBANDS];
+    float logE[NB_TBANDS];
+    float BFCC[8];
+    float features[25];
+    float frame_tonality;
+    float max_frame_tonality;
+    /*float tw_sum=0;*/
+    float frame_noisiness;
+    const float pi4 = (float)(M_PI*M_PI*M_PI*M_PI);
+    float slope=0;
+    float frame_stationarity;
+    float relativeE;
+    float frame_probs[2];
+    float alpha, alphaE, alphaE2;
+    float frame_loudness;
+    float bandwidth_mask;
+    int bandwidth=0;
+    float maxE = 0;
+    float noise_floor;
+    int remaining;
+    AnalysisInfo *info;
+    float hp_ener;
+    float tonality2[240];
+    float midE[8];
+    float spec_variability=0;
+    float band_log2[NB_TBANDS+1];
+    float leakage_from[NB_TBANDS+1];
+    float leakage_to[NB_TBANDS+1];
+    SAVE_STACK;
+
+    alpha = 1.f/IMIN(10, 1+tonal->count);
+    alphaE = 1.f/IMIN(25, 1+tonal->count);
+    alphaE2 = 1.f/IMIN(500, 1+tonal->count);
+
+    if (tonal->Fs == 48000)
+    {
+       /* len and offset are now at 24 kHz. */
+       len/= 2;
+       offset /= 2;
+    } else if (tonal->Fs == 16000) {
+       len = 3*len/2;
+       offset = 3*offset/2;
+    }
+
+    if (tonal->count<4) {
+       if (tonal->application == OPUS_APPLICATION_VOIP)
+          tonal->music_prob = .1f;
+       else
+          tonal->music_prob = .625f;
+    }
+    kfft = celt_mode->mdct.kfft[0];
+    if (tonal->count==0)
+       tonal->mem_fill = 240;
+    tonal->hp_ener_accum += (float)downmix_and_resample(downmix, x,
+          &tonal->inmem[tonal->mem_fill], tonal->downmix_state,
+          IMIN(len, ANALYSIS_BUF_SIZE-tonal->mem_fill), offset, c1, c2, C, tonal->Fs);
+    if (tonal->mem_fill+len < ANALYSIS_BUF_SIZE)
+    {
+       tonal->mem_fill += len;
+       /* Don't have enough to update the analysis */
+       RESTORE_STACK;
+       return;
+    }
+    hp_ener = tonal->hp_ener_accum;
+    info = &tonal->info[tonal->write_pos++];
+    if (tonal->write_pos>=DETECT_SIZE)
+       tonal->write_pos-=DETECT_SIZE;
+
+    ALLOC(in, 480, kiss_fft_cpx);
+    ALLOC(out, 480, kiss_fft_cpx);
+    ALLOC(tonality, 240, float);
+    ALLOC(noisiness, 240, float);
+    for (i=0;i<N2;i++)
+    {
+       float w = analysis_window[i];
+       in[i].r = (kiss_fft_scalar)(w*tonal->inmem[i]);
+       in[i].i = (kiss_fft_scalar)(w*tonal->inmem[N2+i]);
+       in[N-i-1].r = (kiss_fft_scalar)(w*tonal->inmem[N-i-1]);
+       in[N-i-1].i = (kiss_fft_scalar)(w*tonal->inmem[N+N2-i-1]);
+    }
+    OPUS_MOVE(tonal->inmem, tonal->inmem+ANALYSIS_BUF_SIZE-240, 240);
+    remaining = len - (ANALYSIS_BUF_SIZE-tonal->mem_fill);
+    tonal->hp_ener_accum = (float)downmix_and_resample(downmix, x,
+          &tonal->inmem[240], tonal->downmix_state, remaining,
+          offset+ANALYSIS_BUF_SIZE-tonal->mem_fill, c1, c2, C, tonal->Fs);
+    tonal->mem_fill = 240 + remaining;
+    opus_fft(kfft, in, out, tonal->arch);
+#ifndef FIXED_POINT
+    /* If there's any NaN on the input, the entire output will be NaN, so we only need to check one value. */
+    if (celt_isnan(out[0].r))
+    {
+       info->valid = 0;
+       RESTORE_STACK;
+       return;
+    }
+#endif
+
+    for (i=1;i<N2;i++)
+    {
+       float X1r, X2r, X1i, X2i;
+       float angle, d_angle, d2_angle;
+       float angle2, d_angle2, d2_angle2;
+       float mod1, mod2, avg_mod;
+       X1r = (float)out[i].r+out[N-i].r;
+       X1i = (float)out[i].i-out[N-i].i;
+       X2r = (float)out[i].i+out[N-i].i;
+       X2i = (float)out[N-i].r-out[i].r;
+
+       angle = (float)(.5f/M_PI)*fast_atan2f(X1i, X1r);
+       d_angle = angle - A[i];
+       d2_angle = d_angle - dA[i];
+
+       angle2 = (float)(.5f/M_PI)*fast_atan2f(X2i, X2r);
+       d_angle2 = angle2 - angle;
+       d2_angle2 = d_angle2 - d_angle;
+
+       mod1 = d2_angle - (float)float2int(d2_angle);
+       noisiness[i] = ABS16(mod1);
+       mod1 *= mod1;
+       mod1 *= mod1;
+
+       mod2 = d2_angle2 - (float)float2int(d2_angle2);
+       noisiness[i] += ABS16(mod2);
+       mod2 *= mod2;
+       mod2 *= mod2;
+
+       avg_mod = .25f*(d2A[i]+mod1+2*mod2);
+       /* This introduces an extra delay of 2 frames in the detection. */
+       tonality[i] = 1.f/(1.f+40.f*16.f*pi4*avg_mod)-.015f;
+       /* No delay on this detection, but it's less reliable. */
+       tonality2[i] = 1.f/(1.f+40.f*16.f*pi4*mod2)-.015f;
+
+       A[i] = angle2;
+       dA[i] = d_angle2;
+       d2A[i] = mod2;
+    }
+    for (i=2;i<N2-1;i++)
+    {
+       float tt = MIN32(tonality2[i], MAX32(tonality2[i-1], tonality2[i+1]));
+       tonality[i] = .9f*MAX32(tonality[i], tt-.1f);
+    }
+    frame_tonality = 0;
+    max_frame_tonality = 0;
+    /*tw_sum = 0;*/
+    info->activity = 0;
+    frame_noisiness = 0;
+    frame_stationarity = 0;
+    if (!tonal->count)
+    {
+       for (b=0;b<NB_TBANDS;b++)
+       {
+          tonal->lowE[b] = 1e10;
+          tonal->highE[b] = -1e10;
+       }
+    }
+    relativeE = 0;
+    frame_loudness = 0;
+    /* The energy of the very first band is special because of DC. */
+    {
+       float E = 0;
+       float X1r, X2r;
+       X1r = 2*(float)out[0].r;
+       X2r = 2*(float)out[0].i;
+       E = X1r*X1r + X2r*X2r;
+       for (i=1;i<4;i++)
+       {
+          float binE = out[i].r*(float)out[i].r + out[N-i].r*(float)out[N-i].r
+                     + out[i].i*(float)out[i].i + out[N-i].i*(float)out[N-i].i;
+          E += binE;
+       }
+       E = SCALE_ENER(E);
+       band_log2[0] = .5f*1.442695f*(float)log(E+1e-10f);
+    }
+    for (b=0;b<NB_TBANDS;b++)
+    {
+       float E=0, tE=0, nE=0;
+       float L1, L2;
+       float stationarity;
+       for (i=tbands[b];i<tbands[b+1];i++)
+       {
+          float binE = out[i].r*(float)out[i].r + out[N-i].r*(float)out[N-i].r
+                     + out[i].i*(float)out[i].i + out[N-i].i*(float)out[N-i].i;
+          binE = SCALE_ENER(binE);
+          E += binE;
+          tE += binE*MAX32(0, tonality[i]);
+          nE += binE*2.f*(.5f-noisiness[i]);
+       }
+#ifndef FIXED_POINT
+       /* Check for extreme band energies that could cause NaNs later. */
+       if (!(E<1e9f) || celt_isnan(E))
+       {
+          info->valid = 0;
+          RESTORE_STACK;
+          return;
+       }
+#endif
+
+       tonal->E[tonal->E_count][b] = E;
+       frame_noisiness += nE/(1e-15f+E);
+
+       frame_loudness += (float)sqrt(E+1e-10f);
+       logE[b] = (float)log(E+1e-10f);
+       band_log2[b+1] = .5f*1.442695f*(float)log(E+1e-10f);
+       tonal->logE[tonal->E_count][b] = logE[b];
+       if (tonal->count==0)
+          tonal->highE[b] = tonal->lowE[b] = logE[b];
+       if (tonal->highE[b] > tonal->lowE[b] + 7.5)
+       {
+          if (tonal->highE[b] - logE[b] > logE[b] - tonal->lowE[b])
+             tonal->highE[b] -= .01f;
+          else
+             tonal->lowE[b] += .01f;
+       }
+       if (logE[b] > tonal->highE[b])
+       {
+          tonal->highE[b] = logE[b];
+          tonal->lowE[b] = MAX32(tonal->highE[b]-15, tonal->lowE[b]);
+       } else if (logE[b] < tonal->lowE[b])
+       {
+          tonal->lowE[b] = logE[b];
+          tonal->highE[b] = MIN32(tonal->lowE[b]+15, tonal->highE[b]);
+       }
+       relativeE += (logE[b]-tonal->lowE[b])/(1e-15f + (tonal->highE[b]-tonal->lowE[b]));
+
+       L1=L2=0;
+       for (i=0;i<NB_FRAMES;i++)
+       {
+          L1 += (float)sqrt(tonal->E[i][b]);
+          L2 += tonal->E[i][b];
+       }
+
+       stationarity = MIN16(0.99f,L1/(float)sqrt(1e-15+NB_FRAMES*L2));
+       stationarity *= stationarity;
+       stationarity *= stationarity;
+       frame_stationarity += stationarity;
+       /*band_tonality[b] = tE/(1e-15+E)*/;
+       band_tonality[b] = MAX16(tE/(1e-15f+E), stationarity*tonal->prev_band_tonality[b]);
+#if 0
+       if (b>=NB_TONAL_SKIP_BANDS)
+       {
+          frame_tonality += tweight[b]*band_tonality[b];
+          tw_sum += tweight[b];
+       }
+#else
+       frame_tonality += band_tonality[b];
+       if (b>=NB_TBANDS-NB_TONAL_SKIP_BANDS)
+          frame_tonality -= band_tonality[b-NB_TBANDS+NB_TONAL_SKIP_BANDS];
+#endif
+       max_frame_tonality = MAX16(max_frame_tonality, (1.f+.03f*(b-NB_TBANDS))*frame_tonality);
+       slope += band_tonality[b]*(b-8);
+       /*printf("%f %f ", band_tonality[b], stationarity);*/
+       tonal->prev_band_tonality[b] = band_tonality[b];
+    }
+
+    leakage_from[0] = band_log2[0];
+    leakage_to[0] = band_log2[0] - LEAKAGE_OFFSET;
+    for (b=1;b<NB_TBANDS+1;b++)
+    {
+       float leak_slope = LEAKAGE_SLOPE*(tbands[b]-tbands[b-1])/4;
+       leakage_from[b] = MIN16(leakage_from[b-1]+leak_slope, band_log2[b]);
+       leakage_to[b] = MAX16(leakage_to[b-1]-leak_slope, band_log2[b]-LEAKAGE_OFFSET);
+    }
+    for (b=NB_TBANDS-2;b>=0;b--)
+    {
+       float leak_slope = LEAKAGE_SLOPE*(tbands[b+1]-tbands[b])/4;
+       leakage_from[b] = MIN16(leakage_from[b+1]+leak_slope, leakage_from[b]);
+       leakage_to[b] = MAX16(leakage_to[b+1]-leak_slope, leakage_to[b]);
+    }
+    celt_assert(NB_TBANDS+1 <= LEAK_BANDS);
+    for (b=0;b<NB_TBANDS+1;b++)
+    {
+       /* leak_boost[] is made up of two terms. The first, based on leakage_to[],
+          represents the boost needed to overcome the amount of analysis leakage
+          cause in a weaker band b by louder neighbouring bands.
+          The second, based on leakage_from[], applies to a loud band b for
+          which the quantization noise causes synthesis leakage to the weaker
+          neighbouring bands. */
+       float boost = MAX16(0, leakage_to[b] - band_log2[b]) +
+             MAX16(0, band_log2[b] - (leakage_from[b]+LEAKAGE_OFFSET));
+       info->leak_boost[b] = IMIN(255, (int)floor(.5 + 64.f*boost));
+    }
+    for (;b<LEAK_BANDS;b++) info->leak_boost[b] = 0;
+
+    for (i=0;i<NB_FRAMES;i++)
+    {
+       int j;
+       float mindist = 1e15f;
+       for (j=0;j<NB_FRAMES;j++)
+       {
+          int k;
+          float dist=0;
+          for (k=0;k<NB_TBANDS;k++)
+          {
+             float tmp;
+             tmp = tonal->logE[i][k] - tonal->logE[j][k];
+             dist += tmp*tmp;
+          }
+          if (j!=i)
+             mindist = MIN32(mindist, dist);
+       }
+       spec_variability += mindist;
+    }
+    spec_variability = (float)sqrt(spec_variability/NB_FRAMES/NB_TBANDS);
+    bandwidth_mask = 0;
+    bandwidth = 0;
+    maxE = 0;
+    noise_floor = 5.7e-4f/(1<<(IMAX(0,lsb_depth-8)));
+    noise_floor *= noise_floor;
+    for (b=0;b<NB_TBANDS;b++)
+    {
+       float E=0;
+       int band_start, band_end;
+       /* Keep a margin of 300 Hz for aliasing */
+       band_start = tbands[b];
+       band_end = tbands[b+1];
+       for (i=band_start;i<band_end;i++)
+       {
+          float binE = out[i].r*(float)out[i].r + out[N-i].r*(float)out[N-i].r
+                     + out[i].i*(float)out[i].i + out[N-i].i*(float)out[N-i].i;
+          E += binE;
+       }
+       E = SCALE_ENER(E);
+       maxE = MAX32(maxE, E);
+       tonal->meanE[b] = MAX32((1-alphaE2)*tonal->meanE[b], E);
+       E = MAX32(E, tonal->meanE[b]);
+       /* Use a simple follower with 13 dB/Bark slope for spreading function */
+       bandwidth_mask = MAX32(.05f*bandwidth_mask, E);
+       /* Consider the band "active" only if all these conditions are met:
+          1) less than 10 dB below the simple follower
+          2) less than 90 dB below the peak band (maximal masking possible considering
+             both the ATH and the loudness-dependent slope of the spreading function)
+          3) above the PCM quantization noise floor
+          We use b+1 because the first CELT band isn't included in tbands[]
+       */
+       if (E>.1*bandwidth_mask && E*1e9f > maxE && E > noise_floor*(band_end-band_start))
+          bandwidth = b+1;
+    }
+    /* Special case for the last two bands, for which we don't have spectrum but only
+       the energy above 12 kHz. */
+    if (tonal->Fs == 48000) {
+       float ratio;
+       float E = hp_ener*(1.f/(240*240));
+       ratio = tonal->prev_bandwidth==20 ? 0.03f : 0.07f;
+#ifdef FIXED_POINT
+       /* silk_resampler_down2_hp() shifted right by an extra 8 bits. */
+       E *= 256.f*(1.f/Q15ONE)*(1.f/Q15ONE);
+#endif
+       maxE = MAX32(maxE, E);
+       tonal->meanE[b] = MAX32((1-alphaE2)*tonal->meanE[b], E);
+       E = MAX32(E, tonal->meanE[b]);
+       /* Use a simple follower with 13 dB/Bark slope for spreading function */
+       bandwidth_mask = MAX32(.05f*bandwidth_mask, E);
+       if (E>ratio*bandwidth_mask && E*1e9f > maxE && E > noise_floor*160)
+          bandwidth = 20;
+       /* This detector is unreliable, so if the bandwidth is close to SWB, assume it's FB. */
+       if (bandwidth >= 17)
+          bandwidth = 20;
+    }
+    if (tonal->count<=2)
+       bandwidth = 20;
+    frame_loudness = 20*(float)log10(frame_loudness);
+    tonal->Etracker = MAX32(tonal->Etracker-.003f, frame_loudness);
+    tonal->lowECount *= (1-alphaE);
+    if (frame_loudness < tonal->Etracker-30)
+       tonal->lowECount += alphaE;
+
+    for (i=0;i<8;i++)
+    {
+       float sum=0;
+       for (b=0;b<16;b++)
+          sum += dct_table[i*16+b]*logE[b];
+       BFCC[i] = sum;
+    }
+    for (i=0;i<8;i++)
+    {
+       float sum=0;
+       for (b=0;b<16;b++)
+          sum += dct_table[i*16+b]*.5f*(tonal->highE[b]+tonal->lowE[b]);
+       midE[i] = sum;
+    }
+
+    frame_stationarity /= NB_TBANDS;
+    relativeE /= NB_TBANDS;
+    if (tonal->count<10)
+       relativeE = .5f;
+    frame_noisiness /= NB_TBANDS;
+#if 1
+    info->activity = frame_noisiness + (1-frame_noisiness)*relativeE;
+#else
+    info->activity = .5*(1+frame_noisiness-frame_stationarity);
+#endif
+    frame_tonality = (max_frame_tonality/(NB_TBANDS-NB_TONAL_SKIP_BANDS));
+    frame_tonality = MAX16(frame_tonality, tonal->prev_tonality*.8f);
+    tonal->prev_tonality = frame_tonality;
+
+    slope /= 8*8;
+    info->tonality_slope = slope;
+
+    tonal->E_count = (tonal->E_count+1)%NB_FRAMES;
+    tonal->count = IMIN(tonal->count+1, ANALYSIS_COUNT_MAX);
+    info->tonality = frame_tonality;
+
+    for (i=0;i<4;i++)
+       features[i] = -0.12299f*(BFCC[i]+tonal->mem[i+24]) + 0.49195f*(tonal->mem[i]+tonal->mem[i+16]) + 0.69693f*tonal->mem[i+8] - 1.4349f*tonal->cmean[i];
+
+    for (i=0;i<4;i++)
+       tonal->cmean[i] = (1-alpha)*tonal->cmean[i] + alpha*BFCC[i];
+
+    for (i=0;i<4;i++)
+        features[4+i] = 0.63246f*(BFCC[i]-tonal->mem[i+24]) + 0.31623f*(tonal->mem[i]-tonal->mem[i+16]);
+    for (i=0;i<3;i++)
+        features[8+i] = 0.53452f*(BFCC[i]+tonal->mem[i+24]) - 0.26726f*(tonal->mem[i]+tonal->mem[i+16]) -0.53452f*tonal->mem[i+8];
+
+    if (tonal->count > 5)
+    {
+       for (i=0;i<9;i++)
+          tonal->std[i] = (1-alpha)*tonal->std[i] + alpha*features[i]*features[i];
+    }
+    for (i=0;i<4;i++)
+       features[i] = BFCC[i]-midE[i];
+
+    for (i=0;i<8;i++)
+    {
+       tonal->mem[i+24] = tonal->mem[i+16];
+       tonal->mem[i+16] = tonal->mem[i+8];
+       tonal->mem[i+8] = tonal->mem[i];
+       tonal->mem[i] = BFCC[i];
+    }
+    for (i=0;i<9;i++)
+       features[11+i] = (float)sqrt(tonal->std[i]) - std_feature_bias[i];
+    features[18] = spec_variability - 0.78f;
+    features[20] = info->tonality - 0.154723f;
+    features[21] = info->activity - 0.724643f;
+    features[22] = frame_stationarity - 0.743717f;
+    features[23] = info->tonality_slope + 0.069216f;
+    features[24] = tonal->lowECount - 0.067930f;
+
+    mlp_process(&net, features, frame_probs);
+    frame_probs[0] = .5f*(frame_probs[0]+1);
+    /* Curve fitting between the MLP probability and the actual probability */
+    /*frame_probs[0] = .01f + 1.21f*frame_probs[0]*frame_probs[0] - .23f*(float)pow(frame_probs[0], 10);*/
+    /* Probability of active audio (as opposed to silence) */
+    frame_probs[1] = .5f*frame_probs[1]+.5f;
+    frame_probs[1] *= frame_probs[1];
+
+    /* Probability of speech or music vs noise */
+    info->activity_probability = frame_probs[1];
+
+    /*printf("%f %f\n", frame_probs[0], frame_probs[1]);*/
+    {
+       /* Probability of state transition */
+       float tau;
+       /* Represents independence of the MLP probabilities, where
+          beta=1 means fully independent. */
+       float beta;
+       /* Denormalized probability of speech (p0) and music (p1) after update */
+       float p0, p1;
+       /* Probabilities for "all speech" and "all music" */
+       float s0, m0;
+       /* Probability sum for renormalisation */
+       float psum;
+       /* Instantaneous probability of speech and music, with beta pre-applied. */
+       float speech0;
+       float music0;
+       float p, q;
+
+       /* More silence transitions for speech than for music. */
+       tau = .001f*tonal->music_prob + .01f*(1-tonal->music_prob);
+       p = MAX16(.05f,MIN16(.95f,frame_probs[1]));
+       q = MAX16(.05f,MIN16(.95f,tonal->vad_prob));
+       beta = .02f+.05f*ABS16(p-q)/(p*(1-q)+q*(1-p));
+       /* p0 and p1 are the probabilities of speech and music at this frame
+          using only information from previous frame and applying the
+          state transition model */
+       p0 = (1-tonal->vad_prob)*(1-tau) +    tonal->vad_prob *tau;
+       p1 =    tonal->vad_prob *(1-tau) + (1-tonal->vad_prob)*tau;
+       /* We apply the current probability with exponent beta to work around
+          the fact that the probability estimates aren't independent. */
+       p0 *= (float)pow(1-frame_probs[1], beta);
+       p1 *= (float)pow(frame_probs[1], beta);
+       /* Normalise the probabilities to get the Marokv probability of music. */
+       tonal->vad_prob = p1/(p0+p1);
+       info->vad_prob = tonal->vad_prob;
+       /* Consider that silence has a 50-50 probability of being speech or music. */
+       frame_probs[0] = tonal->vad_prob*frame_probs[0] + (1-tonal->vad_prob)*.5f;
+
+       /* One transition every 3 minutes of active audio */
+       tau = .0001f;
+       /* Adapt beta based on how "unexpected" the new prob is */
+       p = MAX16(.05f,MIN16(.95f,frame_probs[0]));
+       q = MAX16(.05f,MIN16(.95f,tonal->music_prob));
+       beta = .02f+.05f*ABS16(p-q)/(p*(1-q)+q*(1-p));
+       /* p0 and p1 are the probabilities of speech and music at this frame
+          using only information from previous frame and applying the
+          state transition model */
+       p0 = (1-tonal->music_prob)*(1-tau) +    tonal->music_prob *tau;
+       p1 =    tonal->music_prob *(1-tau) + (1-tonal->music_prob)*tau;
+       /* We apply the current probability with exponent beta to work around
+          the fact that the probability estimates aren't independent. */
+       p0 *= (float)pow(1-frame_probs[0], beta);
+       p1 *= (float)pow(frame_probs[0], beta);
+       /* Normalise the probabilities to get the Marokv probability of music. */
+       tonal->music_prob = p1/(p0+p1);
+       info->music_prob = tonal->music_prob;
+
+       /*printf("%f %f %f %f\n", frame_probs[0], frame_probs[1], tonal->music_prob, tonal->vad_prob);*/
+       /* This chunk of code deals with delayed decision. */
+       psum=1e-20f;
+       /* Instantaneous probability of speech and music, with beta pre-applied. */
+       speech0 = (float)pow(1-frame_probs[0], beta);
+       music0  = (float)pow(frame_probs[0], beta);
+       if (tonal->count==1)
+       {
+          if (tonal->application == OPUS_APPLICATION_VOIP)
+             tonal->pmusic[0] = .1f;
+          else
+             tonal->pmusic[0] = .625f;
+          tonal->pspeech[0] = 1-tonal->pmusic[0];
+       }
+       /* Updated probability of having only speech (s0) or only music (m0),
+          before considering the new observation. */
+       s0 = tonal->pspeech[0] + tonal->pspeech[1];
+       m0 = tonal->pmusic [0] + tonal->pmusic [1];
+       /* Updates s0 and m0 with instantaneous probability. */
+       tonal->pspeech[0] = s0*(1-tau)*speech0;
+       tonal->pmusic [0] = m0*(1-tau)*music0;
+       /* Propagate the transition probabilities */
+       for (i=1;i<DETECT_SIZE-1;i++)
+       {
+          tonal->pspeech[i] = tonal->pspeech[i+1]*speech0;
+          tonal->pmusic [i] = tonal->pmusic [i+1]*music0;
+       }
+       /* Probability that the latest frame is speech, when all the previous ones were music. */
+       tonal->pspeech[DETECT_SIZE-1] = m0*tau*speech0;
+       /* Probability that the latest frame is music, when all the previous ones were speech. */
+       tonal->pmusic [DETECT_SIZE-1] = s0*tau*music0;
+
+       /* Renormalise probabilities to 1 */
+       for (i=0;i<DETECT_SIZE;i++)
+          psum += tonal->pspeech[i] + tonal->pmusic[i];
+       psum = 1.f/psum;
+       for (i=0;i<DETECT_SIZE;i++)
+       {
+          tonal->pspeech[i] *= psum;
+          tonal->pmusic [i] *= psum;
+       }
+       psum = tonal->pmusic[0];
+       for (i=1;i<DETECT_SIZE;i++)
+          psum += tonal->pspeech[i];
+
+       /* Estimate our confidence in the speech/music decisions */
+       if (frame_probs[1]>.75)
+       {
+          if (tonal->music_prob>.9)
+          {
+             float adapt;
+             adapt = 1.f/(++tonal->music_confidence_count);
+             tonal->music_confidence_count = IMIN(tonal->music_confidence_count, 500);
+             tonal->music_confidence += adapt*MAX16(-.2f,frame_probs[0]-tonal->music_confidence);
+          }
+          if (tonal->music_prob<.1)
+          {
+             float adapt;
+             adapt = 1.f/(++tonal->speech_confidence_count);
+             tonal->speech_confidence_count = IMIN(tonal->speech_confidence_count, 500);
+             tonal->speech_confidence += adapt*MIN16(.2f,frame_probs[0]-tonal->speech_confidence);
+          }
+       }
+    }
+    tonal->last_music = tonal->music_prob>.5f;
+#ifdef MLP_TRAINING
+    for (i=0;i<25;i++)
+       printf("%f ", features[i]);
+    printf("\n");
+#endif
+
+    info->bandwidth = bandwidth;
+    tonal->prev_bandwidth = bandwidth;
+    /*printf("%d %d\n", info->bandwidth, info->opus_bandwidth);*/
+    info->noisiness = frame_noisiness;
+    info->valid = 1;
+    RESTORE_STACK;
+}
+
+void run_analysis(TonalityAnalysisState *analysis, const CELTMode *celt_mode, const void *analysis_pcm,
+                 int analysis_frame_size, int frame_size, int c1, int c2, int C, opus_int32 Fs,
+                 int lsb_depth, downmix_func downmix, AnalysisInfo *analysis_info)
+{
+   int offset;
+   int pcm_len;
+
+   analysis_frame_size -= analysis_frame_size&1;
+   if (analysis_pcm != NULL)
+   {
+      /* Avoid overflow/wrap-around of the analysis buffer */
+      analysis_frame_size = IMIN((DETECT_SIZE-5)*Fs/50, analysis_frame_size);
+
+      pcm_len = analysis_frame_size - analysis->analysis_offset;
+      offset = analysis->analysis_offset;
+      while (pcm_len>0) {
+         tonality_analysis(analysis, celt_mode, analysis_pcm, IMIN(Fs/50, pcm_len), offset, c1, c2, C, lsb_depth, downmix);
+         offset += Fs/50;
+         pcm_len -= Fs/50;
+      }
+      analysis->analysis_offset = analysis_frame_size;
+
+      analysis->analysis_offset -= frame_size;
+   }
+
+   analysis_info->valid = 0;
+   tonality_get_info(analysis, analysis_info, frame_size);
+}
+
+#endif /* DISABLE_FLOAT_API */
diff --git a/opus/src/analysis.h b/opus/src/analysis.h
new file mode 100644 (file)
index 0000000..cac51df
--- /dev/null
@@ -0,0 +1,113 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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 ANALYSIS_H
+#define ANALYSIS_H
+
+#include "celt.h"
+#include "opus_private.h"
+
+#define NB_FRAMES 8
+#define NB_TBANDS 18
+#define ANALYSIS_BUF_SIZE 720 /* 30 ms at 24 kHz */
+
+/* At that point we can stop counting frames because it no longer matters. */
+#define ANALYSIS_COUNT_MAX 10000
+
+#define DETECT_SIZE 100
+
+/* Uncomment this to print the MLP features on stdout. */
+/*#define MLP_TRAINING*/
+
+typedef struct {
+   int arch;
+   int application;
+   opus_int32 Fs;
+#define TONALITY_ANALYSIS_RESET_START angle
+   float angle[240];
+   float d_angle[240];
+   float d2_angle[240];
+   opus_val32 inmem[ANALYSIS_BUF_SIZE];
+   int   mem_fill;                      /* number of usable samples in the buffer */
+   float prev_band_tonality[NB_TBANDS];
+   float prev_tonality;
+   int prev_bandwidth;
+   float E[NB_FRAMES][NB_TBANDS];
+   float logE[NB_FRAMES][NB_TBANDS];
+   float lowE[NB_TBANDS];
+   float highE[NB_TBANDS];
+   float meanE[NB_TBANDS+1];
+   float mem[32];
+   float cmean[8];
+   float std[9];
+   float music_prob;
+   float vad_prob;
+   float Etracker;
+   float lowECount;
+   int E_count;
+   int last_music;
+   int count;
+   int analysis_offset;
+   /** Probability of having speech for time i to DETECT_SIZE-1 (and music before).
+       pspeech[0] is the probability that all frames in the window are speech. */
+   float pspeech[DETECT_SIZE];
+   /** Probability of having music for time i to DETECT_SIZE-1 (and speech before).
+       pmusic[0] is the probability that all frames in the window are music. */
+   float pmusic[DETECT_SIZE];
+   float speech_confidence;
+   float music_confidence;
+   int speech_confidence_count;
+   int music_confidence_count;
+   int write_pos;
+   int read_pos;
+   int read_subframe;
+   float hp_ener_accum;
+   opus_val32 downmix_state[3];
+   AnalysisInfo info[DETECT_SIZE];
+} TonalityAnalysisState;
+
+/** Initialize a TonalityAnalysisState struct.
+ *
+ * This performs some possibly slow initialization steps which should
+ * not be repeated every analysis step. No allocated memory is retained
+ * by the state struct, so no cleanup call is required.
+ */
+void tonality_analysis_init(TonalityAnalysisState *analysis, opus_int32 Fs);
+
+/** Reset a TonalityAnalysisState stuct.
+ *
+ * Call this when there's a discontinuity in the data.
+ */
+void tonality_analysis_reset(TonalityAnalysisState *analysis);
+
+void tonality_get_info(TonalityAnalysisState *tonal, AnalysisInfo *info_out, int len);
+
+void run_analysis(TonalityAnalysisState *analysis, const CELTMode *celt_mode, const void *analysis_pcm,
+                 int analysis_frame_size, int frame_size, int c1, int c2, int C, opus_int32 Fs,
+                 int lsb_depth, downmix_func downmix, AnalysisInfo *analysis_info);
+
+#endif
diff --git a/opus/src/mlp.c b/opus/src/mlp.c
new file mode 100644 (file)
index 0000000..ff9e50d
--- /dev/null
@@ -0,0 +1,145 @@
+/* Copyright (c) 2008-2011 Octasic Inc.
+   Written by 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.
+
+   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 "opus_types.h"
+#include "opus_defines.h"
+
+#include <math.h>
+#include "mlp.h"
+#include "arch.h"
+#include "tansig_table.h"
+#define MAX_NEURONS 100
+
+#if 0
+static OPUS_INLINE opus_val16 tansig_approx(opus_val32 _x) /* Q19 */
+{
+    int i;
+    opus_val16 xx; /* Q11 */
+    /*double x, y;*/
+    opus_val16 dy, yy; /* Q14 */
+    /*x = 1.9073e-06*_x;*/
+    if (_x>=QCONST32(8,19))
+        return QCONST32(1.,14);
+    if (_x<=-QCONST32(8,19))
+        return -QCONST32(1.,14);
+    xx = EXTRACT16(SHR32(_x, 8));
+    /*i = lrint(25*x);*/
+    i = SHR32(ADD32(1024,MULT16_16(25, xx)),11);
+    /*x -= .04*i;*/
+    xx -= EXTRACT16(SHR32(MULT16_16(20972,i),8));
+    /*x = xx*(1./2048);*/
+    /*y = tansig_table[250+i];*/
+    yy = tansig_table[250+i];
+    /*y = yy*(1./16384);*/
+    dy = 16384-MULT16_16_Q14(yy,yy);
+    yy = yy + MULT16_16_Q14(MULT16_16_Q11(xx,dy),(16384 - MULT16_16_Q11(yy,xx)));
+    return yy;
+}
+#else
+/*extern const float tansig_table[501];*/
+static OPUS_INLINE float tansig_approx(float x)
+{
+    int i;
+    float y, dy;
+    float sign=1;
+    /* Tests are reversed to catch NaNs */
+    if (!(x<8))
+        return 1;
+    if (!(x>-8))
+        return -1;
+#ifndef FIXED_POINT
+    /* Another check in case of -ffast-math */
+    if (celt_isnan(x))
+       return 0;
+#endif
+    if (x<0)
+    {
+       x=-x;
+       sign=-1;
+    }
+    i = (int)floor(.5f+25*x);
+    x -= .04f*i;
+    y = tansig_table[i];
+    dy = 1-y*y;
+    y = y + x*dy*(1 - y*x);
+    return sign*y;
+}
+#endif
+
+#if 0
+void mlp_process(const MLP *m, const opus_val16 *in, opus_val16 *out)
+{
+    int j;
+    opus_val16 hidden[MAX_NEURONS];
+    const opus_val16 *W = m->weights;
+    /* Copy to tmp_in */
+    for (j=0;j<m->topo[1];j++)
+    {
+        int k;
+        opus_val32 sum = SHL32(EXTEND32(*W++),8);
+        for (k=0;k<m->topo[0];k++)
+            sum = MAC16_16(sum, in[k],*W++);
+        hidden[j] = tansig_approx(sum);
+    }
+    for (j=0;j<m->topo[2];j++)
+    {
+        int k;
+        opus_val32 sum = SHL32(EXTEND32(*W++),14);
+        for (k=0;k<m->topo[1];k++)
+            sum = MAC16_16(sum, hidden[k], *W++);
+        out[j] = tansig_approx(EXTRACT16(PSHR32(sum,17)));
+    }
+}
+#else
+void mlp_process(const MLP *m, const float *in, float *out)
+{
+    int j;
+    float hidden[MAX_NEURONS];
+    const float *W = m->weights;
+    /* Copy to tmp_in */
+    for (j=0;j<m->topo[1];j++)
+    {
+        int k;
+        float sum = *W++;
+        for (k=0;k<m->topo[0];k++)
+            sum = sum + in[k]**W++;
+        hidden[j] = tansig_approx(sum);
+    }
+    for (j=0;j<m->topo[2];j++)
+    {
+        int k;
+        float sum = *W++;
+        for (k=0;k<m->topo[1];k++)
+            sum = sum + hidden[k]**W++;
+        out[j] = tansig_approx(sum);
+    }
+}
+#endif
diff --git a/opus/src/mlp.h b/opus/src/mlp.h
new file mode 100644 (file)
index 0000000..618e246
--- /dev/null
@@ -0,0 +1,43 @@
+/* Copyright (c) 2008-2011 Octasic Inc.
+   Written by 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.
+
+   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 _MLP_H_
+#define _MLP_H_
+
+#include "arch.h"
+
+typedef struct {
+    int layers;
+    const int *topo;
+    const float *weights;
+} MLP;
+
+extern const MLP net;
+
+void mlp_process(const MLP *m, const float *in, float *out);
+
+#endif /* _MLP_H_ */
diff --git a/opus/src/mlp_data.c b/opus/src/mlp_data.c
new file mode 100644 (file)
index 0000000..a819880
--- /dev/null
@@ -0,0 +1,112 @@
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "mlp.h"
+
+/* RMS error was 0.280492, seed was 1480478173 */
+/* 0.005976 0.031821 (0.280494 0.280492) done */
+
+static const float weights[450] = {
+
+/* hidden layer */
+-0.514624f, 0.0234227f, -0.14329f, -0.0878216f, -0.00187827f,
+-0.0257443f, 0.108524f, 0.00333881f, 0.00585017f, -0.0246132f,
+0.142723f, -0.00436494f, 0.0101354f, -0.11124f, -0.0809367f,
+-0.0750772f, 0.0295524f, 0.00823944f, 0.150392f, 0.0320876f,
+-0.0710564f, -1.43818f, 0.652076f, 0.0650744f, -1.54821f,
+0.168949f, -1.92724f, 0.0517976f, -0.0670737f, -0.0690121f,
+0.00247528f, -0.0522024f, 0.0631368f, 0.0532776f, 0.047751f,
+-0.011715f, 0.142374f, -0.0290885f, -0.279263f, -0.433499f,
+-0.0795174f, -0.380458f, -0.051263f, 0.218537f, -0.322478f,
+1.06667f, -0.104607f, -4.70108f, 0.312037f, 0.277397f,
+-2.71859f, 1.70037f, -0.141845f, 0.0115618f, 0.0629883f,
+0.0403871f, 0.0139428f, -0.00430733f, -0.0429038f, -0.0590318f,
+-0.0501526f, -0.0284802f, -0.0415686f, -0.0438999f, 0.0822666f,
+0.197194f, 0.0363275f, -0.0584307f, 0.0752364f, -0.0799796f,
+-0.146275f, 0.161661f, -0.184585f, 0.145568f, 0.442823f,
+1.61221f, 1.11162f, 2.62177f, -2.482f, -0.112599f,
+-0.110366f, -0.140794f, -0.181694f, 0.0648674f, 0.0842248f,
+0.0933993f, 0.150122f, 0.129171f, 0.176848f, 0.141758f,
+-0.271822f, 0.235113f, 0.0668579f, -0.433957f, 0.113633f,
+-0.169348f, -1.40091f, 0.62861f, -0.134236f, 0.402173f,
+1.86373f, 1.53998f, -4.32084f, 0.735343f, 0.800214f,
+-0.00968415f, 0.0425904f, 0.0196811f, -0.018426f, -0.000343953f,
+-0.00416389f, 0.00111558f, 0.0173069f, -0.00998596f, -0.025898f,
+0.00123764f, -0.00520373f, -0.0565033f, 0.0637394f, 0.0051213f,
+0.0221361f, 0.00819962f, -0.0467061f, -0.0548258f, -0.00314063f,
+-1.18332f, 1.88091f, -0.41148f, -2.95727f, -0.521449f,
+-0.271641f, 0.124946f, -0.0532936f, 0.101515f, 0.000208564f,
+-0.0488748f, 0.0642388f, -0.0383848f, 0.0135046f, -0.0413592f,
+-0.0326402f, -0.0137421f, -0.0225219f, -0.0917294f, -0.277759f,
+-0.185418f, 0.0471128f, -0.125879f, 0.262467f, -0.212794f,
+-0.112931f, -1.99885f, -0.404787f, 0.224402f, 0.637962f,
+-0.27808f, -0.0723953f, -0.0537655f, -0.0336359f, -0.0906601f,
+-0.0641309f, -0.0713542f, 0.0524317f, 0.00608819f, 0.0754101f,
+-0.0488401f, -0.00671865f, 0.0418239f, 0.0536284f, -0.132639f,
+0.0267648f, -0.248432f, -0.0104153f, 0.035544f, -0.212753f,
+-0.302895f, -0.0357854f, 0.376838f, 0.597025f, -0.664647f,
+0.268422f, -0.376772f, -1.05472f, 0.0144178f, 0.179122f,
+0.0360155f, 0.220262f, -0.0056381f, 0.0317197f, 0.0621066f,
+-0.00779298f, 0.00789378f, 0.00350605f, 0.0104809f, 0.0362871f,
+-0.157708f, -0.0659779f, -0.0926278f, 0.00770791f, 0.0631621f,
+0.0817343f, -0.424295f, -0.0437727f, -0.24251f, 0.711217f,
+-0.736455f, -2.194f, -0.107612f, -0.175156f, -0.0366573f,
+-0.0123156f, -0.0628516f, -0.0218977f, -0.00693699f, 0.00695185f,
+0.00507362f, 0.00359334f, 0.0052661f, 0.035561f, 0.0382701f,
+0.0342179f, -0.00790271f, -0.0170925f, 0.047029f, 0.0197362f,
+-0.0153435f, 0.0644152f, -0.36862f, -0.0674876f, -2.82672f,
+1.34122f, -0.0788029f, -3.47792f, 0.507246f, -0.816378f,
+-0.0142383f, -0.127349f, -0.106926f, -0.0359524f, 0.105045f,
+0.291554f, 0.195413f, 0.0866214f, -0.066577f, -0.102188f,
+0.0979466f, -0.12982f, 0.400181f, -0.409336f, -0.0593326f,
+-0.0656203f, -0.204474f, 0.179802f, 0.000509084f, 0.0995954f,
+-2.377f, -0.686359f, 0.934861f, 1.10261f, 1.3901f,
+-4.33616f, -0.00264017f, 0.00713045f, 0.106264f, 0.143726f,
+-0.0685305f, -0.054656f, -0.0176725f, -0.0772669f, -0.0264526f,
+-0.0103824f, -0.0269872f, -0.00687f, 0.225804f, 0.407751f,
+-0.0612611f, -0.0576863f, -0.180131f, -0.222772f, -0.461742f,
+0.335236f, 1.03399f, 4.24112f, -0.345796f, -0.594549f,
+-76.1407f, -0.265276f, 0.0507719f, 0.0643044f, 0.0384832f,
+0.0424459f, -0.0387817f, -0.0235996f, -0.0740556f, -0.0270029f,
+0.00882177f, -0.0552371f, -0.00485851f, 0.314295f, 0.360431f,
+-0.0787085f, 0.110355f, -0.415958f, -0.385088f, -0.272224f,
+-1.55108f, -0.141848f, 0.448877f, -0.563447f, -2.31403f,
+-0.120077f, -1.49918f, -0.817726f, -0.0495854f, -0.0230782f,
+-0.0224014f, 0.117076f, 0.0393216f, 0.051997f, 0.0330763f,
+-0.110796f, 0.0211117f, -0.0197258f, 0.0187461f, 0.0125183f,
+0.14876f, 0.0920565f, -0.342475f, 0.135272f, -0.168155f,
+-0.033423f, -0.0604611f, -0.128835f, 0.664947f, -0.144997f,
+2.27649f, 1.28663f, 0.841217f, -2.42807f, 0.0230471f,
+0.226709f, -0.0374803f, 0.155436f, 0.0400342f, -0.184686f,
+0.128488f, -0.0939518f, -0.0578559f, 0.0265967f, -0.0999322f,
+-0.0322768f, -0.322994f, -0.189371f, -0.738069f, -0.0754914f,
+0.214717f, -0.093728f, -0.695741f, 0.0899298f, -2.06188f,
+-0.273719f, -0.896977f, 0.130553f, 0.134638f, 1.29355f,
+0.00520749f, -0.0324224f, 0.00530451f, 0.0192385f, 0.00328708f,
+0.0250838f, 0.0053365f, -0.0177321f, 0.00618789f, 0.00525364f,
+0.00104596f, -0.0360459f, 0.0402403f, -0.0406351f, 0.0136883f,
+0.0880722f, -0.0197449f, 0.089938f, 0.0100456f, -0.0475638f,
+-0.73267f, 0.037433f, -0.146551f, -0.230221f, -3.06489f,
+-1.40194f, 0.0198483f, 0.0397953f, -0.0190239f, 0.0470715f,
+-0.131363f, -0.191721f, -0.0176224f, -0.0480352f, -0.221799f,
+-0.26794f, -0.0292615f, 0.0612127f, -0.129877f, 0.00628332f,
+-0.085918f, 0.0175379f, 0.0541011f, -0.0810874f, -0.380809f,
+-0.222056f, -0.508859f, -0.473369f, 0.484958f, -2.28411f,
+0.0139516f,
+/* output layer */
+3.90017f, 1.71789f, -1.43372f, -2.70839f, 1.77107f,
+5.48006f, 1.44661f, 2.01134f, -1.88383f, -3.64958f,
+-1.26351f, 0.779421f, 2.11357f, 3.10409f, 1.68846f,
+-4.46197f, -1.61455f, 3.59832f, 2.43531f, -1.26458f,
+0.417941f, 1.47437f, 2.16635f, -1.909f, -0.828869f,
+1.38805f, -2.67975f, -0.110044f, 1.95596f, 0.697931f,
+-0.313226f, -0.889315f, 0.283236f, 0.946102f, };
+
+static const int topo[3] = {25, 16, 2};
+
+const MLP net = {
+    3,
+    topo,
+    weights
+};
diff --git a/opus/src/opus.c b/opus/src/opus.c
new file mode 100644 (file)
index 0000000..cdbd13a
--- /dev/null
@@ -0,0 +1,356 @@
+/* Copyright (c) 2011 Xiph.Org Foundation, Skype Limited
+   Written by Jean-Marc Valin and Koen Vos */
+/*
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus.h"
+#include "opus_private.h"
+
+#ifndef DISABLE_FLOAT_API
+OPUS_EXPORT void opus_pcm_soft_clip(float *_x, int N, int C, float *declip_mem)
+{
+   int c;
+   int i;
+   float *x;
+
+   if (C<1 || N<1 || !_x || !declip_mem) return;
+
+   /* First thing: saturate everything to +/- 2 which is the highest level our
+      non-linearity can handle. At the point where the signal reaches +/-2,
+      the derivative will be zero anyway, so this doesn't introduce any
+      discontinuity in the derivative. */
+   for (i=0;i<N*C;i++)
+      _x[i] = MAX16(-2.f, MIN16(2.f, _x[i]));
+   for (c=0;c<C;c++)
+   {
+      float a;
+      float x0;
+      int curr;
+
+      x = _x+c;
+      a = declip_mem[c];
+      /* Continue applying the non-linearity from the previous frame to avoid
+         any discontinuity. */
+      for (i=0;i<N;i++)
+      {
+         if (x[i*C]*a>=0)
+            break;
+         x[i*C] = x[i*C]+a*x[i*C]*x[i*C];
+      }
+
+      curr=0;
+      x0 = x[0];
+      while(1)
+      {
+         int start, end;
+         float maxval;
+         int special=0;
+         int peak_pos;
+         for (i=curr;i<N;i++)
+         {
+            if (x[i*C]>1 || x[i*C]<-1)
+               break;
+         }
+         if (i==N)
+         {
+            a=0;
+            break;
+         }
+         peak_pos = i;
+         start=end=i;
+         maxval=ABS16(x[i*C]);
+         /* Look for first zero crossing before clipping */
+         while (start>0 && x[i*C]*x[(start-1)*C]>=0)
+            start--;
+         /* Look for first zero crossing after clipping */
+         while (end<N && x[i*C]*x[end*C]>=0)
+         {
+            /* Look for other peaks until the next zero-crossing. */
+            if (ABS16(x[end*C])>maxval)
+            {
+               maxval = ABS16(x[end*C]);
+               peak_pos = end;
+            }
+            end++;
+         }
+         /* Detect the special case where we clip before the first zero crossing */
+         special = (start==0 && x[i*C]*x[0]>=0);
+
+         /* Compute a such that maxval + a*maxval^2 = 1 */
+         a=(maxval-1)/(maxval*maxval);
+         /* Slightly boost "a" by 2^-22. This is just enough to ensure -ffast-math
+            does not cause output values larger than +/-1, but small enough not
+            to matter even for 24-bit output.  */
+         a += a*2.4e-7f;
+         if (x[i*C]>0)
+            a = -a;
+         /* Apply soft clipping */
+         for (i=start;i<end;i++)
+            x[i*C] = x[i*C]+a*x[i*C]*x[i*C];
+
+         if (special && peak_pos>=2)
+         {
+            /* Add a linear ramp from the first sample to the signal peak.
+               This avoids a discontinuity at the beginning of the frame. */
+            float delta;
+            float offset = x0-x[0];
+            delta = offset / peak_pos;
+            for (i=curr;i<peak_pos;i++)
+            {
+               offset -= delta;
+               x[i*C] += offset;
+               x[i*C] = MAX16(-1.f, MIN16(1.f, x[i*C]));
+            }
+         }
+         curr = end;
+         if (curr==N)
+            break;
+      }
+      declip_mem[c] = a;
+   }
+}
+#endif
+
+int encode_size(int size, unsigned char *data)
+{
+   if (size < 252)
+   {
+      data[0] = size;
+      return 1;
+   } else {
+      data[0] = 252+(size&0x3);
+      data[1] = (size-(int)data[0])>>2;
+      return 2;
+   }
+}
+
+static int parse_size(const unsigned char *data, opus_int32 len, opus_int16 *size)
+{
+   if (len<1)
+   {
+      *size = -1;
+      return -1;
+   } else if (data[0]<252)
+   {
+      *size = data[0];
+      return 1;
+   } else if (len<2)
+   {
+      *size = -1;
+      return -1;
+   } else {
+      *size = 4*data[1] + data[0];
+      return 2;
+   }
+}
+
+int opus_packet_get_samples_per_frame(const unsigned char *data,
+      opus_int32 Fs)
+{
+   int audiosize;
+   if (data[0]&0x80)
+   {
+      audiosize = ((data[0]>>3)&0x3);
+      audiosize = (Fs<<audiosize)/400;
+   } else if ((data[0]&0x60) == 0x60)
+   {
+      audiosize = (data[0]&0x08) ? Fs/50 : Fs/100;
+   } else {
+      audiosize = ((data[0]>>3)&0x3);
+      if (audiosize == 3)
+         audiosize = Fs*60/1000;
+      else
+         audiosize = (Fs<<audiosize)/100;
+   }
+   return audiosize;
+}
+
+int opus_packet_parse_impl(const unsigned char *data, opus_int32 len,
+      int self_delimited, unsigned char *out_toc,
+      const unsigned char *frames[48], opus_int16 size[48],
+      int *payload_offset, opus_int32 *packet_offset)
+{
+   int i, bytes;
+   int count;
+   int cbr;
+   unsigned char ch, toc;
+   int framesize;
+   opus_int32 last_size;
+   opus_int32 pad = 0;
+   const unsigned char *data0 = data;
+
+   if (size==NULL || len<0)
+      return OPUS_BAD_ARG;
+   if (len==0)
+      return OPUS_INVALID_PACKET;
+
+   framesize = opus_packet_get_samples_per_frame(data, 48000);
+
+   cbr = 0;
+   toc = *data++;
+   len--;
+   last_size = len;
+   switch (toc&0x3)
+   {
+   /* One frame */
+   case 0:
+      count=1;
+      break;
+   /* Two CBR frames */
+   case 1:
+      count=2;
+      cbr = 1;
+      if (!self_delimited)
+      {
+         if (len&0x1)
+            return OPUS_INVALID_PACKET;
+         last_size = len/2;
+         /* If last_size doesn't fit in size[0], we'll catch it later */
+         size[0] = (opus_int16)last_size;
+      }
+      break;
+   /* Two VBR frames */
+   case 2:
+      count = 2;
+      bytes = parse_size(data, len, size);
+      len -= bytes;
+      if (size[0]<0 || size[0] > len)
+         return OPUS_INVALID_PACKET;
+      data += bytes;
+      last_size = len-size[0];
+      break;
+   /* Multiple CBR/VBR frames (from 0 to 120 ms) */
+   default: /*case 3:*/
+      if (len<1)
+         return OPUS_INVALID_PACKET;
+      /* Number of frames encoded in bits 0 to 5 */
+      ch = *data++;
+      count = ch&0x3F;
+      if (count <= 0 || framesize*count > 5760)
+         return OPUS_INVALID_PACKET;
+      len--;
+      /* Padding flag is bit 6 */
+      if (ch&0x40)
+      {
+         int p;
+         do {
+            int tmp;
+            if (len<=0)
+               return OPUS_INVALID_PACKET;
+            p = *data++;
+            len--;
+            tmp = p==255 ? 254: p;
+            len -= tmp;
+            pad += tmp;
+         } while (p==255);
+      }
+      if (len<0)
+         return OPUS_INVALID_PACKET;
+      /* VBR flag is bit 7 */
+      cbr = !(ch&0x80);
+      if (!cbr)
+      {
+         /* VBR case */
+         last_size = len;
+         for (i=0;i<count-1;i++)
+         {
+            bytes = parse_size(data, len, size+i);
+            len -= bytes;
+            if (size[i]<0 || size[i] > len)
+               return OPUS_INVALID_PACKET;
+            data += bytes;
+            last_size -= bytes+size[i];
+         }
+         if (last_size<0)
+            return OPUS_INVALID_PACKET;
+      } else if (!self_delimited)
+      {
+         /* CBR case */
+         last_size = len/count;
+         if (last_size*count!=len)
+            return OPUS_INVALID_PACKET;
+         for (i=0;i<count-1;i++)
+            size[i] = (opus_int16)last_size;
+      }
+      break;
+   }
+   /* Self-delimited framing has an extra size for the last frame. */
+   if (self_delimited)
+   {
+      bytes = parse_size(data, len, size+count-1);
+      len -= bytes;
+      if (size[count-1]<0 || size[count-1] > len)
+         return OPUS_INVALID_PACKET;
+      data += bytes;
+      /* For CBR packets, apply the size to all the frames. */
+      if (cbr)
+      {
+         if (size[count-1]*count > len)
+            return OPUS_INVALID_PACKET;
+         for (i=0;i<count-1;i++)
+            size[i] = size[count-1];
+      } else if (bytes+size[count-1] > last_size)
+         return OPUS_INVALID_PACKET;
+   } else
+   {
+      /* Because it's not encoded explicitly, it's possible the size of the
+         last packet (or all the packets, for the CBR case) is larger than
+         1275. Reject them here.*/
+      if (last_size > 1275)
+         return OPUS_INVALID_PACKET;
+      size[count-1] = (opus_int16)last_size;
+   }
+
+   if (payload_offset)
+      *payload_offset = (int)(data-data0);
+
+   for (i=0;i<count;i++)
+   {
+      if (frames)
+         frames[i] = data;
+      data += size[i];
+   }
+
+   if (packet_offset)
+      *packet_offset = pad+(opus_int32)(data-data0);
+
+   if (out_toc)
+      *out_toc = toc;
+
+   return count;
+}
+
+int opus_packet_parse(const unsigned char *data, opus_int32 len,
+      unsigned char *out_toc, const unsigned char *frames[48],
+      opus_int16 size[48], int *payload_offset)
+{
+   return opus_packet_parse_impl(data, len, 0, out_toc,
+                                 frames, size, payload_offset, NULL);
+}
+
diff --git a/opus/src/opus_compare.c b/opus/src/opus_compare.c
new file mode 100644 (file)
index 0000000..1956e08
--- /dev/null
@@ -0,0 +1,382 @@
+/* Copyright (c) 2011-2012 Xiph.Org Foundation, Mozilla Corporation
+   Written by Jean-Marc Valin and 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.
+
+   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.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+
+#define OPUS_PI (3.14159265F)
+
+#define OPUS_COSF(_x)        ((float)cos(_x))
+#define OPUS_SINF(_x)        ((float)sin(_x))
+
+static void *check_alloc(void *_ptr){
+  if(_ptr==NULL){
+    fprintf(stderr,"Out of memory.\n");
+    exit(EXIT_FAILURE);
+  }
+  return _ptr;
+}
+
+static void *opus_malloc(size_t _size){
+  return check_alloc(malloc(_size));
+}
+
+static void *opus_realloc(void *_ptr,size_t _size){
+  return check_alloc(realloc(_ptr,_size));
+}
+
+static size_t read_pcm16(float **_samples,FILE *_fin,int _nchannels){
+  unsigned char  buf[1024];
+  float         *samples;
+  size_t         nsamples;
+  size_t         csamples;
+  size_t         xi;
+  size_t         nread;
+  samples=NULL;
+  nsamples=csamples=0;
+  for(;;){
+    nread=fread(buf,2*_nchannels,1024/(2*_nchannels),_fin);
+    if(nread<=0)break;
+    if(nsamples+nread>csamples){
+      do csamples=csamples<<1|1;
+      while(nsamples+nread>csamples);
+      samples=(float *)opus_realloc(samples,
+       _nchannels*csamples*sizeof(*samples));
+    }
+    for(xi=0;xi<nread;xi++){
+      int ci;
+      for(ci=0;ci<_nchannels;ci++){
+        int s;
+        s=buf[2*(xi*_nchannels+ci)+1]<<8|buf[2*(xi*_nchannels+ci)];
+        s=((s&0xFFFF)^0x8000)-0x8000;
+        samples[(nsamples+xi)*_nchannels+ci]=s;
+      }
+    }
+    nsamples+=nread;
+  }
+  *_samples=(float *)opus_realloc(samples,
+   _nchannels*nsamples*sizeof(*samples));
+  return nsamples;
+}
+
+static void band_energy(float *_out,float *_ps,const int *_bands,int _nbands,
+ const float *_in,int _nchannels,size_t _nframes,int _window_sz,
+ int _step,int _downsample){
+  float *window;
+  float *x;
+  float *c;
+  float *s;
+  size_t xi;
+  int    xj;
+  int    ps_sz;
+  window=(float *)opus_malloc((3+_nchannels)*_window_sz*sizeof(*window));
+  c=window+_window_sz;
+  s=c+_window_sz;
+  x=s+_window_sz;
+  ps_sz=_window_sz/2;
+  for(xj=0;xj<_window_sz;xj++){
+    window[xj]=0.5F-0.5F*OPUS_COSF((2*OPUS_PI/(_window_sz-1))*xj);
+  }
+  for(xj=0;xj<_window_sz;xj++){
+    c[xj]=OPUS_COSF((2*OPUS_PI/_window_sz)*xj);
+  }
+  for(xj=0;xj<_window_sz;xj++){
+    s[xj]=OPUS_SINF((2*OPUS_PI/_window_sz)*xj);
+  }
+  for(xi=0;xi<_nframes;xi++){
+    int ci;
+    int xk;
+    int bi;
+    for(ci=0;ci<_nchannels;ci++){
+      for(xk=0;xk<_window_sz;xk++){
+        x[ci*_window_sz+xk]=window[xk]*_in[(xi*_step+xk)*_nchannels+ci];
+      }
+    }
+    for(bi=xj=0;bi<_nbands;bi++){
+      float p[2]={0};
+      for(;xj<_bands[bi+1];xj++){
+        for(ci=0;ci<_nchannels;ci++){
+          float re;
+          float im;
+          int   ti;
+          ti=0;
+          re=im=0;
+          for(xk=0;xk<_window_sz;xk++){
+            re+=c[ti]*x[ci*_window_sz+xk];
+            im-=s[ti]*x[ci*_window_sz+xk];
+            ti+=xj;
+            if(ti>=_window_sz)ti-=_window_sz;
+          }
+          re*=_downsample;
+          im*=_downsample;
+          _ps[(xi*ps_sz+xj)*_nchannels+ci]=re*re+im*im+100000;
+          p[ci]+=_ps[(xi*ps_sz+xj)*_nchannels+ci];
+        }
+      }
+      if(_out){
+        _out[(xi*_nbands+bi)*_nchannels]=p[0]/(_bands[bi+1]-_bands[bi]);
+        if(_nchannels==2){
+          _out[(xi*_nbands+bi)*_nchannels+1]=p[1]/(_bands[bi+1]-_bands[bi]);
+        }
+      }
+    }
+  }
+  free(window);
+}
+
+#define NBANDS (21)
+#define NFREQS (240)
+
+/*Bands on which we compute the pseudo-NMR (Bark-derived
+  CELT bands).*/
+static const int BANDS[NBANDS+1]={
+  0,2,4,6,8,10,12,14,16,20,24,28,32,40,48,56,68,80,96,120,156,200
+};
+
+#define TEST_WIN_SIZE (480)
+#define TEST_WIN_STEP (120)
+
+int main(int _argc,const char **_argv){
+  FILE    *fin1;
+  FILE    *fin2;
+  float   *x;
+  float   *y;
+  float   *xb;
+  float   *X;
+  float   *Y;
+  double    err;
+  float    Q;
+  size_t   xlength;
+  size_t   ylength;
+  size_t   nframes;
+  size_t   xi;
+  int      ci;
+  int      xj;
+  int      bi;
+  int      nchannels;
+  unsigned rate;
+  int      downsample;
+  int      ybands;
+  int      yfreqs;
+  int      max_compare;
+  if(_argc<3||_argc>6){
+    fprintf(stderr,"Usage: %s [-s] [-r rate2] <file1.sw> <file2.sw>\n",
+     _argv[0]);
+    return EXIT_FAILURE;
+  }
+  nchannels=1;
+  if(strcmp(_argv[1],"-s")==0){
+    nchannels=2;
+    _argv++;
+  }
+  rate=48000;
+  ybands=NBANDS;
+  yfreqs=NFREQS;
+  downsample=1;
+  if(strcmp(_argv[1],"-r")==0){
+    rate=atoi(_argv[2]);
+    if(rate!=8000&&rate!=12000&&rate!=16000&&rate!=24000&&rate!=48000){
+      fprintf(stderr,
+       "Sampling rate must be 8000, 12000, 16000, 24000, or 48000\n");
+      return EXIT_FAILURE;
+    }
+    downsample=48000/rate;
+    switch(rate){
+      case  8000:ybands=13;break;
+      case 12000:ybands=15;break;
+      case 16000:ybands=17;break;
+      case 24000:ybands=19;break;
+    }
+    yfreqs=NFREQS/downsample;
+    _argv+=2;
+  }
+  fin1=fopen(_argv[1],"rb");
+  if(fin1==NULL){
+    fprintf(stderr,"Error opening '%s'.\n",_argv[1]);
+    return EXIT_FAILURE;
+  }
+  fin2=fopen(_argv[2],"rb");
+  if(fin2==NULL){
+    fprintf(stderr,"Error opening '%s'.\n",_argv[2]);
+    fclose(fin1);
+    return EXIT_FAILURE;
+  }
+  /*Read in the data and allocate scratch space.*/
+  xlength=read_pcm16(&x,fin1,2);
+  if(nchannels==1){
+    for(xi=0;xi<xlength;xi++)x[xi]=.5*(x[2*xi]+x[2*xi+1]);
+  }
+  fclose(fin1);
+  ylength=read_pcm16(&y,fin2,nchannels);
+  fclose(fin2);
+  if(xlength!=ylength*downsample){
+    fprintf(stderr,"Sample counts do not match (%lu!=%lu).\n",
+     (unsigned long)xlength,(unsigned long)ylength*downsample);
+    return EXIT_FAILURE;
+  }
+  if(xlength<TEST_WIN_SIZE){
+    fprintf(stderr,"Insufficient sample data (%lu<%i).\n",
+     (unsigned long)xlength,TEST_WIN_SIZE);
+    return EXIT_FAILURE;
+  }
+  nframes=(xlength-TEST_WIN_SIZE+TEST_WIN_STEP)/TEST_WIN_STEP;
+  xb=(float *)opus_malloc(nframes*NBANDS*nchannels*sizeof(*xb));
+  X=(float *)opus_malloc(nframes*NFREQS*nchannels*sizeof(*X));
+  Y=(float *)opus_malloc(nframes*yfreqs*nchannels*sizeof(*Y));
+  /*Compute the per-band spectral energy of the original signal
+     and the error.*/
+  band_energy(xb,X,BANDS,NBANDS,x,nchannels,nframes,
+   TEST_WIN_SIZE,TEST_WIN_STEP,1);
+  free(x);
+  band_energy(NULL,Y,BANDS,ybands,y,nchannels,nframes,
+   TEST_WIN_SIZE/downsample,TEST_WIN_STEP/downsample,downsample);
+  free(y);
+  for(xi=0;xi<nframes;xi++){
+    /*Frequency masking (low to high): 10 dB/Bark slope.*/
+    for(bi=1;bi<NBANDS;bi++){
+      for(ci=0;ci<nchannels;ci++){
+        xb[(xi*NBANDS+bi)*nchannels+ci]+=
+         0.1F*xb[(xi*NBANDS+bi-1)*nchannels+ci];
+      }
+    }
+    /*Frequency masking (high to low): 15 dB/Bark slope.*/
+    for(bi=NBANDS-1;bi-->0;){
+      for(ci=0;ci<nchannels;ci++){
+        xb[(xi*NBANDS+bi)*nchannels+ci]+=
+         0.03F*xb[(xi*NBANDS+bi+1)*nchannels+ci];
+      }
+    }
+    if(xi>0){
+      /*Temporal masking: -3 dB/2.5ms slope.*/
+      for(bi=0;bi<NBANDS;bi++){
+        for(ci=0;ci<nchannels;ci++){
+          xb[(xi*NBANDS+bi)*nchannels+ci]+=
+           0.5F*xb[((xi-1)*NBANDS+bi)*nchannels+ci];
+        }
+      }
+    }
+    /* Allowing some cross-talk */
+    if(nchannels==2){
+      for(bi=0;bi<NBANDS;bi++){
+        float l,r;
+        l=xb[(xi*NBANDS+bi)*nchannels+0];
+        r=xb[(xi*NBANDS+bi)*nchannels+1];
+        xb[(xi*NBANDS+bi)*nchannels+0]+=0.01F*r;
+        xb[(xi*NBANDS+bi)*nchannels+1]+=0.01F*l;
+      }
+    }
+
+    /* Apply masking */
+    for(bi=0;bi<ybands;bi++){
+      for(xj=BANDS[bi];xj<BANDS[bi+1];xj++){
+        for(ci=0;ci<nchannels;ci++){
+          X[(xi*NFREQS+xj)*nchannels+ci]+=
+           0.1F*xb[(xi*NBANDS+bi)*nchannels+ci];
+          Y[(xi*yfreqs+xj)*nchannels+ci]+=
+           0.1F*xb[(xi*NBANDS+bi)*nchannels+ci];
+        }
+      }
+    }
+  }
+
+  /* Average of consecutive frames to make comparison slightly less sensitive */
+  for(bi=0;bi<ybands;bi++){
+    for(xj=BANDS[bi];xj<BANDS[bi+1];xj++){
+      for(ci=0;ci<nchannels;ci++){
+         float xtmp;
+         float ytmp;
+         xtmp = X[xj*nchannels+ci];
+         ytmp = Y[xj*nchannels+ci];
+         for(xi=1;xi<nframes;xi++){
+           float xtmp2;
+           float ytmp2;
+           xtmp2 = X[(xi*NFREQS+xj)*nchannels+ci];
+           ytmp2 = Y[(xi*yfreqs+xj)*nchannels+ci];
+           X[(xi*NFREQS+xj)*nchannels+ci] += xtmp;
+           Y[(xi*yfreqs+xj)*nchannels+ci] += ytmp;
+           xtmp = xtmp2;
+           ytmp = ytmp2;
+         }
+      }
+    }
+  }
+
+  /*If working at a lower sampling rate, don't take into account the last
+     300 Hz to allow for different transition bands.
+    For 12 kHz, we don't skip anything, because the last band already skips
+     400 Hz.*/
+  if(rate==48000)max_compare=BANDS[NBANDS];
+  else if(rate==12000)max_compare=BANDS[ybands];
+  else max_compare=BANDS[ybands]-3;
+  err=0;
+  for(xi=0;xi<nframes;xi++){
+    double Ef;
+    Ef=0;
+    for(bi=0;bi<ybands;bi++){
+      double Eb;
+      Eb=0;
+      for(xj=BANDS[bi];xj<BANDS[bi+1]&&xj<max_compare;xj++){
+        for(ci=0;ci<nchannels;ci++){
+          float re;
+          float im;
+          re=Y[(xi*yfreqs+xj)*nchannels+ci]/X[(xi*NFREQS+xj)*nchannels+ci];
+          im=re-log(re)-1;
+          /*Make comparison less sensitive around the SILK/CELT cross-over to
+            allow for mode freedom in the filters.*/
+          if(xj>=79&&xj<=81)im*=0.1F;
+          if(xj==80)im*=0.1F;
+          Eb+=im;
+        }
+      }
+      Eb /= (BANDS[bi+1]-BANDS[bi])*nchannels;
+      Ef += Eb*Eb;
+    }
+    /*Using a fixed normalization value means we're willing to accept slightly
+       lower quality for lower sampling rates.*/
+    Ef/=NBANDS;
+    Ef*=Ef;
+    err+=Ef*Ef;
+  }
+  free(xb);
+  free(X);
+  free(Y);
+  err=pow(err/nframes,1.0/16);
+  Q=100*(1-0.5*log(1+err)/log(1.13));
+  if(Q<0){
+    fprintf(stderr,"Test vector FAILS\n");
+    fprintf(stderr,"Internal weighted error is %f\n",err);
+    return EXIT_FAILURE;
+  }
+  else{
+    fprintf(stderr,"Test vector PASSES\n");
+    fprintf(stderr,
+     "Opus quality metric: %.1f %% (internal weighted error is %f)\n",Q,err);
+    return EXIT_SUCCESS;
+  }
+}
diff --git a/opus/src/opus_decoder.c b/opus/src/opus_decoder.c
new file mode 100644 (file)
index 0000000..149ae7f
--- /dev/null
@@ -0,0 +1,1001 @@
+/* Copyright (c) 2010 Xiph.Org Foundation, Skype Limited
+   Written by Jean-Marc Valin and Koen Vos */
+/*
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#ifndef OPUS_BUILD
+# error "OPUS_BUILD _MUST_ be defined to build Opus. This probably means you need other defines as well, as in a config.h. See the included build files for details."
+#endif
+
+#if defined(__GNUC__) && (__GNUC__ >= 2) && !defined(__OPTIMIZE__) && !defined(OPUS_WILL_BE_SLOW)
+# pragma message "You appear to be compiling without optimization, if so opus will be very slow."
+#endif
+
+#include <stdarg.h>
+#include "celt.h"
+#include "opus.h"
+#include "entdec.h"
+#include "modes.h"
+#include "API.h"
+#include "stack_alloc.h"
+#include "float_cast.h"
+#include "opus_private.h"
+#include "os_support.h"
+#include "structs.h"
+#include "define.h"
+#include "mathops.h"
+#include "cpu_support.h"
+
+struct OpusDecoder {
+   int          celt_dec_offset;
+   int          silk_dec_offset;
+   int          channels;
+   opus_int32   Fs;          /** Sampling rate (at the API level) */
+   silk_DecControlStruct DecControl;
+   int          decode_gain;
+   int          arch;
+
+   /* Everything beyond this point gets cleared on a reset */
+#define OPUS_DECODER_RESET_START stream_channels
+   int          stream_channels;
+
+   int          bandwidth;
+   int          mode;
+   int          prev_mode;
+   int          frame_size;
+   int          prev_redundancy;
+   int          last_packet_duration;
+#ifndef FIXED_POINT
+   opus_val16   softclip_mem[2];
+#endif
+
+   opus_uint32  rangeFinal;
+};
+
+
+int opus_decoder_get_size(int channels)
+{
+   int silkDecSizeBytes, celtDecSizeBytes;
+   int ret;
+   if (channels<1 || channels > 2)
+      return 0;
+   ret = silk_Get_Decoder_Size( &silkDecSizeBytes );
+   if(ret)
+      return 0;
+   silkDecSizeBytes = align(silkDecSizeBytes);
+   celtDecSizeBytes = celt_decoder_get_size(channels);
+   return align(sizeof(OpusDecoder))+silkDecSizeBytes+celtDecSizeBytes;
+}
+
+int opus_decoder_init(OpusDecoder *st, opus_int32 Fs, int channels)
+{
+   void *silk_dec;
+   CELTDecoder *celt_dec;
+   int ret, silkDecSizeBytes;
+
+   if ((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)
+    || (channels!=1&&channels!=2))
+      return OPUS_BAD_ARG;
+
+   OPUS_CLEAR((char*)st, opus_decoder_get_size(channels));
+   /* Initialize SILK encoder */
+   ret = silk_Get_Decoder_Size(&silkDecSizeBytes);
+   if (ret)
+      return OPUS_INTERNAL_ERROR;
+
+   silkDecSizeBytes = align(silkDecSizeBytes);
+   st->silk_dec_offset = align(sizeof(OpusDecoder));
+   st->celt_dec_offset = st->silk_dec_offset+silkDecSizeBytes;
+   silk_dec = (char*)st+st->silk_dec_offset;
+   celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
+   st->stream_channels = st->channels = channels;
+
+   st->Fs = Fs;
+   st->DecControl.API_sampleRate = st->Fs;
+   st->DecControl.nChannelsAPI      = st->channels;
+
+   /* Reset decoder */
+   ret = silk_InitDecoder( silk_dec );
+   if(ret)return OPUS_INTERNAL_ERROR;
+
+   /* Initialize CELT decoder */
+   ret = celt_decoder_init(celt_dec, Fs, channels);
+   if(ret!=OPUS_OK)return OPUS_INTERNAL_ERROR;
+
+   celt_decoder_ctl(celt_dec, CELT_SET_SIGNALLING(0));
+
+   st->prev_mode = 0;
+   st->frame_size = Fs/400;
+   st->arch = opus_select_arch();
+   return OPUS_OK;
+}
+
+OpusDecoder *opus_decoder_create(opus_int32 Fs, int channels, int *error)
+{
+   int ret;
+   OpusDecoder *st;
+   if ((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)
+    || (channels!=1&&channels!=2))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   st = (OpusDecoder *)opus_alloc(opus_decoder_get_size(channels));
+   if (st == NULL)
+   {
+      if (error)
+         *error = OPUS_ALLOC_FAIL;
+      return NULL;
+   }
+   ret = opus_decoder_init(st, Fs, channels);
+   if (error)
+      *error = ret;
+   if (ret != OPUS_OK)
+   {
+      opus_free(st);
+      st = NULL;
+   }
+   return st;
+}
+
+static void smooth_fade(const opus_val16 *in1, const opus_val16 *in2,
+      opus_val16 *out, int overlap, int channels,
+      const opus_val16 *window, opus_int32 Fs)
+{
+   int i, c;
+   int inc = 48000/Fs;
+   for (c=0;c<channels;c++)
+   {
+      for (i=0;i<overlap;i++)
+      {
+         opus_val16 w = MULT16_16_Q15(window[i*inc], window[i*inc]);
+         out[i*channels+c] = SHR32(MAC16_16(MULT16_16(w,in2[i*channels+c]),
+                                   Q15ONE-w, in1[i*channels+c]), 15);
+      }
+   }
+}
+
+static int opus_packet_get_mode(const unsigned char *data)
+{
+   int mode;
+   if (data[0]&0x80)
+   {
+      mode = MODE_CELT_ONLY;
+   } else if ((data[0]&0x60) == 0x60)
+   {
+      mode = MODE_HYBRID;
+   } else {
+      mode = MODE_SILK_ONLY;
+   }
+   return mode;
+}
+
+static int opus_decode_frame(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
+{
+   void *silk_dec;
+   CELTDecoder *celt_dec;
+   int i, silk_ret=0, celt_ret=0;
+   ec_dec dec;
+   opus_int32 silk_frame_size;
+   int pcm_silk_size;
+   VARDECL(opus_int16, pcm_silk);
+   int pcm_transition_silk_size;
+   VARDECL(opus_val16, pcm_transition_silk);
+   int pcm_transition_celt_size;
+   VARDECL(opus_val16, pcm_transition_celt);
+   opus_val16 *pcm_transition=NULL;
+   int redundant_audio_size;
+   VARDECL(opus_val16, redundant_audio);
+
+   int audiosize;
+   int mode;
+   int transition=0;
+   int start_band;
+   int redundancy=0;
+   int redundancy_bytes = 0;
+   int celt_to_silk=0;
+   int c;
+   int F2_5, F5, F10, F20;
+   const opus_val16 *window;
+   opus_uint32 redundant_rng = 0;
+   int celt_accum;
+   ALLOC_STACK;
+
+   silk_dec = (char*)st+st->silk_dec_offset;
+   celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
+   F20 = st->Fs/50;
+   F10 = F20>>1;
+   F5 = F10>>1;
+   F2_5 = F5>>1;
+   if (frame_size < F2_5)
+   {
+      RESTORE_STACK;
+      return OPUS_BUFFER_TOO_SMALL;
+   }
+   /* Limit frame_size to avoid excessive stack allocations. */
+   frame_size = IMIN(frame_size, st->Fs/25*3);
+   /* Payloads of 1 (2 including ToC) or 0 trigger the PLC/DTX */
+   if (len<=1)
+   {
+      data = NULL;
+      /* In that case, don't conceal more than what the ToC says */
+      frame_size = IMIN(frame_size, st->frame_size);
+   }
+   if (data != NULL)
+   {
+      audiosize = st->frame_size;
+      mode = st->mode;
+      ec_dec_init(&dec,(unsigned char*)data,len);
+   } else {
+      audiosize = frame_size;
+      mode = st->prev_mode;
+
+      if (mode == 0)
+      {
+         /* If we haven't got any packet yet, all we can do is return zeros */
+         for (i=0;i<audiosize*st->channels;i++)
+            pcm[i] = 0;
+         RESTORE_STACK;
+         return audiosize;
+      }
+
+      /* Avoids trying to run the PLC on sizes other than 2.5 (CELT), 5 (CELT),
+         10, or 20 (e.g. 12.5 or 30 ms). */
+      if (audiosize > F20)
+      {
+         do {
+            int ret = opus_decode_frame(st, NULL, 0, pcm, IMIN(audiosize, F20), 0);
+            if (ret<0)
+            {
+               RESTORE_STACK;
+               return ret;
+            }
+            pcm += ret*st->channels;
+            audiosize -= ret;
+         } while (audiosize > 0);
+         RESTORE_STACK;
+         return frame_size;
+      } else if (audiosize < F20)
+      {
+         if (audiosize > F10)
+            audiosize = F10;
+         else if (mode != MODE_SILK_ONLY && audiosize > F5 && audiosize < F10)
+            audiosize = F5;
+      }
+   }
+
+   /* In fixed-point, we can tell CELT to do the accumulation on top of the
+      SILK PCM buffer. This saves some stack space. */
+#ifdef FIXED_POINT
+   celt_accum = (mode != MODE_CELT_ONLY) && (frame_size >= F10);
+#else
+   celt_accum = 0;
+#endif
+
+   pcm_transition_silk_size = ALLOC_NONE;
+   pcm_transition_celt_size = ALLOC_NONE;
+   if (data!=NULL && st->prev_mode > 0 && (
+       (mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY && !st->prev_redundancy)
+    || (mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) )
+      )
+   {
+      transition = 1;
+      /* Decide where to allocate the stack memory for pcm_transition */
+      if (mode == MODE_CELT_ONLY)
+         pcm_transition_celt_size = F5*st->channels;
+      else
+         pcm_transition_silk_size = F5*st->channels;
+   }
+   ALLOC(pcm_transition_celt, pcm_transition_celt_size, opus_val16);
+   if (transition && mode == MODE_CELT_ONLY)
+   {
+      pcm_transition = pcm_transition_celt;
+      opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
+   }
+   if (audiosize > frame_size)
+   {
+      /*fprintf(stderr, "PCM buffer too small: %d vs %d (mode = %d)\n", audiosize, frame_size, mode);*/
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   } else {
+      frame_size = audiosize;
+   }
+
+   /* Don't allocate any memory when in CELT-only mode */
+   pcm_silk_size = (mode != MODE_CELT_ONLY && !celt_accum) ? IMAX(F10, frame_size)*st->channels : ALLOC_NONE;
+   ALLOC(pcm_silk, pcm_silk_size, opus_int16);
+
+   /* SILK processing */
+   if (mode != MODE_CELT_ONLY)
+   {
+      int lost_flag, decoded_samples;
+      opus_int16 *pcm_ptr;
+#ifdef FIXED_POINT
+      if (celt_accum)
+         pcm_ptr = pcm;
+      else
+#endif
+         pcm_ptr = pcm_silk;
+
+      if (st->prev_mode==MODE_CELT_ONLY)
+         silk_InitDecoder( silk_dec );
+
+      /* The SILK PLC cannot produce frames of less than 10 ms */
+      st->DecControl.payloadSize_ms = IMAX(10, 1000 * audiosize / st->Fs);
+
+      if (data != NULL)
+      {
+        st->DecControl.nChannelsInternal = st->stream_channels;
+        if( mode == MODE_SILK_ONLY ) {
+           if( st->bandwidth == OPUS_BANDWIDTH_NARROWBAND ) {
+              st->DecControl.internalSampleRate = 8000;
+           } else if( st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND ) {
+              st->DecControl.internalSampleRate = 12000;
+           } else if( st->bandwidth == OPUS_BANDWIDTH_WIDEBAND ) {
+              st->DecControl.internalSampleRate = 16000;
+           } else {
+              st->DecControl.internalSampleRate = 16000;
+              silk_assert( 0 );
+           }
+        } else {
+           /* Hybrid mode */
+           st->DecControl.internalSampleRate = 16000;
+        }
+     }
+
+     lost_flag = data == NULL ? 1 : 2 * decode_fec;
+     decoded_samples = 0;
+     do {
+        /* Call SILK decoder */
+        int first_frame = decoded_samples == 0;
+        silk_ret = silk_Decode( silk_dec, &st->DecControl,
+                                lost_flag, first_frame, &dec, pcm_ptr, &silk_frame_size, st->arch );
+        if( silk_ret ) {
+           if (lost_flag) {
+              /* PLC failure should not be fatal */
+              silk_frame_size = frame_size;
+              for (i=0;i<frame_size*st->channels;i++)
+                 pcm_ptr[i] = 0;
+           } else {
+             RESTORE_STACK;
+             return OPUS_INTERNAL_ERROR;
+           }
+        }
+        pcm_ptr += silk_frame_size * st->channels;
+        decoded_samples += silk_frame_size;
+      } while( decoded_samples < frame_size );
+   }
+
+   start_band = 0;
+   if (!decode_fec && mode != MODE_CELT_ONLY && data != NULL
+    && ec_tell(&dec)+17+20*(st->mode == MODE_HYBRID) <= 8*len)
+   {
+      /* Check if we have a redundant 0-8 kHz band */
+      if (mode == MODE_HYBRID)
+         redundancy = ec_dec_bit_logp(&dec, 12);
+      else
+         redundancy = 1;
+      if (redundancy)
+      {
+         celt_to_silk = ec_dec_bit_logp(&dec, 1);
+         /* redundancy_bytes will be at least two, in the non-hybrid
+            case due to the ec_tell() check above */
+         redundancy_bytes = mode==MODE_HYBRID ?
+               (opus_int32)ec_dec_uint(&dec, 256)+2 :
+               len-((ec_tell(&dec)+7)>>3);
+         len -= redundancy_bytes;
+         /* This is a sanity check. It should never happen for a valid
+            packet, so the exact behaviour is not normative. */
+         if (len*8 < ec_tell(&dec))
+         {
+            len = 0;
+            redundancy_bytes = 0;
+            redundancy = 0;
+         }
+         /* Shrink decoder because of raw bits */
+         dec.storage -= redundancy_bytes;
+      }
+   }
+   if (mode != MODE_CELT_ONLY)
+      start_band = 17;
+
+   {
+      int endband=21;
+
+      switch(st->bandwidth)
+      {
+      case OPUS_BANDWIDTH_NARROWBAND:
+         endband = 13;
+         break;
+      case OPUS_BANDWIDTH_MEDIUMBAND:
+      case OPUS_BANDWIDTH_WIDEBAND:
+         endband = 17;
+         break;
+      case OPUS_BANDWIDTH_SUPERWIDEBAND:
+         endband = 19;
+         break;
+      case OPUS_BANDWIDTH_FULLBAND:
+         endband = 21;
+         break;
+      }
+      celt_decoder_ctl(celt_dec, CELT_SET_END_BAND(endband));
+      celt_decoder_ctl(celt_dec, CELT_SET_CHANNELS(st->stream_channels));
+   }
+
+   if (redundancy)
+   {
+      transition = 0;
+      pcm_transition_silk_size=ALLOC_NONE;
+   }
+
+   ALLOC(pcm_transition_silk, pcm_transition_silk_size, opus_val16);
+
+   if (transition && mode != MODE_CELT_ONLY)
+   {
+      pcm_transition = pcm_transition_silk;
+      opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
+   }
+
+   /* Only allocation memory for redundancy if/when needed */
+   redundant_audio_size = redundancy ? F5*st->channels : ALLOC_NONE;
+   ALLOC(redundant_audio, redundant_audio_size, opus_val16);
+
+   /* 5 ms redundant frame for CELT->SILK*/
+   if (redundancy && celt_to_silk)
+   {
+      celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
+      celt_decode_with_ec(celt_dec, data+len, redundancy_bytes,
+                          redundant_audio, F5, NULL, 0);
+      celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
+   }
+
+   /* MUST be after PLC */
+   celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(start_band));
+
+   if (mode != MODE_SILK_ONLY)
+   {
+      int celt_frame_size = IMIN(F20, frame_size);
+      /* Make sure to discard any previous CELT state */
+      if (mode != st->prev_mode && st->prev_mode > 0 && !st->prev_redundancy)
+         celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
+      /* Decode CELT */
+      celt_ret = celt_decode_with_ec(celt_dec, decode_fec ? NULL : data,
+                                     len, pcm, celt_frame_size, &dec, celt_accum);
+   } else {
+      unsigned char silence[2] = {0xFF, 0xFF};
+      if (!celt_accum)
+      {
+         for (i=0;i<frame_size*st->channels;i++)
+            pcm[i] = 0;
+      }
+      /* For hybrid -> SILK transitions, we let the CELT MDCT
+         do a fade-out by decoding a silence frame */
+      if (st->prev_mode == MODE_HYBRID && !(redundancy && celt_to_silk && st->prev_redundancy) )
+      {
+         celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
+         celt_decode_with_ec(celt_dec, silence, 2, pcm, F2_5, NULL, celt_accum);
+      }
+   }
+
+   if (mode != MODE_CELT_ONLY && !celt_accum)
+   {
+#ifdef FIXED_POINT
+      for (i=0;i<frame_size*st->channels;i++)
+         pcm[i] = SAT16(ADD32(pcm[i], pcm_silk[i]));
+#else
+      for (i=0;i<frame_size*st->channels;i++)
+         pcm[i] = pcm[i] + (opus_val16)((1.f/32768.f)*pcm_silk[i]);
+#endif
+   }
+
+   {
+      const CELTMode *celt_mode;
+      celt_decoder_ctl(celt_dec, CELT_GET_MODE(&celt_mode));
+      window = celt_mode->window;
+   }
+
+   /* 5 ms redundant frame for SILK->CELT */
+   if (redundancy && !celt_to_silk)
+   {
+      celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
+      celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
+
+      celt_decode_with_ec(celt_dec, data+len, redundancy_bytes, redundant_audio, F5, NULL, 0);
+      celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
+      smooth_fade(pcm+st->channels*(frame_size-F2_5), redundant_audio+st->channels*F2_5,
+                  pcm+st->channels*(frame_size-F2_5), F2_5, st->channels, window, st->Fs);
+   }
+   if (redundancy && celt_to_silk)
+   {
+      for (c=0;c<st->channels;c++)
+      {
+         for (i=0;i<F2_5;i++)
+            pcm[st->channels*i+c] = redundant_audio[st->channels*i+c];
+      }
+      smooth_fade(redundant_audio+st->channels*F2_5, pcm+st->channels*F2_5,
+                  pcm+st->channels*F2_5, F2_5, st->channels, window, st->Fs);
+   }
+   if (transition)
+   {
+      if (audiosize >= F5)
+      {
+         for (i=0;i<st->channels*F2_5;i++)
+            pcm[i] = pcm_transition[i];
+         smooth_fade(pcm_transition+st->channels*F2_5, pcm+st->channels*F2_5,
+                     pcm+st->channels*F2_5, F2_5,
+                     st->channels, window, st->Fs);
+      } else {
+         /* Not enough time to do a clean transition, but we do it anyway
+            This will not preserve amplitude perfectly and may introduce
+            a bit of temporal aliasing, but it shouldn't be too bad and
+            that's pretty much the best we can do. In any case, generating this
+            transition it pretty silly in the first place */
+         smooth_fade(pcm_transition, pcm,
+                     pcm, F2_5,
+                     st->channels, window, st->Fs);
+      }
+   }
+
+   if(st->decode_gain)
+   {
+      opus_val32 gain;
+      gain = celt_exp2(MULT16_16_P15(QCONST16(6.48814081e-4f, 25), st->decode_gain));
+      for (i=0;i<frame_size*st->channels;i++)
+      {
+         opus_val32 x;
+         x = MULT16_32_P16(pcm[i],gain);
+         pcm[i] = SATURATE(x, 32767);
+      }
+   }
+
+   if (len <= 1)
+      st->rangeFinal = 0;
+   else
+      st->rangeFinal = dec.rng ^ redundant_rng;
+
+   st->prev_mode = mode;
+   st->prev_redundancy = redundancy && !celt_to_silk;
+
+   if (celt_ret>=0)
+   {
+      if (OPUS_CHECK_ARRAY(pcm, audiosize*st->channels))
+         OPUS_PRINT_INT(audiosize);
+   }
+
+   RESTORE_STACK;
+   return celt_ret < 0 ? celt_ret : audiosize;
+
+}
+
+int opus_decode_native(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec,
+      int self_delimited, opus_int32 *packet_offset, int soft_clip)
+{
+   int i, nb_samples;
+   int count, offset;
+   unsigned char toc;
+   int packet_frame_size, packet_bandwidth, packet_mode, packet_stream_channels;
+   /* 48 x 2.5 ms = 120 ms */
+   opus_int16 size[48];
+   if (decode_fec<0 || decode_fec>1)
+      return OPUS_BAD_ARG;
+   /* For FEC/PLC, frame_size has to be to have a multiple of 2.5 ms */
+   if ((decode_fec || len==0 || data==NULL) && frame_size%(st->Fs/400)!=0)
+      return OPUS_BAD_ARG;
+   if (len==0 || data==NULL)
+   {
+      int pcm_count=0;
+      do {
+         int ret;
+         ret = opus_decode_frame(st, NULL, 0, pcm+pcm_count*st->channels, frame_size-pcm_count, 0);
+         if (ret<0)
+            return ret;
+         pcm_count += ret;
+      } while (pcm_count < frame_size);
+      celt_assert(pcm_count == frame_size);
+      if (OPUS_CHECK_ARRAY(pcm, pcm_count*st->channels))
+         OPUS_PRINT_INT(pcm_count);
+      st->last_packet_duration = pcm_count;
+      return pcm_count;
+   } else if (len<0)
+      return OPUS_BAD_ARG;
+
+   packet_mode = opus_packet_get_mode(data);
+   packet_bandwidth = opus_packet_get_bandwidth(data);
+   packet_frame_size = opus_packet_get_samples_per_frame(data, st->Fs);
+   packet_stream_channels = opus_packet_get_nb_channels(data);
+
+   count = opus_packet_parse_impl(data, len, self_delimited, &toc, NULL,
+                                  size, &offset, packet_offset);
+   if (count<0)
+      return count;
+
+   data += offset;
+
+   if (decode_fec)
+   {
+      int duration_copy;
+      int ret;
+      /* If no FEC can be present, run the PLC (recursive call) */
+      if (frame_size < packet_frame_size || packet_mode == MODE_CELT_ONLY || st->mode == MODE_CELT_ONLY)
+         return opus_decode_native(st, NULL, 0, pcm, frame_size, 0, 0, NULL, soft_clip);
+      /* Otherwise, run the PLC on everything except the size for which we might have FEC */
+      duration_copy = st->last_packet_duration;
+      if (frame_size-packet_frame_size!=0)
+      {
+         ret = opus_decode_native(st, NULL, 0, pcm, frame_size-packet_frame_size, 0, 0, NULL, soft_clip);
+         if (ret<0)
+         {
+            st->last_packet_duration = duration_copy;
+            return ret;
+         }
+         celt_assert(ret==frame_size-packet_frame_size);
+      }
+      /* Complete with FEC */
+      st->mode = packet_mode;
+      st->bandwidth = packet_bandwidth;
+      st->frame_size = packet_frame_size;
+      st->stream_channels = packet_stream_channels;
+      ret = opus_decode_frame(st, data, size[0], pcm+st->channels*(frame_size-packet_frame_size),
+            packet_frame_size, 1);
+      if (ret<0)
+         return ret;
+      else {
+         if (OPUS_CHECK_ARRAY(pcm, frame_size*st->channels))
+            OPUS_PRINT_INT(frame_size);
+         st->last_packet_duration = frame_size;
+         return frame_size;
+      }
+   }
+
+   if (count*packet_frame_size > frame_size)
+      return OPUS_BUFFER_TOO_SMALL;
+
+   /* Update the state as the last step to avoid updating it on an invalid packet */
+   st->mode = packet_mode;
+   st->bandwidth = packet_bandwidth;
+   st->frame_size = packet_frame_size;
+   st->stream_channels = packet_stream_channels;
+
+   nb_samples=0;
+   for (i=0;i<count;i++)
+   {
+      int ret;
+      ret = opus_decode_frame(st, data, size[i], pcm+nb_samples*st->channels, frame_size-nb_samples, 0);
+      if (ret<0)
+         return ret;
+      celt_assert(ret==packet_frame_size);
+      data += size[i];
+      nb_samples += ret;
+   }
+   st->last_packet_duration = nb_samples;
+   if (OPUS_CHECK_ARRAY(pcm, nb_samples*st->channels))
+      OPUS_PRINT_INT(nb_samples);
+#ifndef FIXED_POINT
+   if (soft_clip)
+      opus_pcm_soft_clip(pcm, nb_samples, st->channels, st->softclip_mem);
+   else
+      st->softclip_mem[0]=st->softclip_mem[1]=0;
+#endif
+   return nb_samples;
+}
+
+#ifdef FIXED_POINT
+
+int opus_decode(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
+{
+   if(frame_size<=0)
+      return OPUS_BAD_ARG;
+   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL, 0);
+}
+
+#ifndef DISABLE_FLOAT_API
+int opus_decode_float(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, float *pcm, int frame_size, int decode_fec)
+{
+   VARDECL(opus_int16, out);
+   int ret, i;
+   int nb_samples;
+   ALLOC_STACK;
+
+   if(frame_size<=0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   if (data != NULL && len > 0 && !decode_fec)
+   {
+      nb_samples = opus_decoder_get_nb_samples(st, data, len);
+      if (nb_samples>0)
+         frame_size = IMIN(frame_size, nb_samples);
+      else
+         return OPUS_INVALID_PACKET;
+   }
+   ALLOC(out, frame_size*st->channels, opus_int16);
+
+   ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL, 0);
+   if (ret > 0)
+   {
+      for (i=0;i<ret*st->channels;i++)
+         pcm[i] = (1.f/32768.f)*(out[i]);
+   }
+   RESTORE_STACK;
+   return ret;
+}
+#endif
+
+
+#else
+int opus_decode(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_int16 *pcm, int frame_size, int decode_fec)
+{
+   VARDECL(float, out);
+   int ret, i;
+   int nb_samples;
+   ALLOC_STACK;
+
+   if(frame_size<=0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+
+   if (data != NULL && len > 0 && !decode_fec)
+   {
+      nb_samples = opus_decoder_get_nb_samples(st, data, len);
+      if (nb_samples>0)
+         frame_size = IMIN(frame_size, nb_samples);
+      else
+         return OPUS_INVALID_PACKET;
+   }
+   ALLOC(out, frame_size*st->channels, float);
+
+   ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL, 1);
+   if (ret > 0)
+   {
+      for (i=0;i<ret*st->channels;i++)
+         pcm[i] = FLOAT2INT16(out[i]);
+   }
+   RESTORE_STACK;
+   return ret;
+}
+
+int opus_decode_float(OpusDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
+{
+   if(frame_size<=0)
+      return OPUS_BAD_ARG;
+   return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL, 0);
+}
+
+#endif
+
+int opus_decoder_ctl(OpusDecoder *st, int request, ...)
+{
+   int ret = OPUS_OK;
+   va_list ap;
+   void *silk_dec;
+   CELTDecoder *celt_dec;
+
+   silk_dec = (char*)st+st->silk_dec_offset;
+   celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
+
+
+   va_start(ap, request);
+
+   switch (request)
+   {
+   case OPUS_GET_BANDWIDTH_REQUEST:
+   {
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = st->bandwidth;
+   }
+   break;
+   case OPUS_GET_FINAL_RANGE_REQUEST:
+   {
+      opus_uint32 *value = va_arg(ap, opus_uint32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = st->rangeFinal;
+   }
+   break;
+   case OPUS_RESET_STATE:
+   {
+      OPUS_CLEAR((char*)&st->OPUS_DECODER_RESET_START,
+            sizeof(OpusDecoder)-
+            ((char*)&st->OPUS_DECODER_RESET_START - (char*)st));
+
+      celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
+      silk_InitDecoder( silk_dec );
+      st->stream_channels = st->channels;
+      st->frame_size = st->Fs/400;
+   }
+   break;
+   case OPUS_GET_SAMPLE_RATE_REQUEST:
+   {
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = st->Fs;
+   }
+   break;
+   case OPUS_GET_PITCH_REQUEST:
+   {
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      if (st->prev_mode == MODE_CELT_ONLY)
+         celt_decoder_ctl(celt_dec, OPUS_GET_PITCH(value));
+      else
+         *value = st->DecControl.prevPitchLag;
+   }
+   break;
+   case OPUS_GET_GAIN_REQUEST:
+   {
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = st->decode_gain;
+   }
+   break;
+   case OPUS_SET_GAIN_REQUEST:
+   {
+       opus_int32 value = va_arg(ap, opus_int32);
+       if (value<-32768 || value>32767)
+       {
+          goto bad_arg;
+       }
+       st->decode_gain = value;
+   }
+   break;
+   case OPUS_GET_LAST_PACKET_DURATION_REQUEST:
+   {
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = st->last_packet_duration;
+   }
+   break;
+   case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+   {
+       opus_int32 value = va_arg(ap, opus_int32);
+       if(value<0 || value>1)
+       {
+          goto bad_arg;
+       }
+       celt_decoder_ctl(celt_dec, OPUS_SET_PHASE_INVERSION_DISABLED(value));
+   }
+   break;
+   case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+   {
+       opus_int32 *value = va_arg(ap, opus_int32*);
+       if (!value)
+       {
+          goto bad_arg;
+       }
+       celt_decoder_ctl(celt_dec, OPUS_GET_PHASE_INVERSION_DISABLED(value));
+   }
+   break;
+   default:
+      /*fprintf(stderr, "unknown opus_decoder_ctl() request: %d", request);*/
+      ret = OPUS_UNIMPLEMENTED;
+      break;
+   }
+
+   va_end(ap);
+   return ret;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
+}
+
+void opus_decoder_destroy(OpusDecoder *st)
+{
+   opus_free(st);
+}
+
+
+int opus_packet_get_bandwidth(const unsigned char *data)
+{
+   int bandwidth;
+   if (data[0]&0x80)
+   {
+      bandwidth = OPUS_BANDWIDTH_MEDIUMBAND + ((data[0]>>5)&0x3);
+      if (bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
+         bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+   } else if ((data[0]&0x60) == 0x60)
+   {
+      bandwidth = (data[0]&0x10) ? OPUS_BANDWIDTH_FULLBAND :
+                                   OPUS_BANDWIDTH_SUPERWIDEBAND;
+   } else {
+      bandwidth = OPUS_BANDWIDTH_NARROWBAND + ((data[0]>>5)&0x3);
+   }
+   return bandwidth;
+}
+
+int opus_packet_get_nb_channels(const unsigned char *data)
+{
+   return (data[0]&0x4) ? 2 : 1;
+}
+
+int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len)
+{
+   int count;
+   if (len<1)
+      return OPUS_BAD_ARG;
+   count = packet[0]&0x3;
+   if (count==0)
+      return 1;
+   else if (count!=3)
+      return 2;
+   else if (len<2)
+      return OPUS_INVALID_PACKET;
+   else
+      return packet[1]&0x3F;
+}
+
+int opus_packet_get_nb_samples(const unsigned char packet[], opus_int32 len,
+      opus_int32 Fs)
+{
+   int samples;
+   int count = opus_packet_get_nb_frames(packet, len);
+
+   if (count<0)
+      return count;
+
+   samples = count*opus_packet_get_samples_per_frame(packet, Fs);
+   /* Can't have more than 120 ms */
+   if (samples*25 > Fs*3)
+      return OPUS_INVALID_PACKET;
+   else
+      return samples;
+}
+
+int opus_decoder_get_nb_samples(const OpusDecoder *dec,
+      const unsigned char packet[], opus_int32 len)
+{
+   return opus_packet_get_nb_samples(packet, len, dec->Fs);
+}
diff --git a/opus/src/opus_demo.c b/opus/src/opus_demo.c
new file mode 100644 (file)
index 0000000..50987c9
--- /dev/null
@@ -0,0 +1,893 @@
+/* Copyright (c) 2007-2008 CSIRO
+   Copyright (c) 2007-2009 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include "opus.h"
+#include "debug.h"
+#include "opus_types.h"
+#include "opus_private.h"
+#include "opus_multistream.h"
+
+#define MAX_PACKET 1500
+
+void print_usage( char* argv[] )
+{
+    fprintf(stderr, "Usage: %s [-e] <application> <sampling rate (Hz)> <channels (1/2)> "
+        "<bits per second>  [options] <input> <output>\n", argv[0]);
+    fprintf(stderr, "       %s -d <sampling rate (Hz)> <channels (1/2)> "
+        "[options] <input> <output>\n\n", argv[0]);
+    fprintf(stderr, "application: voip | audio | restricted-lowdelay\n" );
+    fprintf(stderr, "options:\n" );
+    fprintf(stderr, "-e                   : only runs the encoder (output the bit-stream)\n" );
+    fprintf(stderr, "-d                   : only runs the decoder (reads the bit-stream as input)\n" );
+    fprintf(stderr, "-cbr                 : enable constant bitrate; default: variable bitrate\n" );
+    fprintf(stderr, "-cvbr                : enable constrained variable bitrate; default: unconstrained\n" );
+    fprintf(stderr, "-delayed-decision    : use look-ahead for speech/music detection (experts only); default: disabled\n" );
+    fprintf(stderr, "-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate\n" );
+    fprintf(stderr, "-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20 \n" );
+    fprintf(stderr, "-max_payload <bytes> : maximum payload size in bytes, default: 1024\n" );
+    fprintf(stderr, "-complexity <comp>   : complexity, 0 (lowest) ... 10 (highest); default: 10\n" );
+    fprintf(stderr, "-inbandfec           : enable SILK inband FEC\n" );
+    fprintf(stderr, "-forcemono           : force mono encoding, even for stereo input\n" );
+    fprintf(stderr, "-dtx                 : enable SILK DTX\n" );
+    fprintf(stderr, "-loss <perc>         : simulate packet loss, in percent (0-100); default: 0\n" );
+}
+
+static void int_to_char(opus_uint32 i, unsigned char ch[4])
+{
+    ch[0] = i>>24;
+    ch[1] = (i>>16)&0xFF;
+    ch[2] = (i>>8)&0xFF;
+    ch[3] = i&0xFF;
+}
+
+static opus_uint32 char_to_int(unsigned char ch[4])
+{
+    return ((opus_uint32)ch[0]<<24) | ((opus_uint32)ch[1]<<16)
+         | ((opus_uint32)ch[2]<< 8) |  (opus_uint32)ch[3];
+}
+
+static void check_encoder_option(int decode_only, const char *opt)
+{
+   if (decode_only)
+   {
+      fprintf(stderr, "option %s is only for encoding\n", opt);
+      exit(EXIT_FAILURE);
+   }
+}
+
+static const int silk8_test[][4] = {
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   2}
+};
+
+static const int silk12_test[][4] = {
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   2}
+};
+
+static const int silk16_test[][4] = {
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   2}
+};
+
+static const int hybrid24_test[][4] = {
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2}
+};
+
+static const int hybrid48_test[][4] = {
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 1},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2},
+      {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2}
+};
+
+static const int celt_test[][4] = {
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 1},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 1},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 1},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 1},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 1},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 2},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 2},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 2},
+
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 2},
+
+};
+
+static const int celt_hq_test[][4] = {
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
+      {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
+};
+
+#if 0 /* This is a hack that replaces the normal encoder/decoder with the multistream version */
+#define OpusEncoder OpusMSEncoder
+#define OpusDecoder OpusMSDecoder
+#define opus_encode opus_multistream_encode
+#define opus_decode opus_multistream_decode
+#define opus_encoder_ctl opus_multistream_encoder_ctl
+#define opus_decoder_ctl opus_multistream_decoder_ctl
+#define opus_encoder_create ms_opus_encoder_create
+#define opus_decoder_create ms_opus_decoder_create
+#define opus_encoder_destroy opus_multistream_encoder_destroy
+#define opus_decoder_destroy opus_multistream_decoder_destroy
+
+static OpusEncoder *ms_opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
+{
+   int streams, coupled_streams;
+   unsigned char mapping[256];
+   return (OpusEncoder *)opus_multistream_surround_encoder_create(Fs, channels, 1, &streams, &coupled_streams, mapping, application, error);
+}
+static OpusDecoder *ms_opus_decoder_create(opus_int32 Fs, int channels, int *error)
+{
+   int streams;
+   int coupled_streams;
+   unsigned char mapping[256]={0,1};
+   streams = 1;
+   coupled_streams = channels==2;
+   return (OpusDecoder *)opus_multistream_decoder_create(Fs, channels, streams, coupled_streams, mapping, error);
+}
+#endif
+
+int main(int argc, char *argv[])
+{
+    int err;
+    char *inFile, *outFile;
+    FILE *fin, *fout;
+    OpusEncoder *enc=NULL;
+    OpusDecoder *dec=NULL;
+    int args;
+    int len[2];
+    int frame_size, channels;
+    opus_int32 bitrate_bps=0;
+    unsigned char *data[2];
+    unsigned char *fbytes;
+    opus_int32 sampling_rate;
+    int use_vbr;
+    int max_payload_bytes;
+    int complexity;
+    int use_inbandfec;
+    int use_dtx;
+    int forcechannels;
+    int cvbr = 0;
+    int packet_loss_perc;
+    opus_int32 count=0, count_act=0;
+    int k;
+    opus_int32 skip=0;
+    int stop=0;
+    short *in, *out;
+    int application=OPUS_APPLICATION_AUDIO;
+    double bits=0.0, bits_max=0.0, bits_act=0.0, bits2=0.0, nrg;
+    double tot_samples=0;
+    opus_uint64 tot_in, tot_out;
+    int bandwidth=OPUS_AUTO;
+    const char *bandwidth_string;
+    int lost = 0, lost_prev = 1;
+    int toggle = 0;
+    opus_uint32 enc_final_range[2];
+    opus_uint32 dec_final_range;
+    int encode_only=0, decode_only=0;
+    int max_frame_size = 48000*2;
+    size_t num_read;
+    int curr_read=0;
+    int sweep_bps = 0;
+    int random_framesize=0, newsize=0, delayed_celt=0;
+    int sweep_max=0, sweep_min=0;
+    int random_fec=0;
+    const int (*mode_list)[4]=NULL;
+    int nb_modes_in_list=0;
+    int curr_mode=0;
+    int curr_mode_count=0;
+    int mode_switch_time = 48000;
+    int nb_encoded=0;
+    int remaining=0;
+    int variable_duration=OPUS_FRAMESIZE_ARG;
+    int delayed_decision=0;
+
+    if (argc < 5 )
+    {
+       print_usage( argv );
+       return EXIT_FAILURE;
+    }
+
+    tot_in=tot_out=0;
+    fprintf(stderr, "%s\n", opus_get_version_string());
+
+    args = 1;
+    if (strcmp(argv[args], "-e")==0)
+    {
+        encode_only = 1;
+        args++;
+    } else if (strcmp(argv[args], "-d")==0)
+    {
+        decode_only = 1;
+        args++;
+    }
+    if (!decode_only && argc < 7 )
+    {
+       print_usage( argv );
+       return EXIT_FAILURE;
+    }
+
+    if (!decode_only)
+    {
+       if (strcmp(argv[args], "voip")==0)
+          application = OPUS_APPLICATION_VOIP;
+       else if (strcmp(argv[args], "restricted-lowdelay")==0)
+          application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
+       else if (strcmp(argv[args], "audio")!=0) {
+          fprintf(stderr, "unknown application: %s\n", argv[args]);
+          print_usage(argv);
+          return EXIT_FAILURE;
+       }
+       args++;
+    }
+    sampling_rate = (opus_int32)atol(argv[args]);
+    args++;
+
+    if (sampling_rate != 8000 && sampling_rate != 12000
+     && sampling_rate != 16000 && sampling_rate != 24000
+     && sampling_rate != 48000)
+    {
+        fprintf(stderr, "Supported sampling rates are 8000, 12000, "
+                "16000, 24000 and 48000.\n");
+        return EXIT_FAILURE;
+    }
+    frame_size = sampling_rate/50;
+
+    channels = atoi(argv[args]);
+    args++;
+
+    if (channels < 1 || channels > 2)
+    {
+        fprintf(stderr, "Opus_demo supports only 1 or 2 channels.\n");
+        return EXIT_FAILURE;
+    }
+
+    if (!decode_only)
+    {
+       bitrate_bps = (opus_int32)atol(argv[args]);
+       args++;
+    }
+
+    /* defaults: */
+    use_vbr = 1;
+    max_payload_bytes = MAX_PACKET;
+    complexity = 10;
+    use_inbandfec = 0;
+    forcechannels = OPUS_AUTO;
+    use_dtx = 0;
+    packet_loss_perc = 0;
+
+    while( args < argc - 2 ) {
+        /* process command line options */
+        if( strcmp( argv[ args ], "-cbr" ) == 0 ) {
+            check_encoder_option(decode_only, "-cbr");
+            use_vbr = 0;
+            args++;
+        } else if( strcmp( argv[ args ], "-bandwidth" ) == 0 ) {
+            check_encoder_option(decode_only, "-bandwidth");
+            if (strcmp(argv[ args + 1 ], "NB")==0)
+                bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+            else if (strcmp(argv[ args + 1 ], "MB")==0)
+                bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+            else if (strcmp(argv[ args + 1 ], "WB")==0)
+                bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+            else if (strcmp(argv[ args + 1 ], "SWB")==0)
+                bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
+            else if (strcmp(argv[ args + 1 ], "FB")==0)
+                bandwidth = OPUS_BANDWIDTH_FULLBAND;
+            else {
+                fprintf(stderr, "Unknown bandwidth %s. "
+                                "Supported are NB, MB, WB, SWB, FB.\n",
+                                argv[ args + 1 ]);
+                return EXIT_FAILURE;
+            }
+            args += 2;
+        } else if( strcmp( argv[ args ], "-framesize" ) == 0 ) {
+            check_encoder_option(decode_only, "-framesize");
+            if (strcmp(argv[ args + 1 ], "2.5")==0)
+                frame_size = sampling_rate/400;
+            else if (strcmp(argv[ args + 1 ], "5")==0)
+                frame_size = sampling_rate/200;
+            else if (strcmp(argv[ args + 1 ], "10")==0)
+                frame_size = sampling_rate/100;
+            else if (strcmp(argv[ args + 1 ], "20")==0)
+                frame_size = sampling_rate/50;
+            else if (strcmp(argv[ args + 1 ], "40")==0)
+                frame_size = sampling_rate/25;
+            else if (strcmp(argv[ args + 1 ], "60")==0)
+                frame_size = 3*sampling_rate/50;
+            else if (strcmp(argv[ args + 1 ], "80")==0)
+                frame_size = 4*sampling_rate/50;
+            else if (strcmp(argv[ args + 1 ], "100")==0)
+                frame_size = 5*sampling_rate/50;
+            else if (strcmp(argv[ args + 1 ], "120")==0)
+                frame_size = 6*sampling_rate/50;
+            else {
+                fprintf(stderr, "Unsupported frame size: %s ms. "
+                                "Supported are 2.5, 5, 10, 20, 40, 60, 80, 100, 120.\n",
+                                argv[ args + 1 ]);
+                return EXIT_FAILURE;
+            }
+            args += 2;
+        } else if( strcmp( argv[ args ], "-max_payload" ) == 0 ) {
+            check_encoder_option(decode_only, "-max_payload");
+            max_payload_bytes = atoi( argv[ args + 1 ] );
+            args += 2;
+        } else if( strcmp( argv[ args ], "-complexity" ) == 0 ) {
+            check_encoder_option(decode_only, "-complexity");
+            complexity = atoi( argv[ args + 1 ] );
+            args += 2;
+        } else if( strcmp( argv[ args ], "-inbandfec" ) == 0 ) {
+            use_inbandfec = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-forcemono" ) == 0 ) {
+            check_encoder_option(decode_only, "-forcemono");
+            forcechannels = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-cvbr" ) == 0 ) {
+            check_encoder_option(decode_only, "-cvbr");
+            cvbr = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-delayed-decision" ) == 0 ) {
+            check_encoder_option(decode_only, "-delayed-decision");
+            delayed_decision = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-dtx") == 0 ) {
+            check_encoder_option(decode_only, "-dtx");
+            use_dtx = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-loss" ) == 0 ) {
+            packet_loss_perc = atoi( argv[ args + 1 ] );
+            args += 2;
+        } else if( strcmp( argv[ args ], "-sweep" ) == 0 ) {
+            check_encoder_option(decode_only, "-sweep");
+            sweep_bps = atoi( argv[ args + 1 ] );
+            args += 2;
+        } else if( strcmp( argv[ args ], "-random_framesize" ) == 0 ) {
+            check_encoder_option(decode_only, "-random_framesize");
+            random_framesize = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-sweep_max" ) == 0 ) {
+            check_encoder_option(decode_only, "-sweep_max");
+            sweep_max = atoi( argv[ args + 1 ] );
+            args += 2;
+        } else if( strcmp( argv[ args ], "-random_fec" ) == 0 ) {
+            check_encoder_option(decode_only, "-random_fec");
+            random_fec = 1;
+            args++;
+        } else if( strcmp( argv[ args ], "-silk8k_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-silk8k_test");
+            mode_list = silk8_test;
+            nb_modes_in_list = 8;
+            args++;
+        } else if( strcmp( argv[ args ], "-silk12k_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-silk12k_test");
+            mode_list = silk12_test;
+            nb_modes_in_list = 8;
+            args++;
+        } else if( strcmp( argv[ args ], "-silk16k_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-silk16k_test");
+            mode_list = silk16_test;
+            nb_modes_in_list = 8;
+            args++;
+        } else if( strcmp( argv[ args ], "-hybrid24k_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-hybrid24k_test");
+            mode_list = hybrid24_test;
+            nb_modes_in_list = 4;
+            args++;
+        } else if( strcmp( argv[ args ], "-hybrid48k_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-hybrid48k_test");
+            mode_list = hybrid48_test;
+            nb_modes_in_list = 4;
+            args++;
+        } else if( strcmp( argv[ args ], "-celt_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-celt_test");
+            mode_list = celt_test;
+            nb_modes_in_list = 32;
+            args++;
+        } else if( strcmp( argv[ args ], "-celt_hq_test" ) == 0 ) {
+            check_encoder_option(decode_only, "-celt_hq_test");
+            mode_list = celt_hq_test;
+            nb_modes_in_list = 4;
+            args++;
+        } else {
+            printf( "Error: unrecognized setting: %s\n\n", argv[ args ] );
+            print_usage( argv );
+            return EXIT_FAILURE;
+        }
+    }
+
+    if (sweep_max)
+       sweep_min = bitrate_bps;
+
+    if (max_payload_bytes < 0 || max_payload_bytes > MAX_PACKET)
+    {
+        fprintf (stderr, "max_payload_bytes must be between 0 and %d\n",
+                          MAX_PACKET);
+        return EXIT_FAILURE;
+    }
+
+    inFile = argv[argc-2];
+    fin = fopen(inFile, "rb");
+    if (!fin)
+    {
+        fprintf (stderr, "Could not open input file %s\n", argv[argc-2]);
+        return EXIT_FAILURE;
+    }
+    if (mode_list)
+    {
+       int size;
+       fseek(fin, 0, SEEK_END);
+       size = ftell(fin);
+       fprintf(stderr, "File size is %d bytes\n", size);
+       fseek(fin, 0, SEEK_SET);
+       mode_switch_time = size/sizeof(short)/channels/nb_modes_in_list;
+       fprintf(stderr, "Switching mode every %d samples\n", mode_switch_time);
+    }
+
+    outFile = argv[argc-1];
+    fout = fopen(outFile, "wb+");
+    if (!fout)
+    {
+        fprintf (stderr, "Could not open output file %s\n", argv[argc-1]);
+        fclose(fin);
+        return EXIT_FAILURE;
+    }
+
+    if (!decode_only)
+    {
+       enc = opus_encoder_create(sampling_rate, channels, application, &err);
+       if (err != OPUS_OK)
+       {
+          fprintf(stderr, "Cannot create encoder: %s\n", opus_strerror(err));
+          fclose(fin);
+          fclose(fout);
+          return EXIT_FAILURE;
+       }
+       opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
+       opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(bandwidth));
+       opus_encoder_ctl(enc, OPUS_SET_VBR(use_vbr));
+       opus_encoder_ctl(enc, OPUS_SET_VBR_CONSTRAINT(cvbr));
+       opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
+       opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(use_inbandfec));
+       opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(forcechannels));
+       opus_encoder_ctl(enc, OPUS_SET_DTX(use_dtx));
+       opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(packet_loss_perc));
+
+       opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip));
+       opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16));
+       opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
+    }
+    if (!encode_only)
+    {
+       dec = opus_decoder_create(sampling_rate, channels, &err);
+       if (err != OPUS_OK)
+       {
+          fprintf(stderr, "Cannot create decoder: %s\n", opus_strerror(err));
+          fclose(fin);
+          fclose(fout);
+          return EXIT_FAILURE;
+       }
+    }
+
+
+    switch(bandwidth)
+    {
+    case OPUS_BANDWIDTH_NARROWBAND:
+         bandwidth_string = "narrowband";
+         break;
+    case OPUS_BANDWIDTH_MEDIUMBAND:
+         bandwidth_string = "mediumband";
+         break;
+    case OPUS_BANDWIDTH_WIDEBAND:
+         bandwidth_string = "wideband";
+         break;
+    case OPUS_BANDWIDTH_SUPERWIDEBAND:
+         bandwidth_string = "superwideband";
+         break;
+    case OPUS_BANDWIDTH_FULLBAND:
+         bandwidth_string = "fullband";
+         break;
+    case OPUS_AUTO:
+         bandwidth_string = "auto bandwidth";
+         break;
+    default:
+         bandwidth_string = "unknown";
+         break;
+    }
+
+    if (decode_only)
+       fprintf(stderr, "Decoding with %ld Hz output (%d channels)\n",
+                       (long)sampling_rate, channels);
+    else
+       fprintf(stderr, "Encoding %ld Hz input at %.3f kb/s "
+                       "in %s with %d-sample frames.\n",
+                       (long)sampling_rate, bitrate_bps*0.001,
+                       bandwidth_string, frame_size);
+
+    in = (short*)malloc(max_frame_size*channels*sizeof(short));
+    out = (short*)malloc(max_frame_size*channels*sizeof(short));
+    /* We need to allocate for 16-bit PCM data, but we store it as unsigned char. */
+    fbytes = (unsigned char*)malloc(max_frame_size*channels*sizeof(short));
+    data[0] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char));
+    if ( use_inbandfec ) {
+        data[1] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char));
+    }
+    if(delayed_decision)
+    {
+       if (frame_size==sampling_rate/400)
+          variable_duration = OPUS_FRAMESIZE_2_5_MS;
+       else if (frame_size==sampling_rate/200)
+          variable_duration = OPUS_FRAMESIZE_5_MS;
+       else if (frame_size==sampling_rate/100)
+          variable_duration = OPUS_FRAMESIZE_10_MS;
+       else if (frame_size==sampling_rate/50)
+          variable_duration = OPUS_FRAMESIZE_20_MS;
+       else if (frame_size==sampling_rate/25)
+          variable_duration = OPUS_FRAMESIZE_40_MS;
+       else if (frame_size==3*sampling_rate/50)
+          variable_duration = OPUS_FRAMESIZE_60_MS;
+       else if (frame_size==4*sampling_rate/50)
+          variable_duration = OPUS_FRAMESIZE_80_MS;
+       else if (frame_size==5*sampling_rate/50)
+          variable_duration = OPUS_FRAMESIZE_100_MS;
+       else
+          variable_duration = OPUS_FRAMESIZE_120_MS;
+       opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
+       frame_size = 2*48000;
+    }
+    while (!stop)
+    {
+        if (delayed_celt)
+        {
+            frame_size = newsize;
+            delayed_celt = 0;
+        } else if (random_framesize && rand()%20==0)
+        {
+            newsize = rand()%6;
+            switch(newsize)
+            {
+            case 0: newsize=sampling_rate/400; break;
+            case 1: newsize=sampling_rate/200; break;
+            case 2: newsize=sampling_rate/100; break;
+            case 3: newsize=sampling_rate/50; break;
+            case 4: newsize=sampling_rate/25; break;
+            case 5: newsize=3*sampling_rate/50; break;
+            }
+            while (newsize < sampling_rate/25 && bitrate_bps-abs(sweep_bps) <= 3*12*sampling_rate/newsize)
+               newsize*=2;
+            if (newsize < sampling_rate/100 && frame_size >= sampling_rate/100)
+            {
+                opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
+                delayed_celt=1;
+            } else {
+                frame_size = newsize;
+            }
+        }
+        if (random_fec && rand()%30==0)
+        {
+           opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(rand()%4==0));
+        }
+        if (decode_only)
+        {
+            unsigned char ch[4];
+            num_read = fread(ch, 1, 4, fin);
+            if (num_read!=4)
+                break;
+            len[toggle] = char_to_int(ch);
+            if (len[toggle]>max_payload_bytes || len[toggle]<0)
+            {
+                fprintf(stderr, "Invalid payload length: %d\n",len[toggle]);
+                break;
+            }
+            num_read = fread(ch, 1, 4, fin);
+            if (num_read!=4)
+                break;
+            enc_final_range[toggle] = char_to_int(ch);
+            num_read = fread(data[toggle], 1, len[toggle], fin);
+            if (num_read!=(size_t)len[toggle])
+            {
+                fprintf(stderr, "Ran out of input, "
+                                "expecting %d bytes got %d\n",
+                                len[toggle],(int)num_read);
+                break;
+            }
+        } else {
+            int i;
+            if (mode_list!=NULL)
+            {
+                opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(mode_list[curr_mode][1]));
+                opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(mode_list[curr_mode][0]));
+                opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(mode_list[curr_mode][3]));
+                frame_size = mode_list[curr_mode][2];
+            }
+            num_read = fread(fbytes, sizeof(short)*channels, frame_size-remaining, fin);
+            curr_read = (int)num_read;
+            tot_in += curr_read;
+            for(i=0;i<curr_read*channels;i++)
+            {
+                opus_int32 s;
+                s=fbytes[2*i+1]<<8|fbytes[2*i];
+                s=((s&0xFFFF)^0x8000)-0x8000;
+                in[i+remaining*channels]=s;
+            }
+            if (curr_read+remaining < frame_size)
+            {
+                for (i=(curr_read+remaining)*channels;i<frame_size*channels;i++)
+                   in[i] = 0;
+                if (encode_only || decode_only)
+                   stop = 1;
+            }
+            len[toggle] = opus_encode(enc, in, frame_size, data[toggle], max_payload_bytes);
+            nb_encoded = opus_packet_get_samples_per_frame(data[toggle], sampling_rate)*opus_packet_get_nb_frames(data[toggle], len[toggle]);
+            remaining = frame_size-nb_encoded;
+            for(i=0;i<remaining*channels;i++)
+               in[i] = in[nb_encoded*channels+i];
+            if (sweep_bps!=0)
+            {
+               bitrate_bps += sweep_bps;
+               if (sweep_max)
+               {
+                  if (bitrate_bps > sweep_max)
+                     sweep_bps = -sweep_bps;
+                  else if (bitrate_bps < sweep_min)
+                     sweep_bps = -sweep_bps;
+               }
+               /* safety */
+               if (bitrate_bps<1000)
+                  bitrate_bps = 1000;
+               opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
+            }
+            opus_encoder_ctl(enc, OPUS_GET_FINAL_RANGE(&enc_final_range[toggle]));
+            if (len[toggle] < 0)
+            {
+                fprintf (stderr, "opus_encode() returned %d\n", len[toggle]);
+                fclose(fin);
+                fclose(fout);
+                return EXIT_FAILURE;
+            }
+            curr_mode_count += frame_size;
+            if (curr_mode_count > mode_switch_time && curr_mode < nb_modes_in_list-1)
+            {
+               curr_mode++;
+               curr_mode_count = 0;
+            }
+        }
+
+#if 0 /* This is for testing the padding code, do not enable by default */
+        if (len[toggle]<1275)
+        {
+           int new_len = len[toggle]+rand()%(max_payload_bytes-len[toggle]);
+           if ((err = opus_packet_pad(data[toggle], len[toggle], new_len)) != OPUS_OK)
+           {
+              fprintf(stderr, "padding failed: %s\n", opus_strerror(err));
+              return EXIT_FAILURE;
+           }
+           len[toggle] = new_len;
+        }
+#endif
+        if (encode_only)
+        {
+            unsigned char int_field[4];
+            int_to_char(len[toggle], int_field);
+            if (fwrite(int_field, 1, 4, fout) != 4) {
+               fprintf(stderr, "Error writing.\n");
+               return EXIT_FAILURE;
+            }
+            int_to_char(enc_final_range[toggle], int_field);
+            if (fwrite(int_field, 1, 4, fout) != 4) {
+               fprintf(stderr, "Error writing.\n");
+               return EXIT_FAILURE;
+            }
+            if (fwrite(data[toggle], 1, len[toggle], fout) != (unsigned)len[toggle]) {
+               fprintf(stderr, "Error writing.\n");
+               return EXIT_FAILURE;
+            }
+            tot_samples += nb_encoded;
+        } else {
+            opus_int32 output_samples;
+            lost = len[toggle]==0 || (packet_loss_perc>0 && rand()%100 < packet_loss_perc);
+            if (lost)
+               opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
+            else
+               output_samples = max_frame_size;
+            if( count >= use_inbandfec ) {
+                /* delay by one packet when using in-band FEC */
+                if( use_inbandfec  ) {
+                    if( lost_prev ) {
+                        /* attempt to decode with in-band FEC from next packet */
+                        opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
+                        output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 1);
+                    } else {
+                        /* regular decode */
+                        output_samples = max_frame_size;
+                        output_samples = opus_decode(dec, data[1-toggle], len[1-toggle], out, output_samples, 0);
+                    }
+                } else {
+                    output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 0);
+                }
+                if (output_samples>0)
+                {
+                    if (!decode_only && tot_out + output_samples > tot_in)
+                    {
+                       stop=1;
+                       output_samples = (opus_int32)(tot_in - tot_out);
+                    }
+                    if (output_samples>skip) {
+                       int i;
+                       for(i=0;i<(output_samples-skip)*channels;i++)
+                       {
+                          short s;
+                          s=out[i+(skip*channels)];
+                          fbytes[2*i]=s&0xFF;
+                          fbytes[2*i+1]=(s>>8)&0xFF;
+                       }
+                       if (fwrite(fbytes, sizeof(short)*channels, output_samples-skip, fout) != (unsigned)(output_samples-skip)){
+                          fprintf(stderr, "Error writing.\n");
+                          return EXIT_FAILURE;
+                       }
+                       tot_out += output_samples-skip;
+                    }
+                    if (output_samples<skip) skip -= output_samples;
+                    else skip = 0;
+                } else {
+                   fprintf(stderr, "error decoding frame: %s\n",
+                                   opus_strerror(output_samples));
+                }
+                tot_samples += output_samples;
+            }
+        }
+
+        if (!encode_only)
+           opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE(&dec_final_range));
+        /* compare final range encoder rng values of encoder and decoder */
+        if( enc_final_range[toggle^use_inbandfec]!=0  && !encode_only
+         && !lost && !lost_prev
+         && dec_final_range != enc_final_range[toggle^use_inbandfec] ) {
+            fprintf (stderr, "Error: Range coder state mismatch "
+                             "between encoder and decoder "
+                             "in frame %ld: 0x%8lx vs 0x%8lx\n",
+                         (long)count,
+                         (unsigned long)enc_final_range[toggle^use_inbandfec],
+                         (unsigned long)dec_final_range);
+            fclose(fin);
+            fclose(fout);
+            return EXIT_FAILURE;
+        }
+
+        lost_prev = lost;
+        if( count >= use_inbandfec ) {
+            /* count bits */
+            bits += len[toggle]*8;
+            bits_max = ( len[toggle]*8 > bits_max ) ? len[toggle]*8 : bits_max;
+            bits2 += len[toggle]*len[toggle]*64;
+            if (!decode_only)
+            {
+                nrg = 0.0;
+                for ( k = 0; k < frame_size * channels; k++ ) {
+                    nrg += in[ k ] * (double)in[ k ];
+                }
+                nrg /= frame_size * channels;
+                if( nrg > 1e5 ) {
+                    bits_act += len[toggle]*8;
+                    count_act++;
+                }
+            }
+        }
+        count++;
+        toggle = (toggle + use_inbandfec) & 1;
+    }
+
+    /* Print out bitrate statistics */
+    if(decode_only)
+        frame_size = (int)(tot_samples / count);
+    count -= use_inbandfec;
+    fprintf (stderr, "average bitrate:             %7.3f kb/s\n",
+                     1e-3*bits*sampling_rate/tot_samples);
+    fprintf (stderr, "maximum bitrate:             %7.3f kb/s\n",
+                     1e-3*bits_max*sampling_rate/frame_size);
+    if (!decode_only)
+       fprintf (stderr, "active bitrate:              %7.3f kb/s\n",
+               1e-3*bits_act*sampling_rate/(1e-15+frame_size*(double)count_act));
+    fprintf (stderr, "bitrate standard deviation:  %7.3f kb/s\n",
+            1e-3*sqrt(bits2/count - bits*bits/(count*(double)count))*sampling_rate/frame_size);
+    silk_TimerSave("opus_timing.txt");
+    opus_encoder_destroy(enc);
+    opus_decoder_destroy(dec);
+    free(data[0]);
+    if (use_inbandfec)
+        free(data[1]);
+    fclose(fin);
+    fclose(fout);
+    free(in);
+    free(out);
+    free(fbytes);
+    return EXIT_SUCCESS;
+}
diff --git a/opus/src/opus_encoder.c b/opus/src/opus_encoder.c
new file mode 100644 (file)
index 0000000..474e6c2
--- /dev/null
@@ -0,0 +1,2731 @@
+/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
+   Written by Jean-Marc Valin and Koen Vos */
+/*
+   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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdarg.h>
+#include "celt.h"
+#include "entenc.h"
+#include "modes.h"
+#include "API.h"
+#include "stack_alloc.h"
+#include "float_cast.h"
+#include "opus.h"
+#include "arch.h"
+#include "pitch.h"
+#include "opus_private.h"
+#include "os_support.h"
+#include "cpu_support.h"
+#include "analysis.h"
+#include "mathops.h"
+#include "tuning_parameters.h"
+#ifdef FIXED_POINT
+#include "fixed/structs_FIX.h"
+#else
+#include "float/structs_FLP.h"
+#endif
+
+#define MAX_ENCODER_BUFFER 480
+
+#ifndef DISABLE_FLOAT_API
+#define PSEUDO_SNR_THRESHOLD 316.23f    /* 10^(25/10) */
+#endif
+
+typedef struct {
+   opus_val32 XX, XY, YY;
+   opus_val16 smoothed_width;
+   opus_val16 max_follower;
+} StereoWidthState;
+
+struct OpusEncoder {
+    int          celt_enc_offset;
+    int          silk_enc_offset;
+    silk_EncControlStruct silk_mode;
+    int          application;
+    int          channels;
+    int          delay_compensation;
+    int          force_channels;
+    int          signal_type;
+    int          user_bandwidth;
+    int          max_bandwidth;
+    int          user_forced_mode;
+    int          voice_ratio;
+    opus_int32   Fs;
+    int          use_vbr;
+    int          vbr_constraint;
+    int          variable_duration;
+    opus_int32   bitrate_bps;
+    opus_int32   user_bitrate_bps;
+    int          lsb_depth;
+    int          encoder_buffer;
+    int          lfe;
+    int          arch;
+    int          use_dtx;                 /* general DTX for both SILK and CELT */
+#ifndef DISABLE_FLOAT_API
+    TonalityAnalysisState analysis;
+#endif
+
+#define OPUS_ENCODER_RESET_START stream_channels
+    int          stream_channels;
+    opus_int16   hybrid_stereo_width_Q14;
+    opus_int32   variable_HP_smth2_Q15;
+    opus_val16   prev_HB_gain;
+    opus_val32   hp_mem[4];
+    int          mode;
+    int          prev_mode;
+    int          prev_channels;
+    int          prev_framesize;
+    int          bandwidth;
+    /* Bandwidth determined automatically from the rate (before any other adjustment) */
+    int          auto_bandwidth;
+    int          silk_bw_switch;
+    /* Sampling rate (at the API level) */
+    int          first;
+    opus_val16 * energy_masking;
+    StereoWidthState width_mem;
+    opus_val16   delay_buffer[MAX_ENCODER_BUFFER*2];
+#ifndef DISABLE_FLOAT_API
+    int          detected_bandwidth;
+    int          nb_no_activity_frames;
+    opus_val32   peak_signal_energy;
+#endif
+    int          nonfinal_frame; /* current frame is not the final in a packet */
+    opus_uint32  rangeFinal;
+};
+
+/* Transition tables for the voice and music. First column is the
+   middle (memoriless) threshold. The second column is the hysteresis
+   (difference with the middle) */
+static const opus_int32 mono_voice_bandwidth_thresholds[8] = {
+        10000, 1000, /* NB<->MB */
+        11000, 1000, /* MB<->WB */
+        13500, 1000, /* WB<->SWB */
+        14000, 2000, /* SWB<->FB */
+};
+static const opus_int32 mono_music_bandwidth_thresholds[8] = {
+        10000, 1000, /* NB<->MB */
+        11000, 1000, /* MB<->WB */
+        13500, 1000, /* WB<->SWB */
+        14000, 2000, /* SWB<->FB */
+};
+static const opus_int32 stereo_voice_bandwidth_thresholds[8] = {
+        10000, 1000, /* NB<->MB */
+        11000, 1000, /* MB<->WB */
+        13500, 1000, /* WB<->SWB */
+        14000, 2000, /* SWB<->FB */
+};
+static const opus_int32 stereo_music_bandwidth_thresholds[8] = {
+        10000, 1000, /* NB<->MB */
+        11000, 1000, /* MB<->WB */
+        13500, 1000, /* WB<->SWB */
+        14000, 2000, /* SWB<->FB */
+};
+/* Threshold bit-rates for switching between mono and stereo */
+static const opus_int32 stereo_voice_threshold = 24000;
+static const opus_int32 stereo_music_threshold = 24000;
+
+/* Threshold bit-rate for switching between SILK/hybrid and CELT-only */
+static const opus_int32 mode_thresholds[2][2] = {
+      /* voice */ /* music */
+      {  64000,      16000}, /* mono */
+      {  36000,      16000}, /* stereo */
+};
+
+static const opus_int32 fec_thresholds[] = {
+        12000, 1000, /* NB */
+        14000, 1000, /* MB */
+        16000, 1000, /* WB */
+        20000, 1000, /* SWB */
+        22000, 1000, /* FB */
+};
+
+int opus_encoder_get_size(int channels)
+{
+    int silkEncSizeBytes, celtEncSizeBytes;
+    int ret;
+    if (channels<1 || channels > 2)
+        return 0;
+    ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
+    if (ret)
+        return 0;
+    silkEncSizeBytes = align(silkEncSizeBytes);
+    celtEncSizeBytes = celt_encoder_get_size(channels);
+    return align(sizeof(OpusEncoder))+silkEncSizeBytes+celtEncSizeBytes;
+}
+
+int opus_encoder_init(OpusEncoder* st, opus_int32 Fs, int channels, int application)
+{
+    void *silk_enc;
+    CELTEncoder *celt_enc;
+    int err;
+    int ret, silkEncSizeBytes;
+
+   if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
+        (application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
+        && application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
+        return OPUS_BAD_ARG;
+
+    OPUS_CLEAR((char*)st, opus_encoder_get_size(channels));
+    /* Create SILK encoder */
+    ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
+    if (ret)
+        return OPUS_BAD_ARG;
+    silkEncSizeBytes = align(silkEncSizeBytes);
+    st->silk_enc_offset = align(sizeof(OpusEncoder));
+    st->celt_enc_offset = st->silk_enc_offset+silkEncSizeBytes;
+    silk_enc = (char*)st+st->silk_enc_offset;
+    celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
+
+    st->stream_channels = st->channels = channels;
+
+    st->Fs = Fs;
+
+    st->arch = opus_select_arch();
+
+    ret = silk_InitEncoder( silk_enc, st->arch, &st->silk_mode );
+    if(ret)return OPUS_INTERNAL_ERROR;
+
+    /* default SILK parameters */
+    st->silk_mode.nChannelsAPI              = channels;
+    st->silk_mode.nChannelsInternal         = channels;
+    st->silk_mode.API_sampleRate            = st->Fs;
+    st->silk_mode.maxInternalSampleRate     = 16000;
+    st->silk_mode.minInternalSampleRate     = 8000;
+    st->silk_mode.desiredInternalSampleRate = 16000;
+    st->silk_mode.payloadSize_ms            = 20;
+    st->silk_mode.bitRate                   = 25000;
+    st->silk_mode.packetLossPercentage      = 0;
+    st->silk_mode.complexity                = 9;
+    st->silk_mode.useInBandFEC              = 0;
+    st->silk_mode.useDTX                    = 0;
+    st->silk_mode.useCBR                    = 0;
+    st->silk_mode.reducedDependency         = 0;
+
+    /* Create CELT encoder */
+    /* Initialize CELT encoder */
+    err = celt_encoder_init(celt_enc, Fs, channels, st->arch);
+    if(err!=OPUS_OK)return OPUS_INTERNAL_ERROR;
+
+    celt_encoder_ctl(celt_enc, CELT_SET_SIGNALLING(0));
+    celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(st->silk_mode.complexity));
+
+    st->use_vbr = 1;
+    /* Makes constrained VBR the default (safer for real-time use) */
+    st->vbr_constraint = 1;
+    st->user_bitrate_bps = OPUS_AUTO;
+    st->bitrate_bps = 3000+Fs*channels;
+    st->application = application;
+    st->signal_type = OPUS_AUTO;
+    st->user_bandwidth = OPUS_AUTO;
+    st->max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
+    st->force_channels = OPUS_AUTO;
+    st->user_forced_mode = OPUS_AUTO;
+    st->voice_ratio = -1;
+    st->encoder_buffer = st->Fs/100;
+    st->lsb_depth = 24;
+    st->variable_duration = OPUS_FRAMESIZE_ARG;
+
+    /* Delay compensation of 4 ms (2.5 ms for SILK's extra look-ahead
+       + 1.5 ms for SILK resamplers and stereo prediction) */
+    st->delay_compensation = st->Fs/250;
+
+    st->hybrid_stereo_width_Q14 = 1 << 14;
+    st->prev_HB_gain = Q15ONE;
+    st->variable_HP_smth2_Q15 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
+    st->first = 1;
+    st->mode = MODE_HYBRID;
+    st->bandwidth = OPUS_BANDWIDTH_FULLBAND;
+
+#ifndef DISABLE_FLOAT_API
+    tonality_analysis_init(&st->analysis, st->Fs);
+    st->analysis.application = st->application;
+#endif
+
+    return OPUS_OK;
+}
+
+static unsigned char gen_toc(int mode, int framerate, int bandwidth, int channels)
+{
+   int period;
+   unsigned char toc;
+   period = 0;
+   while (framerate < 400)
+   {
+       framerate <<= 1;
+       period++;
+   }
+   if (mode == MODE_SILK_ONLY)
+   {
+       toc = (bandwidth-OPUS_BANDWIDTH_NARROWBAND)<<5;
+       toc |= (period-2)<<3;
+   } else if (mode == MODE_CELT_ONLY)
+   {
+       int tmp = bandwidth-OPUS_BANDWIDTH_MEDIUMBAND;
+       if (tmp < 0)
+           tmp = 0;
+       toc = 0x80;
+       toc |= tmp << 5;
+       toc |= period<<3;
+   } else /* Hybrid */
+   {
+       toc = 0x60;
+       toc |= (bandwidth-OPUS_BANDWIDTH_SUPERWIDEBAND)<<4;
+       toc |= (period-2)<<3;
+   }
+   toc |= (channels==2)<<2;
+   return toc;
+}
+
+#ifndef FIXED_POINT
+static void silk_biquad_float(
+    const opus_val16      *in,            /* I:    Input signal                   */
+    const opus_int32      *B_Q28,         /* I:    MA coefficients [3]            */
+    const opus_int32      *A_Q28,         /* I:    AR coefficients [2]            */
+    opus_val32            *S,             /* I/O:  State vector [2]               */
+    opus_val16            *out,           /* O:    Output signal                  */
+    const opus_int32      len,            /* I:    Signal length (must be even)   */
+    int stride
+)
+{
+    /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
+    opus_int   k;
+    opus_val32 vout;
+    opus_val32 inval;
+    opus_val32 A[2], B[3];
+
+    A[0] = (opus_val32)(A_Q28[0] * (1.f/((opus_int32)1<<28)));
+    A[1] = (opus_val32)(A_Q28[1] * (1.f/((opus_int32)1<<28)));
+    B[0] = (opus_val32)(B_Q28[0] * (1.f/((opus_int32)1<<28)));
+    B[1] = (opus_val32)(B_Q28[1] * (1.f/((opus_int32)1<<28)));
+    B[2] = (opus_val32)(B_Q28[2] * (1.f/((opus_int32)1<<28)));
+
+    /* Negate A_Q28 values and split in two parts */
+
+    for( k = 0; k < len; k++ ) {
+        /* S[ 0 ], S[ 1 ]: Q12 */
+        inval = in[ k*stride ];
+        vout = S[ 0 ] + B[0]*inval;
+
+        S[ 0 ] = S[1] - vout*A[0] + B[1]*inval;
+
+        S[ 1 ] = - vout*A[1] + B[2]*inval + VERY_SMALL;
+
+        /* Scale back to Q0 and saturate */
+        out[ k*stride ] = vout;
+    }
+}
+#endif
+
+static void hp_cutoff(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs, int arch)
+{
+   opus_int32 B_Q28[ 3 ], A_Q28[ 2 ];
+   opus_int32 Fc_Q19, r_Q28, r_Q22;
+   (void)arch;
+
+   silk_assert( cutoff_Hz <= silk_int32_MAX / SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ) );
+   Fc_Q19 = silk_DIV32_16( silk_SMULBB( SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ), cutoff_Hz ), Fs/1000 );
+   silk_assert( Fc_Q19 > 0 && Fc_Q19 < 32768 );
+
+   r_Q28 = SILK_FIX_CONST( 1.0, 28 ) - silk_MUL( SILK_FIX_CONST( 0.92, 9 ), Fc_Q19 );
+
+   /* b = r * [ 1; -2; 1 ]; */
+   /* a = [ 1; -2 * r * ( 1 - 0.5 * Fc^2 ); r^2 ]; */
+   B_Q28[ 0 ] = r_Q28;
+   B_Q28[ 1 ] = silk_LSHIFT( -r_Q28, 1 );
+   B_Q28[ 2 ] = r_Q28;
+
+   /* -r * ( 2 - Fc * Fc ); */
+   r_Q22  = silk_RSHIFT( r_Q28, 6 );
+   A_Q28[ 0 ] = silk_SMULWW( r_Q22, silk_SMULWW( Fc_Q19, Fc_Q19 ) - SILK_FIX_CONST( 2.0,  22 ) );
+   A_Q28[ 1 ] = silk_SMULWW( r_Q22, r_Q22 );
+
+#ifdef FIXED_POINT
+   if( channels == 1 ) {
+      silk_biquad_alt_stride1( in, B_Q28, A_Q28, hp_mem, out, len );
+   } else {
+      silk_biquad_alt_stride2( in, B_Q28, A_Q28, hp_mem, out, len, arch );
+   }
+#else
+   silk_biquad_float( in, B_Q28, A_Q28, hp_mem, out, len, channels );
+   if( channels == 2 ) {
+       silk_biquad_float( in+1, B_Q28, A_Q28, hp_mem+2, out+1, len, channels );
+   }
+#endif
+}
+
+#ifdef FIXED_POINT
+static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
+{
+   int c, i;
+   int shift;
+
+   /* Approximates -round(log2(4.*cutoff_Hz/Fs)) */
+   shift=celt_ilog2(Fs/(cutoff_Hz*3));
+   for (c=0;c<channels;c++)
+   {
+      for (i=0;i<len;i++)
+      {
+         opus_val32 x, tmp, y;
+         x = SHL32(EXTEND32(in[channels*i+c]), 14);
+         /* First stage */
+         tmp = x-hp_mem[2*c];
+         hp_mem[2*c] = hp_mem[2*c] + PSHR32(x - hp_mem[2*c], shift);
+         /* Second stage */
+         y = tmp - hp_mem[2*c+1];
+         hp_mem[2*c+1] = hp_mem[2*c+1] + PSHR32(tmp - hp_mem[2*c+1], shift);
+         out[channels*i+c] = EXTRACT16(SATURATE(PSHR32(y, 14), 32767));
+      }
+   }
+}
+
+#else
+static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
+{
+   int i;
+   float coef, coef2;
+   coef = 4.0f*cutoff_Hz/Fs;
+   coef2 = 1-coef;
+   if (channels==2)
+   {
+      float m0, m1, m2, m3;
+      m0 = hp_mem[0];
+      m1 = hp_mem[1];
+      m2 = hp_mem[2];
+      m3 = hp_mem[3];
+      for (i=0;i<len;i++)
+      {
+         opus_val32 x0, x1, tmp0, tmp1, out0, out1;
+         x0 = in[2*i+0];
+         x1 = in[2*i+1];
+         /* First stage */
+         tmp0 = x0-m0;
+         tmp1 = x1-m2;
+         m0 = coef*x0 + VERY_SMALL + coef2*m0;
+         m2 = coef*x1 + VERY_SMALL + coef2*m2;
+         /* Second stage */
+         out0 = tmp0 - m1;
+         out1 = tmp1 - m3;
+         m1 = coef*tmp0 + VERY_SMALL + coef2*m1;
+         m3 = coef*tmp1 + VERY_SMALL + coef2*m3;
+         out[2*i+0] = out0;
+         out[2*i+1] = out1;
+      }
+      hp_mem[0] = m0;
+      hp_mem[1] = m1;
+      hp_mem[2] = m2;
+      hp_mem[3] = m3;
+   } else {
+      float m0, m1;
+      m0 = hp_mem[0];
+      m1 = hp_mem[1];
+      for (i=0;i<len;i++)
+      {
+         opus_val32 x, tmp, y;
+         x = in[i];
+         /* First stage */
+         tmp = x-m0;
+         m0 = coef*x + VERY_SMALL + coef2*m0;
+         /* Second stage */
+         y = tmp - m1;
+         m1 = coef*tmp + VERY_SMALL + coef2*m1;
+         out[i] = y;
+      }
+      hp_mem[0] = m0;
+      hp_mem[1] = m1;
+   }
+}
+#endif
+
+static void stereo_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
+        int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
+{
+    int i;
+    int overlap;
+    int inc;
+    inc = 48000/Fs;
+    overlap=overlap48/inc;
+    g1 = Q15ONE-g1;
+    g2 = Q15ONE-g2;
+    for (i=0;i<overlap;i++)
+    {
+       opus_val32 diff;
+       opus_val16 g, w;
+       w = MULT16_16_Q15(window[i*inc], window[i*inc]);
+       g = SHR32(MAC16_16(MULT16_16(w,g2),
+             Q15ONE-w, g1), 15);
+       diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
+       diff = MULT16_16_Q15(g, diff);
+       out[i*channels] = out[i*channels] - diff;
+       out[i*channels+1] = out[i*channels+1] + diff;
+    }
+    for (;i<frame_size;i++)
+    {
+       opus_val32 diff;
+       diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
+       diff = MULT16_16_Q15(g2, diff);
+       out[i*channels] = out[i*channels] - diff;
+       out[i*channels+1] = out[i*channels+1] + diff;
+    }
+}
+
+static void gain_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
+        int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
+{
+    int i;
+    int inc;
+    int overlap;
+    int c;
+    inc = 48000/Fs;
+    overlap=overlap48/inc;
+    if (channels==1)
+    {
+       for (i=0;i<overlap;i++)
+       {
+          opus_val16 g, w;
+          w = MULT16_16_Q15(window[i*inc], window[i*inc]);
+          g = SHR32(MAC16_16(MULT16_16(w,g2),
+                Q15ONE-w, g1), 15);
+          out[i] = MULT16_16_Q15(g, in[i]);
+       }
+    } else {
+       for (i=0;i<overlap;i++)
+       {
+          opus_val16 g, w;
+          w = MULT16_16_Q15(window[i*inc], window[i*inc]);
+          g = SHR32(MAC16_16(MULT16_16(w,g2),
+                Q15ONE-w, g1), 15);
+          out[i*2] = MULT16_16_Q15(g, in[i*2]);
+          out[i*2+1] = MULT16_16_Q15(g, in[i*2+1]);
+       }
+    }
+    c=0;do {
+       for (i=overlap;i<frame_size;i++)
+       {
+          out[i*channels+c] = MULT16_16_Q15(g2, in[i*channels+c]);
+       }
+    }
+    while (++c<channels);
+}
+
+OpusEncoder *opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
+{
+   int ret;
+   OpusEncoder *st;
+   if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
+       (application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
+       && application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   st = (OpusEncoder *)opus_alloc(opus_encoder_get_size(channels));
+   if (st == NULL)
+   {
+      if (error)
+         *error = OPUS_ALLOC_FAIL;
+      return NULL;
+   }
+   ret = opus_encoder_init(st, Fs, channels, application);
+   if (error)
+      *error = ret;
+   if (ret != OPUS_OK)
+   {
+      opus_free(st);
+      st = NULL;
+   }
+   return st;
+}
+
+static opus_int32 user_bitrate_to_bitrate(OpusEncoder *st, int frame_size, int max_data_bytes)
+{
+  if(!frame_size)frame_size=st->Fs/400;
+  if (st->user_bitrate_bps==OPUS_AUTO)
+    return 60*st->Fs/frame_size + st->Fs*st->channels;
+  else if (st->user_bitrate_bps==OPUS_BITRATE_MAX)
+    return max_data_bytes*8*st->Fs/frame_size;
+  else
+    return st->user_bitrate_bps;
+}
+
+#ifndef DISABLE_FLOAT_API
+#ifdef FIXED_POINT
+#define PCM2VAL(x) FLOAT2INT16(x)
+#else
+#define PCM2VAL(x) SCALEIN(x)
+#endif
+
+void downmix_float(const void *_x, opus_val32 *y, int subframe, int offset, int c1, int c2, int C)
+{
+   const float *x;
+   int j;
+
+   x = (const float *)_x;
+   for (j=0;j<subframe;j++)
+      y[j] = PCM2VAL(x[(j+offset)*C+c1]);
+   if (c2>-1)
+   {
+      for (j=0;j<subframe;j++)
+         y[j] += PCM2VAL(x[(j+offset)*C+c2]);
+   } else if (c2==-2)
+   {
+      int c;
+      for (c=1;c<C;c++)
+      {
+         for (j=0;j<subframe;j++)
+            y[j] += PCM2VAL(x[(j+offset)*C+c]);
+      }
+   }
+}
+#endif
+
+void downmix_int(const void *_x, opus_val32 *y, int subframe, int offset, int c1, int c2, int C)
+{
+   const opus_int16 *x;
+   int j;
+
+   x = (const opus_int16 *)_x;
+   for (j=0;j<subframe;j++)
+      y[j] = x[(j+offset)*C+c1];
+   if (c2>-1)
+   {
+      for (j=0;j<subframe;j++)
+         y[j] += x[(j+offset)*C+c2];
+   } else if (c2==-2)
+   {
+      int c;
+      for (c=1;c<C;c++)
+      {
+         for (j=0;j<subframe;j++)
+            y[j] += x[(j+offset)*C+c];
+      }
+   }
+}
+
+opus_int32 frame_size_select(opus_int32 frame_size, int variable_duration, opus_int32 Fs)
+{
+   int new_size;
+   if (frame_size<Fs/400)
+      return -1;
+   if (variable_duration == OPUS_FRAMESIZE_ARG)
+      new_size = frame_size;
+   else if (variable_duration >= OPUS_FRAMESIZE_2_5_MS && variable_duration <= OPUS_FRAMESIZE_120_MS)
+   {
+      if (variable_duration <= OPUS_FRAMESIZE_40_MS)
+         new_size = (Fs/400)<<(variable_duration-OPUS_FRAMESIZE_2_5_MS);
+      else
+         new_size = (variable_duration-OPUS_FRAMESIZE_2_5_MS-2)*Fs/50;
+   }
+   else
+      return -1;
+   if (new_size>frame_size)
+      return -1;
+   if (400*new_size!=Fs   && 200*new_size!=Fs   && 100*new_size!=Fs   &&
+        50*new_size!=Fs   &&  25*new_size!=Fs   &&  50*new_size!=3*Fs &&
+        50*new_size!=4*Fs &&  50*new_size!=5*Fs &&  50*new_size!=6*Fs)
+      return -1;
+   return new_size;
+}
+
+opus_val16 compute_stereo_width(const opus_val16 *pcm, int frame_size, opus_int32 Fs, StereoWidthState *mem)
+{
+   opus_val32 xx, xy, yy;
+   opus_val16 sqrt_xx, sqrt_yy;
+   opus_val16 qrrt_xx, qrrt_yy;
+   int frame_rate;
+   int i;
+   opus_val16 short_alpha;
+
+   frame_rate = Fs/frame_size;
+   short_alpha = Q15ONE - MULT16_16(25, Q15ONE)/IMAX(50,frame_rate);
+   xx=xy=yy=0;
+   /* Unroll by 4. The frame size is always a multiple of 4 *except* for
+      2.5 ms frames at 12 kHz. Since this setting is very rare (and very
+      stupid), we just discard the last two samples. */
+   for (i=0;i<frame_size-3;i+=4)
+   {
+      opus_val32 pxx=0;
+      opus_val32 pxy=0;
+      opus_val32 pyy=0;
+      opus_val16 x, y;
+      x = pcm[2*i];
+      y = pcm[2*i+1];
+      pxx = SHR32(MULT16_16(x,x),2);
+      pxy = SHR32(MULT16_16(x,y),2);
+      pyy = SHR32(MULT16_16(y,y),2);
+      x = pcm[2*i+2];
+      y = pcm[2*i+3];
+      pxx += SHR32(MULT16_16(x,x),2);
+      pxy += SHR32(MULT16_16(x,y),2);
+      pyy += SHR32(MULT16_16(y,y),2);
+      x = pcm[2*i+4];
+      y = pcm[2*i+5];
+      pxx += SHR32(MULT16_16(x,x),2);
+      pxy += SHR32(MULT16_16(x,y),2);
+      pyy += SHR32(MULT16_16(y,y),2);
+      x = pcm[2*i+6];
+      y = pcm[2*i+7];
+      pxx += SHR32(MULT16_16(x,x),2);
+      pxy += SHR32(MULT16_16(x,y),2);
+      pyy += SHR32(MULT16_16(y,y),2);
+
+      xx += SHR32(pxx, 10);
+      xy += SHR32(pxy, 10);
+      yy += SHR32(pyy, 10);
+   }
+   mem->XX += MULT16_32_Q15(short_alpha, xx-mem->XX);
+   mem->XY += MULT16_32_Q15(short_alpha, xy-mem->XY);
+   mem->YY += MULT16_32_Q15(short_alpha, yy-mem->YY);
+   mem->XX = MAX32(0, mem->XX);
+   mem->XY = MAX32(0, mem->XY);
+   mem->YY = MAX32(0, mem->YY);
+   if (MAX32(mem->XX, mem->YY)>QCONST16(8e-4f, 18))
+   {
+      opus_val16 corr;
+      opus_val16 ldiff;
+      opus_val16 width;
+      sqrt_xx = celt_sqrt(mem->XX);
+      sqrt_yy = celt_sqrt(mem->YY);
+      qrrt_xx = celt_sqrt(sqrt_xx);
+      qrrt_yy = celt_sqrt(sqrt_yy);
+      /* Inter-channel correlation */
+      mem->XY = MIN32(mem->XY, sqrt_xx*sqrt_yy);
+      corr = SHR32(frac_div32(mem->XY,EPSILON+MULT16_16(sqrt_xx,sqrt_yy)),16);
+      /* Approximate loudness difference */
+      ldiff = MULT16_16(Q15ONE, ABS16(qrrt_xx-qrrt_yy))/(EPSILON+qrrt_xx+qrrt_yy);
+      width = MULT16_16_Q15(celt_sqrt(QCONST32(1.f,30)-MULT16_16(corr,corr)), ldiff);
+      /* Smoothing over one second */
+      mem->smoothed_width += (width-mem->smoothed_width)/frame_rate;
+      /* Peak follower */
+      mem->max_follower = MAX16(mem->max_follower-QCONST16(.02f,15)/frame_rate, mem->smoothed_width);
+   }
+   /*printf("%f %f %f %f %f ", corr/(float)Q15ONE, ldiff/(float)Q15ONE, width/(float)Q15ONE, mem->smoothed_width/(float)Q15ONE, mem->max_follower/(float)Q15ONE);*/
+   return EXTRACT16(MIN32(Q15ONE, MULT16_16(20, mem->max_follower)));
+}
+
+static int decide_fec(int useInBandFEC, int PacketLoss_perc, int last_fec, int mode, int *bandwidth, opus_int32 rate)
+{
+   int orig_bandwidth;
+   if (!useInBandFEC || PacketLoss_perc == 0 || mode == MODE_CELT_ONLY)
+      return 0;
+   orig_bandwidth = *bandwidth;
+   for (;;)
+   {
+      opus_int32 hysteresis;
+      opus_int32 LBRR_rate_thres_bps;
+      /* Compute threshold for using FEC at the current bandwidth setting */
+      LBRR_rate_thres_bps = fec_thresholds[2*(*bandwidth - OPUS_BANDWIDTH_NARROWBAND)];
+      hysteresis = fec_thresholds[2*(*bandwidth - OPUS_BANDWIDTH_NARROWBAND) + 1];
+      if (last_fec == 1) LBRR_rate_thres_bps -= hysteresis;
+      if (last_fec == 0) LBRR_rate_thres_bps += hysteresis;
+      LBRR_rate_thres_bps = silk_SMULWB( silk_MUL( LBRR_rate_thres_bps,
+            125 - silk_min( PacketLoss_perc, 25 ) ), SILK_FIX_CONST( 0.01, 16 ) );
+      /* If loss <= 5%, we look at whether we have enough rate to enable FEC.
+         If loss > 5%, we decrease the bandwidth until we can enable FEC. */
+      if (rate > LBRR_rate_thres_bps)
+         return 1;
+      else if (PacketLoss_perc <= 5)
+         return 0;
+      else if (*bandwidth > OPUS_BANDWIDTH_NARROWBAND)
+         (*bandwidth)--;
+      else
+         break;
+   }
+   /* Couldn't find any bandwidth to enable FEC, keep original bandwidth. */
+   *bandwidth = orig_bandwidth;
+   return 0;
+}
+
+static int compute_silk_rate_for_hybrid(int rate, int bandwidth, int frame20ms, int vbr, int fec) {
+   int entry;
+   int i;
+   int N;
+   int silk_rate;
+   static int rate_table[][5] = {
+  /*  |total| |-------- SILK------------|
+              |-- No FEC -| |--- FEC ---|
+               10ms   20ms   10ms   20ms */
+      {    0,     0,     0,     0,     0},
+      {12000, 10000, 10000, 11000, 11000},
+      {16000, 13500, 13500, 15000, 15000},
+      {20000, 16000, 16000, 18000, 18000},
+      {24000, 18000, 18000, 21000, 21000},
+      {32000, 22000, 22000, 28000, 28000},
+      {64000, 38000, 38000, 50000, 50000}
+   };
+   entry = 1 + frame20ms + 2*fec;
+   N = sizeof(rate_table)/sizeof(rate_table[0]);
+   for (i=1;i<N;i++)
+   {
+      if (rate_table[i][0] > rate) break;
+   }
+   if (i == N)
+   {
+      silk_rate = rate_table[i-1][entry];
+      /* For now, just give 50% of the extra bits to SILK. */
+      silk_rate += (rate-rate_table[i-1][0])/2;
+   } else {
+      opus_int32 lo, hi, x0, x1;
+      lo = rate_table[i-1][entry];
+      hi = rate_table[i][entry];
+      x0 = rate_table[i-1][0];
+      x1 = rate_table[i][0];
+      silk_rate = (lo*(x1-rate) + hi*(rate-x0))/(x1-x0);
+   }
+   if (!vbr)
+   {
+      /* Tiny boost to SILK for CBR. We should probably tune this better. */
+      silk_rate += 100;
+   }
+   if (bandwidth==OPUS_BANDWIDTH_SUPERWIDEBAND)
+      silk_rate += 300;
+   return silk_rate;
+}
+
+/* Returns the equivalent bitrate corresponding to 20 ms frames,
+   complexity 10 VBR operation. */
+static opus_int32 compute_equiv_rate(opus_int32 bitrate, int channels,
+      int frame_rate, int vbr, int mode, int complexity, int loss)
+{
+   opus_int32 equiv;
+   equiv = bitrate;
+   /* Take into account overhead from smaller frames. */
+   equiv -= (40*channels+20)*(frame_rate - 50);
+   /* CBR is about a 8% penalty for both SILK and CELT. */
+   if (!vbr)
+      equiv -= equiv/12;
+   /* Complexity makes about 10% difference (from 0 to 10) in general. */
+   equiv = equiv * (90+complexity)/100;
+   if (mode == MODE_SILK_ONLY || mode == MODE_HYBRID)
+   {
+      /* SILK complexity 0-1 uses the non-delayed-decision NSQ, which
+         costs about 20%. */
+      if (complexity<2)
+         equiv = equiv*4/5;
+      equiv -= equiv*loss/(6*loss + 10);
+   } else if (mode == MODE_CELT_ONLY) {
+      /* CELT complexity 0-4 doesn't have the pitch filter, which costs
+         about 10%. */
+      if (complexity<5)
+         equiv = equiv*9/10;
+   } else {
+      /* Mode not known yet */
+      /* Half the SILK loss*/
+      equiv -= equiv*loss/(12*loss + 20);
+   }
+   return equiv;
+}
+
+#ifndef DISABLE_FLOAT_API
+
+static int is_digital_silence(const opus_val16* pcm, int frame_size, int channels, int lsb_depth)
+{
+   int silence = 0;
+   opus_val32 sample_max = 0;
+#ifdef MLP_TRAINING
+   return 0;
+#endif
+   sample_max = celt_maxabs16(pcm, frame_size*channels);
+
+#ifdef FIXED_POINT
+   silence = (sample_max == 0);
+   (void)lsb_depth;
+#else
+   silence = (sample_max <= (opus_val16) 1 / (1 << lsb_depth));
+#endif
+
+   return silence;
+}
+
+#ifdef FIXED_POINT
+static opus_val32 compute_frame_energy(const opus_val16 *pcm, int frame_size, int channels, int arch)
+{
+   int i;
+   opus_val32 sample_max;
+   int max_shift;
+   int shift;
+   opus_val32 energy = 0;
+   int len = frame_size*channels;
+   (void)arch;
+   /* Max amplitude in the signal */
+   sample_max = celt_maxabs16(pcm, len);
+
+   /* Compute the right shift required in the MAC to avoid an overflow */
+   max_shift = celt_ilog2(len);
+   shift = IMAX(0, (celt_ilog2(sample_max) << 1) + max_shift - 28);
+
+   /* Compute the energy */
+   for (i=0; i<len; i++)
+      energy += SHR32(MULT16_16(pcm[i], pcm[i]), shift);
+
+   /* Normalize energy by the frame size and left-shift back to the original position */
+   energy /= len;
+   energy = SHL32(energy, shift);
+
+   return energy;
+}
+#else
+static opus_val32 compute_frame_energy(const opus_val16 *pcm, int frame_size, int channels, int arch)
+{
+   int len = frame_size*channels;
+   return celt_inner_prod(pcm, pcm, len, arch)/len;
+}
+#endif
+
+/* Decides if DTX should be turned on (=1) or off (=0) */
+static int decide_dtx_mode(float activity_probability,    /* probability that current frame contains speech/music */
+                           int *nb_no_activity_frames,    /* number of consecutive frames with no activity */
+                           opus_val32 peak_signal_energy, /* peak energy of desired signal detected so far */
+                           const opus_val16 *pcm,         /* input pcm signal */
+                           int frame_size,                /* frame size */
+                           int channels,
+                           int is_silence,                 /* only digital silence detected in this frame */
+                           int arch
+                          )
+{
+   int is_noise;
+   opus_val32 noise_energy;
+   int is_sufficiently_quiet;
+
+   if (!is_silence)
+   {
+      is_noise = activity_probability < DTX_ACTIVITY_THRESHOLD;
+      if (is_noise)
+      {
+         noise_energy = compute_frame_energy(pcm, frame_size, channels, arch);
+         is_sufficiently_quiet = peak_signal_energy >= (PSEUDO_SNR_THRESHOLD * noise_energy);
+      }
+   }
+
+   if (is_silence || (is_noise && is_sufficiently_quiet))
+   {
+      /* The number of consecutive DTX frames should be within the allowed bounds */
+      (*nb_no_activity_frames)++;
+
+      if (*nb_no_activity_frames > NB_SPEECH_FRAMES_BEFORE_DTX)
+      {
+         if (*nb_no_activity_frames <= (NB_SPEECH_FRAMES_BEFORE_DTX + MAX_CONSECUTIVE_DTX))
+            /* Valid frame for DTX! */
+            return 1;
+         else
+            (*nb_no_activity_frames) = NB_SPEECH_FRAMES_BEFORE_DTX;
+      }
+   } else
+      (*nb_no_activity_frames) = 0;
+
+   return 0;
+}
+
+#endif
+
+static opus_int32 encode_multiframe_packet(OpusEncoder *st,
+                                           const opus_val16 *pcm,
+                                           int nb_frames,
+                                           int frame_size,
+                                           unsigned char *data,
+                                           opus_int32 out_data_bytes,
+                                           int to_celt,
+                                           int lsb_depth,
+                                           int float_api)
+{
+   int i;
+   int ret = 0;
+   VARDECL(unsigned char, tmp_data);
+   int bak_mode, bak_bandwidth, bak_channels, bak_to_mono;
+   VARDECL(OpusRepacketizer, rp);
+   int max_header_bytes;
+   opus_int32 bytes_per_frame;
+   opus_int32 cbr_bytes;
+   opus_int32 repacketize_len;
+   int tmp_len;
+   ALLOC_STACK;
+
+   /* Worst cases:
+    * 2 frames: Code 2 with different compressed sizes
+    * >2 frames: Code 3 VBR */
+   max_header_bytes = nb_frames == 2 ? 3 : (2+(nb_frames-1)*2);
+
+   if (st->use_vbr || st->user_bitrate_bps==OPUS_BITRATE_MAX)
+      repacketize_len = out_data_bytes;
+   else {
+      cbr_bytes = 3*st->bitrate_bps/(3*8*st->Fs/(frame_size*nb_frames));
+      repacketize_len = IMIN(cbr_bytes, out_data_bytes);
+   }
+   bytes_per_frame = IMIN(1276, 1+(repacketize_len-max_header_bytes)/nb_frames);
+
+   ALLOC(tmp_data, nb_frames*bytes_per_frame, unsigned char);
+   ALLOC(rp, 1, OpusRepacketizer);
+   opus_repacketizer_init(rp);
+
+   bak_mode = st->user_forced_mode;
+   bak_bandwidth = st->user_bandwidth;
+   bak_channels = st->force_channels;
+
+   st->user_forced_mode = st->mode;
+   st->user_bandwidth = st->bandwidth;
+   st->force_channels = st->stream_channels;
+
+   bak_to_mono = st->silk_mode.toMono;
+   if (bak_to_mono)
+      st->force_channels = 1;
+   else
+      st->prev_channels = st->stream_channels;
+
+   for (i=0;i<nb_frames;i++)
+   {
+      st->silk_mode.toMono = 0;
+      st->nonfinal_frame = i<(nb_frames-1);
+
+      /* When switching from SILK/Hybrid to CELT, only ask for a switch at the last frame */
+      if (to_celt && i==nb_frames-1)
+         st->user_forced_mode = MODE_CELT_ONLY;
+
+      tmp_len = opus_encode_native(st, pcm+i*(st->channels*frame_size), frame_size,
+         tmp_data+i*bytes_per_frame, bytes_per_frame, lsb_depth, NULL, 0, 0, 0, 0,
+         NULL, float_api);
+
+      if (tmp_len<0)
+      {
+         RESTORE_STACK;
+         return OPUS_INTERNAL_ERROR;
+      }
+
+      ret = opus_repacketizer_cat(rp, tmp_data+i*bytes_per_frame, tmp_len);
+
+      if (ret<0)
+      {
+         RESTORE_STACK;
+         return OPUS_INTERNAL_ERROR;
+      }
+   }
+
+   ret = opus_repacketizer_out_range_impl(rp, 0, nb_frames, data, repacketize_len, 0, !st->use_vbr);
+
+   if (ret<0)
+   {
+      RESTORE_STACK;
+      return OPUS_INTERNAL_ERROR;
+   }
+
+   /* Discard configs that were forced locally for the purpose of repacketization */
+   st->user_forced_mode = bak_mode;
+   st->user_bandwidth = bak_bandwidth;
+   st->force_channels = bak_channels;
+   st->silk_mode.toMono = bak_to_mono;
+
+   RESTORE_STACK;
+   return ret;
+}
+
+static int compute_redundancy_bytes(opus_int32 max_data_bytes, opus_int32 bitrate_bps, int frame_rate, int channels)
+{
+   int redundancy_bytes_cap;
+   int redundancy_bytes;
+   opus_int32 redundancy_rate;
+   int base_bits;
+   opus_int32 available_bits;
+   base_bits = (40*channels+20);
+
+   /* Equivalent rate for 5 ms frames. */
+   redundancy_rate = bitrate_bps + base_bits*(200 - frame_rate);
+   /* For VBR, further increase the bitrate if we can afford it. It's pretty short
+      and we'll avoid artefacts. */
+   redundancy_rate = 3*redundancy_rate/2;
+   redundancy_bytes = redundancy_rate/1600;
+
+   /* Compute the max rate we can use given CBR or VBR with cap. */
+   available_bits = max_data_bytes*8 - 2*base_bits;
+   redundancy_bytes_cap = (available_bits*240/(240+48000/frame_rate) + base_bits)/8;
+   redundancy_bytes = IMIN(redundancy_bytes, redundancy_bytes_cap);
+   /* It we can't get enough bits for redundancy to be worth it, rely on the decoder PLC. */
+   if (redundancy_bytes > 4 + 8*channels)
+      redundancy_bytes = IMIN(257, redundancy_bytes);
+   else
+      redundancy_bytes = 0;
+   return redundancy_bytes;
+}
+
+opus_int32 opus_encode_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
+                unsigned char *data, opus_int32 out_data_bytes, int lsb_depth,
+                const void *analysis_pcm, opus_int32 analysis_size, int c1, int c2,
+                int analysis_channels, downmix_func downmix, int float_api)
+{
+    void *silk_enc;
+    CELTEncoder *celt_enc;
+    int i;
+    int ret=0;
+    opus_int32 nBytes;
+    ec_enc enc;
+    int bytes_target;
+    int prefill=0;
+    int start_band = 0;
+    int redundancy = 0;
+    int redundancy_bytes = 0; /* Number of bytes to use for redundancy frame */
+    int celt_to_silk = 0;
+    VARDECL(opus_val16, pcm_buf);
+    int nb_compr_bytes;
+    int to_celt = 0;
+    opus_uint32 redundant_rng = 0;
+    int cutoff_Hz, hp_freq_smth1;
+    int voice_est; /* Probability of voice in Q7 */
+    opus_int32 equiv_rate;
+    int delay_compensation;
+    int frame_rate;
+    opus_int32 max_rate; /* Max bitrate we're allowed to use */
+    int curr_bandwidth;
+    opus_val16 HB_gain;
+    opus_int32 max_data_bytes; /* Max number of bytes we're allowed to use */
+    int total_buffer;
+    opus_val16 stereo_width;
+    const CELTMode *celt_mode;
+#ifndef DISABLE_FLOAT_API
+    AnalysisInfo analysis_info;
+    int analysis_read_pos_bak=-1;
+    int analysis_read_subframe_bak=-1;
+    int is_silence = 0;
+#endif
+    VARDECL(opus_val16, tmp_prefill);
+
+    ALLOC_STACK;
+
+    max_data_bytes = IMIN(1276, out_data_bytes);
+
+    st->rangeFinal = 0;
+    if (frame_size <= 0 || max_data_bytes <= 0)
+    {
+       RESTORE_STACK;
+       return OPUS_BAD_ARG;
+    }
+
+    /* Cannot encode 100 ms in 1 byte */
+    if (max_data_bytes==1 && st->Fs==(frame_size*10))
+    {
+      RESTORE_STACK;
+      return OPUS_BUFFER_TOO_SMALL;
+    }
+
+    silk_enc = (char*)st+st->silk_enc_offset;
+    celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
+    if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+       delay_compensation = 0;
+    else
+       delay_compensation = st->delay_compensation;
+
+    lsb_depth = IMIN(lsb_depth, st->lsb_depth);
+
+    celt_encoder_ctl(celt_enc, CELT_GET_MODE(&celt_mode));
+#ifndef DISABLE_FLOAT_API
+    analysis_info.valid = 0;
+#ifdef FIXED_POINT
+    if (st->silk_mode.complexity >= 10 && st->Fs>=16000)
+#else
+    if (st->silk_mode.complexity >= 7 && st->Fs>=16000)
+#endif
+    {
+       if (is_digital_silence(pcm, frame_size, st->channels, lsb_depth))
+       {
+          is_silence = 1;
+       } else {
+          analysis_read_pos_bak = st->analysis.read_pos;
+          analysis_read_subframe_bak = st->analysis.read_subframe;
+          run_analysis(&st->analysis, celt_mode, analysis_pcm, analysis_size, frame_size,
+                c1, c2, analysis_channels, st->Fs,
+                lsb_depth, downmix, &analysis_info);
+       }
+
+       /* Track the peak signal energy */
+       if (!is_silence && analysis_info.activity_probability > DTX_ACTIVITY_THRESHOLD)
+          st->peak_signal_energy = MAX32(MULT16_32_Q15(QCONST16(0.999f, 15), st->peak_signal_energy),
+                compute_frame_energy(pcm, frame_size, st->channels, st->arch));
+    }
+#else
+    (void)analysis_pcm;
+    (void)analysis_size;
+    (void)c1;
+    (void)c2;
+    (void)analysis_channels;
+    (void)downmix;
+#endif
+
+#ifndef DISABLE_FLOAT_API
+    /* Reset voice_ratio if this frame is not silent or if analysis is disabled.
+     * Otherwise, preserve voice_ratio from the last non-silent frame */
+    if (!is_silence)
+      st->voice_ratio = -1;
+
+    st->detected_bandwidth = 0;
+    if (analysis_info.valid)
+    {
+       int analysis_bandwidth;
+       if (st->signal_type == OPUS_AUTO)
+          st->voice_ratio = (int)floor(.5+100*(1-analysis_info.music_prob));
+
+       analysis_bandwidth = analysis_info.bandwidth;
+       if (analysis_bandwidth<=12)
+          st->detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+       else if (analysis_bandwidth<=14)
+          st->detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+       else if (analysis_bandwidth<=16)
+          st->detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+       else if (analysis_bandwidth<=18)
+          st->detected_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
+       else
+          st->detected_bandwidth = OPUS_BANDWIDTH_FULLBAND;
+    }
+#else
+    st->voice_ratio = -1;
+#endif
+
+    if (st->channels==2 && st->force_channels!=1)
+       stereo_width = compute_stereo_width(pcm, frame_size, st->Fs, &st->width_mem);
+    else
+       stereo_width = 0;
+    total_buffer = delay_compensation;
+    st->bitrate_bps = user_bitrate_to_bitrate(st, frame_size, max_data_bytes);
+
+    frame_rate = st->Fs/frame_size;
+    if (!st->use_vbr)
+    {
+       int cbrBytes;
+       /* Multiply by 12 to make sure the division is exact. */
+       int frame_rate12 = 12*st->Fs/frame_size;
+       /* We need to make sure that "int" values always fit in 16 bits. */
+       cbrBytes = IMIN( (12*st->bitrate_bps/8 + frame_rate12/2)/frame_rate12, max_data_bytes);
+       st->bitrate_bps = cbrBytes*(opus_int32)frame_rate12*8/12;
+       /* Make sure we provide at least one byte to avoid failing. */
+       max_data_bytes = IMAX(1, cbrBytes);
+    }
+    if (max_data_bytes<3 || st->bitrate_bps < 3*frame_rate*8
+       || (frame_rate<50 && (max_data_bytes*frame_rate<300 || st->bitrate_bps < 2400)))
+    {
+       /*If the space is too low to do something useful, emit 'PLC' frames.*/
+       int tocmode = st->mode;
+       int bw = st->bandwidth == 0 ? OPUS_BANDWIDTH_NARROWBAND : st->bandwidth;
+       int packet_code = 0;
+       int num_multiframes = 0;
+
+       if (tocmode==0)
+          tocmode = MODE_SILK_ONLY;
+       if (frame_rate>100)
+          tocmode = MODE_CELT_ONLY;
+       /* 40 ms -> 2 x 20 ms if in CELT_ONLY or HYBRID mode */
+       if (frame_rate==25 && tocmode!=MODE_SILK_ONLY)
+       {
+          frame_rate = 50;
+          packet_code = 1;
+       }
+
+       /* >= 60 ms frames */
+       if (frame_rate<=16)
+       {
+          /* 1 x 60 ms, 2 x 40 ms, 2 x 60 ms */
+          if (out_data_bytes==1 || (tocmode==MODE_SILK_ONLY && frame_rate!=10))
+          {
+             tocmode = MODE_SILK_ONLY;
+
+             packet_code = frame_rate <= 12;
+             frame_rate = frame_rate == 12 ? 25 : 16;
+          }
+          else
+          {
+             num_multiframes = 50/frame_rate;
+             frame_rate = 50;
+             packet_code = 3;
+          }
+       }
+
+       if(tocmode==MODE_SILK_ONLY&&bw>OPUS_BANDWIDTH_WIDEBAND)
+          bw=OPUS_BANDWIDTH_WIDEBAND;
+       else if (tocmode==MODE_CELT_ONLY&&bw==OPUS_BANDWIDTH_MEDIUMBAND)
+          bw=OPUS_BANDWIDTH_NARROWBAND;
+       else if (tocmode==MODE_HYBRID&&bw<=OPUS_BANDWIDTH_SUPERWIDEBAND)
+          bw=OPUS_BANDWIDTH_SUPERWIDEBAND;
+
+       data[0] = gen_toc(tocmode, frame_rate, bw, st->stream_channels);
+       data[0] |= packet_code;
+
+       ret = packet_code <= 1 ? 1 : 2;
+
+       max_data_bytes = IMAX(max_data_bytes, ret);
+
+       if (packet_code==3)
+          data[1] = num_multiframes;
+
+       if (!st->use_vbr)
+       {
+          ret = opus_packet_pad(data, ret, max_data_bytes);
+          if (ret == OPUS_OK)
+             ret = max_data_bytes;
+          else
+             ret = OPUS_INTERNAL_ERROR;
+       }
+       RESTORE_STACK;
+       return ret;
+    }
+    max_rate = frame_rate*max_data_bytes*8;
+
+    /* Equivalent 20-ms rate for mode/channel/bandwidth decisions */
+    equiv_rate = compute_equiv_rate(st->bitrate_bps, st->channels, st->Fs/frame_size,
+          st->use_vbr, 0, st->silk_mode.complexity, st->silk_mode.packetLossPercentage);
+
+    if (st->signal_type == OPUS_SIGNAL_VOICE)
+       voice_est = 127;
+    else if (st->signal_type == OPUS_SIGNAL_MUSIC)
+       voice_est = 0;
+    else if (st->voice_ratio >= 0)
+    {
+       voice_est = st->voice_ratio*327>>8;
+       /* For AUDIO, never be more than 90% confident of having speech */
+       if (st->application == OPUS_APPLICATION_AUDIO)
+          voice_est = IMIN(voice_est, 115);
+    } else if (st->application == OPUS_APPLICATION_VOIP)
+       voice_est = 115;
+    else
+       voice_est = 48;
+
+    if (st->force_channels!=OPUS_AUTO && st->channels == 2)
+    {
+        st->stream_channels = st->force_channels;
+    } else {
+#ifdef FUZZING
+       /* Random mono/stereo decision */
+       if (st->channels == 2 && (rand()&0x1F)==0)
+          st->stream_channels = 3-st->stream_channels;
+#else
+       /* Rate-dependent mono-stereo decision */
+       if (st->channels == 2)
+       {
+          opus_int32 stereo_threshold;
+          stereo_threshold = stereo_music_threshold + ((voice_est*voice_est*(stereo_voice_threshold-stereo_music_threshold))>>14);
+          if (st->stream_channels == 2)
+             stereo_threshold -= 1000;
+          else
+             stereo_threshold += 1000;
+          st->stream_channels = (equiv_rate > stereo_threshold) ? 2 : 1;
+       } else {
+          st->stream_channels = st->channels;
+       }
+#endif
+    }
+    /* Update equivalent rate for channels decision. */
+    equiv_rate = compute_equiv_rate(st->bitrate_bps, st->stream_channels, st->Fs/frame_size,
+          st->use_vbr, 0, st->silk_mode.complexity, st->silk_mode.packetLossPercentage);
+
+    /* Mode selection depending on application and signal type */
+    if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+    {
+       st->mode = MODE_CELT_ONLY;
+    } else if (st->user_forced_mode == OPUS_AUTO)
+    {
+#ifdef FUZZING
+       /* Random mode switching */
+       if ((rand()&0xF)==0)
+       {
+          if ((rand()&0x1)==0)
+             st->mode = MODE_CELT_ONLY;
+          else
+             st->mode = MODE_SILK_ONLY;
+       } else {
+          if (st->prev_mode==MODE_CELT_ONLY)
+             st->mode = MODE_CELT_ONLY;
+          else
+             st->mode = MODE_SILK_ONLY;
+       }
+#else
+       opus_int32 mode_voice, mode_music;
+       opus_int32 threshold;
+
+       /* Interpolate based on stereo width */
+       mode_voice = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[0][0])
+             + MULT16_32_Q15(stereo_width,mode_thresholds[1][0]));
+       mode_music = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[1][1])
+             + MULT16_32_Q15(stereo_width,mode_thresholds[1][1]));
+       /* Interpolate based on speech/music probability */
+       threshold = mode_music + ((voice_est*voice_est*(mode_voice-mode_music))>>14);
+       /* Bias towards SILK for VoIP because of some useful features */
+       if (st->application == OPUS_APPLICATION_VOIP)
+          threshold += 8000;
+
+       /*printf("%f %d\n", stereo_width/(float)Q15ONE, threshold);*/
+       /* Hysteresis */
+       if (st->prev_mode == MODE_CELT_ONLY)
+           threshold -= 4000;
+       else if (st->prev_mode>0)
+           threshold += 4000;
+
+       st->mode = (equiv_rate >= threshold) ? MODE_CELT_ONLY: MODE_SILK_ONLY;
+
+       /* When FEC is enabled and there's enough packet loss, use SILK */
+       if (st->silk_mode.useInBandFEC && st->silk_mode.packetLossPercentage > (128-voice_est)>>4)
+          st->mode = MODE_SILK_ONLY;
+       /* When encoding voice and DTX is enabled but the generalized DTX cannot be used,
+          because of complexity and sampling frequency settings, switch to SILK DTX and
+          set the encoder to SILK mode */
+#ifndef DISABLE_FLOAT_API
+       st->silk_mode.useDTX = st->use_dtx && !(analysis_info.valid || is_silence);
+#else
+       st->silk_mode.useDTX = st->use_dtx;
+#endif
+       if (st->silk_mode.useDTX && voice_est > 100)
+          st->mode = MODE_SILK_ONLY;
+#endif
+
+       /* If max_data_bytes represents less than 6 kb/s, switch to CELT-only mode */
+       if (max_data_bytes < (frame_rate > 50 ? 9000 : 6000)*frame_size / (st->Fs * 8))
+          st->mode = MODE_CELT_ONLY;
+    } else {
+       st->mode = st->user_forced_mode;
+    }
+
+    /* Override the chosen mode to make sure we meet the requested frame size */
+    if (st->mode != MODE_CELT_ONLY && frame_size < st->Fs/100)
+       st->mode = MODE_CELT_ONLY;
+    if (st->lfe)
+       st->mode = MODE_CELT_ONLY;
+
+    if (st->prev_mode > 0 &&
+        ((st->mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) ||
+    (st->mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)))
+    {
+        redundancy = 1;
+        celt_to_silk = (st->mode != MODE_CELT_ONLY);
+        if (!celt_to_silk)
+        {
+            /* Switch to SILK/hybrid if frame size is 10 ms or more*/
+            if (frame_size >= st->Fs/100)
+            {
+                st->mode = st->prev_mode;
+                to_celt = 1;
+            } else {
+                redundancy=0;
+            }
+        }
+    }
+
+    /* When encoding multiframes, we can ask for a switch to CELT only in the last frame. This switch
+     * is processed above as the requested mode shouldn't interrupt stereo->mono transition. */
+    if (st->stream_channels == 1 && st->prev_channels ==2 && st->silk_mode.toMono==0
+          && st->mode != MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)
+    {
+       /* Delay stereo->mono transition by two frames so that SILK can do a smooth downmix */
+       st->silk_mode.toMono = 1;
+       st->stream_channels = 2;
+    } else {
+       st->silk_mode.toMono = 0;
+    }
+
+    /* Update equivalent rate with mode decision. */
+    equiv_rate = compute_equiv_rate(st->bitrate_bps, st->stream_channels, st->Fs/frame_size,
+          st->use_vbr, st->mode, st->silk_mode.complexity, st->silk_mode.packetLossPercentage);
+
+    if (st->mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY)
+    {
+        silk_EncControlStruct dummy;
+        silk_InitEncoder( silk_enc, st->arch, &dummy);
+        prefill=1;
+    }
+
+    /* Automatic (rate-dependent) bandwidth selection */
+    if (st->mode == MODE_CELT_ONLY || st->first || st->silk_mode.allowBandwidthSwitch)
+    {
+        const opus_int32 *voice_bandwidth_thresholds, *music_bandwidth_thresholds;
+        opus_int32 bandwidth_thresholds[8];
+        int bandwidth = OPUS_BANDWIDTH_FULLBAND;
+
+        if (st->channels==2 && st->force_channels!=1)
+        {
+           voice_bandwidth_thresholds = stereo_voice_bandwidth_thresholds;
+           music_bandwidth_thresholds = stereo_music_bandwidth_thresholds;
+        } else {
+           voice_bandwidth_thresholds = mono_voice_bandwidth_thresholds;
+           music_bandwidth_thresholds = mono_music_bandwidth_thresholds;
+        }
+        /* Interpolate bandwidth thresholds depending on voice estimation */
+        for (i=0;i<8;i++)
+        {
+           bandwidth_thresholds[i] = music_bandwidth_thresholds[i]
+                    + ((voice_est*voice_est*(voice_bandwidth_thresholds[i]-music_bandwidth_thresholds[i]))>>14);
+        }
+        do {
+            int threshold, hysteresis;
+            threshold = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)];
+            hysteresis = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)+1];
+            if (!st->first)
+            {
+                if (st->auto_bandwidth >= bandwidth)
+                    threshold -= hysteresis;
+                else
+                    threshold += hysteresis;
+            }
+            if (equiv_rate >= threshold)
+                break;
+        } while (--bandwidth>OPUS_BANDWIDTH_NARROWBAND);
+        st->bandwidth = st->auto_bandwidth = bandwidth;
+        /* Prevents any transition to SWB/FB until the SILK layer has fully
+           switched to WB mode and turned the variable LP filter off */
+        if (!st->first && st->mode != MODE_CELT_ONLY && !st->silk_mode.inWBmodeWithoutVariableLP && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
+            st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+    }
+
+    if (st->bandwidth>st->max_bandwidth)
+       st->bandwidth = st->max_bandwidth;
+
+    if (st->user_bandwidth != OPUS_AUTO)
+        st->bandwidth = st->user_bandwidth;
+
+    /* This prevents us from using hybrid at unsafe CBR/max rates */
+    if (st->mode != MODE_CELT_ONLY && max_rate < 15000)
+    {
+       st->bandwidth = IMIN(st->bandwidth, OPUS_BANDWIDTH_WIDEBAND);
+    }
+
+    /* Prevents Opus from wasting bits on frequencies that are above
+       the Nyquist rate of the input signal */
+    if (st->Fs <= 24000 && st->bandwidth > OPUS_BANDWIDTH_SUPERWIDEBAND)
+        st->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
+    if (st->Fs <= 16000 && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
+        st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+    if (st->Fs <= 12000 && st->bandwidth > OPUS_BANDWIDTH_MEDIUMBAND)
+        st->bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+    if (st->Fs <= 8000 && st->bandwidth > OPUS_BANDWIDTH_NARROWBAND)
+        st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+#ifndef DISABLE_FLOAT_API
+    /* Use detected bandwidth to reduce the encoded bandwidth. */
+    if (st->detected_bandwidth && st->user_bandwidth == OPUS_AUTO)
+    {
+       int min_detected_bandwidth;
+       /* Makes bandwidth detection more conservative just in case the detector
+          gets it wrong when we could have coded a high bandwidth transparently.
+          When operating in SILK/hybrid mode, we don't go below wideband to avoid
+          more complicated switches that require redundancy. */
+       if (equiv_rate <= 18000*st->stream_channels && st->mode == MODE_CELT_ONLY)
+          min_detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+       else if (equiv_rate <= 24000*st->stream_channels && st->mode == MODE_CELT_ONLY)
+          min_detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+       else if (equiv_rate <= 30000*st->stream_channels)
+          min_detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+       else if (equiv_rate <= 44000*st->stream_channels)
+          min_detected_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
+       else
+          min_detected_bandwidth = OPUS_BANDWIDTH_FULLBAND;
+
+       st->detected_bandwidth = IMAX(st->detected_bandwidth, min_detected_bandwidth);
+       st->bandwidth = IMIN(st->bandwidth, st->detected_bandwidth);
+    }
+#endif
+    st->silk_mode.LBRR_coded = decide_fec(st->silk_mode.useInBandFEC, st->silk_mode.packetLossPercentage,
+          st->silk_mode.LBRR_coded, st->mode, &st->bandwidth, equiv_rate);
+    celt_encoder_ctl(celt_enc, OPUS_SET_LSB_DEPTH(lsb_depth));
+
+    /* CELT mode doesn't support mediumband, use wideband instead */
+    if (st->mode == MODE_CELT_ONLY && st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
+        st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+    if (st->lfe)
+       st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+
+    curr_bandwidth = st->bandwidth;
+
+    /* Chooses the appropriate mode for speech
+       *NEVER* switch to/from CELT-only mode here as this will invalidate some assumptions */
+    if (st->mode == MODE_SILK_ONLY && curr_bandwidth > OPUS_BANDWIDTH_WIDEBAND)
+        st->mode = MODE_HYBRID;
+    if (st->mode == MODE_HYBRID && curr_bandwidth <= OPUS_BANDWIDTH_WIDEBAND)
+        st->mode = MODE_SILK_ONLY;
+
+    /* Can't support higher than >60 ms frames, and >20 ms when in Hybrid or CELT-only modes */
+    if ((frame_size > st->Fs/50 && (st->mode != MODE_SILK_ONLY)) || frame_size > 3*st->Fs/50)
+    {
+       int enc_frame_size;
+       int nb_frames;
+
+       if (st->mode == MODE_SILK_ONLY)
+       {
+         if (frame_size == 2*st->Fs/25)  /* 80 ms -> 2x 40 ms */
+           enc_frame_size = st->Fs/25;
+         else if (frame_size == 3*st->Fs/25)  /* 120 ms -> 2x 60 ms */
+           enc_frame_size = 3*st->Fs/50;
+         else                            /* 100 ms -> 5x 20 ms */
+           enc_frame_size = st->Fs/50;
+       }
+       else
+         enc_frame_size = st->Fs/50;
+
+       nb_frames = frame_size/enc_frame_size;
+
+#ifndef DISABLE_FLOAT_API
+       if (analysis_read_pos_bak!= -1)
+       {
+          st->analysis.read_pos = analysis_read_pos_bak;
+          st->analysis.read_subframe = analysis_read_subframe_bak;
+       }
+#endif
+
+       ret = encode_multiframe_packet(st, pcm, nb_frames, enc_frame_size, data,
+                                      out_data_bytes, to_celt, lsb_depth, float_api);
+
+       RESTORE_STACK;
+       return ret;
+    }
+
+    /* For the first frame at a new SILK bandwidth */
+    if (st->silk_bw_switch)
+    {
+       redundancy = 1;
+       celt_to_silk = 1;
+       st->silk_bw_switch = 0;
+       prefill=1;
+    }
+
+    /* If we decided to go with CELT, make sure redundancy is off, no matter what
+       we decided earlier. */
+    if (st->mode == MODE_CELT_ONLY)
+        redundancy = 0;
+
+    if (redundancy)
+    {
+       redundancy_bytes = compute_redundancy_bytes(max_data_bytes, st->bitrate_bps, frame_rate, st->stream_channels);
+       if (redundancy_bytes == 0)
+          redundancy = 0;
+    }
+
+    /* printf("%d %d %d %d\n", st->bitrate_bps, st->stream_channels, st->mode, curr_bandwidth); */
+    bytes_target = IMIN(max_data_bytes-redundancy_bytes, st->bitrate_bps * frame_size / (st->Fs * 8)) - 1;
+
+    data += 1;
+
+    ec_enc_init(&enc, data, max_data_bytes-1);
+
+    ALLOC(pcm_buf, (total_buffer+frame_size)*st->channels, opus_val16);
+    OPUS_COPY(pcm_buf, &st->delay_buffer[(st->encoder_buffer-total_buffer)*st->channels], total_buffer*st->channels);
+
+    if (st->mode == MODE_CELT_ONLY)
+       hp_freq_smth1 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
+    else
+       hp_freq_smth1 = ((silk_encoder*)silk_enc)->state_Fxx[0].sCmn.variable_HP_smth1_Q15;
+
+    st->variable_HP_smth2_Q15 = silk_SMLAWB( st->variable_HP_smth2_Q15,
+          hp_freq_smth1 - st->variable_HP_smth2_Q15, SILK_FIX_CONST( VARIABLE_HP_SMTH_COEF2, 16 ) );
+
+    /* convert from log scale to Hertz */
+    cutoff_Hz = silk_log2lin( silk_RSHIFT( st->variable_HP_smth2_Q15, 8 ) );
+
+    if (st->application == OPUS_APPLICATION_VOIP)
+    {
+       hp_cutoff(pcm, cutoff_Hz, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs, st->arch);
+    } else {
+       dc_reject(pcm, 3, &pcm_buf[total_buffer*st->channels], st->hp_mem, frame_size, st->channels, st->Fs);
+    }
+#ifndef FIXED_POINT
+    if (float_api)
+    {
+       opus_val32 sum;
+       sum = celt_inner_prod(&pcm_buf[total_buffer*st->channels], &pcm_buf[total_buffer*st->channels], frame_size*st->channels, st->arch);
+       /* This should filter out both NaNs and ridiculous signals that could
+          cause NaNs further down. */
+       if (!(sum < 1e9f) || celt_isnan(sum))
+       {
+          OPUS_CLEAR(&pcm_buf[total_buffer*st->channels], frame_size*st->channels);
+          st->hp_mem[0] = st->hp_mem[1] = st->hp_mem[2] = st->hp_mem[3] = 0;
+       }
+    }
+#endif
+
+
+    /* SILK processing */
+    HB_gain = Q15ONE;
+    if (st->mode != MODE_CELT_ONLY)
+    {
+        opus_int32 total_bitRate, celt_rate;
+#ifdef FIXED_POINT
+       const opus_int16 *pcm_silk;
+#else
+       VARDECL(opus_int16, pcm_silk);
+       ALLOC(pcm_silk, st->channels*frame_size, opus_int16);
+#endif
+
+        /* Distribute bits between SILK and CELT */
+        total_bitRate = 8 * bytes_target * frame_rate;
+        if( st->mode == MODE_HYBRID ) {
+            /* Base rate for SILK */
+            st->silk_mode.bitRate = compute_silk_rate_for_hybrid(total_bitRate,
+                  curr_bandwidth, st->Fs == 50 * frame_size, st->use_vbr, st->silk_mode.LBRR_coded);
+            if (!st->energy_masking)
+            {
+               /* Increasingly attenuate high band when it gets allocated fewer bits */
+               celt_rate = total_bitRate - st->silk_mode.bitRate;
+               HB_gain = Q15ONE - SHR32(celt_exp2(-celt_rate * QCONST16(1.f/1024, 10)), 1);
+            }
+        } else {
+            /* SILK gets all bits */
+            st->silk_mode.bitRate = total_bitRate;
+        }
+
+        /* Surround masking for SILK */
+        if (st->energy_masking && st->use_vbr && !st->lfe)
+        {
+           opus_val32 mask_sum=0;
+           opus_val16 masking_depth;
+           opus_int32 rate_offset;
+           int c;
+           int end = 17;
+           opus_int16 srate = 16000;
+           if (st->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
+           {
+              end = 13;
+              srate = 8000;
+           } else if (st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
+           {
+              end = 15;
+              srate = 12000;
+           }
+           for (c=0;c<st->channels;c++)
+           {
+              for(i=0;i<end;i++)
+              {
+                 opus_val16 mask;
+                 mask = MAX16(MIN16(st->energy_masking[21*c+i],
+                        QCONST16(.5f, DB_SHIFT)), -QCONST16(2.0f, DB_SHIFT));
+                 if (mask > 0)
+                    mask = HALF16(mask);
+                 mask_sum += mask;
+              }
+           }
+           /* Conservative rate reduction, we cut the masking in half */
+           masking_depth = mask_sum / end*st->channels;
+           masking_depth += QCONST16(.2f, DB_SHIFT);
+           rate_offset = (opus_int32)PSHR32(MULT16_16(srate, masking_depth), DB_SHIFT);
+           rate_offset = MAX32(rate_offset, -2*st->silk_mode.bitRate/3);
+           /* Split the rate change between the SILK and CELT part for hybrid. */
+           if (st->bandwidth==OPUS_BANDWIDTH_SUPERWIDEBAND || st->bandwidth==OPUS_BANDWIDTH_FULLBAND)
+              st->silk_mode.bitRate += 3*rate_offset/5;
+           else
+              st->silk_mode.bitRate += rate_offset;
+        }
+
+        st->silk_mode.payloadSize_ms = 1000 * frame_size / st->Fs;
+        st->silk_mode.nChannelsAPI = st->channels;
+        st->silk_mode.nChannelsInternal = st->stream_channels;
+        if (curr_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
+            st->silk_mode.desiredInternalSampleRate = 8000;
+        } else if (curr_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
+            st->silk_mode.desiredInternalSampleRate = 12000;
+        } else {
+            silk_assert( st->mode == MODE_HYBRID || curr_bandwidth == OPUS_BANDWIDTH_WIDEBAND );
+            st->silk_mode.desiredInternalSampleRate = 16000;
+        }
+        if( st->mode == MODE_HYBRID ) {
+            /* Don't allow bandwidth reduction at lowest bitrates in hybrid mode */
+            st->silk_mode.minInternalSampleRate = 16000;
+        } else {
+            st->silk_mode.minInternalSampleRate = 8000;
+        }
+
+        st->silk_mode.maxInternalSampleRate = 16000;
+        if (st->mode == MODE_SILK_ONLY)
+        {
+           opus_int32 effective_max_rate = max_rate;
+           if (frame_rate > 50)
+              effective_max_rate = effective_max_rate*2/3;
+           if (effective_max_rate < 8000)
+           {
+              st->silk_mode.maxInternalSampleRate = 12000;
+              st->silk_mode.desiredInternalSampleRate = IMIN(12000, st->silk_mode.desiredInternalSampleRate);
+           }
+           if (effective_max_rate < 7000)
+           {
+              st->silk_mode.maxInternalSampleRate = 8000;
+              st->silk_mode.desiredInternalSampleRate = IMIN(8000, st->silk_mode.desiredInternalSampleRate);
+           }
+        }
+
+        st->silk_mode.useCBR = !st->use_vbr;
+
+        /* Call SILK encoder for the low band */
+
+        /* Max bits for SILK, counting ToC, redundancy bytes, and optionally redundancy. */
+        st->silk_mode.maxBits = (max_data_bytes-1)*8;
+        if (redundancy && redundancy_bytes >= 2)
+        {
+           /* Counting 1 bit for redundancy position and 20 bits for flag+size (only for hybrid). */
+           st->silk_mode.maxBits -= redundancy_bytes*8 + 1;
+           if (st->mode == MODE_HYBRID)
+              st->silk_mode.maxBits -= 20;
+        }
+        if (st->silk_mode.useCBR)
+        {
+           if (st->mode == MODE_HYBRID)
+           {
+              st->silk_mode.maxBits = IMIN(st->silk_mode.maxBits, st->silk_mode.bitRate * frame_size / st->Fs);
+           }
+        } else {
+           /* Constrained VBR. */
+           if (st->mode == MODE_HYBRID)
+           {
+              /* Compute SILK bitrate corresponding to the max total bits available */
+              opus_int32 maxBitRate = compute_silk_rate_for_hybrid(st->silk_mode.maxBits*st->Fs / frame_size,
+                    curr_bandwidth, st->Fs == 50 * frame_size, st->use_vbr, st->silk_mode.LBRR_coded);
+              st->silk_mode.maxBits = maxBitRate * frame_size / st->Fs;
+           }
+        }
+
+        if (prefill)
+        {
+            opus_int32 zero=0;
+            int prefill_offset;
+            /* Use a smooth onset for the SILK prefill to avoid the encoder trying to encode
+               a discontinuity. The exact location is what we need to avoid leaving any "gap"
+               in the audio when mixing with the redundant CELT frame. Here we can afford to
+               overwrite st->delay_buffer because the only thing that uses it before it gets
+               rewritten is tmp_prefill[] and even then only the part after the ramp really
+               gets used (rather than sent to the encoder and discarded) */
+            prefill_offset = st->channels*(st->encoder_buffer-st->delay_compensation-st->Fs/400);
+            gain_fade(st->delay_buffer+prefill_offset, st->delay_buffer+prefill_offset,
+                  0, Q15ONE, celt_mode->overlap, st->Fs/400, st->channels, celt_mode->window, st->Fs);
+            OPUS_CLEAR(st->delay_buffer, prefill_offset);
+#ifdef FIXED_POINT
+            pcm_silk = st->delay_buffer;
+#else
+            for (i=0;i<st->encoder_buffer*st->channels;i++)
+                pcm_silk[i] = FLOAT2INT16(st->delay_buffer[i]);
+#endif
+            silk_Encode( silk_enc, &st->silk_mode, pcm_silk, st->encoder_buffer, NULL, &zero, 1 );
+        }
+
+#ifdef FIXED_POINT
+        pcm_silk = pcm_buf+total_buffer*st->channels;
+#else
+        for (i=0;i<frame_size*st->channels;i++)
+            pcm_silk[i] = FLOAT2INT16(pcm_buf[total_buffer*st->channels + i]);
+#endif
+        ret = silk_Encode( silk_enc, &st->silk_mode, pcm_silk, frame_size, &enc, &nBytes, 0 );
+        if( ret ) {
+            /*fprintf (stderr, "SILK encode error: %d\n", ret);*/
+            /* Handle error */
+           RESTORE_STACK;
+           return OPUS_INTERNAL_ERROR;
+        }
+
+        /* Extract SILK internal bandwidth for signaling in first byte */
+        if( st->mode == MODE_SILK_ONLY ) {
+            if( st->silk_mode.internalSampleRate == 8000 ) {
+               curr_bandwidth = OPUS_BANDWIDTH_NARROWBAND;
+            } else if( st->silk_mode.internalSampleRate == 12000 ) {
+               curr_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
+            } else if( st->silk_mode.internalSampleRate == 16000 ) {
+               curr_bandwidth = OPUS_BANDWIDTH_WIDEBAND;
+            }
+        } else {
+            silk_assert( st->silk_mode.internalSampleRate == 16000 );
+        }
+
+        st->silk_mode.opusCanSwitch = st->silk_mode.switchReady && !st->nonfinal_frame;
+
+        if (nBytes==0)
+        {
+           st->rangeFinal = 0;
+           data[-1] = gen_toc(st->mode, st->Fs/frame_size, curr_bandwidth, st->stream_channels);
+           RESTORE_STACK;
+           return 1;
+        }
+
+        /* FIXME: How do we allocate the redundancy for CBR? */
+        if (st->silk_mode.opusCanSwitch)
+        {
+           redundancy_bytes = compute_redundancy_bytes(max_data_bytes, st->bitrate_bps, frame_rate, st->stream_channels);
+           redundancy = (redundancy_bytes != 0);
+           celt_to_silk = 0;
+           st->silk_bw_switch = 1;
+        }
+    }
+
+    /* CELT processing */
+    {
+        int endband=21;
+
+        switch(curr_bandwidth)
+        {
+            case OPUS_BANDWIDTH_NARROWBAND:
+                endband = 13;
+                break;
+            case OPUS_BANDWIDTH_MEDIUMBAND:
+            case OPUS_BANDWIDTH_WIDEBAND:
+                endband = 17;
+                break;
+            case OPUS_BANDWIDTH_SUPERWIDEBAND:
+                endband = 19;
+                break;
+            case OPUS_BANDWIDTH_FULLBAND:
+                endband = 21;
+                break;
+        }
+        celt_encoder_ctl(celt_enc, CELT_SET_END_BAND(endband));
+        celt_encoder_ctl(celt_enc, CELT_SET_CHANNELS(st->stream_channels));
+    }
+    celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(OPUS_BITRATE_MAX));
+    if (st->mode != MODE_SILK_ONLY)
+    {
+        opus_val32 celt_pred=2;
+        celt_encoder_ctl(celt_enc, OPUS_SET_VBR(0));
+        /* We may still decide to disable prediction later */
+        if (st->silk_mode.reducedDependency)
+           celt_pred = 0;
+        celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(celt_pred));
+
+        if (st->mode == MODE_HYBRID)
+        {
+            if( st->use_vbr ) {
+                celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(st->bitrate_bps-st->silk_mode.bitRate));
+                celt_encoder_ctl(celt_enc, OPUS_SET_VBR_CONSTRAINT(0));
+            }
+        } else {
+            if (st->use_vbr)
+            {
+                celt_encoder_ctl(celt_enc, OPUS_SET_VBR(1));
+                celt_encoder_ctl(celt_enc, OPUS_SET_VBR_CONSTRAINT(st->vbr_constraint));
+                celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(st->bitrate_bps));
+            }
+        }
+    }
+
+    ALLOC(tmp_prefill, st->channels*st->Fs/400, opus_val16);
+    if (st->mode != MODE_SILK_ONLY && st->mode != st->prev_mode && st->prev_mode > 0)
+    {
+       OPUS_COPY(tmp_prefill, &st->delay_buffer[(st->encoder_buffer-total_buffer-st->Fs/400)*st->channels], st->channels*st->Fs/400);
+    }
+
+    if (st->channels*(st->encoder_buffer-(frame_size+total_buffer)) > 0)
+    {
+       OPUS_MOVE(st->delay_buffer, &st->delay_buffer[st->channels*frame_size], st->channels*(st->encoder_buffer-frame_size-total_buffer));
+       OPUS_COPY(&st->delay_buffer[st->channels*(st->encoder_buffer-frame_size-total_buffer)],
+             &pcm_buf[0],
+             (frame_size+total_buffer)*st->channels);
+    } else {
+       OPUS_COPY(st->delay_buffer, &pcm_buf[(frame_size+total_buffer-st->encoder_buffer)*st->channels], st->encoder_buffer*st->channels);
+    }
+    /* gain_fade() and stereo_fade() need to be after the buffer copying
+       because we don't want any of this to affect the SILK part */
+    if( st->prev_HB_gain < Q15ONE || HB_gain < Q15ONE ) {
+       gain_fade(pcm_buf, pcm_buf,
+             st->prev_HB_gain, HB_gain, celt_mode->overlap, frame_size, st->channels, celt_mode->window, st->Fs);
+    }
+    st->prev_HB_gain = HB_gain;
+    if (st->mode != MODE_HYBRID || st->stream_channels==1)
+       st->silk_mode.stereoWidth_Q14 = IMIN((1<<14),2*IMAX(0,equiv_rate-24000));
+    if( !st->energy_masking && st->channels == 2 ) {
+        /* Apply stereo width reduction (at low bitrates) */
+        if( st->hybrid_stereo_width_Q14 < (1 << 14) || st->silk_mode.stereoWidth_Q14 < (1 << 14) ) {
+            opus_val16 g1, g2;
+            g1 = st->hybrid_stereo_width_Q14;
+            g2 = (opus_val16)(st->silk_mode.stereoWidth_Q14);
+#ifdef FIXED_POINT
+            g1 = g1==16384 ? Q15ONE : SHL16(g1,1);
+            g2 = g2==16384 ? Q15ONE : SHL16(g2,1);
+#else
+            g1 *= (1.f/16384);
+            g2 *= (1.f/16384);
+#endif
+            stereo_fade(pcm_buf, pcm_buf, g1, g2, celt_mode->overlap,
+                  frame_size, st->channels, celt_mode->window, st->Fs);
+            st->hybrid_stereo_width_Q14 = st->silk_mode.stereoWidth_Q14;
+        }
+    }
+
+    if ( st->mode != MODE_CELT_ONLY && ec_tell(&enc)+17+20*(st->mode == MODE_HYBRID) <= 8*(max_data_bytes-1))
+    {
+        /* For SILK mode, the redundancy is inferred from the length */
+        if (st->mode == MODE_HYBRID)
+           ec_enc_bit_logp(&enc, redundancy, 12);
+        if (redundancy)
+        {
+            int max_redundancy;
+            ec_enc_bit_logp(&enc, celt_to_silk, 1);
+            if (st->mode == MODE_HYBRID)
+            {
+               /* Reserve the 8 bits needed for the redundancy length,
+                  and at least a few bits for CELT if possible */
+               max_redundancy = (max_data_bytes-1)-((ec_tell(&enc)+8+3+7)>>3);
+            }
+            else
+               max_redundancy = (max_data_bytes-1)-((ec_tell(&enc)+7)>>3);
+            /* Target the same bit-rate for redundancy as for the rest,
+               up to a max of 257 bytes */
+            redundancy_bytes = IMIN(max_redundancy, redundancy_bytes);
+            redundancy_bytes = IMIN(257, IMAX(2, redundancy_bytes));
+            if (st->mode == MODE_HYBRID)
+                ec_enc_uint(&enc, redundancy_bytes-2, 256);
+        }
+    } else {
+        redundancy = 0;
+    }
+
+    if (!redundancy)
+    {
+       st->silk_bw_switch = 0;
+       redundancy_bytes = 0;
+    }
+    if (st->mode != MODE_CELT_ONLY)start_band=17;
+
+    if (st->mode == MODE_SILK_ONLY)
+    {
+        ret = (ec_tell(&enc)+7)>>3;
+        ec_enc_done(&enc);
+        nb_compr_bytes = ret;
+    } else {
+       nb_compr_bytes = (max_data_bytes-1)-redundancy_bytes;
+       ec_enc_shrink(&enc, nb_compr_bytes);
+    }
+
+#ifndef DISABLE_FLOAT_API
+    if (redundancy || st->mode != MODE_SILK_ONLY)
+       celt_encoder_ctl(celt_enc, CELT_SET_ANALYSIS(&analysis_info));
+#endif
+    if (st->mode == MODE_HYBRID) {
+       SILKInfo info;
+       info.signalType = st->silk_mode.signalType;
+       info.offset = st->silk_mode.offset;
+       celt_encoder_ctl(celt_enc, CELT_SET_SILK_INFO(&info));
+    } else {
+       celt_encoder_ctl(celt_enc, CELT_SET_SILK_INFO((SILKInfo*)NULL));
+    }
+
+    /* 5 ms redundant frame for CELT->SILK */
+    if (redundancy && celt_to_silk)
+    {
+        int err;
+        celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(0));
+        celt_encoder_ctl(celt_enc, OPUS_SET_VBR(0));
+        celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(OPUS_BITRATE_MAX));
+        err = celt_encode_with_ec(celt_enc, pcm_buf, st->Fs/200, data+nb_compr_bytes, redundancy_bytes, NULL);
+        if (err < 0)
+        {
+           RESTORE_STACK;
+           return OPUS_INTERNAL_ERROR;
+        }
+        celt_encoder_ctl(celt_enc, OPUS_GET_FINAL_RANGE(&redundant_rng));
+        celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
+    }
+
+    celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(start_band));
+
+    if (st->mode != MODE_SILK_ONLY)
+    {
+        if (st->mode != st->prev_mode && st->prev_mode > 0)
+        {
+           unsigned char dummy[2];
+           celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
+
+           /* Prefilling */
+           celt_encode_with_ec(celt_enc, tmp_prefill, st->Fs/400, dummy, 2, NULL);
+           celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(0));
+        }
+        /* If false, we already busted the budget and we'll end up with a "PLC frame" */
+        if (ec_tell(&enc) <= 8*nb_compr_bytes)
+        {
+           /* Set the bitrate again if it was overridden in the redundancy code above*/
+           if (redundancy && celt_to_silk && st->mode==MODE_HYBRID && st->use_vbr)
+              celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(st->bitrate_bps-st->silk_mode.bitRate));
+           celt_encoder_ctl(celt_enc, OPUS_SET_VBR(st->use_vbr));
+           ret = celt_encode_with_ec(celt_enc, pcm_buf, frame_size, NULL, nb_compr_bytes, &enc);
+           if (ret < 0)
+           {
+              RESTORE_STACK;
+              return OPUS_INTERNAL_ERROR;
+           }
+           /* Put CELT->SILK redundancy data in the right place. */
+           if (redundancy && celt_to_silk && st->mode==MODE_HYBRID && st->use_vbr)
+           {
+              OPUS_MOVE(data+ret, data+nb_compr_bytes, redundancy_bytes);
+              nb_compr_bytes = nb_compr_bytes+redundancy_bytes;
+           }
+        }
+    }
+
+    /* 5 ms redundant frame for SILK->CELT */
+    if (redundancy && !celt_to_silk)
+    {
+        int err;
+        unsigned char dummy[2];
+        int N2, N4;
+        N2 = st->Fs/200;
+        N4 = st->Fs/400;
+
+        celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
+        celt_encoder_ctl(celt_enc, CELT_SET_START_BAND(0));
+        celt_encoder_ctl(celt_enc, CELT_SET_PREDICTION(0));
+        celt_encoder_ctl(celt_enc, OPUS_SET_VBR(0));
+        celt_encoder_ctl(celt_enc, OPUS_SET_BITRATE(OPUS_BITRATE_MAX));
+
+        if (st->mode == MODE_HYBRID)
+        {
+           /* Shrink packet to what the encoder actually used. */
+           nb_compr_bytes = ret;
+           ec_enc_shrink(&enc, nb_compr_bytes);
+        }
+        /* NOTE: We could speed this up slightly (at the expense of code size) by just adding a function that prefills the buffer */
+        celt_encode_with_ec(celt_enc, pcm_buf+st->channels*(frame_size-N2-N4), N4, dummy, 2, NULL);
+
+        err = celt_encode_with_ec(celt_enc, pcm_buf+st->channels*(frame_size-N2), N2, data+nb_compr_bytes, redundancy_bytes, NULL);
+        if (err < 0)
+        {
+           RESTORE_STACK;
+           return OPUS_INTERNAL_ERROR;
+        }
+        celt_encoder_ctl(celt_enc, OPUS_GET_FINAL_RANGE(&redundant_rng));
+    }
+
+
+
+    /* Signalling the mode in the first byte */
+    data--;
+    data[0] = gen_toc(st->mode, st->Fs/frame_size, curr_bandwidth, st->stream_channels);
+
+    st->rangeFinal = enc.rng ^ redundant_rng;
+
+    if (to_celt)
+        st->prev_mode = MODE_CELT_ONLY;
+    else
+        st->prev_mode = st->mode;
+    st->prev_channels = st->stream_channels;
+    st->prev_framesize = frame_size;
+
+    st->first = 0;
+
+    /* DTX decision */
+#ifndef DISABLE_FLOAT_API
+    if (st->use_dtx && (analysis_info.valid || is_silence))
+    {
+       if (decide_dtx_mode(analysis_info.activity_probability, &st->nb_no_activity_frames,
+             st->peak_signal_energy, pcm, frame_size, st->channels, is_silence, st->arch))
+       {
+          st->rangeFinal = 0;
+          data[0] = gen_toc(st->mode, st->Fs/frame_size, curr_bandwidth, st->stream_channels);
+          RESTORE_STACK;
+          return 1;
+       }
+    }
+#endif
+
+    /* In the unlikely case that the SILK encoder busted its target, tell
+       the decoder to call the PLC */
+    if (ec_tell(&enc) > (max_data_bytes-1)*8)
+    {
+       if (max_data_bytes < 2)
+       {
+          RESTORE_STACK;
+          return OPUS_BUFFER_TOO_SMALL;
+       }
+       data[1] = 0;
+       ret = 1;
+       st->rangeFinal = 0;
+    } else if (st->mode==MODE_SILK_ONLY&&!redundancy)
+    {
+       /*When in LPC only mode it's perfectly
+         reasonable to strip off trailing zero bytes as
+         the required range decoder behavior is to
+         fill these in. This can't be done when the MDCT
+         modes are used because the decoder needs to know
+         the actual length for allocation purposes.*/
+       while(ret>2&&data[ret]==0)ret--;
+    }
+    /* Count ToC and redundancy */
+    ret += 1+redundancy_bytes;
+    if (!st->use_vbr)
+    {
+       if (opus_packet_pad(data, ret, max_data_bytes) != OPUS_OK)
+       {
+          RESTORE_STACK;
+          return OPUS_INTERNAL_ERROR;
+       }
+       ret = max_data_bytes;
+    }
+    RESTORE_STACK;
+    return ret;
+}
+
+#ifdef FIXED_POINT
+
+#ifndef DISABLE_FLOAT_API
+opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int analysis_frame_size,
+      unsigned char *data, opus_int32 max_data_bytes)
+{
+   int i, ret;
+   int frame_size;
+   VARDECL(opus_int16, in);
+   ALLOC_STACK;
+
+   frame_size = frame_size_select(analysis_frame_size, st->variable_duration, st->Fs);
+   if (frame_size <= 0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   ALLOC(in, frame_size*st->channels, opus_int16);
+
+   for (i=0;i<frame_size*st->channels;i++)
+      in[i] = FLOAT2INT16(pcm[i]);
+   ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16,
+                            pcm, analysis_frame_size, 0, -2, st->channels, downmix_float, 1);
+   RESTORE_STACK;
+   return ret;
+}
+#endif
+
+opus_int32 opus_encode(OpusEncoder *st, const opus_int16 *pcm, int analysis_frame_size,
+                unsigned char *data, opus_int32 out_data_bytes)
+{
+   int frame_size;
+   frame_size = frame_size_select(analysis_frame_size, st->variable_duration, st->Fs);
+   return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 16,
+                             pcm, analysis_frame_size, 0, -2, st->channels, downmix_int, 0);
+}
+
+#else
+opus_int32 opus_encode(OpusEncoder *st, const opus_int16 *pcm, int analysis_frame_size,
+      unsigned char *data, opus_int32 max_data_bytes)
+{
+   int i, ret;
+   int frame_size;
+   VARDECL(float, in);
+   ALLOC_STACK;
+
+   frame_size = frame_size_select(analysis_frame_size, st->variable_duration, st->Fs);
+   if (frame_size <= 0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   ALLOC(in, frame_size*st->channels, float);
+
+   for (i=0;i<frame_size*st->channels;i++)
+      in[i] = (1.0f/32768)*pcm[i];
+   ret = opus_encode_native(st, in, frame_size, data, max_data_bytes, 16,
+                            pcm, analysis_frame_size, 0, -2, st->channels, downmix_int, 0);
+   RESTORE_STACK;
+   return ret;
+}
+opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int analysis_frame_size,
+                      unsigned char *data, opus_int32 out_data_bytes)
+{
+   int frame_size;
+   frame_size = frame_size_select(analysis_frame_size, st->variable_duration, st->Fs);
+   return opus_encode_native(st, pcm, frame_size, data, out_data_bytes, 24,
+                             pcm, analysis_frame_size, 0, -2, st->channels, downmix_float, 1);
+}
+#endif
+
+
+int opus_encoder_ctl(OpusEncoder *st, int request, ...)
+{
+    int ret;
+    CELTEncoder *celt_enc;
+    va_list ap;
+
+    ret = OPUS_OK;
+    va_start(ap, request);
+
+    celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
+
+    switch (request)
+    {
+        case OPUS_SET_APPLICATION_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (   (value != OPUS_APPLICATION_VOIP && value != OPUS_APPLICATION_AUDIO
+                 && value != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+               || (!st->first && st->application != value))
+            {
+               ret = OPUS_BAD_ARG;
+               break;
+            }
+            st->application = value;
+#ifndef DISABLE_FLOAT_API
+            st->analysis.application = value;
+#endif
+        }
+        break;
+        case OPUS_GET_APPLICATION_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->application;
+        }
+        break;
+        case OPUS_SET_BITRATE_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value != OPUS_AUTO && value != OPUS_BITRATE_MAX)
+            {
+                if (value <= 0)
+                    goto bad_arg;
+                else if (value <= 500)
+                    value = 500;
+                else if (value > (opus_int32)300000*st->channels)
+                    value = (opus_int32)300000*st->channels;
+            }
+            st->user_bitrate_bps = value;
+        }
+        break;
+        case OPUS_GET_BITRATE_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = user_bitrate_to_bitrate(st, st->prev_framesize, 1276);
+        }
+        break;
+        case OPUS_SET_FORCE_CHANNELS_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if((value<1 || value>st->channels) && value != OPUS_AUTO)
+            {
+               goto bad_arg;
+            }
+            st->force_channels = value;
+        }
+        break;
+        case OPUS_GET_FORCE_CHANNELS_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->force_channels;
+        }
+        break;
+        case OPUS_SET_MAX_BANDWIDTH_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value < OPUS_BANDWIDTH_NARROWBAND || value > OPUS_BANDWIDTH_FULLBAND)
+            {
+               goto bad_arg;
+            }
+            st->max_bandwidth = value;
+            if (st->max_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
+                st->silk_mode.maxInternalSampleRate = 8000;
+            } else if (st->max_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
+                st->silk_mode.maxInternalSampleRate = 12000;
+            } else {
+                st->silk_mode.maxInternalSampleRate = 16000;
+            }
+        }
+        break;
+        case OPUS_GET_MAX_BANDWIDTH_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->max_bandwidth;
+        }
+        break;
+        case OPUS_SET_BANDWIDTH_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if ((value < OPUS_BANDWIDTH_NARROWBAND || value > OPUS_BANDWIDTH_FULLBAND) && value != OPUS_AUTO)
+            {
+               goto bad_arg;
+            }
+            st->user_bandwidth = value;
+            if (st->user_bandwidth == OPUS_BANDWIDTH_NARROWBAND) {
+                st->silk_mode.maxInternalSampleRate = 8000;
+            } else if (st->user_bandwidth == OPUS_BANDWIDTH_MEDIUMBAND) {
+                st->silk_mode.maxInternalSampleRate = 12000;
+            } else {
+                st->silk_mode.maxInternalSampleRate = 16000;
+            }
+        }
+        break;
+        case OPUS_GET_BANDWIDTH_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->bandwidth;
+        }
+        break;
+        case OPUS_SET_DTX_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>1)
+            {
+               goto bad_arg;
+            }
+            st->use_dtx = value;
+        }
+        break;
+        case OPUS_GET_DTX_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->use_dtx;
+        }
+        break;
+        case OPUS_SET_COMPLEXITY_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>10)
+            {
+               goto bad_arg;
+            }
+            st->silk_mode.complexity = value;
+            celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(value));
+        }
+        break;
+        case OPUS_GET_COMPLEXITY_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->silk_mode.complexity;
+        }
+        break;
+        case OPUS_SET_INBAND_FEC_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>1)
+            {
+               goto bad_arg;
+            }
+            st->silk_mode.useInBandFEC = value;
+        }
+        break;
+        case OPUS_GET_INBAND_FEC_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->silk_mode.useInBandFEC;
+        }
+        break;
+        case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value < 0 || value > 100)
+            {
+               goto bad_arg;
+            }
+            st->silk_mode.packetLossPercentage = value;
+            celt_encoder_ctl(celt_enc, OPUS_SET_PACKET_LOSS_PERC(value));
+        }
+        break;
+        case OPUS_GET_PACKET_LOSS_PERC_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->silk_mode.packetLossPercentage;
+        }
+        break;
+        case OPUS_SET_VBR_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>1)
+            {
+               goto bad_arg;
+            }
+            st->use_vbr = value;
+            st->silk_mode.useCBR = 1-value;
+        }
+        break;
+        case OPUS_GET_VBR_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->use_vbr;
+        }
+        break;
+        case OPUS_SET_VOICE_RATIO_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value<-1 || value>100)
+            {
+               goto bad_arg;
+            }
+            st->voice_ratio = value;
+        }
+        break;
+        case OPUS_GET_VOICE_RATIO_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->voice_ratio;
+        }
+        break;
+        case OPUS_SET_VBR_CONSTRAINT_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>1)
+            {
+               goto bad_arg;
+            }
+            st->vbr_constraint = value;
+        }
+        break;
+        case OPUS_GET_VBR_CONSTRAINT_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->vbr_constraint;
+        }
+        break;
+        case OPUS_SET_SIGNAL_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value!=OPUS_AUTO && value!=OPUS_SIGNAL_VOICE && value!=OPUS_SIGNAL_MUSIC)
+            {
+               goto bad_arg;
+            }
+            st->signal_type = value;
+        }
+        break;
+        case OPUS_GET_SIGNAL_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->signal_type;
+        }
+        break;
+        case OPUS_GET_LOOKAHEAD_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->Fs/400;
+            if (st->application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)
+                *value += st->delay_compensation;
+        }
+        break;
+        case OPUS_GET_SAMPLE_RATE_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->Fs;
+        }
+        break;
+        case OPUS_GET_FINAL_RANGE_REQUEST:
+        {
+            opus_uint32 *value = va_arg(ap, opus_uint32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->rangeFinal;
+        }
+        break;
+        case OPUS_SET_LSB_DEPTH_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value<8 || value>24)
+            {
+               goto bad_arg;
+            }
+            st->lsb_depth=value;
+        }
+        break;
+        case OPUS_GET_LSB_DEPTH_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->lsb_depth;
+        }
+        break;
+        case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if (value != OPUS_FRAMESIZE_ARG    && value != OPUS_FRAMESIZE_2_5_MS &&
+                value != OPUS_FRAMESIZE_5_MS   && value != OPUS_FRAMESIZE_10_MS  &&
+                value != OPUS_FRAMESIZE_20_MS  && value != OPUS_FRAMESIZE_40_MS  &&
+                value != OPUS_FRAMESIZE_60_MS  && value != OPUS_FRAMESIZE_80_MS  &&
+                value != OPUS_FRAMESIZE_100_MS && value != OPUS_FRAMESIZE_120_MS)
+            {
+               goto bad_arg;
+            }
+            st->variable_duration = value;
+            celt_encoder_ctl(celt_enc, OPUS_SET_EXPERT_FRAME_DURATION(value));
+        }
+        break;
+        case OPUS_GET_EXPERT_FRAME_DURATION_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            *value = st->variable_duration;
+        }
+        break;
+        case OPUS_SET_PREDICTION_DISABLED_REQUEST:
+        {
+           opus_int32 value = va_arg(ap, opus_int32);
+           if (value > 1 || value < 0)
+              goto bad_arg;
+           st->silk_mode.reducedDependency = value;
+        }
+        break;
+        case OPUS_GET_PREDICTION_DISABLED_REQUEST:
+        {
+           opus_int32 *value = va_arg(ap, opus_int32*);
+           if (!value)
+              goto bad_arg;
+           *value = st->silk_mode.reducedDependency;
+        }
+        break;
+        case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if(value<0 || value>1)
+            {
+               goto bad_arg;
+            }
+            celt_encoder_ctl(celt_enc, OPUS_SET_PHASE_INVERSION_DISABLED(value));
+        }
+        break;
+        case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+        {
+            opus_int32 *value = va_arg(ap, opus_int32*);
+            if (!value)
+            {
+               goto bad_arg;
+            }
+            celt_encoder_ctl(celt_enc, OPUS_GET_PHASE_INVERSION_DISABLED(value));
+        }
+        break;
+        case OPUS_RESET_STATE:
+        {
+           void *silk_enc;
+           silk_EncControlStruct dummy;
+           char *start;
+           silk_enc = (char*)st+st->silk_enc_offset;
+#ifndef DISABLE_FLOAT_API
+           tonality_analysis_reset(&st->analysis);
+#endif
+
+           start = (char*)&st->OPUS_ENCODER_RESET_START;
+           OPUS_CLEAR(start, sizeof(OpusEncoder) - (start - (char*)st));
+
+           celt_encoder_ctl(celt_enc, OPUS_RESET_STATE);
+           silk_InitEncoder( silk_enc, st->arch, &dummy );
+           st->stream_channels = st->channels;
+           st->hybrid_stereo_width_Q14 = 1 << 14;
+           st->prev_HB_gain = Q15ONE;
+           st->first = 1;
+           st->mode = MODE_HYBRID;
+           st->bandwidth = OPUS_BANDWIDTH_FULLBAND;
+           st->variable_HP_smth2_Q15 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
+        }
+        break;
+        case OPUS_SET_FORCE_MODE_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            if ((value < MODE_SILK_ONLY || value > MODE_CELT_ONLY) && value != OPUS_AUTO)
+            {
+               goto bad_arg;
+            }
+            st->user_forced_mode = value;
+        }
+        break;
+        case OPUS_SET_LFE_REQUEST:
+        {
+            opus_int32 value = va_arg(ap, opus_int32);
+            st->lfe = value;
+            ret = celt_encoder_ctl(celt_enc, OPUS_SET_LFE(value));
+        }
+        break;
+        case OPUS_SET_ENERGY_MASK_REQUEST:
+        {
+            opus_val16 *value = va_arg(ap, opus_val16*);
+            st->energy_masking = value;
+            ret = celt_encoder_ctl(celt_enc, OPUS_SET_ENERGY_MASK(value));
+        }
+        break;
+
+        case CELT_GET_MODE_REQUEST:
+        {
+           const CELTMode ** value = va_arg(ap, const CELTMode**);
+           if (!value)
+           {
+              goto bad_arg;
+           }
+           ret = celt_encoder_ctl(celt_enc, CELT_GET_MODE(value));
+        }
+        break;
+        default:
+            /* fprintf(stderr, "unknown opus_encoder_ctl() request: %d", request);*/
+            ret = OPUS_UNIMPLEMENTED;
+            break;
+    }
+    va_end(ap);
+    return ret;
+bad_arg:
+    va_end(ap);
+    return OPUS_BAD_ARG;
+}
+
+void opus_encoder_destroy(OpusEncoder *st)
+{
+    opus_free(st);
+}
diff --git a/opus/src/opus_multistream.c b/opus/src/opus_multistream.c
new file mode 100644 (file)
index 0000000..09c3639
--- /dev/null
@@ -0,0 +1,92 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_multistream.h"
+#include "opus.h"
+#include "opus_private.h"
+#include "stack_alloc.h"
+#include <stdarg.h>
+#include "float_cast.h"
+#include "os_support.h"
+
+
+int validate_layout(const ChannelLayout *layout)
+{
+   int i, max_channel;
+
+   max_channel = layout->nb_streams+layout->nb_coupled_streams;
+   if (max_channel>255)
+      return 0;
+   for (i=0;i<layout->nb_channels;i++)
+   {
+      if (layout->mapping[i] >= max_channel && layout->mapping[i] != 255)
+         return 0;
+   }
+   return 1;
+}
+
+
+int get_left_channel(const ChannelLayout *layout, int stream_id, int prev)
+{
+   int i;
+   i = (prev<0) ? 0 : prev+1;
+   for (;i<layout->nb_channels;i++)
+   {
+      if (layout->mapping[i]==stream_id*2)
+         return i;
+   }
+   return -1;
+}
+
+int get_right_channel(const ChannelLayout *layout, int stream_id, int prev)
+{
+   int i;
+   i = (prev<0) ? 0 : prev+1;
+   for (;i<layout->nb_channels;i++)
+   {
+      if (layout->mapping[i]==stream_id*2+1)
+         return i;
+   }
+   return -1;
+}
+
+int get_mono_channel(const ChannelLayout *layout, int stream_id, int prev)
+{
+   int i;
+   i = (prev<0) ? 0 : prev+1;
+   for (;i<layout->nb_channels;i++)
+   {
+      if (layout->mapping[i]==stream_id+layout->nb_coupled_streams)
+         return i;
+   }
+   return -1;
+}
+
diff --git a/opus/src/opus_multistream_decoder.c b/opus/src/opus_multistream_decoder.c
new file mode 100644 (file)
index 0000000..e421726
--- /dev/null
@@ -0,0 +1,540 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_multistream.h"
+#include "opus.h"
+#include "opus_private.h"
+#include "stack_alloc.h"
+#include <stdarg.h>
+#include "float_cast.h"
+#include "os_support.h"
+
+struct OpusMSDecoder {
+   ChannelLayout layout;
+   /* Decoder states go here */
+};
+
+
+
+
+/* DECODER */
+
+opus_int32 opus_multistream_decoder_get_size(int nb_streams, int nb_coupled_streams)
+{
+   int coupled_size;
+   int mono_size;
+
+   if(nb_streams<1||nb_coupled_streams>nb_streams||nb_coupled_streams<0)return 0;
+   coupled_size = opus_decoder_get_size(2);
+   mono_size = opus_decoder_get_size(1);
+   return align(sizeof(OpusMSDecoder))
+         + nb_coupled_streams * align(coupled_size)
+         + (nb_streams-nb_coupled_streams) * align(mono_size);
+}
+
+int opus_multistream_decoder_init(
+      OpusMSDecoder *st,
+      opus_int32 Fs,
+      int channels,
+      int streams,
+      int coupled_streams,
+      const unsigned char *mapping
+)
+{
+   int coupled_size;
+   int mono_size;
+   int i, ret;
+   char *ptr;
+
+   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
+       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
+      return OPUS_BAD_ARG;
+
+   st->layout.nb_channels = channels;
+   st->layout.nb_streams = streams;
+   st->layout.nb_coupled_streams = coupled_streams;
+
+   for (i=0;i<st->layout.nb_channels;i++)
+      st->layout.mapping[i] = mapping[i];
+   if (!validate_layout(&st->layout))
+      return OPUS_BAD_ARG;
+
+   ptr = (char*)st + align(sizeof(OpusMSDecoder));
+   coupled_size = opus_decoder_get_size(2);
+   mono_size = opus_decoder_get_size(1);
+
+   for (i=0;i<st->layout.nb_coupled_streams;i++)
+   {
+      ret=opus_decoder_init((OpusDecoder*)ptr, Fs, 2);
+      if(ret!=OPUS_OK)return ret;
+      ptr += align(coupled_size);
+   }
+   for (;i<st->layout.nb_streams;i++)
+   {
+      ret=opus_decoder_init((OpusDecoder*)ptr, Fs, 1);
+      if(ret!=OPUS_OK)return ret;
+      ptr += align(mono_size);
+   }
+   return OPUS_OK;
+}
+
+
+OpusMSDecoder *opus_multistream_decoder_create(
+      opus_int32 Fs,
+      int channels,
+      int streams,
+      int coupled_streams,
+      const unsigned char *mapping,
+      int *error
+)
+{
+   int ret;
+   OpusMSDecoder *st;
+   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
+       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   st = (OpusMSDecoder *)opus_alloc(opus_multistream_decoder_get_size(streams, coupled_streams));
+   if (st==NULL)
+   {
+      if (error)
+         *error = OPUS_ALLOC_FAIL;
+      return NULL;
+   }
+   ret = opus_multistream_decoder_init(st, Fs, channels, streams, coupled_streams, mapping);
+   if (error)
+      *error = ret;
+   if (ret != OPUS_OK)
+   {
+      opus_free(st);
+      st = NULL;
+   }
+   return st;
+}
+
+typedef void (*opus_copy_channel_out_func)(
+  void *dst,
+  int dst_stride,
+  int dst_channel,
+  const opus_val16 *src,
+  int src_stride,
+  int frame_size
+);
+
+static int opus_multistream_packet_validate(const unsigned char *data,
+      opus_int32 len, int nb_streams, opus_int32 Fs)
+{
+   int s;
+   int count;
+   unsigned char toc;
+   opus_int16 size[48];
+   int samples=0;
+   opus_int32 packet_offset;
+
+   for (s=0;s<nb_streams;s++)
+   {
+      int tmp_samples;
+      if (len<=0)
+         return OPUS_INVALID_PACKET;
+      count = opus_packet_parse_impl(data, len, s!=nb_streams-1, &toc, NULL,
+                                     size, NULL, &packet_offset);
+      if (count<0)
+         return count;
+      tmp_samples = opus_packet_get_nb_samples(data, packet_offset, Fs);
+      if (s!=0 && samples != tmp_samples)
+         return OPUS_INVALID_PACKET;
+      samples = tmp_samples;
+      data += packet_offset;
+      len -= packet_offset;
+   }
+   return samples;
+}
+
+static int opus_multistream_decode_native(
+      OpusMSDecoder *st,
+      const unsigned char *data,
+      opus_int32 len,
+      void *pcm,
+      opus_copy_channel_out_func copy_channel_out,
+      int frame_size,
+      int decode_fec,
+      int soft_clip
+)
+{
+   opus_int32 Fs;
+   int coupled_size;
+   int mono_size;
+   int s, c;
+   char *ptr;
+   int do_plc=0;
+   VARDECL(opus_val16, buf);
+   ALLOC_STACK;
+
+   /* Limit frame_size to avoid excessive stack allocations. */
+   opus_multistream_decoder_ctl(st, OPUS_GET_SAMPLE_RATE(&Fs));
+   frame_size = IMIN(frame_size, Fs/25*3);
+   ALLOC(buf, 2*frame_size, opus_val16);
+   ptr = (char*)st + align(sizeof(OpusMSDecoder));
+   coupled_size = opus_decoder_get_size(2);
+   mono_size = opus_decoder_get_size(1);
+
+   if (len==0)
+      do_plc = 1;
+   if (len < 0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+   if (!do_plc && len < 2*st->layout.nb_streams-1)
+   {
+      RESTORE_STACK;
+      return OPUS_INVALID_PACKET;
+   }
+   if (!do_plc)
+   {
+      int ret = opus_multistream_packet_validate(data, len, st->layout.nb_streams, Fs);
+      if (ret < 0)
+      {
+         RESTORE_STACK;
+         return ret;
+      } else if (ret > frame_size)
+      {
+         RESTORE_STACK;
+         return OPUS_BUFFER_TOO_SMALL;
+      }
+   }
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      OpusDecoder *dec;
+      opus_int32 packet_offset;
+      int ret;
+
+      dec = (OpusDecoder*)ptr;
+      ptr += (s < st->layout.nb_coupled_streams) ? align(coupled_size) : align(mono_size);
+
+      if (!do_plc && len<=0)
+      {
+         RESTORE_STACK;
+         return OPUS_INTERNAL_ERROR;
+      }
+      packet_offset = 0;
+      ret = opus_decode_native(dec, data, len, buf, frame_size, decode_fec, s!=st->layout.nb_streams-1, &packet_offset, soft_clip);
+      data += packet_offset;
+      len -= packet_offset;
+      if (ret <= 0)
+      {
+         RESTORE_STACK;
+         return ret;
+      }
+      frame_size = ret;
+      if (s < st->layout.nb_coupled_streams)
+      {
+         int chan, prev;
+         prev = -1;
+         /* Copy "left" audio to the channel(s) where it belongs */
+         while ( (chan = get_left_channel(&st->layout, s, prev)) != -1)
+         {
+            (*copy_channel_out)(pcm, st->layout.nb_channels, chan,
+               buf, 2, frame_size);
+            prev = chan;
+         }
+         prev = -1;
+         /* Copy "right" audio to the channel(s) where it belongs */
+         while ( (chan = get_right_channel(&st->layout, s, prev)) != -1)
+         {
+            (*copy_channel_out)(pcm, st->layout.nb_channels, chan,
+               buf+1, 2, frame_size);
+            prev = chan;
+         }
+      } else {
+         int chan, prev;
+         prev = -1;
+         /* Copy audio to the channel(s) where it belongs */
+         while ( (chan = get_mono_channel(&st->layout, s, prev)) != -1)
+         {
+            (*copy_channel_out)(pcm, st->layout.nb_channels, chan,
+               buf, 1, frame_size);
+            prev = chan;
+         }
+      }
+   }
+   /* Handle muted channels */
+   for (c=0;c<st->layout.nb_channels;c++)
+   {
+      if (st->layout.mapping[c] == 255)
+      {
+         (*copy_channel_out)(pcm, st->layout.nb_channels, c,
+            NULL, 0, frame_size);
+      }
+   }
+   RESTORE_STACK;
+   return frame_size;
+}
+
+#if !defined(DISABLE_FLOAT_API)
+static void opus_copy_channel_out_float(
+  void *dst,
+  int dst_stride,
+  int dst_channel,
+  const opus_val16 *src,
+  int src_stride,
+  int frame_size
+)
+{
+   float *float_dst;
+   opus_int32 i;
+   float_dst = (float*)dst;
+   if (src != NULL)
+   {
+      for (i=0;i<frame_size;i++)
+#if defined(FIXED_POINT)
+         float_dst[i*dst_stride+dst_channel] = (1/32768.f)*src[i*src_stride];
+#else
+         float_dst[i*dst_stride+dst_channel] = src[i*src_stride];
+#endif
+   }
+   else
+   {
+      for (i=0;i<frame_size;i++)
+         float_dst[i*dst_stride+dst_channel] = 0;
+   }
+}
+#endif
+
+static void opus_copy_channel_out_short(
+  void *dst,
+  int dst_stride,
+  int dst_channel,
+  const opus_val16 *src,
+  int src_stride,
+  int frame_size
+)
+{
+   opus_int16 *short_dst;
+   opus_int32 i;
+   short_dst = (opus_int16*)dst;
+   if (src != NULL)
+   {
+      for (i=0;i<frame_size;i++)
+#if defined(FIXED_POINT)
+         short_dst[i*dst_stride+dst_channel] = src[i*src_stride];
+#else
+         short_dst[i*dst_stride+dst_channel] = FLOAT2INT16(src[i*src_stride]);
+#endif
+   }
+   else
+   {
+      for (i=0;i<frame_size;i++)
+         short_dst[i*dst_stride+dst_channel] = 0;
+   }
+}
+
+
+
+#ifdef FIXED_POINT
+int opus_multistream_decode(
+      OpusMSDecoder *st,
+      const unsigned char *data,
+      opus_int32 len,
+      opus_int16 *pcm,
+      int frame_size,
+      int decode_fec
+)
+{
+   return opus_multistream_decode_native(st, data, len,
+       pcm, opus_copy_channel_out_short, frame_size, decode_fec, 0);
+}
+
+#ifndef DISABLE_FLOAT_API
+int opus_multistream_decode_float(OpusMSDecoder *st, const unsigned char *data,
+      opus_int32 len, float *pcm, int frame_size, int decode_fec)
+{
+   return opus_multistream_decode_native(st, data, len,
+       pcm, opus_copy_channel_out_float, frame_size, decode_fec, 0);
+}
+#endif
+
+#else
+
+int opus_multistream_decode(OpusMSDecoder *st, const unsigned char *data,
+      opus_int32 len, opus_int16 *pcm, int frame_size, int decode_fec)
+{
+   return opus_multistream_decode_native(st, data, len,
+       pcm, opus_copy_channel_out_short, frame_size, decode_fec, 1);
+}
+
+int opus_multistream_decode_float(
+      OpusMSDecoder *st,
+      const unsigned char *data,
+      opus_int32 len,
+      float *pcm,
+      int frame_size,
+      int decode_fec
+)
+{
+   return opus_multistream_decode_native(st, data, len,
+       pcm, opus_copy_channel_out_float, frame_size, decode_fec, 0);
+}
+#endif
+
+int opus_multistream_decoder_ctl(OpusMSDecoder *st, int request, ...)
+{
+   va_list ap;
+   int coupled_size, mono_size;
+   char *ptr;
+   int ret = OPUS_OK;
+
+   va_start(ap, request);
+
+   coupled_size = opus_decoder_get_size(2);
+   mono_size = opus_decoder_get_size(1);
+   ptr = (char*)st + align(sizeof(OpusMSDecoder));
+   switch (request)
+   {
+       case OPUS_GET_BANDWIDTH_REQUEST:
+       case OPUS_GET_SAMPLE_RATE_REQUEST:
+       case OPUS_GET_GAIN_REQUEST:
+       case OPUS_GET_LAST_PACKET_DURATION_REQUEST:
+       case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+       {
+          OpusDecoder *dec;
+          /* For int32* GET params, just query the first stream */
+          opus_int32 *value = va_arg(ap, opus_int32*);
+          dec = (OpusDecoder*)ptr;
+          ret = opus_decoder_ctl(dec, request, value);
+       }
+       break;
+       case OPUS_GET_FINAL_RANGE_REQUEST:
+       {
+          int s;
+          opus_uint32 *value = va_arg(ap, opus_uint32*);
+          opus_uint32 tmp;
+          if (!value)
+          {
+             goto bad_arg;
+          }
+          *value = 0;
+          for (s=0;s<st->layout.nb_streams;s++)
+          {
+             OpusDecoder *dec;
+             dec = (OpusDecoder*)ptr;
+             if (s < st->layout.nb_coupled_streams)
+                ptr += align(coupled_size);
+             else
+                ptr += align(mono_size);
+             ret = opus_decoder_ctl(dec, request, &tmp);
+             if (ret != OPUS_OK) break;
+             *value ^= tmp;
+          }
+       }
+       break;
+       case OPUS_RESET_STATE:
+       {
+          int s;
+          for (s=0;s<st->layout.nb_streams;s++)
+          {
+             OpusDecoder *dec;
+
+             dec = (OpusDecoder*)ptr;
+             if (s < st->layout.nb_coupled_streams)
+                ptr += align(coupled_size);
+             else
+                ptr += align(mono_size);
+             ret = opus_decoder_ctl(dec, OPUS_RESET_STATE);
+             if (ret != OPUS_OK)
+                break;
+          }
+       }
+       break;
+       case OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST:
+       {
+          int s;
+          opus_int32 stream_id;
+          OpusDecoder **value;
+          stream_id = va_arg(ap, opus_int32);
+          if (stream_id<0 || stream_id >= st->layout.nb_streams)
+             ret = OPUS_BAD_ARG;
+          value = va_arg(ap, OpusDecoder**);
+          if (!value)
+          {
+             goto bad_arg;
+          }
+          for (s=0;s<stream_id;s++)
+          {
+             if (s < st->layout.nb_coupled_streams)
+                ptr += align(coupled_size);
+             else
+                ptr += align(mono_size);
+          }
+          *value = (OpusDecoder*)ptr;
+       }
+       break;
+       case OPUS_SET_GAIN_REQUEST:
+       case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+       {
+          int s;
+          /* This works for int32 params */
+          opus_int32 value = va_arg(ap, opus_int32);
+          for (s=0;s<st->layout.nb_streams;s++)
+          {
+             OpusDecoder *dec;
+
+             dec = (OpusDecoder*)ptr;
+             if (s < st->layout.nb_coupled_streams)
+                ptr += align(coupled_size);
+             else
+                ptr += align(mono_size);
+             ret = opus_decoder_ctl(dec, request, value);
+             if (ret != OPUS_OK)
+                break;
+          }
+       }
+       break;
+       default:
+          ret = OPUS_UNIMPLEMENTED;
+       break;
+   }
+
+   va_end(ap);
+   return ret;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
+}
+
+
+void opus_multistream_decoder_destroy(OpusMSDecoder *st)
+{
+    opus_free(st);
+}
diff --git a/opus/src/opus_multistream_encoder.c b/opus/src/opus_multistream_encoder.c
new file mode 100644 (file)
index 0000000..032fc00
--- /dev/null
@@ -0,0 +1,1406 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus_multistream.h"
+#include "opus.h"
+#include "opus_private.h"
+#include "stack_alloc.h"
+#include <stdarg.h>
+#include "float_cast.h"
+#include "os_support.h"
+#include "mathops.h"
+#include "mdct.h"
+#include "modes.h"
+#include "bands.h"
+#include "quant_bands.h"
+#include "pitch.h"
+
+typedef struct {
+   int nb_streams;
+   int nb_coupled_streams;
+   unsigned char mapping[8];
+} VorbisLayout;
+
+/* Index is nb_channel-1*/
+static const VorbisLayout vorbis_mappings[8] = {
+      {1, 0, {0}},                      /* 1: mono */
+      {1, 1, {0, 1}},                   /* 2: stereo */
+      {2, 1, {0, 2, 1}},                /* 3: 1-d surround */
+      {2, 2, {0, 1, 2, 3}},             /* 4: quadraphonic surround */
+      {3, 2, {0, 4, 1, 2, 3}},          /* 5: 5-channel surround */
+      {4, 2, {0, 4, 1, 2, 3, 5}},       /* 6: 5.1 surround */
+      {4, 3, {0, 4, 1, 2, 3, 5, 6}},    /* 7: 6.1 surround */
+      {5, 3, {0, 6, 1, 2, 3, 4, 5, 7}}, /* 8: 7.1 surround */
+};
+
+typedef void (*opus_copy_channel_in_func)(
+  opus_val16 *dst,
+  int dst_stride,
+  const void *src,
+  int src_stride,
+  int src_channel,
+  int frame_size
+);
+
+typedef enum {
+  MAPPING_TYPE_NONE,
+  MAPPING_TYPE_SURROUND
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+  ,  /* Do not include comma at end of enumerator list */
+  MAPPING_TYPE_AMBISONICS
+#endif
+} MappingType;
+
+struct OpusMSEncoder {
+   ChannelLayout layout;
+   int arch;
+   int lfe_stream;
+   int application;
+   int variable_duration;
+   MappingType mapping_type;
+   opus_int32 bitrate_bps;
+   /* Encoder states go here */
+   /* then opus_val32 window_mem[channels*120]; */
+   /* then opus_val32 preemph_mem[channels]; */
+};
+
+static opus_val32 *ms_get_preemph_mem(OpusMSEncoder *st)
+{
+   int s;
+   char *ptr;
+   int coupled_size, mono_size;
+
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      if (s < st->layout.nb_coupled_streams)
+         ptr += align(coupled_size);
+      else
+         ptr += align(mono_size);
+   }
+   /* void* cast avoids clang -Wcast-align warning */
+   return (opus_val32*)(void*)(ptr+st->layout.nb_channels*120*sizeof(opus_val32));
+}
+
+static opus_val32 *ms_get_window_mem(OpusMSEncoder *st)
+{
+   int s;
+   char *ptr;
+   int coupled_size, mono_size;
+
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      if (s < st->layout.nb_coupled_streams)
+         ptr += align(coupled_size);
+      else
+         ptr += align(mono_size);
+   }
+   /* void* cast avoids clang -Wcast-align warning */
+   return (opus_val32*)(void*)ptr;
+}
+
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+static int validate_ambisonics(int nb_channels, int *nb_streams, int *nb_coupled_streams)
+{
+   int order_plus_one;
+   int acn_channels;
+   int nondiegetic_channels;
+
+   order_plus_one = isqrt32(nb_channels);
+   acn_channels = order_plus_one * order_plus_one;
+   nondiegetic_channels = nb_channels - acn_channels;
+
+   if (order_plus_one < 1 || order_plus_one > 15 ||
+       (nondiegetic_channels != 0 && nondiegetic_channels != 2))
+      return 0;
+
+   if (nb_streams)
+      *nb_streams = acn_channels + (nondiegetic_channels != 0);
+   if (nb_coupled_streams)
+      *nb_coupled_streams = nondiegetic_channels != 0;
+   return 1;
+}
+#endif
+
+static int validate_encoder_layout(const ChannelLayout *layout)
+{
+   int s;
+   for (s=0;s<layout->nb_streams;s++)
+   {
+      if (s < layout->nb_coupled_streams)
+      {
+         if (get_left_channel(layout, s, -1)==-1)
+            return 0;
+         if (get_right_channel(layout, s, -1)==-1)
+            return 0;
+      } else {
+         if (get_mono_channel(layout, s, -1)==-1)
+            return 0;
+      }
+   }
+   return 1;
+}
+
+static void channel_pos(int channels, int pos[8])
+{
+   /* Position in the mix: 0 don't mix, 1: left, 2: center, 3:right */
+   if (channels==4)
+   {
+      pos[0]=1;
+      pos[1]=3;
+      pos[2]=1;
+      pos[3]=3;
+   } else if (channels==3||channels==5||channels==6)
+   {
+      pos[0]=1;
+      pos[1]=2;
+      pos[2]=3;
+      pos[3]=1;
+      pos[4]=3;
+      pos[5]=0;
+   } else if (channels==7)
+   {
+      pos[0]=1;
+      pos[1]=2;
+      pos[2]=3;
+      pos[3]=1;
+      pos[4]=3;
+      pos[5]=2;
+      pos[6]=0;
+   } else if (channels==8)
+   {
+      pos[0]=1;
+      pos[1]=2;
+      pos[2]=3;
+      pos[3]=1;
+      pos[4]=3;
+      pos[5]=1;
+      pos[6]=3;
+      pos[7]=0;
+   }
+}
+
+#if 1
+/* Computes a rough approximation of log2(2^a + 2^b) */
+static opus_val16 logSum(opus_val16 a, opus_val16 b)
+{
+   opus_val16 max;
+   opus_val32 diff;
+   opus_val16 frac;
+   static const opus_val16 diff_table[17] = {
+         QCONST16(0.5000000f, DB_SHIFT), QCONST16(0.2924813f, DB_SHIFT), QCONST16(0.1609640f, DB_SHIFT), QCONST16(0.0849625f, DB_SHIFT),
+         QCONST16(0.0437314f, DB_SHIFT), QCONST16(0.0221971f, DB_SHIFT), QCONST16(0.0111839f, DB_SHIFT), QCONST16(0.0056136f, DB_SHIFT),
+         QCONST16(0.0028123f, DB_SHIFT)
+   };
+   int low;
+   if (a>b)
+   {
+      max = a;
+      diff = SUB32(EXTEND32(a),EXTEND32(b));
+   } else {
+      max = b;
+      diff = SUB32(EXTEND32(b),EXTEND32(a));
+   }
+   if (!(diff < QCONST16(8.f, DB_SHIFT)))  /* inverted to catch NaNs */
+      return max;
+#ifdef FIXED_POINT
+   low = SHR32(diff, DB_SHIFT-1);
+   frac = SHL16(diff - SHL16(low, DB_SHIFT-1), 16-DB_SHIFT);
+#else
+   low = (int)floor(2*diff);
+   frac = 2*diff - low;
+#endif
+   return max + diff_table[low] + MULT16_16_Q15(frac, SUB16(diff_table[low+1], diff_table[low]));
+}
+#else
+opus_val16 logSum(opus_val16 a, opus_val16 b)
+{
+   return log2(pow(4, a)+ pow(4, b))/2;
+}
+#endif
+
+void surround_analysis(const CELTMode *celt_mode, const void *pcm, opus_val16 *bandLogE, opus_val32 *mem, opus_val32 *preemph_mem,
+      int len, int overlap, int channels, int rate, opus_copy_channel_in_func copy_channel_in, int arch
+)
+{
+   int c;
+   int i;
+   int LM;
+   int pos[8] = {0};
+   int upsample;
+   int frame_size;
+   int freq_size;
+   opus_val16 channel_offset;
+   opus_val32 bandE[21];
+   opus_val16 maskLogE[3][21];
+   VARDECL(opus_val32, in);
+   VARDECL(opus_val16, x);
+   VARDECL(opus_val32, freq);
+   SAVE_STACK;
+
+   upsample = resampling_factor(rate);
+   frame_size = len*upsample;
+   freq_size = IMIN(960, frame_size);
+
+   /* LM = log2(frame_size / 120) */
+   for (LM=0;LM<celt_mode->maxLM;LM++)
+      if (celt_mode->shortMdctSize<<LM==frame_size)
+         break;
+
+   ALLOC(in, frame_size+overlap, opus_val32);
+   ALLOC(x, len, opus_val16);
+   ALLOC(freq, freq_size, opus_val32);
+
+   channel_pos(channels, pos);
+
+   for (c=0;c<3;c++)
+      for (i=0;i<21;i++)
+         maskLogE[c][i] = -QCONST16(28.f, DB_SHIFT);
+
+   for (c=0;c<channels;c++)
+   {
+      int frame;
+      int nb_frames = frame_size/freq_size;
+      celt_assert(nb_frames*freq_size == frame_size);
+      OPUS_COPY(in, mem+c*overlap, overlap);
+      (*copy_channel_in)(x, 1, pcm, channels, c, len);
+      celt_preemphasis(x, in+overlap, frame_size, 1, upsample, celt_mode->preemph, preemph_mem+c, 0);
+#ifndef FIXED_POINT
+      {
+         opus_val32 sum;
+         sum = celt_inner_prod(in, in, frame_size+overlap, 0);
+         /* This should filter out both NaNs and ridiculous signals that could
+            cause NaNs further down. */
+         if (!(sum < 1e18f) || celt_isnan(sum))
+         {
+            OPUS_CLEAR(in, frame_size+overlap);
+            preemph_mem[c] = 0;
+         }
+      }
+#endif
+      OPUS_CLEAR(bandE, 21);
+      for (frame=0;frame<nb_frames;frame++)
+      {
+         opus_val32 tmpE[21];
+         clt_mdct_forward(&celt_mode->mdct, in+960*frame, freq, celt_mode->window,
+               overlap, celt_mode->maxLM-LM, 1, arch);
+         if (upsample != 1)
+         {
+            int bound = freq_size/upsample;
+            for (i=0;i<bound;i++)
+               freq[i] *= upsample;
+            for (;i<freq_size;i++)
+               freq[i] = 0;
+         }
+
+         compute_band_energies(celt_mode, freq, tmpE, 21, 1, LM, arch);
+         /* If we have multiple frames, take the max energy. */
+         for (i=0;i<21;i++)
+            bandE[i] = MAX32(bandE[i], tmpE[i]);
+      }
+      amp2Log2(celt_mode, 21, 21, bandE, bandLogE+21*c, 1);
+      /* Apply spreading function with -6 dB/band going up and -12 dB/band going down. */
+      for (i=1;i<21;i++)
+         bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i-1]-QCONST16(1.f, DB_SHIFT));
+      for (i=19;i>=0;i--)
+         bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i+1]-QCONST16(2.f, DB_SHIFT));
+      if (pos[c]==1)
+      {
+         for (i=0;i<21;i++)
+            maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]);
+      } else if (pos[c]==3)
+      {
+         for (i=0;i<21;i++)
+            maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]);
+      } else if (pos[c]==2)
+      {
+         for (i=0;i<21;i++)
+         {
+            maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT));
+            maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT));
+         }
+      }
+#if 0
+      for (i=0;i<21;i++)
+         printf("%f ", bandLogE[21*c+i]);
+      float sum=0;
+      for (i=0;i<21;i++)
+         sum += bandLogE[21*c+i];
+      printf("%f ", sum/21);
+#endif
+      OPUS_COPY(mem+c*overlap, in+frame_size, overlap);
+   }
+   for (i=0;i<21;i++)
+      maskLogE[1][i] = MIN32(maskLogE[0][i],maskLogE[2][i]);
+   channel_offset = HALF16(celt_log2(QCONST32(2.f,14)/(channels-1)));
+   for (c=0;c<3;c++)
+      for (i=0;i<21;i++)
+         maskLogE[c][i] += channel_offset;
+#if 0
+   for (c=0;c<3;c++)
+   {
+      for (i=0;i<21;i++)
+         printf("%f ", maskLogE[c][i]);
+   }
+#endif
+   for (c=0;c<channels;c++)
+   {
+      opus_val16 *mask;
+      if (pos[c]!=0)
+      {
+         mask = &maskLogE[pos[c]-1][0];
+         for (i=0;i<21;i++)
+            bandLogE[21*c+i] = bandLogE[21*c+i] - mask[i];
+      } else {
+         for (i=0;i<21;i++)
+            bandLogE[21*c+i] = 0;
+      }
+#if 0
+      for (i=0;i<21;i++)
+         printf("%f ", bandLogE[21*c+i]);
+      printf("\n");
+#endif
+#if 0
+      float sum=0;
+      for (i=0;i<21;i++)
+         sum += bandLogE[21*c+i];
+      printf("%f ", sum/(float)QCONST32(21.f, DB_SHIFT));
+      printf("\n");
+#endif
+   }
+   RESTORE_STACK;
+}
+
+opus_int32 opus_multistream_encoder_get_size(int nb_streams, int nb_coupled_streams)
+{
+   int coupled_size;
+   int mono_size;
+
+   if(nb_streams<1||nb_coupled_streams>nb_streams||nb_coupled_streams<0)return 0;
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+   return align(sizeof(OpusMSEncoder))
+        + nb_coupled_streams * align(coupled_size)
+        + (nb_streams-nb_coupled_streams) * align(mono_size);
+}
+
+opus_int32 opus_multistream_surround_encoder_get_size(int channels, int mapping_family)
+{
+   int nb_streams;
+   int nb_coupled_streams;
+   opus_int32 size;
+
+   if (mapping_family==0)
+   {
+      if (channels==1)
+      {
+         nb_streams=1;
+         nb_coupled_streams=0;
+      } else if (channels==2)
+      {
+         nb_streams=1;
+         nb_coupled_streams=1;
+      } else
+         return 0;
+   } else if (mapping_family==1 && channels<=8 && channels>=1)
+   {
+      nb_streams=vorbis_mappings[channels-1].nb_streams;
+      nb_coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams;
+   } else if (mapping_family==255)
+   {
+      nb_streams=channels;
+      nb_coupled_streams=0;
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+   } else if (mapping_family==254)
+   {
+      if (!validate_ambisonics(channels, &nb_streams, &nb_coupled_streams))
+         return 0;
+#endif
+   } else
+      return 0;
+   size = opus_multistream_encoder_get_size(nb_streams, nb_coupled_streams);
+   if (channels>2)
+   {
+      size += channels*(120*sizeof(opus_val32) + sizeof(opus_val32));
+   }
+   return size;
+}
+
+static int opus_multistream_encoder_init_impl(
+      OpusMSEncoder *st,
+      opus_int32 Fs,
+      int channels,
+      int streams,
+      int coupled_streams,
+      const unsigned char *mapping,
+      int application,
+      MappingType mapping_type
+)
+{
+   int coupled_size;
+   int mono_size;
+   int i, ret;
+   char *ptr;
+
+   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
+       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
+      return OPUS_BAD_ARG;
+
+   st->arch = opus_select_arch();
+   st->layout.nb_channels = channels;
+   st->layout.nb_streams = streams;
+   st->layout.nb_coupled_streams = coupled_streams;
+   if (mapping_type != MAPPING_TYPE_SURROUND)
+      st->lfe_stream = -1;
+   st->bitrate_bps = OPUS_AUTO;
+   st->application = application;
+   st->variable_duration = OPUS_FRAMESIZE_ARG;
+   for (i=0;i<st->layout.nb_channels;i++)
+      st->layout.mapping[i] = mapping[i];
+   if (!validate_layout(&st->layout))
+      return OPUS_BAD_ARG;
+   if (mapping_type == MAPPING_TYPE_SURROUND &&
+       !validate_encoder_layout(&st->layout))
+      return OPUS_BAD_ARG;
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+   if (mapping_type == MAPPING_TYPE_AMBISONICS &&
+       !validate_ambisonics(st->layout.nb_channels, NULL, NULL))
+      return OPUS_BAD_ARG;
+#endif
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+
+   for (i=0;i<st->layout.nb_coupled_streams;i++)
+   {
+      ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 2, application);
+      if(ret!=OPUS_OK)return ret;
+      if (i==st->lfe_stream)
+         opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1));
+      ptr += align(coupled_size);
+   }
+   for (;i<st->layout.nb_streams;i++)
+   {
+      ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 1, application);
+      if (i==st->lfe_stream)
+         opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1));
+      if(ret!=OPUS_OK)return ret;
+      ptr += align(mono_size);
+   }
+   if (mapping_type == MAPPING_TYPE_SURROUND)
+   {
+      OPUS_CLEAR(ms_get_preemph_mem(st), channels);
+      OPUS_CLEAR(ms_get_window_mem(st), channels*120);
+   }
+   st->mapping_type = mapping_type;
+   return OPUS_OK;
+}
+
+int opus_multistream_encoder_init(
+      OpusMSEncoder *st,
+      opus_int32 Fs,
+      int channels,
+      int streams,
+      int coupled_streams,
+      const unsigned char *mapping,
+      int application
+)
+{
+   return opus_multistream_encoder_init_impl(st, Fs, channels, streams,
+                                             coupled_streams, mapping,
+                                             application, MAPPING_TYPE_NONE);
+}
+
+int opus_multistream_surround_encoder_init(
+      OpusMSEncoder *st,
+      opus_int32 Fs,
+      int channels,
+      int mapping_family,
+      int *streams,
+      int *coupled_streams,
+      unsigned char *mapping,
+      int application
+)
+{
+   MappingType mapping_type;
+
+   if ((channels>255) || (channels<1))
+      return OPUS_BAD_ARG;
+   st->lfe_stream = -1;
+   if (mapping_family==0)
+   {
+      if (channels==1)
+      {
+         *streams=1;
+         *coupled_streams=0;
+         mapping[0]=0;
+      } else if (channels==2)
+      {
+         *streams=1;
+         *coupled_streams=1;
+         mapping[0]=0;
+         mapping[1]=1;
+      } else
+         return OPUS_UNIMPLEMENTED;
+   } else if (mapping_family==1 && channels<=8 && channels>=1)
+   {
+      int i;
+      *streams=vorbis_mappings[channels-1].nb_streams;
+      *coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams;
+      for (i=0;i<channels;i++)
+         mapping[i] = vorbis_mappings[channels-1].mapping[i];
+      if (channels>=6)
+         st->lfe_stream = *streams-1;
+   } else if (mapping_family==255)
+   {
+      int i;
+      *streams=channels;
+      *coupled_streams=0;
+      for(i=0;i<channels;i++)
+         mapping[i] = i;
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+   } else if (mapping_family==254)
+   {
+      int i;
+      if (!validate_ambisonics(channels, streams, coupled_streams))
+         return OPUS_BAD_ARG;
+      for(i = 0; i < (*streams - *coupled_streams); i++)
+         mapping[i] = i + (*coupled_streams * 2);
+      for(i = 0; i < *coupled_streams * 2; i++)
+         mapping[i + (*streams - *coupled_streams)] = i;
+#endif
+   } else
+      return OPUS_UNIMPLEMENTED;
+
+   if (channels>2 && mapping_family==1) {
+      mapping_type = MAPPING_TYPE_SURROUND;
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+   } else if (mapping_family==254)
+   {
+      mapping_type = MAPPING_TYPE_AMBISONICS;
+#endif
+   } else
+   {
+      mapping_type = MAPPING_TYPE_NONE;
+   }
+   return opus_multistream_encoder_init_impl(st, Fs, channels, *streams,
+                                             *coupled_streams, mapping,
+                                             application, mapping_type);
+}
+
+OpusMSEncoder *opus_multistream_encoder_create(
+      opus_int32 Fs,
+      int channels,
+      int streams,
+      int coupled_streams,
+      const unsigned char *mapping,
+      int application,
+      int *error
+)
+{
+   int ret;
+   OpusMSEncoder *st;
+   if ((channels>255) || (channels<1) || (coupled_streams>streams) ||
+       (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   st = (OpusMSEncoder *)opus_alloc(opus_multistream_encoder_get_size(streams, coupled_streams));
+   if (st==NULL)
+   {
+      if (error)
+         *error = OPUS_ALLOC_FAIL;
+      return NULL;
+   }
+   ret = opus_multistream_encoder_init(st, Fs, channels, streams, coupled_streams, mapping, application);
+   if (ret != OPUS_OK)
+   {
+      opus_free(st);
+      st = NULL;
+   }
+   if (error)
+      *error = ret;
+   return st;
+}
+
+OpusMSEncoder *opus_multistream_surround_encoder_create(
+      opus_int32 Fs,
+      int channels,
+      int mapping_family,
+      int *streams,
+      int *coupled_streams,
+      unsigned char *mapping,
+      int application,
+      int *error
+)
+{
+   int ret;
+   opus_int32 size;
+   OpusMSEncoder *st;
+   if ((channels>255) || (channels<1))
+   {
+      if (error)
+         *error = OPUS_BAD_ARG;
+      return NULL;
+   }
+   size = opus_multistream_surround_encoder_get_size(channels, mapping_family);
+   if (!size)
+   {
+      if (error)
+         *error = OPUS_UNIMPLEMENTED;
+      return NULL;
+   }
+   st = (OpusMSEncoder *)opus_alloc(size);
+   if (st==NULL)
+   {
+      if (error)
+         *error = OPUS_ALLOC_FAIL;
+      return NULL;
+   }
+   ret = opus_multistream_surround_encoder_init(st, Fs, channels, mapping_family, streams, coupled_streams, mapping, application);
+   if (ret != OPUS_OK)
+   {
+      opus_free(st);
+      st = NULL;
+   }
+   if (error)
+      *error = ret;
+   return st;
+}
+
+static void surround_rate_allocation(
+      OpusMSEncoder *st,
+      opus_int32 *rate,
+      int frame_size,
+      opus_int32 Fs
+      )
+{
+   int i;
+   opus_int32 channel_rate;
+   int stream_offset;
+   int lfe_offset;
+   int coupled_ratio; /* Q8 */
+   int lfe_ratio;     /* Q8 */
+   int nb_lfe;
+   int nb_uncoupled;
+   int nb_coupled;
+   int nb_normal;
+   opus_int32 channel_offset;
+   opus_int32 bitrate;
+   int total;
+
+   nb_lfe = (st->lfe_stream!=-1);
+   nb_coupled = st->layout.nb_coupled_streams;
+   nb_uncoupled = st->layout.nb_streams-nb_coupled-nb_lfe;
+   nb_normal = 2*nb_coupled + nb_uncoupled;
+
+   /* Give each non-LFE channel enough bits per channel for coding band energy. */
+   channel_offset = 40*IMAX(50, Fs/frame_size);
+
+   if (st->bitrate_bps==OPUS_AUTO)
+   {
+      bitrate = nb_normal*(channel_offset + Fs + 10000) + 8000*nb_lfe;
+   } else if (st->bitrate_bps==OPUS_BITRATE_MAX)
+   {
+      bitrate = nb_normal*300000 + nb_lfe*128000;
+   } else {
+      bitrate = st->bitrate_bps;
+   }
+
+   /* Give LFE some basic stream_channel allocation but never exceed 1/20 of the
+      total rate for the non-energy part to avoid problems at really low rate. */
+   lfe_offset = IMIN(bitrate/20, 3000) + 15*IMAX(50, Fs/frame_size);
+
+   /* We give each stream (coupled or uncoupled) a starting bitrate.
+      This models the main saving of coupled channels over uncoupled. */
+   stream_offset = (bitrate - channel_offset*nb_normal - lfe_offset*nb_lfe)/nb_normal/2;
+   stream_offset = IMAX(0, IMIN(20000, stream_offset));
+
+   /* Coupled streams get twice the mono rate after the offset is allocated. */
+   coupled_ratio = 512;
+   /* Should depend on the bitrate, for now we assume LFE gets 1/8 the bits of mono */
+   lfe_ratio = 32;
+
+   total = (nb_uncoupled<<8)         /* mono */
+         + coupled_ratio*nb_coupled /* stereo */
+         + nb_lfe*lfe_ratio;
+   channel_rate = 256*(opus_int64)(bitrate - lfe_offset*nb_lfe - stream_offset*(nb_coupled+nb_uncoupled) - channel_offset*nb_normal)/total;
+
+   for (i=0;i<st->layout.nb_streams;i++)
+   {
+      if (i<st->layout.nb_coupled_streams)
+         rate[i] = 2*channel_offset + IMAX(0, stream_offset+(channel_rate*coupled_ratio>>8));
+      else if (i!=st->lfe_stream)
+         rate[i] = channel_offset + IMAX(0, stream_offset + channel_rate);
+      else
+         rate[i] = IMAX(0, lfe_offset+(channel_rate*lfe_ratio>>8));
+   }
+}
+
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+static void ambisonics_rate_allocation(
+      OpusMSEncoder *st,
+      opus_int32 *rate,
+      int frame_size,
+      opus_int32 Fs
+      )
+{
+   int i;
+   int total_rate;
+   int directional_rate;
+   int nondirectional_rate;
+   int leftover_bits;
+
+   /* Each nondirectional channel gets (rate_ratio_num / rate_ratio_den) times
+    * as many bits as all other ambisonics channels.
+    */
+   const int rate_ratio_num = 4;
+   const int rate_ratio_den = 3;
+   const int nb_channels = st->layout.nb_streams + st->layout.nb_coupled_streams;
+   const int nb_nondirectional_channels = st->layout.nb_coupled_streams * 2 + 1;
+   const int nb_directional_channels = st->layout.nb_streams - 1;
+
+   if (st->bitrate_bps==OPUS_AUTO)
+   {
+      total_rate = (st->layout.nb_coupled_streams + st->layout.nb_streams) *
+         (Fs+60*Fs/frame_size) + st->layout.nb_streams * 15000;
+   } else if (st->bitrate_bps==OPUS_BITRATE_MAX)
+   {
+      total_rate = nb_channels * 320000;
+   } else
+   {
+      total_rate = st->bitrate_bps;
+   }
+
+   /* Let y be the directional rate, m be the num of nondirectional channels
+    *   m = (s + 1)
+    * and let p, q be integers such that the nondirectional rate is
+    *   m_rate = (p / q) * y
+    * Also let T be the total bitrate to allocate. Then
+    *   T = (n - m) * y + m * m_rate
+    * Solving for y,
+    *   y = (q * T) / (m * (p - q) + n * q)
+    */
+   directional_rate =
+      total_rate * rate_ratio_den
+      / (nb_nondirectional_channels * (rate_ratio_num - rate_ratio_den)
+       + nb_channels * rate_ratio_den);
+
+   /* Calculate the nondirectional rate.
+    *   m_rate = y * (p / q)
+    */
+   nondirectional_rate = directional_rate * rate_ratio_num / rate_ratio_den;
+
+   /* Calculate the leftover from truncation error.
+    *   leftover = T - y * (n - m) - m_rate * m
+    * Place leftover bits in omnidirectional channel.
+    */
+   leftover_bits = total_rate
+      - directional_rate * nb_directional_channels
+      - nondirectional_rate * nb_nondirectional_channels;
+
+   /* Calculate rates for each channel */
+   for (i = 0; i < st->layout.nb_streams; i++)
+   {
+      if (i < st->layout.nb_coupled_streams)
+      {
+         rate[i] = nondirectional_rate * 2;
+      } else if (i == st->layout.nb_coupled_streams)
+      {
+         rate[i] = nondirectional_rate + leftover_bits;
+      } else
+      {
+         rate[i] = directional_rate;
+      }
+   }
+}
+#endif /* ENABLE_EXPERIMENTAL_AMBISONICS */
+
+static opus_int32 rate_allocation(
+      OpusMSEncoder *st,
+      opus_int32 *rate,
+      int frame_size
+      )
+{
+   int i;
+   opus_int32 rate_sum=0;
+   opus_int32 Fs;
+   char *ptr;
+
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));
+
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+   if (st->mapping_type == MAPPING_TYPE_AMBISONICS) {
+     ambisonics_rate_allocation(st, rate, frame_size, Fs);
+   } else
+#endif
+   {
+     surround_rate_allocation(st, rate, frame_size, Fs);
+   }
+
+   for (i=0;i<st->layout.nb_streams;i++)
+   {
+      rate[i] = IMAX(rate[i], 500);
+      rate_sum += rate[i];
+   }
+   return rate_sum;
+}
+
+/* Max size in case the encoder decides to return six frames (6 x 20 ms = 120 ms) */
+#define MS_FRAME_TMP (6*1275+12)
+static int opus_multistream_encode_native
+(
+    OpusMSEncoder *st,
+    opus_copy_channel_in_func copy_channel_in,
+    const void *pcm,
+    int analysis_frame_size,
+    unsigned char *data,
+    opus_int32 max_data_bytes,
+    int lsb_depth,
+    downmix_func downmix,
+    int float_api
+)
+{
+   opus_int32 Fs;
+   int coupled_size;
+   int mono_size;
+   int s;
+   char *ptr;
+   int tot_size;
+   VARDECL(opus_val16, buf);
+   VARDECL(opus_val16, bandSMR);
+   unsigned char tmp_data[MS_FRAME_TMP];
+   OpusRepacketizer rp;
+   opus_int32 vbr;
+   const CELTMode *celt_mode;
+   opus_int32 bitrates[256];
+   opus_val16 bandLogE[42];
+   opus_val32 *mem = NULL;
+   opus_val32 *preemph_mem=NULL;
+   int frame_size;
+   opus_int32 rate_sum;
+   opus_int32 smallest_packet;
+   ALLOC_STACK;
+
+   if (st->mapping_type == MAPPING_TYPE_SURROUND)
+   {
+      preemph_mem = ms_get_preemph_mem(st);
+      mem = ms_get_window_mem(st);
+   }
+
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs));
+   opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_VBR(&vbr));
+   opus_encoder_ctl((OpusEncoder*)ptr, CELT_GET_MODE(&celt_mode));
+
+   frame_size = frame_size_select(analysis_frame_size, st->variable_duration, Fs);
+   if (frame_size <= 0)
+   {
+      RESTORE_STACK;
+      return OPUS_BAD_ARG;
+   }
+
+   /* Smallest packet the encoder can produce. */
+   smallest_packet = st->layout.nb_streams*2-1;
+   /* 100 ms needs an extra byte per stream for the ToC. */
+   if (Fs/frame_size == 10)
+     smallest_packet += st->layout.nb_streams;
+   if (max_data_bytes < smallest_packet)
+   {
+      RESTORE_STACK;
+      return OPUS_BUFFER_TOO_SMALL;
+   }
+   ALLOC(buf, 2*frame_size, opus_val16);
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+
+   ALLOC(bandSMR, 21*st->layout.nb_channels, opus_val16);
+   if (st->mapping_type == MAPPING_TYPE_SURROUND)
+   {
+      surround_analysis(celt_mode, pcm, bandSMR, mem, preemph_mem, frame_size, 120, st->layout.nb_channels, Fs, copy_channel_in, st->arch);
+   }
+
+   /* Compute bitrate allocation between streams (this could be a lot better) */
+   rate_sum = rate_allocation(st, bitrates, frame_size);
+
+   if (!vbr)
+   {
+      if (st->bitrate_bps == OPUS_AUTO)
+      {
+         max_data_bytes = IMIN(max_data_bytes, 3*rate_sum/(3*8*Fs/frame_size));
+      } else if (st->bitrate_bps != OPUS_BITRATE_MAX)
+      {
+         max_data_bytes = IMIN(max_data_bytes, IMAX(smallest_packet,
+                          3*st->bitrate_bps/(3*8*Fs/frame_size)));
+      }
+   }
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      OpusEncoder *enc;
+      enc = (OpusEncoder*)ptr;
+      if (s < st->layout.nb_coupled_streams)
+         ptr += align(coupled_size);
+      else
+         ptr += align(mono_size);
+      opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrates[s]));
+      if (st->mapping_type == MAPPING_TYPE_SURROUND)
+      {
+         opus_int32 equiv_rate;
+         equiv_rate = st->bitrate_bps;
+         if (frame_size*50 < Fs)
+            equiv_rate -= 60*(Fs/frame_size - 50)*st->layout.nb_channels;
+         if (equiv_rate > 10000*st->layout.nb_channels)
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND));
+         else if (equiv_rate > 7000*st->layout.nb_channels)
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_SUPERWIDEBAND));
+         else if (equiv_rate > 5000*st->layout.nb_channels)
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_WIDEBAND));
+         else
+            opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_NARROWBAND));
+         if (s < st->layout.nb_coupled_streams)
+         {
+            /* To preserve the spatial image, force stereo CELT on coupled streams */
+            opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
+            opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(2));
+         }
+      }
+#ifdef ENABLE_EXPERIMENTAL_AMBISONICS
+      else if (st->mapping_type == MAPPING_TYPE_AMBISONICS) {
+        opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
+      }
+#endif
+   }
+
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   /* Counting ToC */
+   tot_size = 0;
+   for (s=0;s<st->layout.nb_streams;s++)
+   {
+      OpusEncoder *enc;
+      int len;
+      int curr_max;
+      int c1, c2;
+      int ret;
+
+      opus_repacketizer_init(&rp);
+      enc = (OpusEncoder*)ptr;
+      if (s < st->layout.nb_coupled_streams)
+      {
+         int i;
+         int left, right;
+         left = get_left_channel(&st->layout, s, -1);
+         right = get_right_channel(&st->layout, s, -1);
+         (*copy_channel_in)(buf, 2,
+            pcm, st->layout.nb_channels, left, frame_size);
+         (*copy_channel_in)(buf+1, 2,
+            pcm, st->layout.nb_channels, right, frame_size);
+         ptr += align(coupled_size);
+         if (st->mapping_type == MAPPING_TYPE_SURROUND)
+         {
+            for (i=0;i<21;i++)
+            {
+               bandLogE[i] = bandSMR[21*left+i];
+               bandLogE[21+i] = bandSMR[21*right+i];
+            }
+         }
+         c1 = left;
+         c2 = right;
+      } else {
+         int i;
+         int chan = get_mono_channel(&st->layout, s, -1);
+         (*copy_channel_in)(buf, 1,
+            pcm, st->layout.nb_channels, chan, frame_size);
+         ptr += align(mono_size);
+         if (st->mapping_type == MAPPING_TYPE_SURROUND)
+         {
+            for (i=0;i<21;i++)
+               bandLogE[i] = bandSMR[21*chan+i];
+         }
+         c1 = chan;
+         c2 = -1;
+      }
+      if (st->mapping_type == MAPPING_TYPE_SURROUND)
+         opus_encoder_ctl(enc, OPUS_SET_ENERGY_MASK(bandLogE));
+      /* number of bytes left (+Toc) */
+      curr_max = max_data_bytes - tot_size;
+      /* Reserve one byte for the last stream and two for the others */
+      curr_max -= IMAX(0,2*(st->layout.nb_streams-s-1)-1);
+      /* For 100 ms, reserve an extra byte per stream for the ToC */
+      if (Fs/frame_size == 10)
+        curr_max -= st->layout.nb_streams-s-1;
+      curr_max = IMIN(curr_max,MS_FRAME_TMP);
+      /* Repacketizer will add one or two bytes for self-delimited frames */
+      if (s != st->layout.nb_streams-1) curr_max -=  curr_max>253 ? 2 : 1;
+      if (!vbr && s == st->layout.nb_streams-1)
+         opus_encoder_ctl(enc, OPUS_SET_BITRATE(curr_max*(8*Fs/frame_size)));
+      len = opus_encode_native(enc, buf, frame_size, tmp_data, curr_max, lsb_depth,
+            pcm, analysis_frame_size, c1, c2, st->layout.nb_channels, downmix, float_api);
+      if (len<0)
+      {
+         RESTORE_STACK;
+         return len;
+      }
+      /* We need to use the repacketizer to add the self-delimiting lengths
+         while taking into account the fact that the encoder can now return
+         more than one frame at a time (e.g. 60 ms CELT-only) */
+      ret = opus_repacketizer_cat(&rp, tmp_data, len);
+      /* If the opus_repacketizer_cat() fails, then something's seriously wrong
+         with the encoder. */
+      if (ret != OPUS_OK)
+      {
+         RESTORE_STACK;
+         return OPUS_INTERNAL_ERROR;
+      }
+      len = opus_repacketizer_out_range_impl(&rp, 0, opus_repacketizer_get_nb_frames(&rp),
+            data, max_data_bytes-tot_size, s != st->layout.nb_streams-1, !vbr && s == st->layout.nb_streams-1);
+      data += len;
+      tot_size += len;
+   }
+   /*printf("\n");*/
+   RESTORE_STACK;
+   return tot_size;
+}
+
+#if !defined(DISABLE_FLOAT_API)
+static void opus_copy_channel_in_float(
+  opus_val16 *dst,
+  int dst_stride,
+  const void *src,
+  int src_stride,
+  int src_channel,
+  int frame_size
+)
+{
+   const float *float_src;
+   opus_int32 i;
+   float_src = (const float *)src;
+   for (i=0;i<frame_size;i++)
+#if defined(FIXED_POINT)
+      dst[i*dst_stride] = FLOAT2INT16(float_src[i*src_stride+src_channel]);
+#else
+      dst[i*dst_stride] = float_src[i*src_stride+src_channel];
+#endif
+}
+#endif
+
+static void opus_copy_channel_in_short(
+  opus_val16 *dst,
+  int dst_stride,
+  const void *src,
+  int src_stride,
+  int src_channel,
+  int frame_size
+)
+{
+   const opus_int16 *short_src;
+   opus_int32 i;
+   short_src = (const opus_int16 *)src;
+   for (i=0;i<frame_size;i++)
+#if defined(FIXED_POINT)
+      dst[i*dst_stride] = short_src[i*src_stride+src_channel];
+#else
+      dst[i*dst_stride] = (1/32768.f)*short_src[i*src_stride+src_channel];
+#endif
+}
+
+
+#ifdef FIXED_POINT
+int opus_multistream_encode(
+    OpusMSEncoder *st,
+    const opus_val16 *pcm,
+    int frame_size,
+    unsigned char *data,
+    opus_int32 max_data_bytes
+)
+{
+   return opus_multistream_encode_native(st, opus_copy_channel_in_short,
+      pcm, frame_size, data, max_data_bytes, 16, downmix_int, 0);
+}
+
+#ifndef DISABLE_FLOAT_API
+int opus_multistream_encode_float(
+    OpusMSEncoder *st,
+    const float *pcm,
+    int frame_size,
+    unsigned char *data,
+    opus_int32 max_data_bytes
+)
+{
+   return opus_multistream_encode_native(st, opus_copy_channel_in_float,
+      pcm, frame_size, data, max_data_bytes, 16, downmix_float, 1);
+}
+#endif
+
+#else
+
+int opus_multistream_encode_float
+(
+    OpusMSEncoder *st,
+    const opus_val16 *pcm,
+    int frame_size,
+    unsigned char *data,
+    opus_int32 max_data_bytes
+)
+{
+   return opus_multistream_encode_native(st, opus_copy_channel_in_float,
+      pcm, frame_size, data, max_data_bytes, 24, downmix_float, 1);
+}
+
+int opus_multistream_encode(
+    OpusMSEncoder *st,
+    const opus_int16 *pcm,
+    int frame_size,
+    unsigned char *data,
+    opus_int32 max_data_bytes
+)
+{
+   return opus_multistream_encode_native(st, opus_copy_channel_in_short,
+      pcm, frame_size, data, max_data_bytes, 16, downmix_int, 0);
+}
+#endif
+
+int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...)
+{
+   va_list ap;
+   int coupled_size, mono_size;
+   char *ptr;
+   int ret = OPUS_OK;
+
+   va_start(ap, request);
+
+   coupled_size = opus_encoder_get_size(2);
+   mono_size = opus_encoder_get_size(1);
+   ptr = (char*)st + align(sizeof(OpusMSEncoder));
+   switch (request)
+   {
+   case OPUS_SET_BITRATE_REQUEST:
+   {
+      opus_int32 value = va_arg(ap, opus_int32);
+      if (value != OPUS_AUTO && value != OPUS_BITRATE_MAX)
+      {
+         if (value <= 0)
+            goto bad_arg;
+         value = IMIN(300000*st->layout.nb_channels, IMAX(500*st->layout.nb_channels, value));
+      }
+      st->bitrate_bps = value;
+   }
+   break;
+   case OPUS_GET_BITRATE_REQUEST:
+   {
+      int s;
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value = 0;
+      for (s=0;s<st->layout.nb_streams;s++)
+      {
+         opus_int32 rate;
+         OpusEncoder *enc;
+         enc = (OpusEncoder*)ptr;
+         if (s < st->layout.nb_coupled_streams)
+            ptr += align(coupled_size);
+         else
+            ptr += align(mono_size);
+         opus_encoder_ctl(enc, request, &rate);
+         *value += rate;
+      }
+   }
+   break;
+   case OPUS_GET_LSB_DEPTH_REQUEST:
+   case OPUS_GET_VBR_REQUEST:
+   case OPUS_GET_APPLICATION_REQUEST:
+   case OPUS_GET_BANDWIDTH_REQUEST:
+   case OPUS_GET_COMPLEXITY_REQUEST:
+   case OPUS_GET_PACKET_LOSS_PERC_REQUEST:
+   case OPUS_GET_DTX_REQUEST:
+   case OPUS_GET_VOICE_RATIO_REQUEST:
+   case OPUS_GET_VBR_CONSTRAINT_REQUEST:
+   case OPUS_GET_SIGNAL_REQUEST:
+   case OPUS_GET_LOOKAHEAD_REQUEST:
+   case OPUS_GET_SAMPLE_RATE_REQUEST:
+   case OPUS_GET_INBAND_FEC_REQUEST:
+   case OPUS_GET_FORCE_CHANNELS_REQUEST:
+   case OPUS_GET_PREDICTION_DISABLED_REQUEST:
+   case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
+   {
+      OpusEncoder *enc;
+      /* For int32* GET params, just query the first stream */
+      opus_int32 *value = va_arg(ap, opus_int32*);
+      enc = (OpusEncoder*)ptr;
+      ret = opus_encoder_ctl(enc, request, value);
+   }
+   break;
+   case OPUS_GET_FINAL_RANGE_REQUEST:
+   {
+      int s;
+      opus_uint32 *value = va_arg(ap, opus_uint32*);
+      opus_uint32 tmp;
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      *value=0;
+      for (s=0;s<st->layout.nb_streams;s++)
+      {
+         OpusEncoder *enc;
+         enc = (OpusEncoder*)ptr;
+         if (s < st->layout.nb_coupled_streams)
+            ptr += align(coupled_size);
+         else
+            ptr += align(mono_size);
+         ret = opus_encoder_ctl(enc, request, &tmp);
+         if (ret != OPUS_OK) break;
+         *value ^= tmp;
+      }
+   }
+   break;
+   case OPUS_SET_LSB_DEPTH_REQUEST:
+   case OPUS_SET_COMPLEXITY_REQUEST:
+   case OPUS_SET_VBR_REQUEST:
+   case OPUS_SET_VBR_CONSTRAINT_REQUEST:
+   case OPUS_SET_MAX_BANDWIDTH_REQUEST:
+   case OPUS_SET_BANDWIDTH_REQUEST:
+   case OPUS_SET_SIGNAL_REQUEST:
+   case OPUS_SET_APPLICATION_REQUEST:
+   case OPUS_SET_INBAND_FEC_REQUEST:
+   case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
+   case OPUS_SET_DTX_REQUEST:
+   case OPUS_SET_FORCE_MODE_REQUEST:
+   case OPUS_SET_FORCE_CHANNELS_REQUEST:
+   case OPUS_SET_PREDICTION_DISABLED_REQUEST:
+   case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
+   {
+      int s;
+      /* This works for int32 params */
+      opus_int32 value = va_arg(ap, opus_int32);
+      for (s=0;s<st->layout.nb_streams;s++)
+      {
+         OpusEncoder *enc;
+
+         enc = (OpusEncoder*)ptr;
+         if (s < st->layout.nb_coupled_streams)
+            ptr += align(coupled_size);
+         else
+            ptr += align(mono_size);
+         ret = opus_encoder_ctl(enc, request, value);
+         if (ret != OPUS_OK)
+            break;
+      }
+   }
+   break;
+   case OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST:
+   {
+      int s;
+      opus_int32 stream_id;
+      OpusEncoder **value;
+      stream_id = va_arg(ap, opus_int32);
+      if (stream_id<0 || stream_id >= st->layout.nb_streams)
+         ret = OPUS_BAD_ARG;
+      value = va_arg(ap, OpusEncoder**);
+      if (!value)
+      {
+         goto bad_arg;
+      }
+      for (s=0;s<stream_id;s++)
+      {
+         if (s < st->layout.nb_coupled_streams)
+            ptr += align(coupled_size);
+         else
+            ptr += align(mono_size);
+      }
+      *value = (OpusEncoder*)ptr;
+   }
+   break;
+   case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST:
+   {
+       opus_int32 value = va_arg(ap, opus_int32);
+       st->variable_duration = value;
+   }
+   break;
+   case OPUS_GET_EXPERT_FRAME_DURATION_REQUEST:
+   {
+       opus_int32 *value = va_arg(ap, opus_int32*);
+       if (!value)
+       {
+          goto bad_arg;
+       }
+       *value = st->variable_duration;
+   }
+   break;
+   case OPUS_RESET_STATE:
+   {
+      int s;
+      if (st->mapping_type == MAPPING_TYPE_SURROUND)
+      {
+         OPUS_CLEAR(ms_get_preemph_mem(st), st->layout.nb_channels);
+         OPUS_CLEAR(ms_get_window_mem(st), st->layout.nb_channels*120);
+      }
+      for (s=0;s<st->layout.nb_streams;s++)
+      {
+         OpusEncoder *enc;
+         enc = (OpusEncoder*)ptr;
+         if (s < st->layout.nb_coupled_streams)
+            ptr += align(coupled_size);
+         else
+            ptr += align(mono_size);
+         ret = opus_encoder_ctl(enc, OPUS_RESET_STATE);
+         if (ret != OPUS_OK)
+            break;
+      }
+   }
+   break;
+   default:
+      ret = OPUS_UNIMPLEMENTED;
+      break;
+   }
+
+   va_end(ap);
+   return ret;
+bad_arg:
+   va_end(ap);
+   return OPUS_BAD_ARG;
+}
+
+void opus_multistream_encoder_destroy(OpusMSEncoder *st)
+{
+    opus_free(st);
+}
diff --git a/opus/src/opus_private.h b/opus/src/opus_private.h
new file mode 100644 (file)
index 0000000..a731cc5
--- /dev/null
@@ -0,0 +1,126 @@
+/* Copyright (c) 2012 Xiph.Org Foundation
+   Written by 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.
+
+   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 OPUS_PRIVATE_H
+#define OPUS_PRIVATE_H
+
+#include "arch.h"
+#include "opus.h"
+#include "celt.h"
+
+#include <stddef.h> /* offsetof */
+
+struct OpusRepacketizer {
+   unsigned char toc;
+   int nb_frames;
+   const unsigned char *frames[48];
+   opus_int16 len[48];
+   int framesize;
+};
+
+typedef struct ChannelLayout {
+   int nb_channels;
+   int nb_streams;
+   int nb_coupled_streams;
+   unsigned char mapping[256];
+} ChannelLayout;
+
+int validate_layout(const ChannelLayout *layout);
+int get_left_channel(const ChannelLayout *layout, int stream_id, int prev);
+int get_right_channel(const ChannelLayout *layout, int stream_id, int prev);
+int get_mono_channel(const ChannelLayout *layout, int stream_id, int prev);
+
+
+
+#define MODE_SILK_ONLY          1000
+#define MODE_HYBRID             1001
+#define MODE_CELT_ONLY          1002
+
+#define OPUS_SET_VOICE_RATIO_REQUEST         11018
+#define OPUS_GET_VOICE_RATIO_REQUEST         11019
+
+/** Configures the encoder's expected percentage of voice
+  * opposed to music or other signals.
+  *
+  * @note This interface is currently more aspiration than actuality. It's
+  * ultimately expected to bias an automatic signal classifier, but it currently
+  * just shifts the static bitrate to mode mapping around a little bit.
+  *
+  * @param[in] x <tt>int</tt>:   Voice percentage in the range 0-100, inclusive.
+  * @hideinitializer */
+#define OPUS_SET_VOICE_RATIO(x) OPUS_SET_VOICE_RATIO_REQUEST, __opus_check_int(x)
+/** Gets the encoder's configured voice ratio value, @see OPUS_SET_VOICE_RATIO
+  *
+  * @param[out] x <tt>int*</tt>:  Voice percentage in the range 0-100, inclusive.
+  * @hideinitializer */
+#define OPUS_GET_VOICE_RATIO(x) OPUS_GET_VOICE_RATIO_REQUEST, __opus_check_int_ptr(x)
+
+
+#define OPUS_SET_FORCE_MODE_REQUEST    11002
+#define OPUS_SET_FORCE_MODE(x) OPUS_SET_FORCE_MODE_REQUEST, __opus_check_int(x)
+
+typedef void (*downmix_func)(const void *, opus_val32 *, int, int, int, int, int);
+void downmix_float(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C);
+void downmix_int(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C);
+
+int encode_size(int size, unsigned char *data);
+
+opus_int32 frame_size_select(opus_int32 frame_size, int variable_duration, opus_int32 Fs);
+
+opus_int32 opus_encode_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
+      unsigned char *data, opus_int32 out_data_bytes, int lsb_depth,
+      const void *analysis_pcm, opus_int32 analysis_size, int c1, int c2,
+      int analysis_channels, downmix_func downmix, int float_api);
+
+int opus_decode_native(OpusDecoder *st, const unsigned char *data, opus_int32 len,
+      opus_val16 *pcm, int frame_size, int decode_fec, int self_delimited,
+      opus_int32 *packet_offset, int soft_clip);
+
+/* Make sure everything is properly aligned. */
+static OPUS_INLINE int align(int i)
+{
+    struct foo {char c; union { void* p; opus_int32 i; opus_val32 v; } u;};
+
+    unsigned int alignment = offsetof(struct foo, u);
+
+    /* Optimizing compilers should optimize div and multiply into and
+       for all sensible alignment values. */
+    return ((i + alignment - 1) / alignment) * alignment;
+}
+
+int opus_packet_parse_impl(const unsigned char *data, opus_int32 len,
+      int self_delimited, unsigned char *out_toc,
+      const unsigned char *frames[48], opus_int16 size[48],
+      int *payload_offset, opus_int32 *packet_offset);
+
+opus_int32 opus_repacketizer_out_range_impl(OpusRepacketizer *rp, int begin, int end,
+      unsigned char *data, opus_int32 maxlen, int self_delimited, int pad);
+
+int pad_frame(unsigned char *data, opus_int32 len, opus_int32 new_len);
+
+#endif /* OPUS_PRIVATE_H */
diff --git a/opus/src/repacketizer.c b/opus/src/repacketizer.c
new file mode 100644 (file)
index 0000000..c80ee7f
--- /dev/null
@@ -0,0 +1,348 @@
+/* Copyright (c) 2011 Xiph.Org Foundation
+   Written by 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.
+
+   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.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "opus.h"
+#include "opus_private.h"
+#include "os_support.h"
+
+
+int opus_repacketizer_get_size(void)
+{
+   return sizeof(OpusRepacketizer);
+}
+
+OpusRepacketizer *opus_repacketizer_init(OpusRepacketizer *rp)
+{
+   rp->nb_frames = 0;
+   return rp;
+}
+
+OpusRepacketizer *opus_repacketizer_create(void)
+{
+   OpusRepacketizer *rp;
+   rp=(OpusRepacketizer *)opus_alloc(opus_repacketizer_get_size());
+   if(rp==NULL)return NULL;
+   return opus_repacketizer_init(rp);
+}
+
+void opus_repacketizer_destroy(OpusRepacketizer *rp)
+{
+   opus_free(rp);
+}
+
+static int opus_repacketizer_cat_impl(OpusRepacketizer *rp, const unsigned char *data, opus_int32 len, int self_delimited)
+{
+   unsigned char tmp_toc;
+   int curr_nb_frames,ret;
+   /* Set of check ToC */
+   if (len<1) return OPUS_INVALID_PACKET;
+   if (rp->nb_frames == 0)
+   {
+      rp->toc = data[0];
+      rp->framesize = opus_packet_get_samples_per_frame(data, 8000);
+   } else if ((rp->toc&0xFC) != (data[0]&0xFC))
+   {
+      /*fprintf(stderr, "toc mismatch: 0x%x vs 0x%x\n", rp->toc, data[0]);*/
+      return OPUS_INVALID_PACKET;
+   }
+   curr_nb_frames = opus_packet_get_nb_frames(data, len);
+   if(curr_nb_frames<1) return OPUS_INVALID_PACKET;
+
+   /* Check the 120 ms maximum packet size */
+   if ((curr_nb_frames+rp->nb_frames)*rp->framesize > 960)
+   {
+      return OPUS_INVALID_PACKET;
+   }
+
+   ret=opus_packet_parse_impl(data, len, self_delimited, &tmp_toc, &rp->frames[rp->nb_frames], &rp->len[rp->nb_frames], NULL, NULL);
+   if(ret<1)return ret;
+
+   rp->nb_frames += curr_nb_frames;
+   return OPUS_OK;
+}
+
+int opus_repacketizer_cat(OpusRepacketizer *rp, const unsigned char *data, opus_int32 len)
+{
+   return opus_repacketizer_cat_impl(rp, data, len, 0);
+}
+
+int opus_repacketizer_get_nb_frames(OpusRepacketizer *rp)
+{
+   return rp->nb_frames;
+}
+
+opus_int32 opus_repacketizer_out_range_impl(OpusRepacketizer *rp, int begin, int end,
+      unsigned char *data, opus_int32 maxlen, int self_delimited, int pad)
+{
+   int i, count;
+   opus_int32 tot_size;
+   opus_int16 *len;
+   const unsigned char **frames;
+   unsigned char * ptr;
+
+   if (begin<0 || begin>=end || end>rp->nb_frames)
+   {
+      /*fprintf(stderr, "%d %d %d\n", begin, end, rp->nb_frames);*/
+      return OPUS_BAD_ARG;
+   }
+   count = end-begin;
+
+   len = rp->len+begin;
+   frames = rp->frames+begin;
+   if (self_delimited)
+      tot_size = 1 + (len[count-1]>=252);
+   else
+      tot_size = 0;
+
+   ptr = data;
+   if (count==1)
+   {
+      /* Code 0 */
+      tot_size += len[0]+1;
+      if (tot_size > maxlen)
+         return OPUS_BUFFER_TOO_SMALL;
+      *ptr++ = rp->toc&0xFC;
+   } else if (count==2)
+   {
+      if (len[1] == len[0])
+      {
+         /* Code 1 */
+         tot_size += 2*len[0]+1;
+         if (tot_size > maxlen)
+            return OPUS_BUFFER_TOO_SMALL;
+         *ptr++ = (rp->toc&0xFC) | 0x1;
+      } else {
+         /* Code 2 */
+         tot_size += len[0]+len[1]+2+(len[0]>=252);
+         if (tot_size > maxlen)
+            return OPUS_BUFFER_TOO_SMALL;
+         *ptr++ = (rp->toc&0xFC) | 0x2;
+         ptr += encode_size(len[0], ptr);
+      }
+   }
+   if (count > 2 || (pad && tot_size < maxlen))
+   {
+      /* Code 3 */
+      int vbr;
+      int pad_amount=0;
+
+      /* Restart the process for the padding case */
+      ptr = data;
+      if (self_delimited)
+         tot_size = 1 + (len[count-1]>=252);
+      else
+         tot_size = 0;
+      vbr = 0;
+      for (i=1;i<count;i++)
+      {
+         if (len[i] != len[0])
+         {
+            vbr=1;
+            break;
+         }
+      }
+      if (vbr)
+      {
+         tot_size += 2;
+         for (i=0;i<count-1;i++)
+            tot_size += 1 + (len[i]>=252) + len[i];
+         tot_size += len[count-1];
+
+         if (tot_size > maxlen)
+            return OPUS_BUFFER_TOO_SMALL;
+         *ptr++ = (rp->toc&0xFC) | 0x3;
+         *ptr++ = count | 0x80;
+      } else {
+         tot_size += count*len[0]+2;
+         if (tot_size > maxlen)
+            return OPUS_BUFFER_TOO_SMALL;
+         *ptr++ = (rp->toc&0xFC) | 0x3;
+         *ptr++ = count;
+      }
+      pad_amount = pad ? (maxlen-tot_size) : 0;
+      if (pad_amount != 0)
+      {
+         int nb_255s;
+         data[1] |= 0x40;
+         nb_255s = (pad_amount-1)/255;
+         for (i=0;i<nb_255s;i++)
+            *ptr++ = 255;
+         *ptr++ = pad_amount-255*nb_255s-1;
+         tot_size += pad_amount;
+      }
+      if (vbr)
+      {
+         for (i=0;i<count-1;i++)
+            ptr += encode_size(len[i], ptr);
+      }
+   }
+   if (self_delimited) {
+      int sdlen = encode_size(len[count-1], ptr);
+      ptr += sdlen;
+   }
+   /* Copy the actual data */
+   for (i=0;i<count;i++)
+   {
+      /* Using OPUS_MOVE() instead of OPUS_COPY() in case we're doing in-place
+         padding from opus_packet_pad or opus_packet_unpad(). */
+      celt_assert(frames[i] + len[i] <= data || ptr <= frames[i]);
+      OPUS_MOVE(ptr, frames[i], len[i]);
+      ptr += len[i];
+   }
+   if (pad)
+   {
+      /* Fill padding with zeros. */
+      while (ptr<data+maxlen)
+         *ptr++=0;
+   }
+   return tot_size;
+}
+
+opus_int32 opus_repacketizer_out_range(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen)
+{
+   return opus_repacketizer_out_range_impl(rp, begin, end, data, maxlen, 0, 0);
+}
+
+opus_int32 opus_repacketizer_out(OpusRepacketizer *rp, unsigned char *data, opus_int32 maxlen)
+{
+   return opus_repacketizer_out_range_impl(rp, 0, rp->nb_frames, data, maxlen, 0, 0);
+}
+
+int opus_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len)
+{
+   OpusRepacketizer rp;
+   opus_int32 ret;
+   if (len < 1)
+      return OPUS_BAD_ARG;
+   if (len==new_len)
+      return OPUS_OK;
+   else if (len > new_len)
+      return OPUS_BAD_ARG;
+   opus_repacketizer_init(&rp);
+   /* Moving payload to the end of the packet so we can do in-place padding */
+   OPUS_MOVE(data+new_len-len, data, len);
+   ret = opus_repacketizer_cat(&rp, data+new_len-len, len);
+   if (ret != OPUS_OK)
+      return ret;
+   ret = opus_repacketizer_out_range_impl(&rp, 0, rp.nb_frames, data, new_len, 0, 1);
+   if (ret > 0)
+      return OPUS_OK;
+   else
+      return ret;
+}
+
+opus_int32 opus_packet_unpad(unsigned char *data, opus_int32 len)
+{
+   OpusRepacketizer rp;
+   opus_int32 ret;
+   if (len < 1)
+      return OPUS_BAD_ARG;
+   opus_repacketizer_init(&rp);
+   ret = opus_repacketizer_cat(&rp, data, len);
+   if (ret < 0)
+      return ret;
+   ret = opus_repacketizer_out_range_impl(&rp, 0, rp.nb_frames, data, len, 0, 0);
+   celt_assert(ret > 0 && ret <= len);
+   return ret;
+}
+
+int opus_multistream_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len, int nb_streams)
+{
+   int s;
+   int count;
+   unsigned char toc;
+   opus_int16 size[48];
+   opus_int32 packet_offset;
+   opus_int32 amount;
+
+   if (len < 1)
+      return OPUS_BAD_ARG;
+   if (len==new_len)
+      return OPUS_OK;
+   else if (len > new_len)
+      return OPUS_BAD_ARG;
+   amount = new_len - len;
+   /* Seek to last stream */
+   for (s=0;s<nb_streams-1;s++)
+   {
+      if (len<=0)
+         return OPUS_INVALID_PACKET;
+      count = opus_packet_parse_impl(data, len, 1, &toc, NULL,
+                                     size, NULL, &packet_offset);
+      if (count<0)
+         return count;
+      data += packet_offset;
+      len -= packet_offset;
+   }
+   return opus_packet_pad(data, len, len+amount);
+}
+
+opus_int32 opus_multistream_packet_unpad(unsigned char *data, opus_int32 len, int nb_streams)
+{
+   int s;
+   unsigned char toc;
+   opus_int16 size[48];
+   opus_int32 packet_offset;
+   OpusRepacketizer rp;
+   unsigned char *dst;
+   opus_int32 dst_len;
+
+   if (len < 1)
+      return OPUS_BAD_ARG;
+   dst = data;
+   dst_len = 0;
+   /* Unpad all frames */
+   for (s=0;s<nb_streams;s++)
+   {
+      opus_int32 ret;
+      int self_delimited = s!=nb_streams-1;
+      if (len<=0)
+         return OPUS_INVALID_PACKET;
+      opus_repacketizer_init(&rp);
+      ret = opus_packet_parse_impl(data, len, self_delimited, &toc, NULL,
+                                     size, NULL, &packet_offset);
+      if (ret<0)
+         return ret;
+      ret = opus_repacketizer_cat_impl(&rp, data, packet_offset, self_delimited);
+      if (ret < 0)
+         return ret;
+      ret = opus_repacketizer_out_range_impl(&rp, 0, rp.nb_frames, dst, len, self_delimited, 0);
+      if (ret < 0)
+         return ret;
+      else
+         dst_len += ret;
+      dst += ret;
+      data += packet_offset;
+      len -= packet_offset;
+   }
+   return dst_len;
+}
+
diff --git a/opus/src/tansig_table.h b/opus/src/tansig_table.h
new file mode 100644 (file)
index 0000000..c76f844
--- /dev/null
@@ -0,0 +1,45 @@
+/* This file is auto-generated by gen_tables */
+
+static const float tansig_table[201] = {
+0.000000f, 0.039979f, 0.079830f, 0.119427f, 0.158649f,
+0.197375f, 0.235496f, 0.272905f, 0.309507f, 0.345214f,
+0.379949f, 0.413644f, 0.446244f, 0.477700f, 0.507977f,
+0.537050f, 0.564900f, 0.591519f, 0.616909f, 0.641077f,
+0.664037f, 0.685809f, 0.706419f, 0.725897f, 0.744277f,
+0.761594f, 0.777888f, 0.793199f, 0.807569f, 0.821040f,
+0.833655f, 0.845456f, 0.856485f, 0.866784f, 0.876393f,
+0.885352f, 0.893698f, 0.901468f, 0.908698f, 0.915420f,
+0.921669f, 0.927473f, 0.932862f, 0.937863f, 0.942503f,
+0.946806f, 0.950795f, 0.954492f, 0.957917f, 0.961090f,
+0.964028f, 0.966747f, 0.969265f, 0.971594f, 0.973749f,
+0.975743f, 0.977587f, 0.979293f, 0.980869f, 0.982327f,
+0.983675f, 0.984921f, 0.986072f, 0.987136f, 0.988119f,
+0.989027f, 0.989867f, 0.990642f, 0.991359f, 0.992020f,
+0.992631f, 0.993196f, 0.993718f, 0.994199f, 0.994644f,
+0.995055f, 0.995434f, 0.995784f, 0.996108f, 0.996407f,
+0.996682f, 0.996937f, 0.997172f, 0.997389f, 0.997590f,
+0.997775f, 0.997946f, 0.998104f, 0.998249f, 0.998384f,
+0.998508f, 0.998623f, 0.998728f, 0.998826f, 0.998916f,
+0.999000f, 0.999076f, 0.999147f, 0.999213f, 0.999273f,
+0.999329f, 0.999381f, 0.999428f, 0.999472f, 0.999513f,
+0.999550f, 0.999585f, 0.999617f, 0.999646f, 0.999673f,
+0.999699f, 0.999722f, 0.999743f, 0.999763f, 0.999781f,
+0.999798f, 0.999813f, 0.999828f, 0.999841f, 0.999853f,
+0.999865f, 0.999875f, 0.999885f, 0.999893f, 0.999902f,
+0.999909f, 0.999916f, 0.999923f, 0.999929f, 0.999934f,
+0.999939f, 0.999944f, 0.999948f, 0.999952f, 0.999956f,
+0.999959f, 0.999962f, 0.999965f, 0.999968f, 0.999970f,
+0.999973f, 0.999975f, 0.999977f, 0.999978f, 0.999980f,
+0.999982f, 0.999983f, 0.999984f, 0.999986f, 0.999987f,
+0.999988f, 0.999989f, 0.999990f, 0.999990f, 0.999991f,
+0.999992f, 0.999992f, 0.999993f, 0.999994f, 0.999994f,
+0.999994f, 0.999995f, 0.999995f, 0.999996f, 0.999996f,
+0.999996f, 0.999997f, 0.999997f, 0.999997f, 0.999997f,
+0.999997f, 0.999998f, 0.999998f, 0.999998f, 0.999998f,
+0.999998f, 0.999998f, 0.999999f, 0.999999f, 0.999999f,
+0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f,
+0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f,
+1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f,
+1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f,
+1.000000f,
+};
diff --git a/pdcurses/pdcurses.def b/pdcurses/pdcurses.def
new file mode 100644 (file)
index 0000000..440adda
--- /dev/null
@@ -0,0 +1,375 @@
+EXPORTS
+    LINES
+    COLS
+    stdscr
+    curscr
+    SP
+    Mouse_status
+    COLORS
+    COLOR_PAIRS
+    TABSIZE
+    acs_map
+    ttytype
+    addch
+    addchnstr
+    addchstr
+    addnstr
+    addstr
+    attroff
+    attron
+    attrset
+    attr_get
+    attr_off
+    attr_on
+    attr_set
+    baudrate
+    beep
+    bkgd
+    bkgdset
+    border
+    box
+    can_change_color
+    cbreak
+    chgat
+    clearok
+    clear
+    clrtobot
+    clrtoeol
+    color_content
+    color_set
+    copywin
+    curs_set
+    def_prog_mode
+    def_shell_mode
+    delay_output
+    delch
+    deleteln
+    delscreen
+    delwin
+    derwin
+    doupdate
+    dupwin
+    echochar
+    echo
+    endwin
+    erasechar
+    erase
+    filter
+    flash
+    flushinp
+    getbkgd
+    getnstr
+    getstr
+    getwin
+    halfdelay
+    has_colors
+    has_ic
+    has_il
+    hline
+    idcok
+    idlok
+    immedok
+    inchnstr
+    inchstr
+    inch
+    init_color
+    init_pair
+    initscr
+    innstr
+    insch
+    insdelln
+    insertln
+    insnstr
+    insstr
+    instr
+    intrflush
+    isendwin
+    is_linetouched
+    is_wintouched
+    keyname
+    keypad
+    killchar
+    leaveok
+    longname
+    meta
+    move
+    mvaddch
+    mvaddchnstr
+    mvaddchstr
+    mvaddnstr
+    mvaddstr
+    mvchgat
+    mvcur
+    mvdelch
+    mvderwin
+    mvgetch
+    mvgetnstr
+    mvgetstr
+    mvhline
+    mvinch
+    mvinchnstr
+    mvinchstr
+    mvinnstr
+    mvinsch
+    mvinsnstr
+    mvinsstr
+    mvinstr
+    mvprintw
+    mvscanw
+    mvvline
+    mvwaddchnstr
+    mvwaddchstr
+    mvwaddch
+    mvwaddnstr
+    mvwaddstr
+    mvwchgat
+    mvwdelch
+    mvwgetch
+    mvwgetnstr
+    mvwgetstr
+    mvwhline
+    mvwinchnstr
+    mvwinchstr
+    mvwinch
+    mvwinnstr
+    mvwinsch
+    mvwinsnstr
+    mvwinsstr
+    mvwinstr
+    mvwin
+    mvwprintw
+    mvwscanw
+    mvwvline
+    napms
+    newpad
+    newterm
+    newwin
+    nl
+    nocbreak
+    nodelay
+    noecho
+    nonl
+    noqiflush
+    noraw
+    notimeout
+    overlay
+    overwrite
+    pair_content
+    pechochar
+    pnoutrefresh
+    prefresh
+    printw
+    putwin
+    qiflush
+    raw
+    redrawwin
+    refresh
+    reset_prog_mode
+    reset_shell_mode
+    resetty
+    ripoffline
+    savetty
+    scanw
+    scr_dump
+    scr_init
+    scrl
+    scrollok
+    scroll
+    scr_restore
+    scr_set
+    setscrreg
+    setsyx
+    set_term
+    slk_attroff
+    slk_attr_off
+    slk_attron
+    slk_attr_on
+    slk_attrset
+    slk_attr_set
+    slk_clear
+    slk_color
+    slk_init
+    slk_label
+    slk_noutrefresh
+    slk_refresh
+    slk_restore
+    slk_set
+    slk_touch
+    standend
+    standout
+    start_color
+    subpad
+    subwin
+    syncok
+    termattrs
+    term_attrs
+    termname
+    timeout
+    touchline
+    touchwin
+    typeahead
+    untouchwin
+    use_env
+    vidattr
+    vid_attr
+    vidputs
+    vid_puts
+    vline
+    vw_printw
+    vwprintw
+    vw_scanw
+    vwscanw
+    waddchnstr
+    waddchstr
+    waddch
+    waddnstr
+    waddstr
+    wattroff
+    wattron
+    wattrset
+    wattr_get
+    wattr_off
+    wattr_on
+    wattr_set
+    wbkgdset
+    wbkgd
+    wborder
+    wchgat
+    wclear
+    wclrtobot
+    wclrtoeol
+    wcolor_set
+    wcursyncup
+    wdelch
+    wdeleteln
+    wechochar
+    werase
+    wgetch
+    wgetnstr
+    wgetstr
+    whline
+    winchnstr
+    winchstr
+    winch
+    winnstr
+    winsch
+    winsdelln
+    winsertln
+    winsnstr
+    winsstr
+    winstr
+    wmove
+    wnoutrefresh
+    wprintw
+    wredrawln
+    wrefresh
+    wscanw
+    wscrl
+    wsetscrreg
+    wstandend
+    wstandout
+    wsyncdown
+    wsyncup
+    wtimeout
+    wtouchln
+    wvline
+    getattrs
+    getbegx
+    getbegy
+    getmaxx
+    getmaxy
+    getparx
+    getpary
+    getcurx
+    getcury
+    traceoff
+    traceon
+    unctrl
+    crmode
+    nocrmode
+    draino
+    resetterm
+    fixterm
+    saveterm
+    mouse_set
+    mouse_on
+    mouse_off
+    request_mouse_pos
+    map_button
+    wmouse_position
+    getmouse
+    getbmap
+    assume_default_colors
+    curses_version
+    has_key
+    use_default_colors
+    wresize
+    mouseinterval
+    mousemask
+    mouse_trafo
+    nc_getmouse
+    ungetmouse
+    wenclose
+    wmouse_trafo
+    addrawch
+    insrawch
+    is_termresized
+    mvaddrawch
+    mvdeleteln
+    mvinsertln
+    mvinsrawch
+    mvwaddrawch
+    mvwdeleteln
+    mvwinsertln
+    mvwinsrawch
+    raw_output
+    resize_term
+    resize_window
+    waddrawch
+    winsrawch
+    wordchar
+    bottom_panel
+    del_panel
+    hide_panel
+    move_panel
+    new_panel
+    panel_above
+    panel_below
+    panel_hidden
+    panel_userptr
+    panel_window
+    replace_panel
+    set_panel_userptr
+    show_panel
+    top_panel
+    update_panels
+    PDC_debug
+    PDC_ungetch
+    PDC_set_blink
+    PDC_set_line_color
+    PDC_set_title
+    PDC_clearclipboard
+    PDC_freeclipboard
+    PDC_getclipboard
+    PDC_setclipboard
+    PDC_get_input_fd
+    PDC_get_key_modifiers
+    PDC_save_key_modifiers
+    PDC_return_key_modifiers
+    cur_term
+    del_curterm
+    putp
+    restartterm
+    set_curterm
+    setterm
+    setupterm
+    tgetent
+    tgetflag
+    tgetnum
+    tgetstr
+    tgoto
+    tigetflag
+    tigetnum
+    tigetstr
+    tparm
+    tputs
diff --git a/pdcurses/pdcurses.vcproj b/pdcurses/pdcurses.vcproj
deleted file mode 100644 (file)
index ca838cb..0000000
+++ /dev/null
@@ -1,417 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="pdcurses"
-       ProjectGUID="{CC07EA59-8D54-4C51-9C49-728EFFED7832}"
-       RootNamespace="pdcurses"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories=".,..,.\pdcurses,.\win32"
-                               PreprocessorDefinitions="_DEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="3"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/pdcurses.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\pdcurses.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                               CommandLine=""
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories=".,..,.\pdcurses,.\win32"
-                               PreprocessorDefinitions="NDEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/pdcurses.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\pdcurses.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                               CommandLine=""
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\pdcurses\addch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\addchstr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\addstr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\attr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\beep.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\bkgd.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\border.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\clear.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\color.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\debug.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\delch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\deleteln.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\deprec.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\getch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\getstr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\getyx.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\inch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\inchstr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\initscr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\inopts.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\insch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\insstr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\instr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\kernel.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\keyname.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\mouse.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\move.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\outopts.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\overlay.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\pad.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\panel.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcclip.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcdisp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcgetsc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdckbd.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcscrn.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcsetsc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcutil.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\printw.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\refresh.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\scanw.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\scr_dump.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\scroll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\slk.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\termattr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\terminfo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\touch.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\util.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pdcurses\window.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\curses.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\curspriv.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\panel.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\win32\pdcwin.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\term.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/pdcurses/pdcurses.vcxproj b/pdcurses/pdcurses.vcxproj
deleted file mode 100644 (file)
index a2ca564..0000000
+++ /dev/null
@@ -1,296 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{CC07EA59-8D54-4C51-9C49-728EFFED7832}</ProjectGuid>
-    <RootNamespace>pdcurses</RootNamespace>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-    <Import Project="$(VCTargetsPath)\BuildCustomizations\lc.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</PostBuildEventUseInBuild>
-    <PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</PostBuildEventUseInBuild>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>.;..;.\pdcurses;.\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/pdcurses.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\pdcurses.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-    <PostBuildEvent>
-      <Command>
-      </Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>.;..;.\pdcurses;.\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/pdcurses.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\pdcurses.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-    <PostBuildEvent>
-      <Command>
-      </Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>.;..;.\pdcurses;.\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/pdcurses.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\pdcurses.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-    <PostBuildEvent>
-      <Command>cp ../Release\pdcurses.lib ../Release\panel.lib</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>.;..;.\pdcurses;.\win32;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MD;_CONSOLE;_LIB;WIN32;JAPANESE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/pdcurses.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\pdcurses.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-    <PostBuildEvent>
-      <Command>cp ../Release\pdcurses.lib ../Release\panel.lib</Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="pdcurses\addch.c" />
-    <ClCompile Include="pdcurses\addchstr.c" />
-    <ClCompile Include="pdcurses\addstr.c" />
-    <ClCompile Include="pdcurses\attr.c" />
-    <ClCompile Include="pdcurses\beep.c" />
-    <ClCompile Include="pdcurses\bkgd.c" />
-    <ClCompile Include="pdcurses\border.c" />
-    <ClCompile Include="pdcurses\clear.c" />
-    <ClCompile Include="pdcurses\color.c" />
-    <ClCompile Include="pdcurses\debug.c" />
-    <ClCompile Include="pdcurses\delch.c" />
-    <ClCompile Include="pdcurses\deleteln.c" />
-    <ClCompile Include="pdcurses\deprec.c" />
-    <ClCompile Include="pdcurses\getch.c" />
-    <ClCompile Include="pdcurses\getstr.c" />
-    <ClCompile Include="pdcurses\getyx.c" />
-    <ClCompile Include="pdcurses\inch.c" />
-    <ClCompile Include="pdcurses\inchstr.c" />
-    <ClCompile Include="pdcurses\initscr.c" />
-    <ClCompile Include="pdcurses\inopts.c" />
-    <ClCompile Include="pdcurses\insch.c" />
-    <ClCompile Include="pdcurses\insstr.c" />
-    <ClCompile Include="pdcurses\instr.c" />
-    <ClCompile Include="pdcurses\kernel.c" />
-    <ClCompile Include="pdcurses\keyname.c" />
-    <ClCompile Include="pdcurses\mouse.c" />
-    <ClCompile Include="pdcurses\move.c" />
-    <ClCompile Include="pdcurses\outopts.c" />
-    <ClCompile Include="pdcurses\overlay.c" />
-    <ClCompile Include="pdcurses\pad.c" />
-    <ClCompile Include="pdcurses\panel.c" />
-    <ClCompile Include="win32\pdcclip.c" />
-    <ClCompile Include="win32\pdcdisp.c" />
-    <ClCompile Include="win32\pdcgetsc.c" />
-    <ClCompile Include="win32\pdckbd.c" />
-    <ClCompile Include="win32\pdcscrn.c" />
-    <ClCompile Include="win32\pdcsetsc.c" />
-    <ClCompile Include="win32\pdcutil.c" />
-    <ClCompile Include="pdcurses\printw.c" />
-    <ClCompile Include="pdcurses\refresh.c" />
-    <ClCompile Include="pdcurses\scanw.c" />
-    <ClCompile Include="pdcurses\scr_dump.c" />
-    <ClCompile Include="pdcurses\scroll.c" />
-    <ClCompile Include="pdcurses\slk.c" />
-    <ClCompile Include="pdcurses\termattr.c" />
-    <ClCompile Include="pdcurses\terminfo.c" />
-    <ClCompile Include="pdcurses\touch.c" />
-    <ClCompile Include="pdcurses\util.c" />
-    <ClCompile Include="pdcurses\window.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="curses.h" />
-    <ClInclude Include="curspriv.h" />
-    <ClInclude Include="panel.h" />
-    <ClInclude Include="win32\pdcwin.h" />
-    <ClInclude Include="term.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-    <Import Project="$(VCTargetsPath)\BuildCustomizations\lc.targets" />
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/pdcurses/pdcurses.vcxproj.filters b/pdcurses/pdcurses.vcxproj.filters
deleted file mode 100644 (file)
index 80ea801..0000000
+++ /dev/null
@@ -1,179 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{fb5ef3b6-fde7-47fd-bef3-aec780fd0310}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{47ea15e7-097a-46cf-b367-2c9aa58dfc19}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="pdcurses\addch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\addchstr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\addstr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\attr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\beep.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\bkgd.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\border.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\clear.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\color.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\debug.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\delch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\deleteln.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\deprec.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\getch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\getstr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\getyx.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\inch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\inchstr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\initscr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\inopts.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\insch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\insstr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\instr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\kernel.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\keyname.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\mouse.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\move.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\outopts.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\overlay.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\pad.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\panel.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcclip.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcdisp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcgetsc.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdckbd.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcscrn.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcsetsc.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="win32\pdcutil.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\printw.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\refresh.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\scanw.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\scr_dump.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\scroll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\slk.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\termattr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\terminfo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\touch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\util.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pdcurses\window.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="curses.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="curspriv.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="panel.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="win32\pdcwin.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="term.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/pdcurses/pdcurses.vcxproj.user b/pdcurses/pdcurses.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/pdcurses/win32/pdcurses.ico b/pdcurses/win32/pdcurses.ico
new file mode 100644 (file)
index 0000000..53a6dde
Binary files /dev/null and b/pdcurses/win32/pdcurses.ico differ
diff --git a/pdcurses/win32/pdcurses.rc b/pdcurses/win32/pdcurses.rc
new file mode 100644 (file)
index 0000000..1b8bba4
--- /dev/null
@@ -0,0 +1,28 @@
+#include "winver.h"
+
+1 VERSIONINFO
+ FILEVERSION 3,4,0,0
+ PRODUCTVERSION 3,4,0,0
+ FILEFLAGSMASK 0x3fL
+ FILEFLAGS 0x0L
+ FILEOS VOS_UNKNOWN
+ FILETYPE VFT_DLL
+ FILESUBTYPE 0x0L
+BEGIN
+    BLOCK "StringFileInfo"
+    BEGIN
+        BLOCK "040904b0"
+        BEGIN
+            VALUE "Maintainer", "William McBrine\0"
+            VALUE "FileDescription", "Public Domain Curses\0"
+            VALUE "FileVersion", "3.4.0\0"
+            VALUE "InternalName", "PDCurses\0"
+            VALUE "LegalCopyright", "Public Domain\0"
+            VALUE "OriginalFilename", "PDCURSES.DLL\0"
+            VALUE "ProductName", "Public Domain Curses Library\0"
+            VALUE "ProductVersion", "3.4.0\0"
+        END
+    END
+END
+
+1 ICON    DISCARDABLE     "PDCURSES.ico"
diff --git a/portaudio/CMakeLists.txt b/portaudio/CMakeLists.txt
new file mode 100644 (file)
index 0000000..54923f1
--- /dev/null
@@ -0,0 +1,97 @@
+
+add_definitions(
+#    -DPA_USE_ASIO
+    -DPA_USE_DS
+    -DPA_USE_WMME
+    -DPA_USE_WASAPI
+    -DPA_USE_WDMKS
+)
+
+include_directories(src/common src/os/win)
+
+add_library(
+    portaudio SHARED
+
+    include/pa_asio.h
+    include/pa_jack.h
+    include/pa_linux_alsa.h
+    include/pa_mac_core.h
+    include/pa_win_ds.h
+    include/pa_win_wasapi.h
+    include/pa_win_waveformat.h
+    include/pa_win_wdmks.h
+    include/pa_win_wmme.h
+    include/portaudio.h
+
+    src/common/pa_allocation.c
+    src/common/pa_allocation.h
+    src/common/pa_converters.c
+    src/common/pa_converters.h
+    src/common/pa_cpuload.c
+    src/common/pa_cpuload.h
+    src/common/pa_debugprint.c
+    src/common/pa_debugprint.h
+    src/common/pa_dither.c
+    src/common/pa_dither.h
+    src/common/pa_endianness.h
+    src/common/pa_front.c
+    src/common/pa_gitrevision.h
+    src/common/pa_hostapi.h
+    src/common/pa_memorybarrier.h
+    src/common/pa_process.c
+    src/common/pa_process.h
+    src/common/pa_ringbuffer.c
+    src/common/pa_ringbuffer.h
+    src/common/pa_stream.c
+    src/common/pa_stream.h
+    src/common/pa_trace.c
+    src/common/pa_trace.h
+    src/common/pa_types.h
+    src/common/pa_util.h
+#    src/hostapi/alsa/pa_linux_alsa.c
+#    src/hostapi/asihpi/pa_linux_asihpi.c
+#    src/hostapi/asio/iasiothiscallresolver.cpp
+#    src/hostapi/asio/iasiothiscallresolver.h
+#    src/hostapi/asio/pa_asio.cpp
+#    src/hostapi/coreaudio/pa_mac_core.c
+#    src/hostapi/coreaudio/pa_mac_core_blocking.c
+#    src/hostapi/coreaudio/pa_mac_core_blocking.h
+#    src/hostapi/coreaudio/pa_mac_core_internal.h
+#    src/hostapi/coreaudio/pa_mac_core_old.c
+#    src/hostapi/coreaudio/pa_mac_core_utilities.c
+#    src/hostapi/coreaudio/pa_mac_core_utilities.h
+    src/hostapi/dsound/pa_win_ds.c
+    src/hostapi/dsound/pa_win_ds_dynlink.c
+    src/hostapi/dsound/pa_win_ds_dynlink.h
+#    src/hostapi/jack/pa_jack.c
+#    src/hostapi/oss/pa_unix_oss.c
+#    src/hostapi/oss/recplay.c
+    src/hostapi/skeleton/pa_hostapi_skeleton.c
+    src/hostapi/wasapi/pa_win_wasapi.c
+    src/hostapi/wdmks/pa_win_wdmks.c
+    src/hostapi/wmme/pa_win_wmme.c
+#    src/os/unix/pa_unix_hostapis.c
+#    src/os/unix/pa_unix_util.c
+#    src/os/unix/pa_unix_util.h
+    src/os/win/pa_win_coinitialize.c
+    src/os/win/pa_win_coinitialize.h
+    src/os/win/pa_win_hostapis.c
+    src/os/win/pa_win_util.c
+    src/os/win/pa_win_waveformat.c
+    src/os/win/pa_win_wdmks_utils.c
+    src/os/win/pa_win_wdmks_utils.h
+    src/os/win/pa_x86_plain_converters.c
+    src/os/win/pa_x86_plain_converters.h
+
+    portaudio.def
+)
+
+set_target_properties(portaudio PROPERTIES PREFIX "")
+
+if(${CMAKE_SIZEOF_VOID_P} EQUAL 8)
+    set_target_properties(portaudio PROPERTIES OUTPUT_NAME "portaudio_x64")
+else()
+    set_target_properties(portaudio PROPERTIES OUTPUT_NAME "portaudio_x86")
+endif()
+
+target_link_libraries(portaudio ole32 advapi32 setupapi winmm)
diff --git a/portaudio/LICENSE.txt b/portaudio/LICENSE.txt
new file mode 100644 (file)
index 0000000..e0ac4e8
--- /dev/null
@@ -0,0 +1,81 @@
+Portable header file to contain:
+>>>>>
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * PortAudio API Header File
+ * Latest version available at: http://www.portaudio.com
+ *
+ * Copyright (c) 1999-2006 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+<<<<<
+
+Implementation files to contain:
+>>>>>
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Latest version at: http://www.portaudio.com
+ * <platform> Implementation
+ * Copyright (c) 1999-2000 <author(s)>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+<<<<<
\ No newline at end of file
diff --git a/portaudio/README.txt b/portaudio/README.txt
new file mode 100644 (file)
index 0000000..2113827
--- /dev/null
@@ -0,0 +1,98 @@
+README for PortAudio
+
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Copyright (c) 1999-2008 Phil Burk and Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+
+PortAudio is a portable audio I/O library designed for cross-platform
+support of audio. It uses either a callback mechanism to request audio 
+processing, or blocking read/write calls to buffer data between the 
+native audio subsystem and the client. Audio can be processed in various 
+formats, including 32 bit floating point, and will be converted to the 
+native format internally.
+
+Documentation:
+       Documentation is available in "/doc/html/index.html"
+       Also see "src/common/portaudio.h" for API spec.
+       Also see http://www.portaudio.com/docs/
+       And see the "test/" directory for many examples of usage
+               (we suggest "test/patest_saw.c" for an example)
+
+For information on compiling programs with PortAudio, please see the
+tutorial at:
+
+  http://portaudio.com/trac/wiki/TutorialDir/TutorialStart
+  
+We have an active mailing list for user and developer discussions.
+Please feel free to join. See http://www.portaudio.com for details.
+
+
+Important Files and Folders:
+    include/portaudio.h     = header file for PortAudio API. Specifies API.    
+    src/common/             = platform independant code, host independant 
+                              code for all implementations.
+    src/os                  = os specific (but host api neutral) code
+    src/hostapi             = implementations for different host apis
+
+
+Host API Implementations:
+    src/hostapi/alsa        = Advanced Linux Sound Architecture (ALSA)
+    src/hostapi/asihpi      = AudioScience HPI
+    src/hostapi/asio        = ASIO for Windows and Macintosh
+    src/hostapi/coreaudio   = Macintosh Core Audio for OS X
+    src/hostapi/dsound      = Windows Direct Sound
+    src/hostapi/jack        = JACK Audio Connection Kit
+    src/hostapi/oss         = Unix Open Sound System (OSS)
+    src/hostapi/wasapi      = Windows Vista WASAPI
+    src/hostapi/wdmks       = Windows WDM Kernel Streaming
+    src/hostapi/wmme        = Windows MultiMedia Extensions (MME)
+
+
+Test Programs:
+    test/pa_fuzz.c         = guitar fuzz box
+    test/pa_devs.c         = print a list of available devices
+    test/pa_minlat.c       = determine minimum latency for your machine
+    test/paqa_devs.c       = self test that opens all devices
+    test/paqa_errs.c       = test error detection and reporting
+    test/patest_clip.c     = hear a sine wave clipped and unclipped
+    test/patest_dither.c   = hear effects of dithering (extremely subtle)
+    test/patest_pink.c     = fun with pink noise
+    test/patest_record.c   = record and playback some audio
+    test/patest_maxsines.c = how many sine waves can we play? Tests Pa_GetCPULoad().
+    test/patest_sine.c     = output a sine wave in a simple PA app
+    test/patest_sync.c     = test syncronization of audio and video
+    test/patest_wire.c     = pass input to output, wire simulator
diff --git a/portaudio/portaudio.def b/portaudio/portaudio.def
new file mode 100644 (file)
index 0000000..3305117
--- /dev/null
@@ -0,0 +1,48 @@
+EXPORTS
+    Pa_GetVersion                       @1
+    Pa_GetVersionText                   @2
+    Pa_GetErrorText                     @3                 
+    Pa_Initialize                       @4
+    Pa_Terminate                        @5
+    Pa_GetHostApiCount                  @6
+    Pa_GetDefaultHostApi                @7
+    Pa_GetHostApiInfo                   @8
+    Pa_HostApiTypeIdToHostApiIndex      @9
+    Pa_HostApiDeviceIndexToDeviceIndex  @10
+    Pa_GetLastHostErrorInfo             @11
+    Pa_GetDeviceCount                   @12
+    Pa_GetDefaultInputDevice            @13
+    Pa_GetDefaultOutputDevice           @14
+    Pa_GetDeviceInfo                    @15
+    Pa_IsFormatSupported                @16
+    Pa_OpenStream                       @17
+    Pa_OpenDefaultStream                @18
+    Pa_CloseStream                      @19
+    Pa_SetStreamFinishedCallback        @20
+    Pa_StartStream                      @21
+    Pa_StopStream                       @22
+    Pa_AbortStream                      @23
+    Pa_IsStreamStopped                  @24
+    Pa_IsStreamActive                   @25
+    Pa_GetStreamInfo                    @26
+    Pa_GetStreamTime                    @27
+    Pa_GetStreamCpuLoad                 @28
+    Pa_ReadStream                       @29
+    Pa_WriteStream                      @30
+    Pa_GetStreamReadAvailable           @31
+    Pa_GetStreamWriteAvailable          @32
+    Pa_GetSampleSize                    @33
+    Pa_Sleep                            @34
+;    PaAsio_GetAvailableBufferSizes      @50
+;    PaAsio_ShowControlPanel             @51
+    PaUtil_InitializeX86PlainConverters @52
+;    PaAsio_GetInputChannelName          @53
+;    PaAsio_GetOutputChannelName         @54
+    PaUtil_SetDebugPrintFunction        @55
+    PaWasapi_GetDeviceDefaultFormat     @56
+    PaWasapi_GetDeviceRole              @57
+    PaWasapi_ThreadPriorityBoost        @58
+    PaWasapi_ThreadPriorityRevert       @59
+    PaWasapi_GetFramesPerHostBuffer     @60
+    PaWasapi_GetJackDescription         @61
+    PaWasapi_GetJackCount               @62
diff --git a/portaudio/src/common/pa_allocation.c b/portaudio/src/common/pa_allocation.c
new file mode 100644 (file)
index 0000000..51fe15a
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library allocation group implementation
+ * memory allocation group for tracking allocation groups
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Allocation Group implementation.
+*/
+
+
+#include "pa_allocation.h"
+#include "pa_util.h"
+
+
+/*
+    Maintain 3 singly linked lists...
+    linkBlocks: the buffers used to allocate the links
+    spareLinks: links available for use in the allocations list
+    allocations: the buffers currently allocated using PaUtil_ContextAllocateMemory()
+
+    Link block size is doubled every time new links are allocated.
+*/
+
+
+#define PA_INITIAL_LINK_COUNT_    16
+
+struct PaUtilAllocationGroupLink
+{
+    struct PaUtilAllocationGroupLink *next;
+    void *buffer;
+};
+
+/*
+    Allocate a block of links. The first link will have it's buffer member
+    pointing to the block, and it's next member set to <nextBlock>. The remaining
+    links will have NULL buffer members, and each link will point to
+    the next link except the last, which will point to <nextSpare>
+*/
+static struct PaUtilAllocationGroupLink *AllocateLinks( long count,
+        struct PaUtilAllocationGroupLink *nextBlock,
+        struct PaUtilAllocationGroupLink *nextSpare )
+{
+    struct PaUtilAllocationGroupLink *result;
+    int i;
+    
+    result = (struct PaUtilAllocationGroupLink *)PaUtil_AllocateMemory(
+            sizeof(struct PaUtilAllocationGroupLink) * count );
+    if( result )
+    {
+        /* the block link */
+        result[0].buffer = result;
+        result[0].next = nextBlock;
+
+        /* the spare links */
+        for( i=1; i<count; ++i )
+        {
+            result[i].buffer = 0;
+            result[i].next = &result[i+1];
+        }
+        result[count-1].next = nextSpare;
+    }
+    
+    return result;
+}
+
+
+PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void )
+{
+    PaUtilAllocationGroup* result = 0;
+    struct PaUtilAllocationGroupLink *links;
+
+
+    links = AllocateLinks( PA_INITIAL_LINK_COUNT_, 0, 0 );
+    if( links != 0 )
+    {
+        result = (PaUtilAllocationGroup*)PaUtil_AllocateMemory( sizeof(PaUtilAllocationGroup) );
+        if( result )
+        {
+            result->linkCount = PA_INITIAL_LINK_COUNT_;
+            result->linkBlocks = &links[0];
+            result->spareLinks = &links[1];
+            result->allocations = 0;
+        }
+        else
+        {
+            PaUtil_FreeMemory( links );
+        }
+    }
+
+    return result;
+}
+
+
+void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group )
+{
+    struct PaUtilAllocationGroupLink *current = group->linkBlocks;
+    struct PaUtilAllocationGroupLink *next;
+
+    while( current )
+    {
+        next = current->next;
+        PaUtil_FreeMemory( current->buffer );
+        current = next;
+    }
+
+    PaUtil_FreeMemory( group );
+}
+
+
+void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size )
+{
+    struct PaUtilAllocationGroupLink *links, *link;
+    void *result = 0;
+    
+    /* allocate more links if necessary */
+    if( !group->spareLinks )
+    {
+        /* double the link count on each block allocation */
+        links = AllocateLinks( group->linkCount, group->linkBlocks, group->spareLinks );
+        if( links )
+        {
+            group->linkCount += group->linkCount;
+            group->linkBlocks = &links[0];
+            group->spareLinks = &links[1];
+        }
+    }
+
+    if( group->spareLinks )
+    {
+        result = PaUtil_AllocateMemory( size );
+        if( result )
+        {
+            link = group->spareLinks;
+            group->spareLinks = link->next;
+
+            link->buffer = result;
+            link->next = group->allocations;
+
+            group->allocations = link;
+        }
+    }
+
+    return result;    
+}
+
+
+void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer )
+{
+    struct PaUtilAllocationGroupLink *current = group->allocations;
+    struct PaUtilAllocationGroupLink *previous = 0;
+
+    if( buffer == 0 )
+        return;
+
+    /* find the right link and remove it */
+    while( current )
+    {
+        if( current->buffer == buffer )
+        {
+            if( previous )
+            {
+                previous->next = current->next;
+            }
+            else
+            {
+                group->allocations = current->next;
+            }
+
+            current->buffer = 0;
+            current->next = group->spareLinks;
+            group->spareLinks = current;
+
+            break;
+        }
+        
+        previous = current;
+        current = current->next;
+    }
+
+    PaUtil_FreeMemory( buffer ); /* free the memory whether we found it in the list or not */
+}
+
+
+void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group )
+{
+    struct PaUtilAllocationGroupLink *current = group->allocations;
+    struct PaUtilAllocationGroupLink *previous = 0;
+
+    /* free all buffers in the allocations list */
+    while( current )
+    {
+        PaUtil_FreeMemory( current->buffer );
+        current->buffer = 0;
+
+        previous = current;
+        current = current->next;
+    }
+
+    /* link the former allocations list onto the front of the spareLinks list */
+    if( previous )
+    {
+        previous->next = group->spareLinks;
+        group->spareLinks = group->allocations;
+        group->allocations = 0;
+    }
+}
+
diff --git a/portaudio/src/common/pa_allocation.h b/portaudio/src/common/pa_allocation.h
new file mode 100644 (file)
index 0000000..bd1f4b0
--- /dev/null
@@ -0,0 +1,104 @@
+#ifndef PA_ALLOCATION_H
+#define PA_ALLOCATION_H
+/*
+ * $Id$
+ * Portable Audio I/O Library allocation context header
+ * memory allocation context for tracking allocation groups
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Allocation Group prototypes. An Allocation Group makes it easy to
+ allocate multiple blocks of memory and free them all at once.
+ An allocation group is useful for keeping track of multiple blocks
+ of memory which are allocated at the same time (such as during initialization)
+ and need to be deallocated at the same time. The allocation group maintains
+ a list of allocated blocks, and can free all allocations at once. This
+ can be usefull for cleaning up after a partially initialized object fails.
+
+ The allocation group implementation is built on top of the lower
+ level allocation functions defined in pa_util.h
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+typedef struct
+{
+    long linkCount;
+    struct PaUtilAllocationGroupLink *linkBlocks;
+    struct PaUtilAllocationGroupLink *spareLinks;
+    struct PaUtilAllocationGroupLink *allocations;
+}PaUtilAllocationGroup;
+
+
+
+/** Create an allocation group.
+*/
+PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void );
+
+/** Destroy an allocation group, but not the memory allocated through the group.
+*/
+void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group );
+
+/** Allocate a block of memory though an allocation group.
+*/
+void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size );
+
+/** Free a block of memory that was previously allocated though an allocation
+ group. Calling this function is a relatively time consuming operation.
+ Under normal circumstances clients should call PaUtil_FreeAllAllocations to
+ free all allocated blocks simultaneously.
+ @see PaUtil_FreeAllAllocations
+*/
+void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer );
+
+/** Free all blocks of memory which have been allocated through the allocation
+ group. This function doesn't destroy the group itself.
+*/
+void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_ALLOCATION_H */
diff --git a/portaudio/src/common/pa_converters.c b/portaudio/src/common/pa_converters.c
new file mode 100644 (file)
index 0000000..2107f5e
--- /dev/null
@@ -0,0 +1,1983 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library sample conversion mechanism
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Conversion function implementations.
+ If the C9x function lrintf() is available, define PA_USE_C99_LRINTF to use it
+
+ @todo Consider whether functions which dither but don't clip should exist,
+ V18 automatically enabled clipping whenever dithering was selected. Perhaps
+ we should do the same. 
+    see: "require clipping for dithering sample conversion functions?"
+    http://www.portaudio.com/trac/ticket/112
+
+ @todo implement the converters marked IMPLEMENT ME: Int32_To_Int24_Dither,
+ Int32_To_UInt8_Dither, Int24_To_Int16_Dither, Int24_To_Int8_Dither, 
+ Int24_To_UInt8_Dither, Int16_To_Int8_Dither, Int16_To_UInt8_Dither
+    see: "some conversion functions are not implemented in pa_converters.c"
+    http://www.portaudio.com/trac/ticket/35
+
+ @todo review the converters marked REVIEW: Float32_To_Int32,
+ Float32_To_Int32_Dither, Float32_To_Int32_Clip, Float32_To_Int32_DitherClip,
+ Int32_To_Int16_Dither, Int32_To_Int8_Dither, Int16_To_Int32
+*/
+
+
+#include "pa_converters.h"
+#include "pa_dither.h"
+#include "pa_endianness.h"
+#include "pa_types.h"
+
+
+PaSampleFormat PaUtil_SelectClosestAvailableFormat(
+        PaSampleFormat availableFormats, PaSampleFormat format )
+{
+    PaSampleFormat result;
+
+    format &= ~paNonInterleaved;
+    availableFormats &= ~paNonInterleaved;
+    
+    if( (format & availableFormats) == 0 )
+    {
+        /* NOTE: this code depends on the sample format constants being in
+            descending order of quality - ie best quality is 0
+            FIXME: should write an assert which checks that all of the
+            known constants conform to that requirement.
+        */
+
+        if( format != 0x01 )
+        {
+            /* scan for better formats */
+            result = format;
+            do
+            {
+                result >>= 1;
+            }
+            while( (result & availableFormats) == 0 && result != 0 );
+        }
+        else
+        {
+            result = 0;
+        }
+        
+        if( result == 0 ){
+            /* scan for worse formats */
+            result = format;
+            do
+            {
+                result <<= 1;
+            }
+            while( (result & availableFormats) == 0 && result != paCustomFormat );
+
+            if( (result & availableFormats) == 0 )
+                result = paSampleFormatNotSupported;
+        }
+        
+    }else{
+        result = format;
+    }
+
+    return result;
+}
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_SELECT_FORMAT_( format, float32, int32, int24, int16, int8, uint8 ) \
+    switch( format & ~paNonInterleaved ){                                      \
+    case paFloat32:                                                            \
+        float32                                                                \
+    case paInt32:                                                              \
+        int32                                                                  \
+    case paInt24:                                                              \
+        int24                                                                  \
+    case paInt16:                                                              \
+        int16                                                                  \
+    case paInt8:                                                               \
+        int8                                                                   \
+    case paUInt8:                                                              \
+        uint8                                                                  \
+    default: return 0;                                                         \
+    }
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_SELECT_CONVERTER_DITHER_CLIP_( flags, source, destination )         \
+    if( flags & paClipOff ){ /* no clip */                                     \
+        if( flags & paDitherOff ){ /* no dither */                             \
+            return paConverters. source ## _To_ ## destination;                \
+        }else{ /* dither */                                                    \
+            return paConverters. source ## _To_ ## destination ## _Dither;     \
+        }                                                                      \
+    }else{ /* clip */                                                          \
+        if( flags & paDitherOff ){ /* no dither */                             \
+            return paConverters. source ## _To_ ## destination ## _Clip;       \
+        }else{ /* dither */                                                    \
+            return paConverters. source ## _To_ ## destination ## _DitherClip; \
+        }                                                                      \
+    }
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_SELECT_CONVERTER_DITHER_( flags, source, destination )              \
+    if( flags & paDitherOff ){ /* no dither */                                 \
+        return paConverters. source ## _To_ ## destination;                    \
+    }else{ /* dither */                                                        \
+        return paConverters. source ## _To_ ## destination ## _Dither;         \
+    }
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_USE_CONVERTER_( source, destination )\
+    return paConverters. source ## _To_ ## destination;
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_UNITY_CONVERSION_( wordlength )\
+    return paConverters. Copy_ ## wordlength ## _To_ ## wordlength;
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,
+        PaSampleFormat destinationFormat, PaStreamFlags flags )
+{
+    PA_SELECT_FORMAT_( sourceFormat,
+                       /* paFloat32: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_UNITY_CONVERSION_( 32 ),
+                                          /* paInt32: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int32 ),
+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int24 ),
+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int16 ),
+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int8 ),
+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, UInt8 )
+                                        ),
+                       /* paInt32: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int32, Float32 ),
+                                          /* paInt32: */          PA_UNITY_CONVERSION_( 32 ),
+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int24 ),
+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int16 ),
+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int8 ),
+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, UInt8 )
+                                        ),
+                       /* paInt24: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int24, Float32 ),
+                                          /* paInt32: */          PA_USE_CONVERTER_( Int24, Int32 ),
+                                          /* paInt24: */          PA_UNITY_CONVERSION_( 24 ),
+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int16 ),
+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int8 ),
+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, UInt8 )
+                                        ),
+                       /* paInt16: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int16, Float32 ),
+                                          /* paInt32: */          PA_USE_CONVERTER_( Int16, Int32 ),
+                                          /* paInt24: */          PA_USE_CONVERTER_( Int16, Int24 ),
+                                          /* paInt16: */          PA_UNITY_CONVERSION_( 16 ),
+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int16, Int8 ),
+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int16, UInt8 )
+                                        ),
+                       /* paInt8: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int8, Float32 ),
+                                          /* paInt32: */          PA_USE_CONVERTER_( Int8, Int32 ),
+                                          /* paInt24: */          PA_USE_CONVERTER_( Int8, Int24 ),
+                                          /* paInt16: */          PA_USE_CONVERTER_( Int8, Int16 ),
+                                          /* paInt8: */           PA_UNITY_CONVERSION_( 8 ),
+                                          /* paUInt8: */          PA_USE_CONVERTER_( Int8, UInt8 )
+                                        ),
+                       /* paUInt8: */
+                       PA_SELECT_FORMAT_( destinationFormat,
+                                          /* paFloat32: */        PA_USE_CONVERTER_( UInt8, Float32 ),
+                                          /* paInt32: */          PA_USE_CONVERTER_( UInt8, Int32 ),
+                                          /* paInt24: */          PA_USE_CONVERTER_( UInt8, Int24 ),
+                                          /* paInt16: */          PA_USE_CONVERTER_( UInt8, Int16 ),
+                                          /* paInt8: */           PA_USE_CONVERTER_( UInt8, Int8 ),
+                                          /* paUInt8: */          PA_UNITY_CONVERSION_( 8 )
+                                        )
+                     )
+}
+
+/* -------------------------------------------------------------------------- */
+
+#ifdef PA_NO_STANDARD_CONVERTERS
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilConverterTable paConverters = {
+    0, /* PaUtilConverter *Float32_To_Int32; */
+    0, /* PaUtilConverter *Float32_To_Int32_Dither; */
+    0, /* PaUtilConverter *Float32_To_Int32_Clip; */
+    0, /* PaUtilConverter *Float32_To_Int32_DitherClip; */
+
+    0, /* PaUtilConverter *Float32_To_Int24; */
+    0, /* PaUtilConverter *Float32_To_Int24_Dither; */
+    0, /* PaUtilConverter *Float32_To_Int24_Clip; */
+    0, /* PaUtilConverter *Float32_To_Int24_DitherClip; */
+
+    0, /* PaUtilConverter *Float32_To_Int16; */
+    0, /* PaUtilConverter *Float32_To_Int16_Dither; */
+    0, /* PaUtilConverter *Float32_To_Int16_Clip; */
+    0, /* PaUtilConverter *Float32_To_Int16_DitherClip; */
+
+    0, /* PaUtilConverter *Float32_To_Int8; */
+    0, /* PaUtilConverter *Float32_To_Int8_Dither; */
+    0, /* PaUtilConverter *Float32_To_Int8_Clip; */
+    0, /* PaUtilConverter *Float32_To_Int8_DitherClip; */
+
+    0, /* PaUtilConverter *Float32_To_UInt8; */
+    0, /* PaUtilConverter *Float32_To_UInt8_Dither; */
+    0, /* PaUtilConverter *Float32_To_UInt8_Clip; */
+    0, /* PaUtilConverter *Float32_To_UInt8_DitherClip; */
+
+    0, /* PaUtilConverter *Int32_To_Float32; */
+    0, /* PaUtilConverter *Int32_To_Int24; */
+    0, /* PaUtilConverter *Int32_To_Int24_Dither; */
+    0, /* PaUtilConverter *Int32_To_Int16; */
+    0, /* PaUtilConverter *Int32_To_Int16_Dither; */
+    0, /* PaUtilConverter *Int32_To_Int8; */
+    0, /* PaUtilConverter *Int32_To_Int8_Dither; */
+    0, /* PaUtilConverter *Int32_To_UInt8; */
+    0, /* PaUtilConverter *Int32_To_UInt8_Dither; */
+
+    0, /* PaUtilConverter *Int24_To_Float32; */
+    0, /* PaUtilConverter *Int24_To_Int32; */
+    0, /* PaUtilConverter *Int24_To_Int16; */
+    0, /* PaUtilConverter *Int24_To_Int16_Dither; */
+    0, /* PaUtilConverter *Int24_To_Int8; */
+    0, /* PaUtilConverter *Int24_To_Int8_Dither; */
+    0, /* PaUtilConverter *Int24_To_UInt8; */
+    0, /* PaUtilConverter *Int24_To_UInt8_Dither; */
+    
+    0, /* PaUtilConverter *Int16_To_Float32; */
+    0, /* PaUtilConverter *Int16_To_Int32; */
+    0, /* PaUtilConverter *Int16_To_Int24; */
+    0, /* PaUtilConverter *Int16_To_Int8; */
+    0, /* PaUtilConverter *Int16_To_Int8_Dither; */
+    0, /* PaUtilConverter *Int16_To_UInt8; */
+    0, /* PaUtilConverter *Int16_To_UInt8_Dither; */
+
+    0, /* PaUtilConverter *Int8_To_Float32; */
+    0, /* PaUtilConverter *Int8_To_Int32; */
+    0, /* PaUtilConverter *Int8_To_Int24 */
+    0, /* PaUtilConverter *Int8_To_Int16; */
+    0, /* PaUtilConverter *Int8_To_UInt8; */
+
+    0, /* PaUtilConverter *UInt8_To_Float32; */
+    0, /* PaUtilConverter *UInt8_To_Int32; */
+    0, /* PaUtilConverter *UInt8_To_Int24; */
+    0, /* PaUtilConverter *UInt8_To_Int16; */
+    0, /* PaUtilConverter *UInt8_To_Int8; */
+
+    0, /* PaUtilConverter *Copy_8_To_8; */
+    0, /* PaUtilConverter *Copy_16_To_16; */
+    0, /* PaUtilConverter *Copy_24_To_24; */
+    0  /* PaUtilConverter *Copy_32_To_32; */
+};
+
+/* -------------------------------------------------------------------------- */
+
+#else /* PA_NO_STANDARD_CONVERTERS is not defined */
+
+/* -------------------------------------------------------------------------- */
+
+#define PA_CLIP_( val, min, max )\
+    { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); }
+
+
+static const float const_1_div_128_ = 1.0f / 128.0f;  /* 8 bit multiplier */
+
+static const float const_1_div_32768_ = 1.0f / 32768.f; /* 16 bit multiplier */
+
+static const double const_1_div_2147483648_ = 1.0 / 2147483648.0; /* 32 bit multiplier */
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        /* REVIEW */
+#ifdef PA_USE_C99_LRINTF
+        float scaled = *src * 0x7FFFFFFF;
+        *dest = lrintf(scaled-0.5f);
+#else
+        double scaled = *src * 0x7FFFFFFF;
+        *dest = (PaInt32) scaled;        
+#endif
+        
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+
+    while( count-- )
+    {
+        /* REVIEW */
+#ifdef PA_USE_C99_LRINTF
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = ((float)*src * (2147483646.0f)) + dither;
+        *dest = lrintf(dithered - 0.5f);
+#else
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        *dest = (PaInt32) dithered;
+#endif
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        /* REVIEW */
+#ifdef PA_USE_C99_LRINTF
+        float scaled = *src * 0x7FFFFFFF;
+        PA_CLIP_( scaled, -2147483648.f, 2147483647.f  );
+        *dest = lrintf(scaled-0.5f);
+#else
+        double scaled = *src * 0x7FFFFFFF;
+        PA_CLIP_( scaled, -2147483648., 2147483647.  );
+        *dest = (PaInt32) scaled;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+
+    while( count-- )
+    {
+        /* REVIEW */
+#ifdef PA_USE_C99_LRINTF
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = ((float)*src * (2147483646.0f)) + dither;
+        PA_CLIP_( dithered, -2147483648.f, 2147483647.f  );
+        *dest = lrintf(dithered-0.5f);
+#else
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        PA_CLIP_( dithered, -2147483648., 2147483647.  );
+        *dest = (PaInt32) dithered;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    PaInt32 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        /* convert to 32 bit and drop the low 8 bits */
+        double scaled = (double)(*src) * 2147483647.0;
+        temp = (PaInt32) scaled;
+        
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 24);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 8);
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    PaInt32 temp;
+
+    while( count-- )
+    {
+        /* convert to 32 bit and drop the low 8 bits */
+
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        
+        temp = (PaInt32) dithered;
+
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 24);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 8);
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    PaInt32 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        /* convert to 32 bit and drop the low 8 bits */
+        double scaled = *src * 0x7FFFFFFF;
+        PA_CLIP_( scaled, -2147483648., 2147483647.  );
+        temp = (PaInt32) scaled;
+
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 24);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 8);
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    PaInt32 temp;
+    
+    while( count-- )
+    {
+        /* convert to 32 bit and drop the low 8 bits */
+        
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        PA_CLIP_( dithered, -2147483648., 2147483647.  );
+        
+        temp = (PaInt32) dithered;
+
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 24);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 8);
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+#ifdef PA_USE_C99_LRINTF
+        float tempf = (*src * (32767.0f)) ;
+        *dest = lrintf(tempf-0.5f);
+#else
+        short samp = (short) (*src * (32767.0f));
+        *dest = samp;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt16 *dest = (PaInt16*)destinationBuffer;
+
+    while( count-- )
+    {
+
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (32766.0f)) + dither;
+
+#ifdef PA_USE_C99_LRINTF
+        *dest = lrintf(dithered-0.5f);
+#else
+        *dest = (PaInt16) dithered;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+#ifdef PA_USE_C99_LRINTF
+        long samp = lrintf((*src * (32767.0f)) -0.5f);
+#else
+        long samp = (PaInt32) (*src * (32767.0f));
+#endif
+        PA_CLIP_( samp, -0x8000, 0x7FFF );
+        *dest = (PaInt16) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (32766.0f)) + dither;
+        PaInt32 samp = (PaInt32) dithered;
+        PA_CLIP_( samp, -0x8000, 0x7FFF );
+#ifdef PA_USE_C99_LRINTF
+        *dest = lrintf(samp-0.5f);
+#else
+        *dest = (PaInt16) samp;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        signed char samp = (signed char) (*src * (127.0f));
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    
+    while( count-- )
+    {
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (126.0f)) + dither;
+        PaInt32 samp = (PaInt32) dithered;
+        *dest = (signed char) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int8_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        PaInt32 samp = (PaInt32)(*src * (127.0f));
+        PA_CLIP_( samp, -0x80, 0x7F );
+        *dest = (signed char) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int8_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (126.0f)) + dither;
+        PaInt32 samp = (PaInt32) dithered;
+        PA_CLIP_( samp, -0x80, 0x7F );
+        *dest = (signed char) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_UInt8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        unsigned char samp = (unsigned char)(128 + ((unsigned char) (*src * (127.0f))));
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_UInt8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    
+    while( count-- )
+    {
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (126.0f)) + dither;
+        PaInt32 samp = (PaInt32) dithered;
+        *dest = (unsigned char) (128 + samp);
+        
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_UInt8_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        PaInt32 samp = 128 + (PaInt32)(*src * (127.0f));
+        PA_CLIP_( samp, 0x0000, 0x00FF );
+        *dest = (unsigned char) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_UInt8_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        /* use smaller scaler to prevent overflow when we add the dither */
+        float dithered = (*src * (126.0f)) + dither;
+        PaInt32 samp = 128 + (PaInt32) dithered;
+        PA_CLIP_( samp, 0x0000, 0x00FF );
+        *dest = (unsigned char) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Float32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    float *dest =  (float*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        *dest = (float) ((double)*src * const_1_div_2147483648_);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src    = (PaInt32*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    (void) ditherGenerator; /* unused parameter */
+    
+       while( count-- )
+    {
+               /* REVIEW */
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = (unsigned char)(*src >> 8);
+        dest[1] = (unsigned char)(*src >> 16);
+        dest[2] = (unsigned char)(*src >> 24);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(*src >> 24);
+        dest[1] = (unsigned char)(*src >> 16);
+        dest[2] = (unsigned char)(*src >> 8);
+#endif
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int24_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    (void) destinationBuffer; /* unused parameters */
+    (void) destinationStride; /* unused parameters */
+    (void) sourceBuffer; /* unused parameters */
+    (void) sourceStride; /* unused parameters */
+    (void) count; /* unused parameters */
+    (void) ditherGenerator; /* unused parameters */
+    /* IMPLEMENT ME */
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        *dest = (PaInt16) ((*src) >> 16);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int16_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    PaInt32 dither;
+
+    while( count-- )
+    {
+        /* REVIEW */
+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );
+        *dest = (PaInt16) ((((*src)>>1) + dither) >> 15);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        *dest = (signed char) ((*src) >> 24);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_Int8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    PaInt32 dither;
+
+    while( count-- )
+    {
+        /* REVIEW */
+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );
+        *dest = (signed char) ((((*src)>>1) + dither) >> 23);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_UInt8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+               (*dest) = (unsigned char)(((*src) >> 24) + 128); 
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int32_To_UInt8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt32 *src = (PaInt32*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        /* IMPLEMENT ME */
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Float32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    float *dest = (float*)destinationBuffer;
+    PaInt32 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        temp = (((PaInt32)src[0]) << 8);  
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 24);
+#elif defined(PA_BIG_ENDIAN)
+        temp = (((PaInt32)src[0]) << 24);
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 8);
+#endif
+
+        *dest = (float) ((double)temp * const_1_div_2147483648_);
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src  = (unsigned char*)sourceBuffer;
+    PaInt32 *dest = (PaInt32*)  destinationBuffer;
+    PaInt32 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        temp = (((PaInt32)src[0]) << 8);  
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 24);
+#elif defined(PA_BIG_ENDIAN)
+        temp = (((PaInt32)src[0]) << 24);
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 8);
+#endif
+
+        *dest = temp;
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    PaInt16 *dest = (PaInt16*)destinationBuffer;
+    
+    PaInt16 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+        
+    while( count-- )
+    {
+               
+#if defined(PA_LITTLE_ENDIAN)
+               /* src[0] is discarded */
+        temp = (((PaInt16)src[1]));
+        temp = temp | (PaInt16)(((PaInt16)src[2]) << 8);
+#elif defined(PA_BIG_ENDIAN)
+               /* src[2] is discarded */
+        temp = (PaInt16)(((PaInt16)src[0]) << 8);
+        temp = temp | (((PaInt16)src[1]));
+#endif
+
+        *dest = temp;
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Int16_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    PaInt16 *dest = (PaInt16*)destinationBuffer;
+
+    PaInt32 temp, dither;
+
+    while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        temp = (((PaInt32)src[0]) << 8);  
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 24);
+#elif defined(PA_BIG_ENDIAN)
+        temp = (((PaInt32)src[0]) << 24);
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 8);
+#endif
+
+        /* REVIEW */
+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );
+        *dest = (PaInt16) (((temp >> 1) + dither) >> 15);
+
+        src  += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Int8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    signed char  *dest = (signed char*)destinationBuffer;
+    
+    (void) ditherGenerator; /* unused parameter */
+        
+    while( count-- )
+    {  
+       
+#if defined(PA_LITTLE_ENDIAN)
+               /* src[0] is discarded */
+               /* src[1] is discarded */
+        *dest = src[2];
+#elif defined(PA_BIG_ENDIAN)
+               /* src[2] is discarded */
+               /* src[1] is discarded */
+               *dest = src[0];
+#endif
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_Int8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    signed char  *dest = (signed char*)destinationBuffer;
+    
+    PaInt32 temp, dither;
+
+    while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        temp = (((PaInt32)src[0]) << 8);  
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 24);
+#elif defined(PA_BIG_ENDIAN)
+        temp = (((PaInt32)src[0]) << 24);
+        temp = temp | (((PaInt32)src[1]) << 16);
+        temp = temp | (((PaInt32)src[2]) << 8);
+#endif
+
+        /* REVIEW */
+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );
+        *dest = (signed char) (((temp >> 1) + dither) >> 23);
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_UInt8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    
+    (void) ditherGenerator; /* unused parameter */
+        
+    while( count-- )
+    {
+               
+#if defined(PA_LITTLE_ENDIAN)
+               /* src[0] is discarded */
+               /* src[1] is discarded */
+        *dest = (unsigned char)(src[2] + 128);
+#elif defined(PA_BIG_ENDIAN)
+        *dest = (unsigned char)(src[0] + 128);
+               /* src[1] is discarded */
+               /* src[2] is discarded */               
+#endif
+
+        src += sourceStride * 3;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int24_To_UInt8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    (void) destinationBuffer; /* unused parameters */
+    (void) destinationStride; /* unused parameters */
+    (void) sourceBuffer; /* unused parameters */
+    (void) sourceStride; /* unused parameters */
+    (void) count; /* unused parameters */
+    (void) ditherGenerator; /* unused parameters */
+    /* IMPLEMENT ME */
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_Float32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    float *dest =  (float*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        float samp = *src * const_1_div_32768_; /* FIXME: i'm concerned about this being asymetrical with float->int16 -rb */
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        /* REVIEW: we should consider something like
+            (*src << 16) | (*src & 0xFFFF)
+        */
+        
+        *dest = *src << 16;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src   = (PaInt16*) sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    PaInt16 temp;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        temp = *src;
+        
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = 0;
+        dest[1] = (unsigned char)(temp);
+        dest[2] = (unsigned char)(temp >> 8);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp);
+        dest[2] = 0;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_Int8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        (*dest) = (signed char)((*src) >> 8);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_Int8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    signed char *dest =  (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        /* IMPLEMENT ME */
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_UInt8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+               (*dest) = (unsigned char)(((*src) >> 8) + 128); 
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int16_To_UInt8_Dither(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaInt16 *src = (PaInt16*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        /* IMPLEMENT ME */
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int8_To_Float32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    signed char *src = (signed char*)sourceBuffer;
+    float *dest =  (float*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        float samp = *src * const_1_div_128_;
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int8_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    signed char *src = (signed char*)sourceBuffer;
+    PaInt32 *dest =  (PaInt32*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+               (*dest) = (*src) << 24;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int8_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    signed char *src = (signed char*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = 0;
+        dest[1] = 0;
+        dest[2] = (*src);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (*src);
+        dest[1] = 0;
+        dest[2] = 0;
+#endif
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int8_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    signed char *src = (signed char*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        (*dest) = (PaInt16)((*src) << 8);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Int8_To_UInt8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    signed char *src = (signed char*)sourceBuffer;
+    unsigned char *dest =  (unsigned char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        (*dest) = (unsigned char)(*src + 128);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void UInt8_To_Float32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    float *dest =  (float*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        float samp = (*src - 128) * const_1_div_128_;
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void UInt8_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    PaInt32 *dest = (PaInt32*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+               (*dest) = (*src - 128) << 24;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void UInt8_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+       unsigned char *src  = (unsigned char*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    (void) ditherGenerator; /* unused parameters */
+    
+       while( count-- )
+    {
+
+#if defined(PA_LITTLE_ENDIAN)
+        dest[0] = 0;
+        dest[1] = 0;
+        dest[2] = (unsigned char)(*src - 128);
+#elif defined(PA_BIG_ENDIAN)
+        dest[0] = (unsigned char)(*src - 128);
+        dest[1] = 0;
+        dest[2] = 0;
+#endif
+               
+        src += sourceStride;
+        dest += destinationStride * 3;    
+       }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void UInt8_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    PaInt16 *dest =  (PaInt16*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        (*dest) = (PaInt16)((*src - 128) << 8);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void UInt8_To_Int8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    signed char  *dest = (signed char*)destinationBuffer;
+    (void)ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        (*dest) = (signed char)(*src - 128);
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Copy_8_To_8(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+                                                      
+    (void) ditherGenerator; /* unused parameter */
+
+    while( count-- )
+    {
+        *dest = *src;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Copy_16_To_16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaUint16 *src = (PaUint16 *)sourceBuffer;
+    PaUint16 *dest = (PaUint16 *)destinationBuffer;
+                                                        
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        *dest = *src;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Copy_24_To_24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    unsigned char *src = (unsigned char*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        dest[0] = src[0];
+        dest[1] = src[1];
+        dest[2] = src[2];
+
+        src += sourceStride * 3;
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Copy_32_To_32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    PaUint32 *dest = (PaUint32 *)destinationBuffer;
+    PaUint32 *src = (PaUint32 *)sourceBuffer;
+
+    (void) ditherGenerator; /* unused parameter */
+    
+    while( count-- )
+    {
+        *dest = *src;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilConverterTable paConverters = {
+    Float32_To_Int32,              /* PaUtilConverter *Float32_To_Int32; */
+    Float32_To_Int32_Dither,       /* PaUtilConverter *Float32_To_Int32_Dither; */
+    Float32_To_Int32_Clip,         /* PaUtilConverter *Float32_To_Int32_Clip; */
+    Float32_To_Int32_DitherClip,   /* PaUtilConverter *Float32_To_Int32_DitherClip; */
+
+    Float32_To_Int24,              /* PaUtilConverter *Float32_To_Int24; */
+    Float32_To_Int24_Dither,       /* PaUtilConverter *Float32_To_Int24_Dither; */
+    Float32_To_Int24_Clip,         /* PaUtilConverter *Float32_To_Int24_Clip; */
+    Float32_To_Int24_DitherClip,   /* PaUtilConverter *Float32_To_Int24_DitherClip; */
+    
+    Float32_To_Int16,              /* PaUtilConverter *Float32_To_Int16; */
+    Float32_To_Int16_Dither,       /* PaUtilConverter *Float32_To_Int16_Dither; */
+    Float32_To_Int16_Clip,         /* PaUtilConverter *Float32_To_Int16_Clip; */
+    Float32_To_Int16_DitherClip,   /* PaUtilConverter *Float32_To_Int16_DitherClip; */
+
+    Float32_To_Int8,               /* PaUtilConverter *Float32_To_Int8; */
+    Float32_To_Int8_Dither,        /* PaUtilConverter *Float32_To_Int8_Dither; */
+    Float32_To_Int8_Clip,          /* PaUtilConverter *Float32_To_Int8_Clip; */
+    Float32_To_Int8_DitherClip,    /* PaUtilConverter *Float32_To_Int8_DitherClip; */
+
+    Float32_To_UInt8,              /* PaUtilConverter *Float32_To_UInt8; */
+    Float32_To_UInt8_Dither,       /* PaUtilConverter *Float32_To_UInt8_Dither; */
+    Float32_To_UInt8_Clip,         /* PaUtilConverter *Float32_To_UInt8_Clip; */
+    Float32_To_UInt8_DitherClip,   /* PaUtilConverter *Float32_To_UInt8_DitherClip; */
+
+    Int32_To_Float32,              /* PaUtilConverter *Int32_To_Float32; */
+    Int32_To_Int24,                /* PaUtilConverter *Int32_To_Int24; */
+    Int32_To_Int24_Dither,         /* PaUtilConverter *Int32_To_Int24_Dither; */
+    Int32_To_Int16,                /* PaUtilConverter *Int32_To_Int16; */
+    Int32_To_Int16_Dither,         /* PaUtilConverter *Int32_To_Int16_Dither; */
+    Int32_To_Int8,                 /* PaUtilConverter *Int32_To_Int8; */
+    Int32_To_Int8_Dither,          /* PaUtilConverter *Int32_To_Int8_Dither; */
+    Int32_To_UInt8,                /* PaUtilConverter *Int32_To_UInt8; */
+    Int32_To_UInt8_Dither,         /* PaUtilConverter *Int32_To_UInt8_Dither; */
+
+    Int24_To_Float32,              /* PaUtilConverter *Int24_To_Float32; */
+    Int24_To_Int32,                /* PaUtilConverter *Int24_To_Int32; */
+    Int24_To_Int16,                /* PaUtilConverter *Int24_To_Int16; */
+    Int24_To_Int16_Dither,         /* PaUtilConverter *Int24_To_Int16_Dither; */
+    Int24_To_Int8,                 /* PaUtilConverter *Int24_To_Int8; */
+    Int24_To_Int8_Dither,          /* PaUtilConverter *Int24_To_Int8_Dither; */
+    Int24_To_UInt8,                /* PaUtilConverter *Int24_To_UInt8; */
+    Int24_To_UInt8_Dither,         /* PaUtilConverter *Int24_To_UInt8_Dither; */
+
+    Int16_To_Float32,              /* PaUtilConverter *Int16_To_Float32; */
+    Int16_To_Int32,                /* PaUtilConverter *Int16_To_Int32; */
+    Int16_To_Int24,                /* PaUtilConverter *Int16_To_Int24; */
+    Int16_To_Int8,                 /* PaUtilConverter *Int16_To_Int8; */
+    Int16_To_Int8_Dither,          /* PaUtilConverter *Int16_To_Int8_Dither; */
+    Int16_To_UInt8,                /* PaUtilConverter *Int16_To_UInt8; */
+    Int16_To_UInt8_Dither,         /* PaUtilConverter *Int16_To_UInt8_Dither; */
+
+    Int8_To_Float32,               /* PaUtilConverter *Int8_To_Float32; */
+    Int8_To_Int32,                 /* PaUtilConverter *Int8_To_Int32; */
+    Int8_To_Int24,                 /* PaUtilConverter *Int8_To_Int24 */
+    Int8_To_Int16,                 /* PaUtilConverter *Int8_To_Int16; */
+    Int8_To_UInt8,                 /* PaUtilConverter *Int8_To_UInt8; */
+
+    UInt8_To_Float32,              /* PaUtilConverter *UInt8_To_Float32; */
+    UInt8_To_Int32,                /* PaUtilConverter *UInt8_To_Int32; */
+    UInt8_To_Int24,                /* PaUtilConverter *UInt8_To_Int24; */
+    UInt8_To_Int16,                /* PaUtilConverter *UInt8_To_Int16; */
+    UInt8_To_Int8,                 /* PaUtilConverter *UInt8_To_Int8; */
+
+    Copy_8_To_8,                   /* PaUtilConverter *Copy_8_To_8; */
+    Copy_16_To_16,                 /* PaUtilConverter *Copy_16_To_16; */
+    Copy_24_To_24,                 /* PaUtilConverter *Copy_24_To_24; */
+    Copy_32_To_32                  /* PaUtilConverter *Copy_32_To_32; */
+};
+
+/* -------------------------------------------------------------------------- */
+
+#endif /* PA_NO_STANDARD_CONVERTERS */
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat )
+{
+    switch( destinationFormat & ~paNonInterleaved ){
+    case paFloat32:
+        return paZeroers.Zero32;
+    case paInt32:
+        return paZeroers.Zero32;
+    case paInt24:
+        return paZeroers.Zero24;
+    case paInt16:
+        return paZeroers.Zero16;
+    case paInt8:
+        return paZeroers.Zero8;
+    case paUInt8:
+        return paZeroers.ZeroU8;
+    default: return 0;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+#ifdef PA_NO_STANDARD_ZEROERS
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilZeroerTable paZeroers = {
+    0,  /* PaUtilZeroer *ZeroU8; */
+    0,  /* PaUtilZeroer *Zero8; */
+    0,  /* PaUtilZeroer *Zero16; */
+    0,  /* PaUtilZeroer *Zero24; */
+    0,  /* PaUtilZeroer *Zero32; */
+};
+
+/* -------------------------------------------------------------------------- */
+
+#else /* PA_NO_STANDARD_ZEROERS is not defined */
+
+/* -------------------------------------------------------------------------- */
+
+static void ZeroU8( void *destinationBuffer, signed int destinationStride,
+        unsigned int count )
+{
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+
+    while( count-- )
+    {
+        *dest = 128;
+
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Zero8( void *destinationBuffer, signed int destinationStride,
+        unsigned int count )
+{
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+
+    while( count-- )
+    {
+        *dest = 0;
+
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Zero16( void *destinationBuffer, signed int destinationStride,
+        unsigned int count )
+{
+    PaUint16 *dest = (PaUint16 *)destinationBuffer;
+
+    while( count-- )
+    {
+        *dest = 0;
+
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Zero24( void *destinationBuffer, signed int destinationStride,
+        unsigned int count )
+{
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+
+    while( count-- )
+    {
+        dest[0] = 0;
+        dest[1] = 0;
+        dest[2] = 0;
+
+        dest += destinationStride * 3;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Zero32( void *destinationBuffer, signed int destinationStride,
+        unsigned int count )
+{
+    PaUint32 *dest = (PaUint32 *)destinationBuffer;
+
+    while( count-- )
+    {
+        *dest = 0;
+
+        dest += destinationStride;
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+PaUtilZeroerTable paZeroers = {
+    ZeroU8,  /* PaUtilZeroer *ZeroU8; */
+    Zero8,  /* PaUtilZeroer *Zero8; */
+    Zero16,  /* PaUtilZeroer *Zero16; */
+    Zero24,  /* PaUtilZeroer *Zero24; */
+    Zero32,  /* PaUtilZeroer *Zero32; */
+};
+
+/* -------------------------------------------------------------------------- */
+
+#endif /* PA_NO_STANDARD_ZEROERS */
diff --git a/portaudio/src/common/pa_converters.h b/portaudio/src/common/pa_converters.h
new file mode 100644 (file)
index 0000000..469f075
--- /dev/null
@@ -0,0 +1,263 @@
+#ifndef PA_CONVERTERS_H
+#define PA_CONVERTERS_H
+/*
+ * $Id$
+ * Portable Audio I/O Library sample conversion mechanism
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Conversion functions used to convert buffers of samples from one
+ format to another.
+*/
+
+
+#include "portaudio.h"  /* for PaSampleFormat */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+struct PaUtilTriangularDitherGenerator;
+
+
+/** Choose an available sample format which is most appropriate for
+ representing the requested format. If the requested format is not available
+ higher quality formats are considered before lower quality formates.
+ @param availableFormats A variable containing the logical OR of all available
+ formats.
+ @param format The desired format.
+ @return The most appropriate available format for representing the requested
+ format.
+*/
+PaSampleFormat PaUtil_SelectClosestAvailableFormat(
+        PaSampleFormat availableFormats, PaSampleFormat format );
+
+
+/* high level conversions functions for use by implementations */
+
+
+/** The generic sample converter prototype. Sample converters convert count
+    samples from sourceBuffer to destinationBuffer. The actual type of the data
+    pointed to by these parameters varys for different converter functions.
+    @param destinationBuffer A pointer to the first sample of the destination.
+    @param destinationStride An offset between successive destination samples
+    expressed in samples (not bytes.) It may be negative.
+    @param sourceBuffer A pointer to the first sample of the source.
+    @param sourceStride An offset between successive source samples
+    expressed in samples (not bytes.) It may be negative.
+    @param count The number of samples to convert.
+    @param ditherState State information used to calculate dither. Converters
+    that do not perform dithering will ignore this parameter, in which case
+    NULL or invalid dither state may be passed.
+*/
+typedef void PaUtilConverter(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator );
+
+
+/** Find a sample converter function for the given source and destinations
+    formats and flags (clip and dither.)
+    @return
+    A pointer to a PaUtilConverter which will perform the requested
+    conversion, or NULL if the given format conversion is not supported.
+    For conversions where clipping or dithering is not necessary, the
+    clip and dither flags are ignored and a non-clipping or dithering
+    version is returned.
+    If the source and destination formats are the same, a function which
+    copies data of the appropriate size will be returned.
+*/
+PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,
+        PaSampleFormat destinationFormat, PaStreamFlags flags );
+
+
+/** The generic buffer zeroer prototype. Buffer zeroers copy count zeros to
+    destinationBuffer. The actual type of the data pointed to varys for
+    different zeroer functions.
+    @param destinationBuffer A pointer to the first sample of the destination.
+    @param destinationStride An offset between successive destination samples
+    expressed in samples (not bytes.) It may be negative.
+    @param count The number of samples to zero.
+*/
+typedef void PaUtilZeroer(
+    void *destinationBuffer, signed int destinationStride, unsigned int count );
+
+    
+/** Find a buffer zeroer function for the given destination format.
+    @return
+    A pointer to a PaUtilZeroer which will perform the requested
+    zeroing.
+*/
+PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat );
+
+/*----------------------------------------------------------------------------*/
+/* low level functions and data structures which may be used for
+    substituting conversion functions */
+
+
+/** The type used to store all sample conversion functions.
+    @see paConverters;
+*/
+typedef struct{
+    PaUtilConverter *Float32_To_Int32;
+    PaUtilConverter *Float32_To_Int32_Dither;
+    PaUtilConverter *Float32_To_Int32_Clip;
+    PaUtilConverter *Float32_To_Int32_DitherClip;
+
+    PaUtilConverter *Float32_To_Int24;
+    PaUtilConverter *Float32_To_Int24_Dither;
+    PaUtilConverter *Float32_To_Int24_Clip;
+    PaUtilConverter *Float32_To_Int24_DitherClip;
+    
+    PaUtilConverter *Float32_To_Int16;
+    PaUtilConverter *Float32_To_Int16_Dither;
+    PaUtilConverter *Float32_To_Int16_Clip;
+    PaUtilConverter *Float32_To_Int16_DitherClip;
+
+    PaUtilConverter *Float32_To_Int8;
+    PaUtilConverter *Float32_To_Int8_Dither;
+    PaUtilConverter *Float32_To_Int8_Clip;
+    PaUtilConverter *Float32_To_Int8_DitherClip;
+
+    PaUtilConverter *Float32_To_UInt8;
+    PaUtilConverter *Float32_To_UInt8_Dither;
+    PaUtilConverter *Float32_To_UInt8_Clip;
+    PaUtilConverter *Float32_To_UInt8_DitherClip;
+
+    PaUtilConverter *Int32_To_Float32;
+    PaUtilConverter *Int32_To_Int24;
+    PaUtilConverter *Int32_To_Int24_Dither;
+    PaUtilConverter *Int32_To_Int16;
+    PaUtilConverter *Int32_To_Int16_Dither;
+    PaUtilConverter *Int32_To_Int8;
+    PaUtilConverter *Int32_To_Int8_Dither;
+    PaUtilConverter *Int32_To_UInt8;
+    PaUtilConverter *Int32_To_UInt8_Dither;
+
+    PaUtilConverter *Int24_To_Float32;
+    PaUtilConverter *Int24_To_Int32;
+    PaUtilConverter *Int24_To_Int16;
+    PaUtilConverter *Int24_To_Int16_Dither;
+    PaUtilConverter *Int24_To_Int8;
+    PaUtilConverter *Int24_To_Int8_Dither;
+    PaUtilConverter *Int24_To_UInt8;
+    PaUtilConverter *Int24_To_UInt8_Dither;
+
+    PaUtilConverter *Int16_To_Float32;
+    PaUtilConverter *Int16_To_Int32;
+    PaUtilConverter *Int16_To_Int24;
+    PaUtilConverter *Int16_To_Int8;
+    PaUtilConverter *Int16_To_Int8_Dither;
+    PaUtilConverter *Int16_To_UInt8;
+    PaUtilConverter *Int16_To_UInt8_Dither;
+
+    PaUtilConverter *Int8_To_Float32;
+    PaUtilConverter *Int8_To_Int32;
+    PaUtilConverter *Int8_To_Int24;
+    PaUtilConverter *Int8_To_Int16;
+    PaUtilConverter *Int8_To_UInt8;
+    
+    PaUtilConverter *UInt8_To_Float32;
+    PaUtilConverter *UInt8_To_Int32;
+    PaUtilConverter *UInt8_To_Int24;
+    PaUtilConverter *UInt8_To_Int16;
+    PaUtilConverter *UInt8_To_Int8;
+
+    PaUtilConverter *Copy_8_To_8;       /* copy without any conversion */
+    PaUtilConverter *Copy_16_To_16;     /* copy without any conversion */
+    PaUtilConverter *Copy_24_To_24;     /* copy without any conversion */
+    PaUtilConverter *Copy_32_To_32;     /* copy without any conversion */
+} PaUtilConverterTable;
+
+
+/** A table of pointers to all required converter functions.
+    PaUtil_SelectConverter() uses this table to lookup the appropriate
+    conversion functions. The fields of this structure are initialized
+    with default conversion functions. Fields may be NULL, indicating that
+    no conversion function is available. User code may substitue optimised
+    conversion functions by assigning different function pointers to
+    these fields.
+
+    @note
+    If the PA_NO_STANDARD_CONVERTERS preprocessor variable is defined,
+    PortAudio's standard converters will not be compiled, and all fields
+    of this structure will be initialized to NULL. In such cases, users
+    should supply their own conversion functions if the require PortAudio
+    to open a stream that requires sample conversion.
+
+    @see PaUtilConverterTable, PaUtilConverter, PaUtil_SelectConverter
+*/
+extern PaUtilConverterTable paConverters;
+
+
+/** The type used to store all buffer zeroing functions.
+    @see paZeroers;
+*/
+typedef struct{
+    PaUtilZeroer *ZeroU8; /* unsigned 8 bit, zero == 128 */
+    PaUtilZeroer *Zero8;
+    PaUtilZeroer *Zero16;
+    PaUtilZeroer *Zero24;
+    PaUtilZeroer *Zero32;
+} PaUtilZeroerTable;
+
+
+/** A table of pointers to all required zeroer functions.
+    PaUtil_SelectZeroer() uses this table to lookup the appropriate
+    conversion functions. The fields of this structure are initialized
+    with default conversion functions. User code may substitue optimised
+    conversion functions by assigning different function pointers to
+    these fields.
+
+    @note
+    If the PA_NO_STANDARD_ZEROERS preprocessor variable is defined,
+    PortAudio's standard zeroers will not be compiled, and all fields
+    of this structure will be initialized to NULL. In such cases, users
+    should supply their own zeroing functions for the sample sizes which
+    they intend to use.
+
+    @see PaUtilZeroerTable, PaUtilZeroer, PaUtil_SelectZeroer
+*/
+extern PaUtilZeroerTable paZeroers;
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_CONVERTERS_H */
diff --git a/portaudio/src/common/pa_cpuload.c b/portaudio/src/common/pa_cpuload.c
new file mode 100644 (file)
index 0000000..4adf21a
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library CPU Load measurement functions
+ * Portable CPU load measurement facility.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 2002 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Functions to assist in measuring the CPU utilization of a callback
+ stream. Used to implement the Pa_GetStreamCpuLoad() function.
+
+ @todo Dynamically calculate the coefficients used to smooth the CPU Load
+ Measurements over time to provide a uniform characterisation of CPU Load
+ independent of rate at which PaUtil_BeginCpuLoadMeasurement /
+ PaUtil_EndCpuLoadMeasurement are called. see http://www.portaudio.com/trac/ticket/113
+*/
+
+
+#include "pa_cpuload.h"
+
+#include <assert.h>
+
+#include "pa_util.h"   /* for PaUtil_GetTime() */
+
+
+void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate )
+{
+    assert( sampleRate > 0 );
+
+    measurer->samplingPeriod = 1. / sampleRate;
+    measurer->averageLoad = 0.;
+}
+
+void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer )
+{
+    measurer->averageLoad = 0.;
+}
+
+void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer )
+{
+    measurer->measurementStartTime = PaUtil_GetTime();
+}
+
+
+void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed )
+{
+    double measurementEndTime, secondsFor100Percent, measuredLoad;
+
+    if( framesProcessed > 0 ){
+        measurementEndTime = PaUtil_GetTime();
+
+        assert( framesProcessed > 0 );
+        secondsFor100Percent = framesProcessed * measurer->samplingPeriod;
+
+        measuredLoad = (measurementEndTime - measurer->measurementStartTime) / secondsFor100Percent;
+
+        /* Low pass filter the calculated CPU load to reduce jitter using a simple IIR low pass filter. */
+        /** FIXME @todo these coefficients shouldn't be hardwired see: http://www.portaudio.com/trac/ticket/113 */
+#define LOWPASS_COEFFICIENT_0   (0.9)
+#define LOWPASS_COEFFICIENT_1   (0.99999 - LOWPASS_COEFFICIENT_0)
+
+        measurer->averageLoad = (LOWPASS_COEFFICIENT_0 * measurer->averageLoad) +
+                               (LOWPASS_COEFFICIENT_1 * measuredLoad);
+    }
+}
+
+
+double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer )
+{
+    return measurer->averageLoad;
+}
diff --git a/portaudio/src/common/pa_cpuload.h b/portaudio/src/common/pa_cpuload.h
new file mode 100644 (file)
index 0000000..2a323aa
--- /dev/null
@@ -0,0 +1,72 @@
+#ifndef PA_CPULOAD_H
+#define PA_CPULOAD_H
+/*
+ * $Id$
+ * Portable Audio I/O Library CPU Load measurement functions
+ * Portable CPU load measurement facility.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 2002 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Functions to assist in measuring the CPU utilization of a callback
+ stream. Used to implement the Pa_GetStreamCpuLoad() function.
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+typedef struct {
+    double samplingPeriod;
+    double measurementStartTime;
+    double averageLoad;
+} PaUtilCpuLoadMeasurer; /**< @todo need better name than measurer */
+
+void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate );
+void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer );
+void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed );
+void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer );
+double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */     
+#endif /* PA_CPULOAD_H */
diff --git a/portaudio/src/common/pa_debugprint.c b/portaudio/src/common/pa_debugprint.c
new file mode 100644 (file)
index 0000000..f34d4bb
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * $Id: pa_log.c $
+ * Portable Audio I/O Library Multi-Host API front end
+ * Validate function parameters and manage multiple host APIs.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Implements log function.
+
+    PaUtil_SetLogPrintFunction can be user called to replace the provided
+       DefaultLogPrint function, which writes to stderr.
+       One can NOT pass var_args across compiler/dll boundaries as it is not
+       "byte code/abi portable". So the technique used here is to allocate a local
+       a static array, write in it, then callback the user with a pointer to its
+       start.
+*/
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#include "pa_debugprint.h"
+
+// for OutputDebugStringA
+#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
+       #define WIN32_LEAN_AND_MEAN // exclude rare headers
+       #include "windows.h"
+#endif
+
+// User callback
+static PaUtilLogCallback userCB = NULL;
+
+// Sets user callback
+void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
+{
+    userCB = cb;
+}
+
+/*
+ If your platform doesn\92t have vsnprintf, you are stuck with a
+ VERY dangerous alternative, vsprintf (with no n)
+*/
+#if _MSC_VER
+       /* Some Windows Mobile SDKs don't define vsnprintf but all define _vsnprintf (hopefully).
+          According to MSDN "vsnprintf is identical to _vsnprintf". So we use _vsnprintf with MSC.
+       */
+       #define VSNPRINTF  _vsnprintf 
+#else
+       #define VSNPRINTF  vsnprintf
+#endif
+
+#define PA_LOG_BUF_SIZE 2048
+
+void PaUtil_DebugPrint( const char *format, ... )
+{
+       // Optional logging into Output console of Visual Studio
+#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
+       {
+               char buf[PA_LOG_BUF_SIZE];
+               va_list ap;
+               va_start(ap, format);
+               VSNPRINTF(buf, sizeof(buf), format, ap);
+               buf[sizeof(buf)-1] = 0;
+               OutputDebugStringA(buf);
+               va_end(ap);
+       }
+#endif
+
+       // Output to User-Callback
+    if (userCB != NULL)
+    {
+        char strdump[PA_LOG_BUF_SIZE];
+        va_list ap;
+        va_start(ap, format);
+        VSNPRINTF(strdump, sizeof(strdump), format, ap);
+        strdump[sizeof(strdump)-1] = 0;
+        userCB(strdump);
+        va_end(ap);
+    }
+    else
+       // Standard output to stderr
+    {
+        va_list ap;
+        va_start(ap, format);
+        vfprintf(stderr, format, ap);
+        va_end(ap);
+        fflush(stderr);
+    }
+}
diff --git a/portaudio/src/common/pa_debugprint.h b/portaudio/src/common/pa_debugprint.h
new file mode 100644 (file)
index 0000000..5fba766
--- /dev/null
@@ -0,0 +1,149 @@
+#ifndef PA_LOG_H
+#define PA_LOG_H
+/*
+ * Log file redirector function
+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+
+void PaUtil_DebugPrint( const char *format, ... );
+
+
+/*
+    The basic format for log messages is described below. If you need to
+    add any log messages, please follow this format.
+
+    Function entry (void function):
+
+        "FunctionName called.\n"
+
+    Function entry (non void function):
+
+        "FunctionName called:\n"
+        "\tParam1Type param1: param1Value\n"
+        "\tParam2Type param2: param2Value\n"      (etc...)
+
+
+    Function exit (no return value):
+
+        "FunctionName returned.\n"
+
+    Function exit (simple return value):
+
+        "FunctionName returned:\n"
+        "\tReturnType: returnValue\n"
+
+    If the return type is an error code, the error text is displayed in ()
+
+    If the return type is not an error code, but has taken a special value
+    because an error occurred, then the reason for the error is shown in []
+
+    If the return type is a struct ptr, the struct is dumped.
+
+    See the code below for examples
+*/
+
+/** PA_DEBUG() provides a simple debug message printing facility. The macro
+ passes it's argument to a printf-like function called PaUtil_DebugPrint()
+ which prints to stderr and always flushes the stream after printing.
+ Because preprocessor macros cannot directly accept variable length argument
+ lists, calls to the macro must include an additional set of parenthesis, eg:
+ PA_DEBUG(("errorno: %d", 1001 ));
+*/
+
+
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+#define PA_DEBUG(x) PaUtil_DebugPrint x ;
+#else
+#define PA_DEBUG(x)
+#endif
+
+
+#ifdef PA_LOG_API_CALLS
+#define PA_LOGAPI(x) PaUtil_DebugPrint x 
+
+#define PA_LOGAPI_ENTER(functionName) PaUtil_DebugPrint( functionName " called.\n" )
+
+#define PA_LOGAPI_ENTER_PARAMS(functionName) PaUtil_DebugPrint( functionName " called:\n" )
+
+#define PA_LOGAPI_EXIT(functionName) PaUtil_DebugPrint( functionName " returned.\n" )
+
+#define PA_LOGAPI_EXIT_PAERROR( functionName, result ) \
+       PaUtil_DebugPrint( functionName " returned:\n" ); \
+       PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )
+
+#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result ) \
+       PaUtil_DebugPrint( functionName " returned:\n" ); \
+       PaUtil_DebugPrint("\t" resultFormatString "\n", result )
+
+#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result ) \
+       PaUtil_DebugPrint( functionName " returned:\n" ); \
+       if( result > 0 ) \
+        PaUtil_DebugPrint("\t" positiveResultFormatString "\n", result ); \
+    else \
+        PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )
+#else
+#define PA_LOGAPI(x)
+#define PA_LOGAPI_ENTER(functionName)
+#define PA_LOGAPI_ENTER_PARAMS(functionName)
+#define PA_LOGAPI_EXIT(functionName)
+#define PA_LOGAPI_EXIT_PAERROR( functionName, result )
+#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result )
+#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result )
+#endif
+
+    
+typedef void (*PaUtilLogCallback ) (const char *log);
+
+/**
+    Install user provided log function
+*/
+void PaUtil_SetDebugPrintFunction(PaUtilLogCallback  cb);
+
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_LOG_H */
diff --git a/portaudio/src/common/pa_dither.c b/portaudio/src/common/pa_dither.c
new file mode 100644 (file)
index 0000000..140e480
--- /dev/null
@@ -0,0 +1,218 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library triangular dither generator
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Functions for generating dither noise
+*/
+
+#include "pa_types.h"
+#include "pa_dither.h"
+
+
+/* Note that the linear congruential algorithm requires 32 bit integers
+ * because it uses arithmetic overflow. So use PaUint32 instead of
+ * unsigned long so it will work on 64 bit systems.
+ */
+
+#define PA_DITHER_BITS_   (15)
+
+
+void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state )
+{
+    state->previous = 0;
+    state->randSeed1 = 22222;
+    state->randSeed2 = 5555555;
+}
+
+
+PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )
+{
+    PaInt32 current, highPass;
+
+    /* Generate two random numbers. */
+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;
+
+    /* Generate triangular distribution about 0.
+     * Shift before adding to prevent overflow which would skew the distribution.
+     * Also shift an extra bit for the high pass filter. 
+     */
+#define DITHER_SHIFT_  ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1)
+       
+    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
+              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
+
+    /* High pass filter to reduce audibility. */
+    highPass = current - state->previous;
+    state->previous = current;
+    return highPass;
+}
+
+
+/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */
+#define PA_FLOAT_DITHER_SCALE_  (1.0f / ((1<<PA_DITHER_BITS_)-1))
+static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
+
+float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state )
+{
+    PaInt32 current, highPass;
+
+    /* Generate two random numbers. */
+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;
+
+    /* Generate triangular distribution about 0.
+     * Shift before adding to prevent overflow which would skew the distribution.
+     * Also shift an extra bit for the high pass filter. 
+     */
+    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
+              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
+
+    /* High pass filter to reduce audibility. */
+    highPass = current - state->previous;
+    state->previous = current;
+    return ((float)highPass) * const_float_dither_scale_;
+}
+
+
+/*
+The following alternate dither algorithms (from musicdsp.org) could be
+considered
+*/
+
+/*Noise shaped dither  (March 2000)
+-------------------
+
+This is a simple implementation of highpass triangular-PDF dither with
+2nd-order noise shaping, for use when truncating floating point audio
+data to fixed point.
+
+The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz
+sample rate) compared to triangular-PDF dither. The code below assumes
+input data is in the range +1 to -1 and doesn't check for overloads!
+
+To save time when generating dither for multiple channels you can do
+things like this:  r3=(r1 & 0x7F)<<8; instead of calling rand() again.
+
+
+
+  int   r1, r2;                //rectangular-PDF random numbers
+  float s1, s2;                //error feedback buffers
+  float s = 0.5f;              //set to 0.0f for no noise shaping
+  float w = pow(2.0,bits-1);   //word length (usually bits=16)
+  float wi= 1.0f/w;            
+  float d = wi / RAND_MAX;     //dither amplitude (2 lsb)
+  float o = wi * 0.5f;         //remove dc offset
+  float in, tmp;
+  int   out;
+
+
+//for each sample...
+
+  r2=r1;                               //can make HP-TRI dither by
+  r1=rand();                           //subtracting previous rand()
+    
+  in += s * (s1 + s1 - s2);            //error feedback
+  tmp = in + o + d * (float)(r1 - r2); //dc offset and dither 
+  
+  out = (int)(w * tmp);                //truncate downwards
+  if(tmp<0.0f) out--;                  //this is faster than floor()
+
+  s2 = s1;                            
+  s1 = in - wi * (float)out;           //error
+
+
+
+-- 
+paul.kellett@maxim.abel.co.uk
+http://www.maxim.abel.co.uk
+*/
+
+
+/*
+16-to-8-bit first-order dither
+
+Type : First order error feedforward dithering code
+References : Posted by Jon Watte
+
+Notes : 
+This is about as simple a dithering algorithm as you can implement, but it's
+likely to sound better than just truncating to N bits.
+
+Note that you might not want to carry forward the full difference for infinity.
+It's probably likely that the worst performance hit comes from the saturation
+conditionals, which can be avoided with appropriate instructions on many DSPs
+and integer SIMD type instructions, or CMOV.
+
+Last, if sound quality is paramount (such as when going from > 16 bits to 16
+bits) you probably want to use a higher-order dither function found elsewhere
+on this site. 
+
+
+Code : 
+// This code will down-convert and dither a 16-bit signed short 
+// mono signal into an 8-bit unsigned char signal, using a first 
+// order forward-feeding error term dither. 
+
+#define uchar unsigned char 
+
+void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) 
+{ 
+  int m = *memory; 
+  while( count-- > 0 ) { 
+    int i = *input++; 
+    i += m; 
+    int j = i + 32768 - 128; 
+    uchar o; 
+    if( j < 0 ) { 
+      o = 0; 
+    } 
+    else if( j > 65535 ) { 
+      o = 255; 
+    } 
+    else { 
+      o = (uchar)((j>>8)&0xff); 
+    } 
+    m = ((j-32768+128)-i); 
+    *output++ = o; 
+  } 
+  *memory = m; 
+} 
+*/
diff --git a/portaudio/src/common/pa_dither.h b/portaudio/src/common/pa_dither.h
new file mode 100644 (file)
index 0000000..12ffc4f
--- /dev/null
@@ -0,0 +1,106 @@
+#ifndef PA_DITHER_H
+#define PA_DITHER_H
+/*
+ * $Id$
+ * Portable Audio I/O Library triangular dither generator
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Functions for generating dither noise
+*/
+
+#include "pa_types.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/* Note that the linear congruential algorithm requires 32 bit integers
+ * because it uses arithmetic overflow. So use PaUint32 instead of
+ * unsigned long so it will work on 64 bit systems.
+ */
+
+/** @brief State needed to generate a dither signal */
+typedef struct PaUtilTriangularDitherGenerator{
+    PaUint32 previous;
+    PaUint32 randSeed1;
+    PaUint32 randSeed2;
+} PaUtilTriangularDitherGenerator;
+
+
+/** @brief Initialize dither state */
+void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *ditherState );
+
+
+/**
+ @brief Calculate 2 LSB dither signal with a triangular distribution.
+ Ranged for adding to a 1 bit right-shifted 32 bit integer
+ prior to >>15. eg:
+<pre>
+    signed long in = *
+    signed long dither = PaUtil_Generate16BitTriangularDither( ditherState );
+    signed short out = (signed short)(((in>>1) + dither) >> 15);
+</pre>
+ @return
+ A signed 32-bit integer with a range of +32767 to -32768
+*/
+PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
+
+
+/**
+ @brief Calculate 2 LSB dither signal with a triangular distribution.
+ Ranged for adding to a pre-scaled float.
+<pre>
+    float in = *
+    float dither = PaUtil_GenerateFloatTriangularDither( ditherState );
+    // use smaller scaler to prevent overflow when we add the dither
+    signed short out = (signed short)(in*(32766.0f) + dither );
+</pre>
+ @return
+ A float with a range of -2.0 to +1.99999.
+*/
+float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
+
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_DITHER_H */
diff --git a/portaudio/src/common/pa_endianness.h b/portaudio/src/common/pa_endianness.h
new file mode 100644 (file)
index 0000000..9e8e059
--- /dev/null
@@ -0,0 +1,145 @@
+#ifndef PA_ENDIANNESS_H
+#define PA_ENDIANNESS_H
+/*
+ * $Id$
+ * Portable Audio I/O Library current platform endianness macros
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Configure endianness symbols for the target processor.
+
+ Arrange for either the PA_LITTLE_ENDIAN or PA_BIG_ENDIAN preprocessor symbols
+ to be defined. The one that is defined reflects the endianness of the target
+ platform and may be used to implement conditional compilation of byte-order
+ dependent code.
+
+ If either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN is defined already, then no attempt
+ is made to override that setting. This may be useful if you have a better way
+ of determining the platform's endianness. The autoconf mechanism uses this for
+ example.
+
+ A PA_VALIDATE_ENDIANNESS macro is provided to compare the compile time
+ and runtime endiannes and raise an assertion if they don't match.
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/* If this is an apple, we need to do detect endianness this way */
+#if defined(__APPLE__)
+    /* we need to do some endian detection that is sensitive to harware arch */
+    #if defined(__LITTLE_ENDIAN__)
+       #if !defined( PA_LITTLE_ENDIAN )
+          #define PA_LITTLE_ENDIAN
+       #endif
+       #if defined( PA_BIG_ENDIAN )
+          #undef PA_BIG_ENDIAN
+       #endif
+    #else
+       #if !defined( PA_BIG_ENDIAN )
+          #define PA_BIG_ENDIAN
+       #endif
+       #if defined( PA_LITTLE_ENDIAN )
+          #undef PA_LITTLE_ENDIAN
+       #endif
+    #endif
+#else
+    /* this is not an apple, so first check the existing defines, and, failing that,
+       detect well-known architechtures. */
+
+    #if defined(PA_LITTLE_ENDIAN) || defined(PA_BIG_ENDIAN)
+        /* endianness define has been set externally, such as by autoconf */
+
+        #if defined(PA_LITTLE_ENDIAN) && defined(PA_BIG_ENDIAN)
+        #error both PA_LITTLE_ENDIAN and PA_BIG_ENDIAN have been defined externally to pa_endianness.h - only one endianness at a time please
+        #endif
+
+    #else
+        /* endianness define has not been set externally */
+
+        /* set PA_LITTLE_ENDIAN or PA_BIG_ENDIAN by testing well known platform specific defines */
+
+        #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) || defined(LITTLE_ENDIAN) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__)
+            #define PA_LITTLE_ENDIAN /* win32, assume intel byte order */
+        #else
+            #define PA_BIG_ENDIAN
+        #endif
+    #endif
+
+    #if !defined(PA_LITTLE_ENDIAN) && !defined(PA_BIG_ENDIAN)
+        /*
+         If the following error is raised, you either need to modify the code above
+         to automatically determine the endianness from other symbols defined on your
+         platform, or define either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN externally.
+        */
+        #error pa_endianness.h was unable to automatically determine the endianness of the target platform
+    #endif
+
+#endif
+
+
+/* PA_VALIDATE_ENDIANNESS compares the compile time and runtime endianness,
+ and raises an assertion if they don't match. <assert.h> must be included in
+ the context in which this macro is used.
+*/
+#if defined(NDEBUG)
+    #define PA_VALIDATE_ENDIANNESS
+#else
+    #if defined(PA_LITTLE_ENDIAN)
+        #define PA_VALIDATE_ENDIANNESS \
+        { \
+            const long nativeOne = 1; \
+            assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \
+        }
+    #elif defined(PA_BIG_ENDIAN)
+        #define PA_VALIDATE_ENDIANNESS \
+        { \
+            const long nativeOne = 1; \
+            assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \
+        }
+    #endif
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_ENDIANNESS_H */
diff --git a/portaudio/src/common/pa_front.c b/portaudio/src/common/pa_front.c
new file mode 100644 (file)
index 0000000..188cee9
--- /dev/null
@@ -0,0 +1,1811 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library Multi-Host API front end
+ * Validate function parameters and manage multiple host APIs.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Implements PortAudio API functions defined in portaudio.h, checks
+ some errors, delegates platform-specific behavior to host API implementations.
+
+ Implements the functions defined in the PortAudio API (portaudio.h),
+ validates some parameters and checks for state inconsistencies before
+ forwarding API requests to specific Host API implementations (via the
+ interface declared in pa_hostapi.h), and Streams (via the interface
+ declared in pa_stream.h).
+
+ This file manages initialization and termination of Host API
+ implementations via initializer functions stored in the paHostApiInitializers
+ global array (usually defined in an os-specific pa_[os]_hostapis.c file).
+
+ This file maintains a list of all open streams and closes them at Pa_Terminate().
+
+ Some utility functions declared in pa_util.h are implemented in this file.
+
+ All PortAudio API functions can be conditionally compiled with logging code.
+ To compile with logging, define the PA_LOG_API_CALLS precompiler symbol.
+*/
+
+
+#include <stdio.h>
+#include <memory.h>
+#include <string.h>
+#include <stdlib.h> /* needed for strtol() */
+#include <assert.h> /* needed by PA_VALIDATE_ENDIANNESS */
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_endianness.h"
+#include "pa_types.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_trace.h" /* still usefull?*/
+#include "pa_debugprint.h"
+
+#ifndef PA_GIT_REVISION
+#include "pa_gitrevision.h"
+#endif
+
+/**
+ * This is incremented if we make incompatible API changes.
+ * This version scheme is based loosely on http://semver.org/
+ */
+#define paVersionMajor     19
+
+/**
+ * This is incremented when we add functionality in a backwards-compatible manner.
+ * Or it is set to zero when paVersionMajor is incremented.
+ */
+#define paVersionMinor      6
+
+/**
+ * This is incremented when we make backwards-compatible bug fixes.
+ * Or it is set to zero when paVersionMinor changes.
+ */
+#define paVersionSubMinor   0
+
+/**
+ * This is a combination of paVersionMajor, paVersionMinor and paVersionSubMinor.
+ * It will always increase so that version numbers can be compared as integers to
+ * see which is later.
+ */
+#define paVersion  paMakeVersionNumber(paVersionMajor, paVersionMinor, paVersionSubMinor)
+
+#define STRINGIFY(x) #x
+#define TOSTRING(x) STRINGIFY(x)
+
+#define PA_VERSION_STRING_ TOSTRING(paVersionMajor) "." TOSTRING(paVersionMinor) "." TOSTRING(paVersionSubMinor)
+#define PA_VERSION_TEXT_   "PortAudio V" PA_VERSION_STRING_ "-devel, revision " TOSTRING(PA_GIT_REVISION)
+
+int Pa_GetVersion( void )
+{
+    return paVersion;
+}
+
+const char* Pa_GetVersionText( void )
+{
+    return PA_VERSION_TEXT_;
+}
+
+static PaVersionInfo versionInfo_ = {
+    /*.versionMajor =*/ paVersionMajor,
+    /*.versionMinor =*/ paVersionMinor,
+    /*.versionSubMinor =*/ paVersionSubMinor,
+    /*.versionControlRevision =*/ TOSTRING(PA_GIT_REVISION),
+    /*.versionText =*/ PA_VERSION_TEXT_
+};
+
+const PaVersionInfo* Pa_GetVersionInfo()
+{
+    return &versionInfo_;
+}
+
+#define PA_LAST_HOST_ERROR_TEXT_LENGTH_  1024
+
+static char lastHostErrorText_[ PA_LAST_HOST_ERROR_TEXT_LENGTH_ + 1 ] = {0};
+
+static PaHostErrorInfo lastHostErrorInfo_ = { (PaHostApiTypeId)-1, 0, lastHostErrorText_ };
+
+
+void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,
+        const char *errorText )
+{
+    lastHostErrorInfo_.hostApiType = hostApiType;
+    lastHostErrorInfo_.errorCode = errorCode;
+
+    strncpy( lastHostErrorText_, errorText, PA_LAST_HOST_ERROR_TEXT_LENGTH_ );
+}
+
+
+
+static PaUtilHostApiRepresentation **hostApis_ = 0;
+static int hostApisCount_ = 0;
+static int defaultHostApiIndex_ = 0;
+static int initializationCount_ = 0;
+static int deviceCount_ = 0;
+
+PaUtilStreamRepresentation *firstOpenStream_ = NULL;
+
+
+#define PA_IS_INITIALISED_ (initializationCount_ != 0)
+
+
+static int CountHostApiInitializers( void )
+{
+    int result = 0;
+
+    while( paHostApiInitializers[ result ] != 0 )
+        ++result;
+    return result;
+}
+
+
+static void TerminateHostApis( void )
+{
+    /* terminate in reverse order from initialization */
+    PA_DEBUG(("TerminateHostApis in \n"));
+
+    while( hostApisCount_ > 0 )
+    {
+        --hostApisCount_;
+        hostApis_[hostApisCount_]->Terminate( hostApis_[hostApisCount_] );
+    }
+    hostApisCount_ = 0;
+    defaultHostApiIndex_ = 0;
+    deviceCount_ = 0;
+
+    if( hostApis_ != 0 )
+        PaUtil_FreeMemory( hostApis_ );
+    hostApis_ = 0;
+
+    PA_DEBUG(("TerminateHostApis out\n"));
+}
+
+
+static PaError InitializeHostApis( void )
+{
+    PaError result = paNoError;
+    int i, initializerCount, baseDeviceIndex;
+
+    initializerCount = CountHostApiInitializers();
+
+    hostApis_ = (PaUtilHostApiRepresentation**)PaUtil_AllocateMemory(
+            sizeof(PaUtilHostApiRepresentation*) * initializerCount );
+    if( !hostApis_ )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    hostApisCount_ = 0;
+    defaultHostApiIndex_ = -1; /* indicates that we haven't determined the default host API yet */
+    deviceCount_ = 0;
+    baseDeviceIndex = 0;
+
+    for( i=0; i< initializerCount; ++i )
+    {
+        hostApis_[hostApisCount_] = NULL;
+
+        PA_DEBUG(( "before paHostApiInitializers[%d].\n",i));
+
+        result = paHostApiInitializers[i]( &hostApis_[hostApisCount_], hostApisCount_ );
+        if( result != paNoError )
+            goto error;
+
+        PA_DEBUG(( "after paHostApiInitializers[%d].\n",i));
+
+        if( hostApis_[hostApisCount_] )
+        {
+            PaUtilHostApiRepresentation* hostApi = hostApis_[hostApisCount_];
+            assert( hostApi->info.defaultInputDevice < hostApi->info.deviceCount );
+            assert( hostApi->info.defaultOutputDevice < hostApi->info.deviceCount );
+
+            /* the first successfully initialized host API with a default input *or*
+               output device is used as the default host API.
+            */
+            if( (defaultHostApiIndex_ == -1) &&
+                    ( hostApi->info.defaultInputDevice != paNoDevice
+                        || hostApi->info.defaultOutputDevice != paNoDevice ) )
+            {
+                defaultHostApiIndex_ = hostApisCount_;
+            }
+
+            hostApi->privatePaFrontInfo.baseDeviceIndex = baseDeviceIndex;
+
+            if( hostApi->info.defaultInputDevice != paNoDevice )
+                hostApi->info.defaultInputDevice += baseDeviceIndex;
+
+            if( hostApi->info.defaultOutputDevice != paNoDevice )
+                hostApi->info.defaultOutputDevice += baseDeviceIndex;
+
+            baseDeviceIndex += hostApi->info.deviceCount;
+            deviceCount_ += hostApi->info.deviceCount;
+
+            ++hostApisCount_;
+        }
+    }
+
+    /* if no host APIs have devices, the default host API is the first initialized host API */
+    if( defaultHostApiIndex_ == -1 )
+        defaultHostApiIndex_ = 0;
+
+    return result;
+
+error:
+    TerminateHostApis();
+    return result;
+}
+
+
+/*
+    FindHostApi() finds the index of the host api to which
+    <device> belongs and returns it. if <hostSpecificDeviceIndex> is
+    non-null, the host specific device index is returned in it.
+    returns -1 if <device> is out of range.
+
+*/
+static int FindHostApi( PaDeviceIndex device, int *hostSpecificDeviceIndex )
+{
+    int i=0;
+
+    if( !PA_IS_INITIALISED_ )
+        return -1;
+
+    if( device < 0 )
+        return -1;
+
+    while( i < hostApisCount_
+            && device >= hostApis_[i]->info.deviceCount )
+    {
+
+        device -= hostApis_[i]->info.deviceCount;
+        ++i;
+    }
+
+    if( i >= hostApisCount_ )
+        return -1;
+
+    if( hostSpecificDeviceIndex )
+        *hostSpecificDeviceIndex = device;
+
+    return i;
+}
+
+
+static void AddOpenStream( PaStream* stream )
+{
+    ((PaUtilStreamRepresentation*)stream)->nextOpenStream = firstOpenStream_;
+    firstOpenStream_ = (PaUtilStreamRepresentation*)stream;
+}
+
+
+static void RemoveOpenStream( PaStream* stream )
+{
+    PaUtilStreamRepresentation *previous = NULL;
+    PaUtilStreamRepresentation *current = firstOpenStream_;
+
+    while( current != NULL )
+    {
+        if( ((PaStream*)current) == stream )
+        {
+            if( previous == NULL )
+            {
+                firstOpenStream_ = current->nextOpenStream;
+            }
+            else
+            {
+                previous->nextOpenStream = current->nextOpenStream;
+            }
+            return;
+        }
+        else
+        {
+            previous = current;
+            current = current->nextOpenStream;
+        }
+    }
+}
+
+
+static void CloseOpenStreams( void )
+{
+    /* we call Pa_CloseStream() here to ensure that the same destruction
+        logic is used for automatically closed streams */
+
+    while( firstOpenStream_ != NULL )
+        Pa_CloseStream( firstOpenStream_ );
+}
+
+
+PaError Pa_Initialize( void )
+{
+    PaError result;
+
+    PA_LOGAPI_ENTER( "Pa_Initialize" );
+
+    if( PA_IS_INITIALISED_ )
+    {
+        ++initializationCount_;
+        result = paNoError;
+    }
+    else
+    {
+        PA_VALIDATE_TYPE_SIZES;
+        PA_VALIDATE_ENDIANNESS;
+
+        PaUtil_InitializeClock();
+        PaUtil_ResetTraceMessages();
+
+        result = InitializeHostApis();
+        if( result == paNoError )
+            ++initializationCount_;
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_Initialize", result );
+
+    return result;
+}
+
+
+PaError Pa_Terminate( void )
+{
+    PaError result;
+
+    PA_LOGAPI_ENTER( "Pa_Terminate" );
+
+    if( PA_IS_INITIALISED_ )
+    {
+        // leave initializationCount_>0 so that Pa_CloseStream() can execute
+        if( initializationCount_ == 1 )
+        {
+            CloseOpenStreams();
+
+            TerminateHostApis();
+
+            PaUtil_DumpTraceMessages();
+        }
+        --initializationCount_;
+        result = paNoError;
+    }
+    else
+    {
+        result=  paNotInitialized;
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_Terminate", result );
+
+    return result;
+}
+
+
+const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void )
+{
+    return &lastHostErrorInfo_;
+}
+
+
+const char *Pa_GetErrorText( PaError errorCode )
+{
+    const char *result;
+
+    switch( errorCode )
+    {
+    case paNoError:                  result = "Success"; break;
+    case paNotInitialized:           result = "PortAudio not initialized"; break;
+    /** @todo could catenate the last host error text to result in the case of paUnanticipatedHostError. see: http://www.portaudio.com/trac/ticket/114 */
+    case paUnanticipatedHostError:   result = "Unanticipated host error"; break;
+    case paInvalidChannelCount:      result = "Invalid number of channels"; break;
+    case paInvalidSampleRate:        result = "Invalid sample rate"; break;
+    case paInvalidDevice:            result = "Invalid device"; break;
+    case paInvalidFlag:              result = "Invalid flag"; break;
+    case paSampleFormatNotSupported: result = "Sample format not supported"; break;
+    case paBadIODeviceCombination:   result = "Illegal combination of I/O devices"; break;
+    case paInsufficientMemory:       result = "Insufficient memory"; break;
+    case paBufferTooBig:             result = "Buffer too big"; break;
+    case paBufferTooSmall:           result = "Buffer too small"; break;
+    case paNullCallback:             result = "No callback routine specified"; break;
+    case paBadStreamPtr:             result = "Invalid stream pointer"; break;
+    case paTimedOut:                 result = "Wait timed out"; break;
+    case paInternalError:            result = "Internal PortAudio error"; break;
+    case paDeviceUnavailable:        result = "Device unavailable"; break;
+    case paIncompatibleHostApiSpecificStreamInfo:   result = "Incompatible host API specific stream info"; break;
+    case paStreamIsStopped:          result = "Stream is stopped"; break;
+    case paStreamIsNotStopped:       result = "Stream is not stopped"; break;
+    case paInputOverflowed:          result = "Input overflowed"; break;
+    case paOutputUnderflowed:        result = "Output underflowed"; break;
+    case paHostApiNotFound:          result = "Host API not found"; break;
+    case paInvalidHostApi:           result = "Invalid host API"; break;
+    case paCanNotReadFromACallbackStream:       result = "Can't read from a callback stream"; break;
+    case paCanNotWriteToACallbackStream:        result = "Can't write to a callback stream"; break;
+    case paCanNotReadFromAnOutputOnlyStream:    result = "Can't read from an output only stream"; break;
+    case paCanNotWriteToAnInputOnlyStream:      result = "Can't write to an input only stream"; break;
+    case paIncompatibleStreamHostApi: result = "Incompatible stream host API"; break;
+    case paBadBufferPtr:             result = "Bad buffer pointer"; break;
+    default:
+               if( errorCode > 0 )
+                       result = "Invalid error code (value greater than zero)";
+        else
+                       result = "Invalid error code";
+        break;
+    }
+    return result;
+}
+
+
+PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type )
+{
+    PaHostApiIndex result;
+    int i;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiTypeIdToHostApiIndex" );
+    PA_LOGAPI(("\tPaHostApiTypeId type: %d\n", type ));
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        result = paHostApiNotFound;
+
+        for( i=0; i < hostApisCount_; ++i )
+        {
+            if( hostApis_[i]->info.type == type )
+            {
+                result = i;
+                break;
+            }
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiTypeIdToHostApiIndex", "PaHostApiIndex: %d", result );
+
+    return result;
+}
+
+
+PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,
+        PaHostApiTypeId type )
+{
+    PaError result;
+    int i;
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        result = paHostApiNotFound;
+
+        for( i=0; i < hostApisCount_; ++i )
+        {
+            if( hostApis_[i]->info.type == type )
+            {
+                *hostApi = hostApis_[i];
+                result = paNoError;
+                break;
+            }
+        }
+    }
+
+    return result;
+}
+
+
+PaError PaUtil_DeviceIndexToHostApiDeviceIndex(
+        PaDeviceIndex *hostApiDevice, PaDeviceIndex device, struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaError result;
+    PaDeviceIndex x;
+
+    x = device - hostApi->privatePaFrontInfo.baseDeviceIndex;
+
+    if( x < 0 || x >= hostApi->info.deviceCount )
+    {
+        result = paInvalidDevice;
+    }
+    else
+    {
+        *hostApiDevice = x;
+        result = paNoError;
+    }
+
+    return result;
+}
+
+
+PaHostApiIndex Pa_GetHostApiCount( void )
+{
+    int result;
+
+    PA_LOGAPI_ENTER( "Pa_GetHostApiCount" );
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        result = hostApisCount_;
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetHostApiCount", "PaHostApiIndex: %d", result );
+
+    return result;
+}
+
+
+PaHostApiIndex Pa_GetDefaultHostApi( void )
+{
+    int result;
+
+    PA_LOGAPI_ENTER( "Pa_GetDefaultHostApi" );
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        result = defaultHostApiIndex_;
+
+        /* internal consistency check: make sure that the default host api
+         index is within range */
+
+        if( result < 0 || result >= hostApisCount_ )
+        {
+            result = paInternalError;
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDefaultHostApi", "PaHostApiIndex: %d", result );
+
+    return result;
+}
+
+
+const PaHostApiInfo* Pa_GetHostApiInfo( PaHostApiIndex hostApi )
+{
+    PaHostApiInfo *info;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetHostApiInfo" );
+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        info = NULL;
+
+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));
+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ PortAudio not initialized ]\n" ));
+
+    }
+    else if( hostApi < 0 || hostApi >= hostApisCount_ )
+    {
+        info = NULL;
+
+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));
+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ hostApi out of range ]\n" ));
+
+    }
+    else
+    {
+        info = &hostApis_[hostApi]->info;
+
+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));
+        PA_LOGAPI(("\tPaHostApiInfo*: 0x%p\n", info ));
+        PA_LOGAPI(("\t{\n" ));
+        PA_LOGAPI(("\t\tint structVersion: %d\n", info->structVersion ));
+        PA_LOGAPI(("\t\tPaHostApiTypeId type: %d\n", info->type ));
+        PA_LOGAPI(("\t\tconst char *name: %s\n", info->name ));
+        PA_LOGAPI(("\t}\n" ));
+
+    }
+
+     return info;
+}
+
+
+PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, int hostApiDeviceIndex )
+{
+    PaDeviceIndex result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiDeviceIndexToPaDeviceIndex" );
+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));
+    PA_LOGAPI(("\tint hostApiDeviceIndex: %d\n", hostApiDeviceIndex ));
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        if( hostApi < 0 || hostApi >= hostApisCount_ )
+        {
+            result = paInvalidHostApi;
+        }
+        else
+        {
+            if( hostApiDeviceIndex < 0 ||
+                    hostApiDeviceIndex >= hostApis_[hostApi]->info.deviceCount )
+            {
+                result = paInvalidDevice;
+            }
+            else
+            {
+                result = hostApis_[hostApi]->privatePaFrontInfo.baseDeviceIndex + hostApiDeviceIndex;
+            }
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiDeviceIndexToPaDeviceIndex", "PaDeviceIndex: %d", result );
+
+    return result;
+}
+
+
+PaDeviceIndex Pa_GetDeviceCount( void )
+{
+    PaDeviceIndex result;
+
+    PA_LOGAPI_ENTER( "Pa_GetDeviceCount" );
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+    }
+    else
+    {
+        result = deviceCount_;
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDeviceCount", "PaDeviceIndex: %d", result );
+
+    return result;
+}
+
+
+PaDeviceIndex Pa_GetDefaultInputDevice( void )
+{
+    PaHostApiIndex hostApi;
+    PaDeviceIndex result;
+
+    PA_LOGAPI_ENTER( "Pa_GetDefaultInputDevice" );
+
+    hostApi = Pa_GetDefaultHostApi();
+    if( hostApi < 0 )
+    {
+        result = paNoDevice;
+    }
+    else
+    {
+        result = hostApis_[hostApi]->info.defaultInputDevice;
+    }
+
+    PA_LOGAPI_EXIT_T( "Pa_GetDefaultInputDevice", "PaDeviceIndex: %d", result );
+
+    return result;
+}
+
+
+PaDeviceIndex Pa_GetDefaultOutputDevice( void )
+{
+    PaHostApiIndex hostApi;
+    PaDeviceIndex result;
+
+    PA_LOGAPI_ENTER( "Pa_GetDefaultOutputDevice" );
+
+    hostApi = Pa_GetDefaultHostApi();
+    if( hostApi < 0 )
+    {
+        result = paNoDevice;
+    }
+    else
+    {
+        result = hostApis_[hostApi]->info.defaultOutputDevice;
+    }
+
+    PA_LOGAPI_EXIT_T( "Pa_GetDefaultOutputDevice", "PaDeviceIndex: %d", result );
+
+    return result;
+}
+
+
+const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device )
+{
+    int hostSpecificDeviceIndex;
+    int hostApiIndex = FindHostApi( device, &hostSpecificDeviceIndex );
+    PaDeviceInfo *result;
+
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetDeviceInfo" );
+    PA_LOGAPI(("\tPaDeviceIndex device: %d\n", device ));
+
+    if( hostApiIndex < 0 )
+    {
+        result = NULL;
+
+        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));
+        PA_LOGAPI(("\tPaDeviceInfo* NULL [ invalid device index ]\n" ));
+
+    }
+    else
+    {
+        result = hostApis_[hostApiIndex]->deviceInfos[ hostSpecificDeviceIndex ];
+
+        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));
+        PA_LOGAPI(("\tPaDeviceInfo*: 0x%p:\n", result ));
+        PA_LOGAPI(("\t{\n" ));
+
+        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));
+        PA_LOGAPI(("\t\tconst char *name: %s\n", result->name ));
+        PA_LOGAPI(("\t\tPaHostApiIndex hostApi: %d\n", result->hostApi ));
+        PA_LOGAPI(("\t\tint maxInputChannels: %d\n", result->maxInputChannels ));
+        PA_LOGAPI(("\t\tint maxOutputChannels: %d\n", result->maxOutputChannels ));
+        PA_LOGAPI(("\t}\n" ));
+
+    }
+
+    return result;
+}
+
+
+/*
+    SampleFormatIsValid() returns 1 if sampleFormat is a sample format
+    defined in portaudio.h, or 0 otherwise.
+*/
+static int SampleFormatIsValid( PaSampleFormat format )
+{
+    switch( format & ~paNonInterleaved )
+    {
+    case paFloat32: return 1;
+    case paInt16: return 1;
+    case paInt32: return 1;
+    case paInt24: return 1;
+    case paInt8: return 1;
+    case paUInt8: return 1;
+    case paCustomFormat: return 1;
+    default: return 0;
+    }
+}
+
+/*
+    NOTE: make sure this validation list is kept syncronised with the one in
+            pa_hostapi.h
+
+    ValidateOpenStreamParameters() checks that parameters to Pa_OpenStream()
+    conform to the expected values as described below. This function is
+    also designed to be used with the proposed Pa_IsFormatSupported() function.
+
+    There are basically two types of validation that could be performed:
+    Generic conformance validation, and device capability mismatch
+    validation. This function performs only generic conformance validation.
+    Validation that would require knowledge of device capabilities is
+    not performed because of potentially complex relationships between
+    combinations of parameters - for example, even if the sampleRate
+    seems ok, it might not be for a duplex stream - we have no way of
+    checking this in an API-neutral way, so we don't try.
+
+    On success the function returns PaNoError and fills in hostApi,
+    hostApiInputDeviceID, and hostApiOutputDeviceID fields. On failure
+    the function returns an error code indicating the first encountered
+    parameter error.
+
+
+    If ValidateOpenStreamParameters() returns paNoError, the following
+    assertions are guaranteed to be true.
+
+    - at least one of inputParameters & outputParmeters is valid (not NULL)
+
+    - if inputParameters & outputParameters are both valid, that
+        inputParameters->device & outputParameters->device  both use the same host api
+
+    PaDeviceIndex inputParameters->device
+        - is within range (0 to Pa_GetDeviceCount-1) Or:
+        - is paUseHostApiSpecificDeviceSpecification and
+            inputParameters->hostApiSpecificStreamInfo is non-NULL and refers
+            to a valid host api
+
+    int inputParameters->channelCount
+        - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, channelCount is > 0
+        - upper bound is NOT validated against device capabilities
+
+    PaSampleFormat inputParameters->sampleFormat
+        - is one of the sample formats defined in portaudio.h
+
+    void *inputParameters->hostApiSpecificStreamInfo
+        - if supplied its hostApi field matches the input device's host Api
+
+    PaDeviceIndex outputParmeters->device
+        - is within range (0 to Pa_GetDeviceCount-1)
+
+    int outputParmeters->channelCount
+        - if inputDevice is valid, channelCount is > 0
+        - upper bound is NOT validated against device capabilities
+
+    PaSampleFormat outputParmeters->sampleFormat
+        - is one of the sample formats defined in portaudio.h
+
+    void *outputParmeters->hostApiSpecificStreamInfo
+        - if supplied its hostApi field matches the output device's host Api
+
+    double sampleRate
+        - is not an 'absurd' rate (less than 1000. or greater than 384000.)
+        - sampleRate is NOT validated against device capabilities
+
+    PaStreamFlags streamFlags
+        - unused platform neutral flags are zero
+        - paNeverDropInput is only used for full-duplex callback streams with
+            variable buffer size (paFramesPerBufferUnspecified)
+*/
+static PaError ValidateOpenStreamParameters(
+    const PaStreamParameters *inputParameters,
+    const PaStreamParameters *outputParameters,
+    double sampleRate,
+    unsigned long framesPerBuffer,
+    PaStreamFlags streamFlags,
+    PaStreamCallback *streamCallback,
+    PaUtilHostApiRepresentation **hostApi,
+    PaDeviceIndex *hostApiInputDevice,
+    PaDeviceIndex *hostApiOutputDevice )
+{
+    int inputHostApiIndex  = -1, /* Surpress uninitialised var warnings: compiler does */
+        outputHostApiIndex = -1; /* not see that if inputParameters and outputParame-  */
+                                 /* ters are both nonzero, these indices are set.      */
+
+    if( (inputParameters == NULL) && (outputParameters == NULL) )
+    {
+        return paInvalidDevice; /** @todo should be a new error code "invalid device parameters" or something */
+    }
+    else
+    {
+        if( inputParameters == NULL )
+        {
+            *hostApiInputDevice = paNoDevice;
+        }
+        else if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+        {
+            if( inputParameters->hostApiSpecificStreamInfo )
+            {
+                inputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(
+                        ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType );
+
+                if( inputHostApiIndex != -1 )
+                {
+                    *hostApiInputDevice = paUseHostApiSpecificDeviceSpecification;
+                    *hostApi = hostApis_[inputHostApiIndex];
+                }
+                else
+                {
+                    return paInvalidDevice;
+                }
+            }
+            else
+            {
+                return paInvalidDevice;
+            }
+        }
+        else
+        {
+            if( inputParameters->device < 0 || inputParameters->device >= deviceCount_ )
+                return paInvalidDevice;
+
+            inputHostApiIndex = FindHostApi( inputParameters->device, hostApiInputDevice );
+            if( inputHostApiIndex < 0 )
+                return paInternalError;
+
+            *hostApi = hostApis_[inputHostApiIndex];
+
+            if( inputParameters->channelCount <= 0 )
+                return paInvalidChannelCount;
+
+            if( !SampleFormatIsValid( inputParameters->sampleFormat ) )
+                return paSampleFormatNotSupported;
+
+            if( inputParameters->hostApiSpecificStreamInfo != NULL )
+            {
+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType
+                        != (*hostApi)->info.type )
+                    return paIncompatibleHostApiSpecificStreamInfo;
+            }
+        }
+
+        if( outputParameters == NULL )
+        {
+            *hostApiOutputDevice = paNoDevice;
+        }
+        else if( outputParameters->device == paUseHostApiSpecificDeviceSpecification  )
+        {
+            if( outputParameters->hostApiSpecificStreamInfo )
+            {
+                outputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(
+                        ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType );
+
+                if( outputHostApiIndex != -1 )
+                {
+                    *hostApiOutputDevice = paUseHostApiSpecificDeviceSpecification;
+                    *hostApi = hostApis_[outputHostApiIndex];
+                }
+                else
+                {
+                    return paInvalidDevice;
+                }
+            }
+            else
+            {
+                return paInvalidDevice;
+            }
+        }
+        else
+        {
+            if( outputParameters->device < 0 || outputParameters->device >= deviceCount_ )
+                return paInvalidDevice;
+
+            outputHostApiIndex = FindHostApi( outputParameters->device, hostApiOutputDevice );
+            if( outputHostApiIndex < 0 )
+                return paInternalError;
+
+            *hostApi = hostApis_[outputHostApiIndex];
+
+            if( outputParameters->channelCount <= 0 )
+                return paInvalidChannelCount;
+
+            if( !SampleFormatIsValid( outputParameters->sampleFormat ) )
+                return paSampleFormatNotSupported;
+
+            if( outputParameters->hostApiSpecificStreamInfo != NULL )
+            {
+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType
+                        != (*hostApi)->info.type )
+                    return paIncompatibleHostApiSpecificStreamInfo;
+            }
+        }
+
+        if( (inputParameters != NULL) && (outputParameters != NULL) )
+        {
+            /* ensure that both devices use the same API */
+            if( inputHostApiIndex != outputHostApiIndex )
+                return paBadIODeviceCombination;
+        }
+    }
+
+
+    /* Check for absurd sample rates. */
+    if( (sampleRate < 1000.0) || (sampleRate > 384000.0) )
+        return paInvalidSampleRate;
+
+    if( ((streamFlags & ~paPlatformSpecificFlags) & ~(paClipOff | paDitherOff | paNeverDropInput | paPrimeOutputBuffersUsingStreamCallback ) ) != 0 )
+        return paInvalidFlag;
+
+    if( streamFlags & paNeverDropInput )
+    {
+        /* must be a callback stream */
+        if( !streamCallback )
+             return paInvalidFlag;
+
+        /* must be a full duplex stream */
+        if( (inputParameters == NULL) || (outputParameters == NULL) )
+            return paInvalidFlag;
+
+        /* must use paFramesPerBufferUnspecified */
+        if( framesPerBuffer != paFramesPerBufferUnspecified )
+            return paInvalidFlag;
+    }
+
+    return paNoError;
+}
+
+
+PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,
+                              const PaStreamParameters *outputParameters,
+                              double sampleRate )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi = 0;
+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;
+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;
+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;
+
+
+#ifdef PA_LOG_API_CALLS
+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsFormatSupported" );
+
+    if( inputParameters == NULL ){
+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));
+    }else{
+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));
+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));
+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));
+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));
+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));
+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));
+    }
+
+    if( outputParameters == NULL ){
+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));
+    }else{
+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));
+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));
+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));
+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));
+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));
+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));
+    }
+
+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));
+#endif
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+
+        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );
+        return result;
+    }
+
+    result = ValidateOpenStreamParameters( inputParameters,
+                                           outputParameters,
+                                           sampleRate, 0, paNoFlag, 0,
+                                           &hostApi,
+                                           &hostApiInputDevice,
+                                           &hostApiOutputDevice );
+    if( result != paNoError )
+    {
+        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );
+        return result;
+    }
+
+
+    if( inputParameters )
+    {
+        hostApiInputParameters.device = hostApiInputDevice;
+        hostApiInputParameters.channelCount = inputParameters->channelCount;
+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;
+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;
+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;
+        hostApiInputParametersPtr = &hostApiInputParameters;
+    }
+    else
+    {
+        hostApiInputParametersPtr = NULL;
+    }
+
+    if( outputParameters )
+    {
+        hostApiOutputParameters.device = hostApiOutputDevice;
+        hostApiOutputParameters.channelCount = outputParameters->channelCount;
+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;
+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;
+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;
+        hostApiOutputParametersPtr = &hostApiOutputParameters;
+    }
+    else
+    {
+        hostApiOutputParametersPtr = NULL;
+    }
+
+    result = hostApi->IsFormatSupported( hostApi,
+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,
+                                  sampleRate );
+
+#ifdef PA_LOG_API_CALLS
+    PA_LOGAPI(("Pa_OpenStream returned:\n" ));
+    if( result == paFormatIsSupported )
+        PA_LOGAPI(("\tPaError: 0 [ paFormatIsSupported ]\n" ));
+    else
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+#endif
+
+    return result;
+}
+
+
+PaError Pa_OpenStream( PaStream** stream,
+                       const PaStreamParameters *inputParameters,
+                       const PaStreamParameters *outputParameters,
+                       double sampleRate,
+                       unsigned long framesPerBuffer,
+                       PaStreamFlags streamFlags,
+                       PaStreamCallback *streamCallback,
+                       void *userData )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi = 0;
+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;
+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;
+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;
+
+
+#ifdef PA_LOG_API_CALLS
+    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenStream" );
+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));
+
+    if( inputParameters == NULL ){
+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));
+    }else{
+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));
+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));
+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));
+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));
+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));
+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));
+    }
+
+    if( outputParameters == NULL ){
+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));
+    }else{
+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));
+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));
+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));
+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));
+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));
+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));
+    }
+
+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));
+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));
+    PA_LOGAPI(("\tPaStreamFlags streamFlags: 0x%x\n", streamFlags ));
+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));
+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));
+#endif
+
+    if( !PA_IS_INITIALISED_ )
+    {
+        result = paNotInitialized;
+
+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));
+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+        return result;
+    }
+
+    /* Check for parameter errors.
+        NOTE: make sure this validation list is kept syncronised with the one
+        in pa_hostapi.h
+    */
+
+    if( stream == NULL )
+    {
+        result = paBadStreamPtr;
+
+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));
+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+        return result;
+    }
+
+    result = ValidateOpenStreamParameters( inputParameters,
+                                           outputParameters,
+                                           sampleRate, framesPerBuffer,
+                                           streamFlags, streamCallback,
+                                           &hostApi,
+                                           &hostApiInputDevice,
+                                           &hostApiOutputDevice );
+    if( result != paNoError )
+    {
+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));
+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+        return result;
+    }
+
+
+    if( inputParameters )
+    {
+        hostApiInputParameters.device = hostApiInputDevice;
+        hostApiInputParameters.channelCount = inputParameters->channelCount;
+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;
+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;
+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;
+        hostApiInputParametersPtr = &hostApiInputParameters;
+    }
+    else
+    {
+        hostApiInputParametersPtr = NULL;
+    }
+
+    if( outputParameters )
+    {
+        hostApiOutputParameters.device = hostApiOutputDevice;
+        hostApiOutputParameters.channelCount = outputParameters->channelCount;
+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;
+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;
+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;
+        hostApiOutputParametersPtr = &hostApiOutputParameters;
+    }
+    else
+    {
+        hostApiOutputParametersPtr = NULL;
+    }
+
+    result = hostApi->OpenStream( hostApi, stream,
+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,
+                                  sampleRate, framesPerBuffer, streamFlags, streamCallback, userData );
+
+    if( result == paNoError )
+        AddOpenStream( *stream );
+
+
+    PA_LOGAPI(("Pa_OpenStream returned:\n" ));
+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p\n", *stream ));
+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+
+    return result;
+}
+
+
+PaError Pa_OpenDefaultStream( PaStream** stream,
+                              int inputChannelCount,
+                              int outputChannelCount,
+                              PaSampleFormat sampleFormat,
+                              double sampleRate,
+                              unsigned long framesPerBuffer,
+                              PaStreamCallback *streamCallback,
+                              void *userData )
+{
+    PaError result;
+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;
+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenDefaultStream" );
+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));
+    PA_LOGAPI(("\tint inputChannelCount: %d\n", inputChannelCount ));
+    PA_LOGAPI(("\tint outputChannelCount: %d\n", outputChannelCount ));
+    PA_LOGAPI(("\tPaSampleFormat sampleFormat: %d\n", sampleFormat ));
+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));
+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));
+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));
+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));
+
+
+    if( inputChannelCount > 0 )
+    {
+        hostApiInputParameters.device = Pa_GetDefaultInputDevice();
+               if( hostApiInputParameters.device == paNoDevice )
+                       return paDeviceUnavailable;
+
+        hostApiInputParameters.channelCount = inputChannelCount;
+        hostApiInputParameters.sampleFormat = sampleFormat;
+        /* defaultHighInputLatency is used below instead of
+           defaultLowInputLatency because it is more important for the default
+           stream to work reliably than it is for it to work with the lowest
+           latency.
+         */
+        hostApiInputParameters.suggestedLatency =
+             Pa_GetDeviceInfo( hostApiInputParameters.device )->defaultHighInputLatency;
+        hostApiInputParameters.hostApiSpecificStreamInfo = NULL;
+        hostApiInputParametersPtr = &hostApiInputParameters;
+    }
+    else
+    {
+        hostApiInputParametersPtr = NULL;
+    }
+
+    if( outputChannelCount > 0 )
+    {
+        hostApiOutputParameters.device = Pa_GetDefaultOutputDevice();
+               if( hostApiOutputParameters.device == paNoDevice )
+                       return paDeviceUnavailable;
+
+        hostApiOutputParameters.channelCount = outputChannelCount;
+        hostApiOutputParameters.sampleFormat = sampleFormat;
+        /* defaultHighOutputLatency is used below instead of
+           defaultLowOutputLatency because it is more important for the default
+           stream to work reliably than it is for it to work with the lowest
+           latency.
+         */
+        hostApiOutputParameters.suggestedLatency =
+             Pa_GetDeviceInfo( hostApiOutputParameters.device )->defaultHighOutputLatency;
+        hostApiOutputParameters.hostApiSpecificStreamInfo = NULL;
+        hostApiOutputParametersPtr = &hostApiOutputParameters;
+    }
+    else
+    {
+        hostApiOutputParametersPtr = NULL;
+    }
+
+
+    result = Pa_OpenStream(
+                 stream, hostApiInputParametersPtr, hostApiOutputParametersPtr,
+                 sampleRate, framesPerBuffer, paNoFlag, streamCallback, userData );
+
+    PA_LOGAPI(("Pa_OpenDefaultStream returned:\n" ));
+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p", *stream ));
+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+
+    return result;
+}
+
+
+PaError PaUtil_ValidateStreamPointer( PaStream* stream )
+{
+    if( !PA_IS_INITIALISED_ ) return paNotInitialized;
+
+    if( stream == NULL ) return paBadStreamPtr;
+
+    if( ((PaUtilStreamRepresentation*)stream)->magic != PA_STREAM_MAGIC )
+        return paBadStreamPtr;
+
+    return paNoError;
+}
+
+
+PaError Pa_CloseStream( PaStream* stream )
+{
+    PaUtilStreamInterface *interface;
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_CloseStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    /* always remove the open stream from our list, even if this function
+        eventually returns an error. Otherwise CloseOpenStreams() will
+        get stuck in an infinite loop */
+    RemoveOpenStream( stream ); /* be sure to call this _before_ closing the stream */
+
+    if( result == paNoError )
+    {
+        interface = PA_STREAM_INTERFACE(stream);
+
+        /* abort the stream if it isn't stopped */
+        result = interface->IsStopped( stream );
+        if( result == 1 )
+            result = paNoError;
+        else if( result == 0 )
+            result = interface->Abort( stream );
+
+        if( result == paNoError )                 /** @todo REVIEW: shouldn't we close anyway? see: http://www.portaudio.com/trac/ticket/115 */
+            result = interface->Close( stream );
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_CloseStream", result );
+
+    return result;
+}
+
+
+PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_SetStreamFinishedCallback" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+    PA_LOGAPI(("\tPaStreamFinishedCallback* streamFinishedCallback: 0x%p\n", streamFinishedCallback ));
+
+    if( result == paNoError )
+    {
+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+        if( result == 0 )
+        {
+            result = paStreamIsNotStopped ;
+        }
+        if( result == 1 )
+        {
+            PA_STREAM_REP( stream )->streamFinishedCallback = streamFinishedCallback;
+            result = paNoError;
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_SetStreamFinishedCallback", result );
+
+    return result;
+
+}
+
+
+PaError Pa_StartStream( PaStream *stream )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_StartStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+    {
+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+        if( result == 0 )
+        {
+            result = paStreamIsNotStopped ;
+        }
+        else if( result == 1 )
+        {
+            result = PA_STREAM_INTERFACE(stream)->Start( stream );
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_StartStream", result );
+
+    return result;
+}
+
+
+PaError Pa_StopStream( PaStream *stream )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_StopStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+    {
+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+        if( result == 0 )
+        {
+            result = PA_STREAM_INTERFACE(stream)->Stop( stream );
+        }
+        else if( result == 1 )
+        {
+            result = paStreamIsStopped;
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_StopStream", result );
+
+    return result;
+}
+
+
+PaError Pa_AbortStream( PaStream *stream )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_AbortStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+    {
+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+        if( result == 0 )
+        {
+            result = PA_STREAM_INTERFACE(stream)->Abort( stream );
+        }
+        else if( result == 1 )
+        {
+            result = paStreamIsStopped;
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_AbortStream", result );
+
+    return result;
+}
+
+
+PaError Pa_IsStreamStopped( PaStream *stream )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamStopped" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamStopped", result );
+
+    return result;
+}
+
+
+PaError Pa_IsStreamActive( PaStream *stream )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamActive" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+        result = PA_STREAM_INTERFACE(stream)->IsActive( stream );
+
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamActive", result );
+
+    return result;
+}
+
+
+const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream )
+{
+    PaError error = PaUtil_ValidateStreamPointer( stream );
+    const PaStreamInfo *result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamInfo" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( error != paNoError )
+    {
+        result = 0;
+
+        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));
+        PA_LOGAPI(("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n", error, Pa_GetErrorText( error ) ));
+
+    }
+    else
+    {
+        result = &PA_STREAM_REP( stream )->streamInfo;
+
+        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));
+        PA_LOGAPI(("\tconst PaStreamInfo*: 0x%p:\n", result ));
+        PA_LOGAPI(("\t{" ));
+
+        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));
+        PA_LOGAPI(("\t\tPaTime inputLatency: %f\n", result->inputLatency ));
+        PA_LOGAPI(("\t\tPaTime outputLatency: %f\n", result->outputLatency ));
+        PA_LOGAPI(("\t\tdouble sampleRate: %f\n", result->sampleRate ));
+        PA_LOGAPI(("\t}\n" ));
+
+    }
+
+    return result;
+}
+
+
+PaTime Pa_GetStreamTime( PaStream *stream )
+{
+    PaError error = PaUtil_ValidateStreamPointer( stream );
+    PaTime result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamTime" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( error != paNoError )
+    {
+        result = 0;
+
+        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));
+        PA_LOGAPI(("\tPaTime: 0 [PaError error:%d ( %s )]\n", result, error, Pa_GetErrorText( error ) ));
+
+    }
+    else
+    {
+        result = PA_STREAM_INTERFACE(stream)->GetTime( stream );
+
+        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));
+        PA_LOGAPI(("\tPaTime: %g\n", result ));
+
+    }
+
+    return result;
+}
+
+
+double Pa_GetStreamCpuLoad( PaStream* stream )
+{
+    PaError error = PaUtil_ValidateStreamPointer( stream );
+    double result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamCpuLoad" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( error != paNoError )
+    {
+
+        result = 0.0;
+
+        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));
+        PA_LOGAPI(("\tdouble: 0.0 [PaError error: %d ( %s )]\n", error, Pa_GetErrorText( error ) ));
+
+    }
+    else
+    {
+        result = PA_STREAM_INTERFACE(stream)->GetCpuLoad( stream );
+
+        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));
+        PA_LOGAPI(("\tdouble: %g\n", result ));
+
+    }
+
+    return result;
+}
+
+
+PaError Pa_ReadStream( PaStream* stream,
+                       void *buffer,
+                       unsigned long frames )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_ReadStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+    {
+        if( frames == 0 )
+        {
+            /* @todo Should we not allow the implementation to signal any overflow condition? see: http://www.portaudio.com/trac/ticket/116*/
+            result = paNoError;
+        }
+        else if( buffer == 0 )
+        {
+            result = paBadBufferPtr;
+        }
+        else
+        {
+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+            if( result == 0 )
+            {
+                result = PA_STREAM_INTERFACE(stream)->Read( stream, buffer, frames );
+            }
+            else if( result == 1 )
+            {
+                result = paStreamIsStopped;
+            }
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_ReadStream", result );
+
+    return result;
+}
+
+
+PaError Pa_WriteStream( PaStream* stream,
+                        const void *buffer,
+                        unsigned long frames )
+{
+    PaError result = PaUtil_ValidateStreamPointer( stream );
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_WriteStream" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( result == paNoError )
+    {
+        if( frames == 0 )
+        {
+            /* @todo Should we not allow the implementation to signal any underflow condition? see: http://www.portaudio.com/trac/ticket/116*/
+            result = paNoError;
+        }
+        else if( buffer == 0 )
+        {
+            result = paBadBufferPtr;
+        }
+        else
+        {
+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );
+            if( result == 0 )
+            {
+                result = PA_STREAM_INTERFACE(stream)->Write( stream, buffer, frames );
+            }
+            else if( result == 1 )
+            {
+                result = paStreamIsStopped;
+            }
+        }
+    }
+
+    PA_LOGAPI_EXIT_PAERROR( "Pa_WriteStream", result );
+
+    return result;
+}
+
+signed long Pa_GetStreamReadAvailable( PaStream* stream )
+{
+    PaError error = PaUtil_ValidateStreamPointer( stream );
+    signed long result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamReadAvailable" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( error != paNoError )
+    {
+        result = 0;
+
+        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));
+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));
+
+    }
+    else
+    {
+        result = PA_STREAM_INTERFACE(stream)->GetReadAvailable( stream );
+
+        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+
+    }
+
+    return result;
+}
+
+
+signed long Pa_GetStreamWriteAvailable( PaStream* stream )
+{
+    PaError error = PaUtil_ValidateStreamPointer( stream );
+    signed long result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamWriteAvailable" );
+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));
+
+    if( error != paNoError )
+    {
+        result = 0;
+
+        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));
+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));
+
+    }
+    else
+    {
+        result = PA_STREAM_INTERFACE(stream)->GetWriteAvailable( stream );
+
+        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));
+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));
+
+    }
+
+    return result;
+}
+
+
+PaError Pa_GetSampleSize( PaSampleFormat format )
+{
+    int result;
+
+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetSampleSize" );
+    PA_LOGAPI(("\tPaSampleFormat format: %d\n", format ));
+
+    switch( format & ~paNonInterleaved )
+    {
+
+    case paUInt8:
+    case paInt8:
+        result = 1;
+        break;
+
+    case paInt16:
+        result = 2;
+        break;
+
+    case paInt24:
+        result = 3;
+        break;
+
+    case paFloat32:
+    case paInt32:
+        result = 4;
+        break;
+
+    default:
+        result = paSampleFormatNotSupported;
+        break;
+    }
+
+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetSampleSize", "int: %d", result );
+
+    return (PaError) result;
+}
+
diff --git a/portaudio/src/common/pa_gitrevision.h b/portaudio/src/common/pa_gitrevision.h
new file mode 100644 (file)
index 0000000..2a6cfca
--- /dev/null
@@ -0,0 +1 @@
+#define PA_GIT_REVISION 396fe4b6699ae929d3a685b3ef8a7e97396139a4
diff --git a/portaudio/src/common/pa_hostapi.h b/portaudio/src/common/pa_hostapi.h
new file mode 100644 (file)
index 0000000..54b527e
--- /dev/null
@@ -0,0 +1,362 @@
+#ifndef PA_HOSTAPI_H
+#define PA_HOSTAPI_H
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * host api representation
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Interfaces and representation structures used by pa_front.c 
+ to manage and communicate with host API implementations.
+*/
+
+#include "portaudio.h"
+
+/**
+The PA_NO_* host API macros are now deprecated in favor of PA_USE_* macros.
+PA_USE_* indicates whether a particular host API will be initialized by PortAudio.
+An undefined or 0 value indicates that the host API will not be used. A value of 1 
+indicates that the host API will be used. PA_USE_* macros should be left undefined 
+or defined to either 0 or 1.
+
+The code below ensures that PA_USE_* macros are always defined and have value
+0 or 1. Undefined symbols are defaulted to 0. Symbols that are neither 0 nor 1 
+are defaulted to 1.
+*/
+
+#ifndef PA_USE_SKELETON
+#define PA_USE_SKELETON 0
+#elif (PA_USE_SKELETON != 0) && (PA_USE_SKELETON != 1)
+#undef PA_USE_SKELETON
+#define PA_USE_SKELETON 1
+#endif 
+
+#if defined(PA_NO_ASIO) || defined(PA_NO_DS) || defined(PA_NO_WMME) || defined(PA_NO_WASAPI) || defined(PA_NO_WDMKS)
+#error "Portaudio: PA_NO_<APINAME> is no longer supported, please remove definition and use PA_USE_<APINAME> instead"
+#endif
+
+#ifndef PA_USE_ASIO
+#define PA_USE_ASIO 0
+#elif (PA_USE_ASIO != 0) && (PA_USE_ASIO != 1)
+#undef PA_USE_ASIO
+#define PA_USE_ASIO 1
+#endif 
+
+#ifndef PA_USE_DS
+#define PA_USE_DS 0
+#elif (PA_USE_DS != 0) && (PA_USE_DS != 1)
+#undef PA_USE_DS
+#define PA_USE_DS 1
+#endif 
+
+#ifndef PA_USE_WMME
+#define PA_USE_WMME 0
+#elif (PA_USE_WMME != 0) && (PA_USE_WMME != 1)
+#undef PA_USE_WMME
+#define PA_USE_WMME 1
+#endif 
+
+#ifndef PA_USE_WASAPI
+#define PA_USE_WASAPI 0
+#elif (PA_USE_WASAPI != 0) && (PA_USE_WASAPI != 1)
+#undef PA_USE_WASAPI
+#define PA_USE_WASAPI 1
+#endif 
+
+#ifndef PA_USE_WDMKS
+#define PA_USE_WDMKS 0
+#elif (PA_USE_WDMKS != 0) && (PA_USE_WDMKS != 1)
+#undef PA_USE_WDMKS
+#define PA_USE_WDMKS 1
+#endif 
+
+/* Set default values for Unix based APIs. */
+#if defined(PA_NO_OSS) || defined(PA_NO_ALSA) || defined(PA_NO_JACK) || defined(PA_NO_COREAUDIO) || defined(PA_NO_SGI) || defined(PA_NO_ASIHPI)
+#error "Portaudio: PA_NO_<APINAME> is no longer supported, please remove definition and use PA_USE_<APINAME> instead"
+#endif
+
+#ifndef PA_USE_OSS
+#define PA_USE_OSS 0
+#elif (PA_USE_OSS != 0) && (PA_USE_OSS != 1)
+#undef PA_USE_OSS
+#define PA_USE_OSS 1
+#endif 
+
+#ifndef PA_USE_ALSA
+#define PA_USE_ALSA 0
+#elif (PA_USE_ALSA != 0) && (PA_USE_ALSA != 1)
+#undef PA_USE_ALSA
+#define PA_USE_ALSA 1
+#endif 
+
+#ifndef PA_USE_JACK
+#define PA_USE_JACK 0
+#elif (PA_USE_JACK != 0) && (PA_USE_JACK != 1)
+#undef PA_USE_JACK
+#define PA_USE_JACK 1
+#endif 
+
+#ifndef PA_USE_SGI
+#define PA_USE_SGI 0
+#elif (PA_USE_SGI != 0) && (PA_USE_SGI != 1)
+#undef PA_USE_SGI
+#define PA_USE_SGI 1
+#endif 
+
+#ifndef PA_USE_COREAUDIO
+#define PA_USE_COREAUDIO 0
+#elif (PA_USE_COREAUDIO != 0) && (PA_USE_COREAUDIO != 1)
+#undef PA_USE_COREAUDIO
+#define PA_USE_COREAUDIO 1
+#endif 
+
+#ifndef PA_USE_ASIHPI
+#define PA_USE_ASIHPI 0
+#elif (PA_USE_ASIHPI != 0) && (PA_USE_ASIHPI != 1)
+#undef PA_USE_ASIHPI
+#define PA_USE_ASIHPI 1
+#endif 
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/** **FOR THE USE OF pa_front.c ONLY**
+    Do NOT use fields in this structure, they my change at any time.
+    Use functions defined in pa_util.h if you think you need functionality
+    which can be derived from here.
+*/
+typedef struct PaUtilPrivatePaFrontHostApiInfo {
+
+
+    unsigned long baseDeviceIndex;
+}PaUtilPrivatePaFrontHostApiInfo;
+
+
+/** The common header for all data structures whose pointers are passed through
+ the hostApiSpecificStreamInfo field of the PaStreamParameters structure.
+ Note that in order to keep the public PortAudio interface clean, this structure
+ is not used explicitly when declaring hostApiSpecificStreamInfo data structures.
+ However, some code in pa_front depends on the first 3 members being equivalent
+ with this structure.
+ @see PaStreamParameters
+*/
+typedef struct PaUtilHostApiSpecificStreamInfoHeader
+{
+    unsigned long size;             /**< size of whole structure including this header */
+    PaHostApiTypeId hostApiType;    /**< host API for which this data is intended */
+    unsigned long version;          /**< structure version */
+} PaUtilHostApiSpecificStreamInfoHeader;
+
+
+
+/** A structure representing the interface to a host API. Contains both
+ concrete data and pointers to functions which implement the interface.
+*/
+typedef struct PaUtilHostApiRepresentation {
+    PaUtilPrivatePaFrontHostApiInfo privatePaFrontInfo;
+
+    /** The host api implementation should populate the info field. In the
+        case of info.defaultInputDevice and info.defaultOutputDevice the
+        values stored should be 0 based indices within the host api's own
+        device index range (0 to deviceCount). These values will be converted
+        to global device indices by pa_front after PaUtilHostApiInitializer()
+        returns.
+    */
+    PaHostApiInfo info;
+
+    PaDeviceInfo** deviceInfos;
+
+    /**
+        (*Terminate)() is guaranteed to be called with a valid <hostApi>
+        parameter, which was previously returned from the same implementation's
+        initializer.
+    */
+    void (*Terminate)( struct PaUtilHostApiRepresentation *hostApi );
+
+    /**
+        The inputParameters and outputParameters pointers should not be saved
+        as they will not remain valid after OpenStream is called.
+
+        
+        The following guarantees are made about parameters to (*OpenStream)():
+
+            [NOTE: the following list up to *END PA FRONT VALIDATIONS* should be
+                kept in sync with the one for ValidateOpenStreamParameters and
+                Pa_OpenStream in pa_front.c]
+                
+            PaHostApiRepresentation *hostApi
+                - is valid for this implementation
+
+            PaStream** stream
+                - is non-null
+
+            - at least one of inputParameters & outputParmeters is valid (not NULL)
+
+            - if inputParameters & outputParmeters are both valid, that
+                inputParameters->device & outputParmeters->device  both use the same host api
+            PaDeviceIndex inputParameters->device
+                - is within range (0 to Pa_CountDevices-1) Or:
+                - is paUseHostApiSpecificDeviceSpecification and
+                    inputParameters->hostApiSpecificStreamInfo is non-NULL and refers
+                    to a valid host api
+
+            int inputParameters->numChannels
+                - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, numInputChannels is > 0
+                - upper bound is NOT validated against device capabilities
+            PaSampleFormat inputParameters->sampleFormat
+                - is one of the sample formats defined in portaudio.h
+
+            void *inputParameters->hostApiSpecificStreamInfo
+                - if supplied its hostApi field matches the input device's host Api
+            PaDeviceIndex outputParmeters->device
+                - is within range (0 to Pa_CountDevices-1)
+            int outputParmeters->numChannels
+                - if inputDevice is valid, numInputChannels is > 0
+                - upper bound is NOT validated against device capabilities
+            PaSampleFormat outputParmeters->sampleFormat
+                - is one of the sample formats defined in portaudio.h
+        
+            void *outputParmeters->hostApiSpecificStreamInfo
+                - if supplied its hostApi field matches the output device's host Api
+            double sampleRate
+                - is not an 'absurd' rate (less than 1000. or greater than 384000.)
+                - sampleRate is NOT validated against device capabilities
+            PaStreamFlags streamFlags
+                - unused platform neutral flags are zero
+                - paNeverDropInput is only used for full-duplex callback streams
+                    with variable buffer size (paFramesPerBufferUnspecified)
+
+            [*END PA FRONT VALIDATIONS*]
+
+
+        The following validations MUST be performed by (*OpenStream)():
+
+            - check that input device can support numInputChannels
+            
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - if inputStreamInfo is supplied, validate its contents,
+                or return an error if no inputStreamInfo is expected
+
+            - check that output device can support numOutputChannels
+            
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - if outputStreamInfo is supplied, validate its contents,
+                or return an error if no outputStreamInfo is expected
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+
+            - check that the device supports sampleRate
+
+            - alter sampleRate to a close allowable rate if necessary
+
+            - validate inputLatency and outputLatency
+
+            - validate any platform specific flags, if flags are supplied they
+                must be valid.
+    */
+    PaError (*OpenStream)( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** stream,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerCallback,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+
+
+    PaError (*IsFormatSupported)( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+} PaUtilHostApiRepresentation;
+
+
+/** Prototype for the initialization function which must be implemented by every
+ host API.
+ This function should only return an error other than paNoError if it encounters 
+ an unexpected and fatal error (memory allocation error for example). In general, 
+ there may be conditions under which it returns a NULL interface pointer and also 
+ returns paNoError. For example, if the ASIO implementation detects that ASIO is 
+ not installed, it should return a NULL interface, and paNoError.
+
+ @see paHostApiInitializers
+*/
+typedef PaError PaUtilHostApiInitializer( PaUtilHostApiRepresentation**, PaHostApiIndex );
+
+
+/** paHostApiInitializers is a NULL-terminated array of host API initialization
+ functions. These functions are called by pa_front.c to initialize the host APIs
+ when the client calls Pa_Initialize(). 
+ The initialization functions are invoked in order.
+
+ The first successfully initialized host API that has a default input *or* output 
+ device is used as the default PortAudio host API. This is based on the logic that
+ there is only one default host API, and it must contain the default input and output
+ devices (if defined).
+
+ There is a platform specific file that defines paHostApiInitializers for that
+ platform, pa_win/pa_win_hostapis.c contains the Win32 definitions for example.
+*/
+extern PaUtilHostApiInitializer *paHostApiInitializers[];
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_HOSTAPI_H */
diff --git a/portaudio/src/common/pa_memorybarrier.h b/portaudio/src/common/pa_memorybarrier.h
new file mode 100644 (file)
index 0000000..2879ce3
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * $Id: pa_memorybarrier.h 1240 2007-07-17 13:05:07Z bjornroche $
+ * Portable Audio I/O Library
+ * Memory barrier utilities
+ *
+ * Author: Bjorn Roche, XO Audio, LLC
+ *
+ * This program uses the PortAudio Portable Audio Library.
+ * For more information see: http://www.portaudio.com
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file pa_memorybarrier.h
+ @ingroup common_src
+*/
+
+/****************
+ * Some memory barrier primitives based on the system.
+ * right now only OS X, FreeBSD, and Linux are supported. In addition to providing
+ * memory barriers, these functions should ensure that data cached in registers
+ * is written out to cache where it can be snooped by other CPUs. (ie, the volatile
+ * keyword should not be required)
+ *
+ * the primitives that must be defined are:
+ *
+ * PaUtil_FullMemoryBarrier()
+ * PaUtil_ReadMemoryBarrier()
+ * PaUtil_WriteMemoryBarrier()
+ *
+ ****************/
+
+#if defined(__APPLE__)
+#   include <libkern/OSAtomic.h>
+    /* Here are the memory barrier functions. Mac OS X only provides
+       full memory barriers, so the three types of barriers are the same,
+       however, these barriers are superior to compiler-based ones. */
+#   define PaUtil_FullMemoryBarrier()  OSMemoryBarrier()
+#   define PaUtil_ReadMemoryBarrier()  OSMemoryBarrier()
+#   define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()
+#elif defined(__GNUC__)
+    /* GCC >= 4.1 has built-in intrinsics. We'll use those */
+#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
+#      define PaUtil_FullMemoryBarrier()  __sync_synchronize()
+#      define PaUtil_ReadMemoryBarrier()  __sync_synchronize()
+#      define PaUtil_WriteMemoryBarrier() __sync_synchronize()
+    /* as a fallback, GCC understands volatile asm and "memory" to mean it
+     * should not reorder memory read/writes */
+    /* Note that it is not clear that any compiler actually defines __PPC__,
+     * it can probably removed safely. */
+#   elif defined( __ppc__ ) || defined( __powerpc__) || defined( __PPC__ )
+#      define PaUtil_FullMemoryBarrier()  asm volatile("sync":::"memory")
+#      define PaUtil_ReadMemoryBarrier()  asm volatile("sync":::"memory")
+#      define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")
+#   elif defined( __i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \
+         defined( __i686__ ) || defined( __x86_64__ )
+#      define PaUtil_FullMemoryBarrier()  asm volatile("mfence":::"memory")
+#      define PaUtil_ReadMemoryBarrier()  asm volatile("lfence":::"memory")
+#      define PaUtil_WriteMemoryBarrier() asm volatile("sfence":::"memory")
+#   else
+#      ifdef ALLOW_SMP_DANGERS
+#         warning Memory barriers not defined on this system or system unknown
+#         warning For SMP safety, you should fix this.
+#         define PaUtil_FullMemoryBarrier()
+#         define PaUtil_ReadMemoryBarrier()
+#         define PaUtil_WriteMemoryBarrier()
+#      else
+#         error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
+#      endif
+#   endif
+#elif (_MSC_VER >= 1400) && !defined(_WIN32_WCE)
+#   include <intrin.h>
+#   pragma intrinsic(_ReadWriteBarrier)
+#   pragma intrinsic(_ReadBarrier)
+#   pragma intrinsic(_WriteBarrier)
+/* note that MSVC intrinsics _ReadWriteBarrier(), _ReadBarrier(), _WriteBarrier() are just compiler barriers *not* memory barriers */
+#   define PaUtil_FullMemoryBarrier()  _ReadWriteBarrier()
+#   define PaUtil_ReadMemoryBarrier()  _ReadBarrier()
+#   define PaUtil_WriteMemoryBarrier() _WriteBarrier()
+#elif defined(_WIN32_WCE)
+#   define PaUtil_FullMemoryBarrier()
+#   define PaUtil_ReadMemoryBarrier()
+#   define PaUtil_WriteMemoryBarrier()
+#elif defined(_MSC_VER) || defined(__BORLANDC__)
+#   define PaUtil_FullMemoryBarrier()  _asm { lock add    [esp], 0 }
+#   define PaUtil_ReadMemoryBarrier()  _asm { lock add    [esp], 0 }
+#   define PaUtil_WriteMemoryBarrier() _asm { lock add    [esp], 0 }
+#else
+#   ifdef ALLOW_SMP_DANGERS
+#      warning Memory barriers not defined on this system or system unknown
+#      warning For SMP safety, you should fix this.
+#      define PaUtil_FullMemoryBarrier()
+#      define PaUtil_ReadMemoryBarrier()
+#      define PaUtil_WriteMemoryBarrier()
+#   else
+#      error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
+#   endif
+#endif
diff --git a/portaudio/src/common/pa_process.c b/portaudio/src/common/pa_process.c
new file mode 100644 (file)
index 0000000..0faf841
--- /dev/null
@@ -0,0 +1,1831 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * streamCallback <-> host buffer processing adapter
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Buffer Processor implementation.
+*/
+
+
+#include <assert.h>
+#include <string.h> /* memset() */
+
+#include "pa_process.h"
+#include "pa_util.h"
+
+
+#define PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_    1024
+
+#define PA_MIN_( a, b ) ( ((a)<(b)) ? (a) : (b) )
+
+
+/* greatest common divisor - PGCD in French */
+static unsigned long GCD( unsigned long a, unsigned long b )
+{
+    return (b==0) ? a : GCD( b, a%b);
+}
+
+/* least common multiple - PPCM in French */
+static unsigned long LCM( unsigned long a, unsigned long b )
+{
+    return (a*b) / GCD(a,b);
+}
+
+#define PA_MAX_( a, b ) (((a) > (b)) ? (a) : (b))
+
+static unsigned long CalculateFrameShift( unsigned long M, unsigned long N )
+{
+    unsigned long result = 0;
+    unsigned long i;
+    unsigned long lcm;
+
+    assert( M > 0 );
+    assert( N > 0 );
+
+    lcm = LCM( M, N );
+    for( i = M; i < lcm; i += M )
+        result = PA_MAX_( result, i % N );
+
+    return result;
+}
+
+
+PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp,
+        int inputChannelCount, PaSampleFormat userInputSampleFormat,
+        PaSampleFormat hostInputSampleFormat,
+        int outputChannelCount, PaSampleFormat userOutputSampleFormat,
+        PaSampleFormat hostOutputSampleFormat,
+        double sampleRate,
+        PaStreamFlags streamFlags,
+        unsigned long framesPerUserBuffer,
+        unsigned long framesPerHostBuffer,
+        PaUtilHostBufferSizeMode hostBufferSizeMode,
+        PaStreamCallback *streamCallback, void *userData )
+{
+    PaError result = paNoError;
+    PaError bytesPerSample;
+    unsigned long tempInputBufferSize, tempOutputBufferSize;
+    PaStreamFlags tempInputStreamFlags;
+
+    if( streamFlags & paNeverDropInput )
+    {
+        /* paNeverDropInput is only valid for full-duplex callback streams, with an unspecified number of frames per buffer. */
+        if( !streamCallback || !(inputChannelCount > 0 && outputChannelCount > 0) ||
+                framesPerUserBuffer != paFramesPerBufferUnspecified )
+            return paInvalidFlag;
+    }
+
+    /* initialize buffer ptrs to zero so they can be freed if necessary in error */
+    bp->tempInputBuffer = 0;
+    bp->tempInputBufferPtrs = 0;
+    bp->tempOutputBuffer = 0;
+    bp->tempOutputBufferPtrs = 0;
+
+    bp->framesPerUserBuffer = framesPerUserBuffer;
+    bp->framesPerHostBuffer = framesPerHostBuffer;
+
+    bp->inputChannelCount = inputChannelCount;
+    bp->outputChannelCount = outputChannelCount;
+
+    bp->hostBufferSizeMode = hostBufferSizeMode;
+
+    bp->hostInputChannels[0] = bp->hostInputChannels[1] = 0;
+    bp->hostOutputChannels[0] = bp->hostOutputChannels[1] = 0;
+
+    if( framesPerUserBuffer == 0 ) /* streamCallback will accept any buffer size */
+    {
+        bp->useNonAdaptingProcess = 1;
+        bp->initialFramesInTempInputBuffer = 0;
+        bp->initialFramesInTempOutputBuffer = 0;
+
+        if( hostBufferSizeMode == paUtilFixedHostBufferSize
+                || hostBufferSizeMode == paUtilBoundedHostBufferSize )
+        {
+            bp->framesPerTempBuffer = framesPerHostBuffer;
+        }
+        else /* unknown host buffer size */
+        {
+             bp->framesPerTempBuffer = PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_;
+        }
+    }
+    else
+    {
+        bp->framesPerTempBuffer = framesPerUserBuffer;
+
+        if( hostBufferSizeMode == paUtilFixedHostBufferSize
+                && framesPerHostBuffer % framesPerUserBuffer == 0 )
+        {
+            bp->useNonAdaptingProcess = 1;
+            bp->initialFramesInTempInputBuffer = 0;
+            bp->initialFramesInTempOutputBuffer = 0;
+        }
+        else
+        {
+            bp->useNonAdaptingProcess = 0;
+
+            if( inputChannelCount > 0 && outputChannelCount > 0 )
+            {
+                /* full duplex */
+                if( hostBufferSizeMode == paUtilFixedHostBufferSize )
+                {
+                    unsigned long frameShift =
+                        CalculateFrameShift( framesPerHostBuffer, framesPerUserBuffer );
+
+                    if( framesPerUserBuffer > framesPerHostBuffer )
+                    {
+                        bp->initialFramesInTempInputBuffer = frameShift;
+                        bp->initialFramesInTempOutputBuffer = 0;
+                    }
+                    else
+                    {
+                        bp->initialFramesInTempInputBuffer = 0;
+                        bp->initialFramesInTempOutputBuffer = frameShift;
+                    }
+                }
+                else /* variable host buffer size, add framesPerUserBuffer latency */
+                {
+                    bp->initialFramesInTempInputBuffer = 0;
+                    bp->initialFramesInTempOutputBuffer = framesPerUserBuffer;
+                }
+            }
+            else
+            {
+                /* half duplex */
+                bp->initialFramesInTempInputBuffer = 0;
+                bp->initialFramesInTempOutputBuffer = 0;
+            }
+        }
+    }
+
+
+    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;
+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;
+
+    
+    if( inputChannelCount > 0 )
+    {
+        bytesPerSample = Pa_GetSampleSize( hostInputSampleFormat );
+        if( bytesPerSample > 0 )
+        {
+            bp->bytesPerHostInputSample = bytesPerSample;
+        }
+        else
+        {
+            result = bytesPerSample;
+            goto error;
+        }
+
+        bytesPerSample = Pa_GetSampleSize( userInputSampleFormat );
+        if( bytesPerSample > 0 )
+        {
+            bp->bytesPerUserInputSample = bytesPerSample;
+        }
+        else
+        {
+            result = bytesPerSample;
+            goto error;
+        }
+
+        /* Under the assumption that no ADC in existence delivers better than 24bits resolution,
+            we disable dithering when host input format is paInt32 and user format is paInt24, 
+            since the host samples will just be padded with zeros anyway. */
+
+        tempInputStreamFlags = streamFlags;
+        if( !(tempInputStreamFlags & paDitherOff) /* dither is on */
+                && (hostInputSampleFormat & paInt32) /* host input format is int32 */
+                && (userInputSampleFormat & paInt24) /* user requested format is int24 */ ){
+
+            tempInputStreamFlags = tempInputStreamFlags | paDitherOff;
+        }
+
+        bp->inputConverter =
+            PaUtil_SelectConverter( hostInputSampleFormat, userInputSampleFormat, tempInputStreamFlags );
+
+        bp->inputZeroer = PaUtil_SelectZeroer( userInputSampleFormat );
+            
+        bp->userInputIsInterleaved = (userInputSampleFormat & paNonInterleaved)?0:1;
+               
+        bp->hostInputIsInterleaved = (hostInputSampleFormat & paNonInterleaved)?0:1;
+
+        bp->userInputSampleFormatIsEqualToHost = ((userInputSampleFormat & ~paNonInterleaved) == (hostInputSampleFormat & ~paNonInterleaved));
+
+        tempInputBufferSize =
+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * inputChannelCount;
+         
+        bp->tempInputBuffer = PaUtil_AllocateMemory( tempInputBufferSize );
+        if( bp->tempInputBuffer == 0 )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        
+        if( bp->framesInTempInputBuffer > 0 )
+            memset( bp->tempInputBuffer, 0, tempInputBufferSize );
+
+        if( userInputSampleFormat & paNonInterleaved )
+        {
+            bp->tempInputBufferPtrs =
+                (void **)PaUtil_AllocateMemory( sizeof(void*)*inputChannelCount );
+            if( bp->tempInputBufferPtrs == 0 )
+            {
+                result = paInsufficientMemory;
+                goto error;
+            }
+        }
+
+        bp->hostInputChannels[0] = (PaUtilChannelDescriptor*)
+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor) * inputChannelCount * 2);
+        if( bp->hostInputChannels[0] == 0 )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        bp->hostInputChannels[1] = &bp->hostInputChannels[0][inputChannelCount];
+    }
+
+    if( outputChannelCount > 0 )
+    {
+        bytesPerSample = Pa_GetSampleSize( hostOutputSampleFormat );
+        if( bytesPerSample > 0 )
+        {
+            bp->bytesPerHostOutputSample = bytesPerSample;
+        }
+        else
+        {
+            result = bytesPerSample;
+            goto error;
+        }
+
+        bytesPerSample = Pa_GetSampleSize( userOutputSampleFormat );
+        if( bytesPerSample > 0 )
+        {
+            bp->bytesPerUserOutputSample = bytesPerSample;
+        }
+        else
+        {
+            result = bytesPerSample;
+            goto error;
+        }
+
+        bp->outputConverter =
+            PaUtil_SelectConverter( userOutputSampleFormat, hostOutputSampleFormat, streamFlags );
+
+        bp->outputZeroer = PaUtil_SelectZeroer( hostOutputSampleFormat );
+
+        bp->userOutputIsInterleaved = (userOutputSampleFormat & paNonInterleaved)?0:1;
+
+        bp->hostOutputIsInterleaved = (hostOutputSampleFormat & paNonInterleaved)?0:1;
+
+        bp->userOutputSampleFormatIsEqualToHost = ((userOutputSampleFormat & ~paNonInterleaved) == (hostOutputSampleFormat & ~paNonInterleaved));
+
+        tempOutputBufferSize =
+                bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * outputChannelCount;
+
+        bp->tempOutputBuffer = PaUtil_AllocateMemory( tempOutputBufferSize );
+        if( bp->tempOutputBuffer == 0 )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        if( bp->framesInTempOutputBuffer > 0 )
+            memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );
+        
+        if( userOutputSampleFormat & paNonInterleaved )
+        {
+            bp->tempOutputBufferPtrs =
+                (void **)PaUtil_AllocateMemory( sizeof(void*)*outputChannelCount );
+            if( bp->tempOutputBufferPtrs == 0 )
+            {
+                result = paInsufficientMemory;
+                goto error;
+            }
+        }
+
+        bp->hostOutputChannels[0] = (PaUtilChannelDescriptor*)
+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor)*outputChannelCount * 2 );
+        if( bp->hostOutputChannels[0] == 0 )
+        {                                                                     
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        bp->hostOutputChannels[1] = &bp->hostOutputChannels[0][outputChannelCount];
+    }
+
+    PaUtil_InitializeTriangularDitherState( &bp->ditherGenerator );
+
+    bp->samplePeriod = 1. / sampleRate;
+
+    bp->streamCallback = streamCallback;
+    bp->userData = userData;
+
+    return result;
+
+error:
+    if( bp->tempInputBuffer )
+        PaUtil_FreeMemory( bp->tempInputBuffer );
+
+    if( bp->tempInputBufferPtrs )
+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );
+
+    if( bp->hostInputChannels[0] )
+        PaUtil_FreeMemory( bp->hostInputChannels[0] );
+
+    if( bp->tempOutputBuffer )
+        PaUtil_FreeMemory( bp->tempOutputBuffer );
+
+    if( bp->tempOutputBufferPtrs )
+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );
+
+    if( bp->hostOutputChannels[0] )
+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );
+
+    return result;
+}
+
+
+void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bp )
+{
+    if( bp->tempInputBuffer )
+        PaUtil_FreeMemory( bp->tempInputBuffer );
+
+    if( bp->tempInputBufferPtrs )
+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );
+
+    if( bp->hostInputChannels[0] )
+        PaUtil_FreeMemory( bp->hostInputChannels[0] );
+        
+    if( bp->tempOutputBuffer )
+        PaUtil_FreeMemory( bp->tempOutputBuffer );
+
+    if( bp->tempOutputBufferPtrs )
+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );
+
+    if( bp->hostOutputChannels[0] )
+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );
+}
+
+
+void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bp )
+{
+    unsigned long tempInputBufferSize, tempOutputBufferSize;
+
+    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;
+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;
+
+    if( bp->framesInTempInputBuffer > 0 )
+    {
+        tempInputBufferSize =
+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * bp->inputChannelCount;
+        memset( bp->tempInputBuffer, 0, tempInputBufferSize );
+    }
+
+    if( bp->framesInTempOutputBuffer > 0 )
+    {      
+        tempOutputBufferSize =
+            bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * bp->outputChannelCount;
+        memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );
+    }
+}
+
+
+unsigned long PaUtil_GetBufferProcessorInputLatencyFrames( PaUtilBufferProcessor* bp )
+{
+    return bp->initialFramesInTempInputBuffer;
+}
+
+
+unsigned long PaUtil_GetBufferProcessorOutputLatencyFrames( PaUtilBufferProcessor* bp )
+{
+    return bp->initialFramesInTempOutputBuffer;
+}
+
+
+void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bp,
+        unsigned long frameCount )
+{
+    if( frameCount == 0 )
+        bp->hostInputFrameCount[0] = bp->framesPerHostBuffer;
+    else
+        bp->hostInputFrameCount[0] = frameCount;
+}
+        
+
+void PaUtil_SetNoInput( PaUtilBufferProcessor* bp )
+{
+    assert( bp->inputChannelCount > 0 );
+
+    bp->hostInputChannels[0][0].data = 0;
+}
+
+
+void PaUtil_SetInputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data, unsigned int stride )
+{
+    assert( channel < bp->inputChannelCount );
+    
+    bp->hostInputChannels[0][channel].data = data;
+    bp->hostInputChannels[0][channel].stride = stride;
+}
+
+
+void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bp,
+        unsigned int firstChannel, void *data, unsigned int channelCount )
+{
+    unsigned int i;
+    unsigned int channel = firstChannel;
+    unsigned char *p = (unsigned char*)data;
+
+    if( channelCount == 0 )
+        channelCount = bp->inputChannelCount;
+
+    assert( firstChannel < bp->inputChannelCount );
+    assert( firstChannel + channelCount <= bp->inputChannelCount );
+    assert( bp->hostInputIsInterleaved );
+
+    for( i=0; i< channelCount; ++i )
+    {
+        bp->hostInputChannels[0][channel+i].data = p;
+        p += bp->bytesPerHostInputSample;
+        bp->hostInputChannels[0][channel+i].stride = channelCount;
+    }
+}
+
+
+void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data )
+{
+    assert( channel < bp->inputChannelCount );
+    assert( !bp->hostInputIsInterleaved );
+    
+    bp->hostInputChannels[0][channel].data = data;
+    bp->hostInputChannels[0][channel].stride = 1;
+}
+
+
+void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bp,
+        unsigned long frameCount )
+{
+    bp->hostInputFrameCount[1] = frameCount;
+}
+
+
+void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data, unsigned int stride )
+{
+    assert( channel < bp->inputChannelCount );
+
+    bp->hostInputChannels[1][channel].data = data;
+    bp->hostInputChannels[1][channel].stride = stride;
+}
+
+
+void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bp,
+        unsigned int firstChannel, void *data, unsigned int channelCount )
+{
+    unsigned int i;
+    unsigned int channel = firstChannel;
+    unsigned char *p = (unsigned char*)data;
+
+    if( channelCount == 0 )
+        channelCount = bp->inputChannelCount;
+
+    assert( firstChannel < bp->inputChannelCount );
+    assert( firstChannel + channelCount <= bp->inputChannelCount );
+    assert( bp->hostInputIsInterleaved );
+    
+    for( i=0; i< channelCount; ++i )
+    {
+        bp->hostInputChannels[1][channel+i].data = p;
+        p += bp->bytesPerHostInputSample;
+        bp->hostInputChannels[1][channel+i].stride = channelCount;
+    }
+}
+
+        
+void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data )
+{
+    assert( channel < bp->inputChannelCount );
+    assert( !bp->hostInputIsInterleaved );
+    
+    bp->hostInputChannels[1][channel].data = data;
+    bp->hostInputChannels[1][channel].stride = 1;
+}
+
+
+void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bp,
+        unsigned long frameCount )
+{
+    if( frameCount == 0 )
+        bp->hostOutputFrameCount[0] = bp->framesPerHostBuffer;
+    else
+        bp->hostOutputFrameCount[0] = frameCount;
+}
+
+
+void PaUtil_SetNoOutput( PaUtilBufferProcessor* bp )
+{
+    assert( bp->outputChannelCount > 0 );
+
+    bp->hostOutputChannels[0][0].data = 0;
+
+    /* note that only NonAdaptingProcess is able to deal with no output at this stage. not implemented for AdaptingProcess */
+}
+
+
+void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data, unsigned int stride )
+{
+    assert( channel < bp->outputChannelCount );
+    assert( data != NULL );
+
+    bp->hostOutputChannels[0][channel].data = data;
+    bp->hostOutputChannels[0][channel].stride = stride;
+}
+
+
+void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bp,
+        unsigned int firstChannel, void *data, unsigned int channelCount )
+{
+    unsigned int i;
+    unsigned int channel = firstChannel;
+    unsigned char *p = (unsigned char*)data;
+
+    if( channelCount == 0 )
+        channelCount = bp->outputChannelCount;
+
+    assert( firstChannel < bp->outputChannelCount );
+    assert( firstChannel + channelCount <= bp->outputChannelCount );
+    assert( bp->hostOutputIsInterleaved );
+    
+    for( i=0; i< channelCount; ++i )
+    {
+        PaUtil_SetOutputChannel( bp, channel + i, p, channelCount );
+        p += bp->bytesPerHostOutputSample;
+    }
+}
+
+
+void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data )
+{
+    assert( channel < bp->outputChannelCount );
+    assert( !bp->hostOutputIsInterleaved );
+
+    PaUtil_SetOutputChannel( bp, channel, data, 1 );
+}
+
+
+void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bp,
+        unsigned long frameCount )
+{
+    bp->hostOutputFrameCount[1] = frameCount;
+}
+
+
+void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data, unsigned int stride )
+{
+    assert( channel < bp->outputChannelCount );
+    assert( data != NULL );
+
+    bp->hostOutputChannels[1][channel].data = data;
+    bp->hostOutputChannels[1][channel].stride = stride;
+}
+
+
+void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bp,
+        unsigned int firstChannel, void *data, unsigned int channelCount )
+{
+    unsigned int i;
+    unsigned int channel = firstChannel;
+    unsigned char *p = (unsigned char*)data;
+
+    if( channelCount == 0 )
+        channelCount = bp->outputChannelCount;
+
+    assert( firstChannel < bp->outputChannelCount );
+    assert( firstChannel + channelCount <= bp->outputChannelCount );
+    assert( bp->hostOutputIsInterleaved );
+    
+    for( i=0; i< channelCount; ++i )
+    {
+        PaUtil_Set2ndOutputChannel( bp, channel + i, p, channelCount );
+        p += bp->bytesPerHostOutputSample;
+    }
+}
+
+        
+void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,
+        unsigned int channel, void *data )
+{
+    assert( channel < bp->outputChannelCount );
+    assert( !bp->hostOutputIsInterleaved );
+    
+    PaUtil_Set2ndOutputChannel( bp, channel, data, 1 );
+}
+
+
+void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bp,
+        PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags )
+{
+    bp->timeInfo = timeInfo;
+
+    /* the first streamCallback will be called to process samples which are
+        currently in the input buffer before the ones starting at the timeInfo time */
+        
+    bp->timeInfo->inputBufferAdcTime -= bp->framesInTempInputBuffer * bp->samplePeriod;
+    
+    /* We just pass through timeInfo->currentTime provided by the caller. This is
+        not strictly conformant to the word of the spec, since the buffer processor 
+        might call the callback multiple times, and we never refresh currentTime. */
+
+    /* the first streamCallback will be called to generate samples which will be
+        outputted after the frames currently in the output buffer have been
+        outputted. */
+    bp->timeInfo->outputBufferDacTime += bp->framesInTempOutputBuffer * bp->samplePeriod;
+
+    bp->callbackStatusFlags = callbackStatusFlags;
+
+    bp->hostInputFrameCount[1] = 0;
+    bp->hostOutputFrameCount[1] = 0;
+}
+
+
+/*
+    NonAdaptingProcess() is a simple buffer copying adaptor that can handle
+    both full and half duplex copies. It processes framesToProcess frames,
+    broken into blocks bp->framesPerTempBuffer long.
+    This routine can be used when the streamCallback doesn't care what length
+    the buffers are, or when framesToProcess is an integer multiple of
+    bp->framesPerTempBuffer, in which case streamCallback will always be called
+    with bp->framesPerTempBuffer samples.
+*/
+static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
+        int *streamCallbackResult,
+        PaUtilChannelDescriptor *hostInputChannels,
+        PaUtilChannelDescriptor *hostOutputChannels,
+        unsigned long framesToProcess )
+{
+    void *userInput, *userOutput;
+    unsigned char *srcBytePtr, *destBytePtr;
+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i;
+    unsigned long frameCount;
+    unsigned long framesToGo = framesToProcess;
+    unsigned long framesProcessed = 0;
+    int skipOutputConvert = 0;
+    int skipInputConvert = 0;
+
+
+    if( *streamCallbackResult == paContinue )
+    {
+        do
+        {
+            frameCount = PA_MIN_( bp->framesPerTempBuffer, framesToGo );
+
+            /* configure user input buffer and convert input data (host -> user) */
+            if( bp->inputChannelCount == 0 )
+            {
+                /* no input */
+                userInput = 0;
+            }
+            else /* there are input channels */
+            {
+                
+                destBytePtr = (unsigned char *)bp->tempInputBuffer;
+
+                if( bp->userInputIsInterleaved )
+                {
+                    destSampleStrideSamples = bp->inputChannelCount;
+                    destChannelStrideBytes = bp->bytesPerUserInputSample;
+
+                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved,
+                     * or if num channels differs between the host (set in stride) and the user (eg with some Alsa hw:) */
+                    if( bp->userInputSampleFormatIsEqualToHost && bp->hostInputIsInterleaved
+                        && bp->hostInputChannels[0][0].data && bp->inputChannelCount == hostInputChannels[0].stride )
+                    {
+                        userInput = hostInputChannels[0].data;
+                        destBytePtr = (unsigned char *)hostInputChannels[0].data;
+                        skipInputConvert = 1;
+                    }
+                    else
+                    {
+                        userInput = bp->tempInputBuffer;
+                    }
+                }
+                else /* user input is not interleaved */
+                {
+                    destSampleStrideSamples = 1;
+                    destChannelStrideBytes = frameCount * bp->bytesPerUserInputSample;
+
+                    /* setup non-interleaved ptrs */
+                    if( bp->userInputSampleFormatIsEqualToHost && !bp->hostInputIsInterleaved && bp->hostInputChannels[0][0].data )
+                    {
+                        for( i=0; i<bp->inputChannelCount; ++i )
+                        {
+                            bp->tempInputBufferPtrs[i] = hostInputChannels[i].data;
+                        }
+                        skipInputConvert = 1;
+                    }
+                    else
+                    {
+                        for( i=0; i<bp->inputChannelCount; ++i )
+                        {
+                            bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +
+                                i * bp->bytesPerUserInputSample * frameCount;
+                        }
+                    }
+                
+                    userInput = bp->tempInputBufferPtrs;
+                }
+
+                if( !bp->hostInputChannels[0][0].data )
+                {
+                    /* no input was supplied (see PaUtil_SetNoInput), so
+                        zero the input buffer */
+
+                    for( i=0; i<bp->inputChannelCount; ++i )
+                    {
+                        bp->inputZeroer( destBytePtr, destSampleStrideSamples, frameCount );
+                        destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
+                    }
+                }
+                else
+                   {
+                    if( skipInputConvert )
+                    {
+                        for( i=0; i<bp->inputChannelCount; ++i )
+                        {
+                            /* advance src ptr for next iteration */
+                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+                        }
+                    }
+                    else
+                    {
+                        for( i=0; i<bp->inputChannelCount; ++i )
+                        {
+                            bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                                    hostInputChannels[i].data,
+                                                    hostInputChannels[i].stride,
+                                                    frameCount, &bp->ditherGenerator );
+
+                            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
+
+                            /* advance src ptr for next iteration */
+                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+                        }
+                    }
+                }
+            }
+
+            /* configure user output buffer */
+            if( bp->outputChannelCount == 0 )
+            {
+                /* no output */
+                userOutput = 0;
+            }
+            else /* there are output channels */
+            {
+                if( bp->userOutputIsInterleaved )
+                {
+                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved,
+                     * or if num channels differs between the host (set in stride) and the user (eg with some Alsa hw:) */
+                    if( bp->userOutputSampleFormatIsEqualToHost && bp->hostOutputIsInterleaved
+                          && bp->outputChannelCount == hostOutputChannels[0].stride )
+                    {
+                        userOutput = hostOutputChannels[0].data;
+                        skipOutputConvert = 1;
+                    }
+                    else
+                    {
+                        userOutput = bp->tempOutputBuffer;
+                    }
+                }
+                else /* user output is not interleaved */
+                {
+                    if( bp->userOutputSampleFormatIsEqualToHost && !bp->hostOutputIsInterleaved )
+                    {
+                        for( i=0; i<bp->outputChannelCount; ++i )
+                        {
+                            bp->tempOutputBufferPtrs[i] = hostOutputChannels[i].data;
+                        }
+                        skipOutputConvert = 1;
+                    }
+                    else
+                    {
+                        for( i=0; i<bp->outputChannelCount; ++i )
+                        {
+                            bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +
+                                i * bp->bytesPerUserOutputSample * frameCount;
+                        }
+                    }
+
+                    userOutput = bp->tempOutputBufferPtrs;
+                }
+            }
+        
+            *streamCallbackResult = bp->streamCallback( userInput, userOutput,
+                    frameCount, bp->timeInfo, bp->callbackStatusFlags, bp->userData );
+
+            if( *streamCallbackResult == paAbort )
+            {
+                /* callback returned paAbort, don't advance framesProcessed
+                        and framesToGo, they will be handled below */
+            }
+            else
+            {
+                bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod;
+                bp->timeInfo->outputBufferDacTime += frameCount * bp->samplePeriod;
+
+                /* convert output data (user -> host) */
+                
+                if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )
+                {
+                    if( skipOutputConvert )
+                                       {
+                                               for( i=0; i<bp->outputChannelCount; ++i )
+                       {
+                               /* advance dest ptr for next iteration */
+                               hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                                   frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+                       }
+                                       }
+                                       else
+                                       {
+
+                       srcBytePtr = (unsigned char *)bp->tempOutputBuffer;
+
+                       if( bp->userOutputIsInterleaved )
+                       {
+                               srcSampleStrideSamples = bp->outputChannelCount;
+                               srcChannelStrideBytes = bp->bytesPerUserOutputSample;
+                       }
+                       else /* user output is not interleaved */
+                       {
+                               srcSampleStrideSamples = 1;
+                               srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample;
+                       }
+
+                       for( i=0; i<bp->outputChannelCount; ++i )
+                       {
+                               bp->outputConverter(    hostOutputChannels[i].data,
+                                                       hostOutputChannels[i].stride,
+                                                       srcBytePtr, srcSampleStrideSamples,
+                                                       frameCount, &bp->ditherGenerator );
+
+                               srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
+
+                               /* advance dest ptr for next iteration */
+                               hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                                               frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+                       }
+                                       }
+                }
+             
+                framesProcessed += frameCount;
+
+                framesToGo -= frameCount;
+            }
+        }
+        while( framesToGo > 0  && *streamCallbackResult == paContinue );
+    }
+
+    if( framesToGo > 0 )
+    {
+        /* zero any remaining frames output. There will only be remaining frames
+            if the callback has returned paComplete or paAbort */
+
+        frameCount = framesToGo;
+
+        if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )
+        {
+            for( i=0; i<bp->outputChannelCount; ++i )
+            {
+                bp->outputZeroer(   hostOutputChannels[i].data,
+                                    hostOutputChannels[i].stride,
+                                    frameCount );
+
+                /* advance dest ptr for next iteration */
+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+            }
+        }
+
+        framesProcessed += frameCount;
+    }
+
+    return framesProcessed;
+}
+
+
+/*
+    AdaptingInputOnlyProcess() is a half duplex input buffer processor. It
+    converts data from the input buffers into the temporary input buffer,
+    when the temporary input buffer is full, it calls the streamCallback.
+*/
+static unsigned long AdaptingInputOnlyProcess( PaUtilBufferProcessor *bp,
+        int *streamCallbackResult,
+        PaUtilChannelDescriptor *hostInputChannels,
+        unsigned long framesToProcess )
+{
+    void *userInput, *userOutput;
+    unsigned char *destBytePtr;
+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i;
+    unsigned long frameCount;
+    unsigned long framesToGo = framesToProcess;
+    unsigned long framesProcessed = 0;
+    
+    userOutput = 0;
+
+    do
+    {
+        frameCount = ( bp->framesInTempInputBuffer + framesToGo > bp->framesPerUserBuffer )
+                ? ( bp->framesPerUserBuffer - bp->framesInTempInputBuffer )
+                : framesToGo;
+
+        /* convert frameCount samples into temp buffer */
+
+        if( bp->userInputIsInterleaved )
+        {
+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) +
+                    bp->bytesPerUserInputSample * bp->inputChannelCount *
+                    bp->framesInTempInputBuffer;
+                      
+            destSampleStrideSamples = bp->inputChannelCount;
+            destChannelStrideBytes = bp->bytesPerUserInputSample;
+
+            userInput = bp->tempInputBuffer;
+        }
+        else /* user input is not interleaved */
+        {
+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) +
+                    bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;
+
+            destSampleStrideSamples = 1;
+            destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;
+
+            /* setup non-interleaved ptrs */
+            for( i=0; i<bp->inputChannelCount; ++i )
+            {
+                bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +
+                    i * bp->bytesPerUserInputSample * bp->framesPerUserBuffer;
+            }
+                    
+            userInput = bp->tempInputBufferPtrs;
+        }
+
+        for( i=0; i<bp->inputChannelCount; ++i )
+        {
+            bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                    hostInputChannels[i].data,
+                                    hostInputChannels[i].stride,
+                                    frameCount, &bp->ditherGenerator );
+
+            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
+
+            /* advance src ptr for next iteration */
+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+        }
+
+        bp->framesInTempInputBuffer += frameCount;
+
+        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer )
+        {
+            /**
+            @todo (non-critical optimisation)
+            The conditional below implements the continue/complete/abort mechanism
+            simply by continuing on iterating through the input buffer, but not
+            passing the data to the callback. With care, the outer loop could be
+            terminated earlier, thus some unneeded conversion cycles would be
+            saved.
+            */
+            if( *streamCallbackResult == paContinue )
+            {
+                bp->timeInfo->outputBufferDacTime = 0;
+
+                *streamCallbackResult = bp->streamCallback( userInput, userOutput,
+                        bp->framesPerUserBuffer, bp->timeInfo,
+                        bp->callbackStatusFlags, bp->userData );
+
+                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;
+            }
+            
+            bp->framesInTempInputBuffer = 0;
+        }
+
+        framesProcessed += frameCount;
+
+        framesToGo -= frameCount;
+    }while( framesToGo > 0 );
+
+    return framesProcessed;
+}
+
+
+/*
+    AdaptingOutputOnlyProcess() is a half duplex output buffer processor.
+    It converts data from the temporary output buffer, to the output buffers,
+    when the temporary output buffer is empty, it calls the streamCallback.
+*/
+static unsigned long AdaptingOutputOnlyProcess( PaUtilBufferProcessor *bp,
+        int *streamCallbackResult,
+        PaUtilChannelDescriptor *hostOutputChannels,
+        unsigned long framesToProcess )
+{
+    void *userInput, *userOutput;
+    unsigned char *srcBytePtr;
+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int srcChannelStrideBytes;  /* stride from one channel to the next, in bytes */
+    unsigned int i;
+    unsigned long frameCount;
+    unsigned long framesToGo = framesToProcess;
+    unsigned long framesProcessed = 0;
+
+    do
+    {
+        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult == paContinue )
+        {
+            userInput = 0;
+
+            /* setup userOutput */
+            if( bp->userOutputIsInterleaved )
+            {
+                userOutput = bp->tempOutputBuffer;
+            }
+            else /* user output is not interleaved */
+            {
+                for( i = 0; i < bp->outputChannelCount; ++i )
+                {
+                    bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +
+                            i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;
+                }
+
+                userOutput = bp->tempOutputBufferPtrs;
+            }
+
+            bp->timeInfo->inputBufferAdcTime = 0;
+            
+            *streamCallbackResult = bp->streamCallback( userInput, userOutput,
+                    bp->framesPerUserBuffer, bp->timeInfo,
+                    bp->callbackStatusFlags, bp->userData );
+
+            if( *streamCallbackResult == paAbort )
+            {
+                /* if the callback returned paAbort, we disregard its output */
+            }
+            else
+            {
+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;
+
+                bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;
+            }
+        }
+
+        if( bp->framesInTempOutputBuffer > 0 )
+        {
+            /* convert frameCount frames from user buffer to host buffer */
+
+            frameCount = PA_MIN_( bp->framesInTempOutputBuffer, framesToGo );
+
+            if( bp->userOutputIsInterleaved )
+            {
+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +
+                        bp->bytesPerUserOutputSample * bp->outputChannelCount *
+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);
+
+                srcSampleStrideSamples = bp->outputChannelCount;
+                srcChannelStrideBytes = bp->bytesPerUserOutputSample;
+            }
+            else /* user output is not interleaved */
+            {
+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +
+                        bp->bytesPerUserOutputSample *
+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);
+                            
+                srcSampleStrideSamples = 1;
+                srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;
+            }
+
+            for( i=0; i<bp->outputChannelCount; ++i )
+            {
+                bp->outputConverter(    hostOutputChannels[i].data,
+                                        hostOutputChannels[i].stride,
+                                        srcBytePtr, srcSampleStrideSamples,
+                                        frameCount, &bp->ditherGenerator );
+
+                srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
+
+                /* advance dest ptr for next iteration */
+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+            }
+
+            bp->framesInTempOutputBuffer -= frameCount;
+        }
+        else
+        {
+            /* no more user data is available because the callback has returned
+                paComplete or paAbort. Fill the remainder of the host buffer
+                with zeros.
+            */
+
+            frameCount = framesToGo;
+
+            for( i=0; i<bp->outputChannelCount; ++i )
+            {
+                bp->outputZeroer(   hostOutputChannels[i].data,
+                                    hostOutputChannels[i].stride,
+                                    frameCount );
+
+                /* advance dest ptr for next iteration */
+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+            }
+        }
+        
+        framesProcessed += frameCount;
+        
+        framesToGo -= frameCount;
+
+    }while( framesToGo > 0 );
+
+    return framesProcessed;
+}
+
+/* CopyTempOutputBuffersToHostOutputBuffers is called from AdaptingProcess to copy frames from
+       tempOutputBuffer to hostOutputChannels. This includes data conversion
+       and interleaving. 
+*/
+static void CopyTempOutputBuffersToHostOutputBuffers( PaUtilBufferProcessor *bp)
+{
+    unsigned long maxFramesToCopy;
+    PaUtilChannelDescriptor *hostOutputChannels;
+    unsigned int frameCount;
+    unsigned char *srcBytePtr;
+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i;
+
+     /* copy frames from user to host output buffers */
+     while( bp->framesInTempOutputBuffer > 0 &&
+             ((bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) > 0) )
+     {
+         maxFramesToCopy = bp->framesInTempOutputBuffer;
+
+         /* select the output buffer set (1st or 2nd) */
+         if( bp->hostOutputFrameCount[0] > 0 )
+         {
+             hostOutputChannels = bp->hostOutputChannels[0];
+             frameCount = PA_MIN_( bp->hostOutputFrameCount[0], maxFramesToCopy );
+         }
+         else
+         {
+             hostOutputChannels = bp->hostOutputChannels[1];
+             frameCount = PA_MIN_( bp->hostOutputFrameCount[1], maxFramesToCopy );
+         }
+
+         if( bp->userOutputIsInterleaved )
+         {
+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +
+                     bp->bytesPerUserOutputSample * bp->outputChannelCount *
+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);
+                         
+             srcSampleStrideSamples = bp->outputChannelCount;
+             srcChannelStrideBytes = bp->bytesPerUserOutputSample;
+         }
+         else /* user output is not interleaved */
+         {
+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +
+                     bp->bytesPerUserOutputSample *
+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);
+
+             srcSampleStrideSamples = 1;
+             srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;
+         }
+
+         for( i=0; i<bp->outputChannelCount; ++i )
+         {
+             assert( hostOutputChannels[i].data != NULL );
+             bp->outputConverter(    hostOutputChannels[i].data,
+                                     hostOutputChannels[i].stride,
+                                     srcBytePtr, srcSampleStrideSamples,
+                                     frameCount, &bp->ditherGenerator );
+
+             srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
+
+             /* advance dest ptr for next iteration */
+             hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                     frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+         }
+
+         if( bp->hostOutputFrameCount[0] > 0 )
+             bp->hostOutputFrameCount[0] -= frameCount;
+         else
+             bp->hostOutputFrameCount[1] -= frameCount;
+
+         bp->framesInTempOutputBuffer -= frameCount;
+     }
+}
+
+/*
+    AdaptingProcess is a full duplex adapting buffer processor. It converts
+    data from the temporary output buffer into the host output buffers, then
+    from the host input buffers into the temporary input buffers. Calling the
+    streamCallback when necessary.
+    When processPartialUserBuffers is 0, all available input data will be
+    consumed and all available output space will be filled. When
+    processPartialUserBuffers is non-zero, as many full user buffers
+    as possible will be processed, but partial buffers will not be consumed.
+*/
+static unsigned long AdaptingProcess( PaUtilBufferProcessor *bp,
+        int *streamCallbackResult, int processPartialUserBuffers )
+{
+    void *userInput, *userOutput;
+    unsigned long framesProcessed = 0;
+    unsigned long framesAvailable;
+    unsigned long endProcessingMinFrameCount;
+    unsigned long maxFramesToCopy;
+    PaUtilChannelDescriptor *hostInputChannels, *hostOutputChannels;
+    unsigned int frameCount;
+    unsigned char *destBytePtr;
+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i, j;
+
+    framesAvailable = bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1];/* this is assumed to be the same as the output buffer's frame count */
+
+    if( processPartialUserBuffers )
+        endProcessingMinFrameCount = 0;
+    else
+        endProcessingMinFrameCount = (bp->framesPerUserBuffer - 1);
+
+    /* Fill host output with remaining frames in user output (tempOutputBuffer) */
+    CopyTempOutputBuffersToHostOutputBuffers( bp );                    
+
+    while( framesAvailable > endProcessingMinFrameCount ) 
+    {
+
+        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult != paContinue )
+        {
+            /* the callback will not be called any more, so zero what remains
+                of the host output buffers */
+
+            for( i=0; i<2; ++i )
+            {
+                frameCount = bp->hostOutputFrameCount[i];
+                if( frameCount > 0 )
+                {
+                    hostOutputChannels = bp->hostOutputChannels[i];
+                    
+                    for( j=0; j<bp->outputChannelCount; ++j )
+                    {
+                        bp->outputZeroer(   hostOutputChannels[j].data,
+                                            hostOutputChannels[j].stride,
+                                            frameCount );
+
+                        /* advance dest ptr for next iteration  */
+                        hostOutputChannels[j].data = ((unsigned char*)hostOutputChannels[j].data) +
+                                frameCount * hostOutputChannels[j].stride * bp->bytesPerHostOutputSample;
+                    }
+                    bp->hostOutputFrameCount[i] = 0;
+                }
+            }
+        }          
+
+
+        /* copy frames from host to user input buffers */
+        while( bp->framesInTempInputBuffer < bp->framesPerUserBuffer &&
+                ((bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) > 0) )
+        {
+            maxFramesToCopy = bp->framesPerUserBuffer - bp->framesInTempInputBuffer;
+
+            /* select the input buffer set (1st or 2nd) */
+            if( bp->hostInputFrameCount[0] > 0 )
+            {
+                hostInputChannels = bp->hostInputChannels[0];
+                frameCount = PA_MIN_( bp->hostInputFrameCount[0], maxFramesToCopy );
+            }
+            else
+            {
+                hostInputChannels = bp->hostInputChannels[1];
+                frameCount = PA_MIN_( bp->hostInputFrameCount[1], maxFramesToCopy );
+            }
+
+            /* configure conversion destination pointers */
+            if( bp->userInputIsInterleaved )
+            {
+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) +
+                        bp->bytesPerUserInputSample * bp->inputChannelCount *
+                        bp->framesInTempInputBuffer;
+
+                destSampleStrideSamples = bp->inputChannelCount;
+                destChannelStrideBytes = bp->bytesPerUserInputSample;
+            }
+            else /* user input is not interleaved */
+            {
+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) +
+                        bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;
+
+                destSampleStrideSamples = 1;
+                destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;
+            }
+
+            for( i=0; i<bp->inputChannelCount; ++i )
+            {
+                bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                        hostInputChannels[i].data,
+                                        hostInputChannels[i].stride,
+                                        frameCount, &bp->ditherGenerator );
+
+                destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
+
+                /* advance src ptr for next iteration */
+                hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                        frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+            }
+
+            if( bp->hostInputFrameCount[0] > 0 )
+                bp->hostInputFrameCount[0] -= frameCount;
+            else
+                bp->hostInputFrameCount[1] -= frameCount;
+                
+            bp->framesInTempInputBuffer += frameCount;
+
+            /* update framesAvailable and framesProcessed based on input consumed
+                unless something is very wrong this will also correspond to the
+                amount of output generated */
+            framesAvailable -= frameCount;
+            framesProcessed += frameCount;
+        }
+
+        /* call streamCallback */
+        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer &&
+            bp->framesInTempOutputBuffer == 0 )
+        {
+            if( *streamCallbackResult == paContinue )
+            {
+                /* setup userInput */
+                if( bp->userInputIsInterleaved )
+                {
+                    userInput = bp->tempInputBuffer;
+                }
+                else /* user input is not interleaved */
+                {
+                    for( i = 0; i < bp->inputChannelCount; ++i )
+                    {
+                        bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +
+                                i * bp->framesPerUserBuffer * bp->bytesPerUserInputSample;
+                    }
+
+                    userInput = bp->tempInputBufferPtrs;
+                }
+
+                /* setup userOutput */
+                if( bp->userOutputIsInterleaved )
+                {
+                    userOutput = bp->tempOutputBuffer;
+                }
+                else /* user output is not interleaved */
+                {
+                    for( i = 0; i < bp->outputChannelCount; ++i )
+                    {
+                        bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +
+                                i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;
+                    }
+
+                    userOutput = bp->tempOutputBufferPtrs;
+                }
+
+                /* call streamCallback */
+
+                *streamCallbackResult = bp->streamCallback( userInput, userOutput,
+                        bp->framesPerUserBuffer, bp->timeInfo,
+                        bp->callbackStatusFlags, bp->userData );
+
+                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;
+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;
+
+                bp->framesInTempInputBuffer = 0;
+
+                if( *streamCallbackResult == paAbort )
+                    bp->framesInTempOutputBuffer = 0;
+                else
+                    bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;
+            }
+            else
+            {
+                /* paComplete or paAbort has already been called. */
+
+                bp->framesInTempInputBuffer = 0;
+            }
+        }
+
+        /* copy frames from user (tempOutputBuffer) to host output buffers (hostOutputChannels) 
+           Means to process the user output provided by the callback. Has to be called after
+            each callback. */
+        CopyTempOutputBuffersToHostOutputBuffers( bp );                        
+
+    }
+    
+    return framesProcessed;
+}
+
+
+unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bp, int *streamCallbackResult )
+{
+    unsigned long framesToProcess, framesToGo;
+    unsigned long framesProcessed = 0;
+    
+    if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0
+            && bp->hostInputChannels[0][0].data /* input was supplied (see PaUtil_SetNoInput) */
+            && bp->hostOutputChannels[0][0].data /* output was supplied (see PaUtil_SetNoOutput) */ )
+    {
+        assert( (bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) ==
+                (bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) );
+    }
+
+    assert( *streamCallbackResult == paContinue
+            || *streamCallbackResult == paComplete
+            || *streamCallbackResult == paAbort ); /* don't forget to pass in a valid callback result value */
+
+    if( bp->useNonAdaptingProcess )
+    {
+        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )
+        {
+            /* full duplex non-adapting process, splice buffers if they are
+                different lengths */
+
+            framesToGo = bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]; /* relies on assert above for input/output equivalence */
+
+            do{
+                unsigned long noInputInputFrameCount;
+                unsigned long *hostInputFrameCount;
+                PaUtilChannelDescriptor *hostInputChannels;
+                unsigned long noOutputOutputFrameCount;
+                unsigned long *hostOutputFrameCount;
+                PaUtilChannelDescriptor *hostOutputChannels;
+                unsigned long framesProcessedThisIteration;
+
+                if( !bp->hostInputChannels[0][0].data )
+                {
+                    /* no input was supplied (see PaUtil_SetNoInput)
+                        NonAdaptingProcess knows how to deal with this
+                    */
+                    noInputInputFrameCount = framesToGo;
+                    hostInputFrameCount = &noInputInputFrameCount;
+                    hostInputChannels = 0;
+                }
+                else if( bp->hostInputFrameCount[0] != 0 )
+                {
+                    hostInputFrameCount = &bp->hostInputFrameCount[0];
+                    hostInputChannels = bp->hostInputChannels[0];
+                }
+                else
+                {
+                    hostInputFrameCount = &bp->hostInputFrameCount[1];
+                    hostInputChannels = bp->hostInputChannels[1];
+                }
+
+                if( !bp->hostOutputChannels[0][0].data )
+                {
+                    /* no output was supplied (see PaUtil_SetNoOutput)
+                        NonAdaptingProcess knows how to deal with this
+                    */
+                    noOutputOutputFrameCount = framesToGo;
+                    hostOutputFrameCount = &noOutputOutputFrameCount;
+                    hostOutputChannels = 0;
+                }
+                if( bp->hostOutputFrameCount[0] != 0 )
+                {
+                    hostOutputFrameCount = &bp->hostOutputFrameCount[0];
+                    hostOutputChannels = bp->hostOutputChannels[0];
+                }
+                else
+                {
+                    hostOutputFrameCount = &bp->hostOutputFrameCount[1];
+                    hostOutputChannels = bp->hostOutputChannels[1];
+                }
+
+                framesToProcess = PA_MIN_( *hostInputFrameCount,
+                                       *hostOutputFrameCount );
+
+                assert( framesToProcess != 0 );
+                
+                framesProcessedThisIteration = NonAdaptingProcess( bp, streamCallbackResult,
+                        hostInputChannels, hostOutputChannels,
+                        framesToProcess );                                       
+
+                *hostInputFrameCount -= framesProcessedThisIteration;
+                *hostOutputFrameCount -= framesProcessedThisIteration;
+
+                framesProcessed += framesProcessedThisIteration;
+                framesToGo -= framesProcessedThisIteration;
+                
+            }while( framesToGo > 0 );
+        }
+        else
+        {
+            /* half duplex non-adapting process, just process 1st and 2nd buffer */
+            /* process first buffer */
+
+            framesToProcess = (bp->inputChannelCount != 0)
+                            ? bp->hostInputFrameCount[0]
+                            : bp->hostOutputFrameCount[0];
+
+            framesProcessed = NonAdaptingProcess( bp, streamCallbackResult,
+                        bp->hostInputChannels[0], bp->hostOutputChannels[0],
+                        framesToProcess );
+
+            /* process second buffer if provided */
+    
+            framesToProcess = (bp->inputChannelCount != 0)
+                            ? bp->hostInputFrameCount[1]
+                            : bp->hostOutputFrameCount[1];
+            if( framesToProcess > 0 )
+            {
+                framesProcessed += NonAdaptingProcess( bp, streamCallbackResult,
+                    bp->hostInputChannels[1], bp->hostOutputChannels[1],
+                    framesToProcess );
+            }
+        }
+    }
+    else /* block adaption necessary*/
+    {
+
+        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )
+        {
+            /* full duplex */
+            
+            if( bp->hostBufferSizeMode == paUtilVariableHostBufferSizePartialUsageAllowed  )
+            {
+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,
+                        0 /* dont process partial user buffers */ );
+            }
+            else
+            {
+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,
+                        1 /* process partial user buffers */ );
+            }
+        }
+        else if( bp->inputChannelCount != 0 )
+        {
+            /* input only */
+            framesToProcess = bp->hostInputFrameCount[0];
+
+            framesProcessed = AdaptingInputOnlyProcess( bp, streamCallbackResult,
+                        bp->hostInputChannels[0], framesToProcess );
+
+            framesToProcess = bp->hostInputFrameCount[1];
+            if( framesToProcess > 0 )
+            {
+                framesProcessed += AdaptingInputOnlyProcess( bp, streamCallbackResult,
+                        bp->hostInputChannels[1], framesToProcess );
+            }
+        }
+        else
+        {
+            /* output only */
+            framesToProcess = bp->hostOutputFrameCount[0];
+
+            framesProcessed = AdaptingOutputOnlyProcess( bp, streamCallbackResult,
+                        bp->hostOutputChannels[0], framesToProcess );
+
+            framesToProcess = bp->hostOutputFrameCount[1];
+            if( framesToProcess > 0 )
+            {
+                framesProcessed += AdaptingOutputOnlyProcess( bp, streamCallbackResult,
+                        bp->hostOutputChannels[1], framesToProcess );
+            }
+        }
+    }
+
+    return framesProcessed;
+}
+
+
+int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bp )
+{
+    return (bp->framesInTempOutputBuffer) ? 0 : 1;
+} 
+
+
+unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bp,
+        void **buffer, unsigned long frameCount )
+{
+    PaUtilChannelDescriptor *hostInputChannels;
+    unsigned int framesToCopy;
+    unsigned char *destBytePtr;
+    void **nonInterleavedDestPtrs;
+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i;
+
+    hostInputChannels = bp->hostInputChannels[0];
+    framesToCopy = PA_MIN_( bp->hostInputFrameCount[0], frameCount );
+
+    if( bp->userInputIsInterleaved )
+    {
+        destBytePtr = (unsigned char*)*buffer;
+        
+        destSampleStrideSamples = bp->inputChannelCount;
+        destChannelStrideBytes = bp->bytesPerUserInputSample;
+
+        for( i=0; i<bp->inputChannelCount; ++i )
+        {
+            bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                hostInputChannels[i].data,
+                                hostInputChannels[i].stride,
+                                framesToCopy, &bp->ditherGenerator );
+
+            destBytePtr += destChannelStrideBytes;  /* skip to next dest channel */
+
+            /* advance source ptr for next iteration */
+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+        }
+
+        /* advance callers dest pointer (buffer) */
+        *buffer = ((unsigned char *)*buffer) +
+                framesToCopy * bp->inputChannelCount * bp->bytesPerUserInputSample;
+    }
+    else
+    {
+        /* user input is not interleaved */
+        
+        nonInterleavedDestPtrs = (void**)*buffer;
+
+        destSampleStrideSamples = 1;
+        
+        for( i=0; i<bp->inputChannelCount; ++i )
+        {
+            destBytePtr = (unsigned char*)nonInterleavedDestPtrs[i];
+
+            bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                hostInputChannels[i].data,
+                                hostInputChannels[i].stride,
+                                framesToCopy, &bp->ditherGenerator );
+
+            /* advance callers dest pointer (nonInterleavedDestPtrs[i]) */
+            destBytePtr += bp->bytesPerUserInputSample * framesToCopy;
+            nonInterleavedDestPtrs[i] = destBytePtr;
+            
+            /* advance source ptr for next iteration */
+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
+        }
+    }
+
+    bp->hostInputFrameCount[0] -= framesToCopy;
+    
+    return framesToCopy;
+}
+
+unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bp,
+        const void ** buffer, unsigned long frameCount )
+{
+    PaUtilChannelDescriptor *hostOutputChannels;
+    unsigned int framesToCopy;
+    unsigned char *srcBytePtr;
+    void **nonInterleavedSrcPtrs;
+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */
+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */
+    unsigned int i;
+
+    hostOutputChannels = bp->hostOutputChannels[0];
+    framesToCopy = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );
+
+    if( bp->userOutputIsInterleaved )
+    {
+        srcBytePtr = (unsigned char*)*buffer;
+        
+        srcSampleStrideSamples = bp->outputChannelCount;
+        srcChannelStrideBytes = bp->bytesPerUserOutputSample;
+
+        for( i=0; i<bp->outputChannelCount; ++i )
+        {
+            bp->outputConverter(    hostOutputChannels[i].data,
+                                    hostOutputChannels[i].stride,
+                                    srcBytePtr, srcSampleStrideSamples,
+                                    framesToCopy, &bp->ditherGenerator );
+
+            srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
+
+            /* advance dest ptr for next iteration */
+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+        }
+
+        /* advance callers source pointer (buffer) */
+        *buffer = ((unsigned char *)*buffer) +
+                framesToCopy * bp->outputChannelCount * bp->bytesPerUserOutputSample;
+
+    }
+    else
+    {
+        /* user output is not interleaved */
+        
+        nonInterleavedSrcPtrs = (void**)*buffer;
+
+        srcSampleStrideSamples = 1;
+        
+        for( i=0; i<bp->outputChannelCount; ++i )
+        {
+            srcBytePtr = (unsigned char*)nonInterleavedSrcPtrs[i];
+            
+            bp->outputConverter(    hostOutputChannels[i].data,
+                                    hostOutputChannels[i].stride,
+                                    srcBytePtr, srcSampleStrideSamples,
+                                    framesToCopy, &bp->ditherGenerator );
+
+
+            /* advance callers source pointer (nonInterleavedSrcPtrs[i]) */
+            srcBytePtr += bp->bytesPerUserOutputSample * framesToCopy;
+            nonInterleavedSrcPtrs[i] = srcBytePtr;
+            
+            /* advance dest ptr for next iteration */
+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+        }
+    }
+
+    bp->hostOutputFrameCount[0] += framesToCopy;
+    
+    return framesToCopy;
+}
+
+
+unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bp, unsigned long frameCount )
+{
+    PaUtilChannelDescriptor *hostOutputChannels;
+    unsigned int framesToZero;
+    unsigned int i;
+
+    hostOutputChannels = bp->hostOutputChannels[0];
+    framesToZero = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );
+
+    for( i=0; i<bp->outputChannelCount; ++i )
+    {
+        bp->outputZeroer(   hostOutputChannels[i].data,
+                            hostOutputChannels[i].stride,
+                            framesToZero );
+
+
+        /* advance dest ptr for next iteration */
+        hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                framesToZero * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+    }
+
+    bp->hostOutputFrameCount[0] += framesToZero;
+    
+    return framesToZero;
+}
diff --git a/portaudio/src/common/pa_process.h b/portaudio/src/common/pa_process.h
new file mode 100644 (file)
index 0000000..37b91d7
--- /dev/null
@@ -0,0 +1,754 @@
+#ifndef PA_PROCESS_H
+#define PA_PROCESS_H
+/*
+ * $Id$
+ * Portable Audio I/O Library callback buffer processing adapters
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+/** @file
+ @ingroup common_src
+
+ @brief Buffer Processor prototypes. A Buffer Processor performs buffer length
+ adaption, coordinates sample format conversion, and interleaves/deinterleaves
+ channels.
+
+ <h3>Overview</h3>
+
+ The "Buffer Processor" (PaUtilBufferProcessor) manages conversion of audio
+ data from host buffers to user buffers and back again. Where required, the
+ buffer processor takes care of converting between host and user sample formats,
+ interleaving and deinterleaving multichannel buffers, and adapting between host
+ and user buffers with different lengths. The buffer processor may be used with
+ full and half duplex streams, for both callback streams and blocking read/write
+ streams.
+
+ One of the important capabilities provided by the buffer processor is
+ the ability to adapt between user and host buffer sizes of different lengths
+ with minimum latency. Although this task is relatively easy to perform when
+ the host buffer size is an integer multiple of the user buffer size, the
+ problem is more complicated when this is not the case - especially for
+ full-duplex callback streams. Where necessary the adaption is implemented by
+ internally buffering some input and/or output data. The buffer adation
+ algorithm used by the buffer processor was originally implemented by
+ Stephan Letz for the ASIO version of PortAudio, and is described in his
+ Callback_adaption_.pdf which is included in the distribution.
+
+ The buffer processor performs sample conversion using the functions provided
+ by pa_converters.c.
+
+ The following sections provide an overview of how to use the buffer processor.
+ Interested readers are advised to consult the host API implementations for
+ examples of buffer processor usage.
+
+ <h4>Initialization, resetting and termination</h4>
+
+ When a stream is opened, the buffer processor should be initialized using
+ PaUtil_InitializeBufferProcessor. This function initializes internal state
+ and allocates temporary buffers as neccesary according to the supplied
+ configuration parameters. Some of the parameters correspond to those requested
+ by the user in their call to Pa_OpenStream(), others reflect the requirements
+ of the host API implementation - they indicate host buffer sizes, formats,
+ and the type of buffering which the Host API uses. The buffer processor should
+ be initialized for callback streams and blocking read/write streams.
+
+ Call PaUtil_ResetBufferProcessor to clear any sample data which is present
+ in the buffer processor before starting to use it (for example when
+ Pa_StartStream is called).
+
+ When the buffer processor is no longer used call
+ PaUtil_TerminateBufferProcessor.
+
+ <h4>Using the buffer processor for a callback stream</h4>
+
+ The buffer processor's role in a callback stream is to take host input buffers
+ process them with the stream callback, and fill host output buffers. For a
+ full duplex stream, the buffer processor handles input and output simultaneously
+ due to the requirements of the minimum-latency buffer adation algorithm.
+
+ When a host buffer becomes available, the implementation should call
+ the buffer processor to process the buffer. The buffer processor calls the
+ stream callback to consume and/or produce audio data as necessary. The buffer
+ processor will convert sample formats, interleave/deinterleave channels,
+ and slice or chunk the data to the appropriate buffer lengths according to
+ the requirements of the stream callback and the host API.
+
+ To process a host buffer (or a pair of host buffers for a full-duplex stream)
+ use the following calling sequence:
+
+ -# Call PaUtil_BeginBufferProcessing
+ -# For a stream which takes input:
+    - Call PaUtil_SetInputFrameCount with the number of frames in the host input
+        buffer.
+    - Call one of the following functions one or more times to tell the
+        buffer processor about the host input buffer(s): PaUtil_SetInputChannel,
+        PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.
+        Which function you call will depend on whether the host buffer(s) are
+        interleaved or not.
+    - If the available host data is split accross two buffers (for example a
+        data range at the end of a circular buffer and another range at the
+        beginning of the circular buffer), also call
+        PaUtil_Set2ndInputFrameCount, PaUtil_Set2ndInputChannel,
+        PaUtil_Set2ndInterleavedInputChannels,
+        PaUtil_Set2ndNonInterleavedInputChannel as necessary to tell the buffer
+        processor about the second buffer.
+ -# For a stream which generates output:
+    - Call PaUtil_SetOutputFrameCount with the number of frames in the host
+        output buffer.
+    - Call one of the following functions one or more times to tell the
+        buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,
+        PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.
+        Which function you call will depend on whether the host buffer(s) are
+        interleaved or not.
+    - If the available host output buffer space is split accross two buffers
+        (for example a data range at the end of a circular buffer and another
+        range at the beginning of the circular buffer), call
+        PaUtil_Set2ndOutputFrameCount, PaUtil_Set2ndOutputChannel,
+        PaUtil_Set2ndInterleavedOutputChannels,
+        PaUtil_Set2ndNonInterleavedOutputChannel as necessary to tell the buffer
+        processor about the second buffer.
+ -# Call PaUtil_EndBufferProcessing, this function performs the actual data
+    conversion and processing.
+
+
+ <h4>Using the buffer processor for a blocking read/write stream</h4>
+
+ Blocking read/write streams use the buffer processor to convert and copy user
+ output data to a host buffer, and to convert and copy host input data to
+ the user's buffer. The buffer processor does not perform any buffer adaption.
+ When using the buffer processor in a blocking read/write stream the input and
+ output conversion are performed separately by the PaUtil_CopyInput and
+ PaUtil_CopyOutput functions.
+
+ To copy data from a host input buffer to the buffer(s) which the user supplies
+ to Pa_ReadStream, use the following calling sequence.
+
+ - Repeat the following three steps until the user buffer(s) have been filled
+    with samples from the host input buffers:
+     -# Call PaUtil_SetInputFrameCount with the number of frames in the host
+        input buffer.
+     -# Call one of the following functions one or more times to tell the
+        buffer processor about the host input buffer(s): PaUtil_SetInputChannel,
+        PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.
+        Which function you call will depend on whether the host buffer(s) are
+        interleaved or not.
+     -# Call PaUtil_CopyInput with the user buffer pointer (or a copy of the
+        array of buffer pointers for a non-interleaved stream) passed to
+        Pa_ReadStream, along with the number of frames in the user buffer(s).
+        Be careful to pass a <i>copy</i> of the user buffer pointers to
+        PaUtil_CopyInput because PaUtil_CopyInput advances the pointers to
+        the start of the next region to copy.
+ - PaUtil_CopyInput will not copy more data than is available in the
+    host buffer(s), so the above steps need to be repeated until the user
+    buffer(s) are full.
+
+ To copy data to the host output buffer from the user buffers(s) supplied
+ to Pa_WriteStream use the following calling sequence.
+
+ - Repeat the following three steps until all frames from the user buffer(s)
+    have been copied to the host API:
+     -# Call PaUtil_SetOutputFrameCount with the number of frames in the host
+        output buffer.
+     -# Call one of the following functions one or more times to tell the
+        buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,
+        PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.
+        Which function you call will depend on whether the host buffer(s) are
+        interleaved or not.
+     -# Call PaUtil_CopyOutput with the user buffer pointer (or a copy of the
+        array of buffer pointers for a non-interleaved stream) passed to
+        Pa_WriteStream, along with the number of frames in the user buffer(s).
+        Be careful to pass a <i>copy</i> of the user buffer pointers to 
+        PaUtil_CopyOutput because PaUtil_CopyOutput advances the pointers to
+        the start of the next region to copy.
+ - PaUtil_CopyOutput will not copy more data than fits in the host buffer(s),
+    so the above steps need to be repeated until all user data is copied.
+*/
+
+
+#include "portaudio.h"
+#include "pa_converters.h"
+#include "pa_dither.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/** @brief Mode flag passed to PaUtil_InitializeBufferProcessor indicating the type
+ of buffering that the host API uses.
+
+ The mode used depends on whether the host API or the implementation manages
+ the buffers, and how these buffers are used (scatter gather, circular buffer).
+*/
+typedef enum {
+/** The host buffer size is a fixed known size. */
+    paUtilFixedHostBufferSize,
+
+/** The host buffer size may vary, but has a known maximum size. */
+    paUtilBoundedHostBufferSize,
+
+/** Nothing is known about the host buffer size. */
+    paUtilUnknownHostBufferSize,
+
+/** The host buffer size varies, and the client does not require the buffer
+ processor to consume all of the input and fill all of the output buffer. This
+ is useful when the implementation has access to the host API's circular buffer
+ and only needs to consume/fill some of it, not necessarily all of it, with each
+ call to the buffer processor. This is the only mode where
+ PaUtil_EndBufferProcessing() may not consume the whole buffer.
+*/
+    paUtilVariableHostBufferSizePartialUsageAllowed
+}PaUtilHostBufferSizeMode;
+
+
+/** @brief An auxilliary data structure used internally by the buffer processor
+ to represent host input and output buffers. */
+typedef struct PaUtilChannelDescriptor{
+    void *data;
+    unsigned int stride;  /**< stride in samples, not bytes */
+}PaUtilChannelDescriptor;
+
+
+/** @brief The main buffer processor data structure.
+
+ Allocate one of these, initialize it with PaUtil_InitializeBufferProcessor
+ and terminate it with PaUtil_TerminateBufferProcessor.
+*/
+typedef struct {
+    unsigned long framesPerUserBuffer;
+    unsigned long framesPerHostBuffer;
+
+    PaUtilHostBufferSizeMode hostBufferSizeMode;
+    int useNonAdaptingProcess;
+    int userOutputSampleFormatIsEqualToHost;
+    int userInputSampleFormatIsEqualToHost;
+    unsigned long framesPerTempBuffer;
+
+    unsigned int inputChannelCount;
+    unsigned int bytesPerHostInputSample;
+    unsigned int bytesPerUserInputSample;
+    int userInputIsInterleaved;
+    PaUtilConverter *inputConverter;
+    PaUtilZeroer *inputZeroer;
+    
+    unsigned int outputChannelCount;
+    unsigned int bytesPerHostOutputSample;
+    unsigned int bytesPerUserOutputSample;
+    int userOutputIsInterleaved;
+    PaUtilConverter *outputConverter;
+    PaUtilZeroer *outputZeroer;
+
+    unsigned long initialFramesInTempInputBuffer;
+    unsigned long initialFramesInTempOutputBuffer;
+
+    void *tempInputBuffer;          /**< used for slips, block adaption, and conversion. */
+    void **tempInputBufferPtrs;     /**< storage for non-interleaved buffer pointers, NULL for interleaved user input */
+    unsigned long framesInTempInputBuffer; /**< frames remaining in input buffer from previous adaption iteration */
+
+    void *tempOutputBuffer;         /**< used for slips, block adaption, and conversion. */
+    void **tempOutputBufferPtrs;    /**< storage for non-interleaved buffer pointers, NULL for interleaved user output */
+    unsigned long framesInTempOutputBuffer; /**< frames remaining in input buffer from previous adaption iteration */
+
+    PaStreamCallbackTimeInfo *timeInfo;
+
+    PaStreamCallbackFlags callbackStatusFlags;
+
+    int hostInputIsInterleaved;
+    unsigned long hostInputFrameCount[2];
+    PaUtilChannelDescriptor *hostInputChannels[2]; /**< pointers to arrays of channel descriptors.
+                                                        pointers are NULL for half-duplex output processing.
+                                                        hostInputChannels[i].data is NULL when the caller
+                                                        calls PaUtil_SetNoInput()
+                                                        */
+    int hostOutputIsInterleaved;
+    unsigned long hostOutputFrameCount[2];
+    PaUtilChannelDescriptor *hostOutputChannels[2]; /**< pointers to arrays of channel descriptors.
+                                                         pointers are NULL for half-duplex input processing.
+                                                         hostOutputChannels[i].data is NULL when the caller
+                                                         calls PaUtil_SetNoOutput()
+                                                         */
+
+    PaUtilTriangularDitherGenerator ditherGenerator;
+
+    double samplePeriod;
+
+    PaStreamCallback *streamCallback;
+    void *userData;
+} PaUtilBufferProcessor;
+
+
+/** @name Initialization, termination, resetting and info */
+/*@{*/
+
+/** Initialize a buffer processor's representation stored in a
+ PaUtilBufferProcessor structure. Be sure to call
+ PaUtil_TerminateBufferProcessor after finishing with a buffer processor.
+
+ @param bufferProcessor The buffer processor structure to initialize.
+
+ @param inputChannelCount The number of input channels as passed to
+ Pa_OpenStream or 0 for an output-only stream.
+
+ @param userInputSampleFormat Format of user input samples, as passed to
+ Pa_OpenStream. This parameter is ignored for ouput-only streams.
+ @param hostInputSampleFormat Format of host input samples. This parameter is
+ ignored for output-only streams. See note about host buffer interleave below.
+
+ @param outputChannelCount The number of output channels as passed to
+ Pa_OpenStream or 0 for an input-only stream.
+
+ @param userOutputSampleFormat Format of user output samples, as passed to
+ Pa_OpenStream. This parameter is ignored for input-only streams.
+ @param hostOutputSampleFormat Format of host output samples. This parameter is
+ ignored for input-only streams. See note about host buffer interleave below.
+
+ @param sampleRate Sample rate of the stream. The more accurate this is the
+ better - it is used for updating time stamps when adapting buffers.
+ @param streamFlags Stream flags as passed to Pa_OpenStream, this parameter is
+ used for selecting special sample conversion options such as clipping and
+ dithering.
+ @param framesPerUserBuffer Number of frames per user buffer, as requested
+ by the framesPerBuffer parameter to Pa_OpenStream. This parameter may be
+ zero to indicate that the user will accept any (and varying) buffer sizes.
+
+ @param framesPerHostBuffer Specifies the number of frames per host buffer
+ for the fixed buffer size mode, and the maximum number of frames
+ per host buffer for the bounded host buffer size mode. It is ignored for
+ the other modes.
+
+ @param hostBufferSizeMode A mode flag indicating the size variability of
+ host buffers that will be passed to the buffer processor. See
+ PaUtilHostBufferSizeMode for further details.
+ @param streamCallback The user stream callback passed to Pa_OpenStream.
+
+ @param userData The user data field passed to Pa_OpenStream.
+    
+ @note The interleave flag is ignored for host buffer formats. Host
+ interleave is determined by the use of different SetInput and SetOutput
+ functions.
+
+ @return An error code indicating whether the initialization was successful.
+ If the error code is not PaNoError, the buffer processor was not initialized
+ and should not be used.
+ @see Pa_OpenStream, PaUtilHostBufferSizeMode, PaUtil_TerminateBufferProcessor
+*/
+PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bufferProcessor,
+            int inputChannelCount, PaSampleFormat userInputSampleFormat,
+            PaSampleFormat hostInputSampleFormat,
+            int outputChannelCount, PaSampleFormat userOutputSampleFormat,
+            PaSampleFormat hostOutputSampleFormat,
+            double sampleRate,
+            PaStreamFlags streamFlags,
+            unsigned long framesPerUserBuffer, /* 0 indicates don't care */
+            unsigned long framesPerHostBuffer,
+            PaUtilHostBufferSizeMode hostBufferSizeMode,
+            PaStreamCallback *streamCallback, void *userData );
+
+
+/** Terminate a buffer processor's representation. Deallocates any temporary
+ buffers allocated by PaUtil_InitializeBufferProcessor.
+ @param bufferProcessor The buffer processor structure to terminate.
+
+ @see PaUtil_InitializeBufferProcessor.
+*/
+void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bufferProcessor );
+
+
+/** Clear any internally buffered data. If you call
+ PaUtil_InitializeBufferProcessor in your OpenStream routine, make sure you
+ call PaUtil_ResetBufferProcessor in your StartStream call.
+
+ @param bufferProcessor The buffer processor to reset.
+*/
+void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bufferProcessor );
+
+
+/** Retrieve the input latency of a buffer processor, in frames.
+
+ @param bufferProcessor The buffer processor examine.
+
+ @return The input latency introduced by the buffer processor, in frames.
+
+ @see PaUtil_GetBufferProcessorOutputLatencyFrames
+*/
+unsigned long PaUtil_GetBufferProcessorInputLatencyFrames( PaUtilBufferProcessor* bufferProcessor );
+
+/** Retrieve the output latency of a buffer processor, in frames.
+
+ @param bufferProcessor The buffer processor examine.
+
+ @return The output latency introduced by the buffer processor, in frames.
+
+ @see PaUtil_GetBufferProcessorInputLatencyFrames
+*/
+unsigned long PaUtil_GetBufferProcessorOutputLatencyFrames( PaUtilBufferProcessor* bufferProcessor );
+
+/*@}*/
+
+
+/** @name Host buffer pointer configuration
+
+ Functions to set host input and output buffers, used by both callback streams
+ and blocking read/write streams.
+*/
+/*@{*/ 
+
+
+/** Set the number of frames in the input host buffer(s) specified by the
+ PaUtil_Set*InputChannel functions.
+
+ @param bufferProcessor The buffer processor.
+
+ @param frameCount The number of host input frames. A 0 frameCount indicates to
+ use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.
+
+ @see PaUtil_SetNoInput, PaUtil_SetInputChannel,
+ PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel
+*/
+void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bufferProcessor,
+        unsigned long frameCount );
+
+        
+/** Indicate that no input is avalable. This function should be used when
+ priming the output of a full-duplex stream opened with the
+ paPrimeOutputBuffersUsingStreamCallback flag. Note that it is not necessary
+ to call this or any othe PaUtil_Set*Input* functions for ouput-only streams.
+
+ @param bufferProcessor The buffer processor.
+*/
+void PaUtil_SetNoInput( PaUtilBufferProcessor* bufferProcessor );
+
+
+/** Provide the buffer processor with a pointer to a host input channel.
+
+ @param bufferProcessor The buffer processor.
+ @param channel The channel number.
+ @param data The buffer.
+ @param stride The stride from one sample to the next, in samples. For
+ interleaved host buffers, the stride will usually be the same as the number of
+ channels in the buffer.
+*/
+void PaUtil_SetInputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data, unsigned int stride );
+
+
+/** Provide the buffer processor with a pointer to an number of interleaved
+ host input channels.
+
+ @param bufferProcessor The buffer processor.
+ @param firstChannel The first channel number.
+ @param data The buffer.
+ @param channelCount The number of interleaved channels in the buffer. If
+ channelCount is zero, the number of channels specified to
+ PaUtil_InitializeBufferProcessor will be used.
+*/
+void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int firstChannel, void *data, unsigned int channelCount );
+
+
+/** Provide the buffer processor with a pointer to one non-interleaved host
+ output channel.
+
+ @param bufferProcessor The buffer processor.
+ @param channel The channel number.
+ @param data The buffer.
+*/
+void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data );
+
+
+/** Use for the second buffer half when the input buffer is split in two halves.
+ @see PaUtil_SetInputFrameCount
+*/
+void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bufferProcessor,
+        unsigned long frameCount );
+
+/** Use for the second buffer half when the input buffer is split in two halves.
+ @see PaUtil_SetInputChannel
+*/
+void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data, unsigned int stride );
+
+/** Use for the second buffer half when the input buffer is split in two halves.
+ @see PaUtil_SetInterleavedInputChannels
+*/
+void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int firstChannel, void *data, unsigned int channelCount );
+
+/** Use for the second buffer half when the input buffer is split in two halves.
+ @see PaUtil_SetNonInterleavedInputChannel
+*/
+void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data );
+
+        
+/** Set the number of frames in the output host buffer(s) specified by the
+ PaUtil_Set*OutputChannel functions.
+
+ @param bufferProcessor The buffer processor.
+
+ @param frameCount The number of host output frames. A 0 frameCount indicates to
+ use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.
+
+ @see PaUtil_SetOutputChannel, PaUtil_SetInterleavedOutputChannels,
+ PaUtil_SetNonInterleavedOutputChannel
+*/
+void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,
+        unsigned long frameCount );
+
+
+/** Indicate that the output will be discarded. This function should be used
+ when implementing the paNeverDropInput mode for full duplex streams.
+
+ @param bufferProcessor The buffer processor.
+*/
+void PaUtil_SetNoOutput( PaUtilBufferProcessor* bufferProcessor );
+
+
+/** Provide the buffer processor with a pointer to a host output channel.
+
+ @param bufferProcessor The buffer processor.
+ @param channel The channel number.
+ @param data The buffer.
+ @param stride The stride from one sample to the next, in samples. For
+ interleaved host buffers, the stride will usually be the same as the number of
+ channels in the buffer.
+*/
+void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data, unsigned int stride );
+
+
+/** Provide the buffer processor with a pointer to a number of interleaved
+ host output channels.
+
+ @param bufferProcessor The buffer processor.
+ @param firstChannel The first channel number.
+ @param data The buffer.
+ @param channelCount The number of interleaved channels in the buffer. If
+ channelCount is zero, the number of channels specified to
+ PaUtil_InitializeBufferProcessor will be used.
+*/
+void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int firstChannel, void *data, unsigned int channelCount );
+
+        
+/** Provide the buffer processor with a pointer to one non-interleaved host
+ output channel.
+
+ @param bufferProcessor The buffer processor.
+ @param channel The channel number.
+ @param data The buffer.
+*/
+void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data );
+
+
+/** Use for the second buffer half when the output buffer is split in two halves.
+ @see PaUtil_SetOutputFrameCount
+*/
+void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,
+        unsigned long frameCount );
+
+/** Use for the second buffer half when the output buffer is split in two halves.
+ @see PaUtil_SetOutputChannel
+*/
+void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data, unsigned int stride );
+
+/** Use for the second buffer half when the output buffer is split in two halves.
+ @see PaUtil_SetInterleavedOutputChannels
+*/
+void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int firstChannel, void *data, unsigned int channelCount );
+
+/** Use for the second buffer half when the output buffer is split in two halves.
+ @see PaUtil_SetNonInterleavedOutputChannel
+*/
+void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,
+        unsigned int channel, void *data );
+
+/*@}*/
+
+
+/** @name Buffer processing functions for callback streams
+*/
+/*@{*/
+
+/** Commence processing a host buffer (or a pair of host buffers in the
+ full-duplex case) for a callback stream.
+
+ @param bufferProcessor The buffer processor.
+
+ @param timeInfo Timing information for the first sample of the host
+ buffer(s). This information may be adjusted when buffer adaption is being
+ performed.
+
+ @param callbackStatusFlags Flags indicating whether underruns and overruns
+ have occurred since the last time the buffer processor was called.
+*/
+void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bufferProcessor,
+        PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags );
+
+        
+/** Finish processing a host buffer (or a pair of host buffers in the
+ full-duplex case) for a callback stream.
+
+ @param bufferProcessor The buffer processor.
+ @param callbackResult On input, indicates a previous callback result, and on
+ exit, the result of the user stream callback, if it is called.
+ On entry callbackResult should contain one of { paContinue, paComplete, or
+ paAbort}. If paComplete is passed, the stream callback will not be called
+ but any audio that was generated by previous stream callbacks will be copied
+ to the output buffer(s). You can check whether the buffer processor's internal
+ buffer is empty by calling PaUtil_IsBufferProcessorOutputEmpty.
+
+ If the stream callback is called its result is stored in *callbackResult. If
+ the stream callback returns paComplete or paAbort, all output buffers will be
+ full of valid data - some of which may be zeros to acount for data that
+ wasn't generated by the terminating callback.
+
+ @return The number of frames processed. This usually corresponds to the
+ number of frames specified by the PaUtil_Set*FrameCount functions, exept in
+ the paUtilVariableHostBufferSizePartialUsageAllowed buffer size mode when a
+ smaller value may be returned.
+*/
+unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bufferProcessor,
+        int *callbackResult );
+
+
+/** Determine whether any callback generated output remains in the bufffer
+ processor's internal buffers. This method may be used to determine when to
+ continue calling PaUtil_EndBufferProcessing() after the callback has returned
+ a callbackResult of paComplete.
+
+ @param bufferProcessor The buffer processor.
+ @return Returns non-zero when callback generated output remains in the internal
+ buffer and zero (0) when there internal buffer contains no callback generated
+ data.
+*/
+int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bufferProcessor );
+
+/*@}*/
+
+
+/** @name Buffer processing functions for blocking read/write streams
+*/
+/*@{*/
+
+/** Copy samples from host input channels set up by the PaUtil_Set*InputChannels
+ functions to a user supplied buffer. This function is intended for use with
+ blocking read/write streams. Copies the minimum of the number of
+ user frames (specified by the frameCount parameter) and the number of available
+ host frames (specified in a previous call to SetInputFrameCount()).
+
+ @param bufferProcessor The buffer processor.
+
+ @param buffer A pointer to the user buffer pointer, or a pointer to a pointer
+ to an array of user buffer pointers for a non-interleaved stream. It is
+ important that this parameter points to a copy of the user buffer pointers,
+ not to the actual user buffer pointers, because this function updates the
+ pointers before returning.
+
+ @param frameCount The number of frames of data in the buffer(s) pointed to by
+ the buffer parameter.
+
+ @return The number of frames copied. The buffer pointer(s) pointed to by the
+ buffer parameter are advanced to point to the frame(s) following the last one
+ filled.
+*/
+unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bufferProcessor,
+        void **buffer, unsigned long frameCount );
+
+
+/* Copy samples from a user supplied buffer to host output channels set up by
+ the PaUtil_Set*OutputChannels functions. This function is intended for use with
+ blocking read/write streams. Copies the minimum of the number of
+ user frames (specified by the frameCount parameter) and the number of
+ host frames (specified in a previous call to SetOutputFrameCount()).
+
+ @param bufferProcessor The buffer processor.
+
+ @param buffer A pointer to the user buffer pointer, or a pointer to a pointer
+ to an array of user buffer pointers for a non-interleaved stream. It is
+ important that this parameter points to a copy of the user buffer pointers,
+ not to the actual user buffer pointers, because this function updates the
+ pointers before returning.
+
+ @param frameCount The number of frames of data in the buffer(s) pointed to by
+ the buffer parameter.
+
+ @return The number of frames copied. The buffer pointer(s) pointed to by the
+ buffer parameter are advanced to point to the frame(s) following the last one
+ copied.
+*/
+unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bufferProcessor,
+        const void ** buffer, unsigned long frameCount );
+
+
+/* Zero samples in host output channels set up by the PaUtil_Set*OutputChannels
+ functions. This function is useful for flushing streams.
+ Zeros the minimum of frameCount and the number of host frames specified in a
+ previous call to SetOutputFrameCount().
+
+ @param bufferProcessor The buffer processor.
+
+ @param frameCount The maximum number of frames to zero.
+ @return The number of frames zeroed.
+*/
+unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bufferProcessor,
+        unsigned long frameCount );
+
+
+/*@}*/
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_PROCESS_H */
diff --git a/portaudio/src/common/pa_ringbuffer.c b/portaudio/src/common/pa_ringbuffer.c
new file mode 100644 (file)
index 0000000..93b3e43
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * Ring Buffer utility.
+ *
+ * Author: Phil Burk, http://www.softsynth.com
+ * modified for SMP safety on Mac OS X by Bjorn Roche
+ * modified for SMP safety on Linux by Leland Lucius
+ * also, allowed for const where possible
+ * modified for multiple-byte-sized data elements by Sven Fischer 
+ *
+ * Note that this is safe only for a single-thread reader and a
+ * single-thread writer.
+ *
+ * This program uses the PortAudio Portable Audio Library.
+ * For more information see: http://www.portaudio.com
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup common_src
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include "pa_ringbuffer.h"
+#include <string.h>
+#include "pa_memorybarrier.h"
+
+/***************************************************************************
+ * Initialize FIFO.
+ * elementCount must be power of 2, returns -1 if not.
+ */
+ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr )
+{
+    if( ((elementCount-1) & elementCount) != 0) return -1; /* Not Power of two. */
+    rbuf->bufferSize = elementCount;
+    rbuf->buffer = (char *)dataPtr;
+    PaUtil_FlushRingBuffer( rbuf );
+    rbuf->bigMask = (elementCount*2)-1;
+    rbuf->smallMask = (elementCount)-1;
+    rbuf->elementSizeBytes = elementSizeBytes;
+    return 0;
+}
+
+/***************************************************************************
+** Return number of elements available for reading. */
+ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( const PaUtilRingBuffer *rbuf )
+{
+    return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );
+}
+/***************************************************************************
+** Return number of elements available for writing. */
+ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( const PaUtilRingBuffer *rbuf )
+{
+    return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));
+}
+
+/***************************************************************************
+** Clear buffer. Should only be called when buffer is NOT being read or written. */
+void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )
+{
+    rbuf->writeIndex = rbuf->readIndex = 0;
+}
+
+/***************************************************************************
+** Get address of region(s) to which we can write data.
+** If the region is contiguous, size2 will be zero.
+** If non-contiguous, size2 will be the size of second region.
+** Returns room available to be written or elementCount, whichever is smaller.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
+                                       void **dataPtr1, ring_buffer_size_t *sizePtr1,
+                                       void **dataPtr2, ring_buffer_size_t *sizePtr2 )
+{
+    ring_buffer_size_t   index;
+    ring_buffer_size_t   available = PaUtil_GetRingBufferWriteAvailable( rbuf );
+    if( elementCount > available ) elementCount = available;
+    /* Check to see if write is not contiguous. */
+    index = rbuf->writeIndex & rbuf->smallMask;
+    if( (index + elementCount) > rbuf->bufferSize )
+    {
+        /* Write data in two blocks that wrap the buffer. */
+        ring_buffer_size_t   firstHalf = rbuf->bufferSize - index;
+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        *sizePtr1 = firstHalf;
+        *dataPtr2 = &rbuf->buffer[0];
+        *sizePtr2 = elementCount - firstHalf;
+    }
+    else
+    {
+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        *sizePtr1 = elementCount;
+        *dataPtr2 = NULL;
+        *sizePtr2 = 0;
+    }
+
+    if( available )
+        PaUtil_FullMemoryBarrier(); /* (write-after-read) => full barrier */
+
+    return elementCount;
+}
+
+
+/***************************************************************************
+*/
+ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
+{
+    /* ensure that previous writes are seen before we update the write index 
+       (write after write)
+    */
+    PaUtil_WriteMemoryBarrier();
+    return rbuf->writeIndex = (rbuf->writeIndex + elementCount) & rbuf->bigMask;
+}
+
+/***************************************************************************
+** Get address of region(s) from which we can read data.
+** If the region is contiguous, size2 will be zero.
+** If non-contiguous, size2 will be the size of second region.
+** Returns room available to be read or elementCount, whichever is smaller.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
+                                void **dataPtr1, ring_buffer_size_t *sizePtr1,
+                                void **dataPtr2, ring_buffer_size_t *sizePtr2 )
+{
+    ring_buffer_size_t   index;
+    ring_buffer_size_t   available = PaUtil_GetRingBufferReadAvailable( rbuf ); /* doesn't use memory barrier */
+    if( elementCount > available ) elementCount = available;
+    /* Check to see if read is not contiguous. */
+    index = rbuf->readIndex & rbuf->smallMask;
+    if( (index + elementCount) > rbuf->bufferSize )
+    {
+        /* Write data in two blocks that wrap the buffer. */
+        ring_buffer_size_t firstHalf = rbuf->bufferSize - index;
+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        *sizePtr1 = firstHalf;
+        *dataPtr2 = &rbuf->buffer[0];
+        *sizePtr2 = elementCount - firstHalf;
+    }
+    else
+    {
+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        *sizePtr1 = elementCount;
+        *dataPtr2 = NULL;
+        *sizePtr2 = 0;
+    }
+    
+    if( available )
+        PaUtil_ReadMemoryBarrier(); /* (read-after-read) => read barrier */
+
+    return elementCount;
+}
+/***************************************************************************
+*/
+ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
+{
+    /* ensure that previous reads (copies out of the ring buffer) are always completed before updating (writing) the read index. 
+       (write-after-read) => full barrier
+    */
+    PaUtil_FullMemoryBarrier();
+    return rbuf->readIndex = (rbuf->readIndex + elementCount) & rbuf->bigMask;
+}
+
+/***************************************************************************
+** Return elements written. */
+ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount )
+{
+    ring_buffer_size_t size1, size2, numWritten;
+    void *data1, *data2;
+    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
+    if( size2 > 0 )
+    {
+
+        memcpy( data1, data, size1*rbuf->elementSizeBytes );
+        data = ((char *)data) + size1*rbuf->elementSizeBytes;
+        memcpy( data2, data, size2*rbuf->elementSizeBytes );
+    }
+    else
+    {
+        memcpy( data1, data, size1*rbuf->elementSizeBytes );
+    }
+    PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );
+    return numWritten;
+}
+
+/***************************************************************************
+** Return elements read. */
+ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount )
+{
+    ring_buffer_size_t size1, size2, numRead;
+    void *data1, *data2;
+    numRead = PaUtil_GetRingBufferReadRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
+    if( size2 > 0 )
+    {
+        memcpy( data, data1, size1*rbuf->elementSizeBytes );
+        data = ((char *)data) + size1*rbuf->elementSizeBytes;
+        memcpy( data, data2, size2*rbuf->elementSizeBytes );
+    }
+    else
+    {
+        memcpy( data, data1, size1*rbuf->elementSizeBytes );
+    }
+    PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );
+    return numRead;
+}
diff --git a/portaudio/src/common/pa_ringbuffer.h b/portaudio/src/common/pa_ringbuffer.h
new file mode 100644 (file)
index 0000000..9edba0d
--- /dev/null
@@ -0,0 +1,236 @@
+#ifndef PA_RINGBUFFER_H
+#define PA_RINGBUFFER_H
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * Ring Buffer utility.
+ *
+ * Author: Phil Burk, http://www.softsynth.com
+ * modified for SMP safety on OS X by Bjorn Roche.
+ * also allowed for const where possible.
+ * modified for multiple-byte-sized data elements by Sven Fischer 
+ *
+ * Note that this is safe only for a single-thread reader
+ * and a single-thread writer.
+ *
+ * This program is distributed with the PortAudio Portable Audio Library.
+ * For more information see: http://www.portaudio.com
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+ @brief Single-reader single-writer lock-free ring buffer
+
+ PaUtilRingBuffer is a ring buffer used to transport samples between
+ different execution contexts (threads, OS callbacks, interrupt handlers)
+ without requiring the use of any locks. This only works when there is
+ a single reader and a single writer (ie. one thread or callback writes
+ to the ring buffer, another thread or callback reads from it).
+
+ The PaUtilRingBuffer structure manages a ring buffer containing N 
+ elements, where N must be a power of two. An element may be any size 
+ (specified in bytes).
+
+ The memory area used to store the buffer elements must be allocated by 
+ the client prior to calling PaUtil_InitializeRingBuffer() and must outlive
+ the use of the ring buffer.
+ @note The ring buffer functions are not normally exposed in the PortAudio libraries. 
+ If you want to call them then you will need to add pa_ringbuffer.c to your application source code.
+*/
+
+#if defined(__APPLE__)
+#include <sys/types.h>
+typedef int32_t ring_buffer_size_t;
+#elif defined( __GNUC__ )
+typedef long ring_buffer_size_t;
+#elif (_MSC_VER >= 1400)
+typedef long ring_buffer_size_t;
+#elif defined(_MSC_VER) || defined(__BORLANDC__)
+typedef long ring_buffer_size_t;
+#else
+typedef long ring_buffer_size_t;
+#endif
+
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+typedef struct PaUtilRingBuffer
+{
+    ring_buffer_size_t  bufferSize; /**< Number of elements in FIFO. Power of 2. Set by PaUtil_InitRingBuffer. */
+    volatile ring_buffer_size_t  writeIndex; /**< Index of next writable element. Set by PaUtil_AdvanceRingBufferWriteIndex. */
+    volatile ring_buffer_size_t  readIndex;  /**< Index of next readable element. Set by PaUtil_AdvanceRingBufferReadIndex. */
+    ring_buffer_size_t  bigMask;    /**< Used for wrapping indices with extra bit to distinguish full/empty. */
+    ring_buffer_size_t  smallMask;  /**< Used for fitting indices to buffer. */
+    ring_buffer_size_t  elementSizeBytes; /**< Number of bytes per element. */
+    char  *buffer;    /**< Pointer to the buffer containing the actual data. */
+}PaUtilRingBuffer;
+
+/** Initialize Ring Buffer to empty state ready to have elements written to it.
+
+ @param rbuf The ring buffer.
+
+ @param elementSizeBytes The size of a single data element in bytes.
+
+ @param elementCount The number of elements in the buffer (must be a power of 2).
+
+ @param dataPtr A pointer to a previously allocated area where the data
+ will be maintained.  It must be elementCount*elementSizeBytes long.
+
+ @return -1 if elementCount is not a power of 2, otherwise 0.
+*/
+ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr );
+
+/** Reset buffer to empty. Should only be called when buffer is NOT being read or written.
+
+ @param rbuf The ring buffer.
+*/
+void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf );
+
+/** Retrieve the number of elements available in the ring buffer for writing.
+
+ @param rbuf The ring buffer.
+
+ @return The number of elements available for writing.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( const PaUtilRingBuffer *rbuf );
+
+/** Retrieve the number of elements available in the ring buffer for reading.
+
+ @param rbuf The ring buffer.
+
+ @return The number of elements available for reading.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( const PaUtilRingBuffer *rbuf );
+
+/** Write data to the ring buffer.
+
+ @param rbuf The ring buffer.
+
+ @param data The address of new data to write to the buffer.
+
+ @param elementCount The number of elements to be written.
+
+ @return The number of elements written.
+*/
+ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount );
+
+/** Read data from the ring buffer.
+
+ @param rbuf The ring buffer.
+
+ @param data The address where the data should be stored.
+
+ @param elementCount The number of elements to be read.
+
+ @return The number of elements read.
+*/
+ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount );
+
+/** Get address of region(s) to which we can write data.
+
+ @param rbuf The ring buffer.
+
+ @param elementCount The number of elements desired.
+
+ @param dataPtr1 The address where the first (or only) region pointer will be
+ stored.
+
+ @param sizePtr1 The address where the first (or only) region length will be
+ stored.
+
+ @param dataPtr2 The address where the second region pointer will be stored if
+ the first region is too small to satisfy elementCount.
+
+ @param sizePtr2 The address where the second region length will be stored if
+ the first region is too small to satisfy elementCount.
+
+ @return The room available to be written or elementCount, whichever is smaller.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
+                                       void **dataPtr1, ring_buffer_size_t *sizePtr1,
+                                       void **dataPtr2, ring_buffer_size_t *sizePtr2 );
+
+/** Advance the write index to the next location to be written.
+
+ @param rbuf The ring buffer.
+
+ @param elementCount The number of elements to advance.
+
+ @return The new position.
+*/
+ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
+
+/** Get address of region(s) from which we can read data.
+
+ @param rbuf The ring buffer.
+
+ @param elementCount The number of elements desired.
+
+ @param dataPtr1 The address where the first (or only) region pointer will be
+ stored.
+
+ @param sizePtr1 The address where the first (or only) region length will be
+ stored.
+
+ @param dataPtr2 The address where the second region pointer will be stored if
+ the first region is too small to satisfy elementCount.
+
+ @param sizePtr2 The address where the second region length will be stored if
+ the first region is too small to satisfy elementCount.
+
+ @return The number of elements available for reading.
+*/
+ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
+                                      void **dataPtr1, ring_buffer_size_t *sizePtr1,
+                                      void **dataPtr2, ring_buffer_size_t *sizePtr2 );
+
+/** Advance the read index to the next location to be read.
+
+ @param rbuf The ring buffer.
+
+ @param elementCount The number of elements to advance.
+
+ @return The new position.
+*/
+ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_RINGBUFFER_H */
diff --git a/portaudio/src/common/pa_stream.c b/portaudio/src/common/pa_stream.c
new file mode 100644 (file)
index 0000000..03a0ee6
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * stream interface
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 2008 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Stream interfaces, representation structures and helper functions
+ used to interface between pa_front.c host API implementations.
+*/
+
+
+#include "pa_stream.h"
+
+
+void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,
+                                       PaError (*Close)( PaStream* ),
+                                       PaError (*Start)( PaStream* ),
+                                       PaError (*Stop)( PaStream* ),
+                                       PaError (*Abort)( PaStream* ),
+                                       PaError (*IsStopped)( PaStream* ),
+                                       PaError (*IsActive)( PaStream* ),
+                                       PaTime (*GetTime)( PaStream* ),
+                                       double (*GetCpuLoad)( PaStream* ),
+                                       PaError (*Read)( PaStream*, void *, unsigned long ),
+                                       PaError (*Write)( PaStream*, const void *, unsigned long ),
+                                       signed long (*GetReadAvailable)( PaStream* ),
+                                       signed long (*GetWriteAvailable)( PaStream* )  )
+{
+    streamInterface->Close = Close;
+    streamInterface->Start = Start;
+    streamInterface->Stop = Stop;
+    streamInterface->Abort = Abort;
+    streamInterface->IsStopped = IsStopped;
+    streamInterface->IsActive = IsActive;
+    streamInterface->GetTime = GetTime;
+    streamInterface->GetCpuLoad = GetCpuLoad;
+    streamInterface->Read = Read;
+    streamInterface->Write = Write;
+    streamInterface->GetReadAvailable = GetReadAvailable;
+    streamInterface->GetWriteAvailable = GetWriteAvailable;
+}
+
+
+void PaUtil_InitializeStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation,
+        PaUtilStreamInterface *streamInterface,
+        PaStreamCallback *streamCallback,
+        void *userData )
+{
+    streamRepresentation->magic = PA_STREAM_MAGIC;
+    streamRepresentation->nextOpenStream = 0;
+    streamRepresentation->streamInterface = streamInterface;
+    streamRepresentation->streamCallback = streamCallback;
+    streamRepresentation->streamFinishedCallback = 0;
+
+    streamRepresentation->userData = userData;
+
+    streamRepresentation->streamInfo.inputLatency = 0.;
+    streamRepresentation->streamInfo.outputLatency = 0.;
+    streamRepresentation->streamInfo.sampleRate = 0.;
+}
+
+
+void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation )
+{
+    streamRepresentation->magic = 0;
+}
+
+
+PaError PaUtil_DummyRead( PaStream* stream,
+                               void *buffer,
+                               unsigned long frames )
+{
+    (void)stream; /* unused parameter */
+    (void)buffer; /* unused parameter */
+    (void)frames; /* unused parameter */
+
+    return paCanNotReadFromACallbackStream;
+}
+
+
+PaError PaUtil_DummyWrite( PaStream* stream,
+                               const void *buffer,
+                               unsigned long frames )
+{
+    (void)stream; /* unused parameter */
+    (void)buffer; /* unused parameter */
+    (void)frames; /* unused parameter */
+
+    return paCanNotWriteToACallbackStream;
+}
+
+
+signed long PaUtil_DummyGetReadAvailable( PaStream* stream )
+{
+    (void)stream; /* unused parameter */
+
+    return paCanNotReadFromACallbackStream;
+}
+
+
+signed long PaUtil_DummyGetWriteAvailable( PaStream* stream )
+{
+    (void)stream; /* unused parameter */
+
+    return paCanNotWriteToACallbackStream;
+}
+
+
+double PaUtil_DummyGetCpuLoad( PaStream* stream )
+{
+    (void)stream; /* unused parameter */
+
+    return 0.0;
+}
diff --git a/portaudio/src/common/pa_stream.h b/portaudio/src/common/pa_stream.h
new file mode 100644 (file)
index 0000000..678e2ad
--- /dev/null
@@ -0,0 +1,205 @@
+#ifndef PA_STREAM_H
+#define PA_STREAM_H
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * stream interface
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Stream interfaces, representation structures and helper functions
+ used to interface between pa_front.c host API implementations.
+*/
+
+
+#include "portaudio.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+#define PA_STREAM_MAGIC (0x18273645)
+
+
+/** A structure representing an (abstract) interface to a host API. Contains
+ pointers to functions which implement the interface.
+
+ All PaStreamInterface functions are guaranteed to be called with a non-null,
+ valid stream parameter.
+*/
+typedef struct {
+    PaError (*Close)( PaStream* stream );
+    PaError (*Start)( PaStream *stream );
+    PaError (*Stop)( PaStream *stream );
+    PaError (*Abort)( PaStream *stream );
+    PaError (*IsStopped)( PaStream *stream );
+    PaError (*IsActive)( PaStream *stream );
+    PaTime (*GetTime)( PaStream *stream );
+    double (*GetCpuLoad)( PaStream* stream );
+    PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames );
+    PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames );
+    signed long (*GetReadAvailable)( PaStream* stream );
+    signed long (*GetWriteAvailable)( PaStream* stream );
+} PaUtilStreamInterface;
+
+
+/** Initialize the fields of a PaUtilStreamInterface structure.
+*/
+void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,
+    PaError (*Close)( PaStream* ),
+    PaError (*Start)( PaStream* ),
+    PaError (*Stop)( PaStream* ),
+    PaError (*Abort)( PaStream* ),
+    PaError (*IsStopped)( PaStream* ),
+    PaError (*IsActive)( PaStream* ),
+    PaTime (*GetTime)( PaStream* ),
+    double (*GetCpuLoad)( PaStream* ),
+    PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames ),
+    PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames ),
+    signed long (*GetReadAvailable)( PaStream* stream ),
+    signed long (*GetWriteAvailable)( PaStream* stream ) );
+
+
+/** Dummy Read function for use in interfaces to a callback based streams.
+ Pass to the Read parameter of PaUtil_InitializeStreamInterface.
+ @return An error code indicating that the function has no effect
+ because the stream is a callback stream.
+*/
+PaError PaUtil_DummyRead( PaStream* stream,
+                       void *buffer,
+                       unsigned long frames );
+
+
+/** Dummy Write function for use in an interfaces to callback based streams.
+ Pass to the Write parameter of PaUtil_InitializeStreamInterface.
+ @return An error code indicating that the function has no effect
+ because the stream is a callback stream.
+*/
+PaError PaUtil_DummyWrite( PaStream* stream,
+                       const void *buffer,
+                       unsigned long frames );
+
+
+/** Dummy GetReadAvailable function for use in interfaces to callback based
+ streams. Pass to the GetReadAvailable parameter of PaUtil_InitializeStreamInterface.
+ @return An error code indicating that the function has no effect
+ because the stream is a callback stream.
+*/
+signed long PaUtil_DummyGetReadAvailable( PaStream* stream );
+
+
+/** Dummy GetWriteAvailable function for use in interfaces to callback based
+ streams. Pass to the GetWriteAvailable parameter of PaUtil_InitializeStreamInterface.
+ @return An error code indicating that the function has no effect
+ because the stream is a callback stream.
+*/
+signed long PaUtil_DummyGetWriteAvailable( PaStream* stream );
+
+
+
+/** Dummy GetCpuLoad function for use in an interface to a read/write stream.
+ Pass to the GetCpuLoad parameter of PaUtil_InitializeStreamInterface.
+ @return Returns 0.
+*/
+double PaUtil_DummyGetCpuLoad( PaStream* stream );
+
+
+/** Non host specific data for a stream. This data is used by pa_front to
+ forward to the appropriate functions in the streamInterface structure.
+*/
+typedef struct PaUtilStreamRepresentation {
+    unsigned long magic;    /**< set to PA_STREAM_MAGIC */
+    struct PaUtilStreamRepresentation *nextOpenStream; /**< field used by multi-api code */
+    PaUtilStreamInterface *streamInterface;
+    PaStreamCallback *streamCallback;
+    PaStreamFinishedCallback *streamFinishedCallback;
+    void *userData;
+    PaStreamInfo streamInfo;
+} PaUtilStreamRepresentation;
+
+
+/** Initialize a PaUtilStreamRepresentation structure.
+
+ @see PaUtil_InitializeStreamRepresentation
+*/
+void PaUtil_InitializeStreamRepresentation(
+        PaUtilStreamRepresentation *streamRepresentation,
+        PaUtilStreamInterface *streamInterface,
+        PaStreamCallback *streamCallback,
+        void *userData );
+        
+
+/** Clean up a PaUtilStreamRepresentation structure previously initialized
+ by a call to PaUtil_InitializeStreamRepresentation.
+
+ @see PaUtil_InitializeStreamRepresentation
+*/
+void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation );
+
+
+/** Check that the stream pointer is valid.
+
+ @return Returns paNoError if the stream pointer appears to be OK, otherwise
+ returns an error indicating the cause of failure.
+*/
+PaError PaUtil_ValidateStreamPointer( PaStream *stream );
+
+
+/** Cast an opaque stream pointer into a pointer to a PaUtilStreamRepresentation.
+
+ @see PaUtilStreamRepresentation
+*/
+#define PA_STREAM_REP( stream )\
+    ((PaUtilStreamRepresentation*) (stream) )
+
+
+/** Cast an opaque stream pointer into a pointer to a PaUtilStreamInterface.
+
+ @see PaUtilStreamRepresentation, PaUtilStreamInterface
+*/
+#define PA_STREAM_INTERFACE( stream )\
+    PA_STREAM_REP( (stream) )->streamInterface
+
+
+    
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_STREAM_H */
diff --git a/portaudio/src/common/pa_trace.c b/portaudio/src/common/pa_trace.c
new file mode 100644 (file)
index 0000000..818abff
--- /dev/null
@@ -0,0 +1,238 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library Trace Facility
+ * Store trace information in real-time for later printing.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Real-time safe event trace logging facility for debugging.
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <assert.h>
+#include "pa_trace.h"
+#include "pa_util.h"
+#include "pa_debugprint.h"
+
+#if PA_TRACE_REALTIME_EVENTS
+
+static char const *traceTextArray[PA_MAX_TRACE_RECORDS];
+static int traceIntArray[PA_MAX_TRACE_RECORDS];
+static int traceIndex = 0;
+static int traceBlock = 0;
+
+/*********************************************************************/
+void PaUtil_ResetTraceMessages()
+{
+    traceIndex = 0;
+}
+
+/*********************************************************************/
+void PaUtil_DumpTraceMessages()
+{
+    int i;
+    int messageCount = (traceIndex < PA_MAX_TRACE_RECORDS) ? traceIndex : PA_MAX_TRACE_RECORDS;
+
+    printf("DumpTraceMessages: traceIndex = %d\n", traceIndex );
+    for( i=0; i<messageCount; i++ )
+    {
+        printf("%3d: %s = 0x%08X\n",
+               i, traceTextArray[i], traceIntArray[i] );
+    }
+    PaUtil_ResetTraceMessages();
+    fflush(stdout);
+}
+
+/*********************************************************************/
+void PaUtil_AddTraceMessage( const char *msg, int data )
+{
+    if( (traceIndex == PA_MAX_TRACE_RECORDS) && (traceBlock == 0) )
+    {
+        traceBlock = 1;
+        /*  PaUtil_DumpTraceMessages(); */
+    }
+    else if( traceIndex < PA_MAX_TRACE_RECORDS )
+    {
+        traceTextArray[traceIndex] = msg;
+        traceIntArray[traceIndex] = data;
+        traceIndex++;
+    }
+}
+
+/************************************************************************/
+/* High performance log alternative                                     */
+/************************************************************************/
+
+typedef unsigned long long  PaUint64;
+
+typedef struct __PaHighPerformanceLog
+{
+    unsigned    magik;
+    int         writePtr;
+    int         readPtr;
+    int         size;
+    double      refTime;
+    char*       data;
+} PaHighPerformanceLog;
+
+static const unsigned kMagik = 0xcafebabe;
+
+#define USEC_PER_SEC    (1000000ULL)
+
+int PaUtil_InitializeHighSpeedLog( LogHandle* phLog, unsigned maxSizeInBytes )
+{
+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)PaUtil_AllocateMemory(sizeof(PaHighPerformanceLog));
+    if (pLog == 0)
+    {
+        return paInsufficientMemory;
+    }
+    assert(phLog != 0);
+    *phLog = pLog;
+
+    pLog->data = (char*)PaUtil_AllocateMemory(maxSizeInBytes);
+    if (pLog->data == 0)
+    {
+        PaUtil_FreeMemory(pLog);
+        return paInsufficientMemory;
+    }
+    pLog->magik = kMagik;
+    pLog->size = maxSizeInBytes;
+    pLog->refTime = PaUtil_GetTime();
+    return paNoError;
+}
+
+void PaUtil_ResetHighSpeedLogTimeRef( LogHandle hLog )
+{
+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
+    assert(pLog->magik == kMagik);
+    pLog->refTime = PaUtil_GetTime();
+}
+
+typedef struct __PaLogEntryHeader
+{
+    int    size;
+    double timeStamp;
+} PaLogEntryHeader;
+
+#ifdef __APPLE__
+#define _vsnprintf vsnprintf
+#define min(a,b) ((a)<(b)?(a):(b))
+#endif
+
+
+int PaUtil_AddHighSpeedLogMessage( LogHandle hLog, const char* fmt, ... )
+{
+    va_list l;
+    int n = 0;
+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
+    if (pLog != 0)
+    {
+        PaLogEntryHeader* pHeader;
+        char* p;
+        int maxN;
+        assert(pLog->magik == kMagik);
+        pHeader = (PaLogEntryHeader*)( pLog->data + pLog->writePtr );
+        p = (char*)( pHeader + 1 );
+        maxN = pLog->size - pLog->writePtr - 2 * sizeof(PaLogEntryHeader);
+
+        pHeader->timeStamp = PaUtil_GetTime() - pLog->refTime;
+        if (maxN > 0)
+        {
+            if (maxN > 32)
+            {
+                va_start(l, fmt);
+                n = _vsnprintf(p, min(1024, maxN), fmt, l);
+                va_end(l);
+            }
+            else {
+                n = sprintf(p, "End of log...");
+            }
+            n = ((n + sizeof(unsigned)) & ~(sizeof(unsigned)-1)) + sizeof(PaLogEntryHeader);
+            pHeader->size = n;
+#if 0
+            PaUtil_DebugPrint("%05u.%03u: %s\n", pHeader->timeStamp/1000, pHeader->timeStamp%1000, p);
+#endif
+            pLog->writePtr += n;
+        }
+    }
+    return n;
+}
+
+void PaUtil_DumpHighSpeedLog( LogHandle hLog, const char* fileName )
+{
+    FILE* f = (fileName != NULL) ? fopen(fileName, "w") : stdout;
+    unsigned localWritePtr;
+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
+    assert(pLog->magik == kMagik);
+    localWritePtr = pLog->writePtr;
+    while (pLog->readPtr != localWritePtr)
+    {
+        const PaLogEntryHeader* pHeader = (const PaLogEntryHeader*)( pLog->data + pLog->readPtr );
+        const char* p = (const char*)( pHeader + 1 );
+        const PaUint64 ts = (const PaUint64)( pHeader->timeStamp * USEC_PER_SEC );
+        assert(pHeader->size < (1024+sizeof(unsigned)+sizeof(PaLogEntryHeader)));
+        fprintf(f, "%05u.%03u: %s\n", (unsigned)(ts/1000), (unsigned)(ts%1000), p);
+        pLog->readPtr += pHeader->size;
+    }
+    if (f != stdout)
+    {
+        fclose(f);
+    }
+}
+
+void PaUtil_DiscardHighSpeedLog( LogHandle hLog )
+{
+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
+    assert(pLog->magik == kMagik);
+    PaUtil_FreeMemory(pLog->data);
+    PaUtil_FreeMemory(pLog);
+}
+
+#else
+/* This stub was added so that this file will generate a symbol.
+ * Otherwise linker/archiver programs will complain.
+ */
+int PaUtil_TraceStubToSatisfyLinker(void)
+{
+       return 0;
+}
+#endif /* TRACE_REALTIME_EVENTS */
diff --git a/portaudio/src/common/pa_trace.h b/portaudio/src/common/pa_trace.h
new file mode 100644 (file)
index 0000000..6dfaeb7
--- /dev/null
@@ -0,0 +1,117 @@
+#ifndef PA_TRACE_H
+#define PA_TRACE_H
+/*
+ * $Id$
+ * Portable Audio I/O Library Trace Facility
+ * Store trace information in real-time for later printing.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Real-time safe event trace logging facility for debugging.
+
+ Allows data to be logged to a fixed size trace buffer in a real-time
+ execution context (such as at interrupt time). Each log entry consists 
+ of a message comprising a string pointer and an int.  The trace buffer 
+ may be dumped to stdout later.
+
+ This facility is only active if PA_TRACE_REALTIME_EVENTS is set to 1,
+ otherwise the trace functions expand to no-ops.
+
+ @fn PaUtil_ResetTraceMessages
+ @brief Clear the trace buffer.
+
+ @fn PaUtil_AddTraceMessage
+ @brief Add a message to the trace buffer. A message consists of string and an int.
+ @param msg The string pointer must remain valid until PaUtil_DumpTraceMessages 
+    is called. As a result, usually only string literals should be passed as 
+    the msg parameter.
+
+ @fn PaUtil_DumpTraceMessages
+ @brief Print all messages in the trace buffer to stdout and clear the trace buffer.
+*/
+
+#ifndef PA_TRACE_REALTIME_EVENTS
+#define PA_TRACE_REALTIME_EVENTS     (0)   /**< Set to 1 to enable logging using the trace functions defined below */
+#endif
+
+#ifndef PA_MAX_TRACE_RECORDS
+#define PA_MAX_TRACE_RECORDS      (2048)   /**< Maximum number of records stored in trace buffer */   
+#endif
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+#if PA_TRACE_REALTIME_EVENTS
+
+void PaUtil_ResetTraceMessages();
+void PaUtil_AddTraceMessage( const char *msg, int data );
+void PaUtil_DumpTraceMessages();
+
+/* Alternative interface */
+
+typedef void* LogHandle;
+
+int PaUtil_InitializeHighSpeedLog(LogHandle* phLog, unsigned maxSizeInBytes);
+void PaUtil_ResetHighSpeedLogTimeRef(LogHandle hLog);
+int PaUtil_AddHighSpeedLogMessage(LogHandle hLog, const char* fmt, ...);
+void PaUtil_DumpHighSpeedLog(LogHandle hLog, const char* fileName);
+void PaUtil_DiscardHighSpeedLog(LogHandle hLog);
+
+#else
+
+#define PaUtil_ResetTraceMessages() /* noop */
+#define PaUtil_AddTraceMessage(msg,data) /* noop */
+#define PaUtil_DumpTraceMessages() /* noop */
+
+#define PaUtil_InitializeHighSpeedLog(phLog, maxSizeInBytes)  (0)
+#define PaUtil_ResetHighSpeedLogTimeRef(hLog)
+#define PaUtil_AddHighSpeedLogMessage(...)   (0)
+#define PaUtil_DumpHighSpeedLog(hLog, fileName)
+#define PaUtil_DiscardHighSpeedLog(hLog)
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* PA_TRACE_H */
diff --git a/portaudio/src/common/pa_types.h b/portaudio/src/common/pa_types.h
new file mode 100644 (file)
index 0000000..5b647d6
--- /dev/null
@@ -0,0 +1,107 @@
+#ifndef PA_TYPES_H
+#define PA_TYPES_H
+
+/* 
+ * Portable Audio I/O Library
+ * integer type definitions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Definition of 16 and 32 bit integer types (PaInt16, PaInt32 etc)
+
+ SIZEOF_SHORT, SIZEOF_INT and SIZEOF_LONG are set by the configure script
+ when it is used. Otherwise we default to the common 32 bit values, if your
+ platform doesn't use configure, and doesn't use the default values below
+ you will need to explicitly define these symbols in your make file.
+
+ A PA_VALIDATE_SIZES macro is provided to assert that the values set in this
+ file are correct.
+*/
+
+#ifndef SIZEOF_SHORT
+#define SIZEOF_SHORT 2
+#endif
+
+#ifndef SIZEOF_INT
+#define SIZEOF_INT 4
+#endif
+
+#ifndef SIZEOF_LONG
+#define SIZEOF_LONG 4
+#endif
+
+
+#if SIZEOF_SHORT == 2
+typedef signed short PaInt16;
+typedef unsigned short PaUint16;
+#elif SIZEOF_INT == 2
+typedef signed int PaInt16;
+typedef unsigned int PaUint16;
+#else
+#error pa_types.h was unable to determine which type to use for 16bit integers on the target platform
+#endif
+
+#if SIZEOF_SHORT == 4
+typedef signed short PaInt32;
+typedef unsigned short PaUint32;
+#elif SIZEOF_INT == 4
+typedef signed int PaInt32;
+typedef unsigned int PaUint32;
+#elif SIZEOF_LONG == 4
+typedef signed long PaInt32;
+typedef unsigned long PaUint32;
+#else
+#error pa_types.h was unable to determine which type to use for 32bit integers on the target platform
+#endif
+
+
+/* PA_VALIDATE_TYPE_SIZES compares the size of the integer types at runtime to
+ ensure that PortAudio was configured correctly, and raises an assertion if
+ they don't match the expected values. <assert.h> must be included in the
+ context in which this macro is used.
+*/
+#define PA_VALIDATE_TYPE_SIZES \
+    { \
+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint16 ) == 2 ); \
+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt16 ) == 2 ); \
+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint32 ) == 4 ); \
+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt32 ) == 4 ); \
+    }
+
+
+#endif /* PA_TYPES_H */
diff --git a/portaudio/src/common/pa_util.h b/portaudio/src/common/pa_util.h
new file mode 100644 (file)
index 0000000..ad5dac5
--- /dev/null
@@ -0,0 +1,159 @@
+#ifndef PA_UTIL_H
+#define PA_UTIL_H
+/*
+ * $Id$
+ * Portable Audio I/O Library implementation utilities header
+ * common implementation utilities and interfaces
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+    @brief Prototypes for utility functions used by PortAudio implementations.
+
+    Some functions declared here are defined in pa_front.c while others
+    are implemented separately for each platform.
+*/
+
+
+#include "portaudio.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+struct PaUtilHostApiRepresentation;
+
+
+/** Retrieve a specific host API representation. This function can be used
+ by implementations to retrieve a pointer to their representation in
+ host api specific extension functions which aren't passed a rep pointer
+ by pa_front.c.
+
+ @param hostApi A pointer to a host API represenation pointer. Apon success
+ this will receive the requested representation pointer.
+
+ @param type A valid host API type identifier.
+
+ @returns An error code. If the result is PaNoError then a pointer to the
+ requested host API representation will be stored in *hostApi. If the host API
+ specified by type is not found, this function returns paHostApiNotFound.
+*/
+PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,
+        PaHostApiTypeId type );
+
+
+/** Convert a PortAudio device index into a host API specific device index.
+ @param hostApiDevice Pointer to a device index, on success this will recieve the
+ converted device index value.
+ @param device The PortAudio device index to convert.
+ @param hostApi The host api which the index should be converted for.
+
+ @returns On success returns PaNoError and places the converted index in the
+ hostApiDevice parameter.
+*/
+PaError PaUtil_DeviceIndexToHostApiDeviceIndex(
+        PaDeviceIndex *hostApiDevice, PaDeviceIndex device,
+        struct PaUtilHostApiRepresentation *hostApi );
+
+
+/** Set the host error information returned by Pa_GetLastHostErrorInfo. This
+ function and the paUnanticipatedHostError error code should be used as a
+ last resort.  Implementors should use existing PA error codes where possible,
+ or nominate new ones. Note that at it is always better to use
+ PaUtil_SetLastHostErrorInfo() and paUnanticipatedHostError than to return an
+ ambiguous or inaccurate PaError code.
+
+ @param hostApiType  The host API which encountered the error (ie of the caller)
+
+ @param errorCode The error code returned by the native API function.
+
+ @param errorText A string describing the error. PaUtil_SetLastHostErrorInfo
+ makes a copy of the string, so it is not necessary for the pointer to remain
+ valid after the call to PaUtil_SetLastHostErrorInfo() returns.
+
+*/
+void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,
+        const char *errorText );
+
+
+        
+/* the following functions are implemented in a platform platform specific
+ .c file
+*/
+
+/** Allocate size bytes, guaranteed to be aligned to a FIXME byte boundary */
+void *PaUtil_AllocateMemory( long size );
+
+
+/** Realease block if non-NULL. block may be NULL */
+void PaUtil_FreeMemory( void *block );
+
+
+/** Return the number of currently allocated blocks. This function can be
+ used for detecting memory leaks.
+
+ @note Allocations will only be tracked if PA_TRACK_MEMORY is #defined. If
+ it isn't, this function will always return 0.
+*/
+int PaUtil_CountCurrentlyAllocatedBlocks( void );
+
+
+/** Initialize the clock used by PaUtil_GetTime(). Call this before calling
+ PaUtil_GetTime.
+
+ @see PaUtil_GetTime
+*/
+void PaUtil_InitializeClock( void );
+
+
+/** Return the system time in seconds. Used to implement CPU load functions
+
+ @see PaUtil_InitializeClock
+*/
+double PaUtil_GetTime( void );
+
+
+/* void Pa_Sleep( long msec );  must also be implemented in per-platform .c file */
+
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_UTIL_H */
diff --git a/portaudio/src/hostapi/alsa/pa_linux_alsa.c b/portaudio/src/hostapi/alsa/pa_linux_alsa.c
new file mode 100644 (file)
index 0000000..584cde8
--- /dev/null
@@ -0,0 +1,4639 @@
+/*
+ * $Id$
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * ALSA implementation by Joshua Haberman and Arve Knudsen
+ *
+ * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
+ * Copyright (c) 2005-2009 Arve Knudsen <arve.knudsen@gmail.com>
+ * Copyright (c) 2008 Kevin Kofler <kevin.kofler@chello.at>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#define ALSA_PCM_NEW_HW_PARAMS_API
+#define ALSA_PCM_NEW_SW_PARAMS_API
+#include <alsa/asoundlib.h>
+#undef ALSA_PCM_NEW_HW_PARAMS_API
+#undef ALSA_PCM_NEW_SW_PARAMS_API
+
+#include <sys/poll.h>
+#include <string.h> /* strlen() */
+#include <limits.h>
+#include <math.h>
+#include <pthread.h>
+#include <signal.h>
+#include <time.h>
+#include <sys/mman.h>
+#include <signal.h> /* For sig_atomic_t */
+#ifdef PA_ALSA_DYNAMIC
+    #include <dlfcn.h> /* For dlXXX functions */
+#endif
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_unix_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_endianness.h"
+#include "pa_debugprint.h"
+
+#include "pa_linux_alsa.h"
+
+/* Add missing define (for compatibility with older ALSA versions) */
+#ifndef SND_PCM_TSTAMP_ENABLE
+    #define SND_PCM_TSTAMP_ENABLE SND_PCM_TSTAMP_MMAP
+#endif
+
+/* Combine version elements into a single (unsigned) integer */
+#define ALSA_VERSION_INT(major, minor, subminor)  ((major << 16) | (minor << 8) | subminor)
+
+/* The acceptable tolerance of sample rate set, to that requested (as a ratio, eg 50 is 2%, 100 is 1%) */
+#define RATE_MAX_DEVIATE_RATIO 100
+
+/* Defines Alsa function types and pointers to these functions. */
+#define _PA_DEFINE_FUNC(x)  typedef typeof(x) x##_ft; static x##_ft *alsa_##x = 0
+
+/* Alloca helper. */
+#define __alsa_snd_alloca(ptr,type) do { size_t __alsa_alloca_size = alsa_##type##_sizeof(); (*ptr) = (type##_t *) alloca(__alsa_alloca_size); memset(*ptr, 0, __alsa_alloca_size); } while (0)
+
+_PA_DEFINE_FUNC(snd_pcm_open);
+_PA_DEFINE_FUNC(snd_pcm_close);
+_PA_DEFINE_FUNC(snd_pcm_nonblock);
+_PA_DEFINE_FUNC(snd_pcm_frames_to_bytes);
+_PA_DEFINE_FUNC(snd_pcm_prepare);
+_PA_DEFINE_FUNC(snd_pcm_start);
+_PA_DEFINE_FUNC(snd_pcm_resume);
+_PA_DEFINE_FUNC(snd_pcm_wait);
+_PA_DEFINE_FUNC(snd_pcm_state);
+_PA_DEFINE_FUNC(snd_pcm_avail_update);
+_PA_DEFINE_FUNC(snd_pcm_areas_silence);
+_PA_DEFINE_FUNC(snd_pcm_mmap_begin);
+_PA_DEFINE_FUNC(snd_pcm_mmap_commit);
+_PA_DEFINE_FUNC(snd_pcm_readi);
+_PA_DEFINE_FUNC(snd_pcm_readn);
+_PA_DEFINE_FUNC(snd_pcm_writei);
+_PA_DEFINE_FUNC(snd_pcm_writen);
+_PA_DEFINE_FUNC(snd_pcm_drain);
+_PA_DEFINE_FUNC(snd_pcm_recover);
+_PA_DEFINE_FUNC(snd_pcm_drop);
+_PA_DEFINE_FUNC(snd_pcm_area_copy);
+_PA_DEFINE_FUNC(snd_pcm_poll_descriptors);
+_PA_DEFINE_FUNC(snd_pcm_poll_descriptors_count);
+_PA_DEFINE_FUNC(snd_pcm_poll_descriptors_revents);
+_PA_DEFINE_FUNC(snd_pcm_format_size);
+_PA_DEFINE_FUNC(snd_pcm_link);
+_PA_DEFINE_FUNC(snd_pcm_delay);
+
+_PA_DEFINE_FUNC(snd_pcm_hw_params_sizeof);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_malloc);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_free);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_any);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_access);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_format);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_channels);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_set_periods_near);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_rate_near); //!!!
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_rate);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_rate_resample);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_set_buffer_time_near);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_buffer_size);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_buffer_size_near); //!!!
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_buffer_size_min);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_set_period_time_near);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_period_size_near);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_periods_integer);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_periods_min);
+
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_buffer_size);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_get_period_size);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_get_access);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_get_periods);
+//_PA_DEFINE_FUNC(snd_pcm_hw_params_get_rate);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_channels_min);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_channels_max);
+
+_PA_DEFINE_FUNC(snd_pcm_hw_params_test_period_size);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_test_format);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_test_access);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_dump);
+_PA_DEFINE_FUNC(snd_pcm_hw_params);
+
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_periods_min);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_periods_max);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_set_period_size);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_period_size_min);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_period_size_max);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_buffer_size_max);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_rate_min);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_rate_max);
+_PA_DEFINE_FUNC(snd_pcm_hw_params_get_rate_numden);
+#define alsa_snd_pcm_hw_params_alloca(ptr) __alsa_snd_alloca(ptr, snd_pcm_hw_params)
+
+_PA_DEFINE_FUNC(snd_pcm_sw_params_sizeof);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_malloc);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_current);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_avail_min);
+_PA_DEFINE_FUNC(snd_pcm_sw_params);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_free);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_start_threshold);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_stop_threshold);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_get_boundary);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_silence_threshold);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_silence_size);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_xfer_align);
+_PA_DEFINE_FUNC(snd_pcm_sw_params_set_tstamp_mode);
+#define alsa_snd_pcm_sw_params_alloca(ptr) __alsa_snd_alloca(ptr, snd_pcm_sw_params)
+
+_PA_DEFINE_FUNC(snd_pcm_info);
+_PA_DEFINE_FUNC(snd_pcm_info_sizeof);
+_PA_DEFINE_FUNC(snd_pcm_info_malloc);
+_PA_DEFINE_FUNC(snd_pcm_info_free);
+_PA_DEFINE_FUNC(snd_pcm_info_set_device);
+_PA_DEFINE_FUNC(snd_pcm_info_set_subdevice);
+_PA_DEFINE_FUNC(snd_pcm_info_set_stream);
+_PA_DEFINE_FUNC(snd_pcm_info_get_name);
+_PA_DEFINE_FUNC(snd_pcm_info_get_card);
+#define alsa_snd_pcm_info_alloca(ptr) __alsa_snd_alloca(ptr, snd_pcm_info)
+
+_PA_DEFINE_FUNC(snd_ctl_pcm_next_device);
+_PA_DEFINE_FUNC(snd_ctl_pcm_info);
+_PA_DEFINE_FUNC(snd_ctl_open);
+_PA_DEFINE_FUNC(snd_ctl_close);
+_PA_DEFINE_FUNC(snd_ctl_card_info_malloc);
+_PA_DEFINE_FUNC(snd_ctl_card_info_free);
+_PA_DEFINE_FUNC(snd_ctl_card_info);
+_PA_DEFINE_FUNC(snd_ctl_card_info_sizeof);
+_PA_DEFINE_FUNC(snd_ctl_card_info_get_name);
+#define alsa_snd_ctl_card_info_alloca(ptr) __alsa_snd_alloca(ptr, snd_ctl_card_info)
+
+_PA_DEFINE_FUNC(snd_config);
+_PA_DEFINE_FUNC(snd_config_update);
+_PA_DEFINE_FUNC(snd_config_search);
+_PA_DEFINE_FUNC(snd_config_iterator_entry);
+_PA_DEFINE_FUNC(snd_config_iterator_first);
+_PA_DEFINE_FUNC(snd_config_iterator_end);
+_PA_DEFINE_FUNC(snd_config_iterator_next);
+_PA_DEFINE_FUNC(snd_config_get_string);
+_PA_DEFINE_FUNC(snd_config_get_id);
+_PA_DEFINE_FUNC(snd_config_update_free_global);
+
+_PA_DEFINE_FUNC(snd_pcm_status);
+_PA_DEFINE_FUNC(snd_pcm_status_sizeof);
+_PA_DEFINE_FUNC(snd_pcm_status_get_tstamp);
+_PA_DEFINE_FUNC(snd_pcm_status_get_state);
+_PA_DEFINE_FUNC(snd_pcm_status_get_trigger_tstamp);
+_PA_DEFINE_FUNC(snd_pcm_status_get_delay);
+#define alsa_snd_pcm_status_alloca(ptr) __alsa_snd_alloca(ptr, snd_pcm_status)
+
+_PA_DEFINE_FUNC(snd_card_next);
+_PA_DEFINE_FUNC(snd_asoundlib_version);
+_PA_DEFINE_FUNC(snd_strerror);
+_PA_DEFINE_FUNC(snd_output_stdio_attach);
+
+#define alsa_snd_config_for_each(pos, next, node)\
+    for (pos = alsa_snd_config_iterator_first(node),\
+         next = alsa_snd_config_iterator_next(pos);\
+         pos != alsa_snd_config_iterator_end(node); pos = next, next = alsa_snd_config_iterator_next(pos))
+
+#undef _PA_DEFINE_FUNC
+
+/* Redefine 'PA_ALSA_PATHNAME' to a different Alsa library name if desired. */
+#ifndef PA_ALSA_PATHNAME
+    #define PA_ALSA_PATHNAME "libasound.so"
+#endif
+static const char *g_AlsaLibName = PA_ALSA_PATHNAME;
+
+/* Handle to dynamically loaded library. */
+static void *g_AlsaLib = NULL;
+
+#ifdef PA_ALSA_DYNAMIC
+
+#define _PA_LOCAL_IMPL(x) __pa_local_##x
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_set_rate_near) (snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
+{
+    int ret;
+
+    if(( ret = alsa_snd_pcm_hw_params_set_rate(pcm, params, (*val), (*dir)) ) < 0 )
+        return ret;
+
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_set_buffer_size_near) (snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val)
+{
+    int ret;
+
+    if(( ret = alsa_snd_pcm_hw_params_set_buffer_size(pcm, params, (*val)) ) < 0 )
+        return ret;
+
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_set_period_size_near) (snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val, int *dir)
+{
+    int ret;
+
+    if(( ret = alsa_snd_pcm_hw_params_set_period_size(pcm, params, (*val), (*dir)) ) < 0 )
+        return ret;
+
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_channels_min) (const snd_pcm_hw_params_t *params, unsigned int *val)
+{
+    (*val) = 1;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_channels_max) (const snd_pcm_hw_params_t *params, unsigned int *val)
+{
+    (*val) = 2;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_periods_min) (const snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
+{
+    (*val) = 2;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_periods_max) (const snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
+{
+    (*val) = 8;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_period_size_min) (const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *frames, int *dir)
+{
+    (*frames) = 64;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_period_size_max) (const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *frames, int *dir)
+{
+    (*frames) = 512;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_buffer_size_max) (const snd_pcm_hw_params_t *params, snd_pcm_uframes_t *val)
+{
+    int ret;
+    int dir                = 0;
+    snd_pcm_uframes_t pmax = 0;
+    unsigned int      pcnt = 0;
+
+    if(( ret = _PA_LOCAL_IMPL(snd_pcm_hw_params_get_period_size_max)(params, &pmax, &dir) ) < 0 )
+        return ret;
+    if(( ret = _PA_LOCAL_IMPL(snd_pcm_hw_params_get_periods_max)(params, &pcnt, &dir) ) < 0 )
+        return ret;
+
+    (*val) = pmax * pcnt;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_rate_min) (const snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
+{
+    (*val) = 44100;
+    return 0;
+}
+
+int _PA_LOCAL_IMPL(snd_pcm_hw_params_get_rate_max) (const snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
+{
+    (*val) = 44100;
+    return 0;
+}
+
+#endif // PA_ALSA_DYNAMIC
+
+/* Trying to load Alsa library dynamically if 'PA_ALSA_DYNAMIC' is defined, othervise
+   will link during compilation.
+*/
+static int PaAlsa_LoadLibrary()
+{
+#ifdef PA_ALSA_DYNAMIC
+
+    PA_DEBUG(( "%s: loading ALSA library file - %s\n", __FUNCTION__, g_AlsaLibName ));
+
+    dlerror();
+    g_AlsaLib = dlopen(g_AlsaLibName, (RTLD_NOW|RTLD_GLOBAL) );
+    if (g_AlsaLib == NULL)
+    {
+        PA_DEBUG(( "%s: failed dlopen() ALSA library file - %s, error: %s\n", __FUNCTION__, g_AlsaLibName, dlerror() ));
+        return 0;
+    }
+
+    PA_DEBUG(( "%s: loading ALSA API\n", __FUNCTION__ ));
+
+    #define _PA_LOAD_FUNC(x) do {             \
+        alsa_##x = dlsym( g_AlsaLib, #x );      \
+        if( alsa_##x == NULL ) {               \
+            PA_DEBUG(( "%s: symbol [%s] not found in - %s, error: %s\n", __FUNCTION__, #x, g_AlsaLibName, dlerror() )); }\
+        } while(0)
+
+#else
+
+    #define _PA_LOAD_FUNC(x) alsa_##x = &x
+
+#endif
+
+    _PA_LOAD_FUNC(snd_pcm_open);
+    _PA_LOAD_FUNC(snd_pcm_close);
+    _PA_LOAD_FUNC(snd_pcm_nonblock);
+    _PA_LOAD_FUNC(snd_pcm_frames_to_bytes);
+    _PA_LOAD_FUNC(snd_pcm_prepare);
+    _PA_LOAD_FUNC(snd_pcm_start);
+    _PA_LOAD_FUNC(snd_pcm_resume);
+    _PA_LOAD_FUNC(snd_pcm_wait);
+    _PA_LOAD_FUNC(snd_pcm_state);
+    _PA_LOAD_FUNC(snd_pcm_avail_update);
+    _PA_LOAD_FUNC(snd_pcm_areas_silence);
+    _PA_LOAD_FUNC(snd_pcm_mmap_begin);
+    _PA_LOAD_FUNC(snd_pcm_mmap_commit);
+    _PA_LOAD_FUNC(snd_pcm_readi);
+    _PA_LOAD_FUNC(snd_pcm_readn);
+    _PA_LOAD_FUNC(snd_pcm_writei);
+    _PA_LOAD_FUNC(snd_pcm_writen);
+    _PA_LOAD_FUNC(snd_pcm_drain);
+    _PA_LOAD_FUNC(snd_pcm_recover);
+    _PA_LOAD_FUNC(snd_pcm_drop);
+    _PA_LOAD_FUNC(snd_pcm_area_copy);
+    _PA_LOAD_FUNC(snd_pcm_poll_descriptors);
+    _PA_LOAD_FUNC(snd_pcm_poll_descriptors_count);
+    _PA_LOAD_FUNC(snd_pcm_poll_descriptors_revents);
+    _PA_LOAD_FUNC(snd_pcm_format_size);
+    _PA_LOAD_FUNC(snd_pcm_link);
+    _PA_LOAD_FUNC(snd_pcm_delay);
+
+    _PA_LOAD_FUNC(snd_pcm_hw_params_sizeof);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_malloc);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_free);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_any);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_access);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_format);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_channels);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_set_periods_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_rate_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_rate);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_rate_resample);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_set_buffer_time_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_buffer_size);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_buffer_size_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_buffer_size_min);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_set_period_time_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_period_size_near);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_periods_integer);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_periods_min);
+
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_buffer_size);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_get_period_size);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_get_access);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_get_periods);
+//    _PA_LOAD_FUNC(snd_pcm_hw_params_get_rate);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_channels_min);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_channels_max);
+
+    _PA_LOAD_FUNC(snd_pcm_hw_params_test_period_size);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_test_format);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_test_access);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_dump);
+    _PA_LOAD_FUNC(snd_pcm_hw_params);
+
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_periods_min);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_periods_max);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_set_period_size);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_period_size_min);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_period_size_max);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_buffer_size_max);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_rate_min);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_rate_max);
+    _PA_LOAD_FUNC(snd_pcm_hw_params_get_rate_numden);
+
+    _PA_LOAD_FUNC(snd_pcm_sw_params_sizeof);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_malloc);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_current);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_avail_min);
+    _PA_LOAD_FUNC(snd_pcm_sw_params);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_free);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_start_threshold);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_stop_threshold);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_get_boundary);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_silence_threshold);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_silence_size);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_xfer_align);
+    _PA_LOAD_FUNC(snd_pcm_sw_params_set_tstamp_mode);
+
+    _PA_LOAD_FUNC(snd_pcm_info);
+    _PA_LOAD_FUNC(snd_pcm_info_sizeof);
+    _PA_LOAD_FUNC(snd_pcm_info_malloc);
+    _PA_LOAD_FUNC(snd_pcm_info_free);
+    _PA_LOAD_FUNC(snd_pcm_info_set_device);
+    _PA_LOAD_FUNC(snd_pcm_info_set_subdevice);
+    _PA_LOAD_FUNC(snd_pcm_info_set_stream);
+    _PA_LOAD_FUNC(snd_pcm_info_get_name);
+    _PA_LOAD_FUNC(snd_pcm_info_get_card);
+
+    _PA_LOAD_FUNC(snd_ctl_pcm_next_device);
+    _PA_LOAD_FUNC(snd_ctl_pcm_info);
+    _PA_LOAD_FUNC(snd_ctl_open);
+    _PA_LOAD_FUNC(snd_ctl_close);
+    _PA_LOAD_FUNC(snd_ctl_card_info_malloc);
+    _PA_LOAD_FUNC(snd_ctl_card_info_free);
+    _PA_LOAD_FUNC(snd_ctl_card_info);
+    _PA_LOAD_FUNC(snd_ctl_card_info_sizeof);
+    _PA_LOAD_FUNC(snd_ctl_card_info_get_name);
+
+    _PA_LOAD_FUNC(snd_config);
+    _PA_LOAD_FUNC(snd_config_update);
+    _PA_LOAD_FUNC(snd_config_search);
+    _PA_LOAD_FUNC(snd_config_iterator_entry);
+    _PA_LOAD_FUNC(snd_config_iterator_first);
+    _PA_LOAD_FUNC(snd_config_iterator_end);
+    _PA_LOAD_FUNC(snd_config_iterator_next);
+    _PA_LOAD_FUNC(snd_config_get_string);
+    _PA_LOAD_FUNC(snd_config_get_id);
+    _PA_LOAD_FUNC(snd_config_update_free_global);
+
+    _PA_LOAD_FUNC(snd_pcm_status);
+    _PA_LOAD_FUNC(snd_pcm_status_sizeof);
+    _PA_LOAD_FUNC(snd_pcm_status_get_tstamp);
+    _PA_LOAD_FUNC(snd_pcm_status_get_state);
+    _PA_LOAD_FUNC(snd_pcm_status_get_trigger_tstamp);
+    _PA_LOAD_FUNC(snd_pcm_status_get_delay);
+
+    _PA_LOAD_FUNC(snd_card_next);
+    _PA_LOAD_FUNC(snd_asoundlib_version);
+    _PA_LOAD_FUNC(snd_strerror);
+    _PA_LOAD_FUNC(snd_output_stdio_attach);
+#undef _PA_LOAD_FUNC
+
+#ifdef PA_ALSA_DYNAMIC
+    PA_DEBUG(( "%s: loaded ALSA API - ok\n", __FUNCTION__ ));
+
+#define _PA_VALIDATE_LOAD_REPLACEMENT(x)\
+    do {\
+        if( alsa_##x == NULL )\
+        {\
+            alsa_##x = &_PA_LOCAL_IMPL(x);\
+            PA_DEBUG(( "%s: replacing [%s] with local implementation\n", __FUNCTION__, #x ));\
+        }\
+    } while (0)
+
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_set_rate_near);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_set_buffer_size_near);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_set_period_size_near);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_channels_min);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_channels_max);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_periods_min);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_periods_max);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_period_size_min);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_period_size_max);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_buffer_size_max);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_rate_min);
+    _PA_VALIDATE_LOAD_REPLACEMENT(snd_pcm_hw_params_get_rate_max);
+
+#undef _PA_LOCAL_IMPL
+#undef _PA_VALIDATE_LOAD_REPLACEMENT
+
+#endif // PA_ALSA_DYNAMIC
+
+    return 1;
+}
+
+void PaAlsa_SetLibraryPathName( const char *pathName )
+{
+#ifdef PA_ALSA_DYNAMIC
+    g_AlsaLibName = pathName;
+#else
+    (void)pathName;
+#endif
+}
+
+/* Close handle to Alsa library. */
+static void PaAlsa_CloseLibrary()
+{
+#ifdef PA_ALSA_DYNAMIC
+    dlclose(g_AlsaLib);
+    g_AlsaLib = NULL;
+#endif
+}
+
+/* Check return value of ALSA function, and map it to PaError */
+#define ENSURE_(expr, code) \
+    do { \
+        int __pa_unsure_error_id;\
+        if( UNLIKELY( (__pa_unsure_error_id = (expr)) < 0 ) ) \
+        { \
+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+            if( (code) == paUnanticipatedHostError && pthread_equal( pthread_self(), paUnixMainThread) ) \
+            { \
+                PaUtil_SetLastHostErrorInfo( paALSA, __pa_unsure_error_id, alsa_snd_strerror( __pa_unsure_error_id ) ); \
+            } \
+            PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
+            if( (code) == paUnanticipatedHostError ) \
+                PA_DEBUG(( "Host error description: %s\n", alsa_snd_strerror( __pa_unsure_error_id ) )); \
+            result = (code); \
+            goto error; \
+        } \
+    } while (0)
+
+#define ASSERT_CALL_(expr, success) \
+    do {\
+        int __pa_assert_error_id;\
+        __pa_assert_error_id = (expr);\
+        assert( success == __pa_assert_error_id );\
+    } while (0)
+
+static int numPeriods_ = 4;
+static int busyRetries_ = 100;
+
+int PaAlsa_SetNumPeriods( int numPeriods )
+{
+    numPeriods_ = numPeriods;
+    return paNoError;
+}
+
+typedef enum
+{
+    StreamDirection_In,
+    StreamDirection_Out
+} StreamDirection;
+
+typedef struct
+{
+    PaSampleFormat hostSampleFormat;
+    int numUserChannels, numHostChannels;
+    int userInterleaved, hostInterleaved;
+    int canMmap;
+    void *nonMmapBuffer;
+    unsigned int nonMmapBufferSize;
+    PaDeviceIndex device;     /* Keep the device index */
+    int deviceIsPlug; /* Distinguish plug types from direct 'hw:' devices */
+    int useReventFix; /* Alsa older than 1.0.16, plug devices need a fix */
+
+    snd_pcm_t *pcm;
+    snd_pcm_uframes_t framesPerPeriod, alsaBufferSize;
+    snd_pcm_format_t nativeFormat;
+    unsigned int nfds;
+    int ready;  /* Marked ready from poll */
+    void **userBuffers;
+    snd_pcm_uframes_t offset;
+    StreamDirection streamDir;
+
+    snd_pcm_channel_area_t *channelAreas;  /* Needed for channel adaption */
+} PaAlsaStreamComponent;
+
+/* Implementation specific stream structure */
+typedef struct PaAlsaStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+    PaUnixThread thread;
+
+    unsigned long framesPerUserBuffer, maxFramesPerHostBuffer;
+
+    int primeBuffers;
+    int callbackMode;              /* bool: are we running in callback mode? */
+    int pcmsSynced;                /* Have we successfully synced pcms */
+    int rtSched;
+
+    /* the callback thread uses these to poll the sound device(s), waiting
+     * for data to be ready/available */
+    struct pollfd* pfds;
+    int pollTimeout;
+
+    /* Used in communication between threads */
+    volatile sig_atomic_t callback_finished; /* bool: are we in the "callback finished" state? */
+    volatile sig_atomic_t callbackAbort;    /* Drop frames? */
+    volatile sig_atomic_t isActive;         /* Is stream in active state? (Between StartStream and StopStream || !paContinue) */
+    PaUnixMutex stateMtx;                   /* Used to synchronize access to stream state */
+
+    int neverDropInput;
+
+    PaTime underrun;
+    PaTime overrun;
+
+    PaAlsaStreamComponent capture, playback;
+}
+PaAlsaStream;
+
+/* PaAlsaHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct PaAlsaHostApiRepresentation
+{
+    PaUtilHostApiRepresentation baseHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    PaHostApiIndex hostApiIndex;
+    PaUint32 alsaLibVersion; /* Retrieved from the library at run-time */
+}
+PaAlsaHostApiRepresentation;
+
+typedef struct PaAlsaDeviceInfo
+{
+    PaDeviceInfo baseDeviceInfo;
+    char *alsaName;
+    int isPlug;
+    int minInputChannels;
+    int minOutputChannels;
+}
+PaAlsaDeviceInfo;
+
+/* prototypes for functions declared in this file */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *callback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *hostApi );
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate );
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate );
+static PaUint32 PaAlsaVersionNum(void);
+
+/* Callback prototypes */
+static void *CallbackThreadFunc( void *userData );
+
+/* Blocking prototypes */
+static signed long GetStreamReadAvailable( PaStream* s );
+static signed long GetStreamWriteAvailable( PaStream* s );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+
+
+static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation *hostApi, int device )
+{
+    return (const PaAlsaDeviceInfo *)hostApi->deviceInfos[device];
+}
+
+/** Uncommented because AlsaErrorHandler is unused for anything good yet. If AlsaErrorHandler is
+    to be used, do not forget to register this callback in PaAlsa_Initialize, and unregister in Terminate.
+*/
+/*static void AlsaErrorHandler(const char *file, int line, const char *function, int err, const char *fmt, ...)
+{
+}*/
+
+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaAlsaHostApiRepresentation *alsaHostApi = NULL;
+
+    /* Try loading Alsa library. */
+    if (!PaAlsa_LoadLibrary())
+        return paHostApiNotFound;
+
+    PA_UNLESS( alsaHostApi = (PaAlsaHostApiRepresentation*) PaUtil_AllocateMemory(
+                sizeof(PaAlsaHostApiRepresentation) ), paInsufficientMemory );
+    PA_UNLESS( alsaHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+    alsaHostApi->hostApiIndex = hostApiIndex;
+    alsaHostApi->alsaLibVersion = PaAlsaVersionNum();
+
+    *hostApi = (PaUtilHostApiRepresentation*)alsaHostApi;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paALSA;
+    (*hostApi)->info.name = "ALSA";
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    /** If AlsaErrorHandler is to be used, do not forget to unregister callback pointer in
+        Terminate function.
+    */
+    /*ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError );*/
+
+    PA_ENSURE( BuildDeviceList( alsaHostApi ) );
+
+    PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream,
+                                      IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable,
+                                      PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &alsaHostApi->blockingStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream,
+                                      IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream,
+                                      GetStreamReadAvailable,
+                                      GetStreamWriteAvailable );
+
+    PA_ENSURE( PaUnixThreading_Initialize() );
+
+    return result;
+
+error:
+    if( alsaHostApi )
+    {
+        if( alsaHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+        }
+
+        PaUtil_FreeMemory( alsaHostApi );
+    }
+
+    return result;
+}
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+
+    assert( hostApi );
+
+    /** See AlsaErrorHandler and PaAlsa_Initialize for details.
+    */
+    /*snd_lib_error_set_handler(NULL);*/
+
+    if( alsaHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( alsaHostApi );
+    alsa_snd_config_update_free_global();
+
+    /* Close Alsa library. */
+    PaAlsa_CloseLibrary();
+}
+
+/** Determine max channels and default latencies.
+ *
+ * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for
+ * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero,
+ * and a suitable result returned. The device is closed before returning.
+ */
+static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking,
+        PaAlsaDeviceInfo* devInfo )
+{
+    PaError result = paNoError;
+    snd_pcm_hw_params_t *hwParams;
+    snd_pcm_uframes_t alsaBufferFrames, alsaPeriodFrames;
+    unsigned int minChans, maxChans;
+    int* minChannels, * maxChannels;
+    double * defaultLowLatency, * defaultHighLatency, * defaultSampleRate =
+        &devInfo->baseDeviceInfo.defaultSampleRate;
+    double defaultSr = *defaultSampleRate;
+    int dir;
+
+    assert( pcm );
+
+    PA_DEBUG(( "%s: collecting info ..\n", __FUNCTION__ ));
+
+    if( StreamDirection_In == mode )
+    {
+        minChannels = &devInfo->minInputChannels;
+        maxChannels = &devInfo->baseDeviceInfo.maxInputChannels;
+        defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowInputLatency;
+        defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighInputLatency;
+    }
+    else
+    {
+        minChannels = &devInfo->minOutputChannels;
+        maxChannels = &devInfo->baseDeviceInfo.maxOutputChannels;
+        defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowOutputLatency;
+        defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighOutputLatency;
+    }
+
+    ENSURE_( alsa_snd_pcm_nonblock( pcm, 0 ), paUnanticipatedHostError );
+
+    alsa_snd_pcm_hw_params_alloca( &hwParams );
+    alsa_snd_pcm_hw_params_any( pcm, hwParams );
+
+    if( defaultSr >= 0 )
+    {
+        /* Could be that the device opened in one mode supports samplerates that the other mode wont have,
+         * so try again .. */
+        if( SetApproximateSampleRate( pcm, hwParams, defaultSr ) < 0 )
+        {
+            defaultSr = -1.;
+            alsa_snd_pcm_hw_params_any( pcm, hwParams ); /* Clear any params (rate) that might have been set */
+            PA_DEBUG(( "%s: Original default samplerate failed, trying again ..\n", __FUNCTION__ ));
+        }
+    }
+
+    if( defaultSr < 0. )           /* Default sample rate not set */
+    {
+        unsigned int sampleRate = 44100;        /* Will contain approximate rate returned by alsa-lib */
+
+        /* Don't allow rate resampling when probing for the default rate (but ignore if this call fails) */
+        alsa_snd_pcm_hw_params_set_rate_resample( pcm, hwParams, 0 );
+        if( alsa_snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ) < 0 )
+        {
+            result = paUnanticipatedHostError;
+            goto error;
+        }
+        ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError );
+    }
+
+    ENSURE_( alsa_snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError );
+    assert( maxChans <= INT_MAX );
+    assert( maxChans > 0 );    /* Weird linking issue could cause wrong version of ALSA symbols to be called,
+                                   resulting in zeroed values */
+
+    /* XXX: Limit to sensible number (ALSA plugins accept a crazy amount of channels)? */
+    if( isPlug && maxChans > 128 )
+    {
+        maxChans = 128;
+        PA_DEBUG(( "%s: Limiting number of plugin channels to %u\n", __FUNCTION__, maxChans ));
+    }
+
+    /* TWEAKME:
+     * Giving values for default min and max latency is not straightforward.
+     *  * for low latency, we want to give the lowest value that will work reliably.
+     *      This varies based on the sound card, kernel, CPU, etc.  Better to give
+     *      sub-optimal latency than to give a number too low and cause dropouts.
+     *  * for high latency we want to give a large enough value that dropouts are basically impossible.
+     *      This doesn't really require as much tweaking, since providing too large a number will
+     *      just cause us to select the nearest setting that will work at stream config time.
+     */
+    /* Try low latency values, (sometimes the buffer & period that result are larger) */
+    alsaBufferFrames = 512;
+    alsaPeriodFrames = 128;
+    ENSURE_( alsa_snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &alsaBufferFrames ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPeriodFrames, &dir ), paUnanticipatedHostError );
+    *defaultLowLatency = (double) (alsaBufferFrames - alsaPeriodFrames) / defaultSr;
+
+    /* Base the high latency case on values four times larger */
+    alsaBufferFrames = 2048;
+    alsaPeriodFrames = 512;
+    /* Have to reset hwParams, to set new buffer size; need to also set sample rate again */
+    ENSURE_( alsa_snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+    ENSURE_( SetApproximateSampleRate( pcm, hwParams, defaultSr ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &alsaBufferFrames ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPeriodFrames, &dir ), paUnanticipatedHostError );
+    *defaultHighLatency = (double) (alsaBufferFrames - alsaPeriodFrames) / defaultSr;
+
+    *minChannels = (int)minChans;
+    *maxChannels = (int)maxChans;
+    *defaultSampleRate = defaultSr;
+
+end:
+    alsa_snd_pcm_close( pcm );
+    return result;
+
+error:
+    goto end;
+}
+
+/* Initialize device info with invalid values (maxInputChannels and maxOutputChannels are set to zero since these indicate
+ * whether input/output is available) */
+static void InitializeDeviceInfo( PaDeviceInfo *deviceInfo )
+{
+    deviceInfo->structVersion = -1;
+    deviceInfo->name = NULL;
+    deviceInfo->hostApi = -1;
+    deviceInfo->maxInputChannels = 0;
+    deviceInfo->maxOutputChannels = 0;
+    deviceInfo->defaultLowInputLatency = -1.;
+    deviceInfo->defaultLowOutputLatency = -1.;
+    deviceInfo->defaultHighInputLatency = -1.;
+    deviceInfo->defaultHighOutputLatency = -1.;
+    deviceInfo->defaultSampleRate = -1.;
+}
+
+
+/* Retrieve the version of the runtime Alsa-lib, as a single number equivalent to
+ * SND_LIB_VERSION.  Only a version string is available ("a.b.c") so this has to be converted.
+ * Assume 'a' and 'b' are single digits only.
+ */
+static PaUint32 PaAlsaVersionNum(void)
+{
+    char* verStr;
+    PaUint32 verNum;
+
+    verStr = (char*) alsa_snd_asoundlib_version();
+    verNum = ALSA_VERSION_INT( atoi(verStr), atoi(verStr + 2), atoi(verStr + 4) );
+    PA_DEBUG(( "ALSA version (build): " SND_LIB_VERSION_STR "\nALSA version (runtime): %s\n", verStr ));
+
+    return verNum;
+}
+
+
+/* Helper struct */
+typedef struct
+{
+    char *alsaName;
+    char *name;
+    int isPlug;
+    int hasPlayback;
+    int hasCapture;
+} HwDevInfo;
+
+
+HwDevInfo predefinedNames[] = {
+    { "center_lfe", NULL, 0, 1, 0 },
+/* { "default", NULL, 0, 1, 1 }, */
+    { "dmix", NULL, 0, 1, 0 },
+/* { "dpl", NULL, 0, 1, 0 }, */
+/* { "dsnoop", NULL, 0, 0, 1 }, */
+    { "front", NULL, 0, 1, 0 },
+    { "iec958", NULL, 0, 1, 0 },
+/* { "modem", NULL, 0, 1, 0 }, */
+    { "rear", NULL, 0, 1, 0 },
+    { "side", NULL, 0, 1, 0 },
+/*     { "spdif", NULL, 0, 0, 0 }, */
+    { "surround40", NULL, 0, 1, 0 },
+    { "surround41", NULL, 0, 1, 0 },
+    { "surround50", NULL, 0, 1, 0 },
+    { "surround51", NULL, 0, 1, 0 },
+    { "surround71", NULL, 0, 1, 0 },
+
+    { "AndroidPlayback_Earpiece_normal",         NULL, 0, 1, 0 },
+    { "AndroidPlayback_Speaker_normal",          NULL, 0, 1, 0 },
+    { "AndroidPlayback_Bluetooth_normal",        NULL, 0, 1, 0 },
+    { "AndroidPlayback_Headset_normal",          NULL, 0, 1, 0 },
+    { "AndroidPlayback_Speaker_Headset_normal",  NULL, 0, 1, 0 },
+    { "AndroidPlayback_Bluetooth-A2DP_normal",   NULL, 0, 1, 0 },
+    { "AndroidPlayback_ExtraDockSpeaker_normal", NULL, 0, 1, 0 },
+    { "AndroidPlayback_TvOut_normal",            NULL, 0, 1, 0 },
+
+    { "AndroidRecord_Microphone",                NULL, 0, 0, 1 },
+    { "AndroidRecord_Earpiece_normal",           NULL, 0, 0, 1 },
+    { "AndroidRecord_Speaker_normal",            NULL, 0, 0, 1 },
+    { "AndroidRecord_Headset_normal",            NULL, 0, 0, 1 },
+    { "AndroidRecord_Bluetooth_normal",          NULL, 0, 0, 1 },
+    { "AndroidRecord_Speaker_Headset_normal",    NULL, 0, 0, 1 },
+
+    { NULL, NULL, 0, 1, 0 }
+};
+
+static const HwDevInfo *FindDeviceName( const char *name )
+{
+    int i;
+
+    for( i = 0; predefinedNames[i].alsaName; i++ )
+    {
+        if( strcmp( name, predefinedNames[i].alsaName ) == 0 )
+        {
+            return &predefinedNames[i];
+        }
+    }
+
+    return NULL;
+}
+
+static PaError PaAlsa_StrDup( PaAlsaHostApiRepresentation *alsaApi,
+        char **dst,
+        const char *src)
+{
+    PaError result = paNoError;
+    int len = strlen( src ) + 1;
+
+    /* PA_DEBUG(("PaStrDup %s %d\n", src, len)); */
+
+    PA_UNLESS( *dst = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+            paInsufficientMemory );
+    strncpy( *dst, src, len );
+
+error:
+    return result;
+}
+
+/* Disregard some standard plugins
+ */
+static int IgnorePlugin( const char *pluginId )
+{
+    static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee",
+        "file", "null", "shm", "cards", "rate_convert", NULL};
+    int i = 0;
+    while( ignoredPlugins[i] )
+    {
+        if( !strcmp( pluginId, ignoredPlugins[i] ) )
+        {
+            return 1;
+        }
+        ++i;
+    }
+
+    return 0;
+}
+
+/* Skip past parts at the beginning of a (pcm) info name that are already in the card name, to avoid duplication */
+static char *SkipCardDetailsInName( char *infoSkipName, char *cardRefName )
+{
+    char *lastSpacePosn = infoSkipName;
+
+    /* Skip matching chars; but only in chunks separated by ' ' (not part words etc), so track lastSpacePosn */
+    while( *cardRefName )
+    {
+        while( *infoSkipName && *cardRefName && *infoSkipName == *cardRefName)
+        {
+            infoSkipName++;
+            cardRefName++;
+            if( *infoSkipName == ' ' || *infoSkipName == '\0' )
+                lastSpacePosn = infoSkipName;
+        }
+        infoSkipName = lastSpacePosn;
+        /* Look for another chunk; post-increment means ends pointing to next char */
+        while( *cardRefName && ( *cardRefName++ != ' ' ));
+    }
+    if( *infoSkipName == '\0' )
+        return "-"; /* The 2 names were identical; instead of a nul-string, return a marker string */
+
+    /* Now want to move to the first char after any spaces */
+    while( *lastSpacePosn && *lastSpacePosn == ' ' )
+        lastSpacePosn++;
+    /* Skip a single separator char if present in the remaining pcm name; (pa will add its own) */
+    if(( *lastSpacePosn == '-' || *lastSpacePosn == ':' ) && *(lastSpacePosn + 1) == ' ' )
+        lastSpacePosn += 2;
+
+    return lastSpacePosn;
+}
+
+/** Open PCM device.
+ *
+ * Wrapper around alsa_snd_pcm_open which may repeatedly retry opening a device if it is busy, for
+ * a certain time. This is because dmix may temporarily hold on to a device after it (dmix)
+ * has been opened and closed.
+ * @param mode: Open mode (e.g., SND_PCM_BLOCKING).
+ * @param waitOnBusy: Retry opening busy device for up to one second?
+ **/
+static int OpenPcm( snd_pcm_t **pcmp, const char *name, snd_pcm_stream_t stream, int mode, int waitOnBusy )
+{
+    int ret, tries = 0, maxTries = waitOnBusy ? busyRetries_ : 0;
+
+    ret = alsa_snd_pcm_open( pcmp, name, stream, mode );
+
+    for( tries = 0; tries < maxTries && -EBUSY == ret; ++tries )
+    {
+        Pa_Sleep( 10 );
+        ret = alsa_snd_pcm_open( pcmp, name, stream, mode );
+        if( -EBUSY != ret )
+        {
+            PA_DEBUG(( "%s: Successfully opened initially busy device after %d tries\n", __FUNCTION__, tries ));
+        }
+    }
+    if( -EBUSY == ret )
+    {
+        PA_DEBUG(( "%s: Failed to open busy device '%s'\n", __FUNCTION__, name ));
+    }
+    else
+    {
+        if( ret < 0 )
+            PA_DEBUG(( "%s: Opened device '%s' ptr[%p] - result: [%d:%s]\n", __FUNCTION__, name, *pcmp, ret, alsa_snd_strerror(ret) ));
+    }
+
+    return ret;
+}
+
+static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* deviceHwInfo, int blocking,
+        PaAlsaDeviceInfo* devInfo, int* devIdx )
+{
+    PaError result = 0;
+    PaDeviceInfo *baseDeviceInfo = &devInfo->baseDeviceInfo;
+    snd_pcm_t *pcm = NULL;
+    PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
+
+    PA_DEBUG(( "%s: Filling device info for: %s\n", __FUNCTION__, deviceHwInfo->name ));
+
+    /* Zero fields */
+    InitializeDeviceInfo( baseDeviceInfo );
+
+    /* To determine device capabilities, we must open the device and query the
+     * hardware parameter configuration space */
+
+    /* Query capture */
+    if( deviceHwInfo->hasCapture &&
+        OpenPcm( &pcm, deviceHwInfo->alsaName, SND_PCM_STREAM_CAPTURE, blocking, 0 ) >= 0 )
+    {
+        if( GropeDevice( pcm, deviceHwInfo->isPlug, StreamDirection_In, blocking, devInfo ) != paNoError )
+        {
+            /* Error */
+            PA_DEBUG(( "%s: Failed groping %s for capture\n", __FUNCTION__, deviceHwInfo->alsaName ));
+            goto end;
+        }
+    }
+
+    /* Query playback */
+    if( deviceHwInfo->hasPlayback &&
+        OpenPcm( &pcm, deviceHwInfo->alsaName, SND_PCM_STREAM_PLAYBACK, blocking, 0 ) >= 0 )
+    {
+        if( GropeDevice( pcm, deviceHwInfo->isPlug, StreamDirection_Out, blocking, devInfo ) != paNoError )
+        {
+            /* Error */
+            PA_DEBUG(( "%s: Failed groping %s for playback\n", __FUNCTION__, deviceHwInfo->alsaName ));
+            goto end;
+        }
+    }
+
+    baseDeviceInfo->structVersion = 2;
+    baseDeviceInfo->hostApi = alsaApi->hostApiIndex;
+    baseDeviceInfo->name = deviceHwInfo->name;
+    devInfo->alsaName = deviceHwInfo->alsaName;
+    devInfo->isPlug = deviceHwInfo->isPlug;
+
+    /* A: Storing pointer to PaAlsaDeviceInfo object as pointer to PaDeviceInfo object.
+     * Should now be safe to add device info, unless the device supports neither capture nor playback
+     */
+    if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 )
+    {
+        /* Make device default if there isn't already one or it is the ALSA "default" device */
+        if( ( baseApi->info.defaultInputDevice == paNoDevice ||
+            !strcmp( deviceHwInfo->alsaName, "default" ) ) && baseDeviceInfo->maxInputChannels > 0 )
+        {
+            baseApi->info.defaultInputDevice = *devIdx;
+            PA_DEBUG(( "Default input device: %s\n", deviceHwInfo->name ));
+        }
+        if( ( baseApi->info.defaultOutputDevice == paNoDevice ||
+            !strcmp( deviceHwInfo->alsaName, "default" ) ) && baseDeviceInfo->maxOutputChannels > 0 )
+        {
+            baseApi->info.defaultOutputDevice = *devIdx;
+            PA_DEBUG(( "Default output device: %s\n", deviceHwInfo->name ));
+        }
+        PA_DEBUG(( "%s: Adding device %s: %d\n", __FUNCTION__, deviceHwInfo->name, *devIdx ));
+        baseApi->deviceInfos[*devIdx] = (PaDeviceInfo *) devInfo;
+        (*devIdx) += 1;
+    }
+    else
+    {
+        PA_DEBUG(( "%s: Skipped device: %s, all channels == 0\n", __FUNCTION__, deviceHwInfo->name ));
+    }
+
+end:
+    return result;
+}
+
+/* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
+{
+    PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
+    PaAlsaDeviceInfo *deviceInfoArray;
+    int cardIdx = -1, devIdx = 0;
+    snd_ctl_card_info_t *cardInfo;
+    PaError result = paNoError;
+    size_t numDeviceNames = 0, maxDeviceNames = 1, i;
+    HwDevInfo *hwDevInfos = NULL;
+    snd_config_t *topNode = NULL;
+    snd_pcm_info_t *pcmInfo;
+    int res;
+    int blocking = SND_PCM_NONBLOCK;
+    int usePlughw = 0;
+    char *hwPrefix = "";
+    char alsaCardName[50];
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+    PaTime startTime = PaUtil_GetTime();
+#endif
+
+    if( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) && atoi( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) ) )
+        blocking = 0;
+
+    /* If PA_ALSA_PLUGHW is 1 (non-zero), use the plughw: pcm throughout instead of hw: */
+    if( getenv( "PA_ALSA_PLUGHW" ) && atoi( getenv( "PA_ALSA_PLUGHW" ) ) )
+    {
+        usePlughw = 1;
+        hwPrefix = "plug";
+        PA_DEBUG(( "%s: Using Plughw\n", __FUNCTION__ ));
+    }
+
+    /* These two will be set to the first working input and output device, respectively */
+    baseApi->info.defaultInputDevice = paNoDevice;
+    baseApi->info.defaultOutputDevice = paNoDevice;
+
+    /* Gather info about hw devices
+
+     * alsa_snd_card_next() modifies the integer passed to it to be:
+     *      the index of the first card if the parameter is -1
+     *      the index of the next card if the parameter is the index of a card
+     *      -1 if there are no more cards
+     *
+     * The function itself returns 0 if it succeeded. */
+    cardIdx = -1;
+    alsa_snd_ctl_card_info_alloca( &cardInfo );
+    alsa_snd_pcm_info_alloca( &pcmInfo );
+    while( alsa_snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 )
+    {
+        char *cardName;
+        int devIdx = -1;
+        snd_ctl_t *ctl;
+        char buf[50];
+
+        snprintf( alsaCardName, sizeof (alsaCardName), "hw:%d", cardIdx );
+
+        /* Acquire name of card */
+        if( alsa_snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 )
+        {
+            /* Unable to open card :( */
+            PA_DEBUG(( "%s: Unable to open device %s\n", __FUNCTION__, alsaCardName ));
+            continue;
+        }
+        alsa_snd_ctl_card_info( ctl, cardInfo );
+
+        PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, alsa_snd_ctl_card_info_get_name( cardInfo )) );
+
+        while( alsa_snd_ctl_pcm_next_device( ctl, &devIdx ) == 0 && devIdx >= 0 )
+        {
+            char *alsaDeviceName, *deviceName, *infoName;
+            size_t len;
+            int hasPlayback = 0, hasCapture = 0;
+
+            snprintf( buf, sizeof (buf), "%s%s,%d", hwPrefix, alsaCardName, devIdx );
+
+            /* Obtain info about this particular device */
+            alsa_snd_pcm_info_set_device( pcmInfo, devIdx );
+            alsa_snd_pcm_info_set_subdevice( pcmInfo, 0 );
+            alsa_snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_CAPTURE );
+            if( alsa_snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+            {
+                hasCapture = 1;
+            }
+
+            alsa_snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK );
+            if( alsa_snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+            {
+                hasPlayback = 1;
+            }
+
+            if( !hasPlayback && !hasCapture )
+            {
+                /* Error */
+                continue;
+            }
+
+            infoName = SkipCardDetailsInName( (char *)alsa_snd_pcm_info_get_name( pcmInfo ), cardName );
+
+            /* The length of the string written by snprintf plus terminating 0 */
+            len = snprintf( NULL, 0, "%s: %s (%s)", cardName, infoName, buf ) + 1;
+            PA_UNLESS( deviceName = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+                    paInsufficientMemory );
+            snprintf( deviceName, len, "%s: %s (%s)", cardName, infoName, buf );
+
+            ++numDeviceNames;
+            if( !hwDevInfos || numDeviceNames > maxDeviceNames )
+            {
+                maxDeviceNames *= 2;
+                PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ),
+                        paInsufficientMemory );
+            }
+
+            PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) );
+
+            hwDevInfos[ numDeviceNames - 1 ].alsaName = alsaDeviceName;
+            hwDevInfos[ numDeviceNames - 1 ].name = deviceName;
+            hwDevInfos[ numDeviceNames - 1 ].isPlug = usePlughw;
+            hwDevInfos[ numDeviceNames - 1 ].hasPlayback = hasPlayback;
+            hwDevInfos[ numDeviceNames - 1 ].hasCapture = hasCapture;
+        }
+        alsa_snd_ctl_close( ctl );
+    }
+
+    /* Iterate over plugin devices */
+    if( NULL == (*alsa_snd_config) )
+    {
+        /* alsa_snd_config_update is called implicitly by some functions, if this hasn't happened snd_config will be NULL (bleh) */
+        ENSURE_( alsa_snd_config_update(), paUnanticipatedHostError );
+        PA_DEBUG(( "Updating snd_config\n" ));
+    }
+    assert( *alsa_snd_config );
+    if( ( res = alsa_snd_config_search( *alsa_snd_config, "pcm", &topNode ) ) >= 0 )
+    {
+        snd_config_iterator_t i, next;
+
+        alsa_snd_config_for_each( i, next, topNode )
+        {
+            const char *tpStr = "unknown", *idStr = NULL;
+            int err = 0;
+
+            char *alsaDeviceName, *deviceName;
+            const HwDevInfo *predefined = NULL;
+            snd_config_t *n = alsa_snd_config_iterator_entry( i ), * tp = NULL;;
+
+            if( (err = alsa_snd_config_search( n, "type", &tp )) < 0 )
+            {
+                if( -ENOENT != err )
+                {
+                    ENSURE_(err, paUnanticipatedHostError);
+                }
+            }
+            else
+            {
+                ENSURE_( alsa_snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError );
+            }
+            ENSURE_( alsa_snd_config_get_id( n, &idStr ), paUnanticipatedHostError );
+            if( IgnorePlugin( idStr ) )
+            {
+                PA_DEBUG(( "%s: Ignoring ALSA plugin device [%s] of type [%s]\n", __FUNCTION__, idStr, tpStr ));
+                continue;
+            }
+            PA_DEBUG(( "%s: Found plugin [%s] of type [%s]\n", __FUNCTION__, idStr, tpStr ));
+
+            PA_UNLESS( alsaDeviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+                                                            strlen(idStr) + 6 ), paInsufficientMemory );
+            strcpy( alsaDeviceName, idStr );
+            PA_UNLESS( deviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+                                                            strlen(idStr) + 1 ), paInsufficientMemory );
+            strcpy( deviceName, idStr );
+
+            ++numDeviceNames;
+            if( !hwDevInfos || numDeviceNames > maxDeviceNames )
+            {
+                maxDeviceNames *= 2;
+                PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ),
+                        paInsufficientMemory );
+            }
+
+            predefined = FindDeviceName( alsaDeviceName );
+
+            hwDevInfos[numDeviceNames - 1].alsaName = alsaDeviceName;
+            hwDevInfos[numDeviceNames - 1].name     = deviceName;
+            hwDevInfos[numDeviceNames - 1].isPlug   = 1;
+
+            if( predefined )
+            {
+                hwDevInfos[numDeviceNames - 1].hasPlayback = predefined->hasPlayback;
+                hwDevInfos[numDeviceNames - 1].hasCapture  = predefined->hasCapture;
+            }
+            else
+            {
+                hwDevInfos[numDeviceNames - 1].hasPlayback = 1;
+                hwDevInfos[numDeviceNames - 1].hasCapture  = 1;
+            }
+        }
+    }
+    else
+        PA_DEBUG(( "%s: Iterating over ALSA plugins failed: %s\n", __FUNCTION__, alsa_snd_strerror( res ) ));
+
+    /* allocate deviceInfo memory based on the number of devices */
+    PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+            alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory );
+
+    /* allocate all device info structs in a contiguous block */
+    PA_UNLESS( deviceInfoArray = (PaAlsaDeviceInfo*)PaUtil_GroupAllocateMemory(
+            alsaApi->allocations, sizeof(PaAlsaDeviceInfo) * numDeviceNames ), paInsufficientMemory );
+
+    /* Loop over list of cards, filling in info. If a device is deemed unavailable (can't get name),
+     * it's ignored.
+     *
+     * Note that we do this in two stages. This is a workaround owing to the fact that the 'dmix'
+     * plugin may cause the underlying hardware device to be busy for a short while even after it
+     * (dmix) is closed. The 'default' plugin may also point to the dmix plugin, so the same goes
+     * for this.
+     */
+    PA_DEBUG(( "%s: Filling device info for %d devices\n", __FUNCTION__, numDeviceNames ));
+    for( i = 0, devIdx = 0; i < numDeviceNames; ++i )
+    {
+        PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i];
+        HwDevInfo* hwInfo = &hwDevInfos[i];
+        if( !strcmp( hwInfo->name, "dmix" ) || !strcmp( hwInfo->name, "default" ) )
+        {
+            continue;
+        }
+
+        PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo, &devIdx ) );
+    }
+    assert( devIdx < numDeviceNames );
+    /* Now inspect 'dmix' and 'default' plugins */
+    for( i = 0; i < numDeviceNames; ++i )
+    {
+        PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i];
+        HwDevInfo* hwInfo = &hwDevInfos[i];
+        if( strcmp( hwInfo->name, "dmix" ) && strcmp( hwInfo->name, "default" ) )
+        {
+            continue;
+        }
+
+        PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo, &devIdx ) );
+    }
+    free( hwDevInfos );
+
+    baseApi->info.deviceCount = devIdx;   /* Number of successfully queried devices */
+
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+    PA_DEBUG(( "%s: Building device list took %f seconds\n", __FUNCTION__, PaUtil_GetTime() - startTime ));
+#endif
+
+end:
+    return result;
+
+error:
+    /* No particular action */
+    goto end;
+}
+
+/* Check against known device capabilities */
+static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilHostApiRepresentation *hostApi, StreamDirection mode )
+{
+    PaError result = paNoError;
+    int maxChans;
+    const PaAlsaDeviceInfo *deviceInfo = NULL;
+    assert( parameters );
+
+    if( parameters->device != paUseHostApiSpecificDeviceSpecification )
+    {
+        assert( parameters->device < hostApi->info.deviceCount );
+        PA_UNLESS( parameters->hostApiSpecificStreamInfo == NULL, paBadIODeviceCombination );
+        deviceInfo = GetDeviceInfo( hostApi, parameters->device );
+    }
+    else
+    {
+        const PaAlsaStreamInfo *streamInfo = parameters->hostApiSpecificStreamInfo;
+
+        PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice );
+        PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1,
+                paIncompatibleHostApiSpecificStreamInfo );
+        PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice );
+
+        /* Skip further checking */
+        return paNoError;
+    }
+
+    assert( deviceInfo );
+    assert( parameters->hostApiSpecificStreamInfo == NULL );
+    maxChans = ( StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels :
+        deviceInfo->baseDeviceInfo.maxOutputChannels );
+    PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount );
+
+error:
+    return result;
+}
+
+/* Given an open stream, what sample formats are available? */
+static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm )
+{
+    PaSampleFormat available = 0;
+    snd_pcm_hw_params_t *hwParams;
+    alsa_snd_pcm_hw_params_alloca( &hwParams );
+
+    alsa_snd_pcm_hw_params_any( pcm, hwParams );
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0)
+        available |= paFloat32;
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0)
+        available |= paInt32;
+
+#ifdef PA_LITTLE_ENDIAN
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3LE ) >= 0)
+        available |= paInt24;
+#elif defined PA_BIG_ENDIAN
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3BE ) >= 0)
+        available |= paInt24;
+#endif
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0)
+        available |= paInt16;
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0)
+        available |= paUInt8;
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0)
+        available |= paInt8;
+
+    return available;
+}
+
+/* Output to console all formats supported by device */
+static void LogAllAvailableFormats( snd_pcm_t *pcm )
+{
+    PaSampleFormat available = 0;
+    snd_pcm_hw_params_t *hwParams;
+    alsa_snd_pcm_hw_params_alloca( &hwParams );
+
+    alsa_snd_pcm_hw_params_any( pcm, hwParams );
+
+    PA_DEBUG(( " --- Supported Formats ---\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S8\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U8\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S16_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S16_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U16_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U16_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U16_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U16_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S24_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S24_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U24_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U24_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U24_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U24_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT64_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT64_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT64_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT64_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_IEC958_SUBFRAME_LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_IEC958_SUBFRAME_LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_IEC958_SUBFRAME_BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_IEC958_SUBFRAME_BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_MU_LAW ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_MU_LAW\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_A_LAW ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_A_LAW\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_IMA_ADPCM ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_IMA_ADPCM\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_MPEG ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_MPEG\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_GSM ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_GSM\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_SPECIAL ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_SPECIAL\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S24_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S24_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U24_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U24_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U24_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U24_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S20_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S20_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S20_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S20_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U20_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U20_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U20_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U20_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S18_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S18_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S18_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S18_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U18_3LE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U18_3LE\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U18_3BE ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U18_3BE\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S16\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U16 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U16\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S24\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U24 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U24\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_S32\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U32 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_U32\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT\n" ));
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT64 ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_FLOAT64\n" ));
+
+    if( alsa_snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_IEC958_SUBFRAME ) >= 0)
+        PA_DEBUG(( "SND_PCM_FORMAT_IEC958_SUBFRAME\n" ));
+
+    PA_DEBUG(( " -------------------------\n" ));
+}
+
+static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat )
+{
+    switch( paFormat )
+    {
+        case paFloat32:
+            return SND_PCM_FORMAT_FLOAT;
+
+        case paInt16:
+            return SND_PCM_FORMAT_S16;
+
+        case paInt24:
+#ifdef PA_LITTLE_ENDIAN
+            return SND_PCM_FORMAT_S24_3LE;
+#elif defined PA_BIG_ENDIAN
+            return SND_PCM_FORMAT_S24_3BE;
+#endif
+
+        case paInt32:
+            return SND_PCM_FORMAT_S32;
+
+        case paInt8:
+            return SND_PCM_FORMAT_S8;
+
+        case paUInt8:
+            return SND_PCM_FORMAT_U8;
+
+        default:
+            return SND_PCM_FORMAT_UNKNOWN;
+    }
+}
+
+/** Open an ALSA pcm handle.
+ *
+ * The device to be open can be specified by name in a custom PaAlsaStreamInfo struct, or it will be by
+ * the Portaudio device number supplied in the stream parameters.
+ */
+static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *params, StreamDirection
+        streamDir, snd_pcm_t **pcm )
+{
+    PaError result = paNoError;
+    int ret;
+    const char* deviceName = "";
+    const PaAlsaDeviceInfo *deviceInfo = NULL;
+    PaAlsaStreamInfo *streamInfo = (PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo;
+
+    if( !streamInfo )
+    {
+        deviceInfo = GetDeviceInfo( hostApi, params->device );
+        deviceName = deviceInfo->alsaName;
+    }
+    else
+        deviceName = streamInfo->deviceString;
+
+    PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName ));
+    if( (ret = OpenPcm( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
+                    SND_PCM_NONBLOCK, 1 )) < 0 )
+    {
+        /* Not to be closed */
+        *pcm = NULL;
+        ENSURE_( ret, -EBUSY == ret ? paDeviceUnavailable : paBadIODeviceCombination );
+    }
+    ENSURE_( alsa_snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError );
+
+end:
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *parameters,
+        double sampleRate, StreamDirection streamDir )
+{
+    PaError result = paNoError;
+    snd_pcm_t *pcm = NULL;
+    PaSampleFormat availableFormats;
+    /* We are able to adapt to a number of channels less than what the device supports */
+    unsigned int numHostChannels;
+    PaSampleFormat hostFormat;
+    snd_pcm_hw_params_t *hwParams;
+    alsa_snd_pcm_hw_params_alloca( &hwParams );
+
+    if( !parameters->hostApiSpecificStreamInfo )
+    {
+        const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device );
+        numHostChannels = PA_MAX( parameters->channelCount, StreamDirection_In == streamDir ?
+                devInfo->minInputChannels : devInfo->minOutputChannels );
+    }
+    else
+        numHostChannels = parameters->channelCount;
+
+    PA_ENSURE( AlsaOpen( hostApi, parameters, streamDir, &pcm ) );
+
+    alsa_snd_pcm_hw_params_any( pcm, hwParams );
+
+    if( SetApproximateSampleRate( pcm, hwParams, sampleRate ) < 0 )
+    {
+        result = paInvalidSampleRate;
+        goto error;
+    }
+
+    if( alsa_snd_pcm_hw_params_set_channels( pcm, hwParams, numHostChannels ) < 0 )
+    {
+        result = paInvalidChannelCount;
+        goto error;
+    }
+
+    /* See if we can find a best possible match */
+    availableFormats = GetAvailableFormats( pcm );
+    PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) );
+
+    /* Some specific hardware (reported: Audio8 DJ) can fail with assertion during this step. */
+    ENSURE_( alsa_snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError );
+
+    {
+        /* It happens that this call fails because the device is busy */
+        int ret = 0;
+        if( ( ret = alsa_snd_pcm_hw_params( pcm, hwParams ) ) < 0 )
+        {
+            if( -EINVAL == ret )
+            {
+                /* Don't know what to return here */
+                result = paBadIODeviceCombination;
+                goto error;
+            }
+            else if( -EBUSY == ret )
+            {
+                result = paDeviceUnavailable;
+                PA_DEBUG(( "%s: Device is busy\n", __FUNCTION__ ));
+            }
+            else
+            {
+                result = paUnanticipatedHostError;
+            }
+
+            ENSURE_( ret, result );
+        }
+    }
+
+end:
+    if( pcm )
+    {
+        alsa_snd_pcm_close( pcm );
+    }
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    int inputChannelCount = 0, outputChannelCount = 0;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaError result = paFormatIsSupported;
+
+    if( inputParameters )
+    {
+        PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+    }
+
+    if( outputParameters )
+    {
+        PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+    }
+
+    if( inputChannelCount )
+    {
+        if( ( result = TestParameters( hostApi, inputParameters, sampleRate, StreamDirection_In ) )
+                != paNoError )
+            goto error;
+    }
+    if ( outputChannelCount )
+    {
+        if( ( result = TestParameters( hostApi, outputParameters, sampleRate, StreamDirection_Out ) )
+                != paNoError )
+            goto error;
+    }
+
+    return paFormatIsSupported;
+
+error:
+    return result;
+}
+
+
+static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, PaAlsaHostApiRepresentation *alsaApi,
+        const PaStreamParameters *params, StreamDirection streamDir, int callbackMode )
+{
+    PaError result = paNoError;
+    PaSampleFormat userSampleFormat = params->sampleFormat, hostSampleFormat = paNoError;
+    assert( params->channelCount > 0 );
+
+    /* Make sure things have an initial value */
+    memset( self, 0, sizeof (PaAlsaStreamComponent) );
+
+    if( NULL == params->hostApiSpecificStreamInfo )
+    {
+        const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device );
+        self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels
+                : devInfo->minOutputChannels );
+        self->deviceIsPlug = devInfo->isPlug;
+        PA_DEBUG(( "%s: Host Chans %c %i\n", __FUNCTION__, streamDir == StreamDirection_In ? 'C' : 'P', self->numHostChannels ));
+    }
+    else
+    {
+        /* We're blissfully unaware of the minimum channelCount */
+        self->numHostChannels = params->channelCount;
+        /* Check if device name does not start with hw: to determine if it is a 'plug' device */
+        if( strncmp( "hw:", ((PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo)->deviceString, 3 ) != 0  )
+            self->deviceIsPlug = 1; /* An Alsa plug device, not a direct hw device */
+    }
+    if( self->deviceIsPlug && alsaApi->alsaLibVersion < ALSA_VERSION_INT( 1, 0, 16 ) )
+        self->useReventFix = 1; /* Prior to Alsa1.0.16, plug devices may stutter without this fix */
+
+    self->device = params->device;
+
+    PA_ENSURE( AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm ) );
+    self->nfds = alsa_snd_pcm_poll_descriptors_count( self->pcm );
+
+    PA_ENSURE( hostSampleFormat = PaUtil_SelectClosestAvailableFormat( GetAvailableFormats( self->pcm ), userSampleFormat ) );
+
+    self->hostSampleFormat = hostSampleFormat;
+    self->nativeFormat = Pa2AlsaFormat( hostSampleFormat );
+    self->hostInterleaved = self->userInterleaved = !( userSampleFormat & paNonInterleaved );
+    self->numUserChannels = params->channelCount;
+    self->streamDir = streamDir;
+    self->canMmap = 0;
+    self->nonMmapBuffer = NULL;
+    self->nonMmapBufferSize = 0;
+
+    if( !callbackMode && !self->userInterleaved )
+    {
+        /* Pre-allocate non-interleaved user provided buffers */
+        PA_UNLESS( self->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * self->numUserChannels ),
+                paInsufficientMemory );
+    }
+
+error:
+
+    /* Log all available formats. */
+    if ( hostSampleFormat == paSampleFormatNotSupported )
+    {
+        LogAllAvailableFormats( self->pcm );
+        PA_DEBUG(( "%s: Please provide the log output to PortAudio developers, your hardware does not have any sample format implemented yet.\n", __FUNCTION__ ));
+    }
+
+    return result;
+}
+
+static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self )
+{
+    alsa_snd_pcm_close( self->pcm );
+    PaUtil_FreeMemory( self->userBuffers ); /* (Ptr can be NULL; PaUtil_FreeMemory includes a NULL check) */
+    PaUtil_FreeMemory( self->nonMmapBuffer );
+}
+
+/*
+static int nearbyint_(float value) {
+    if(  value - (int)value > .5 )
+        return (int)ceil( value );
+    return (int)floor( value );
+}
+*/
+
+/** Initiate configuration, preparing for determining a period size suitable for both capture and playback components.
+ *
+ */
+static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params,
+        int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+    /* Configuration consists of setting all of ALSA's parameters.
+     * These parameters come in two flavors: hardware parameters
+     * and software paramters.  Hardware parameters will affect
+     * the way the device is initialized, software parameters
+     * affect the way ALSA interacts with me, the user-level client.
+     */
+
+    PaError result = paNoError;
+    snd_pcm_access_t accessMode, alternateAccessMode;
+    int dir = 0;
+    snd_pcm_t *pcm = self->pcm;
+    double sr = *sampleRate;
+    unsigned int minPeriods = 2;
+
+    /* self->framesPerPeriod = framesPerHostBuffer; */
+
+    /* ... fill up the configuration space with all possibile
+     * combinations of parameters this device will accept */
+    ENSURE_( alsa_snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+
+    ENSURE_( alsa_snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError );
+    /* I think there should be at least 2 periods (even though ALSA doesn't appear to enforce this) */
+    dir = 0;
+    ENSURE_( alsa_snd_pcm_hw_params_set_periods_min( pcm, hwParams, &minPeriods, &dir ), paUnanticipatedHostError );
+
+    if( self->userInterleaved )
+    {
+        accessMode          = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+        alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+
+        /* test if MMAP supported */
+        self->canMmap = alsa_snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ||
+                        alsa_snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0;
+
+        PA_DEBUG(( "%s: device MMAP SND_PCM_ACCESS_MMAP_INTERLEAVED: %s\n", __FUNCTION__, ( alsa_snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ? "YES" : "NO" ) ));
+        PA_DEBUG(( "%s: device MMAP SND_PCM_ACCESS_MMAP_NONINTERLEAVED: %s\n", __FUNCTION__, ( alsa_snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0 ? "YES" : "NO" ) ));
+
+        if( !self->canMmap )
+        {
+            accessMode          = SND_PCM_ACCESS_RW_INTERLEAVED;
+            alternateAccessMode = SND_PCM_ACCESS_RW_NONINTERLEAVED;
+        }
+    }
+    else
+    {
+        accessMode          = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+        alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+
+        /* test if MMAP supported */
+        self->canMmap = alsa_snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ||
+                        alsa_snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0;
+
+        PA_DEBUG((" %s: device MMAP SND_PCM_ACCESS_MMAP_NONINTERLEAVED: %s\n", __FUNCTION__, ( alsa_snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ? "YES" : "NO" ) ));
+        PA_DEBUG(( "%s: device MMAP SND_PCM_ACCESS_MMAP_INTERLEAVED: %s\n", __FUNCTION__, ( alsa_snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0 ? "YES" : "NO" ) ));
+
+        if( !self->canMmap )
+        {
+            accessMode          = SND_PCM_ACCESS_RW_NONINTERLEAVED;
+            alternateAccessMode = SND_PCM_ACCESS_RW_INTERLEAVED;
+        }
+    }
+
+    PA_DEBUG(( "%s: device can MMAP: %s\n", __FUNCTION__, ( self->canMmap ? "YES" : "NO" ) ));
+
+    /* If requested access mode fails, try alternate mode */
+    if( alsa_snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 )
+    {
+        int err = 0;
+        if( ( err = alsa_snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0 )
+        {
+            result = paUnanticipatedHostError;
+            PaUtil_SetLastHostErrorInfo( paALSA, err, alsa_snd_strerror( err ) );
+            goto error;
+        }
+        /* Flip mode */
+        self->hostInterleaved = !self->userInterleaved;
+    }
+
+    /* Some specific hardware (reported: Audio8 DJ) can fail with assertion during this step. */
+    ENSURE_( alsa_snd_pcm_hw_params_set_format( pcm, hwParams, self->nativeFormat ), paUnanticipatedHostError );
+
+    if( ( result = SetApproximateSampleRate( pcm, hwParams, sr )) != paUnanticipatedHostError )
+    {
+        ENSURE_( GetExactSampleRate( hwParams, &sr ), paUnanticipatedHostError );
+        if( result == paInvalidSampleRate ) /* From the SetApproximateSampleRate() call above */
+        { /* The sample rate was returned as 'out of tolerance' of the one requested */
+            PA_DEBUG(( "%s: Wanted %.3f, closest sample rate was %.3f\n", __FUNCTION__, sampleRate, sr ));
+            PA_ENSURE( paInvalidSampleRate );
+        }
+    }
+    else
+    {
+       PA_ENSURE( paUnanticipatedHostError );
+    }
+
+    ENSURE_( alsa_snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount );
+
+    *sampleRate = sr;
+
+end:
+    return result;
+
+error:
+    /* No particular action */
+    goto end;
+}
+
+/** Finish the configuration of the component's ALSA device.
+ *
+ * As part of this method, the component's alsaBufferSize attribute will be set.
+ * @param latency: The latency for this component.
+ */
+static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *self, snd_pcm_hw_params_t* hwParams,
+        const PaStreamParameters *params, int primeBuffers, double sampleRate, PaTime* latency )
+{
+    PaError result = paNoError;
+    snd_pcm_sw_params_t* swParams;
+    snd_pcm_uframes_t bufSz = 0;
+    *latency = -1.;
+
+    alsa_snd_pcm_sw_params_alloca( &swParams );
+
+    bufSz = params->suggestedLatency * sampleRate + self->framesPerPeriod;
+    ENSURE_( alsa_snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError );
+
+    /* Set the parameters! */
+    {
+        int r = alsa_snd_pcm_hw_params( self->pcm, hwParams );
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+        if( r < 0 )
+        {
+            snd_output_t *output = NULL;
+            alsa_snd_output_stdio_attach( &output, stderr, 0 );
+            alsa_snd_pcm_hw_params_dump( hwParams, output );
+        }
+#endif
+        ENSURE_( r, paUnanticipatedHostError );
+    }
+    if( alsa_snd_pcm_hw_params_get_buffer_size != NULL )
+    {
+        ENSURE_( alsa_snd_pcm_hw_params_get_buffer_size( hwParams, &self->alsaBufferSize ), paUnanticipatedHostError );
+    }
+    else
+    {
+        self->alsaBufferSize = bufSz;
+    }
+
+    /* Latency in seconds */
+    *latency = (self->alsaBufferSize - self->framesPerPeriod) / sampleRate;
+
+    /* Now software parameters... */
+    ENSURE_( alsa_snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError );
+
+    ENSURE_( alsa_snd_pcm_sw_params_set_start_threshold( self->pcm, swParams, self->framesPerPeriod ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_sw_params_set_stop_threshold( self->pcm, swParams, self->alsaBufferSize ), paUnanticipatedHostError );
+
+    /* Silence buffer in the case of underrun */
+    if( !primeBuffers ) /* XXX: Make sense? */
+    {
+        snd_pcm_uframes_t boundary;
+        ENSURE_( alsa_snd_pcm_sw_params_get_boundary( swParams, &boundary ), paUnanticipatedHostError );
+        ENSURE_( alsa_snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError );
+        ENSURE_( alsa_snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError );
+    }
+
+    ENSURE_( alsa_snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerPeriod ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError );
+    ENSURE_( alsa_snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_ENABLE ), paUnanticipatedHostError );
+
+    /* Set the parameters! */
+    ENSURE_( alsa_snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError );
+
+error:
+    return result;
+}
+
+static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams,
+        const PaStreamParameters *outParams, double sampleRate, unsigned long framesPerUserBuffer, PaStreamCallback callback,
+        PaStreamFlags streamFlags, void *userData )
+{
+    PaError result = paNoError;
+    assert( self );
+
+    memset( self, 0, sizeof( PaAlsaStream ) );
+
+    if( NULL != callback )
+    {
+        PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+                                               &alsaApi->callbackStreamInterface,
+                                               callback, userData );
+        self->callbackMode = 1;
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+                                               &alsaApi->blockingStreamInterface,
+                                               NULL, userData );
+    }
+
+    self->framesPerUserBuffer = framesPerUserBuffer;
+    self->neverDropInput = streamFlags & paNeverDropInput;
+    /* XXX: Ignore paPrimeOutputBuffersUsingStreamCallback untill buffer priming is fully supported in pa_process.c */
+    /*
+    if( outParams & streamFlags & paPrimeOutputBuffersUsingStreamCallback )
+        self->primeBuffers = 1;
+        */
+    memset( &self->capture, 0, sizeof (PaAlsaStreamComponent) );
+    memset( &self->playback, 0, sizeof (PaAlsaStreamComponent) );
+    if( inParams )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback ) );
+    }
+    if( outParams )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->playback, alsaApi, outParams, StreamDirection_Out, NULL != callback ) );
+    }
+
+    assert( self->capture.nfds || self->playback.nfds );
+
+    PA_UNLESS( self->pfds = (struct pollfd*)PaUtil_AllocateMemory( ( self->capture.nfds +
+                    self->playback.nfds ) * sizeof( struct pollfd ) ), paInsufficientMemory );
+
+    PaUtil_InitializeCpuLoadMeasurer( &self->cpuLoadMeasurer, sampleRate );
+    ASSERT_CALL_( PaUnixMutex_Initialize( &self->stateMtx ), paNoError );
+
+error:
+    return result;
+}
+
+/** Free resources associated with stream, and eventually stream itself.
+ *
+ * Frees allocated memory, and terminates individual StreamComponents.
+ */
+static void PaAlsaStream_Terminate( PaAlsaStream *self )
+{
+    assert( self );
+
+    if( self->capture.pcm )
+    {
+        PaAlsaStreamComponent_Terminate( &self->capture );
+    }
+    if( self->playback.pcm )
+    {
+        PaAlsaStreamComponent_Terminate( &self->playback );
+    }
+
+    PaUtil_FreeMemory( self->pfds );
+    ASSERT_CALL_( PaUnixMutex_Terminate( &self->stateMtx ), paNoError );
+
+    PaUtil_FreeMemory( self );
+}
+
+/** Calculate polling timeout
+ *
+ * @param frames Time to wait
+ * @return Polling timeout in milliseconds
+ */
+static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frames )
+{
+    assert( stream->streamRepresentation.streamInfo.sampleRate > 0.0 );
+    /* Period in msecs, rounded up */
+    return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate );
+}
+
+/** Align value in backward direction.
+ *
+ * @param v: Value to align.
+ * @param align: Alignment.
+ */
+static unsigned long PaAlsa_AlignBackward(unsigned long v, unsigned long align)
+{
+    return ( v - ( align ? v % align : 0 ) );
+}
+
+/** Align value in forward direction.
+ *
+ * @param v: Value to align.
+ * @param align: Alignment.
+ */
+static unsigned long PaAlsa_AlignForward(unsigned long v, unsigned long align)
+{
+    unsigned long remainder = ( align ? ( v % align ) : 0);
+    return ( remainder != 0 ? v + ( align - remainder ) : v );
+}
+
+/** Get size of host buffer maintained from the number of user frames, sample rate and suggested latency. Minimum double buffering
+ *  is maintained to allow 100% CPU usage inside user callback.
+ *
+ * @param userFramesPerBuffer: User buffer size in number of frames.
+ * @param suggestedLatency: User provided desired latency.
+ * @param sampleRate: Sample rate.
+ */
+static unsigned long PaAlsa_GetFramesPerHostBuffer(unsigned long userFramesPerBuffer, PaTime suggestedLatency, double sampleRate)
+{
+    unsigned long frames = userFramesPerBuffer + PA_MAX( userFramesPerBuffer, (unsigned long)( suggestedLatency * sampleRate ) );
+    return frames;
+}
+
+/** Determine size per host buffer.
+ *
+ * During this method call, the component's framesPerPeriod attribute gets computed, and the corresponding period size
+ * gets configured for the device.
+ * @param accurate: If the configured period size is non-integer, this will be set to 0.
+ */
+static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamComponent* self, const PaStreamParameters* params,
+        unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate )
+{
+    PaError result = paNoError;
+    unsigned long bufferSize, framesPerHostBuffer;
+    int dir = 0;
+
+    /* Calculate host buffer size */
+    bufferSize = PaAlsa_GetFramesPerHostBuffer(framesPerUserBuffer, params->suggestedLatency, sampleRate);
+
+    /* Log */
+    PA_DEBUG(( "%s: user-buffer (frames)           = %lu\n", __FUNCTION__, framesPerUserBuffer ));
+    PA_DEBUG(( "%s: user-buffer (sec)              = %f\n",  __FUNCTION__, (double)(framesPerUserBuffer / sampleRate) ));
+    PA_DEBUG(( "%s: suggested latency (sec)        = %f\n",  __FUNCTION__, params->suggestedLatency ));
+    PA_DEBUG(( "%s: suggested host buffer (frames) = %lu\n", __FUNCTION__, bufferSize ));
+    PA_DEBUG(( "%s: suggested host buffer (sec)    = %f\n",  __FUNCTION__, (double)(bufferSize / sampleRate) ));
+
+#ifdef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
+
+    if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+    {
+        /* Preferably the host buffer size should be a multiple of the user buffer size */
+
+        if( bufferSize > framesPerUserBuffer )
+        {
+            snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer;
+            if( remainder > framesPerUserBuffer / 2. )
+                bufferSize += framesPerUserBuffer - remainder;
+            else
+                bufferSize -= remainder;
+
+            assert( bufferSize % framesPerUserBuffer == 0 );
+        }
+        else if( framesPerUserBuffer % bufferSize != 0 )
+        {
+            /*  Find a good compromise between user specified latency and buffer size */
+            if( bufferSize > framesPerUserBuffer * .75 )
+            {
+                bufferSize = framesPerUserBuffer;
+            }
+            else
+            {
+                snd_pcm_uframes_t newSz = framesPerUserBuffer;
+                while( newSz / 2 >= bufferSize )
+                {
+                    if( framesPerUserBuffer % (newSz / 2) != 0 )
+                    {
+                        /* No use dividing any further */
+                        break;
+                    }
+                    newSz /= 2;
+                }
+                bufferSize = newSz;
+            }
+
+            assert( framesPerUserBuffer % bufferSize == 0 );
+        }
+    }
+
+#endif
+
+    {
+        unsigned numPeriods = numPeriods_, maxPeriods = 0, minPeriods = numPeriods_;
+
+        /* It may be that the device only supports 2 periods for instance */
+        dir = 0;
+        ENSURE_( alsa_snd_pcm_hw_params_get_periods_min( hwParams, &minPeriods, &dir ), paUnanticipatedHostError );
+        ENSURE_( alsa_snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError );
+        assert( maxPeriods > 1 );
+
+        /* Clamp to min/max */
+        numPeriods = PA_MIN(maxPeriods, PA_MAX(minPeriods, numPeriods));
+
+        PA_DEBUG(( "%s: periods min = %lu, max = %lu, req = %lu \n", __FUNCTION__, minPeriods, maxPeriods, numPeriods ));
+
+#ifndef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
+
+        /* Calculate period size */
+        framesPerHostBuffer = (bufferSize / numPeriods);
+
+        /* Align & test size */
+        if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+        {
+            /* Align to user buffer size */
+            framesPerHostBuffer = PaAlsa_AlignForward(framesPerHostBuffer, framesPerUserBuffer);
+
+            /* Test (borrowed from older implementation) */
+            if( framesPerHostBuffer < framesPerUserBuffer )
+            {
+                assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
+                if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
+                        framesPerHostBuffer *= 2;
+                    else if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
+                        framesPerHostBuffer /= 2;
+                }
+            }
+            else
+            {
+                assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
+                if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer += framesPerUserBuffer;
+                    else if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer -= framesPerUserBuffer;
+                }
+            }
+        }
+#endif
+
+#ifdef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
+
+        if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+        {
+            /* Try to get a power-of-two of the user buffer size. */
+            framesPerHostBuffer = framesPerUserBuffer;
+            if( framesPerHostBuffer < bufferSize )
+            {
+                while( bufferSize / framesPerHostBuffer > numPeriods )
+                {
+                    framesPerHostBuffer *= 2;
+                }
+                /* One extra period is preferrable to one less (should be more robust) */
+                if( bufferSize / framesPerHostBuffer < numPeriods )
+                {
+                    framesPerHostBuffer /= 2;
+                }
+            }
+            else
+            {
+                while( bufferSize / framesPerHostBuffer < numPeriods )
+                {
+                    if( framesPerUserBuffer % ( framesPerHostBuffer / 2 ) != 0 )
+                    {
+                        /* Can't be divided any further */
+                        break;
+                    }
+                    framesPerHostBuffer /= 2;
+                }
+            }
+
+            if( framesPerHostBuffer < framesPerUserBuffer )
+            {
+                assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
+                if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
+                        framesPerHostBuffer *= 2;
+                    else if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
+                        framesPerHostBuffer /= 2;
+                }
+            }
+            else
+            {
+                assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
+                if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer += framesPerUserBuffer;
+                    else if( alsa_snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer -= framesPerUserBuffer;
+                }
+            }
+        }
+        else
+        {
+            framesPerHostBuffer = bufferSize / numPeriods;
+        }
+
+        /* non-mmap mode needs a reasonably-sized buffer or it'll stutter */
+        if( !self->canMmap && framesPerHostBuffer < 2048 )
+            framesPerHostBuffer = 2048;
+#endif
+        PA_DEBUG(( "%s: suggested host buffer period   = %lu \n", __FUNCTION__, framesPerHostBuffer ));
+    }
+
+    {
+        /* Get min/max period sizes and adjust our chosen */
+        snd_pcm_uframes_t min = 0, max = 0, minmax_diff;
+        ENSURE_( alsa_snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError );
+        ENSURE_( alsa_snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError );
+        minmax_diff = max - min;
+
+        if( framesPerHostBuffer < min )
+        {
+            PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__, framesPerHostBuffer, min ));
+            framesPerHostBuffer = (( minmax_diff == 2 ) ? min + 1 : min );
+        }
+        else if( framesPerHostBuffer > max )
+        {
+            PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__, framesPerHostBuffer, max ));
+            framesPerHostBuffer = (( minmax_diff == 2 ) ? max - 1 : max );
+        }
+
+        PA_DEBUG(( "%s: device period minimum          = %lu\n", __FUNCTION__, min ));
+        PA_DEBUG(( "%s: device period maximum          = %lu\n", __FUNCTION__, max ));
+        PA_DEBUG(( "%s: host buffer period             = %lu\n", __FUNCTION__, framesPerHostBuffer ));
+        PA_DEBUG(( "%s: host buffer period latency     = %f\n", __FUNCTION__, (double)( framesPerHostBuffer / sampleRate ) ));
+
+        /* Try setting period size */
+        dir = 0;
+        ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ), paUnanticipatedHostError );
+        if( dir != 0 )
+        {
+            PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir ));
+            *accurate = 0;
+        }
+    }
+
+    /* Set result */
+    self->framesPerPeriod = framesPerHostBuffer;
+
+error:
+    return result;
+}
+
+/* We need to determine how many frames per host buffer (period) to use.  Our
+ * goals are to provide the best possible performance, but also to
+ * honor the requested latency settings as closely as we can. Therefore this
+ * decision is based on:
+ *
+ *   - the period sizes that playback and/or capture support.  The
+ *     host buffer size has to be one of these.
+ *   - the number of periods that playback and/or capture support.
+ *
+ * We want to make period_size*(num_periods-1) to be as close as possible
+ * to latency*rate for both playback and capture.
+ *
+ * This method will determine suitable period sizes for capture and playback handles, and report the maximum number of
+ * frames per host buffer. The latter is relevant, in case we should be so unfortunate that the period size differs
+ * between capture and playback. If this should happen, the stream's hostBufferSizeMode attribute will be set to
+ * paUtilBoundedHostBufferSize, because the best we can do is limit the size of individual host buffers to the upper
+ * bound. The size of host buffers scheduled for processing should only matter if the user has specified a buffer size,
+ * but when he/she does we must strive for an optimal configuration. By default we'll opt for a fixed host buffer size,
+ * which should be fine if the period size is the same for capture and playback. In general, if there is a specified user
+ * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size.
+ *
+ * The framesPerPeriod attributes of the individual capture and playback components of the stream are set to corresponding
+ * values determined here. Since these should be reported as
+ *
+ * This is one of those blocks of code that will just take a lot of
+ * refinement to be any good.
+ *
+ * In the full-duplex case it is possible that the routine was unable
+ * to find a number of frames per buffer acceptable to both devices
+ * TODO: Implement an algorithm to find the value closest to acceptance
+ * by both devices, to minimize difference between period sizes?
+ *
+ * @param determinedFramesPerHostBuffer: The determined host buffer size.
+ */
+static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double sampleRate, const PaStreamParameters* inputParameters,
+        const PaStreamParameters* outputParameters, unsigned long framesPerUserBuffer, snd_pcm_hw_params_t* hwParamsCapture,
+        snd_pcm_hw_params_t* hwParamsPlayback, PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+    PaError result = paNoError;
+    unsigned long framesPerHostBuffer = 0;
+    int dir = 0;
+    int accurate = 1;
+    unsigned numPeriods = numPeriods_;
+
+    if( self->capture.pcm && self->playback.pcm )
+    {
+        if( framesPerUserBuffer == paFramesPerBufferUnspecified )
+        {
+            /* Come up with a common desired latency */
+            snd_pcm_uframes_t desiredBufSz, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize,
+                              minCapture, minPlayback, maxCapture, maxPlayback;
+
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError );
+            minPeriodSize = PA_MAX( minPlayback, minCapture );
+            maxPeriodSize = PA_MIN( maxPlayback, maxCapture );
+            PA_UNLESS( minPeriodSize <= maxPeriodSize, paBadIODeviceCombination );
+
+            desiredBufSz = (snd_pcm_uframes_t)( PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency )
+                    * sampleRate );
+            /* Clamp desiredBufSz */
+            {
+                snd_pcm_uframes_t maxBufferSize;
+                snd_pcm_uframes_t maxBufferSizeCapture, maxBufferSizePlayback;
+                ENSURE_( alsa_snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &maxBufferSizeCapture ), paUnanticipatedHostError );
+                ENSURE_( alsa_snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSizePlayback ), paUnanticipatedHostError );
+                maxBufferSize = PA_MIN( maxBufferSizeCapture, maxBufferSizePlayback );
+
+                desiredBufSz = PA_MIN( desiredBufSz, maxBufferSize );
+            }
+
+            /* Find the closest power of 2 */
+            e = ilogb( minPeriodSize );
+            if( minPeriodSize & ( minPeriodSize - 1 ) )
+                e += 1;
+            periodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+            while( periodSize <= maxPeriodSize )
+            {
+                if( alsa_snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 &&
+                        alsa_snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 )
+                {
+                    /* OK! */
+                    break;
+                }
+
+                periodSize *= 2;
+            }
+
+            optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize );
+            optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+            /* Find the closest power of 2 */
+            e = ilogb( optimalPeriodSize );
+            if( optimalPeriodSize & (optimalPeriodSize - 1) )
+                e += 1;
+            optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+            while( optimalPeriodSize >= periodSize )
+            {
+                if( alsa_snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 )
+                        >= 0 && alsa_snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback,
+                            optimalPeriodSize, 0 ) >= 0 )
+                {
+                    break;
+                }
+                optimalPeriodSize /= 2;
+            }
+
+            if( optimalPeriodSize > periodSize )
+                periodSize = optimalPeriodSize;
+
+            if( periodSize <= maxPeriodSize )
+            {
+                /* Looks good, the periodSize _should_ be acceptable by both devices */
+                ENSURE_( alsa_snd_pcm_hw_params_set_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ),
+                        paUnanticipatedHostError );
+                ENSURE_( alsa_snd_pcm_hw_params_set_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ),
+                        paUnanticipatedHostError );
+                self->capture.framesPerPeriod = self->playback.framesPerPeriod = periodSize;
+                framesPerHostBuffer = periodSize;
+            }
+            else
+            {
+                /* Unable to find a common period size, oh well */
+                optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize );
+                optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+                self->capture.framesPerPeriod = optimalPeriodSize;
+                dir = 0;
+                ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( self->capture.pcm, hwParamsCapture, &self->capture.framesPerPeriod, &dir ),
+                        paUnanticipatedHostError );
+                self->playback.framesPerPeriod = optimalPeriodSize;
+                dir = 0;
+                ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( self->playback.pcm, hwParamsPlayback, &self->playback.framesPerPeriod, &dir ),
+                        paUnanticipatedHostError );
+                framesPerHostBuffer = PA_MAX( self->capture.framesPerPeriod, self->playback.framesPerPeriod );
+                *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+            }
+        }
+        else
+        {
+            /* We choose the simple route and determine a suitable number of frames per buffer for one component of
+             * the stream, then we hope that this will work for the other component too (it should!).
+             */
+
+            unsigned maxPeriods = 0;
+            PaAlsaStreamComponent* first = &self->capture, * second = &self->playback;
+            const PaStreamParameters* firstStreamParams = inputParameters;
+            snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback;
+
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError );
+            if( maxPeriods < numPeriods )
+            {
+                /* The playback component is trickier to get right, try that first */
+                first = &self->playback;
+                second = &self->capture;
+                firstStreamParams = outputParameters;
+                firstHwParams = hwParamsPlayback;
+                secondHwParams = hwParamsCapture;
+            }
+
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer,
+                        sampleRate, firstHwParams, &accurate ) );
+
+            second->framesPerPeriod = first->framesPerPeriod;
+            dir = 0;
+            ENSURE_( alsa_snd_pcm_hw_params_set_period_size_near( second->pcm, secondHwParams, &second->framesPerPeriod, &dir ),
+                    paUnanticipatedHostError );
+            if( self->capture.framesPerPeriod == self->playback.framesPerPeriod )
+            {
+                framesPerHostBuffer = self->capture.framesPerPeriod;
+            }
+            else
+            {
+                framesPerHostBuffer = PA_MAX( self->capture.framesPerPeriod, self->playback.framesPerPeriod );
+                *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+            }
+        }
+    }
+    else    /* half-duplex is a slightly simpler case */
+    {
+        if( self->capture.pcm )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->capture, inputParameters, framesPerUserBuffer,
+                        sampleRate, hwParamsCapture, &accurate) );
+            framesPerHostBuffer = self->capture.framesPerPeriod;
+        }
+        else
+        {
+            assert( self->playback.pcm );
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->playback, outputParameters, framesPerUserBuffer,
+                        sampleRate, hwParamsPlayback, &accurate ) );
+            framesPerHostBuffer = self->playback.framesPerPeriod;
+        }
+    }
+
+    PA_UNLESS( framesPerHostBuffer != 0, paInternalError );
+    self->maxFramesPerHostBuffer = framesPerHostBuffer;
+
+    if( !self->playback.canMmap || !accurate )
+    {
+        /* Don't know the exact size per host buffer */
+        *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+        /* Raise upper bound */
+        if( !accurate )
+            ++self->maxFramesPerHostBuffer;
+    }
+
+error:
+    return result;
+}
+
+/** Set up ALSA stream parameters.
+ *
+ */
+static PaError PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters*
+        outParams, double sampleRate, unsigned long framesPerUserBuffer, double* inputLatency, double* outputLatency,
+        PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+    PaError result = paNoError;
+    double realSr = sampleRate;
+    snd_pcm_hw_params_t* hwParamsCapture, * hwParamsPlayback;
+
+    alsa_snd_pcm_hw_params_alloca( &hwParamsCapture );
+    alsa_snd_pcm_hw_params_alloca( &hwParamsPlayback );
+
+    if( self->capture.pcm )
+        PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->capture, inParams, self->primeBuffers, hwParamsCapture,
+                    &realSr ) );
+    if( self->playback.pcm )
+        PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback,
+                    &realSr ) );
+
+    PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer,
+                hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) );
+
+    if( self->capture.pcm )
+    {
+        assert( self->capture.framesPerPeriod != 0 );
+        PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->capture, hwParamsCapture, inParams, self->primeBuffers, realSr,
+                    inputLatency ) );
+        PA_DEBUG(( "%s: Capture period size: %lu, latency: %f\n", __FUNCTION__, self->capture.framesPerPeriod, *inputLatency ));
+    }
+    if( self->playback.pcm )
+    {
+        assert( self->playback.framesPerPeriod != 0 );
+        PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->playback, hwParamsPlayback, outParams, self->primeBuffers, realSr,
+                    outputLatency ) );
+        PA_DEBUG(( "%s: Playback period size: %lu, latency: %f\n", __FUNCTION__, self->playback.framesPerPeriod, *outputLatency ));
+    }
+
+    /* Should be exact now */
+    self->streamRepresentation.streamInfo.sampleRate = realSr;
+
+    /* this will cause the two streams to automatically start/stop/prepare in sync.
+     * We only need to execute these operations on one of the pair.
+     * A: We don't want to do this on a blocking stream.
+     */
+    if( self->callbackMode && self->capture.pcm && self->playback.pcm )
+    {
+        int err = alsa_snd_pcm_link( self->capture.pcm, self->playback.pcm );
+        if( err == 0 )
+            self->pcmsSynced = 1;
+        else
+            PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, alsa_snd_strerror( err ) ));
+    }
+
+    {
+        unsigned long minFramesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerPeriod : ULONG_MAX,
+            self->playback.pcm ? self->playback.framesPerPeriod : ULONG_MAX );
+        self->pollTimeout = CalculatePollTimeout( self, minFramesPerHostBuffer );    /* Period in msecs, rounded up */
+
+        /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */
+        /* self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); */
+    }
+
+    if( self->callbackMode )
+    {
+        /* If the user expects a certain number of frames per callback we will either have to rely on block adaption
+         * (framesPerHostBuffer is not an integer multiple of framesPerPeriod) or we can simply align the number
+         * of host buffer frames with what the user specified */
+        if( self->framesPerUserBuffer != paFramesPerBufferUnspecified )
+        {
+            /* self->alignFrames = 1; */
+
+            /* Unless the ratio between number of host and user buffer frames is an integer we will have to rely
+             * on block adaption */
+        /*
+            if( framesPerHostBuffer % framesPerPeriod != 0 || (self->capture.pcm && self->playback.pcm &&
+                        self->capture.framesPerPeriod != self->playback.framesPerPeriod) )
+                self->useBlockAdaption = 1;
+            else
+                self->alignFrames = 1;
+        */
+        }
+    }
+
+error:
+    return result;
+}
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback* callback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+    PaAlsaStream *stream = NULL;
+    PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0;
+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+    int numInputChannels = 0, numOutputChannels = 0;
+    PaTime inputLatency, outputLatency;
+    /* Operate with fixed host buffer size by default, since other modes will invariably lead to block adaption */
+    /* XXX: Use Bounded by default? Output tends to get stuttery with Fixed ... */
+    PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilFixedHostBufferSize;
+
+    if( ( streamFlags & paPlatformSpecificFlags ) != 0 )
+        return paInvalidFlag;
+
+    if( inputParameters )
+    {
+        PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+        numInputChannels = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+    }
+    if( outputParameters )
+    {
+        PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+        numOutputChannels = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+    }
+
+    /* XXX: Why do we support this anyway? */
+    if( framesPerBuffer == paFramesPerBufferUnspecified && getenv( "PA_ALSA_PERIODSIZE" ) != NULL )
+    {
+        PA_DEBUG(( "%s: Getting framesPerBuffer (Alsa period-size) from environment\n", __FUNCTION__ ));
+        framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") );
+    }
+
+    PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory );
+    PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate,
+                framesPerBuffer, callback, streamFlags, userData ) );
+
+    PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer,
+                &inputLatency, &outputLatency, &hostBufferSizeMode ) );
+    hostInputSampleFormat = stream->capture.hostSampleFormat | (!stream->capture.hostInterleaved ? paNonInterleaved : 0);
+    hostOutputSampleFormat = stream->playback.hostSampleFormat | (!stream->playback.hostInterleaved ? paNonInterleaved : 0);
+
+    PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                    numInputChannels, inputSampleFormat, hostInputSampleFormat,
+                    numOutputChannels, outputSampleFormat, hostOutputSampleFormat,
+                    sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer,
+                    hostBufferSizeMode, callback, userData ) );
+
+    /* Ok, buffer processor is initialized, now we can deduce it's latency */
+    if( numInputChannels > 0 )
+        stream->streamRepresentation.streamInfo.inputLatency = inputLatency + (PaTime)(
+                PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor ) / sampleRate);
+    if( numOutputChannels > 0 )
+        stream->streamRepresentation.streamInfo.outputLatency = outputLatency + (PaTime)(
+                PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor ) / sampleRate);
+
+    PA_DEBUG(( "%s: Stream: framesPerBuffer = %lu, maxFramesPerHostBuffer = %lu, latency i=%f, o=%f\n", __FUNCTION__, framesPerBuffer, stream->maxFramesPerHostBuffer, stream->streamRepresentation.streamInfo.inputLatency, stream->streamRepresentation.streamInfo.outputLatency));
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( stream )
+    {
+        PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ ));
+        PaAlsaStream_Terminate( stream );
+    }
+
+    return result;
+}
+
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+    PaAlsaStream_Terminate( stream );
+
+    return result;
+}
+
+static void SilenceBuffer( PaAlsaStream *stream )
+{
+    const snd_pcm_channel_area_t *areas;
+    snd_pcm_uframes_t frames = (snd_pcm_uframes_t)alsa_snd_pcm_avail_update( stream->playback.pcm ), offset;
+
+    alsa_snd_pcm_mmap_begin( stream->playback.pcm, &areas, &offset, &frames );
+    alsa_snd_pcm_areas_silence( areas, offset, stream->playback.numHostChannels, frames, stream->playback.nativeFormat );
+    alsa_snd_pcm_mmap_commit( stream->playback.pcm, offset, frames );
+}
+
+/** Start/prepare pcm(s) for streaming.
+ *
+ * Depending on whether the stream is in callback or blocking mode, we will respectively start or simply
+ * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and
+ * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will
+ * be started automatically as the user writes to output.
+ *
+ * The capture pcm, however, will simply be prepared and started.
+ */
+static PaError AlsaStart( PaAlsaStream *stream, int priming )
+{
+    PaError result = paNoError;
+
+    if( stream->playback.pcm )
+    {
+        if( stream->callbackMode )
+        {
+            if( !priming )
+            {
+                /* Buffer isn't primed, so prepare and silence */
+                ENSURE_( alsa_snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+                if( stream->playback.canMmap )
+                    SilenceBuffer( stream );
+            }
+            if( stream->playback.canMmap )
+                ENSURE_( alsa_snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+        else
+            ENSURE_( alsa_snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+    }
+    if( stream->capture.pcm && !stream->pcmsSynced )
+    {
+        ENSURE_( alsa_snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+        /* For a blocking stream we want to start capture as well, since nothing will happen otherwise */
+        ENSURE_( alsa_snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+    }
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Utility function for determining if pcms are in running state.
+ *
+ */
+#if 0
+static int IsRunning( PaAlsaStream *stream )
+{
+    int result = 0;
+
+    PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+    if( stream->capture.pcm )
+    {
+        snd_pcm_state_t capture_state = alsa_snd_pcm_state( stream->capture.pcm );
+
+        if( capture_state == SND_PCM_STATE_RUNNING || capture_state == SND_PCM_STATE_XRUN
+                || capture_state == SND_PCM_STATE_DRAINING )
+        {
+            result = 1;
+            goto end;
+        }
+    }
+
+    if( stream->playback.pcm )
+    {
+        snd_pcm_state_t playback_state = alsa_snd_pcm_state( stream->playback.pcm );
+
+        if( playback_state == SND_PCM_STATE_RUNNING || playback_state == SND_PCM_STATE_XRUN
+                || playback_state == SND_PCM_STATE_DRAINING )
+        {
+            result = 1;
+            goto end;
+        }
+    }
+
+end:
+    ASSERT_CALL_( PaUnixMutex_Unlock( &stream->stateMtx ), paNoError );
+    return result;
+error:
+    goto error;
+}
+#endif
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAlsaStream* stream = (PaAlsaStream*)s;
+    int streamStarted = 0;  /* So we can know whether we need to take the stream down */
+
+    /* Ready the processor */
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    /* Set now, so we can test for activity further down */
+    stream->isActive = 1;
+
+    if( stream->callbackMode )
+    {
+        PA_ENSURE( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., stream->rtSched ) );
+    }
+    else
+    {
+        PA_ENSURE( AlsaStart( stream, 0 ) );
+        streamStarted = 1;
+    }
+
+end:
+    return result;
+error:
+    if( streamStarted )
+    {
+        AbortStream( stream );
+    }
+    stream->isActive = 0;
+
+    goto end;
+}
+
+/** Stop PCM handle, either softly or abruptly.
+ */
+static PaError AlsaStop( PaAlsaStream *stream, int abort )
+{
+    PaError result = paNoError;
+    /* XXX: alsa_snd_pcm_drain tends to lock up, avoid it until we find out more */
+    abort = 1;
+    /*
+    if( stream->capture.pcm && !strcmp( Pa_GetDeviceInfo( stream->capture.device )->name,
+                "dmix" ) )
+    {
+        abort = 1;
+    }
+    else if( stream->playback.pcm && !strcmp( Pa_GetDeviceInfo( stream->playback.device )->name,
+                "dmix" ) )
+    {
+        abort = 1;
+    }
+    */
+
+    if( abort )
+    {
+        if( stream->playback.pcm )
+        {
+            ENSURE_( alsa_snd_pcm_drop( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+        if( stream->capture.pcm && !stream->pcmsSynced )
+        {
+            ENSURE_( alsa_snd_pcm_drop( stream->capture.pcm ), paUnanticipatedHostError );
+        }
+
+        PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ ));
+    }
+    else
+    {
+        if( stream->playback.pcm )
+        {
+            ENSURE_( alsa_snd_pcm_nonblock( stream->playback.pcm, 0 ), paUnanticipatedHostError );
+            if( alsa_snd_pcm_drain( stream->playback.pcm ) < 0 )
+            {
+                PA_DEBUG(( "%s: Draining playback handle failed!\n", __FUNCTION__ ));
+            }
+        }
+        if( stream->capture.pcm && !stream->pcmsSynced )
+        {
+            /* We don't need to retrieve any remaining frames */
+            if( alsa_snd_pcm_drain( stream->capture.pcm ) < 0 )
+            {
+                PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ ));
+            }
+        }
+    }
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Stop or abort stream.
+ *
+ * If a stream is in callback mode we will have to inspect whether the background thread has
+ * finished, or we will have to take it out. In either case we join the thread before
+ * returning. In blocking mode, we simply tell ALSA to stop abruptly (abort) or finish
+ * buffers (drain)
+ *
+ * Stream will be considered inactive (!PaAlsaStream::isActive) after a call to this function
+ */
+static PaError RealStop( PaAlsaStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    /* First deal with the callback thread, cancelling and/or joining
+     * it if necessary
+     */
+    if( stream->callbackMode )
+    {
+        PaError threadRes;
+        stream->callbackAbort = abort;
+
+        if( !abort )
+        {
+            PA_DEBUG(( "Stopping callback\n" ));
+        }
+        PA_ENSURE( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) );
+        if( threadRes != paNoError )
+        {
+            PA_DEBUG(( "Callback thread returned: %d\n", threadRes ));
+        }
+#if 0
+        if( watchdogRes != paNoError )
+            PA_DEBUG(( "Watchdog thread returned: %d\n", watchdogRes ));
+#endif
+
+        stream->callback_finished = 0;
+    }
+    else
+    {
+        PA_ENSURE( AlsaStop( stream, abort ) );
+    }
+
+    stream->isActive = 0;
+
+end:
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError StopStream( PaStream *s )
+{
+    return RealStop( (PaAlsaStream *) s, 0 );
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    return RealStop( (PaAlsaStream * ) s, 1 );
+}
+
+/** The stream is considered stopped before StartStream, or AFTER a call to Abort/StopStream (callback
+ * returning !paContinue is not considered)
+ *
+ */
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream *)s;
+
+    /* callback_finished indicates we need to join callback thread (ie. in Abort/StopStream) */
+    return !IsStreamActive( s ) && !stream->callback_finished;
+}
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    return stream->isActive;
+}
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    snd_timestamp_t timestamp;
+    snd_pcm_status_t* status;
+    alsa_snd_pcm_status_alloca( &status );
+
+    /* TODO: what if we have both?  does it really matter? */
+
+    /* TODO: if running in callback mode, this will mean
+     * libasound routines are being called from multiple threads.
+     * need to verify that libasound is thread-safe. */
+
+    if( stream->capture.pcm )
+    {
+        alsa_snd_pcm_status( stream->capture.pcm, status );
+    }
+    else if( stream->playback.pcm )
+    {
+        alsa_snd_pcm_status( stream->playback.pcm, status );
+    }
+
+    alsa_snd_pcm_status_get_tstamp( status, &timestamp );
+    return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6;
+}
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+/* Set the stream sample rate to a nominal value requested; allow only a defined tolerance range */
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate )
+{
+    PaError result = paNoError;
+    unsigned int reqRate, setRate, deviation;
+
+    assert( pcm && hwParams );
+
+    /* The Alsa sample rate is set by integer value; also the actual rate may differ */
+    reqRate = setRate = (unsigned int) sampleRate;
+
+    ENSURE_( alsa_snd_pcm_hw_params_set_rate_near( pcm, hwParams, &setRate, NULL ), paUnanticipatedHostError );
+    /* The value actually set will be put in 'setRate' (may be way off); check the deviation as a proportion
+     * of the requested-rate with reference to the max-deviate-ratio (larger values allow less deviation) */
+    deviation = abs( setRate - reqRate );
+    if( deviation > 0 && deviation * RATE_MAX_DEVIATE_RATIO > reqRate )
+        result = paInvalidSampleRate;
+
+end:
+    return result;
+
+error:
+    /* Log */
+    {
+        unsigned int _min = 0, _max = 0;
+        int _dir = 0;
+        ENSURE_( alsa_snd_pcm_hw_params_get_rate_min( hwParams, &_min, &_dir ), paUnanticipatedHostError );
+        ENSURE_( alsa_snd_pcm_hw_params_get_rate_max( hwParams, &_max, &_dir ), paUnanticipatedHostError );
+        PA_DEBUG(( "%s: SR min = %u, max = %u, req = %u\n", __FUNCTION__, _min, _max, reqRate ));
+    }
+    goto end;
+}
+
+/* Return exact sample rate in param sampleRate */
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+    unsigned int num, den = 1;
+    int err;
+
+    assert( hwParams );
+
+    err = alsa_snd_pcm_hw_params_get_rate_numden( hwParams, &num, &den );
+    *sampleRate = (double) num / den;
+
+    return err;
+}
+
+/* Utility functions for blocking/callback interfaces */
+
+/* Atomic restart of stream (we don't want the intermediate state visible) */
+static PaError AlsaRestart( PaAlsaStream *stream )
+{
+    PaError result = paNoError;
+
+    PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+    PA_ENSURE( AlsaStop( stream, 0 ) );
+    PA_ENSURE( AlsaStart( stream, 0 ) );
+
+    PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ ));
+
+error:
+    PA_ENSURE( PaUnixMutex_Unlock( &stream->stateMtx ) );
+
+    return result;
+}
+
+/** Recover from xrun state.
+ *
+ */
+static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
+{
+    PaError result = paNoError;
+    snd_pcm_status_t *st;
+    PaTime now = PaUtil_GetTime();
+    snd_timestamp_t t;
+    int restartAlsa = 0; /* do not restart Alsa by default */
+
+    alsa_snd_pcm_status_alloca( &st );
+
+    if( self->playback.pcm )
+    {
+        alsa_snd_pcm_status( self->playback.pcm, st );
+        if( alsa_snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+        {
+            alsa_snd_pcm_status_get_trigger_tstamp( st, &t );
+            self->underrun = now * 1000 - ( (PaTime)t.tv_sec * 1000 + (PaTime)t.tv_usec / 1000 );
+
+            if( !self->playback.canMmap )
+            {
+                if( alsa_snd_pcm_recover( self->playback.pcm, -EPIPE, 0 ) < 0 )
+                {
+                    PA_DEBUG(( "%s: [playback] non-MMAP-PCM failed recovering from XRUN, will restart Alsa\n", __FUNCTION__ ));
+                    ++ restartAlsa; /* did not manage to recover */
+                }
+            }
+            else
+                ++ restartAlsa; /* always restart MMAPed device */
+        }
+    }
+    if( self->capture.pcm )
+    {
+        alsa_snd_pcm_status( self->capture.pcm, st );
+        if( alsa_snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+        {
+            alsa_snd_pcm_status_get_trigger_tstamp( st, &t );
+            self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
+
+            if (!self->capture.canMmap)
+            {
+                if (alsa_snd_pcm_recover( self->capture.pcm, -EPIPE, 0 ) < 0)
+                {
+                    PA_DEBUG(( "%s: [capture] non-MMAP-PCM failed recovering from XRUN, will restart Alsa\n", __FUNCTION__ ));
+                    ++ restartAlsa; /* did not manage to recover */
+                }
+            }
+            else
+                ++ restartAlsa; /* always restart MMAPed device */
+        }
+    }
+
+    if( restartAlsa )
+    {
+        PA_DEBUG(( "%s: restarting Alsa to recover from XRUN\n", __FUNCTION__ ));
+        PA_ENSURE( AlsaRestart( self ) );
+    }
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Decide if we should continue polling for specified direction, eventually adjust the poll timeout.
+ *
+ */
+static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll )
+{
+    PaError result = paNoError;
+    snd_pcm_sframes_t delay, margin;
+    int err;
+    const PaAlsaStreamComponent *component = NULL, *otherComponent = NULL;
+
+    *continuePoll = 1;
+
+    if( StreamDirection_In == streamDir )
+    {
+        component = &stream->capture;
+        otherComponent = &stream->playback;
+    }
+    else
+    {
+        component = &stream->playback;
+        otherComponent = &stream->capture;
+    }
+
+    /* ALSA docs say that negative delay should indicate xrun, but in my experience alsa_snd_pcm_delay returns -EPIPE */
+    if( ( err = alsa_snd_pcm_delay( otherComponent->pcm, &delay ) ) < 0 )
+    {
+        if( err == -EPIPE )
+        {
+            /* Xrun */
+            *continuePoll = 0;
+            goto error;
+        }
+
+        ENSURE_( err, paUnanticipatedHostError );
+    }
+
+    if( StreamDirection_Out == streamDir )
+    {
+        /* Number of eligible frames before capture overrun */
+        delay = otherComponent->alsaBufferSize - delay;
+    }
+    margin = delay - otherComponent->framesPerPeriod / 2;
+
+    if( margin < 0 )
+    {
+        PA_DEBUG(( "%s: Stopping poll for %s\n", __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback" ));
+        *continuePoll = 0;
+    }
+    else if( margin < otherComponent->framesPerPeriod )
+    {
+        *pollTimeout = CalculatePollTimeout( stream, margin );
+        PA_DEBUG(( "%s: Trying to poll again for %s frames, pollTimeout: %d\n",
+                    __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback", *pollTimeout ));
+    }
+
+error:
+    return result;
+}
+
+/* Callback interface */
+
+static void OnExit( void *data )
+{
+    PaAlsaStream *stream = (PaAlsaStream *) data;
+
+    assert( data );
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+    stream->callback_finished = 1;  /* Let the outside world know stream was stopped in callback */
+    PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ ));
+    AlsaStop( stream, stream->callbackAbort );
+
+    PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
+
+    /* Eventually notify user all buffers have played */
+    if( stream->streamRepresentation.streamFinishedCallback )
+    {
+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+    stream->isActive = 0;
+}
+
+static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *timeInfo )
+{
+    snd_pcm_status_t *capture_status, *playback_status;
+    snd_timestamp_t capture_timestamp, playback_timestamp;
+    PaTime capture_time = 0., playback_time = 0.;
+
+    alsa_snd_pcm_status_alloca( &capture_status );
+    alsa_snd_pcm_status_alloca( &playback_status );
+
+    if( stream->capture.pcm )
+    {
+        snd_pcm_sframes_t capture_delay;
+
+        alsa_snd_pcm_status( stream->capture.pcm, capture_status );
+        alsa_snd_pcm_status_get_tstamp( capture_status, &capture_timestamp );
+
+        capture_time = capture_timestamp.tv_sec +
+            ( (PaTime)capture_timestamp.tv_usec / 1000000.0 );
+        timeInfo->currentTime = capture_time;
+
+        capture_delay = alsa_snd_pcm_status_get_delay( capture_status );
+        timeInfo->inputBufferAdcTime = timeInfo->currentTime -
+            (PaTime)capture_delay / stream->streamRepresentation.streamInfo.sampleRate;
+    }
+    if( stream->playback.pcm )
+    {
+        snd_pcm_sframes_t playback_delay;
+
+        alsa_snd_pcm_status( stream->playback.pcm, playback_status );
+        alsa_snd_pcm_status_get_tstamp( playback_status, &playback_timestamp );
+
+        playback_time = playback_timestamp.tv_sec +
+            ((PaTime)playback_timestamp.tv_usec / 1000000.0);
+
+        if( stream->capture.pcm ) /* Full duplex */
+        {
+            /* Hmm, we have both a playback and a capture timestamp.
+             * Hopefully they are the same... */
+            if( fabs( capture_time - playback_time ) > 0.01 )
+                PA_DEBUG(( "Capture time and playback time differ by %f\n", fabs( capture_time-playback_time ) ));
+        }
+        else
+            timeInfo->currentTime = playback_time;
+
+        playback_delay = alsa_snd_pcm_status_get_delay( playback_status );
+        timeInfo->outputBufferDacTime = timeInfo->currentTime +
+            (PaTime)playback_delay / stream->streamRepresentation.streamInfo.sampleRate;
+    }
+}
+
+/** Called after buffer processing is finished.
+ *
+ * A number of mmapped frames is committed, it is possible that an xrun has occurred in the meantime.
+ *
+ * @param numFrames The number of frames that has been processed
+ * @param xrun Return whether an xrun has occurred
+ */
+static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun )
+{
+    PaError result = paNoError;
+    int res = 0;
+
+    /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed
+     * afterwards
+     */
+    if( !self->ready )
+        goto end;
+
+    if( !self->canMmap && StreamDirection_Out == self->streamDir )
+    {
+        /* Play sound */
+        if( self->hostInterleaved )
+            res = alsa_snd_pcm_writei( self->pcm, self->nonMmapBuffer, numFrames );
+        else
+        {
+            void *bufs[self->numHostChannels];
+            int bufsize = alsa_snd_pcm_format_size( self->nativeFormat, self->framesPerPeriod + 1 );
+            unsigned char *buffer = self->nonMmapBuffer;
+            int i;
+            for( i = 0; i < self->numHostChannels; ++i )
+            {
+                bufs[i] = buffer;
+                buffer += bufsize;
+            }
+            res = alsa_snd_pcm_writen( self->pcm, bufs, numFrames );
+        }
+    }
+
+    if( self->canMmap )
+        res = alsa_snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
+
+    if( res == -EPIPE || res == -ESTRPIPE )
+    {
+        *xrun = 1;
+    }
+    else
+    {
+        ENSURE_( res, paUnanticipatedHostError );
+    }
+
+end:
+error:
+    return result;
+}
+
+/* Extract buffer from channel area */
+static unsigned char *ExtractAddress( const snd_pcm_channel_area_t *area, snd_pcm_uframes_t offset )
+{
+    return (unsigned char *) area->addr + ( area->first + offset * area->step ) / 8;
+}
+
+/** Do necessary adaption between user and host channels.
+ *
+    @concern ChannelAdaption Adapting between user and host channels can involve silencing unused channels and
+    duplicating mono information if host outputs come in pairs.
+ */
+static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *self, PaUtilBufferProcessor *bp, int numFrames )
+{
+    PaError result = paNoError;
+    unsigned char *p;
+    int i;
+    int unusedChans = self->numHostChannels - self->numUserChannels;
+    unsigned char *src, *dst;
+    int convertMono = ( self->numHostChannels % 2 ) == 0 && ( self->numUserChannels % 2 ) != 0;
+
+    assert( StreamDirection_Out == self->streamDir );
+
+    if( self->hostInterleaved )
+    {
+        int swidth = alsa_snd_pcm_format_size( self->nativeFormat, 1 );
+        unsigned char *buffer = self->canMmap ? ExtractAddress( self->channelAreas, self->offset ) : self->nonMmapBuffer;
+
+        /* Start after the last user channel */
+        p = buffer + self->numUserChannels * swidth;
+
+        if( convertMono )
+        {
+            /* Convert the last user channel into stereo pair */
+            src = buffer + ( self->numUserChannels - 1 ) * swidth;
+            for( i = 0; i < numFrames; ++i )
+            {
+                dst = src + swidth;
+                memcpy( dst, src, swidth );
+                src += self->numHostChannels * swidth;
+            }
+
+            /* Don't touch the channel we just wrote to */
+            p += swidth;
+            --unusedChans;
+        }
+
+        if( unusedChans > 0 )
+        {
+            /* Silence unused output channels */
+            for( i = 0; i < numFrames; ++i )
+            {
+                memset( p, 0, swidth * unusedChans );
+                p += self->numHostChannels * swidth;
+            }
+        }
+    }
+    else
+    {
+        /* We extract the last user channel */
+        if( convertMono )
+        {
+            ENSURE_( alsa_snd_pcm_area_copy( self->channelAreas + self->numUserChannels, self->offset, self->channelAreas +
+                    ( self->numUserChannels - 1 ), self->offset, numFrames, self->nativeFormat ), paUnanticipatedHostError );
+            --unusedChans;
+        }
+        if( unusedChans > 0 )
+        {
+            alsa_snd_pcm_areas_silence( self->channelAreas + ( self->numHostChannels - unusedChans ), self->offset, unusedChans, numFrames,
+                    self->nativeFormat );
+        }
+    }
+
+error:
+    return result;
+}
+
+static PaError PaAlsaStream_EndProcessing( PaAlsaStream *self, unsigned long numFrames, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    int xrun = 0;
+
+    if( self->capture.pcm )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->capture, numFrames, &xrun ) );
+    }
+    if( self->playback.pcm )
+    {
+        if( self->playback.numHostChannels > self->playback.numUserChannels )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_DoChannelAdaption( &self->playback, &self->bufferProcessor, numFrames ) );
+        }
+        PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->playback, numFrames, &xrun ) );
+    }
+
+error:
+    *xrunOccurred = xrun;
+    return result;
+}
+
+/** Update the number of available frames.
+ *
+ */
+static PaError PaAlsaStreamComponent_GetAvailableFrames( PaAlsaStreamComponent *self, unsigned long *numFrames, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    snd_pcm_sframes_t framesAvail = alsa_snd_pcm_avail_update( self->pcm );
+    *xrunOccurred = 0;
+
+    if( -EPIPE == framesAvail )
+    {
+        *xrunOccurred = 1;
+        framesAvail = 0;
+    }
+    else
+    {
+        ENSURE_( framesAvail, paUnanticipatedHostError );
+    }
+
+    *numFrames = framesAvail;
+
+error:
+    return result;
+}
+
+/** Fill in pollfd objects.
+ */
+static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent* self, struct pollfd* pfds )
+{
+    PaError result = paNoError;
+    int ret = alsa_snd_pcm_poll_descriptors( self->pcm, pfds, self->nfds );
+    (void)ret;  /* Prevent unused variable warning if asserts are turned off */
+    assert( ret == self->nfds );
+
+    self->ready = 0;
+
+    return result;
+}
+
+/** Examine results from poll().
+ *
+ * @param pfds pollfds to inspect
+ * @param shouldPoll Should we continue to poll
+ * @param xrun Has an xrun occurred
+ */
+static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun )
+{
+    PaError result = paNoError;
+    unsigned short revents;
+
+    ENSURE_( alsa_snd_pcm_poll_descriptors_revents( self->pcm, pfds, self->nfds, &revents ), paUnanticipatedHostError );
+    if( revents != 0 )
+    {
+        if( revents & POLLERR )
+        {
+            *xrun = 1;
+        }
+        else if( revents & POLLHUP )
+        {
+            *xrun = 1;
+            PA_DEBUG(( "%s: revents has POLLHUP, processing as XRUN\n", __FUNCTION__ ));
+        }
+        else
+            self->ready = 1;
+
+        *shouldPoll = 0;
+    }
+    else /* (A zero revent occurred) */
+        /* Work around an issue with Alsa older than 1.0.16 using some plugins (eg default with plug + dmix) where
+         * POLLIN or POLLOUT are zeroed by Alsa-lib if _mmap_avail() is a few frames short of avail_min at period
+         * boundary, possibly due to erratic dma interrupts at period boundary?  Treat as a valid event.
+         */
+        if( self->useReventFix )
+        {
+            self->ready = 1;
+            *shouldPoll = 0;
+        }
+
+error:
+    return result;
+}
+
+/** Return the number of available frames for this stream.
+ *
+ * @concern FullDuplex The minimum available for the two directions is calculated, it might be desirable to ignore
+ * one direction however (not marked ready from poll), so this is controlled by queryCapture and queryPlayback.
+ *
+ * @param queryCapture Check available for capture
+ * @param queryPlayback Check available for playback
+ * @param available The returned number of frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCapture, int queryPlayback, unsigned long
+        *available, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    unsigned long captureFrames, playbackFrames;
+    *xrunOccurred = 0;
+
+    assert( queryCapture || queryPlayback );
+
+    if( queryCapture )
+    {
+        assert( self->capture.pcm );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->capture, &captureFrames, xrunOccurred ) );
+        if( *xrunOccurred )
+        {
+            goto end;
+        }
+    }
+    if( queryPlayback )
+    {
+        assert( self->playback.pcm );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->playback, &playbackFrames, xrunOccurred ) );
+        if( *xrunOccurred )
+        {
+            goto end;
+        }
+    }
+
+    if( queryCapture && queryPlayback )
+    {
+        *available = PA_MIN( captureFrames, playbackFrames );
+        /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/
+    }
+    else if( queryCapture )
+    {
+        *available = captureFrames;
+    }
+    else
+    {
+        *available = playbackFrames;
+    }
+
+end:
+error:
+    return result;
+}
+
+/** Wait for and report available buffer space from ALSA.
+ *
+ * Unless ALSA reports a minimum of frames available for I/O, we poll the ALSA filedescriptors for more.
+ * Both of these operations can uncover xrun conditions.
+ *
+ * @concern Xruns Both polling and querying available frames can report an xrun condition.
+ *
+ * @param framesAvail Return the number of available frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL;
+    int pollTimeout = self->pollTimeout;
+    int xrun = 0, timeouts = 0;
+    int pollResults;
+
+    assert( self );
+    assert( framesAvail );
+
+    if( !self->callbackMode )
+    {
+        /* In blocking mode we will only wait if necessary */
+        PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, self->capture.pcm != NULL, self->playback.pcm != NULL,
+                    framesAvail, &xrun ) );
+        if( xrun )
+        {
+            goto end;
+        }
+
+        if( *framesAvail > 0 )
+        {
+            /* Mark pcms ready from poll */
+            if( self->capture.pcm )
+                self->capture.ready = 1;
+            if( self->playback.pcm )
+                self->playback.ready = 1;
+
+            goto end;
+        }
+    }
+
+    while( pollPlayback || pollCapture )
+    {
+        int totalFds = 0;
+        struct pollfd *capturePfds = NULL, *playbackPfds = NULL;
+
+#ifdef PTHREAD_CANCELED
+        pthread_testcancel();
+#endif
+        if( pollCapture )
+        {
+            capturePfds = self->pfds;
+            PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->capture, capturePfds ) );
+            totalFds += self->capture.nfds;
+        }
+        if( pollPlayback )
+        {
+            /* self->pfds is in effect an array of fds; if necessary, index past the capture fds */
+            playbackPfds = self->pfds + (pollCapture ? self->capture.nfds : 0);
+            PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) );
+            totalFds += self->playback.nfds;
+        }
+
+#ifdef PTHREAD_CANCELED
+        if( self->callbackMode )
+        {
+            /* To allow 'Abort' to terminate the callback thread, enable cancelability just for poll() (& disable after) */
+            pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL );
+        }
+#endif
+
+        pollResults = poll( self->pfds, totalFds, pollTimeout );
+
+#ifdef PTHREAD_CANCELED
+        if( self->callbackMode )
+        {
+            pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, NULL );
+        }
+#endif
+
+        if( pollResults < 0 )
+        {
+            /*  XXX: Depend on preprocessor condition? */
+            if( errno == EINTR )
+            {
+                /* gdb */
+                Pa_Sleep( 1 ); /* avoid hot loop */
+                continue;
+            }
+
+            /* TODO: Add macro for checking system calls */
+            PA_ENSURE( paInternalError );
+        }
+        else if( pollResults == 0 )
+        {
+           /* Suspended, paused or failed device can provide 0 poll results. To avoid deadloop in such situation
+            * we simply run counter 'timeouts' which detects 0 poll result and accumulates. As soon as 2048 timouts (around 2 seconds)
+            * are achieved we simply fail function with paTimedOut to notify waiting methods that device is not capable
+            * of providing audio data anymore and needs some corresponding recovery action.
+            * Note that 'timeouts' is reset to 0 if poll() managed to return non 0 results.
+            */
+
+            /*PA_DEBUG(( "%s: poll == 0 results, timed out, %d times left\n", __FUNCTION__, 2048 - timeouts ));*/
+            ++ timeouts;
+            if( timeouts > 1 ) /* sometimes device times out, but normally once, so we do not sleep any time */
+            {
+                Pa_Sleep( 1 ); /* avoid hot loop */
+            }
+            /* not else ! */
+            if( timeouts >= 2048 ) /* audio device not working, shall return error to notify waiters */
+            {
+                *framesAvail = 0; /* no frames available for processing */
+                xrun = 1; /* try recovering device */
+
+                PA_DEBUG(( "%s: poll timed out\n", __FUNCTION__, timeouts ));
+                goto end;/*PA_ENSURE( paTimedOut );*/
+            }
+        }
+        else if( pollResults > 0 )
+        {
+            /* reset timouts counter */
+            timeouts = 0;
+
+            /* check the return status of our pfds */
+            if( pollCapture )
+            {
+                PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
+            }
+            if( pollPlayback )
+            {
+                PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
+            }
+            if( xrun )
+            {
+                break;
+            }
+        }
+
+        /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two.
+         * If there is less than half a period's worth of samples left of frames in the other pcm's buffer we will
+         * stop polling.
+         */
+        if( self->capture.pcm && self->playback.pcm )
+        {
+            if( pollCapture && !pollPlayback )
+            {
+                PA_ENSURE( ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture ) );
+            }
+            else if( pollPlayback && !pollCapture )
+            {
+                PA_ENSURE( ContinuePoll( self, StreamDirection_Out, &pollTimeout, &pollPlayback ) );
+            }
+        }
+    }
+
+    if( !xrun )
+    {
+        /* Get the number of available frames for the pcms that are marked ready.
+         * @concern FullDuplex If only one direction is marked ready (from poll), the number of frames available for
+         * the other direction is returned. Output is normally preferred over capture however, so capture frames may be
+         * discarded to avoid overrun unless paNeverDropInput is specified.
+         */
+        int captureReady = self->capture.pcm ? self->capture.ready : 0,
+            playbackReady = self->playback.pcm ? self->playback.ready : 0;
+        PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, captureReady, playbackReady, framesAvail, &xrun ) );
+
+        if( self->capture.pcm && self->playback.pcm )
+        {
+            if( !self->playback.ready && !self->neverDropInput )
+            {
+                /* Drop input, a period's worth */
+                assert( self->capture.ready );
+                PaAlsaStreamComponent_EndProcessing( &self->capture, PA_MIN( self->capture.framesPerPeriod,
+                            *framesAvail ), &xrun );
+                *framesAvail = 0;
+                self->capture.ready = 0;
+            }
+        }
+        else if( self->capture.pcm )
+            assert( self->capture.ready );
+        else
+            assert( self->playback.ready );
+    }
+
+end:
+error:
+    if( xrun )
+    {
+        /* Recover from the xrun state */
+        PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+        *framesAvail = 0;
+    }
+    else
+    {
+        if( 0 != *framesAvail )
+        {
+            /* If we're reporting frames eligible for processing, one of the handles better be ready */
+            PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+        }
+    }
+    *xrunOccurred = xrun;
+
+    return result;
+}
+
+/** Register per-channel ALSA buffer information with buffer processor.
+ *
+ * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the
+ * number of host and user channels is taken into account.
+ *
+ * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames.
+ */
+static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp,
+        unsigned long* numFrames, int* xrun )
+{
+    PaError result = paNoError;
+    const snd_pcm_channel_area_t *areas, *area;
+    void (*setChannel)(PaUtilBufferProcessor *, unsigned int, void *, unsigned int) =
+        StreamDirection_In == self->streamDir ? PaUtil_SetInputChannel : PaUtil_SetOutputChannel;
+    unsigned char *buffer, *p;
+    int i;
+    unsigned long framesAvail;
+
+    /* This _must_ be called before mmap_begin */
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( self, &framesAvail, xrun ) );
+    if( *xrun )
+    {
+        *numFrames = 0;
+        goto end;
+    }
+
+    if( self->canMmap )
+    {
+        ENSURE_( alsa_snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
+        /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
+        self->channelAreas = (snd_pcm_channel_area_t *)areas;
+    }
+    else
+    {
+        unsigned int bufferSize = self->numHostChannels * alsa_snd_pcm_format_size( self->nativeFormat, *numFrames );
+        if( bufferSize > self->nonMmapBufferSize )
+        {
+            self->nonMmapBuffer = realloc( self->nonMmapBuffer, ( self->nonMmapBufferSize = bufferSize ) );
+            if( !self->nonMmapBuffer )
+            {
+                result = paInsufficientMemory;
+                goto error;
+            }
+        }
+    }
+
+    if( self->hostInterleaved )
+    {
+        int swidth = alsa_snd_pcm_format_size( self->nativeFormat, 1 );
+
+        p = buffer = self->canMmap ? ExtractAddress( areas, self->offset ) : self->nonMmapBuffer;
+        for( i = 0; i < self->numUserChannels; ++i )
+        {
+            /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */
+            setChannel( bp, i, p, self->numHostChannels );
+            p += swidth;
+        }
+    }
+    else
+    {
+        if( self->canMmap )
+        {
+            for( i = 0; i < self->numUserChannels; ++i )
+            {
+                area = areas + i;
+                buffer = ExtractAddress( area, self->offset );
+                setChannel( bp, i, buffer, 1 );
+            }
+        }
+        else
+        {
+            unsigned int buf_per_ch_size = self->nonMmapBufferSize / self->numHostChannels;
+            buffer = self->nonMmapBuffer;
+            for( i = 0; i < self->numUserChannels; ++i )
+            {
+                setChannel( bp, i, buffer, 1 );
+                buffer += buf_per_ch_size;
+            }
+        }
+    }
+
+    if( !self->canMmap && StreamDirection_In == self->streamDir )
+    {
+        /* Read sound */
+        int res;
+        if( self->hostInterleaved )
+            res = alsa_snd_pcm_readi( self->pcm, self->nonMmapBuffer, *numFrames );
+        else
+        {
+            void *bufs[self->numHostChannels];
+            unsigned int buf_per_ch_size = self->nonMmapBufferSize / self->numHostChannels;
+            unsigned char *buffer = self->nonMmapBuffer;
+            int i;
+            for( i = 0; i < self->numHostChannels; ++i )
+            {
+                bufs[i] = buffer;
+                buffer += buf_per_ch_size;
+            }
+            res = alsa_snd_pcm_readn( self->pcm, bufs, *numFrames );
+        }
+        if( res == -EPIPE || res == -ESTRPIPE )
+        {
+            *xrun = 1;
+            *numFrames = 0;
+        }
+    }
+
+end:
+error:
+    return result;
+}
+
+/** Initiate buffer processing.
+ *
+ * ALSA buffers are registered with the PA buffer processor and the buffer size (in frames) set.
+ *
+ * @concern FullDuplex If both directions are being processed, the minimum amount of frames for the two directions is
+ * calculated.
+ *
+ * @param numFrames On entrance the number of available frames, on exit the number of received frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* numFrames, int* xrunOccurred )
+{
+    PaError result = paNoError;
+    unsigned long captureFrames = ULONG_MAX, playbackFrames = ULONG_MAX, commonFrames = 0;
+    int xrun = 0;
+
+    if( *xrunOccurred )
+    {
+        *numFrames = 0;
+        return result;
+    }
+    /* If we got here at least one of the pcm's should be marked ready */
+    PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+
+    /* Extract per-channel ALSA buffer pointers and register them with the buffer processor.
+     * It is possible that a direction is not marked ready however, because it is out of sync with the other.
+     */
+    if( self->capture.pcm && self->capture.ready )
+    {
+        captureFrames = *numFrames;
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames,
+                    &xrun ) );
+    }
+    if( self->playback.pcm && self->playback.ready )
+    {
+        playbackFrames = *numFrames;
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames,
+                    &xrun ) );
+    }
+    if( xrun )
+    {
+        /* Nothing more to do */
+        assert( 0 == commonFrames );
+        goto end;
+    }
+
+    commonFrames = PA_MIN( captureFrames, playbackFrames );
+    /* assert( commonFrames <= *numFrames ); */
+    if( commonFrames > *numFrames )
+    {
+        /* Hmmm ... how come there are more frames available than we requested!? Blah. */
+        PA_DEBUG(( "%s: Common available frames are reported to be more than number requested: %lu, %lu, callbackMode: %d\n", __FUNCTION__,
+                    commonFrames, *numFrames, self->callbackMode ));
+        if( self->capture.pcm )
+        {
+            PA_DEBUG(( "%s: captureFrames: %lu, capture.ready: %d\n", __FUNCTION__, captureFrames, self->capture.ready ));
+        }
+        if( self->playback.pcm )
+        {
+            PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready ));
+        }
+
+        commonFrames = 0;
+        goto end;
+    }
+
+    /* Inform PortAudio of the number of frames we got.
+     * @concern FullDuplex We might be experiencing underflow in either end; if its an input underflow, we go on
+     * with output. If its output underflow however, depending on the paNeverDropInput flag, we may want to simply
+     * discard the excess input or call the callback with paOutputOverflow flagged.
+     */
+    if( self->capture.pcm )
+    {
+        if( self->capture.ready )
+        {
+            PaUtil_SetInputFrameCount( &self->bufferProcessor, commonFrames );
+        }
+        else
+        {
+            /* We have input underflow */
+            PaUtil_SetNoInput( &self->bufferProcessor );
+        }
+    }
+    if( self->playback.pcm )
+    {
+        if( self->playback.ready )
+        {
+            PaUtil_SetOutputFrameCount( &self->bufferProcessor, commonFrames );
+        }
+        else
+        {
+            /* We have output underflow, but keeping input data (paNeverDropInput) */
+            assert( self->neverDropInput );
+            assert( self->capture.pcm != NULL );
+            PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ ));
+            PaUtil_SetNoOutput( &self->bufferProcessor );
+        }
+    }
+
+end:
+    *numFrames = commonFrames;
+error:
+    if( xrun )
+    {
+        PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+        *numFrames = 0;
+    }
+    *xrunOccurred = xrun;
+
+    return result;
+}
+
+/** Callback thread's function.
+ *
+ * Roughly, the workflow can be described in the following way: The number of available frames that can be processed
+ * directly is obtained from ALSA, we then request as much directly accessible memory as possible within this amount
+ * from ALSA. The buffer memory is registered with the PA buffer processor and processing is carried out with
+ * PaUtil_EndBufferProcessing. Finally, the number of processed frames is reported to ALSA. The processing can
+ * happen in several iterations untill we have consumed the known number of available frames (or an xrun is detected).
+ */
+static void *CallbackThreadFunc( void *userData )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*) userData;
+    PaStreamCallbackTimeInfo timeInfo = {0, 0, 0};
+    snd_pcm_sframes_t startThreshold = 0;
+    int callbackResult = paContinue;
+    PaStreamCallbackFlags cbFlags = 0;  /* We might want to keep state across iterations */
+    int streamStarted = 0;
+
+    assert( stream );
+    /* Not implemented */
+    assert( !stream->primeBuffers );
+
+    /* Execute OnExit when exiting */
+    pthread_cleanup_push( &OnExit, stream );
+#ifdef PTHREAD_CANCELED
+    /* 'Abort' will use thread cancellation to terminate the callback thread, but the Alsa-lib functions
+     * are NOT cancel-safe, (and can end up in an inconsistent state).  So, disable cancelability for
+     * the thread here, and just re-enable it for the poll() in PaAlsaStream_WaitForFrames(). */
+    pthread_testcancel();
+    pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, NULL );
+#endif
+
+    /* @concern StreamStart If the output is being primed the output pcm needs to be prepared, otherwise the
+     * stream is started immediately. The latter involves signaling the waiting main thread.
+     */
+    if( stream->primeBuffers )
+    {
+        snd_pcm_sframes_t avail;
+
+        if( stream->playback.pcm )
+            ENSURE_( alsa_snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+        if( stream->capture.pcm && !stream->pcmsSynced )
+            ENSURE_( alsa_snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+
+        /* We can't be certain that the whole ring buffer is available for priming, but there should be
+         * at least one period */
+        avail = alsa_snd_pcm_avail_update( stream->playback.pcm );
+        startThreshold = avail - (avail % stream->playback.framesPerPeriod);
+        assert( startThreshold >= stream->playback.framesPerPeriod );
+    }
+    else
+    {
+        PA_ENSURE( PaUnixThread_PrepareNotify( &stream->thread ) );
+        /* Buffer will be zeroed */
+        PA_ENSURE( AlsaStart( stream, 0 ) );
+        PA_ENSURE( PaUnixThread_NotifyParent( &stream->thread ) );
+
+        streamStarted = 1;
+    }
+
+    while( 1 )
+    {
+        unsigned long framesAvail, framesGot;
+        int xrun = 0;
+
+#ifdef PTHREAD_CANCELED
+        pthread_testcancel();
+#endif
+
+        /* @concern StreamStop if the main thread has requested a stop and the stream has not been effectively
+         * stopped we signal this condition by modifying callbackResult (we'll want to flush buffered output).
+         */
+        if( PaUnixThread_StopRequested( &stream->thread ) && paContinue == callbackResult )
+        {
+            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+            callbackResult = paComplete;
+        }
+
+        if( paContinue != callbackResult )
+        {
+            stream->callbackAbort = ( paAbort == callbackResult );
+            if( stream->callbackAbort ||
+                    /** @concern BlockAdaption: Go on if adaption buffers are empty */
+                    PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+            {
+                goto end;
+            }
+
+            PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ ));
+            /* There is still buffered output that needs to be processed */
+        }
+
+        /* Wait for data to become available, this comes down to polling the ALSA file descriptors untill we have
+         * a number of available frames.
+         */
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        if( xrun )
+        {
+            assert( 0 == framesAvail );
+            continue;
+
+            /* XXX: Report xruns to the user? A situation is conceivable where the callback is never invoked due
+             * to constant xruns, it might be desirable to notify the user of this.
+             */
+        }
+
+        /* Consume buffer space. Once we have a number of frames available for consumption we must retrieve the
+         * mmapped buffers from ALSA, this is contiguously accessible memory however, so we may receive smaller
+         * portions at a time than is available as a whole. Therefore we should be prepared to process several
+         * chunks successively. The buffers are passed to the PA buffer processor.
+         */
+        while( framesAvail > 0 )
+        {
+            xrun = 0;
+
+            /** @concern Xruns Under/overflows are to be reported to the callback */
+            if( stream->underrun > 0.0 )
+            {
+                cbFlags |= paOutputUnderflow;
+                stream->underrun = 0.0;
+            }
+            if( stream->overrun > 0.0 )
+            {
+                cbFlags |= paInputOverflow;
+                stream->overrun = 0.0;
+            }
+            if( stream->capture.pcm && stream->playback.pcm )
+            {
+                /** @concern FullDuplex It's possible that only one direction is being processed to avoid an
+                 * under- or overflow, this should be reported correspondingly */
+                if( !stream->capture.ready )
+                {
+                    cbFlags |= paInputUnderflow;
+                    PA_DEBUG(( "%s: Input underflow\n", __FUNCTION__ ));
+                }
+                else if( !stream->playback.ready )
+                {
+                    cbFlags |= paOutputOverflow;
+                    PA_DEBUG(( "%s: Output overflow\n", __FUNCTION__ ));
+                }
+            }
+
+#if 0
+            CallbackUpdate( &stream->threading );
+#endif
+
+            CalculateTimeInfo( stream, &timeInfo );
+            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags );
+            cbFlags = 0;
+
+            /* CPU load measurement should include processing activity external to the stream callback */
+            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+            framesGot = framesAvail;
+            if( paUtilFixedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode )
+            {
+                /* We've committed to a fixed host buffer size, stick to that */
+                framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0;
+            }
+            else
+            {
+                /* We've committed to an upper bound on the size of host buffers */
+                assert( paUtilBoundedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode );
+                framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer );
+            }
+            PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+            /* Check the host buffer size against the buffer processor configuration */
+            framesAvail -= framesGot;
+
+            if( framesGot > 0 )
+            {
+                assert( !xrun );
+                PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+                PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            }
+            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot );
+
+            if( 0 == framesGot )
+            {
+                /* Go back to polling for more frames */
+                break;
+            }
+
+            if( paContinue != callbackResult )
+                break;
+        }
+    }
+
+end:
+    ; /* Hack to fix "label at end of compound statement" error caused by pthread_cleanup_pop(1) macro. */
+    /* Match pthread_cleanup_push */
+    pthread_cleanup_pop( 1 );
+
+    PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() ));
+    PaUnixThreading_EXIT( result );
+
+error:
+    PA_DEBUG(( "%s: Thread %d is canceled due to error %d\n ", __FUNCTION__, pthread_self(), result ));
+    goto end;
+}
+
+/* Blocking interface */
+
+static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long framesGot, framesAvail;
+    void *userBuffer;
+    snd_pcm_t *save = stream->playback.pcm;
+
+    assert( stream );
+
+    PA_UNLESS( stream->capture.pcm, paCanNotReadFromAnOutputOnlyStream );
+
+    /* Disregard playback */
+    stream->playback.pcm = NULL;
+
+    if( stream->overrun > 0. )
+    {
+        result = paInputOverflowed;
+        stream->overrun = 0.0;
+    }
+
+    if( stream->capture.userInterleaved )
+    {
+        userBuffer = buffer;
+    }
+    else
+    {
+        /* Copy channels into local array */
+        userBuffer = stream->capture.userBuffers;
+        memcpy( userBuffer, buffer, sizeof (void *) * stream->capture.numUserChannels );
+    }
+
+    /* Start stream if in prepared state */
+    if( alsa_snd_pcm_state( stream->capture.pcm ) == SND_PCM_STATE_PREPARED )
+    {
+        ENSURE_( alsa_snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+    }
+
+    while( frames > 0 )
+    {
+        int xrun = 0;
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        framesGot = PA_MIN( framesAvail, frames );
+
+        PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            frames -= framesGot;
+        }
+    }
+
+end:
+    stream->playback.pcm = save;
+    return result;
+error:
+    goto end;
+}
+
+static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frames )
+{
+    PaError result = paNoError;
+    signed long err;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    snd_pcm_uframes_t framesGot, framesAvail;
+    const void *userBuffer;
+    snd_pcm_t *save = stream->capture.pcm;
+
+    assert( stream );
+
+    PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream );
+
+    /* Disregard capture */
+    stream->capture.pcm = NULL;
+
+    if( stream->underrun > 0. )
+    {
+        result = paOutputUnderflowed;
+        stream->underrun = 0.0;
+    }
+
+    if( stream->playback.userInterleaved )
+        userBuffer = buffer;
+    else /* Copy channels into local array */
+    {
+        userBuffer = stream->playback.userBuffers;
+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback.numUserChannels );
+    }
+
+    while( frames > 0 )
+    {
+        int xrun = 0;
+        snd_pcm_uframes_t hwAvail;
+
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        framesGot = PA_MIN( framesAvail, frames );
+
+        PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            frames -= framesGot;
+        }
+
+        /* Start stream after one period of samples worth */
+
+        /* Frames residing in buffer */
+        PA_ENSURE( err = GetStreamWriteAvailable( stream ) );
+        framesAvail = err;
+        hwAvail = stream->playback.alsaBufferSize - framesAvail;
+
+        if( alsa_snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED &&
+                hwAvail >= stream->playback.framesPerPeriod )
+        {
+            ENSURE_( alsa_snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+    }
+
+end:
+    stream->capture.pcm = save;
+    return result;
+error:
+    goto end;
+}
+
+/* Return frames available for reading. In the event of an overflow, the capture pcm will be restarted */
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long avail;
+    int xrun;
+
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+    if( xrun )
+    {
+        PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+        if( xrun )
+            PA_ENSURE( paInputOverflowed );
+    }
+
+    return (signed long)avail;
+
+error:
+    return result;
+}
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long avail;
+    int xrun;
+
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->playback, &avail, &xrun ) );
+    if( xrun )
+    {
+        snd_pcm_sframes_t savail;
+
+        PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+        savail = alsa_snd_pcm_avail_update( stream->playback.pcm );
+
+        /* savail should not contain -EPIPE now, since PaAlsaStream_HandleXrun will only prepare the pcm */
+        ENSURE_( savail, paUnanticipatedHostError );
+
+        avail = (unsigned long) savail;
+    }
+
+    return (signed long)avail;
+
+error:
+    return result;
+}
+
+/* Extensions */
+
+void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info )
+{
+    info->size = sizeof (PaAlsaStreamInfo);
+    info->hostApiType = paALSA;
+    info->version = 1;
+    info->deviceString = NULL;
+}
+
+void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable )
+{
+    PaAlsaStream *stream = (PaAlsaStream *) s;
+    stream->rtSched = enable;
+}
+
+#if 0
+void PaAlsa_EnableWatchdog( PaStream *s, int enable )
+{
+    PaAlsaStream *stream = (PaAlsaStream *) s;
+    stream->thread.useWatchdog = enable;
+}
+#endif
+
+static PaError GetAlsaStreamPointer( PaStream* s, PaAlsaStream** stream )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation* hostApi;
+    PaAlsaHostApiRepresentation* alsaHostApi;
+
+    PA_ENSURE( PaUtil_ValidateStreamPointer( s ) );
+    PA_ENSURE( PaUtil_GetHostApiRepresentation( &hostApi, paALSA ) );
+    alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+
+    PA_UNLESS( PA_STREAM_REP( s )->streamInterface == &alsaHostApi->callbackStreamInterface
+            || PA_STREAM_REP( s )->streamInterface == &alsaHostApi->blockingStreamInterface,
+        paIncompatibleStreamHostApi );
+
+    *stream = (PaAlsaStream*)s;
+error:
+    return paNoError;
+}
+
+PaError PaAlsa_GetStreamInputCard( PaStream* s, int* card )
+{
+    PaAlsaStream *stream;
+    PaError result = paNoError;
+    snd_pcm_info_t* pcmInfo;
+
+    PA_ENSURE( GetAlsaStreamPointer( s, &stream ) );
+
+    /* XXX: More descriptive error? */
+    PA_UNLESS( stream->capture.pcm, paDeviceUnavailable );
+
+    alsa_snd_pcm_info_alloca( &pcmInfo );
+    PA_ENSURE( alsa_snd_pcm_info( stream->capture.pcm, pcmInfo ) );
+    *card = alsa_snd_pcm_info_get_card( pcmInfo );
+
+error:
+    return result;
+}
+
+PaError PaAlsa_GetStreamOutputCard( PaStream* s, int* card )
+{
+    PaAlsaStream *stream;
+    PaError result = paNoError;
+    snd_pcm_info_t* pcmInfo;
+
+    PA_ENSURE( GetAlsaStreamPointer( s, &stream ) );
+
+    /* XXX: More descriptive error? */
+    PA_UNLESS( stream->playback.pcm, paDeviceUnavailable );
+
+    alsa_snd_pcm_info_alloca( &pcmInfo );
+    PA_ENSURE( alsa_snd_pcm_info( stream->playback.pcm, pcmInfo ) );
+    *card = alsa_snd_pcm_info_get_card( pcmInfo );
+
+error:
+    return result;
+}
+
+PaError PaAlsa_SetRetriesBusy( int retries )
+{
+    busyRetries_ = retries;
+    return paNoError;
+}
diff --git a/portaudio/src/hostapi/asihpi/pa_linux_asihpi.c b/portaudio/src/hostapi/asihpi/pa_linux_asihpi.c
new file mode 100644 (file)
index 0000000..f5a5290
--- /dev/null
@@ -0,0 +1,2893 @@
+/*
+ * $Id:$
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * AudioScience HPI implementation by Fred Gleason, Ludwig Schwardt and
+ * Eliot Blennerhassett
+ *
+ * Copyright (c) 2003 Fred Gleason <fredg@salemradiolabs.com>
+ * Copyright (c) 2005,2006 Ludwig Schwardt <schwardt@sun.ac.za>
+ * Copyright (c) 2011 Eliot Blennerhassett <eblennerhassett@audioscience.com>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/*
+ * Modification History
+ * 12/2003 - Initial version
+ * 09/2005 - v19 version [rewrite]
+ */
+
+/** @file
+ @ingroup hostapi_src
+ @brief Host API implementation supporting AudioScience cards
+        via the Linux HPI interface.
+
+ <h3>Overview</h3>
+
+ This is a PortAudio implementation for the AudioScience HPI Audio API
+ on the Linux platform. AudioScience makes a range of audio adapters customised
+ for the broadcasting industry, with support for both Windows and Linux.
+ More information on their products can be found on their website:
+
+     http://www.audioscience.com
+
+ Documentation for the HPI API can be found at:
+
+     http://www.audioscience.com/internet/download/sdk/hpi_usermanual_html/html/index.html
+
+ The Linux HPI driver itself (a kernel module + library) can be downloaded from:
+
+     http://www.audioscience.com/internet/download/linux_drivers.htm
+
+ <h3>Implementation strategy</h3>
+
+ *Note* Ideally, AudioScience cards should be handled by the PortAudio ALSA
+ implementation on Linux, as ALSA is the preferred Linux soundcard API. The existence
+ of this host API implementation might therefore seem a bit flawed. Unfortunately, at
+ the time of the creation of this implementation (June 2006), the PA ALSA implementation
+ could not make use of the existing AudioScience ALSA driver. PA ALSA uses the
+ "memory-mapped" (mmap) ALSA access mode to interact with the ALSA library, while the
+ AudioScience ALSA driver only supports the "read-write" access mode. The appropriate
+ solution to this problem is to add "read-write" support to PortAudio ALSA, thereby
+ extending the range of soundcards it supports (AudioScience cards are not the only
+ ones with this problem). Given the author's limited knowledge of ALSA and the
+ simplicity of the HPI API, the second-best solution was born...
+
+ The following mapping between HPI and PA was followed:
+ HPI subsystem => PortAudio host API
+ HPI adapter => nothing specific
+ HPI stream => PortAudio device
+
+ Each HPI stream is either input or output (not both), and can support
+ different channel counts, sampling rates and sample formats. It is therefore
+ a more natural fit to a PA device. A PA stream can therefore combine two
+ HPI streams (one input and one output) into a "full-duplex" stream. These
+ HPI streams can even be on different physical adapters. The two streams ought to be
+ sample-synchronised when they reside on the same adapter, as most AudioScience adapters
+ derive their ADC and DAC clocks from one master clock. When combining two adapters
+ into one full-duplex stream, however, the use of a word clock connection between the
+ adapters is strongly recommended.
+
+ The HPI interface is inherently blocking, making use of read and write calls to
+ transfer data between user buffers and driver buffers. The callback interface therefore
+ requires a helper thread ("callback engine") which periodically transfers data (one thread
+ per PA stream, in fact). The current implementation explicitly sleeps via Pa_Sleep() until
+ enough samples can be transferred (select() or poll() would be better, but currently seems
+ impossible...). The thread implementation makes use of the Unix thread helper functions
+ and some pthread calls here and there. If a unified PA thread exists, this host API
+ implementation might also compile on Windows, as this is the only real Linux-specific
+ part of the code.
+
+ There is no inherent fixed buffer size in the HPI interface, as in some other host APIs.
+ The PortAudio implementation contains a buffer that is allocated during OpenStream and
+ used to transfer data between the callback and the HPI driver buffer. The size of this
+ buffer is quite flexible and is derived from latency suggestions and matched to the
+ requested callback buffer size as far as possible. It can become quite huge, as the
+ AudioScience cards are typically geared towards higher-latency applications and contain
+ large hardware buffers.
+
+ The HPI interface natively supports most common sample formats and sample rates (some
+ conversion is done on the adapter itself).
+
+ Stream time is measured based on the number of processed frames, which is adjusted by the
+ number of frames currently buffered by the HPI driver.
+
+ There is basic support for detecting overflow and underflow. The HPI interface does not
+ explicitly indicate this, so thresholds on buffer levels are used in combination with
+ stream state. Recovery from overflow and underflow is left to the PA client.
+
+ Blocking streams are also implemented. It makes use of the same polling routines that
+ the callback interface uses, in order to prevent the allocation of variable-sized
+ buffers during reading and writing. The framesPerBuffer parameter is therefore still
+ relevant, and this can be increased in the blocking case to improve efficiency.
+
+ The implementation contains extensive reporting macros (slightly modified PA_ENSURE and
+ PA_UNLESS versions) and a useful stream dump routine to provide debugging feedback.
+
+ Output buffer priming via the user callback (i.e. paPrimeOutputBuffersUsingStreamCallback
+ and friends) is not implemented yet. All output is primed with silence.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>          /* strlen() */
+#include <pthread.h>         /* pthreads and friends */
+#include <assert.h>          /* assert */
+#include <math.h>            /* ceil, floor */
+
+#include <asihpi/hpi.h>      /* HPI API */
+
+#include "portaudio.h"       /* PortAudio API */
+#include "pa_util.h"         /* PA_DEBUG, other small utilities */
+#include "pa_unix_util.h"    /* Unix threading utilities */
+#include "pa_allocation.h"   /* Group memory allocation */
+#include "pa_hostapi.h"      /* Host API structs */
+#include "pa_stream.h"       /* Stream interface structs */
+#include "pa_cpuload.h"      /* CPU load measurer */
+#include "pa_process.h"      /* Buffer processor */
+#include "pa_converters.h"   /* PaUtilZeroer */
+#include "pa_debugprint.h"
+
+/* -------------------------------------------------------------------------- */
+
+/*
+ * Defines
+ */
+
+/* Error reporting and assertions */
+
+/** Evaluate expression, and return on any PortAudio errors */
+#define PA_ENSURE_(expr) \
+    do { \
+        PaError paError = (expr); \
+        if( UNLIKELY( paError < paNoError ) ) \
+        { \
+            PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = paError; \
+            goto error; \
+        } \
+    } while (0);
+
+/** Assert expression, else return the provided PaError */
+#define PA_UNLESS_(expr, paError) \
+    do { \
+        if( UNLIKELY( (expr) == 0 ) ) \
+        { \
+            PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = (paError); \
+            goto error; \
+        } \
+    } while( 0 );
+
+/** Check return value of HPI function, and map it to PaError */
+#define PA_ASIHPI_UNLESS_(expr, paError) \
+    do { \
+        hpi_err_t hpiError = (expr); \
+        /* If HPI error occurred */ \
+        if( UNLIKELY( hpiError ) ) \
+        { \
+           char szError[256]; \
+           HPI_GetErrorText( hpiError, szError ); \
+           PA_DEBUG(( "HPI error %d occurred: %s\n", hpiError, szError )); \
+           /* This message will always be displayed, even if debug info is disabled */ \
+            PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            if( (paError) == paUnanticipatedHostError ) \
+           { \
+               PA_DEBUG(( "Host error description: %s\n", szError )); \
+               /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+               if( pthread_equal( pthread_self(), paUnixMainThread ) ) \
+                { \
+                   PaUtil_SetLastHostErrorInfo( paInDevelopment, hpiError, szError ); \
+                } \
+           } \
+           /* If paNoError is specified, continue as usual */ \
+            /* (useful if you only want to print out the debug messages above) */ \
+           if( (paError) < 0 ) \
+           { \
+               result = (paError); \
+               goto error; \
+           } \
+        } \
+    } while( 0 );
+
+/** Report HPI error code and text */
+#define PA_ASIHPI_REPORT_ERROR_(hpiErrorCode) \
+    do { \
+        char szError[256]; \
+        HPI_GetErrorText( hpiError, szError ); \
+        PA_DEBUG(( "HPI error %d occurred: %s\n", hpiError, szError )); \
+        /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+        if( pthread_equal( pthread_self(), paUnixMainThread ) ) \
+       { \
+           PaUtil_SetLastHostErrorInfo( paInDevelopment, (hpiErrorCode), szError ); \
+       } \
+    } while( 0 );
+
+/* Defaults */
+
+/** Sample formats available natively on AudioScience hardware */
+#define PA_ASIHPI_AVAILABLE_FORMATS_ (paFloat32 | paInt32 | paInt24 | paInt16 | paUInt8)
+/** Enable background bus mastering (BBM) for buffer transfers, if available (see HPI docs) */
+#define PA_ASIHPI_USE_BBM_ 1
+/** Minimum number of frames in HPI buffer (for either data or available space).
+ If buffer contains less data/space, it indicates xrun or completion. */
+#define PA_ASIHPI_MIN_FRAMES_ 1152
+/** Minimum polling interval in milliseconds, which determines minimum host buffer size */
+#define PA_ASIHPI_MIN_POLLING_INTERVAL_ 10
+
+/* -------------------------------------------------------------------------- */
+
+/*
+ * Structures
+ */
+
+/** Host API global data */
+typedef struct PaAsiHpiHostApiRepresentation
+{
+    /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */
+    PaUtilHostApiRepresentation baseHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    /* implementation specific data goes here */
+
+    PaHostApiIndex hostApiIndex;
+}
+PaAsiHpiHostApiRepresentation;
+
+
+/** Device data */
+typedef struct PaAsiHpiDeviceInfo
+{
+    /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */
+    /** Common PortAudio device information */
+    PaDeviceInfo baseDeviceInfo;
+
+    /* implementation specific data goes here */
+
+    /** Adapter index */
+    uint16_t adapterIndex;
+    /** Adapter model number (hex) */
+    uint16_t adapterType;
+    /** Adapter HW/SW version */
+    uint16_t adapterVersion;
+    /** Adapter serial number */
+    uint32_t adapterSerialNumber;
+    /** Stream number */
+    uint16_t streamIndex;
+    /** 0=Input, 1=Output (HPI streams are either input or output but not both) */
+    uint16_t streamIsOutput;
+}
+PaAsiHpiDeviceInfo;
+
+
+/** Stream state as defined by PortAudio.
+ It seems that the host API implementation has to keep track of the PortAudio stream state.
+ Please note that this is NOT the same as the state of the underlying HPI stream. By separating
+ these two concepts, a lot of flexibility is gained. There is a rough match between the two,
+ of course, but forcing a precise match is difficult. For example, HPI_STATE_DRAINED can occur
+ during the Active state of PortAudio (due to underruns) and also during CallBackFinished in
+ the case of an output stream. Similarly, HPI_STATE_STOPPED mostly coincides with the Stopped
+ PortAudio state, by may also occur in the CallbackFinished state when recording is finished.
+
+ Here is a rough match-up:
+
+ PortAudio state   =>     HPI state
+ ---------------          ---------
+ Active            =>     HPI_STATE_RECORDING, HPI_STATE_PLAYING, (HPI_STATE_DRAINED)
+ Stopped           =>     HPI_STATE_STOPPED
+ CallbackFinished  =>     HPI_STATE_STOPPED, HPI_STATE_DRAINED */
+typedef enum PaAsiHpiStreamState
+{
+    paAsiHpiStoppedState=0,
+    paAsiHpiActiveState=1,
+    paAsiHpiCallbackFinishedState=2
+}
+PaAsiHpiStreamState;
+
+
+/** Stream component data (associated with one direction, i.e. either input or output) */
+typedef struct PaAsiHpiStreamComponent
+{
+    /** Device information (HPI handles, etc) */
+    PaAsiHpiDeviceInfo *hpiDevice;
+    /** Stream handle, as passed to HPI interface. */
+    hpi_handle_t hpiStream;
+    /** Stream format, as passed to HPI interface */
+    struct hpi_format hpiFormat;
+    /** Number of bytes per frame, derived from hpiFormat and saved for convenience */
+    uint32_t bytesPerFrame;
+    /** Size of hardware (on-card) buffer of stream in bytes */
+    uint32_t hardwareBufferSize;
+    /** Size of host (BBM) buffer of stream in bytes (if used) */
+    uint32_t hostBufferSize;
+    /** Upper limit on the utilization of output stream buffer (both hardware and host).
+     This prevents large latencies in an output-only stream with a potentially huge buffer
+     and a fast data generator, which would otherwise keep the hardware buffer filled to
+     capacity. See also the "Hardware Buffering=off" option in the AudioScience WAV driver. */
+    uint32_t outputBufferCap;
+    /** Sample buffer (halfway station between HPI and buffer processor) */
+    uint8_t *tempBuffer;
+    /** Sample buffer size, in bytes */
+    uint32_t tempBufferSize;
+}
+PaAsiHpiStreamComponent;
+
+
+/** Stream data */
+typedef struct PaAsiHpiStream
+{
+    /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */
+    PaUtilStreamRepresentation baseStreamRep;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    PaUtilAllocationGroup *allocations;
+
+    /* implementation specific data goes here */
+
+    /** Separate structs for input and output sides of stream */
+    PaAsiHpiStreamComponent *input, *output;
+
+    /** Polling interval (in milliseconds) */
+    uint32_t pollingInterval;
+    /** Are we running in callback mode? */
+    int callbackMode;
+    /** Number of frames to transfer at a time to/from HPI */
+    unsigned long maxFramesPerHostBuffer;
+    /** Indicates that the stream is in the paNeverDropInput mode */
+    int neverDropInput;
+    /** Contains copy of user buffers, used by blocking interface to transfer non-interleaved data.
+     It went here instead of to each stream component, as the stream component buffer setup in
+     PaAsiHpi_SetupBuffers doesn't know the stream details such as callbackMode.
+     (Maybe a problem later if ReadStream and WriteStream happens concurrently on same stream.) */
+    void **blockingUserBufferCopy;
+
+    /* Thread-related variables */
+
+    /** Helper thread which will deliver data to user callback */
+    PaUnixThread thread;
+    /** PortAudio stream state (Active/Stopped/CallbackFinished) */
+    volatile sig_atomic_t state;
+    /** Hard abort, i.e. drop frames? */
+    volatile sig_atomic_t callbackAbort;
+    /** True if stream stopped via exiting callback with paComplete/paAbort flag
+     (as opposed to explicit call to StopStream/AbortStream) */
+    volatile sig_atomic_t callbackFinished;
+}
+PaAsiHpiStream;
+
+
+/** Stream state information, collected together for convenience */
+typedef struct PaAsiHpiStreamInfo
+{
+    /** HPI stream state (HPI_STATE_STOPPED, HPI_STATE_PLAYING, etc.) */
+    uint16_t state;
+    /** Size (in bytes) of recording/playback data buffer in HPI driver */
+    uint32_t bufferSize;
+    /** Amount of data (in bytes) available in the buffer */
+    uint32_t dataSize;
+    /** Number of frames played/recorded since last stream reset */
+    uint32_t frameCounter;
+    /** Amount of data (in bytes) in hardware (on-card) buffer.
+     This differs from dataSize if bus mastering (BBM) is used, which introduces another
+     driver-level buffer to which dataSize/bufferSize then refers. */
+    uint32_t auxDataSize;
+    /** Total number of data frames currently buffered by HPI driver (host + hw buffers) */
+    uint32_t totalBufferedData;
+    /** Size of immediately available data (for input) or space (for output) in frames.
+     This only checks the first-level buffer (typically host buffer). This amount can be
+     transferred immediately. */
+    uint32_t availableFrames;
+    /** Indicates that hardware buffer is getting too full */
+    int overflow;
+    /** Indicates that hardware buffer is getting too empty */
+    int underflow;
+}
+PaAsiHpiStreamInfo;
+
+/* -------------------------------------------------------------------------- */
+
+/*
+ * Function prototypes
+ */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+    /* The only exposed function in the entire host API implementation */
+    PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+
+/* Stream prototypes */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream **s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream *s );
+static PaError StartStream( PaStream *s );
+static PaError StopStream( PaStream *s );
+static PaError AbortStream( PaStream *s );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *s );
+static PaTime GetStreamTime( PaStream *s );
+static double GetStreamCpuLoad( PaStream *s );
+
+/* Blocking prototypes */
+static PaError ReadStream( PaStream *s, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream *s );
+static signed long GetStreamWriteAvailable( PaStream *s );
+
+/* Callback prototypes */
+static void *CallbackThreadFunc( void *userData );
+
+/* Functions specific to this API */
+static PaError PaAsiHpi_BuildDeviceList( PaAsiHpiHostApiRepresentation *hpiHostApi );
+static uint16_t PaAsiHpi_PaToHpiFormat( PaSampleFormat paFormat );
+static PaSampleFormat PaAsiHpi_HpiToPaFormat( uint16_t hpiFormat );
+static PaError PaAsiHpi_CreateFormat( struct PaUtilHostApiRepresentation *hostApi,
+                                      const PaStreamParameters *parameters, double sampleRate,
+                                      PaAsiHpiDeviceInfo **hpiDevice, struct hpi_format *hpiFormat );
+static PaError PaAsiHpi_OpenInput( struct PaUtilHostApiRepresentation *hostApi,
+                                   const PaAsiHpiDeviceInfo *hpiDevice, const struct hpi_format *hpiFormat,
+                                   hpi_handle_t *hpiStream );
+static PaError PaAsiHpi_OpenOutput( struct PaUtilHostApiRepresentation *hostApi,
+                                    const PaAsiHpiDeviceInfo *hpiDevice, const struct hpi_format *hpiFormat,
+                                    hpi_handle_t *hpiStream );
+static PaError PaAsiHpi_GetStreamInfo( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStreamInfo *info );
+static void PaAsiHpi_StreamComponentDump( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStream *stream );
+static void PaAsiHpi_StreamDump( PaAsiHpiStream *stream );
+static PaError PaAsiHpi_SetupBuffers( PaAsiHpiStreamComponent *streamComp, uint32_t pollingInterval,
+                                      unsigned long framesPerPaHostBuffer, PaTime suggestedLatency );
+static PaError PaAsiHpi_PrimeOutputWithSilence( PaAsiHpiStream *stream );
+static PaError PaAsiHpi_StartStream( PaAsiHpiStream *stream, int outputPrimed );
+static PaError PaAsiHpi_StopStream( PaAsiHpiStream *stream, int abort );
+static PaError PaAsiHpi_ExplicitStop( PaAsiHpiStream *stream, int abort );
+static void PaAsiHpi_OnThreadExit( void *userData );
+static PaError PaAsiHpi_WaitForFrames( PaAsiHpiStream *stream, unsigned long *framesAvail,
+                                       PaStreamCallbackFlags *cbFlags );
+static void PaAsiHpi_CalculateTimeInfo( PaAsiHpiStream *stream, PaStreamCallbackTimeInfo *timeInfo );
+static PaError PaAsiHpi_BeginProcessing( PaAsiHpiStream* stream, unsigned long* numFrames,
+        PaStreamCallbackFlags *cbFlags );
+static PaError PaAsiHpi_EndProcessing( PaAsiHpiStream *stream, unsigned long numFrames,
+                                       PaStreamCallbackFlags *cbFlags );
+
+/* ==========================================================================
+ * ============================= IMPLEMENTATION =============================
+ * ========================================================================== */
+
+/* --------------------------- Host API Interface --------------------------- */
+
+/** Enumerate all PA devices (= HPI streams).
+ This compiles a list of all HPI adapters, and registers a PA device for each input and
+ output stream it finds. Most errors are ignored, as missing or erroneous devices are
+ simply skipped.
+
+ @param hpiHostApi Pointer to HPI host API struct
+
+ @return PortAudio error code (only paInsufficientMemory in practice)
+ */
+static PaError PaAsiHpi_BuildDeviceList( PaAsiHpiHostApiRepresentation *hpiHostApi )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *hostApi = &hpiHostApi->baseHostApiRep;
+    PaHostApiInfo *baseApiInfo = &hostApi->info;
+    PaAsiHpiDeviceInfo *hpiDeviceList;
+    int numAdapters;
+    hpi_err_t hpiError = 0;
+    int i, j, deviceCount = 0, deviceIndex = 0;
+
+    assert( hpiHostApi );
+
+    /* Errors not considered critical here (subsystem may report 0 devices), but report them */
+    /* in debug mode. */
+    PA_ASIHPI_UNLESS_( HPI_SubSysGetNumAdapters( NULL, &numAdapters), paNoError );
+
+    for( i=0; i < numAdapters; ++i )
+    {
+        uint16_t inStreams, outStreams;
+        uint16_t version;
+        uint32_t serial;
+        uint16_t type;
+        uint32_t idx;
+
+        hpiError = HPI_SubSysGetAdapter(NULL, i, &idx, &type);
+        if (hpiError)
+            continue;
+
+        /* Try to open adapter */
+        hpiError = HPI_AdapterOpen( NULL, idx );
+        /* Report error and skip to next device on failure */
+        if( hpiError )
+        {
+            PA_ASIHPI_REPORT_ERROR_( hpiError );
+            continue;
+        }
+        hpiError = HPI_AdapterGetInfo( NULL, idx, &outStreams, &inStreams,
+                                       &version, &serial, &type );
+        /* Skip to next device on failure */
+        if( hpiError )
+        {
+            PA_ASIHPI_REPORT_ERROR_( hpiError );
+            continue;
+        }
+        else
+        {
+            /* Assign default devices if available and increment device count */
+            if( (baseApiInfo->defaultInputDevice == paNoDevice) && (inStreams > 0) )
+                baseApiInfo->defaultInputDevice = deviceCount;
+            deviceCount += inStreams;
+            if( (baseApiInfo->defaultOutputDevice == paNoDevice) && (outStreams > 0) )
+                baseApiInfo->defaultOutputDevice = deviceCount;
+            deviceCount += outStreams;
+        }
+    }
+
+    /* Register any discovered devices */
+    if( deviceCount > 0 )
+    {
+        /* Memory allocation */
+        PA_UNLESS_( hostApi->deviceInfos = (PaDeviceInfo**) PaUtil_GroupAllocateMemory(
+                                               hpiHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount ),
+                    paInsufficientMemory );
+        /* Allocate all device info structs in a contiguous block */
+        PA_UNLESS_( hpiDeviceList = (PaAsiHpiDeviceInfo*) PaUtil_GroupAllocateMemory(
+                                        hpiHostApi->allocations, sizeof(PaAsiHpiDeviceInfo) * deviceCount ),
+                    paInsufficientMemory );
+
+        /* Now query devices again for information */
+        for( i=0; i < numAdapters; ++i )
+        {
+            uint16_t inStreams, outStreams;
+            uint16_t version;
+            uint32_t serial;
+            uint16_t type;
+            uint32_t idx;
+
+            hpiError = HPI_SubSysGetAdapter( NULL, i, &idx, &type );
+            if (hpiError)
+                continue;
+
+            /* Assume adapter is still open from previous round */
+            hpiError = HPI_AdapterGetInfo( NULL, idx,
+                                           &outStreams, &inStreams, &version, &serial, &type );
+            /* Report error and skip to next device on failure */
+            if( hpiError )
+            {
+                PA_ASIHPI_REPORT_ERROR_( hpiError );
+                continue;
+            }
+            else
+            {
+                PA_DEBUG(( "Found HPI Adapter ID=%4X Idx=%d #In=%d #Out=%d S/N=%d HWver=%c%d DSPver=%03d\n",
+                           type, idx, inStreams, outStreams, serial,
+                           ((version>>3)&0xf)+'A',                  /* Hw version major */
+                           version&0x7,                             /* Hw version minor */
+                           ((version>>13)*100)+((version>>7)&0x3f)  /* DSP code version */
+                         ));
+            }
+
+            /* First add all input streams as devices */
+            for( j=0; j < inStreams; ++j )
+            {
+                PaAsiHpiDeviceInfo *hpiDevice = &hpiDeviceList[deviceIndex];
+                PaDeviceInfo *baseDeviceInfo = &hpiDevice->baseDeviceInfo;
+                char srcName[72];
+                char *deviceName;
+
+                memset( hpiDevice, 0, sizeof(PaAsiHpiDeviceInfo) );
+                /* Set implementation-specific device details */
+                hpiDevice->adapterIndex = idx;
+                hpiDevice->adapterType = type;
+                hpiDevice->adapterVersion = version;
+                hpiDevice->adapterSerialNumber = serial;
+                hpiDevice->streamIndex = j;
+                hpiDevice->streamIsOutput = 0;
+                /* Set common PortAudio device stats */
+                baseDeviceInfo->structVersion = 2;
+                /* Make sure name string is owned by API info structure */
+                sprintf( srcName,
+                         "Adapter %d (%4X) - Input Stream %d", i+1, type, j+1 );
+                PA_UNLESS_( deviceName = (char *) PaUtil_GroupAllocateMemory(
+                                             hpiHostApi->allocations, strlen(srcName) + 1 ), paInsufficientMemory );
+                strcpy( deviceName, srcName );
+                baseDeviceInfo->name = deviceName;
+                baseDeviceInfo->hostApi = hpiHostApi->hostApiIndex;
+                baseDeviceInfo->maxInputChannels = HPI_MAX_CHANNELS;
+                baseDeviceInfo->maxOutputChannels = 0;
+                /* Default latency values for interactive performance */
+                baseDeviceInfo->defaultLowInputLatency = 0.01;
+                baseDeviceInfo->defaultLowOutputLatency = -1.0;
+                /* Default latency values for robust non-interactive applications (eg. playing sound files) */
+                baseDeviceInfo->defaultHighInputLatency = 0.2;
+                baseDeviceInfo->defaultHighOutputLatency = -1.0;
+                /* HPI interface can actually handle any sampling rate to 1 Hz accuracy,
+                * so this default is as good as any */
+                baseDeviceInfo->defaultSampleRate = 44100;
+
+                /* Store device in global PortAudio list */
+                hostApi->deviceInfos[deviceIndex++] = (PaDeviceInfo *) hpiDevice;
+            }
+
+            /* Now add all output streams as devices (I know, the repetition is painful) */
+            for( j=0; j < outStreams; ++j )
+            {
+                PaAsiHpiDeviceInfo *hpiDevice = &hpiDeviceList[deviceIndex];
+                PaDeviceInfo *baseDeviceInfo = &hpiDevice->baseDeviceInfo;
+                char srcName[72];
+                char *deviceName;
+
+                memset( hpiDevice, 0, sizeof(PaAsiHpiDeviceInfo) );
+                /* Set implementation-specific device details */
+                hpiDevice->adapterIndex = idx;
+                hpiDevice->adapterType = type;
+                hpiDevice->adapterVersion = version;
+                hpiDevice->adapterSerialNumber = serial;
+                hpiDevice->streamIndex = j;
+                hpiDevice->streamIsOutput = 1;
+                /* Set common PortAudio device stats */
+                baseDeviceInfo->structVersion = 2;
+                /* Make sure name string is owned by API info structure */
+                sprintf( srcName,
+                         "Adapter %d (%4X) - Output Stream %d", i+1, type, j+1 );
+                PA_UNLESS_( deviceName = (char *) PaUtil_GroupAllocateMemory(
+                                             hpiHostApi->allocations, strlen(srcName) + 1 ), paInsufficientMemory );
+                strcpy( deviceName, srcName );
+                baseDeviceInfo->name = deviceName;
+                baseDeviceInfo->hostApi = hpiHostApi->hostApiIndex;
+                baseDeviceInfo->maxInputChannels = 0;
+                baseDeviceInfo->maxOutputChannels = HPI_MAX_CHANNELS;
+                /* Default latency values for interactive performance. */
+                baseDeviceInfo->defaultLowInputLatency = -1.0;
+                baseDeviceInfo->defaultLowOutputLatency = 0.01;
+                /* Default latency values for robust non-interactive applications (eg. playing sound files). */
+                baseDeviceInfo->defaultHighInputLatency = -1.0;
+                baseDeviceInfo->defaultHighOutputLatency = 0.2;
+                /* HPI interface can actually handle any sampling rate to 1 Hz accuracy,
+                * so this default is as good as any */
+                baseDeviceInfo->defaultSampleRate = 44100;
+
+                /* Store device in global PortAudio list */
+                hostApi->deviceInfos[deviceIndex++] = (PaDeviceInfo *) hpiDevice;
+            }
+        }
+    }
+
+    /* Finally acknowledge checked devices */
+    baseApiInfo->deviceCount = deviceIndex;
+
+error:
+    return result;
+}
+
+
+/** Initialize host API implementation.
+ This is the only function exported beyond this file. It is called by PortAudio to initialize
+ the host API. It stores API info, finds and registers all devices, and sets up callback and
+ blocking interfaces.
+
+ @param hostApi Pointer to host API struct
+
+ @param hostApiIndex Index of current (HPI) host API
+
+ @return PortAudio error code
+ */
+PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaAsiHpiHostApiRepresentation *hpiHostApi = NULL;
+    PaHostApiInfo *baseApiInfo;
+
+    /* Try to initialize HPI subsystem */
+    if (!HPI_SubSysCreate())
+    {
+        /* the V19 development docs say that if an implementation
+         * detects that it cannot be used, it should return a NULL
+         * interface and paNoError */
+        PA_DEBUG(( "Could not open HPI interface\n" ));
+
+       *hostApi = NULL;
+        return paNoError;
+    }
+    else
+    {
+        uint32_t hpiVersion;
+        PA_ASIHPI_UNLESS_( HPI_SubSysGetVersionEx( NULL, &hpiVersion ), paUnanticipatedHostError );
+        PA_DEBUG(( "HPI interface v%d.%02d.%02d\n",
+                   hpiVersion >> 16,  (hpiVersion >> 8) & 0x0F, (hpiVersion & 0x0F) ));
+    }
+
+    /* Allocate host API structure */
+    PA_UNLESS_( hpiHostApi = (PaAsiHpiHostApiRepresentation*) PaUtil_AllocateMemory(
+                                 sizeof(PaAsiHpiHostApiRepresentation) ), paInsufficientMemory );
+    PA_UNLESS_( hpiHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+
+    hpiHostApi->hostApiIndex = hostApiIndex;
+
+    *hostApi = &hpiHostApi->baseHostApiRep;
+    baseApiInfo = &((*hostApi)->info);
+    /* Fill in common API details */
+    baseApiInfo->structVersion = 1;
+    baseApiInfo->type = paAudioScienceHPI;
+    baseApiInfo->name = "AudioScience HPI";
+    baseApiInfo->deviceCount = 0;
+    baseApiInfo->defaultInputDevice = paNoDevice;
+    baseApiInfo->defaultOutputDevice = paNoDevice;
+
+    PA_ENSURE_( PaAsiHpi_BuildDeviceList( hpiHostApi ) );
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &hpiHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &hpiHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    /* Store identity of main thread */
+    PA_ENSURE_( PaUnixThreading_Initialize() );
+
+    return result;
+error:
+    if (hpiHostApi)
+        PaUtil_FreeMemory( hpiHostApi );
+    return result;
+}
+
+
+/** Terminate host API implementation.
+ This closes all HPI adapters and frees the HPI subsystem. It also frees the host API struct
+ memory. It should be called once for every PaAsiHpi_Initialize call.
+
+ @param Pointer to host API struct
+ */
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi;
+    int i;
+    PaError result = paNoError;
+
+    if( hpiHostApi )
+    {
+        /* Get rid of HPI-specific structures */
+        uint16_t lastAdapterIndex = HPI_MAX_ADAPTERS;
+        /* Iterate through device list and close adapters */
+        for( i=0; i < hostApi->info.deviceCount; ++i )
+        {
+            PaAsiHpiDeviceInfo *hpiDevice = (PaAsiHpiDeviceInfo *) hostApi->deviceInfos[ i ];
+            /* Close adapter only if it differs from previous one */
+            if( hpiDevice->adapterIndex != lastAdapterIndex )
+            {
+                /* Ignore errors (report only during debugging) */
+                PA_ASIHPI_UNLESS_( HPI_AdapterClose( NULL,
+                                                     hpiDevice->adapterIndex ), paNoError );
+                lastAdapterIndex = hpiDevice->adapterIndex;
+            }
+        }
+        /* Finally dismantle HPI subsystem */
+        HPI_SubSysFree( NULL );
+
+        if( hpiHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( hpiHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( hpiHostApi->allocations );
+        }
+
+        PaUtil_FreeMemory( hpiHostApi );
+    }
+error:
+    return;
+}
+
+
+/** Converts PortAudio sample format to equivalent HPI format.
+
+ @param paFormat PortAudio sample format
+
+ @return HPI sample format
+ */
+static uint16_t PaAsiHpi_PaToHpiFormat( PaSampleFormat paFormat )
+{
+    /* Ignore interleaving flag */
+    switch( paFormat & ~paNonInterleaved )
+    {
+    case paFloat32:
+        return HPI_FORMAT_PCM32_FLOAT;
+
+    case paInt32:
+        return HPI_FORMAT_PCM32_SIGNED;
+
+    case paInt24:
+        return HPI_FORMAT_PCM24_SIGNED;
+
+    case paInt16:
+        return HPI_FORMAT_PCM16_SIGNED;
+
+    case paUInt8:
+        return HPI_FORMAT_PCM8_UNSIGNED;
+
+        /* Default is 16-bit signed */
+    case paInt8:
+    default:
+        return HPI_FORMAT_PCM16_SIGNED;
+    }
+}
+
+
+/** Converts HPI sample format to equivalent PortAudio format.
+
+ @param paFormat HPI sample format
+
+ @return PortAudio sample format
+ */
+static PaSampleFormat PaAsiHpi_HpiToPaFormat( uint16_t hpiFormat )
+{
+    switch( hpiFormat )
+    {
+    case HPI_FORMAT_PCM32_FLOAT:
+        return paFloat32;
+
+    case HPI_FORMAT_PCM32_SIGNED:
+        return paInt32;
+
+    case HPI_FORMAT_PCM24_SIGNED:
+        return paInt24;
+
+    case HPI_FORMAT_PCM16_SIGNED:
+        return paInt16;
+
+    case HPI_FORMAT_PCM8_UNSIGNED:
+        return paUInt8;
+
+        /* Default is custom format (e.g. for HPI MP3 format) */
+    default:
+        return paCustomFormat;
+    }
+}
+
+
+/** Creates HPI format struct based on PortAudio parameters.
+ This also does some checks to see whether the desired format is valid, and whether
+ the device allows it. This only checks the format of one half (input or output) of the
+ PortAudio stream.
+
+ @param hostApi Pointer to host API struct
+
+ @param parameters Pointer to stream parameter struct
+
+ @param sampleRate Desired sample rate
+
+ @param hpiDevice Pointer to HPI device struct
+
+ @param hpiFormat Resulting HPI format returned here
+
+ @return PortAudio error code (typically indicating a problem with stream format)
+ */
+static PaError PaAsiHpi_CreateFormat( struct PaUtilHostApiRepresentation *hostApi,
+                                      const PaStreamParameters *parameters, double sampleRate,
+                                      PaAsiHpiDeviceInfo **hpiDevice, struct hpi_format *hpiFormat )
+{
+    int maxChannelCount = 0;
+    PaSampleFormat hostSampleFormat = 0;
+    hpi_err_t hpiError = 0;
+
+    /* Unless alternate device specification is supported, reject the use of
+       paUseHostApiSpecificDeviceSpecification */
+    if( parameters->device == paUseHostApiSpecificDeviceSpecification )
+        return paInvalidDevice;
+    else
+    {
+        assert( parameters->device < hostApi->info.deviceCount );
+        *hpiDevice = (PaAsiHpiDeviceInfo*) hostApi->deviceInfos[ parameters->device ];
+    }
+
+    /* Validate streamInfo - this implementation doesn't use custom stream info */
+    if( parameters->hostApiSpecificStreamInfo )
+        return paIncompatibleHostApiSpecificStreamInfo;
+
+    /* Check that device can support channel count */
+    if( (*hpiDevice)->streamIsOutput )
+    {
+        maxChannelCount = (*hpiDevice)->baseDeviceInfo.maxOutputChannels;
+    }
+    else
+    {
+        maxChannelCount = (*hpiDevice)->baseDeviceInfo.maxInputChannels;
+    }
+    if( (maxChannelCount == 0) || (parameters->channelCount > maxChannelCount) )
+        return paInvalidChannelCount;
+
+    /* All standard sample formats are supported by the buffer adapter,
+       and this implementation doesn't support any custom sample formats */
+    if( parameters->sampleFormat & paCustomFormat )
+        return paSampleFormatNotSupported;
+
+    /* Switch to closest HPI native format */
+    hostSampleFormat = PaUtil_SelectClosestAvailableFormat(PA_ASIHPI_AVAILABLE_FORMATS_,
+                       parameters->sampleFormat );
+    /* Setup format + info objects */
+    hpiError = HPI_FormatCreate( hpiFormat, (uint16_t)parameters->channelCount,
+                                 PaAsiHpi_PaToHpiFormat( hostSampleFormat ),
+                                 (uint32_t)sampleRate, 0, 0 );
+    if( hpiError )
+    {
+        PA_ASIHPI_REPORT_ERROR_( hpiError );
+        switch( hpiError )
+        {
+        case HPI_ERROR_INVALID_FORMAT:
+            return paSampleFormatNotSupported;
+
+        case HPI_ERROR_INVALID_SAMPLERATE:
+        case HPI_ERROR_INCOMPATIBLE_SAMPLERATE:
+            return paInvalidSampleRate;
+
+        case HPI_ERROR_INVALID_CHANNELS:
+            return paInvalidChannelCount;
+        }
+    }
+
+    return paNoError;
+}
+
+
+/** Open HPI input stream with given format.
+ This attempts to open HPI input stream with desired format. If the format is not supported
+ or the device is unavailable, the stream is closed and a PortAudio error code is returned.
+
+ @param hostApi Pointer to host API struct
+
+ @param hpiDevice Pointer to HPI device struct
+
+ @param hpiFormat Pointer to HPI format struct
+
+ @return PortAudio error code (typically indicating a problem with stream format or device)
+*/
+static PaError PaAsiHpi_OpenInput( struct PaUtilHostApiRepresentation *hostApi,
+                                   const PaAsiHpiDeviceInfo *hpiDevice, const struct hpi_format *hpiFormat,
+                                   hpi_handle_t *hpiStream )
+{
+    PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi;
+    PaError result = paNoError;
+    hpi_err_t hpiError = 0;
+
+    /* Catch misplaced output devices, as they typically have 0 input channels */
+    PA_UNLESS_( !hpiDevice->streamIsOutput, paInvalidChannelCount );
+    /* Try to open input stream */
+    PA_ASIHPI_UNLESS_( HPI_InStreamOpen( NULL, hpiDevice->adapterIndex,
+                                         hpiDevice->streamIndex, hpiStream ), paDeviceUnavailable );
+    /* Set input format (checking it in the process) */
+    /* Could also use HPI_InStreamQueryFormat, but this economizes the process */
+    hpiError = HPI_InStreamSetFormat( NULL, *hpiStream, (struct hpi_format*)hpiFormat );
+    if( hpiError )
+    {
+        PA_ASIHPI_REPORT_ERROR_( hpiError );
+        PA_ASIHPI_UNLESS_( HPI_InStreamClose( NULL, *hpiStream ), paNoError );
+        switch( hpiError )
+        {
+        case HPI_ERROR_INVALID_FORMAT:
+            return paSampleFormatNotSupported;
+
+        case HPI_ERROR_INVALID_SAMPLERATE:
+        case HPI_ERROR_INCOMPATIBLE_SAMPLERATE:
+            return paInvalidSampleRate;
+
+        case HPI_ERROR_INVALID_CHANNELS:
+            return paInvalidChannelCount;
+
+        default:
+            /* In case anything else went wrong */
+            return paInvalidDevice;
+        }
+    }
+
+error:
+    return result;
+}
+
+
+/** Open HPI output stream with given format.
+ This attempts to open HPI output stream with desired format. If the format is not supported
+ or the device is unavailable, the stream is closed and a PortAudio error code is returned.
+
+ @param hostApi Pointer to host API struct
+
+ @param hpiDevice Pointer to HPI device struct
+
+ @param hpiFormat Pointer to HPI format struct
+
+ @return PortAudio error code (typically indicating a problem with stream format or device)
+*/
+static PaError PaAsiHpi_OpenOutput( struct PaUtilHostApiRepresentation *hostApi,
+                                    const PaAsiHpiDeviceInfo *hpiDevice, const struct hpi_format *hpiFormat,
+                                    hpi_handle_t *hpiStream )
+{
+    PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi;
+    PaError result = paNoError;
+    hpi_err_t hpiError = 0;
+
+    /* Catch misplaced input devices, as they typically have 0 output channels */
+    PA_UNLESS_( hpiDevice->streamIsOutput, paInvalidChannelCount );
+    /* Try to open output stream */
+    PA_ASIHPI_UNLESS_( HPI_OutStreamOpen( NULL, hpiDevice->adapterIndex,
+                                          hpiDevice->streamIndex, hpiStream ), paDeviceUnavailable );
+
+    /* Check output format (format is set on first write to output stream) */
+    hpiError = HPI_OutStreamQueryFormat( NULL, *hpiStream, (struct hpi_format*)hpiFormat );
+    if( hpiError )
+    {
+        PA_ASIHPI_REPORT_ERROR_( hpiError );
+        PA_ASIHPI_UNLESS_( HPI_OutStreamClose( NULL, *hpiStream ), paNoError );
+        switch( hpiError )
+        {
+        case HPI_ERROR_INVALID_FORMAT:
+            return paSampleFormatNotSupported;
+
+        case HPI_ERROR_INVALID_SAMPLERATE:
+        case HPI_ERROR_INCOMPATIBLE_SAMPLERATE:
+            return paInvalidSampleRate;
+
+        case HPI_ERROR_INVALID_CHANNELS:
+            return paInvalidChannelCount;
+
+        default:
+            /* In case anything else went wrong */
+            return paInvalidDevice;
+        }
+    }
+
+error:
+    return result;
+}
+
+
+/** Checks whether the desired stream formats and devices are supported
+ (for both input and output).
+ This is done by actually opening the appropriate HPI streams and closing them again.
+
+ @param hostApi Pointer to host API struct
+
+ @param inputParameters Pointer to stream parameter struct for input side of stream
+
+ @param outputParameters Pointer to stream parameter struct for output side of stream
+
+ @param sampleRate Desired sample rate
+
+ @return PortAudio error code (paFormatIsSupported on success)
+ */
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaError result = paFormatIsSupported;
+    PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi;
+    PaAsiHpiDeviceInfo *hpiDevice = NULL;
+    struct hpi_format hpiFormat;
+
+    /* Input stream */
+    if( inputParameters )
+    {
+        hpi_handle_t hpiStream;
+        PA_DEBUG(( "%s: Checking input params: dev=%d, sr=%d, chans=%d, fmt=%d\n",
+                   __FUNCTION__, inputParameters->device, (int)sampleRate,
+                   inputParameters->channelCount, inputParameters->sampleFormat ));
+        /* Create and validate format */
+        PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, inputParameters, sampleRate,
+                                           &hpiDevice, &hpiFormat ) );
+        /* Open stream to further check format */
+        PA_ENSURE_( PaAsiHpi_OpenInput( hostApi, hpiDevice, &hpiFormat, &hpiStream ) );
+        /* Close stream again */
+        PA_ASIHPI_UNLESS_( HPI_InStreamClose( NULL, hpiStream ), paNoError );
+    }
+
+    /* Output stream */
+    if( outputParameters )
+    {
+        hpi_handle_t hpiStream;
+        PA_DEBUG(( "%s: Checking output params: dev=%d, sr=%d, chans=%d, fmt=%d\n",
+                   __FUNCTION__, outputParameters->device, (int)sampleRate,
+                   outputParameters->channelCount, outputParameters->sampleFormat ));
+        /* Create and validate format */
+        PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, outputParameters, sampleRate,
+                                           &hpiDevice, &hpiFormat ) );
+        /* Open stream to further check format */
+        PA_ENSURE_( PaAsiHpi_OpenOutput( hostApi, hpiDevice, &hpiFormat, &hpiStream ) );
+        /* Close stream again */
+        PA_ASIHPI_UNLESS_( HPI_OutStreamClose( NULL, hpiStream ), paNoError );
+    }
+
+error:
+    return result;
+}
+
+/* ---------------------------- Stream Interface ---------------------------- */
+
+/** Obtain HPI stream information.
+ This obtains info such as stream state and available data/space in buffers. It also
+ estimates whether an underflow or overflow occurred.
+
+ @param streamComp Pointer to stream component (input or output) to query
+
+ @param info Pointer to stream info struct that will contain result
+
+ @return PortAudio error code (either paNoError, paDeviceUnavailable or paUnanticipatedHostError)
+ */
+static PaError PaAsiHpi_GetStreamInfo( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStreamInfo *info )
+{
+    PaError result = paDeviceUnavailable;
+    uint16_t state;
+    uint32_t bufferSize, dataSize, frameCounter, auxDataSize, threshold;
+    uint32_t hwBufferSize, hwDataSize;
+
+    assert( streamComp );
+    assert( info );
+
+    /* First blank the stream info struct, in case something goes wrong below.
+       This saves the caller from initializing the struct. */
+    info->state = 0;
+    info->bufferSize = 0;
+    info->dataSize = 0;
+    info->frameCounter = 0;
+    info->auxDataSize = 0;
+    info->totalBufferedData = 0;
+    info->availableFrames = 0;
+    info->underflow = 0;
+    info->overflow = 0;
+
+    if( streamComp->hpiDevice && streamComp->hpiStream )
+    {
+        /* Obtain detailed stream info (either input or output) */
+        if( streamComp->hpiDevice->streamIsOutput )
+        {
+            PA_ASIHPI_UNLESS_( HPI_OutStreamGetInfoEx( NULL,
+                               streamComp->hpiStream,
+                               &state, &bufferSize, &dataSize, &frameCounter,
+                               &auxDataSize ), paUnanticipatedHostError );
+        }
+        else
+        {
+            PA_ASIHPI_UNLESS_( HPI_InStreamGetInfoEx( NULL,
+                               streamComp->hpiStream,
+                               &state, &bufferSize, &dataSize, &frameCounter,
+                               &auxDataSize ), paUnanticipatedHostError );
+        }
+        /* Load stream info */
+        info->state = state;
+        info->bufferSize = bufferSize;
+        info->dataSize = dataSize;
+        info->frameCounter = frameCounter;
+        info->auxDataSize = auxDataSize;
+        /* Determine total buffered data */
+        info->totalBufferedData = dataSize;
+        if( streamComp->hostBufferSize > 0 )
+            info->totalBufferedData += auxDataSize;
+        info->totalBufferedData /= streamComp->bytesPerFrame;
+        /* Determine immediately available frames */
+        info->availableFrames = streamComp->hpiDevice->streamIsOutput ?
+                                bufferSize - dataSize : dataSize;
+        info->availableFrames /= streamComp->bytesPerFrame;
+        /* Minimum space/data required in buffers */
+        threshold = PA_MIN( streamComp->tempBufferSize,
+                            streamComp->bytesPerFrame * PA_ASIHPI_MIN_FRAMES_ );
+        /* Obtain hardware buffer stats first, to simplify things */
+        hwBufferSize = streamComp->hardwareBufferSize;
+        hwDataSize = streamComp->hostBufferSize > 0 ? auxDataSize : dataSize;
+        /* Underflow is a bit tricky */
+        info->underflow = streamComp->hpiDevice->streamIsOutput ?
+                          /* Stream seems to start in drained state sometimes, so ignore initial underflow */
+                          (frameCounter > 0) && ( (state == HPI_STATE_DRAINED) || (hwDataSize == 0) ) :
+                          /* Input streams check the first-level (host) buffer for underflow */
+                          (state != HPI_STATE_STOPPED) && (dataSize < threshold);
+        /* Check for overflow in second-level (hardware) buffer for both input and output */
+        info->overflow = (state != HPI_STATE_STOPPED) && (hwBufferSize - hwDataSize < threshold);
+
+        return paNoError;
+    }
+
+error:
+    return result;
+}
+
+
+/** Display stream component information for debugging purposes.
+
+ @param streamComp Pointer to stream component (input or output) to query
+
+ @param stream Pointer to stream struct which contains the component above
+ */
+static void PaAsiHpi_StreamComponentDump( PaAsiHpiStreamComponent *streamComp,
+        PaAsiHpiStream *stream )
+{
+    PaAsiHpiStreamInfo streamInfo;
+
+    assert( streamComp );
+    assert( stream );
+
+    /* Name of soundcard/device used by component */
+    PA_DEBUG(( "device: %s\n", streamComp->hpiDevice->baseDeviceInfo.name ));
+    /* Unfortunately some overlap between input and output here */
+    if( streamComp->hpiDevice->streamIsOutput )
+    {
+        /* Settings on the user side (as experienced by user callback) */
+        PA_DEBUG(( "user: %d-bit, %d ",
+                   8*stream->bufferProcessor.bytesPerUserOutputSample,
+                   stream->bufferProcessor.outputChannelCount));
+        if( stream->bufferProcessor.userOutputIsInterleaved )
+        {
+            PA_DEBUG(( "interleaved channels, " ));
+        }
+        else
+        {
+            PA_DEBUG(( "non-interleaved channels, " ));
+        }
+        PA_DEBUG(( "%d frames/buffer, latency = %5.1f ms\n",
+                   stream->bufferProcessor.framesPerUserBuffer,
+                   1000*stream->baseStreamRep.streamInfo.outputLatency ));
+        /* Settings on the host side (internal to PortAudio host API) */
+        PA_DEBUG(( "host: %d-bit, %d interleaved channels, %d frames/buffer ",
+                   8*stream->bufferProcessor.bytesPerHostOutputSample,
+                   stream->bufferProcessor.outputChannelCount,
+                   stream->bufferProcessor.framesPerHostBuffer ));
+    }
+    else
+    {
+        /* Settings on the user side (as experienced by user callback) */
+        PA_DEBUG(( "user: %d-bit, %d ",
+                   8*stream->bufferProcessor.bytesPerUserInputSample,
+                   stream->bufferProcessor.inputChannelCount));
+        if( stream->bufferProcessor.userInputIsInterleaved )
+        {
+            PA_DEBUG(( "interleaved channels, " ));
+        }
+        else
+        {
+            PA_DEBUG(( "non-interleaved channels, " ));
+        }
+        PA_DEBUG(( "%d frames/buffer, latency = %5.1f ms\n",
+                   stream->bufferProcessor.framesPerUserBuffer,
+                   1000*stream->baseStreamRep.streamInfo.inputLatency ));
+        /* Settings on the host side (internal to PortAudio host API) */
+        PA_DEBUG(( "host: %d-bit, %d interleaved channels, %d frames/buffer ",
+                   8*stream->bufferProcessor.bytesPerHostInputSample,
+                   stream->bufferProcessor.inputChannelCount,
+                   stream->bufferProcessor.framesPerHostBuffer ));
+    }
+    switch( stream->bufferProcessor.hostBufferSizeMode )
+    {
+    case paUtilFixedHostBufferSize:
+        PA_DEBUG(( "[fixed] " ));
+        break;
+    case paUtilBoundedHostBufferSize:
+        PA_DEBUG(( "[bounded] " ));
+        break;
+    case paUtilUnknownHostBufferSize:
+        PA_DEBUG(( "[unknown] " ));
+        break;
+    case paUtilVariableHostBufferSizePartialUsageAllowed:
+        PA_DEBUG(( "[variable] " ));
+        break;
+    }
+    PA_DEBUG(( "(%d max)\n", streamComp->tempBufferSize / streamComp->bytesPerFrame ));
+    /* HPI hardware settings */
+    PA_DEBUG(( "HPI: adapter %d stream %d, %d-bit, %d-channel, %d Hz\n",
+               streamComp->hpiDevice->adapterIndex, streamComp->hpiDevice->streamIndex,
+               8 * streamComp->bytesPerFrame / streamComp->hpiFormat.wChannels,
+               streamComp->hpiFormat.wChannels,
+               streamComp->hpiFormat.dwSampleRate ));
+    /* Stream state and buffer levels */
+    PA_DEBUG(( "HPI: " ));
+    PaAsiHpi_GetStreamInfo( streamComp, &streamInfo );
+    switch( streamInfo.state )
+    {
+    case HPI_STATE_STOPPED:
+        PA_DEBUG(( "[STOPPED] " ));
+        break;
+    case HPI_STATE_PLAYING:
+        PA_DEBUG(( "[PLAYING] " ));
+        break;
+    case HPI_STATE_RECORDING:
+        PA_DEBUG(( "[RECORDING] " ));
+        break;
+    case HPI_STATE_DRAINED:
+        PA_DEBUG(( "[DRAINED] " ));
+        break;
+    default:
+        PA_DEBUG(( "[unknown state] " ));
+        break;
+    }
+    if( streamComp->hostBufferSize )
+    {
+        PA_DEBUG(( "host = %d/%d B, ", streamInfo.dataSize, streamComp->hostBufferSize ));
+        PA_DEBUG(( "hw = %d/%d (%d) B, ", streamInfo.auxDataSize,
+                   streamComp->hardwareBufferSize, streamComp->outputBufferCap ));
+    }
+    else
+    {
+        PA_DEBUG(( "hw = %d/%d B, ", streamInfo.dataSize, streamComp->hardwareBufferSize ));
+    }
+    PA_DEBUG(( "count = %d", streamInfo.frameCounter ));
+    if( streamInfo.overflow )
+    {
+        PA_DEBUG(( " [overflow]" ));
+    }
+    else if( streamInfo.underflow )
+    {
+        PA_DEBUG(( " [underflow]" ));
+    }
+    PA_DEBUG(( "\n" ));
+}
+
+
+/** Display stream information for debugging purposes.
+
+ @param stream Pointer to stream to query
+ */
+static void PaAsiHpi_StreamDump( PaAsiHpiStream *stream )
+{
+    assert( stream );
+
+    PA_DEBUG(( "\n------------------------- STREAM INFO FOR %p ---------------------------\n", stream ));
+    /* General stream info (input+output) */
+    if( stream->baseStreamRep.streamCallback )
+    {
+        PA_DEBUG(( "[callback] " ));
+    }
+    else
+    {
+        PA_DEBUG(( "[blocking] " ));
+    }
+    PA_DEBUG(( "sr=%d Hz, poll=%d ms, max %d frames/buf ",
+               (int)stream->baseStreamRep.streamInfo.sampleRate,
+               stream->pollingInterval, stream->maxFramesPerHostBuffer ));
+    switch( stream->state )
+    {
+    case paAsiHpiStoppedState:
+        PA_DEBUG(( "[stopped]\n" ));
+        break;
+    case paAsiHpiActiveState:
+        PA_DEBUG(( "[active]\n" ));
+        break;
+    case paAsiHpiCallbackFinishedState:
+        PA_DEBUG(( "[cb fin]\n" ));
+        break;
+    default:
+        PA_DEBUG(( "[unknown state]\n" ));
+        break;
+    }
+    if( stream->callbackMode )
+    {
+        PA_DEBUG(( "cb info: thread=%p, cbAbort=%d, cbFinished=%d\n",
+                   stream->thread.thread, stream->callbackAbort, stream->callbackFinished ));
+    }
+
+    PA_DEBUG(( "----------------------------------- Input  ------------------------------------\n" ));
+    if( stream->input )
+    {
+        PaAsiHpi_StreamComponentDump( stream->input, stream );
+    }
+    else
+    {
+        PA_DEBUG(( "*none*\n" ));
+    }
+
+    PA_DEBUG(( "----------------------------------- Output ------------------------------------\n" ));
+    if( stream->output )
+    {
+        PaAsiHpi_StreamComponentDump( stream->output, stream );
+    }
+    else
+    {
+        PA_DEBUG(( "*none*\n" ));
+    }
+    PA_DEBUG(( "-------------------------------------------------------------------------------\n\n" ));
+
+}
+
+
+/** Determine buffer sizes and allocate appropriate stream buffers.
+ This attempts to allocate a BBM (host) buffer for the HPI stream component (either input
+ or output, as both have similar buffer needs). Not all AudioScience adapters support BBM,
+ in which case the hardware buffer has to suffice. The size of the HPI host buffer is chosen
+ as a multiple of framesPerPaHostBuffer, and also influenced by the suggested latency and the
+ estimated minimum polling interval. The HPI host and hardware buffer sizes are stored, and an
+ appropriate cap for the hardware buffer is also calculated. Finally, the temporary stream
+ buffer which serves as the PortAudio host buffer for this implementation is allocated.
+ This buffer contains an integer number of user buffers, to simplify buffer adaption in the
+ buffer processor. The function returns paBufferTooBig if the HPI interface cannot allocate
+ an HPI host buffer of the desired size.
+
+ @param streamComp Pointer to stream component struct
+
+ @param pollingInterval Polling interval for stream, in milliseconds
+
+ @param framesPerPaHostBuffer Size of PortAudio host buffer, in frames
+
+ @param suggestedLatency Suggested latency for stream component, in seconds
+
+ @return PortAudio error code (possibly paBufferTooBig or paInsufficientMemory)
+ */
+static PaError PaAsiHpi_SetupBuffers( PaAsiHpiStreamComponent *streamComp, uint32_t pollingInterval,
+                                      unsigned long framesPerPaHostBuffer, PaTime suggestedLatency )
+{
+    PaError result = paNoError;
+    PaAsiHpiStreamInfo streamInfo;
+    unsigned long hpiBufferSize = 0, paHostBufferSize = 0;
+
+    assert( streamComp );
+    assert( streamComp->hpiDevice );
+
+    /* Obtain size of hardware buffer of HPI stream, since we will be activating BBM shortly
+       and afterwards the buffer size will refer to the BBM (host-side) buffer.
+       This is necessary to enable reliable detection of xruns. */
+    PA_ENSURE_( PaAsiHpi_GetStreamInfo( streamComp, &streamInfo ) );
+    streamComp->hardwareBufferSize = streamInfo.bufferSize;
+    hpiBufferSize = streamInfo.bufferSize;
+
+    /* Check if BBM (background bus mastering) is to be enabled */
+    if( PA_ASIHPI_USE_BBM_ )
+    {
+        uint32_t bbmBufferSize = 0, preLatencyBufferSize = 0;
+        hpi_err_t hpiError = 0;
+        PaTime pollingOverhead;
+
+        /* Check overhead of Pa_Sleep() call (minimum sleep duration in ms -> OS dependent) */
+        pollingOverhead = PaUtil_GetTime();
+        Pa_Sleep( 0 );
+        pollingOverhead = 1000*(PaUtil_GetTime() - pollingOverhead);
+        PA_DEBUG(( "polling overhead = %f ms (length of 0-second sleep)\n", pollingOverhead ));
+        /* Obtain minimum recommended size for host buffer (in bytes) */
+        PA_ASIHPI_UNLESS_( HPI_StreamEstimateBufferSize( &streamComp->hpiFormat,
+                           pollingInterval + (uint32_t)ceil( pollingOverhead ),
+                           &bbmBufferSize ), paUnanticipatedHostError );
+        /* BBM places more stringent requirements on buffer size (see description */
+        /* of HPI_StreamEstimateBufferSize in HPI API document) */
+        bbmBufferSize *= 3;
+        /* Make sure the BBM buffer contains multiple PA host buffers */
+        if( bbmBufferSize < 3 * streamComp->bytesPerFrame * framesPerPaHostBuffer )
+            bbmBufferSize = 3 * streamComp->bytesPerFrame * framesPerPaHostBuffer;
+        /* Try to honor latency suggested by user by growing buffer (no decrease possible) */
+        if( suggestedLatency > 0.0 )
+        {
+            PaTime bufferDuration = ((PaTime)bbmBufferSize) / streamComp->bytesPerFrame
+                                    / streamComp->hpiFormat.dwSampleRate;
+            /* Don't decrease buffer */
+            if( bufferDuration < suggestedLatency )
+            {
+                /* Save old buffer size, to be retried if new size proves too big */
+                preLatencyBufferSize = bbmBufferSize;
+                bbmBufferSize = (uint32_t)ceil( suggestedLatency * streamComp->bytesPerFrame
+                                            * streamComp->hpiFormat.dwSampleRate );
+            }
+        }
+        /* Choose closest memory block boundary (HPI API document states that
+        "a buffer size of Nx4096 - 20 makes the best use of memory"
+        (under the entry for HPI_StreamEstimateBufferSize)) */
+        bbmBufferSize = ((uint32_t)ceil((bbmBufferSize + 20)/4096.0))*4096 - 20;
+        streamComp->hostBufferSize = bbmBufferSize;
+        /* Allocate BBM host buffer (this enables bus mastering transfers in background) */
+        if( streamComp->hpiDevice->streamIsOutput )
+            hpiError = HPI_OutStreamHostBufferAllocate( NULL,
+                       streamComp->hpiStream,
+                       bbmBufferSize );
+        else
+            hpiError = HPI_InStreamHostBufferAllocate( NULL,
+                       streamComp->hpiStream,
+                       bbmBufferSize );
+        if( hpiError )
+        {
+            /* Indicate that BBM is disabled */
+            streamComp->hostBufferSize = 0;
+            /* Retry with smaller buffer size (transfers will still work, but not via BBM) */
+            if( hpiError == HPI_ERROR_INVALID_DATASIZE )
+            {
+                /* Retry BBM allocation with smaller size if requested latency proved too big */
+                if( preLatencyBufferSize > 0 )
+                {
+                    PA_DEBUG(( "Retrying BBM allocation with smaller size (%d vs. %d bytes)\n",
+                               preLatencyBufferSize, bbmBufferSize ));
+                    bbmBufferSize = preLatencyBufferSize;
+                    if( streamComp->hpiDevice->streamIsOutput )
+                        hpiError = HPI_OutStreamHostBufferAllocate( NULL,
+                                   streamComp->hpiStream,
+                                   bbmBufferSize );
+                    else
+                        hpiError = HPI_InStreamHostBufferAllocate( NULL,
+                                   streamComp->hpiStream,
+                                   bbmBufferSize );
+                    /* Another round of error checking */
+                    if( hpiError )
+                    {
+                        PA_ASIHPI_REPORT_ERROR_( hpiError );
+                        /* No escapes this time */
+                        if( hpiError == HPI_ERROR_INVALID_DATASIZE )
+                        {
+                            result = paBufferTooBig;
+                            goto error;
+                        }
+                        else if( hpiError != HPI_ERROR_INVALID_OPERATION )
+                        {
+                            result = paUnanticipatedHostError;
+                            goto error;
+                        }
+                    }
+                    else
+                    {
+                        streamComp->hostBufferSize = bbmBufferSize;
+                        hpiBufferSize = bbmBufferSize;
+                    }
+                }
+                else
+                {
+                    result = paBufferTooBig;
+                    goto error;
+                }
+            }
+            /* If BBM not supported, foreground transfers will be used, but not a show-stopper */
+            /* Anything else is an error */
+            else if (( hpiError != HPI_ERROR_INVALID_OPERATION ) &&
+                    ( hpiError != HPI_ERROR_INVALID_FUNC ))
+            {
+                PA_ASIHPI_REPORT_ERROR_( hpiError );
+                result = paUnanticipatedHostError;
+                goto error;
+            }
+        }
+        else
+        {
+            hpiBufferSize = bbmBufferSize;
+        }
+    }
+
+    /* Final check of buffer size */
+    paHostBufferSize = streamComp->bytesPerFrame * framesPerPaHostBuffer;
+    if( hpiBufferSize < 3*paHostBufferSize )
+    {
+        result = paBufferTooBig;
+        goto error;
+    }
+    /* Set cap on output buffer size, based on latency suggestions */
+    if( streamComp->hpiDevice->streamIsOutput )
+    {
+        PaTime latency = suggestedLatency > 0.0 ? suggestedLatency :
+                         streamComp->hpiDevice->baseDeviceInfo.defaultHighOutputLatency;
+        streamComp->outputBufferCap =
+            (uint32_t)ceil( latency * streamComp->bytesPerFrame * streamComp->hpiFormat.dwSampleRate );
+        /* The cap should not be too small, to prevent underflow */
+        if( streamComp->outputBufferCap < 4*paHostBufferSize )
+            streamComp->outputBufferCap = 4*paHostBufferSize;
+    }
+    else
+    {
+        streamComp->outputBufferCap = 0;
+    }
+    /* Temp buffer size should be multiple of PA host buffer size (or 1x, if using fixed blocks) */
+    streamComp->tempBufferSize = paHostBufferSize;
+    /* Allocate temp buffer */
+    PA_UNLESS_( streamComp->tempBuffer = (uint8_t *)PaUtil_AllocateMemory( streamComp->tempBufferSize ),
+                paInsufficientMemory );
+error:
+    return result;
+}
+
+
+/** Opens PortAudio stream.
+ This determines a suitable value for framesPerBuffer, if the user didn't specify it,
+ based on the suggested latency. It then opens each requested stream direction with the
+ appropriate stream format, and allocates the required stream buffers. It sets up the
+ various PortAudio structures dealing with streams, and estimates the stream latency.
+
+ See pa_hostapi.h for a list of validity guarantees made about OpenStream parameters.
+
+ @param hostApi Pointer to host API struct
+
+ @param s List of open streams, where successfully opened stream will go
+
+ @param inputParameters Pointer to stream parameter struct for input side of stream
+
+ @param outputParameters Pointer to stream parameter struct for output side of stream
+
+ @param sampleRate Desired sample rate
+
+ @param framesPerBuffer Desired number of frames per buffer passed to user callback
+                        (or chunk size for blocking stream)
+
+ @param streamFlags Stream flags
+
+ @param streamCallback Pointer to user callback function (zero for blocking interface)
+
+ @param userData Pointer to user data that will be passed to callback function along with data
+
+ @return PortAudio error code
+*/
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream **s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi;
+    PaAsiHpiStream *stream = NULL;
+    unsigned long framesPerHostBuffer = framesPerBuffer;
+    int inputChannelCount = 0, outputChannelCount = 0;
+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+    PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0;
+    PaTime maxSuggestedLatency = 0.0;
+
+    /* Validate platform-specific flags -> none expected for HPI */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform-specific flag */
+
+    /* Create blank stream structure */
+    PA_UNLESS_( stream = (PaAsiHpiStream *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStream) ),
+                paInsufficientMemory );
+    memset( stream, 0, sizeof(PaAsiHpiStream) );
+
+    /* If the number of frames per buffer is unspecified, we have to come up with one. */
+    if( framesPerHostBuffer == paFramesPerBufferUnspecified )
+    {
+        if( inputParameters )
+            maxSuggestedLatency = inputParameters->suggestedLatency;
+        if( outputParameters && (outputParameters->suggestedLatency > maxSuggestedLatency) )
+            maxSuggestedLatency = outputParameters->suggestedLatency;
+        /* Use suggested latency if available */
+        if( maxSuggestedLatency > 0.0 )
+            framesPerHostBuffer = (unsigned long)ceil( maxSuggestedLatency * sampleRate );
+        else
+            /* AudioScience cards like BIG buffers by default */
+            framesPerHostBuffer = 4096;
+    }
+    /* Lower bounds on host buffer size, due to polling and HPI constraints */
+    if( 1000.0*framesPerHostBuffer/sampleRate < PA_ASIHPI_MIN_POLLING_INTERVAL_ )
+        framesPerHostBuffer = (unsigned long)ceil( sampleRate * PA_ASIHPI_MIN_POLLING_INTERVAL_ / 1000.0 );
+    /*    if( framesPerHostBuffer < PA_ASIHPI_MIN_FRAMES_ )
+            framesPerHostBuffer = PA_ASIHPI_MIN_FRAMES_; */
+    /* Efficient if host buffer size is integer multiple of user buffer size */
+    if( framesPerBuffer > 0 )
+        framesPerHostBuffer = (unsigned long)ceil( (double)framesPerHostBuffer / framesPerBuffer ) * framesPerBuffer;
+    /* Buffer should always be a multiple of 4 bytes to facilitate 32-bit PCI transfers.
+     By keeping the frames a multiple of 4, this is ensured even for 8-bit mono sound. */
+    framesPerHostBuffer = (framesPerHostBuffer / 4) * 4;
+    /* Polling is based on time length (in milliseconds) of user-requested block size */
+    stream->pollingInterval = (uint32_t)ceil( 1000.0*framesPerHostBuffer/sampleRate );
+    assert( framesPerHostBuffer > 0 );
+
+    /* Open underlying streams, check formats and allocate buffers */
+    if( inputParameters )
+    {
+        /* Create blank stream component structure */
+        PA_UNLESS_( stream->input = (PaAsiHpiStreamComponent *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStreamComponent) ),
+                    paInsufficientMemory );
+        memset( stream->input, 0, sizeof(PaAsiHpiStreamComponent) );
+        /* Create/validate format */
+        PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, inputParameters, sampleRate,
+                                           &stream->input->hpiDevice, &stream->input->hpiFormat ) );
+        /* Open stream and set format */
+        PA_ENSURE_( PaAsiHpi_OpenInput( hostApi, stream->input->hpiDevice, &stream->input->hpiFormat,
+                                        &stream->input->hpiStream ) );
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        hostInputSampleFormat = PaAsiHpi_HpiToPaFormat( stream->input->hpiFormat.wFormat );
+        stream->input->bytesPerFrame = inputChannelCount * Pa_GetSampleSize( hostInputSampleFormat );
+        assert( stream->input->bytesPerFrame > 0 );
+        /* Allocate host and temp buffers of appropriate size */
+        PA_ENSURE_( PaAsiHpi_SetupBuffers( stream->input, stream->pollingInterval,
+                                           framesPerHostBuffer, inputParameters->suggestedLatency ) );
+    }
+    if( outputParameters )
+    {
+        /* Create blank stream component structure */
+        PA_UNLESS_( stream->output = (PaAsiHpiStreamComponent *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStreamComponent) ),
+                    paInsufficientMemory );
+        memset( stream->output, 0, sizeof(PaAsiHpiStreamComponent) );
+        /* Create/validate format */
+        PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, outputParameters, sampleRate,
+                                           &stream->output->hpiDevice, &stream->output->hpiFormat ) );
+        /* Open stream and check format */
+        PA_ENSURE_( PaAsiHpi_OpenOutput( hostApi, stream->output->hpiDevice,
+                                         &stream->output->hpiFormat,
+                                         &stream->output->hpiStream ) );
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        hostOutputSampleFormat = PaAsiHpi_HpiToPaFormat( stream->output->hpiFormat.wFormat );
+        stream->output->bytesPerFrame = outputChannelCount * Pa_GetSampleSize( hostOutputSampleFormat );
+        /* Allocate host and temp buffers of appropriate size */
+        PA_ENSURE_( PaAsiHpi_SetupBuffers( stream->output, stream->pollingInterval,
+                                           framesPerHostBuffer, outputParameters->suggestedLatency ) );
+    }
+
+    /* Determine maximum frames per host buffer (least common denominator of input/output) */
+    if( inputParameters && outputParameters )
+    {
+        stream->maxFramesPerHostBuffer = PA_MIN( stream->input->tempBufferSize / stream->input->bytesPerFrame,
+                                         stream->output->tempBufferSize / stream->output->bytesPerFrame );
+    }
+    else
+    {
+        stream->maxFramesPerHostBuffer = inputParameters ? stream->input->tempBufferSize / stream->input->bytesPerFrame
+                                         : stream->output->tempBufferSize / stream->output->bytesPerFrame;
+    }
+    assert( stream->maxFramesPerHostBuffer > 0 );
+    /* Initialize various other stream parameters */
+    stream->neverDropInput = streamFlags & paNeverDropInput;
+    stream->state = paAsiHpiStoppedState;
+
+    /* Initialize either callback or blocking interface */
+    if( streamCallback )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->baseStreamRep,
+                                               &hpiHostApi->callbackStreamInterface,
+                                               streamCallback, userData );
+        stream->callbackMode = 1;
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->baseStreamRep,
+                                               &hpiHostApi->blockingStreamInterface,
+                                               streamCallback, userData );
+        /* Pre-allocate non-interleaved user buffer pointers for blocking interface */
+        PA_UNLESS_( stream->blockingUserBufferCopy =
+                        PaUtil_AllocateMemory( sizeof(void *) * PA_MAX( inputChannelCount, outputChannelCount ) ),
+                    paInsufficientMemory );
+        stream->callbackMode = 0;
+    }
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+    /* Following pa_linux_alsa's lead, we operate with fixed host buffer size by default, */
+    /* since other modes will invariably lead to block adaption (maybe Bounded better?) */
+    PA_ENSURE_( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+                outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+                sampleRate, streamFlags,
+                framesPerBuffer, framesPerHostBuffer, paUtilFixedHostBufferSize,
+                streamCallback, userData ) );
+
+    stream->baseStreamRep.streamInfo.structVersion = 1;
+    stream->baseStreamRep.streamInfo.sampleRate = sampleRate;
+    /* Determine input latency from buffer processor and buffer sizes */
+    if( stream->input )
+    {
+        PaTime bufferDuration = ( stream->input->hostBufferSize + stream->input->hardwareBufferSize )
+                                / sampleRate / stream->input->bytesPerFrame;
+        stream->baseStreamRep.streamInfo.inputLatency =
+            bufferDuration +
+            ((PaTime)PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor ) -
+                stream->maxFramesPerHostBuffer) / sampleRate;
+        assert( stream->baseStreamRep.streamInfo.inputLatency > 0.0 );
+    }
+    /* Determine output latency from buffer processor and buffer sizes */
+    if( stream->output )
+    {
+        PaTime bufferDuration = ( stream->output->hostBufferSize + stream->output->hardwareBufferSize )
+                                / sampleRate / stream->output->bytesPerFrame;
+        /* Take buffer size cap into account (see PaAsiHpi_WaitForFrames) */
+        if( !stream->input && (stream->output->outputBufferCap > 0) )
+        {
+            bufferDuration = PA_MIN( bufferDuration,
+                                     stream->output->outputBufferCap / sampleRate / stream->output->bytesPerFrame );
+        }
+        stream->baseStreamRep.streamInfo.outputLatency =
+            bufferDuration +
+            ((PaTime)PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor ) -
+                stream->maxFramesPerHostBuffer) / sampleRate;
+        assert( stream->baseStreamRep.streamInfo.outputLatency > 0.0 );
+    }
+
+    /* Report stream info, for debugging purposes */
+    PaAsiHpi_StreamDump( stream );
+
+    /* Save initialized stream to PA stream list */
+    *s = (PaStream*)stream;
+    return result;
+
+error:
+    CloseStream( (PaStream*)stream );
+    return result;
+}
+
+
+/** Close PortAudio stream.
+ When CloseStream() is called, the multi-api layer ensures that the stream has already
+ been stopped or aborted. This closes the underlying HPI streams and deallocates stream
+ buffers and structs.
+
+ @param s Pointer to PortAudio stream
+
+ @return PortAudio error code
+*/
+static PaError CloseStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+
+    /* If stream is already gone, all is well */
+    if( stream == NULL )
+        return paNoError;
+
+    /* Generic stream cleanup */
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->baseStreamRep );
+
+    /* Implementation-specific details - close internal streams */
+    if( stream->input )
+    {
+        /* Close HPI stream (freeing BBM host buffer in the process, if used) */
+        if( stream->input->hpiStream )
+        {
+            PA_ASIHPI_UNLESS_( HPI_InStreamClose( NULL,
+                                                  stream->input->hpiStream ), paUnanticipatedHostError );
+        }
+        /* Free temp buffer and stream component */
+        PaUtil_FreeMemory( stream->input->tempBuffer );
+        PaUtil_FreeMemory( stream->input );
+    }
+    if( stream->output )
+    {
+        /* Close HPI stream (freeing BBM host buffer in the process, if used) */
+        if( stream->output->hpiStream )
+        {
+            PA_ASIHPI_UNLESS_( HPI_OutStreamClose( NULL,
+                                                   stream->output->hpiStream ), paUnanticipatedHostError );
+        }
+        /* Free temp buffer and stream component */
+        PaUtil_FreeMemory( stream->output->tempBuffer );
+        PaUtil_FreeMemory( stream->output );
+    }
+
+    PaUtil_FreeMemory( stream->blockingUserBufferCopy );
+    PaUtil_FreeMemory( stream );
+
+error:
+    return result;
+}
+
+
+/** Prime HPI output stream with silence.
+ This resets the output stream and uses PortAudio helper routines to fill the
+ temp buffer with silence. It then writes two host buffers to the stream. This is supposed
+ to be called before the stream is started. It has no effect on input-only streams.
+
+ @param stream Pointer to stream struct
+
+ @return PortAudio error code
+ */
+static PaError PaAsiHpi_PrimeOutputWithSilence( PaAsiHpiStream *stream )
+{
+    PaError result = paNoError;
+    PaAsiHpiStreamComponent *out;
+    PaUtilZeroer *zeroer;
+    PaSampleFormat outputFormat;
+    assert( stream );
+    out = stream->output;
+    /* Only continue if stream has output channels */
+    if( !out )
+        return result;
+    assert( out->tempBuffer );
+
+    /* Clear all existing data in hardware playback buffer */
+    PA_ASIHPI_UNLESS_( HPI_OutStreamReset( NULL,
+                                           out->hpiStream ), paUnanticipatedHostError );
+    /* Fill temp buffer with silence */
+    outputFormat = PaAsiHpi_HpiToPaFormat( out->hpiFormat.wFormat );
+    zeroer = PaUtil_SelectZeroer( outputFormat );
+    zeroer(out->tempBuffer, 1, out->tempBufferSize / Pa_GetSampleSize(outputFormat) );
+    /* Write temp buffer to hardware fifo twice, to get started */
+    PA_ASIHPI_UNLESS_( HPI_OutStreamWriteBuf( NULL, out->hpiStream,
+                                              out->tempBuffer, out->tempBufferSize, &out->hpiFormat),
+                                              paUnanticipatedHostError );
+    PA_ASIHPI_UNLESS_( HPI_OutStreamWriteBuf( NULL, out->hpiStream,
+                                              out->tempBuffer, out->tempBufferSize, &out->hpiFormat),
+                                              paUnanticipatedHostError );
+error:
+    return result;
+}
+
+
+/** Start HPI streams (both input + output).
+ This starts all HPI streams in the PortAudio stream. Output streams are first primed with
+ silence, if required. After this call the PA stream is in the Active state.
+
+ @todo Implement priming via the user callback
+
+ @param stream Pointer to stream struct
+
+ @param outputPrimed True if output is already primed (if false, silence will be loaded before starting)
+
+ @return PortAudio error code
+ */
+static PaError PaAsiHpi_StartStream( PaAsiHpiStream *stream, int outputPrimed )
+{
+    PaError result = paNoError;
+
+    if( stream->input )
+    {
+        PA_ASIHPI_UNLESS_( HPI_InStreamStart( NULL,
+                                              stream->input->hpiStream ), paUnanticipatedHostError );
+    }
+    if( stream->output )
+    {
+        if( !outputPrimed )
+        {
+            /* Buffer isn't primed, so load stream with silence */
+            PA_ENSURE_( PaAsiHpi_PrimeOutputWithSilence( stream ) );
+        }
+        PA_ASIHPI_UNLESS_( HPI_OutStreamStart( NULL,
+                                               stream->output->hpiStream ), paUnanticipatedHostError );
+    }
+    stream->state = paAsiHpiActiveState;
+    stream->callbackFinished = 0;
+
+    /* Report stream info for debugging purposes */
+    /*    PaAsiHpi_StreamDump( stream );   */
+
+error:
+    return result;
+}
+
+
+/** Start PortAudio stream.
+ If the stream has a callback interface, this starts a helper thread to feed the user callback.
+ The thread will then take care of starting the HPI streams, and this function will block
+ until the streams actually start. In the case of a blocking interface, the HPI streams
+ are simply started.
+
+ @param s Pointer to PortAudio stream
+
+ @return PortAudio error code
+*/
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+
+    assert( stream );
+
+    /* Ready the processor */
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    if( stream->callbackMode )
+    {
+        /* Create and start callback engine thread */
+        /* Also waits 1 second for stream to be started by engine thread (otherwise aborts) */
+        PA_ENSURE_( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., 0 /*rtSched*/ ) );
+    }
+    else
+    {
+        PA_ENSURE_( PaAsiHpi_StartStream( stream, 0 ) );
+    }
+
+error:
+    return result;
+}
+
+
+/** Stop HPI streams (input + output), either softly or abruptly.
+ If abort is false, the function blocks until the output stream is drained, otherwise it
+ stops immediately and discards data in the stream hardware buffers.
+
+ This function is safe to call from the callback engine thread as well as the main thread.
+
+ @param stream Pointer to stream struct
+
+ @param abort True if samples in output buffer should be discarded (otherwise blocks until stream is done)
+
+ @return PortAudio error code
+
+ */
+static PaError PaAsiHpi_StopStream( PaAsiHpiStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    assert( stream );
+
+    /* Input channels */
+    if( stream->input )
+    {
+        PA_ASIHPI_UNLESS_( HPI_InStreamReset( NULL,
+                                              stream->input->hpiStream ), paUnanticipatedHostError );
+    }
+    /* Output channels */
+    if( stream->output )
+    {
+        if( !abort )
+        {
+            /* Wait until HPI output stream is drained */
+            while( 1 )
+            {
+                PaAsiHpiStreamInfo streamInfo;
+                PaTime timeLeft;
+
+                /* Obtain number of samples waiting to be played */
+                PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &streamInfo ) );
+                /* Check if stream is drained */
+                if( (streamInfo.state != HPI_STATE_PLAYING) &&
+                        (streamInfo.dataSize < stream->output->bytesPerFrame * PA_ASIHPI_MIN_FRAMES_) )
+                    break;
+                /* Sleep amount of time represented by remaining samples */
+                timeLeft = 1000.0 * streamInfo.dataSize / stream->output->bytesPerFrame
+                           / stream->baseStreamRep.streamInfo.sampleRate;
+                Pa_Sleep( (long)ceil( timeLeft ) );
+            }
+        }
+        PA_ASIHPI_UNLESS_( HPI_OutStreamReset( NULL,
+                                               stream->output->hpiStream ), paUnanticipatedHostError );
+    }
+
+    /* Report stream info for debugging purposes */
+    /*    PaAsiHpi_StreamDump( stream ); */
+
+error:
+    return result;
+}
+
+
+/** Stop or abort PortAudio stream.
+
+ This function is used to explicitly stop the PortAudio stream (via StopStream/AbortStream),
+ as opposed to the situation when the callback finishes with a result other than paContinue.
+ If a stream is in callback mode we will have to inspect whether the background thread has
+ finished, or we will have to take it out. In either case we join the thread before returning.
+ In blocking mode, we simply tell HPI to stop abruptly (abort) or finish buffers (drain).
+ The PortAudio stream will be in the Stopped state after a call to this function.
+
+ Don't call this from the callback engine thread!
+
+ @param stream Pointer to stream struct
+
+ @param abort True if samples in output buffer should be discarded (otherwise blocks until stream is done)
+
+ @return PortAudio error code
+*/
+static PaError PaAsiHpi_ExplicitStop( PaAsiHpiStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    /* First deal with the callback thread, cancelling and/or joining it if necessary */
+    if( stream->callbackMode )
+    {
+        PaError threadRes;
+        stream->callbackAbort = abort;
+        if( abort )
+        {
+            PA_DEBUG(( "Aborting callback\n" ));
+        }
+        else
+        {
+            PA_DEBUG(( "Stopping callback\n" ));
+        }
+        PA_ENSURE_( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) );
+        if( threadRes != paNoError )
+        {
+            PA_DEBUG(( "Callback thread returned: %d\n", threadRes ));
+        }
+    }
+    else
+    {
+        PA_ENSURE_( PaAsiHpi_StopStream( stream, abort ) );
+    }
+
+    stream->state = paAsiHpiStoppedState;
+
+error:
+    return result;
+}
+
+
+/** Stop PortAudio stream.
+ This blocks until the output buffers are drained.
+
+ @param s Pointer to PortAudio stream
+
+ @return PortAudio error code
+*/
+static PaError StopStream( PaStream *s )
+{
+    return PaAsiHpi_ExplicitStop( (PaAsiHpiStream *) s, 0 );
+}
+
+
+/** Abort PortAudio stream.
+ This discards any existing data in output buffers and stops the stream immediately.
+
+ @param s Pointer to PortAudio stream
+
+ @return PortAudio error code
+*/
+static PaError AbortStream( PaStream *s )
+{
+    return PaAsiHpi_ExplicitStop( (PaAsiHpiStream * ) s, 1 );
+}
+
+
+/** Determine whether the stream is stopped.
+ A stream is considered to be stopped prior to a successful call to StartStream and after
+ a successful call to StopStream or AbortStream. If a stream callback returns a value other
+ than paContinue the stream is NOT considered to be stopped (it is in CallbackFinished state).
+
+ @param s Pointer to PortAudio stream
+
+ @return Returns one (1) when the stream is stopped, zero (0) when the stream is running, or
+         a PaErrorCode (which are always negative) if PortAudio is not initialized or an
+         error is encountered.
+*/
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+
+    assert( stream );
+    return stream->state == paAsiHpiStoppedState ? 1 : 0;
+}
+
+
+/** Determine whether the stream is active.
+ A stream is active after a successful call to StartStream(), until it becomes inactive either
+ as a result of a call to StopStream() or AbortStream(), or as a result of a return value
+ other than paContinue from the stream callback. In the latter case, the stream is considered
+ inactive after the last buffer has finished playing.
+
+ @param s Pointer to PortAudio stream
+
+ @return Returns one (1) when the stream is active (i.e. playing or recording audio),
+         zero (0) when not playing, or a PaErrorCode (which are always negative)
+         if PortAudio is not initialized or an error is encountered.
+*/
+static PaError IsStreamActive( PaStream *s )
+{
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+
+    assert( stream );
+    return stream->state == paAsiHpiActiveState ? 1 : 0;
+}
+
+
+/** Returns current stream time.
+ This corresponds to the system clock. The clock should run continuously while the stream
+ is open, i.e. between calls to OpenStream() and CloseStream(), therefore a frame counter
+ is not good enough.
+
+ @param s Pointer to PortAudio stream
+
+ @return Stream time, in seconds
+ */
+static PaTime GetStreamTime( PaStream *s )
+{
+    return PaUtil_GetTime();
+}
+
+
+/** Returns CPU load.
+
+ @param s Pointer to PortAudio stream
+
+ @return CPU load (0.0 if blocking interface is used)
+ */
+static double GetStreamCpuLoad( PaStream *s )
+{
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+
+    return stream->callbackMode ? PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) : 0.0;
+}
+
+/* --------------------------- Callback Interface --------------------------- */
+
+/** Exit routine which is called when callback thread quits.
+ This takes care of stopping the HPI streams (either waiting for output to finish, or
+ abruptly). It also calls the user-supplied StreamFinished callback, and sets the
+ stream state to CallbackFinished if it was reached via a non-paContinue return from
+ the user callback function.
+
+ @param userData A pointer to an open stream previously created with Pa_OpenStream
+ */
+static void PaAsiHpi_OnThreadExit( void *userData )
+{
+    PaAsiHpiStream *stream = (PaAsiHpiStream *) userData;
+
+    assert( stream );
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+    PA_DEBUG(( "%s: Stopping HPI streams\n", __FUNCTION__ ));
+    PaAsiHpi_StopStream( stream, stream->callbackAbort );
+    PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
+
+    /* Eventually notify user all buffers have played */
+    if( stream->baseStreamRep.streamFinishedCallback )
+    {
+        stream->baseStreamRep.streamFinishedCallback( stream->baseStreamRep.userData );
+    }
+
+    /* Unfortunately both explicit calls to Stop/AbortStream (leading to Stopped state)
+     and implicit stops via paComplete/paAbort (leading to CallbackFinished state)
+     end up here - need another flag to remind us which is the case */
+    if( stream->callbackFinished )
+        stream->state = paAsiHpiCallbackFinishedState;
+}
+
+
+/** Wait until there is enough frames to fill a host buffer.
+ The routine attempts to sleep until at least a full host buffer can be retrieved from the
+ input HPI stream and passed to the output HPI stream. It will first sleep until enough
+ output space is available, as this is usually easily achievable. If it is an output-only
+ stream, it will also sleep if the hardware buffer is too full, thereby throttling the
+ filling of the output buffer and reducing output latency. The routine then blocks until
+ enough input samples are available, unless this will cause an output underflow. In the
+ process, input overflows and output underflows are indicated.
+
+ @param stream Pointer to stream struct
+
+ @param framesAvail Returns the number of available frames
+
+ @param cbFlags Overflows and underflows indicated in here
+
+ @return PortAudio error code (only paUnanticipatedHostError expected)
+ */
+static PaError PaAsiHpi_WaitForFrames( PaAsiHpiStream *stream, unsigned long *framesAvail,
+                                       PaStreamCallbackFlags *cbFlags )
+{
+    PaError result = paNoError;
+    double sampleRate;
+    unsigned long framesTarget;
+    uint32_t outputData = 0, outputSpace = 0, inputData = 0, framesLeft = 0;
+
+    assert( stream );
+    assert( stream->input || stream->output );
+
+    sampleRate = stream->baseStreamRep.streamInfo.sampleRate;
+    /* We have to come up with this much frames on both input and output */
+    framesTarget = stream->bufferProcessor.framesPerHostBuffer;
+    assert( framesTarget > 0 );
+
+    while( 1 )
+    {
+        PaAsiHpiStreamInfo info;
+        /* Check output first, as this takes priority in the default full-duplex mode */
+        if( stream->output )
+        {
+            PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) );
+            /* Wait until enough space is available in output buffer to receive a full block */
+            if( info.availableFrames < framesTarget )
+            {
+                framesLeft = framesTarget - info.availableFrames;
+                Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) );
+                continue;
+            }
+            /* Wait until the data in hardware buffer has dropped to a sensible level.
+             Without this, the hardware buffer quickly fills up in the absence of an input
+             stream to regulate its data rate (if data generation is fast). This leads to
+             large latencies, as the AudioScience hardware buffers are humongous.
+             This is similar to the default "Hardware Buffering=off" option in the
+             AudioScience WAV driver. */
+            if( !stream->input && (stream->output->outputBufferCap > 0) &&
+                    ( info.totalBufferedData > stream->output->outputBufferCap / stream->output->bytesPerFrame ) )
+            {
+                framesLeft = info.totalBufferedData - stream->output->outputBufferCap / stream->output->bytesPerFrame;
+                Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) );
+                continue;
+            }
+            outputData = info.totalBufferedData;
+            outputSpace = info.availableFrames;
+            /* Report output underflow to callback */
+            if( info.underflow )
+            {
+                *cbFlags |= paOutputUnderflow;
+            }
+        }
+
+        /* Now check input side */
+        if( stream->input )
+        {
+            PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) );
+            /* If a full block of samples hasn't been recorded yet, wait for it if possible */
+            if( info.availableFrames < framesTarget )
+            {
+                framesLeft = framesTarget - info.availableFrames;
+                /* As long as output is not disrupted in the process, wait for a full
+                block of input samples */
+                if( !stream->output || (outputData > framesLeft) )
+                {
+                    Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) );
+                    continue;
+                }
+            }
+            inputData = info.availableFrames;
+            /** @todo The paInputOverflow flag should be set in the callback containing the
+             first input sample following the overflow. That means the block currently sitting
+             at the fore-front of recording, i.e. typically the one containing the newest (last)
+             sample in the HPI buffer system. This is most likely not the same as the current
+             block of data being passed to the callback. The current overflow should ideally
+             be noted in an overflow list of sorts, with an indication of when it should be
+             reported. The trouble starts if there are several separate overflow incidents,
+             given a big input buffer. Oh well, something to try out later... */
+            if( info.overflow )
+            {
+                *cbFlags |= paInputOverflow;
+            }
+        }
+        break;
+    }
+    /* Full-duplex stream */
+    if( stream->input && stream->output )
+    {
+        if( outputSpace >= framesTarget )
+            *framesAvail = outputSpace;
+        /* If input didn't make the target, keep the output count instead (input underflow) */
+        if( (inputData >= framesTarget) && (inputData < outputSpace) )
+            *framesAvail = inputData;
+    }
+    else
+    {
+        *framesAvail = stream->input ? inputData : outputSpace;
+    }
+
+error:
+    return result;
+}
+
+
+/** Obtain recording, current and playback timestamps of stream.
+ The current time is determined by the system clock. This "now" timestamp occurs at the
+ forefront of recording (and playback in the full-duplex case), which happens later than the
+ input timestamp by an amount equal to the total number of recorded frames in the input buffer.
+ The output timestamp indicates when the next generated sample will actually be played. This
+ happens after all the samples currently in the output buffer are played. The output timestamp
+ therefore follows the current timestamp by an amount equal to the number of frames yet to be
+ played back in the output buffer.
+
+ If the current timestamp is the present, the input timestamp is in the past and the output
+ timestamp is in the future.
+
+ @param stream Pointer to stream struct
+
+ @param timeInfo Pointer to timeInfo struct that will contain timestamps
+ */
+static void PaAsiHpi_CalculateTimeInfo( PaAsiHpiStream *stream, PaStreamCallbackTimeInfo *timeInfo )
+{
+    PaAsiHpiStreamInfo streamInfo;
+    double sampleRate;
+
+    assert( stream );
+    assert( timeInfo );
+    sampleRate = stream->baseStreamRep.streamInfo.sampleRate;
+
+    /* The current time ("now") is at the forefront of both recording and playback */
+    timeInfo->currentTime = GetStreamTime( (PaStream *)stream );
+    /* The last sample in the input buffer was recorded just now, so the first sample
+     happened (number of recorded samples)/sampleRate ago */
+    timeInfo->inputBufferAdcTime = timeInfo->currentTime;
+    if( stream->input )
+    {
+        PaAsiHpi_GetStreamInfo( stream->input, &streamInfo );
+        timeInfo->inputBufferAdcTime -= streamInfo.totalBufferedData / sampleRate;
+    }
+    /* The first of the outgoing samples will be played after all the samples in the output
+     buffer is done */
+    timeInfo->outputBufferDacTime = timeInfo->currentTime;
+    if( stream->output )
+    {
+        PaAsiHpi_GetStreamInfo( stream->output, &streamInfo );
+        timeInfo->outputBufferDacTime += streamInfo.totalBufferedData / sampleRate;
+    }
+}
+
+
+/** Read from HPI input stream and register buffers.
+ This reads data from the HPI input stream (if it exists) and registers the temp stream
+ buffers of both input and output streams with the buffer processor. In the process it also
+ handles input underflows in the full-duplex case.
+
+ @param stream Pointer to stream struct
+
+ @param numFrames On entrance the number of available frames, on exit the number of
+                  received frames
+
+ @param cbFlags Indicates overflows and underflows
+
+ @return PortAudio error code
+ */
+static PaError PaAsiHpi_BeginProcessing( PaAsiHpiStream *stream, unsigned long *numFrames,
+        PaStreamCallbackFlags *cbFlags )
+{
+    PaError result = paNoError;
+
+    assert( stream );
+    if( *numFrames > stream->maxFramesPerHostBuffer )
+        *numFrames = stream->maxFramesPerHostBuffer;
+
+    if( stream->input )
+    {
+        PaAsiHpiStreamInfo info;
+
+        uint32_t framesToGet = *numFrames;
+
+        /* Check for overflows and underflows yet again */
+        PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) );
+        if( info.overflow )
+        {
+            *cbFlags |= paInputOverflow;
+        }
+        /* Input underflow if less than expected number of samples pitch up */
+        if( framesToGet > info.availableFrames )
+        {
+            PaUtilZeroer *zeroer;
+            PaSampleFormat inputFormat;
+
+            /* Never call an input-only stream with InputUnderflow set */
+            if( stream->output )
+                *cbFlags |= paInputUnderflow;
+            framesToGet = info.availableFrames;
+            /* Fill temp buffer with silence (to make up for missing input samples) */
+            inputFormat = PaAsiHpi_HpiToPaFormat( stream->input->hpiFormat.wFormat );
+            zeroer = PaUtil_SelectZeroer( inputFormat );
+            zeroer(stream->input->tempBuffer, 1,
+                   stream->input->tempBufferSize / Pa_GetSampleSize(inputFormat) );
+        }
+
+        /* Read block of data into temp buffer */
+        PA_ASIHPI_UNLESS_( HPI_InStreamReadBuf( NULL,
+                                             stream->input->hpiStream,
+                                             stream->input->tempBuffer,
+                                             framesToGet * stream->input->bytesPerFrame),
+                           paUnanticipatedHostError );
+        /* Register temp buffer with buffer processor (always FULL buffer) */
+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, *numFrames );
+        /* HPI interface only allows interleaved channels */
+        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
+                                            0, stream->input->tempBuffer,
+                                            stream->input->hpiFormat.wChannels );
+    }
+    if( stream->output )
+    {
+        /* Register temp buffer with buffer processor */
+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, *numFrames );
+        /* HPI interface only allows interleaved channels */
+        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
+                                             0, stream->output->tempBuffer,
+                                             stream->output->hpiFormat.wChannels );
+    }
+
+error:
+    return result;
+}
+
+
+/** Flush output buffers to HPI output stream.
+ This completes the processing cycle by writing the temp buffer to the HPI interface.
+ Additional output underflows are caught before data is written to the stream, as this
+ action typically remedies the underflow and hides it in the process.
+
+ @param stream Pointer to stream struct
+
+ @param numFrames The number of frames to write to the output stream
+
+ @param cbFlags Indicates overflows and underflows
+ */
+static PaError PaAsiHpi_EndProcessing( PaAsiHpiStream *stream, unsigned long numFrames,
+                                       PaStreamCallbackFlags *cbFlags )
+{
+    PaError result = paNoError;
+
+    assert( stream );
+
+    if( stream->output )
+    {
+        PaAsiHpiStreamInfo info;
+        /* Check for underflows after the (potentially time-consuming) callback */
+        PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) );
+        if( info.underflow )
+        {
+            *cbFlags |= paOutputUnderflow;
+        }
+
+        /* Write temp buffer to HPI stream */
+        PA_ASIHPI_UNLESS_( HPI_OutStreamWriteBuf( NULL,
+                                           stream->output->hpiStream,
+                                           stream->output->tempBuffer,
+                                           numFrames * stream->output->bytesPerFrame,
+                                           &stream->output->hpiFormat),
+                           paUnanticipatedHostError );
+    }
+
+error:
+    return result;
+}
+
+
+/** Main callback engine.
+ This function runs in a separate thread and does all the work of fetching audio data from
+ the AudioScience card via the HPI interface, feeding it to the user callback via the buffer
+ processor, and delivering the resulting output data back to the card via HPI calls.
+ It is started and terminated when the PortAudio stream is started and stopped, and starts
+ the HPI streams on startup.
+
+ @param userData A pointer to an open stream previously created with Pa_OpenStream.
+*/
+static void *CallbackThreadFunc( void *userData )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream *) userData;
+    int callbackResult = paContinue;
+
+    assert( stream );
+
+    /* Cleanup routine stops streams on thread exit */
+    pthread_cleanup_push( &PaAsiHpi_OnThreadExit, stream );
+
+    /* Start HPI streams and notify parent when we're done */
+    PA_ENSURE_( PaUnixThread_PrepareNotify( &stream->thread ) );
+    /* Buffer will be primed with silence */
+    PA_ENSURE_( PaAsiHpi_StartStream( stream, 0 ) );
+    PA_ENSURE_( PaUnixThread_NotifyParent( &stream->thread ) );
+
+    /* MAIN LOOP */
+    while( 1 )
+    {
+        PaStreamCallbackFlags cbFlags = 0;
+        unsigned long framesAvail, framesGot;
+
+        pthread_testcancel();
+
+        /** @concern StreamStop if the main thread has requested a stop and the stream has not
+        * been effectively stopped we signal this condition by modifying callbackResult
+        * (we'll want to flush buffered output). */
+        if( PaUnixThread_StopRequested( &stream->thread ) && (callbackResult == paContinue) )
+        {
+            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+            callbackResult = paComplete;
+        }
+
+        /* Start winding down thread if requested */
+        if( callbackResult != paContinue )
+        {
+            stream->callbackAbort = (callbackResult == paAbort);
+            if( stream->callbackAbort ||
+                    /** @concern BlockAdaption: Go on if adaption buffers are empty */
+                    PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+            {
+                goto end;
+            }
+            PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ ));
+            /* There is still buffered output that needs to be processed */
+        }
+
+        /* SLEEP */
+        /* Wait for data (or buffer space) to become available. This basically sleeps and
+        polls the HPI interface until a full block of frames can be moved. */
+        PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) );
+
+        /* Consume buffer space. Once we have a number of frames available for consumption we
+        must retrieve the data from the HPI interface and pass it to the PA buffer processor.
+        We should be prepared to process several chunks successively. */
+        while( framesAvail > 0 )
+        {
+            PaStreamCallbackTimeInfo timeInfo = {0, 0, 0};
+
+            pthread_testcancel();
+
+            framesGot = framesAvail;
+            if( stream->bufferProcessor.hostBufferSizeMode == paUtilFixedHostBufferSize )
+            {
+                /* We've committed to a fixed host buffer size, stick to that */
+                framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0;
+            }
+            else
+            {
+                /* We've committed to an upper bound on the size of host buffers */
+                assert( stream->bufferProcessor.hostBufferSizeMode == paUtilBoundedHostBufferSize );
+                framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer );
+            }
+
+            /* Obtain buffer timestamps */
+            PaAsiHpi_CalculateTimeInfo( stream, &timeInfo );
+            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags );
+            /* CPU load measurement should include processing activivity external to the stream callback */
+            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+            if( framesGot > 0 )
+            {
+                /* READ FROM HPI INPUT STREAM */
+                PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) );
+                /* Input overflow in a full-duplex stream makes for interesting times */
+                if( stream->input && stream->output && (cbFlags & paInputOverflow) )
+                {
+                    /* Special full-duplex paNeverDropInput mode */
+                    if( stream->neverDropInput )
+                    {
+                        PaUtil_SetNoOutput( &stream->bufferProcessor );
+                        cbFlags |= paOutputOverflow;
+                    }
+                }
+                /* CALL USER CALLBACK WITH INPUT DATA, AND OBTAIN OUTPUT DATA */
+                PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+                /* Clear overflow and underflow information (but PaAsiHpi_EndProcessing might
+                still show up output underflow that will carry over to next round) */
+                cbFlags = 0;
+                /*  WRITE TO HPI OUTPUT STREAM */
+                PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) );
+                /* Advance frame counter */
+                framesAvail -= framesGot;
+            }
+            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot );
+
+            if( framesGot == 0 )
+            {
+                /* Go back to polling for more frames */
+                break;
+
+            }
+            if( callbackResult != paContinue )
+                break;
+        }
+    }
+
+    /* This code is unreachable, but important to include regardless because it
+     * is possibly a macro with a closing brace to match the opening brace in
+     * pthread_cleanup_push() above.  The documentation states that they must
+     * always occur in pairs. */
+    pthread_cleanup_pop( 1 );
+
+end:
+    /* Indicates normal exit of callback, as opposed to the thread getting killed explicitly */
+    stream->callbackFinished = 1;
+    PA_DEBUG(( "%s: Thread %d exiting (callbackResult = %d)\n ",
+               __FUNCTION__, pthread_self(), callbackResult ));
+    /* Exit from thread and report any PortAudio error in the process */
+    PaUnixThreading_EXIT( result );
+error:
+    goto end;
+}
+
+/* --------------------------- Blocking Interface --------------------------- */
+
+/* As separate stream interfaces are used for blocking and callback streams, the following
+ functions can be guaranteed to only be called for blocking streams. */
+
+/** Read data from input stream.
+ This reads the indicated number of frames into the supplied buffer from an input stream,
+ and blocks until this is done.
+
+ @param s Pointer to PortAudio stream
+
+ @param buffer Pointer to buffer that will receive interleaved data (or an array of pointers
+               to a buffer for each non-interleaved channel)
+
+ @param frames Number of frames to read from stream
+
+ @return PortAudio error code (also indicates overflow via paInputOverflowed)
+ */
+static PaError ReadStream( PaStream *s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+    PaAsiHpiStreamInfo info;
+    void *userBuffer;
+
+    assert( stream );
+    PA_UNLESS_( stream->input, paCanNotReadFromAnOutputOnlyStream );
+
+    /* Check for input overflow since previous call to ReadStream */
+    PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) );
+    if( info.overflow )
+    {
+        result = paInputOverflowed;
+    }
+
+    /* NB Make copy of user buffer pointers, since they are advanced by buffer processor */
+    if( stream->bufferProcessor.userInputIsInterleaved )
+    {
+        userBuffer = buffer;
+    }
+    else
+    {
+        /* Copy channels into local array */
+        userBuffer = stream->blockingUserBufferCopy;
+        memcpy( userBuffer, buffer, sizeof (void *) * stream->input->hpiFormat.wChannels );
+    }
+
+    while( frames > 0 )
+    {
+        unsigned long framesGot, framesAvail;
+        PaStreamCallbackFlags cbFlags = 0;
+
+        PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) );
+        framesGot = PA_MIN( framesAvail, frames );
+        PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) );
+
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) );
+            /* Advance frame counter */
+            frames -= framesGot;
+        }
+    }
+
+error:
+    return result;
+}
+
+
+/** Write data to output stream.
+ This writes the indicated number of frames from the supplied buffer to an output stream,
+ and blocks until this is done.
+
+ @param s Pointer to PortAudio stream
+
+ @param buffer Pointer to buffer that provides interleaved data (or an array of pointers
+               to a buffer for each non-interleaved channel)
+
+ @param frames Number of frames to write to stream
+
+ @return PortAudio error code (also indicates underflow via paOutputUnderflowed)
+ */
+static PaError WriteStream( PaStream *s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+    PaAsiHpiStreamInfo info;
+    const void *userBuffer;
+
+    assert( stream );
+    PA_UNLESS_( stream->output, paCanNotWriteToAnInputOnlyStream );
+
+    /* Check for output underflow since previous call to WriteStream */
+    PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) );
+    if( info.underflow )
+    {
+        result = paOutputUnderflowed;
+    }
+
+    /* NB Make copy of user buffer pointers, since they are advanced by buffer processor */
+    if( stream->bufferProcessor.userOutputIsInterleaved )
+    {
+        userBuffer = buffer;
+    }
+    else
+    {
+        /* Copy channels into local array */
+        userBuffer = stream->blockingUserBufferCopy;
+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->output->hpiFormat.wChannels );
+    }
+
+    while( frames > 0 )
+    {
+        unsigned long framesGot, framesAvail;
+        PaStreamCallbackFlags cbFlags = 0;
+
+        PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) );
+        framesGot = PA_MIN( framesAvail, frames );
+        PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) );
+
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) );
+            /* Advance frame counter */
+            frames -= framesGot;
+        }
+    }
+
+error:
+    return result;
+}
+
+
+/** Number of frames that can be read from input stream without blocking.
+
+ @param s Pointer to PortAudio stream
+
+ @return Number of frames, or PortAudio error code
+ */
+static signed long GetStreamReadAvailable( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+    PaAsiHpiStreamInfo info;
+
+    assert( stream );
+    PA_UNLESS_( stream->input, paCanNotReadFromAnOutputOnlyStream );
+
+    PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) );
+    /* Round down to the nearest host buffer multiple */
+    result = (info.availableFrames / stream->maxFramesPerHostBuffer) * stream->maxFramesPerHostBuffer;
+    if( info.overflow )
+    {
+        result = paInputOverflowed;
+    }
+
+error:
+    return result;
+}
+
+
+/** Number of frames that can be written to output stream without blocking.
+
+ @param s Pointer to PortAudio stream
+
+ @return Number of frames, or PortAudio error code
+ */
+static signed long GetStreamWriteAvailable( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsiHpiStream *stream = (PaAsiHpiStream*)s;
+    PaAsiHpiStreamInfo info;
+
+    assert( stream );
+    PA_UNLESS_( stream->output, paCanNotWriteToAnInputOnlyStream );
+
+    PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) );
+    /* Round down to the nearest host buffer multiple */
+    result = (info.availableFrames / stream->maxFramesPerHostBuffer) * stream->maxFramesPerHostBuffer;
+    if( info.underflow )
+    {
+        result = paOutputUnderflowed;
+    }
+
+error:
+    return result;
+}
diff --git a/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp b/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
new file mode 100644 (file)
index 0000000..08c55ea
--- /dev/null
@@ -0,0 +1,572 @@
+/*
+       IASIOThiscallResolver.cpp see the comments in iasiothiscallresolver.h for
+    the top level description - this comment describes the technical details of
+    the implementation.
+
+    The latest version of this file is available from:
+    http://www.audiomulch.com/~rossb/code/calliasio
+
+    please email comments to Ross Bencina <rossb@audiomulch.com>
+
+    BACKGROUND
+
+    The IASIO interface declared in the Steinberg ASIO 2 SDK declares
+    functions with no explicit calling convention. This causes MSVC++ to default
+    to using the thiscall convention, which is a proprietary convention not
+    implemented by some non-microsoft compilers - notably borland BCC,
+    C++Builder, and gcc. MSVC++ is the defacto standard compiler used by
+    Steinberg. As a result of this situation, the ASIO sdk will compile with
+    any compiler, however attempting to execute the compiled code will cause a
+    crash due to different default calling conventions on non-Microsoft
+    compilers.
+
+    IASIOThiscallResolver solves the problem by providing an adapter class that
+    delegates to the IASIO interface using the correct calling convention
+    (thiscall). Due to the lack of support for thiscall in the Borland and GCC
+    compilers, the calls have been implemented in assembly language.
+
+    A number of macros are defined for thiscall function calls with different
+    numbers of parameters, with and without return values - it may be possible
+    to modify the format of these macros to make them work with other inline
+    assemblers.
+
+
+    THISCALL DEFINITION
+
+    A number of definitions of the thiscall calling convention are floating
+    around the internet. The following definition has been validated against
+    output from the MSVC++ compiler:
+
+    For non-vararg functions, thiscall works as follows: the object (this)
+    pointer is passed in ECX. All arguments are passed on the stack in
+    right to left order. The return value is placed in EAX. The callee
+    clears the passed arguments from the stack.
+
+
+    FINDING FUNCTION POINTERS FROM AN IASIO POINTER
+
+    The first field of a COM object is a pointer to its vtble. Thus a pointer
+    to an object implementing the IASIO interface also points to a pointer to
+    that object's vtbl. The vtble is a table of function pointers for all of
+    the virtual functions exposed by the implemented interfaces.
+
+    If we consider a variable declared as a pointer to IASO:
+
+    IASIO *theAsioDriver
+
+    theAsioDriver points to:
+
+    object implementing IASIO
+    {
+        IASIOvtbl *vtbl
+        other data
+    }
+
+    in other words, theAsioDriver points to a pointer to an IASIOvtbl
+
+    vtbl points to a table of function pointers:
+
+    IASIOvtbl ( interface IASIO : public IUnknown )
+    {
+    (IUnknown functions)
+    0   virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0;
+    4   virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0;
+    8   virtual ULONG STDMETHODCALLTYPE (*Release)() = 0;      
+
+    (IASIO functions)
+    12 virtual ASIOBool (*init)(void *sysHandle) = 0;
+    16 virtual void (*getDriverName)(char *name) = 0;
+    20 virtual long (*getDriverVersion)() = 0;
+    24 virtual void (*getErrorMessage)(char *string) = 0;
+    28 virtual ASIOError (*start)() = 0;
+    32 virtual ASIOError (*stop)() = 0;
+    36 virtual ASIOError (*getChannels)(long *numInputChannels, long *numOutputChannels) = 0;
+    40 virtual ASIOError (*getLatencies)(long *inputLatency, long *outputLatency) = 0;
+    44 virtual ASIOError (*getBufferSize)(long *minSize, long *maxSize,
+            long *preferredSize, long *granularity) = 0;
+    48 virtual ASIOError (*canSampleRate)(ASIOSampleRate sampleRate) = 0;
+    52 virtual ASIOError (*getSampleRate)(ASIOSampleRate *sampleRate) = 0;
+    56 virtual ASIOError (*setSampleRate)(ASIOSampleRate sampleRate) = 0;
+    60 virtual ASIOError (*getClockSources)(ASIOClockSource *clocks, long *numSources) = 0;
+    64 virtual ASIOError (*setClockSource)(long reference) = 0;
+    68 virtual ASIOError (*getSamplePosition)(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0;
+    72 virtual ASIOError (*getChannelInfo)(ASIOChannelInfo *info) = 0;
+    76 virtual ASIOError (*createBuffers)(ASIOBufferInfo *bufferInfos, long numChannels,
+            long bufferSize, ASIOCallbacks *callbacks) = 0;
+    80 virtual ASIOError (*disposeBuffers)() = 0;
+    84 virtual ASIOError (*controlPanel)() = 0;
+    88 virtual ASIOError (*future)(long selector,void *opt) = 0;
+    92 virtual ASIOError (*outputReady)() = 0;
+    };
+
+    The numbers in the left column show the byte offset of each function ptr
+    from the beginning of the vtbl. These numbers are used in the code below
+    to select different functions.
+
+    In order to find the address of a particular function, theAsioDriver
+    must first be dereferenced to find the value of the vtbl pointer:
+
+    mov     eax, theAsioDriver
+    mov     edx, [theAsioDriver]  // edx now points to vtbl[0]
+
+    Then an offset must be added to the vtbl pointer to select a
+    particular function, for example vtbl+44 points to the slot containing
+    a pointer to the getBufferSize function.
+
+    Finally vtbl+x must be dereferenced to obtain the value of the function
+    pointer stored in that address:
+
+    call    [edx+44]    // call the function pointed to by
+                        // the value in the getBufferSize field of the vtbl
+
+
+    SEE ALSO
+
+    Martin Fay's OpenASIO DLL at http://www.martinfay.com solves the same
+    problem by providing a new COM interface which wraps IASIO with an
+    interface that uses portable calling conventions. OpenASIO must be compiled
+    with MSVC, and requires that you ship the OpenASIO DLL with your
+    application.
+
+    
+    ACKNOWLEDGEMENTS
+
+    Ross Bencina: worked out the thiscall details above, wrote the original
+    Borland asm macros, and a patch for asio.cpp (which is no longer needed).
+    Thanks to Martin Fay for introducing me to the issues discussed here,
+    and to Rene G. Ceballos for assisting with asm dumps from MSVC++.
+
+    Antti Silvast: converted the original calliasio to work with gcc and NASM
+    by implementing the asm code in a separate file.
+
+       Fraser Adams: modified the original calliasio containing the Borland inline
+    asm to add inline asm for gcc i.e. Intel syntax for Borland and AT&T syntax
+    for gcc. This seems a neater approach for gcc than to have a separate .asm
+    file and it means that we only need one version of the thiscall patch.
+
+    Fraser Adams: rewrote the original calliasio patch in the form of the
+    IASIOThiscallResolver class in order to avoid modifications to files from
+    the Steinberg SDK, which may have had potential licence issues.
+
+    Andrew Baldwin: contributed fixes for compatibility problems with more
+    recent versions of the gcc assembler.
+*/
+
+
+// We only need IASIOThiscallResolver at all if we are on Win32. For other
+// platforms we simply bypass the IASIOThiscallResolver definition to allow us
+// to be safely #include'd whatever the platform to keep client code portable
+#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
+
+
+// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
+// is not used.
+#if !defined(_MSC_VER)
+
+
+#include <new>
+#include <assert.h>
+
+// We have a mechanism in iasiothiscallresolver.h to ensure that asio.h is
+// #include'd before it in client code, we do NOT want to do this test here.
+#define iasiothiscallresolver_sourcefile 1
+#include "iasiothiscallresolver.h"
+#undef iasiothiscallresolver_sourcefile
+
+// iasiothiscallresolver.h redefines ASIOInit for clients, but we don't want
+// this macro defined in this translation unit.
+#undef ASIOInit
+
+
+// theAsioDriver is a global pointer to the current IASIO instance which the
+// ASIO SDK uses to perform all actions on the IASIO interface. We substitute
+// our own forwarding interface into this pointer.
+extern IASIO* theAsioDriver;
+
+
+// The following macros define the inline assembler for BORLAND first then gcc
+
+#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__)          
+
+
+#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\
+    void *this_ = (thisPtr);                                                \
+    __asm {                                                                 \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+        mov     resultName, eax       ;                                     \
+    }
+
+
+#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )\
+    void *this_ = (thisPtr);                                                \
+    __asm {                                                                 \
+        mov     eax, param1           ;                                     \
+        push    eax                   ;                                     \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+    }
+
+
+#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )\
+    void *this_ = (thisPtr);                                                \
+    __asm {                                                                 \
+        mov     eax, param1           ;                                     \
+        push    eax                   ;                                     \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+        mov     resultName, eax       ;                                     \
+    }
+
+
+#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )\
+    void *this_ = (thisPtr);                                                \
+    void *doubleParamPtr_ (&param1);                                        \
+    __asm {                                                                 \
+        mov     eax, doubleParamPtr_  ;                                     \
+        push    [eax+4]               ;                                     \
+        push    [eax]                 ;                                     \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+        mov     resultName, eax       ;                                     \
+    }
+
+
+#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )\
+    void *this_ = (thisPtr);                                                \
+    __asm {                                                                 \
+        mov     eax, param2           ;                                     \
+        push    eax                   ;                                     \
+        mov     eax, param1           ;                                     \
+        push    eax                   ;                                     \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+        mov     resultName, eax       ;                                     \
+    }
+
+
+#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
+    void *this_ = (thisPtr);                                                \
+    __asm {                                                                 \
+        mov     eax, param4           ;                                     \
+        push    eax                   ;                                     \
+        mov     eax, param3           ;                                     \
+        push    eax                   ;                                     \
+        mov     eax, param2           ;                                     \
+        push    eax                   ;                                     \
+        mov     eax, param1           ;                                     \
+        push    eax                   ;                                     \
+        mov     ecx, this_            ;                                     \
+        mov     eax, [ecx]            ;                                     \
+        call    [eax+funcOffset]      ;                                     \
+        mov     resultName, eax       ;                                     \
+    }
+
+
+#elif defined(__GNUC__)
+
+
+#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )                  \
+    __asm__ __volatile__ ("movl (%1), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx)\n\t"                  \
+                          :"=a"(resultName) /* Output Operands */           \
+                          :"c"(thisPtr)     /* Input Operands */            \
+                          : "%edx" /* Clobbered Registers */                \
+                         );                                                 \
+
+
+#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )                 \
+    __asm__ __volatile__ ("pushl %0\n\t"                                    \
+                          "movl (%1), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx)\n\t"                  \
+                          :                 /* Output Operands */           \
+                          :"r"(param1),     /* Input Operands */            \
+                           "c"(thisPtr)                                     \
+                          : "%edx" /* Clobbered Registers */                \
+                         );                                                 \
+
+
+#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )          \
+    __asm__ __volatile__ ("pushl %1\n\t"                                    \
+                          "movl (%2), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx)\n\t"                  \
+                          :"=a"(resultName) /* Output Operands */           \
+                          :"r"(param1),     /* Input Operands */            \
+                           "c"(thisPtr)                                     \
+                          : "%edx" /* Clobbered Registers */                \
+                          );                                                \
+
+
+#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )   \
+    do {                                                                    \
+    double param1f64 = param1; /* Cast explicitly to double */              \
+    double *param1f64Ptr = &param1f64; /* Make pointer to address */        \
+     __asm__ __volatile__ ("pushl 4(%1)\n\t"                                \
+                           "pushl (%1)\n\t"                                 \
+                           "movl (%2), %%edx\n\t"                           \
+                           "call *"#funcOffset"(%%edx);\n\t"                \
+                           : "=a"(resultName) /* Output Operands */         \
+                           : "r"(param1f64Ptr),  /* Input Operands */       \
+                           "c"(thisPtr),                                    \
+                           "m"(*param1f64Ptr) /* Using address */           \
+                           : "%edx" /* Clobbered Registers */               \
+                           );                                               \
+    } while (0);                                                            \
+
+
+#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )  \
+    __asm__ __volatile__ ("pushl %1\n\t"                                    \
+                          "pushl %2\n\t"                                    \
+                          "movl (%3), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx)\n\t"                  \
+                          :"=a"(resultName) /* Output Operands */           \
+                          :"r"(param2),     /* Input Operands */            \
+                           "r"(param1),                                     \
+                           "c"(thisPtr)                                     \
+                          : "%edx" /* Clobbered Registers */                \
+                          );                                                \
+
+
+#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
+    __asm__ __volatile__ ("pushl %1\n\t"                                    \
+                          "pushl %2\n\t"                                    \
+                          "pushl %3\n\t"                                    \
+                          "pushl %4\n\t"                                    \
+                          "movl (%5), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx)\n\t"                  \
+                          :"=a"(resultName) /* Output Operands */           \
+                          :"r"(param4),     /* Input Operands  */           \
+                           "r"(param3),                                     \
+                           "r"(param2),                                     \
+                           "r"(param1),                                     \
+                           "c"(thisPtr)                                     \
+                          : "%edx" /* Clobbered Registers */                \
+                          );                                                \
+
+#endif
+
+
+
+// Our static singleton instance.
+IASIOThiscallResolver IASIOThiscallResolver::instance;
+
+// Constructor called to initialize static Singleton instance above. Note that
+// it is important not to clear that_ incase it has already been set by the call
+// to placement new in ASIOInit().
+IASIOThiscallResolver::IASIOThiscallResolver()
+{
+}
+
+// Constructor called from ASIOInit() below
+IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that)
+: that_( that )
+{
+}
+
+// Implement IUnknown methods as assert(false). IASIOThiscallResolver is not
+// really a COM object, just a wrapper which will work with the ASIO SDK.
+// If you wanted to use ASIO without the SDK you might want to implement COM
+// aggregation in these methods.
+HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv)
+{
+    (void)riid;     // suppress unused variable warning
+
+    assert( false ); // this function should never be called by the ASIO SDK.
+
+    *ppv = NULL;
+    return E_NOINTERFACE;
+}
+
+ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef()
+{
+    assert( false ); // this function should never be called by the ASIO SDK.
+
+    return 1;
+}
+
+ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release()
+{
+    assert( false ); // this function should never be called by the ASIO SDK.
+    
+    return 1;
+}
+
+
+// Implement the IASIO interface methods by performing the vptr manipulation
+// described above then delegating to the real implementation.
+ASIOBool IASIOThiscallResolver::init(void *sysHandle)
+{
+    ASIOBool result;
+    CALL_THISCALL_1( result, that_, 12, sysHandle );
+    return result;
+}
+
+void IASIOThiscallResolver::getDriverName(char *name)
+{
+    CALL_VOID_THISCALL_1( that_, 16, name );
+}
+
+long IASIOThiscallResolver::getDriverVersion()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 20 );
+    return result;
+}
+
+void IASIOThiscallResolver::getErrorMessage(char *string)
+{
+     CALL_VOID_THISCALL_1( that_, 24, string );
+}
+
+ASIOError IASIOThiscallResolver::start()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 28 );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::stop()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 32 );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels)
+{
+    ASIOBool result;
+    CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency)
+{
+    ASIOBool result;
+    CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize,
+        long *preferredSize, long *granularity)
+{
+    ASIOBool result;
+    CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate)
+{
+    ASIOBool result;
+    CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate)
+{
+    ASIOBool result;
+    CALL_THISCALL_1( result, that_, 52, sampleRate );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate)
+{    
+    ASIOBool result;
+    CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources)
+{
+    ASIOBool result;
+    CALL_THISCALL_2( result, that_, 60, clocks, numSources );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::setClockSource(long reference)
+{
+    ASIOBool result;
+    CALL_THISCALL_1( result, that_, 64, reference );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp)
+{
+    ASIOBool result;
+    CALL_THISCALL_2( result, that_, 68, sPos, tStamp );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info)
+{
+    ASIOBool result;
+    CALL_THISCALL_1( result, that_, 72, info );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos,
+        long numChannels, long bufferSize, ASIOCallbacks *callbacks)
+{
+    ASIOBool result;
+    CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::disposeBuffers()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 80 );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::controlPanel()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 84 );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::future(long selector,void *opt)
+{
+    ASIOBool result;
+    CALL_THISCALL_2( result, that_, 88, selector, opt );
+    return result;
+}
+
+ASIOError IASIOThiscallResolver::outputReady()
+{
+    ASIOBool result;
+    CALL_THISCALL_0( result, that_, 92 );
+    return result;
+}
+
+
+// Implement our substitute ASIOInit() method
+ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info)
+{
+    // To ensure that our instance's vptr is correctly constructed, even if
+    // ASIOInit is called prior to main(), we explicitly call its constructor
+    // (potentially over the top of an existing instance). Note that this is
+    // pretty ugly, and is only safe because IASIOThiscallResolver has no
+    // destructor and contains no objects with destructors.
+    new((void*)&instance) IASIOThiscallResolver( theAsioDriver );
+
+    // Interpose between ASIO client code and the real driver.
+    theAsioDriver = &instance;
+
+    // Note that we never need to switch theAsioDriver back to point to the
+    // real driver because theAsioDriver is reset to zero in ASIOExit().
+
+    // Delegate to the real ASIOInit
+       return ::ASIOInit(info);
+}
+
+
+#endif /* !defined(_MSC_VER) */
+
+#endif /* Win32 */
+
diff --git a/portaudio/src/hostapi/asio/iasiothiscallresolver.h b/portaudio/src/hostapi/asio/iasiothiscallresolver.h
new file mode 100644 (file)
index 0000000..21d53b3
--- /dev/null
@@ -0,0 +1,197 @@
+// ****************************************************************************
+// File:                       IASIOThiscallResolver.h
+// Description:     The IASIOThiscallResolver class implements the IASIO
+//                                     interface and acts as a proxy to the real IASIO interface by
+//                  calling through its vptr table using the thiscall calling
+//                  convention. To put it another way, we interpose
+//                  IASIOThiscallResolver between ASIO SDK code and the driver.
+//                  This is necessary because most non-Microsoft compilers don't
+//                  implement the thiscall calling convention used by IASIO.
+//
+//                                     iasiothiscallresolver.cpp contains the background of this
+//                                     problem plus a technical description of the vptr
+//                  manipulations.
+//
+//                                     In order to use this mechanism one simply has to add
+//                                     iasiothiscallresolver.cpp to the list of files to compile
+//                  and #include <iasiothiscallresolver.h>
+//
+//                                     Note that this #include must come after the other ASIO SDK
+//                  #includes, for example:
+//
+//                                     #include <windows.h>
+//                                     #include <asiosys.h>
+//                                     #include <asio.h>
+//                                     #include <asiodrivers.h>
+//                                     #include <iasiothiscallresolver.h>
+//
+//                                     Actually the important thing is to #include
+//                  <iasiothiscallresolver.h> after <asio.h>. We have
+//                  incorporated a test to enforce this ordering.
+//
+//                                     The code transparently takes care of the interposition by
+//                  using macro substitution to intercept calls to ASIOInit()
+//                  and ASIOExit(). We save the original ASIO global
+//                  "theAsioDriver" in our "that" variable, and then set
+//                  "theAsioDriver" to equal our IASIOThiscallResolver instance.
+//
+//                                     Whilst this method of resolving the thiscall problem requires
+//                                     the addition of #include <iasiothiscallresolver.h> to client
+//                  code it has the advantage that it does not break the terms
+//                  of the ASIO licence by publishing it. We are NOT modifying
+//                  any Steinberg code here, we are merely implementing the IASIO
+//                                     interface in the same way that we would need to do if we
+//                                     wished to provide an open source ASIO driver.
+//
+//                                     For compilation with MinGW -lole32 needs to be added to the
+//                  linker options. For BORLAND, linking with Import32.lib is
+//                  sufficient.
+//
+//                                     The dependencies are with: CoInitialize, CoUninitialize,
+//                                     CoCreateInstance, CLSIDFromString - used by asiolist.cpp
+//                                     and are required on Windows whether ThiscallResolver is used
+//                                     or not.
+//
+//                                     Searching for the above strings in the root library path
+//                                     of your compiler should enable the correct libraries to be
+//                                     identified if they aren't immediately obvious.
+//
+//                  Note that the current implementation of IASIOThiscallResolver
+//                  is not COM compliant - it does not correctly implement the
+//                  IUnknown interface. Implementing it is not necessary because
+//                  it is not called by parts of the ASIO SDK which call through
+//                  theAsioDriver ptr. The IUnknown methods are implemented as
+//                  assert(false) to ensure that the code fails if they are
+//                  ever called.
+// Restrictions:       None. Public Domain & Open Source distribute freely
+//                                     You may use IASIOThiscallResolver commercially as well as
+//                  privately.
+//                                     You the user assume the responsibility for the use of the
+//                                     files, binary or text, and there is no guarantee or warranty,
+//                                     expressed or implied, including but not limited to the
+//                                     implied warranties of merchantability and fitness for a
+//                                     particular purpose. You assume all responsibility and agree
+//                                     to hold no entity, copyright holder or distributors liable
+//                                     for any loss of data or inaccurate representations of data
+//                                     as a result of using IASIOThiscallResolver.
+// Version:         1.4 Added separate macro CALL_THISCALL_1_DOUBLE from
+//                  Andrew Baldwin, and volatile for whole gcc asm blocks,
+//                  both for compatibility with newer gcc versions. Cleaned up
+//                  Borland asm to use one less register.
+//                  1.3 Switched to including assert.h for better compatibility.
+//                  Wrapped entire .h and .cpp contents with a check for
+//                  _MSC_VER to provide better compatibility with MS compilers.
+//                  Changed Singleton implementation to use static instance
+//                  instead of freestore allocated instance. Removed ASIOExit
+//                  macro as it is no longer needed.
+//                  1.2 Removed semicolons from ASIOInit and ASIOExit macros to
+//                  allow them to be embedded in expressions (if statements).
+//                  Cleaned up some comments. Removed combase.c dependency (it
+//                  doesn't compile with BCB anyway) by stubbing IUnknown.
+//                  1.1 Incorporated comments from Ross Bencina including things
+//                                     such as changing name from ThiscallResolver to
+//                                     IASIOThiscallResolver, tidying up the constructor, fixing
+//                                     a bug in IASIOThiscallResolver::ASIOExit() and improving
+//                                     portability through the use of conditional compilation
+//                                     1.0 Initial working version.
+// Created:                    6/09/2003
+// Authors:         Fraser Adams
+//                  Ross Bencina
+//                  Rene G. Ceballos
+//                  Martin Fay
+//                  Antti Silvast
+//                  Andrew Baldwin
+//
+// ****************************************************************************
+
+
+#ifndef included_iasiothiscallresolver_h
+#define included_iasiothiscallresolver_h
+
+// We only need IASIOThiscallResolver at all if we are on Win32. For other
+// platforms we simply bypass the IASIOThiscallResolver definition to allow us
+// to be safely #include'd whatever the platform to keep client code portable
+#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
+
+
+// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
+// is not used.
+#if !defined(_MSC_VER)
+
+
+// The following is in order to ensure that this header is only included after
+// the other ASIO headers (except for the case of iasiothiscallresolver.cpp).
+// We need to do this because IASIOThiscallResolver works by eclipsing the
+// original definition of ASIOInit() with a macro (see below).
+#if !defined(iasiothiscallresolver_sourcefile)
+       #if !defined(__ASIO_H)
+       #error iasiothiscallresolver.h must be included AFTER asio.h
+       #endif
+#endif
+
+#include <windows.h>
+#include <asiodrvr.h> /* From ASIO SDK */
+
+
+class IASIOThiscallResolver : public IASIO {
+private:
+       IASIO* that_; // Points to the real IASIO
+
+       static IASIOThiscallResolver instance; // Singleton instance
+
+       // Constructors - declared private so construction is limited to
+    // our Singleton instance
+    IASIOThiscallResolver();
+       IASIOThiscallResolver(IASIO* that);
+public:
+
+    // Methods from the IUnknown interface. We don't fully implement IUnknown
+    // because the ASIO SDK never calls these methods through theAsioDriver ptr.
+    // These methods are implemented as assert(false).
+    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
+    virtual ULONG STDMETHODCALLTYPE AddRef();
+    virtual ULONG STDMETHODCALLTYPE Release();
+
+    // Methods from the IASIO interface, implemented as forwarning calls to that.
+       virtual ASIOBool init(void *sysHandle);
+       virtual void getDriverName(char *name);
+       virtual long getDriverVersion();
+       virtual void getErrorMessage(char *string);
+       virtual ASIOError start();
+       virtual ASIOError stop();
+       virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels);
+       virtual ASIOError getLatencies(long *inputLatency, long *outputLatency);
+       virtual ASIOError getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity);
+       virtual ASIOError canSampleRate(ASIOSampleRate sampleRate);
+       virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate);
+       virtual ASIOError setSampleRate(ASIOSampleRate sampleRate);
+       virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources);
+       virtual ASIOError setClockSource(long reference);
+       virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp);
+       virtual ASIOError getChannelInfo(ASIOChannelInfo *info);
+       virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks);
+       virtual ASIOError disposeBuffers();
+       virtual ASIOError controlPanel();
+       virtual ASIOError future(long selector,void *opt);
+       virtual ASIOError outputReady();
+
+    // Class method, see ASIOInit() macro below.
+    static ASIOError ASIOInit(ASIODriverInfo *info); // Delegates to ::ASIOInit
+};
+
+
+// Replace calls to ASIOInit with our interposing version.
+// This macro enables us to perform thiscall resolution simply by #including
+// <iasiothiscallresolver.h> after the asio #includes (this file _must_ be
+// included _after_ the asio #includes)
+
+#define ASIOInit(name) IASIOThiscallResolver::ASIOInit((name))
+
+
+#endif /* !defined(_MSC_VER) */
+
+#endif /* Win32 */
+
+#endif /* included_iasiothiscallresolver_h */
+
+
diff --git a/portaudio/src/hostapi/asio/pa_asio.cpp b/portaudio/src/hostapi/asio/pa_asio.cpp
new file mode 100644 (file)
index 0000000..f230d87
--- /dev/null
@@ -0,0 +1,4251 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library for ASIO Drivers
+ *
+ * Author: Stephane Letz
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 2000-2002 Stephane Letz, Phil Burk, Ross Bencina
+ * Blocking i/o implementation by Sven Fischer, Institute of Hearing
+ * Technology and Audiology (www.hoertechnik-audiologie.de)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/* Modification History
+
+        08-03-01 First version : Stephane Letz
+        08-06-01 Tweaks for PC, use C++, buffer allocation, Float32 to Int32 conversion : Phil Burk
+        08-20-01 More conversion, PA_StreamTime, Pa_GetHostError : Stephane Letz
+        08-21-01 PaUInt8 bug correction, implementation of ASIOSTFloat32LSB and ASIOSTFloat32MSB native formats : Stephane Letz
+        08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil
+        08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when
+                 the stream is stopped : Stephane Letz
+        08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when
+                 the stream is stopped : Stephane Letz
+        10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that
+                 respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz
+        10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz
+        10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil
+        10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk
+        10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz
+        11-06-01 Rename functions : Stephane Letz
+        11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz
+        11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk
+        01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly :  Stephane Letz
+        02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz
+        19-02-02 New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows : Stephane Letz
+        09-04-02 Correct error code management in PaHost_Term, removes various compiler warning : Stephane Letz
+        12-04-02 Add Mac includes for <Devices.h> and <Timer.h> : Phil Burk
+        13-04-02 Removes another compiler warning : Stephane Letz
+        30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz
+        12-06-02 Rehashed into new multi-api infrastructure, added support for all ASIO sample formats : Ross Bencina
+        18-06-02 Added pa_asio.h, PaAsio_GetAvailableLatencyValues() : Ross B.
+        21-06-02 Added SelectHostBufferSize() which selects host buffer size based on user latency parameters : Ross Bencina
+        ** NOTE  maintanance history is now stored in CVS **
+*/
+
+/** @file
+    @ingroup hostapi_src
+
+    Note that specific support for paInputUnderflow, paOutputOverflow and
+    paNeverDropInput is not necessary or possible with this driver due to the
+    synchronous full duplex double-buffered architecture of ASIO.
+*/
+
+
+#include <stdio.h>
+#include <assert.h>
+#include <string.h>
+//#include <values.h>
+#include <new>
+
+#include <windows.h>
+#include <mmsystem.h>
+
+#include "portaudio.h"
+#include "pa_asio.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_debugprint.h"
+#include "pa_ringbuffer.h"
+
+#include "pa_win_coinitialize.h"
+
+/* This version of pa_asio.cpp is currently only targetted at Win32,
+   It would require a few tweaks to work with pre-OS X Macintosh.
+   To make configuration easier, we define WIN32 here to make sure
+   that the ASIO SDK knows this is Win32.
+*/
+#ifndef WIN32
+#define WIN32
+#endif
+
+#include "asiosys.h"
+#include "asio.h"
+#include "asiodrivers.h"
+#include "iasiothiscallresolver.h"
+
+/*
+#if MAC
+#include <Devices.h>
+#include <Timer.h>
+#include <Math64.h>
+#else
+*/
+/*
+#include <math.h>
+#include <windows.h>
+#include <mmsystem.h>
+*/
+/*
+#endif
+*/
+
+
+/* winmm.lib is needed for timeGetTime() (this is in winmm.a if you're using gcc) */
+#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment(lib, "winmm.lib")
+#endif
+
+
+/* external reference to ASIO SDK's asioDrivers.
+
+ This is a bit messy because we want to explicitly manage 
+ allocation/deallocation of this structure, but some layers of the SDK 
+ which we currently use (eg the implementation in asio.cpp) still
+ use this global version.
+
+ For now we keep it in sync with our local instance in the host
+ API representation structure, but later we should be able to remove
+ all dependence on it.
+*/
+extern AsioDrivers* asioDrivers;
+
+
+/* We are trying to be compatible with CARBON but this has not been thoroughly tested. */
+/* not tested at all since new V19 code was introduced. */
+#define CARBON_COMPATIBLE  (0)
+
+
+/* prototypes for functions declared in this file */
+
+extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex );
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+/* Blocking i/o callback function. */
+static int BlockingIoPaCallback(const void                     *inputBuffer    ,
+                                      void                     *outputBuffer   ,
+                                      unsigned long             framesPerBuffer,
+                                const PaStreamCallbackTimeInfo *timeInfo       ,
+                                      PaStreamCallbackFlags     statusFlags    ,
+                                      void                     *userData       );
+
+/* our ASIO callback functions */
+
+static void bufferSwitch(long index, ASIOBool processNow);
+static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow);
+static void sampleRateChanged(ASIOSampleRate sRate);
+static long asioMessages(long selector, long value, void* message, double* opt);
+
+static ASIOCallbacks asioCallbacks_ =
+    { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo };
+
+
+#define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+    PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText )
+
+
+static void PaAsio_SetLastSystemError( DWORD errorCode )
+{
+    LPVOID lpMsgBuf;
+    FormatMessage(
+        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+        NULL,
+        errorCode,
+        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+        (LPTSTR) &lpMsgBuf,
+        0,
+        NULL
+    );
+    PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf );
+    LocalFree( lpMsgBuf );
+}
+
+#define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \
+    PaAsio_SetLastSystemError( errorCode )
+
+
+static const char* PaAsio_GetAsioErrorText( ASIOError asioError )
+{
+    const char *result;
+
+    switch( asioError ){
+        case ASE_OK:
+        case ASE_SUCCESS:           result = "Success"; break;
+        case ASE_NotPresent:        result = "Hardware input or output is not present or available"; break;
+        case ASE_HWMalfunction:     result = "Hardware is malfunctioning"; break;
+        case ASE_InvalidParameter:  result = "Input parameter invalid"; break;
+        case ASE_InvalidMode:       result = "Hardware is in a bad mode or used in a bad mode"; break;
+        case ASE_SPNotAdvancing:    result = "Hardware is not running when sample position is inquired"; break;
+        case ASE_NoClock:           result = "Sample clock or rate cannot be determined or is not present"; break;
+        case ASE_NoMemory:          result = "Not enough memory for completing the request"; break;
+        default:                    result = "Unknown ASIO error"; break;
+    }
+
+    return result;
+}
+
+
+#define PA_ASIO_SET_LAST_ASIO_ERROR( asioError ) \
+    PaUtil_SetLastHostErrorInfo( paASIO, asioError, PaAsio_GetAsioErrorText( asioError ) )
+
+
+
+
+// Atomic increment and decrement operations
+#if MAC
+    /* need to be implemented on Mac */
+    inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}
+    inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}
+#elif WINDOWS
+    inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}
+    inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}
+#endif
+
+
+
+typedef struct PaAsioDriverInfo
+{
+    ASIODriverInfo asioDriverInfo;
+    long inputChannelCount, outputChannelCount;
+    long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity;
+    bool postOutput;
+}
+PaAsioDriverInfo;
+
+
+/* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    PaWinUtilComInitializationResult comInitializationResult;
+
+    AsioDrivers *asioDrivers;
+    void *systemSpecific;
+    
+    /* the ASIO C API only allows one ASIO driver to be open at a time,
+        so we keep track of whether we have the driver open here, and
+        use this information to return errors from OpenStream if the
+        driver is already open.
+
+        openAsioDeviceIndex will be PaNoDevice if there is no device open
+        and a valid pa_asio (not global) device index otherwise.
+
+        openAsioDriverInfo is populated with the driver info for the
+        currently open device (if any)
+    */
+    PaDeviceIndex openAsioDeviceIndex;
+    PaAsioDriverInfo openAsioDriverInfo;
+}
+PaAsioHostApiRepresentation;
+
+
+/*
+    Retrieve <driverCount> driver names from ASIO, returned in a char**
+    allocated in <group>.
+*/
+static char **GetAsioDriverNames( PaAsioHostApiRepresentation *asioHostApi, PaUtilAllocationGroup *group, long driverCount )
+{
+    char **result = 0;
+    int i;
+
+    result =(char**)PaUtil_GroupAllocateMemory(
+            group, sizeof(char*) * driverCount );
+    if( !result )
+        goto error;
+
+    result[0] = (char*)PaUtil_GroupAllocateMemory(
+            group, 32 * driverCount );
+    if( !result[0] )
+        goto error;
+
+    for( i=0; i<driverCount; ++i )
+        result[i] = result[0] + (32 * i);
+
+    asioHostApi->asioDrivers->getDriverNames( result, driverCount );
+
+error:
+    return result;
+}
+
+
+static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type)
+{
+    switch (type) {
+        case ASIOSTInt16MSB:
+        case ASIOSTInt16LSB:
+                return paInt16;
+
+        case ASIOSTFloat32MSB:
+        case ASIOSTFloat32LSB:
+        case ASIOSTFloat64MSB:
+        case ASIOSTFloat64LSB:
+                return paFloat32;
+
+        case ASIOSTInt32MSB:
+        case ASIOSTInt32LSB:
+        case ASIOSTInt32MSB16:
+        case ASIOSTInt32LSB16:
+        case ASIOSTInt32MSB18:
+        case ASIOSTInt32MSB20:
+        case ASIOSTInt32MSB24:
+        case ASIOSTInt32LSB18:
+        case ASIOSTInt32LSB20:
+        case ASIOSTInt32LSB24:
+                return paInt32;
+
+        case ASIOSTInt24MSB:
+        case ASIOSTInt24LSB:
+                return paInt24;
+
+        default:
+                return paCustomFormat;
+    }
+}
+
+void AsioSampleTypeLOG(ASIOSampleType type)
+{
+    switch (type) {
+        case ASIOSTInt16MSB:  PA_DEBUG(("ASIOSTInt16MSB\n"));  break;
+        case ASIOSTInt16LSB:  PA_DEBUG(("ASIOSTInt16LSB\n"));  break;
+        case ASIOSTFloat32MSB:PA_DEBUG(("ASIOSTFloat32MSB\n"));break;
+        case ASIOSTFloat32LSB:PA_DEBUG(("ASIOSTFloat32LSB\n"));break;
+        case ASIOSTFloat64MSB:PA_DEBUG(("ASIOSTFloat64MSB\n"));break;
+        case ASIOSTFloat64LSB:PA_DEBUG(("ASIOSTFloat64LSB\n"));break;
+        case ASIOSTInt32MSB:  PA_DEBUG(("ASIOSTInt32MSB\n"));  break;
+        case ASIOSTInt32LSB:  PA_DEBUG(("ASIOSTInt32LSB\n"));  break;
+        case ASIOSTInt32MSB16:PA_DEBUG(("ASIOSTInt32MSB16\n"));break;
+        case ASIOSTInt32LSB16:PA_DEBUG(("ASIOSTInt32LSB16\n"));break;
+        case ASIOSTInt32MSB18:PA_DEBUG(("ASIOSTInt32MSB18\n"));break;
+        case ASIOSTInt32MSB20:PA_DEBUG(("ASIOSTInt32MSB20\n"));break;
+        case ASIOSTInt32MSB24:PA_DEBUG(("ASIOSTInt32MSB24\n"));break;
+        case ASIOSTInt32LSB18:PA_DEBUG(("ASIOSTInt32LSB18\n"));break;
+        case ASIOSTInt32LSB20:PA_DEBUG(("ASIOSTInt32LSB20\n"));break;
+        case ASIOSTInt32LSB24:PA_DEBUG(("ASIOSTInt32LSB24\n"));break;
+        case ASIOSTInt24MSB:  PA_DEBUG(("ASIOSTInt24MSB\n"));  break;
+        case ASIOSTInt24LSB:  PA_DEBUG(("ASIOSTInt24LSB\n"));  break;
+        default:              PA_DEBUG(("Custom Format%d\n",type));break;
+
+    }
+}
+
+static int BytesPerAsioSample( ASIOSampleType sampleType )
+{
+    switch (sampleType) {
+        case ASIOSTInt16MSB:
+        case ASIOSTInt16LSB:
+            return 2;
+
+        case ASIOSTFloat64MSB:
+        case ASIOSTFloat64LSB:
+            return 8;
+
+        case ASIOSTFloat32MSB:
+        case ASIOSTFloat32LSB:
+        case ASIOSTInt32MSB:
+        case ASIOSTInt32LSB:
+        case ASIOSTInt32MSB16:
+        case ASIOSTInt32LSB16:
+        case ASIOSTInt32MSB18:
+        case ASIOSTInt32MSB20:
+        case ASIOSTInt32MSB24:
+        case ASIOSTInt32LSB18:
+        case ASIOSTInt32LSB20:
+        case ASIOSTInt32LSB24:
+            return 4;
+
+        case ASIOSTInt24MSB:
+        case ASIOSTInt24LSB:
+            return 3;
+
+        default:
+            return 0;
+    }
+}
+
+
+static void Swap16( void *buffer, long shift, long count )
+{
+    unsigned short *p = (unsigned short*)buffer;
+    unsigned short temp;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+    {
+        temp = *p;
+        *p++ = (unsigned short)((temp<<8) | (temp>>8));
+    }
+}
+
+static void Swap24( void *buffer, long shift, long count )
+{
+    unsigned char *p = (unsigned char*)buffer;
+    unsigned char temp;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+    {
+        temp = *p;
+        *p = *(p+2);
+        *(p+2) = temp;
+        p += 3;
+    }
+}
+
+#define PA_SWAP32_( x ) ((x>>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24));
+
+static void Swap32( void *buffer, long shift, long count )
+{
+    unsigned long *p = (unsigned long*)buffer;
+    unsigned long temp;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+    {
+        temp = *p;
+        *p++ = PA_SWAP32_( temp);
+    }
+}
+
+static void SwapShiftLeft32( void *buffer, long shift, long count )
+{
+    unsigned long *p = (unsigned long*)buffer;
+    unsigned long temp;
+
+    while( count-- )
+    {
+        temp = *p;
+        temp = PA_SWAP32_( temp);
+        *p++ = temp << shift;
+    }
+}
+
+static void ShiftRightSwap32( void *buffer, long shift, long count )
+{
+    unsigned long *p = (unsigned long*)buffer;
+    unsigned long temp;
+
+    while( count-- )
+    {
+        temp = *p >> shift;
+        *p++ = PA_SWAP32_( temp);
+    }
+}
+
+static void ShiftLeft32( void *buffer, long shift, long count )
+{
+    unsigned long *p = (unsigned long*)buffer;
+    unsigned long temp;
+
+    while( count-- )
+    {
+        temp = *p;
+        *p++ = temp << shift;
+    }
+}
+
+static void ShiftRight32( void *buffer, long shift, long count )
+{
+    unsigned long *p = (unsigned long*)buffer;
+    unsigned long temp;
+
+    while( count-- )
+    {
+        temp = *p;
+        *p++ = temp >> shift;
+    }
+}
+
+#define PA_SWAP_( x, y ) temp=x; x = y; y = temp;
+
+static void Swap64ConvertFloat64ToFloat32( void *buffer, long shift, long count )
+{
+    double *in = (double*)buffer;
+    float *out = (float*)buffer;
+    unsigned char *p;
+    unsigned char temp;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+    {
+        p = (unsigned char*)in;
+        PA_SWAP_( p[0], p[7] );
+        PA_SWAP_( p[1], p[6] );
+        PA_SWAP_( p[2], p[5] );
+        PA_SWAP_( p[3], p[4] );
+
+        *out++ = (float) (*in++);
+    }
+}
+
+static void ConvertFloat64ToFloat32( void *buffer, long shift, long count )
+{
+    double *in = (double*)buffer;
+    float *out = (float*)buffer;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+        *out++ = (float) (*in++);
+}
+
+static void ConvertFloat32ToFloat64Swap64( void *buffer, long shift, long count )
+{
+    float *in = ((float*)buffer) + (count-1);
+    double *out = ((double*)buffer) + (count-1);
+    unsigned char *p;
+    unsigned char temp;
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+    {
+        *out = *in--;
+
+        p = (unsigned char*)out;
+        PA_SWAP_( p[0], p[7] );
+        PA_SWAP_( p[1], p[6] );
+        PA_SWAP_( p[2], p[5] );
+        PA_SWAP_( p[3], p[4] );
+
+        out--;
+    }
+}
+
+static void ConvertFloat32ToFloat64( void *buffer, long shift, long count )
+{
+    float *in = ((float*)buffer) + (count-1);
+    double *out = ((double*)buffer) + (count-1);
+    (void) shift; /* unused parameter */
+
+    while( count-- )
+        *out-- = *in--;
+}
+
+#ifdef MAC
+#define PA_MSB_IS_NATIVE_
+#undef PA_LSB_IS_NATIVE_
+#endif
+
+#ifdef WINDOWS
+#undef PA_MSB_IS_NATIVE_
+#define PA_LSB_IS_NATIVE_
+#endif
+
+typedef void PaAsioBufferConverter( void *, long, long );
+
+static void SelectAsioToPaConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
+{
+    *shift = 0;
+    *converter = 0;
+
+    switch (type) {
+        case ASIOSTInt16MSB:
+            /* dest: paInt16, no conversion necessary, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap16;
+            #endif
+            break;
+        case ASIOSTInt16LSB:
+            /* dest: paInt16, no conversion necessary, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap16;
+            #endif
+            break;
+        case ASIOSTFloat32MSB:
+            /* dest: paFloat32, no conversion necessary, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTFloat32LSB:
+            /* dest: paFloat32, no conversion necessary, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTFloat64MSB:
+            /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap64ConvertFloat64ToFloat32;
+            #else
+                *converter = ConvertFloat64ToFloat32;
+            #endif
+            break;
+        case ASIOSTFloat64LSB:
+            /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap64ConvertFloat64ToFloat32;
+            #else
+                *converter = ConvertFloat64ToFloat32;
+            #endif
+            break;
+        case ASIOSTInt32MSB:
+            /* dest: paInt32, no conversion necessary, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTInt32LSB:
+            /* dest: paInt32, no conversion necessary, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTInt32MSB16:
+            /* dest: paInt32, 16 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 16;
+            break;
+        case ASIOSTInt32MSB18:
+            /* dest: paInt32, 14 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 14;
+            break;
+        case ASIOSTInt32MSB20:
+            /* dest: paInt32, 12 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 12;
+            break;
+        case ASIOSTInt32MSB24:
+            /* dest: paInt32, 8 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 8;
+            break;
+        case ASIOSTInt32LSB16:
+            /* dest: paInt32, 16 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 16;
+            break;
+        case ASIOSTInt32LSB18:
+            /* dest: paInt32, 14 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 14;
+            break;
+        case ASIOSTInt32LSB20:
+            /* dest: paInt32, 12 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 12;
+            break;
+        case ASIOSTInt32LSB24:
+            /* dest: paInt32, 8 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = SwapShiftLeft32;
+            #else
+                *converter = ShiftLeft32;
+            #endif
+            *shift = 8;
+            break;
+        case ASIOSTInt24MSB:
+            /* dest: paInt24, no conversion necessary, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap24;
+            #endif
+            break;
+        case ASIOSTInt24LSB:
+            /* dest: paInt24, no conversion necessary, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap24;
+            #endif
+            break;
+    }
+}
+
+
+static void SelectPaToAsioConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
+{
+    *shift = 0;
+    *converter = 0;
+
+    switch (type) {
+        case ASIOSTInt16MSB:
+            /* src: paInt16, no conversion necessary, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap16;
+            #endif
+            break;
+        case ASIOSTInt16LSB:
+            /* src: paInt16, no conversion necessary, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap16;
+            #endif
+            break;
+        case ASIOSTFloat32MSB:
+            /* src: paFloat32, no conversion necessary, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTFloat32LSB:
+            /* src: paFloat32, no conversion necessary, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTFloat64MSB:
+            /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = ConvertFloat32ToFloat64Swap64;
+            #else
+                *converter = ConvertFloat32ToFloat64;
+            #endif
+            break;
+        case ASIOSTFloat64LSB:
+            /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = ConvertFloat32ToFloat64Swap64;
+            #else
+                *converter = ConvertFloat32ToFloat64;
+            #endif
+            break;
+        case ASIOSTInt32MSB:
+            /* src: paInt32, no conversion necessary, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTInt32LSB:
+            /* src: paInt32, no conversion necessary, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap32;
+            #endif
+            break;
+        case ASIOSTInt32MSB16:
+            /* src: paInt32, 16 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 16;
+            break;
+        case ASIOSTInt32MSB18:
+            /* src: paInt32, 14 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 14;
+            break;
+        case ASIOSTInt32MSB20:
+            /* src: paInt32, 12 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 12;
+            break;
+        case ASIOSTInt32MSB24:
+            /* src: paInt32, 8 bit shift, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 8;
+            break;
+        case ASIOSTInt32LSB16:
+            /* src: paInt32, 16 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 16;
+            break;
+        case ASIOSTInt32LSB18:
+            /* src: paInt32, 14 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 14;
+            break;
+        case ASIOSTInt32LSB20:
+            /* src: paInt32, 12 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 12;
+            break;
+        case ASIOSTInt32LSB24:
+            /* src: paInt32, 8 bit shift, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = ShiftRightSwap32;
+            #else
+                *converter = ShiftRight32;
+            #endif
+            *shift = 8;
+            break;
+        case ASIOSTInt24MSB:
+            /* src: paInt24, no conversion necessary, possible byte swap */
+            #ifdef PA_LSB_IS_NATIVE_
+                *converter = Swap24;
+            #endif
+            break;
+        case ASIOSTInt24LSB:
+            /* src: paInt24, no conversion necessary, possible byte swap */
+            #ifdef PA_MSB_IS_NATIVE_
+                *converter = Swap24;
+            #endif
+            break;
+    }
+}
+
+
+typedef struct PaAsioDeviceInfo
+{
+    PaDeviceInfo commonDeviceInfo;
+    long minBufferSize;
+    long maxBufferSize;
+    long preferredBufferSize;
+    long bufferGranularity;
+
+    ASIOChannelInfo *asioChannelInfos;
+}
+PaAsioDeviceInfo;
+
+
+PaError PaAsio_GetAvailableBufferSizes( PaDeviceIndex device,
+        long *minBufferSizeFrames, long *maxBufferSizeFrames, long *preferredBufferSizeFrames, long *granularity )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi;
+    PaDeviceIndex hostApiDevice;
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+
+    if( result == paNoError )
+    {
+        result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+
+        if( result == paNoError )
+        {
+            PaAsioDeviceInfo *asioDeviceInfo =
+                    (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+            *minBufferSizeFrames = asioDeviceInfo->minBufferSize;
+            *maxBufferSizeFrames = asioDeviceInfo->maxBufferSize;
+            *preferredBufferSizeFrames = asioDeviceInfo->preferredBufferSize;
+            *granularity = asioDeviceInfo->bufferGranularity;
+        }
+    }
+
+    return result;
+}
+
+/* Unload whatever we loaded in LoadAsioDriver().
+*/
+static void UnloadAsioDriver( void )
+{
+       ASIOExit();
+}
+
+/*
+    load the asio driver named by <driverName> and return statistics about
+    the driver in info. If no error occurred, the driver will remain open
+    and must be closed by the called by calling UnloadAsioDriver() - if an error
+    is returned the driver will already be unloaded.
+*/
+static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const char *driverName,
+        PaAsioDriverInfo *driverInfo, void *systemSpecific )
+{
+    PaError result = paNoError;
+    ASIOError asioError;
+    int asioIsInitialized = 0;
+
+    if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(driverName) ) )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" );
+        goto error;
+    }
+
+    memset( &driverInfo->asioDriverInfo, 0, sizeof(ASIODriverInfo) );
+    driverInfo->asioDriverInfo.asioVersion = 2;
+    driverInfo->asioDriverInfo.sysRef = systemSpecific;
+    if( (asioError = ASIOInit( &driverInfo->asioDriverInfo )) != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        goto error;
+    }
+    else
+    {
+        asioIsInitialized = 1;
+    }
+
+    if( (asioError = ASIOGetChannels(&driverInfo->inputChannelCount,
+            &driverInfo->outputChannelCount)) != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        goto error;
+    }
+
+    if( (asioError = ASIOGetBufferSize(&driverInfo->bufferMinSize,
+            &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize,
+            &driverInfo->bufferGranularity)) != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        goto error;
+    }
+
+    if( ASIOOutputReady() == ASE_OK )
+        driverInfo->postOutput = true;
+    else
+        driverInfo->postOutput = false;
+
+    return result;
+
+error:
+    if( asioIsInitialized )
+       {
+               ASIOExit();
+       }
+
+    return result;
+}
+
+
+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_     13   /* must be the same number of elements as in the array below */
+static ASIOSampleRate defaultSampleRateSearchOrder_[]
+     = {44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0,
+        192000.0, 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
+
+
+static PaError InitPaDeviceInfoFromAsioDriver( PaAsioHostApiRepresentation *asioHostApi, 
+        const char *driverName, int driverIndex,
+        PaDeviceInfo *deviceInfo, PaAsioDeviceInfo *asioDeviceInfo )
+{
+    PaError result = paNoError;
+
+    /* Due to the headless design of the ASIO API, drivers are free to write over data given to them (like M-Audio
+       drivers f.i.). This is an attempt to overcome that. */
+    union _tag_local {
+        PaAsioDriverInfo info;
+        char _padding[4096];
+    } paAsioDriver;
+
+    asioDeviceInfo->asioChannelInfos = 0; /* we check this below to handle error cleanup */
+
+    result = LoadAsioDriver( asioHostApi, driverName, &paAsioDriver.info, asioHostApi->systemSpecific );
+    if( result == paNoError )
+    {
+        PA_DEBUG(("PaAsio_Initialize: drv:%d name = %s\n",  driverIndex,deviceInfo->name));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d inputChannels       = %d\n", driverIndex, paAsioDriver.info.inputChannelCount));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d outputChannels      = %d\n", driverIndex, paAsioDriver.info.outputChannelCount));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMinSize       = %d\n", driverIndex, paAsioDriver.info.bufferMinSize));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMaxSize       = %d\n", driverIndex, paAsioDriver.info.bufferMaxSize));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", driverIndex, paAsioDriver.info.bufferPreferredSize));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d bufferGranularity   = %d\n", driverIndex, paAsioDriver.info.bufferGranularity));
+
+        deviceInfo->maxInputChannels  = paAsioDriver.info.inputChannelCount;
+        deviceInfo->maxOutputChannels = paAsioDriver.info.outputChannelCount;
+
+        deviceInfo->defaultSampleRate = 0.;
+        bool foundDefaultSampleRate = false;
+        for( int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j )
+        {
+            ASIOError asioError = ASIOCanSampleRate( defaultSampleRateSearchOrder_[j] );
+            if( asioError != ASE_NoClock && asioError != ASE_NotPresent )
+            {
+                deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[j];
+                foundDefaultSampleRate = true;
+                break;
+            }
+        }
+
+        PA_DEBUG(("PaAsio_Initialize: drv:%d defaultSampleRate = %f\n", driverIndex, deviceInfo->defaultSampleRate));
+
+        if( foundDefaultSampleRate ){
+
+            /* calculate default latency values from bufferPreferredSize
+                for default low latency, and bufferMaxSize
+                for default high latency.
+                use the default sample rate to convert from samples to
+                seconds. Without knowing what sample rate the user will
+                use this is the best we can do.
+            */
+
+            double defaultLowLatency =
+                    paAsioDriver.info.bufferPreferredSize / deviceInfo->defaultSampleRate;
+
+            deviceInfo->defaultLowInputLatency = defaultLowLatency;
+            deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+
+            double defaultHighLatency =
+                    paAsioDriver.info.bufferMaxSize / deviceInfo->defaultSampleRate;
+
+            if( defaultHighLatency < defaultLowLatency )
+                defaultHighLatency = defaultLowLatency; /* just in case the driver returns something strange */ 
+                    
+            deviceInfo->defaultHighInputLatency = defaultHighLatency;
+            deviceInfo->defaultHighOutputLatency = defaultHighLatency;
+            
+        }else{
+
+            deviceInfo->defaultLowInputLatency = 0.;
+            deviceInfo->defaultLowOutputLatency = 0.;
+            deviceInfo->defaultHighInputLatency = 0.;
+            deviceInfo->defaultHighOutputLatency = 0.;
+        }
+
+        PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", driverIndex, deviceInfo->defaultLowInputLatency));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", driverIndex, deviceInfo->defaultLowOutputLatency));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", driverIndex, deviceInfo->defaultHighInputLatency));
+        PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", driverIndex, deviceInfo->defaultHighOutputLatency));
+
+        asioDeviceInfo->minBufferSize = paAsioDriver.info.bufferMinSize;
+        asioDeviceInfo->maxBufferSize = paAsioDriver.info.bufferMaxSize;
+        asioDeviceInfo->preferredBufferSize = paAsioDriver.info.bufferPreferredSize;
+        asioDeviceInfo->bufferGranularity = paAsioDriver.info.bufferGranularity;
+
+
+        asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*)PaUtil_GroupAllocateMemory(
+                asioHostApi->allocations,
+                sizeof(ASIOChannelInfo) * (deviceInfo->maxInputChannels
+                        + deviceInfo->maxOutputChannels) );
+        if( !asioDeviceInfo->asioChannelInfos )
+        {
+            result = paInsufficientMemory;
+            goto error_unload;
+        }
+
+        int a;
+
+        for( a=0; a < deviceInfo->maxInputChannels; ++a ){
+            asioDeviceInfo->asioChannelInfos[a].channel = a;
+            asioDeviceInfo->asioChannelInfos[a].isInput = ASIOTrue;
+            ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[a] );
+            if( asioError != ASE_OK )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+                goto error_unload;
+            }
+        }
+
+        for( a=0; a < deviceInfo->maxOutputChannels; ++a ){
+            int b = deviceInfo->maxInputChannels + a;
+            asioDeviceInfo->asioChannelInfos[b].channel = a;
+            asioDeviceInfo->asioChannelInfos[b].isInput = ASIOFalse;
+            ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[b] );
+            if( asioError != ASE_OK )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+                goto error_unload;
+            }
+        }
+
+        /* unload the driver */
+        UnloadAsioDriver();
+    }
+
+    return result;
+
+error_unload:
+    UnloadAsioDriver();
+
+    if( asioDeviceInfo->asioChannelInfos ){
+        PaUtil_GroupFreeMemory( asioHostApi->allocations, asioDeviceInfo->asioChannelInfos );
+        asioDeviceInfo->asioChannelInfos = 0;
+    }
+
+    return result;
+}
+
+
+/* we look up IsDebuggerPresent at runtime incase it isn't present (on Win95 for example) */
+typedef BOOL (WINAPI *IsDebuggerPresentPtr)(VOID);
+IsDebuggerPresentPtr IsDebuggerPresent_ = 0;
+//FARPROC IsDebuggerPresent_ = 0; // this is the current way to do it apparently according to davidv
+
+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int i, driverCount;
+    PaAsioHostApiRepresentation *asioHostApi;
+    PaAsioDeviceInfo *deviceInfoArray;
+    char **names;
+    asioHostApi = (PaAsioHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaAsioHostApiRepresentation) );
+    if( !asioHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    memset( asioHostApi, 0, sizeof(PaAsioHostApiRepresentation) ); /* ensure all fields are zeroed. especially asioHostApi->allocations */
+
+    /*
+        We initialize COM ourselves here and uninitialize it in Terminate().
+        This should be the only COM initialization needed in this module.
+
+        The ASIO SDK may also initialize COM but since we want to reduce dependency
+        on the ASIO SDK we manage COM initialization ourselves.
+
+        There used to be code that initialized COM in other situations
+        such as when creating a Stream. This made PA work when calling Pa_CreateStream
+        from a non-main thread. However we currently consider initialization 
+        of COM in non-main threads to be the caller's responsibility.
+    */
+    result = PaWinUtil_CoInitialize( paASIO, &asioHostApi->comInitializationResult );
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    asioHostApi->asioDrivers = 0; /* avoid surprises in our error handler below */
+
+    asioHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !asioHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Allocate the AsioDrivers() driver list (class from ASIO SDK) */
+    try
+    {
+        asioHostApi->asioDrivers = new AsioDrivers(); /* invokes CoInitialize(0) in AsioDriverList::AsioDriverList */
+    } 
+    catch (std::bad_alloc)
+    {
+        asioHostApi->asioDrivers = 0;
+    }
+    /* some implementations of new (ie MSVC, see http://support.microsoft.com/?kbid=167733)
+       don't throw std::bad_alloc, so we also explicitly test for a null return. */
+    if( asioHostApi->asioDrivers == 0 )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    asioDrivers = asioHostApi->asioDrivers; /* keep SDK global in sync until we stop depending on it */
+
+    asioHostApi->systemSpecific = 0;
+    asioHostApi->openAsioDeviceIndex = paNoDevice;
+
+    *hostApi = &asioHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+
+    (*hostApi)->info.type = paASIO;
+    (*hostApi)->info.name = "ASIO";
+    (*hostApi)->info.deviceCount = 0;
+
+    #ifdef WINDOWS
+        /* use desktop window as system specific ptr */
+        asioHostApi->systemSpecific = GetDesktopWindow();
+    #endif
+
+    /* driverCount is the number of installed drivers - not necessarily
+        the number of installed physical devices. */
+    #if MAC
+        driverCount = asioHostApi->asioDrivers->getNumFragments();
+    #elif WINDOWS
+        driverCount = asioHostApi->asioDrivers->asioGetNumDev();
+    #endif
+
+    if( driverCount > 0 )
+    {
+        names = GetAsioDriverNames( asioHostApi, asioHostApi->allocations, driverCount );
+        if( !names )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+
+        /* allocate enough space for all drivers, even if some aren't installed */
+
+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                asioHostApi->allocations, sizeof(PaDeviceInfo*) * driverCount );
+        if( !(*hostApi)->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaAsioDeviceInfo*)PaUtil_GroupAllocateMemory(
+                asioHostApi->allocations, sizeof(PaAsioDeviceInfo) * driverCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        IsDebuggerPresent_ = (IsDebuggerPresentPtr)GetProcAddress( LoadLibraryA( "Kernel32.dll" ), "IsDebuggerPresent" );
+
+        for( i=0; i < driverCount; ++i )
+        {
+            PA_DEBUG(("ASIO names[%d]:%s\n",i,names[i]));
+
+            // Since portaudio opens ALL ASIO drivers, and no one else does that,
+            // we face fact that some drivers were not meant for it, drivers which act
+            // like shells on top of REAL drivers, for instance.
+            // so we get duplicate handles, locks and other problems.
+            // so lets NOT try to load any such wrappers. 
+            // The ones i [davidv] know of so far are:
+
+            if (   strcmp (names[i],"ASIO DirectX Full Duplex Driver") == 0
+                || strcmp (names[i],"ASIO Multimedia Driver")          == 0
+                || strncmp(names[i],"Premiere",8)                      == 0   //"Premiere Elements Windows Sound 1.0"
+                || strncmp(names[i],"Adobe",5)                         == 0   //"Adobe Default Windows Sound 1.5"
+               )
+            {
+                PA_DEBUG(("BLACKLISTED!!!\n"));
+                continue;
+            }
+
+
+            if( IsDebuggerPresent_ && IsDebuggerPresent_() )  
+            {
+                /* ASIO Digidesign Driver uses PACE copy protection which quits out
+                   if a debugger is running. So we don't load it if a debugger is running. */
+                if( strcmp(names[i], "ASIO Digidesign Driver") == 0 )  
+                {
+                    PA_DEBUG(("BLACKLISTED!!! ASIO Digidesign Driver would quit the debugger\n"));  
+                    continue;
+                }  
+            }  
+
+
+            /* Attempt to init device info from the asio driver... */
+            {
+                PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+                PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo;
+
+                deviceInfo->structVersion = 2;
+                deviceInfo->hostApi = hostApiIndex;
+
+                deviceInfo->name = names[i];
+
+                if( InitPaDeviceInfoFromAsioDriver( asioHostApi, names[i], i, deviceInfo, asioDeviceInfo ) == paNoError )
+                {
+                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+                    ++(*hostApi)->info.deviceCount;
+                }
+                               else
+                               {
+                    PA_DEBUG(("Skipping ASIO device:%s\n",names[i]));
+                    continue;
+                }
+            }
+        }
+    }
+
+    if( (*hostApi)->info.deviceCount > 0 )
+    {
+        (*hostApi)->info.defaultInputDevice = 0;
+        (*hostApi)->info.defaultOutputDevice = 0;
+    }
+    else
+    {
+        (*hostApi)->info.defaultInputDevice = paNoDevice;
+        (*hostApi)->info.defaultOutputDevice = paNoDevice;
+    }
+
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &asioHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &asioHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    return result;
+
+error:
+    if( asioHostApi )
+    {
+        if( asioHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( asioHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
+        }
+
+        delete asioHostApi->asioDrivers;
+        asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
+
+        PaWinUtil_CoUninitialize( paASIO, &asioHostApi->comInitializationResult );
+
+        PaUtil_FreeMemory( asioHostApi );
+    }
+
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+
+    /*
+        IMPLEMENT ME:
+            - clean up any resources not handled by the allocation group (need to review if there are any)
+    */
+
+    if( asioHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( asioHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
+    }
+
+    delete asioHostApi->asioDrivers;
+    asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
+
+    PaWinUtil_CoUninitialize( paASIO, &asioHostApi->comInitializationResult );
+
+    PaUtil_FreeMemory( asioHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaError result = paNoError;
+    PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+    PaAsioDriverInfo *driverInfo = &asioHostApi->openAsioDriverInfo;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaDeviceIndex asioDeviceIndex;                                  
+    ASIOError asioError;
+    
+    if( inputParameters && outputParameters )
+    {
+        /* full duplex ASIO stream must use the same device for input and output */
+
+        if( inputParameters->device != outputParameters->device )
+            return paBadIODeviceCombination;
+    }
+    
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( inputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        asioDeviceIndex = inputParameters->device;
+
+        /* validate inputStreamInfo */
+        /** @todo do more validation here */
+        // if( inputParameters->hostApiSpecificStreamInfo )
+        //    return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( outputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        asioDeviceIndex = outputParameters->device;
+
+        /* validate outputStreamInfo */
+        /** @todo do more validation here */
+        // if( outputParameters->hostApiSpecificStreamInfo )
+        //    return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+
+
+
+    /* if an ASIO device is open we can only get format information for the currently open device */
+
+    if( asioHostApi->openAsioDeviceIndex != paNoDevice 
+            && asioHostApi->openAsioDeviceIndex != asioDeviceIndex )
+    {
+        return paDeviceUnavailable;
+    }
+
+
+    /* NOTE: we load the driver and use its current settings
+        rather than the ones in our device info structure which may be stale */
+
+    /* open the device if it's not already open */
+    if( asioHostApi->openAsioDeviceIndex == paNoDevice )
+    {
+        result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+                driverInfo, asioHostApi->systemSpecific );
+        if( result != paNoError )
+            return result;
+    }
+
+    /* check that input device can support inputChannelCount */
+    if( inputChannelCount > 0 )
+    {
+        if( inputChannelCount > driverInfo->inputChannelCount )
+        {
+            result = paInvalidChannelCount;
+            goto done;
+        }
+    }
+
+    /* check that output device can support outputChannelCount */
+    if( outputChannelCount )
+    {
+        if( outputChannelCount > driverInfo->outputChannelCount )
+        {
+            result = paInvalidChannelCount;
+            goto done;
+        }
+    }
+    
+    /* query for sample rate support */
+    asioError = ASIOCanSampleRate( sampleRate );
+    if( asioError == ASE_NoClock || asioError == ASE_NotPresent )
+    {
+        result = paInvalidSampleRate;
+        goto done;
+    }
+
+done:
+    /* close the device if it wasn't already open */
+    if( asioHostApi->openAsioDeviceIndex == paNoDevice )
+    {
+        UnloadAsioDriver(); /* not sure if we should check for errors here */
+    }
+
+    if( result == paNoError )
+        return paFormatIsSupported;
+    else
+        return result;
+}
+
+
+
+/** A data structure specifically for storing blocking i/o related data. */
+typedef struct PaAsioStreamBlockingState
+{
+    int stopFlag; /**< Flag indicating that block processing is to be stopped. */
+
+    unsigned long writeBuffersRequested; /**< The number of available output buffers, requested by the #WriteStream() function. */
+    unsigned long readFramesRequested;   /**< The number of available input frames, requested by the #ReadStream() function. */
+
+    int writeBuffersRequestedFlag; /**< Flag to indicate that #WriteStream() has requested more output buffers to be available. */
+    int readFramesRequestedFlag;   /**< Flag to indicate that #ReadStream() requires more input frames to be available. */
+
+    HANDLE writeBuffersReadyEvent; /**< Event to signal that requested output buffers are available. */
+    HANDLE readFramesReadyEvent;   /**< Event to signal that requested input frames are available. */
+
+    void *writeRingBufferData; /**< The actual ring buffer memory, used by the output ring buffer. */
+    void *readRingBufferData;  /**< The actual ring buffer memory, used by the input ring buffer. */
+
+    PaUtilRingBuffer writeRingBuffer; /**< Frame-aligned blocking i/o ring buffer to store output data (interleaved user format). */
+    PaUtilRingBuffer readRingBuffer;  /**< Frame-aligned blocking i/o ring buffer to store input data (interleaved user format). */
+
+    long writeRingBufferInitialFrames; /**< The initial number of silent frames within the output ring buffer. */
+
+    const void **writeStreamBuffer; /**< Temp buffer, used by #WriteStream() for handling non-interleaved data. */
+    void **readStreamBuffer; /**< Temp buffer, used by #ReadStream() for handling non-interleaved data. */
+
+    PaUtilBufferProcessor bufferProcessor; /**< Buffer processor, used to handle the blocking i/o ring buffers. */
+
+    int outputUnderflowFlag; /**< Flag to signal an output underflow from within the callback function. */
+    int inputOverflowFlag; /**< Flag to signal an input overflow from within the callback function. */
+}
+PaAsioStreamBlockingState;
+
+
+
+/* PaAsioStream - a stream data structure specifically for this implementation */
+
+typedef struct PaAsioStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    PaAsioHostApiRepresentation *asioHostApi;
+    unsigned long framesPerHostCallback;
+
+    /* ASIO driver info  - these may not be needed for the life of the stream,
+        but store them here until we work out how format conversion is going
+        to work. */
+
+    ASIOBufferInfo *asioBufferInfos;
+    ASIOChannelInfo *asioChannelInfos;
+    long asioInputLatencyFrames, asioOutputLatencyFrames; // actual latencies returned by asio
+
+    long inputChannelCount, outputChannelCount;
+    bool postOutput;
+
+    void **bufferPtrs; /* this is carved up for inputBufferPtrs and outputBufferPtrs */
+    void **inputBufferPtrs[2];
+    void **outputBufferPtrs[2];
+
+    PaAsioBufferConverter *inputBufferConverter;
+    long inputShift;
+    PaAsioBufferConverter *outputBufferConverter;
+    long outputShift;
+
+    volatile bool stopProcessing;
+    int stopPlayoutCount;
+    HANDLE completedBuffersPlayedEvent;
+
+    bool streamFinishedCallbackCalled;
+    int isStopped;
+    volatile int isActive;
+    volatile bool zeroOutput; /* all future calls to the callback will output silence */
+
+    volatile long reenterCount;
+    volatile long reenterError;
+
+    PaStreamCallbackFlags callbackFlags;
+
+    PaAsioStreamBlockingState *blockingState; /**< Blocking i/o data struct, or NULL when using callback interface. */
+}
+PaAsioStream;
+
+static PaAsioStream *theAsioStream = 0; /* due to ASIO sdk limitations there can be only one stream */
+
+
+static void ZeroOutputBuffers( PaAsioStream *stream, long index )
+{
+    int i;
+
+    for( i=0; i < stream->outputChannelCount; ++i )
+    {
+        void *buffer = stream->asioBufferInfos[ i + stream->inputChannelCount ].buffers[index];
+
+        int bytesPerSample = BytesPerAsioSample( stream->asioChannelInfos[ i + stream->inputChannelCount ].type );
+
+        memset( buffer, 0, stream->framesPerHostCallback * bytesPerSample );
+    }
+}
+
+
+/* return the next power of two >= x. 
+   Returns the input parameter if it is already a power of two. 
+   http://stackoverflow.com/questions/364985/algorithm-for-finding-the-smallest-power-of-two-thats-greater-or-equal-to-a-giv 
+*/
+static unsigned long NextPowerOfTwo( unsigned long x )
+{
+    --x;
+    x |= x >> 1;
+    x |= x >> 2;
+    x |= x >> 4;
+    x |= x >> 8;
+    x |= x >> 16;
+    /* If you needed to deal with numbers > 2^32 the following would be needed. 
+       For latencies, we don't deal with values this large. 
+     x |= x >> 16;
+    */
+
+    return x + 1;
+}
+
+
+static unsigned long SelectHostBufferSizeForUnspecifiedUserFramesPerBuffer( 
+        unsigned long targetBufferingLatencyFrames, PaAsioDriverInfo *driverInfo )
+{
+       /* Choose a host buffer size based only on targetBufferingLatencyFrames and the 
+          device's supported buffer sizes. Always returns a valid value.
+       */
+
+       unsigned long result;
+
+       if( targetBufferingLatencyFrames <= (unsigned long)driverInfo->bufferMinSize )
+    {
+        result = driverInfo->bufferMinSize;
+    }
+    else if( targetBufferingLatencyFrames >= (unsigned long)driverInfo->bufferMaxSize )
+    {
+        result = driverInfo->bufferMaxSize;
+    }
+    else
+    {
+               if( driverInfo->bufferGranularity == 0 ) /* single fixed host buffer size */
+        {
+            /* The documentation states that bufferGranularity should be zero 
+               when bufferMinSize, bufferMaxSize and bufferPreferredSize are the 
+               same. We assume that is the case.
+            */
+
+            result = driverInfo->bufferPreferredSize;
+        }
+               else if( driverInfo->bufferGranularity == -1 ) /* power-of-two */
+        {
+                   /* We assume bufferMinSize and bufferMaxSize are powers of two. */
+
+            result = NextPowerOfTwo( targetBufferingLatencyFrames );
+
+            if( result < (unsigned long)driverInfo->bufferMinSize )
+                result = driverInfo->bufferMinSize;
+
+            if( result > (unsigned long)driverInfo->bufferMaxSize )
+                result = driverInfo->bufferMaxSize;
+        }
+        else /* modulo bufferGranularity */
+        {
+            /* round up to the next multiple of granularity */
+            unsigned long n = (targetBufferingLatencyFrames + driverInfo->bufferGranularity - 1) 
+                    / driverInfo->bufferGranularity;
+            
+            result = n * driverInfo->bufferGranularity;
+
+            if( result < (unsigned long)driverInfo->bufferMinSize )
+                result = driverInfo->bufferMinSize;
+
+            if( result > (unsigned long)driverInfo->bufferMaxSize )
+                result = driverInfo->bufferMaxSize;
+        }
+    }
+
+       return result;
+}
+
+
+static unsigned long SelectHostBufferSizeForSpecifiedUserFramesPerBuffer( 
+        unsigned long targetBufferingLatencyFrames, unsigned long userFramesPerBuffer,
+        PaAsioDriverInfo *driverInfo )
+{
+       /* Select a host buffer size conforming to targetBufferingLatencyFrames 
+          and the device's supported buffer sizes.
+          The return value will always be a multiple of userFramesPerBuffer. 
+          If a valid buffer size can not be found the function returns 0.
+
+          The current implementation uses a simple iterative search for clarity.
+          Feel free to suggest a closed form solution.
+       */
+       unsigned long result = 0;
+
+       assert( userFramesPerBuffer != 0 );
+       
+       if( driverInfo->bufferGranularity == 0 ) /* single fixed host buffer size */
+    {
+        /* The documentation states that bufferGranularity should be zero 
+           when bufferMinSize, bufferMaxSize and bufferPreferredSize are the 
+           same. We assume that is the case.
+        */
+
+               if( (driverInfo->bufferPreferredSize % userFramesPerBuffer) == 0 )
+                       result = driverInfo->bufferPreferredSize;
+    }
+       else if( driverInfo->bufferGranularity == -1 ) /* power-of-two */
+    {
+               /* We assume bufferMinSize and bufferMaxSize are powers of two. */
+
+        /* Search all powers of two in the range [bufferMinSize,bufferMaxSize] 
+           for multiples of userFramesPerBuffer. We prefer the first multiple
+           that is equal or greater than targetBufferingLatencyFrames, or  
+           failing that, the largest multiple less than 
+           targetBufferingLatencyFrames.
+        */
+        unsigned long x = (unsigned long)driverInfo->bufferMinSize; 
+               do {
+                       if( (x % userFramesPerBuffer) == 0 )
+                       {
+                /* any multiple of userFramesPerBuffer is acceptable */
+                               result = x;
+                               if( result >= targetBufferingLatencyFrames )
+                                       break; /* stop. a value >= to targetBufferingLatencyFrames is ideal. */
+                       }
+
+                       x *= 2;
+               } while( x <= (unsigned long)driverInfo->bufferMaxSize );
+    }
+    else /* modulo granularity */
+    {
+               /* We assume bufferMinSize is a multiple of bufferGranularity. */
+
+        /* Search all multiples of bufferGranularity in the range 
+           [bufferMinSize,bufferMaxSize] for multiples of userFramesPerBuffer. 
+           We prefer the first multiple that is equal or greater than 
+           targetBufferingLatencyFrames, or failing that, the largest multiple  
+           less than targetBufferingLatencyFrames.
+        */
+               unsigned long x = (unsigned long)driverInfo->bufferMinSize; 
+               do {
+                       if( (x % userFramesPerBuffer) == 0 )
+                       {
+                /* any multiple of userFramesPerBuffer is acceptable */
+                               result = x;
+                               if( result >= targetBufferingLatencyFrames )
+                                       break; /* stop. a value >= to targetBufferingLatencyFrames is ideal. */
+                       }
+
+                       x += driverInfo->bufferGranularity;
+               } while( x <= (unsigned long)driverInfo->bufferMaxSize );
+    }
+
+       return result;
+}
+
+
+static unsigned long SelectHostBufferSize( 
+        unsigned long targetBufferingLatencyFrames, 
+        unsigned long userFramesPerBuffer, PaAsioDriverInfo *driverInfo )
+{
+    unsigned long result = 0;
+
+    /* We select a host buffer size based on the following requirements 
+       (in priority order):
+
+        1. The host buffer size must be permissible according to the ASIO 
+           driverInfo buffer size constraints (min, max, granularity or 
+           powers-of-two).
+
+        2. If the user specifies a non-zero framesPerBuffer parameter 
+           (userFramesPerBuffer here) the host buffer should be a multiple of 
+           this (subject to the constraints in (1) above).
+
+           [NOTE: Where no permissible host buffer size is a multiple of 
+           userFramesPerBuffer, we choose a value as if userFramesPerBuffer were 
+           zero (i.e. we ignore it). This strategy is open for review ~ perhaps 
+           there are still "more optimal" buffer sizes related to 
+           userFramesPerBuffer that we could use.]
+
+        3. The host buffer size should be greater than or equal to 
+           targetBufferingLatencyFrames, subject to (1) and (2) above. Where it 
+           is not possible to select a host buffer size equal or greater than 
+           targetBufferingLatencyFrames, the highest buffer size conforming to  
+           (1) and (2) should be chosen.
+    */
+
+       if( userFramesPerBuffer != 0 )
+       {
+               /* userFramesPerBuffer is specified, try to find a buffer size that's 
+           a multiple of it */
+               result = SelectHostBufferSizeForSpecifiedUserFramesPerBuffer( 
+                targetBufferingLatencyFrames, userFramesPerBuffer, driverInfo );
+       }
+
+       if( result == 0 )
+       {
+               /* either userFramesPerBuffer was not specified, or we couldn't find a 
+           host buffer size that is a multiple of it. Select a host buffer size 
+           according to targetBufferingLatencyFrames and the ASIO driverInfo 
+           buffer size constraints.
+            */
+               result = SelectHostBufferSizeForUnspecifiedUserFramesPerBuffer( 
+                targetBufferingLatencyFrames, driverInfo );
+       }
+
+       return result;
+}
+
+
+/* returns channelSelectors if present */
+
+static PaError ValidateAsioSpecificStreamInfo(
+        const PaStreamParameters *streamParameters,
+        const PaAsioStreamInfo *streamInfo,
+        int deviceChannelCount,
+        int **channelSelectors )
+{
+    if( streamInfo )
+    {
+        if( streamInfo->size != sizeof( PaAsioStreamInfo )
+                || streamInfo->version != 1 )
+        {
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        if( streamInfo->flags & paAsioUseChannelSelectors )
+            *channelSelectors = streamInfo->channelSelectors;
+
+        if( !(*channelSelectors) )
+            return paIncompatibleHostApiSpecificStreamInfo;
+
+        for( int i=0; i < streamParameters->channelCount; ++i ){
+             if( (*channelSelectors)[i] < 0
+                    || (*channelSelectors)[i] >= deviceChannelCount ){
+                return paInvalidChannelCount;
+             }           
+        }
+    }
+
+    return paNoError;
+}
+
+
+static bool IsUsingExternalClockSource()
+{
+    bool result = false;
+    ASIOError asioError;
+    ASIOClockSource clocks[32];
+    long numSources=32;
+
+    /* davidv: listing ASIO Clock sources. there is an ongoing investigation by
+       me about whether or not to call ASIOSetSampleRate if an external Clock is
+       used. A few drivers expected different things here */
+    
+    asioError = ASIOGetClockSources(clocks, &numSources);
+    if( asioError != ASE_OK ){
+        PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+    }else{
+        PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources ));
+        for (int i=0;i<numSources;++i){
+            PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i, clocks[i].name, clocks[i].isCurrentSource ));
+           
+            if (clocks[i].isCurrentSource)
+                result = true;
+        }
+    }
+
+    return result;
+}
+
+
+static PaError ValidateAndSetSampleRate( double sampleRate )
+{
+    PaError result = paNoError;
+    ASIOError asioError;
+
+    // check that the device supports the requested sample rate 
+
+    asioError = ASIOCanSampleRate( sampleRate );
+    PA_DEBUG(("ASIOCanSampleRate(%f):%d\n", sampleRate, asioError ));
+
+    if( asioError != ASE_OK )
+    {
+        result = paInvalidSampleRate;
+        PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        goto error;
+    }
+
+    // retrieve the current sample rate, we only change to the requested
+    // sample rate if the device is not already in that rate.
+
+    ASIOSampleRate oldRate;
+    asioError = ASIOGetSampleRate(&oldRate);
+    if( asioError != ASE_OK )
+    {
+        result = paInvalidSampleRate;
+        PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        goto error;
+    }
+    PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate));
+
+    if (oldRate != sampleRate){
+        /* Set sample rate */
+
+        PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate));
+
+        /*
+            If you have problems with some drivers when externally clocked, 
+            try switching on the following line and commenting out the one after it.
+            See IsUsingExternalClockSource() for more info.
+        */
+        //if( IsUsingExternalClockSource() ){
+        if( false ){
+            asioError = ASIOSetSampleRate( 0 );
+        }else{
+            asioError = ASIOSetSampleRate( sampleRate );
+        }
+        if( asioError != ASE_OK )
+        {
+            result = paInvalidSampleRate;
+            PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+            goto error;
+        }
+        PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate));
+    }
+    else
+    {
+        PA_DEBUG(("No Need to change SR\n"));
+    }
+
+error:
+    return result;
+}
+
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream  parameters */
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+    PaAsioStream *stream = 0;
+    PaAsioStreamInfo *inputStreamInfo, *outputStreamInfo;
+    unsigned long framesPerHostBuffer;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+    unsigned long suggestedInputLatencyFrames;
+    unsigned long suggestedOutputLatencyFrames;
+    PaDeviceIndex asioDeviceIndex;
+    ASIOError asioError;
+    int asioIsInitialized = 0;
+    int asioBuffersCreated = 0;
+    int completedBuffersPlayedEventInited = 0;
+    int i;
+    PaAsioDriverInfo *driverInfo;
+    int *inputChannelSelectors = 0;
+    int *outputChannelSelectors = 0;
+
+    /* Are we using blocking i/o interface? */
+    int usingBlockingIo = ( !streamCallback ) ? TRUE : FALSE;
+    /* Blocking i/o stuff */
+    long lBlockingBufferSize     = 0; /* Desired ring buffer size in samples. */
+    long lBlockingBufferSizePow2 = 0; /* Power-of-2 rounded ring buffer size. */
+    long lBytesPerFrame          = 0; /* Number of bytes per input/output frame. */
+    int blockingWriteBuffersReadyEventInitialized = 0; /* Event init flag. */
+    int blockingReadFramesReadyEventInitialized   = 0; /* Event init flag. */
+
+    int callbackBufferProcessorInited = FALSE;
+    int blockingBufferProcessorInited = FALSE;
+
+    /* unless we move to using lower level ASIO calls, we can only have
+        one device open at a time */
+    if( asioHostApi->openAsioDeviceIndex != paNoDevice )
+    {
+        PA_DEBUG(("OpenStream paDeviceUnavailable\n"));
+        return paDeviceUnavailable;
+    }
+
+    assert( theAsioStream == 0 );
+
+    if( inputParameters && outputParameters )
+    {
+        /* full duplex ASIO stream must use the same device for input and output */
+
+        if( inputParameters->device != outputParameters->device )
+        {
+            PA_DEBUG(("OpenStream paBadIODeviceCombination\n"));
+            return paBadIODeviceCombination;
+        }
+    }
+
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        suggestedInputLatencyFrames = (unsigned long)((inputParameters->suggestedLatency * sampleRate)+0.5f);
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        asioDeviceIndex = inputParameters->device;
+
+        PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
+
+        /* validate hostApiSpecificStreamInfo */
+        inputStreamInfo = (PaAsioStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+        result = ValidateAsioSpecificStreamInfo( inputParameters, inputStreamInfo,
+            asioDeviceInfo->commonDeviceInfo.maxInputChannels,
+            &inputChannelSelectors
+        );
+        if( result != paNoError ) return result;
+    }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = 0;
+        suggestedInputLatencyFrames = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        suggestedOutputLatencyFrames = (unsigned long)((outputParameters->suggestedLatency * sampleRate)+0.5f);
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        asioDeviceIndex = outputParameters->device;
+
+        PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
+
+        /* validate hostApiSpecificStreamInfo */
+        outputStreamInfo = (PaAsioStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+        result = ValidateAsioSpecificStreamInfo( outputParameters, outputStreamInfo,
+            asioDeviceInfo->commonDeviceInfo.maxOutputChannels,
+            &outputChannelSelectors
+        );
+        if( result != paNoError ) return result;
+    }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = 0;
+        suggestedOutputLatencyFrames = 0;
+    }
+
+    driverInfo = &asioHostApi->openAsioDriverInfo;
+
+    /* NOTE: we load the driver and use its current settings
+        rather than the ones in our device info structure which may be stale */
+
+    result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+            driverInfo, asioHostApi->systemSpecific );
+    if( result == paNoError )
+        asioIsInitialized = 1;
+    else{
+        PA_DEBUG(("OpenStream ERROR1 - LoadAsioDriver returned %d\n", result));
+        goto error;
+    }
+
+    /* check that input device can support inputChannelCount */
+    if( inputChannelCount > 0 )
+    {
+        if( inputChannelCount > driverInfo->inputChannelCount )
+        {
+            result = paInvalidChannelCount;
+            PA_DEBUG(("OpenStream ERROR2\n"));
+            goto error;
+        }
+    }
+
+    /* check that output device can support outputChannelCount */
+    if( outputChannelCount )
+    {
+        if( outputChannelCount > driverInfo->outputChannelCount )
+        {
+            result = paInvalidChannelCount;
+            PA_DEBUG(("OpenStream ERROR3\n"));
+            goto error;
+        }
+    }
+
+    result = ValidateAndSetSampleRate( sampleRate );
+    if( result != paNoError )
+        goto error;
+
+    /*
+        IMPLEMENT ME:
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+    */
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 ){
+        PA_DEBUG(("OpenStream invalid flags!!\n"));
+        return paInvalidFlag; /* unexpected platform specific flag */
+    }
+
+
+    stream = (PaAsioStream*)PaUtil_AllocateMemory( sizeof(PaAsioStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        PA_DEBUG(("OpenStream ERROR5\n"));
+        goto error;
+    }
+    stream->blockingState = NULL; /* Blocking i/o not initialized, yet. */
+
+
+    stream->completedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
+    if( stream->completedBuffersPlayedEvent == NULL )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+        PA_DEBUG(("OpenStream ERROR6\n"));
+        goto error;
+    }
+    completedBuffersPlayedEventInited = 1;
+
+
+    stream->asioBufferInfos = 0; /* for deallocation in error */
+    stream->asioChannelInfos = 0; /* for deallocation in error */
+    stream->bufferPtrs = 0; /* for deallocation in error */
+
+    /* Using blocking i/o interface... */
+    if( usingBlockingIo )
+    {
+        /* Blocking i/o is implemented by running callback mode, using a special blocking i/o callback. */
+        streamCallback = BlockingIoPaCallback; /* Setup PA to use the ASIO blocking i/o callback. */
+        userData       = &theAsioStream;       /* The callback user data will be the PA ASIO stream. */
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &asioHostApi->blockingStreamInterface, streamCallback, userData );
+    }
+    else /* Using callback interface... */
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &asioHostApi->callbackStreamInterface, streamCallback, userData );
+    }
+
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+    stream->asioBufferInfos = (ASIOBufferInfo*)PaUtil_AllocateMemory(
+            sizeof(ASIOBufferInfo) * (inputChannelCount + outputChannelCount) );
+    if( !stream->asioBufferInfos )
+    {
+        result = paInsufficientMemory;
+        PA_DEBUG(("OpenStream ERROR7\n"));
+        goto error;
+    }
+
+
+    for( i=0; i < inputChannelCount; ++i )
+    {
+        ASIOBufferInfo *info = &stream->asioBufferInfos[i];
+
+        info->isInput = ASIOTrue;
+
+        if( inputChannelSelectors ){
+            // inputChannelSelectors values have already been validated in
+            // ValidateAsioSpecificStreamInfo() above
+            info->channelNum = inputChannelSelectors[i];
+        }else{
+            info->channelNum = i;
+        }
+
+        info->buffers[0] = info->buffers[1] = 0;
+    }
+
+    for( i=0; i < outputChannelCount; ++i ){
+        ASIOBufferInfo *info = &stream->asioBufferInfos[inputChannelCount+i];
+
+        info->isInput = ASIOFalse;
+
+        if( outputChannelSelectors ){
+            // outputChannelSelectors values have already been validated in
+            // ValidateAsioSpecificStreamInfo() above
+            info->channelNum = outputChannelSelectors[i];
+        }else{
+            info->channelNum = i;
+        }
+        
+        info->buffers[0] = info->buffers[1] = 0;
+    }
+
+
+    /* Using blocking i/o interface... */
+    if( usingBlockingIo )
+    {
+/** @todo REVIEW selection of host buffer size for blocking i/o */
+
+        framesPerHostBuffer = SelectHostBufferSize( 0, framesPerBuffer, driverInfo );
+
+    }
+    else /* Using callback interface... */
+    {
+        /* Select the host buffer size based on user framesPerBuffer and the
+           maximum of suggestedInputLatencyFrames and 
+           suggestedOutputLatencyFrames.
+
+           We should subtract any fixed known driver latency from 
+           suggestedLatencyFrames before computing the host buffer size.
+           However, the ASIO API doesn't provide a method for determining fixed 
+           latencies independent of the host buffer size. ASIOGetLatencies()  
+           only returns latencies after the buffer size has been configured, so 
+           we can't reliably use it to determine fixed latencies here.
+
+           We could set the preferred buffer size and then subtract it from
+           the values returned from ASIOGetLatencies, but this would not be 100%
+           reliable, so we don't do it.
+        */
+
+        unsigned long targetBufferingLatencyFrames = 
+                (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames )
+                ? suggestedInputLatencyFrames 
+                : suggestedOutputLatencyFrames);
+
+        framesPerHostBuffer = SelectHostBufferSize( targetBufferingLatencyFrames, 
+                framesPerBuffer, driverInfo );
+    }
+
+
+    PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n",  framesPerHostBuffer));
+
+    asioError = ASIOCreateBuffers( stream->asioBufferInfos,
+            inputChannelCount+outputChannelCount,
+            framesPerHostBuffer, &asioCallbacks_ );
+
+    if( asioError != ASE_OK
+            && framesPerHostBuffer != (unsigned long)driverInfo->bufferPreferredSize )
+    {
+        PA_DEBUG(("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        /*
+            Some buggy drivers (like the Hoontech DSP24) give incorrect
+            [min, preferred, max] values They should work with the preferred size
+            value, thus if Pa_ASIO_CreateBuffers fails with the hostBufferSize
+            computed in SelectHostBufferSize, we try again with the preferred size.
+        */
+
+        framesPerHostBuffer = driverInfo->bufferPreferredSize;
+
+        PA_DEBUG(("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n",  framesPerHostBuffer));
+
+        ASIOError asioError2 = ASIOCreateBuffers( stream->asioBufferInfos,
+                inputChannelCount+outputChannelCount,
+                 framesPerHostBuffer, &asioCallbacks_ );
+        if( asioError2 == ASE_OK )
+            asioError = ASE_OK;
+    }
+
+    if( asioError != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        PA_DEBUG(("OpenStream ERROR9\n"));
+        goto error;
+    }
+
+    asioBuffersCreated = 1;
+
+    stream->asioChannelInfos = (ASIOChannelInfo*)PaUtil_AllocateMemory(
+            sizeof(ASIOChannelInfo) * (inputChannelCount + outputChannelCount) );
+    if( !stream->asioChannelInfos )
+    {
+        result = paInsufficientMemory;
+        PA_DEBUG(("OpenStream ERROR10\n"));
+        goto error;
+    }
+
+    for( i=0; i < inputChannelCount + outputChannelCount; ++i )
+    {
+        stream->asioChannelInfos[i].channel = stream->asioBufferInfos[i].channelNum;
+        stream->asioChannelInfos[i].isInput = stream->asioBufferInfos[i].isInput;
+        asioError = ASIOGetChannelInfo( &stream->asioChannelInfos[i] );
+        if( asioError != ASE_OK )
+        {
+            result = paUnanticipatedHostError;
+            PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+            PA_DEBUG(("OpenStream ERROR11\n"));
+            goto error;
+        }
+    }
+
+    stream->bufferPtrs = (void**)PaUtil_AllocateMemory(
+            2 * sizeof(void*) * (inputChannelCount + outputChannelCount) );
+    if( !stream->bufferPtrs )
+    {
+        result = paInsufficientMemory;
+        PA_DEBUG(("OpenStream ERROR12\n"));
+        goto error;
+    }
+
+    if( inputChannelCount > 0 )
+    {
+        stream->inputBufferPtrs[0] = stream-> bufferPtrs;
+        stream->inputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount];
+
+        for( i=0; i<inputChannelCount; ++i )
+        {
+            stream->inputBufferPtrs[0][i] = stream->asioBufferInfos[i].buffers[0];
+            stream->inputBufferPtrs[1][i] = stream->asioBufferInfos[i].buffers[1];
+        }
+    }
+    else
+    {
+        stream->inputBufferPtrs[0] = 0;
+        stream->inputBufferPtrs[1] = 0;
+    }
+
+    if( outputChannelCount > 0 )
+    {
+        stream->outputBufferPtrs[0] = &stream->bufferPtrs[inputChannelCount*2];
+        stream->outputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount*2 + outputChannelCount];
+
+        for( i=0; i<outputChannelCount; ++i )
+        {
+            stream->outputBufferPtrs[0][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[0];
+            stream->outputBufferPtrs[1][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[1];
+        }
+    }
+    else
+    {
+        stream->outputBufferPtrs[0] = 0;
+        stream->outputBufferPtrs[1] = 0;
+    }
+
+    if( inputChannelCount > 0 )
+    {
+        /* FIXME: assume all channels use the same type for now 
+        
+            see: "ASIO devices with multiple sample formats are unsupported"
+            http://www.portaudio.com/trac/ticket/106
+        */
+        ASIOSampleType inputType = stream->asioChannelInfos[0].type;
+
+        PA_DEBUG(("ASIO Input  type:%d",inputType));
+        AsioSampleTypeLOG(inputType);
+        hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( inputType );
+
+        SelectAsioToPaConverter( inputType, &stream->inputBufferConverter, &stream->inputShift );
+    }
+    else
+    {
+        hostInputSampleFormat = 0;
+        stream->inputBufferConverter = 0;
+    }
+
+    if( outputChannelCount > 0 )
+    {
+        /* FIXME: assume all channels use the same type for now 
+        
+            see: "ASIO devices with multiple sample formats are unsupported"
+            http://www.portaudio.com/trac/ticket/106
+        */
+        ASIOSampleType outputType = stream->asioChannelInfos[inputChannelCount].type;
+
+        PA_DEBUG(("ASIO Output type:%d",outputType));
+        AsioSampleTypeLOG(outputType);
+        hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( outputType );
+
+        SelectPaToAsioConverter( outputType, &stream->outputBufferConverter, &stream->outputShift );
+    }
+    else
+    {
+        hostOutputSampleFormat = 0;
+        stream->outputBufferConverter = 0;
+    }
+
+    /* Values returned by ASIOGetLatencies() include the latency introduced by 
+       the ASIO double buffer. */
+    ASIOGetLatencies( &stream->asioInputLatencyFrames, &stream->asioOutputLatencyFrames );
+
+
+    /* Using blocking i/o interface... */
+    if( usingBlockingIo )
+    {
+        /* Allocate the blocking i/o input ring buffer memory. */
+        stream->blockingState = (PaAsioStreamBlockingState*)PaUtil_AllocateMemory( sizeof(PaAsioStreamBlockingState) );
+        if( !stream->blockingState )
+        {
+            result = paInsufficientMemory;
+            PA_DEBUG(("ERROR! Blocking i/o interface struct allocation failed in OpenStream()\n"));
+            goto error;
+        }
+
+        /* Initialize blocking i/o interface struct. */
+        stream->blockingState->readFramesReadyEvent   = NULL; /* Uninitialized, yet. */
+        stream->blockingState->writeBuffersReadyEvent = NULL; /* Uninitialized, yet. */
+        stream->blockingState->readRingBufferData     = NULL; /* Uninitialized, yet. */
+        stream->blockingState->writeRingBufferData    = NULL; /* Uninitialized, yet. */
+        stream->blockingState->readStreamBuffer       = NULL; /* Uninitialized, yet. */
+        stream->blockingState->writeStreamBuffer      = NULL; /* Uninitialized, yet. */
+        stream->blockingState->stopFlag               = TRUE; /* Not started, yet. */
+
+
+        /* If the user buffer is unspecified */
+        if( framesPerBuffer == paFramesPerBufferUnspecified )
+        {
+            /* Make the user buffer the same size as the host buffer. */
+            framesPerBuffer = framesPerHostBuffer;
+        }
+
+
+        /* Initialize callback buffer processor. */
+        result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor               ,
+                                                    inputChannelCount                     ,
+                                                    inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
+                                                    (hostInputSampleFormat | paNonInterleaved), /* Host format. */
+                                                    outputChannelCount                    ,
+                                                    outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
+                                                    (hostOutputSampleFormat | paNonInterleaved), /* Host format. */
+                                                    sampleRate                            ,
+                                                    streamFlags                           ,
+                                                    framesPerBuffer                       , /* Frames per ring buffer block. */
+                                                    framesPerHostBuffer                   , /* Frames per asio buffer. */
+                                                    paUtilFixedHostBufferSize             ,
+                                                    streamCallback                        ,
+                                                    userData                               );
+        if( result != paNoError ){
+            PA_DEBUG(("OpenStream ERROR13\n"));
+            goto error;
+        }
+        callbackBufferProcessorInited = TRUE;
+
+        /* Initialize the blocking i/o buffer processor. */
+        result = PaUtil_InitializeBufferProcessor(&stream->blockingState->bufferProcessor,
+                                                   inputChannelCount                     ,
+                                                   inputSampleFormat                     , /* User format. */
+                                                   inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
+                                                   outputChannelCount                    ,
+                                                   outputSampleFormat                    , /* User format. */
+                                                   outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
+                                                   sampleRate                            ,
+                                                   paClipOff | paDitherOff               , /* Don't use dither nor clipping. */
+                                                   framesPerBuffer                       , /* Frames per user buffer. */
+                                                   framesPerBuffer                       , /* Frames per ring buffer block. */
+                                                   paUtilBoundedHostBufferSize           ,
+                                                   NULL, NULL                            );/* No callback! */
+        if( result != paNoError ){
+            PA_DEBUG(("ERROR! Blocking i/o buffer processor initialization failed in OpenStream()\n"));
+            goto error;
+        }
+        blockingBufferProcessorInited = TRUE;
+
+        /* If input is requested. */
+        if( inputChannelCount )
+        {
+            /* Create the callback sync-event. */
+            stream->blockingState->readFramesReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
+            if( stream->blockingState->readFramesReadyEvent == NULL )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+                PA_DEBUG(("ERROR! Blocking i/o \"read frames ready\" event creation failed in OpenStream()\n"));
+                goto error;
+            }
+            blockingReadFramesReadyEventInitialized = 1;
+
+
+            /* Create pointer buffer to access non-interleaved data in ReadStream() */
+            stream->blockingState->readStreamBuffer = (void**)PaUtil_AllocateMemory( sizeof(void*) * inputChannelCount );
+            if( !stream->blockingState->readStreamBuffer )
+            {
+                result = paInsufficientMemory;
+                PA_DEBUG(("ERROR! Blocking i/o read stream buffer allocation failed in OpenStream()\n"));
+                goto error;
+            }
+
+            /* The ring buffer should store as many data blocks as needed
+               to achieve the requested latency. Whereas it must be large
+               enough to store at least two complete data blocks.
+
+               1) Determine the amount of latency to be added to the
+                  prefered ASIO latency.
+               2) Make sure we have at lest one additional latency frame.
+               3) Divide the number of frames by the desired block size to
+                  get the number (rounded up to pure integer) of blocks to
+                  be stored in the buffer.
+               4) Add one additional block for block processing and convert
+                  to samples frames.
+               5) Get the next larger (or equal) power-of-two buffer size.
+             */
+            lBlockingBufferSize = suggestedInputLatencyFrames - stream->asioInputLatencyFrames;
+            lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
+            lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
+            lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
+
+            /* Get the next larger or equal power-of-two buffersize. */
+            lBlockingBufferSizePow2 = 1;
+            while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
+            lBlockingBufferSize = lBlockingBufferSizePow2;
+
+            /* Compute total intput latency in seconds */
+            stream->streamRepresentation.streamInfo.inputLatency =
+                (double)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor               )
+                        + PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor)
+                        + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
+                        + stream->asioInputLatencyFrames )
+                / sampleRate;
+
+            /* The code below prints the ASIO latency which doesn't include
+               the buffer processor latency nor the blocking i/o latency. It
+               reports the added latency separately.
+            */
+            PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms),\n         added buffProc:%ld (%ld ms),\n         added blocking:%ld (%ld ms)\n",
+                stream->asioInputLatencyFrames,
+                (long)( stream->asioInputLatencyFrames * (1000.0 / sampleRate) ),
+                PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor),
+                (long)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
+                PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
+                (long)( (PaUtil_GetBufferProcessorInputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
+                ));
+
+            /* Determine the size of ring buffer in bytes. */
+            lBytesPerFrame = inputChannelCount * Pa_GetSampleSize(inputSampleFormat );
+
+            /* Allocate the blocking i/o input ring buffer memory. */
+            stream->blockingState->readRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
+            if( !stream->blockingState->readRingBufferData )
+            {
+                result = paInsufficientMemory;
+                PA_DEBUG(("ERROR! Blocking i/o input ring buffer allocation failed in OpenStream()\n"));
+                goto error;
+            }
+
+            /* Initialize the input ring buffer struct. */
+            PaUtil_InitializeRingBuffer( &stream->blockingState->readRingBuffer    ,
+                                          lBytesPerFrame                           ,
+                                          lBlockingBufferSize                      ,
+                                          stream->blockingState->readRingBufferData );
+        }
+
+        /* If output is requested. */
+        if( outputChannelCount )
+        {
+            stream->blockingState->writeBuffersReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
+            if( stream->blockingState->writeBuffersReadyEvent == NULL )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+                PA_DEBUG(("ERROR! Blocking i/o \"write buffers ready\" event creation failed in OpenStream()\n"));
+                goto error;
+            }
+            blockingWriteBuffersReadyEventInitialized = 1;
+
+            /* Create pointer buffer to access non-interleaved data in WriteStream() */
+            stream->blockingState->writeStreamBuffer = (const void**)PaUtil_AllocateMemory( sizeof(const void*) * outputChannelCount );
+            if( !stream->blockingState->writeStreamBuffer )
+            {
+                result = paInsufficientMemory;
+                PA_DEBUG(("ERROR! Blocking i/o write stream buffer allocation failed in OpenStream()\n"));
+                goto error;
+            }
+
+            /* The ring buffer should store as many data blocks as needed
+               to achieve the requested latency. Whereas it must be large
+               enough to store at least two complete data blocks.
+
+               1) Determine the amount of latency to be added to the
+                  prefered ASIO latency.
+               2) Make sure we have at lest one additional latency frame.
+               3) Divide the number of frames by the desired block size to
+                  get the number (rounded up to pure integer) of blocks to
+                  be stored in the buffer.
+               4) Add one additional block for block processing and convert
+                  to samples frames.
+               5) Get the next larger (or equal) power-of-two buffer size.
+             */
+            lBlockingBufferSize = suggestedOutputLatencyFrames - stream->asioOutputLatencyFrames;
+            lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
+            lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
+            lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
+
+            /* The buffer size (without the additional block) corresponds
+               to the initial number of silent samples in the output ring
+               buffer. */
+            stream->blockingState->writeRingBufferInitialFrames = lBlockingBufferSize - framesPerBuffer;
+
+            /* Get the next larger or equal power-of-two buffersize. */
+            lBlockingBufferSizePow2 = 1;
+            while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
+            lBlockingBufferSize = lBlockingBufferSizePow2;
+
+            /* Compute total output latency in seconds */
+            stream->streamRepresentation.streamInfo.outputLatency =
+                (double)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
+                        + PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor)
+                        + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
+                        + stream->asioOutputLatencyFrames )
+                / sampleRate;
+
+            /* The code below prints the ASIO latency which doesn't include
+               the buffer processor latency nor the blocking i/o latency. It
+               reports the added latency separately.
+            */
+            PA_DEBUG(("PaAsio : ASIO OutputLatency = %ld (%ld ms),\n         added buffProc:%ld (%ld ms),\n         added blocking:%ld (%ld ms)\n",
+                stream->asioOutputLatencyFrames,
+                (long)( stream->asioOutputLatencyFrames * (1000.0 / sampleRate) ),
+                PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor),
+                (long)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
+                PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
+                (long)( (PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
+                ));
+
+            /* Determine the size of ring buffer in bytes. */
+            lBytesPerFrame = outputChannelCount * Pa_GetSampleSize(outputSampleFormat);
+
+            /* Allocate the blocking i/o output ring buffer memory. */
+            stream->blockingState->writeRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
+            if( !stream->blockingState->writeRingBufferData )
+            {
+                result = paInsufficientMemory;
+                PA_DEBUG(("ERROR! Blocking i/o output ring buffer allocation failed in OpenStream()\n"));
+                goto error;
+            }
+
+            /* Initialize the output ring buffer struct. */
+            PaUtil_InitializeRingBuffer( &stream->blockingState->writeRingBuffer    ,
+                                          lBytesPerFrame                            ,
+                                          lBlockingBufferSize                       ,
+                                          stream->blockingState->writeRingBufferData );
+        }
+
+        stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+
+    }
+    else /* Using callback interface... */
+    {
+        result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                        inputChannelCount, inputSampleFormat, (hostInputSampleFormat | paNonInterleaved),
+                        outputChannelCount, outputSampleFormat, (hostOutputSampleFormat | paNonInterleaved),
+                        sampleRate, streamFlags, framesPerBuffer,
+                        framesPerHostBuffer, paUtilFixedHostBufferSize,
+                        streamCallback, userData );
+        if( result != paNoError ){
+            PA_DEBUG(("OpenStream ERROR13\n"));
+            goto error;
+        }
+        callbackBufferProcessorInited = TRUE;
+
+        stream->streamRepresentation.streamInfo.inputLatency =
+                (double)( PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
+                    + stream->asioInputLatencyFrames) / sampleRate;   // seconds
+        stream->streamRepresentation.streamInfo.outputLatency =
+                (double)( PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
+                    + stream->asioOutputLatencyFrames) / sampleRate; // seconds
+        stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+        // the code below prints the ASIO latency which doesn't include the
+        // buffer processor latency. it reports the added latency separately
+        PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+                stream->asioInputLatencyFrames,
+                (long)((stream->asioInputLatencyFrames*1000)/ sampleRate),  
+                PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor),
+                (long)((PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)*1000)/ sampleRate)
+                ));
+
+        PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+                stream->asioOutputLatencyFrames,
+                (long)((stream->asioOutputLatencyFrames*1000)/ sampleRate), 
+                PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor),
+                (long)((PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)*1000)/ sampleRate)
+                ));
+    }
+
+    stream->asioHostApi = asioHostApi;
+    stream->framesPerHostCallback = framesPerHostBuffer;
+
+    stream->inputChannelCount = inputChannelCount;
+    stream->outputChannelCount = outputChannelCount;
+    stream->postOutput = driverInfo->postOutput;
+    stream->isStopped = 1;
+    stream->isActive = 0;
+    
+    asioHostApi->openAsioDeviceIndex = asioDeviceIndex;
+
+    theAsioStream = stream;
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    PA_DEBUG(("goto errored\n"));
+    if( stream )
+    {
+        if( stream->blockingState )
+        {
+            if( blockingBufferProcessorInited )
+                PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
+
+            if( stream->blockingState->writeRingBufferData )
+                PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
+            if( stream->blockingState->writeStreamBuffer )
+                PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
+            if( blockingWriteBuffersReadyEventInitialized )
+                CloseHandle( stream->blockingState->writeBuffersReadyEvent );
+
+            if( stream->blockingState->readRingBufferData )
+                PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
+            if( stream->blockingState->readStreamBuffer )
+                PaUtil_FreeMemory( stream->blockingState->readStreamBuffer );
+            if( blockingReadFramesReadyEventInitialized )
+                CloseHandle( stream->blockingState->readFramesReadyEvent );
+
+            PaUtil_FreeMemory( stream->blockingState );
+        }
+
+        if( callbackBufferProcessorInited )
+            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+        if( completedBuffersPlayedEventInited )
+            CloseHandle( stream->completedBuffersPlayedEvent );
+
+        if( stream->asioBufferInfos )
+            PaUtil_FreeMemory( stream->asioBufferInfos );
+
+        if( stream->asioChannelInfos )
+            PaUtil_FreeMemory( stream->asioChannelInfos );
+
+        if( stream->bufferPtrs )
+            PaUtil_FreeMemory( stream->bufferPtrs );
+
+        PaUtil_FreeMemory( stream );
+    }
+
+    if( asioBuffersCreated )
+        ASIODisposeBuffers();
+
+    if( asioIsInitialized )
+       {
+               UnloadAsioDriver();
+       }
+    return result;
+}
+
+
+/*
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAsioStream *stream = (PaAsioStream*)s;
+
+    /*
+        IMPLEMENT ME:
+            - additional stream closing + cleanup
+    */
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+    stream->asioHostApi->openAsioDeviceIndex = paNoDevice;
+
+    CloseHandle( stream->completedBuffersPlayedEvent );
+
+    /* Using blocking i/o interface... */
+    if( stream->blockingState )
+    {
+        PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
+
+        if( stream->inputChannelCount ) {
+            PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
+            PaUtil_FreeMemory( stream->blockingState->readStreamBuffer  );
+            CloseHandle( stream->blockingState->readFramesReadyEvent );
+        }
+        if( stream->outputChannelCount ) {
+            PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
+            PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
+            CloseHandle( stream->blockingState->writeBuffersReadyEvent );
+        }
+
+        PaUtil_FreeMemory( stream->blockingState );
+    }
+
+    PaUtil_FreeMemory( stream->asioBufferInfos );
+    PaUtil_FreeMemory( stream->asioChannelInfos );
+    PaUtil_FreeMemory( stream->bufferPtrs );
+    PaUtil_FreeMemory( stream );
+
+    ASIODisposeBuffers();
+    UnloadAsioDriver();
+
+    theAsioStream = 0;
+
+    return result;
+}
+
+
+static void bufferSwitch(long index, ASIOBool directProcess)
+{
+//TAKEN FROM THE ASIO SDK
+
+    // the actual processing callback.
+    // Beware that this is normally in a seperate thread, hence be sure that
+    // you take care about thread synchronization. This is omitted here for
+    // simplicity.
+
+    // as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs
+    // to be created though it will only set the timeInfo.samplePosition and
+    // timeInfo.systemTime fields and the according flags
+
+    ASIOTime  timeInfo;
+    memset( &timeInfo, 0, sizeof (timeInfo) );
+
+    // get the time stamp of the buffer, not necessary if no
+    // synchronization to other media is required
+    if( ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK)
+            timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid;
+
+    // Call the real callback
+    bufferSwitchTimeInfo( &timeInfo, index, directProcess );
+}
+
+
+// conversion from 64 bit ASIOSample/ASIOTimeStamp to double float
+#if NATIVE_INT64
+    #define ASIO64toDouble(a)  (a)
+#else
+    const double twoRaisedTo32 = 4294967296.;
+    #define ASIO64toDouble(a)  ((a).lo + (a).hi * twoRaisedTo32)
+#endif
+
+static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool directProcess )
+{
+    // the actual processing callback.
+    // Beware that this is normally in a seperate thread, hence be sure that
+    // you take care about thread synchronization.
+
+
+    /* The SDK says the following about the directProcess flag:
+        suggests to the host whether it should immediately start processing
+        (directProcess == ASIOTrue), or whether its process should be deferred
+        because the call comes from a very low level (for instance, a high level
+        priority interrupt), and direct processing would cause timing instabilities for
+        the rest of the system. If in doubt, directProcess should be set to ASIOFalse.
+
+        We just ignore directProcess. This could cause incompatibilities with
+        drivers which really don't want the audio processing to occur in this
+        callback, but none have been identified yet.
+    */
+
+    (void) directProcess; /* suppress unused parameter warning */
+
+#if 0
+    // store the timeInfo for later use
+    asioDriverInfo.tInfo = *timeInfo;
+
+    // get the time stamp of the buffer, not necessary if no
+    // synchronization to other media is required
+
+    if (timeInfo->timeInfo.flags & kSystemTimeValid)
+            asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime);
+    else
+            asioDriverInfo.nanoSeconds = 0;
+
+    if (timeInfo->timeInfo.flags & kSamplePositionValid)
+            asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
+    else
+            asioDriverInfo.samples = 0;
+
+    if (timeInfo->timeCode.flags & kTcValid)
+            asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
+    else
+            asioDriverInfo.tcSamples = 0;
+
+    // get the system reference time
+    asioDriverInfo.sysRefTime = get_sys_reference_time();
+#endif
+
+#if 0
+    // a few debug messages for the Windows device driver developer
+    // tells you the time when driver got its interrupt and the delay until the app receives
+    // the event notification.
+    static double last_samples = 0;
+    char tmp[128];
+    sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples                 \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples));
+    OutputDebugString (tmp);
+    last_samples = asioDriverInfo.samples;
+#endif
+
+
+    if( !theAsioStream )
+        return 0L;
+
+    // protect against reentrancy
+    if( PaAsio_AtomicIncrement(&theAsioStream->reenterCount) )
+    {
+        theAsioStream->reenterError++;
+        //DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError));
+        return 0L;
+    }
+
+    int buffersDone = 0;
+    
+    do
+    {
+        if( buffersDone > 0 )
+        {
+            // this is a reentered buffer, we missed processing it on time
+            // set the input overflow and output underflow flags as appropriate
+            
+            if( theAsioStream->inputChannelCount > 0 )
+                theAsioStream->callbackFlags |= paInputOverflow;
+                
+            if( theAsioStream->outputChannelCount > 0 )
+                theAsioStream->callbackFlags |= paOutputUnderflow;
+        }
+        else
+        {
+            if( theAsioStream->zeroOutput )
+            {
+                ZeroOutputBuffers( theAsioStream, index );
+
+                // Finally if the driver supports the ASIOOutputReady() optimization,
+                // do it here, all data are in place
+                if( theAsioStream->postOutput )
+                    ASIOOutputReady();
+
+                if( theAsioStream->stopProcessing )
+                {
+                    if( theAsioStream->stopPlayoutCount < 2 )
+                    {
+                        ++theAsioStream->stopPlayoutCount;
+                        if( theAsioStream->stopPlayoutCount == 2 )
+                        {
+                            theAsioStream->isActive = 0;
+                            if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
+                                theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
+                            theAsioStream->streamFinishedCallbackCalled = true;
+                            SetEvent( theAsioStream->completedBuffersPlayedEvent );
+                        }
+                    }
+                }
+            }
+            else
+            {
+
+#if 0
+/*
+    see: "ASIO callback underflow/overflow buffer slip detection doesn't work"
+    http://www.portaudio.com/trac/ticket/110
+*/
+
+// test code to try to detect slip conditions... these may work on some systems
+// but neither of them work on the RME Digi96
+
+// check that sample delta matches buffer size (otherwise we must have skipped
+// a buffer.
+static double last_samples = -512;
+double samples;
+//if( timeInfo->timeCode.flags & kTcValid )
+//    samples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
+//else
+    samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
+int delta = samples - last_samples;
+//printf( "%d\n", delta);
+last_samples = samples;
+
+if( delta > theAsioStream->framesPerHostCallback )
+{
+    if( theAsioStream->inputChannelCount > 0 )
+        theAsioStream->callbackFlags |= paInputOverflow;
+
+    if( theAsioStream->outputChannelCount > 0 )
+        theAsioStream->callbackFlags |= paOutputUnderflow;
+}
+
+// check that the buffer index is not the previous index (which would indicate
+// that a buffer was skipped.
+static int previousIndex = 1;
+if( index == previousIndex )
+{
+    if( theAsioStream->inputChannelCount > 0 )
+        theAsioStream->callbackFlags |= paInputOverflow;
+
+    if( theAsioStream->outputChannelCount > 0 )
+        theAsioStream->callbackFlags |= paOutputUnderflow;
+}
+previousIndex = index;
+#endif
+
+                int i;
+
+                PaUtil_BeginCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer );
+
+                PaStreamCallbackTimeInfo paTimeInfo;
+
+                // asio systemTime is supposed to be measured according to the same
+                // clock as timeGetTime
+                paTimeInfo.currentTime = (ASIO64toDouble( timeInfo->timeInfo.systemTime ) * .000000001);
+
+                /* patch from Paul Boege */
+                paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime -
+                    ((double)theAsioStream->asioInputLatencyFrames/theAsioStream->streamRepresentation.streamInfo.sampleRate);
+
+                paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime +
+                    ((double)theAsioStream->asioOutputLatencyFrames/theAsioStream->streamRepresentation.streamInfo.sampleRate);
+
+                /* old version is buggy because the buffer processor also adds in its latency to the time parameters
+                paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency;
+                paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency;
+                */
+
+/* Disabled! Stopping and re-starting the stream causes an input overflow / output underflow. S.Fischer */
+#if 0
+// detect underflows by checking inter-callback time > 2 buffer period
+static double previousTime = -1;
+if( previousTime > 0 ){
+
+    double delta = paTimeInfo.currentTime - previousTime;
+
+    if( delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate) ){
+        if( theAsioStream->inputChannelCount > 0 )
+            theAsioStream->callbackFlags |= paInputOverflow;
+
+        if( theAsioStream->outputChannelCount > 0 )
+            theAsioStream->callbackFlags |= paOutputUnderflow;
+    }
+}
+previousTime = paTimeInfo.currentTime;
+#endif
+
+                // note that the above input and output times do not need to be
+                // adjusted for the latency of the buffer processor -- the buffer
+                // processor handles that.
+
+                if( theAsioStream->inputBufferConverter )
+                {
+                    for( i=0; i<theAsioStream->inputChannelCount; i++ )
+                    {
+                        theAsioStream->inputBufferConverter( theAsioStream->inputBufferPtrs[index][i],
+                                theAsioStream->inputShift, theAsioStream->framesPerHostCallback );
+                    }
+                }
+
+                PaUtil_BeginBufferProcessing( &theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags );
+
+                /* reset status flags once they've been passed to the callback */
+                theAsioStream->callbackFlags = 0;
+
+                PaUtil_SetInputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
+                for( i=0; i<theAsioStream->inputChannelCount; ++i )
+                    PaUtil_SetNonInterleavedInputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i] );
+
+                PaUtil_SetOutputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
+                for( i=0; i<theAsioStream->outputChannelCount; ++i )
+                    PaUtil_SetNonInterleavedOutputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i] );
+
+                int callbackResult;
+                if( theAsioStream->stopProcessing )
+                    callbackResult = paComplete;
+                else
+                    callbackResult = paContinue;
+                unsigned long framesProcessed = PaUtil_EndBufferProcessing( &theAsioStream->bufferProcessor, &callbackResult );
+
+                if( theAsioStream->outputBufferConverter )
+                {
+                    for( i=0; i<theAsioStream->outputChannelCount; i++ )
+                    {
+                        theAsioStream->outputBufferConverter( theAsioStream->outputBufferPtrs[index][i],
+                                theAsioStream->outputShift, theAsioStream->framesPerHostCallback );
+                    }
+                }
+
+                PaUtil_EndCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer, framesProcessed );
+
+                // Finally if the driver supports the ASIOOutputReady() optimization,
+                // do it here, all data are in place
+                if( theAsioStream->postOutput )
+                    ASIOOutputReady();
+
+                if( callbackResult == paContinue )
+                {
+                    /* nothing special to do */
+                }
+                else if( callbackResult == paAbort )
+                {
+                    /* finish playback immediately  */
+                    theAsioStream->isActive = 0;
+                    if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
+                        theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
+                    theAsioStream->streamFinishedCallbackCalled = true;
+                    SetEvent( theAsioStream->completedBuffersPlayedEvent );
+                    theAsioStream->zeroOutput = true;
+                }
+                else /* paComplete or other non-zero value indicating complete */
+                {
+                    /* Finish playback once currently queued audio has completed. */
+                    theAsioStream->stopProcessing = true;
+
+                    if( PaUtil_IsBufferProcessorOutputEmpty( &theAsioStream->bufferProcessor ) )
+                    {
+                        theAsioStream->zeroOutput = true;
+                        theAsioStream->stopPlayoutCount = 0;
+                    }
+                }
+            }
+        }
+        
+        ++buffersDone;
+    }while( PaAsio_AtomicDecrement(&theAsioStream->reenterCount) >= 0 );
+
+    return 0L;
+}
+
+
+static void sampleRateChanged(ASIOSampleRate sRate)
+{
+    // TAKEN FROM THE ASIO SDK
+    // do whatever you need to do if the sample rate changed
+    // usually this only happens during external sync.
+    // Audio processing is not stopped by the driver, actual sample rate
+    // might not have even changed, maybe only the sample rate status of an
+    // AES/EBU or S/PDIF digital input at the audio device.
+    // You might have to update time/sample related conversion routines, etc.
+
+    (void) sRate; /* unused parameter */
+    PA_DEBUG( ("sampleRateChanged : %d \n", sRate));
+}
+
+static long asioMessages(long selector, long value, void* message, double* opt)
+{
+// TAKEN FROM THE ASIO SDK
+    // currently the parameters "value", "message" and "opt" are not used.
+    long ret = 0;
+
+    (void) message; /* unused parameters */
+    (void) opt;
+
+    PA_DEBUG( ("asioMessages : %d , %d \n", selector, value));
+
+    switch(selector)
+    {
+        case kAsioSelectorSupported:
+            if(value == kAsioResetRequest
+            || value == kAsioEngineVersion
+            || value == kAsioResyncRequest
+            || value == kAsioLatenciesChanged
+            // the following three were added for ASIO 2.0, you don't necessarily have to support them
+            || value == kAsioSupportsTimeInfo
+            || value == kAsioSupportsTimeCode
+            || value == kAsioSupportsInputMonitor)
+                    ret = 1L;
+            break;
+
+        case kAsioBufferSizeChange:
+            //printf("kAsioBufferSizeChange \n");
+            break;
+
+        case kAsioResetRequest:
+            // defer the task and perform the reset of the driver during the next "safe" situation
+            // You cannot reset the driver right now, as this code is called from the driver.
+            // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction
+            // Afterwards you initialize the driver again.
+
+            /*FIXME: commented the next line out
+
+                see: "PA/ASIO ignores some driver notifications it probably shouldn't"
+                http://www.portaudio.com/trac/ticket/108
+            */
+            //asioDriverInfo.stopped;  // In this sample the processing will just stop
+            ret = 1L;
+            break;
+
+        case kAsioResyncRequest:
+            // This informs the application, that the driver encountered some non fatal data loss.
+            // It is used for synchronization purposes of different media.
+            // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the
+            // Windows Multimedia system, which could loose data because the Mutex was hold too long
+            // by another thread.
+            // However a driver can issue it in other situations, too.
+            ret = 1L;
+            break;
+
+        case kAsioLatenciesChanged:
+            // This will inform the host application that the drivers were latencies changed.
+            // Beware, it this does not mean that the buffer sizes have changed!
+            // You might need to update internal delay data.
+            ret = 1L;
+            //printf("kAsioLatenciesChanged \n");
+            break;
+
+        case kAsioEngineVersion:
+            // return the supported ASIO version of the host application
+            // If a host applications does not implement this selector, ASIO 1.0 is assumed
+            // by the driver
+            ret = 2L;
+            break;
+
+        case kAsioSupportsTimeInfo:
+            // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback
+            // is supported.
+            // For compatibility with ASIO 1.0 drivers the host application should always support
+            // the "old" bufferSwitch method, too.
+            ret = 1;
+            break;
+
+        case kAsioSupportsTimeCode:
+            // informs the driver wether application is interested in time code info.
+            // If an application does not need to know about time code, the driver has less work
+            // to do.
+            ret = 0;
+            break;
+    }
+    return ret;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsioStream *stream = (PaAsioStream*)s;
+    PaAsioStreamBlockingState *blockingState = stream->blockingState;
+    ASIOError asioError;
+
+    if( stream->outputChannelCount > 0 )
+    {
+        ZeroOutputBuffers( stream, 0 );
+        ZeroOutputBuffers( stream, 1 );
+    }
+
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+    stream->stopProcessing = false;
+    stream->zeroOutput = false;
+
+    /* Reentrancy counter initialisation */
+    stream->reenterCount = -1;
+    stream->reenterError = 0;
+
+    stream->callbackFlags = 0;
+
+    if( ResetEvent( stream->completedBuffersPlayedEvent ) == 0 )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+    }
+
+
+    /* Using blocking i/o interface... */
+    if( blockingState )
+    {
+        /* Reset blocking i/o buffer processor. */
+        PaUtil_ResetBufferProcessor( &blockingState->bufferProcessor );
+
+        /* If we're about to process some input data. */
+        if( stream->inputChannelCount )
+        {
+            /* Reset callback-ReadStream sync event. */
+            if( ResetEvent( blockingState->readFramesReadyEvent ) == 0 )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+            }
+
+            /* Flush blocking i/o ring buffer. */
+            PaUtil_FlushRingBuffer( &blockingState->readRingBuffer );
+            (*blockingState->bufferProcessor.inputZeroer)( blockingState->readRingBuffer.buffer, 1, blockingState->bufferProcessor.inputChannelCount * blockingState->readRingBuffer.bufferSize );
+        }
+
+        /* If we're about to process some output data. */
+        if( stream->outputChannelCount )
+        {
+            /* Reset callback-WriteStream sync event. */
+            if( ResetEvent( blockingState->writeBuffersReadyEvent ) == 0 )
+            {
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+            }
+
+            /* Flush blocking i/o ring buffer. */
+            PaUtil_FlushRingBuffer( &blockingState->writeRingBuffer );
+            (*blockingState->bufferProcessor.outputZeroer)( blockingState->writeRingBuffer.buffer, 1, blockingState->bufferProcessor.outputChannelCount * blockingState->writeRingBuffer.bufferSize );
+
+            /* Initialize the output ring buffer to "silence". */
+            PaUtil_AdvanceRingBufferWriteIndex( &blockingState->writeRingBuffer, blockingState->writeRingBufferInitialFrames );
+        }
+
+        /* Clear requested frames / buffers count. */
+        blockingState->writeBuffersRequested     = 0;
+        blockingState->readFramesRequested       = 0;
+        blockingState->writeBuffersRequestedFlag = FALSE;
+        blockingState->readFramesRequestedFlag   = FALSE;
+        blockingState->outputUnderflowFlag       = FALSE;
+        blockingState->inputOverflowFlag         = FALSE;
+        blockingState->stopFlag                  = FALSE;
+    }
+
+
+    if( result == paNoError )
+    {
+        assert( theAsioStream == stream ); /* theAsioStream should be set correctly in OpenStream */
+
+        /* initialize these variables before the callback has a chance to be invoked */
+        stream->isStopped = 0;
+        stream->isActive = 1;
+        stream->streamFinishedCallbackCalled = false;
+
+        asioError = ASIOStart();
+        if( asioError != ASE_OK )
+        {
+            stream->isStopped = 1;
+            stream->isActive = 0;
+
+            result = paUnanticipatedHostError;
+            PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        }
+    }
+
+    return result;
+}
+
+static void EnsureCallbackHasCompleted( PaAsioStream *stream )
+{
+    // make sure that the callback is not still in-flight after ASIOStop()
+    // returns. This has been observed to happen on the Hoontech DSP24 for
+    // example.
+    int count = 2000;  // only wait for 2 seconds, rather than hanging.
+    while( stream->reenterCount != -1 && count > 0 )
+    {
+        Sleep(1);
+        --count;
+    }
+}
+
+static PaError StopStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsioStream *stream = (PaAsioStream*)s;
+    PaAsioStreamBlockingState *blockingState = stream->blockingState;
+    ASIOError asioError;
+
+    if( stream->isActive )
+    {
+        /* If blocking i/o output is in use */
+        if( blockingState && stream->outputChannelCount )
+        {
+            /* Request the whole output buffer to be available. */
+            blockingState->writeBuffersRequested = blockingState->writeRingBuffer.bufferSize;
+            /* Signalize that additional buffers are need. */
+            blockingState->writeBuffersRequestedFlag = TRUE;
+            /* Set flag to indicate the playback is to be stopped. */
+            blockingState->stopFlag = TRUE;
+
+            /* Wait until requested number of buffers has been freed. Time
+               out after twice the blocking i/o ouput buffer could have
+               been consumed. */
+            DWORD timeout = (DWORD)( 2 * blockingState->writeRingBuffer.bufferSize * 1000
+                                       / stream->streamRepresentation.streamInfo.sampleRate );
+            DWORD waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
+
+            /* If something seriously went wrong... */
+            if( waitResult == WAIT_FAILED )
+            {
+                PA_DEBUG(("WaitForSingleObject() failed in StopStream()\n"));
+                result = paUnanticipatedHostError;
+                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+            }
+            else if( waitResult == WAIT_TIMEOUT )
+            {
+                PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n"));
+                result = paTimedOut;
+            }
+        }
+
+        stream->stopProcessing = true;
+
+        /* wait for the stream to finish playing out enqueued buffers.
+            timeout after four times the stream latency.
+
+            @todo should use a better time out value - if the user buffer
+            length is longer than the asio buffer size then that should
+            be taken into account.
+        */
+        if( WaitForSingleObject( stream->completedBuffersPlayedEvent,
+                (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) )
+                    == WAIT_TIMEOUT )
+        {
+            PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" ));
+        }
+    }
+
+    asioError = ASIOStop();
+    if( asioError == ASE_OK )
+    {
+        EnsureCallbackHasCompleted( stream );
+    }
+    else
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+    }
+
+    stream->isStopped = 1;
+    stream->isActive = 0;
+
+    if( !stream->streamFinishedCallbackCalled )
+    {
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+
+    return result;
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAsioStream *stream = (PaAsioStream*)s;
+    ASIOError asioError;
+
+    stream->zeroOutput = true;
+
+    asioError = ASIOStop();
+    if( asioError == ASE_OK )
+    {
+        EnsureCallbackHasCompleted( stream );
+    }
+    else
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+    }
+
+    stream->isStopped = 1;
+    stream->isActive = 0;
+
+    if( !stream->streamFinishedCallbackCalled )
+    {
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+
+    return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
+    
+    return stream->isStopped;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
+
+    return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    (void) s; /* unused parameter */
+
+    return (double)timeGetTime() * .001;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+    As separate stream interfaces are used for blocking and callback
+    streams, the following functions can be guaranteed to only be called
+    for blocking streams.
+*/
+
+static PaError ReadStream( PaStream      *s     ,
+                           void          *buffer,
+                           unsigned long  frames )
+{
+    PaError result = paNoError; /* Initial return value. */
+    PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
+
+    /* Pointer to the blocking i/o data struct. */
+    PaAsioStreamBlockingState *blockingState = stream->blockingState;
+
+    /* Get blocking i/o buffer processor and ring buffer pointers. */
+    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
+    PaUtilRingBuffer      *pRb = &blockingState->readRingBuffer;
+
+    /* Ring buffer segment(s) used for writing. */
+    void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
+    void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
+
+    /* Number of frames per ring buffer segment. */
+    long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
+    long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
+
+    /* Get number of frames to be processed per data block. */
+    unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
+    /* Actual number of frames that has been copied into the ring buffer. */
+    unsigned long lFramesCopied = 0;
+    /* The number of remaining unprocessed dtat frames. */
+    unsigned long lFramesRemaining = frames;
+
+    /* Copy the input argument to avoid pointer increment! */
+    const void *userBuffer;
+    unsigned int i; /* Just a counter. */
+
+    /* About the time, needed to process 8 data blocks. */
+    DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
+    DWORD waitResult = 0;
+
+
+    /* Check if the stream is still available ready to gather new data. */
+    if( blockingState->stopFlag || !stream->isActive )
+    {
+        PA_DEBUG(("Warning! Stream no longer available for reading in ReadStream()\n"));
+        result = paStreamIsStopped;
+        return result;
+    }
+
+    /* If the stream is a input stream. */
+    if( stream->inputChannelCount )
+    {
+        /* Prepare buffer access. */
+        if( !pBp->userOutputIsInterleaved )
+        {
+            userBuffer = blockingState->readStreamBuffer;
+            for( i = 0; i<pBp->inputChannelCount; ++i )
+            {
+                ((void**)userBuffer)[i] = ((void**)buffer)[i];
+            }
+        } /* Use the unchanged buffer. */
+        else { userBuffer = buffer; }
+
+        do /* Internal block processing for too large user data buffers. */
+        {
+            /* Get the size of the current data block to be processed. */
+            lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
+                            ? lFramesPerBlock : lFramesRemaining;
+            /* Use predefined block size for as long there are enough
+               buffers available, thereafter reduce the processing block
+               size to match the number of remaining buffers. So the final
+               data block is processed although it may be incomplete. */
+
+            /* If the available amount of data frames is insufficient. */
+            if( PaUtil_GetRingBufferReadAvailable(pRb) < (long) lFramesPerBlock )
+            {
+                /* Make sure, the event isn't already set! */
+                /* ResetEvent( blockingState->readFramesReadyEvent ); */
+
+                /* Set the number of requested buffers. */
+                blockingState->readFramesRequested = lFramesPerBlock;
+
+                /* Signalize that additional buffers are need. */
+                blockingState->readFramesRequestedFlag = TRUE;
+
+                /* Wait until requested number of buffers has been freed. */
+                waitResult = WaitForSingleObject( blockingState->readFramesReadyEvent, timeout );
+
+                /* If something seriously went wrong... */
+                if( waitResult == WAIT_FAILED )
+                {
+                    PA_DEBUG(("WaitForSingleObject() failed in ReadStream()\n"));
+                    result = paUnanticipatedHostError;
+                    PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+                    return result;
+                }
+                else if( waitResult == WAIT_TIMEOUT )
+                {
+                    PA_DEBUG(("WaitForSingleObject() timed out in ReadStream()\n"));
+
+                    /* If block processing has stopped, abort! */
+                    if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
+
+                    /* If a timeout is encountered, give up eventually. */
+                    return result = paTimedOut;
+                }
+            }
+            /* Now, the ring buffer contains the required amount of data
+               frames.
+               (Therefor we don't need to check the return argument of
+               PaUtil_GetRingBufferReadRegions(). ;-) )
+            */
+
+            /* Retrieve pointer(s) to the ring buffer's current write
+               position(s). If the first buffer segment is too small to
+               store the requested number of bytes, an additional second
+               segment is returned. Otherwise, i.e. if the first segment
+               is large enough, the second segment's pointer will be NULL.
+            */
+            PaUtil_GetRingBufferReadRegions(pRb                ,
+                                            lFramesPerBlock    ,
+                                            &pRingBufferData1st,
+                                            &lRingBufferSize1st,
+                                            &pRingBufferData2nd,
+                                            &lRingBufferSize2nd);
+
+            /* Set number of frames to be copied from the ring buffer. */
+            PaUtil_SetInputFrameCount( pBp, lRingBufferSize1st ); 
+            /* Setup ring buffer access. */
+            PaUtil_SetInterleavedInputChannels(pBp               ,  /* Buffer processor. */
+                                               0                 ,  /* The first channel's index. */
+                                               pRingBufferData1st,  /* First ring buffer segment. */
+                                               0                 ); /* Use all available channels. */
+
+            /* If a second ring buffer segment is required. */
+            if( lRingBufferSize2nd ) {
+                /* Set number of frames to be copied from the ring buffer. */
+                PaUtil_Set2ndInputFrameCount( pBp, lRingBufferSize2nd );
+                /* Setup ring buffer access. */
+                PaUtil_Set2ndInterleavedInputChannels(pBp               ,  /* Buffer processor. */
+                                                      0                 ,  /* The first channel's index. */
+                                                      pRingBufferData2nd,  /* Second ring buffer segment. */
+                                                      0                 ); /* Use all available channels. */
+            }
+
+            /* Let the buffer processor handle "copy and conversion" and
+               update the ring buffer indices manually. */
+            lFramesCopied = PaUtil_CopyInput( pBp, &buffer, lFramesPerBlock );
+            PaUtil_AdvanceRingBufferReadIndex( pRb, lFramesCopied );
+
+            /* Decrease number of unprocessed frames. */
+            lFramesRemaining -= lFramesCopied;
+
+        } /* Continue with the next data chunk. */
+        while( lFramesRemaining );
+
+
+        /* If there has been an input overflow within the callback */
+        if( blockingState->inputOverflowFlag )
+        {
+            blockingState->inputOverflowFlag = FALSE;
+
+            /* Return the corresponding error code. */
+            result = paInputOverflowed;
+        }
+
+    } /* If this is not an input stream. */
+    else {
+        result = paCanNotReadFromAnOutputOnlyStream;
+    }
+
+    return result;
+}
+
+static PaError WriteStream( PaStream      *s     ,
+                            const void    *buffer,
+                            unsigned long  frames )
+{
+    PaError result = paNoError; /* Initial return value. */
+    PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
+
+    /* Pointer to the blocking i/o data struct. */
+    PaAsioStreamBlockingState *blockingState = stream->blockingState;
+
+    /* Get blocking i/o buffer processor and ring buffer pointers. */
+    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
+    PaUtilRingBuffer      *pRb = &blockingState->writeRingBuffer;
+
+    /* Ring buffer segment(s) used for writing. */
+    void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
+    void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
+
+    /* Number of frames per ring buffer segment. */
+    long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
+    long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
+
+    /* Get number of frames to be processed per data block. */
+    unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
+    /* Actual number of frames that has been copied into the ring buffer. */
+    unsigned long lFramesCopied = 0;
+    /* The number of remaining unprocessed dtat frames. */
+    unsigned long lFramesRemaining = frames;
+
+    /* About the time, needed to process 8 data blocks. */
+    DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
+    DWORD waitResult = 0;
+
+    /* Copy the input argument to avoid pointer increment! */
+    const void *userBuffer;
+    unsigned int i; /* Just a counter. */
+
+
+    /* Check if the stream ist still available ready to recieve new data. */
+    if( blockingState->stopFlag || !stream->isActive )
+    {
+        PA_DEBUG(("Warning! Stream no longer available for writing in WriteStream()\n"));
+        result = paStreamIsStopped;
+        return result;
+    }
+
+    /* If the stream is a output stream. */
+    if( stream->outputChannelCount )
+    {
+        /* Prepare buffer access. */
+        if( !pBp->userOutputIsInterleaved )
+        {
+            userBuffer = blockingState->writeStreamBuffer;
+            for( i = 0; i<pBp->outputChannelCount; ++i )
+            {
+                ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
+            }
+        } /* Use the unchanged buffer. */
+        else { userBuffer = buffer; }
+
+
+        do /* Internal block processing for too large user data buffers. */
+        {
+            /* Get the size of the current data block to be processed. */
+            lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
+                            ? lFramesPerBlock : lFramesRemaining;
+            /* Use predefined block size for as long there are enough
+               frames available, thereafter reduce the processing block
+               size to match the number of remaining frames. So the final
+               data block is processed although it may be incomplete. */
+
+            /* If the available amount of buffers is insufficient. */
+            if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) lFramesPerBlock )
+            {
+                /* Make sure, the event isn't already set! */
+                /* ResetEvent( blockingState->writeBuffersReadyEvent ); */
+
+                /* Set the number of requested buffers. */
+                blockingState->writeBuffersRequested = lFramesPerBlock;
+
+                /* Signalize that additional buffers are need. */
+                blockingState->writeBuffersRequestedFlag = TRUE;
+
+                /* Wait until requested number of buffers has been freed. */
+                waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
+
+                /* If something seriously went wrong... */
+                if( waitResult == WAIT_FAILED )
+                {
+                    PA_DEBUG(("WaitForSingleObject() failed in WriteStream()\n"));
+                    result = paUnanticipatedHostError;
+                    PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+                    return result;
+                }
+                else if( waitResult == WAIT_TIMEOUT )
+                {
+                    PA_DEBUG(("WaitForSingleObject() timed out in WriteStream()\n"));
+
+                    /* If block processing has stopped, abort! */
+                    if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
+                    
+                    /* If a timeout is encountered, give up eventually. */
+                    return result = paTimedOut;
+                }
+            }
+            /* Now, the ring buffer contains the required amount of free
+               space to store the provided number of data frames.
+               (Therefor we don't need to check the return argument of
+               PaUtil_GetRingBufferWriteRegions(). ;-) )
+            */
+
+            /* Retrieve pointer(s) to the ring buffer's current write
+               position(s). If the first buffer segment is too small to
+               store the requested number of bytes, an additional second
+               segment is returned. Otherwise, i.e. if the first segment
+               is large enough, the second segment's pointer will be NULL.
+            */
+            PaUtil_GetRingBufferWriteRegions(pRb                ,
+                                             lFramesPerBlock    ,
+                                             &pRingBufferData1st,
+                                             &lRingBufferSize1st,
+                                             &pRingBufferData2nd,
+                                             &lRingBufferSize2nd);
+
+            /* Set number of frames to be copied to the ring buffer. */
+            PaUtil_SetOutputFrameCount( pBp, lRingBufferSize1st ); 
+            /* Setup ring buffer access. */
+            PaUtil_SetInterleavedOutputChannels(pBp               ,  /* Buffer processor. */
+                                                0                 ,  /* The first channel's index. */
+                                                pRingBufferData1st,  /* First ring buffer segment. */
+                                                0                 ); /* Use all available channels. */
+
+            /* If a second ring buffer segment is required. */
+            if( lRingBufferSize2nd ) {
+                /* Set number of frames to be copied to the ring buffer. */
+                PaUtil_Set2ndOutputFrameCount( pBp, lRingBufferSize2nd );
+                /* Setup ring buffer access. */
+                PaUtil_Set2ndInterleavedOutputChannels(pBp               ,  /* Buffer processor. */
+                                                       0                 ,  /* The first channel's index. */
+                                                       pRingBufferData2nd,  /* Second ring buffer segment. */
+                                                       0                 ); /* Use all available channels. */
+            }
+
+            /* Let the buffer processor handle "copy and conversion" and
+               update the ring buffer indices manually. */
+            lFramesCopied = PaUtil_CopyOutput( pBp, &userBuffer, lFramesPerBlock );
+            PaUtil_AdvanceRingBufferWriteIndex( pRb, lFramesCopied );
+
+            /* Decrease number of unprocessed frames. */
+            lFramesRemaining -= lFramesCopied;
+
+        } /* Continue with the next data chunk. */
+        while( lFramesRemaining );
+
+
+        /* If there has been an output underflow within the callback */
+        if( blockingState->outputUnderflowFlag )
+        {
+            blockingState->outputUnderflowFlag = FALSE;
+
+            /* Return the corresponding error code. */
+            result = paOutputUnderflowed;
+        }
+
+    } /* If this is not an output stream. */
+    else
+    {
+        result = paCanNotWriteToAnInputOnlyStream;
+    }
+
+    return result;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
+
+    /* Call buffer utility routine to get the number of available frames. */
+    return PaUtil_GetRingBufferReadAvailable( &stream->blockingState->readRingBuffer );
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
+
+    /* Call buffer utility routine to get the number of empty buffers. */
+    return PaUtil_GetRingBufferWriteAvailable( &stream->blockingState->writeRingBuffer );
+}
+
+
+/* This routine will be called by the PortAudio engine when audio is needed.
+** It may called at interrupt level on some machines so don't do anything
+** that could mess up the system like calling malloc() or free().
+*/
+static int BlockingIoPaCallback(const void                     *inputBuffer    ,
+                                      void                     *outputBuffer   ,
+                                      unsigned long             framesPerBuffer,
+                                const PaStreamCallbackTimeInfo *timeInfo       ,
+                                      PaStreamCallbackFlags     statusFlags    ,
+                                      void                     *userData       )
+{
+    PaError result = paNoError; /* Initial return value. */
+    PaAsioStream *stream = *(PaAsioStream**)userData; /* The PA ASIO stream. */
+    PaAsioStreamBlockingState *blockingState = stream->blockingState; /* Persume blockingState is valid, otherwise the callback wouldn't be running. */
+
+    /* Get a pointer to the stream's blocking i/o buffer processor. */
+    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
+    PaUtilRingBuffer      *pRb = NULL;
+
+    /* If output data has been requested. */
+    if( stream->outputChannelCount )
+    {
+        /* If the callback input argument signalizes a output underflow,
+           make sure the WriteStream() function knows about it, too! */
+        if( statusFlags & paOutputUnderflowed ) {
+            blockingState->outputUnderflowFlag = TRUE;
+        }
+
+        /* Access the corresponding ring buffer. */
+        pRb = &blockingState->writeRingBuffer;
+
+        /* If the blocking i/o buffer contains enough output data, */
+        if( PaUtil_GetRingBufferReadAvailable(pRb) >= (long) framesPerBuffer )
+        {
+            /* Extract the requested data from the ring buffer. */
+            PaUtil_ReadRingBuffer( pRb, outputBuffer, framesPerBuffer );
+        }
+        else /* If no output data is available :-( */
+        {
+            /* Signalize a write-buffer underflow. */
+            blockingState->outputUnderflowFlag = TRUE;
+
+            /* Fill the output buffer with silence. */
+            (*pBp->outputZeroer)( outputBuffer, 1, pBp->outputChannelCount * framesPerBuffer );
+
+            /* If playback is to be stopped */
+            if( blockingState->stopFlag && PaUtil_GetRingBufferReadAvailable(pRb) < (long) framesPerBuffer )
+            {
+                /* Extract all the remaining data from the ring buffer,
+                   whether it is a complete data block or not. */
+                PaUtil_ReadRingBuffer( pRb, outputBuffer, PaUtil_GetRingBufferReadAvailable(pRb) );
+            }
+        }
+
+        /* Set blocking i/o event? */
+        if( blockingState->writeBuffersRequestedFlag && PaUtil_GetRingBufferWriteAvailable(pRb) >= (long) blockingState->writeBuffersRequested )
+        {
+            /* Reset buffer request. */
+            blockingState->writeBuffersRequestedFlag = FALSE;
+            blockingState->writeBuffersRequested     = 0;
+            /* Signalize that requested buffers are ready. */
+            SetEvent( blockingState->writeBuffersReadyEvent );
+            /* What do we do if SetEvent() returns zero, i.e. the event
+               could not be set? How to return errors from within the
+               callback? - S.Fischer */
+        }
+    }
+
+    /* If input data has been supplied. */
+    if( stream->inputChannelCount )
+    {
+        /* If the callback input argument signalizes a input overflow,
+           make sure the ReadStream() function knows about it, too! */
+        if( statusFlags & paInputOverflowed ) {
+            blockingState->inputOverflowFlag = TRUE;
+        }
+
+        /* Access the corresponding ring buffer. */
+        pRb = &blockingState->readRingBuffer;
+
+        /* If the blocking i/o buffer contains not enough input buffers */
+        if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) framesPerBuffer )
+        {
+            /* Signalize a read-buffer overflow. */
+            blockingState->inputOverflowFlag = TRUE;
+
+            /* Remove some old data frames from the buffer. */
+            PaUtil_AdvanceRingBufferReadIndex( pRb, framesPerBuffer );
+        }
+
+        /* Insert the current input data into the ring buffer. */
+        PaUtil_WriteRingBuffer( pRb, inputBuffer, framesPerBuffer );
+
+        /* Set blocking i/o event? */
+        if( blockingState->readFramesRequestedFlag && PaUtil_GetRingBufferReadAvailable(pRb) >= (long) blockingState->readFramesRequested )
+        {
+            /* Reset buffer request. */
+            blockingState->readFramesRequestedFlag = FALSE;
+            blockingState->readFramesRequested     = 0;
+            /* Signalize that requested buffers are ready. */
+            SetEvent( blockingState->readFramesReadyEvent );
+            /* What do we do if SetEvent() returns zero, i.e. the event
+               could not be set? How to return errors from within the
+               callback? - S.Fischer */
+            /** @todo report an error with PA_DEBUG */
+        }
+    }
+
+    return paContinue;
+}
+
+
+PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *hostApi;
+    PaDeviceIndex hostApiDevice;
+    ASIODriverInfo asioDriverInfo;
+    ASIOError asioError;
+    int asioIsInitialized = 0;
+    PaAsioHostApiRepresentation *asioHostApi;
+    PaAsioDeviceInfo *asioDeviceInfo;
+    PaWinUtilComInitializationResult comInitializationResult;
+
+    /* initialize COM again here, we might be in another thread */
+    result = PaWinUtil_CoInitialize( paASIO, &comInitializationResult );
+    if( result != paNoError )
+        return result;
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+    if( result != paNoError )
+        goto error;
+
+    result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+    if( result != paNoError )
+        goto error;
+
+    /*
+        In theory we could proceed if the currently open device was the same
+        one for which the control panel was requested, however  because the
+        window pointer is not available until this function is called we
+        currently need to call ASIOInit() again here, which of course can't be
+        done safely while a stream is open.
+    */
+
+    asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+    if( asioHostApi->openAsioDeviceIndex != paNoDevice )
+    {
+        result = paDeviceUnavailable;
+        goto error;
+    }
+
+    asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+    if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) )
+    {
+        result = paUnanticipatedHostError;
+        goto error;
+    }
+
+    /* CRUCIAL!!! */
+    memset( &asioDriverInfo, 0, sizeof(ASIODriverInfo) );
+    asioDriverInfo.asioVersion = 2;
+    asioDriverInfo.sysRef = systemSpecific;
+    asioError = ASIOInit( &asioDriverInfo );
+    if( asioError != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        goto error;
+    }
+    else
+    {
+        asioIsInitialized = 1;
+    }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+PA_DEBUG(("asioVersion: ASIOInit(): %ld\n",   asioDriverInfo.asioVersion )); 
+PA_DEBUG(("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion )); 
+PA_DEBUG(("Name: ASIOInit(): %s\n",           asioDriverInfo.name )); 
+PA_DEBUG(("ErrorMessage: ASIOInit(): %s\n",   asioDriverInfo.errorMessage )); 
+
+    asioError = ASIOControlPanel();
+    if( asioError != ASE_OK )
+    {
+        PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        goto error;
+    }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+
+    asioError = ASIOExit();
+    if( asioError != ASE_OK )
+    {
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        asioIsInitialized = 0;
+        goto error;
+    }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+
+    return result;
+
+error:
+    if( asioIsInitialized )
+       {
+               ASIOExit();
+       }
+
+    PaWinUtil_CoUninitialize( paASIO, &comInitializationResult );
+
+    return result;
+}
+
+
+PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex,
+        const char** channelName )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *hostApi;
+    PaDeviceIndex hostApiDevice;
+    PaAsioDeviceInfo *asioDeviceInfo;
+
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+    if( result != paNoError )
+        goto error;
+
+    result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+    if( result != paNoError )
+        goto error;
+
+    asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+    if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels ){
+        result = paInvalidChannelCount;
+        goto error;
+    }
+
+    *channelName = asioDeviceInfo->asioChannelInfos[channelIndex].name;
+
+    return paNoError;
+    
+error:
+    return result;
+}
+
+
+PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
+        const char** channelName )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *hostApi;
+    PaDeviceIndex hostApiDevice;
+    PaAsioDeviceInfo *asioDeviceInfo;
+
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+    if( result != paNoError )
+        goto error;
+
+    result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+    if( result != paNoError )
+        goto error;
+
+    asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+    if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels ){
+        result = paInvalidChannelCount;
+        goto error;
+    }
+
+    *channelName = asioDeviceInfo->asioChannelInfos[
+            asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name;
+
+    return paNoError;
+    
+error:
+    return result;
+}
+
+
+/* NOTE: the following functions are ASIO-stream specific, and are called directly
+    by client code. We need to check for many more error conditions here because
+    we don't have the benefit of pa_front.c's parameter checking.
+*/
+
+static PaError GetAsioStreamPointer( PaAsioStream **stream, PaStream *s )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi;
+    PaAsioHostApiRepresentation *asioHostApi;
+    
+    result = PaUtil_ValidateStreamPointer( s );
+    if( result != paNoError )
+        return result;
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+    if( result != paNoError )
+        return result;
+
+    asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+    
+    if( PA_STREAM_REP( s )->streamInterface == &asioHostApi->callbackStreamInterface
+            || PA_STREAM_REP( s )->streamInterface == &asioHostApi->blockingStreamInterface )
+    {
+        /* s is an ASIO  stream */
+        *stream = (PaAsioStream *)s;
+        return paNoError;
+    }
+    else
+    {
+        return paIncompatibleStreamHostApi;
+    }
+}
+
+
+PaError PaAsio_SetStreamSampleRate( PaStream* s, double sampleRate )
+{
+    PaAsioStream *stream;
+    PaError result = GetAsioStreamPointer( &stream, s );
+    if( result != paNoError )
+        return result;
+
+    if( stream != theAsioStream )
+        return paBadStreamPtr;
+
+    return ValidateAndSetSampleRate( sampleRate );
+}
+
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core.c b/portaudio/src/hostapi/coreaudio/pa_mac_core.c
new file mode 100644 (file)
index 0000000..257e9de
--- /dev/null
@@ -0,0 +1,2836 @@
+/*
+ * Implementation of the PortAudio API for Apple AUHAL
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file pa_mac_core
+ @ingroup hostapi_src
+ @author Bjorn Roche
+ @brief AUHAL implementation of PortAudio
+*/
+
+/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo()
+ * PaMacCore_SetError() will do this.
+ */
+
+#include "pa_mac_core_internal.h"
+
+#include <string.h> /* strlen(), memcmp() etc. */
+#include <libkern/OSAtomic.h>
+
+#include "pa_mac_core.h"
+#include "pa_mac_core_utilities.h"
+#include "pa_mac_core_blocking.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+       
+/* This is a reasonable size for a small buffer based on experience. */
+#define PA_MAC_SMALL_BUFFER_SIZE    (64)
+       
+/* prototypes for functions declared in this file */
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+/*
+ * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct
+ * with the requested flags and initializes channel map.
+ */
+void PaMacCore_SetupStreamInfo(  PaMacCoreStreamInfo *data, const unsigned long flags )
+{
+   bzero( data, sizeof( PaMacCoreStreamInfo ) );
+   data->size = sizeof( PaMacCoreStreamInfo );
+   data->hostApiType = paCoreAudio;
+   data->version = 0x01;
+   data->flags = flags;
+   data->channelMap = NULL;
+   data->channelMapSize = 0;
+}
+
+/*
+ * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct
+ */
+void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize )
+{
+   data->channelMap = channelMap;
+   data->channelMapSize = channelMapSize;
+}
+static char *channelName = NULL;
+static int channelNameSize = 0;
+static bool ensureChannelNameSize( int size )
+{
+   if( size >= channelNameSize ) {
+      free( channelName );
+      channelName = (char *) malloc( ( channelNameSize = size ) + 1 );
+      if( !channelName ) {
+         channelNameSize = 0;
+         return false;
+      }
+   }
+   return true;
+}
+/*
+ * Function declared in pa_mac_core.h. retrives channel names.
+ */
+const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )
+{
+       struct PaUtilHostApiRepresentation *hostApi;
+       PaError err;
+       OSStatus error;
+       err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
+       assert(err == paNoError);
+       if( err != paNoError )
+               return NULL;
+       PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
+       AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];
+       CFStringRef nameRef;
+       
+       /* First try with CFString */
+       UInt32 size = sizeof(nameRef);
+       error = AudioDeviceGetProperty( hostApiDevice,
+                                                                  channelIndex + 1,
+                                                                  input,
+                                                                  kAudioDevicePropertyChannelNameCFString,
+                                                                  &size,
+                                                                  &nameRef );
+       if( error )
+       {
+               /* try the C String */
+               size = 0;
+               error = AudioDeviceGetPropertyInfo( hostApiDevice,
+                                                                                  channelIndex + 1,
+                                                                                  input,
+                                                                                  kAudioDevicePropertyChannelName,
+                                                                                  &size,
+                                                                                  NULL);
+               if( !error )
+               {
+                       if( !ensureChannelNameSize( size ) )
+                               return NULL;
+                       
+                       error = AudioDeviceGetProperty( hostApiDevice,
+                                                                                  channelIndex + 1,
+                                                                                  input,
+                                                                                  kAudioDevicePropertyChannelName,
+                                                                                  &size,
+                                                                                  channelName );
+                       
+                       
+                       if( !error )
+                               return channelName;
+               }
+               
+               /* as a last-ditch effort, we use the device name and append the channel number. */
+               nameRef = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%s: %d"), hostApi->deviceInfos[device]->name, channelIndex + 1 );
+               
+               
+               size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);;
+               if( !ensureChannelNameSize( size ) )
+               {
+                       CFRelease( nameRef );
+                       return NULL;
+               }
+               CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 );
+               CFRelease( nameRef );
+       }
+       else
+       {
+               size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);;
+               if( !ensureChannelNameSize( size ) )
+               {
+                       CFRelease( nameRef );
+                       return NULL;
+               }
+               CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 );
+               CFRelease( nameRef );
+       }
+       
+       return channelName;
+}
+
+    
+PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device,
+                                      long *minBufferSizeFrames, long *maxBufferSizeFrames )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi;
+    
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
+    
+    if( result == paNoError )
+    {
+        PaDeviceIndex hostApiDeviceIndex;
+        result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDeviceIndex, device, hostApi );
+        if( result == paNoError )
+        {
+            PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
+            AudioDeviceID macCoreDeviceId = macCoreHostApi->devIds[hostApiDeviceIndex];
+            AudioValueRange audioRange;
+            UInt32 propSize = sizeof( audioRange );
+            
+            // return the size range for the output scope unless we only have inputs
+            Boolean isInput = 0;
+            if( macCoreHostApi->inheritedHostApiRep.deviceInfos[hostApiDeviceIndex]->maxOutputChannels == 0 )
+                isInput = 1;
+           
+            result = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
+
+            *minBufferSizeFrames = audioRange.mMinimum;
+            *maxBufferSizeFrames = audioRange.mMaximum;
+        }
+    }
+    
+    return result;
+}
+
+
+AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("PaMacCore_GetStreamInputHandle()\n"));
+
+    return ( stream->inputDevice );
+}
+
+AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("PaMacCore_GetStreamOutputHandle()\n"));
+
+    return ( stream->outputDevice );
+}
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static OSStatus AudioIOProc( void *inRefCon,
+                               AudioUnitRenderActionFlags *ioActionFlags,
+                               const AudioTimeStamp *inTimeStamp,
+                               UInt32 inBusNumber,
+                               UInt32 inNumberFrames,
+                               AudioBufferList *ioData );
+static double GetStreamCpuLoad( PaStream* stream );
+
+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
+                               PaDeviceInfo *deviceInfo,
+                               AudioDeviceID macCoreDeviceId,
+                               int isInput);
+
+static PaError OpenAndSetupOneAudioUnit(
+                                   const PaMacCoreStream *stream,
+                                   const PaStreamParameters *inStreamParams,
+                                   const PaStreamParameters *outStreamParams,
+                                   const UInt32 requestedFramesPerBuffer,
+                                   UInt32 *actualInputFramesPerBuffer,
+                                   UInt32 *actualOutputFramesPerBuffer,
+                                   const PaMacAUHAL *auhalHostApi,
+                                   AudioUnit *audioUnit,
+                                   AudioConverterRef *srConverter,
+                                   AudioDeviceID *audioDevice,
+                                   const double sampleRate,
+                                   void *refCon );
+
+/* for setting errors. */
+#define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+    PaUtil_SetLastHostErrorInfo( paCoreAudio, errorCode, errorText )
+
+/*
+ * Callback called when starting or stopping a stream.
+ */
+static void startStopCallback(
+   void *               inRefCon,
+   AudioUnit            ci,
+   AudioUnitPropertyID  inID,
+   AudioUnitScope       inScope,
+   AudioUnitElement     inElement )
+{
+   PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon;
+   UInt32 isRunning;
+   UInt32 size = sizeof( isRunning );
+   OSStatus err;
+   err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size );
+   assert( !err );
+   if( err )
+      isRunning = false; //it's very unclear what to do in case of error here. There's no real way to notify the user, and crashing seems unreasonable.
+   if( isRunning )
+      return; //We are only interested in when we are stopping
+   // -- if we are using 2 I/O units, we only need one notification!
+   if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit )
+      return;
+   PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback;
+   if( stream->state == STOPPING )
+      stream->state = STOPPED ;
+   if( sfc )
+      sfc( stream->streamRepresentation.userData );
+}
+
+
+/*currently, this is only used in initialization, but it might be modified
+  to be used when the list of devices changes.*/
+static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)
+{
+    UInt32 size;
+    UInt32 propsize;
+    VVDBUG(("gatherDeviceInfo()\n"));
+    /* -- free any previous allocations -- */
+    if( auhalHostApi->devIds )
+        PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds);
+    auhalHostApi->devIds = NULL;
+
+    /* -- figure out how many devices there are -- */
+    AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
+                                  &propsize,
+                                  NULL );
+    auhalHostApi->devCount = propsize / sizeof( AudioDeviceID );
+
+    VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) );
+
+    /* -- copy the device IDs -- */
+    auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory(
+                             auhalHostApi->allocations,
+                             propsize );
+    if( !auhalHostApi->devIds )
+        return paInsufficientMemory;
+    AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
+                                  &propsize,
+                                  auhalHostApi->devIds );
+#ifdef MAC_CORE_VERBOSE_DEBUG
+    {
+       int i;
+       for( i=0; i<auhalHostApi->devCount; ++i )
+          printf( "Device %d\t: %ld\n", i, auhalHostApi->devIds[i] );
+    }
+#endif
+
+    size = sizeof(AudioDeviceID);
+    auhalHostApi->defaultIn  = kAudioDeviceUnknown;
+    auhalHostApi->defaultOut = kAudioDeviceUnknown;
+
+    /* determine the default device. */
+    /* I am not sure how these calls to AudioHardwareGetProperty()
+       could fail, but in case they do, we use the first available
+       device as the default. */
+    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
+                     &size,
+                     &auhalHostApi->defaultIn) ) {
+       int i;
+       auhalHostApi->defaultIn  = kAudioDeviceUnknown;
+       VDBUG(("Failed to get default input device from OS."));
+       VDBUG((" I will substitute the first available input Device."));
+       for( i=0; i<auhalHostApi->devCount; ++i ) {
+          PaDeviceInfo devInfo;
+          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
+                                   auhalHostApi->devIds[i], TRUE ) )
+             if( devInfo.maxInputChannels ) {
+                auhalHostApi->defaultIn = auhalHostApi->devIds[i];
+                break;
+             }
+       }
+    }   
+    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
+                     &size,
+                     &auhalHostApi->defaultOut) ) {
+       int i;
+       auhalHostApi->defaultIn  = kAudioDeviceUnknown;
+       VDBUG(("Failed to get default output device from OS."));
+       VDBUG((" I will substitute the first available output Device."));
+       for( i=0; i<auhalHostApi->devCount; ++i ) {
+          PaDeviceInfo devInfo;
+          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
+                                   auhalHostApi->devIds[i], FALSE ) )
+             if( devInfo.maxOutputChannels ) {
+                auhalHostApi->defaultOut = auhalHostApi->devIds[i];
+                break;
+             }
+       }
+    }   
+
+    VDBUG( ( "Default in : %ld\n", auhalHostApi->defaultIn  ) );
+    VDBUG( ( "Default out: %ld\n", auhalHostApi->defaultOut ) );
+
+    return paNoError;
+}
+
+/* =================================================================================================== */
+/**
+ * @internal
+ * @brief Clip the desired size against the allowed IO buffer size range for the device.
+ */
+static PaError ClipToDeviceBufferSize( AudioDeviceID macCoreDeviceId,
+                                                                       int isInput, UInt32 desiredSize, UInt32 *allowedSize )
+{
+       UInt32 resultSize = desiredSize;
+       AudioValueRange audioRange;
+       UInt32 propSize = sizeof( audioRange );
+       PaError err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
+       resultSize = MAX( resultSize, audioRange.mMinimum );
+       resultSize = MIN( resultSize, audioRange.mMaximum );
+       *allowedSize = resultSize;
+       return err;
+}
+
+/* =================================================================================================== */
+#if 0
+static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId,
+                          int isInput )
+{
+    PaError err;
+    int i;
+    UInt32 propSize;
+    UInt32 deviceLatency;
+    UInt32 streamLatency;
+    UInt32 bufferFrames;
+    UInt32 safetyOffset;
+    AudioStreamID streamIDs[128];
+    
+    printf("\n======= latency query : macCoreDeviceId = %d, isInput %d =======\n", (int)macCoreDeviceId, isInput );    
+    
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
+    printf("kAudioDevicePropertyBufferFrameSize: err = %d, propSize = %d, value = %d\n", err, propSize, bufferFrames );
+    
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
+    printf("kAudioDevicePropertySafetyOffset: err = %d, propSize = %d, value = %d\n", err, propSize, safetyOffset );
+    
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
+    printf("kAudioDevicePropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, deviceLatency );
+    
+    AudioValueRange audioRange;
+    propSize = sizeof( audioRange );
+    err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
+    printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, minimum = %g\n", err, propSize, audioRange.mMinimum);
+    printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, maximum = %g\n", err, propSize, audioRange.mMaximum );
+    
+    /* Get the streams from the device and query their latency. */
+    propSize = sizeof(streamIDs);
+    err  = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
+    int numStreams = propSize / sizeof(AudioStreamID);
+    for( i=0; i<numStreams; i++ )
+    {
+        printf("Stream #%d = %d---------------------- \n", i, streamIDs[i] );
+        
+        propSize = sizeof(UInt32);
+        err  = WARNING(AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
+        printf("  kAudioStreamPropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, streamLatency );
+    }
+}
+#endif
+
+/* =================================================================================================== */
+/**
+ * @internal
+ * Calculate the fixed latency from the system and the device.
+ * Sum of kAudioStreamPropertyLatency +
+ *        kAudioDevicePropertySafetyOffset +
+ *        kAudioDevicePropertyLatency
+ *
+ * Some useful info from Jeff Moore on latency.
+ * http://osdir.com/ml/coreaudio-api/2010-01/msg00046.html
+ * http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html
+ */
+static PaError CalculateFixedDeviceLatency( AudioDeviceID macCoreDeviceId, int isInput, UInt32 *fixedLatencyPtr )
+{
+    PaError err;
+    UInt32 propSize;
+    UInt32 deviceLatency;
+    UInt32 streamLatency;
+    UInt32 safetyOffset;
+    AudioStreamID streamIDs[1];
+    
+    // To get stream latency we have to get a streamID from the device.
+    // We are only going to look at the first stream so only fetch one stream.
+    propSize = sizeof(streamIDs);
+    err  = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
+    if( err != paNoError ) goto error;
+    if( propSize == sizeof(AudioStreamID) )
+    {        
+        propSize = sizeof(UInt32);
+        err  = WARNING(AudioStreamGetProperty(streamIDs[0], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
+    }
+    
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
+    if( err != paNoError ) goto error;
+    
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
+    if( err != paNoError ) goto error;
+
+    *fixedLatencyPtr = deviceLatency + streamLatency + safetyOffset;
+    return err;
+error:
+    return err;
+}
+
+/* =================================================================================================== */
+static PaError CalculateDefaultDeviceLatencies( AudioDeviceID macCoreDeviceId,
+                                               int isInput, UInt32 *lowLatencyFramesPtr,
+                                               UInt32 *highLatencyFramesPtr )
+{
+    UInt32 propSize;
+    UInt32 bufferFrames = 0;
+    UInt32 fixedLatency = 0;
+    UInt32 clippedMinBufferSize = 0;
+    
+    //DumpDeviceProperties( macCoreDeviceId, isInput );
+    
+    PaError err = CalculateFixedDeviceLatency( macCoreDeviceId, isInput, &fixedLatency );
+    if( err != paNoError ) goto error;
+    
+    // For low latency use a small fixed size buffer clipped to the device range.
+    err = ClipToDeviceBufferSize( macCoreDeviceId, isInput, PA_MAC_SMALL_BUFFER_SIZE, &clippedMinBufferSize );
+    if( err != paNoError ) goto error;
+    
+    // For high latency use the default device buffer size.
+    propSize = sizeof(UInt32);
+    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
+    if( err != paNoError ) goto error;
+    
+    *lowLatencyFramesPtr = fixedLatency + clippedMinBufferSize;
+    *highLatencyFramesPtr = fixedLatency + bufferFrames;
+    
+    return err;
+error:
+    return err;
+}
+
+/* =================================================================================================== */
+
+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
+                               PaDeviceInfo *deviceInfo,
+                               AudioDeviceID macCoreDeviceId,
+                               int isInput)
+{
+    UInt32 propSize;
+    PaError err = paNoError;
+    UInt32 i;
+    int numChannels = 0;
+    AudioBufferList *buflist = NULL;
+    
+    VVDBUG(("GetChannelInfo()\n"));
+
+    /* Get the number of channels from the stream configuration.
+       Fail if we can't get this. */
+
+    err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));
+    if (err)
+        return err;
+
+    buflist = PaUtil_AllocateMemory(propSize);
+    if( !buflist )
+       return paInsufficientMemory;
+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
+    if (err)
+        goto error;
+
+    for (i = 0; i < buflist->mNumberBuffers; ++i)
+        numChannels += buflist->mBuffers[i].mNumberChannels;
+
+    if (isInput)
+        deviceInfo->maxInputChannels = numChannels;
+    else
+        deviceInfo->maxOutputChannels = numChannels;
+      
+    if (numChannels > 0) /* do not try to retrieve the latency if there are no channels. */
+    {
+        /* Get the latency.  Don't fail if we can't get this. */
+        /* default to something reasonable */
+        deviceInfo->defaultLowInputLatency = .01;
+        deviceInfo->defaultHighInputLatency = .10;
+        deviceInfo->defaultLowOutputLatency = .01;
+        deviceInfo->defaultHighOutputLatency = .10;        
+        UInt32 lowLatencyFrames = 0;
+        UInt32 highLatencyFrames = 0;
+        err = CalculateDefaultDeviceLatencies( macCoreDeviceId, isInput, &lowLatencyFrames, &highLatencyFrames );
+        if( err == 0 )
+        {
+            
+            double lowLatencySeconds = lowLatencyFrames / deviceInfo->defaultSampleRate;
+            double highLatencySeconds = highLatencyFrames / deviceInfo->defaultSampleRate;
+            if (isInput)
+            {
+                deviceInfo->defaultLowInputLatency = lowLatencySeconds;
+                deviceInfo->defaultHighInputLatency = highLatencySeconds;
+            }
+            else
+            {
+                deviceInfo->defaultLowOutputLatency = lowLatencySeconds;
+                deviceInfo->defaultHighOutputLatency = highLatencySeconds;
+            }
+        }
+    }
+    PaUtil_FreeMemory( buflist );
+    return paNoError;
+ error:
+    PaUtil_FreeMemory( buflist );
+    return err;
+}
+
+/* =================================================================================================== */
+static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi,
+                                     PaDeviceInfo *deviceInfo,
+                                     AudioDeviceID macCoreDeviceId,
+                                     PaHostApiIndex hostApiIndex )
+{
+    Float64 sampleRate;
+    char *name;
+    PaError err = paNoError;
+       CFStringRef nameRef;
+    UInt32 propSize;
+
+    VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId));
+
+    memset(deviceInfo, 0, sizeof(PaDeviceInfo));
+
+    deviceInfo->structVersion = 2;
+    deviceInfo->hostApi = hostApiIndex;
+  
+    /* Get the device name using CFString */
+       propSize = sizeof(nameRef);
+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceNameCFString, &propSize, &nameRef));
+    if (err)
+    {
+               /* Get the device name using c string.  Fail if we can't get it. */
+               err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));
+               if (err)
+                       return err;
+
+               name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize+1);
+               if ( !name )
+                       return paInsufficientMemory;
+               err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
+               if (err)
+                       return err;
+       }
+       else
+       {
+               /* valid CFString so we just allocate a c string big enough to contain the data */
+               propSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);
+               name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations, propSize+1);
+               if ( !name )
+               {
+                       CFRelease(nameRef);
+                       return paInsufficientMemory;
+               }
+               CFStringGetCString(nameRef, name, propSize+1, kCFStringEncodingUTF8);
+               CFRelease(nameRef);
+       }
+    deviceInfo->name = name;
+
+    /* Try to get the default sample rate.  Don't fail if we can't get this. */
+    propSize = sizeof(Float64);
+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
+    if (err)
+        deviceInfo->defaultSampleRate = 0.0;
+    else
+        deviceInfo->defaultSampleRate = sampleRate;
+
+    /* Get the maximum number of input and output channels.  Fail if we can't get this. */
+
+    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1);
+    if (err)
+        return err;
+
+    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0);
+    if (err)
+        return err;
+
+    return paNoError;
+}
+
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int i;
+    PaMacAUHAL *auhalHostApi = NULL;
+    PaDeviceInfo *deviceInfoArray;
+    int unixErr;
+
+    VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));
+       
+       SInt32 major;
+       SInt32 minor;
+       Gestalt(gestaltSystemVersionMajor, &major);
+       Gestalt(gestaltSystemVersionMinor, &minor);
+       
+       // Starting with 10.6 systems, the HAL notification thread is created internally
+       if (major == 10 && minor >= 6) {
+               CFRunLoopRef theRunLoop = NULL;
+               AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
+               OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
+               if (osErr != noErr) {
+                       goto error;
+               }
+       }
+       
+    unixErr = initializeXRunListenerList();
+    if( 0 != unixErr ) {
+       return UNIX_ERR(unixErr);
+    }
+
+    auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );
+    if( !auhalHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    auhalHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !auhalHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    auhalHostApi->devIds = NULL;
+    auhalHostApi->devCount = 0;
+
+    /* get the info we need about the devices */
+    result = gatherDeviceInfo( auhalHostApi );
+    if( result != paNoError )
+       goto error;
+
+    *hostApi = &auhalHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paCoreAudio;
+    (*hostApi)->info.name = "Core Audio";
+
+    (*hostApi)->info.defaultInputDevice = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+
+    (*hostApi)->info.deviceCount = 0;  
+
+    if( auhalHostApi->devCount > 0 )
+    {
+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount);
+        if( !(*hostApi)->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
+                auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for( i=0; i < auhalHostApi->devCount; ++i )
+        {
+            int err;
+            err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i],
+                                      auhalHostApi->devIds[i],
+                                      hostApiIndex );
+            if (err == paNoError)
+            { /* copy some info and set the defaults */
+                (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i];
+                if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn)
+                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+                if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut)
+                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+                (*hostApi)->info.deviceCount++;
+            }
+            else
+            { /* there was an error. we need to shift the devices down, so we ignore this one */
+                int j;
+                auhalHostApi->devCount--;
+                for( j=i; j<auhalHostApi->devCount; ++j )
+                   auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1];
+                i--;
+            }
+        }
+    }
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped,
+                                      IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable,
+                                      PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped,
+                                      IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream,
+                                      GetStreamReadAvailable,
+                                      GetStreamWriteAvailable );
+
+    return result;
+
+error:
+    if( auhalHostApi )
+    {
+        if( auhalHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( auhalHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
+        }
+                
+        PaUtil_FreeMemory( auhalHostApi );
+    }
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    int unixErr;
+
+    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
+
+    VVDBUG(("Terminate()\n"));
+
+    unixErr = destroyXRunListenerList();
+    if( 0 != unixErr )
+       UNIX_ERR(unixErr);
+
+    /*
+        IMPLEMENT ME:
+            - clean up any resources not handled by the allocation group
+        TODO: Double check that everything is handled by alloc group
+    */
+
+    if( auhalHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( auhalHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( auhalHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+    VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n",
+                inputParameters  ? inputParameters->channelCount  : -1,
+                inputParameters  ? inputParameters->sampleFormat  : -1,
+                outputParameters ? outputParameters->channelCount : -1,
+                outputParameters ? outputParameters->sampleFormat : -1,
+                (float) sampleRate ));
+    /** These first checks are standard PA checks. We do some fancier checks
+        later. */
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( inputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( outputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support outputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+    /* FEEDBACK */
+    /*        I think the only way to check a given format SR combo is     */
+    /*        to try opening it. This could be disruptive, is that Okay?   */
+    /*        The alternative is to just read off available sample rates,  */
+    /*        but this will not work %100 of the time (eg, a device that   */
+    /*        supports N output at one rate but only N/2 at a higher rate.)*/
+
+    /* The following code opens the device with the requested parameters to
+       see if it works. */
+    {
+       PaError err;
+       PaStream *s;
+       err = OpenStream( hostApi, &s, inputParameters, outputParameters,
+                           sampleRate, 1024, 0, (PaStreamCallback *)1, NULL );
+       if( err != paNoError && err != paInvalidSampleRate )
+          DBUG( ( "OpenStream @ %g returned: %d: %s\n",
+                  (float) sampleRate, err, Pa_GetErrorText( err ) ) );
+       if( err ) 
+          return err;
+       err = CloseStream( s );
+       if( err ) {
+          /* FEEDBACK: is this more serious? should we assert? */
+          DBUG( ( "WARNING: could not close Stream. %d: %s\n",
+                  err, Pa_GetErrorText( err ) ) );
+       }
+    }
+
+    return paFormatIsSupported;
+}
+
+/* ================================================================================= */
+static void InitializeDeviceProperties( PaMacCoreDeviceProperties *deviceProperties )
+{
+    memset( deviceProperties, 0, sizeof(PaMacCoreDeviceProperties) );
+    deviceProperties->sampleRate = 1.0; // Better than random. Overwritten by actual values later on.
+    deviceProperties->samplePeriod = 1.0 / deviceProperties->sampleRate;
+}
+
+static Float64 CalculateSoftwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
+{
+    UInt32 latencyFrames = deviceProperties->bufferFrameSize + deviceProperties->deviceLatency + deviceProperties->safetyOffset;
+    return latencyFrames * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
+}
+
+static Float64 CalculateHardwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
+{
+    return deviceProperties->deviceLatency * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
+}
+
+/* Calculate values used to convert Apple timestamps into PA timestamps
+ * from the device properties. The final results of this calculation
+ * will be used in the audio callback function.
+ */
+static void UpdateTimeStampOffsets( PaMacCoreStream *stream )
+{
+    Float64 inputSoftwareLatency = 0.0;
+    Float64 inputHardwareLatency = 0.0;
+    Float64 outputSoftwareLatency = 0.0;
+    Float64 outputHardwareLatency = 0.0;
+    
+    if( stream->inputUnit != NULL )
+    {
+        inputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->inputProperties );
+        inputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->inputProperties );
+    }    
+    if( stream->outputUnit != NULL )
+    {
+        outputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->outputProperties );
+        outputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->outputProperties );
+    }    
+    
+    /* We only need a mutex around setting these variables as a group. */
+       pthread_mutex_lock( &stream->timingInformationMutex );
+    stream->timestampOffsetCombined = inputSoftwareLatency + outputSoftwareLatency;
+    stream->timestampOffsetInputDevice = inputHardwareLatency;
+    stream->timestampOffsetOutputDevice = outputHardwareLatency;
+       pthread_mutex_unlock( &stream->timingInformationMutex );
+}
+
+/* ================================================================================= */
+
+/* can be used to update from nominal or actual sample rate */
+static OSStatus UpdateSampleRateFromDeviceProperty( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID sampleRatePropertyID )
+{
+    PaMacCoreDeviceProperties * deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
+       
+       Float64 sampleRate = 0.0;
+       UInt32 propSize = sizeof(Float64);
+    OSStatus osErr = AudioDeviceGetProperty( deviceID, 0, isInput, sampleRatePropertyID, &propSize, &sampleRate);
+       if( (osErr == noErr) && (sampleRate > 1000.0) ) /* avoid divide by zero if there's an error */
+       {
+        deviceProperties->sampleRate = sampleRate;
+        deviceProperties->samplePeriod = 1.0 / sampleRate;
+    }
+    return osErr;
+}
+
+static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
+{
+       PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
+    
+    // Make sure the callback is operating on a stream that is still valid!
+    assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );
+
+       OSStatus osErr = UpdateSampleRateFromDeviceProperty( stream, inDevice, isInput, kAudioDevicePropertyActualSampleRate );
+    if( osErr == noErr )
+    {
+        UpdateTimeStampOffsets( stream );
+    }
+    return osErr;
+}
+
+/* ================================================================================= */
+static OSStatus QueryUInt32DeviceProperty( AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID propertyID, UInt32 *outValue )
+{
+       UInt32 propertyValue = 0;
+       UInt32 propertySize = sizeof(UInt32);
+       OSStatus osErr = AudioDeviceGetProperty( deviceID, 0, isInput, propertyID, &propertySize, &propertyValue);
+       if( osErr == noErr )
+       {
+        *outValue = propertyValue;
+       }
+    return osErr;
+}
+
+static OSStatus AudioDevicePropertyGenericListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
+{
+    OSStatus osErr = noErr;
+       PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
+    
+    // Make sure the callback is operating on a stream that is still valid!
+    assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );
+    
+    PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
+    UInt32 *valuePtr = NULL;
+    switch( inPropertyID )
+    {
+        case kAudioDevicePropertySafetyOffset:
+            valuePtr = &deviceProperties->safetyOffset;
+            break;
+                        
+        case kAudioDevicePropertyLatency:
+            valuePtr = &deviceProperties->deviceLatency;
+            break;
+            
+        case kAudioDevicePropertyBufferFrameSize:
+            valuePtr = &deviceProperties->bufferFrameSize;
+            break;            
+    }
+    if( valuePtr != NULL )
+    {
+        osErr = QueryUInt32DeviceProperty( inDevice, isInput, inPropertyID, valuePtr );
+        if( osErr == noErr )
+        {
+            UpdateTimeStampOffsets( stream );
+        }
+    }
+    return osErr;
+}
+
+/* ================================================================================= */
+/*
+ * Setup listeners in case device properties change during the run. */
+static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
+{
+    OSStatus osErr = noErr;
+    PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
+    
+    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
+                                           kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr;
+    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
+                                           kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr;
+    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
+                                           kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr;
+    
+    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, 
+                                   AudioDevicePropertyActualSampleRateListenerProc, stream );
+    
+    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioStreamPropertyLatency, 
+                                   AudioDevicePropertyGenericListenerProc, stream );
+    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, 
+                                   AudioDevicePropertyGenericListenerProc, stream );
+    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, 
+                                   AudioDevicePropertyGenericListenerProc, stream );
+    
+    return osErr;
+}
+
+static void CleanupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
+{    
+    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, 
+                                   AudioDevicePropertyActualSampleRateListenerProc );
+    
+    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyLatency, 
+                                   AudioDevicePropertyGenericListenerProc );   
+    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, 
+                                   AudioDevicePropertyGenericListenerProc );
+    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, 
+                                   AudioDevicePropertyGenericListenerProc );
+}
+
+/* ================================================================================= */
+static PaError OpenAndSetupOneAudioUnit(
+                                   const PaMacCoreStream *stream,
+                                   const PaStreamParameters *inStreamParams,
+                                   const PaStreamParameters *outStreamParams,
+                                   const UInt32 requestedFramesPerBuffer,
+                                   UInt32 *actualInputFramesPerBuffer,
+                                   UInt32 *actualOutputFramesPerBuffer,
+                                   const PaMacAUHAL *auhalHostApi,
+                                   AudioUnit *audioUnit,
+                                   AudioConverterRef *srConverter,
+                                   AudioDeviceID *audioDevice,
+                                   const double sampleRate,
+                                   void *refCon )
+{
+    ComponentDescription desc;
+    Component comp;
+    /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/
+    AudioStreamBasicDescription desiredFormat;
+    OSStatus result = noErr;
+    PaError paResult = paNoError;
+    int line = 0;
+    UInt32 callbackKey;
+    AURenderCallbackStruct rcbs;
+    unsigned long macInputStreamFlags  = paMacCorePlayNice;
+    unsigned long macOutputStreamFlags = paMacCorePlayNice;
+    SInt32 const *inChannelMap = NULL;
+    SInt32 const *outChannelMap = NULL;
+    unsigned long inChannelMapSize = 0;
+    unsigned long outChannelMapSize = 0;
+
+    VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n",
+                inStreamParams  ? inStreamParams->channelCount  : -1,
+                inStreamParams  ? inStreamParams->sampleFormat  : -1,
+                outStreamParams ? outStreamParams->channelCount : -1,
+                outStreamParams ? outStreamParams->sampleFormat : -1,
+                requestedFramesPerBuffer ));
+
+    /* -- handle the degenerate case  -- */
+    if( !inStreamParams && !outStreamParams ) {
+       *audioUnit = NULL;
+       *audioDevice = kAudioDeviceUnknown;
+       return paNoError;
+    }
+
+    /* -- get the user's api specific info, if they set any -- */
+    if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo )
+    {
+       macInputStreamFlags=
+            ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+                  ->flags;
+       inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+                  ->channelMap;
+       inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+                  ->channelMapSize;
+    }
+    if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo )
+    {
+       macOutputStreamFlags=
+            ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+                  ->flags;
+       outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+                  ->channelMap;
+       outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+                  ->channelMapSize; 
+    }
+    /* Override user's flags here, if desired for testing. */
+
+    /*
+     * The HAL AU is a Mac OS style "component".
+     * the first few steps deal with that.
+     * Later steps work on a combination of Mac OS
+     * components and the slightly lower level
+     * HAL.
+     */
+
+    /* -- describe the output type AudioUnit -- */
+    /*  Note: for the default AudioUnit, we could use the
+     *  componentSubType value kAudioUnitSubType_DefaultOutput;
+     *  but I don't think that's relevant here.
+     */
+    desc.componentType         = kAudioUnitType_Output;
+    desc.componentSubType      = kAudioUnitSubType_HALOutput;
+    desc.componentManufacturer = kAudioUnitManufacturer_Apple;
+    desc.componentFlags        = 0;
+    desc.componentFlagsMask    = 0;
+    /* -- find the component -- */
+    comp = FindNextComponent( NULL, &desc );
+    if( !comp )
+    {
+       DBUG( ( "AUHAL component not found." ) );
+       *audioUnit = NULL;
+       *audioDevice = kAudioDeviceUnknown;
+       return paUnanticipatedHostError;
+    }
+    /* -- open it -- */
+    result = OpenAComponent( comp, audioUnit );
+    if( result )
+    {
+       DBUG( ( "Failed to open AUHAL component." ) );
+       *audioUnit = NULL;
+       *audioDevice = kAudioDeviceUnknown;
+       return ERR( result );
+    }
+    /* -- prepare a little error handling logic / hackery -- */
+#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0)
+
+    /* -- if there is input, we have to explicitly enable input -- */
+    if( inStreamParams )
+    {
+       UInt32 enableIO = 1;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                 kAudioOutputUnitProperty_EnableIO,
+                 kAudioUnitScope_Input,
+                 INPUT_ELEMENT,
+                 &enableIO,
+                 sizeof(enableIO) ) );
+    }
+    /* -- if there is no output, we must explicitly disable output -- */
+    if( !outStreamParams )
+    {
+       UInt32 enableIO = 0;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                 kAudioOutputUnitProperty_EnableIO,
+                 kAudioUnitScope_Output,
+                 OUTPUT_ELEMENT,
+                 &enableIO,
+                 sizeof(enableIO) ) );
+    }
+
+    /* -- set the devices -- */
+    /* make sure input and output are the same device if we are doing input and
+       output. */
+    if( inStreamParams && outStreamParams )
+    {
+       assert( outStreamParams->device == inStreamParams->device );
+    }
+    if( inStreamParams )
+    {
+       *audioDevice = auhalHostApi->devIds[inStreamParams->device] ;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                    kAudioOutputUnitProperty_CurrentDevice,
+                    kAudioUnitScope_Global,
+                    INPUT_ELEMENT,
+                    audioDevice,
+                    sizeof(AudioDeviceID) ) );
+    }
+    if( outStreamParams && outStreamParams != inStreamParams )
+    {
+       *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                    kAudioOutputUnitProperty_CurrentDevice,
+                    kAudioUnitScope_Global,
+                    OUTPUT_ELEMENT,
+                    audioDevice,
+                    sizeof(AudioDeviceID) ) );
+    }
+    /* -- add listener for dropouts -- */
+    result = AudioDeviceAddPropertyListener( *audioDevice,
+                                             0,
+                                             outStreamParams ? false : true,
+                                             kAudioDeviceProcessorOverload,
+                                             xrunCallback,
+                                             addToXRunListenerList( (void *)stream ) ) ;
+    if( result == kAudioHardwareIllegalOperationError ) {
+       // -- already registered, we're good
+    } else {
+       // -- not already registered, just check for errors
+       ERR_WRAP( result );
+    }
+    /* -- listen for stream start and stop -- */
+    ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit,
+                                            kAudioOutputUnitProperty_IsRunning,
+                                            startStopCallback,
+                                            (void *)stream ) );
+
+    /* -- set format -- */
+    bzero( &desiredFormat, sizeof(desiredFormat) );
+    desiredFormat.mFormatID         = kAudioFormatLinearPCM ;
+    desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;
+    desiredFormat.mFramesPerPacket  = 1;
+    desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;
+
+    result = 0;
+    /*  set device format first, but only touch the device if the user asked */
+    if( inStreamParams ) {
+       /*The callback never calls back if we don't set the FPB */
+       /*This seems wierd, because I would think setting anything on the device
+         would be disruptive.*/
+       paResult = setBestFramesPerBuffer( *audioDevice, FALSE,
+                                          requestedFramesPerBuffer,
+                                          actualInputFramesPerBuffer );
+       if( paResult ) goto error;
+       if( macInputStreamFlags & paMacCoreChangeDeviceParameters ) {
+          bool requireExact;
+          requireExact=macInputStreamFlags & paMacCoreFailIfConversionRequired;
+          paResult = setBestSampleRateForDevice( *audioDevice, FALSE,
+                                                 requireExact, sampleRate );
+          if( paResult ) goto error;
+       }
+       if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer )
+          *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ;
+    }
+    if( outStreamParams && !inStreamParams ) {
+       /*The callback never calls back if we don't set the FPB */
+       /*This seems wierd, because I would think setting anything on the device
+         would be disruptive.*/
+       paResult = setBestFramesPerBuffer( *audioDevice, TRUE,
+                                          requestedFramesPerBuffer,
+                                          actualOutputFramesPerBuffer );
+       if( paResult ) goto error;
+       if( macOutputStreamFlags & paMacCoreChangeDeviceParameters ) {
+          bool requireExact;
+          requireExact=macOutputStreamFlags & paMacCoreFailIfConversionRequired;
+          paResult = setBestSampleRateForDevice( *audioDevice, TRUE,
+                                                 requireExact, sampleRate );
+          if( paResult ) goto error;
+       }
+    }
+
+    /* -- set the quality of the output converter -- */
+    if( outStreamParams ) {
+       UInt32 value = kAudioConverterQuality_Max;
+       switch( macOutputStreamFlags & 0x0700 ) {
+       case 0x0100: /*paMacCore_ConversionQualityMin:*/
+          value=kRenderQuality_Min;
+          break;
+       case 0x0200: /*paMacCore_ConversionQualityLow:*/
+          value=kRenderQuality_Low;
+          break;
+       case 0x0300: /*paMacCore_ConversionQualityMedium:*/
+          value=kRenderQuality_Medium;
+          break;
+       case 0x0400: /*paMacCore_ConversionQualityHigh:*/
+          value=kRenderQuality_High;
+          break;
+       }
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                    kAudioUnitProperty_RenderQuality,
+                    kAudioUnitScope_Global,
+                    OUTPUT_ELEMENT,
+                    &value,
+                    sizeof(value) ) );
+    }
+    /* now set the format on the Audio Units. */
+    if( outStreamParams )
+    {
+       desiredFormat.mSampleRate    =sampleRate;
+       desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount;
+       desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount;
+       desiredFormat.mChannelsPerFrame = outStreamParams->channelCount;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                            kAudioUnitProperty_StreamFormat,
+                            kAudioUnitScope_Input,
+                            OUTPUT_ELEMENT,
+                            &desiredFormat,
+                            sizeof(AudioStreamBasicDescription) ) );
+    }
+    if( inStreamParams )
+    {
+       AudioStreamBasicDescription sourceFormat;
+       UInt32 size = sizeof( AudioStreamBasicDescription );
+
+       /* keep the sample rate of the device, or we confuse AUHAL */
+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+                            kAudioUnitProperty_StreamFormat,
+                            kAudioUnitScope_Input,
+                            INPUT_ELEMENT,
+                            &sourceFormat,
+                            &size ) );
+       desiredFormat.mSampleRate = sourceFormat.mSampleRate;
+       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
+       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
+       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                            kAudioUnitProperty_StreamFormat,
+                            kAudioUnitScope_Output,
+                            INPUT_ELEMENT,
+                            &desiredFormat,
+                            sizeof(AudioStreamBasicDescription) ) );
+    }
+    /* set the maximumFramesPerSlice */
+    /* not doing this causes real problems
+       (eg. the callback might not be called). The idea of setting both this
+       and the frames per buffer on the device is that we'll be most likely
+       to actually get the frame size we requested in the callback with the
+       minimum latency. */
+    if( outStreamParams ) {
+       UInt32 size = sizeof( *actualOutputFramesPerBuffer );
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                            kAudioUnitProperty_MaximumFramesPerSlice,
+                            kAudioUnitScope_Input,
+                            OUTPUT_ELEMENT,
+                            actualOutputFramesPerBuffer,
+                            sizeof(*actualOutputFramesPerBuffer) ) );
+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+                            kAudioUnitProperty_MaximumFramesPerSlice,
+                            kAudioUnitScope_Global,
+                            OUTPUT_ELEMENT,
+                            actualOutputFramesPerBuffer,
+                            &size ) );
+    }
+    if( inStreamParams ) {
+       /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/
+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+                            kAudioUnitProperty_MaximumFramesPerSlice,
+                            kAudioUnitScope_Output,
+                            INPUT_ELEMENT,
+                            actualInputFramesPerBuffer,
+                            sizeof(*actualInputFramesPerBuffer) ) );
+/* Don't know why this causes problems
+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+                            kAudioUnitProperty_MaximumFramesPerSlice,
+                            kAudioUnitScope_Global, //Output,
+                            INPUT_ELEMENT,
+                            actualInputFramesPerBuffer,
+                            &size ) );
+*/
+    }
+
+    /* -- if we have input, we may need to setup an SR converter -- */
+    /* even if we got the sample rate we asked for, we need to do
+       the conversion in case another program changes the underlying SR. */
+    /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */
+    if( inStreamParams ) {
+       AudioStreamBasicDescription desiredFormat;
+       AudioStreamBasicDescription sourceFormat;
+       UInt32 sourceSize = sizeof( sourceFormat );
+       bzero( &desiredFormat, sizeof(desiredFormat) );
+       desiredFormat.mSampleRate       = sampleRate;
+       desiredFormat.mFormatID         = kAudioFormatLinearPCM ;
+       desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;
+       desiredFormat.mFramesPerPacket  = 1;
+       desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;
+       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
+       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
+       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
+
+       /* get the source format */
+       ERR_WRAP( AudioUnitGetProperty(
+                         *audioUnit,
+                         kAudioUnitProperty_StreamFormat,
+                         kAudioUnitScope_Output,
+                         INPUT_ELEMENT,
+                         &sourceFormat,
+                         &sourceSize ) );
+
+       if( desiredFormat.mSampleRate != sourceFormat.mSampleRate )
+       {
+          UInt32 value = kAudioConverterQuality_Max;
+          switch( macInputStreamFlags & 0x0700 ) {
+          case 0x0100: /*paMacCore_ConversionQualityMin:*/
+             value=kAudioConverterQuality_Min;
+             break;
+          case 0x0200: /*paMacCore_ConversionQualityLow:*/
+             value=kAudioConverterQuality_Low;
+             break;
+          case 0x0300: /*paMacCore_ConversionQualityMedium:*/
+             value=kAudioConverterQuality_Medium;
+             break;
+          case 0x0400: /*paMacCore_ConversionQualityHigh:*/
+             value=kAudioConverterQuality_High;
+             break;
+          }
+          VDBUG(( "Creating sample rate converter for input"
+                  " to convert from %g to %g\n",
+                  (float)sourceFormat.mSampleRate,
+                  (float)desiredFormat.mSampleRate ) );
+          /* create our converter */
+          ERR_WRAP( AudioConverterNew( 
+                             &sourceFormat,
+                             &desiredFormat,
+                             srConverter ) );
+          /* Set quality */
+          ERR_WRAP( AudioConverterSetProperty(
+                             *srConverter,
+                             kAudioConverterSampleRateConverterQuality,
+                             sizeof( value ),
+                             &value ) );
+       }
+    }
+    /* -- set IOProc (callback) -- */
+    callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback
+                                  : kAudioOutputUnitProperty_SetInputCallback ;
+    rcbs.inputProc = AudioIOProc;
+    rcbs.inputProcRefCon = refCon;
+    ERR_WRAP( AudioUnitSetProperty(
+                               *audioUnit,
+                               callbackKey,
+                               kAudioUnitScope_Output,
+                               outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT,
+                               &rcbs,
+                               sizeof(rcbs)) );
+
+    if( inStreamParams && outStreamParams && *srConverter )
+           ERR_WRAP( AudioUnitSetProperty(
+                               *audioUnit,
+                               kAudioOutputUnitProperty_SetInputCallback,
+                               kAudioUnitScope_Output,
+                               INPUT_ELEMENT,
+                               &rcbs,
+                               sizeof(rcbs)) );
+
+    /* channel mapping. */
+    if(inChannelMap)
+    {
+        UInt32 mapSize = inChannelMapSize *sizeof(SInt32);
+
+        //for each channel of desired input, map the channel from
+        //the device's output channel.
+        ERR_WRAP( AudioUnitSetProperty(*audioUnit,
+                                kAudioOutputUnitProperty_ChannelMap,
+                                kAudioUnitScope_Output,
+                                INPUT_ELEMENT,
+                                inChannelMap,
+                                mapSize));
+    }
+    if(outChannelMap)
+    {
+        UInt32 mapSize = outChannelMapSize *sizeof(SInt32);
+
+        //for each channel of desired output, map the channel from
+        //the device's output channel.
+        ERR_WRAP(AudioUnitSetProperty(*audioUnit,
+                                kAudioOutputUnitProperty_ChannelMap,
+                                kAudioUnitScope_Output,
+                                OUTPUT_ELEMENT,
+                                outChannelMap,
+                                mapSize));
+    }
+    /* initialize the audio unit */
+    ERR_WRAP( AudioUnitInitialize(*audioUnit) );
+
+    if( inStreamParams && outStreamParams )
+    {
+        VDBUG( ("Opened device %ld for input and output.\n", *audioDevice ) );
+    }
+    else if( inStreamParams )
+    {
+        VDBUG( ("Opened device %ld for input.\n", *audioDevice ) );
+    }
+    else if( outStreamParams )
+    {
+        VDBUG( ("Opened device %ld for output.\n", *audioDevice ) );
+    }
+    return paNoError;
+#undef ERR_WRAP
+
+    error:
+       CloseComponent( *audioUnit );
+       *audioUnit = NULL;
+       if( result )
+          return PaMacCore_SetError( result, line, 1 );
+       return paResult;
+}
+
+/* =================================================================================================== */
+
+static UInt32 CalculateOptimalBufferSize( PaMacAUHAL *auhalHostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  UInt32 fixedInputLatency,
+                                  UInt32 fixedOutputLatency,
+                                  double sampleRate,
+                                  UInt32 requestedFramesPerBuffer )
+{
+    UInt32 resultBufferSizeFrames = 0;  
+    // Use maximum of suggested input and output latencies.
+    if( inputParameters )
+    {
+        UInt32 suggestedLatencyFrames = inputParameters->suggestedLatency * sampleRate;
+        // Calculate a buffer size assuming we are double buffered.
+        SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedInputLatency;
+        // Prevent negative latency.
+        variableLatencyFrames = MAX( variableLatencyFrames, 0 );       
+        resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames );
+    }
+    if( outputParameters )
+    {        
+        UInt32 suggestedLatencyFrames = outputParameters->suggestedLatency * sampleRate;
+        SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedOutputLatency;
+        variableLatencyFrames = MAX( variableLatencyFrames, 0 );
+        resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames );
+    }
+    
+    // can't have zero frames. code to round up to next user buffer requires non-zero
+    resultBufferSizeFrames = MAX( resultBufferSizeFrames, 1 );
+    
+    if( requestedFramesPerBuffer != paFramesPerBufferUnspecified )
+    {
+        // make host buffer the next highest integer multiple of user frames per buffer
+        UInt32 n = (resultBufferSizeFrames + requestedFramesPerBuffer - 1) / requestedFramesPerBuffer;
+        resultBufferSizeFrames = n * requestedFramesPerBuffer;
+
+        
+        // FIXME: really we should be searching for a multiple of requestedFramesPerBuffer
+        // that is >= suggested latency and also fits within device buffer min/max
+        
+    }else{
+       VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n",
+            resultBufferSizeFrames ) );
+    }
+    
+    // Clip to the capabilities of the device.
+    if( inputParameters )
+    {
+        ClipToDeviceBufferSize( auhalHostApi->devIds[inputParameters->device],
+                               true, // In the old code isInput was false!
+                               resultBufferSizeFrames, &resultBufferSizeFrames );
+    }
+    if( outputParameters )
+    {
+        ClipToDeviceBufferSize( auhalHostApi->devIds[outputParameters->device],
+                               false, resultBufferSizeFrames, &resultBufferSizeFrames );
+    }
+    VDBUG(("After querying hardware, setting block size to %ld.\n", resultBufferSizeFrames));
+
+    return resultBufferSizeFrames;
+}
+
+/* =================================================================================================== */
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long requestedFramesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
+    PaMacCoreStream *stream = 0;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+    UInt32 fixedInputLatency = 0;
+    UInt32 fixedOutputLatency = 0;
+    // Accumulate contributions to latency in these variables.
+    UInt32 inputLatencyFrames = 0;
+    UInt32 outputLatencyFrames = 0;
+    UInt32 suggestedLatencyFramesPerBuffer = requestedFramesPerBuffer;
+    
+    VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n",
+                inputParameters  ? inputParameters->channelCount  : -1,
+                inputParameters  ? inputParameters->sampleFormat  : -1,
+                outputParameters ? outputParameters->channelCount : -1,
+                outputParameters ? outputParameters->sampleFormat : -1,
+                (float) sampleRate,
+                requestedFramesPerBuffer ));
+    VDBUG( ("Opening Stream.\n") );
+       
+    /* These first few bits of code are from paSkeleton with few modifications. */
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+               /* @todo Blocking read/write on Mac is not yet supported. */
+               if( !streamCallback && inputSampleFormat & paNonInterleaved )
+               {
+                       return paSampleFormatNotSupported;
+               }
+               
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* Host supports interleaved float32 */
+        hostInputSampleFormat = paFloat32;
+    }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = hostInputSampleFormat = paFloat32; /* Surpress 'uninitialised var' warnings. */
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        
+               /* @todo Blocking read/write on Mac is not yet supported. */
+               if( !streamCallback && outputSampleFormat & paNonInterleaved )
+               {
+                       return paSampleFormatNotSupported;
+               }
+               
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* Host supports interleaved float32 */
+        hostOutputSampleFormat = paFloat32;
+    }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Surpress 'uninitialized var' warnings. */
+    }
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+
+    stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* If we fail after this point, we my be left in a bad state, with
+       some data structures setup and others not. So, first thing we
+       do is initialize everything so that if we fail, we know what hasn't
+       been touched.
+     */
+    bzero( stream, sizeof( PaMacCoreStream ) );
+    
+    /*
+    stream->blio.inputRingBuffer.buffer = NULL;
+    stream->blio.outputRingBuffer.buffer = NULL;
+    stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0;
+    stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat);
+    stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0;
+    stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat);
+    */
+
+    /* assert( streamCallback ) ; */ /* only callback mode is implemented */
+    if( streamCallback )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                        &auhalHostApi->callbackStreamInterface,
+                                        streamCallback, userData );
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                        &auhalHostApi->blockingStreamInterface,
+                                        BlioCallback, &stream->blio );
+    }
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+    
+    if( inputParameters )
+    {
+        CalculateFixedDeviceLatency( auhalHostApi->devIds[inputParameters->device], true, &fixedInputLatency );
+        inputLatencyFrames += fixedInputLatency;
+    }
+    if( outputParameters )
+    {        
+        CalculateFixedDeviceLatency( auhalHostApi->devIds[outputParameters->device], false, &fixedOutputLatency );
+        outputLatencyFrames += fixedOutputLatency;
+
+    }
+    
+    suggestedLatencyFramesPerBuffer = CalculateOptimalBufferSize( auhalHostApi, inputParameters, outputParameters,
+                                                                 fixedInputLatency, fixedOutputLatency,
+                                                                 sampleRate, requestedFramesPerBuffer );
+    if( requestedFramesPerBuffer == paFramesPerBufferUnspecified )
+       {
+        requestedFramesPerBuffer = suggestedLatencyFramesPerBuffer;
+    }
+
+    /* -- Now we actually open and setup streams. -- */
+    if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )
+    { /* full duplex. One device. */
+       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
+       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
+       result = OpenAndSetupOneAudioUnit( stream,
+                                          inputParameters,
+                                          outputParameters,
+                                          suggestedLatencyFramesPerBuffer,
+                                          &inputFramesPerBuffer,
+                                          &outputFramesPerBuffer,
+                                          auhalHostApi,
+                                          &(stream->inputUnit),
+                                          &(stream->inputSRConverter),
+                                          &(stream->inputDevice),
+                                          sampleRate,
+                                          stream );
+       stream->inputFramesPerBuffer = inputFramesPerBuffer;
+       stream->outputFramesPerBuffer = outputFramesPerBuffer;
+       stream->outputUnit = stream->inputUnit;
+       stream->outputDevice = stream->inputDevice;
+       if( result != paNoError )
+           goto error;
+    }
+    else
+    { /* full duplex, different devices OR simplex */
+       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
+       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
+       result = OpenAndSetupOneAudioUnit( stream,
+                                          NULL,
+                                          outputParameters,
+                                          suggestedLatencyFramesPerBuffer,
+                                          NULL,
+                                          &outputFramesPerBuffer,
+                                          auhalHostApi,
+                                          &(stream->outputUnit),
+                                          NULL,
+                                          &(stream->outputDevice),
+                                          sampleRate,
+                                          stream );
+       if( result != paNoError )
+           goto error;
+       result = OpenAndSetupOneAudioUnit( stream,
+                                          inputParameters,
+                                          NULL,
+                                          suggestedLatencyFramesPerBuffer,
+                                          &inputFramesPerBuffer,
+                                          NULL,
+                                          auhalHostApi,
+                                          &(stream->inputUnit),
+                                          &(stream->inputSRConverter),
+                                          &(stream->inputDevice),
+                                          sampleRate,
+                                          stream );
+       if( result != paNoError )
+           goto error;
+       stream->inputFramesPerBuffer = inputFramesPerBuffer;
+       stream->outputFramesPerBuffer = outputFramesPerBuffer;
+    }
+    
+    inputLatencyFrames += stream->inputFramesPerBuffer;
+    outputLatencyFrames += stream->outputFramesPerBuffer;
+    
+    if( stream->inputUnit ) {
+       const size_t szfl = sizeof(float);
+       /* setup the AudioBufferList used for input */
+       bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) );
+       stream->inputAudioBufferList.mNumberBuffers = 1;
+       stream->inputAudioBufferList.mBuffers[0].mNumberChannels
+                 = inputChannelCount;
+       stream->inputAudioBufferList.mBuffers[0].mDataByteSize
+                 = stream->inputFramesPerBuffer*inputChannelCount*szfl;
+       stream->inputAudioBufferList.mBuffers[0].mData
+                 = (float *) calloc(
+                               stream->inputFramesPerBuffer*inputChannelCount,
+                               szfl );
+       if( !stream->inputAudioBufferList.mBuffers[0].mData )
+       {
+          result = paInsufficientMemory;
+          goto error;
+       }
+        
+       /*
+        * If input and output devs are different or we are doing SR conversion,
+        * we also need a ring buffer to store input data while waiting for
+        * output data.
+        */
+       if( (stream->outputUnit && (stream->inputUnit != stream->outputUnit))
+           || stream->inputSRConverter )
+       {
+          /* May want the ringSize or initial position in
+             ring buffer to depend somewhat on sample rate change */
+
+          void *data;
+          long ringSize;
+
+          ringSize = computeRingBufferSize( inputParameters,
+                                            outputParameters,
+                                            stream->inputFramesPerBuffer,
+                                            stream->outputFramesPerBuffer,
+                                            sampleRate );
+          /*ringSize <<= 4; *//*16x bigger, for testing */
+
+
+          /*now, we need to allocate memory for the ring buffer*/
+          data = calloc( ringSize, szfl*inputParameters->channelCount );
+          if( !data )
+          {
+             result = paInsufficientMemory;
+             goto error;
+          }
+
+          /* now we can initialize the ring buffer */
+          result = PaUtil_InitializeRingBuffer( &stream->inputRingBuffer, szfl*inputParameters->channelCount, ringSize, data );
+          if( result != 0 )
+          {
+              /* The only reason this should fail is if ringSize is not a power of 2, which we do not anticipate happening. */
+              result = paUnanticipatedHostError;
+              free(data);
+              goto error;
+          }
+
+          /* advance the read point a little, so we are reading from the
+             middle of the buffer */
+          if( stream->outputUnit )
+             PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize / RING_BUFFER_ADVANCE_DENOMINATOR );
+           
+           // Just adds to input latency between input device and PA full duplex callback.
+           inputLatencyFrames += ringSize;
+       }
+    }
+
+    /* -- initialize Blio Buffer Processors -- */
+    if( !streamCallback )
+    {
+       long ringSize;
+
+       ringSize = computeRingBufferSize( inputParameters,
+                                         outputParameters,
+                                         stream->inputFramesPerBuffer,
+                                         stream->outputFramesPerBuffer,
+                                         sampleRate );
+       result = initializeBlioRingBuffers( &stream->blio,
+              inputParameters ? inputParameters->sampleFormat : 0,
+              outputParameters ? outputParameters->sampleFormat : 0,
+              ringSize,
+              inputParameters ? inputChannelCount : 0,
+              outputParameters ? outputChannelCount : 0 ) ;
+       if( result != paNoError )
+          goto error;
+        
+        inputLatencyFrames += ringSize;
+        outputLatencyFrames += ringSize;
+        
+    }
+
+    /* -- initialize Buffer Processor -- */
+    {
+       unsigned long maxHostFrames = stream->inputFramesPerBuffer;
+       if( stream->outputFramesPerBuffer > maxHostFrames )
+          maxHostFrames = stream->outputFramesPerBuffer;
+       result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                 inputChannelCount, inputSampleFormat,
+                 hostInputSampleFormat,
+                 outputChannelCount, outputSampleFormat,
+                 hostOutputSampleFormat,
+                 sampleRate,
+                 streamFlags,
+                 requestedFramesPerBuffer,
+                 /* If sample rate conversion takes place, the buffer size
+                    will not be known. */
+                 maxHostFrames,
+                 stream->inputSRConverter
+                              ? paUtilUnknownHostBufferSize
+                              : paUtilBoundedHostBufferSize,
+                 streamCallback ? streamCallback : BlioCallback,
+                 streamCallback ? userData : &stream->blio );
+       if( result != paNoError )
+           goto error;
+    }
+    stream->bufferProcessorIsInitialized = TRUE;
+
+    // Calculate actual latency from the sum of individual latencies.
+    if( inputParameters ) 
+    {
+        inputLatencyFrames += PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor);
+        stream->streamRepresentation.streamInfo.inputLatency = inputLatencyFrames / sampleRate;
+    }
+    else
+    {
+        stream->streamRepresentation.streamInfo.inputLatency = 0.0;
+    }
+    
+    if( outputParameters ) 
+    {
+        outputLatencyFrames += PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor);
+        stream->streamRepresentation.streamInfo.outputLatency = outputLatencyFrames / sampleRate;
+    }
+    else
+    {
+        stream->streamRepresentation.streamInfo.outputLatency = 0.0;
+    }
+    
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    stream->sampleRate = sampleRate;
+    
+    stream->userInChan  = inputChannelCount;
+    stream->userOutChan = outputChannelCount;
+
+    // Setup property listeners for timestamp and latency calculations.
+       pthread_mutex_init( &stream->timingInformationMutex, NULL );
+       stream->timingInformationMutexIsInitialized = 1;
+    InitializeDeviceProperties( &stream->inputProperties );     // zeros the struct. doesn't actually init it to useful values
+    InitializeDeviceProperties( &stream->outputProperties );    // zeros the struct. doesn't actually init it to useful values
+       if( stream->outputUnit )
+    {
+        Boolean isInput = FALSE;
+        
+        // Start with the current values for the device properties.
+        // Init with nominal sample rate. Use actual sample rate where available
+        
+        result = ERR( UpdateSampleRateFromDeviceProperty( 
+                stream, stream->outputDevice, isInput, kAudioDevicePropertyNominalSampleRate )  );
+        if( result )
+            goto error; /* fail if we can't even get a nominal device sample rate */
+        
+        UpdateSampleRateFromDeviceProperty( stream, stream->outputDevice, isInput, kAudioDevicePropertyActualSampleRate );
+        
+        SetupDevicePropertyListeners( stream, stream->outputDevice, isInput );
+    }
+       if( stream->inputUnit )
+    {
+        Boolean isInput = TRUE;
+       
+        // as above
+        result = ERR( UpdateSampleRateFromDeviceProperty( 
+                stream, stream->inputDevice, isInput, kAudioDevicePropertyNominalSampleRate )  );
+        if( result )
+            goto error;
+        
+        UpdateSampleRateFromDeviceProperty( stream, stream->inputDevice, isInput, kAudioDevicePropertyActualSampleRate );
+        
+        SetupDevicePropertyListeners( stream, stream->inputDevice, isInput );
+       }
+    UpdateTimeStampOffsets( stream );
+    // Setup timestamp copies to be used by audio callback.
+    stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined;
+    stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice;
+    stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice;
+
+    stream->state = STOPPED;
+    stream->xrunFlags = 0;
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    CloseStream( stream );
+    return result;
+}
+
+
+#define HOST_TIME_TO_PA_TIME( x ) ( AudioConvertHostTimeToNanos( (x) ) * 1.0E-09) /* convert to nanoseconds and then to seconds */
+
+PaTime GetStreamTime( PaStream *s )
+{
+       return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); 
+}
+
+#define RING_BUFFER_EMPTY (1000)
+
+static OSStatus ringBufferIOProc( AudioConverterRef inAudioConverter, 
+                             UInt32*ioDataSize, 
+                             void** outData, 
+                             void*inUserData )
+{
+   void *dummyData;
+   ring_buffer_size_t dummySize;
+   PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData;
+
+   VVDBUG(("ringBufferIOProc()\n"));
+
+   if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) {
+      *outData = NULL;
+      *ioDataSize = 0;
+      return RING_BUFFER_EMPTY;
+   }
+   assert(sizeof(UInt32) == sizeof(ring_buffer_size_t));
+   assert( ( (*ioDataSize) / rb->elementSizeBytes ) * rb->elementSizeBytes == (*ioDataSize) ) ;
+   (*ioDataSize) /= rb->elementSizeBytes ;
+   PaUtil_GetRingBufferReadRegions( rb, *ioDataSize,
+                                    outData, (ring_buffer_size_t *)ioDataSize, 
+                                    &dummyData, &dummySize );
+   assert( *ioDataSize );
+   PaUtil_AdvanceRingBufferReadIndex( rb, *ioDataSize );
+   (*ioDataSize) *= rb->elementSizeBytes ;
+
+   return noErr;
+}
+
+/*
+ * Called by the AudioUnit API to process audio from the sound card.
+ * This is where the magic happens.
+ */
+/* FEEDBACK: there is a lot of redundant code here because of how all the cases differ. This makes it hard to maintain, so if there are suggestinos for cleaning it up, I'm all ears. */
+static OSStatus AudioIOProc( void *inRefCon,
+                               AudioUnitRenderActionFlags *ioActionFlags,
+                               const AudioTimeStamp *inTimeStamp,
+                               UInt32 inBusNumber,
+                               UInt32 inNumberFrames,
+                               AudioBufferList *ioData )
+{
+   unsigned long framesProcessed     = 0;
+   PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+   PaMacCoreStream *stream           = (PaMacCoreStream*)inRefCon;
+   const bool isRender               = inBusNumber == OUTPUT_ELEMENT;
+   int callbackResult                = paContinue ;
+   double hostTimeStampInPaTime      = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime);
+    
+   VVDBUG(("AudioIOProc()\n"));
+
+   PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+    
+   /* -----------------------------------------------------------------*\
+      This output may be useful for debugging,
+      But printing durring the callback is a bad enough idea that
+      this is not enabled by enableing the usual debugging calls.
+   \* -----------------------------------------------------------------*/
+   /*
+   static int renderCount = 0;
+   static int inputCount = 0;
+   printf( "-------------------  starting reder/input\n" );
+   if( isRender )
+      printf("Render callback (%d):\t", ++renderCount);
+   else
+      printf("Input callback  (%d):\t", ++inputCount);
+   printf( "Call totals: %d (input), %d (render)\n", inputCount, renderCount );
+
+   printf( "--- inBusNumber: %lu\n", inBusNumber );
+   printf( "--- inNumberFrames: %lu\n", inNumberFrames );
+   printf( "--- %x ioData\n", (unsigned) ioData );
+   if( ioData )
+   {
+      int i=0;
+      printf( "--- ioData.mNumBuffers %lu: \n", ioData->mNumberBuffers );
+      for( i=0; i<ioData->mNumberBuffers; ++i )
+         printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize );
+   }
+      ----------------------------------------------------------------- */
+
+       /* compute PaStreamCallbackTimeInfo */
+       
+       if( pthread_mutex_trylock( &stream->timingInformationMutex ) == 0 ){
+               /* snapshot the ioproc copy of timing information */
+               stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined;
+               stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice;
+               stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice;
+               pthread_mutex_unlock( &stream->timingInformationMutex );
+       }
+       
+       /* For timeInfo.currentTime we could calculate current time backwards from the HAL audio 
+        output time to give a more accurate impression of the current timeslice but it doesn't 
+        seem worth it at the moment since other PA host APIs don't do any better.
+        */
+       timeInfo.currentTime = HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() );
+       
+       /*
+        For an input HAL AU, inTimeStamp is the time the samples are received from the hardware,
+        for an output HAL AU inTimeStamp is the time the samples are sent to the hardware. 
+        PA expresses timestamps in terms of when the samples enter the ADC or leave the DAC
+        so we add or subtract kAudioDevicePropertyLatency below.
+        */
+       
+       /* FIXME: not sure what to do below if the host timestamps aren't valid (kAudioTimeStampHostTimeValid isn't set)
+        Could ask on CA mailing list if it is possible for it not to be set. If so, could probably grab a now timestamp
+        at the top and compute from there (modulo scheduling jitter) or ask on mailing list for other options. */
+       
+       if( isRender )
+       {
+               if( stream->inputUnit ) /* full duplex */
+               {
+                       if( stream->inputUnit == stream->outputUnit ) /* full duplex AUHAL IOProc */
+                       {
+                // Ross and Phil agreed that the following calculation is correct based on an email from Jeff Moore:
+                // http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html
+                // Basically the difference between the Apple output timestamp and the PA timestamp is kAudioDevicePropertyLatency.
+                               timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - 
+                    (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy);
+                               timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
+                       }
+                       else /* full duplex with ring-buffer from a separate input AUHAL ioproc */
+                       {
+                               /* FIXME: take the ring buffer latency into account */
+                               timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - 
+                    (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy);
+                               timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
+                       }
+               }
+               else /* output only */
+               {
+                       timeInfo.inputBufferAdcTime = 0;
+                       timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
+               }
+       }
+       else /* input only */
+       {
+               timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - stream->timestampOffsetInputDevice_ioProcCopy; 
+               timeInfo.outputBufferDacTime = 0;
+       }
+       
+   //printf( "---%g, %g, %g\n", timeInfo.inputBufferAdcTime, timeInfo.currentTime, timeInfo.outputBufferDacTime );
+
+   if( isRender && stream->inputUnit == stream->outputUnit
+                && !stream->inputSRConverter )
+   {
+      /* --------- Full Duplex, One Device, no SR Conversion -------
+       *
+       * This is the lowest latency case, and also the simplest.
+       * Input data and output data are available at the same time.
+       * we do not use the input SR converter or the input ring buffer.
+       *
+       */
+      OSStatus err = 0;
+       unsigned long frames;
+       long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
+
+      /* -- start processing -- */
+      PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+                                    &timeInfo,
+                                    stream->xrunFlags );
+      stream->xrunFlags = 0; //FIXME: this flag also gets set outside by a callback, which calls the xrunCallback function. It should be in the same thread as the main audio callback, but the apple docs just use the word "usually" so it may be possible to loose an xrun notification, if that callback happens here.
+
+      /* -- compute frames. do some checks -- */
+      assert( ioData->mNumberBuffers == 1 );
+      assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
+
+      frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame;
+      /* -- copy and process input data -- */
+      err= AudioUnitRender(stream->inputUnit,
+                    ioActionFlags,
+                    inTimeStamp,
+                    INPUT_ELEMENT,
+                    inNumberFrames,
+                    &stream->inputAudioBufferList );
+      if(err != noErr)
+      {
+        goto stop_stream;
+      }
+
+      PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+      PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                          0,
+                          stream->inputAudioBufferList.mBuffers[0].mData,
+                          stream->inputAudioBufferList.mBuffers[0].mNumberChannels);
+      /* -- Copy and process output data -- */
+      PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
+      PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
+                                        0,
+                                        ioData->mBuffers[0].mData,
+                                        ioData->mBuffers[0].mNumberChannels);
+      /* -- complete processing -- */
+      framesProcessed =
+                 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                             &callbackResult );
+   }
+   else if( isRender )
+   {
+      /* -------- Output Side of Full Duplex (Separate Devices or SR Conversion)
+       *       -- OR Simplex Output
+       *
+       * This case handles output data as in the full duplex case,
+       * and, if there is input data, reads it off the ring buffer 
+       * and into the PA buffer processor. If sample rate conversion
+       * is required on input, that is done here as well.
+       */
+       unsigned long frames;
+       long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
+
+      /* Sometimes, when stopping a duplex stream we get erroneous
+         xrun flags, so if this is our last run, clear the flags. */
+      int xrunFlags = stream->xrunFlags;
+/*
+      if( xrunFlags & paInputUnderflow )
+         printf( "input underflow.\n" );
+      if( xrunFlags & paInputOverflow )
+         printf( "input overflow.\n" );
+*/
+      if( stream->state == STOPPING || stream->state == CALLBACK_STOPPED )
+         xrunFlags = 0;
+
+      /* -- start processing -- */
+      PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+                                    &timeInfo,
+                                    xrunFlags );
+      stream->xrunFlags = 0; /* FEEDBACK: we only send flags to Buf Proc once */
+
+      /* -- Copy and process output data -- */
+      assert( ioData->mNumberBuffers == 1 );
+      frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame;
+      assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
+      PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
+      PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
+                                     0,
+                                     ioData->mBuffers[0].mData,
+                                     ioData->mBuffers[0].mNumberChannels);
+
+      /* -- copy and process input data, and complete processing -- */
+      if( stream->inputUnit ) {
+         const int flsz = sizeof( float );
+         /* Here, we read the data out of the ring buffer, through the
+            audio converter. */
+         int inChan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels;
+         long bytesPerFrame = flsz * inChan;
+          
+         if( stream->inputSRConverter )
+         {
+               OSStatus err;
+               UInt32 size;
+               float data[ inChan * frames ];
+               size = sizeof( data );
+               err = AudioConverterFillBuffer( 
+                             stream->inputSRConverter,
+                             ringBufferIOProc,
+                             &stream->inputRingBuffer,
+                             &size,
+                             (void *)&data );
+               if( err == RING_BUFFER_EMPTY )
+               { /* the ring buffer callback underflowed */
+                  err = 0;
+                  bzero( ((char *)data) + size, sizeof(data)-size );
+                  /* The ring buffer can underflow normally when the stream is stopping.
+                   * So only report an error if the stream is active. */
+                  if( stream->state == ACTIVE )
+                  {
+                      stream->xrunFlags |= paInputUnderflow;
+                  }
+               }
+               ERR( err );
+               if(err != noErr)
+               {
+                 goto stop_stream;
+               }
+
+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                                   0,
+                                   data,
+                                   inChan );
+               framesProcessed =
+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                                &callbackResult );
+         }
+         else
+         {
+            /* Without the AudioConverter is actually a bit more complex
+               because we have to do a little buffer processing that the
+               AudioConverter would otherwise handle for us. */
+            void *data1, *data2;
+            ring_buffer_size_t size1, size2;
+            ring_buffer_size_t framesReadable = PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer,
+                                             frames,
+                                             &data1, &size1,
+                                             &data2, &size2 );
+            if( size1 == frames ) {
+               /* simplest case: all in first buffer */
+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                                   0,
+                                   data1,
+                                   inChan );
+               framesProcessed =
+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                                &callbackResult );
+               PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1 );
+            } else if( framesReadable < frames ) {
+                
+                long sizeBytes1 = size1 * bytesPerFrame;
+                long sizeBytes2 = size2 * bytesPerFrame;
+               /*we underflowed. take what data we can, zero the rest.*/
+               unsigned char data[ frames * bytesPerFrame ];
+               if( size1 > 0 )
+               {   
+                   memcpy( data, data1, sizeBytes1 );
+               }
+               if( size2 > 0 )
+               {
+                   memcpy( data+sizeBytes1, data2, sizeBytes2 );
+               }
+               bzero( data+sizeBytes1+sizeBytes2, (frames*bytesPerFrame) - sizeBytes1 - sizeBytes2 );
+
+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                                   0,
+                                   data,
+                                   inChan );
+               framesProcessed =
+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                                &callbackResult );
+               PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer,
+                                                  framesReadable );
+               /* flag underflow */
+               stream->xrunFlags |= paInputUnderflow;
+            } else {
+               /*we got all the data, but split between buffers*/
+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), size1 );
+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                                   0,
+                                   data1,
+                                   inChan );
+               PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor), size2 );
+               PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor),
+                                   0,
+                                   data2,
+                                   inChan );
+               framesProcessed =
+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                                &callbackResult );
+               PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, framesReadable );
+            }
+         }
+      } else {
+         framesProcessed =
+                 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                             &callbackResult );
+      }
+
+   }
+   else
+   {
+      /* ------------------ Input
+       *
+       * First, we read off the audio data and put it in the ring buffer.
+       * if this is an input-only stream, we need to process it more,
+       * otherwise, we let the output case deal with it.
+       */
+      OSStatus err = 0;
+      int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ;
+      /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */
+      do {
+         err= AudioUnitRender(stream->inputUnit,
+                 ioActionFlags,
+                 inTimeStamp,
+                 INPUT_ELEMENT,
+                 inNumberFrames,
+                 &stream->inputAudioBufferList );
+         if( err == -10874 )
+            inNumberFrames /= 2;
+      } while( err == -10874 && inNumberFrames > 1 );
+      ERR( err );
+      if(err != noErr)
+      {
+          goto stop_stream;
+      }
+
+      if( stream->inputSRConverter || stream->outputUnit )
+      {
+         /* If this is duplex or we use a converter, put the data
+            into the ring buffer. */
+          ring_buffer_size_t framesWritten = PaUtil_WriteRingBuffer( &stream->inputRingBuffer,
+                                            stream->inputAudioBufferList.mBuffers[0].mData,
+                                            inNumberFrames );
+         if( framesWritten != inNumberFrames )
+         {
+             stream->xrunFlags |= paInputOverflow ;
+         }
+      }
+      else
+      {
+         /* for simplex input w/o SR conversion,
+            just pop the data into the buffer processor.*/
+         PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+                              &timeInfo,
+                              stream->xrunFlags );
+         stream->xrunFlags = 0;
+
+         PaUtil_SetInputFrameCount( &(stream->bufferProcessor), inNumberFrames);
+         PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                             0,
+                             stream->inputAudioBufferList.mBuffers[0].mData,
+                             chan );
+         framesProcessed =
+              PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                          &callbackResult );
+      }
+      if( !stream->outputUnit && stream->inputSRConverter )
+      {
+         /* ------------------ Simplex Input w/ SR Conversion
+          *
+          * if this is a simplex input stream, we need to read off the buffer,
+          * do our sample rate conversion and pass the results to the buffer
+          * processor.
+          * The logic here is complicated somewhat by the fact that we don't
+          * know how much data is available, so we loop on reasonably sized
+          * chunks, and let the BufferProcessor deal with the rest.
+          *
+          */
+         /* This might be too big or small depending on SR conversion. */
+         float data[ chan * inNumberFrames ];
+         OSStatus err;
+         do
+         { /* Run the buffer processor until we are out of data. */
+            UInt32 size;
+            long f;
+
+            size = sizeof( data );
+            err = AudioConverterFillBuffer( 
+                          stream->inputSRConverter,
+                          ringBufferIOProc,
+                          &stream->inputRingBuffer,
+                          &size,
+                          (void *)data );
+            if( err != RING_BUFFER_EMPTY )
+               ERR( err );
+            if( err != noErr && err != RING_BUFFER_EMPTY )
+            {
+                goto stop_stream;
+            }
+
+
+            f = size / ( chan * sizeof(float) );
+            PaUtil_SetInputFrameCount( &(stream->bufferProcessor), f );
+            if( f )
+            {
+               PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+                                             &timeInfo,
+                                             stream->xrunFlags );
+               stream->xrunFlags = 0;
+
+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+                                0,
+                                data,
+                                chan );
+               framesProcessed =
+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+                                                &callbackResult );
+            }
+         } while( callbackResult == paContinue && !err );
+      }
+   }
+
+    // Should we return successfully or fall through to stopping the stream?
+    if( callbackResult == paContinue )
+    {
+        PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+        return noErr;
+    }
+
+stop_stream:
+    stream->state = CALLBACK_STOPPED ;
+    if( stream->outputUnit )
+        AudioOutputUnitStop(stream->outputUnit);
+    if( stream->inputUnit )
+        AudioOutputUnitStop(stream->inputUnit);
+
+    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+    return noErr;
+}
+
+/*
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    /* This may be called from a failed OpenStream.
+       Therefore, each piece of info is treated seperately. */
+    PaError result = paNoError;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+    VVDBUG(("CloseStream()\n"));
+    VDBUG( ( "Closing stream.\n" ) );
+
+    if( stream ) {
+               
+               if( stream->outputUnit )
+        {
+            Boolean isInput = FALSE;
+            CleanupDevicePropertyListeners( stream, stream->outputDevice, isInput );
+               }
+               
+               if( stream->inputUnit )
+        {
+            Boolean isInput = TRUE;
+            CleanupDevicePropertyListeners( stream, stream->inputDevice, isInput );
+               }
+               
+       if( stream->outputUnit ) {
+          int count = removeFromXRunListenerList( stream );
+          if( count == 0 )
+             AudioDeviceRemovePropertyListener( stream->outputDevice,
+                                                0,
+                                                false,
+                                                kAudioDeviceProcessorOverload,
+                                                xrunCallback );
+       }
+       if( stream->inputUnit && stream->outputUnit != stream->inputUnit ) {
+          int count = removeFromXRunListenerList( stream );
+          if( count == 0 )
+             AudioDeviceRemovePropertyListener( stream->inputDevice,
+                                                0,
+                                                true,
+                                                kAudioDeviceProcessorOverload,
+                                                xrunCallback );
+       }
+       if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
+          AudioUnitUninitialize( stream->outputUnit );
+          CloseComponent( stream->outputUnit );
+       }
+       stream->outputUnit = NULL;
+       if( stream->inputUnit )
+       {
+          AudioUnitUninitialize( stream->inputUnit );
+          CloseComponent( stream->inputUnit );
+          stream->inputUnit = NULL;
+       }
+       if( stream->inputRingBuffer.buffer )
+          free( (void *) stream->inputRingBuffer.buffer );
+       stream->inputRingBuffer.buffer = NULL;
+       /*TODO: is there more that needs to be done on error
+               from AudioConverterDispose?*/
+       if( stream->inputSRConverter )
+          ERR( AudioConverterDispose( stream->inputSRConverter ) );
+       stream->inputSRConverter = NULL;
+       if( stream->inputAudioBufferList.mBuffers[0].mData )
+          free( stream->inputAudioBufferList.mBuffers[0].mData );
+       stream->inputAudioBufferList.mBuffers[0].mData = NULL;
+
+       result = destroyBlioRingBuffers( &stream->blio );
+       if( result )
+          return result;
+       if( stream->bufferProcessorIsInitialized )
+          PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+               
+       if( stream->timingInformationMutexIsInitialized )
+          pthread_mutex_destroy( &stream->timingInformationMutex );
+
+       PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+       PaUtil_FreeMemory( stream );
+    }
+
+    return result;
+}
+
+static PaError StartStream( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    OSStatus result = noErr;
+    VVDBUG(("StartStream()\n"));
+    VDBUG( ( "Starting stream.\n" ) );
+
+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
+
+    /*FIXME: maybe want to do this on close/abort for faster start? */
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+    if(  stream->inputSRConverter )
+       ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) );
+
+    /* -- start -- */
+    stream->state = ACTIVE;
+    if( stream->inputUnit ) {
+       ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) );
+    }
+    if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
+       ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) );
+    }
+       
+    return paNoError;
+#undef ERR_WRAP
+}
+
+// it's not clear from appl's docs that this really waits
+// until all data is flushed.
+static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioUnitElement element )
+{
+    Boolean isRunning = 1;
+    while( isRunning ) {
+       UInt32 s = sizeof( isRunning );
+       ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element,  &isRunning, &s );
+       if( err )
+          return err;
+       Pa_Sleep( 100 );
+    }
+    return noErr;
+}
+
+static PaError FinishStoppingStream( PaMacCoreStream *stream )
+{
+    OSStatus result = noErr;
+    PaError paErr;
+
+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
+    /* -- stop and reset -- */
+    if( stream->inputUnit == stream->outputUnit && stream->inputUnit )
+    {
+       ERR_WRAP( AudioOutputUnitStop(stream->inputUnit) );
+       ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,0) );
+       ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
+       ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) );
+       ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) );
+    }
+    else
+    {
+       if( stream->inputUnit )
+       {
+          ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) );
+          ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
+          ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1));
+       }
+       if( stream->outputUnit )
+       {
+          ERR_WRAP(AudioOutputUnitStop(stream->outputUnit));
+          ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->outputUnit,0) );
+          ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0));
+       }
+    }
+    if( stream->inputRingBuffer.buffer ) {
+       PaUtil_FlushRingBuffer( &stream->inputRingBuffer );
+       bzero( (void *)stream->inputRingBuffer.buffer,
+              stream->inputRingBuffer.bufferSize );
+       /* advance the write point a little, so we are reading from the
+          middle of the buffer. We'll need extra at the end because
+          testing has shown that this helps. */
+       if( stream->outputUnit )
+          PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer,
+                                              stream->inputRingBuffer.bufferSize
+                                              / RING_BUFFER_ADVANCE_DENOMINATOR );
+    }
+
+    stream->xrunFlags = 0;
+    stream->state = STOPPED;
+
+    paErr = resetBlioRingBuffers( &stream->blio );
+    if( paErr )
+       return paErr;
+
+    VDBUG( ( "Stream Stopped.\n" ) );
+    return paNoError;
+#undef ERR_WRAP
+}
+
+/* Block until buffer is empty then stop the stream. */
+static PaError StopStream( PaStream *s )
+{
+    PaError paErr;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("StopStream()\n"));
+
+    /* Tell WriteStream to stop filling the buffer. */
+    stream->state = STOPPING;
+
+    if( stream->userOutChan > 0 ) /* Does this stream do output? */
+    {
+        size_t maxHostFrames = MAX( stream->inputFramesPerBuffer, stream->outputFramesPerBuffer );
+        VDBUG( ("Waiting for write buffer to be drained.\n") );
+        paErr = waitUntilBlioWriteBufferIsEmpty( &stream->blio, stream->sampleRate,
+                                                maxHostFrames );
+        VDBUG( ( "waitUntilBlioWriteBufferIsEmpty returned %d\n", paErr ) );
+    }
+    return FinishStoppingStream( stream );
+}
+
+/* Immediately stop the stream. */
+static PaError AbortStream( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VDBUG( ( "AbortStream()\n" ) );
+    stream->state = STOPPING;
+    return FinishStoppingStream( stream );
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("IsStreamStopped()\n"));
+
+    return stream->state == STOPPED ? 1 : 0;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("IsStreamActive()\n"));
+    return ( stream->state == ACTIVE || stream->state == STOPPING );
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    VVDBUG(("GetStreamCpuLoad()\n"));
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
new file mode 100644 (file)
index 0000000..679c6ba
--- /dev/null
@@ -0,0 +1,637 @@
+/*
+ * Implementation of the PortAudio API for Apple AUHAL
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+
+ This file contains the implementation
+ required for blocking I/O. It is separated from pa_mac_core.c simply to ease
+ development.
+*/
+
+#include "pa_mac_core_blocking.h"
+#include "pa_mac_core_internal.h"
+#include <assert.h>
+#ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS
+# define OSAtomicOr32( a, b ) ( (*(b)) |= (a) )
+# define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) )
+#else
+# include <libkern/OSAtomic.h>
+#endif
+
+/*
+ * This function determines the size of a particular sample format.
+ * if the format is not recognized, this returns zero.
+ */
+static size_t computeSampleSizeFromFormat( PaSampleFormat format )
+{
+   switch( format & (~paNonInterleaved) ) {
+   case paFloat32: return 4;
+   case paInt32: return 4;
+   case paInt24: return 3;
+   case paInt16: return 2;
+   case paInt8: case paUInt8: return 1;
+   default: return 0;
+   }
+}
+/*
+ * Same as computeSampleSizeFromFormat, except that if
+ * the size is not a power of two, it returns the next power of two up
+ */
+static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format )
+{
+   switch( format & (~paNonInterleaved) ) {
+   case paFloat32: return 4;
+   case paInt32: return 4;
+   case paInt24: return 4;
+   case paInt16: return 2;
+   case paInt8: case paUInt8: return 1;
+   default: return 0;
+   }
+}
+
+
+
+/*
+ * Functions for initializing, resetting, and destroying BLIO structures.
+ *
+ */
+
+/**
+ * This should be called with the relevant info when initializing a stream for callback.
+ *
+ * @param ringBufferSizeInFrames must be a power of 2
+ */
+PaError initializeBlioRingBuffers(
+                                       PaMacBlio *blio,
+                                       PaSampleFormat inputSampleFormat,
+                                       PaSampleFormat outputSampleFormat,
+                                       long ringBufferSizeInFrames,
+                                       int inChan,
+                                       int outChan )
+{
+   void *data;
+   int result;
+   OSStatus err;
+
+   /* zeroify things */
+   bzero( blio, sizeof( PaMacBlio ) );
+   /* this is redundant, but the buffers are used to check
+      if the buffers have been initialized, so we do it explicitly. */
+   blio->inputRingBuffer.buffer = NULL;
+   blio->outputRingBuffer.buffer = NULL;
+
+   /* initialize simple data */
+   blio->ringBufferFrames = ringBufferSizeInFrames;
+   blio->inputSampleFormat = inputSampleFormat;
+   blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat);
+   blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat); // FIXME: WHY?
+   blio->outputSampleFormat = outputSampleFormat;
+   blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat);
+   blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat);
+
+   blio->inChan = inChan;
+   blio->outChan = outChan;
+   blio->statusFlags = 0;
+   blio->errors = paNoError;
+#ifdef PA_MAC_BLIO_MUTEX
+   blio->isInputEmpty = false;
+   blio->isOutputFull = false;
+#endif
+
+   /* setup ring buffers */
+#ifdef PA_MAC_BLIO_MUTEX
+   result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 );
+   if( result )
+      goto error;
+   result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) );
+   if( result )
+      goto error;
+   result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) );
+   if( result )
+      goto error;
+   result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );
+#endif
+   if( inChan ) {
+      data = calloc( ringBufferSizeInFrames, blio->inputSampleSizePow2 * inChan );
+      if( !data )
+      {
+         result = paInsufficientMemory;
+         goto error;
+      }
+
+      err = PaUtil_InitializeRingBuffer(
+            &blio->inputRingBuffer,
+            blio->inputSampleSizePow2 * inChan,
+            ringBufferSizeInFrames,
+            data );
+      assert( !err );
+   }
+   if( outChan ) {
+      data = calloc( ringBufferSizeInFrames, blio->outputSampleSizePow2 * outChan );
+      if( !data )
+      {
+         result = paInsufficientMemory;
+         goto error;
+      }
+
+      err = PaUtil_InitializeRingBuffer(
+            &blio->outputRingBuffer,
+            blio->outputSampleSizePow2 * outChan,
+            ringBufferSizeInFrames,
+            data );
+      assert( !err );
+   }
+
+   result = resetBlioRingBuffers( blio );
+   if( result )
+      goto error;
+
+   return 0;
+
+ error:
+   destroyBlioRingBuffers( blio );
+   return result;
+}
+
+#ifdef PA_MAC_BLIO_MUTEX
+PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty )
+{
+   PaError result = paNoError;
+   if( isEmpty == blio->isInputEmpty )
+      goto done;
+
+   /* we need to update the value. Here's what we do:
+    * - Lock the mutex, so noone else can write.
+    * - update the value.
+    * - unlock.
+    * - broadcast to all listeners.
+    */
+   result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
+   if( result )
+      goto done;
+   blio->isInputEmpty = isEmpty;
+   result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
+   if( result )
+      goto done;
+   result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) );
+   if( result )
+      goto done;
+
+ done:
+   return result;
+}
+PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull )
+{
+   PaError result = paNoError;
+   if( isFull == blio->isOutputFull )
+      goto done;
+
+   /* we need to update the value. Here's what we do:
+    * - Lock the mutex, so noone else can write.
+    * - update the value.
+    * - unlock.
+    * - broadcast to all listeners.
+    */
+   result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
+   if( result )
+      goto done;
+   blio->isOutputFull = isFull;
+   result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
+   if( result )
+      goto done;
+   result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) );
+   if( result )
+      goto done;
+
+ done:
+   return result;
+}
+#endif
+
+/* This should be called after stopping or aborting the stream, so that on next
+   start, the buffers will be ready. */
+PaError resetBlioRingBuffers( PaMacBlio *blio )
+{
+#ifdef PA_MAC__BLIO_MUTEX
+   int result;
+#endif
+   blio->statusFlags = 0;
+   if( blio->outputRingBuffer.buffer ) {
+       PaUtil_FlushRingBuffer( &blio->outputRingBuffer );
+       /* Fill the buffer with zeros. */
+       bzero( blio->outputRingBuffer.buffer,
+             blio->outputRingBuffer.bufferSize * blio->outputRingBuffer.elementSizeBytes );
+       PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames );
+
+      /* Update isOutputFull. */
+#ifdef PA_MAC__BLIO_MUTEX
+      result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize );
+      if( result )
+         goto error;
+#endif
+/*
+      printf( "------%d\n" ,  blio->outChan );
+      printf( "------%d\n" ,  blio->outputSampleSize );
+*/
+   }
+   if( blio->inputRingBuffer.buffer ) {
+      PaUtil_FlushRingBuffer( &blio->inputRingBuffer );
+      bzero( blio->inputRingBuffer.buffer,
+             blio->inputRingBuffer.bufferSize * blio->inputRingBuffer.elementSizeBytes );
+      /* Update isInputEmpty. */
+#ifdef PA_MAC__BLIO_MUTEX
+      result = blioSetIsInputEmpty( blio, true );
+      if( result )
+         goto error;
+#endif
+   }
+   return paNoError;
+#ifdef PA_MAC__BLIO_MUTEX
+ error:
+   return result;
+#endif
+}
+
+/*This should be called when you are done with the blio. It can safely be called
+  multiple times if there are no exceptions. */
+PaError destroyBlioRingBuffers( PaMacBlio *blio )
+{
+   PaError result = paNoError;
+   if( blio->inputRingBuffer.buffer ) {
+      free( blio->inputRingBuffer.buffer );
+#ifdef PA_MAC__BLIO_MUTEX
+      result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) );
+      if( result ) return result;
+      result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) );
+      if( result ) return result;
+#endif
+   }
+   blio->inputRingBuffer.buffer = NULL;
+   if( blio->outputRingBuffer.buffer ) {
+      free( blio->outputRingBuffer.buffer );
+#ifdef PA_MAC__BLIO_MUTEX
+      result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) );
+      if( result ) return result;
+      result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) );
+      if( result ) return result;
+#endif
+   }
+   blio->outputRingBuffer.buffer = NULL;
+
+   return result;
+}
+
+/*
+ * this is the BlioCallback function. It expects to recieve a PaMacBlio Object
+ * pointer as userData.
+ *
+ */
+int BlioCallback( const void *input, void *output, unsigned long frameCount,
+       const PaStreamCallbackTimeInfo* timeInfo,
+        PaStreamCallbackFlags statusFlags,
+        void *userData )
+{
+   PaMacBlio *blio = (PaMacBlio*)userData;
+   ring_buffer_size_t framesAvailable;
+   ring_buffer_size_t framesToTransfer;
+   ring_buffer_size_t framesTransferred;
+
+   /* set flags returned by OS: */
+   OSAtomicOr32( statusFlags, &blio->statusFlags ) ;
+
+   /* --- Handle Input Buffer --- */
+   if( blio->inChan ) {
+      framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );
+
+      /* check for underflow */
+      if( framesAvailable < frameCount )
+      {
+          OSAtomicOr32( paInputOverflow, &blio->statusFlags );
+          framesToTransfer = framesAvailable;
+      }
+      else
+      {
+          framesToTransfer = (ring_buffer_size_t)frameCount;
+      }
+
+      /* Copy the data from the audio input to the application ring buffer. */
+      /*printf( "reading %d\n", toRead );*/
+      framesTransferred = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, framesToTransfer );
+      assert( framesToTransfer == framesTransferred );
+#ifdef PA_MAC__BLIO_MUTEX
+      /* Priority inversion. See notes below. */
+      blioSetIsInputEmpty( blio, false );
+#endif
+   }
+
+
+   /* --- Handle Output Buffer --- */
+   if( blio->outChan ) {
+      framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
+
+      /* check for underflow */
+      if( framesAvailable < frameCount )
+      {
+          /* zero out the end of the output buffer that we do not have data for */
+          framesToTransfer = framesAvailable;
+
+          size_t bytesPerFrame = blio->outputSampleSizeActual * blio->outChan;
+          size_t offsetInBytes = framesToTransfer * bytesPerFrame;
+          size_t countInBytes = (frameCount - framesToTransfer) * bytesPerFrame;
+          bzero( ((char *)output) + offsetInBytes, countInBytes );
+
+          OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );
+          framesToTransfer = framesAvailable;
+      }
+      else
+      {
+          framesToTransfer = (ring_buffer_size_t)frameCount;
+      }
+
+      /* copy the data */
+      /*printf( "writing %d\n", toWrite );*/
+      framesTransferred = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, framesToTransfer );
+      assert( framesToTransfer == framesTransferred );
+#ifdef PA_MAC__BLIO_MUTEX
+      /* We have a priority inversion here. However, we will only have to
+         wait if this was true and is now false, which means we've got
+         some room in the buffer.
+         Hopefully problems will be minimized. */
+      blioSetIsOutputFull( blio, false );
+#endif
+   }
+
+   return paContinue;
+}
+
+PaError ReadStream( PaStream* stream,
+                           void *buffer,
+                           unsigned long framesRequested )
+{
+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+    char *cbuf = (char *) buffer;
+    PaError ret = paNoError;
+    VVDBUG(("ReadStream()\n"));
+
+    while( framesRequested > 0 ) {
+       ring_buffer_size_t framesAvailable;
+       ring_buffer_size_t framesToTransfer;
+       ring_buffer_size_t framesTransferred;
+       do {
+          framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
+/*
+          printf( "Read Buffer is %%%g full: %ld of %ld.\n",
+                  100 * (float)avail / (float) blio->inputRingBuffer.bufferSize,
+                  framesAvailable, blio->inputRingBuffer.bufferSize );
+*/
+          if( framesAvailable == 0 ) {
+#ifdef PA_MAC_BLIO_MUTEX
+             /**block when empty*/
+             ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
+             if( ret )
+                return ret;
+             while( blio->isInputEmpty ) {
+                ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) );
+                if( ret )
+                   return ret;
+             }
+             ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
+             if( ret )
+                return ret;
+#else
+             Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
+#endif
+          }
+       } while( framesAvailable == 0 );
+       framesToTransfer = (ring_buffer_size_t) MIN( framesAvailable, framesRequested );
+       framesTransferred = PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, framesToTransfer );
+       cbuf += framesTransferred * blio->inputSampleSizeActual * blio->inChan;
+       framesRequested -= framesTransferred;
+
+       if( framesToTransfer == framesAvailable ) {
+#ifdef PA_MAC_BLIO_MUTEX
+          /* we just emptied the buffer, so we need to mark it as empty. */
+          ret = blioSetIsInputEmpty( blio, true );
+          if( ret )
+             return ret;
+          /* of course, in the meantime, the callback may have put some sats
+             in, so
+             so check for that, too, to avoid a race condition. */
+          /* FIXME - this does not seem to fix any race condition. */
+          if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) {
+             blioSetIsInputEmpty( blio, false );
+             /* FIXME - why check? ret has not been set? */
+             if( ret )
+                return ret;
+          }
+#endif
+       }
+    }
+
+    /*   Report either paNoError or paInputOverflowed. */
+    /*   may also want to report other errors, but this is non-standard. */
+    /* FIXME should not clobber ret, use if(blio->statusFlags & paInputOverflow) */
+    ret = blio->statusFlags & paInputOverflow;
+
+    /* report underflow only once: */
+    if( ret ) {
+       OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags );
+       ret = paInputOverflowed;
+    }
+
+    return ret;
+}
+
+
+PaError WriteStream( PaStream* stream,
+                            const void *buffer,
+                            unsigned long framesRequested )
+{
+    PaMacCoreStream *macStream = (PaMacCoreStream*)stream;
+    PaMacBlio *blio = &macStream->blio;
+    char *cbuf = (char *) buffer;
+    PaError ret = paNoError;
+    VVDBUG(("WriteStream()\n"));
+
+    while( framesRequested > 0 && macStream->state != STOPPING ) {
+        ring_buffer_size_t framesAvailable;
+        ring_buffer_size_t framesToTransfer;
+        ring_buffer_size_t framesTransferred;
+
+       do {
+          framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
+/*
+          printf( "Write Buffer is %%%g full: %ld of %ld.\n",
+                  100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize,
+                  framesAvailable, blio->outputRingBuffer.bufferSize );
+*/
+          if( framesAvailable == 0 ) {
+#ifdef PA_MAC_BLIO_MUTEX
+             /*block while full*/
+             ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
+             if( ret )
+                return ret;
+             while( blio->isOutputFull ) {
+                ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) );
+                if( ret )
+                   return ret;
+             }
+             ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
+             if( ret )
+                return ret;
+#else
+             Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
+#endif
+          }
+       } while( framesAvailable == 0 && macStream->state != STOPPING );
+
+       if( macStream->state == STOPPING )
+       {
+           break;
+       }
+
+       framesToTransfer = MIN( framesAvailable, framesRequested );
+       framesTransferred = PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, framesToTransfer );
+       cbuf += framesTransferred * blio->outputSampleSizeActual * blio->outChan;
+       framesRequested -= framesTransferred;
+
+#ifdef PA_MAC_BLIO_MUTEX
+       if( framesToTransfer == framesAvailable ) {
+          /* we just filled up the buffer, so we need to mark it as filled. */
+          ret = blioSetIsOutputFull( blio, true );
+          if( ret )
+             return ret;
+          /* of course, in the meantime, we may have emptied the buffer, so
+             so check for that, too, to avoid a race condition. */
+          if( PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ) ) {
+             blioSetIsOutputFull( blio, false );
+              /* FIXME remove or review this code, does not fix race, ret not set! */
+             if( ret )
+                return ret;
+          }
+       }
+#endif
+    }
+
+    if ( macStream->state == STOPPING )
+    {
+        ret = paInternalError;
+    }
+    else if (ret == paNoError )
+    {
+        /*   Test for underflow. */
+        ret = blio->statusFlags & paOutputUnderflow;
+
+        /* report underflow only once: */
+        if( ret )
+        {
+            OSAtomicAnd32( (uint32_t)(~paOutputUnderflow), &blio->statusFlags );
+            ret = paOutputUnderflowed;
+        }
+    }
+
+    return ret;
+}
+
+/*
+ * Wait until the data in the buffer has finished playing.
+ */
+PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate,
+                                        size_t framesPerBuffer )
+{
+    PaError result = paNoError;
+    if( blio->outputRingBuffer.buffer ) {
+        ring_buffer_size_t framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
+
+        /* Calculate when we should give up waiting. To be safe wait for two extra periods. */
+        PaTime now = PaUtil_GetTime();
+        PaTime startTime = now;
+        PaTime timeoutTime = startTime + (framesLeft + (2 * framesPerBuffer)) / sampleRate;
+
+        long msecPerBuffer = 1 + (long)( 1000.0 * framesPerBuffer / sampleRate);
+        while( framesLeft > 0 && now < timeoutTime ) {
+            VDBUG(( "waitUntilBlioWriteBufferIsFlushed: framesLeft = %d, framesPerBuffer = %ld\n",
+                  framesLeft, framesPerBuffer ));
+            Pa_Sleep( msecPerBuffer );
+            framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
+            now = PaUtil_GetTime();
+        }
+
+        if( framesLeft > 0 )
+        {
+            VDBUG(( "waitUntilBlioWriteBufferIsFlushed: TIMED OUT - framesLeft = %d\n", framesLeft ));
+            result = paTimedOut;
+        }
+    }
+    return result;
+}
+
+signed long GetStreamReadAvailable( PaStream* stream )
+{
+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+    VVDBUG(("GetStreamReadAvailable()\n"));
+
+    return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
+}
+
+
+signed long GetStreamWriteAvailable( PaStream* stream )
+{
+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+    VVDBUG(("GetStreamWriteAvailable()\n"));
+
+    return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
+}
+
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
new file mode 100644 (file)
index 0000000..c994f09
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * Internal blocking interfaces for PortAudio Apple AUHAL implementation
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#ifndef PA_MAC_CORE_BLOCKING_H_
+#define PA_MAC_CORE_BLOCKING_H_
+
+#include "pa_ringbuffer.h"
+#include "portaudio.h"
+#include "pa_mac_core_utilities.h"
+
+/*
+ * Number of milliseconds to busy wait while waiting for data in blocking calls.
+ */
+#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5)
+/*
+ * Define exactly one of these blocking methods
+ * PA_MAC_BLIO_MUTEX is not actively maintained.
+ */
+#define PA_MAC_BLIO_BUSY_WAIT
+/*
+#define PA_MAC_BLIO_MUTEX
+*/
+
+typedef struct {
+    PaUtilRingBuffer inputRingBuffer;
+    PaUtilRingBuffer outputRingBuffer;
+    ring_buffer_size_t ringBufferFrames;
+    PaSampleFormat inputSampleFormat;
+    size_t inputSampleSizeActual;
+    size_t inputSampleSizePow2;
+    PaSampleFormat outputSampleFormat;
+    size_t outputSampleSizeActual;
+    size_t outputSampleSizePow2;
+
+    int inChan;
+    int outChan;
+
+    //PaStreamCallbackFlags statusFlags;
+    uint32_t statusFlags;
+    PaError errors;
+
+    /* Here we handle blocking, using condition variables. */
+#ifdef  PA_MAC_BLIO_MUTEX
+    volatile bool isInputEmpty;
+    pthread_mutex_t inputMutex;
+    pthread_cond_t inputCond;
+
+    volatile bool isOutputFull;
+    pthread_mutex_t outputMutex;
+    pthread_cond_t outputCond;
+#endif
+}
+PaMacBlio;
+
+/*
+ * These functions operate on condition and related variables.
+ */
+
+PaError initializeBlioRingBuffers(
+                                       PaMacBlio *blio,
+                                       PaSampleFormat inputSampleFormat,
+                                       PaSampleFormat outputSampleFormat,
+                                       long ringBufferSizeInFrames,
+                                       int inChan,
+                                       int outChan );
+PaError destroyBlioRingBuffers( PaMacBlio *blio );
+PaError resetBlioRingBuffers( PaMacBlio *blio );
+
+int BlioCallback(
+        const void *input, void *output,
+        unsigned long frameCount,
+        const PaStreamCallbackTimeInfo* timeInfo,
+        PaStreamCallbackFlags statusFlags,
+        void *userData );
+
+PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate,
+                                        size_t framesPerBuffer );
+
+#endif /*PA_MAC_CORE_BLOCKING_H_*/
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
new file mode 100644 (file)
index 0000000..14e3d07
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ * Internal interfaces for PortAudio Apple AUHAL implementation
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file pa_mac_core
+ @ingroup hostapi_src
+ @author Bjorn Roche
+ @brief AUHAL implementation of PortAudio
+*/
+
+#ifndef PA_MAC_CORE_INTERNAL_H__
+#define PA_MAC_CORE_INTERNAL_H__
+
+#include <CoreAudio/CoreAudio.h>
+#include <CoreServices/CoreServices.h>
+#include <AudioUnit/AudioUnit.h>
+#include <AudioToolbox/AudioToolbox.h>
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_allocation.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_ringbuffer.h"
+
+#include "pa_mac_core_blocking.h"
+
+/* function prototypes */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)
+
+PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+signed long GetStreamReadAvailable( PaStream* stream );
+signed long GetStreamWriteAvailable( PaStream* stream );
+/* PaMacAUHAL - host api datastructure specific to this implementation */
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    /* implementation specific data goes here */
+    long devCount;
+    AudioDeviceID *devIds; /*array of all audio devices*/
+    AudioDeviceID defaultIn;
+    AudioDeviceID defaultOut;
+}
+PaMacAUHAL;
+
+typedef struct PaMacCoreDeviceProperties
+{
+    /* Values in Frames from property queries. */
+    UInt32 safetyOffset;
+    UInt32 bufferFrameSize;
+    // UInt32 streamLatency; // Seems to be the same as deviceLatency!?
+    UInt32 deviceLatency;
+    /* Current device sample rate. May change! 
+       These are initialized to the nominal device sample rate, 
+       and updated with the actual sample rate, when/where available. 
+       Note that these are the *device* sample rates, prior to any required 
+       SR conversion. */
+    Float64 sampleRate;
+    Float64 samplePeriod; // reciprocal
+}
+PaMacCoreDeviceProperties;
+
+/* stream data structure specifically for this implementation */
+typedef struct PaMacCoreStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    /* implementation specific data goes here */
+    bool bufferProcessorIsInitialized;
+    AudioUnit inputUnit;
+    AudioUnit outputUnit;
+    AudioDeviceID inputDevice;
+    AudioDeviceID outputDevice;
+    size_t userInChan;
+    size_t userOutChan;
+    size_t inputFramesPerBuffer;
+    size_t outputFramesPerBuffer;
+    PaMacBlio blio;
+    /* We use this ring buffer when input and out devs are different. */
+    PaUtilRingBuffer inputRingBuffer;
+    /* We may need to do SR conversion on input. */
+    AudioConverterRef inputSRConverter;
+    /* We need to preallocate an inputBuffer for reading data. */
+    AudioBufferList inputAudioBufferList;
+    AudioTimeStamp startTime;
+    /* FIXME: instead of volatile, these should be properly memory barriered */
+    volatile uint32_t xrunFlags; /*PaStreamCallbackFlags*/
+    volatile enum {
+       STOPPED          = 0, /* playback is completely stopped,
+                                and the user has called StopStream(). */
+       CALLBACK_STOPPED = 1, /* callback has requested stop,
+                                but user has not yet called StopStream(). */
+       STOPPING         = 2, /* The stream is in the process of closing
+                                because the user has called StopStream.
+                                This state is just used internally;
+                                externally it is indistinguishable from
+                                ACTIVE.*/
+       ACTIVE           = 3  /* The stream is active and running. */
+    } state;
+    double sampleRate;
+    PaMacCoreDeviceProperties  inputProperties;
+    PaMacCoreDeviceProperties  outputProperties;
+    
+       /* data updated by main thread and notifications, protected by timingInformationMutex */
+       int timingInformationMutexIsInitialized;
+       pthread_mutex_t timingInformationMutex;
+
+    /* These are written by the PA thread or from CoreAudio callbacks. Protected by the mutex. */
+    Float64 timestampOffsetCombined;
+    Float64 timestampOffsetInputDevice;
+    Float64 timestampOffsetOutputDevice;
+       
+       /* Offsets in seconds to be applied to Apple timestamps to convert them to PA timestamps.
+     * While the io proc is active, the following values are only accessed and manipulated by the ioproc */
+    Float64 timestampOffsetCombined_ioProcCopy;
+    Float64 timestampOffsetInputDevice_ioProcCopy;
+    Float64 timestampOffsetOutputDevice_ioProcCopy;
+    
+}
+PaMacCoreStream;
+
+#endif /* PA_MAC_CORE_INTERNAL_H__ */
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c
new file mode 100644 (file)
index 0000000..0e9b357
--- /dev/null
@@ -0,0 +1,913 @@
+/*
+ * $Id$
+ * pa_mac_core.c
+ * Implementation of PortAudio for Mac OS X CoreAudio       
+ *                                                                                         
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Authors: Ross Bencina and Phil Burk
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+#include <CoreAudio/CoreAudio.h>
+#include <AudioToolbox/AudioToolbox.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <assert.h>
+
+#include "portaudio.h"
+#include "pa_trace.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+
+// =====  constants  =====
+
+// =====  structs  =====
+#pragma mark structs
+
+// PaMacCoreHostApiRepresentation - host api datastructure specific to this implementation
+typedef struct PaMacCore_HAR
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+    
+    PaUtilAllocationGroup *allocations;
+    AudioDeviceID *macCoreDeviceIds;
+}
+PaMacCoreHostApiRepresentation;
+
+typedef struct PaMacCore_DI
+{
+    PaDeviceInfo inheritedDeviceInfo;
+}
+PaMacCoreDeviceInfo;
+
+// PaMacCoreStream - a stream data structure specifically for this implementation
+typedef struct PaMacCore_S
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+    
+    int primeStreamUsingCallback;
+    
+    AudioDeviceID inputDevice;
+    AudioDeviceID outputDevice;
+    
+    // Processing thread management --------------
+//    HANDLE abortEvent;
+//    HANDLE processingThread;
+//    DWORD processingThreadId;
+    
+    char throttleProcessingThreadOnOverload; // 0 -> don't throtte, non-0 -> throttle
+    int processingThreadPriority;
+    int highThreadPriority;
+    int throttledThreadPriority;
+    unsigned long throttledSleepMsecs;
+    
+    int isStopped;
+    volatile int isActive;
+    volatile int stopProcessing; // stop thread once existing buffers have been returned
+    volatile int abortProcessing; // stop thread immediately
+    
+//    DWORD allBuffersDurationMs; // used to calculate timeouts
+}
+PaMacCoreStream;
+
+// Data needed by the CoreAudio callback functions
+typedef struct PaMacCore_CD
+{
+    PaMacCoreStream *stream;
+    PaStreamCallback *callback;
+    void *userData;
+    PaUtilConverter *inputConverter;
+    PaUtilConverter *outputConverter;
+    void *inputBuffer;
+    void *outputBuffer;
+    int inputChannelCount;
+    int outputChannelCount;
+    PaSampleFormat inputSampleFormat;
+    PaSampleFormat outputSampleFormat;
+    PaUtilTriangularDitherGenerator *ditherGenerator;
+}
+PaMacClientData;
+
+// =====  CoreAudio-PortAudio bridge functions =====
+#pragma mark CoreAudio-PortAudio bridge functions
+
+// Maps CoreAudio OSStatus codes to PortAudio PaError codes
+static PaError conv_err(OSStatus error)
+{
+    PaError result;
+    
+    switch (error) {
+        case kAudioHardwareNoError:
+            result = paNoError; break;
+        case kAudioHardwareNotRunningError:
+            result = paInternalError; break;
+        case kAudioHardwareUnspecifiedError:
+            result = paInternalError; break;
+        case kAudioHardwareUnknownPropertyError:
+            result = paInternalError; break;
+        case kAudioHardwareBadPropertySizeError:
+            result = paInternalError; break;
+        case kAudioHardwareIllegalOperationError:
+            result = paInternalError; break;
+        case kAudioHardwareBadDeviceError:
+            result = paInvalidDevice; break;
+        case kAudioHardwareBadStreamError:
+            result = paBadStreamPtr; break;
+        case kAudioHardwareUnsupportedOperationError:
+            result = paInternalError; break;
+        case kAudioDeviceUnsupportedFormatError:
+            result = paSampleFormatNotSupported; break;
+        case kAudioDevicePermissionsError:
+            result = paDeviceUnavailable; break;
+        default:
+            result = paInternalError;
+    }
+    
+    return result;
+}
+
+/* This function is unused
+static AudioStreamBasicDescription *InitializeStreamDescription(const PaStreamParameters *parameters, double sampleRate)
+{
+    struct AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(sizeof(AudioStreamBasicDescription));
+    streamDescription->mSampleRate = sampleRate;
+    streamDescription->mFormatID = kAudioFormatLinearPCM;
+    streamDescription->mFormatFlags = 0;
+    streamDescription->mFramesPerPacket = 1;
+    
+    if (parameters->sampleFormat & paNonInterleaved) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsNonInterleaved;
+        streamDescription->mChannelsPerFrame = 1;
+        streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat);
+        streamDescription->mBytesPerPacket = Pa_GetSampleSize(parameters->sampleFormat);
+    }
+    else {
+        streamDescription->mChannelsPerFrame = parameters->channelCount;
+    }
+    
+    streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat) * streamDescription->mChannelsPerFrame;
+    streamDescription->mBytesPerPacket = streamDescription->mBytesPerFrame * streamDescription->mFramesPerPacket;
+    
+    if (parameters->sampleFormat & paFloat32) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsFloat;
+        streamDescription->mBitsPerChannel = 32;
+    }
+    else if (parameters->sampleFormat & paInt32) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+        streamDescription->mBitsPerChannel = 32;
+    }
+    else if (parameters->sampleFormat & paInt24) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+        streamDescription->mBitsPerChannel = 24;
+    }
+    else if (parameters->sampleFormat & paInt16) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+        streamDescription->mBitsPerChannel = 16;
+    }
+    else if (parameters->sampleFormat & paInt8) {
+        streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+        streamDescription->mBitsPerChannel = 8;
+    }    
+    else if (parameters->sampleFormat & paInt32) {
+        streamDescription->mBitsPerChannel = 8;
+    }
+    
+    return streamDescription;
+}
+*/
+
+static PaStreamCallbackTimeInfo *InitializeTimeInfo(const AudioTimeStamp* now, const AudioTimeStamp* inputTime, const AudioTimeStamp* outputTime)
+{
+    PaStreamCallbackTimeInfo *timeInfo = PaUtil_AllocateMemory(sizeof(PaStreamCallbackTimeInfo));
+    
+    timeInfo->inputBufferAdcTime = inputTime->mSampleTime;
+    timeInfo->currentTime = now->mSampleTime;
+    timeInfo->outputBufferDacTime = outputTime->mSampleTime;
+    
+    return timeInfo;
+}
+
+// =====  support functions  =====
+#pragma mark support functions
+
+static void CleanUp(PaMacCoreHostApiRepresentation *macCoreHostApi)
+{
+    if( macCoreHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( macCoreHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( macCoreHostApi->allocations );
+    }
+    
+    PaUtil_FreeMemory( macCoreHostApi );    
+}
+
+static PaError GetChannelInfo(PaDeviceInfo *deviceInfo, AudioDeviceID macCoreDeviceId, int isInput)
+{
+    UInt32 propSize;
+    PaError err = paNoError;
+    UInt32 i;
+    int numChannels = 0;
+    AudioBufferList *buflist;
+
+    err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));
+    buflist = PaUtil_AllocateMemory(propSize);
+    err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
+    if (!err) {
+        for (i = 0; i < buflist->mNumberBuffers; ++i) {
+            numChannels += buflist->mBuffers[i].mNumberChannels;
+        }
+               
+               if (isInput)
+                       deviceInfo->maxInputChannels = numChannels;
+               else
+                       deviceInfo->maxOutputChannels = numChannels;
+               
+        int frameLatency;
+        propSize = sizeof(UInt32);
+        err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency));
+        if (!err) {
+            double secondLatency = frameLatency / deviceInfo->defaultSampleRate;
+            if (isInput) {
+                deviceInfo->defaultLowInputLatency = secondLatency;
+                deviceInfo->defaultHighInputLatency = secondLatency;
+            }
+            else {
+                deviceInfo->defaultLowOutputLatency = secondLatency;
+                deviceInfo->defaultHighOutputLatency = secondLatency;
+            }
+        }
+    }
+    PaUtil_FreeMemory(buflist);
+    
+    return err;
+}
+
+static PaError InitializeDeviceInfo(PaMacCoreDeviceInfo *macCoreDeviceInfo,  AudioDeviceID macCoreDeviceId, PaHostApiIndex hostApiIndex )
+{
+    PaDeviceInfo *deviceInfo = &macCoreDeviceInfo->inheritedDeviceInfo;
+    deviceInfo->structVersion = 2;
+    deviceInfo->hostApi = hostApiIndex;
+    
+    PaError err = paNoError;
+    UInt32 propSize;
+
+    err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));
+    // FIXME: this allocation should be part of the allocations group
+    char *name = PaUtil_AllocateMemory(propSize);
+    err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
+    if (!err) {
+        deviceInfo->name = name;
+    }
+    
+    Float64 sampleRate;
+    propSize = sizeof(Float64);
+    err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
+    if (!err) {
+        deviceInfo->defaultSampleRate = sampleRate;
+    }
+
+
+    // Get channel info
+    err = GetChannelInfo(deviceInfo, macCoreDeviceId, 1);
+    err = GetChannelInfo(deviceInfo, macCoreDeviceId, 0);
+
+    return err;
+}
+
+static PaError InitializeDeviceInfos( PaMacCoreHostApiRepresentation *macCoreHostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *hostApi;
+    PaMacCoreDeviceInfo *deviceInfoArray;
+
+    // initialise device counts and default devices under the assumption that there are no devices. These values are incremented below if and when devices are successfully initialized.
+    hostApi = &macCoreHostApi->inheritedHostApiRep;
+    hostApi->info.deviceCount = 0;
+    hostApi->info.defaultInputDevice = paNoDevice;
+    hostApi->info.defaultOutputDevice = paNoDevice;
+    
+    UInt32 propsize;
+    AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propsize, NULL);
+    int numDevices = propsize / sizeof(AudioDeviceID);
+    hostApi->info.deviceCount = numDevices;
+    if (numDevices > 0) {
+        hostApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                                            macCoreHostApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
+        if( !hostApi->deviceInfos )
+        {
+            return paInsufficientMemory;
+        }
+
+        // allocate all device info structs in a contiguous block
+        deviceInfoArray = (PaMacCoreDeviceInfo*)PaUtil_GroupAllocateMemory(
+                                macCoreHostApi->allocations, sizeof(PaMacCoreDeviceInfo) * numDevices );
+        if( !deviceInfoArray )
+        {
+            return paInsufficientMemory;
+        }
+        
+        macCoreHostApi->macCoreDeviceIds = PaUtil_GroupAllocateMemory(macCoreHostApi->allocations, propsize);
+        AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propsize, macCoreHostApi->macCoreDeviceIds);
+
+        AudioDeviceID defaultInputDevice, defaultOutputDevice;
+        propsize = sizeof(AudioDeviceID);
+        AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &propsize, &defaultInputDevice);
+        AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propsize, &defaultOutputDevice);
+        
+        UInt32 i;
+        for (i = 0; i < numDevices; ++i) {
+            if (macCoreHostApi->macCoreDeviceIds[i] == defaultInputDevice) {
+                hostApi->info.defaultInputDevice = i;
+            }
+            if (macCoreHostApi->macCoreDeviceIds[i] == defaultOutputDevice) {
+                hostApi->info.defaultOutputDevice = i;
+            }
+            InitializeDeviceInfo(&deviceInfoArray[i], macCoreHostApi->macCoreDeviceIds[i], hostApiIndex);
+            hostApi->deviceInfos[i] = &(deviceInfoArray[i].inheritedDeviceInfo);      
+        }
+    }
+
+    return result;
+}
+
+static OSStatus CheckFormat(AudioDeviceID macCoreDeviceId, const PaStreamParameters *parameters, double sampleRate, int isInput)
+{
+    UInt32 propSize = sizeof(AudioStreamBasicDescription);
+    AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(propSize);
+
+    streamDescription->mSampleRate = sampleRate;
+    streamDescription->mFormatID = 0;
+    streamDescription->mFormatFlags = 0;
+    streamDescription->mBytesPerPacket = 0;
+    streamDescription->mFramesPerPacket = 0;
+    streamDescription->mBytesPerFrame = 0;
+    streamDescription->mChannelsPerFrame = 0;
+    streamDescription->mBitsPerChannel = 0;
+    streamDescription->mReserved = 0;
+
+    OSStatus result = AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamFormatSupported, &propSize, streamDescription);
+    PaUtil_FreeMemory(streamDescription);
+    return result;
+}
+
+static OSStatus CopyInputData(PaMacClientData* destination, const AudioBufferList *source, unsigned long frameCount)
+{
+    int frameSpacing, channelSpacing;
+    if (destination->inputSampleFormat & paNonInterleaved) {
+        frameSpacing = 1;
+        channelSpacing = destination->inputChannelCount;
+    }
+    else {
+        frameSpacing = destination->inputChannelCount;
+        channelSpacing = 1;
+    }
+    
+    AudioBuffer const *inputBuffer = &source->mBuffers[0];
+    void *coreAudioBuffer = inputBuffer->mData;
+    void *portAudioBuffer = destination->inputBuffer;
+    UInt32 i, streamNumber, streamChannel;
+    for (i = streamNumber = streamChannel = 0; i < destination->inputChannelCount; ++i, ++streamChannel) {
+        if (streamChannel >= inputBuffer->mNumberChannels) {
+            ++streamNumber;
+            inputBuffer = &source->mBuffers[streamNumber];
+            coreAudioBuffer = inputBuffer->mData;
+            streamChannel = 0;
+        }
+        destination->inputConverter(portAudioBuffer, frameSpacing, coreAudioBuffer, inputBuffer->mNumberChannels, frameCount, destination->ditherGenerator);
+        coreAudioBuffer += sizeof(Float32);
+        portAudioBuffer += Pa_GetSampleSize(destination->inputSampleFormat) * channelSpacing;
+    }
+    return noErr;
+}
+
+static OSStatus CopyOutputData(AudioBufferList* destination, PaMacClientData *source, unsigned long frameCount)
+{
+    int frameSpacing, channelSpacing;
+    if (source->outputSampleFormat & paNonInterleaved) {
+        frameSpacing = 1;
+        channelSpacing = source->outputChannelCount;
+    }
+    else {
+        frameSpacing = source->outputChannelCount;
+        channelSpacing = 1;
+    }
+    
+    AudioBuffer *outputBuffer = &destination->mBuffers[0];
+    void *coreAudioBuffer = outputBuffer->mData;
+    void *portAudioBuffer = source->outputBuffer;
+    UInt32 i, streamNumber, streamChannel;
+    for (i = streamNumber = streamChannel = 0; i < source->outputChannelCount; ++i, ++streamChannel) {
+        if (streamChannel >= outputBuffer->mNumberChannels) {
+            ++streamNumber;
+            outputBuffer = &destination->mBuffers[streamNumber];
+            coreAudioBuffer = outputBuffer->mData;
+            streamChannel = 0;
+        }
+        source->outputConverter(coreAudioBuffer, outputBuffer->mNumberChannels, portAudioBuffer, frameSpacing, frameCount, NULL);
+        coreAudioBuffer += sizeof(Float32);
+        portAudioBuffer += Pa_GetSampleSize(source->outputSampleFormat) * channelSpacing;
+    }
+    return noErr;
+}
+
+static OSStatus AudioIOProc( AudioDeviceID inDevice,
+                      const AudioTimeStamp* inNow,
+                      const AudioBufferList* inInputData,
+                      const AudioTimeStamp* inInputTime,
+                      AudioBufferList* outOutputData, 
+                      const AudioTimeStamp* inOutputTime,
+                      void* inClientData)
+{
+    PaMacClientData *clientData = (PaMacClientData *)inClientData;
+    PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+    
+    PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+    
+    AudioBuffer *outputBuffer = &outOutputData->mBuffers[0];
+    unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32));
+
+    if (clientData->inputBuffer) {
+        CopyInputData(clientData, inInputData, frameCount);
+    }
+    PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+    if (clientData->outputBuffer) {
+        CopyOutputData(outOutputData, clientData, frameCount);
+    }
+
+    PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+    
+    if (result == paComplete || result == paAbort) {
+        Pa_StopStream(clientData->stream);
+    }
+
+    PaUtil_FreeMemory( timeInfo );
+    return noErr;
+}
+
+// This is not for input-only streams, this is for streams where the input device is different from the output device
+static OSStatus AudioInputProc( AudioDeviceID inDevice,
+                         const AudioTimeStamp* inNow,
+                         const AudioBufferList* inInputData,
+                         const AudioTimeStamp* inInputTime,
+                         AudioBufferList* outOutputData, 
+                         const AudioTimeStamp* inOutputTime,
+                         void* inClientData)
+{
+    PaMacClientData *clientData = (PaMacClientData *)inClientData;
+    PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+
+    PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+
+    AudioBuffer const *inputBuffer = &inInputData->mBuffers[0];
+    unsigned long frameCount = inputBuffer->mDataByteSize / (inputBuffer->mNumberChannels * sizeof(Float32));
+
+    CopyInputData(clientData, inInputData, frameCount);
+    PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+    
+    PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+    if( result == paComplete || result == paAbort )
+       Pa_StopStream(clientData->stream);
+    PaUtil_FreeMemory( timeInfo );
+    return noErr;
+}
+
+// This is not for output-only streams, this is for streams where the input device is different from the output device
+static OSStatus AudioOutputProc( AudioDeviceID inDevice,
+                          const AudioTimeStamp* inNow,
+                          const AudioBufferList* inInputData,
+                          const AudioTimeStamp* inInputTime,
+                          AudioBufferList* outOutputData, 
+                          const AudioTimeStamp* inOutputTime,
+                          void* inClientData)
+{
+    PaMacClientData *clientData = (PaMacClientData *)inClientData;
+    //PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+
+    PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+
+    AudioBuffer *outputBuffer = &outOutputData->mBuffers[0];
+    unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32));
+
+    //clientData->callback(NULL, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+
+    CopyOutputData(outOutputData, clientData, frameCount);
+
+    PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+    return noErr;
+}
+
+static PaError SetSampleRate(AudioDeviceID device, double sampleRate, int isInput)
+{
+    PaError result = paNoError;
+    
+    double actualSampleRate;
+    UInt32 propSize = sizeof(double);
+    result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyNominalSampleRate, propSize, &sampleRate));
+    
+    result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyNominalSampleRate, &propSize, &actualSampleRate));
+    
+    if (result == paNoError && actualSampleRate != sampleRate) {
+        result = paInvalidSampleRate;
+    }
+    
+    return result;    
+}
+
+static PaError SetFramesPerBuffer(AudioDeviceID device, unsigned long framesPerBuffer, int isInput)
+{
+    PaError result = paNoError;
+    UInt32 preferredFramesPerBuffer = framesPerBuffer;
+    //    while (preferredFramesPerBuffer > UINT32_MAX) {
+    //        preferredFramesPerBuffer /= 2;
+    //    }
+    
+    UInt32 actualFramesPerBuffer;
+    UInt32 propSize = sizeof(UInt32);
+    result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyBufferFrameSize, propSize, &preferredFramesPerBuffer));
+    
+    result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &actualFramesPerBuffer));
+    
+    if (result != paNoError) {
+        // do nothing
+    }
+    else if (actualFramesPerBuffer > framesPerBuffer) {
+        result = paBufferTooSmall;
+    }
+    else if (actualFramesPerBuffer < framesPerBuffer) {
+        result = paBufferTooBig;
+    }
+    
+    return result;    
+}
+    
+static PaError SetUpUnidirectionalStream(AudioDeviceID device, double sampleRate, unsigned long framesPerBuffer, int isInput)
+{
+    PaError err = paNoError;
+    err = SetSampleRate(device, sampleRate, isInput);
+    if( err == paNoError )
+        err = SetFramesPerBuffer(device, framesPerBuffer, isInput);
+    return err;
+}
+
+// =====  PortAudio functions  =====
+#pragma mark PortAudio functions
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+    
+    PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+    
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi;
+    
+    CleanUp(macCoreHostApi);
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi;
+    PaDeviceInfo *deviceInfo;
+    
+    PaError result = paNoError;
+    if (inputParameters) {
+        deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
+        if (inputParameters->channelCount > deviceInfo->maxInputChannels)
+            result = paInvalidChannelCount;
+        else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[inputParameters->device], inputParameters, sampleRate, 1) != kAudioHardwareNoError) {
+            result = paInvalidSampleRate;
+        }
+    }
+    if (outputParameters && result == paNoError) {
+        deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
+        if (outputParameters->channelCount > deviceInfo->maxOutputChannels)
+            result = paInvalidChannelCount;
+        else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[outputParameters->device], outputParameters, sampleRate, 0) != kAudioHardwareNoError) {
+            result = paInvalidSampleRate;
+        }
+    }
+
+    return result;
+}
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError err = paNoError;
+    PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)hostApi;
+    PaMacCoreStream *stream = PaUtil_AllocateMemory(sizeof(PaMacCoreStream));
+    stream->isActive = 0;
+    stream->isStopped = 1;
+    stream->inputDevice = kAudioDeviceUnknown;
+    stream->outputDevice = kAudioDeviceUnknown;
+    
+    PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                           ( (streamCallback)
+                                             ? &macCoreHostApi->callbackStreamInterface
+                                             : &macCoreHostApi->blockingStreamInterface ),
+                                           streamCallback, userData );
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+    
+    *s = (PaStream*)stream;
+    PaMacClientData *clientData = PaUtil_AllocateMemory(sizeof(PaMacClientData));
+    clientData->stream = stream;
+    clientData->callback = streamCallback;
+    clientData->userData = userData;
+    clientData->inputBuffer = 0;
+    clientData->outputBuffer = 0;
+    clientData->ditherGenerator = PaUtil_AllocateMemory(sizeof(PaUtilTriangularDitherGenerator));
+    PaUtil_InitializeTriangularDitherState(clientData->ditherGenerator);
+    
+    if (inputParameters != NULL) {
+        stream->inputDevice = macCoreHostApi->macCoreDeviceIds[inputParameters->device];
+        clientData->inputConverter = PaUtil_SelectConverter(paFloat32, inputParameters->sampleFormat, streamFlags);
+        clientData->inputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(inputParameters->sampleFormat) * framesPerBuffer * inputParameters->channelCount);
+        clientData->inputChannelCount = inputParameters->channelCount;
+        clientData->inputSampleFormat = inputParameters->sampleFormat;
+        err = SetUpUnidirectionalStream(stream->inputDevice, sampleRate, framesPerBuffer, 1);
+    }
+    
+    if (err == paNoError && outputParameters != NULL) {
+        stream->outputDevice = macCoreHostApi->macCoreDeviceIds[outputParameters->device];
+        clientData->outputConverter = PaUtil_SelectConverter(outputParameters->sampleFormat, paFloat32, streamFlags);
+        clientData->outputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(outputParameters->sampleFormat) * framesPerBuffer * outputParameters->channelCount);
+        clientData->outputChannelCount = outputParameters->channelCount;
+        clientData->outputSampleFormat = outputParameters->sampleFormat;
+        err = SetUpUnidirectionalStream(stream->outputDevice, sampleRate, framesPerBuffer, 0);
+    }
+
+    if (inputParameters == NULL || outputParameters == NULL || stream->inputDevice == stream->outputDevice) {
+        AudioDeviceID device = (inputParameters == NULL) ? stream->outputDevice : stream->inputDevice;
+
+        AudioDeviceAddIOProc(device, AudioIOProc, clientData);
+    }
+    else {
+        // using different devices for input and output
+        AudioDeviceAddIOProc(stream->inputDevice, AudioInputProc, clientData);
+        AudioDeviceAddIOProc(stream->outputDevice, AudioOutputProc, clientData);
+    }
+    
+    return err;
+}
+
+// Note: When CloseStream() is called, the multi-api layer ensures that the stream has already been stopped or aborted.
+static PaError CloseStream( PaStream* s )
+{
+    PaError err = paNoError;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+    if (stream->inputDevice != kAudioDeviceUnknown) {
+        if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+            err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioIOProc));
+        }
+        else {
+            err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioInputProc));
+            err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioOutputProc));
+        }
+    }
+    else {
+        err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioIOProc));
+    }
+    
+    return err;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+    PaError err = paNoError;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+    if (stream->inputDevice != kAudioDeviceUnknown) {
+        if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+            err = conv_err(AudioDeviceStart(stream->inputDevice, AudioIOProc));
+        }
+        else {
+            err = conv_err(AudioDeviceStart(stream->inputDevice, AudioInputProc));
+            err = conv_err(AudioDeviceStart(stream->outputDevice, AudioOutputProc));
+        }
+    }
+    else {
+        err = conv_err(AudioDeviceStart(stream->outputDevice, AudioIOProc));
+    }
+    
+    stream->isActive = 1;
+    stream->isStopped = 0;
+    return err;
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    PaError err = paNoError;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    
+    if (stream->inputDevice != kAudioDeviceUnknown) {
+        if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+            err = conv_err(AudioDeviceStop(stream->inputDevice, AudioIOProc));
+        }
+        else {
+            err = conv_err(AudioDeviceStop(stream->inputDevice, AudioInputProc));
+            err = conv_err(AudioDeviceStop(stream->outputDevice, AudioOutputProc));
+        }
+    }
+    else {
+        err = conv_err(AudioDeviceStop(stream->outputDevice, AudioIOProc));
+    }
+    
+    stream->isActive = 0;
+    stream->isStopped = 1;
+    return err;
+}    
+
+static PaError StopStream( PaStream *s )
+{
+    // TODO: this should be nicer than abort
+    return AbortStream(s);
+}
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    
+    return stream->isStopped;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+    return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    OSStatus err;
+    PaTime result;
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+    AudioTimeStamp *timeStamp = PaUtil_AllocateMemory(sizeof(AudioTimeStamp));
+    if (stream->inputDevice != kAudioDeviceUnknown) {
+        err = AudioDeviceGetCurrentTime(stream->inputDevice, timeStamp);
+    }
+    else {
+        err = AudioDeviceGetCurrentTime(stream->outputDevice, timeStamp);
+    }
+    
+    result = err ? 0 : timeStamp->mSampleTime;
+    PaUtil_FreeMemory(timeStamp);
+
+    return result;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+// As separate stream interfaces are used for blocking and callback streams, the following functions can be guaranteed to only be called for blocking streams.
+
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    return paInternalError;
+}
+
+
+static PaError WriteStream( PaStream* s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    return paInternalError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    return paInternalError;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    return paInternalError;
+}
+
+// HostAPI-specific initialization function
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaMacCoreHostApiRepresentation) );
+    if( !macCoreHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    
+    macCoreHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !macCoreHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    
+    *hostApi = &macCoreHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paCoreAudio;
+    (*hostApi)->info.name = "CoreAudio";
+
+    result = InitializeDeviceInfos(macCoreHostApi, hostApiIndex);
+    if (result != paNoError) {
+        goto error;
+    }
+    
+    // Set up the proper callbacks to this HostApi's functions
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+    
+    PaUtil_InitializeStreamInterface( &macCoreHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+    
+    PaUtil_InitializeStreamInterface( &macCoreHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+    
+    return result;
+    
+error:
+        if( macCoreHostApi ) {
+            CleanUp(macCoreHostApi);
+        }
+    
+    return result;
+}
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
new file mode 100644 (file)
index 0000000..63e616f
--- /dev/null
@@ -0,0 +1,701 @@
+/*
+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include "pa_mac_core_utilities.h"
+#include "pa_mac_core_internal.h"
+#include <libkern/OSAtomic.h>
+#include <strings.h>
+#include <pthread.h>
+#include <sys/time.h>
+
+PaError PaMacCore_SetUnixError( int err, int line )
+{
+   PaError ret;
+   const char *errorText;
+
+   if( err == 0 )
+   {
+      return paNoError;
+   }
+
+   ret = paNoError;
+   errorText = strerror( err );
+
+   /** Map Unix error to PaError. Pretty much the only one that maps
+       is ENOMEM. */
+   if( err == ENOMEM )
+      ret = paInsufficientMemory;
+   else
+      ret = paInternalError;
+
+   DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));
+   PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );
+
+   return ret;
+}
+
+/*
+ * Translates MacOS generated errors into PaErrors
+ */
+PaError PaMacCore_SetError(OSStatus error, int line, int isError)
+{
+    /*FIXME: still need to handle possible ComponentResult values.*/
+    /*       unfortunately, they don't seem to be documented anywhere.*/
+    PaError result;
+    const char *errorType; 
+    const char *errorText;
+    
+    switch (error) {
+    case kAudioHardwareNoError:
+        return paNoError;
+    case kAudioHardwareNotRunningError:
+        errorText = "Audio Hardware Not Running";
+        result = paInternalError; break;
+    case kAudioHardwareUnspecifiedError: 
+        errorText = "Unspecified Audio Hardware Error";
+        result = paInternalError; break;
+    case kAudioHardwareUnknownPropertyError:
+        errorText = "Audio Hardware: Unknown Property";
+        result = paInternalError; break;
+    case kAudioHardwareBadPropertySizeError:
+        errorText = "Audio Hardware: Bad Property Size";
+        result = paInternalError; break;
+    case kAudioHardwareIllegalOperationError: 
+        errorText = "Audio Hardware: Illegal Operation";
+        result = paInternalError; break;
+    case kAudioHardwareBadDeviceError:
+        errorText = "Audio Hardware: Bad Device";
+        result = paInvalidDevice; break;
+    case kAudioHardwareBadStreamError:
+        errorText = "Audio Hardware: BadStream";
+        result = paBadStreamPtr; break;
+    case kAudioHardwareUnsupportedOperationError:
+        errorText = "Audio Hardware: Unsupported Operation";
+        result = paInternalError; break;
+    case kAudioDeviceUnsupportedFormatError:
+        errorText = "Audio Device: Unsupported Format";
+        result = paSampleFormatNotSupported; break;
+    case kAudioDevicePermissionsError:
+        errorText = "Audio Device: Permissions Error";
+        result = paDeviceUnavailable; break;
+    /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
+    case kAudioUnitErr_InvalidProperty:
+        errorText = "Audio Unit: Invalid Property";
+        result = paInternalError; break;
+    case kAudioUnitErr_InvalidParameter:
+        errorText = "Audio Unit: Invalid Parameter";
+        result = paInternalError; break;
+    case kAudioUnitErr_NoConnection:
+        errorText = "Audio Unit: No Connection";
+        result = paInternalError; break;
+    case kAudioUnitErr_FailedInitialization:
+        errorText = "Audio Unit: Initialization Failed";
+        result = paInternalError; break;
+    case kAudioUnitErr_TooManyFramesToProcess:
+        errorText = "Audio Unit: Too Many Frames";
+        result = paInternalError; break;
+    case kAudioUnitErr_IllegalInstrument:
+        errorText = "Audio Unit: Illegal Instrument";
+        result = paInternalError; break;
+    case kAudioUnitErr_InstrumentTypeNotFound:
+        errorText = "Audio Unit: Instrument Type Not Found";
+        result = paInternalError; break;
+    case kAudioUnitErr_InvalidFile:
+        errorText = "Audio Unit: Invalid File";
+        result = paInternalError; break;
+    case kAudioUnitErr_UnknownFileType:
+        errorText = "Audio Unit: Unknown File Type";
+        result = paInternalError; break;
+    case kAudioUnitErr_FileNotSpecified:
+        errorText = "Audio Unit: File Not Specified";
+        result = paInternalError; break;
+    case kAudioUnitErr_FormatNotSupported:
+        errorText = "Audio Unit: Format Not Supported";
+        result = paInternalError; break;
+    case kAudioUnitErr_Uninitialized:
+        errorText = "Audio Unit: Unitialized";
+        result = paInternalError; break;
+    case kAudioUnitErr_InvalidScope:
+        errorText = "Audio Unit: Invalid Scope";
+        result = paInternalError; break;
+    case kAudioUnitErr_PropertyNotWritable:
+        errorText = "Audio Unit: PropertyNotWritable";
+        result = paInternalError; break;
+    case kAudioUnitErr_InvalidPropertyValue:
+        errorText = "Audio Unit: Invalid Property Value";
+        result = paInternalError; break;
+    case kAudioUnitErr_PropertyNotInUse:
+        errorText = "Audio Unit: Property Not In Use";
+        result = paInternalError; break;
+    case kAudioUnitErr_Initialized:
+        errorText = "Audio Unit: Initialized";
+        result = paInternalError; break;
+    case kAudioUnitErr_InvalidOfflineRender:
+        errorText = "Audio Unit: Invalid Offline Render";
+        result = paInternalError; break;
+    case kAudioUnitErr_Unauthorized:
+        errorText = "Audio Unit: Unauthorized";
+        result = paInternalError; break;
+    case kAudioUnitErr_CannotDoInCurrentContext:
+        errorText = "Audio Unit: cannot do in current context";
+        result = paInternalError; break;
+    default:
+        errorText = "Unknown Error";
+        result = paInternalError;
+    }
+
+    if (isError)
+        errorType = "Error";
+    else
+        errorType = "Warning";
+
+    char str[20];
+    // see if it appears to be a 4-char-code
+    *(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
+    if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4]))
+    {
+        str[0] = str[5] = '\'';
+        str[6] = '\0';
+    } else {
+        // no, format it as an integer
+        sprintf(str, "%d", (int)error);
+    }
+
+    DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText));
+
+    PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );
+
+    return result;
+}
+
+/*
+ * This function computes an appropriate ring buffer size given
+ * a requested latency (in seconds), sample rate and framesPerBuffer.
+ *
+ * The returned ringBufferSize is computed using the following
+ * constraints:
+ *   - it must be at least 4.
+ *   - it must be at least 3x framesPerBuffer.
+ *   - it must be at least 2x the suggestedLatency.
+ *   - it must be a power of 2.
+ * This function attempts to compute the minimum such size.
+ *
+ * FEEDBACK: too liberal/conservative/another way?
+ */
+long computeRingBufferSize( const PaStreamParameters *inputParameters,
+                                   const PaStreamParameters *outputParameters,
+                                   long inputFramesPerBuffer,
+                                   long outputFramesPerBuffer,
+                                   double sampleRate )
+{
+   long ringSize;
+   int index;
+   int i;
+   double latency ;
+   long framesPerBuffer ;
+
+   VVDBUG(( "computeRingBufferSize()\n" ));
+
+   assert( inputParameters || outputParameters );
+
+   if( outputParameters && inputParameters )
+   {
+      latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency );
+      framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer );
+   } 
+   else if( outputParameters )
+   {
+      latency = outputParameters->suggestedLatency;
+      framesPerBuffer = outputFramesPerBuffer ;
+   }
+   else /* we have inputParameters  */
+   {
+      latency = inputParameters->suggestedLatency;
+      framesPerBuffer = inputFramesPerBuffer ;
+   }
+
+   ringSize = (long) ( latency * sampleRate * 2 + .5);
+   VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) );
+   if( ringSize < framesPerBuffer * 3 )
+      ringSize = framesPerBuffer * 3 ;
+   VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer));
+   VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));
+
+   /* make sure it's at least 4 */
+   ringSize = MAX( ringSize, 4 );
+
+   /* round up to the next power of 2 */
+   index = -1;
+   for( i=0; i<sizeof(long)*8; ++i )
+      if( ringSize >> i & 0x01 )
+         index = i;
+   assert( index > 0 );
+   if( ringSize <= ( 0x01 << index ) )
+      ringSize = 0x01 << index ;
+   else
+      ringSize = 0x01 << ( index + 1 );
+
+   VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));
+   return ringSize;
+}
+
+
+/*
+ * Durring testing of core audio, I found that serious crashes could occur
+ * if properties such as sample rate were changed multiple times in rapid
+ * succession. The function below could be used to with a condition variable.
+ * to prevent propertychanges from happening until the last property
+ * change is acknowledged. Instead, I implemented a busy-wait, which is simpler
+ * to implement b/c in second round of testing (nov '09) property changes occured
+ * quickly and so there was no real way to test the condition variable implementation.
+ * therefore, this function is not used, but it is aluded to in commented code below,
+ * since it represents a theoretically better implementation.
+ */
+
+OSStatus propertyProc(
+    AudioDeviceID inDevice, 
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID, 
+    void* inClientData )
+{
+   // this is where we would set the condition variable
+   return noErr;
+}
+
+/* sets the value of the given property and waits for the change to 
+   be acknowledged, and returns the final value, which is not guaranteed
+   by this function to be the same as the desired value. Obviously, this
+   function can only be used for data whose input and output are the
+   same size and format, and their size and format are known in advance.
+   whether or not the call succeeds, if the data is successfully read,
+   it is returned in outPropertyData. If it is not read successfully,
+   outPropertyData is zeroed, which may or may not be useful in
+   determining if the property was read. */
+PaError AudioDeviceSetPropertyNowAndWaitForChange(
+    AudioDeviceID inDevice,
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID,
+    UInt32 inPropertyDataSize, 
+    const void *inPropertyData,
+    void *outPropertyData )
+{
+   OSStatus macErr;
+   UInt32 outPropertyDataSize = inPropertyDataSize;
+
+   /* First, see if it already has that value. If so, return. */
+   macErr = AudioDeviceGetProperty( inDevice, inChannel,
+                                 isInput, inPropertyID, 
+                                 &outPropertyDataSize, outPropertyData );
+   if( macErr ) {
+      memset( outPropertyData, 0, inPropertyDataSize );
+      goto failMac;
+   }
+   if( inPropertyDataSize!=outPropertyDataSize )
+      return paInternalError;
+   if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
+      return paNoError;
+
+   /* Ideally, we'd use a condition variable to determine changes.
+      we could set that up here. */
+
+   /* If we were using a cond variable, we'd do something useful here,
+      but for now, this is just to make 10.6 happy. */
+   macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
+                                   inPropertyID, propertyProc,
+                                   NULL ); 
+   if( macErr )
+      /* we couldn't add a listener. */
+      goto failMac;
+
+   /* set property */
+   macErr  = AudioDeviceSetProperty( inDevice, NULL, inChannel,
+                                 isInput, inPropertyID,
+                                 inPropertyDataSize, inPropertyData );
+   if( macErr )
+      goto failMac;
+
+   /* busy-wait up to 30 seconds for the property to change */
+   /* busy-wait is justified here only because the correct alternative (condition variable)
+      was hard to test, since most of the waiting ended up being for setting rather than
+      getting in OS X 10.5. This was not the case in earlier OS versions. */
+   struct timeval tv1, tv2;
+   gettimeofday( &tv1, NULL );
+   memcpy( &tv2, &tv1, sizeof( struct timeval ) );
+   while( tv2.tv_sec - tv1.tv_sec < 30 ) {
+      /* now read the property back out */
+      macErr = AudioDeviceGetProperty( inDevice, inChannel,
+                                    isInput, inPropertyID, 
+                                    &outPropertyDataSize, outPropertyData );
+      if( macErr ) {
+         memset( outPropertyData, 0, inPropertyDataSize );
+         goto failMac;
+      }
+      /* and compare... */
+      if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) {
+         AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
+         return paNoError;
+      }
+      /* No match yet, so let's sleep and try again. */
+      Pa_Sleep( 100 );
+      gettimeofday( &tv2, NULL );
+   }
+   DBUG( ("Timeout waiting for device setting.\n" ) );
+   
+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
+   return paNoError;
+
+ failMac:
+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
+   return ERR( macErr );
+}
+
+/*
+ * Sets the sample rate the HAL device.
+ * if requireExact: set the sample rate or fail.
+ *
+ * otherwise      : set the exact sample rate.
+ *             If that fails, check for available sample rates, and choose one
+ *             higher than the requested rate. If there isn't a higher one,
+ *             just use the highest available.
+ */
+PaError setBestSampleRateForDevice( const AudioDeviceID device,
+                                    const bool isOutput,
+                                    const bool requireExact,
+                                    const Float64 desiredSrate )
+{
+   const bool isInput = isOutput ? 0 : 1;
+   Float64 srate;
+   UInt32 propsize = sizeof( Float64 );
+   OSErr err;
+   AudioValueRange *ranges;
+   int i=0;
+   Float64 max  = -1; /*the maximum rate available*/
+   Float64 best = -1; /*the lowest sample rate still greater than desired rate*/
+   VDBUG(("Setting sample rate for device %ld to %g.\n",device,(float)desiredSrate));
+
+   /* -- try setting the sample rate -- */
+   srate = 0;
+   err = AudioDeviceSetPropertyNowAndWaitForChange(
+                                 device, 0, isInput,
+                                 kAudioDevicePropertyNominalSampleRate,
+                                 propsize, &desiredSrate, &srate );
+
+   /* -- if the rate agrees, and was changed, we are done -- */
+   if( srate != 0 && srate == desiredSrate )
+      return paNoError;
+   /* -- if the rate agrees, and we got no errors, we are done -- */
+   if( !err && srate == desiredSrate )
+      return paNoError;
+   /* -- we've failed if the rates disagree and we are setting input -- */
+   if( requireExact )
+      return paInvalidSampleRate;
+
+   /* -- generate a list of available sample rates -- */
+   err = AudioDeviceGetPropertyInfo( device, 0, isInput,
+                                kAudioDevicePropertyAvailableNominalSampleRates,
+                                &propsize, NULL );
+   if( err )
+      return ERR( err );
+   ranges = (AudioValueRange *)calloc( 1, propsize );
+   if( !ranges )
+      return paInsufficientMemory;
+   err = AudioDeviceGetProperty( device, 0, isInput,
+                                kAudioDevicePropertyAvailableNominalSampleRates,
+                                &propsize, ranges );
+   if( err )
+   {
+      free( ranges );
+      return ERR( err );
+   }
+   VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));
+   VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));
+#ifdef MAC_CORE_VERBOSE_DEBUG
+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+      VDBUG( ("\t%g-%g\n",
+              (float) ranges[i].mMinimum,
+              (float) ranges[i].mMaximum ) );
+#endif
+   VDBUG(("-----\n"));
+   
+   /* -- now pick the best available sample rate -- */
+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+   {
+      if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;
+      if( ranges[i].mMinimum > desiredSrate ) {
+         if( best < 0 )
+            best = ranges[i].mMinimum;
+         else if( ranges[i].mMinimum < best )
+            best = ranges[i].mMinimum;
+      }
+   }
+   if( best < 0 )
+      best = max;
+   VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );
+   free( ranges );
+
+   /* -- set the sample rate -- */
+   propsize = sizeof( best );
+   srate = 0;
+   err = AudioDeviceSetPropertyNowAndWaitForChange(
+                                 device, 0, isInput,
+                                 kAudioDevicePropertyNominalSampleRate,
+                                 propsize, &best, &srate );
+
+   /* -- if the set rate matches, we are done -- */
+   if( srate != 0 && srate == best )
+      return paNoError;
+
+   if( err )
+      return ERR( err );
+
+   /* -- otherwise, something wierd happened: we didn't set the rate, and we got no errors. Just bail. */
+   return paInternalError;
+}
+
+
+/*
+   Attempts to set the requestedFramesPerBuffer. If it can't set the exact
+   value, it settles for something smaller if available. If nothing smaller
+   is available, it uses the smallest available size.
+   actualFramesPerBuffer will be set to the actual value on successful return.
+   OK to pass NULL to actualFramesPerBuffer.
+   The logic is very simmilar too setBestSampleRate only failure here is
+   not usually catastrophic.
+*/
+PaError setBestFramesPerBuffer( const AudioDeviceID device,
+                                const bool isOutput,
+                                UInt32 requestedFramesPerBuffer, 
+                                UInt32 *actualFramesPerBuffer )
+{
+    UInt32 afpb;
+    const bool isInput = !isOutput;
+    UInt32 propsize = sizeof(UInt32);
+    OSErr err;
+    AudioValueRange range;
+
+    if( actualFramesPerBuffer == NULL )
+    {
+        actualFramesPerBuffer = &afpb;
+    }
+
+    /* -- try and set exact FPB -- */
+    err = AudioDeviceSetProperty( device, NULL, 0, isInput,
+                                 kAudioDevicePropertyBufferFrameSize,
+                                 propsize, &requestedFramesPerBuffer);
+    err = AudioDeviceGetProperty( device, 0, isInput,
+                           kAudioDevicePropertyBufferFrameSize,
+                           &propsize, actualFramesPerBuffer);
+    if( err )
+    {
+        return ERR( err );
+    }
+    // Did we get the size we asked for?
+    if( *actualFramesPerBuffer == requestedFramesPerBuffer )
+    {
+        return paNoError; /* we are done */
+    }
+    
+    // Clip requested value against legal range for the device.
+    propsize = sizeof(AudioValueRange);
+    err = AudioDeviceGetProperty( device, 0, isInput,
+                                kAudioDevicePropertyBufferFrameSizeRange,
+                                &propsize, &range );
+    if( err )
+    {
+      return ERR( err );
+    }
+    if( requestedFramesPerBuffer < range.mMinimum )
+    {
+        requestedFramesPerBuffer = range.mMinimum;
+    }
+    else if( requestedFramesPerBuffer > range.mMaximum )
+    {
+        requestedFramesPerBuffer = range.mMaximum;
+    }
+    
+   /* --- set the buffer size (ignore errors) -- */
+    propsize = sizeof( UInt32 );
+   err = AudioDeviceSetProperty( device, NULL, 0, isInput,
+                                 kAudioDevicePropertyBufferFrameSize,
+                                 propsize, &requestedFramesPerBuffer );
+   /* --- read the property to check that it was set -- */
+   err = AudioDeviceGetProperty( device, 0, isInput,
+                                 kAudioDevicePropertyBufferFrameSize,
+                                 &propsize, actualFramesPerBuffer );
+
+   if( err )
+      return ERR( err );
+
+   return paNoError;
+}
+
+/**********************
+ *
+ * XRun stuff
+ *
+ **********************/
+
+struct PaMacXRunListNode_s {
+   PaMacCoreStream *stream;
+   struct PaMacXRunListNode_s *next;
+} ;
+
+typedef struct PaMacXRunListNode_s PaMacXRunListNode;
+
+/** Always empty, so that it can always be the one returned by
+    addToXRunListenerList. note that it's not a pointer. */
+static PaMacXRunListNode firstXRunListNode;
+static int xRunListSize;
+static pthread_mutex_t xrunMutex;
+
+OSStatus xrunCallback(
+    AudioDeviceID inDevice, 
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID, 
+    void* inClientData)
+{
+   PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData;
+
+   int ret = pthread_mutex_trylock( &xrunMutex ) ;
+
+   if( ret == 0 ) {
+
+      node = node->next ; //skip the first node
+
+      for( ; node; node=node->next ) {
+         PaMacCoreStream *stream = node->stream;
+
+         if( stream->state != ACTIVE )
+            continue; //if the stream isn't active, we don't care if the device is dropping
+
+         if( isInput ) {
+            if( stream->inputDevice == inDevice )
+               OSAtomicOr32( paInputOverflow, &stream->xrunFlags );
+         } else {
+            if( stream->outputDevice == inDevice )
+               OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags );
+         }
+      }
+
+      pthread_mutex_unlock( &xrunMutex );
+   }
+
+   return 0;
+}
+
+int initializeXRunListenerList()
+{
+   xRunListSize = 0;
+   bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) );
+   return pthread_mutex_init( &xrunMutex, NULL );
+}
+int destroyXRunListenerList()
+{
+   PaMacXRunListNode *node;
+   node = firstXRunListNode.next;
+   while( node ) {
+      PaMacXRunListNode *tmp = node;
+      node = node->next;
+      free( tmp );
+   }
+   xRunListSize = 0;
+   return pthread_mutex_destroy( &xrunMutex );
+}
+
+void *addToXRunListenerList( void *stream )
+{
+   pthread_mutex_lock( &xrunMutex );
+   PaMacXRunListNode *newNode;
+   // setup new node:
+   newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) );
+   newNode->stream = (PaMacCoreStream *) stream;
+   newNode->next = firstXRunListNode.next;
+   // insert:
+   firstXRunListNode.next = newNode;
+   pthread_mutex_unlock( &xrunMutex );
+
+   return &firstXRunListNode;
+}
+
+int removeFromXRunListenerList( void *stream )
+{
+   pthread_mutex_lock( &xrunMutex );
+   PaMacXRunListNode *node, *prev;
+   prev = &firstXRunListNode;
+   node = firstXRunListNode.next;
+   while( node ) {
+      if( node->stream == stream ) {
+         //found it:
+         --xRunListSize;
+         prev->next = node->next;
+         free( node );
+         pthread_mutex_unlock( &xrunMutex );
+         return xRunListSize;
+      }
+      prev = prev->next;
+      node = node->next;
+   }
+
+   pthread_mutex_unlock( &xrunMutex );
+   // failure
+   return xRunListSize;
+}
+
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
new file mode 100644 (file)
index 0000000..7c4afe5
--- /dev/null
@@ -0,0 +1,218 @@
+/*
+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ * 
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#ifndef PA_MAC_CORE_UTILITIES_H__
+#define PA_MAC_CORE_UTILITIES_H__
+
+#include <pthread.h>
+#include "portaudio.h"
+#include "pa_util.h"
+#include <AudioUnit/AudioUnit.h>
+#include <AudioToolbox/AudioToolbox.h>
+
+#ifndef MIN
+#define MIN(a, b)  (((a)<(b))?(a):(b))
+#endif
+
+#ifndef MAX
+#define MAX(a, b)  (((a)<(b))?(b):(a))
+#endif
+
+#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) 
+#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 )
+
+
+/* Help keep track of AUHAL element numbers */
+#define INPUT_ELEMENT  (1)
+#define OUTPUT_ELEMENT (0)
+
+/* Normal level of debugging: fine for most apps that don't mind the occational warning being printf'ed */
+/*
+ */
+#define MAC_CORE_DEBUG
+#ifdef MAC_CORE_DEBUG
+# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define DBUG(MSG)
+#endif
+
+/* Verbose Debugging: useful for developement */
+/*
+#define MAC_CORE_VERBOSE_DEBUG
+*/
+#ifdef MAC_CORE_VERBOSE_DEBUG
+# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define VDBUG(MSG)
+#endif
+
+/* Very Verbose Debugging: Traces every call. */
+/*
+#define MAC_CORE_VERY_VERBOSE_DEBUG
+ */
+#ifdef MAC_CORE_VERY_VERBOSE_DEBUG
+# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define VVDBUG(MSG)
+#endif
+
+
+
+
+
+#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ )
+
+PaError PaMacCore_SetUnixError( int err, int line );
+
+/*
+ * Translates MacOS generated errors into PaErrors
+ */
+PaError PaMacCore_SetError(OSStatus error, int line, int isError);
+
+/*
+ * This function computes an appropriate ring buffer size given
+ * a requested latency (in seconds), sample rate and framesPerBuffer.
+ *
+ * The returned ringBufferSize is computed using the following
+ * constraints:
+ *   - it must be at least 4.
+ *   - it must be at least 3x framesPerBuffer.
+ *   - it must be at least 2x the suggestedLatency.
+ *   - it must be a power of 2.
+ * This function attempts to compute the minimum such size.
+ *
+ */
+long computeRingBufferSize( const PaStreamParameters *inputParameters,
+                                   const PaStreamParameters *outputParameters,
+                                   long inputFramesPerBuffer,
+                                   long outputFramesPerBuffer,
+                                   double sampleRate );
+
+OSStatus propertyProc(
+    AudioDeviceID inDevice, 
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID, 
+    void* inClientData );
+
+/* sets the value of the given property and waits for the change to 
+   be acknowledged, and returns the final value, which is not guaranteed
+   by this function to be the same as the desired value. Obviously, this
+   function can only be used for data whose input and output are the
+   same size and format, and their size and format are known in advance.*/
+PaError AudioDeviceSetPropertyNowAndWaitForChange(
+    AudioDeviceID inDevice,
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID,
+    UInt32 inPropertyDataSize, 
+    const void *inPropertyData,
+    void *outPropertyData );
+
+/*
+ * Sets the sample rate the HAL device.
+ * if requireExact: set the sample rate or fail.
+ *
+ * otherwise      : set the exact sample rate.
+ *             If that fails, check for available sample rates, and choose one
+ *             higher than the requested rate. If there isn't a higher one,
+ *             just use the highest available.
+ */
+PaError setBestSampleRateForDevice( const AudioDeviceID device,
+                                    const bool isOutput,
+                                    const bool requireExact,
+                                    const Float64 desiredSrate );
+/*
+   Attempts to set the requestedFramesPerBuffer. If it can't set the exact
+   value, it settles for something smaller if available. If nothing smaller
+   is available, it uses the smallest available size.
+   actualFramesPerBuffer will be set to the actual value on successful return.
+   OK to pass NULL to actualFramesPerBuffer.
+   The logic is very simmilar too setBestSampleRate only failure here is
+   not usually catastrophic.
+*/
+PaError setBestFramesPerBuffer( const AudioDeviceID device,
+                                const bool isOutput,
+                                UInt32 requestedFramesPerBuffer, 
+                                UInt32 *actualFramesPerBuffer );
+
+
+/*********************
+ *
+ *  xrun handling
+ *
+ *********************/
+
+OSStatus xrunCallback(
+    AudioDeviceID inDevice, 
+    UInt32 inChannel, 
+    Boolean isInput, 
+    AudioDevicePropertyID inPropertyID, 
+    void* inClientData ) ;
+
+/** returns zero on success or a unix style error code. */
+int initializeXRunListenerList();
+/** returns zero on success or a unix style error code. */
+int destroyXRunListenerList();
+
+/**Returns the list, so that it can be passed to CorAudio.*/
+void *addToXRunListenerList( void *stream );
+/**Returns the number of Listeners in the list remaining.*/
+int removeFromXRunListenerList( void *stream );
+
+#endif /* PA_MAC_CORE_UTILITIES_H__*/
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds.c b/portaudio/src/hostapi/dsound/pa_win_ds.c
new file mode 100644 (file)
index 0000000..168442a
--- /dev/null
@@ -0,0 +1,3269 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library DirectSound implementation
+ *
+ * Authors: Phil Burk, Robert Marsanyi & Ross Bencina
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2007 Ross Bencina, Phil Burk, Robert Marsanyi
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup hostapi_src
+*/
+
+/* Until May 2011 PA/DS has used a multimedia timer to perform the callback.
+   We're replacing this with a new implementation using a thread and a different timer mechanim.
+   Defining PA_WIN_DS_USE_WMME_TIMER uses the old (pre-May 2011) behavior.
+*/
+//#define PA_WIN_DS_USE_WMME_TIMER
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h> /* strlen() */
+
+#define _WIN32_WINNT 0x0400 /* required to get waitable timer APIs */
+#include <initguid.h> /* make sure ds guids get defined */
+#include <windows.h>
+#include <mmsystem.h>
+#include <objbase.h>
+
+
+/*
+  Use the earliest version of DX required, no need to polute the namespace
+*/
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+#define DIRECTSOUND_VERSION 0x0800
+#else
+#define DIRECTSOUND_VERSION 0x0300
+#endif
+#include <dsound.h>
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+#include <dsconf.h>
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+#ifndef UNDER_CE
+#include <process.h>
+#endif
+#endif
+
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_debugprint.h"
+
+#include "pa_win_ds.h"
+#include "pa_win_ds_dynlink.h"
+#include "pa_win_waveformat.h"
+#include "pa_win_wdmks_utils.h"
+#include "pa_win_coinitialize.h"
+
+#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment( lib, "dsound.lib" )
+#pragma comment( lib, "winmm.lib" )
+#pragma comment( lib, "kernel32.lib" )
+#endif
+
+/* use CreateThread for CYGWIN, _beginthreadex for all others */
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+
+#if !defined(__CYGWIN__) && !defined(UNDER_CE)
+#define CREATE_THREAD (HANDLE)_beginthreadex
+#undef CLOSE_THREAD_HANDLE /* as per documentation we don't call CloseHandle on a thread created with _beginthreadex */
+#define PA_THREAD_FUNC static unsigned WINAPI
+#define PA_THREAD_ID unsigned
+#else
+#define CREATE_THREAD CreateThread
+#define CLOSE_THREAD_HANDLE CloseHandle
+#define PA_THREAD_FUNC static DWORD WINAPI
+#define PA_THREAD_ID DWORD
+#endif
+
+#if (defined(UNDER_CE))
+#pragma comment(lib, "Coredll.lib")
+#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment(lib, "winmm.lib")
+#endif
+
+PA_THREAD_FUNC ProcessingThreadProc( void *pArg );
+
+#if !defined(UNDER_CE)
+#define PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT /* use waitable timer where possible, otherwise we use a WaitForSingleObject timeout */
+#endif
+
+#endif /* !PA_WIN_DS_USE_WMME_TIMER */
+
+
+/*
+ provided in newer platform sdks and x64
+ */
+#ifndef DWORD_PTR
+    #if defined(_WIN64)
+        #define DWORD_PTR unsigned __int64
+    #else
+        #define DWORD_PTR unsigned long
+    #endif
+#endif
+
+#define PRINT(x) PA_DEBUG(x);
+#define ERR_RPT(x) PRINT(x)
+#define DBUG(x)   PRINT(x)
+#define DBUGX(x)  PRINT(x)
+
+#define PA_USE_HIGH_LATENCY   (0)
+#if PA_USE_HIGH_LATENCY
+#define PA_DS_WIN_9X_DEFAULT_LATENCY_     (.500)
+#define PA_DS_WIN_NT_DEFAULT_LATENCY_     (.600)
+#else
+#define PA_DS_WIN_9X_DEFAULT_LATENCY_     (.140)
+#define PA_DS_WIN_NT_DEFAULT_LATENCY_     (.280)
+#endif
+
+#define PA_DS_WIN_WDM_DEFAULT_LATENCY_    (.120)
+
+/* we allow the polling period to range between 1 and 100ms.
+   prior to August 2011 we limited the minimum polling period to 10ms.
+*/
+#define PA_DS_MINIMUM_POLLING_PERIOD_SECONDS    (0.001) /* 1ms */
+#define PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS    (0.100) /* 100ms */
+#define PA_DS_POLLING_JITTER_SECONDS            (0.001) /* 1ms */
+
+#define SECONDS_PER_MSEC      (0.001)
+#define MSECS_PER_SECOND       (1000)
+
+/* prototypes for functions declared in this file */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+
+/* FIXME: should convert hr to a string */
+#define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \
+    PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )
+
+/************************************************* DX Prototypes **********/
+static BOOL CALLBACK CollectGUIDsProcW(LPGUID lpGUID,
+                                     LPCWSTR lpszDesc,
+                                     LPCWSTR lpszDrvName,
+                                     LPVOID lpContext );
+
+/************************************************************************************/
+/********************** Structures **************************************************/
+/************************************************************************************/
+/* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct PaWinDsDeviceInfo
+{
+    PaDeviceInfo        inheritedDeviceInfo;
+    GUID                guid;
+    GUID                *lpGUID;
+    double              sampleRates[3];
+    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
+    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
+} PaWinDsDeviceInfo;
+
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface    callbackStreamInterface;
+    PaUtilStreamInterface    blockingStreamInterface;
+
+    PaUtilAllocationGroup   *allocations;
+
+    /* implementation specific data goes here */
+
+    PaWinUtilComInitializationResult comInitializationResult;
+
+} PaWinDsHostApiRepresentation;
+
+
+/* PaWinDsStream - a stream data structure specifically for this implementation */
+
+typedef struct PaWinDsStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+/* DirectSound specific data. */
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+    LPDIRECTSOUNDFULLDUPLEX8 pDirectSoundFullDuplex8;
+#endif
+
+/* Output */
+    LPDIRECTSOUND        pDirectSound;
+    LPDIRECTSOUNDBUFFER  pDirectSoundPrimaryBuffer;
+    LPDIRECTSOUNDBUFFER  pDirectSoundOutputBuffer;
+    DWORD                outputBufferWriteOffsetBytes;     /* last write position */
+    INT                  outputBufferSizeBytes;
+    INT                  outputFrameSizeBytes;
+    /* Try to detect play buffer underflows. */
+    LARGE_INTEGER        perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */
+    LARGE_INTEGER        previousPlayTime;
+    DWORD                previousPlayCursor;
+    UINT                 outputUnderflowCount;
+    BOOL                 outputIsRunning;
+    INT                  finalZeroBytesWritten; /* used to determine when we've flushed the whole buffer */
+
+/* Input */
+    LPDIRECTSOUNDCAPTURE pDirectSoundCapture;
+    LPDIRECTSOUNDCAPTUREBUFFER   pDirectSoundInputBuffer;
+    INT                  inputFrameSizeBytes;
+    UINT                 readOffset;      /* last read position */
+    UINT                 inputBufferSizeBytes;
+
+    
+    int              hostBufferSizeFrames; /* input and output host ringbuffers have the same number of frames */
+    double           framesWritten;
+    double           secondsPerHostByte; /* Used to optimize latency calculation for outTime */
+    double           pollingPeriodSeconds;
+
+    PaStreamCallbackFlags callbackFlags;
+
+    PaStreamFlags    streamFlags;
+    int              callbackResult;
+    HANDLE           processingCompleted;
+    
+/* FIXME - move all below to PaUtilStreamRepresentation */
+    volatile int     isStarted;
+    volatile int     isActive;
+    volatile int     stopProcessing; /* stop thread once existing buffers have been returned */
+    volatile int     abortProcessing; /* stop thread immediately */
+
+    UINT             systemTimerResolutionPeriodMs; /* set to 0 if we were unable to set the timer period */ 
+
+#ifdef PA_WIN_DS_USE_WMME_TIMER
+    MMRESULT         timerID;
+#else
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+    HANDLE           waitableTimer;
+#endif
+    HANDLE           processingThread;
+    PA_THREAD_ID     processingThreadId;
+    HANDLE           processingThreadCompleted;
+#endif
+
+} PaWinDsStream;
+
+
+/* Set minimal latency based on the current OS version.
+ * NT has higher latency.
+ */
+static double PaWinDS_GetMinSystemLatencySeconds( void )
+{
+/*
+NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
+versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
+Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
+is is faster, for now we just disable the deprecation warning.
+See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
+See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
+*/
+#pragma warning (disable : 4996) /* use of GetVersionEx */
+
+    double minLatencySeconds;
+    /* Set minimal latency based on whether NT or other OS.
+     * NT has higher latency.
+     */
+
+    OSVERSIONINFO osvi;
+    osvi.dwOSVersionInfoSize = sizeof( osvi );
+    GetVersionEx( &osvi );
+    DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));
+    DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));
+    DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));
+    /* Check for NT */
+    if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
+    {
+        minLatencySeconds = PA_DS_WIN_NT_DEFAULT_LATENCY_;
+    }
+    else if(osvi.dwMajorVersion >= 5)
+    {
+        minLatencySeconds = PA_DS_WIN_WDM_DEFAULT_LATENCY_;
+    }
+    else
+    {
+        minLatencySeconds = PA_DS_WIN_9X_DEFAULT_LATENCY_;
+    }
+    return minLatencySeconds;
+
+#pragma warning (default : 4996)
+}
+
+
+/*************************************************************************
+** Return minimum workable latency required for this host. This is returned
+** As the default stream latency in PaDeviceInfo.
+** Latency can be optionally set by user by setting an environment variable. 
+** For example, to set latency to 200 msec, put:
+**
+**    set PA_MIN_LATENCY_MSEC=200
+**
+** in the AUTOEXEC.BAT file and reboot.
+** If the environment variable is not set, then the latency will be determined
+** based on the OS. Windows NT has higher latency than Win95.
+*/
+#define PA_LATENCY_ENV_NAME  ("PA_MIN_LATENCY_MSEC")
+#define PA_ENV_BUF_SIZE  (32)
+
+static double PaWinDs_GetMinLatencySeconds( double sampleRate )
+{
+    char      envbuf[PA_ENV_BUF_SIZE];
+    DWORD     hresult;
+    double    minLatencySeconds = 0;
+
+    /* Let user determine minimal latency by setting environment variable. */
+    hresult = GetEnvironmentVariableA( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );
+    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )
+    {
+        minLatencySeconds = atoi( envbuf ) * SECONDS_PER_MSEC;
+    }
+    else
+    {
+        minLatencySeconds = PaWinDS_GetMinSystemLatencySeconds();
+#if PA_USE_HIGH_LATENCY
+        PRINT(("PA - Minimum Latency set to %f msec!\n", minLatencySeconds * MSECS_PER_SECOND ));
+#endif
+    }
+
+    return minLatencySeconds;
+}
+
+
+/************************************************************************************
+** Duplicate and convert the input string using the group allocations allocator.
+** A NULL string is converted to a zero length string.
+** If memory cannot be allocated, NULL is returned.
+**/
+static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const wchar_t* src )
+{
+    char *result = 0;
+    
+    if( src != NULL )
+    {
+#if !defined(_UNICODE) && !defined(UNICODE)
+        size_t len = WideCharToMultiByte(CP_ACP, 0, src, -1, NULL, 0, NULL, NULL);
+
+        result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );
+        if( result ) {
+            if (WideCharToMultiByte(CP_ACP, 0, src, -1, result, (int)len, NULL, NULL) == 0) {
+                result = 0;
+            }
+        }
+#else
+        size_t len = WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
+
+        result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );
+        if( result ) {
+            if (WideCharToMultiByte(CP_UTF8, 0, src, -1, result, (int)len, NULL, NULL) == 0) {
+                result = 0;
+            }
+        }
+#endif
+    }
+    else
+    {
+        result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );
+        if( result )
+            result[0] = '\0';
+    }
+
+    return result;
+}
+
+/************************************************************************************
+** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary
+** information during device enumeration.
+*/
+typedef struct DSDeviceNameAndGUID{
+    char *name; // allocated from parent's allocations, never deleted by this structure
+    GUID guid;
+    LPGUID lpGUID;
+    void *pnpInterface;  // wchar_t* interface path, allocated using the DS host api's allocation group
+} DSDeviceNameAndGUID;
+
+typedef struct DSDeviceNameAndGUIDVector{
+    PaUtilAllocationGroup *allocations;
+    PaError enumerationError;
+
+    int count;
+    int free;
+    DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()
+} DSDeviceNameAndGUIDVector;
+
+typedef struct DSDeviceNamesAndGUIDs{
+    PaWinDsHostApiRepresentation *winDsHostApi;
+    DSDeviceNameAndGUIDVector inputNamesAndGUIDs;
+    DSDeviceNameAndGUIDVector outputNamesAndGUIDs;
+} DSDeviceNamesAndGUIDs;
+
+static PaError InitializeDSDeviceNameAndGUIDVector(
+        DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )
+{
+    PaError result = paNoError;
+
+    guidVector->allocations = allocations;
+    guidVector->enumerationError = paNoError;
+
+    guidVector->count = 0;
+    guidVector->free = 8;
+    guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );
+    if( guidVector->items == NULL )
+        result = paInsufficientMemory;
+    
+    return result;
+}
+
+static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
+{
+    PaError result = paNoError;
+    DSDeviceNameAndGUID *newItems;
+    int i;
+    
+    /* double size of vector */
+    int size = guidVector->count + guidVector->free;
+    guidVector->free += size;
+
+    newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );
+    if( newItems == NULL )
+    {
+        result = paInsufficientMemory;
+    }
+    else
+    {
+        for( i=0; i < guidVector->count; ++i )
+        {
+            newItems[i].name = guidVector->items[i].name;
+            if( guidVector->items[i].lpGUID == NULL )
+            {
+                newItems[i].lpGUID = NULL;
+            }
+            else
+            {
+                newItems[i].lpGUID = &newItems[i].guid;
+                memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );
+            }
+            newItems[i].pnpInterface = guidVector->items[i].pnpInterface;
+        }
+
+        LocalFree( guidVector->items );
+        guidVector->items = newItems;
+    }                                
+
+    return result;
+}
+
+/*
+    it's safe to call DSDeviceNameAndGUIDVector multiple times
+*/
+static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
+{
+    PaError result = paNoError;
+
+    if( guidVector->items != NULL )
+    {
+        if( LocalFree( guidVector->items ) != NULL )
+            result = paInsufficientMemory;              /** @todo this isn't the correct error to return from a deallocation failure */
+
+        guidVector->items = NULL;
+    }
+
+    return result;
+}
+
+/************************************************************************************
+** Collect preliminary device information during DirectSound enumeration 
+*/
+static BOOL CALLBACK CollectGUIDsProcW(LPGUID lpGUID,
+                                     LPCWSTR lpszDesc,
+                                     LPCWSTR lpszDrvName,
+                                     LPVOID lpContext )
+{
+    DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;
+    PaError error;
+
+    (void) lpszDrvName; /* unused variable */
+
+    if( namesAndGUIDs->free == 0 )
+    {
+        error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );
+        if( error != paNoError )
+        {
+            namesAndGUIDs->enumerationError = error;
+            return FALSE;
+        }
+    }
+    
+    /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */
+    if( lpGUID == NULL )
+    {
+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;
+    }
+    else
+    {
+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =
+                &namesAndGUIDs->items[namesAndGUIDs->count].guid;
+      
+        memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );
+    }
+
+    namesAndGUIDs->items[namesAndGUIDs->count].name =
+            DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );
+    if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )
+    {
+        namesAndGUIDs->enumerationError = paInsufficientMemory;
+        return FALSE;
+    }
+
+    namesAndGUIDs->items[namesAndGUIDs->count].pnpInterface = 0;
+
+    ++namesAndGUIDs->count;
+    --namesAndGUIDs->free;
+    
+    return TRUE;
+}
+
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+
+static void *DuplicateWCharString( PaUtilAllocationGroup *allocations, wchar_t *source )
+{
+    size_t len;
+    wchar_t *result;
+
+    len = wcslen( source );
+    result = (wchar_t*)PaUtil_GroupAllocateMemory( allocations, (long) ((len+1) * sizeof(wchar_t)) );
+    wcscpy( result, source );
+    return result;
+}
+
+static BOOL CALLBACK KsPropertySetEnumerateCallback( PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA data, LPVOID context )
+{
+    int i;
+    DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs = (DSDeviceNamesAndGUIDs*)context;
+
+    /*
+        Apparently data->Interface can be NULL in some cases. 
+        Possibly virtual devices without hardware.
+        So we check for NULLs now. See mailing list message November 10, 2012:
+        "[Portaudio] portaudio initialization crash in KsPropertySetEnumerateCallback(pa_win_ds.c)"
+    */
+    if( data->Interface )
+    {
+        if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_RENDER )
+        {
+            for( i=0; i < deviceNamesAndGUIDs->outputNamesAndGUIDs.count; ++i )
+            {
+                if( deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID
+                    && memcmp( &data->DeviceId, deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
+                {
+                    deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].pnpInterface = 
+                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
+                    break;
+                }
+            }
+        }
+        else if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE )
+        {
+            for( i=0; i < deviceNamesAndGUIDs->inputNamesAndGUIDs.count; ++i )
+            {
+                if( deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID
+                    && memcmp( &data->DeviceId, deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
+                {
+                    deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].pnpInterface = 
+                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
+                    break;
+                }
+            }
+        }
+    }
+
+    return TRUE;
+}
+
+
+static GUID pawin_CLSID_DirectSoundPrivate = 
+{ 0x11ab3ec0, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
+
+static GUID pawin_DSPROPSETID_DirectSoundDevice = 
+{ 0x84624f82, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
+
+static GUID pawin_IID_IKsPropertySet = 
+{ 0x31efac30, 0x515c, 0x11d0, 0xa9, 0xaa, 0x00, 0xaa, 0x00, 0x61, 0xbe, 0x93 };
+
+
+/*
+    FindDevicePnpInterfaces fills in the pnpInterface fields in deviceNamesAndGUIDs
+    with UNICODE file paths to the devices. The DS documentation mentions
+    at least two techniques by which these Interface paths can be found using IKsPropertySet on
+    the DirectSound class object. One is using the DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION 
+    property, and the other is using DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE.
+    I tried both methods and only the second worked. I found two postings on the
+    net from people who had the same problem with the first method, so I think the method used here is 
+    more common/likely to work. The probem is that IKsPropertySet_Get returns S_OK
+    but the fields of the device description are not filled in.
+
+    The mechanism we use works by registering an enumeration callback which is called for 
+    every DSound device. Our callback searches for a device in our deviceNamesAndGUIDs list
+    with the matching GUID and copies the pointer to the Interface path.
+    Note that we could have used this enumeration callback to perform the original 
+    device enumeration, however we choose not to so we can disable this step easily.
+
+    Apparently the IKsPropertySet mechanism was added in DirectSound 9c 2004
+    http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2004-12/0099.html
+
+        -- rossb
+*/
+static void FindDevicePnpInterfaces( DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs )
+{
+    IClassFactory *pClassFactory;
+   
+    if( paWinDsDSoundEntryPoints.DllGetClassObject(&pawin_CLSID_DirectSoundPrivate, &IID_IClassFactory, (PVOID *) &pClassFactory) == S_OK ){
+        IKsPropertySet *pPropertySet;
+        if( pClassFactory->lpVtbl->CreateInstance( pClassFactory, NULL, &pawin_IID_IKsPropertySet, (PVOID *) &pPropertySet) == S_OK ){
+            
+            DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA data;
+            ULONG bytesReturned;
+
+            data.Callback = KsPropertySetEnumerateCallback;
+            data.Context = deviceNamesAndGUIDs;
+
+            IKsPropertySet_Get( pPropertySet,
+                &pawin_DSPROPSETID_DirectSoundDevice,
+                DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W,
+                NULL,
+                0,
+                &data,
+                sizeof(data),
+                &bytesReturned
+            );
+            
+            IKsPropertySet_Release( pPropertySet );
+        }
+        pClassFactory->lpVtbl->Release( pClassFactory );
+    }
+
+    /*
+        The following code fragment, which I chose not to use, queries for the 
+        device interface for a device with a specific GUID:
+
+        ULONG BytesReturned;
+        DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA Property;
+
+        memset (&Property, 0, sizeof(Property));
+        Property.DataFlow = DIRECTSOUNDDEVICE_DATAFLOW_RENDER;
+        Property.DeviceId = *lpGUID;  
+
+        hr = IKsPropertySet_Get( pPropertySet,
+            &pawin_DSPROPSETID_DirectSoundDevice,
+            DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W,
+            NULL,
+            0,
+            &Property,
+            sizeof(Property),
+            &BytesReturned
+        );
+
+        if( hr == S_OK )
+        {
+            //pnpInterface = Property.Interface;
+        }
+    */
+}
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+
+/* 
+    GUIDs for emulated devices which we blacklist below.
+    are there more than two of them??
+*/
+
+GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};
+GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};
+
+
+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */
+static double defaultSampleRateSearchOrder_[] =
+    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
+        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
+
+/************************************************************************************
+** Extract capabilities from an output device, and add it to the device info list
+** if successful. This function assumes that there is enough room in the
+** device info list to accomodate all entries.
+**
+** The device will not be added to the device list if any errors are encountered.
+*/
+static PaError AddOutputDeviceInfoFromDirectSound(
+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
+{
+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;
+    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
+    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
+    HRESULT                       hr;
+    LPDIRECTSOUND                 lpDirectSound;
+    DSCAPS                        caps;
+    int                           deviceOK = TRUE;
+    PaError                       result = paNoError;
+    int                           i;
+
+    /* Copy GUID to the device info structure. Set pointer. */
+    if( lpGUID == NULL )
+    {
+        winDsDeviceInfo->lpGUID = NULL;
+    }
+    else
+    {
+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
+    }
+    
+    if( lpGUID )
+    {
+        if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||
+            IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )
+        {
+            PA_DEBUG(("BLACKLISTED: %s \n",name));
+            return paNoError;
+        }
+    }
+
+    /* Create a DirectSound object for the specified GUID
+        Note that using CoCreateInstance doesn't work on windows CE.
+    */
+    hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );
+
+    /** try using CoCreateInstance because DirectSoundCreate was hanging under
+        some circumstances - note this was probably related to the
+        #define BOOL short bug which has now been fixed
+        @todo delete this comment and the following code once we've ensured
+        there is no bug.
+    */
+    /*
+    hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,
+            &IID_IDirectSound, (void**)&lpDirectSound );
+
+    if( hr == S_OK )
+    {
+        hr = IDirectSound_Initialize( lpDirectSound, lpGUID );
+    }
+    */
+    
+    if( hr != DS_OK )
+    {
+        if (hr == DSERR_ALLOCATED)
+            PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));
+        DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));
+        if (lpGUID)
+            DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n",
+                 name,
+                 lpGUID->Data1,
+                 lpGUID->Data2,
+                 lpGUID->Data3,
+                 lpGUID->Data4[0],
+                 lpGUID->Data4[1],
+                 lpGUID->Data4[2],
+                 lpGUID->Data4[3],
+                 lpGUID->Data4[4],
+                 lpGUID->Data4[5],
+                 lpGUID->Data4[6],
+                 lpGUID->Data4[7]));
+
+        deviceOK = FALSE;
+    }
+    else
+    {
+        /* Query device characteristics. */
+        memset( &caps, 0, sizeof(caps) ); 
+        caps.dwSize = sizeof(caps);
+        hr = IDirectSound_GetCaps( lpDirectSound, &caps );
+        if( hr != DS_OK )
+        {
+            DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));
+            deviceOK = FALSE;
+        }
+        else
+        {
+
+#if PA_USE_WMME
+            if( caps.dwFlags & DSCAPS_EMULDRIVER )
+            {
+                /* If WMME supported, then reject Emulated drivers because they are lousy. */
+                deviceOK = FALSE;
+            }
+#endif
+
+            if( deviceOK )
+            {
+                deviceInfo->maxInputChannels = 0;
+                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
+
+                /* DS output capabilities only indicate supported number of channels
+                   using two flags which indicate mono and/or stereo.
+                   We assume that stereo devices may support more than 2 channels
+                   (as is the case with 5.1 devices for example) and so
+                   set deviceOutputChannelCountIsKnown to 0 (unknown).
+                   In this case OpenStream will try to open the device
+                   when the user requests more than 2 channels, rather than
+                   returning an error. 
+                */
+                if( caps.dwFlags & DSCAPS_PRIMARYSTEREO )
+                {
+                    deviceInfo->maxOutputChannels = 2;
+                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 0;
+                }
+                else
+                {
+                    deviceInfo->maxOutputChannels = 1;
+                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+                }
+
+                /* Guess channels count from speaker configuration. We do it only when 
+                   pnpInterface is NULL or when PAWIN_USE_WDMKS_DEVICE_INFO is undefined.
+                */
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+                if( !pnpInterface )
+#endif
+                {
+                    DWORD spkrcfg;
+                    if( SUCCEEDED(IDirectSound_GetSpeakerConfig( lpDirectSound, &spkrcfg )) )
+                    {
+                        int count = 0;
+                        switch (DSSPEAKER_CONFIG(spkrcfg))
+                        {
+                            case DSSPEAKER_HEADPHONE:        count = 2; break;
+                            case DSSPEAKER_MONO:             count = 1; break;
+                            case DSSPEAKER_QUAD:             count = 4; break;
+                            case DSSPEAKER_STEREO:           count = 2; break;
+                            case DSSPEAKER_SURROUND:         count = 4; break;
+                            case DSSPEAKER_5POINT1:          count = 6; break;
+                            case DSSPEAKER_7POINT1:          count = 8; break;
+#ifndef DSSPEAKER_7POINT1_SURROUND
+#define DSSPEAKER_7POINT1_SURROUND 0x00000008
+#endif                            
+                            case DSSPEAKER_7POINT1_SURROUND: count = 8; break;
+#ifndef DSSPEAKER_5POINT1_SURROUND
+#define DSSPEAKER_5POINT1_SURROUND 0x00000009
+#endif
+                            case DSSPEAKER_5POINT1_SURROUND: count = 6; break;
+                        }
+                        if( count )
+                        {
+                            deviceInfo->maxOutputChannels = count;
+                            winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+                        }
+                    }
+                }
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+                if( pnpInterface )
+                {
+                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 0  );
+                    if( count > 0 )
+                    {
+                        deviceInfo->maxOutputChannels = count;
+                        winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+                    }
+                }
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+                /* initialize defaultSampleRate */
+                
+                if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )
+                {
+                    /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */
+                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
+
+                    for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
+                    {
+                        if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate
+                                && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate )
+                        {
+                            deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];
+                            break;
+                        }
+                    }
+                }
+                else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )
+                {
+                    if( caps.dwMinSecondarySampleRate == 0 )
+                    {
+                        /*
+                        ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!
+                        ** But it supports continuous sampling.
+                        ** So fake range of rates, and hope it really supports it.
+                        */
+                        deviceInfo->defaultSampleRate = 48000.0f;  /* assume 48000 as the default */
+
+                        DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));
+                    }
+                    else
+                    {
+                        deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
+                    }
+                }
+                else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )
+                {
+                    /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.
+                    ** But we know that they really support a range of rates!
+                    ** So when we see a ridiculous set of rates, assume it is a range.
+                    */
+                  deviceInfo->defaultSampleRate = 48000.0f;  /* assume 48000 as the default */
+                  DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));
+                }
+                else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
+
+                //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );
+                // dwFlags | DSCAPS_CONTINUOUSRATE 
+
+                deviceInfo->defaultLowInputLatency = 0.;
+                deviceInfo->defaultHighInputLatency = 0.;
+
+                deviceInfo->defaultLowOutputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );
+                deviceInfo->defaultHighOutputLatency = deviceInfo->defaultLowOutputLatency * 2;
+            }
+        }
+
+        IDirectSound_Release( lpDirectSound );
+    }
+
+    if( deviceOK )
+    {
+        deviceInfo->name = name;
+
+        if( lpGUID == NULL )
+            hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;
+            
+        hostApi->info.deviceCount++;
+    }
+
+    return result;
+}
+
+
+/************************************************************************************
+** Extract capabilities from an input device, and add it to the device info list
+** if successful. This function assumes that there is enough room in the
+** device info list to accomodate all entries.
+**
+** The device will not be added to the device list if any errors are encountered.
+*/
+static PaError AddInputDeviceInfoFromDirectSoundCapture(
+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
+{
+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;
+    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
+    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
+    HRESULT                       hr;
+    LPDIRECTSOUNDCAPTURE          lpDirectSoundCapture;
+    DSCCAPS                       caps;
+    int                           deviceOK = TRUE;
+    PaError                       result = paNoError;
+    
+    /* Copy GUID to the device info structure. Set pointer. */
+    if( lpGUID == NULL )
+    {
+        winDsDeviceInfo->lpGUID = NULL;
+    }
+    else
+    {
+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
+    }
+
+    hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );
+
+    /** try using CoCreateInstance because DirectSoundCreate was hanging under
+        some circumstances - note this was probably related to the
+        #define BOOL short bug which has now been fixed
+        @todo delete this comment and the following code once we've ensured
+        there is no bug.
+    */
+    /*
+    hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,
+            &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );
+    */
+    if( hr != DS_OK )
+    {
+        DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));
+        deviceOK = FALSE;
+    }
+    else
+    {
+        /* Query device characteristics. */
+        memset( &caps, 0, sizeof(caps) );
+        caps.dwSize = sizeof(caps);
+        hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );
+        if( hr != DS_OK )
+        {
+            DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));
+            deviceOK = FALSE;
+        }
+        else
+        {
+#if PA_USE_WMME
+            if( caps.dwFlags & DSCAPS_EMULDRIVER )
+            {
+                /* If WMME supported, then reject Emulated drivers because they are lousy. */
+                deviceOK = FALSE;
+            }
+#endif
+
+            if( deviceOK )
+            {
+                deviceInfo->maxInputChannels = caps.dwChannels;
+                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
+
+                deviceInfo->maxOutputChannels = 0;
+                winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+                if( pnpInterface )
+                {
+                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 1  );
+                    if( count > 0 )
+                    {
+                        deviceInfo->maxInputChannels = count;
+                        winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
+                    }
+                }
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+/*  constants from a WINE patch by Francois Gouget, see:
+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
+
+    ---
+    Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)
+    From: Francois Gouget <fgouget@ ... .fr>
+    To: Ross Bencina <rbencina@ ... .au>
+    Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library
+
+    [snip]
+
+    I give you permission to use the patch below under the BSD license.
+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
+
+    [snip]
+*/
+#ifndef WAVE_FORMAT_48M08
+#define WAVE_FORMAT_48M08      0x00001000    /* 48     kHz, Mono,   8-bit  */
+#define WAVE_FORMAT_48S08      0x00002000    /* 48     kHz, Stereo, 8-bit  */
+#define WAVE_FORMAT_48M16      0x00004000    /* 48     kHz, Mono,   16-bit */
+#define WAVE_FORMAT_48S16      0x00008000    /* 48     kHz, Stereo, 16-bit */
+#define WAVE_FORMAT_96M08      0x00010000    /* 96     kHz, Mono,   8-bit  */
+#define WAVE_FORMAT_96S08      0x00020000    /* 96     kHz, Stereo, 8-bit  */
+#define WAVE_FORMAT_96M16      0x00040000    /* 96     kHz, Mono,   16-bit */
+#define WAVE_FORMAT_96S16      0x00080000    /* 96     kHz, Stereo, 16-bit */
+#endif
+
+                /* defaultSampleRate */
+                if( caps.dwChannels == 2 )
+                {
+                    if( caps.dwFormats & WAVE_FORMAT_4S16 )
+                        deviceInfo->defaultSampleRate = 44100.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_48S16 )
+                        deviceInfo->defaultSampleRate = 48000.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_2S16 )
+                        deviceInfo->defaultSampleRate = 22050.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_1S16 )
+                        deviceInfo->defaultSampleRate = 11025.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_96S16 )
+                        deviceInfo->defaultSampleRate = 96000.0;
+                    else
+                        deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
+                }
+                else if( caps.dwChannels == 1 )
+                {
+                    if( caps.dwFormats & WAVE_FORMAT_4M16 )
+                        deviceInfo->defaultSampleRate = 44100.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_48M16 )
+                        deviceInfo->defaultSampleRate = 48000.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_2M16 )
+                        deviceInfo->defaultSampleRate = 22050.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_1M16 )
+                        deviceInfo->defaultSampleRate = 11025.0;
+                    else if( caps.dwFormats & WAVE_FORMAT_96M16 )
+                        deviceInfo->defaultSampleRate = 96000.0;
+                    else
+                        deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
+                }
+                else deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
+
+                deviceInfo->defaultLowInputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );
+                deviceInfo->defaultHighInputLatency = deviceInfo->defaultLowInputLatency * 2;
+        
+                deviceInfo->defaultLowOutputLatency = 0.;
+                deviceInfo->defaultHighOutputLatency = 0.;
+            }
+        }
+        
+        IDirectSoundCapture_Release( lpDirectSoundCapture );
+    }
+
+    if( deviceOK )
+    {
+        deviceInfo->name = name;
+
+        if( lpGUID == NULL )
+            hostApi->info.defaultInputDevice = hostApi->info.deviceCount;
+
+        hostApi->info.deviceCount++;
+    }
+
+    return result;
+}
+
+
+/***********************************************************************************/
+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int i, deviceCount;
+    PaWinDsHostApiRepresentation *winDsHostApi;
+    DSDeviceNamesAndGUIDs deviceNamesAndGUIDs;
+    PaWinDsDeviceInfo *deviceInfoArray;
+
+    PaWinDs_InitializeDSoundEntryPoints();
+
+    /* initialise guid vectors so they can be safely deleted on error */
+    deviceNamesAndGUIDs.winDsHostApi = NULL;
+    deviceNamesAndGUIDs.inputNamesAndGUIDs.items = NULL;
+    deviceNamesAndGUIDs.outputNamesAndGUIDs.items = NULL;
+
+    winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );
+    if( !winDsHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    memset( winDsHostApi, 0, sizeof(PaWinDsHostApiRepresentation) ); /* ensure all fields are zeroed. especially winDsHostApi->allocations */
+
+    result = PaWinUtil_CoInitialize( paDirectSound, &winDsHostApi->comInitializationResult );
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    winDsHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !winDsHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi = &winDsHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paDirectSound;
+    (*hostApi)->info.name = "Windows DirectSound";
+    
+    (*hostApi)->info.deviceCount = 0;
+    (*hostApi)->info.defaultInputDevice = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+
+    
+/* DSound - enumerate devices to count them and to gather their GUIDs */
+
+    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs, winDsHostApi->allocations );
+    if( result != paNoError )
+        goto error;
+
+    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs, winDsHostApi->allocations );
+    if( result != paNoError )
+        goto error;
+
+    paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW( (LPDSENUMCALLBACKW)CollectGUIDsProcW, (void *)&deviceNamesAndGUIDs.inputNamesAndGUIDs );
+
+    paWinDsDSoundEntryPoints.DirectSoundEnumerateW( (LPDSENUMCALLBACKW)CollectGUIDsProcW, (void *)&deviceNamesAndGUIDs.outputNamesAndGUIDs );
+
+    if( deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError != paNoError )
+    {
+        result = deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError;
+        goto error;
+    }
+
+    if( deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError != paNoError )
+    {
+        result = deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError;
+        goto error;
+    }
+
+    deviceCount = deviceNamesAndGUIDs.inputNamesAndGUIDs.count + deviceNamesAndGUIDs.outputNamesAndGUIDs.count;
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+    if( deviceCount > 0 )
+    {
+        deviceNamesAndGUIDs.winDsHostApi = winDsHostApi;
+        FindDevicePnpInterfaces( &deviceNamesAndGUIDs );
+    }
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+    if( deviceCount > 0 )
+    {
+        /* allocate array for pointers to PaDeviceInfo structs */
+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );
+        if( !(*hostApi)->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all PaDeviceInfo structs in a contiguous block */
+        deviceInfoArray = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(
+                winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for( i=0; i < deviceCount; ++i )
+        {
+            PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo;
+            deviceInfo->structVersion = 2;
+            deviceInfo->hostApi = hostApiIndex;
+            deviceInfo->name = 0;
+            (*hostApi)->deviceInfos[i] = deviceInfo;
+        }
+
+        for( i=0; i < deviceNamesAndGUIDs.inputNamesAndGUIDs.count; ++i )
+        {
+            result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,
+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].name,
+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].lpGUID,
+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].pnpInterface );
+            if( result != paNoError )
+                goto error;
+        }
+
+        for( i=0; i < deviceNamesAndGUIDs.outputNamesAndGUIDs.count; ++i )
+        {
+            result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,
+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].name,
+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].lpGUID,
+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].pnpInterface );
+            if( result != paNoError )
+                goto error;
+        }
+    }    
+
+    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
+    if( result != paNoError )
+        goto error;
+
+    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
+    if( result != paNoError )
+        goto error;
+
+    
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    return result;
+
+error:
+    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
+    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
+
+    Terminate( (struct PaUtilHostApiRepresentation *)winDsHostApi );
+
+    return result;
+}
+
+
+/***********************************************************************************/
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
+
+    if( winDsHostApi ){
+        if( winDsHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( winDsHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
+        }
+
+        PaWinUtil_CoUninitialize( paDirectSound, &winDsHostApi->comInitializationResult );
+
+        PaUtil_FreeMemory( winDsHostApi );
+    }
+
+    PaWinDs_TerminateDSoundEntryPoints();
+}
+
+static PaError ValidateWinDirectSoundSpecificStreamInfo(
+        const PaStreamParameters *streamParameters,
+        const PaWinDirectSoundStreamInfo *streamInfo )
+{
+    if( streamInfo )
+    {
+        if( streamInfo->size != sizeof( PaWinDirectSoundStreamInfo )
+                || streamInfo->version != 2 )
+        {
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        if( streamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
+        {
+            if( streamInfo->framesPerBuffer <= 0 )
+                return paIncompatibleHostApiSpecificStreamInfo;
+
+        }
+    }
+
+    return paNoError;
+}
+
+/***********************************************************************************/
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaError result;
+    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
+
+    if( inputParameters )
+    {
+        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
+        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
+                && inputChannelCount > inputDeviceInfo->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
+        if( result != paNoError ) return result;
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
+        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
+                && outputChannelCount > outputDeviceInfo->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
+        if( result != paNoError ) return result;
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+    
+    /*
+        IMPLEMENT ME:
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported if necessary
+
+            - check that the device supports sampleRate
+
+        Because the buffer adapter handles conversion between all standard
+        sample formats, the following checks are only required if paCustomFormat
+        is implemented, or under some other unusual conditions.
+
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+    */
+
+    return paFormatIsSupported;
+}
+
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+static HRESULT InitFullDuplexInputOutputBuffers( PaWinDsStream *stream,
+                                       PaWinDsDeviceInfo *inputDevice,
+                                       PaSampleFormat hostInputSampleFormat,
+                                       WORD inputChannelCount, 
+                                       int bytesPerInputBuffer,
+                                       PaWinWaveFormatChannelMask inputChannelMask,
+                                       PaWinDsDeviceInfo *outputDevice,
+                                       PaSampleFormat hostOutputSampleFormat,
+                                       WORD outputChannelCount, 
+                                       int bytesPerOutputBuffer,
+                                       PaWinWaveFormatChannelMask outputChannelMask,
+                                       unsigned long nFrameRate
+                                        )
+{
+    HRESULT hr;
+    DSCBUFFERDESC  captureDesc;
+    PaWinWaveFormat captureWaveFormat;
+    DSBUFFERDESC   secondaryRenderDesc;
+    PaWinWaveFormat renderWaveFormat;
+    LPDIRECTSOUNDBUFFER8 pRenderBuffer8;
+    LPDIRECTSOUNDCAPTUREBUFFER8 pCaptureBuffer8;
+
+    // capture buffer description
+
+    // only try wave format extensible. assume it's available on all ds 8 systems
+    PaWin_InitializeWaveFormatExtensible( &captureWaveFormat, inputChannelCount, 
+                hostInputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostInputSampleFormat ),
+                nFrameRate, inputChannelMask );
+
+    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
+    captureDesc.dwSize = sizeof(DSCBUFFERDESC);
+    captureDesc.dwFlags = 0;
+    captureDesc.dwBufferBytes = bytesPerInputBuffer;
+    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&captureWaveFormat;
+
+    // render buffer description
+
+    PaWin_InitializeWaveFormatExtensible( &renderWaveFormat, outputChannelCount, 
+                hostOutputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostOutputSampleFormat ),
+                nFrameRate, outputChannelMask );
+
+    ZeroMemory(&secondaryRenderDesc, sizeof(DSBUFFERDESC));
+    secondaryRenderDesc.dwSize = sizeof(DSBUFFERDESC);
+    secondaryRenderDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
+    secondaryRenderDesc.dwBufferBytes = bytesPerOutputBuffer;
+    secondaryRenderDesc.lpwfxFormat = (WAVEFORMATEX*)&renderWaveFormat;
+
+    /* note that we don't create a primary buffer here at all */
+
+    hr = paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8( 
+            inputDevice->lpGUID, outputDevice->lpGUID,
+            &captureDesc, &secondaryRenderDesc,
+            GetDesktopWindow(), /* see InitOutputBuffer() for a discussion of whether this is a good idea */
+            DSSCL_EXCLUSIVE,
+            &stream->pDirectSoundFullDuplex8,
+            &pCaptureBuffer8,
+            &pRenderBuffer8,
+            NULL /* pUnkOuter must be NULL */ 
+        );
+
+    if( hr == DS_OK )
+    {
+        PA_DEBUG(("DirectSoundFullDuplexCreate succeeded!\n"));
+
+        /* retrieve the pre ds 8 buffer interfaces which are used by the rest of the code */
+
+        hr = IUnknown_QueryInterface( pCaptureBuffer8, &IID_IDirectSoundCaptureBuffer, (LPVOID *)&stream->pDirectSoundInputBuffer );
+        
+        if( hr == DS_OK )
+            hr = IUnknown_QueryInterface( pRenderBuffer8, &IID_IDirectSoundBuffer, (LPVOID *)&stream->pDirectSoundOutputBuffer );
+
+        /* release the ds 8 interfaces, we don't need them */
+        IUnknown_Release( pCaptureBuffer8 );
+        IUnknown_Release( pRenderBuffer8 );
+
+        if( !stream->pDirectSoundInputBuffer || !stream->pDirectSoundOutputBuffer ){
+            /* couldn't get pre ds 8 interfaces for some reason. clean up. */
+            if( stream->pDirectSoundInputBuffer )
+            {
+                IUnknown_Release( stream->pDirectSoundInputBuffer );
+                stream->pDirectSoundInputBuffer = NULL;
+            }
+
+            if( stream->pDirectSoundOutputBuffer )
+            {
+                IUnknown_Release( stream->pDirectSoundOutputBuffer );
+                stream->pDirectSoundOutputBuffer = NULL;
+            }
+            
+            IUnknown_Release( stream->pDirectSoundFullDuplex8 );
+            stream->pDirectSoundFullDuplex8 = NULL;
+        }
+    }
+    else
+    {
+        PA_DEBUG(("DirectSoundFullDuplexCreate failed. hr=%d\n", hr));
+    }
+
+    return hr;
+}
+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
+
+
+static HRESULT InitInputBuffer( PaWinDsStream *stream, 
+                               PaWinDsDeviceInfo *device, 
+                               PaSampleFormat sampleFormat, 
+                               unsigned long nFrameRate, 
+                               WORD nChannels, 
+                               int bytesPerBuffer, 
+                               PaWinWaveFormatChannelMask channelMask )
+{
+    DSCBUFFERDESC  captureDesc;
+    PaWinWaveFormat waveFormat;
+    HRESULT        result;
+    
+    if( (result = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( 
+            device->lpGUID, &stream->pDirectSoundCapture, NULL) ) != DS_OK ){
+         ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
+         return result;
+    }
+
+    // Setup the secondary buffer description
+    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
+    captureDesc.dwSize = sizeof(DSCBUFFERDESC);
+    captureDesc.dwFlags = 0;
+    captureDesc.dwBufferBytes = bytesPerBuffer;
+    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat;
+    
+    // Create the capture buffer
+
+    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
+    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, 
+                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
+                nFrameRate, channelMask );
+
+    if( IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
+                  &captureDesc, &stream->pDirectSoundInputBuffer, NULL) != DS_OK )
+    {
+        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, 
+                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
+
+        if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
+                    &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;
+    }
+
+    stream->readOffset = 0;  // reset last read position to start of buffer
+    return DS_OK;
+}
+
+
+static HRESULT InitOutputBuffer( PaWinDsStream *stream, PaWinDsDeviceInfo *device, 
+                                PaSampleFormat sampleFormat, unsigned long nFrameRate, 
+                                WORD nChannels, int bytesPerBuffer, 
+                                PaWinWaveFormatChannelMask channelMask )
+{
+    HRESULT        result;
+    HWND           hWnd;
+    HRESULT        hr;
+    PaWinWaveFormat waveFormat;
+    DSBUFFERDESC   primaryDesc;
+    DSBUFFERDESC   secondaryDesc;
+    
+    if( (hr = paWinDsDSoundEntryPoints.DirectSoundCreate( 
+                device->lpGUID, &stream->pDirectSound, NULL )) != DS_OK ){
+        ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
+        return hr;
+    }
+
+    // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the
+    // applications's window. Also if that window is closed before the Buffer is closed
+    // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)
+    // So we will use GetDesktopWindow() which was suggested by Miller Puckette.
+    // hWnd = GetForegroundWindow();
+    //
+    //  FIXME: The example code I have on the net creates a hidden window that
+    //      is managed by our code - I think we should do that - one hidden
+    //      window for the whole of Pa_DS
+    //
+    hWnd = GetDesktopWindow();
+
+    // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.
+    // exclusive also prevents unexpected sounds from other apps during a performance.
+    if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,
+              hWnd, DSSCL_EXCLUSIVE)) != DS_OK)
+    {
+        return hr;
+    }
+
+    // -----------------------------------------------------------------------
+    // Create primary buffer and set format just so we can specify our custom format.
+    // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.
+    // Setup the primary buffer description
+    ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));
+    primaryDesc.dwSize        = sizeof(DSBUFFERDESC);
+    primaryDesc.dwFlags       = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth
+    primaryDesc.dwBufferBytes = 0;
+    primaryDesc.lpwfxFormat   = NULL;
+    // Create the buffer
+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
+                  &primaryDesc, &stream->pDirectSoundPrimaryBuffer, NULL)) != DS_OK)
+        goto error;
+
+    // Set the primary buffer's format
+
+    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
+    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, 
+                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
+                nFrameRate, channelMask );
+
+    if( IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat) != DS_OK )
+    {
+        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, 
+                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
+
+        if((result = IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat)) != DS_OK)
+            goto error;
+    }
+
+    // ----------------------------------------------------------------------
+    // Setup the secondary buffer description
+    ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));
+    secondaryDesc.dwSize = sizeof(DSBUFFERDESC);
+    secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
+    secondaryDesc.dwBufferBytes = bytesPerBuffer;
+    secondaryDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; /* waveFormat contains whatever format was negotiated for the primary buffer above */
+    // Create the secondary buffer
+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
+                  &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK)
+      goto error;
+    
+    return DS_OK;
+
+error:
+
+    if( stream->pDirectSoundPrimaryBuffer )
+    {
+        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
+        stream->pDirectSoundPrimaryBuffer = NULL;
+    }
+
+    return result;
+}
+
+
+static void CalculateBufferSettings( unsigned long *hostBufferSizeFrames, 
+                                    unsigned long *pollingPeriodFrames,
+                                    int isFullDuplex,
+                                    unsigned long suggestedInputLatencyFrames,
+                                    unsigned long suggestedOutputLatencyFrames,
+                                    double sampleRate, unsigned long userFramesPerBuffer )
+{
+    unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);
+    unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);
+    unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);
+    
+    if( userFramesPerBuffer == paFramesPerBufferUnspecified )
+    {
+        unsigned long targetBufferingLatencyFrames = max( suggestedInputLatencyFrames, suggestedOutputLatencyFrames );
+
+        *pollingPeriodFrames = targetBufferingLatencyFrames / 4;
+        if( *pollingPeriodFrames < minimumPollingPeriodFrames )
+        {
+            *pollingPeriodFrames = minimumPollingPeriodFrames;
+        }
+        else if( *pollingPeriodFrames > maximumPollingPeriodFrames )
+        {
+            *pollingPeriodFrames = maximumPollingPeriodFrames;
+        }
+
+        *hostBufferSizeFrames = *pollingPeriodFrames 
+                + max( *pollingPeriodFrames + pollingJitterFrames, targetBufferingLatencyFrames);
+    }
+    else
+    {
+        unsigned long targetBufferingLatencyFrames = suggestedInputLatencyFrames;
+        if( isFullDuplex )
+        {
+            /* In full duplex streams we know that the buffer adapter adds userFramesPerBuffer
+               extra fixed latency. so we subtract it here as a fixed latency before computing
+               the buffer size. being careful not to produce an unrepresentable negative result.
+               
+               Note: this only works as expected if output latency is greater than input latency.
+               Otherwise we use input latency anyway since we do max(in,out).
+            */
+
+            if( userFramesPerBuffer < suggestedOutputLatencyFrames )
+            {
+                unsigned long adjustedSuggestedOutputLatencyFrames = 
+                        suggestedOutputLatencyFrames - userFramesPerBuffer;
+
+                /* maximum of input and adjusted output suggested latency */
+                if( adjustedSuggestedOutputLatencyFrames > targetBufferingLatencyFrames )
+                    targetBufferingLatencyFrames = adjustedSuggestedOutputLatencyFrames;
+            }
+        }
+        else
+        {
+            /* maximum of input and output suggested latency */
+            if( suggestedOutputLatencyFrames > suggestedInputLatencyFrames )
+                targetBufferingLatencyFrames = suggestedOutputLatencyFrames;
+        }   
+
+        *hostBufferSizeFrames = userFramesPerBuffer 
+                + max( userFramesPerBuffer + pollingJitterFrames, targetBufferingLatencyFrames);
+
+        *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), targetBufferingLatencyFrames / 16 );
+
+        if( *pollingPeriodFrames > maximumPollingPeriodFrames )
+        {
+            *pollingPeriodFrames = maximumPollingPeriodFrames;
+        }
+    } 
+}
+
+
+static void CalculatePollingPeriodFrames( unsigned long hostBufferSizeFrames, 
+                                    unsigned long *pollingPeriodFrames,
+                                    double sampleRate, unsigned long userFramesPerBuffer )
+{
+    unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);
+    unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);
+    unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);
+
+    *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), hostBufferSizeFrames / 16 );
+
+    if( *pollingPeriodFrames > maximumPollingPeriodFrames )
+    {
+        *pollingPeriodFrames = maximumPollingPeriodFrames;
+    }
+}
+
+
+static void SetStreamInfoLatencies( PaWinDsStream *stream, 
+                                   unsigned long userFramesPerBuffer, 
+                                   unsigned long pollingPeriodFrames,
+                                   double sampleRate )
+{
+    /* compute the stream info actual latencies based on framesPerBuffer, polling period, hostBufferSizeFrames, 
+    and the configuration of the buffer processor */
+
+    unsigned long effectiveFramesPerBuffer = (userFramesPerBuffer == paFramesPerBufferUnspecified)
+                                             ? pollingPeriodFrames
+                                             : userFramesPerBuffer;
+
+    if( stream->bufferProcessor.inputChannelCount > 0 )
+    {
+        /* stream info input latency is the minimum buffering latency 
+           (unlike suggested and default which are *maximums*) */
+        stream->streamRepresentation.streamInfo.inputLatency =
+                (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
+                    + effectiveFramesPerBuffer) / sampleRate;
+    }
+    else
+    {
+        stream->streamRepresentation.streamInfo.inputLatency = 0;
+    }
+
+    if( stream->bufferProcessor.outputChannelCount > 0 )
+    {
+        stream->streamRepresentation.streamInfo.outputLatency =
+                (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
+                    + (stream->hostBufferSizeFrames - effectiveFramesPerBuffer)) / sampleRate;
+    }
+    else
+    {
+        stream->streamRepresentation.streamInfo.outputLatency = 0;
+    }
+}
+
+
+/***********************************************************************************/
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
+    PaWinDsStream *stream = 0;
+    int bufferProcessorIsInitialized = 0;
+    int streamRepresentationIsInitialized = 0;
+    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+    int userRequestedHostInputBufferSizeFrames = 0;
+    int userRequestedHostOutputBufferSizeFrames = 0;
+    unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;
+    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
+    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
+    unsigned long pollingPeriodFrames = 0;
+
+    if( inputParameters )
+    {
+        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
+        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);
+
+        /* IDEA: the following 3 checks could be performed by default by pa_front
+            unless some flag indicated otherwise */
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
+                && inputChannelCount > inputDeviceInfo->maxInputChannels )
+            return paInvalidChannelCount;
+            
+        /* validate hostApiSpecificStreamInfo */
+        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
+        if( result != paNoError ) return result;
+
+        if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
+            userRequestedHostInputBufferSizeFrames = inputStreamInfo->framesPerBuffer;
+
+        if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseChannelMask )
+            inputChannelMask = inputStreamInfo->channelMask;
+        else
+            inputChannelMask = PaWin_DefaultChannelMask( inputChannelCount );
+    }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = 0;
+        suggestedInputLatencyFrames = 0;
+    }
+
+
+    if( outputParameters )
+    {
+        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
+        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support outputChannelCount */
+        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
+                && outputChannelCount > outputDeviceInfo->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate hostApiSpecificStreamInfo */
+        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
+        if( result != paNoError ) return result;   
+
+        if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
+            userRequestedHostOutputBufferSizeFrames = outputStreamInfo->framesPerBuffer;
+
+        if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseChannelMask )
+            outputChannelMask = outputStreamInfo->channelMask;
+        else
+            outputChannelMask = PaWin_DefaultChannelMask( outputChannelCount );
+    }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = 0;
+        suggestedOutputLatencyFrames = 0;
+    }
+
+    /*
+        If low level host buffer size is specified for both input and output
+        the current code requires the sizes to match.
+    */
+
+    if( (userRequestedHostInputBufferSizeFrames > 0 && userRequestedHostOutputBufferSizeFrames > 0)
+            && userRequestedHostInputBufferSizeFrames != userRequestedHostOutputBufferSizeFrames )
+        return paIncompatibleHostApiSpecificStreamInfo;
+
+
+
+    /*
+        IMPLEMENT ME:
+
+        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )
+
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+
+            - check that the device supports sampleRate
+
+            - alter sampleRate to a close allowable rate if possible / necessary
+
+            - validate suggestedInputLatency and suggestedOutputLatency parameters,
+                use default values where necessary
+    */
+
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+
+
+    stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */
+
+    if( streamCallback )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &winDsHostApi->callbackStreamInterface, streamCallback, userData );
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &winDsHostApi->blockingStreamInterface, streamCallback, userData );
+    }
+    
+    streamRepresentationIsInitialized = 1;
+
+    stream->streamFlags = streamFlags;
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+    if( inputParameters )
+    {
+        /* IMPLEMENT ME - establish which  host formats are available */
+        PaSampleFormat nativeInputFormats = paInt16;
+        /* PaSampleFormat nativeFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */
+
+        hostInputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( nativeInputFormats, inputParameters->sampleFormat );
+    }
+    else
+    {
+        hostInputSampleFormat = 0;
+    }
+
+    if( outputParameters )
+    {
+        /* IMPLEMENT ME - establish which  host formats are available */
+        PaSampleFormat nativeOutputFormats = paInt16;
+        /* PaSampleFormat nativeOutputFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */
+
+        hostOutputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( nativeOutputFormats, outputParameters->sampleFormat );
+    }
+    else
+    {
+        hostOutputSampleFormat = 0;
+    }
+
+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+                    sampleRate, streamFlags, framesPerBuffer,
+                    0, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */
+                /* This next mode is required because DS can split the host buffer when it wraps around. */
+                    paUtilVariableHostBufferSizePartialUsageAllowed,
+                    streamCallback, userData );
+    if( result != paNoError )
+        goto error;
+
+    bufferProcessorIsInitialized = 1;
+
+   
+/* DirectSound specific initialization */ 
+    {
+        HRESULT          hr;
+        unsigned long    integerSampleRate = (unsigned long) (sampleRate + 0.5);
+        
+        stream->processingCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );
+        if( stream->processingCompleted == NULL )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+#ifdef PA_WIN_DS_USE_WMME_TIMER
+        stream->timerID = 0;
+#endif
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+        stream->waitableTimer = (HANDLE)CreateWaitableTimer( 0, FALSE, NULL );
+        if( stream->waitableTimer == NULL )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
+            goto error;
+        }
+#endif
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+        stream->processingThreadCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );
+        if( stream->processingThreadCompleted == NULL )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
+            goto error;
+        }
+#endif
+
+        /* set up i/o parameters */
+
+        if( userRequestedHostInputBufferSizeFrames > 0 || userRequestedHostOutputBufferSizeFrames > 0 )
+        {
+            /* use low level parameters */
+
+            /* since we use the same host buffer size for input and output
+               we choose the highest user specified value.
+            */
+            stream->hostBufferSizeFrames = max( userRequestedHostInputBufferSizeFrames, userRequestedHostOutputBufferSizeFrames );
+
+            CalculatePollingPeriodFrames( 
+                    stream->hostBufferSizeFrames, &pollingPeriodFrames,
+                    sampleRate, framesPerBuffer );
+        }
+        else
+        {
+            CalculateBufferSettings( &stream->hostBufferSizeFrames, &pollingPeriodFrames,
+                    /* isFullDuplex = */ (inputParameters && outputParameters),
+                    suggestedInputLatencyFrames,
+                    suggestedOutputLatencyFrames, 
+                    sampleRate, framesPerBuffer );
+        }
+
+        stream->pollingPeriodSeconds = pollingPeriodFrames / sampleRate;
+
+        DBUG(("DirectSound host buffer size frames: %d, polling period seconds: %f, @ sr: %f\n", 
+                stream->hostBufferSizeFrames, stream->pollingPeriodSeconds, sampleRate ));
+
+
+        /* ------------------ OUTPUT */
+        if( outputParameters )
+        {
+            LARGE_INTEGER  counterFrequency;
+
+            /*
+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];
+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));
+            */
+            
+            int sampleSizeBytes = Pa_GetSampleSize(hostOutputSampleFormat);
+            stream->outputFrameSizeBytes = outputParameters->channelCount * sampleSizeBytes;
+
+            stream->outputBufferSizeBytes = stream->hostBufferSizeFrames * stream->outputFrameSizeBytes;
+            if( stream->outputBufferSizeBytes < DSBSIZE_MIN )
+            {
+                result = paBufferTooSmall;
+                goto error;
+            }
+            else if( stream->outputBufferSizeBytes > DSBSIZE_MAX )
+            {
+                result = paBufferTooBig;
+                goto error;
+            }
+
+            /* Calculate value used in latency calculation to avoid real-time divides. */
+            stream->secondsPerHostByte = 1.0 /
+                (stream->bufferProcessor.bytesPerHostOutputSample *
+                outputChannelCount * sampleRate);
+
+            stream->outputIsRunning = FALSE;
+            stream->outputUnderflowCount = 0;
+            
+            /* perfCounterTicksPerBuffer is used by QueryOutputSpace for overflow detection */
+            if( QueryPerformanceFrequency( &counterFrequency ) )
+            {
+                stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * stream->hostBufferSizeFrames) / integerSampleRate;
+            }
+            else
+            {
+                stream->perfCounterTicksPerBuffer.QuadPart = 0;
+            }
+        }
+
+        /* ------------------ INPUT */
+        if( inputParameters )
+        {
+            /*
+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];
+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));
+            */
+            
+            int sampleSizeBytes = Pa_GetSampleSize(hostInputSampleFormat);
+            stream->inputFrameSizeBytes = inputParameters->channelCount * sampleSizeBytes;
+
+            stream->inputBufferSizeBytes = stream->hostBufferSizeFrames * stream->inputFrameSizeBytes;
+            if( stream->inputBufferSizeBytes < DSBSIZE_MIN )
+            {
+                result = paBufferTooSmall;
+                goto error;
+            }
+            else if( stream->inputBufferSizeBytes > DSBSIZE_MAX )
+            {
+                result = paBufferTooBig;
+                goto error;
+            }
+        }
+
+        /* open/create the DirectSound buffers */
+
+        /* interface ptrs should be zeroed when stream is zeroed. */
+        assert( stream->pDirectSoundCapture == NULL );
+        assert( stream->pDirectSoundInputBuffer == NULL );
+        assert( stream->pDirectSound == NULL );
+        assert( stream->pDirectSoundPrimaryBuffer == NULL );
+        assert( stream->pDirectSoundOutputBuffer == NULL );
+        
+
+        if( inputParameters && outputParameters )
+        {
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+            /* try to use the full-duplex DX8 API to create the buffers.
+                if that fails we fall back to the half-duplex API below */
+
+            hr = InitFullDuplexInputOutputBuffers( stream,
+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
+                                       hostInputSampleFormat,
+                                       (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,
+                                       inputChannelMask,
+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
+                                       hostOutputSampleFormat,
+                                       (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,
+                                       outputChannelMask,
+                                       integerSampleRate
+                                        );
+            DBUG(("InitFullDuplexInputOutputBuffers() returns %x\n", hr));
+            /* ignore any error returned by InitFullDuplexInputOutputBuffers. 
+                we retry opening the buffers below */
+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
+        }
+
+        /*  create half duplex buffers. also used for full-duplex streams which didn't 
+            succeed when using the full duplex API. that could happen because
+            DX8 or greater isnt installed, the i/o devices aren't the same 
+            physical device. etc.
+        */
+
+        if( outputParameters && !stream->pDirectSoundOutputBuffer )
+        {
+            hr = InitOutputBuffer( stream,
+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
+                                       hostOutputSampleFormat,
+                                       integerSampleRate,
+                                       (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,
+                                       outputChannelMask );
+            DBUG(("InitOutputBuffer() returns %x\n", hr));
+            if( hr != DS_OK )
+            {
+                result = paUnanticipatedHostError;
+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
+                goto error;
+            }
+        }
+
+        if( inputParameters && !stream->pDirectSoundInputBuffer )
+        {
+            hr = InitInputBuffer( stream,
+                                      (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
+                                      hostInputSampleFormat,
+                                      integerSampleRate,
+                                      (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,
+                                      inputChannelMask );
+            DBUG(("InitInputBuffer() returns %x\n", hr));
+            if( hr != DS_OK )
+            {
+                ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
+                result = paUnanticipatedHostError;
+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
+                goto error;
+            }
+        }
+    }
+
+    SetStreamInfoLatencies( stream, framesPerBuffer, pollingPeriodFrames, sampleRate );
+
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( stream )
+    {
+        if( stream->processingCompleted != NULL )
+            CloseHandle( stream->processingCompleted );
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+        if( stream->waitableTimer != NULL )
+            CloseHandle( stream->waitableTimer );
+#endif
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+        if( stream->processingThreadCompleted != NULL )
+            CloseHandle( stream->processingThreadCompleted );
+#endif
+
+        if( stream->pDirectSoundOutputBuffer )
+        {
+            IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
+            IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
+            stream->pDirectSoundOutputBuffer = NULL;
+        }
+
+        if( stream->pDirectSoundPrimaryBuffer )
+        {
+            IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
+            stream->pDirectSoundPrimaryBuffer = NULL;
+        }
+
+        if( stream->pDirectSoundInputBuffer )
+        {
+            IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
+            IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
+            stream->pDirectSoundInputBuffer = NULL;
+        }
+
+        if( stream->pDirectSoundCapture )
+        {
+            IDirectSoundCapture_Release( stream->pDirectSoundCapture );
+            stream->pDirectSoundCapture = NULL;
+        }
+
+        if( stream->pDirectSound )
+        {
+            IDirectSound_Release( stream->pDirectSound );
+            stream->pDirectSound = NULL;
+        }
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+        if( stream->pDirectSoundFullDuplex8 )
+        {
+            IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
+            stream->pDirectSoundFullDuplex8 = NULL;
+        }
+#endif
+        if( bufferProcessorIsInitialized )
+            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+        if( streamRepresentationIsInitialized )
+            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+        PaUtil_FreeMemory( stream );
+    }
+
+    return result;
+}
+
+
+/************************************************************************************
+ * Determine how much space can be safely written to in DS buffer.
+ * Detect underflows and overflows.
+ * Does not allow writing into safety gap maintained by DirectSound.
+ */
+static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )
+{
+    HRESULT hr;
+    DWORD   playCursor;
+    DWORD   writeCursor;
+    long    numBytesEmpty;
+    long    playWriteGap;
+    // Query to see how much room is in buffer.
+    hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
+            &playCursor, &writeCursor );
+    if( hr != DS_OK )
+    {
+        return hr;
+    }
+
+    // Determine size of gap between playIndex and WriteIndex that we cannot write into.
+    playWriteGap = writeCursor - playCursor;
+    if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap
+
+    /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */
+    /* Attempt to detect playCursor wrap-around and correct it. */
+    if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )
+    {
+        /* How much time has elapsed since last check. */
+        LARGE_INTEGER   currentTime;
+        LARGE_INTEGER   elapsedTime;
+        long            bytesPlayed;
+        long            bytesExpected;
+        long            buffersWrapped;
+
+        QueryPerformanceCounter( &currentTime );
+        elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;
+        stream->previousPlayTime = currentTime;
+
+        /* How many bytes does DirectSound say have been played. */
+        bytesPlayed = playCursor - stream->previousPlayCursor;
+        if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap
+        stream->previousPlayCursor = playCursor;
+
+        /* Calculate how many bytes we would have expected to been played by now. */
+        bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);
+        buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;
+        if( buffersWrapped > 0 )
+        {
+            playCursor += (buffersWrapped * stream->outputBufferSizeBytes);
+            bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);
+        }
+    }
+    numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;
+    if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset
+
+    /* Have we underflowed? */
+    if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )
+    {
+        if( stream->outputIsRunning )
+        {
+            stream->outputUnderflowCount += 1;
+        }
+
+        /*
+            From MSDN:
+                The write cursor indicates the position at which it is safe  
+            to write new data to the buffer. The write cursor always leads the
+            play cursor, typically by about 15 milliseconds' worth of audio
+            data.
+                It is always safe to change data that is behind the position 
+            indicated by the lpdwCurrentPlayCursor parameter.
+        */
+
+        stream->outputBufferWriteOffsetBytes = writeCursor;
+        numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;
+    }
+    *bytesEmpty = numBytesEmpty;
+    return hr;
+}
+
+/***********************************************************************************/
+static int TimeSlice( PaWinDsStream *stream )
+{
+    long              numFrames = 0;
+    long              bytesEmpty = 0;
+    long              bytesFilled = 0;
+    long              bytesToXfer = 0;
+    long              framesToXfer = 0; /* the number of frames we'll process this tick */
+    long              numInFramesReady = 0;
+    long              numOutFramesReady = 0;
+    long              bytesProcessed;
+    HRESULT           hresult;
+    double            outputLatency = 0;
+    double            inputLatency = 0;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+    
+/* Input */
+    LPBYTE            lpInBuf1 = NULL;
+    LPBYTE            lpInBuf2 = NULL;
+    DWORD             dwInSize1 = 0;
+    DWORD             dwInSize2 = 0;
+/* Output */
+    LPBYTE            lpOutBuf1 = NULL;
+    LPBYTE            lpOutBuf2 = NULL;
+    DWORD             dwOutSize1 = 0;
+    DWORD             dwOutSize2 = 0;
+
+    /* How much input data is available? */
+    if( stream->bufferProcessor.inputChannelCount > 0 )
+    {
+        HRESULT hr;
+        DWORD capturePos;
+        DWORD readPos;
+        long  filled = 0;
+        // Query to see how much data is in buffer.
+        // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly
+        // so let's pass a pointer just to be safe.
+        hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );
+        if( hr == DS_OK )
+        {
+            filled = readPos - stream->readOffset;
+            if( filled < 0 ) filled += stream->inputBufferSizeBytes; // unwrap offset
+            bytesFilled = filled;
+
+            inputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;
+        }
+            // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?
+
+        framesToXfer = numInFramesReady = bytesFilled / stream->inputFrameSizeBytes; 
+
+        /** @todo Check for overflow */
+    }
+
+    /* How much output room is available? */
+    if( stream->bufferProcessor.outputChannelCount > 0 )
+    {
+        UINT previousUnderflowCount = stream->outputUnderflowCount;
+        QueryOutputSpace( stream, &bytesEmpty );
+        framesToXfer = numOutFramesReady = bytesEmpty / stream->outputFrameSizeBytes;
+
+        /* Check for underflow */
+        /* FIXME QueryOutputSpace should not adjust underflow count as a side effect. 
+            A query function should be a const operator on the stream and return a flag on underflow. */
+        if( stream->outputUnderflowCount != previousUnderflowCount )
+            stream->callbackFlags |= paOutputUnderflow;
+
+        /* We are about to compute audio into the first byte of empty space in the output buffer.
+           This audio will reach the DAC after all of the current (non-empty) audio
+           in the buffer has played. Therefore the output time is the current time
+           plus the time it takes to play the non-empty bytes in the buffer,
+           computed here:
+        */
+        outputLatency = ((double)(stream->outputBufferSizeBytes - bytesEmpty)) * stream->secondsPerHostByte;
+    }
+
+    /* if it's a full duplex stream, set framesToXfer to the minimum of input and output frames ready */
+    if( stream->bufferProcessor.inputChannelCount > 0 && stream->bufferProcessor.outputChannelCount > 0 )
+    {
+        framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;
+    }
+
+    if( framesToXfer > 0 )
+    {
+        PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+    /* The outputBufferDacTime parameter should indicates the time at which
+        the first sample of the output buffer is heard at the DACs. */
+        timeInfo.currentTime = PaUtil_GetTime();
+
+        PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );
+        stream->callbackFlags = 0;
+        
+    /* Input */
+        if( stream->bufferProcessor.inputChannelCount > 0 )
+        {
+            timeInfo.inputBufferAdcTime = timeInfo.currentTime - inputLatency; 
+
+            bytesToXfer = framesToXfer * stream->inputFrameSizeBytes;
+            hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,
+                stream->readOffset, bytesToXfer,
+                (void **) &lpInBuf1, &dwInSize1,
+                (void **) &lpInBuf2, &dwInSize2, 0);
+            if (hresult != DS_OK)
+            {
+                ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));
+                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
+                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
+                stream->callbackResult = paComplete;
+                goto error2;
+            }
+
+            numFrames = dwInSize1 / stream->inputFrameSizeBytes;
+            PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );
+            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );
+        /* Is input split into two regions. */
+            if( dwInSize2 > 0 )
+            {
+                numFrames = dwInSize2 / stream->inputFrameSizeBytes;
+                PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );
+                PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );
+            }
+        }
+
+    /* Output */
+        if( stream->bufferProcessor.outputChannelCount > 0 )
+        {
+            /*
+            We don't currently add outputLatency here because it appears to produce worse
+            results than not adding it. Need to do more testing to verify this.
+            */
+            /* timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency; */
+            timeInfo.outputBufferDacTime = timeInfo.currentTime;
+
+            bytesToXfer = framesToXfer * stream->outputFrameSizeBytes;
+            hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,
+                stream->outputBufferWriteOffsetBytes, bytesToXfer,
+                (void **) &lpOutBuf1, &dwOutSize1,
+                (void **) &lpOutBuf2, &dwOutSize2, 0);
+            if (hresult != DS_OK)
+            {
+                ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));
+                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
+                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
+                stream->callbackResult = paComplete;
+                goto error1;
+            }
+
+            numFrames = dwOutSize1 / stream->outputFrameSizeBytes;
+            PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );
+            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );
+
+        /* Is output split into two regions. */
+            if( dwOutSize2 > 0 )
+            {
+                numFrames = dwOutSize2 / stream->outputFrameSizeBytes;
+                PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );
+                PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );
+            }
+        }
+
+        numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &stream->callbackResult );
+        stream->framesWritten += numFrames;
+        
+        if( stream->bufferProcessor.outputChannelCount > 0 )
+        {
+        /* FIXME: an underflow could happen here */
+
+        /* Update our buffer offset and unlock sound buffer */
+            bytesProcessed = numFrames * stream->outputFrameSizeBytes;
+            stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;
+            IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);
+        }
+
+error1:
+        if( stream->bufferProcessor.inputChannelCount > 0 )
+        {
+        /* FIXME: an overflow could happen here */
+
+        /* Update our buffer offset and unlock sound buffer */
+            bytesProcessed = numFrames * stream->inputFrameSizeBytes;
+            stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputBufferSizeBytes;
+            IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);
+        }
+error2:
+
+        PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );        
+    }
+
+    if( stream->callbackResult == paComplete && !PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+    {
+        /* don't return completed until the buffer processor has been drained */
+        return paContinue;
+    }
+    else
+    {
+        return stream->callbackResult;
+    }
+}
+/*******************************************************************/
+
+static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )
+{
+    HRESULT hr;
+    LPBYTE lpbuf1 = NULL;
+    LPBYTE lpbuf2 = NULL;
+    DWORD dwsize1 = 0;
+    DWORD dwsize2 = 0;
+    long  bytesEmpty;
+    hr = QueryOutputSpace( stream, &bytesEmpty );
+    if (hr != DS_OK) return hr;
+    if( bytesEmpty == 0 ) return DS_OK;
+    // Lock free space in the DS
+    hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,
+                                    bytesEmpty, (void **) &lpbuf1, &dwsize1,
+                                    (void **) &lpbuf2, &dwsize2, 0);
+    if (hr == DS_OK)
+    {
+        // Copy the buffer into the DS
+        ZeroMemory(lpbuf1, dwsize1);
+        if(lpbuf2 != NULL)
+        {
+            ZeroMemory(lpbuf2, dwsize2);
+        }
+        // Update our buffer offset and unlock sound buffer
+        stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;
+        IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);
+
+        stream->finalZeroBytesWritten += dwsize1 + dwsize2;
+    }
+    return hr;
+}
+
+
+static void CALLBACK TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)
+{
+    PaWinDsStream *stream;
+    int isFinished = 0;
+
+    /* suppress unused variable warnings */
+    (void) uID;
+    (void) uMsg;
+    (void) dw1;
+    (void) dw2;
+    
+    stream = (PaWinDsStream *) dwUser;
+    if( stream == NULL ) return;
+
+    if( stream->isActive )
+    {
+        if( stream->abortProcessing )
+        {
+            isFinished = 1;
+        }
+        else if( stream->stopProcessing )
+        {
+            if( stream->bufferProcessor.outputChannelCount > 0 )
+            {
+                ZeroAvailableOutputSpace( stream );
+                if( stream->finalZeroBytesWritten >= stream->outputBufferSizeBytes )
+                {
+                    /* once we've flushed the whole output buffer with zeros we know all data has been played */
+                    isFinished = 1;
+                }
+            }
+            else
+            {
+                isFinished = 1;
+            }
+        }
+        else
+        {
+            int callbackResult = TimeSlice( stream );
+            if( callbackResult != paContinue )
+            {
+                /* FIXME implement handling of paComplete and paAbort if possible 
+                   At the moment this should behave as if paComplete was called and 
+                   flush the buffer.
+                */
+
+                stream->stopProcessing = 1;
+            }
+        }
+
+        if( isFinished )
+        {
+            if( stream->streamRepresentation.streamFinishedCallback != 0 )
+                stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+
+            stream->isActive = 0; /* don't set this until the stream really is inactive */
+            SetEvent( stream->processingCompleted );
+        }
+    }
+}
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+
+static void CALLBACK WaitableTimerAPCProc(
+   LPVOID lpArg,               // Data value
+   DWORD dwTimerLowValue,      // Timer low value
+   DWORD dwTimerHighValue )    // Timer high value
+
+{
+    (void)dwTimerLowValue;
+    (void)dwTimerHighValue;
+
+    TimerCallback( 0, 0, (DWORD_PTR)lpArg, 0, 0 );
+}
+
+#endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */
+
+
+PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
+{
+    PaWinDsStream *stream = (PaWinDsStream *)pArg;
+    LARGE_INTEGER dueTime;
+    int timerPeriodMs;
+
+    timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);
+    if( timerPeriodMs < 1 )
+        timerPeriodMs = 1;
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+    assert( stream->waitableTimer != NULL );
+
+    /* invoke first timeout immediately */
+    dueTime.LowPart = timerPeriodMs * 1000 * 10;
+    dueTime.HighPart = 0;
+
+    /* tick using waitable timer */
+    if( SetWaitableTimer( stream->waitableTimer, &dueTime, timerPeriodMs, WaitableTimerAPCProc, pArg, FALSE ) != 0 )
+    {
+        DWORD wfsoResult = 0;
+        do
+        {
+            /* wait for processingCompleted to be signaled or our timer APC to be called */
+            wfsoResult = WaitForSingleObjectEx( stream->processingCompleted, timerPeriodMs * 10, /* alertable = */ TRUE );
+
+        }while( wfsoResult == WAIT_TIMEOUT || wfsoResult == WAIT_IO_COMPLETION );
+    }
+
+    CancelWaitableTimer( stream->waitableTimer );
+
+#else
+
+    /* tick using WaitForSingleObject timout */
+    while ( WaitForSingleObject( stream->processingCompleted, timerPeriodMs ) == WAIT_TIMEOUT )
+    {
+        TimerCallback( 0, 0, (DWORD_PTR)pArg, 0, 0 );
+    }
+#endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */
+
+    SetEvent( stream->processingThreadCompleted );
+
+    return 0;
+}
+
+#endif /* !PA_WIN_DS_USE_WMME_TIMER */
+
+/***********************************************************************************
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    CloseHandle( stream->processingCompleted );
+
+#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
+    if( stream->waitableTimer != NULL )
+        CloseHandle( stream->waitableTimer );
+#endif
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+    CloseHandle( stream->processingThreadCompleted );
+#endif
+
+    // Cleanup the sound buffers
+    if( stream->pDirectSoundOutputBuffer )
+    {
+        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
+        IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
+        stream->pDirectSoundOutputBuffer = NULL;
+    }
+
+    if( stream->pDirectSoundPrimaryBuffer )
+    {
+        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
+        stream->pDirectSoundPrimaryBuffer = NULL;
+    }
+
+    if( stream->pDirectSoundInputBuffer )
+    {
+        IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
+        IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
+        stream->pDirectSoundInputBuffer = NULL;
+    }
+
+    if( stream->pDirectSoundCapture )
+    {
+        IDirectSoundCapture_Release( stream->pDirectSoundCapture );
+        stream->pDirectSoundCapture = NULL;
+    }
+
+    if( stream->pDirectSound )
+    {
+        IDirectSound_Release( stream->pDirectSound );
+        stream->pDirectSound = NULL;
+    }
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+    if( stream->pDirectSoundFullDuplex8 )
+    {
+        IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
+        stream->pDirectSoundFullDuplex8 = NULL;
+    }
+#endif
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+    PaUtil_FreeMemory( stream );
+
+    return result;
+}
+
+/***********************************************************************************/
+static HRESULT ClearOutputBuffer( PaWinDsStream *stream )
+{
+    PaError          result = paNoError;
+    unsigned char*   pDSBuffData;
+    DWORD            dwDataLen;
+    HRESULT          hr;
+
+    hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );
+    DBUG(("PaHost_ClearOutputBuffer: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));
+    if( hr != DS_OK )
+        return hr;
+
+    // Lock the DS buffer
+    if ((hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,
+                                           &dwDataLen, NULL, 0, 0)) != DS_OK )
+        return hr;
+
+    // Zero the DS buffer
+    ZeroMemory(pDSBuffData, dwDataLen);
+    // Unlock the DS buffer
+    if ((hr = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK)
+        return hr;
+    
+    // Let DSound set the starting write position because if we set it to zero, it looks like the
+    // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.
+    if ((hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
+            &stream->previousPlayCursor, &stream->outputBufferWriteOffsetBytes )) != DS_OK)
+        return hr;
+
+    /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */
+
+    return DS_OK;
+}
+
+static PaError StartStream( PaStream *s )
+{
+    PaError          result = paNoError;
+    PaWinDsStream   *stream = (PaWinDsStream*)s;
+    HRESULT          hr;
+        
+    stream->callbackResult = paContinue;
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+    
+    ResetEvent( stream->processingCompleted );
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+    ResetEvent( stream->processingThreadCompleted );
+#endif
+
+    if( stream->bufferProcessor.inputChannelCount > 0 )
+    {
+        // Start the buffer capture
+        if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary
+        {
+            hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );
+        }
+
+        DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));
+        if( hr != DS_OK )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
+            goto error;
+        }
+    }
+
+    stream->framesWritten = 0;
+    stream->callbackFlags = 0;
+
+    stream->abortProcessing = 0;
+    stream->stopProcessing = 0;
+
+    if( stream->bufferProcessor.outputChannelCount > 0 )
+    {
+        QueryPerformanceCounter( &stream->previousPlayTime );
+        stream->finalZeroBytesWritten = 0;
+
+        hr = ClearOutputBuffer( stream );
+        if( hr != DS_OK )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
+            goto error;
+        }
+
+        if( stream->streamRepresentation.streamCallback && (stream->streamFlags & paPrimeOutputBuffersUsingStreamCallback) )
+        {
+            stream->callbackFlags = paPrimingOutput;
+
+            TimeSlice( stream );
+            /* we ignore the return value from TimeSlice here and start the stream as usual.
+                The first timer callback will detect if the callback has completed. */
+
+            stream->callbackFlags = 0;
+        }
+
+        // Start the buffer playback in a loop.
+        if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here
+        {
+            hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );
+            DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));
+            if( hr != DS_OK )
+            {
+                result = paUnanticipatedHostError;
+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
+                goto error;
+            }
+            stream->outputIsRunning = TRUE;
+        }
+    }
+
+    if( stream->streamRepresentation.streamCallback )
+    {
+        TIMECAPS timecaps;
+        int timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);
+        if( timerPeriodMs < 1 )
+            timerPeriodMs = 1;
+
+        /* set windows scheduler granularity only as fine as needed, no finer */
+        /* Although this is not fully documented by MS, it appears that
+           timeBeginPeriod() affects the scheduling granulatity of all timers
+           including Waitable Timer Objects. So we always call timeBeginPeriod, whether
+           we're using an MM timer callback via timeSetEvent or not.
+        */
+        assert( stream->systemTimerResolutionPeriodMs == 0 );
+        if( timeGetDevCaps( &timecaps, sizeof(TIMECAPS) ) == MMSYSERR_NOERROR && timecaps.wPeriodMin > 0 )
+        {
+            /* aim for resolution 4 times higher than polling rate */
+            stream->systemTimerResolutionPeriodMs = (UINT)((stream->pollingPeriodSeconds * MSECS_PER_SECOND) * .25);
+            if( stream->systemTimerResolutionPeriodMs < timecaps.wPeriodMin )
+                stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMin;
+            if( stream->systemTimerResolutionPeriodMs > timecaps.wPeriodMax )
+                stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMax;
+
+            if( timeBeginPeriod( stream->systemTimerResolutionPeriodMs ) != MMSYSERR_NOERROR )
+                stream->systemTimerResolutionPeriodMs = 0; /* timeBeginPeriod failed, so we don't need to call timeEndPeriod() later */
+        }
+
+
+#ifdef PA_WIN_DS_USE_WMME_TIMER
+        /* Create timer that will wake us up so we can fill the DSound buffer. */
+        /* We have deprecated timeSetEvent because all MM timer callbacks
+           are serialised onto a single thread. Which creates problems with multiple
+           PA streams, or when also using timers for other time critical tasks
+        */
+        stream->timerID = timeSetEvent( timerPeriodMs, stream->systemTimerResolutionPeriodMs, (LPTIMECALLBACK) TimerCallback,
+                                             (DWORD_PTR) stream, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS );
+    
+        if( stream->timerID == 0 )
+        {
+            stream->isActive = 0;
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
+            goto error;
+        }
+#else
+        /* Create processing thread which calls TimerCallback */
+
+        stream->processingThread = CREATE_THREAD( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );
+        if( !stream->processingThread )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
+            goto error;
+        }
+
+        if( !SetThreadPriority( stream->processingThread, THREAD_PRIORITY_TIME_CRITICAL ) )
+        {
+            result = paUnanticipatedHostError;
+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
+            goto error;
+        }
+#endif
+    }
+
+    stream->isActive = 1;
+    stream->isStarted = 1;
+
+    assert( result == paNoError );
+    return result;
+
+error:
+
+    if( stream->pDirectSoundOutputBuffer != NULL && stream->outputIsRunning )
+        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
+    stream->outputIsRunning = FALSE;
+
+#ifndef PA_WIN_DS_USE_WMME_TIMER
+    if( stream->processingThread )
+    {
+#ifdef CLOSE_THREAD_HANDLE
+        CLOSE_THREAD_HANDLE( stream->processingThread ); /* Delete thread. */
+#endif
+        stream->processingThread = NULL;
+    }
+#endif
+
+    return result;
+}
+
+
+/***********************************************************************************/
+static PaError StopStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+    HRESULT          hr;
+    int timeoutMsec;
+
+    if( stream->streamRepresentation.streamCallback )
+    {
+        stream->stopProcessing = 1;
+
+        /* Set timeout at 4 times maximum time we might wait. */
+        timeoutMsec = (int) (4 * MSECS_PER_SECOND * (stream->hostBufferSizeFrames / stream->streamRepresentation.streamInfo.sampleRate));
+
+        WaitForSingleObject( stream->processingCompleted, timeoutMsec );
+    }
+
+#ifdef PA_WIN_DS_USE_WMME_TIMER
+    if( stream->timerID != 0 )
+    {
+        timeKillEvent(stream->timerID);  /* Stop callback timer. */
+        stream->timerID = 0;
+    }
+#else
+    if( stream->processingThread )
+    {
+        if( WaitForSingleObject( stream->processingThreadCompleted, 30*100 ) == WAIT_TIMEOUT )
+            return paUnanticipatedHostError;
+
+#ifdef CLOSE_THREAD_HANDLE
+        CloseHandle( stream->processingThread ); /* Delete thread. */
+        stream->processingThread = NULL;
+#endif
+
+    }
+#endif
+
+    if( stream->systemTimerResolutionPeriodMs > 0 ){
+        timeEndPeriod( stream->systemTimerResolutionPeriodMs );
+        stream->systemTimerResolutionPeriodMs = 0;
+    }  
+
+    if( stream->bufferProcessor.outputChannelCount > 0 )
+    {
+        // Stop the buffer playback
+        if( stream->pDirectSoundOutputBuffer != NULL )
+        {
+            stream->outputIsRunning = FALSE;
+            // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?
+            hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
+
+            if( stream->pDirectSoundPrimaryBuffer )
+                IDirectSoundBuffer_Stop( stream->pDirectSoundPrimaryBuffer ); /* FIXME we never started the primary buffer so I'm not sure we need to stop it */
+        }
+    }
+
+    if( stream->bufferProcessor.inputChannelCount > 0 )
+    {
+        // Stop the buffer capture
+        if( stream->pDirectSoundInputBuffer != NULL )
+        {
+            // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?
+            hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
+        }
+    }
+
+    stream->isStarted = 0;
+
+    return result;
+}
+
+
+/***********************************************************************************/
+static PaError AbortStream( PaStream *s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    stream->abortProcessing = 1;
+    return StopStream( s );
+}
+
+
+/***********************************************************************************/
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    return !stream->isStarted;
+}
+
+
+/***********************************************************************************/
+static PaError IsStreamActive( PaStream *s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    return stream->isActive;
+}
+
+/***********************************************************************************/
+static PaTime GetStreamTime( PaStream *s )
+{
+    /* suppress unused variable warnings */
+    (void) s;
+
+    return PaUtil_GetTime();
+}
+
+
+/***********************************************************************************/
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/***********************************************************************************
+    As separate stream interfaces are used for blocking and callback
+    streams, the following functions can be guaranteed to only be called
+    for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return paNoError;
+}
+
+
+/***********************************************************************************/
+static PaError WriteStream( PaStream* s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return paNoError;
+}
+
+
+/***********************************************************************************/
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return 0;
+}
+
+
+/***********************************************************************************/
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaWinDsStream *stream = (PaWinDsStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return 0;
+}
+
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c b/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c
new file mode 100644 (file)
index 0000000..c4e3c4e
--- /dev/null
@@ -0,0 +1,224 @@
+/*
+ * Interface for dynamically loading directsound and providing a dummy
+ * implementation if it isn't present.
+ *
+ * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
+ *
+ * For PortAudio Portable Real-Time Audio Library
+ * For more information see: http://www.portaudio.com
+ * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include "pa_win_ds_dynlink.h"
+#include "pa_debugprint.h"
+
+PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 };
+
+
+static HRESULT WINAPI DummyDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
+{
+    (void)rclsid; /* unused parameter */
+    (void)riid; /* unused parameter */
+    (void)ppv; /* unused parameter */
+    return CLASS_E_CLASSNOTAVAILABLE;
+}
+
+static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)
+{
+    (void)lpcGuidDevice; /* unused parameter */
+    (void)ppDS; /* unused parameter */
+    (void)pUnkOuter; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext)
+{
+    (void)lpDSEnumCallback; /* unused parameter */
+    (void)lpContext; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext)
+{
+    (void)lpDSEnumCallback; /* unused parameter */
+    (void)lpContext; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter)
+{
+    (void)lpcGUID; /* unused parameter */
+    (void)lplpDSC; /* unused parameter */
+    (void)pUnkOuter; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext)
+{
+    (void)lpDSCEnumCallback; /* unused parameter */
+    (void)lpContext; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext)
+{
+    (void)lpDSCEnumCallback; /* unused parameter */
+    (void)lpContext; /* unused parameter */
+    return E_NOTIMPL;
+}
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+static HRESULT WINAPI DummyDirectSoundFullDuplexCreate8(
+         LPCGUID pcGuidCaptureDevice,
+         LPCGUID pcGuidRenderDevice,
+         LPCDSCBUFFERDESC pcDSCBufferDesc,
+         LPCDSBUFFERDESC pcDSBufferDesc,
+         HWND hWnd,
+         DWORD dwLevel,
+         LPDIRECTSOUNDFULLDUPLEX * ppDSFD,
+         LPDIRECTSOUNDCAPTUREBUFFER8 * ppDSCBuffer8,
+         LPDIRECTSOUNDBUFFER8 * ppDSBuffer8,
+         LPUNKNOWN pUnkOuter)
+{
+    (void)pcGuidCaptureDevice; /* unused parameter */
+    (void)pcGuidRenderDevice; /* unused parameter */
+    (void)pcDSCBufferDesc; /* unused parameter */
+    (void)pcDSBufferDesc; /* unused parameter */
+    (void)hWnd; /* unused parameter */
+    (void)dwLevel; /* unused parameter */
+    (void)ppDSFD; /* unused parameter */
+    (void)ppDSCBuffer8; /* unused parameter */
+    (void)ppDSBuffer8; /* unused parameter */
+    (void)pUnkOuter; /* unused parameter */
+
+    return E_NOTIMPL;
+}
+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
+
+void PaWinDs_InitializeDSoundEntryPoints(void)
+{
+    paWinDsDSoundEntryPoints.hInstance_ = LoadLibraryA("dsound.dll");
+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
+    {
+        paWinDsDSoundEntryPoints.DllGetClassObject =
+                (HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DllGetClassObject" );
+        if( paWinDsDSoundEntryPoints.DllGetClassObject == NULL )
+            paWinDsDSoundEntryPoints.DllGetClassObject = DummyDllGetClassObject;
+
+        paWinDsDSoundEntryPoints.DirectSoundCreate =
+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" );
+        if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
+
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW =
+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" );
+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
+
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA =
+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" );
+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
+
+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate =
+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" );
+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
+
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW =
+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" );
+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
+
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA =
+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" );
+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 =
+                (HRESULT (WINAPI *)(LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
+                                    HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *, 
+                                    LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN))
+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundFullDuplexCreate" );
+        if( paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 == NULL )
+            paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
+#endif
+    }
+    else
+    {
+        DWORD errorCode = GetLastError(); // 126 (0x7E) == ERROR_MOD_NOT_FOUND
+        PA_DEBUG(("Couldn't load dsound.dll error code: %d \n",errorCode));
+
+        /* initialize with dummy entry points to make live easy when ds isn't present */
+        paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
+#endif
+    }
+}
+
+
+void PaWinDs_TerminateDSoundEntryPoints(void)
+{
+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
+    {
+        /* ensure that we crash reliably if the entry points arent initialised */
+        paWinDsDSoundEntryPoints.DirectSoundCreate = 0;
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0;
+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0;
+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0;
+
+        FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ );
+        paWinDsDSoundEntryPoints.hInstance_ = NULL;
+    }
+}
\ No newline at end of file
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h b/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h
new file mode 100644 (file)
index 0000000..9e366ff
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Interface for dynamically loading directsound and providing a dummy
+ * implementation if it isn't present.
+ *
+ * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
+ *
+ * For PortAudio Portable Real-Time Audio Library
+ * For more information see: http://www.portaudio.com
+ * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#ifndef INCLUDED_PA_DSOUND_DYNLINK_H
+#define INCLUDED_PA_DSOUND_DYNLINK_H
+
+/* on Borland compilers, WIN32 doesn't seem to be defined by default, which
+    breaks dsound.h. Adding the define here fixes the problem. - rossb. */
+#ifdef __BORLANDC__
+#if !defined(WIN32)
+#define WIN32
+#endif
+#endif
+
+/*
+  Use the earliest version of DX required, no need to polute the namespace
+*/
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+#define DIRECTSOUND_VERSION 0x0800
+#else
+#define DIRECTSOUND_VERSION 0x0300
+#endif
+#include <windows.h>
+#include <mmsystem.h>
+#include <dsound.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+typedef struct
+{
+    HINSTANCE hInstance_;
+    
+    HRESULT (WINAPI *DllGetClassObject)(REFCLSID , REFIID , LPVOID *);
+
+    HRESULT (WINAPI *DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
+    HRESULT (WINAPI *DirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
+    HRESULT (WINAPI *DirectSoundEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
+
+    HRESULT (WINAPI *DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN);
+    HRESULT (WINAPI *DirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
+    HRESULT (WINAPI *DirectSoundCaptureEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
+
+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
+    HRESULT (WINAPI *DirectSoundFullDuplexCreate8)(
+                LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
+                HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *, 
+                LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN );
+#endif
+}PaWinDsDSoundEntryPoints;
+
+extern PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints;
+
+void PaWinDs_InitializeDSoundEntryPoints(void);
+void PaWinDs_TerminateDSoundEntryPoints(void);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* INCLUDED_PA_DSOUND_DYNLINK_H */
diff --git a/portaudio/src/hostapi/jack/pa_jack.c b/portaudio/src/hostapi/jack/pa_jack.c
new file mode 100644 (file)
index 0000000..a800f8e
--- /dev/null
@@ -0,0 +1,1769 @@
+/*
+ * $Id$
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * JACK Implementation by Joshua Haberman
+ *
+ * Copyright (c) 2004 Stefan Westerfeld <stefan@space.twc.de>
+ * Copyright (c) 2004 Arve Knudsen <aknuds-1@broadpark.no>
+ * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include <string.h>
+#include <regex.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <assert.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <errno.h>  /* EBUSY */
+#include <signal.h> /* sig_atomic_t */
+#include <math.h>
+#include <semaphore.h>
+
+#include <jack/types.h>
+#include <jack/jack.h>
+
+#include "pa_util.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_process.h"
+#include "pa_allocation.h"
+#include "pa_cpuload.h"
+#include "pa_ringbuffer.h"
+#include "pa_debugprint.h"
+
+static pthread_t mainThread_;
+static char *jackErr_ = NULL;
+static const char* clientName_ = "PortAudio";
+
+#define STRINGIZE_HELPER(expr) #expr
+#define STRINGIZE(expr) STRINGIZE_HELPER(expr)
+
+/* Check PaError */
+#define ENSURE_PA(expr) \
+    do { \
+        PaError paErr; \
+        if( (paErr = (expr)) < paNoError ) \
+        { \
+            if( (paErr) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+            { \
+                const char *err = jackErr_; \
+                if (! err ) err = "unknown error"; \
+                PaUtil_SetLastHostErrorInfo( paJACK, -1, err ); \
+            } \
+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = paErr; \
+            goto error; \
+        } \
+    } while( 0 )
+
+#define UNLESS(expr, code) \
+    do { \
+        if( (expr) == 0 ) \
+        { \
+            if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+            { \
+                const char *err = jackErr_; \
+                if (!err) err = "unknown error"; \
+                PaUtil_SetLastHostErrorInfo( paJACK, -1, err ); \
+            } \
+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = (code); \
+            goto error; \
+        } \
+    } while( 0 )
+
+#define ASSERT_CALL(expr, success) \
+    do { \
+        int err = (expr); \
+        assert( err == success ); \
+    } while( 0 )
+
+/*
+ * Functions that directly map to the PortAudio stream interface
+ */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+/*static PaTime GetStreamInputLatency( PaStream *stream );*/
+/*static PaTime GetStreamOutputLatency( PaStream *stream );*/
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+
+
+/*
+ * Data specific to this API
+ */
+
+struct PaJackStream;
+
+typedef struct
+{
+    PaUtilHostApiRepresentation commonHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *deviceInfoMemory;
+
+    jack_client_t *jack_client;
+    int jack_buffer_size;
+    PaHostApiIndex hostApiIndex;
+
+    pthread_mutex_t mtx;
+    pthread_cond_t cond;
+    unsigned long inputBase, outputBase;
+
+    /* For dealing with the process thread */
+    volatile int xrun;     /* Received xrun notification from JACK? */
+    struct PaJackStream * volatile toAdd, * volatile toRemove;
+    struct PaJackStream *processQueue;
+    volatile sig_atomic_t jackIsDown;
+}
+PaJackHostApiRepresentation;
+
+/* PaJackStream - a stream data structure specifically for this implementation */
+
+typedef struct PaJackStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilBufferProcessor bufferProcessor;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaJackHostApiRepresentation *hostApi;
+
+    /* our input and output ports */
+    jack_port_t **local_input_ports;
+    jack_port_t **local_output_ports;
+
+    /* the input and output ports of the client we are connecting to */
+    jack_port_t **remote_input_ports;
+    jack_port_t **remote_output_ports;
+
+    int num_incoming_connections;
+    int num_outgoing_connections;
+
+    jack_client_t *jack_client;
+
+    /* The stream is running if it's still producing samples.
+     * The stream is active if samples it produced are still being heard.
+     */
+    volatile sig_atomic_t is_running;
+    volatile sig_atomic_t is_active;
+    /* Used to signal processing thread that stream should start or stop, respectively */
+    volatile sig_atomic_t doStart, doStop, doAbort;
+
+    jack_nframes_t t0;
+
+    PaUtilAllocationGroup *stream_memory;
+
+    /* These are useful in the process callback */
+
+    int callbackResult;
+    int isSilenced;
+    int xrun;
+
+    /* These are useful for the blocking API */
+
+    int                     isBlockingStream;
+    PaUtilRingBuffer        inFIFO;
+    PaUtilRingBuffer        outFIFO;
+    volatile sig_atomic_t   data_available;
+    sem_t                   data_semaphore;
+    int                     bytesPerFrame;
+    int                     samplesPerFrame;
+
+    struct PaJackStream *next;
+}
+PaJackStream;
+
+/* In calls to jack_get_ports() this filter expression is used instead of ""
+ * to prevent any other types (eg Midi ports etc) being listed */
+#define JACK_PORT_TYPE_FILTER "audio"
+
+#define TRUE 1
+#define FALSE 0
+
+/*
+ * Functions specific to this API
+ */
+
+static int JackCallback( jack_nframes_t frames, void *userData );
+
+
+/*
+ *
+ * Implementation
+ *
+ */
+
+/* ---- blocking emulation layer ---- */
+
+/* Allocate buffer. */
+static PaError BlockingInitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long bytesPerFrame )
+{
+    long numBytes = numFrames * bytesPerFrame;
+    char *buffer = (char *) malloc( numBytes );
+    if( buffer == NULL ) return paInsufficientMemory;
+    memset( buffer, 0, numBytes );
+    return (PaError) PaUtil_InitializeRingBuffer( rbuf, 1, numBytes, buffer );
+}
+
+/* Free buffer. */
+static PaError BlockingTermFIFO( PaUtilRingBuffer *rbuf )
+{
+    if( rbuf->buffer ) free( rbuf->buffer );
+    rbuf->buffer = NULL;
+    return paNoError;
+}
+
+static int
+BlockingCallback( const void                      *inputBuffer,
+                  void                            *outputBuffer,
+                 unsigned long                    framesPerBuffer,
+                 const PaStreamCallbackTimeInfo*  timeInfo,
+                 PaStreamCallbackFlags            statusFlags,
+                 void                             *userData )
+{
+    struct PaJackStream *stream = (PaJackStream *)userData;
+    long numBytes = stream->bytesPerFrame * framesPerBuffer;
+
+    /* This may get called with NULL inputBuffer during initial setup. */
+    if( inputBuffer != NULL )
+    {
+        PaUtil_WriteRingBuffer( &stream->inFIFO, inputBuffer, numBytes );
+    }
+    if( outputBuffer != NULL )
+    {
+        int numRead = PaUtil_ReadRingBuffer( &stream->outFIFO, outputBuffer, numBytes );
+        /* Zero out remainder of buffer if we run out of data. */
+        memset( (char *)outputBuffer + numRead, 0, numBytes - numRead );
+    }
+
+    if( !stream->data_available )
+    {
+        stream->data_available = 1;
+        sem_post( &stream->data_semaphore );
+    }
+    return paContinue;
+}
+
+static PaError
+BlockingBegin( PaJackStream *stream, int minimum_buffer_size )
+{
+    long    doRead = 0;
+    long    doWrite = 0;
+    PaError result = paNoError;
+    long    numFrames;
+
+    doRead = stream->local_input_ports != NULL;
+    doWrite = stream->local_output_ports != NULL;
+    /* <FIXME> */
+    stream->samplesPerFrame = 2;
+    stream->bytesPerFrame = sizeof(float) * stream->samplesPerFrame;
+    /* </FIXME> */
+    numFrames = 32;
+    while (numFrames < minimum_buffer_size)
+        numFrames *= 2;
+
+    if( doRead )
+    {
+        ENSURE_PA( BlockingInitFIFO( &stream->inFIFO, numFrames, stream->bytesPerFrame ) );
+    }
+    if( doWrite )
+    {
+        long numBytes;
+
+        ENSURE_PA( BlockingInitFIFO( &stream->outFIFO, numFrames, stream->bytesPerFrame ) );
+
+        /* Make Write FIFO appear full initially. */
+        numBytes = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO );
+        PaUtil_AdvanceRingBufferWriteIndex( &stream->outFIFO, numBytes );
+    }
+
+    stream->data_available = 0;
+    sem_init( &stream->data_semaphore, 0, 0 );
+
+error:
+    return result;
+}
+
+static void
+BlockingEnd( PaJackStream *stream )
+{
+    BlockingTermFIFO( &stream->inFIFO );
+    BlockingTermFIFO( &stream->outFIFO );
+
+    sem_destroy( &stream->data_semaphore );
+}
+
+static PaError BlockingReadStream( PaStream* s, void *data, unsigned long numFrames )
+{
+    PaError result = paNoError;
+    PaJackStream *stream = (PaJackStream *)s;
+
+    long bytesRead;
+    char *p = (char *) data;
+    long numBytes = stream->bytesPerFrame * numFrames;
+    while( numBytes > 0 )
+    {
+        bytesRead = PaUtil_ReadRingBuffer( &stream->inFIFO, p, numBytes );
+        numBytes -= bytesRead;
+        p += bytesRead;
+        if( numBytes > 0 )
+        {
+            /* see write for an explanation */
+            if( stream->data_available )
+                stream->data_available = 0;
+            else
+                sem_wait( &stream->data_semaphore );
+        }
+    }
+
+    return result;
+}
+
+static PaError BlockingWriteStream( PaStream* s, const void *data, unsigned long numFrames )
+{
+    PaError result = paNoError;
+    PaJackStream *stream = (PaJackStream *)s;
+    long bytesWritten;
+    char *p = (char *) data;
+    long numBytes = stream->bytesPerFrame * numFrames;
+    while( numBytes > 0 )
+    {
+        bytesWritten = PaUtil_WriteRingBuffer( &stream->outFIFO, p, numBytes );
+        numBytes -= bytesWritten;
+        p += bytesWritten;
+        if( numBytes > 0 )
+        {
+            /* we use the following algorithm:
+             *   (1) write data
+             *   (2) if some data didn't fit into the ringbuffer, set data_available to 0
+             *       to indicate to the audio that if space becomes available, we want to know
+             *   (3) retry to write data (because it might be that between (1) and (2)
+             *       new space in the buffer became available)
+             *   (4) if this failed, we are sure that the buffer is really empty and
+             *       we will definitely receive a notification when it becomes available
+             *       thus we can safely sleep
+             *
+             * if the algorithm bailed out in step (3) before, it leaks a count of 1
+             * on the semaphore; however, it doesn't matter, because if we block in (4),
+             * we also do it in a loop
+             */
+            if( stream->data_available )
+                stream->data_available = 0;
+            else
+                sem_wait( &stream->data_semaphore );
+        }
+    }
+
+    return result;
+}
+
+static signed long
+BlockingGetStreamReadAvailable( PaStream* s )
+{
+    PaJackStream *stream = (PaJackStream *)s;
+
+    int bytesFull = PaUtil_GetRingBufferReadAvailable( &stream->inFIFO );
+    return bytesFull / stream->bytesPerFrame;
+}
+
+static signed long
+BlockingGetStreamWriteAvailable( PaStream* s )
+{
+    PaJackStream *stream = (PaJackStream *)s;
+
+    int bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO );
+    return bytesEmpty / stream->bytesPerFrame;
+}
+
+static PaError
+BlockingWaitEmpty( PaStream *s )
+{
+    PaJackStream *stream = (PaJackStream *)s;
+
+    while( PaUtil_GetRingBufferReadAvailable( &stream->outFIFO ) > 0 )
+    {
+        stream->data_available = 0;
+        sem_wait( &stream->data_semaphore );
+    }
+    return 0;
+}
+
+/* ---- jack driver ---- */
+
+/* BuildDeviceList():
+ *
+ * The process of determining a list of PortAudio "devices" from
+ * JACK's client/port system is fairly involved, so it is separated
+ * into its own routine.
+ */
+
+static PaError BuildDeviceList( PaJackHostApiRepresentation *jackApi )
+{
+    /* Utility macros for the repetitive process of allocating memory */
+
+    /* JACK has no concept of a device.  To JACK, there are clients
+     * which have an arbitrary number of ports.  To make this
+     * intelligible to PortAudio clients, we will group each JACK client
+     * into a device, and make each port of that client a channel */
+
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *commonApi = &jackApi->commonHostApiRep;
+
+    const char **jack_ports = NULL;
+    char **client_names = NULL;
+    char *regex_pattern = NULL;
+    int port_index, client_index, i;
+    double globalSampleRate;
+    regex_t port_regex;
+    unsigned long numClients = 0, numPorts = 0;
+    char *tmp_client_name = NULL;
+
+    commonApi->info.defaultInputDevice = paNoDevice;
+    commonApi->info.defaultOutputDevice = paNoDevice;
+    commonApi->info.deviceCount = 0;
+
+    /* Parse the list of ports, using a regex to grab the client names */
+    ASSERT_CALL( regcomp( &port_regex, "^[^:]*", REG_EXTENDED ), 0 );
+
+    /* since we are rebuilding the list of devices, free all memory
+     * associated with the previous list */
+    PaUtil_FreeAllAllocations( jackApi->deviceInfoMemory );
+
+    regex_pattern = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() + 3 );
+    tmp_client_name = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() );
+
+    /* We can only retrieve the list of clients indirectly, by first
+     * asking for a list of all ports, then parsing the port names
+     * according to the client_name:port_name convention (which is
+     * enforced by jackd)
+     * A: If jack_get_ports returns NULL, there's nothing for us to do */
+    UNLESS( (jack_ports = jack_get_ports( jackApi->jack_client, "", JACK_PORT_TYPE_FILTER, 0 )) && jack_ports[0], paNoError );
+    /* Find number of ports */
+    while( jack_ports[numPorts] )
+        ++numPorts;
+    /* At least there will be one port per client :) */
+    UNLESS( client_names = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, numPorts *
+                sizeof (char *) ), paInsufficientMemory );
+
+    /* Build a list of clients from the list of ports */
+    for( numClients = 0, port_index = 0; jack_ports[port_index] != NULL; port_index++ )
+    {
+        int client_seen = FALSE;
+        regmatch_t match_info;
+        const char *port = jack_ports[port_index];
+
+        /* extract the client name from the port name, using a regex
+         * that parses the clientname:portname syntax */
+        UNLESS( !regexec( &port_regex, port, 1, &match_info, 0 ), paInternalError );
+        assert(match_info.rm_eo - match_info.rm_so < jack_client_name_size());
+        memcpy( tmp_client_name, port + match_info.rm_so,
+                match_info.rm_eo - match_info.rm_so );
+        tmp_client_name[match_info.rm_eo - match_info.rm_so] = '\0';
+
+        /* do we know about this port's client yet? */
+        for( i = 0; i < numClients; i++ )
+        {
+            if( strcmp( tmp_client_name, client_names[i] ) == 0 )
+                client_seen = TRUE;
+        }
+
+        if (client_seen)
+            continue;   /* A: Nothing to see here, move along */
+
+        UNLESS( client_names[numClients] = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+                    strlen(tmp_client_name) + 1), paInsufficientMemory );
+
+        /* The alsa_pcm client should go in spot 0.  If this
+         * is the alsa_pcm client AND we are NOT about to put
+         * it in spot 0 put it in spot 0 and move whatever
+         * was already in spot 0 to the end. */
+        if( strcmp( "alsa_pcm", tmp_client_name ) == 0 && numClients > 0 )
+        {
+            /* alsa_pcm goes in spot 0 */
+            strcpy( client_names[ numClients ], client_names[0] );
+            strcpy( client_names[0], tmp_client_name );
+        }
+        else
+        {
+            /* put the new client at the end of the client list */
+            strcpy( client_names[ numClients ], tmp_client_name );
+        }
+        ++numClients;
+    }
+
+    /* Now we have a list of clients, which will become the list of
+     * PortAudio devices. */
+
+    /* there is one global sample rate all clients must conform to */
+
+    globalSampleRate = jack_get_sample_rate( jackApi->jack_client );
+    UNLESS( commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+                sizeof(PaDeviceInfo*) * numClients ), paInsufficientMemory );
+
+    assert( commonApi->info.deviceCount == 0 );
+
+    /* Create a PaDeviceInfo structure for every client */
+    for( client_index = 0; client_index < numClients; client_index++ )
+    {
+        PaDeviceInfo *curDevInfo;
+        const char **clientPorts = NULL;
+
+        UNLESS( curDevInfo = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+                    sizeof(PaDeviceInfo) ), paInsufficientMemory );
+        UNLESS( curDevInfo->name = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+                    strlen(client_names[client_index]) + 1 ), paInsufficientMemory );
+        strcpy( (char *)curDevInfo->name, client_names[client_index] );
+
+        curDevInfo->structVersion = 2;
+        curDevInfo->hostApi = jackApi->hostApiIndex;
+
+        /* JACK is very inflexible: there is one sample rate the whole
+         * system must run at, and all clients must speak IEEE float. */
+        curDevInfo->defaultSampleRate = globalSampleRate;
+
+        /* To determine how many input and output channels are available,
+         * we re-query jackd with more specific parameters. */
+
+        sprintf( regex_pattern, "%s:.*", client_names[client_index] );
+
+        /* ... what are your output ports (that we could input from)? */
+        clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
+                                     JACK_PORT_TYPE_FILTER, JackPortIsOutput);
+        curDevInfo->maxInputChannels = 0;
+        curDevInfo->defaultLowInputLatency = 0.;
+        curDevInfo->defaultHighInputLatency = 0.;
+        if( clientPorts )
+        {
+            jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
+            curDevInfo->defaultLowInputLatency = curDevInfo->defaultHighInputLatency =
+                jack_port_get_latency( p ) / globalSampleRate;
+
+            for( i = 0; clientPorts[i] != NULL; i++)
+            {
+                /* The number of ports returned is the number of output channels.
+                 * We don't care what they are, we just care how many */
+                curDevInfo->maxInputChannels++;
+            }
+            free(clientPorts);
+        }
+
+        /* ... what are your input ports (that we could output to)? */
+        clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
+                                     JACK_PORT_TYPE_FILTER, JackPortIsInput);
+        curDevInfo->maxOutputChannels = 0;
+        curDevInfo->defaultLowOutputLatency = 0.;
+        curDevInfo->defaultHighOutputLatency = 0.;
+        if( clientPorts )
+        {
+            jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
+            curDevInfo->defaultLowOutputLatency = curDevInfo->defaultHighOutputLatency =
+                jack_port_get_latency( p ) / globalSampleRate;
+
+            for( i = 0; clientPorts[i] != NULL; i++)
+            {
+                /* The number of ports returned is the number of input channels.
+                 * We don't care what they are, we just care how many */
+                curDevInfo->maxOutputChannels++;
+            }
+            free(clientPorts);
+        }
+
+        /* Add this client to the list of devices */
+        commonApi->deviceInfos[client_index] = curDevInfo;
+        ++commonApi->info.deviceCount;
+        if( commonApi->info.defaultInputDevice == paNoDevice && curDevInfo->maxInputChannels > 0 )
+            commonApi->info.defaultInputDevice = client_index;
+        if( commonApi->info.defaultOutputDevice == paNoDevice && curDevInfo->maxOutputChannels > 0 )
+            commonApi->info.defaultOutputDevice = client_index;
+    }
+
+error:
+    regfree( &port_regex );
+    free( jack_ports );
+    return result;
+}
+
+static void UpdateSampleRate( PaJackStream *stream, double sampleRate )
+{
+    /* XXX: Maybe not the cleanest way of going about this? */
+    stream->cpuLoadMeasurer.samplingPeriod = stream->bufferProcessor.samplePeriod = 1. / sampleRate;
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+}
+
+static void JackErrorCallback( const char *msg )
+{
+    if( pthread_self() == mainThread_ )
+    {
+        assert( msg );
+        jackErr_ = realloc( jackErr_, strlen( msg ) + 1 );
+        strcpy( jackErr_, msg );
+    }
+}
+
+static void JackOnShutdown( void *arg )
+{
+    PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
+    PaJackStream *stream = jackApi->processQueue;
+
+    PA_DEBUG(( "%s: JACK server is shutting down\n", __FUNCTION__ ));
+    for( ; stream; stream = stream->next )
+    {
+        stream->is_active = 0;
+    }
+
+    /* Make sure that the main thread doesn't get stuck waiting on the condition */
+    ASSERT_CALL( pthread_mutex_lock( &jackApi->mtx ), 0 );
+    jackApi->jackIsDown = 1;
+    ASSERT_CALL( pthread_cond_signal( &jackApi->cond ), 0 );
+    ASSERT_CALL( pthread_mutex_unlock( &jackApi->mtx ), 0 );
+
+}
+
+static int JackSrCb( jack_nframes_t nframes, void *arg )
+{
+    PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
+    double sampleRate = (double)nframes;
+    PaJackStream *stream = jackApi->processQueue;
+
+    /* Update all streams in process queue */
+    PA_DEBUG(( "%s: Acting on change in JACK samplerate: %f\n", __FUNCTION__, sampleRate ));
+    for( ; stream; stream = stream->next )
+    {
+        if( stream->streamRepresentation.streamInfo.sampleRate != sampleRate )
+        {
+            PA_DEBUG(( "%s: Updating samplerate\n", __FUNCTION__ ));
+            UpdateSampleRate( stream, sampleRate );
+        }
+    }
+
+    return 0;
+}
+
+static int JackXRunCb(void *arg) {
+    PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)arg;
+    assert( hostApi );
+    hostApi->xrun = TRUE;
+    PA_DEBUG(( "%s: JACK signalled xrun\n", __FUNCTION__ ));
+    return 0;
+}
+
+PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi,
+                           PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation *jackHostApi;
+    int activated = 0;
+    jack_status_t jackStatus = 0;
+    *hostApi = NULL;    /* Initialize to NULL */
+
+    UNLESS( jackHostApi = (PaJackHostApiRepresentation*)
+        PaUtil_AllocateMemory( sizeof(PaJackHostApiRepresentation) ), paInsufficientMemory );
+    UNLESS( jackHostApi->deviceInfoMemory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+
+    mainThread_ = pthread_self();
+    ASSERT_CALL( pthread_mutex_init( &jackHostApi->mtx, NULL ), 0 );
+    ASSERT_CALL( pthread_cond_init( &jackHostApi->cond, NULL ), 0 );
+
+    /* Try to become a client of the JACK server.  If we cannot do
+     * this, then this API cannot be used.
+     *
+     * Without the JackNoStartServer option, the jackd server is started
+     * automatically which we do not want.
+     */
+
+    jackHostApi->jack_client = jack_client_open( clientName_, JackNoStartServer, &jackStatus );
+    if( !jackHostApi->jack_client )
+    {
+        /* the V19 development docs say that if an implementation
+         * detects that it cannot be used, it should return a NULL
+         * interface and paNoError */
+        PA_DEBUG(( "%s: Couldn't connect to JACK, status: %d\n", __FUNCTION__, jackStatus ));
+        result = paNoError;
+        goto error;
+    }
+
+    jackHostApi->hostApiIndex = hostApiIndex;
+
+    *hostApi = &jackHostApi->commonHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paJACK;
+    (*hostApi)->info.name = "JACK Audio Connection Kit";
+
+    /* Build a device list by querying the JACK server */
+    ENSURE_PA( BuildDeviceList( jackHostApi ) );
+
+    /* Register functions */
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &jackHostApi->callbackStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream,
+                                      IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable,
+                                      PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &jackHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      BlockingReadStream, BlockingWriteStream,
+                                      BlockingGetStreamReadAvailable, BlockingGetStreamWriteAvailable );
+
+    jackHostApi->inputBase = jackHostApi->outputBase = 0;
+    jackHostApi->xrun = 0;
+    jackHostApi->toAdd = jackHostApi->toRemove = NULL;
+    jackHostApi->processQueue = NULL;
+    jackHostApi->jackIsDown = 0;
+
+    jack_on_shutdown( jackHostApi->jack_client, JackOnShutdown, jackHostApi );
+    jack_set_error_function( JackErrorCallback );
+    jackHostApi->jack_buffer_size = jack_get_buffer_size ( jackHostApi->jack_client );
+    /* Don't check for error, may not be supported (deprecated in at least jackdmp) */
+    jack_set_sample_rate_callback( jackHostApi->jack_client, JackSrCb, jackHostApi );
+    UNLESS( !jack_set_xrun_callback( jackHostApi->jack_client, JackXRunCb, jackHostApi ), paUnanticipatedHostError );
+    UNLESS( !jack_set_process_callback( jackHostApi->jack_client, JackCallback, jackHostApi ), paUnanticipatedHostError );
+    UNLESS( !jack_activate( jackHostApi->jack_client ), paUnanticipatedHostError );
+    activated = 1;
+
+    return result;
+
+error:
+    if( activated )
+        ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
+
+    if( jackHostApi )
+    {
+        if( jackHostApi->jack_client )
+            ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
+
+        if( jackHostApi->deviceInfoMemory )
+        {
+            PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
+            PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
+        }
+
+        PaUtil_FreeMemory( jackHostApi );
+    }
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
+
+    /* note: this automatically disconnects all ports, since a deactivated
+     * client is not allowed to have any ports connected */
+    ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
+
+    ASSERT_CALL( pthread_mutex_destroy( &jackHostApi->mtx ), 0 );
+    ASSERT_CALL( pthread_cond_destroy( &jackHostApi->cond ), 0 );
+
+    ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
+
+    if( jackHostApi->deviceInfoMemory )
+    {
+        PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
+        PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
+    }
+
+    PaUtil_FreeMemory( jackHostApi );
+
+    free( jackErr_ );
+    jackErr_ = NULL;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    int inputChannelCount = 0, outputChannelCount = 0;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+
+    /*
+        The following check is not necessary for JACK.
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+
+
+        Because the buffer adapter handles conversion between all standard
+        sample formats, the following checks are only required if paCustomFormat
+        is implemented, or under some other unusual conditions.
+
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+    */
+
+    /* check that the device supports sampleRate */
+
+#define ABS(x) ( (x) > 0 ? (x) : -(x) )
+    if( ABS(sampleRate - jack_get_sample_rate(((PaJackHostApiRepresentation *) hostApi)->jack_client )) > 1 )
+       return paInvalidSampleRate;
+#undef ABS
+
+    return paFormatIsSupported;
+}
+
+/* Basic stream initialization */
+static PaError InitializeStream( PaJackStream *stream, PaJackHostApiRepresentation *hostApi, int numInputChannels,
+        int numOutputChannels )
+{
+    PaError result = paNoError;
+    assert( stream );
+
+    memset( stream, 0, sizeof (PaJackStream) );
+    UNLESS( stream->stream_memory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+    stream->jack_client = hostApi->jack_client;
+    stream->hostApi = hostApi;
+
+    if( numInputChannels > 0 )
+    {
+        UNLESS( stream->local_input_ports =
+                (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
+                paInsufficientMemory );
+        memset( stream->local_input_ports, 0, sizeof(jack_port_t*) * numInputChannels );
+        UNLESS( stream->remote_output_ports =
+                (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
+                paInsufficientMemory );
+        memset( stream->remote_output_ports, 0, sizeof(jack_port_t*) * numInputChannels );
+    }
+    if( numOutputChannels > 0 )
+    {
+        UNLESS( stream->local_output_ports =
+                (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
+                paInsufficientMemory );
+        memset( stream->local_output_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
+        UNLESS( stream->remote_input_ports =
+                (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
+                paInsufficientMemory );
+        memset( stream->remote_input_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
+    }
+
+    stream->num_incoming_connections = numInputChannels;
+    stream->num_outgoing_connections = numOutputChannels;
+
+error:
+    return result;
+}
+
+/*!
+ * Free resources associated with stream, and eventually stream itself.
+ *
+ * Frees allocated memory, and closes opened pcms.
+ */
+static void CleanUpStream( PaJackStream *stream, int terminateStreamRepresentation, int terminateBufferProcessor )
+{
+    int i;
+    assert( stream );
+
+    if( stream->isBlockingStream )
+        BlockingEnd( stream );
+
+    for( i = 0; i < stream->num_incoming_connections; ++i )
+    {
+        if( stream->local_input_ports[i] )
+            ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_input_ports[i] ), 0 );
+    }
+    for( i = 0; i < stream->num_outgoing_connections; ++i )
+    {
+        if( stream->local_output_ports[i] )
+            ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_output_ports[i] ), 0 );
+    }
+
+    if( terminateStreamRepresentation )
+        PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+    if( terminateBufferProcessor )
+        PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+    if( stream->stream_memory )
+    {
+        PaUtil_FreeAllAllocations( stream->stream_memory );
+        PaUtil_DestroyAllocationGroup( stream->stream_memory );
+    }
+    PaUtil_FreeMemory( stream );
+}
+
+static PaError WaitCondition( PaJackHostApiRepresentation *hostApi )
+{
+    PaError result = paNoError;
+    int err = 0;
+    PaTime pt = PaUtil_GetTime();
+    struct timespec ts;
+
+    ts.tv_sec = (time_t) floor( pt + 10 * 60 /* 10 minutes */ );
+    ts.tv_nsec = (long) ((pt - floor( pt )) * 1000000000);
+    /* XXX: Best enclose in loop, in case of spurious wakeups? */
+    err = pthread_cond_timedwait( &hostApi->cond, &hostApi->mtx, &ts );
+
+    /* Make sure we didn't time out */
+    UNLESS( err != ETIMEDOUT, paTimedOut );
+    UNLESS( !err, paInternalError );
+
+error:
+    return result;
+}
+
+static PaError AddStream( PaJackStream *stream )
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation *hostApi = stream->hostApi;
+    /* Add to queue of streams that should be processed */
+    ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
+    if( !hostApi->jackIsDown )
+    {
+        hostApi->toAdd = stream;
+        /* Unlock mutex and await signal from processing thread */
+        result = WaitCondition( stream->hostApi );
+    }
+    ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+    ENSURE_PA( result );
+
+    UNLESS( !hostApi->jackIsDown, paDeviceUnavailable );
+
+error:
+    return result;
+}
+
+/* Remove stream from processing queue */
+static PaError RemoveStream( PaJackStream *stream )
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation *hostApi = stream->hostApi;
+
+    /* Add to queue over streams that should be processed */
+    ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
+    if( !hostApi->jackIsDown )
+    {
+        hostApi->toRemove = stream;
+        /* Unlock mutex and await signal from processing thread */
+        result = WaitCondition( stream->hostApi );
+    }
+    ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+    ENSURE_PA( result );
+
+error:
+    return result;
+}
+
+/* Add stream to JACK callback processing queue */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
+    PaJackStream *stream = NULL;
+    char *port_string = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, jack_port_name_size() );
+    unsigned long regexSz = jack_client_name_size() + 3;
+    char *regex_pattern = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, regexSz );
+    const char **jack_ports = NULL;
+    /* int jack_max_buffer_size = jack_get_buffer_size( jackHostApi->jack_client ); */
+    int i;
+    int inputChannelCount, outputChannelCount;
+    const double jackSr = jack_get_sample_rate( jackHostApi->jack_client );
+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+    int bpInitialized = 0, srInitialized = 0;   /* Initialized buffer processor and stream representation? */
+    unsigned long ofs;
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+    if( (streamFlags & paPrimeOutputBuffersUsingStreamCallback) != 0 )
+    {
+        streamFlags &= ~paPrimeOutputBuffersUsingStreamCallback;
+        /*return paInvalidFlag;*/   /* This implementation does not support buffer priming */
+    }
+
+    if( framesPerBuffer != paFramesPerBufferUnspecified )
+    {
+        /* Jack operates with power of two buffers, and we don't support non-integer buffer adaption (yet) */
+        /*UNLESS( !(framesPerBuffer & (framesPerBuffer - 1)), paBufferTooBig );*/  /* TODO: Add descriptive error code? */
+    }
+
+    /* Preliminary checks */
+
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+
+    /* ... check that the sample rate exactly matches the ONE acceptable rate
+     * A: This rate isn't necessarily constant though? */
+
+#define ABS(x) ( (x) > 0 ? (x) : -(x) )
+    if( ABS(sampleRate - jackSr) > 1 )
+       return paInvalidSampleRate;
+#undef ABS
+
+    UNLESS( stream = (PaJackStream*)PaUtil_AllocateMemory( sizeof(PaJackStream) ), paInsufficientMemory );
+    ENSURE_PA( InitializeStream( stream, jackHostApi, inputChannelCount, outputChannelCount ) );
+
+    /* the blocking emulation, if necessary */
+    stream->isBlockingStream = !streamCallback;
+    if( stream->isBlockingStream )
+    {
+        float latency = 0.001; /* 1ms is the absolute minimum we support */
+        int   minimum_buffer_frames = 0;
+
+        if( inputParameters && inputParameters->suggestedLatency > latency )
+            latency = inputParameters->suggestedLatency;
+        else if( outputParameters && outputParameters->suggestedLatency > latency )
+            latency = outputParameters->suggestedLatency;
+
+        /* the latency the user asked for indicates the minimum buffer size in frames */
+        minimum_buffer_frames = (int) (latency * jack_get_sample_rate( jackHostApi->jack_client ));
+
+        /* we also need to be able to store at least three full jack buffers to avoid dropouts */
+        if( jackHostApi->jack_buffer_size * 3 > minimum_buffer_frames )
+            minimum_buffer_frames = jackHostApi->jack_buffer_size * 3;
+
+        /* setup blocking API data structures (FIXME: can fail) */
+        BlockingBegin( stream, minimum_buffer_frames );
+
+        /* install our own callback for the blocking API */
+        streamCallback = BlockingCallback;
+        userData = stream;
+
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &jackHostApi->blockingStreamInterface, streamCallback, userData );
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &jackHostApi->callbackStreamInterface, streamCallback, userData );
+    }
+    srInitialized = 1;
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, jackSr );
+
+    /* create the JACK ports.  We cannot connect them until audio
+     * processing begins */
+
+    /* Register a unique set of ports for this stream
+     * TODO: Robust allocation of new port names */
+
+    ofs = jackHostApi->inputBase;
+    for( i = 0; i < inputChannelCount; i++ )
+    {
+        snprintf( port_string, jack_port_name_size(), "in_%lu", ofs + i );
+        UNLESS( stream->local_input_ports[i] = jack_port_register(
+              jackHostApi->jack_client, port_string,
+              JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 ), paInsufficientMemory );
+    }
+    jackHostApi->inputBase += inputChannelCount;
+
+    ofs = jackHostApi->outputBase;
+    for( i = 0; i < outputChannelCount; i++ )
+    {
+        snprintf( port_string, jack_port_name_size(), "out_%lu", ofs + i );
+        UNLESS( stream->local_output_ports[i] = jack_port_register(
+             jackHostApi->jack_client, port_string,
+             JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 ), paInsufficientMemory );
+    }
+    jackHostApi->outputBase += outputChannelCount;
+
+    /* look up the jack_port_t's for the remote ports.  We could do
+     * this at stream start time, but doing it here ensures the
+     * name lookup only happens once. */
+
+    if( inputChannelCount > 0 )
+    {
+        int err = 0;
+
+        /* Get output ports of our capture device */
+        snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ inputParameters->device ]->name );
+        UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
+                                     JACK_PORT_TYPE_FILTER, JackPortIsOutput ), paUnanticipatedHostError );
+        for( i = 0; i < inputChannelCount && jack_ports[i]; i++ )
+        {
+            if( (stream->remote_output_ports[i] = jack_port_by_name(
+                 jackHostApi->jack_client, jack_ports[i] )) == NULL )
+            {
+                err = 1;
+                break;
+            }
+        }
+        free( jack_ports );
+        UNLESS( !err, paInsufficientMemory );
+
+        /* Fewer ports than expected? */
+        UNLESS( i == inputChannelCount, paInternalError );
+    }
+
+    if( outputChannelCount > 0 )
+    {
+        int err = 0;
+
+        /* Get input ports of our playback device */
+        snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ outputParameters->device ]->name );
+        UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
+                                     JACK_PORT_TYPE_FILTER, JackPortIsInput ), paUnanticipatedHostError );
+        for( i = 0; i < outputChannelCount && jack_ports[i]; i++ )
+        {
+            if( (stream->remote_input_ports[i] = jack_port_by_name(
+                 jackHostApi->jack_client, jack_ports[i] )) == 0 )
+            {
+                err = 1;
+                break;
+            }
+        }
+        free( jack_ports );
+        UNLESS( !err , paInsufficientMemory );
+
+        /* Fewer ports than expected? */
+        UNLESS( i == outputChannelCount, paInternalError );
+    }
+
+    ENSURE_PA( PaUtil_InitializeBufferProcessor(
+                  &stream->bufferProcessor,
+                  inputChannelCount,
+                  inputSampleFormat,
+                  paFloat32 | paNonInterleaved, /* hostInputSampleFormat */
+                  outputChannelCount,
+                  outputSampleFormat,
+                  paFloat32 | paNonInterleaved, /* hostOutputSampleFormat */
+                  jackSr,
+                  streamFlags,
+                  framesPerBuffer,
+                  0,                            /* Ignored */
+                  paUtilUnknownHostBufferSize,  /* Buffer size may vary on JACK's discretion */
+                  streamCallback,
+                  userData ) );
+    bpInitialized = 1;
+
+    if( stream->num_incoming_connections > 0 )
+        stream->streamRepresentation.streamInfo.inputLatency = (jack_port_get_latency( stream->remote_output_ports[0] )
+                - jack_get_buffer_size( jackHostApi->jack_client )  /* One buffer is not counted as latency */
+            + PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor )) / sampleRate;
+    if( stream->num_outgoing_connections > 0 )
+        stream->streamRepresentation.streamInfo.outputLatency = (jack_port_get_latency( stream->remote_input_ports[0] )
+                - jack_get_buffer_size( jackHostApi->jack_client )  /* One buffer is not counted as latency */
+            + PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor )) / sampleRate;
+
+    stream->streamRepresentation.streamInfo.sampleRate = jackSr;
+    stream->t0 = jack_frame_time( jackHostApi->jack_client );   /* A: Time should run from Pa_OpenStream */
+
+    /* Add to queue of opened streams */
+    ENSURE_PA( AddStream( stream ) );
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( stream )
+        CleanUpStream( stream, srInitialized, bpInitialized );
+
+    return result;
+}
+
+/*
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaJackStream *stream = (PaJackStream*)s;
+
+    /* Remove this stream from the processing queue */
+    ENSURE_PA( RemoveStream( stream ) );
+
+error:
+    CleanUpStream( stream, 1, 1 );
+    return result;
+}
+
+static PaError RealProcess( PaJackStream *stream, jack_nframes_t frames )
+{
+    PaError result = paNoError;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+    int chn;
+    int framesProcessed;
+    const double sr = jack_get_sample_rate( stream->jack_client );    /* Shouldn't change during the process callback */
+    PaStreamCallbackFlags cbFlags = 0;
+
+    /* If the user has returned !paContinue from the callback we'll want to flush the internal buffers,
+     * when these are empty we can finally mark the stream as inactive */
+    if( stream->callbackResult != paContinue &&
+            PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+    {
+        stream->is_active = 0;
+        if( stream->streamRepresentation.streamFinishedCallback )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+        PA_DEBUG(( "%s: Callback finished\n", __FUNCTION__ ));
+
+        goto end;
+    }
+
+    timeInfo.currentTime = (jack_frame_time( stream->jack_client ) - stream->t0) / sr;
+    if( stream->num_incoming_connections > 0 )
+        timeInfo.inputBufferAdcTime = timeInfo.currentTime - jack_port_get_latency( stream->remote_output_ports[0] )
+            / sr;
+    if( stream->num_outgoing_connections > 0 )
+        timeInfo.outputBufferDacTime = timeInfo.currentTime + jack_port_get_latency( stream->remote_input_ports[0] )
+            / sr;
+
+    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+    if( stream->xrun )
+    {
+        /* XXX: Any way to tell which of these occurred? */
+        cbFlags = paOutputUnderflow | paInputOverflow;
+        stream->xrun = FALSE;
+    }
+    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
+            cbFlags );
+
+    if( stream->num_incoming_connections > 0 )
+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, frames );
+    if( stream->num_outgoing_connections > 0 )
+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, frames );
+
+    for( chn = 0; chn < stream->num_incoming_connections; chn++ )
+    {
+        jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
+            jack_port_get_buffer( stream->local_input_ports[chn],
+                    frames );
+
+        PaUtil_SetNonInterleavedInputChannel( &stream->bufferProcessor,
+                chn,
+                channel_buf );
+    }
+
+    for( chn = 0; chn < stream->num_outgoing_connections; chn++ )
+    {
+        jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
+            jack_port_get_buffer( stream->local_output_ports[chn],
+                    frames );
+
+        PaUtil_SetNonInterleavedOutputChannel( &stream->bufferProcessor,
+                chn,
+                channel_buf );
+    }
+
+    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
+            &stream->callbackResult );
+    /* We've specified a host buffer size mode where every frame should be consumed by the buffer processor */
+    assert( framesProcessed == frames );
+
+    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+end:
+    return result;
+}
+
+/* Update the JACK callback's stream processing queue. */
+static PaError UpdateQueue( PaJackHostApiRepresentation *hostApi )
+{
+    PaError result = paNoError;
+    int queueModified = 0;
+    const double jackSr = jack_get_sample_rate( hostApi->jack_client );
+    int err;
+
+    if( (err = pthread_mutex_trylock( &hostApi->mtx )) != 0 )
+    {
+        assert( err == EBUSY );
+        return paNoError;
+    }
+
+    if( hostApi->toAdd )
+    {
+        if( hostApi->processQueue )
+        {
+            PaJackStream *node = hostApi->processQueue;
+            /* Advance to end of queue */
+            while( node->next )
+                node = node->next;
+
+            node->next = hostApi->toAdd;
+        }
+        else
+        {
+            /* The only queue entry. */
+            hostApi->processQueue = (PaJackStream *)hostApi->toAdd;
+        }
+
+        /* If necessary, update stream state */
+        if( hostApi->toAdd->streamRepresentation.streamInfo.sampleRate != jackSr )
+            UpdateSampleRate( hostApi->toAdd, jackSr );
+
+        hostApi->toAdd = NULL;
+        queueModified = 1;
+    }
+    if( hostApi->toRemove )
+    {
+        int removed = 0;
+        PaJackStream *node = hostApi->processQueue, *prev = NULL;
+        assert( hostApi->processQueue );
+
+        while( node )
+        {
+            if( node == hostApi->toRemove )
+            {
+                if( prev )
+                    prev->next = node->next;
+                else
+                    hostApi->processQueue = (PaJackStream *)node->next;
+
+                removed = 1;
+                break;
+            }
+
+            prev = node;
+            node = node->next;
+        }
+        UNLESS( removed, paInternalError );
+        hostApi->toRemove = NULL;
+        PA_DEBUG(( "%s: Removed stream from processing queue\n", __FUNCTION__ ));
+        queueModified = 1;
+    }
+
+    if( queueModified )
+    {
+        /* Signal that we've done what was asked of us */
+        ASSERT_CALL( pthread_cond_signal( &hostApi->cond ), 0 );
+    }
+
+error:
+    ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+
+    return result;
+}
+
+/* Audio processing callback invoked periodically from JACK. */
+static int JackCallback( jack_nframes_t frames, void *userData )
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)userData;
+    PaJackStream *stream = NULL;
+    int xrun = hostApi->xrun;
+    hostApi->xrun = 0;
+
+    assert( hostApi );
+
+    ENSURE_PA( UpdateQueue( hostApi ) );
+
+    /* Process each stream */
+    stream = hostApi->processQueue;
+    for( ; stream; stream = stream->next )
+    {
+        if( xrun )  /* Don't override if already set */
+            stream->xrun = 1;
+
+        /* See if this stream is to be started */
+        if( stream->doStart )
+        {
+            /* If we can't obtain a lock, we'll try next time */
+            int err = pthread_mutex_trylock( &stream->hostApi->mtx );
+            if( !err )
+            {
+                if( stream->doStart )   /* Could potentially change before obtaining the lock */
+                {
+                    stream->is_active = 1;
+                    stream->doStart = 0;
+                    PA_DEBUG(( "%s: Starting stream\n", __FUNCTION__ ));
+                    ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
+                    stream->callbackResult = paContinue;
+                    stream->isSilenced = 0;
+                }
+
+                ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+            }
+            else
+                assert( err == EBUSY );
+        }
+        else if( stream->doStop || stream->doAbort )    /* Should we stop/abort stream? */
+        {
+            if( stream->callbackResult == paContinue )     /* Ok, make it stop */
+            {
+                PA_DEBUG(( "%s: Stopping stream\n", __FUNCTION__ ));
+                stream->callbackResult = stream->doStop ? paComplete : paAbort;
+            }
+        }
+
+        if( stream->is_active )
+            ENSURE_PA( RealProcess( stream, frames ) );
+        /* If we have just entered inactive state, silence output */
+        if( !stream->is_active && !stream->isSilenced )
+        {
+            int i;
+
+            /* Silence buffer after entering inactive state */
+            PA_DEBUG(( "Silencing the output\n" ));
+            for( i = 0; i < stream->num_outgoing_connections; ++i )
+            {
+                jack_default_audio_sample_t *buffer = jack_port_get_buffer( stream->local_output_ports[i], frames );
+                memset( buffer, 0, sizeof (jack_default_audio_sample_t) * frames );
+            }
+
+            stream->isSilenced = 1;
+        }
+
+        if( stream->doStop || stream->doAbort )
+        {
+            /* See if RealProcess has acted on the request */
+            if( !stream->is_active )   /* Ok, signal to the main thread that we've carried out the operation */
+            {
+                /* If we can't obtain a lock, we'll try next time */
+                int err = pthread_mutex_trylock( &stream->hostApi->mtx );
+                if( !err )
+                {
+                    stream->doStop = stream->doAbort = 0;
+                    ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
+                    ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+                }
+                else
+                    assert( err == EBUSY );
+            }
+        }
+    }
+
+    return 0;
+error:
+    return -1;
+}
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaJackStream *stream = (PaJackStream*)s;
+    int i;
+
+    /* Ready the processor */
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    /* Connect the ports. Note that the ports may already have been connected by someone else in
+     * the meantime, in which case JACK returns EEXIST. */
+
+    if( stream->num_incoming_connections > 0 )
+    {
+        for( i = 0; i < stream->num_incoming_connections; i++ )
+        {
+            int r = jack_connect( stream->jack_client, jack_port_name( stream->remote_output_ports[i] ),
+                    jack_port_name( stream->local_input_ports[i] ) );
+           UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError );
+        }
+    }
+
+    if( stream->num_outgoing_connections > 0 )
+    {
+        for( i = 0; i < stream->num_outgoing_connections; i++ )
+        {
+            int r = jack_connect( stream->jack_client, jack_port_name( stream->local_output_ports[i] ),
+                    jack_port_name( stream->remote_input_ports[i] ) );
+           UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError );
+        }
+    }
+
+    stream->xrun = FALSE;
+
+    /* Enable processing */
+
+    ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
+    stream->doStart = 1;
+
+    /* Wait for stream to be started */
+    result = WaitCondition( stream->hostApi );
+    /*
+    do
+    {
+        err = pthread_cond_timedwait( &stream->hostApi->cond, &stream->hostApi->mtx, &ts );
+    } while( !stream->is_active && !err );
+    */
+    if( result != paNoError )   /* Something went wrong, call off the stream start */
+    {
+        stream->doStart = 0;
+        stream->is_active = 0;  /* Cancel any processing */
+    }
+    ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+
+    ENSURE_PA( result );
+
+    stream->is_running = TRUE;
+    PA_DEBUG(( "%s: Stream started\n", __FUNCTION__ ));
+
+error:
+    return result;
+}
+
+static PaError RealStop( PaJackStream *stream, int abort )
+{
+    PaError result = paNoError;
+    int i;
+
+    if( stream->isBlockingStream )
+        BlockingWaitEmpty ( stream );
+
+    ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
+    if( abort )
+        stream->doAbort = 1;
+    else
+        stream->doStop = 1;
+
+    /* Wait for stream to be stopped */
+    result = WaitCondition( stream->hostApi );
+    ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+    ENSURE_PA( result );
+
+    UNLESS( !stream->is_active, paInternalError );
+
+    PA_DEBUG(( "%s: Stream stopped\n", __FUNCTION__ ));
+
+error:
+    stream->is_running = FALSE;
+
+    /* Disconnect ports belonging to this stream */
+
+    if( !stream->hostApi->jackIsDown )  /* XXX: Well? */
+    {
+        for( i = 0; i < stream->num_incoming_connections; i++ )
+        {
+            if( jack_port_connected( stream->local_input_ports[i] ) )
+            {
+                UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_input_ports[i] ),
+                        paUnanticipatedHostError );
+            }
+        }
+        for( i = 0; i < stream->num_outgoing_connections; i++ )
+        {
+            if( jack_port_connected( stream->local_output_ports[i] ) )
+            {
+                UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_output_ports[i] ),
+                        paUnanticipatedHostError );
+            }
+        }
+    }
+
+    return result;
+}
+
+static PaError StopStream( PaStream *s )
+{
+    assert(s);
+    return RealStop( (PaJackStream *)s, 0 );
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    assert(s);
+    return RealStop( (PaJackStream *)s, 1 );
+}
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaJackStream *stream = (PaJackStream*)s;
+    return !stream->is_running;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaJackStream *stream = (PaJackStream*)s;
+    return stream->is_active;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaJackStream *stream = (PaJackStream*)s;
+
+    /* A: Is this relevant?? --> TODO: what if we're recording-only? */
+    return (jack_frame_time( stream->jack_client ) - stream->t0) / (PaTime)jack_get_sample_rate( stream->jack_client );
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaJackStream *stream = (PaJackStream*)s;
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+PaError PaJack_SetClientName( const char* name )
+{
+    if( strlen( name ) > jack_client_name_size() )
+    {
+        /* OK, I don't know any better error code */
+        return paInvalidFlag;
+    }
+    clientName_ = name;
+    return paNoError;
+}
+
+PaError PaJack_GetClientName(const char** clientName)
+{
+    PaError result = paNoError;
+    PaJackHostApiRepresentation* jackHostApi = NULL;
+    PaJackHostApiRepresentation** ref = &jackHostApi;
+    ENSURE_PA( PaUtil_GetHostApiRepresentation( (PaUtilHostApiRepresentation**)ref, paJACK ) );
+    *clientName = jack_get_client_name( jackHostApi->jack_client );
+
+error:
+    return result;
+}
diff --git a/portaudio/src/hostapi/oss/pa_unix_oss.c b/portaudio/src/hostapi/oss/pa_unix_oss.c
new file mode 100644 (file)
index 0000000..51e9630
--- /dev/null
@@ -0,0 +1,2045 @@
+/*
+ * $Id$
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * OSS implementation by:
+ *   Douglas Repetto
+ *   Phil Burk
+ *   Dominic Mazzoni
+ *   Arve Knudsen
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/poll.h>
+#include <limits.h>
+#include <semaphore.h>
+
+#ifdef HAVE_SYS_SOUNDCARD_H
+# include <sys/soundcard.h>
+# ifdef __NetBSD__
+#  define DEVICE_NAME_BASE           "/dev/audio"
+# else
+#  define DEVICE_NAME_BASE           "/dev/dsp"
+# endif
+#elif defined(HAVE_LINUX_SOUNDCARD_H)
+# include <linux/soundcard.h>
+# define DEVICE_NAME_BASE            "/dev/dsp"
+#elif defined(HAVE_MACHINE_SOUNDCARD_H)
+# include <machine/soundcard.h> /* JH20010905 */
+# define DEVICE_NAME_BASE            "/dev/audio"
+#else
+# error No sound card header file
+#endif
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_unix_util.h"
+#include "pa_debugprint.h"
+
+static int sysErr_;
+static pthread_t mainThread_;
+
+/* Check return value of system call, and map it to PaError */
+#define ENSURE_(expr, code) \
+    do { \
+        if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \
+        { \
+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+            if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+            { \
+                PaUtil_SetLastHostErrorInfo( paOSS, sysErr_, strerror( errno ) ); \
+            } \
+            \
+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = (code); \
+            goto error; \
+        } \
+    } while( 0 );
+
+#ifndef AFMT_S16_NE
+#define AFMT_S16_NE  Get_AFMT_S16_NE()
+/*********************************************************************
+ * Some versions of OSS do not define AFMT_S16_NE. So check CPU.
+ * PowerPC is Big Endian. X86 is Little Endian.
+ */
+static int Get_AFMT_S16_NE( void )
+{
+    long testData = 1;
+    char *ptr = (char *) &testData;
+    int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */
+    return isLittle ? AFMT_S16_LE : AFMT_S16_BE;
+}
+#endif
+
+/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    PaHostApiIndex hostApiIndex;
+}
+PaOSSHostApiRepresentation;
+
+/** Per-direction structure for PaOssStream.
+ *
+ * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,
+ * but with different number of channels we will have to adapt between the number of user and host
+ * channels for at least one direction, since the configuration space is the same for both directions
+ * of an OSS device.
+ */
+typedef struct
+{
+    int fd;
+    const char *devName;
+    int userChannelCount, hostChannelCount;
+    int userInterleaved;
+    void *buffer;
+    PaSampleFormat userFormat, hostFormat;
+    double latency;
+    unsigned long hostFrames, numBufs;
+    void **userBuffers; /* For non-interleaved blocking */
+} PaOssStreamComponent;
+
+/** Implementation specific representation of a PaStream.
+ *
+ */
+typedef struct PaOssStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    PaUtilThreading threading;
+
+    int sharedDevice;
+    unsigned long framesPerHostBuffer;
+    int triggered;  /* Have the devices been triggered yet (first start) */
+
+    int isActive;
+    int isStopped;
+
+    int lastPosPtr;
+    double lastStreamBytes;
+
+    int framesProcessed;
+
+    double sampleRate;
+
+    int callbackMode;
+    volatile int callbackStop, callbackAbort;
+
+    PaOssStreamComponent *capture, *playback;
+    unsigned long pollTimeout;
+    sem_t semaphore;
+}
+PaOssStream;
+
+typedef enum {
+    StreamMode_In,
+    StreamMode_Out
+} StreamMode;
+
+/* prototypes for functions declared in this file */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );
+
+
+/** Initialize the OSS API implementation.
+ *
+ * This function will initialize host API datastructures and query host devices for information.
+ *
+ * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here
+ *
+ * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,
+ * this happens with the usual "error" label.
+ */
+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaOSSHostApiRepresentation *ossHostApi = NULL;
+
+    PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),
+            paInsufficientMemory );
+    PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+    ossHostApi->hostApiIndex = hostApiIndex;
+
+    /* Initialize host API structure */
+    *hostApi = &ossHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paOSS;
+    (*hostApi)->info.name = "OSS";
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PA_ENSURE( BuildDeviceList( ossHostApi ) );
+
+    PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable,
+                                      PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    mainThread_ = pthread_self();
+
+    return result;
+
+error:
+    if( ossHostApi )
+    {
+        if( ossHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( ossHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
+        }
+
+        PaUtil_FreeMemory( ossHostApi );
+    }
+    return result;
+}
+
+PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,
+        int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,
+        PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations  )
+{
+    PaError result = paNoError;
+
+    deviceInfo->structVersion = 2;
+    if( allocations )
+    {
+        size_t len = strlen( name ) + 1;
+        PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );
+        strncpy( (char *)deviceInfo->name, name, len );
+    }
+    else
+        deviceInfo->name = name;
+
+    deviceInfo->hostApi = hostApiIndex;
+    deviceInfo->maxInputChannels = maxInputChannels;
+    deviceInfo->maxOutputChannels = maxOutputChannels;
+    deviceInfo->defaultLowInputLatency = defaultLowInputLatency;
+    deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;
+    deviceInfo->defaultHighInputLatency = defaultHighInputLatency;
+    deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;
+    deviceInfo->defaultSampleRate = defaultSampleRate;
+
+error:
+    return result;
+}
+
+static int CalcHigherLogTwo( int n )
+{
+    int log2 = 0;
+    while( (1<<log2) < n ) log2++;
+    return log2;
+}
+
+static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,
+        double *defaultLowLatency, double *defaultHighLatency )
+{
+    PaError result = paNoError;
+    int numChannels, maxNumChannels;
+    int busy = 0;
+    int devHandle = -1;
+    int sr;
+    *maxChannelCount = 0;  /* Default value in case this fails */
+    int temp, frgmt;
+    unsigned long fragFrames;
+
+    if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK ))  < 0 )
+    {
+        if( errno == EBUSY || errno == EAGAIN )
+        {
+            PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));
+        }
+        else
+        {
+            /* Ignore ENOENT, which means we've tried a non-existent device */
+            if( errno != ENOENT )
+            {
+                PA_DEBUG(( "%s: Can't access device %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
+            }
+        }
+
+        return paDeviceUnavailable;
+    }
+
+    /* Negotiate for the maximum number of channels for this device. PLB20010927
+     * Consider up to 16 as the upper number of channels.
+     * Variable maxNumChannels should contain the actual upper limit after the call.
+     * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
+     */
+    maxNumChannels = 0;
+    for( numChannels = 1; numChannels <= 16; numChannels++ )
+    {
+        temp = numChannels;
+        if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )
+        {
+            busy = EAGAIN == errno || EBUSY == errno;
+            /* ioctl() failed so bail out if we already have stereo */
+            if( maxNumChannels >= 2 )
+                break;
+        }
+        else
+        {
+            /* ioctl() worked but bail out if it does not support numChannels.
+             * We don't want to leave gaps in the numChannels supported.
+             */
+            if( (numChannels > 2) && (temp != numChannels) )
+                break;
+            if( temp > maxNumChannels )
+                maxNumChannels = temp; /* Save maximum. */
+        }
+    }
+    /* A: We're able to open a device for capture if it's busy playing back and vice versa,
+     * but we can't configure anything */
+    if( 0 == maxNumChannels && busy )
+    {
+        result = paDeviceUnavailable;
+        goto error;
+    }
+
+    /* The above negotiation may fail for an old driver so try this older technique. */
+    if( maxNumChannels < 1 )
+    {
+        int stereo = 1;
+        if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )
+        {
+            maxNumChannels = 1;
+        }
+        else
+        {
+            maxNumChannels = (stereo) ? 2 : 1;
+        }
+        PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ));
+    }
+
+    /* During channel negotiation, the last ioctl() may have failed. This can
+     * also cause sample rate negotiation to fail. Hence the following, to return
+     * to a supported number of channels. SG20011005 */
+    {
+        /* use most reasonable default value */
+        numChannels = PA_MIN( maxNumChannels, 2 );
+        ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &numChannels ), paUnanticipatedHostError );
+    }
+
+    /* Get supported sample rate closest to 44100 Hz */
+    if( *defaultSampleRate < 0 )
+    {
+        sr = 44100;
+        ENSURE_( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ), paUnanticipatedHostError );
+
+        *defaultSampleRate = sr;
+    }
+
+    *maxChannelCount = maxNumChannels;
+
+    /* Attempt to set low latency with 4 frags-per-buffer, 128 frames-per-frag (total buffer 512 frames)
+     * since the ioctl sets bytes, multiply by numChannels, and base on 2 bytes-per-sample, */
+    fragFrames = 128;
+    frgmt = (4 << 16) + (CalcHigherLogTwo( fragFrames * numChannels * 2 ) & 0xffff);
+    ENSURE_( ioctl( devHandle, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
+
+    /* Use the value set by the ioctl to give the latency achieved */
+    fragFrames = pow( 2, frgmt & 0xffff ) / (numChannels * 2);
+    *defaultLowLatency = ((frgmt >> 16) - 1) * fragFrames / *defaultSampleRate;
+
+    /* Cannot now try setting a high latency (device would need closing and opening again).  Make
+     * high-latency 4 times the low unless the fragFrames are significantly more than requested 128 */
+    temp = (fragFrames < 256) ? 4 : (fragFrames < 512) ? 2 : 1;
+    *defaultHighLatency = temp * *defaultLowLatency;
+
+error:
+    if( devHandle >= 0 )
+        close( devHandle );
+
+    return result;
+}
+
+/** Query OSS device.
+ *
+ * This is where PaDeviceInfo objects are constructed and filled in with relevant information.
+ *
+ * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed
+ * in place.
+ */
+static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )
+{
+    PaError result = paNoError;
+    double sampleRate = -1.;
+    int maxInputChannels, maxOutputChannels;
+    PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;
+    PaError tmpRes = paNoError;
+    int busy = 0;
+    *deviceInfo = NULL;
+
+    /* douglas:
+       we have to do this querying in a slightly different order. apparently
+       some sound cards will give you different info based on their settins.
+       e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
+       the correct order for OSS is: format, channels, sample rate
+    */
+
+    /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is
+     * opened in, it may have more channels available for capture than playback and vice versa. Therefore
+     * we will open the device in both read- and write-only mode to determine the supported number.
+     */
+    if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,
+                &defaultHighInputLatency )) != paNoError )
+    {
+        if( tmpRes != paDeviceUnavailable )
+        {
+            PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));
+            /* PA_ENSURE( tmpRes ); */
+        }
+        ++busy;
+    }
+    if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,
+                &defaultHighOutputLatency )) != paNoError )
+    {
+        if( tmpRes != paDeviceUnavailable )
+        {
+            PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));
+            /* PA_ENSURE( tmpRes ); */
+        }
+        ++busy;
+    }
+    assert( 0 <= busy && busy <= 2 );
+    if( 2 == busy )     /* Both directions are unavailable to us */
+    {
+        result = paDeviceUnavailable;
+        goto error;
+    }
+
+    PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );
+    PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,
+                defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,
+                ossApi->allocations ) );
+
+error:
+    return result;
+}
+
+/** Query host devices.
+ *
+ * Loop over host devices and query their capabilitiesu
+ *
+ * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object
+ * per device, these are placed in the host api representation's deviceInfos array.
+ */
+static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
+{
+    PaError result = paNoError;
+    PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;
+    int i;
+    int numDevices = 0, maxDeviceInfos = 1;
+    PaDeviceInfo **deviceInfos = NULL;
+
+    /* These two will be set to the first working input and output device, respectively */
+    commonApi->info.defaultInputDevice = paNoDevice;
+    commonApi->info.defaultOutputDevice = paNoDevice;
+
+    /* Find devices by calling QueryDevice on each
+     * potential device names.  When we find a valid one,
+     * add it to a linked list.
+     * A: Set an arbitrary of 100 devices, should probably be a smarter way. */
+
+    for( i = 0; i < 100; i++ )
+    {
+       char deviceName[32];
+       PaDeviceInfo *deviceInfo;
+       int testResult;
+
+       if( i == 0 )
+          snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
+       else
+          snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);
+
+       /* PA_DEBUG(("%s: trying device %s\n", __FUNCTION__, deviceName )); */
+       if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
+       {
+           if( testResult != paDeviceUnavailable )
+               PA_ENSURE( testResult );
+
+           continue;
+       }
+
+       ++numDevices;
+       if( !deviceInfos || numDevices > maxDeviceInfos )
+       {
+           maxDeviceInfos *= 2;
+           PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),
+                   paInsufficientMemory );
+       }
+       {
+           int devIdx = numDevices - 1;
+           deviceInfos[devIdx] = deviceInfo;
+
+           if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )
+               commonApi->info.defaultInputDevice = devIdx;
+           if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )
+               commonApi->info.defaultOutputDevice = devIdx;
+       }
+    }
+
+    /* Make an array of PaDeviceInfo pointers out of the linked list */
+
+    PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));
+
+    commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+        ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
+    memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );
+
+    commonApi->info.deviceCount = numDevices;
+
+error:
+    free( deviceInfos );
+
+    return result;
+}
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
+
+    if( ossHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( ossHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( ossHostApi );
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaError result = paNoError;
+    PaDeviceIndex device;
+    PaDeviceInfo *deviceInfo;
+    char *deviceName;
+    int inputChannelCount, outputChannelCount;
+    int tempDevHandle = -1;
+    int flags;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+
+    if (inputChannelCount == 0 && outputChannelCount == 0)
+        return paInvalidChannelCount;
+
+    /* if full duplex, make sure that they're the same device */
+
+    if (inputChannelCount > 0 && outputChannelCount > 0 &&
+        inputParameters->device != outputParameters->device)
+        return paInvalidDevice;
+
+    /* if full duplex, also make sure that they're the same number of channels */
+
+    if (inputChannelCount > 0 && outputChannelCount > 0 &&
+        inputChannelCount != outputChannelCount)
+       return paInvalidChannelCount;
+
+    /* open the device so we can do more tests */
+
+    if( inputChannelCount > 0 )
+    {
+        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);
+        if (result != paNoError)
+            return result;
+    }
+    else
+    {
+        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);
+        if (result != paNoError)
+            return result;
+    }
+
+    deviceInfo = hostApi->deviceInfos[device];
+    deviceName = (char *)deviceInfo->name;
+
+    flags = O_NONBLOCK;
+    if (inputChannelCount > 0 && outputChannelCount > 0)
+       flags |= O_RDWR;
+    else if (inputChannelCount > 0)
+       flags |= O_RDONLY;
+    else
+       flags |= O_WRONLY;
+
+    ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );
+
+    /* PaOssStream_Configure will do the rest of the checking for us */
+    /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */
+
+    /* everything succeeded! */
+
+ error:
+    if( tempDevHandle >= 0 )
+        close( tempDevHandle );
+
+    return result;
+}
+
+/** Validate stream parameters.
+ *
+ * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device
+ */
+static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )
+{
+    int maxChans;
+
+    assert( parameters );
+
+    if( parameters->device == paUseHostApiSpecificDeviceSpecification )
+    {
+        return paInvalidDevice;
+    }
+
+    maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels :
+        deviceInfo->maxOutputChannels);
+    if( parameters->channelCount > maxChans )
+    {
+        return paInvalidChannelCount;
+    }
+
+    return paNoError;
+}
+
+static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,
+        int callbackMode, int fd, const char *deviceName )
+{
+    PaError result = paNoError;
+    assert( component );
+
+    memset( component, 0, sizeof (PaOssStreamComponent) );
+
+    component->fd = fd;
+    component->devName = deviceName;
+    component->userChannelCount = parameters->channelCount;
+    component->userFormat = parameters->sampleFormat;
+    component->latency = parameters->suggestedLatency;
+    component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);
+
+    if( !callbackMode && !component->userInterleaved )
+    {
+        /* Pre-allocate non-interleaved user provided buffers */
+        PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),
+                paInsufficientMemory );
+    }
+
+error:
+    return result;
+}
+
+static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )
+{
+    assert( component );
+
+    if( component->fd >= 0 )
+        close( component->fd );
+    if( component->buffer )
+        PaUtil_FreeMemory( component->buffer );
+
+    if( component->userBuffers )
+        PaUtil_FreeMemory( component->userBuffers );
+
+    PaUtil_FreeMemory( component );
+}
+
+static PaError ModifyBlocking( int fd, int blocking )
+{
+    PaError result = paNoError;
+    int fflags;
+
+    ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );
+
+    if( blocking )
+        fflags &= ~O_NONBLOCK;
+    else
+        fflags |= O_NONBLOCK;
+
+    ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );
+
+error:
+    return result;
+}
+
+/** Open input and output devices.
+ *
+ * @param idev: Returned input device file descriptor.
+ * @param odev: Returned output device file descriptor.
+ */
+static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
+{
+    PaError result = paNoError;
+    int flags = O_NONBLOCK, duplex = 0;
+    *idev = *odev = -1;
+
+    if( idevName && odevName )
+    {
+        duplex = 1;
+        flags |= O_RDWR;
+    }
+    else if( idevName )
+        flags |= O_RDONLY;
+    else
+        flags |= O_WRONLY;
+
+    /* open first in nonblocking mode, in case it's busy...
+     * A: then unset the non-blocking attribute */
+    assert( flags & O_NONBLOCK );
+    if( idevName )
+    {
+        ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
+        PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
+    }
+    if( odevName )
+    {
+        if( !idevName )
+        {
+            ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
+            PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
+        }
+        else
+        {
+            ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );
+        }
+    }
+
+error:
+    return result;
+}
+
+static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,
+        PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,
+        PaOSSHostApiRepresentation *ossApi )
+{
+    PaError result = paNoError;
+    int idev, odev;
+    PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;
+    const char *idevName = NULL, *odevName = NULL;
+
+    assert( stream );
+
+    memset( stream, 0, sizeof (PaOssStream) );
+    stream->isStopped = 1;
+
+    PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );
+
+    if( inputParameters && outputParameters )
+    {
+        if( inputParameters->device == outputParameters->device )
+            stream->sharedDevice = 1;
+    }
+
+    if( inputParameters )
+        idevName = hostApi->deviceInfos[inputParameters->device]->name;
+    if( outputParameters )
+        odevName = hostApi->deviceInfos[outputParameters->device]->name;
+    PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );
+    if( inputParameters )
+    {
+        PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
+        PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );
+    }
+    if( outputParameters )
+    {
+        PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
+        PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );
+    }
+
+    if( callback != NULL )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &ossApi->callbackStreamInterface, callback, userData );
+        stream->callbackMode = 1;
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &ossApi->blockingStreamInterface, callback, userData );
+    }
+
+    ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );
+
+error:
+    return result;
+}
+
+static void PaOssStream_Terminate( PaOssStream *stream )
+{
+    assert( stream );
+
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+    PaUtil_TerminateThreading( &stream->threading );
+
+    if( stream->capture )
+        PaOssStreamComponent_Terminate( stream->capture );
+    if( stream->playback )
+        PaOssStreamComponent_Terminate( stream->playback );
+
+    sem_destroy( &stream->semaphore );
+
+    PaUtil_FreeMemory( stream );
+}
+
+/** Translate from PA format to OSS native.
+ *
+ */
+static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )
+{
+    switch( paFormat )
+    {
+        case paUInt8:
+            *ossFormat = AFMT_U8;
+            break;
+        case paInt8:
+            *ossFormat = AFMT_S8;
+            break;
+        case paInt16:
+            *ossFormat = AFMT_S16_NE;
+            break;
+        default:
+            return paInternalError;     /* This shouldn't happen */
+    }
+
+    return paNoError;
+}
+
+/** Return the PA-compatible formats that this device can support.
+ *
+ */
+static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )
+{
+    PaError result = paNoError;
+    int mask = 0;
+    PaSampleFormat frmts = 0;
+
+    ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );
+    if( mask & AFMT_U8 )
+        frmts |= paUInt8;
+    if( mask & AFMT_S8 )
+        frmts |= paInt8;
+    if( mask & AFMT_S16_NE )
+        frmts |= paInt16;
+    else
+        result = paSampleFormatNotSupported;
+
+    *availableFormats = frmts;
+
+error:
+    return result;
+}
+
+static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )
+{
+    return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;
+}
+
+/** Buffer size in bytes.
+ *
+ */
+static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )
+{
+    return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;
+}
+
+/** Configure stream component device parameters.
+ */
+static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long
+        framesPerBuffer, StreamMode streamMode, PaOssStreamComponent *master )
+{
+    PaError result = paNoError;
+    int temp, nativeFormat;
+    int sr = (int)sampleRate;
+    PaSampleFormat availableFormats = 0, hostFormat = 0;
+    int chans = component->userChannelCount;
+    int frgmt;
+    int numBufs;
+    int bytesPerBuf;
+    unsigned long bufSz;
+    unsigned long fragSz;
+    audio_buf_info bufInfo;
+
+    /* We may have a situation where only one component (the master) is configured, if both point to the same device.
+     * In that case, the second component will copy settings from the other */
+    if( !master )
+    {
+        /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.
+         * The hardware need not respect the requested fragment size, so we may have to adapt.
+         */
+        if( framesPerBuffer == paFramesPerBufferUnspecified )
+        {
+            /* Aim for 4 fragments in the complete buffer; the latency comes from 3 of these */
+            fragSz = (unsigned long)(component->latency * sampleRate / 3);
+            bufSz = fragSz * 4;
+        }
+        else
+        {
+            fragSz = framesPerBuffer;
+            bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */
+        }
+
+        PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );
+        hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );
+
+        /* OSS demands at least 2 buffers, and 16 bytes per buffer */
+        numBufs = (int)PA_MAX( bufSz / fragSz, 2 );
+        bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );
+
+        /* The fragment parameters are encoded like this:
+         * Most significant byte: number of fragments
+         * Least significant byte: exponent of fragment size (i.e., for 256, 8)
+         */
+        frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);
+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
+
+        /* A: according to the OSS programmer's guide parameters should be set in this order:
+         * format, channels, rate */
+
+        /* This format should be deemed good before we get this far */
+        PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );
+        nativeFormat = temp;
+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );
+        PA_UNLESS( temp == nativeFormat, paInternalError );
+
+        /* try to set the number of channels */
+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported );   /* XXX: Should be paInvalidChannelCount? */
+        /* It's possible that the minimum number of host channels is greater than what the user requested */
+        PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );
+
+        /* try to set the sample rate */
+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );
+
+        /* reject if there's no sample rate within 1% of the one requested */
+        if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )
+        {
+            PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
+            PA_ENSURE( paInvalidSampleRate );
+        }
+
+        ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),
+                paUnanticipatedHostError );
+        component->numBufs = bufInfo.fragstotal;
+
+        /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */
+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );
+
+        component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;
+        component->hostChannelCount = chans;
+        component->hostFormat = hostFormat;
+    }
+    else
+    {
+        component->hostFormat = master->hostFormat;
+        component->hostFrames = master->hostFrames;
+        component->hostChannelCount = master->hostChannelCount;
+        component->numBufs = master->numBufs;
+    }
+
+    PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),
+            paInsufficientMemory );
+
+error:
+    return result;
+}
+
+static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )
+{
+    PaError result = paNoError;
+    size_t len = *frames * PaOssStreamComponent_FrameSize( component );
+    ssize_t bytesRead;
+
+    ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );
+    *frames = bytesRead / PaOssStreamComponent_FrameSize( component );
+    /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */
+
+error:
+    return result;
+}
+
+static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )
+{
+    PaError result = paNoError;
+    size_t len = *frames * PaOssStreamComponent_FrameSize( component );
+    ssize_t bytesWritten;
+
+    ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );
+    *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );
+    /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */
+
+error:
+    return result;
+}
+
+/** Configure the stream according to input/output parameters.
+ *
+ * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by
+ * the user, if so we'll record the actual number of host channels and adapt later.
+ */
+static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,
+        double *inputLatency, double *outputLatency )
+{
+    PaError result = paNoError;
+    int duplex = stream->capture && stream->playback;
+    unsigned long framesPerHostBuffer = 0;
+
+    /* We should request full duplex first thing after opening the device */
+    if( duplex && stream->sharedDevice )
+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );
+
+    if( stream->capture )
+    {
+        PaOssStreamComponent *component = stream->capture;
+        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In,
+                    NULL ) );
+
+        assert( component->hostChannelCount > 0 );
+        assert( component->hostFrames > 0 );
+
+        *inputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
+    }
+    if( stream->playback )
+    {
+        PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;
+        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,
+                    master ) );
+
+        assert( component->hostChannelCount > 0 );
+        assert( component->hostFrames > 0 );
+
+        *outputLatency = (component->hostFrames * (component->numBufs - 1)) / sampleRate;
+    }
+
+    if( duplex )
+        framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );
+    else if( stream->capture )
+        framesPerHostBuffer = stream->capture->hostFrames;
+    else if( stream->playback )
+        framesPerHostBuffer = stream->playback->hostFrames;
+
+    stream->framesPerHostBuffer = framesPerHostBuffer;
+    stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate );    /* Period in usecs, rounded up */
+
+    stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+error:
+    return result;
+}
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+/** Open a PA OSS stream.
+ *
+ * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the
+ * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both
+ * directions are the same device we will demand the same number of channels. The number of channels can range
+ * from 1 to the maximum supported by the device.
+ *
+ * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback
+ * must reflect this, in addition the host latency per device should approximate the corresponding
+ * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that
+ * both capture and playback can agree on (they can be different devices), the buffer processor can adapt
+ * between host and user buffer size, but the ratio should preferably be integral.
+ */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
+    PaOssStream *stream = NULL;
+    int inputChannelCount = 0, outputChannelCount = 0;
+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;
+    const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
+    int bpInitialized = 0;
+    double inLatency = 0., outLatency = 0.;
+    int i = 0;
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+
+    if( inputParameters )
+    {
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];
+        PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+    }
+    if( outputParameters )
+    {
+        outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];
+        PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+    }
+
+    /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same
+     * device is opened for both directions
+     */
+    if( inputChannelCount > 0 && outputChannelCount > 0 )
+    {
+        if( inputParameters->device == outputParameters->device )
+        {
+            if( inputParameters->channelCount != outputParameters->channelCount )
+                return paInvalidChannelCount;
+        }
+    }
+
+    /* Round framesPerBuffer to the next power-of-two to make OSS happy. */
+    if( framesPerBuffer != paFramesPerBufferUnspecified )
+    {
+        framesPerBuffer &= INT_MAX;
+        for (i = 1; framesPerBuffer > i; i <<= 1) ;
+        framesPerBuffer = i;
+    }
+
+    /* allocate and do basic initialization of the stream structure */
+    PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
+    PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );
+
+    PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+    if( inputParameters )
+    {
+        inputHostFormat = stream->capture->hostFormat;
+        stream->streamRepresentation.streamInfo.inputLatency = inLatency +
+            PaUtil_GetBufferProcessorInputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
+    }
+    if( outputParameters )
+    {
+        outputHostFormat = stream->playback->hostFormat;
+        stream->streamRepresentation.streamInfo.outputLatency = outLatency +
+            PaUtil_GetBufferProcessorOutputLatencyFrames( &stream->bufferProcessor ) / sampleRate;
+    }
+
+    /* Initialize buffer processor with fixed host buffer size.
+     * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will
+     * convert between the two.
+     */
+    PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+              inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,
+              outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,
+              paUtilFixedHostBufferSize, streamCallback, userData ) );
+    bpInitialized = 1;
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( bpInitialized )
+        PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    if( stream )
+        PaOssStream_Terminate( stream );
+
+    return result;
+}
+
+/*! Poll on I/O filedescriptors.
+
+  Poll till we've determined there's data for read or write. In the full-duplex case,
+  we don't want to hang around forever waiting for either input or output frames, so
+  whenever we have a timed out filedescriptor we check if we're nearing under/overrun
+  for the other direction (critical limit set at one buffer). If so, we exit the waiting
+  state, and go on with what we got. We align the number of frames on a host buffer
+  boundary because it is possible that the buffer size differs for the two directions and
+  the host buffer size is a compromise between the two.
+  */
+static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )
+{
+    PaError result = paNoError;
+    int pollPlayback = 0, pollCapture = 0;
+    int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;
+    audio_buf_info bufInfo;
+    /* int ofs = 0, nfds = stream->nfds; */
+    fd_set readFds, writeFds;
+    int nfds = 0;
+    struct timeval selectTimeval = {0, 0};
+    unsigned long timeout = stream->pollTimeout;    /* In usecs */
+    int captureFd = -1, playbackFd = -1;
+
+    assert( stream );
+    assert( frames );
+
+    if( stream->capture )
+    {
+        pollCapture = 1;
+        captureFd = stream->capture->fd;
+        /* stream->capture->pfd->events = POLLIN; */
+    }
+    if( stream->playback )
+    {
+        pollPlayback = 1;
+        playbackFd = stream->playback->fd;
+        /* stream->playback->pfd->events = POLLOUT; */
+    }
+
+    FD_ZERO( &readFds );
+    FD_ZERO( &writeFds );
+
+    while( pollPlayback || pollCapture )
+    {
+#ifdef PTHREAD_CANCELED
+        pthread_testcancel();
+#else
+        /* avoid indefinite waiting on thread not supporting cancelation */
+        if( stream->callbackStop || stream->callbackAbort )
+        {
+            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
+            (*frames) = 0;
+            return paNoError;
+        }
+#endif
+
+        /* select may modify the timeout parameter */
+        selectTimeval.tv_usec = timeout;
+        nfds = 0;
+
+        if( pollCapture )
+        {
+            FD_SET( captureFd, &readFds );
+            nfds = captureFd + 1;
+        }
+        if( pollPlayback )
+        {
+            FD_SET( playbackFd, &writeFds );
+            nfds = PA_MAX( nfds, playbackFd + 1 );
+        }
+        ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );
+        /*
+        if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )
+        {
+
+            ENSURE_( -1, paUnanticipatedHostError );
+        }
+        */
+#ifdef PTHREAD_CANCELED
+        pthread_testcancel();
+#else
+        /* avoid indefinite waiting on thread not supporting cancelation */
+        if( stream->callbackStop || stream->callbackAbort )
+        {
+            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
+            (*frames) = 0;
+            return paNoError;
+        }
+#endif
+        if( pollCapture )
+        {
+            if( FD_ISSET( captureFd, &readFds ) )
+            {
+                FD_CLR( captureFd, &readFds );
+                pollCapture = 0;
+            }
+            /*
+            if( stream->capture->pfd->revents & POLLIN )
+            {
+                --nfds;
+                ++ofs;
+                pollCapture = 0;
+            }
+            */
+            else if( stream->playback ) /* Timed out, go on with playback? */
+            {
+                /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",
+                            __FUNCTION__, stream->pollTimeout ));*/
+            }
+        }
+        if( pollPlayback )
+        {
+            if( FD_ISSET( playbackFd, &writeFds ) )
+            {
+                FD_CLR( playbackFd, &writeFds );
+                pollPlayback = 0;
+            }
+            /*
+            if( stream->playback->pfd->revents & POLLOUT )
+            {
+                --nfds;
+                pollPlayback = 0;
+            }
+            */
+            else if( stream->capture )  /* Timed out, go on with capture? */
+            {
+                /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",
+                            __FUNCTION__, stream->pollTimeout ));*/
+            }
+        }
+    }
+
+    if( stream->capture )
+    {
+        ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );
+        captureAvail = bufInfo.fragments * stream->capture->hostFrames;
+        if( !captureAvail )
+            PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));
+
+        captureAvail = captureAvail == 0 ? INT_MAX : captureAvail;      /* Disregard if zero */
+    }
+    if( stream->playback )
+    {
+        ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );
+        playbackAvail = bufInfo.fragments * stream->playback->hostFrames;
+        if( !playbackAvail )
+        {
+            PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));
+        }
+
+        playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail;      /* Disregard if zero */
+    }
+
+    commonAvail = PA_MIN( captureAvail, playbackAvail );
+    if( commonAvail == INT_MAX )
+        commonAvail = 0;
+    commonAvail -= commonAvail % stream->framesPerHostBuffer;
+
+    assert( commonAvail != INT_MAX );
+    assert( commonAvail >= 0 );
+    *frames = commonAvail;
+
+error:
+    return result;
+}
+
+/** Prepare stream for capture/playback.
+ *
+ * In order to synchronize capture and playback properly we use the SETTRIGGER command.
+ */
+static PaError PaOssStream_Prepare( PaOssStream *stream )
+{
+    PaError result = paNoError;
+    int enableBits = 0;
+
+    if( stream->triggered )
+        return result;
+
+    /* The OSS reference instructs us to clear direction bits before setting them.*/
+    if( stream->playback )
+        ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+    if( stream->capture )
+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+
+    if( stream->playback )
+    {
+        size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
+        memset( stream->playback->buffer, 0, bufSz );
+
+        /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer
+         * OSS will complain. */
+        PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
+        while (1)
+        {
+            if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )
+                break;
+        }
+        PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );
+    }
+
+    if( stream->sharedDevice )
+    {
+        enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+    }
+    else
+    {
+        if( stream->capture )
+        {
+            enableBits = PCM_ENABLE_INPUT;
+            ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+        }
+        if( stream->playback )
+        {
+            enableBits = PCM_ENABLE_OUTPUT;
+            ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+        }
+    }
+
+    /* Ok, we have triggered the stream */
+    stream->triggered = 1;
+
+error:
+    return result;
+}
+
+/** Stop audio processing
+ *
+ */
+static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
+     * Also disable capture/playback till the stream is started again.
+     */
+    int captureErr = 0, playbackErr = 0;
+    if( stream->capture )
+    {
+        if( (captureErr = ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 )) < 0 )
+        {
+            PA_DEBUG(( "%s: Failed to stop capture device, error: %d\n", __FUNCTION__, captureErr ));
+        }
+    }
+    if( stream->playback && !stream->sharedDevice )
+    {
+        if( (playbackErr = ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 )) < 0 )
+        {
+            PA_DEBUG(( "%s: Failed to stop playback device, error: %d\n", __FUNCTION__, playbackErr ));
+        }
+    }
+
+    if( captureErr || playbackErr )
+    {
+        result = paUnanticipatedHostError;
+    }
+
+    return result;
+}
+
+/** Clean up after thread exit.
+ *
+ * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here
+ */
+static void OnExit( void *data )
+{
+    PaOssStream *stream = (PaOssStream *) data;
+    assert( data );
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+    PaOssStream_Stop( stream, stream->callbackAbort );
+
+    PA_DEBUG(( "OnExit: Stoppage\n" ));
+
+    /* Eventually notify user all buffers have played */
+    if( stream->streamRepresentation.streamFinishedCallback )
+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+
+    stream->callbackAbort = 0;      /* Clear state */
+    stream->isActive = 0;
+}
+
+static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )
+{
+    PaError result = paNoError;
+
+    if( stream->capture )
+    {
+        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,
+                stream->capture->hostChannelCount );
+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );
+    }
+    if( stream->playback )
+    {
+        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,
+                stream->playback->hostChannelCount );
+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );
+    }
+
+    return result;
+}
+
+/** Thread procedure for callback processing.
+ *
+ * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the
+ * callback should be used for buffer priming. When the stream is cancelled a separate function will
+ * take care of the transition to the Callback Finished state (the stream isn't considered Stopped
+ * before StopStream() or AbortStream() are called).
+ */
+static void *PaOSS_AudioThreadProc( void *userData )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)userData;
+    unsigned long framesAvail = 0, framesProcessed = 0;
+    int callbackResult = paContinue;
+    int triggered = stream->triggered;  /* See if SNDCTL_DSP_TRIGGER has been issued already */
+    int initiateProcessing = triggered;    /* Already triggered? */
+    PaStreamCallbackFlags cbFlags = 0;  /* We might want to keep state across iterations */
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */
+
+    /*
+#if ( SOUND_VERSION > 0x030904 )
+        audio_errinfo errinfo;
+#endif
+*/
+
+    assert( stream );
+
+    pthread_cleanup_push( &OnExit, stream );   /* Execute OnExit when exiting */
+
+    /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and
+     * playback in sync, when the stream is restarted after being stopped we simply start by reading/
+     * writing.
+     */
+    PA_ENSURE( PaOssStream_Prepare( stream ) );
+
+    /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */
+    if( initiateProcessing )
+    {
+        /* Make sure devices are in blocking mode */
+        if( stream->capture )
+            ModifyBlocking( stream->capture->fd, 1 );
+        if( stream->playback )
+            ModifyBlocking( stream->playback->fd, 1 );
+    }
+
+    while( 1 )
+    {
+#ifdef PTHREAD_CANCELED
+        pthread_testcancel();
+#else
+        if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
+        {
+            PA_DEBUG(( "Aborting callback thread\n" ));
+            break;
+        }
+#endif
+        if( stream->callbackStop && callbackResult == paContinue )
+        {
+            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+            callbackResult = paComplete;
+        }
+
+        /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless
+         * the stream has been recently started, we will have to go right ahead and read/write in blocking
+         * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch
+         * to non-blocking mode.
+         */
+        if( !initiateProcessing )
+        {
+            /* Wait on available frames */
+            PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) );
+            assert( framesAvail % stream->framesPerHostBuffer == 0 );
+        }
+        else
+        {
+            framesAvail = stream->framesPerHostBuffer;
+        }
+
+        while( framesAvail > 0 )
+        {
+            unsigned long frames = framesAvail;
+
+#ifdef PTHREAD_CANCELED
+            pthread_testcancel();
+#else
+            if( stream->callbackStop )
+            {
+                PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+                callbackResult = paComplete;
+            }
+
+            if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
+            {
+                PA_DEBUG(( "Aborting callback thread\n" ));
+                break;
+            }
+#endif
+            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+            /* Read data */
+            if ( stream->capture )
+            {
+                PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );
+                if( frames < framesAvail )
+                {
+                    PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames ));
+                    framesAvail = frames;
+                }
+            }
+
+#if ( SOUND_VERSION >= 0x030904 )
+            /*
+               Check with OSS to see if there have been any under/overruns
+               since last time we checked.
+               */
+            /*
+            if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )
+            {
+                if( errinfo.play_underruns )
+                    cbFlags |= paOutputUnderflow ;
+                if( errinfo.record_underruns )
+                    cbFlags |= paInputUnderflow ;
+            }
+            else
+                PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));
+                */
+#endif
+
+            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
+                    cbFlags );
+            cbFlags = 0;
+            PA_ENSURE( SetUpBuffers( stream, framesAvail ) );
+
+            framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
+                    &callbackResult );
+            assert( framesProcessed == framesAvail );
+            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+            if ( stream->playback )
+            {
+                frames = framesAvail;
+
+                PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );
+                if( frames < framesAvail )
+                {
+                    /* TODO: handle bytesWritten != bytesRequested (slippage?) */
+                    PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames ));
+                }
+            }
+
+            framesAvail -= framesProcessed;
+            stream->framesProcessed += framesProcessed;
+
+            if( callbackResult != paContinue )
+                break;
+        }
+
+        if( initiateProcessing || !triggered )
+        {
+            /* Non-blocking */
+            if( stream->capture )
+                PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );
+            if( stream->playback && !stream->sharedDevice )
+                PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
+
+            initiateProcessing = 0;
+            sem_post( &stream->semaphore );
+        }
+
+        if( callbackResult != paContinue )
+        {
+            stream->callbackAbort = callbackResult == paAbort;
+            if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+                break;
+        }
+    }
+
+    pthread_cleanup_pop( 1 );
+
+error:
+    pthread_exit( NULL );
+}
+
+/** Close the stream.
+ *
+ */
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+
+    assert( stream );
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaOssStream_Terminate( stream );
+
+    return result;
+}
+
+/** Start the stream.
+ *
+ * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual
+ * callback will be repeatedly called in a separate thread. If a separate thread is started this function
+ * will block untill it has started processing audio, otherwise audio processing is started directly.
+ */
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+
+    stream->isActive = 1;
+    stream->isStopped = 0;
+    stream->lastPosPtr = 0;
+    stream->lastStreamBytes = 0;
+    stream->framesProcessed = 0;
+
+    /* only use the thread for callback streams */
+    if( stream->bufferProcessor.streamCallback )
+    {
+        PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );
+        sem_wait( &stream->semaphore );
+    }
+    else
+        PA_ENSURE( PaOssStream_Prepare( stream ) );
+
+error:
+    return result;
+}
+
+static PaError RealStop( PaOssStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    if( stream->callbackMode )
+    {
+        if( abort )
+            stream->callbackAbort = 1;
+        else
+            stream->callbackStop = 1;
+
+        PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );
+
+        stream->callbackStop = stream->callbackAbort = 0;
+    }
+    else
+        PA_ENSURE( PaOssStream_Stop( stream, abort ) );
+
+    stream->isStopped = 1;
+
+error:
+    return result;
+}
+
+/** Stop the stream.
+ *
+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued
+ * buffers.
+ */
+static PaError StopStream( PaStream *s )
+{
+    return RealStop( (PaOssStream *)s, 0 );
+}
+
+/** Abort the stream.
+ *
+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued
+ * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing
+ * the OSS device.
+ */
+static PaError AbortStream( PaStream *s )
+{
+    return RealStop( (PaOssStream *)s, 1 );
+}
+
+/** Is the stream in the Stopped state.
+ *
+ */
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaOssStream *stream = (PaOssStream*)s;
+
+    return (stream->isStopped);
+}
+
+/** Is the stream in the Active state.
+ *
+ */
+static PaError IsStreamActive( PaStream *s )
+{
+    PaOssStream *stream = (PaOssStream*)s;
+
+    return (stream->isActive);
+}
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaOssStream *stream = (PaOssStream*)s;
+    count_info info;
+    int delta;
+
+    if( stream->playback ) {
+        if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {
+            delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;
+            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;
+        }
+    }
+    else {
+        if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {
+            delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;
+            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;
+        }
+    }
+
+    /* the ioctl failed, but we can still give a coarse estimate */
+
+    return stream->framesProcessed / stream->sampleRate;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaOssStream *stream = (PaOssStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+    As separate stream interfaces are used for blocking and callback
+    streams, the following functions can be guaranteed to only be called
+    for blocking streams.
+*/
+
+
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+    int bytesRequested, bytesRead;
+    unsigned long framesRequested;
+    void *userBuffer;
+
+    /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,
+     * so we copy the user provided pointers */
+    if( stream->bufferProcessor.userInputIsInterleaved )
+        userBuffer = buffer;
+    else /* Copy channels into local array */
+    {
+        userBuffer = stream->capture->userBuffers;
+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );
+    }
+
+    while( frames )
+    {
+        framesRequested = PA_MIN( frames, stream->capture->hostFrames );
+
+       bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
+       ENSURE_( (bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested )),
+                 paUnanticipatedHostError );
+       if ( bytesRequested != bytesRead )
+       {
+           PA_DEBUG(( "Requested %d bytes, read %d\n", bytesRequested, bytesRead ));
+           return paUnanticipatedHostError;
+       }
+
+       PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
+       PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
+        PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
+       frames -= framesRequested;
+    }
+
+error:
+    return result;
+}
+
+
+static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+    int bytesRequested, bytesWritten;
+    unsigned long framesConverted;
+    const void *userBuffer;
+
+    /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,
+     * so we copy the user provided pointers */
+    if( stream->bufferProcessor.userOutputIsInterleaved )
+        userBuffer = buffer;
+    else
+    {
+        /* Copy channels into local array */
+        userBuffer = stream->playback->userBuffers;
+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );
+    }
+
+    while( frames )
+    {
+       PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );
+       PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );
+
+       framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );
+       frames -= framesConverted;
+
+       bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
+       ENSURE_( (bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested )),
+                 paUnanticipatedHostError );
+
+       if ( bytesRequested != bytesWritten )
+       {
+           PA_DEBUG(( "Requested %d bytes, wrote %d\n", bytesRequested, bytesWritten ));
+           return paUnanticipatedHostError;
+       }
+    }
+
+error:
+    return result;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+    audio_buf_info info;
+
+    ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ), paUnanticipatedHostError );
+    return info.fragments * stream->capture->hostFrames;
+
+error:
+    return result;
+}
+
+
+/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaOssStream *stream = (PaOssStream*)s;
+    int delay = 0;
+#ifdef SNDCTL_DSP_GETODELAY
+    ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ), paUnanticipatedHostError );
+#endif
+    return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
+
+/* Conditionally compile this to avoid warning about unused label */
+#ifdef SNDCTL_DSP_GETODELAY
+error:
+    return result;
+#endif
+}
+
diff --git a/portaudio/src/hostapi/oss/recplay.c b/portaudio/src/hostapi/oss/recplay.c
new file mode 100644 (file)
index 0000000..9d4c78c
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * recplay.c
+ * Phil Burk
+ * Minimal record and playback test.
+ * 
+ */
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#ifndef __STDC__
+/* #include <getopt.h> */
+#endif /* __STDC__ */
+#include <fcntl.h>
+#ifdef __STDC__
+#include <string.h>
+#else /* __STDC__ */
+#include <strings.h>
+#endif /* __STDC__ */
+#include <sys/soundcard.h>
+
+#define NUM_BYTES   (64*1024)
+#define BLOCK_SIZE   (4*1024)
+
+#define AUDIO "/dev/dsp"
+
+char buffer[NUM_BYTES];
+
+int audioDev = 0;
+
+main (int argc, char *argv[])
+{
+    int   numLeft;
+    char *ptr;
+    int   num;
+    int   samplesize;
+
+    /********** RECORD ********************/
+    /* Open audio device. */
+    audioDev = open (AUDIO, O_RDONLY, 0);
+    if (audioDev == -1)
+    {
+        perror (AUDIO);
+        exit (-1);
+    }
+
+    /* Set to 16 bit samples. */
+    samplesize = 16;
+    ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize);
+    if (samplesize != 16)
+    {
+        perror("Unable to set the sample size.");
+        exit(-1);
+    }
+
+    /* Record in blocks */
+    printf("Begin recording.\n");
+    numLeft = NUM_BYTES;
+    ptr = buffer;
+    while( numLeft >= BLOCK_SIZE )
+    {
+        if ( (num = read (audioDev, ptr, BLOCK_SIZE)) < 0 )
+        {
+            perror (AUDIO);
+            exit (-1);
+        }
+        else
+        {
+            printf("Read %d bytes\n", num);
+            ptr += num;
+            numLeft -= num;
+        }
+    }
+
+    close( audioDev );
+
+    /********** PLAYBACK ********************/
+    /* Open audio device for writing. */
+    audioDev = open (AUDIO, O_WRONLY, 0);
+    if (audioDev == -1)
+    {
+        perror (AUDIO);
+        exit (-1);
+    }
+
+    /* Set to 16 bit samples. */
+    samplesize = 16;
+    ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize);
+    if (samplesize != 16)
+    {
+        perror("Unable to set the sample size.");
+        exit(-1);
+    }
+
+    /* Play in blocks */
+    printf("Begin playing.\n");
+    numLeft = NUM_BYTES;
+    ptr = buffer;
+    while( numLeft >= BLOCK_SIZE )
+    {
+        if ( (num = write (audioDev, ptr, BLOCK_SIZE)) < 0 )
+        {
+            perror (AUDIO);
+            exit (-1);
+        }
+        else
+        {
+            printf("Wrote %d bytes\n", num);
+            ptr += num;
+            numLeft -= num;
+        }
+    }
+
+    close( audioDev );
+}
diff --git a/portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c b/portaudio/src/hostapi/skeleton/pa_hostapi_skeleton.c
new file mode 100644 (file)
index 0000000..6edc22c
--- /dev/null
@@ -0,0 +1,818 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library skeleton implementation
+ * demonstrates how to use the common functions to implement support
+ * for a host API
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Skeleton implementation of support for a host API.
+
+ This file is provided as a starting point for implementing support for
+ a new host API. It provides examples of how the common code can be used.
+
+ @note IMPLEMENT ME comments are used to indicate functionality
+ which much be customised for each implementation.
+*/
+
+
+#include <string.h> /* strlen() */
+
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+
+
+/* prototypes for functions declared in this file */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+
+/* IMPLEMENT ME: a macro like the following one should be used for reporting
+ host errors */
+#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+    PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )
+
+/* PaSkeletonHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    /* implementation specific data goes here */
+}
+PaSkeletonHostApiRepresentation;  /* IMPLEMENT ME: rename this */
+
+
+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int i, deviceCount;
+    PaSkeletonHostApiRepresentation *skeletonHostApi;
+    PaDeviceInfo *deviceInfoArray;
+
+    skeletonHostApi = (PaSkeletonHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaSkeletonHostApiRepresentation) );
+    if( !skeletonHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    skeletonHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !skeletonHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi = &skeletonHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paInDevelopment;            /* IMPLEMENT ME: change to correct type id */
+    (*hostApi)->info.name = "skeleton implementation";  /* IMPLEMENT ME: change to correct name */
+
+    (*hostApi)->info.defaultInputDevice = paNoDevice;  /* IMPLEMENT ME */
+    (*hostApi)->info.defaultOutputDevice = paNoDevice; /* IMPLEMENT ME */
+
+    (*hostApi)->info.deviceCount = 0;  
+
+    deviceCount = 0; /* IMPLEMENT ME */
+    
+    if( deviceCount > 0 )
+    {
+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                skeletonHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );
+        if( !(*hostApi)->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
+                skeletonHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for( i=0; i < deviceCount; ++i )
+        {
+            PaDeviceInfo *deviceInfo = &deviceInfoArray[i];
+            deviceInfo->structVersion = 2;
+            deviceInfo->hostApi = hostApiIndex;
+            deviceInfo->name = 0; /* IMPLEMENT ME: allocate block and copy name eg:
+                deviceName = (char*)PaUtil_GroupAllocateMemory( skeletonHostApi->allocations, strlen(srcName) + 1 );
+                if( !deviceName )
+                {
+                    result = paInsufficientMemory;
+                    goto error;
+                }
+                strcpy( deviceName, srcName );
+                deviceInfo->name = deviceName;
+            */
+
+            deviceInfo->maxInputChannels = 0;  /* IMPLEMENT ME */
+            deviceInfo->maxOutputChannels = 0;  /* IMPLEMENT ME */
+            
+            deviceInfo->defaultLowInputLatency = 0.;  /* IMPLEMENT ME */
+            deviceInfo->defaultLowOutputLatency = 0.;  /* IMPLEMENT ME */
+            deviceInfo->defaultHighInputLatency = 0.;  /* IMPLEMENT ME */
+            deviceInfo->defaultHighOutputLatency = 0.;  /* IMPLEMENT ME */  
+
+            deviceInfo->defaultSampleRate = 0.; /* IMPLEMENT ME */
+            
+            (*hostApi)->deviceInfos[i] = deviceInfo;
+            ++(*hostApi)->info.deviceCount;
+        }
+    }
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &skeletonHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &skeletonHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    return result;
+
+error:
+    if( skeletonHostApi )
+    {
+        if( skeletonHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( skeletonHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations );
+        }
+                
+        PaUtil_FreeMemory( skeletonHostApi );
+    }
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi;
+
+    /*
+        IMPLEMENT ME:
+            - clean up any resources not handled by the allocation group
+    */
+
+    if( skeletonHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( skeletonHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( skeletonHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( inputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( outputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+            
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support outputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+    
+    /*
+        IMPLEMENT ME:
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported if necessary
+
+            - check that the device supports sampleRate
+
+        Because the buffer adapter handles conversion between all standard
+        sample formats, the following checks are only required if paCustomFormat
+        is implemented, or under some other unusual conditions.
+
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from inputSampleFormat to
+                a native format
+
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+    */
+
+
+    /* suppress unused variable warnings */
+    (void) sampleRate;
+
+    return paFormatIsSupported;
+}
+
+/* PaSkeletonStream - a stream data structure specifically for this implementation */
+
+typedef struct PaSkeletonStream
+{ /* IMPLEMENT ME: rename this */
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    /* IMPLEMENT ME:
+            - implementation specific data goes here
+    */
+    unsigned long framesPerHostCallback; /* just an example */
+}
+PaSkeletonStream;
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi;
+    PaSkeletonStream *stream = 0;
+    unsigned long framesPerHostBuffer = framesPerBuffer; /* these may not be equivalent for all implementations */
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+
+
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+
+        /* IMPLEMENT ME - establish which  host formats are available */
+        hostInputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );
+    }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+            return paInvalidDevice;
+
+        /* check that output device can support inputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+
+        /* IMPLEMENT ME - establish which  host formats are available */
+        hostOutputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );
+    }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */
+    }
+
+    /*
+        IMPLEMENT ME:
+
+        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() FIXME - checks needed? )
+
+            - check that input device can support inputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - check that output device can support outputSampleFormat, or that
+                we have the capability to convert from outputSampleFormat to
+                a native format
+
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+
+            - check that the device supports sampleRate
+
+            - alter sampleRate to a close allowable rate if possible / necessary
+
+            - validate suggestedInputLatency and suggestedOutputLatency parameters,
+                use default values where necessary
+    */
+
+
+
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+
+
+    stream = (PaSkeletonStream*)PaUtil_AllocateMemory( sizeof(PaSkeletonStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    if( streamCallback )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &skeletonHostApi->callbackStreamInterface, streamCallback, userData );
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                               &skeletonHostApi->blockingStreamInterface, streamCallback, userData );
+    }
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+    /* we assume a fixed host buffer size in this example, but the buffer processor
+        can also support bounded and unknown host buffer sizes by passing 
+        paUtilBoundedHostBufferSize or paUtilUnknownHostBufferSize instead of
+        paUtilFixedHostBufferSize below. */
+        
+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+              inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+              outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+              sampleRate, streamFlags, framesPerBuffer,
+              framesPerHostBuffer, paUtilFixedHostBufferSize,
+              streamCallback, userData );
+    if( result != paNoError )
+        goto error;
+
+
+    /*
+        IMPLEMENT ME: initialise the following fields with estimated or actual
+        values.
+    */
+    stream->streamRepresentation.streamInfo.inputLatency =
+            (PaTime)PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) / sampleRate; /* inputLatency is specified in _seconds_ */
+    stream->streamRepresentation.streamInfo.outputLatency =
+            (PaTime)PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) / sampleRate; /* outputLatency is specified in _seconds_ */
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    
+    /*
+        IMPLEMENT ME:
+            - additional stream setup + opening
+    */
+
+    stream->framesPerHostCallback = framesPerHostBuffer;
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( stream )
+        PaUtil_FreeMemory( stream );
+
+    return result;
+}
+
+/*
+    ExampleHostProcessingLoop() illustrates the kind of processing which may
+    occur in a host implementation.
+*/
+static void ExampleHostProcessingLoop( void *inputBuffer, void *outputBuffer, void *userData )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)userData;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* IMPLEMENT ME */
+    int callbackResult;
+    unsigned long framesProcessed;
+    
+    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+    
+    /*
+        IMPLEMENT ME:
+            - generate timing information
+            - handle buffer slips
+    */
+
+    /*
+        If you need to byte swap or shift inputBuffer to convert it into a
+        portaudio format, do it here.
+    */
+
+
+
+    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */ );
+
+    /*
+        depending on whether the host buffers are interleaved, non-interleaved
+        or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),
+        PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.
+    */
+    
+    PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+    PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
+            0, /* first channel of inputBuffer is channel 0 */
+            inputBuffer,
+            0 ); /* 0 - use inputChannelCount passed to init buffer processor */
+
+    PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
+            0, /* first channel of outputBuffer is channel 0 */
+            outputBuffer,
+            0 ); /* 0 - use outputChannelCount passed to init buffer processor */
+
+    /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()
+        in general you would pass paContinue for normal operation, and
+        paComplete to drain the buffer processor's internal output buffer.
+        You can check whether the buffer processor's output buffer is empty
+        using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )
+    */
+    callbackResult = paContinue;
+    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+
+    
+    /*
+        If you need to byte swap or shift outputBuffer to convert it to
+        host format, do it here.
+    */
+
+    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+
+    if( callbackResult == paContinue )
+    {
+        /* nothing special to do */
+    }
+    else if( callbackResult == paAbort )
+    {
+        /* IMPLEMENT ME - finish playback immediately  */
+
+        /* once finished, call the finished callback */
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+    else
+    {
+        /* User callback has asked us to stop with paComplete or other non-zero value */
+
+        /* IMPLEMENT ME - finish playback once currently queued audio has completed  */
+
+        /* once finished, call the finished callback */
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+}
+
+
+/*
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /*
+        IMPLEMENT ME:
+            - additional stream closing + cleanup
+    */
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+    PaUtil_FreeMemory( stream );
+
+    return result;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior */
+
+    /* suppress unused function warning. the code in ExampleHostProcessingLoop or
+       something similar should be implemented to feed samples to and from the
+       host after StartStream() is called.
+    */
+    (void) ExampleHostProcessingLoop;
+
+    return result;
+}
+
+
+static PaError StopStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior */
+
+    return result;
+}
+
+
+static PaError AbortStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior */
+
+    return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior */
+
+    return 0;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior */
+
+    return 0;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return 0;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+    As separate stream interfaces are used for blocking and callback
+    streams, the following functions can be guaranteed to only be called
+    for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return paNoError;
+}
+
+
+static PaError WriteStream( PaStream* s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return paNoError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return 0;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaSkeletonStream *stream = (PaSkeletonStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+    
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+
+    return 0;
+}
+
+
+
+
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ks.h b/portaudio/src/hostapi/wasapi/mingw-include/ks.h
new file mode 100644 (file)
index 0000000..2261e6c
--- /dev/null
@@ -0,0 +1,3666 @@
+/**
+ * This file has no copyright assigned and is placed in the Public Domain.
+ * This file is part of the w64 mingw-runtime package.
+ * No warranty is given; refer to the file DISCLAIMER.PD within this package.
+ */
+#ifndef _KS_
+#define _KS_
+
+#if __GNUC__ >= 3
+#pragma GCC system_header
+#endif
+
+#ifndef __MINGW_EXTENSION
+#if defined(__GNUC__) || defined(__GNUG__)
+#define __MINGW_EXTENSION __extension__
+#else
+#define __MINGW_EXTENSION
+#endif
+#endif 
+
+#ifdef __TCS__
+#define _KS_NO_ANONYMOUS_STRUCTURES_ 1
+#endif
+
+#ifdef  _KS_NO_ANONYMOUS_STRUCTURES_
+#define _KS_ANON_STRUCT(X)                     struct X
+#else
+#define _KS_ANON_STRUCT(X)     __MINGW_EXTENSION struct
+#endif
+
+#ifndef _NTRTL_
+#ifndef DEFINE_GUIDEX
+#define DEFINE_GUIDEX(name) EXTERN_C const CDECL GUID name
+#endif
+#ifndef STATICGUIDOF
+#define STATICGUIDOF(guid) STATIC_##guid
+#endif
+#endif /* _NTRTL_ */
+
+#ifndef SIZEOF_ARRAY
+#define SIZEOF_ARRAY(ar) (sizeof(ar)/sizeof((ar)[0]))
+#endif
+
+#define DEFINE_GUIDSTRUCT(g,n) DEFINE_GUIDEX(n)
+#define DEFINE_GUIDNAMED(n) n
+
+#define STATIC_GUID_NULL                                               \
+       0x00000000L,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
+
+DEFINE_GUIDSTRUCT("00000000-0000-0000-0000-000000000000",GUID_NULL);
+#define GUID_NULL DEFINE_GUIDNAMED(GUID_NULL)
+
+#define IOCTL_KS_PROPERTY CTL_CODE(FILE_DEVICE_KS,0x000,METHOD_NEITHER,FILE_ANY_ACCESS)
+#define IOCTL_KS_ENABLE_EVENT CTL_CODE(FILE_DEVICE_KS,0x001,METHOD_NEITHER,FILE_ANY_ACCESS)
+#define IOCTL_KS_DISABLE_EVENT CTL_CODE(FILE_DEVICE_KS,0x002,METHOD_NEITHER,FILE_ANY_ACCESS)
+#define IOCTL_KS_METHOD CTL_CODE(FILE_DEVICE_KS,0x003,METHOD_NEITHER,FILE_ANY_ACCESS)
+#define IOCTL_KS_WRITE_STREAM CTL_CODE(FILE_DEVICE_KS,0x004,METHOD_NEITHER,FILE_WRITE_ACCESS)
+#define IOCTL_KS_READ_STREAM CTL_CODE(FILE_DEVICE_KS,0x005,METHOD_NEITHER,FILE_READ_ACCESS)
+#define IOCTL_KS_RESET_STATE CTL_CODE(FILE_DEVICE_KS,0x006,METHOD_NEITHER,FILE_ANY_ACCESS)
+
+typedef enum {
+  KSRESET_BEGIN,
+  KSRESET_END
+} KSRESET;
+
+typedef enum {
+  KSSTATE_STOP,
+  KSSTATE_ACQUIRE,
+  KSSTATE_PAUSE,
+  KSSTATE_RUN
+} KSSTATE,*PKSSTATE;
+
+#define KSPRIORITY_LOW         0x00000001
+#define KSPRIORITY_NORMAL      0x40000000
+#define KSPRIORITY_HIGH                0x80000000
+#define KSPRIORITY_EXCLUSIVE   0xFFFFFFFF
+
+typedef struct {
+  ULONG PriorityClass;
+  ULONG PrioritySubClass;
+} KSPRIORITY,*PKSPRIORITY;
+
+typedef struct {
+  __MINGW_EXTENSION union {
+    _KS_ANON_STRUCT(_IDENTIFIER)
+    {
+      GUID Set;
+      ULONG Id;
+      ULONG Flags;
+    };
+    LONGLONG Alignment;
+  };
+} KSIDENTIFIER,*PKSIDENTIFIER;
+
+typedef KSIDENTIFIER KSPROPERTY,*PKSPROPERTY,KSMETHOD,*PKSMETHOD,KSEVENT,*PKSEVENT;
+
+#define KSMETHOD_TYPE_NONE             0x00000000
+#define KSMETHOD_TYPE_READ             0x00000001
+#define KSMETHOD_TYPE_WRITE            0x00000002
+#define KSMETHOD_TYPE_MODIFY           0x00000003
+#define KSMETHOD_TYPE_SOURCE           0x00000004
+
+#define KSMETHOD_TYPE_SEND             0x00000001
+#define KSMETHOD_TYPE_SETSUPPORT       0x00000100
+#define KSMETHOD_TYPE_BASICSUPPORT     0x00000200
+
+#define KSMETHOD_TYPE_TOPOLOGY         0x10000000
+
+#define KSPROPERTY_TYPE_GET            0x00000001
+#define KSPROPERTY_TYPE_SET            0x00000002
+#define KSPROPERTY_TYPE_SETSUPPORT     0x00000100
+#define KSPROPERTY_TYPE_BASICSUPPORT   0x00000200
+#define KSPROPERTY_TYPE_RELATIONS      0x00000400
+#define KSPROPERTY_TYPE_SERIALIZESET   0x00000800
+#define KSPROPERTY_TYPE_UNSERIALIZESET 0x00001000
+#define KSPROPERTY_TYPE_SERIALIZERAW   0x00002000
+#define KSPROPERTY_TYPE_UNSERIALIZERAW 0x00004000
+#define KSPROPERTY_TYPE_SERIALIZESIZE  0x00008000
+#define KSPROPERTY_TYPE_DEFAULTVALUES  0x00010000
+
+#define KSPROPERTY_TYPE_TOPOLOGY       0x10000000
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG NodeId;
+  ULONG Reserved;
+} KSP_NODE,*PKSP_NODE;
+
+typedef struct {
+  KSMETHOD Method;
+  ULONG NodeId;
+  ULONG Reserved;
+} KSM_NODE,*PKSM_NODE;
+
+typedef struct {
+  KSEVENT Event;
+  ULONG NodeId;
+  ULONG Reserved;
+} KSE_NODE,*PKSE_NODE;
+
+#define STATIC_KSPROPTYPESETID_General                                 \
+       0x97E99BA0L,0xBDEA,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("97E99BA0-BDEA-11CF-A5D6-28DB04C10000",KSPROPTYPESETID_General);
+#define KSPROPTYPESETID_General DEFINE_GUIDNAMED(KSPROPTYPESETID_General)
+
+typedef struct {
+  ULONG Size;
+  ULONG Count;
+} KSMULTIPLE_ITEM,*PKSMULTIPLE_ITEM;
+
+typedef struct {
+  ULONG AccessFlags;
+  ULONG DescriptionSize;
+  KSIDENTIFIER PropTypeSet;
+  ULONG MembersListCount;
+  ULONG Reserved;
+} KSPROPERTY_DESCRIPTION,*PKSPROPERTY_DESCRIPTION;
+
+#define KSPROPERTY_MEMBER_RANGES               0x00000001
+#define KSPROPERTY_MEMBER_STEPPEDRANGES                0x00000002
+#define KSPROPERTY_MEMBER_VALUES               0x00000003
+
+#define KSPROPERTY_MEMBER_FLAG_DEFAULT         0x00000001
+#define KSPROPERTY_MEMBER_FLAG_BASICSUPPORT_MULTICHANNEL 0x00000002
+#define KSPROPERTY_MEMBER_FLAG_BASICSUPPORT_UNIFORM    0x00000004
+
+typedef struct {
+  ULONG MembersFlags;
+  ULONG MembersSize;
+  ULONG MembersCount;
+  ULONG Flags;
+} KSPROPERTY_MEMBERSHEADER,*PKSPROPERTY_MEMBERSHEADER;
+
+typedef union {
+  _KS_ANON_STRUCT(_SIGNED)
+  {
+    LONG SignedMinimum;
+    LONG SignedMaximum;
+  };
+  _KS_ANON_STRUCT(_UNSIGNED)
+  {
+    ULONG UnsignedMinimum;
+    ULONG UnsignedMaximum;
+  };
+} KSPROPERTY_BOUNDS_LONG,*PKSPROPERTY_BOUNDS_LONG;
+
+typedef union {
+  _KS_ANON_STRUCT(_SIGNED64)
+  {
+    LONGLONG SignedMinimum;
+    LONGLONG SignedMaximum;
+  };
+  _KS_ANON_STRUCT(_UNSIGNED64)
+  {
+    DWORDLONG UnsignedMinimum;
+    DWORDLONG UnsignedMaximum;
+  };
+} KSPROPERTY_BOUNDS_LONGLONG,*PKSPROPERTY_BOUNDS_LONGLONG;
+
+typedef struct {
+  ULONG SteppingDelta;
+  ULONG Reserved;
+  KSPROPERTY_BOUNDS_LONG Bounds;
+} KSPROPERTY_STEPPING_LONG,*PKSPROPERTY_STEPPING_LONG;
+
+typedef struct {
+  DWORDLONG SteppingDelta;
+  KSPROPERTY_BOUNDS_LONGLONG Bounds;
+} KSPROPERTY_STEPPING_LONGLONG,*PKSPROPERTY_STEPPING_LONGLONG;
+
+#if defined(_NTDDK_)
+typedef struct _KSDEVICE_DESCRIPTOR KSDEVICE_DESCRIPTOR, *PKSDEVICE_DESCRIPTOR;
+typedef struct _KSDEVICE_DISPATCH KSDEVICE_DISPATCH, *PKSDEVICE_DISPATCH;
+typedef struct _KSDEVICE KSDEVICE, *PKSDEVICE;
+typedef struct _KSFILTERFACTORY KSFILTERFACTORY, *PKSFILTERFACTORY;
+typedef struct _KSFILTER_DESCRIPTOR KSFILTER_DESCRIPTOR, *PKSFILTER_DESCRIPTOR;
+typedef struct _KSFILTER_DISPATCH KSFILTER_DISPATCH, *PKSFILTER_DISPATCH;
+typedef struct _KSFILTER KSFILTER, *PKSFILTER;
+typedef struct _KSPIN_DESCRIPTOR_EX KSPIN_DESCRIPTOR_EX, *PKSPIN_DESCRIPTOR_EX;
+typedef struct _KSPIN_DISPATCH KSPIN_DISPATCH, *PKSPIN_DISPATCH;
+typedef struct _KSCLOCK_DISPATCH KSCLOCK_DISPATCH, *PKSCLOCK_DISPATCH;
+typedef struct _KSALLOCATOR_DISPATCH KSALLOCATOR_DISPATCH, *PKSALLOCATOR_DISPATCH;
+typedef struct _KSPIN KSPIN, *PKSPIN;
+typedef struct _KSNODE_DESCRIPTOR KSNODE_DESCRIPTOR, *PKSNODE_DESCRIPTOR;
+typedef struct _KSSTREAM_POINTER_OFFSET KSSTREAM_POINTER_OFFSET, *PKSSTREAM_POINTER_OFFSET;
+typedef struct _KSSTREAM_POINTER KSSTREAM_POINTER, *PKSSTREAM_POINTER;
+typedef struct _KSMAPPING KSMAPPING, *PKSMAPPING;
+typedef struct _KSPROCESSPIN KSPROCESSPIN, *PKSPROCESSPIN;
+typedef struct _KSPROCESSPIN_INDEXENTRY KSPROCESSPIN_INDEXENTRY, *PKSPROCESSPIN_INDEXENTRY;
+#endif /* _NTDDK_ */
+
+typedef PVOID PKSWORKER;
+
+
+typedef struct {
+  ULONG NotificationType;
+  __MINGW_EXTENSION union {
+    struct {
+      HANDLE Event;
+      ULONG_PTR Reserved[2];
+    } EventHandle;
+    struct {
+      HANDLE Semaphore;
+      ULONG Reserved;
+      LONG Adjustment;
+    } SemaphoreHandle;
+#if defined(_NTDDK_)
+    struct {
+      PVOID Event;
+      KPRIORITY Increment;
+      ULONG_PTR Reserved;
+    } EventObject;
+    struct {
+      PVOID Semaphore;
+      KPRIORITY Increment;
+      LONG Adjustment;
+    } SemaphoreObject;
+    struct {
+      PKDPC Dpc;
+      ULONG ReferenceCount;
+      ULONG_PTR Reserved;
+    } Dpc;
+    struct {
+      PWORK_QUEUE_ITEM WorkQueueItem;
+      WORK_QUEUE_TYPE WorkQueueType;
+      ULONG_PTR Reserved;
+    } WorkItem;
+    struct {
+      PWORK_QUEUE_ITEM WorkQueueItem;
+      PKSWORKER KsWorkerObject;
+      ULONG_PTR Reserved;
+    } KsWorkItem;
+#endif /* _NTDDK_ */
+    struct {
+      PVOID Unused;
+      LONG_PTR Alignment[2];
+    } Alignment;
+  };
+} KSEVENTDATA,*PKSEVENTDATA;
+
+#define KSEVENTF_EVENT_HANDLE          0x00000001
+#define KSEVENTF_SEMAPHORE_HANDLE      0x00000002
+#if defined(_NTDDK_)
+#define KSEVENTF_EVENT_OBJECT          0x00000004
+#define KSEVENTF_SEMAPHORE_OBJECT      0x00000008
+#define KSEVENTF_DPC                   0x00000010
+#define KSEVENTF_WORKITEM              0x00000020
+#define KSEVENTF_KSWORKITEM            0x00000080
+#endif /* _NTDDK_ */
+
+#define KSEVENT_TYPE_ENABLE            0x00000001
+#define KSEVENT_TYPE_ONESHOT           0x00000002
+#define KSEVENT_TYPE_ENABLEBUFFERED    0x00000004
+#define KSEVENT_TYPE_SETSUPPORT                0x00000100
+#define KSEVENT_TYPE_BASICSUPPORT      0x00000200
+#define KSEVENT_TYPE_QUERYBUFFER       0x00000400
+
+#define KSEVENT_TYPE_TOPOLOGY          0x10000000
+
+typedef struct {
+  KSEVENT Event;
+  PKSEVENTDATA EventData;
+  PVOID Reserved;
+} KSQUERYBUFFER,*PKSQUERYBUFFER;
+
+typedef struct {
+  ULONG Size;
+  ULONG Flags;
+  __MINGW_EXTENSION union {
+    HANDLE ObjectHandle;
+    PVOID ObjectPointer;
+  };
+  PVOID Reserved;
+  KSEVENT Event;
+  KSEVENTDATA EventData;
+} KSRELATIVEEVENT;
+
+#define KSRELATIVEEVENT_FLAG_HANDLE    0x00000001
+#define KSRELATIVEEVENT_FLAG_POINTER   0x00000002
+
+typedef struct {
+  KSEVENTDATA EventData;
+  LONGLONG MarkTime;
+} KSEVENT_TIME_MARK,*PKSEVENT_TIME_MARK;
+
+typedef struct {
+  KSEVENTDATA EventData;
+  LONGLONG TimeBase;
+  LONGLONG Interval;
+} KSEVENT_TIME_INTERVAL,*PKSEVENT_TIME_INTERVAL;
+
+typedef struct {
+  LONGLONG TimeBase;
+  LONGLONG Interval;
+} KSINTERVAL,*PKSINTERVAL;
+
+#define STATIC_KSPROPSETID_General                                     \
+       0x1464EDA5L,0x6A8F,0x11D1,0x9A,0xA7,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("1464EDA5-6A8F-11D1-9AA7-00A0C9223196",KSPROPSETID_General);
+#define KSPROPSETID_General DEFINE_GUIDNAMED(KSPROPSETID_General)
+
+typedef enum {
+  KSPROPERTY_GENERAL_COMPONENTID
+} KSPROPERTY_GENERAL;
+
+typedef struct {
+  GUID Manufacturer;
+  GUID Product;
+  GUID Component;
+  GUID Name;
+  ULONG Version;
+  ULONG Revision;
+} KSCOMPONENTID,*PKSCOMPONENTID;
+
+#define DEFINE_KSPROPERTY_ITEM_GENERAL_COMPONENTID(Handler)            \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_GENERAL_COMPONENTID,         \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSCOMPONENTID),                  \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define STATIC_KSMETHODSETID_StreamIo  \
+       0x65D003CAL,0x1523,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("65D003CA-1523-11D2-B27A-00A0C9223196",KSMETHODSETID_StreamIo);
+#define KSMETHODSETID_StreamIo DEFINE_GUIDNAMED(KSMETHODSETID_StreamIo)
+
+typedef enum {
+  KSMETHOD_STREAMIO_READ,
+  KSMETHOD_STREAMIO_WRITE
+} KSMETHOD_STREAMIO;
+
+#define DEFINE_KSMETHOD_ITEM_STREAMIO_READ(Handler)                    \
+       DEFINE_KSMETHOD_ITEM(                                           \
+                               KSMETHOD_STREAMIO_READ,                 \
+                               KSMETHOD_TYPE_WRITE,                    \
+                               (Handler),                              \
+                               sizeof(KSMETHOD),                       \
+                               0,                                      \
+                               NULL)
+
+#define DEFINE_KSMETHOD_ITEM_STREAMIO_WRITE(Handler)                   \
+       DEFINE_KSMETHOD_ITEM(                                           \
+                               KSMETHOD_STREAMIO_WRITE,                \
+                               KSMETHOD_TYPE_READ,                     \
+                               (Handler),                              \
+                               sizeof(KSMETHOD),                       \
+                               0,                                      \
+                               NULL)
+
+#define STATIC_KSPROPSETID_MediaSeeking                                        \
+       0xEE904F0CL,0xD09B,0x11D0,0xAB,0xE9,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("EE904F0C-D09B-11D0-ABE9-00A0C9223196",KSPROPSETID_MediaSeeking);
+#define KSPROPSETID_MediaSeeking DEFINE_GUIDNAMED(KSPROPSETID_MediaSeeking)
+
+typedef enum {
+  KSPROPERTY_MEDIASEEKING_CAPABILITIES,
+  KSPROPERTY_MEDIASEEKING_FORMATS,
+  KSPROPERTY_MEDIASEEKING_TIMEFORMAT,
+  KSPROPERTY_MEDIASEEKING_POSITION,
+  KSPROPERTY_MEDIASEEKING_STOPPOSITION,
+  KSPROPERTY_MEDIASEEKING_POSITIONS,
+  KSPROPERTY_MEDIASEEKING_DURATION,
+  KSPROPERTY_MEDIASEEKING_AVAILABLE,
+  KSPROPERTY_MEDIASEEKING_PREROLL,
+  KSPROPERTY_MEDIASEEKING_CONVERTTIMEFORMAT
+} KSPROPERTY_MEDIASEEKING;
+
+typedef enum {
+  KS_SEEKING_NoPositioning,
+  KS_SEEKING_AbsolutePositioning,
+  KS_SEEKING_RelativePositioning,
+  KS_SEEKING_IncrementalPositioning,
+  KS_SEEKING_PositioningBitsMask = 0x3,
+  KS_SEEKING_SeekToKeyFrame,
+  KS_SEEKING_ReturnTime = 0x8
+} KS_SEEKING_FLAGS;
+
+typedef enum {
+  KS_SEEKING_CanSeekAbsolute = 0x1,
+  KS_SEEKING_CanSeekForwards = 0x2,
+  KS_SEEKING_CanSeekBackwards = 0x4,
+  KS_SEEKING_CanGetCurrentPos = 0x8,
+  KS_SEEKING_CanGetStopPos = 0x10,
+  KS_SEEKING_CanGetDuration = 0x20,
+  KS_SEEKING_CanPlayBackwards = 0x40
+} KS_SEEKING_CAPABILITIES;
+
+typedef struct {
+  LONGLONG Current;
+  LONGLONG Stop;
+  KS_SEEKING_FLAGS CurrentFlags;
+  KS_SEEKING_FLAGS StopFlags;
+} KSPROPERTY_POSITIONS,*PKSPROPERTY_POSITIONS;
+
+typedef struct {
+  LONGLONG Earliest;
+  LONGLONG Latest;
+} KSPROPERTY_MEDIAAVAILABLE,*PKSPROPERTY_MEDIAAVAILABLE;
+
+typedef struct {
+  KSPROPERTY Property;
+  GUID SourceFormat;
+  GUID TargetFormat;
+  LONGLONG Time;
+} KSP_TIMEFORMAT,*PKSP_TIMEFORMAT;
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_CAPABILITIES(Handler)      \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_CAPABILITIES,   \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KS_SEEKING_CAPABILITIES),        \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_FORMATS(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_FORMATS,        \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_TIMEFORMAT(GetHandler,SetHandler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_TIMEFORMAT,     \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(GUID),                           \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_POSITION(Handler)          \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_POSITION,       \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_STOPPOSITION(Handler)      \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_STOPPOSITION,   \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_POSITIONS(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_POSITIONS,      \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSPROPERTY_POSITIONS),           \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_DURATION(Handler)          \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_DURATION,       \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_AVAILABLE(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_AVAILABLE,      \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSPROPERTY_MEDIAAVAILABLE),      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_PREROLL(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_PREROLL,        \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_CONVERTTIMEFORMAT(Handler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_MEDIASEEKING_CONVERTTIMEFORMAT, \
+                               (Handler),                              \
+                               sizeof(KSP_TIMEFORMAT),                 \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define STATIC_KSPROPSETID_Topology                                    \
+       0x720D4AC0L,0x7533,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("720D4AC0-7533-11D0-A5D6-28DB04C10000",KSPROPSETID_Topology);
+#define KSPROPSETID_Topology DEFINE_GUIDNAMED(KSPROPSETID_Topology)
+
+typedef enum {
+  KSPROPERTY_TOPOLOGY_CATEGORIES,
+  KSPROPERTY_TOPOLOGY_NODES,
+  KSPROPERTY_TOPOLOGY_CONNECTIONS,
+  KSPROPERTY_TOPOLOGY_NAME
+} KSPROPERTY_TOPOLOGY;
+
+#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CATEGORIES(Handler)            \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_TOPOLOGY_CATEGORIES,         \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               NULL, NULL, 0,NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NODES(Handler)                 \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_TOPOLOGY_NODES,              \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CONNECTIONS(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_TOPOLOGY_CONNECTIONS,        \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NAME(Handler)                  \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_TOPOLOGY_NAME,               \
+                               (Handler),                              \
+                               sizeof(KSP_NODE),                       \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_TOPOLOGYSET(TopologySet,Handler)             \
+DEFINE_KSPROPERTY_TABLE(TopologySet) {                                 \
+       DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CATEGORIES(Handler),            \
+       DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NODES(Handler),                 \
+       DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CONNECTIONS(Handler),           \
+       DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NAME(Handler)                   \
+}
+
+#define STATIC_KSCATEGORY_BRIDGE                                       \
+       0x085AFF00L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("085AFF00-62CE-11CF-A5D6-28DB04C10000",KSCATEGORY_BRIDGE);
+#define KSCATEGORY_BRIDGE DEFINE_GUIDNAMED(KSCATEGORY_BRIDGE)
+
+#define STATIC_KSCATEGORY_CAPTURE                                      \
+       0x65E8773DL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("65E8773D-8F56-11D0-A3B9-00A0C9223196",KSCATEGORY_CAPTURE);
+#define KSCATEGORY_CAPTURE DEFINE_GUIDNAMED(KSCATEGORY_CAPTURE)
+
+#define STATIC_KSCATEGORY_RENDER                                       \
+       0x65E8773EL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("65E8773E-8F56-11D0-A3B9-00A0C9223196",KSCATEGORY_RENDER);
+#define KSCATEGORY_RENDER DEFINE_GUIDNAMED(KSCATEGORY_RENDER)
+
+#define STATIC_KSCATEGORY_MIXER                                                \
+       0xAD809C00L,0x7B88,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("AD809C00-7B88-11D0-A5D6-28DB04C10000",KSCATEGORY_MIXER);
+#define KSCATEGORY_MIXER DEFINE_GUIDNAMED(KSCATEGORY_MIXER)
+
+#define STATIC_KSCATEGORY_SPLITTER                                     \
+       0x0A4252A0L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("0A4252A0-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_SPLITTER);
+#define KSCATEGORY_SPLITTER DEFINE_GUIDNAMED(KSCATEGORY_SPLITTER)
+
+#define STATIC_KSCATEGORY_DATACOMPRESSOR                               \
+       0x1E84C900L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("1E84C900-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATACOMPRESSOR);
+#define KSCATEGORY_DATACOMPRESSOR DEFINE_GUIDNAMED(KSCATEGORY_DATACOMPRESSOR)
+
+#define STATIC_KSCATEGORY_DATADECOMPRESSOR                             \
+       0x2721AE20L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("2721AE20-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATADECOMPRESSOR);
+#define KSCATEGORY_DATADECOMPRESSOR DEFINE_GUIDNAMED(KSCATEGORY_DATADECOMPRESSOR)
+
+#define STATIC_KSCATEGORY_DATATRANSFORM                                        \
+       0x2EB07EA0L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("2EB07EA0-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATATRANSFORM);
+#define KSCATEGORY_DATATRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_DATATRANSFORM)
+
+#define STATIC_KSCATEGORY_COMMUNICATIONSTRANSFORM                      \
+       0xCF1DDA2CL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("CF1DDA2C-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_COMMUNICATIONSTRANSFORM);
+#define KSCATEGORY_COMMUNICATIONSTRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_COMMUNICATIONSTRANSFORM)
+
+#define STATIC_KSCATEGORY_INTERFACETRANSFORM                           \
+       0xCF1DDA2DL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("CF1DDA2D-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_INTERFACETRANSFORM);
+#define KSCATEGORY_INTERFACETRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_INTERFACETRANSFORM)
+
+#define STATIC_KSCATEGORY_MEDIUMTRANSFORM                              \
+       0xCF1DDA2EL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("CF1DDA2E-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_MEDIUMTRANSFORM);
+#define KSCATEGORY_MEDIUMTRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_MEDIUMTRANSFORM)
+
+#define STATIC_KSCATEGORY_FILESYSTEM                                   \
+       0x760FED5EL,0x9357,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("760FED5E-9357-11D0-A3CC-00A0C9223196",KSCATEGORY_FILESYSTEM);
+#define KSCATEGORY_FILESYSTEM DEFINE_GUIDNAMED(KSCATEGORY_FILESYSTEM)
+
+#define STATIC_KSCATEGORY_CLOCK                                                \
+       0x53172480L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("53172480-4791-11D0-A5D6-28DB04C10000",KSCATEGORY_CLOCK);
+#define KSCATEGORY_CLOCK DEFINE_GUIDNAMED(KSCATEGORY_CLOCK)
+
+#define STATIC_KSCATEGORY_PROXY                                                \
+       0x97EBAACAL,0x95BD,0x11D0,0xA3,0xEA,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("97EBAACA-95BD-11D0-A3EA-00A0C9223196",KSCATEGORY_PROXY);
+#define KSCATEGORY_PROXY DEFINE_GUIDNAMED(KSCATEGORY_PROXY)
+
+#define STATIC_KSCATEGORY_QUALITY                                      \
+       0x97EBAACBL,0x95BD,0x11D0,0xA3,0xEA,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("97EBAACB-95BD-11D0-A3EA-00A0C9223196",KSCATEGORY_QUALITY);
+#define KSCATEGORY_QUALITY DEFINE_GUIDNAMED(KSCATEGORY_QUALITY)
+
+typedef struct {
+  ULONG FromNode;
+  ULONG FromNodePin;
+  ULONG ToNode;
+  ULONG ToNodePin;
+} KSTOPOLOGY_CONNECTION,*PKSTOPOLOGY_CONNECTION;
+
+typedef struct {
+  ULONG CategoriesCount;
+  const GUID *Categories;
+  ULONG TopologyNodesCount;
+  const GUID *TopologyNodes;
+  ULONG TopologyConnectionsCount;
+  const KSTOPOLOGY_CONNECTION *TopologyConnections;
+  const GUID *TopologyNodesNames;
+  ULONG Reserved;
+} KSTOPOLOGY,*PKSTOPOLOGY;
+
+#define KSFILTER_NODE  ((ULONG)-1)
+#define KSALL_NODES    ((ULONG)-1)
+
+typedef struct {
+  ULONG CreateFlags;
+  ULONG Node;
+} KSNODE_CREATE,*PKSNODE_CREATE;
+
+#define STATIC_KSTIME_FORMAT_NONE      STATIC_GUID_NULL
+#define KSTIME_FORMAT_NONE             GUID_NULL
+
+#define STATIC_KSTIME_FORMAT_FRAME                                     \
+       0x7b785570L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
+DEFINE_GUIDSTRUCT("7b785570-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_FRAME);
+#define KSTIME_FORMAT_FRAME DEFINE_GUIDNAMED(KSTIME_FORMAT_FRAME)
+
+#define STATIC_KSTIME_FORMAT_BYTE                                      \
+       0x7b785571L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
+DEFINE_GUIDSTRUCT("7b785571-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_BYTE);
+#define KSTIME_FORMAT_BYTE DEFINE_GUIDNAMED(KSTIME_FORMAT_BYTE)
+
+#define STATIC_KSTIME_FORMAT_SAMPLE                                    \
+       0x7b785572L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
+DEFINE_GUIDSTRUCT("7b785572-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_SAMPLE);
+#define KSTIME_FORMAT_SAMPLE DEFINE_GUIDNAMED(KSTIME_FORMAT_SAMPLE)
+
+#define STATIC_KSTIME_FORMAT_FIELD                                     \
+       0x7b785573L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
+DEFINE_GUIDSTRUCT("7b785573-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_FIELD);
+#define KSTIME_FORMAT_FIELD DEFINE_GUIDNAMED(KSTIME_FORMAT_FIELD)
+
+#define STATIC_KSTIME_FORMAT_MEDIA_TIME                                        \
+       0x7b785574L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
+DEFINE_GUIDSTRUCT("7b785574-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_MEDIA_TIME);
+#define KSTIME_FORMAT_MEDIA_TIME DEFINE_GUIDNAMED(KSTIME_FORMAT_MEDIA_TIME)
+
+typedef KSIDENTIFIER KSPIN_INTERFACE,*PKSPIN_INTERFACE;
+
+#define STATIC_KSINTERFACESETID_Standard                               \
+       0x1A8766A0L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("1A8766A0-62CE-11CF-A5D6-28DB04C10000",KSINTERFACESETID_Standard);
+#define KSINTERFACESETID_Standard DEFINE_GUIDNAMED(KSINTERFACESETID_Standard)
+
+typedef enum {
+  KSINTERFACE_STANDARD_STREAMING,
+  KSINTERFACE_STANDARD_LOOPED_STREAMING,
+  KSINTERFACE_STANDARD_CONTROL
+} KSINTERFACE_STANDARD;
+
+#define STATIC_KSINTERFACESETID_FileIo                                 \
+       0x8C6F932CL,0xE771,0x11D0,0xB8,0xFF,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("8C6F932C-E771-11D0-B8FF-00A0C9223196",KSINTERFACESETID_FileIo);
+#define KSINTERFACESETID_FileIo DEFINE_GUIDNAMED(KSINTERFACESETID_FileIo)
+
+typedef enum {
+  KSINTERFACE_FILEIO_STREAMING
+} KSINTERFACE_FILEIO;
+
+#define KSMEDIUM_TYPE_ANYINSTANCE              0
+
+#define STATIC_KSMEDIUMSETID_Standard                                  \
+       0x4747B320L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("4747B320-62CE-11CF-A5D6-28DB04C10000",KSMEDIUMSETID_Standard);
+#define KSMEDIUMSETID_Standard DEFINE_GUIDNAMED(KSMEDIUMSETID_Standard)
+
+#define KSMEDIUM_STANDARD_DEVIO KSMEDIUM_TYPE_ANYINSTANCE
+
+#define STATIC_KSPROPSETID_Pin                                         \
+       0x8C134960L,0x51AD,0x11CF,0x87,0x8A,0x94,0xF8,0x01,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("8C134960-51AD-11CF-878A-94F801C10000",KSPROPSETID_Pin);
+#define KSPROPSETID_Pin DEFINE_GUIDNAMED(KSPROPSETID_Pin)
+
+typedef enum {
+  KSPROPERTY_PIN_CINSTANCES,
+  KSPROPERTY_PIN_CTYPES,
+  KSPROPERTY_PIN_DATAFLOW,
+  KSPROPERTY_PIN_DATARANGES,
+  KSPROPERTY_PIN_DATAINTERSECTION,
+  KSPROPERTY_PIN_INTERFACES,
+  KSPROPERTY_PIN_MEDIUMS,
+  KSPROPERTY_PIN_COMMUNICATION,
+  KSPROPERTY_PIN_GLOBALCINSTANCES,
+  KSPROPERTY_PIN_NECESSARYINSTANCES,
+  KSPROPERTY_PIN_PHYSICALCONNECTION,
+  KSPROPERTY_PIN_CATEGORY,
+  KSPROPERTY_PIN_NAME,
+  KSPROPERTY_PIN_CONSTRAINEDDATARANGES,
+  KSPROPERTY_PIN_PROPOSEDATAFORMAT
+} KSPROPERTY_PIN;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG PinId;
+  ULONG Reserved;
+} KSP_PIN,*PKSP_PIN;
+
+#define KSINSTANCE_INDETERMINATE       ((ULONG)-1)
+
+typedef struct {
+  ULONG PossibleCount;
+  ULONG CurrentCount;
+} KSPIN_CINSTANCES,*PKSPIN_CINSTANCES;
+
+typedef enum {
+  KSPIN_DATAFLOW_IN = 1,
+  KSPIN_DATAFLOW_OUT
+} KSPIN_DATAFLOW,*PKSPIN_DATAFLOW;
+
+#define KSDATAFORMAT_BIT_TEMPORAL_COMPRESSION  0
+#define KSDATAFORMAT_TEMPORAL_COMPRESSION      (1 << KSDATAFORMAT_BIT_TEMPORAL_COMPRESSION)
+#define KSDATAFORMAT_BIT_ATTRIBUTES            1
+#define KSDATAFORMAT_ATTRIBUTES                        (1 << KSDATAFORMAT_BIT_ATTRIBUTES)
+
+#define KSDATARANGE_BIT_ATTRIBUTES             1
+#define KSDATARANGE_ATTRIBUTES                 (1 << KSDATARANGE_BIT_ATTRIBUTES)
+#define KSDATARANGE_BIT_REQUIRED_ATTRIBUTES    2
+#define KSDATARANGE_REQUIRED_ATTRIBUTES                (1 << KSDATARANGE_BIT_REQUIRED_ATTRIBUTES)
+
+typedef union {
+  __MINGW_EXTENSION struct {
+    ULONG FormatSize;
+    ULONG Flags;
+    ULONG SampleSize;
+    ULONG Reserved;
+    GUID MajorFormat;
+    GUID SubFormat;
+    GUID Specifier;
+  };
+  LONGLONG Alignment;
+} KSDATAFORMAT,*PKSDATAFORMAT,KSDATARANGE,*PKSDATARANGE;
+
+#define KSATTRIBUTE_REQUIRED           0x00000001
+
+typedef struct {
+  ULONG Size;
+  ULONG Flags;
+  GUID Attribute;
+} KSATTRIBUTE,*PKSATTRIBUTE;
+
+#if defined(_NTDDK_)
+typedef struct {
+  ULONG Count;
+  PKSATTRIBUTE *Attributes;
+} KSATTRIBUTE_LIST,*PKSATTRIBUTE_LIST;
+#endif /* _NTDDK_ */
+
+typedef enum {
+  KSPIN_COMMUNICATION_NONE,
+  KSPIN_COMMUNICATION_SINK,
+  KSPIN_COMMUNICATION_SOURCE,
+  KSPIN_COMMUNICATION_BOTH,
+  KSPIN_COMMUNICATION_BRIDGE
+} KSPIN_COMMUNICATION,*PKSPIN_COMMUNICATION;
+
+typedef KSIDENTIFIER KSPIN_MEDIUM,*PKSPIN_MEDIUM;
+
+typedef struct {
+  KSPIN_INTERFACE Interface;
+  KSPIN_MEDIUM Medium;
+  ULONG PinId;
+  HANDLE PinToHandle;
+  KSPRIORITY Priority;
+} KSPIN_CONNECT,*PKSPIN_CONNECT;
+
+typedef struct {
+  ULONG Size;
+  ULONG Pin;
+  WCHAR SymbolicLinkName[1];
+} KSPIN_PHYSICALCONNECTION,*PKSPIN_PHYSICALCONNECTION;
+
+#if defined(_NTDDK_)
+typedef NTSTATUS (*PFNKSINTERSECTHANDLER) ( PIRP Irp, PKSP_PIN Pin,
+                                           PKSDATARANGE DataRange,
+                                           PVOID Data);
+typedef NTSTATUS (*PFNKSINTERSECTHANDLEREX)(PVOID Context, PIRP Irp,
+                                           PKSP_PIN Pin,
+                                           PKSDATARANGE DataRange,
+                                           PKSDATARANGE MatchingDataRange,
+                                           ULONG DataBufferSize,
+                                           PVOID Data,
+                                           PULONG DataSize);
+#endif /* _NTDDK_ */
+
+#define DEFINE_KSPIN_INTERFACE_TABLE(tablename)                                \
+       const KSPIN_INTERFACE tablename[] =
+
+#define DEFINE_KSPIN_INTERFACE_ITEM(guid,_interFace)                   \
+       {                                                               \
+               STATICGUIDOF(guid),                                     \
+               (_interFace),                                           \
+               0                                                       \
+       }
+
+#define DEFINE_KSPIN_MEDIUM_TABLE(tablename)                           \
+       const KSPIN_MEDIUM tablename[] =
+
+#define DEFINE_KSPIN_MEDIUM_ITEM(guid,medium)                          \
+               DEFINE_KSPIN_INTERFACE_ITEM(guid,medium)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(Handler)                 \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_CINSTANCES,              \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(KSPIN_CINSTANCES),               \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(Handler)                     \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_CTYPES,                  \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(ULONG),                          \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(Handler)                   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_DATAFLOW,                \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(KSPIN_DATAFLOW),                 \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(Handler)                 \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_DATARANGES,              \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_DATAINTERSECTION,        \
+                               (Handler),                              \
+                               sizeof(KSP_PIN) + sizeof(KSMULTIPLE_ITEM),\
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(Handler)                 \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_INTERFACES,              \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(Handler)                    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_MEDIUMS,                 \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(Handler)              \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_COMMUNICATION,           \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(KSPIN_COMMUNICATION),            \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_GLOBALCINSTANCES(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_GLOBALCINSTANCES,        \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(KSPIN_CINSTANCES),               \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_NECESSARYINSTANCES(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_NECESSARYINSTANCES,      \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(ULONG),                          \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_PHYSICALCONNECTION(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_PHYSICALCONNECTION,      \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(Handler)                   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_CATEGORY,                \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(GUID),                           \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_NAME(Handler)                       \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_NAME,                    \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_CONSTRAINEDDATARANGES(Handler)      \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_CONSTRAINEDDATARANGES,   \
+                               (Handler),                              \
+                               sizeof(KSP_PIN),                        \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_PIN_PROPOSEDATAFORMAT(Handler)          \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_PIN_PROPOSEDATAFORMAT,       \
+                               NULL,                                   \
+                               sizeof(KSP_PIN),                        \
+                               sizeof(KSDATAFORMAT),                   \
+                               (Handler), NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_PINSET(PinSet,PropGeneral,PropInstances,PropIntersection) \
+DEFINE_KSPROPERTY_TABLE(PinSet) {                                      \
+       DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(PropInstances),           \
+       DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(PropGeneral),                 \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(PropGeneral),               \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(PropGeneral),             \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(PropIntersection),  \
+       DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(PropGeneral),             \
+       DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(PropGeneral),                \
+       DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(PropGeneral),          \
+       DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(PropGeneral),               \
+       DEFINE_KSPROPERTY_ITEM_PIN_NAME(PropGeneral)                    \
+}
+
+#define DEFINE_KSPROPERTY_PINSETCONSTRAINED(PinSet,PropGeneral,PropInstances,PropIntersection) \
+DEFINE_KSPROPERTY_TABLE(PinSet) {                                      \
+       DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(PropInstances),           \
+       DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(PropGeneral),                 \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(PropGeneral),               \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(PropGeneral),             \
+       DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(PropIntersection),  \
+       DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(PropGeneral),             \
+       DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(PropGeneral),                \
+       DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(PropGeneral),          \
+       DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(PropGeneral),               \
+       DEFINE_KSPROPERTY_ITEM_PIN_NAME(PropGeneral),                   \
+       DEFINE_KSPROPERTY_ITEM_PIN_CONSTRAINEDDATARANGES(PropGeneral)   \
+}
+
+#define STATIC_KSNAME_Filter                                           \
+       0x9b365890L,0x165f,0x11d0,0xa1,0x95,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("9b365890-165f-11d0-a195-0020afd156e4",KSNAME_Filter);
+#define KSNAME_Filter DEFINE_GUIDNAMED(KSNAME_Filter)
+
+#define KSSTRING_Filter                L"{9B365890-165F-11D0-A195-0020AFD156E4}"
+
+#define STATIC_KSNAME_Pin                                              \
+       0x146F1A80L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("146F1A80-4791-11D0-A5D6-28DB04C10000",KSNAME_Pin);
+#define KSNAME_Pin DEFINE_GUIDNAMED(KSNAME_Pin)
+
+#define KSSTRING_Pin           L"{146F1A80-4791-11D0-A5D6-28DB04C10000}"
+
+#define STATIC_KSNAME_Clock                                            \
+       0x53172480L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("53172480-4791-11D0-A5D6-28DB04C10000",KSNAME_Clock);
+#define KSNAME_Clock DEFINE_GUIDNAMED(KSNAME_Clock)
+
+#define KSSTRING_Clock         L"{53172480-4791-11D0-A5D6-28DB04C10000}"
+
+#define STATIC_KSNAME_Allocator                                                \
+       0x642F5D00L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("642F5D00-4791-11D0-A5D6-28DB04C10000",KSNAME_Allocator);
+#define KSNAME_Allocator DEFINE_GUIDNAMED(KSNAME_Allocator)
+
+#define KSSTRING_Allocator     L"{642F5D00-4791-11D0-A5D6-28DB04C10000}"
+
+#define KSSTRING_AllocatorEx   L"{091BB63B-603F-11D1-B067-00A0C9062802}"
+
+#define STATIC_KSNAME_TopologyNode                                     \
+       0x0621061AL,0xEE75,0x11D0,0xB9,0x15,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("0621061A-EE75-11D0-B915-00A0C9223196",KSNAME_TopologyNode);
+#define KSNAME_TopologyNode DEFINE_GUIDNAMED(KSNAME_TopologyNode)
+
+#define KSSTRING_TopologyNode  L"{0621061A-EE75-11D0-B915-00A0C9223196}"
+
+#if defined(_NTDDK_)
+typedef struct {
+  ULONG InterfacesCount;
+  const KSPIN_INTERFACE *Interfaces;
+  ULONG MediumsCount;
+  const KSPIN_MEDIUM *Mediums;
+  ULONG DataRangesCount;
+  const PKSDATARANGE *DataRanges;
+  KSPIN_DATAFLOW DataFlow;
+  KSPIN_COMMUNICATION Communication;
+  const GUID *Category;
+  const GUID *Name;
+  __MINGW_EXTENSION union {
+    LONGLONG Reserved;
+    __MINGW_EXTENSION struct {
+      ULONG ConstrainedDataRangesCount;
+      PKSDATARANGE *ConstrainedDataRanges;
+    };
+  };
+} KSPIN_DESCRIPTOR, *PKSPIN_DESCRIPTOR;
+typedef const KSPIN_DESCRIPTOR *PCKSPIN_DESCRIPTOR;
+
+#define DEFINE_KSPIN_DESCRIPTOR_TABLE(tablename)                       \
+       const KSPIN_DESCRIPTOR tablename[] =
+
+#define DEFINE_KSPIN_DESCRIPTOR_ITEM(InterfacesCount,Interfaces,MediumsCount, Mediums,DataRangesCount,DataRanges,DataFlow,Communication)\
+{                                                                      \
+               InterfacesCount, Interfaces, MediumsCount, Mediums,     \
+               DataRangesCount, DataRanges, DataFlow, Communication,   \
+               NULL, NULL, 0                                           \
+}
+
+#define DEFINE_KSPIN_DESCRIPTOR_ITEMEX(InterfacesCount,Interfaces,MediumsCount,Mediums,DataRangesCount,DataRanges,DataFlow,Communication,Category,Name)\
+{                                                                      \
+               InterfacesCount, Interfaces, MediumsCount, Mediums,     \
+               DataRangesCount, DataRanges, DataFlow, Communication,   \
+               Category, Name, 0                                       \
+}
+#endif /* _NTDDK_ */
+
+#define STATIC_KSDATAFORMAT_TYPE_WILDCARD      STATIC_GUID_NULL
+#define KSDATAFORMAT_TYPE_WILDCARD             GUID_NULL
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_WILDCARD   STATIC_GUID_NULL
+#define KSDATAFORMAT_SUBTYPE_WILDCARD          GUID_NULL
+
+#define STATIC_KSDATAFORMAT_TYPE_STREAM                                        \
+       0xE436EB83L,0x524F,0x11CE,0x9F,0x53,0x00,0x20,0xAF,0x0B,0xA7,0x70
+DEFINE_GUIDSTRUCT("E436EB83-524F-11CE-9F53-0020AF0BA770",KSDATAFORMAT_TYPE_STREAM);
+#define KSDATAFORMAT_TYPE_STREAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STREAM)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_NONE                               \
+       0xE436EB8EL,0x524F,0x11CE,0x9F,0x53,0x00,0x20,0xAF,0x0B,0xA7,0x70
+DEFINE_GUIDSTRUCT("E436EB8E-524F-11CE-9F53-0020AF0BA770",KSDATAFORMAT_SUBTYPE_NONE);
+#define KSDATAFORMAT_SUBTYPE_NONE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NONE)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_WILDCARD STATIC_GUID_NULL
+#define KSDATAFORMAT_SPECIFIER_WILDCARD                GUID_NULL
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_FILENAME                         \
+       0xAA797B40L,0xE974,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("AA797B40-E974-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SPECIFIER_FILENAME);
+#define KSDATAFORMAT_SPECIFIER_FILENAME DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_FILENAME)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_FILEHANDLE                       \
+       0x65E8773CL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("65E8773C-8F56-11D0-A3B9-00A0C9223196",KSDATAFORMAT_SPECIFIER_FILEHANDLE);
+#define KSDATAFORMAT_SPECIFIER_FILEHANDLE DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_FILEHANDLE)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_NONE                             \
+       0x0F6417D6L,0xC318,0x11D0,0xA4,0x3F,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("0F6417D6-C318-11D0-A43F-00A0C9223196",KSDATAFORMAT_SPECIFIER_NONE);
+#define KSDATAFORMAT_SPECIFIER_NONE DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_NONE)
+
+#define STATIC_KSPROPSETID_Quality                                     \
+       0xD16AD380L,0xAC1A,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("D16AD380-AC1A-11CF-A5D6-28DB04C10000",KSPROPSETID_Quality);
+#define KSPROPSETID_Quality DEFINE_GUIDNAMED(KSPROPSETID_Quality)
+
+typedef enum {
+  KSPROPERTY_QUALITY_REPORT,
+  KSPROPERTY_QUALITY_ERROR
+} KSPROPERTY_QUALITY;
+
+#define DEFINE_KSPROPERTY_ITEM_QUALITY_REPORT(GetHandler,SetHandler)   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_QUALITY_REPORT,              \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSQUALITY),                      \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_QUALITY_ERROR(GetHandler,SetHandler)    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_QUALITY_ERROR,               \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSERROR),                        \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define STATIC_KSPROPSETID_Connection                                  \
+       0x1D58C920L,0xAC9B,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("1D58C920-AC9B-11CF-A5D6-28DB04C10000",KSPROPSETID_Connection);
+#define KSPROPSETID_Connection DEFINE_GUIDNAMED(KSPROPSETID_Connection)
+
+typedef enum {
+  KSPROPERTY_CONNECTION_STATE,
+  KSPROPERTY_CONNECTION_PRIORITY,
+  KSPROPERTY_CONNECTION_DATAFORMAT,
+  KSPROPERTY_CONNECTION_ALLOCATORFRAMING,
+  KSPROPERTY_CONNECTION_PROPOSEDATAFORMAT,
+  KSPROPERTY_CONNECTION_ACQUIREORDERING,
+  KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,
+  KSPROPERTY_CONNECTION_STARTAT
+} KSPROPERTY_CONNECTION;
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_STATE(GetHandler,SetHandler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_STATE,            \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSSTATE),                        \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_PRIORITY(GetHandler,SetHandler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_PRIORITY,         \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSPRIORITY),                     \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_DATAFORMAT(GetHandler,SetHandler)\
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_DATAFORMAT,       \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ALLOCATORFRAMING(Handler)    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_ALLOCATORFRAMING, \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSALLOCATOR_FRAMING),            \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ALLOCATORFRAMING_EX(Handler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,\
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_PROPOSEDATAFORMAT(Handler)   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_PROPOSEDATAFORMAT,\
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSDATAFORMAT),                   \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ACQUIREORDERING(Handler)     \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_ACQUIREORDERING,  \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(int),                            \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CONNECTION_STARTAT(Handler)             \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CONNECTION_STARTAT,          \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSRELATIVEEVENT),                \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define KSALLOCATOR_REQUIREMENTF_INPLACE_MODIFIER      0x00000001
+#define KSALLOCATOR_REQUIREMENTF_SYSTEM_MEMORY         0x00000002
+#define KSALLOCATOR_REQUIREMENTF_FRAME_INTEGRITY       0x00000004
+#define KSALLOCATOR_REQUIREMENTF_MUST_ALLOCATE         0x00000008
+#define KSALLOCATOR_REQUIREMENTF_PREFERENCES_ONLY      0x80000000
+
+#define KSALLOCATOR_OPTIONF_COMPATIBLE                 0x00000001
+#define KSALLOCATOR_OPTIONF_SYSTEM_MEMORY              0x00000002
+#define KSALLOCATOR_OPTIONF_VALID                      0x00000003
+
+#define KSALLOCATOR_FLAG_PARTIAL_READ_SUPPORT          0x00000010
+#define KSALLOCATOR_FLAG_DEVICE_SPECIFIC               0x00000020
+#define KSALLOCATOR_FLAG_CAN_ALLOCATE                  0x00000040
+#define KSALLOCATOR_FLAG_INSIST_ON_FRAMESIZE_RATIO     0x00000080
+#define KSALLOCATOR_FLAG_NO_FRAME_INTEGRITY            0x00000100
+#define KSALLOCATOR_FLAG_MULTIPLE_OUTPUT               0x00000200
+#define KSALLOCATOR_FLAG_CYCLE                         0x00000400
+#define KSALLOCATOR_FLAG_ALLOCATOR_EXISTS              0x00000800
+#define KSALLOCATOR_FLAG_INDEPENDENT_RANGES            0x00001000
+#define KSALLOCATOR_FLAG_ATTENTION_STEPPING            0x00002000
+
+typedef struct {
+  __MINGW_EXTENSION union {
+    ULONG OptionsFlags;
+    ULONG RequirementsFlags;
+  };
+#if defined(_NTDDK_)
+  POOL_TYPE PoolType;
+#else
+  ULONG PoolType;
+#endif /* _NTDDK_ */
+  ULONG Frames;
+  ULONG FrameSize;
+  ULONG FileAlignment;
+  ULONG Reserved;
+} KSALLOCATOR_FRAMING,*PKSALLOCATOR_FRAMING;
+
+#if defined(_NTDDK_)
+typedef PVOID (*PFNKSDEFAULTALLOCATE)(PVOID Context);
+typedef VOID (*PFNKSDEFAULTFREE)(PVOID Context, PVOID Buffer);
+typedef NTSTATUS (*PFNKSINITIALIZEALLOCATOR)(PVOID InitialContext,
+                                       PKSALLOCATOR_FRAMING AllocatorFraming,
+                                       PVOID* Context);
+typedef VOID (*PFNKSDELETEALLOCATOR) (PVOID Context);
+#endif /* _NTDDK_ */
+
+typedef struct {
+  ULONG MinFrameSize;
+  ULONG MaxFrameSize;
+  ULONG Stepping;
+} KS_FRAMING_RANGE,*PKS_FRAMING_RANGE;
+
+typedef struct {
+  KS_FRAMING_RANGE Range;
+  ULONG InPlaceWeight;
+  ULONG NotInPlaceWeight;
+} KS_FRAMING_RANGE_WEIGHTED,*PKS_FRAMING_RANGE_WEIGHTED;
+
+typedef struct {
+  ULONG RatioNumerator;
+  ULONG RatioDenominator;
+  ULONG RatioConstantMargin;
+} KS_COMPRESSION,*PKS_COMPRESSION;
+
+typedef struct {
+  GUID MemoryType;
+  GUID BusType;
+  ULONG MemoryFlags;
+  ULONG BusFlags;
+  ULONG Flags;
+  ULONG Frames;
+  ULONG FileAlignment;
+  ULONG MemoryTypeWeight;
+  KS_FRAMING_RANGE PhysicalRange;
+  KS_FRAMING_RANGE_WEIGHTED FramingRange;
+} KS_FRAMING_ITEM,*PKS_FRAMING_ITEM;
+
+typedef struct {
+  ULONG CountItems;
+  ULONG PinFlags;
+  KS_COMPRESSION OutputCompression;
+  ULONG PinWeight;
+  KS_FRAMING_ITEM FramingItem[1];
+} KSALLOCATOR_FRAMING_EX,*PKSALLOCATOR_FRAMING_EX;
+
+#define KSMEMORY_TYPE_WILDCARD         GUID_NULL
+#define STATIC_KSMEMORY_TYPE_WILDCARD  STATIC_GUID_NULL
+
+#define KSMEMORY_TYPE_DONT_CARE                GUID_NULL
+#define STATIC_KSMEMORY_TYPE_DONT_CARE STATIC_GUID_NULL
+
+#define KS_TYPE_DONT_CARE              GUID_NULL
+#define STATIC_KS_TYPE_DONT_CARE       STATIC_GUID_NULL
+
+#define STATIC_KSMEMORY_TYPE_SYSTEM                                    \
+       0x091bb638L,0x603f,0x11d1,0xb0,0x67,0x00,0xa0,0xc9,0x06,0x28,0x02
+DEFINE_GUIDSTRUCT("091bb638-603f-11d1-b067-00a0c9062802",KSMEMORY_TYPE_SYSTEM);
+#define KSMEMORY_TYPE_SYSTEM DEFINE_GUIDNAMED(KSMEMORY_TYPE_SYSTEM)
+
+#define STATIC_KSMEMORY_TYPE_USER                                      \
+       0x8cb0fc28L,0x7893,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
+DEFINE_GUIDSTRUCT("8cb0fc28-7893-11d1-b069-00a0c9062802",KSMEMORY_TYPE_USER);
+#define KSMEMORY_TYPE_USER DEFINE_GUIDNAMED(KSMEMORY_TYPE_USER)
+
+#define STATIC_KSMEMORY_TYPE_KERNEL_PAGED                              \
+       0xd833f8f8L,0x7894,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
+DEFINE_GUIDSTRUCT("d833f8f8-7894-11d1-b069-00a0c9062802",KSMEMORY_TYPE_KERNEL_PAGED);
+#define KSMEMORY_TYPE_KERNEL_PAGED DEFINE_GUIDNAMED(KSMEMORY_TYPE_KERNEL_PAGED)
+
+#define STATIC_KSMEMORY_TYPE_KERNEL_NONPAGED                           \
+       0x4a6d5fc4L,0x7895,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
+DEFINE_GUIDSTRUCT("4a6d5fc4-7895-11d1-b069-00a0c9062802",KSMEMORY_TYPE_KERNEL_NONPAGED);
+#define KSMEMORY_TYPE_KERNEL_NONPAGED DEFINE_GUIDNAMED(KSMEMORY_TYPE_KERNEL_NONPAGED)
+
+#define STATIC_KSMEMORY_TYPE_DEVICE_UNKNOWN                            \
+       0x091bb639L,0x603f,0x11d1,0xb0,0x67,0x00,0xa0,0xc9,0x06,0x28,0x02
+DEFINE_GUIDSTRUCT("091bb639-603f-11d1-b067-00a0c9062802",KSMEMORY_TYPE_DEVICE_UNKNOWN);
+#define KSMEMORY_TYPE_DEVICE_UNKNOWN DEFINE_GUIDNAMED(KSMEMORY_TYPE_DEVICE_UNKNOWN)
+
+#define DECLARE_SIMPLE_FRAMING_EX(FramingExName,MemoryType,Flags,Frames,Alignment,MinFrameSize,MaxFrameSize) \
+const KSALLOCATOR_FRAMING_EX FramingExName =                           \
+{                                                                      \
+       1,                                                              \
+       0,                                                              \
+       {                                                               \
+               1,                                                      \
+               1,                                                      \
+               0                                                       \
+       },                                                              \
+       0,                                                              \
+       {                                                               \
+               {                                                       \
+                       MemoryType,                                     \
+                       STATIC_KS_TYPE_DONT_CARE,                       \
+                       0,                                              \
+                       0,                                              \
+                       Flags,                                          \
+                       Frames,                                         \
+                       Alignment,                                      \
+                       0,                                              \
+                       {                                               \
+                               0,                                      \
+                               (ULONG)-1,                              \
+                               1                                       \
+                       },                                              \
+                       {                                               \
+                               {                                       \
+                                       MinFrameSize,                   \
+                                       MaxFrameSize,                   \
+                                       1                               \
+                               },                                      \
+                               0,                                      \
+                               0                                       \
+                       }                                               \
+               }                                                       \
+       }                                                               \
+}
+
+#define SetDefaultKsCompression(KsCompressionPointer)                  \
+{                                                                      \
+       KsCompressionPointer->RatioNumerator = 1;                       \
+       KsCompressionPointer->RatioDenominator = 1;                     \
+       KsCompressionPointer->RatioConstantMargin = 0;                  \
+}
+
+#define SetDontCareKsFramingRange(KsFramingRangePointer)               \
+{                                                                      \
+       KsFramingRangePointer->MinFrameSize = 0;                        \
+       KsFramingRangePointer->MaxFrameSize = (ULONG) -1;               \
+       KsFramingRangePointer->Stepping = 1;                            \
+}
+
+#define SetKsFramingRange(KsFramingRangePointer,P_MinFrameSize,P_MaxFrameSize) \
+{                                                                      \
+       KsFramingRangePointer->MinFrameSize = P_MinFrameSize;           \
+       KsFramingRangePointer->MaxFrameSize = P_MaxFrameSize;           \
+       KsFramingRangePointer->Stepping = 1;                            \
+}
+
+#define SetKsFramingRangeWeighted(KsFramingRangeWeightedPointer,P_MinFrameSize,P_MaxFrameSize) \
+{                                                                      \
+       KS_FRAMING_RANGE *KsFramingRange =                              \
+                               &KsFramingRangeWeightedPointer->Range;  \
+       SetKsFramingRange(KsFramingRange,P_MinFrameSize,P_MaxFrameSize);\
+       KsFramingRangeWeightedPointer->InPlaceWeight = 0;               \
+       KsFramingRangeWeightedPointer->NotInPlaceWeight = 0;            \
+}
+
+#define INITIALIZE_SIMPLE_FRAMING_EX(FramingExPointer,P_MemoryType,P_Flags,P_Frames,P_Alignment,P_MinFrameSize,P_MaxFrameSize) \
+{                                                                      \
+       KS_COMPRESSION *KsCompression =                                 \
+                       &FramingExPointer->OutputCompression;           \
+       KS_FRAMING_RANGE *KsFramingRange =                              \
+                       &FramingExPointer->FramingItem[0].PhysicalRange;\
+       KS_FRAMING_RANGE_WEIGHTED *KsFramingRangeWeighted =             \
+                       &FramingExPointer->FramingItem[0].FramingRange; \
+       FramingExPointer->CountItems = 1;                               \
+       FramingExPointer->PinFlags = 0;                                 \
+       SetDefaultKsCompression(KsCompression);                         \
+       FramingExPointer->PinWeight = 0;                                \
+       FramingExPointer->FramingItem[0].MemoryType = P_MemoryType;     \
+       FramingExPointer->FramingItem[0].BusType = KS_TYPE_DONT_CARE;   \
+       FramingExPointer->FramingItem[0].MemoryFlags = 0;               \
+       FramingExPointer->FramingItem[0].BusFlags = 0;                  \
+       FramingExPointer->FramingItem[0].Flags = P_Flags;               \
+       FramingExPointer->FramingItem[0].Frames = P_Frames;             \
+       FramingExPointer->FramingItem[0].FileAlignment = P_Alignment;   \
+       FramingExPointer->FramingItem[0].MemoryTypeWeight = 0;          \
+       SetDontCareKsFramingRange(KsFramingRange);                      \
+       SetKsFramingRangeWeighted(KsFramingRangeWeighted,               \
+                                 P_MinFrameSize,P_MaxFrameSize);       \
+}
+
+#define STATIC_KSEVENTSETID_StreamAllocator                            \
+       0x75d95571L,0x073c,0x11d0,0xa1,0x61,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("75d95571-073c-11d0-a161-0020afd156e4",KSEVENTSETID_StreamAllocator);
+#define KSEVENTSETID_StreamAllocator DEFINE_GUIDNAMED(KSEVENTSETID_StreamAllocator)
+
+typedef enum {
+  KSEVENT_STREAMALLOCATOR_INTERNAL_FREEFRAME,
+  KSEVENT_STREAMALLOCATOR_FREEFRAME
+} KSEVENT_STREAMALLOCATOR;
+
+#define STATIC_KSMETHODSETID_StreamAllocator                           \
+       0xcf6e4341L,0xec87,0x11cf,0xa1,0x30,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("cf6e4341-ec87-11cf-a130-0020afd156e4",KSMETHODSETID_StreamAllocator);
+#define KSMETHODSETID_StreamAllocator DEFINE_GUIDNAMED(KSMETHODSETID_StreamAllocator)
+
+typedef enum {
+  KSMETHOD_STREAMALLOCATOR_ALLOC,
+  KSMETHOD_STREAMALLOCATOR_FREE
+} KSMETHOD_STREAMALLOCATOR;
+
+#define DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_ALLOC(Handler)            \
+       DEFINE_KSMETHOD_ITEM(                                           \
+                               KSMETHOD_STREAMALLOCATOR_ALLOC,         \
+                               KSMETHOD_TYPE_WRITE,                    \
+                               (Handler),                              \
+                               sizeof(KSMETHOD),                       \
+                               sizeof(PVOID),                          \
+                               NULL)
+
+#define DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_FREE(Handler)             \
+       DEFINE_KSMETHOD_ITEM(                                           \
+                               KSMETHOD_STREAMALLOCATOR_FREE,          \
+                               KSMETHOD_TYPE_READ,                     \
+                               (Handler),                              \
+                               sizeof(KSMETHOD),                       \
+                               sizeof(PVOID),                          \
+                               NULL)
+
+#define DEFINE_KSMETHOD_ALLOCATORSET(AllocatorSet,MethodAlloc,MethodFree)\
+DEFINE_KSMETHOD_TABLE(AllocatorSet) {                                  \
+       DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_ALLOC(MethodAlloc),        \
+       DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_FREE(MethodFree)           \
+}
+
+#define STATIC_KSPROPSETID_StreamAllocator                             \
+       0xcf6e4342L,0xec87,0x11cf,0xa1,0x30,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("cf6e4342-ec87-11cf-a130-0020afd156e4",KSPROPSETID_StreamAllocator);
+#define KSPROPSETID_StreamAllocator DEFINE_GUIDNAMED(KSPROPSETID_StreamAllocator)
+
+#if defined(_NTDDK_)
+typedef enum {
+  KSPROPERTY_STREAMALLOCATOR_FUNCTIONTABLE,
+  KSPROPERTY_STREAMALLOCATOR_STATUS
+} KSPROPERTY_STREAMALLOCATOR;
+
+#define DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_FUNCTIONTABLE(Handler)  \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAMALLOCATOR_FUNCTIONTABLE,\
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSSTREAMALLOCATOR_FUNCTIONTABLE),\
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_STATUS(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAMALLOCATOR_STATUS,      \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSSTREAMALLOCATOR_STATUS),       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ALLOCATORSET(AllocatorSet,PropFunctionTable,PropStatus)\
+DEFINE_KSPROPERTY_TABLE(AllocatorSet) {                                        \
+       DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_STATUS(PropStatus),      \
+       DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_FUNCTIONTABLE(PropFunctionTable)\
+}
+
+typedef NTSTATUS (*PFNALLOCATOR_ALLOCATEFRAME) (PFILE_OBJECT FileObject,
+                                               PVOID *Frame);
+typedef VOID (*PFNALLOCATOR_FREEFRAME) (PFILE_OBJECT FileObject, PVOID Frame);
+
+typedef struct {
+  PFNALLOCATOR_ALLOCATEFRAME AllocateFrame;
+  PFNALLOCATOR_FREEFRAME FreeFrame;
+} KSSTREAMALLOCATOR_FUNCTIONTABLE, *PKSSTREAMALLOCATOR_FUNCTIONTABLE;
+#endif /* _NTDDK_ */
+
+typedef struct {
+  KSALLOCATOR_FRAMING Framing;
+  ULONG AllocatedFrames;
+  ULONG Reserved;
+} KSSTREAMALLOCATOR_STATUS,*PKSSTREAMALLOCATOR_STATUS;
+
+typedef struct {
+  KSALLOCATOR_FRAMING_EX Framing;
+  ULONG AllocatedFrames;
+  ULONG Reserved;
+} KSSTREAMALLOCATOR_STATUS_EX,*PKSSTREAMALLOCATOR_STATUS_EX;
+
+#define KSSTREAM_HEADER_OPTIONSF_SPLICEPOINT           0x00000001
+#define KSSTREAM_HEADER_OPTIONSF_PREROLL               0x00000002
+#define KSSTREAM_HEADER_OPTIONSF_DATADISCONTINUITY     0x00000004
+#define KSSTREAM_HEADER_OPTIONSF_TYPECHANGED           0x00000008
+#define KSSTREAM_HEADER_OPTIONSF_TIMEVALID             0x00000010
+#define KSSTREAM_HEADER_OPTIONSF_TIMEDISCONTINUITY     0x00000040
+#define KSSTREAM_HEADER_OPTIONSF_FLUSHONPAUSE          0x00000080
+#define KSSTREAM_HEADER_OPTIONSF_DURATIONVALID         0x00000100
+#define KSSTREAM_HEADER_OPTIONSF_ENDOFSTREAM           0x00000200
+#define KSSTREAM_HEADER_OPTIONSF_LOOPEDDATA            0x80000000
+
+typedef struct {
+  LONGLONG Time;
+  ULONG Numerator;
+  ULONG Denominator;
+} KSTIME,*PKSTIME;
+
+typedef struct {
+  ULONG Size;
+  ULONG TypeSpecificFlags;
+  KSTIME PresentationTime;
+  LONGLONG Duration;
+  ULONG FrameExtent;
+  ULONG DataUsed;
+  PVOID Data;
+  ULONG OptionsFlags;
+#ifdef _WIN64
+  ULONG Reserved;
+#endif
+} KSSTREAM_HEADER,*PKSSTREAM_HEADER;
+
+#define STATIC_KSPROPSETID_StreamInterface                             \
+       0x1fdd8ee1L,0x9cd3,0x11d0,0x82,0xaa,0x00,0x00,0xf8,0x22,0xfe,0x8a
+DEFINE_GUIDSTRUCT("1fdd8ee1-9cd3-11d0-82aa-0000f822fe8a",KSPROPSETID_StreamInterface);
+#define KSPROPSETID_StreamInterface DEFINE_GUIDNAMED(KSPROPSETID_StreamInterface)
+
+typedef enum {
+  KSPROPERTY_STREAMINTERFACE_HEADERSIZE
+} KSPROPERTY_STREAMINTERFACE;
+
+#define DEFINE_KSPROPERTY_ITEM_STREAMINTERFACE_HEADERSIZE(GetHandler)  \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAMINTERFACE_HEADERSIZE,  \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(ULONG),                          \
+                               NULL,NULL,0,NULL,NULL,0)
+
+#define DEFINE_KSPROPERTY_STREAMINTERFACESET(StreamInterfaceSet,HeaderSizeHandler) \
+DEFINE_KSPROPERTY_TABLE(StreamInterfaceSet) {                          \
+       DEFINE_KSPROPERTY_ITEM_STREAMINTERFACE_HEADERSIZE(HeaderSizeHandler)\
+}
+
+#define STATIC_KSPROPSETID_Stream                                      \
+       0x65aaba60L,0x98ae,0x11cf,0xa1,0x0d,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("65aaba60-98ae-11cf-a10d-0020afd156e4",KSPROPSETID_Stream);
+#define KSPROPSETID_Stream DEFINE_GUIDNAMED(KSPROPSETID_Stream)
+
+typedef enum {
+  KSPROPERTY_STREAM_ALLOCATOR,
+  KSPROPERTY_STREAM_QUALITY,
+  KSPROPERTY_STREAM_DEGRADATION,
+  KSPROPERTY_STREAM_MASTERCLOCK,
+  KSPROPERTY_STREAM_TIMEFORMAT,
+  KSPROPERTY_STREAM_PRESENTATIONTIME,
+  KSPROPERTY_STREAM_PRESENTATIONEXTENT,
+  KSPROPERTY_STREAM_FRAMETIME,
+  KSPROPERTY_STREAM_RATECAPABILITY,
+  KSPROPERTY_STREAM_RATE,
+  KSPROPERTY_STREAM_PIPE_ID
+} KSPROPERTY_STREAM;
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_ALLOCATOR(GetHandler,SetHandler) \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_ALLOCATOR,            \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(HANDLE),                         \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_QUALITY(Handler)                 \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_QUALITY,              \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSQUALITY_MANAGER),              \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_DEGRADATION(GetHandler,SetHandler)\
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_DEGRADATION,          \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_MASTERCLOCK(GetHandler,SetHandler)\
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_MASTERCLOCK,          \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(HANDLE),                         \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_TIMEFORMAT(Handler)              \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_TIMEFORMAT,           \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(GUID),                           \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_PRESENTATIONTIME(GetHandler,SetHandler)\
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_PRESENTATIONTIME,     \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSTIME),                         \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_PRESENTATIONEXTENT(Handler)      \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_PRESENTATIONEXTENT,   \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(LONGLONG),                       \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_FRAMETIME(Handler)               \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_FRAMETIME,            \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSFRAMETIME),                    \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_RATECAPABILITY(Handler)          \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_RATECAPABILITY,       \
+                               (Handler),                              \
+                               sizeof(KSRATE_CAPABILITY),              \
+                               sizeof(KSRATE),                         \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_RATE(GetHandler,SetHandler)      \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_RATE,                 \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSRATE),                         \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_STREAM_PIPE_ID(GetHandler,SetHandler)   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_STREAM_PIPE_ID,              \
+                               (GetHandler),                           \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(HANDLE),                         \
+                               (SetHandler),                           \
+                               NULL, 0, NULL, NULL, 0)
+
+typedef struct {
+  HANDLE QualityManager;
+  PVOID Context;
+} KSQUALITY_MANAGER,*PKSQUALITY_MANAGER;
+
+typedef struct {
+  LONGLONG Duration;
+  ULONG FrameFlags;
+  ULONG Reserved;
+} KSFRAMETIME,*PKSFRAMETIME;
+
+#define KSFRAMETIME_VARIABLESIZE       0x00000001
+
+typedef struct {
+  LONGLONG PresentationStart;
+  LONGLONG Duration;
+  KSPIN_INTERFACE Interface;
+  LONG Rate;
+  ULONG Flags;
+} KSRATE,*PKSRATE;
+
+#define KSRATE_NOPRESENTATIONSTART     0x00000001
+#define KSRATE_NOPRESENTATIONDURATION  0x00000002
+
+typedef struct {
+  KSPROPERTY Property;
+  KSRATE Rate;
+} KSRATE_CAPABILITY,*PKSRATE_CAPABILITY;
+
+#define STATIC_KSPROPSETID_Clock                                       \
+       0xDF12A4C0L,0xAC17,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("DF12A4C0-AC17-11CF-A5D6-28DB04C10000",KSPROPSETID_Clock);
+#define KSPROPSETID_Clock DEFINE_GUIDNAMED(KSPROPSETID_Clock)
+
+#define NANOSECONDS 10000000
+#define KSCONVERT_PERFORMANCE_TIME(Frequency,PerformanceTime)          \
+       ((((ULONGLONG)(ULONG)(PerformanceTime).HighPart *NANOSECONDS / (Frequency)) << 32) +    \
+        ((((((ULONGLONG)(ULONG)(PerformanceTime).HighPart *NANOSECONDS) % (Frequency)) << 32) +\
+        ((ULONGLONG)(PerformanceTime).LowPart *NANOSECONDS)) / (Frequency)))
+
+typedef struct {
+  ULONG CreateFlags;
+} KSCLOCK_CREATE,*PKSCLOCK_CREATE;
+
+typedef struct {
+  LONGLONG Time;
+  LONGLONG SystemTime;
+} KSCORRELATED_TIME,*PKSCORRELATED_TIME;
+
+typedef struct {
+  LONGLONG Granularity;
+  LONGLONG Error;
+} KSRESOLUTION,*PKSRESOLUTION;
+
+typedef enum {
+  KSPROPERTY_CLOCK_TIME,
+  KSPROPERTY_CLOCK_PHYSICALTIME,
+  KSPROPERTY_CLOCK_CORRELATEDTIME,
+  KSPROPERTY_CLOCK_CORRELATEDPHYSICALTIME,
+  KSPROPERTY_CLOCK_RESOLUTION,
+  KSPROPERTY_CLOCK_STATE,
+#if defined(_NTDDK_)
+  KSPROPERTY_CLOCK_FUNCTIONTABLE
+#endif /* _NTDDK_ */
+} KSPROPERTY_CLOCK;
+
+#if defined(_NTDDK_)
+typedef LONGLONG (FASTCALL *PFNKSCLOCK_GETTIME)(PFILE_OBJECT FileObject);
+typedef LONGLONG (FASTCALL *PFNKSCLOCK_CORRELATEDTIME)(PFILE_OBJECT FileObject,
+                                                       PLONGLONG SystemTime);
+
+typedef struct {
+   PFNKSCLOCK_GETTIME GetTime;
+   PFNKSCLOCK_GETTIME GetPhysicalTime;
+   PFNKSCLOCK_CORRELATEDTIME GetCorrelatedTime;
+   PFNKSCLOCK_CORRELATEDTIME GetCorrelatedPhysicalTime;
+} KSCLOCK_FUNCTIONTABLE, *PKSCLOCK_FUNCTIONTABLE;
+
+typedef BOOLEAN (*PFNKSSETTIMER)(PVOID Context, PKTIMER Timer,
+                                LARGE_INTEGER DueTime, PKDPC Dpc);
+typedef BOOLEAN (*PFNKSCANCELTIMER) (PVOID Context, PKTIMER Timer);
+typedef LONGLONG (FASTCALL *PFNKSCORRELATEDTIME)(PVOID Context,
+                                                PLONGLONG SystemTime);
+
+typedef PVOID                  PKSDEFAULTCLOCK;
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_TIME(Handler)                     \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_TIME,                  \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY), sizeof(LONGLONG),   \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_PHYSICALTIME(Handler)             \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_PHYSICALTIME,          \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY), sizeof(LONGLONG),   \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDTIME(Handler)           \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_CORRELATEDTIME,        \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSCORRELATED_TIME),              \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDPHYSICALTIME(Handler)   \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_CORRELATEDPHYSICALTIME,\
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSCORRELATED_TIME),              \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_RESOLUTION(Handler)               \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_RESOLUTION,            \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),sizeof(KSRESOLUTION),\
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_STATE(Handler)                    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_STATE,                 \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY), sizeof(KSSTATE),    \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_CLOCK_FUNCTIONTABLE(Handler)            \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_CLOCK_FUNCTIONTABLE,         \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSCLOCK_FUNCTIONTABLE),          \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_CLOCKSET(ClockSet,PropTime,PropPhysicalTime,PropCorrelatedTime,PropCorrelatedPhysicalTime,PropResolution,PropState,PropFunctionTable)\
+DEFINE_KSPROPERTY_TABLE(ClockSet) {                                    \
+       DEFINE_KSPROPERTY_ITEM_CLOCK_TIME(PropTime),                    \
+       DEFINE_KSPROPERTY_ITEM_CLOCK_PHYSICALTIME(PropPhysicalTime),    \
+       DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDTIME(PropCorrelatedTime),\
+       DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDPHYSICALTIME(PropCorrelatedPhysicalTime),\
+       DEFINE_KSPROPERTY_ITEM_CLOCK_RESOLUTION(PropResolution),        \
+       DEFINE_KSPROPERTY_ITEM_CLOCK_STATE(PropState),                  \
+       DEFINE_KSPROPERTY_ITEM_CLOCK_FUNCTIONTABLE(PropFunctionTable),  \
+}
+#endif /* _NTDDK_ */
+
+#define STATIC_KSEVENTSETID_Clock                                      \
+       0x364D8E20L,0x62C7,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("364D8E20-62C7-11CF-A5D6-28DB04C10000",KSEVENTSETID_Clock);
+#define KSEVENTSETID_Clock DEFINE_GUIDNAMED(KSEVENTSETID_Clock)
+
+typedef enum {
+  KSEVENT_CLOCK_INTERVAL_MARK,
+  KSEVENT_CLOCK_POSITION_MARK
+} KSEVENT_CLOCK_POSITION;
+
+#define STATIC_KSEVENTSETID_Connection                                 \
+       0x7f4bcbe0L,0x9ea5,0x11cf,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00
+DEFINE_GUIDSTRUCT("7f4bcbe0-9ea5-11cf-a5d6-28db04c10000",KSEVENTSETID_Connection);
+#define KSEVENTSETID_Connection DEFINE_GUIDNAMED(KSEVENTSETID_Connection)
+
+typedef enum {
+  KSEVENT_CONNECTION_POSITIONUPDATE,
+  KSEVENT_CONNECTION_DATADISCONTINUITY,
+  KSEVENT_CONNECTION_TIMEDISCONTINUITY,
+  KSEVENT_CONNECTION_PRIORITY,
+  KSEVENT_CONNECTION_ENDOFSTREAM
+} KSEVENT_CONNECTION;
+
+typedef struct {
+  PVOID Context;
+  ULONG Proportion;
+  LONGLONG DeltaTime;
+} KSQUALITY,*PKSQUALITY;
+
+typedef struct {
+  PVOID Context;
+  ULONG Status;
+} KSERROR,*PKSERROR;
+
+typedef KSIDENTIFIER KSDEGRADE,*PKSDEGRADE;
+
+#define STATIC_KSDEGRADESETID_Standard                                 \
+       0x9F564180L,0x704C,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("9F564180-704C-11D0-A5D6-28DB04C10000",KSDEGRADESETID_Standard);
+#define KSDEGRADESETID_Standard DEFINE_GUIDNAMED(KSDEGRADESETID_Standard)
+
+typedef enum {
+  KSDEGRADE_STANDARD_SAMPLE,
+  KSDEGRADE_STANDARD_QUALITY,
+  KSDEGRADE_STANDARD_COMPUTATION,
+  KSDEGRADE_STANDARD_SKIP
+} KSDEGRADE_STANDARD;
+
+#if defined(_NTDDK_)
+
+#define KSPROBE_STREAMREAD             0x00000000
+#define KSPROBE_STREAMWRITE            0x00000001
+#define KSPROBE_ALLOCATEMDL            0x00000010
+#define KSPROBE_PROBEANDLOCK           0x00000020
+#define KSPROBE_SYSTEMADDRESS          0x00000040
+#define KSPROBE_MODIFY                 0x00000200
+#define KSPROBE_STREAMWRITEMODIFY      (KSPROBE_MODIFY | KSPROBE_STREAMWRITE)
+#define KSPROBE_ALLOWFORMATCHANGE      0x00000080
+#define KSSTREAM_READ                  KSPROBE_STREAMREAD
+#define KSSTREAM_WRITE                 KSPROBE_STREAMWRITE
+#define KSSTREAM_PAGED_DATA            0x00000000
+#define KSSTREAM_NONPAGED_DATA         0x00000100
+#define KSSTREAM_SYNCHRONOUS           0x00001000
+#define KSSTREAM_FAILUREEXCEPTION      0x00002000
+
+typedef NTSTATUS (*PFNKSCONTEXT_DISPATCH)(PVOID Context, PIRP Irp);
+typedef NTSTATUS (*PFNKSHANDLER)(PIRP Irp, PKSIDENTIFIER Request, PVOID Data);
+typedef BOOLEAN (*PFNKSFASTHANDLER)(PFILE_OBJECT FileObject,
+                                   PKSIDENTIFIER Request,
+                                   ULONG RequestLength, PVOID Data,
+                                   ULONG DataLength,
+                                   PIO_STATUS_BLOCK IoStatus);
+typedef NTSTATUS (*PFNKSALLOCATOR) (PIRP Irp, ULONG BufferSize,
+                                   BOOLEAN InputOperation);
+
+typedef struct {
+  KSPROPERTY_MEMBERSHEADER MembersHeader;
+  const VOID *Members;
+} KSPROPERTY_MEMBERSLIST, *PKSPROPERTY_MEMBERSLIST;
+
+typedef struct {
+  KSIDENTIFIER PropTypeSet;
+  ULONG MembersListCount;
+  const KSPROPERTY_MEMBERSLIST *MembersList;
+} KSPROPERTY_VALUES, *PKSPROPERTY_VALUES;
+
+#define DEFINE_KSPROPERTY_TABLE(tablename)                             \
+       const KSPROPERTY_ITEM tablename[] =
+
+#define DEFINE_KSPROPERTY_ITEM(PropertyId,GetHandler,MinProperty,MinData,SetHandler,Values,RelationsCount,Relations,SupportHandler,SerializedSize)\
+{                                                                      \
+                       PropertyId, (PFNKSHANDLER)GetHandler,           \
+                       MinProperty, MinData,                           \
+                       (PFNKSHANDLER)SetHandler,                       \
+                       (PKSPROPERTY_VALUES)Values, RelationsCount,     \
+                       (PKSPROPERTY)Relations,                         \
+                       (PFNKSHANDLER)SupportHandler,                   \
+                       (ULONG)SerializedSize                           \
+}
+
+typedef struct {
+  ULONG PropertyId;
+  __MINGW_EXTENSION union {
+    PFNKSHANDLER GetPropertyHandler;
+    BOOLEAN GetSupported;
+  };
+  ULONG MinProperty;
+  ULONG MinData;
+  __MINGW_EXTENSION union {
+    PFNKSHANDLER SetPropertyHandler;
+    BOOLEAN SetSupported;
+  };
+  const KSPROPERTY_VALUES *Values;
+  ULONG RelationsCount;
+  const KSPROPERTY *Relations;
+  PFNKSHANDLER SupportHandler;
+  ULONG SerializedSize;
+} KSPROPERTY_ITEM, *PKSPROPERTY_ITEM;
+
+#define DEFINE_KSFASTPROPERTY_ITEM(PropertyId, GetHandler, SetHandler) \
+{                                                                      \
+                       PropertyId, (PFNKSFASTHANDLER)GetHandler,       \
+                       (PFNKSFASTHANDLER)SetHandler, 0                 \
+}
+
+typedef struct {
+  ULONG PropertyId;
+  __MINGW_EXTENSION union {
+    PFNKSFASTHANDLER GetPropertyHandler;
+    BOOLEAN GetSupported;
+  };
+  __MINGW_EXTENSION union {
+    PFNKSFASTHANDLER SetPropertyHandler;
+    BOOLEAN SetSupported;
+  };
+  ULONG Reserved;
+} KSFASTPROPERTY_ITEM, *PKSFASTPROPERTY_ITEM;
+
+#define DEFINE_KSPROPERTY_SET(Set,PropertiesCount,PropertyItem,FastIoCount,FastIoTable)\
+{                                                                      \
+                       Set,                                            \
+                       PropertiesCount, PropertyItem,                  \
+                       FastIoCount, FastIoTable                        \
+}
+
+#define DEFINE_KSPROPERTY_SET_TABLE(tablename)                         \
+       const KSPROPERTY_SET tablename[] =
+
+typedef struct {
+  const GUID *Set;
+  ULONG PropertiesCount;
+  const KSPROPERTY_ITEM *PropertyItem;
+  ULONG FastIoCount;
+  const KSFASTPROPERTY_ITEM *FastIoTable;
+} KSPROPERTY_SET, *PKSPROPERTY_SET;
+
+#define DEFINE_KSMETHOD_TABLE(tablename)                               \
+       const KSMETHOD_ITEM tablename[] =
+
+#define DEFINE_KSMETHOD_ITEM(MethodId,Flags,MethodHandler,MinMethod,MinData,SupportHandler)\
+{                                                                      \
+                       MethodId, (PFNKSHANDLER)MethodHandler,          \
+                       MinMethod, MinData,                             \
+                       SupportHandler, Flags                           \
+}
+
+typedef struct {
+  ULONG MethodId;
+  __MINGW_EXTENSION union {
+    PFNKSHANDLER MethodHandler;
+    BOOLEAN MethodSupported;
+  };
+  ULONG MinMethod;
+  ULONG MinData;
+  PFNKSHANDLER SupportHandler;
+  ULONG Flags;
+} KSMETHOD_ITEM, *PKSMETHOD_ITEM;
+
+#define DEFINE_KSFASTMETHOD_ITEM(MethodId,MethodHandler)               \
+{                                                                      \
+                       MethodId, (PFNKSFASTHANDLER)MethodHandler       \
+}
+
+typedef struct {
+  ULONG MethodId;
+  __MINGW_EXTENSION union {
+    PFNKSFASTHANDLER MethodHandler;
+    BOOLEAN MethodSupported;
+  };
+} KSFASTMETHOD_ITEM, *PKSFASTMETHOD_ITEM;
+
+#define DEFINE_KSMETHOD_SET(Set,MethodsCount,MethodItem,FastIoCount,FastIoTable)\
+{                                                                      \
+                       Set,                                            \
+                       MethodsCount, MethodItem,                       \
+                       FastIoCount, FastIoTable                        \
+}
+
+#define DEFINE_KSMETHOD_SET_TABLE(tablename)                           \
+       const KSMETHOD_SET tablename[] =
+
+typedef struct {
+  const GUID *Set;
+  ULONG MethodsCount;
+  const KSMETHOD_ITEM *MethodItem;
+  ULONG FastIoCount;
+  const KSFASTMETHOD_ITEM *FastIoTable;
+} KSMETHOD_SET, *PKSMETHOD_SET;
+
+typedef struct _KSEVENT_ENTRY  KSEVENT_ENTRY, *PKSEVENT_ENTRY;
+typedef NTSTATUS (*PFNKSADDEVENT)(PIRP Irp, PKSEVENTDATA EventData,
+                                 struct _KSEVENT_ENTRY* EventEntry);
+typedef VOID (*PFNKSREMOVEEVENT)(PFILE_OBJECT FileObject,
+                                struct _KSEVENT_ENTRY* EventEntry);
+
+#define DEFINE_KSEVENT_TABLE(tablename)                                        \
+       const KSEVENT_ITEM tablename[] =
+
+#define DEFINE_KSEVENT_ITEM(EventId,DataInput,ExtraEntryData,AddHandler,RemoveHandler,SupportHandler)\
+{                                                                      \
+                       EventId, DataInput, ExtraEntryData,             \
+                       AddHandler, RemoveHandler, SupportHandler       \
+}
+
+typedef struct {
+  ULONG EventId;
+  ULONG DataInput;
+  ULONG ExtraEntryData;
+  PFNKSADDEVENT AddHandler;
+  PFNKSREMOVEEVENT RemoveHandler;
+  PFNKSHANDLER SupportHandler;
+} KSEVENT_ITEM, *PKSEVENT_ITEM;
+
+#define DEFINE_KSEVENT_SET(Set,EventsCount,EventItem)                  \
+{                                                                      \
+                       Set, EventsCount, EventItem                     \
+}
+
+#define DEFINE_KSEVENT_SET_TABLE(tablename)                            \
+       const KSEVENT_SET tablename[] =
+
+typedef struct {
+  const GUID *Set;
+  ULONG EventsCount;
+  const KSEVENT_ITEM *EventItem;
+} KSEVENT_SET, *PKSEVENT_SET;
+
+typedef struct {
+  KDPC Dpc;
+  ULONG ReferenceCount;
+  KSPIN_LOCK AccessLock;
+} KSDPC_ITEM, *PKSDPC_ITEM;
+
+typedef struct {
+  KSDPC_ITEM DpcItem;
+  LIST_ENTRY BufferList;
+} KSBUFFER_ITEM, *PKSBUFFER_ITEM;
+
+
+#define KSEVENT_ENTRY_DELETED          1
+#define KSEVENT_ENTRY_ONESHOT          2
+#define KSEVENT_ENTRY_BUFFERED         4
+
+struct _KSEVENT_ENTRY {
+  LIST_ENTRY ListEntry;
+  PVOID Object;
+  __MINGW_EXTENSION union {
+    PKSDPC_ITEM DpcItem;
+    PKSBUFFER_ITEM BufferItem;
+  };
+  PKSEVENTDATA EventData;
+  ULONG NotificationType;
+  const KSEVENT_SET *EventSet;
+  const KSEVENT_ITEM *EventItem;
+  PFILE_OBJECT FileObject;
+  ULONG SemaphoreAdjustment;
+  ULONG Reserved;
+  ULONG Flags;
+};
+
+typedef enum {
+  KSEVENTS_NONE,
+  KSEVENTS_SPINLOCK,
+  KSEVENTS_MUTEX,
+  KSEVENTS_FMUTEX,
+  KSEVENTS_FMUTEXUNSAFE,
+  KSEVENTS_INTERRUPT,
+  KSEVENTS_ERESOURCE
+} KSEVENTS_LOCKTYPE;
+
+#define KSDISPATCH_FASTIO                      0x80000000
+
+typedef struct {
+  PDRIVER_DISPATCH Create;
+  PVOID Context;
+  UNICODE_STRING ObjectClass;
+  PSECURITY_DESCRIPTOR SecurityDescriptor;
+  ULONG Flags;
+} KSOBJECT_CREATE_ITEM, *PKSOBJECT_CREATE_ITEM;
+
+typedef VOID (*PFNKSITEMFREECALLBACK)(PKSOBJECT_CREATE_ITEM CreateItem);
+
+#define KSCREATE_ITEM_SECURITYCHANGED          0x00000001
+#define KSCREATE_ITEM_WILDCARD                 0x00000002
+#define KSCREATE_ITEM_NOPARAMETERS             0x00000004
+#define KSCREATE_ITEM_FREEONSTOP               0x00000008
+
+#define DEFINE_KSCREATE_DISPATCH_TABLE( tablename )                    \
+       KSOBJECT_CREATE_ITEM tablename[] =
+
+#define DEFINE_KSCREATE_ITEM(DispatchCreate,TypeName,Context)          \
+{                                                                      \
+                       (DispatchCreate), (PVOID)(Context),             \
+                       {                                               \
+                               sizeof(TypeName) - sizeof(UNICODE_NULL),\
+                               sizeof(TypeName),                       \
+                               (PWCHAR)(TypeName)                      \
+                       },                                              \
+                       NULL, 0                                         \
+}
+
+#define DEFINE_KSCREATE_ITEMEX(DispatchCreate,TypeName,Context,Flags)  \
+{                                                                      \
+                       (DispatchCreate),                               \
+                       (PVOID)(Context),                               \
+                       {                                               \
+                               sizeof(TypeName) - sizeof(UNICODE_NULL),\
+                               sizeof(TypeName),                       \
+                               (PWCHAR)(TypeName)                      \
+                       },                                              \
+                       NULL, (Flags)                                   \
+}
+
+#define DEFINE_KSCREATE_ITEMNULL(DispatchCreate,Context)               \
+{                                                                      \
+                       DispatchCreate, Context,                        \
+                       {                                               \
+                               0, 0, NULL,                             \
+                       },                                              \
+                       NULL, 0                                         \
+}
+
+typedef struct {
+  ULONG CreateItemsCount;
+  PKSOBJECT_CREATE_ITEM CreateItemsList;
+} KSOBJECT_CREATE, *PKSOBJECT_CREATE;
+
+typedef struct {
+  PDRIVER_DISPATCH DeviceIoControl;
+  PDRIVER_DISPATCH Read;
+  PDRIVER_DISPATCH Write;
+  PDRIVER_DISPATCH Flush;
+  PDRIVER_DISPATCH Close;
+  PDRIVER_DISPATCH QuerySecurity;
+  PDRIVER_DISPATCH SetSecurity;
+  PFAST_IO_DEVICE_CONTROL FastDeviceIoControl;
+  PFAST_IO_READ FastRead;
+  PFAST_IO_WRITE FastWrite;
+} KSDISPATCH_TABLE, *PKSDISPATCH_TABLE;
+
+#define DEFINE_KSDISPATCH_TABLE(tablename,DeviceIoControl,Read,Write,Flush,Close,QuerySecurity,SetSecurity,FastDeviceIoControl,FastRead,FastWrite)\
+       const KSDISPATCH_TABLE tablename =                              \
+       {                                                               \
+               DeviceIoControl,                                        \
+               Read,                                                   \
+               Write,                                                  \
+               Flush,                                                  \
+               Close,                                                  \
+               QuerySecurity,                                          \
+               SetSecurity,                                            \
+               FastDeviceIoControl,                                    \
+               FastRead,                                               \
+               FastWrite,                                              \
+       }
+
+#define KSCREATE_ITEM_IRP_STORAGE(Irp)                                 \
+       (*(PKSOBJECT_CREATE_ITEM *)&(Irp)->Tail.Overlay.DriverContext[0])
+#define KSEVENT_SET_IRP_STORAGE(Irp)                                   \
+       (*(const KSEVENT_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
+#define KSEVENT_ITEM_IRP_STORAGE(Irp)                                  \
+       (*(const KSEVENT_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
+#define KSEVENT_ENTRY_IRP_STORAGE(Irp)                                 \
+       (*(PKSEVENT_ENTRY *)&(Irp)->Tail.Overlay.DriverContext[0])
+#define KSMETHOD_SET_IRP_STORAGE(Irp)                                  \
+       (*(const KSMETHOD_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
+#define KSMETHOD_ITEM_IRP_STORAGE(Irp)                                 \
+       (*(const KSMETHOD_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
+#define KSMETHOD_TYPE_IRP_STORAGE(Irp)                                 \
+       (*(ULONG_PTR *)(&(Irp)->Tail.Overlay.DriverContext[2]))
+#define KSQUEUE_SPINLOCK_IRP_STORAGE(Irp)                              \
+       (*(PKSPIN_LOCK *)&(Irp)->Tail.Overlay.DriverContext[1])
+#define KSPROPERTY_SET_IRP_STORAGE(Irp)                                        \
+       (*(const KSPROPERTY_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
+#define KSPROPERTY_ITEM_IRP_STORAGE(Irp)                               \
+       (*(const KSPROPERTY_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
+#define KSPROPERTY_ATTRIBUTES_IRP_STORAGE(Irp)                         \
+       (*(PKSATTRIBUTE_LIST *)&(Irp)->Tail.Overlay.DriverContext[2])
+
+typedef PVOID          KSDEVICE_HEADER, KSOBJECT_HEADER;
+
+typedef enum {
+  KsInvokeOnSuccess = 1,
+  KsInvokeOnError = 2,
+  KsInvokeOnCancel = 4
+} KSCOMPLETION_INVOCATION;
+
+typedef enum {
+  KsListEntryTail,
+  KsListEntryHead
+} KSLIST_ENTRY_LOCATION;
+
+typedef enum {
+  KsAcquireOnly,
+  KsAcquireAndRemove,
+  KsAcquireOnlySingleItem,
+  KsAcquireAndRemoveOnlySingleItem
+} KSIRP_REMOVAL_OPERATION;
+
+typedef enum {
+  KsStackCopyToNewLocation,
+  KsStackReuseCurrentLocation,
+  KsStackUseNewLocation
+} KSSTACK_USE;
+
+typedef enum {
+  KSTARGET_STATE_DISABLED,
+  KSTARGET_STATE_ENABLED
+} KSTARGET_STATE;
+
+typedef NTSTATUS (*PFNKSIRPLISTCALLBACK)(PIRP Irp, PVOID Context);
+typedef VOID (*PFNREFERENCEDEVICEOBJECT)(PVOID Context);
+typedef VOID (*PFNDEREFERENCEDEVICEOBJECT)(PVOID Context);
+typedef NTSTATUS (*PFNQUERYREFERENCESTRING)(PVOID Context, PWCHAR *String);
+
+#define BUS_INTERFACE_REFERENCE_VERSION                        0x100
+
+typedef struct {
+  INTERFACE Interface;
+
+  PFNREFERENCEDEVICEOBJECT ReferenceDeviceObject;
+  PFNDEREFERENCEDEVICEOBJECT DereferenceDeviceObject;
+  PFNQUERYREFERENCESTRING QueryReferenceString;
+} BUS_INTERFACE_REFERENCE, *PBUS_INTERFACE_REFERENCE;
+
+#define STATIC_REFERENCE_BUS_INTERFACE         STATIC_KSMEDIUMSETID_Standard
+#define REFERENCE_BUS_INTERFACE                        KSMEDIUMSETID_Standard
+
+#endif /* _NTDDK_ */
+
+#ifndef PACK_PRAGMAS_NOT_SUPPORTED
+#include <pshpack1.h>
+#endif
+
+typedef struct {
+  GUID PropertySet;
+  ULONG Count;
+} KSPROPERTY_SERIALHDR,*PKSPROPERTY_SERIALHDR;
+
+#ifndef PACK_PRAGMAS_NOT_SUPPORTED
+#include <poppack.h>
+#endif
+
+typedef struct {
+  KSIDENTIFIER PropTypeSet;
+  ULONG Id;
+  ULONG PropertyLength;
+} KSPROPERTY_SERIAL,*PKSPROPERTY_SERIAL;
+
+
+#if defined(_NTDDK_)
+
+#define IOCTL_KS_HANDSHAKE                                             \
+       CTL_CODE(FILE_DEVICE_KS, 0x007, METHOD_NEITHER, FILE_ANY_ACCESS)
+
+typedef struct {
+  GUID ProtocolId;
+  PVOID Argument1;
+  PVOID Argument2;
+} KSHANDSHAKE, *PKSHANDSHAKE;
+
+typedef struct _KSGATE         KSGATE, *PKSGATE;
+
+struct _KSGATE {
+  LONG Count;
+  PKSGATE NextGate;
+};
+
+typedef PVOID KSOBJECT_BAG;
+
+
+typedef BOOLEAN (*PFNKSGENERATEEVENTCALLBACK)(PVOID Context,
+                                             PKSEVENT_ENTRY EventEntry);
+
+typedef NTSTATUS (*PFNKSDEVICECREATE)(PKSDEVICE Device);
+
+typedef NTSTATUS (*PFNKSDEVICEPNPSTART)(PKSDEVICE Device,PIRP Irp,
+                               PCM_RESOURCE_LIST TranslatedResourceList,
+                               PCM_RESOURCE_LIST UntranslatedResourceList);
+
+typedef NTSTATUS (*PFNKSDEVICE)(PKSDEVICE Device);
+
+typedef NTSTATUS (*PFNKSDEVICEIRP)(PKSDEVICE Device,PIRP Irp);
+
+typedef void (*PFNKSDEVICEIRPVOID)(PKSDEVICE Device,PIRP Irp);
+
+typedef NTSTATUS (*PFNKSDEVICEQUERYCAPABILITIES)(PKSDEVICE Device,PIRP Irp,
+                                        PDEVICE_CAPABILITIES Capabilities);
+
+typedef NTSTATUS (*PFNKSDEVICEQUERYPOWER)(PKSDEVICE Device,PIRP Irp,
+                                         DEVICE_POWER_STATE DeviceTo,
+                                         DEVICE_POWER_STATE DeviceFrom,
+                                         SYSTEM_POWER_STATE SystemTo,
+                                         SYSTEM_POWER_STATE SystemFrom,
+                                         POWER_ACTION Action);
+
+typedef void (*PFNKSDEVICESETPOWER)(PKSDEVICE Device,PIRP Irp,
+                                   DEVICE_POWER_STATE To,
+                                   DEVICE_POWER_STATE From);
+
+typedef NTSTATUS (*PFNKSFILTERFACTORYVOID)(PKSFILTERFACTORY FilterFactory);
+
+typedef void (*PFNKSFILTERFACTORYPOWER)(PKSFILTERFACTORY FilterFactory,
+                                       DEVICE_POWER_STATE State);
+
+typedef NTSTATUS (*PFNKSFILTERIRP)(PKSFILTER Filter,PIRP Irp);
+
+typedef NTSTATUS (*PFNKSFILTERPROCESS)(PKSFILTER Filter,
+                                       PKSPROCESSPIN_INDEXENTRY Index);
+
+typedef NTSTATUS (*PFNKSFILTERVOID)(PKSFILTER Filter);
+
+typedef void (*PFNKSFILTERPOWER)(PKSFILTER Filter,DEVICE_POWER_STATE State);
+
+typedef NTSTATUS (*PFNKSPINIRP)(PKSPIN Pin,PIRP Irp);
+
+typedef NTSTATUS (*PFNKSPINSETDEVICESTATE)(PKSPIN Pin,KSSTATE ToState,
+                                          KSSTATE FromState);
+
+typedef NTSTATUS (*PFNKSPINSETDATAFORMAT)(PKSPIN Pin,PKSDATAFORMAT OldFormat,
+                                         PKSMULTIPLE_ITEM OldAttributeList,
+                                         const KSDATARANGE *DataRange,
+                                         const KSATTRIBUTE_LIST *AttributeRange);
+
+typedef NTSTATUS (*PFNKSPINHANDSHAKE)(PKSPIN Pin,PKSHANDSHAKE In,
+                                     PKSHANDSHAKE Out);
+
+typedef NTSTATUS (*PFNKSPIN)(PKSPIN Pin);
+
+typedef void (*PFNKSPINVOID)(PKSPIN Pin);
+
+typedef void (*PFNKSPINPOWER)(PKSPIN Pin,DEVICE_POWER_STATE State);
+
+typedef BOOLEAN (*PFNKSPINSETTIMER)(PKSPIN Pin,PKTIMER Timer,
+                                   LARGE_INTEGER DueTime,PKDPC Dpc);
+
+typedef BOOLEAN (*PFNKSPINCANCELTIMER)(PKSPIN Pin,PKTIMER Timer);
+
+typedef LONGLONG (FASTCALL *PFNKSPINCORRELATEDTIME)(PKSPIN Pin,
+                                                   PLONGLONG SystemTime);
+
+typedef void (*PFNKSPINRESOLUTION)(PKSPIN Pin,PKSRESOLUTION Resolution);
+
+typedef NTSTATUS (*PFNKSPININITIALIZEALLOCATOR)(PKSPIN Pin,
+                                       PKSALLOCATOR_FRAMING AllocatorFraming,
+                                       PVOID *Context);
+
+typedef void (*PFNKSSTREAMPOINTER)(PKSSTREAM_POINTER StreamPointer);
+
+
+typedef struct KSAUTOMATION_TABLE_ KSAUTOMATION_TABLE,*PKSAUTOMATION_TABLE;
+
+struct KSAUTOMATION_TABLE_ {
+  ULONG PropertySetsCount;
+  ULONG PropertyItemSize;
+  const KSPROPERTY_SET *PropertySets;
+  ULONG MethodSetsCount;
+  ULONG MethodItemSize;
+  const KSMETHOD_SET *MethodSets;
+  ULONG EventSetsCount;
+  ULONG EventItemSize;
+  const KSEVENT_SET *EventSets;
+#ifndef _WIN64
+  PVOID Alignment;
+#endif
+};
+
+#define DEFINE_KSAUTOMATION_TABLE(table)                               \
+               const KSAUTOMATION_TABLE table =
+
+#define DEFINE_KSAUTOMATION_PROPERTIES(table)                          \
+               SIZEOF_ARRAY(table),                                    \
+               sizeof(KSPROPERTY_ITEM),                                \
+               table
+
+#define DEFINE_KSAUTOMATION_METHODS(table)                             \
+               SIZEOF_ARRAY(table),                                    \
+               sizeof(KSMETHOD_ITEM),                                  \
+               table
+
+#define DEFINE_KSAUTOMATION_EVENTS(table)                              \
+               SIZEOF_ARRAY(table),                                    \
+               sizeof(KSEVENT_ITEM),                                   \
+               table
+
+#define DEFINE_KSAUTOMATION_PROPERTIES_NULL                            \
+               0,                                                      \
+               sizeof(KSPROPERTY_ITEM),                                \
+               NULL
+
+#define DEFINE_KSAUTOMATION_METHODS_NULL                               \
+               0,                                                      \
+               sizeof(KSMETHOD_ITEM),                                  \
+               NULL
+
+#define DEFINE_KSAUTOMATION_EVENTS_NULL                                        \
+               0,                                                      \
+               sizeof(KSEVENT_ITEM),                                   \
+               NULL
+
+#define MIN_DEV_VER_FOR_QI             (0x100)
+
+struct _KSDEVICE_DISPATCH {
+  PFNKSDEVICECREATE Add;
+  PFNKSDEVICEPNPSTART Start;
+  PFNKSDEVICE PostStart;
+  PFNKSDEVICEIRP QueryStop;
+  PFNKSDEVICEIRPVOID CancelStop;
+  PFNKSDEVICEIRPVOID Stop;
+  PFNKSDEVICEIRP QueryRemove;
+  PFNKSDEVICEIRPVOID CancelRemove;
+  PFNKSDEVICEIRPVOID Remove;
+  PFNKSDEVICEQUERYCAPABILITIES QueryCapabilities;
+  PFNKSDEVICEIRPVOID SurpriseRemoval;
+  PFNKSDEVICEQUERYPOWER QueryPower;
+  PFNKSDEVICESETPOWER SetPower;
+  PFNKSDEVICEIRP QueryInterface;
+};
+
+struct _KSFILTER_DISPATCH {
+  PFNKSFILTERIRP Create;
+  PFNKSFILTERIRP Close;
+  PFNKSFILTERPROCESS Process;
+  PFNKSFILTERVOID Reset;
+};
+
+struct _KSPIN_DISPATCH {
+  PFNKSPINIRP Create;
+  PFNKSPINIRP Close;
+  PFNKSPIN Process;
+  PFNKSPINVOID Reset;
+  PFNKSPINSETDATAFORMAT SetDataFormat;
+  PFNKSPINSETDEVICESTATE SetDeviceState;
+  PFNKSPIN Connect;
+  PFNKSPINVOID Disconnect;
+  const KSCLOCK_DISPATCH *Clock;
+  const KSALLOCATOR_DISPATCH *Allocator;
+};
+
+struct _KSCLOCK_DISPATCH {
+  PFNKSPINSETTIMER SetTimer;
+  PFNKSPINCANCELTIMER CancelTimer;
+  PFNKSPINCORRELATEDTIME CorrelatedTime;
+  PFNKSPINRESOLUTION Resolution;
+};
+
+struct _KSALLOCATOR_DISPATCH {
+  PFNKSPININITIALIZEALLOCATOR InitializeAllocator;
+  PFNKSDELETEALLOCATOR DeleteAllocator;
+  PFNKSDEFAULTALLOCATE Allocate;
+  PFNKSDEFAULTFREE Free;
+};
+
+#define KSDEVICE_DESCRIPTOR_VERSION    (0x100)
+
+struct _KSDEVICE_DESCRIPTOR {
+  const KSDEVICE_DISPATCH *Dispatch;
+  ULONG FilterDescriptorsCount;
+  const KSFILTER_DESCRIPTOR*const *FilterDescriptors;
+  ULONG Version;
+};
+
+struct _KSFILTER_DESCRIPTOR {
+  const KSFILTER_DISPATCH *Dispatch;
+  const KSAUTOMATION_TABLE *AutomationTable;
+  ULONG Version;
+#define KSFILTER_DESCRIPTOR_VERSION    ((ULONG)-1)
+  ULONG Flags;
+#define KSFILTER_FLAG_DISPATCH_LEVEL_PROCESSING                0x00000001
+#define KSFILTER_FLAG_CRITICAL_PROCESSING              0x00000002
+#define KSFILTER_FLAG_HYPERCRITICAL_PROCESSING         0x00000004
+#define KSFILTER_FLAG_RECEIVE_ZERO_LENGTH_SAMPLES      0x00000008
+#define KSFILTER_FLAG_DENY_USERMODE_ACCESS             0x80000000
+  const GUID *ReferenceGuid;
+  ULONG PinDescriptorsCount;
+  ULONG PinDescriptorSize;
+  const KSPIN_DESCRIPTOR_EX *PinDescriptors;
+  ULONG CategoriesCount;
+  const GUID *Categories;
+  ULONG NodeDescriptorsCount;
+  ULONG NodeDescriptorSize;
+  const KSNODE_DESCRIPTOR *NodeDescriptors;
+  ULONG ConnectionsCount;
+  const KSTOPOLOGY_CONNECTION *Connections;
+  const KSCOMPONENTID *ComponentId;
+};
+
+#define DEFINE_KSFILTER_DESCRIPTOR(descriptor)                         \
+       const KSFILTER_DESCRIPTOR descriptor =
+
+#define DEFINE_KSFILTER_PIN_DESCRIPTORS(table)                         \
+       SIZEOF_ARRAY(table),                                            \
+       sizeof(table[0]),                                               \
+       table
+
+#define DEFINE_KSFILTER_CATEGORIES(table)                              \
+       SIZEOF_ARRAY(table),                                            \
+       table
+
+#define DEFINE_KSFILTER_CATEGORY(category)                             \
+       1,                                                              \
+       &(category)
+
+#define DEFINE_KSFILTER_CATEGORIES_NULL                                        \
+       0,                                                              \
+       NULL
+
+#define DEFINE_KSFILTER_NODE_DESCRIPTORS(table)                                \
+       SIZEOF_ARRAY(table),                                            \
+       sizeof(table[0]),                                               \
+       table
+
+#define DEFINE_KSFILTER_NODE_DESCRIPTORS_NULL                          \
+       0,                                                              \
+       sizeof(KSNODE_DESCRIPTOR),                                      \
+       NULL
+
+#define DEFINE_KSFILTER_CONNECTIONS(table)                             \
+       SIZEOF_ARRAY(table),                                            \
+       table
+
+#define DEFINE_KSFILTER_DEFAULT_CONNECTIONS                            \
+       0,                                                              \
+       NULL
+
+#define DEFINE_KSFILTER_DESCRIPTOR_TABLE(table)                                \
+       const KSFILTER_DESCRIPTOR*const table[] =
+
+struct _KSPIN_DESCRIPTOR_EX {
+  const KSPIN_DISPATCH *Dispatch;
+  const KSAUTOMATION_TABLE *AutomationTable;
+  KSPIN_DESCRIPTOR PinDescriptor;
+  ULONG Flags;
+#define KSPIN_FLAG_DISPATCH_LEVEL_PROCESSING   KSFILTER_FLAG_DISPATCH_LEVEL_PROCESSING
+#define KSPIN_FLAG_CRITICAL_PROCESSING         KSFILTER_FLAG_CRITICAL_PROCESSING
+#define KSPIN_FLAG_HYPERCRITICAL_PROCESSING    KSFILTER_FLAG_HYPERCRITICAL_PROCESSING
+#define KSPIN_FLAG_ASYNCHRONOUS_PROCESSING                     0x00000008
+#define KSPIN_FLAG_DO_NOT_INITIATE_PROCESSING                  0x00000010
+#define KSPIN_FLAG_INITIATE_PROCESSING_ON_EVERY_ARRIVAL                0x00000020
+#define KSPIN_FLAG_FRAMES_NOT_REQUIRED_FOR_PROCESSING          0x00000040
+#define KSPIN_FLAG_ENFORCE_FIFO                                        0x00000080
+#define KSPIN_FLAG_GENERATE_MAPPINGS                           0x00000100
+#define KSPIN_FLAG_DISTINCT_TRAILING_EDGE                      0x00000200
+#define KSPIN_FLAG_PROCESS_IN_RUN_STATE_ONLY                   0x00010000
+#define KSPIN_FLAG_SPLITTER                                    0x00020000
+#define KSPIN_FLAG_USE_STANDARD_TRANSPORT                      0x00040000
+#define KSPIN_FLAG_DO_NOT_USE_STANDARD_TRANSPORT               0x00080000
+#define KSPIN_FLAG_FIXED_FORMAT                                        0x00100000
+#define KSPIN_FLAG_GENERATE_EOS_EVENTS                         0x00200000
+#define KSPIN_FLAG_RENDERER                    (KSPIN_FLAG_PROCESS_IN_RUN_STATE_ONLY|KSPIN_FLAG_GENERATE_EOS_EVENTS)
+#define KSPIN_FLAG_IMPLEMENT_CLOCK                             0x00400000
+#define KSPIN_FLAG_SOME_FRAMES_REQUIRED_FOR_PROCESSING         0x00800000
+#define KSPIN_FLAG_PROCESS_IF_ANY_IN_RUN_STATE                 0x01000000
+#define KSPIN_FLAG_DENY_USERMODE_ACCESS                                0x80000000
+  ULONG InstancesPossible;
+  ULONG InstancesNecessary;
+  const KSALLOCATOR_FRAMING_EX *AllocatorFraming;
+  PFNKSINTERSECTHANDLEREX IntersectHandler;
+};
+
+#define DEFINE_KSPIN_DEFAULT_INTERFACES                                        \
+       0,                                                              \
+       NULL
+
+#define DEFINE_KSPIN_DEFAULT_MEDIUMS                                   \
+       0,                                                              \
+       NULL
+
+struct _KSNODE_DESCRIPTOR {
+  const KSAUTOMATION_TABLE *AutomationTable;
+  const GUID *Type;
+  const GUID *Name;
+#ifndef _WIN64
+  PVOID Alignment;
+#endif
+};
+
+#ifndef _WIN64
+#define DEFINE_NODE_DESCRIPTOR(automation,type,name)                   \
+       { (automation), (type), (name), NULL }
+#else
+#define DEFINE_NODE_DESCRIPTOR(automation,type,name)                   \
+       { (automation), (type), (name) }
+#endif
+
+struct _KSDEVICE {
+  const KSDEVICE_DESCRIPTOR *Descriptor;
+  KSOBJECT_BAG Bag;
+  PVOID Context;
+  PDEVICE_OBJECT FunctionalDeviceObject;
+  PDEVICE_OBJECT PhysicalDeviceObject;
+  PDEVICE_OBJECT NextDeviceObject;
+  BOOLEAN Started;
+  SYSTEM_POWER_STATE SystemPowerState;
+  DEVICE_POWER_STATE DevicePowerState;
+};
+
+struct _KSFILTERFACTORY {
+  const KSFILTER_DESCRIPTOR *FilterDescriptor;
+  KSOBJECT_BAG Bag;
+  PVOID Context;
+};
+
+struct _KSFILTER {
+  const KSFILTER_DESCRIPTOR *Descriptor;
+  KSOBJECT_BAG Bag;
+  PVOID Context;
+};
+
+struct _KSPIN {
+  const KSPIN_DESCRIPTOR_EX *Descriptor;
+  KSOBJECT_BAG Bag;
+  PVOID Context;
+  ULONG Id;
+  KSPIN_COMMUNICATION Communication;
+  BOOLEAN ConnectionIsExternal;
+  KSPIN_INTERFACE ConnectionInterface;
+  KSPIN_MEDIUM ConnectionMedium;
+  KSPRIORITY ConnectionPriority;
+  PKSDATAFORMAT ConnectionFormat;
+  PKSMULTIPLE_ITEM AttributeList;
+  ULONG StreamHeaderSize;
+  KSPIN_DATAFLOW DataFlow;
+  KSSTATE DeviceState;
+  KSRESET ResetState;
+  KSSTATE ClientState;
+};
+
+struct _KSMAPPING {
+  PHYSICAL_ADDRESS PhysicalAddress;
+  ULONG ByteCount;
+  ULONG Alignment;
+};
+
+struct _KSSTREAM_POINTER_OFFSET
+{
+#if defined(_NTDDK_)
+  __MINGW_EXTENSION union {
+    PUCHAR Data;
+    PKSMAPPING Mappings;
+  };
+#else
+  PUCHAR Data;
+#endif /* _NTDDK_ */
+#ifndef _WIN64
+  PVOID Alignment;
+#endif
+  ULONG Count;
+  ULONG Remaining;
+};
+
+struct _KSSTREAM_POINTER
+{
+  PVOID Context;
+  PKSPIN Pin;
+  PKSSTREAM_HEADER StreamHeader;
+  PKSSTREAM_POINTER_OFFSET Offset;
+  KSSTREAM_POINTER_OFFSET OffsetIn;
+  KSSTREAM_POINTER_OFFSET OffsetOut;
+};
+
+struct _KSPROCESSPIN {
+  PKSPIN Pin;
+  PKSSTREAM_POINTER StreamPointer;
+  PKSPROCESSPIN InPlaceCounterpart;
+  PKSPROCESSPIN DelegateBranch;
+  PKSPROCESSPIN CopySource;
+  PVOID Data;
+  ULONG BytesAvailable;
+  ULONG BytesUsed;
+  ULONG Flags;
+  BOOLEAN Terminate;
+};
+
+struct _KSPROCESSPIN_INDEXENTRY {
+  PKSPROCESSPIN *Pins;
+  ULONG Count;
+};
+
+typedef enum {
+  KsObjectTypeDevice,
+  KsObjectTypeFilterFactory,
+  KsObjectTypeFilter,
+  KsObjectTypePin
+} KSOBJECTTYPE;
+
+
+typedef void (*PFNKSFREE)(PVOID Data);
+
+typedef void (*PFNKSPINFRAMERETURN)(PKSPIN Pin,PVOID Data,ULONG Size,PMDL Mdl,
+                                   PVOID Context,NTSTATUS Status);
+
+typedef void (*PFNKSPINIRPCOMPLETION)(PKSPIN Pin,PIRP Irp);
+
+
+#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
+#ifndef _IKsControl_
+#define _IKsControl_
+
+typedef struct IKsControl *PIKSCONTROL;
+
+#ifndef DEFINE_ABSTRACT_UNKNOWN
+#define DEFINE_ABSTRACT_UNKNOWN()                                      \
+       STDMETHOD_(NTSTATUS,QueryInterface) (THIS_                      \
+                                               REFIID InterfaceId,     \
+                                               PVOID *Interface        \
+                                           ) PURE;                     \
+       STDMETHOD_(ULONG,AddRef)(THIS) PURE;                            \
+       STDMETHOD_(ULONG,Release)(THIS) PURE;
+#endif
+
+#undef INTERFACE
+#define INTERFACE IKsControl
+DECLARE_INTERFACE_(IKsControl,IUnknown)
+{
+  DEFINE_ABSTRACT_UNKNOWN()
+  STDMETHOD_(NTSTATUS,KsProperty)(THIS_
+                                       PKSPROPERTY Property,
+                                       ULONG PropertyLength,
+                                       PVOID PropertyData,
+                                       ULONG DataLength,
+                                       ULONG *BytesReturned
+                                ) PURE;
+  STDMETHOD_(NTSTATUS,KsMethod)        (THIS_
+                                       PKSMETHOD Method,
+                                       ULONG MethodLength,
+                                       PVOID MethodData,
+                                       ULONG DataLength,
+                                       ULONG *BytesReturned
+                                ) PURE;
+  STDMETHOD_(NTSTATUS,KsEvent) (THIS_
+                                       PKSEVENT Event,
+                                       ULONG EventLength,
+                                       PVOID EventData,
+                                       ULONG DataLength,
+                                       ULONG *BytesReturned
+                               ) PURE;
+};
+typedef struct IKsReferenceClock *PIKSREFERENCECLOCK;
+
+#undef INTERFACE
+#define INTERFACE IKsReferenceClock
+DECLARE_INTERFACE_(IKsReferenceClock,IUnknown)
+{
+  DEFINE_ABSTRACT_UNKNOWN()
+  STDMETHOD_(LONGLONG,GetTime)         (THIS) PURE;
+  STDMETHOD_(LONGLONG,GetPhysicalTime) (THIS) PURE;
+  STDMETHOD_(LONGLONG,GetCorrelatedTime)(THIS_
+                                               PLONGLONG SystemTime
+                                       ) PURE;
+  STDMETHOD_(LONGLONG,GetCorrelatedPhysicalTime)(THIS_
+                                               PLONGLONG SystemTime
+                                       ) PURE;
+  STDMETHOD_(NTSTATUS,GetResolution)   (THIS_
+                                               PKSRESOLUTION Resolution
+                                       ) PURE;
+  STDMETHOD_(NTSTATUS,GetState)                (THIS_
+                                               PKSSTATE State
+                                       ) PURE;
+};
+#undef INTERFACE
+
+#define INTERFACE IKsDeviceFunctions
+DECLARE_INTERFACE_(IKsDeviceFunctions,IUnknown)
+{
+  DEFINE_ABSTRACT_UNKNOWN()
+  STDMETHOD_(NTSTATUS,RegisterAdapterObjectEx) (THIS_
+                                                 PADAPTER_OBJECT AdapterObject,
+                                                 PDEVICE_DESCRIPTION DeviceDescription,
+                                                 ULONG NumberOfMapRegisters,
+                                                 ULONG MaxMappingsByteCount,
+                                                 ULONG MappingTableStride
+                                               ) PURE;
+};
+
+#undef INTERFACE
+#define STATIC_IID_IKsControl                                          \
+       0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUID(IID_IKsControl,
+       0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96);
+#define STATIC_IID_IKsFastClock                                                \
+       0xc9902485,0xc180,0x11d2,0x84,0x73,0xd4,0x23,0x94,0x45,0x9e,0x5e
+DEFINE_GUID(IID_IKsFastClock,
+       0xc9902485,0xc180,0x11d2,0x84,0x73,0xd4,0x23,0x94,0x45,0x9e,0x5e);
+#define STATIC_IID_IKsDeviceFunctions                                  \
+       0xe234f2e2,0xbd69,0x4f8c,0xb3,0xf2,0x7c,0xd7,0x9e,0xd4,0x66,0xbd
+DEFINE_GUID(IID_IKsDeviceFunctions,
+       0xe234f2e2,0xbd69,0x4f8c,0xb3,0xf2,0x7c,0xd7,0x9e,0xd4,0x66,0xbd);
+#endif /* _IKsControl_ */
+#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
+
+#endif /* _NTDDK_ */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef _KSDDK_
+#define KSDDKAPI
+#else
+#define KSDDKAPI DECLSPEC_IMPORT
+#endif
+
+#if defined(_NTDDK_)
+
+KSDDKAPI NTSTATUS NTAPI KsEnableEvent
+                       (PIRP Irp, ULONG EventSetsCount, const KSEVENT_SET *EventSet,
+                        PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
+                        PVOID EventsLock);
+
+KSDDKAPI NTSTATUS NTAPI KsEnableEventWithAllocator
+                       (PIRP Irp, ULONG EventSetsCount, const KSEVENT_SET *EventSet,
+                        PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
+                        PVOID EventsLock, PFNKSALLOCATOR Allocator, ULONG EventItemSize);
+
+KSDDKAPI NTSTATUS NTAPI KsDisableEvent
+                       (PIRP Irp, PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
+                        PVOID EventsLock);
+
+KSDDKAPI VOID NTAPI KsDiscardEvent (PKSEVENT_ENTRY EventEntry);
+
+KSDDKAPI VOID NTAPI KsFreeEventList
+                       (PFILE_OBJECT FileObject, PLIST_ENTRY EventsList,
+                        KSEVENTS_LOCKTYPE EventsFlags, PVOID EventsLock);
+
+KSDDKAPI NTSTATUS NTAPI KsGenerateEvent (PKSEVENT_ENTRY EventEntry);
+
+KSDDKAPI NTSTATUS NTAPI KsGenerateDataEvent
+                       (PKSEVENT_ENTRY EventEntry, ULONG DataSize, PVOID Data);
+
+KSDDKAPI VOID NTAPI KsGenerateEventList
+                       (GUID *Set, ULONG EventId, PLIST_ENTRY EventsList,
+                        KSEVENTS_LOCKTYPE EventsFlags, PVOID EventsLock);
+
+KSDDKAPI NTSTATUS NTAPI KsPropertyHandler
+                       (PIRP Irp, ULONG PropertySetsCount,
+                        const KSPROPERTY_SET *PropertySet);
+
+KSDDKAPI NTSTATUS NTAPI KsPropertyHandlerWithAllocator
+                       (PIRP Irp, ULONG PropertySetsCount,
+                        const KSPROPERTY_SET *PropertySet, PFNKSALLOCATOR Allocator,
+                        ULONG PropertyItemSize);
+
+KSDDKAPI BOOLEAN NTAPI KsFastPropertyHandler
+                       (PFILE_OBJECT FileObject, PKSPROPERTY Property,
+                        ULONG PropertyLength, PVOID Data, ULONG DataLength,
+                        PIO_STATUS_BLOCK IoStatus, ULONG PropertySetsCount,
+                        const KSPROPERTY_SET *PropertySet);
+
+KSDDKAPI NTSTATUS NTAPI KsMethodHandler
+                       (PIRP Irp, ULONG MethodSetsCount,
+                        const KSMETHOD_SET *MethodSet);
+
+KSDDKAPI NTSTATUS NTAPI KsMethodHandlerWithAllocator
+                       (PIRP Irp, ULONG MethodSetsCount,
+                        const KSMETHOD_SET *MethodSet, PFNKSALLOCATOR Allocator,
+                        ULONG MethodItemSize);
+
+KSDDKAPI BOOLEAN NTAPI KsFastMethodHandler
+                       (PFILE_OBJECT FileObject, PKSMETHOD Method, ULONG MethodLength,
+                        PVOID Data, ULONG DataLength, PIO_STATUS_BLOCK IoStatus,
+                        ULONG MethodSetsCount, const KSMETHOD_SET *MethodSet);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateDefaultAllocator (PIRP Irp);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateDefaultAllocatorEx
+                       (PIRP Irp, PVOID InitializeContext,
+                        PFNKSDEFAULTALLOCATE DefaultAllocate,
+                        PFNKSDEFAULTFREE DefaultFree,
+                        PFNKSINITIALIZEALLOCATOR InitializeAllocator,
+                        PFNKSDELETEALLOCATOR DeleteAllocator);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateAllocator
+                       (HANDLE ConnectionHandle, PKSALLOCATOR_FRAMING AllocatorFraming,
+                        PHANDLE AllocatorHandle);
+
+KSDDKAPI NTSTATUS NTAPI KsValidateAllocatorCreateRequest
+                       (PIRP Irp, PKSALLOCATOR_FRAMING *AllocatorFraming);
+
+KSDDKAPI NTSTATUS NTAPI KsValidateAllocatorFramingEx
+                       (PKSALLOCATOR_FRAMING_EX Framing, ULONG BufferSize,
+                        const KSALLOCATOR_FRAMING_EX *PinFraming);
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateDefaultClock (PKSDEFAULTCLOCK *DefaultClock);
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateDefaultClockEx
+                       (PKSDEFAULTCLOCK *DefaultClock, PVOID Context,
+                        PFNKSSETTIMER SetTimer, PFNKSCANCELTIMER CancelTimer,
+                        PFNKSCORRELATEDTIME CorrelatedTime,
+                        const KSRESOLUTION *Resolution, ULONG Flags);
+
+KSDDKAPI VOID NTAPI KsFreeDefaultClock (PKSDEFAULTCLOCK DefaultClock);
+KSDDKAPI NTSTATUS NTAPI KsCreateDefaultClock (PIRP Irp, PKSDEFAULTCLOCK DefaultClock);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateClock
+                       (HANDLE ConnectionHandle, PKSCLOCK_CREATE ClockCreate,
+                        PHANDLE ClockHandle);
+
+KSDDKAPI NTSTATUS NTAPI KsValidateClockCreateRequest
+                       (PIRP Irp, PKSCLOCK_CREATE *ClockCreate);
+
+KSDDKAPI KSSTATE NTAPI KsGetDefaultClockState (PKSDEFAULTCLOCK DefaultClock);
+KSDDKAPI VOID NTAPI KsSetDefaultClockState(PKSDEFAULTCLOCK DefaultClock, KSSTATE State);
+KSDDKAPI LONGLONG NTAPI KsGetDefaultClockTime (PKSDEFAULTCLOCK DefaultClock);
+KSDDKAPI VOID NTAPI KsSetDefaultClockTime(PKSDEFAULTCLOCK DefaultClock, LONGLONG Time);
+
+KSDDKAPI NTSTATUS NTAPI KsCreatePin
+                       (HANDLE FilterHandle, PKSPIN_CONNECT Connect,
+                        ACCESS_MASK DesiredAccess, PHANDLE ConnectionHandle);
+
+KSDDKAPI NTSTATUS NTAPI KsValidateConnectRequest
+                       (PIRP Irp, ULONG DescriptorsCount,
+                        const KSPIN_DESCRIPTOR *Descriptor, PKSPIN_CONNECT *Connect);
+
+KSDDKAPI NTSTATUS NTAPI KsPinPropertyHandler
+                       (PIRP Irp, PKSPROPERTY Property, PVOID Data,
+                        ULONG DescriptorsCount, const KSPIN_DESCRIPTOR *Descriptor);
+
+KSDDKAPI NTSTATUS NTAPI KsPinDataIntersection
+                       (PIRP Irp, PKSP_PIN Pin, PVOID Data, ULONG DescriptorsCount,
+                        const KSPIN_DESCRIPTOR *Descriptor,
+                        PFNKSINTERSECTHANDLER IntersectHandler);
+
+KSDDKAPI NTSTATUS NTAPI KsPinDataIntersectionEx
+                       (PIRP Irp, PKSP_PIN Pin, PVOID Data, ULONG DescriptorsCount,
+                        const KSPIN_DESCRIPTOR *Descriptor, ULONG DescriptorSize,
+                        PFNKSINTERSECTHANDLEREX IntersectHandler, PVOID HandlerContext);
+
+KSDDKAPI NTSTATUS NTAPI KsHandleSizedListQuery
+                       (PIRP Irp, ULONG DataItemsCount, ULONG DataItemSize,
+                        const VOID *DataItems);
+
+#ifndef MAKEINTRESOURCE
+#define MAKEINTRESOURCE(r)             ((ULONG_PTR) (USHORT) r)
+#endif
+#ifndef RT_STRING
+#define RT_STRING                      MAKEINTRESOURCE(6)
+#define RT_RCDATA                      MAKEINTRESOURCE(10)
+#endif
+
+KSDDKAPI NTSTATUS NTAPI KsLoadResource
+                       (PVOID ImageBase, POOL_TYPE PoolType, ULONG_PTR ResourceName,
+                        ULONG ResourceType, PVOID *Resource, PULONG ResourceSize);
+
+KSDDKAPI NTSTATUS NTAPI KsGetImageNameAndResourceId
+                       (HANDLE RegKey, PUNICODE_STRING ImageName, PULONG_PTR ResourceId,
+                        PULONG ValueType);
+
+KSDDKAPI NTSTATUS NTAPI KsMapModuleName
+                       (PDEVICE_OBJECT PhysicalDeviceObject, PUNICODE_STRING ModuleName,
+                        PUNICODE_STRING ImageName, PULONG_PTR ResourceId,
+                        PULONG ValueType);
+
+KSDDKAPI NTSTATUS NTAPI KsReferenceBusObject (KSDEVICE_HEADER Header);
+KSDDKAPI VOID NTAPI KsDereferenceBusObject (KSDEVICE_HEADER Header);
+KSDDKAPI NTSTATUS NTAPI KsDispatchQuerySecurity (PDEVICE_OBJECT DeviceObject, PIRP Irp);
+KSDDKAPI NTSTATUS NTAPI KsDispatchSetSecurity (PDEVICE_OBJECT DeviceObject, PIRP Irp);
+KSDDKAPI NTSTATUS NTAPI KsDispatchSpecificProperty (PIRP Irp, PFNKSHANDLER Handler);
+KSDDKAPI NTSTATUS NTAPI KsDispatchSpecificMethod (PIRP Irp, PFNKSHANDLER Handler);
+
+KSDDKAPI NTSTATUS NTAPI KsReadFile
+                       (PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
+                        PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length,
+                        ULONG Key, KPROCESSOR_MODE RequestorMode);
+
+KSDDKAPI NTSTATUS NTAPI KsWriteFile
+                       (PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
+                        PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length,
+                        ULONG Key, KPROCESSOR_MODE RequestorMode);
+
+KSDDKAPI NTSTATUS NTAPI KsQueryInformationFile
+                       (PFILE_OBJECT FileObject, PVOID FileInformation, ULONG Length,
+                        FILE_INFORMATION_CLASS FileInformationClass);
+
+KSDDKAPI NTSTATUS NTAPI KsSetInformationFile
+                       (PFILE_OBJECT FileObject, PVOID FileInformation, ULONG Length,
+                        FILE_INFORMATION_CLASS FileInformationClass);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamIo
+                       (PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
+                        PIO_COMPLETION_ROUTINE CompletionRoutine, PVOID CompletionContext,
+                        KSCOMPLETION_INVOCATION CompletionInvocationFlags,
+                        PIO_STATUS_BLOCK IoStatusBlock, PVOID StreamHeaders, ULONG Length,
+                        ULONG Flags, KPROCESSOR_MODE RequestorMode);
+
+KSDDKAPI NTSTATUS NTAPI KsProbeStreamIrp(PIRP Irp, ULONG ProbeFlags, ULONG HeaderSize);
+KSDDKAPI NTSTATUS NTAPI KsAllocateExtraData(PIRP Irp, ULONG ExtraSize, PVOID *ExtraBuffer);
+KSDDKAPI VOID NTAPI KsNullDriverUnload (PDRIVER_OBJECT DriverObject);
+
+KSDDKAPI NTSTATUS NTAPI KsSetMajorFunctionHandler
+                       (PDRIVER_OBJECT DriverObject, ULONG MajorFunction);
+
+KSDDKAPI NTSTATUS NTAPI KsDispatchInvalidDeviceRequest
+                       (PDEVICE_OBJECT DeviceObject, PIRP Irp);
+
+KSDDKAPI NTSTATUS NTAPI KsDefaultDeviceIoCompletion
+                       (PDEVICE_OBJECT DeviceObject, PIRP Irp);
+
+KSDDKAPI NTSTATUS NTAPI KsDispatchIrp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
+
+KSDDKAPI BOOLEAN NTAPI KsDispatchFastIoDeviceControlFailure
+                       (PFILE_OBJECT FileObject, BOOLEAN Wait, PVOID InputBuffer,
+                        ULONG InputBufferLength, PVOID OutputBuffer,
+                        ULONG OutputBufferLength, ULONG IoControlCode,
+                        PIO_STATUS_BLOCK IoStatus, PDEVICE_OBJECT DeviceObject);
+
+KSDDKAPI BOOLEAN NTAPI KsDispatchFastReadFailure
+                       (PFILE_OBJECT FileObject, PLARGE_INTEGER FileOffset,
+                        ULONG Length, BOOLEAN Wait, ULONG LockKey, PVOID Buffer,
+                        PIO_STATUS_BLOCK IoStatus, PDEVICE_OBJECT DeviceObject);
+
+#define KsDispatchFastWriteFailure             KsDispatchFastReadFailure
+
+KSDDKAPI VOID NTAPI KsCancelRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp);
+KSDDKAPI VOID NTAPI KsCancelIo(PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock);
+KSDDKAPI VOID NTAPI KsReleaseIrpOnCancelableQueue(PIRP Irp, PDRIVER_CANCEL DriverCancel);
+
+KSDDKAPI PIRP NTAPI KsRemoveIrpFromCancelableQueue
+                       (PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock,
+                        KSLIST_ENTRY_LOCATION ListLocation,
+                        KSIRP_REMOVAL_OPERATION RemovalOperation);
+
+KSDDKAPI NTSTATUS NTAPI KsMoveIrpsOnCancelableQueue
+                       (PLIST_ENTRY SourceList, PKSPIN_LOCK SourceLock,
+                        PLIST_ENTRY DestinationList, PKSPIN_LOCK DestinationLock,
+                        KSLIST_ENTRY_LOCATION ListLocation,
+                        PFNKSIRPLISTCALLBACK ListCallback, PVOID Context);
+
+KSDDKAPI VOID NTAPI KsRemoveSpecificIrpFromCancelableQueue (PIRP Irp);
+
+KSDDKAPI VOID NTAPI KsAddIrpToCancelableQueue
+                       (PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock, PIRP Irp,
+                        KSLIST_ENTRY_LOCATION ListLocation, PDRIVER_CANCEL DriverCancel);
+
+KSDDKAPI NTSTATUS NTAPI KsAcquireResetValue(PIRP Irp, KSRESET *ResetValue);
+
+KSDDKAPI NTSTATUS NTAPI KsTopologyPropertyHandler
+                       (PIRP Irp, PKSPROPERTY Property, PVOID Data,
+                        const KSTOPOLOGY *Topology);
+
+KSDDKAPI VOID NTAPI KsAcquireDeviceSecurityLock(KSDEVICE_HEADER Header, BOOLEAN Exclusive);
+KSDDKAPI VOID NTAPI KsReleaseDeviceSecurityLock (KSDEVICE_HEADER Header);
+KSDDKAPI NTSTATUS NTAPI KsDefaultDispatchPnp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
+KSDDKAPI NTSTATUS NTAPI KsDefaultDispatchPower(PDEVICE_OBJECT DeviceObject, PIRP Irp);
+KSDDKAPI NTSTATUS NTAPI KsDefaultForwardIrp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
+
+KSDDKAPI VOID NTAPI KsSetDevicePnpAndBaseObject
+                       (KSDEVICE_HEADER Header, PDEVICE_OBJECT PnpDeviceObject,
+                        PDEVICE_OBJECT BaseObject);
+
+KSDDKAPI PDEVICE_OBJECT NTAPI KsQueryDevicePnpObject (KSDEVICE_HEADER Header);
+KSDDKAPI ACCESS_MASK NTAPI KsQueryObjectAccessMask (KSOBJECT_HEADER Header);
+
+KSDDKAPI VOID NTAPI KsRecalculateStackDepth
+                       (KSDEVICE_HEADER Header, BOOLEAN ReuseStackLocation);
+
+KSDDKAPI VOID NTAPI KsSetTargetState
+                       (KSOBJECT_HEADER Header, KSTARGET_STATE TargetState);
+
+KSDDKAPI VOID NTAPI KsSetTargetDeviceObject
+                       (KSOBJECT_HEADER Header, PDEVICE_OBJECT TargetDevice);
+
+KSDDKAPI VOID NTAPI KsSetPowerDispatch
+                       (KSOBJECT_HEADER Header, PFNKSCONTEXT_DISPATCH PowerDispatch,
+                        PVOID PowerContext);
+
+KSDDKAPI PKSOBJECT_CREATE_ITEM NTAPI KsQueryObjectCreateItem (KSOBJECT_HEADER Header);
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateDeviceHeader
+                       (KSDEVICE_HEADER *Header, ULONG ItemsCount,
+                        PKSOBJECT_CREATE_ITEM ItemsList);
+
+KSDDKAPI VOID NTAPI KsFreeDeviceHeader (KSDEVICE_HEADER Header);
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateObjectHeader
+                       (KSOBJECT_HEADER *Header, ULONG ItemsCount,
+                        PKSOBJECT_CREATE_ITEM ItemsList, PIRP Irp,
+                        const KSDISPATCH_TABLE *Table);
+
+KSDDKAPI VOID NTAPI KsFreeObjectHeader (KSOBJECT_HEADER Header);
+
+KSDDKAPI NTSTATUS NTAPI KsAddObjectCreateItemToDeviceHeader
+                       (KSDEVICE_HEADER Header, PDRIVER_DISPATCH Create, PVOID Context,
+                        PWSTR ObjectClass, PSECURITY_DESCRIPTOR SecurityDescriptor);
+
+KSDDKAPI NTSTATUS NTAPI KsAddObjectCreateItemToObjectHeader
+                       (KSOBJECT_HEADER Header, PDRIVER_DISPATCH Create, PVOID Context,
+                        PWSTR ObjectClass, PSECURITY_DESCRIPTOR SecurityDescriptor);
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateObjectCreateItem
+                       (KSDEVICE_HEADER Header, PKSOBJECT_CREATE_ITEM CreateItem,
+                        BOOLEAN AllocateEntry, PFNKSITEMFREECALLBACK ItemFreeCallback);
+
+KSDDKAPI NTSTATUS NTAPI KsFreeObjectCreateItem
+                       (KSDEVICE_HEADER Header, PUNICODE_STRING CreateItem);
+
+KSDDKAPI NTSTATUS NTAPI KsFreeObjectCreateItemsByContext
+                       (KSDEVICE_HEADER Header, PVOID Context);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateDefaultSecurity
+                       (PSECURITY_DESCRIPTOR ParentSecurity,
+                        PSECURITY_DESCRIPTOR *DefaultSecurity);
+
+KSDDKAPI NTSTATUS NTAPI KsForwardIrp
+                       (PIRP Irp, PFILE_OBJECT FileObject, BOOLEAN ReuseStackLocation);
+
+KSDDKAPI NTSTATUS NTAPI KsForwardAndCatchIrp
+                       (PDEVICE_OBJECT DeviceObject, PIRP Irp, PFILE_OBJECT FileObject,
+                        KSSTACK_USE StackUse);
+
+KSDDKAPI NTSTATUS NTAPI KsSynchronousIoControlDevice
+                       (PFILE_OBJECT FileObject, KPROCESSOR_MODE RequestorMode,
+                        ULONG IoControl, PVOID InBuffer, ULONG InSize, PVOID OutBuffer,
+                        ULONG OutSize, PULONG BytesReturned);
+
+KSDDKAPI NTSTATUS NTAPI KsUnserializeObjectPropertiesFromRegistry
+                       (PFILE_OBJECT FileObject, HANDLE ParentKey,
+                        PUNICODE_STRING RegistryPath);
+
+KSDDKAPI NTSTATUS NTAPI KsCacheMedium
+                       (PUNICODE_STRING SymbolicLink, PKSPIN_MEDIUM Medium,
+                        ULONG PinDirection);
+
+KSDDKAPI NTSTATUS NTAPI KsRegisterWorker
+                       (WORK_QUEUE_TYPE WorkQueueType, PKSWORKER *Worker);
+
+KSDDKAPI NTSTATUS NTAPI KsRegisterCountedWorker
+                       (WORK_QUEUE_TYPE WorkQueueType, PWORK_QUEUE_ITEM CountedWorkItem,
+                        PKSWORKER *Worker);
+
+KSDDKAPI VOID NTAPI KsUnregisterWorker (PKSWORKER Worker);
+KSDDKAPI NTSTATUS NTAPI KsQueueWorkItem(PKSWORKER Worker, PWORK_QUEUE_ITEM WorkItem);
+KSDDKAPI ULONG NTAPI KsIncrementCountedWorker (PKSWORKER Worker);
+KSDDKAPI ULONG NTAPI KsDecrementCountedWorker (PKSWORKER Worker);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateTopologyNode
+                       (HANDLE ParentHandle, PKSNODE_CREATE NodeCreate,
+                        ACCESS_MASK DesiredAccess, PHANDLE NodeHandle);
+
+KSDDKAPI NTSTATUS NTAPI KsValidateTopologyNodeCreateRequest
+                       (PIRP Irp, PKSTOPOLOGY Topology, PKSNODE_CREATE *NodeCreate);
+
+KSDDKAPI NTSTATUS NTAPI KsMergeAutomationTables
+                       (PKSAUTOMATION_TABLE *AutomationTableAB,
+                        PKSAUTOMATION_TABLE AutomationTableA,
+                        PKSAUTOMATION_TABLE AutomationTableB,
+                        KSOBJECT_BAG Bag);
+
+KSDDKAPI NTSTATUS NTAPI KsInitializeDriver
+                       (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPathName,
+                        const KSDEVICE_DESCRIPTOR *Descriptor);
+
+KSDDKAPI NTSTATUS NTAPI KsAddDevice
+                       (PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT PhysicalDeviceObject);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateDevice
+                       (PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT PhysicalDeviceObject,
+                        const KSDEVICE_DESCRIPTOR *Descriptor, ULONG ExtensionSize,
+                        PKSDEVICE *Device);
+
+KSDDKAPI NTSTATUS NTAPI KsInitializeDevice
+                       (PDEVICE_OBJECT FunctionalDeviceObject,
+                        PDEVICE_OBJECT PhysicalDeviceObject,
+                        PDEVICE_OBJECT NextDeviceObject,
+                        const KSDEVICE_DESCRIPTOR *Descriptor);
+
+KSDDKAPI void NTAPI KsTerminateDevice (PDEVICE_OBJECT DeviceObject);
+KSDDKAPI PKSDEVICE NTAPI KsGetDeviceForDeviceObject (PDEVICE_OBJECT FunctionalDeviceObject);
+KSDDKAPI void NTAPI KsAcquireDevice (PKSDEVICE Device);
+KSDDKAPI void NTAPI KsReleaseDevice (PKSDEVICE Device);
+
+KSDDKAPI void NTAPI KsDeviceRegisterAdapterObject
+                       (PKSDEVICE Device, PADAPTER_OBJECT AdapterObject,
+                        ULONG MaxMappingsByteCount, ULONG MappingTableStride);
+
+KSDDKAPI ULONG NTAPI KsDeviceGetBusData
+                       (PKSDEVICE Device, ULONG DataType, PVOID Buffer, ULONG Offset,
+                        ULONG Length);
+
+KSDDKAPI ULONG NTAPI KsDeviceSetBusData
+                       (PKSDEVICE Device, ULONG DataType, PVOID Buffer, ULONG Offset,
+                        ULONG Length);
+
+KSDDKAPI NTSTATUS NTAPI KsCreateFilterFactory
+                       (PDEVICE_OBJECT DeviceObject, const KSFILTER_DESCRIPTOR *Descriptor,
+                        PWSTR RefString, PSECURITY_DESCRIPTOR SecurityDescriptor,
+                        ULONG CreateItemFlags, PFNKSFILTERFACTORYPOWER SleepCallback,
+                        PFNKSFILTERFACTORYPOWER WakeCallback,
+                        PKSFILTERFACTORY *FilterFactory);
+
+#define KsDeleteFilterFactory(FilterFactory)                                                                                           \
+       KsFreeObjectCreateItemsByContext( *(KSDEVICE_HEADER *)(                                                                         \
+                                               KsFilterFactoryGetParentDevice(FilterFactory)->FunctionalDeviceObject->DeviceExtension),\
+                                          FilterFactory)
+
+KSDDKAPI NTSTATUS NTAPI KsFilterFactoryUpdateCacheData
+                       (PKSFILTERFACTORY FilterFactory,
+                        const KSFILTER_DESCRIPTOR *FilterDescriptor);
+
+KSDDKAPI NTSTATUS NTAPI KsFilterFactoryAddCreateItem
+                       (PKSFILTERFACTORY FilterFactory, PWSTR RefString,
+                        PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG CreateItemFlags);
+
+KSDDKAPI NTSTATUS NTAPI KsFilterFactorySetDeviceClassesState
+                       (PKSFILTERFACTORY FilterFactory, BOOLEAN NewState);
+
+KSDDKAPI PUNICODE_STRING NTAPI KsFilterFactoryGetSymbolicLink
+                       (PKSFILTERFACTORY FilterFactory);
+
+KSDDKAPI void NTAPI KsAddEvent(PVOID Object, PKSEVENT_ENTRY EventEntry);
+
+void __forceinline KsFilterAddEvent (PKSFILTER Filter, PKSEVENT_ENTRY EventEntry)
+{
+       KsAddEvent(Filter, EventEntry);
+}
+
+void __forceinline KsPinAddEvent (PKSPIN Pin, PKSEVENT_ENTRY EventEntry)
+{
+       KsAddEvent(Pin, EventEntry);
+}
+
+KSDDKAPI NTSTATUS NTAPI KsDefaultAddEventHandler
+                       (PIRP Irp, PKSEVENTDATA EventData, PKSEVENT_ENTRY EventEntry);
+
+KSDDKAPI void NTAPI KsGenerateEvents
+                       (PVOID Object, const GUID *EventSet, ULONG EventId,
+                        ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
+                        PVOID CallBackContext);
+
+void __forceinline KsFilterGenerateEvents
+                       (PKSFILTER Filter, const GUID *EventSet, ULONG EventId,
+                        ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
+                        PVOID CallBackContext)
+{
+       KsGenerateEvents(Filter, EventSet, EventId, DataSize, Data, CallBack,
+                        CallBackContext);
+}
+
+void __forceinline KsPinGenerateEvents
+                       (PKSPIN Pin, const GUID *EventSet, ULONG EventId,
+                        ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
+                        PVOID CallBackContext)
+{
+       KsGenerateEvents(Pin, EventSet, EventId, DataSize, Data, CallBack,
+                        CallBackContext);
+}
+
+typedef enum {
+  KSSTREAM_POINTER_STATE_UNLOCKED = 0,
+  KSSTREAM_POINTER_STATE_LOCKED
+} KSSTREAM_POINTER_STATE;
+
+KSDDKAPI NTSTATUS NTAPI KsPinGetAvailableByteCount
+                       (PKSPIN Pin, PLONG InputDataBytes, PLONG OutputBufferBytes);
+
+KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetLeadingEdgeStreamPointer
+                       (PKSPIN Pin, KSSTREAM_POINTER_STATE State);
+
+KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetTrailingEdgeStreamPointer
+                       (PKSPIN Pin, KSSTREAM_POINTER_STATE State);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamPointerSetStatusCode
+                       (PKSSTREAM_POINTER StreamPointer, NTSTATUS Status);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamPointerLock (PKSSTREAM_POINTER StreamPointer);
+KSDDKAPI void NTAPI KsStreamPointerUnlock(PKSSTREAM_POINTER StreamPointer, BOOLEAN Eject);
+
+KSDDKAPI void NTAPI KsStreamPointerAdvanceOffsetsAndUnlock
+                       (PKSSTREAM_POINTER StreamPointer, ULONG InUsed, ULONG OutUsed,
+                        BOOLEAN Eject);
+
+KSDDKAPI void NTAPI KsStreamPointerDelete (PKSSTREAM_POINTER StreamPointer);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamPointerClone
+                       (PKSSTREAM_POINTER StreamPointer, PFNKSSTREAMPOINTER CancelCallback,
+                        ULONG ContextSize, PKSSTREAM_POINTER *CloneStreamPointer);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamPointerAdvanceOffsets
+                       (PKSSTREAM_POINTER StreamPointer, ULONG InUsed, ULONG OutUsed,
+                        BOOLEAN Eject);
+
+KSDDKAPI NTSTATUS NTAPI KsStreamPointerAdvance (PKSSTREAM_POINTER StreamPointer);
+KSDDKAPI PMDL NTAPI KsStreamPointerGetMdl (PKSSTREAM_POINTER StreamPointer);
+
+KSDDKAPI PIRP NTAPI KsStreamPointerGetIrp
+                       (PKSSTREAM_POINTER StreamPointer, PBOOLEAN FirstFrameInIrp,
+                        PBOOLEAN LastFrameInIrp);
+
+KSDDKAPI void NTAPI KsStreamPointerScheduleTimeout
+                       (PKSSTREAM_POINTER StreamPointer, PFNKSSTREAMPOINTER Callback,
+                        ULONGLONG Interval);
+
+KSDDKAPI void NTAPI KsStreamPointerCancelTimeout (PKSSTREAM_POINTER StreamPointer);
+KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetFirstCloneStreamPointer (PKSPIN Pin);
+
+KSDDKAPI PKSSTREAM_POINTER NTAPI KsStreamPointerGetNextClone
+                       (PKSSTREAM_POINTER StreamPointer);
+
+KSDDKAPI NTSTATUS NTAPI KsPinHandshake(PKSPIN Pin, PKSHANDSHAKE In, PKSHANDSHAKE Out);
+KSDDKAPI void NTAPI KsCompletePendingRequest (PIRP Irp);
+KSDDKAPI KSOBJECTTYPE NTAPI KsGetObjectTypeFromIrp (PIRP Irp);
+KSDDKAPI PVOID NTAPI KsGetObjectFromFileObject (PFILE_OBJECT FileObject);
+KSDDKAPI KSOBJECTTYPE NTAPI KsGetObjectTypeFromFileObject (PFILE_OBJECT FileObject);
+
+PKSFILTER __forceinline KsGetFilterFromFileObject (PFILE_OBJECT FileObject)
+{
+       return (PKSFILTER) KsGetObjectFromFileObject(FileObject);
+}
+
+PKSPIN __forceinline KsGetPinFromFileObject (PFILE_OBJECT FileObject)
+{
+       return (PKSPIN) KsGetObjectFromFileObject(FileObject);
+}
+
+KSDDKAPI PKSGATE NTAPI KsFilterGetAndGate (PKSFILTER Filter);
+KSDDKAPI void NTAPI KsFilterAcquireProcessingMutex (PKSFILTER Filter);
+KSDDKAPI void NTAPI KsFilterReleaseProcessingMutex (PKSFILTER Filter);
+KSDDKAPI void NTAPI KsFilterAttemptProcessing(PKSFILTER Filter, BOOLEAN Asynchronous);
+KSDDKAPI PKSGATE NTAPI KsPinGetAndGate(PKSPIN Pin);
+KSDDKAPI void NTAPI KsPinAttachAndGate(PKSPIN Pin, PKSGATE AndGate);
+KSDDKAPI void NTAPI KsPinAttachOrGate (PKSPIN Pin, PKSGATE OrGate);
+KSDDKAPI void NTAPI KsPinAcquireProcessingMutex (PKSPIN Pin);
+KSDDKAPI void NTAPI KsPinReleaseProcessingMutex (PKSPIN Pin);
+KSDDKAPI BOOLEAN NTAPI KsProcessPinUpdate (PKSPROCESSPIN ProcessPin);
+
+KSDDKAPI void NTAPI KsPinGetCopyRelationships
+                       (PKSPIN Pin, PKSPIN *CopySource, PKSPIN *DelegateBranch);
+
+KSDDKAPI void NTAPI KsPinAttemptProcessing(PKSPIN Pin, BOOLEAN Asynchronous);
+KSDDKAPI PVOID NTAPI KsGetParent (PVOID Object);
+
+PKSDEVICE __forceinline KsFilterFactoryGetParentDevice (PKSFILTERFACTORY FilterFactory)
+{
+       return (PKSDEVICE) KsGetParent((PVOID) FilterFactory);
+}
+
+PKSFILTERFACTORY __forceinline KsFilterGetParentFilterFactory (PKSFILTER Filter)
+{
+       return (PKSFILTERFACTORY) KsGetParent((PVOID) Filter);
+}
+
+KSDDKAPI PKSFILTER NTAPI KsPinGetParentFilter (PKSPIN Pin);
+KSDDKAPI PVOID NTAPI KsGetFirstChild (PVOID Object);
+
+PKSFILTERFACTORY __forceinline KsDeviceGetFirstChildFilterFactory (PKSDEVICE Device)
+{
+       return (PKSFILTERFACTORY) KsGetFirstChild((PVOID) Device);
+}
+
+PKSFILTER __forceinline KsFilterFactoryGetFirstChildFilter (PKSFILTERFACTORY FilterFactory)
+{
+       return (PKSFILTER) KsGetFirstChild((PVOID) FilterFactory);
+}
+
+KSDDKAPI ULONG NTAPI KsFilterGetChildPinCount(PKSFILTER Filter, ULONG PinId);
+KSDDKAPI PKSPIN NTAPI KsFilterGetFirstChildPin(PKSFILTER Filter, ULONG PinId);
+KSDDKAPI PVOID NTAPI KsGetNextSibling (PVOID Object);
+KSDDKAPI PKSPIN NTAPI KsPinGetNextSiblingPin (PKSPIN Pin);
+
+PKSFILTERFACTORY __forceinline KsFilterFactoryGetNextSiblingFilterFactory
+                       (PKSFILTERFACTORY FilterFactory)
+{
+       return (PKSFILTERFACTORY) KsGetNextSibling((PVOID) FilterFactory);
+}
+
+PKSFILTER __forceinline KsFilterGetNextSiblingFilter (PKSFILTER Filter)
+{
+       return (PKSFILTER) KsGetNextSibling((PVOID) Filter);
+}
+
+KSDDKAPI PKSDEVICE NTAPI KsGetDevice (PVOID Object);
+
+PKSDEVICE __forceinline KsFilterFactoryGetDevice (PKSFILTERFACTORY FilterFactory)
+{
+       return KsGetDevice((PVOID) FilterFactory);
+}
+
+PKSDEVICE __forceinline KsFilterGetDevice (PKSFILTER Filter)
+{
+       return KsGetDevice((PVOID) Filter);
+}
+
+PKSDEVICE __forceinline KsPinGetDevice (PKSPIN Pin)
+{
+       return KsGetDevice((PVOID) Pin);
+}
+
+KSDDKAPI PKSFILTER NTAPI KsGetFilterFromIrp (PIRP Irp);
+KSDDKAPI PKSPIN NTAPI KsGetPinFromIrp (PIRP Irp);
+KSDDKAPI ULONG NTAPI KsGetNodeIdFromIrp (PIRP Irp);
+KSDDKAPI void NTAPI KsAcquireControl (PVOID Object);
+KSDDKAPI void NTAPI KsReleaseControl (PVOID Object);
+
+void __forceinline KsFilterAcquireControl (PKSFILTER Filter)
+{
+       KsAcquireControl((PVOID) Filter);
+}
+
+void __forceinline KsFilterReleaseControl (PKSFILTER Filter)
+{
+       KsReleaseControl((PVOID) Filter);
+}
+
+void __forceinline KsPinAcquireControl (PKSPIN Pin)
+{
+       KsAcquireControl((PVOID) Pin);
+}
+
+void __forceinline KsPinReleaseControl (PKSPIN Pin)
+{
+       KsReleaseControl((PVOID) Pin);
+}
+
+KSDDKAPI NTSTATUS NTAPI KsAddItemToObjectBag
+                       (KSOBJECT_BAG ObjectBag, PVOID Item, PFNKSFREE Free);
+
+KSDDKAPI ULONG NTAPI KsRemoveItemFromObjectBag
+                       (KSOBJECT_BAG ObjectBag, PVOID Item, BOOLEAN Free);
+
+#define KsDiscard(Object,Pointer)                                      \
+       KsRemoveItemFromObjectBag((Object)->Bag, (PVOID)(Pointer), TRUE)
+
+KSDDKAPI NTSTATUS NTAPI KsAllocateObjectBag(PKSDEVICE Device, KSOBJECT_BAG *ObjectBag);
+KSDDKAPI void NTAPI KsFreeObjectBag (KSOBJECT_BAG ObjectBag);
+
+KSDDKAPI NTSTATUS NTAPI KsCopyObjectBagItems
+                       (KSOBJECT_BAG ObjectBagDestination, KSOBJECT_BAG ObjectBagSource);
+
+KSDDKAPI NTSTATUS NTAPI _KsEdit
+                       (KSOBJECT_BAG ObjectBag, PVOID *PointerToPointerToItem,
+                        ULONG NewSize, ULONG OldSize, ULONG Tag);
+
+#define KsEdit(Object, PointerToPointer, Tag)                                          \
+       _KsEdit((Object)->Bag, (PVOID*)(PointerToPointer),                              \
+               sizeof(**(PointerToPointer)), sizeof(**(PointerToPointer)), (Tag))
+
+#define KsEditSized(Object, PointerToPointer, NewSize, OldSize, Tag)                   \
+       _KsEdit((Object)->Bag, (PVOID*)(PointerToPointer), (NewSize), (OldSize), (Tag))
+
+KSDDKAPI NTSTATUS NTAPI KsRegisterFilterWithNoKSPins
+                       (PDEVICE_OBJECT DeviceObject, const GUID *InterfaceClassGUID,
+                        ULONG PinCount, WINBOOL *PinDirection, KSPIN_MEDIUM *MediumList,
+                        GUID *CategoryList);
+
+KSDDKAPI NTSTATUS NTAPI KsFilterCreatePinFactory
+                       (PKSFILTER Filter, const KSPIN_DESCRIPTOR_EX *const PinDescriptor,
+                        PULONG PinID);
+
+KSDDKAPI NTSTATUS NTAPI KsFilterCreateNode
+                       (PKSFILTER Filter, const KSNODE_DESCRIPTOR *const NodeDescriptor,
+                        PULONG NodeID);
+
+KSDDKAPI NTSTATUS NTAPI KsFilterAddTopologyConnections
+                       (PKSFILTER Filter, ULONG NewConnectionsCount,
+                        const KSTOPOLOGY_CONNECTION *const NewTopologyConnections);
+
+KSDDKAPI NTSTATUS NTAPI KsPinGetConnectedPinInterface
+                       (PKSPIN Pin, const GUID *InterfaceId, PVOID *Interface);
+
+KSDDKAPI PFILE_OBJECT NTAPI KsPinGetConnectedPinFileObject (PKSPIN Pin);
+KSDDKAPI PDEVICE_OBJECT NTAPI KsPinGetConnectedPinDeviceObject (PKSPIN Pin);
+
+KSDDKAPI NTSTATUS NTAPI KsPinGetConnectedFilterInterface
+                       (PKSPIN Pin, const GUID *InterfaceId, PVOID *Interface);
+
+#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
+KSDDKAPI NTSTATUS NTAPI KsPinGetReferenceClockInterface
+                       (PKSPIN Pin, PIKSREFERENCECLOCK *Interface);
+#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
+
+KSDDKAPI VOID NTAPI KsPinSetPinClockTime(PKSPIN Pin, LONGLONG Time);
+
+KSDDKAPI NTSTATUS NTAPI KsPinSubmitFrame
+                       (PKSPIN Pin, PVOID Data, ULONG Size,
+                        PKSSTREAM_HEADER StreamHeader, PVOID Context);
+
+KSDDKAPI NTSTATUS NTAPI KsPinSubmitFrameMdl
+                       (PKSPIN Pin, PMDL Mdl, PKSSTREAM_HEADER StreamHeader,
+                        PVOID Context);
+
+KSDDKAPI void NTAPI KsPinRegisterFrameReturnCallback
+                       (PKSPIN Pin, PFNKSPINFRAMERETURN FrameReturn);
+
+KSDDKAPI void NTAPI KsPinRegisterIrpCompletionCallback
+                       (PKSPIN Pin, PFNKSPINIRPCOMPLETION IrpCompletion);
+
+KSDDKAPI void NTAPI KsPinRegisterHandshakeCallback
+                       (PKSPIN Pin, PFNKSPINHANDSHAKE Handshake);
+
+KSDDKAPI void NTAPI KsFilterRegisterPowerCallbacks
+                       (PKSFILTER Filter, PFNKSFILTERPOWER Sleep, PFNKSFILTERPOWER Wake);
+
+KSDDKAPI void NTAPI KsPinRegisterPowerCallbacks
+                       (PKSPIN Pin, PFNKSPINPOWER Sleep, PFNKSPINPOWER Wake);
+
+#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
+KSDDKAPI PUNKNOWN NTAPI KsRegisterAggregatedClientUnknown
+                       (PVOID Object, PUNKNOWN ClientUnknown);
+
+KSDDKAPI PUNKNOWN NTAPI KsGetOuterUnknown (PVOID Object);
+
+PUNKNOWN __forceinline KsDeviceRegisterAggregatedClientUnknown
+                       (PKSDEVICE Device, PUNKNOWN ClientUnknown)
+{
+       return KsRegisterAggregatedClientUnknown((PVOID)Device, ClientUnknown);
+}
+
+PUNKNOWN __forceinline KsDeviceGetOuterUnknown (PKSDEVICE Device)
+{
+       return KsGetOuterUnknown((PVOID) Device);
+}
+
+PUNKNOWN __forceinline KsFilterFactoryRegisterAggregatedClientUnknown
+                       (PKSFILTERFACTORY FilterFactory, PUNKNOWN ClientUnknown)
+{
+       return KsRegisterAggregatedClientUnknown((PVOID)FilterFactory, ClientUnknown);
+}
+
+PUNKNOWN __forceinline KsFilterFactoryGetOuterUnknown (PKSFILTERFACTORY FilterFactory)
+{
+       return KsGetOuterUnknown((PVOID)FilterFactory);
+}
+
+PUNKNOWN __forceinline KsFilterRegisterAggregatedClientUnknown
+                       (PKSFILTER Filter, PUNKNOWN ClientUnknown)
+{
+       return KsRegisterAggregatedClientUnknown((PVOID)Filter, ClientUnknown);
+}
+
+PUNKNOWN __forceinline KsFilterGetOuterUnknown (PKSFILTER Filter)
+{
+       return KsGetOuterUnknown((PVOID)Filter);
+}
+
+PUNKNOWN __forceinline KsPinRegisterAggregatedClientUnknown
+                       (PKSPIN Pin, PUNKNOWN ClientUnknown)
+{
+       return KsRegisterAggregatedClientUnknown((PVOID)Pin, ClientUnknown);
+}
+
+PUNKNOWN __forceinline KsPinGetOuterUnknown (PKSPIN Pin)
+{
+       return KsGetOuterUnknown((PVOID)Pin);
+}
+#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
+
+#else /* _NTDDK_ */
+
+#ifndef KS_NO_CREATE_FUNCTIONS
+KSDDKAPI DWORD WINAPI KsCreateAllocator(HANDLE ConnectionHandle,PKSALLOCATOR_FRAMING AllocatorFraming,PHANDLE AllocatorHandle);
+KSDDKAPI DWORD NTAPI KsCreateClock(HANDLE ConnectionHandle,PKSCLOCK_CREATE ClockCreate,PHANDLE ClockHandle);
+KSDDKAPI DWORD WINAPI KsCreatePin(HANDLE FilterHandle,PKSPIN_CONNECT Connect,ACCESS_MASK DesiredAccess,PHANDLE ConnectionHandle);
+KSDDKAPI DWORD WINAPI KsCreateTopologyNode(HANDLE ParentHandle,PKSNODE_CREATE NodeCreate,ACCESS_MASK DesiredAccess,PHANDLE NodeHandle);
+#endif
+
+#endif /* _NTDDK_ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#define DENY_USERMODE_ACCESS(pIrp,CompleteRequest)                     \
+       if(pIrp->RequestorMode!=KernelMode) {                           \
+               pIrp->IoStatus.Information = 0;                         \
+               pIrp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;  \
+               if(CompleteRequest)                                     \
+                       IoCompleteRequest (pIrp,IO_NO_INCREMENT);       \
+               return STATUS_INVALID_DEVICE_REQUEST;                   \
+       }
+
+#endif /* _KS_ */
+
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h b/portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h
new file mode 100644 (file)
index 0000000..f029b01
--- /dev/null
@@ -0,0 +1,4610 @@
+/**
+ * This file has no copyright assigned and is placed in the Public Domain.
+ * This file is part of the w64 mingw-runtime package.
+ * No warranty is given; refer to the file DISCLAIMER.PD within this package.
+ */
+#if !defined(_KS_)
+#warning ks.h must be included before ksmedia.h
+#include "ks.h"
+#endif
+
+#if __GNUC__ >= 3
+#pragma GCC system_header
+#endif
+
+#if !defined(_KSMEDIA_)
+#define _KSMEDIA_
+
+typedef struct {
+  KSPROPERTY Property;
+  KSMULTIPLE_ITEM MultipleItem;
+} KSMULTIPLE_DATA_PROP,*PKSMULTIPLE_DATA_PROP;
+
+#define STATIC_KSMEDIUMSETID_MidiBus                                   \
+       0x05908040L,0x3246,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("05908040-3246-11D0-A5D6-28DB04C10000",KSMEDIUMSETID_MidiBus);
+#define KSMEDIUMSETID_MidiBus DEFINE_GUIDNAMED(KSMEDIUMSETID_MidiBus)
+
+#define STATIC_KSMEDIUMSETID_VPBus                                     \
+       0xA18C15ECL,0xCE43,0x11D0,0xAB,0xE7,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("A18C15EC-CE43-11D0-ABE7-00A0C9223196",KSMEDIUMSETID_VPBus);
+#define KSMEDIUMSETID_VPBus DEFINE_GUIDNAMED(KSMEDIUMSETID_VPBus)
+
+#define STATIC_KSINTERFACESETID_Media                                  \
+       0x3A13EB40L,0x30A7,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("3A13EB40-30A7-11D0-A5D6-28DB04C10000",KSINTERFACESETID_Media);
+#define KSINTERFACESETID_Media DEFINE_GUIDNAMED(KSINTERFACESETID_Media)
+
+typedef enum {
+  KSINTERFACE_MEDIA_MUSIC,
+  KSINTERFACE_MEDIA_WAVE_BUFFERED,
+  KSINTERFACE_MEDIA_WAVE_QUEUED
+} KSINTERFACE_MEDIA;
+
+#ifndef INIT_USBAUDIO_MID
+#define INIT_USBAUDIO_MID(guid,id)                                     \
+{                                                                      \
+       (guid)->Data1 = 0x4e1cecd2 + (USHORT)(id);                      \
+       (guid)->Data2 = 0x1679;                                         \
+       (guid)->Data3 = 0x463b;                                         \
+       (guid)->Data4[0] = 0xa7;                                        \
+       (guid)->Data4[1] = 0x2f;                                        \
+       (guid)->Data4[2] = 0xa5;                                        \
+       (guid)->Data4[3] = 0xbf;                                        \
+       (guid)->Data4[4] = 0x64;                                        \
+       (guid)->Data4[5] = 0xc8;                                        \
+       (guid)->Data4[6] = 0x6e;                                        \
+       (guid)->Data4[7] = 0xba;                                        \
+}
+#define EXTRACT_USBAUDIO_MID(guid)                                     \
+       (USHORT)((guid)->Data1 - 0x4e1cecd2)
+#define DEFINE_USBAUDIO_MID_GUID(id)                                   \
+       0x4e1cecd2+(USHORT)(id),0x1679,0x463b,0xa7,0x2f,0xa5,0xbf,0x64,0xc8,0x6e,0xba
+#define IS_COMPATIBLE_USBAUDIO_MID(guid)                               \
+       (((guid)->Data1 >= 0x4e1cecd2) &&                               \
+        ((guid)->Data1 < 0x4e1cecd2 + 0xffff) &&                       \
+        ((guid)->Data2 == 0x1679) &&                                   \
+        ((guid)->Data3 == 0x463b) &&                                   \
+        ((guid)->Data4[0] == 0xa7) &&                                  \
+        ((guid)->Data4[1] == 0x2f) &&                                  \
+        ((guid)->Data4[2] == 0xa5) &&                                  \
+        ((guid)->Data4[3] == 0xbf) &&                                  \
+        ((guid)->Data4[4] == 0x64) &&                                  \
+        ((guid)->Data4[5] == 0xc8) &&                                  \
+        ((guid)->Data4[6] == 0x6e) &&                                  \
+        ((guid)->Data4[7] == 0xba) )
+#endif /* INIT_USBAUDIO_MID */
+
+#ifndef INIT_USBAUDIO_PID
+#define INIT_USBAUDIO_PID(guid,id)                                     \
+{                                                                      \
+       (guid)->Data1 = 0xabcc5a5e + (USHORT)(id);                      \
+       (guid)->Data2 = 0xc263;                                         \
+       (guid)->Data3 = 0x463b;                                         \
+       (guid)->Data4[0] = 0xa7;                                        \
+       (guid)->Data4[1] = 0x2f;                                        \
+       (guid)->Data4[2] = 0xa5;                                        \
+       (guid)->Data4[3] = 0xbf;                                        \
+       (guid)->Data4[4] = 0x64;                                        \
+       (guid)->Data4[5] = 0xc8;                                        \
+       (guid)->Data4[6] = 0x6e;                                        \
+       (guid)->Data4[7] = 0xba;                                        \
+}
+#define EXTRACT_USBAUDIO_PID(guid)                                     \
+       (USHORT)((guid)->Data1 - 0xabcc5a5e)
+#define DEFINE_USBAUDIO_PID_GUID(id)                                   \
+       0xabcc5a5e+(USHORT)(id),0xc263,0x463b,0xa7,0x2f,0xa5,0xbf,0x64,0xc8,0x6e,0xba
+#define IS_COMPATIBLE_USBAUDIO_PID(guid)                               \
+       (((guid)->Data1 >= 0xabcc5a5e) &&                               \
+        ((guid)->Data1 < 0xabcc5a5e + 0xffff) &&                       \
+        ((guid)->Data2 == 0xc263) &&                                   \
+        ((guid)->Data3 == 0x463b) &&                                   \
+        ((guid)->Data4[0] == 0xa7) &&                                  \
+        ((guid)->Data4[1] == 0x2f) &&                                  \
+        ((guid)->Data4[2] == 0xa5) &&                                  \
+        ((guid)->Data4[3] == 0xbf) &&                                  \
+        ((guid)->Data4[4] == 0x64) &&                                  \
+        ((guid)->Data4[5] == 0xc8) &&                                  \
+        ((guid)->Data4[6] == 0x6e) &&                                  \
+        ((guid)->Data4[7] == 0xba) )
+#endif /* INIT_USBAUDIO_PID */
+
+#ifndef INIT_USBAUDIO_PRODUCT_NAME
+#define INIT_USBAUDIO_PRODUCT_NAME(guid,vid,pid,strIndex)              \
+{                                                                      \
+       (guid)->Data1 = 0XFC575048 + (USHORT)(vid);                     \
+       (guid)->Data2 = 0x2E08 + (USHORT)(pid);                         \
+       (guid)->Data3 = 0x463B + (USHORT)(strIndex);                    \
+       (guid)->Data4[0] = 0xA7;                                        \
+       (guid)->Data4[1] = 0x2F;                                        \
+       (guid)->Data4[2] = 0xA5;                                        \
+       (guid)->Data4[3] = 0xBF;                                        \
+       (guid)->Data4[4] = 0x64;                                        \
+       (guid)->Data4[5] = 0xC8;                                        \
+       (guid)->Data4[6] = 0x6E;                                        \
+       (guid)->Data4[7] = 0xBA;                                        \
+}
+#define DEFINE_USBAUDIO_PRODUCT_NAME(vid,pid,strIndex)                 \
+       0xFC575048+(USHORT)(vid),0x2E08+(USHORT)(pid),0x463B+(USHORT)(strIndex),0xA7,0x2F,0xA5,0xBF,0x64,0xC8,0x6E,0xBA
+#endif /* INIT_USBAUDIO_PRODUCT_NAME */
+
+#define STATIC_KSCOMPONENTID_USBAUDIO                                  \
+       0x8F1275F0,0x26E9,0x4264,0xBA,0x4D,0x39,0xFF,0xF0,0x1D,0x94,0xAA
+DEFINE_GUIDSTRUCT("8F1275F0-26E9-4264-BA4D-39FFF01D94AA",KSCOMPONENTID_USBAUDIO);
+#define KSCOMPONENTID_USBAUDIO DEFINE_GUIDNAMED(KSCOMPONENTID_USBAUDIO)
+
+#define INIT_USB_TERMINAL(guid,id)                                     \
+{                                                                      \
+       (guid)->Data1 = 0xDFF219E0 + (USHORT)(id);                      \
+       (guid)->Data2 = 0xF70F;                                         \
+       (guid)->Data3 = 0x11D0;                                         \
+       (guid)->Data4[0] = 0xb9;                                        \
+       (guid)->Data4[1] = 0x17;                                        \
+       (guid)->Data4[2] = 0x00;                                        \
+       (guid)->Data4[3] = 0xa0;                                        \
+       (guid)->Data4[4] = 0xc9;                                        \
+       (guid)->Data4[5] = 0x22;                                        \
+       (guid)->Data4[6] = 0x31;                                        \
+       (guid)->Data4[7] = 0x96;                                        \
+}
+#define EXTRACT_USB_TERMINAL(guid)                                     \
+       (USHORT)((guid)->Data1 - 0xDFF219E0)
+#define DEFINE_USB_TERMINAL_GUID(id)                                   \
+       0xDFF219E0+(USHORT)(id),0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+
+#define STATIC_KSNODETYPE_MICROPHONE                                   \
+       DEFINE_USB_TERMINAL_GUID(0x0201)
+DEFINE_GUIDSTRUCT("DFF21BE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MICROPHONE);
+#define KSNODETYPE_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_MICROPHONE)
+
+#define STATIC_KSNODETYPE_DESKTOP_MICROPHONE                           \
+       DEFINE_USB_TERMINAL_GUID(0x0202)
+DEFINE_GUIDSTRUCT("DFF21BE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DESKTOP_MICROPHONE);
+#define KSNODETYPE_DESKTOP_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_DESKTOP_MICROPHONE)
+
+#define STATIC_KSNODETYPE_PERSONAL_MICROPHONE                          \
+       DEFINE_USB_TERMINAL_GUID(0x0203)
+DEFINE_GUIDSTRUCT("DFF21BE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PERSONAL_MICROPHONE);
+#define KSNODETYPE_PERSONAL_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_PERSONAL_MICROPHONE)
+
+#define STATIC_KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE                  \
+       DEFINE_USB_TERMINAL_GUID(0x0204)
+DEFINE_GUIDSTRUCT("DFF21BE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE);
+#define KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE)
+
+#define STATIC_KSNODETYPE_MICROPHONE_ARRAY                             \
+       DEFINE_USB_TERMINAL_GUID(0x0205)
+DEFINE_GUIDSTRUCT("DFF21BE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MICROPHONE_ARRAY);
+#define KSNODETYPE_MICROPHONE_ARRAY DEFINE_GUIDNAMED(KSNODETYPE_MICROPHONE_ARRAY)
+
+#define STATIC_KSNODETYPE_PROCESSING_MICROPHONE_ARRAY                  \
+       DEFINE_USB_TERMINAL_GUID(0x0206)
+DEFINE_GUIDSTRUCT("DFF21BE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PROCESSING_MICROPHONE_ARRAY);
+#define KSNODETYPE_PROCESSING_MICROPHONE_ARRAY DEFINE_GUIDNAMED(KSNODETYPE_PROCESSING_MICROPHONE_ARRAY)
+
+#define STATIC_KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR                   \
+       0x830a44f2,0xa32d,0x476b,0xbe,0x97,0x42,0x84,0x56,0x73,0xb3,0x5a
+DEFINE_GUIDSTRUCT("830a44f2-a32d-476b-be97-42845673b35a",KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR);
+#define KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR DEFINE_GUIDNAMED(KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR)
+
+#define STATIC_KSNODETYPE_SPEAKER                                      \
+       DEFINE_USB_TERMINAL_GUID(0x0301)
+DEFINE_GUIDSTRUCT("DFF21CE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPEAKER);
+#define KSNODETYPE_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_SPEAKER)
+
+#define STATIC_KSNODETYPE_HEADPHONES                                   \
+       DEFINE_USB_TERMINAL_GUID(0x0302)
+DEFINE_GUIDSTRUCT("DFF21CE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEADPHONES);
+#define KSNODETYPE_HEADPHONES DEFINE_GUIDNAMED(KSNODETYPE_HEADPHONES)
+
+#define STATIC_KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO                   \
+       DEFINE_USB_TERMINAL_GUID(0x0303)
+DEFINE_GUIDSTRUCT("DFF21CE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO);
+#define KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO)
+
+#define STATIC_KSNODETYPE_DESKTOP_SPEAKER                              \
+       DEFINE_USB_TERMINAL_GUID(0x0304)
+DEFINE_GUIDSTRUCT("DFF21CE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DESKTOP_SPEAKER);
+#define KSNODETYPE_DESKTOP_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_DESKTOP_SPEAKER)
+
+#define STATIC_KSNODETYPE_ROOM_SPEAKER                                 \
+       DEFINE_USB_TERMINAL_GUID(0x0305)
+DEFINE_GUIDSTRUCT("DFF21CE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ROOM_SPEAKER);
+#define KSNODETYPE_ROOM_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_ROOM_SPEAKER)
+
+#define STATIC_KSNODETYPE_COMMUNICATION_SPEAKER                                \
+       DEFINE_USB_TERMINAL_GUID(0x0306)
+DEFINE_GUIDSTRUCT("DFF21CE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_COMMUNICATION_SPEAKER);
+#define KSNODETYPE_COMMUNICATION_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_COMMUNICATION_SPEAKER)
+
+#define STATIC_KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER                        \
+       DEFINE_USB_TERMINAL_GUID(0x0307)
+DEFINE_GUIDSTRUCT("DFF21CE7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER);
+#define KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER)
+
+#define STATIC_KSNODETYPE_HANDSET                                      \
+       DEFINE_USB_TERMINAL_GUID(0x0401)
+DEFINE_GUIDSTRUCT("DFF21DE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HANDSET);
+#define KSNODETYPE_HANDSET DEFINE_GUIDNAMED(KSNODETYPE_HANDSET)
+
+#define STATIC_KSNODETYPE_HEADSET                                      \
+       DEFINE_USB_TERMINAL_GUID(0x0402)
+DEFINE_GUIDSTRUCT("DFF21DE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEADSET);
+#define KSNODETYPE_HEADSET DEFINE_GUIDNAMED(KSNODETYPE_HEADSET)
+
+#define STATIC_KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION               \
+       DEFINE_USB_TERMINAL_GUID(0x0403)
+DEFINE_GUIDSTRUCT("DFF21DE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION);
+#define KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION DEFINE_GUIDNAMED(KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION)
+
+#define STATIC_KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE                        \
+       DEFINE_USB_TERMINAL_GUID(0x0404)
+DEFINE_GUIDSTRUCT("DFF21DE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE);
+#define KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE DEFINE_GUIDNAMED(KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE)
+
+#define STATIC_KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE                  \
+       DEFINE_USB_TERMINAL_GUID(0x0405)
+DEFINE_GUIDSTRUCT("DFF21DE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE);
+#define KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE DEFINE_GUIDNAMED(KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE)
+
+#define STATIC_KSNODETYPE_PHONE_LINE                                   \
+       DEFINE_USB_TERMINAL_GUID(0x0501)
+DEFINE_GUIDSTRUCT("DFF21EE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PHONE_LINE);
+#define KSNODETYPE_PHONE_LINE DEFINE_GUIDNAMED(KSNODETYPE_PHONE_LINE)
+
+#define STATIC_KSNODETYPE_TELEPHONE                                    \
+       DEFINE_USB_TERMINAL_GUID(0x0502)
+DEFINE_GUIDSTRUCT("DFF21EE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_TELEPHONE);
+#define KSNODETYPE_TELEPHONE DEFINE_GUIDNAMED(KSNODETYPE_TELEPHONE)
+
+#define STATIC_KSNODETYPE_DOWN_LINE_PHONE                              \
+       DEFINE_USB_TERMINAL_GUID(0x0503)
+DEFINE_GUIDSTRUCT("DFF21EE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DOWN_LINE_PHONE);
+#define KSNODETYPE_DOWN_LINE_PHONE DEFINE_GUIDNAMED(KSNODETYPE_DOWN_LINE_PHONE)
+
+#define STATIC_KSNODETYPE_ANALOG_CONNECTOR                             \
+       DEFINE_USB_TERMINAL_GUID(0x601)
+DEFINE_GUIDSTRUCT("DFF21FE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ANALOG_CONNECTOR);
+#define KSNODETYPE_ANALOG_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_ANALOG_CONNECTOR)
+
+#define STATIC_KSNODETYPE_DIGITAL_AUDIO_INTERFACE                      \
+       DEFINE_USB_TERMINAL_GUID(0x0602)
+DEFINE_GUIDSTRUCT("DFF21FE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DIGITAL_AUDIO_INTERFACE);
+#define KSNODETYPE_DIGITAL_AUDIO_INTERFACE DEFINE_GUIDNAMED(KSNODETYPE_DIGITAL_AUDIO_INTERFACE)
+
+#define STATIC_KSNODETYPE_LINE_CONNECTOR                               \
+       DEFINE_USB_TERMINAL_GUID(0x0603)
+DEFINE_GUIDSTRUCT("DFF21FE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LINE_CONNECTOR);
+#define KSNODETYPE_LINE_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_LINE_CONNECTOR)
+
+#define STATIC_KSNODETYPE_LEGACY_AUDIO_CONNECTOR                       \
+       DEFINE_USB_TERMINAL_GUID(0x0604)
+DEFINE_GUIDSTRUCT("DFF21FE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LEGACY_AUDIO_CONNECTOR);
+#define KSNODETYPE_LEGACY_AUDIO_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_LEGACY_AUDIO_CONNECTOR)
+
+#define STATIC_KSNODETYPE_SPDIF_INTERFACE                              \
+       DEFINE_USB_TERMINAL_GUID(0x0605)
+DEFINE_GUIDSTRUCT("DFF21FE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPDIF_INTERFACE);
+#define KSNODETYPE_SPDIF_INTERFACE DEFINE_GUIDNAMED(KSNODETYPE_SPDIF_INTERFACE)
+
+#define STATIC_KSNODETYPE_1394_DA_STREAM                               \
+       DEFINE_USB_TERMINAL_GUID(0x0606)
+DEFINE_GUIDSTRUCT("DFF21FE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_1394_DA_STREAM);
+#define KSNODETYPE_1394_DA_STREAM DEFINE_GUIDNAMED(KSNODETYPE_1394_DA_STREAM)
+
+#define STATIC_KSNODETYPE_1394_DV_STREAM_SOUNDTRACK                    \
+       DEFINE_USB_TERMINAL_GUID(0x0607)
+DEFINE_GUIDSTRUCT("DFF21FE7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_1394_DV_STREAM_SOUNDTRACK);
+#define KSNODETYPE_1394_DV_STREAM_SOUNDTRACK DEFINE_GUIDNAMED(KSNODETYPE_1394_DV_STREAM_SOUNDTRACK)
+
+#define STATIC_KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE               \
+       DEFINE_USB_TERMINAL_GUID(0x0701)
+DEFINE_GUIDSTRUCT("DFF220E1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE);
+#define KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE DEFINE_GUIDNAMED(KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE)
+
+#define STATIC_KSNODETYPE_EQUALIZATION_NOISE                           \
+       DEFINE_USB_TERMINAL_GUID(0x0702)
+DEFINE_GUIDSTRUCT("DFF220E2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_EQUALIZATION_NOISE);
+#define KSNODETYPE_EQUALIZATION_NOISE DEFINE_GUIDNAMED(KSNODETYPE_EQUALIZATION_NOISE)
+
+#define STATIC_KSNODETYPE_CD_PLAYER                                    \
+       DEFINE_USB_TERMINAL_GUID(0x0703)
+DEFINE_GUIDSTRUCT("DFF220E3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_CD_PLAYER);
+#define KSNODETYPE_CD_PLAYER DEFINE_GUIDNAMED(KSNODETYPE_CD_PLAYER)
+
+#define STATIC_KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE                    \
+       DEFINE_USB_TERMINAL_GUID(0x0704)
+DEFINE_GUIDSTRUCT("DFF220E4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE);
+#define KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE DEFINE_GUIDNAMED(KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE)
+
+#define STATIC_KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE              \
+       DEFINE_USB_TERMINAL_GUID(0x0705)
+DEFINE_GUIDSTRUCT("DFF220E5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE);
+#define KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE DEFINE_GUIDNAMED(KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE)
+
+#define STATIC_KSNODETYPE_MINIDISK                                     \
+       DEFINE_USB_TERMINAL_GUID(0x0706)
+DEFINE_GUIDSTRUCT("DFF220E6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MINIDISK);
+#define KSNODETYPE_MINIDISK DEFINE_GUIDNAMED(KSNODETYPE_MINIDISK)
+
+#define STATIC_KSNODETYPE_ANALOG_TAPE                                  \
+       DEFINE_USB_TERMINAL_GUID(0x0707)
+DEFINE_GUIDSTRUCT("DFF220E7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ANALOG_TAPE);
+#define KSNODETYPE_ANALOG_TAPE DEFINE_GUIDNAMED(KSNODETYPE_ANALOG_TAPE)
+
+#define STATIC_KSNODETYPE_PHONOGRAPH                                   \
+       DEFINE_USB_TERMINAL_GUID(0x0708)
+DEFINE_GUIDSTRUCT("DFF220E8-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PHONOGRAPH);
+#define KSNODETYPE_PHONOGRAPH DEFINE_GUIDNAMED(KSNODETYPE_PHONOGRAPH)
+
+#define STATIC_KSNODETYPE_VCR_AUDIO                                    \
+       DEFINE_USB_TERMINAL_GUID(0x0708)
+DEFINE_GUIDSTRUCT("DFF220E9-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VCR_AUDIO);
+#define KSNODETYPE_VCR_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_VCR_AUDIO)
+
+#define STATIC_KSNODETYPE_VIDEO_DISC_AUDIO                             \
+       DEFINE_USB_TERMINAL_GUID(0x070A)
+DEFINE_GUIDSTRUCT("DFF220EA-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_DISC_AUDIO);
+#define KSNODETYPE_VIDEO_DISC_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_DISC_AUDIO)
+
+#define STATIC_KSNODETYPE_DVD_AUDIO                                    \
+       DEFINE_USB_TERMINAL_GUID(0x070B)
+DEFINE_GUIDSTRUCT("DFF220EB-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DVD_AUDIO);
+#define KSNODETYPE_DVD_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_DVD_AUDIO)
+
+#define STATIC_KSNODETYPE_TV_TUNER_AUDIO                               \
+       DEFINE_USB_TERMINAL_GUID(0x070C)
+DEFINE_GUIDSTRUCT("DFF220EC-F70F-11D0-B917-00A0C9223196",KSNODETYPE_TV_TUNER_AUDIO);
+#define KSNODETYPE_TV_TUNER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_TV_TUNER_AUDIO)
+
+#define STATIC_KSNODETYPE_SATELLITE_RECEIVER_AUDIO                     \
+       DEFINE_USB_TERMINAL_GUID(0x070D)
+DEFINE_GUIDSTRUCT("DFF220ED-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SATELLITE_RECEIVER_AUDIO);
+#define KSNODETYPE_SATELLITE_RECEIVER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_SATELLITE_RECEIVER_AUDIO)
+
+#define STATIC_KSNODETYPE_CABLE_TUNER_AUDIO                            \
+       DEFINE_USB_TERMINAL_GUID(0x070E)
+DEFINE_GUIDSTRUCT("DFF220EE-F70F-11D0-B917-00A0C9223196",KSNODETYPE_CABLE_TUNER_AUDIO);
+#define KSNODETYPE_CABLE_TUNER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_CABLE_TUNER_AUDIO)
+
+#define STATIC_KSNODETYPE_DSS_AUDIO                                    \
+       DEFINE_USB_TERMINAL_GUID(0x070F)
+DEFINE_GUIDSTRUCT("DFF220EF-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DSS_AUDIO);
+#define KSNODETYPE_DSS_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_DSS_AUDIO)
+
+#define STATIC_KSNODETYPE_RADIO_RECEIVER                               \
+       DEFINE_USB_TERMINAL_GUID(0x0710)
+DEFINE_GUIDSTRUCT("DFF220F0-F70F-11D0-B917-00A0C9223196",KSNODETYPE_RADIO_RECEIVER);
+#define KSNODETYPE_RADIO_RECEIVER DEFINE_GUIDNAMED(KSNODETYPE_RADIO_RECEIVER)
+
+#define STATIC_KSNODETYPE_RADIO_TRANSMITTER                            \
+       DEFINE_USB_TERMINAL_GUID(0x0711)
+DEFINE_GUIDSTRUCT("DFF220F1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_RADIO_TRANSMITTER);
+#define KSNODETYPE_RADIO_TRANSMITTER DEFINE_GUIDNAMED(KSNODETYPE_RADIO_TRANSMITTER)
+
+#define STATIC_KSNODETYPE_MULTITRACK_RECORDER                          \
+       DEFINE_USB_TERMINAL_GUID(0x0712)
+DEFINE_GUIDSTRUCT("DFF220F2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MULTITRACK_RECORDER);
+#define KSNODETYPE_MULTITRACK_RECORDER DEFINE_GUIDNAMED(KSNODETYPE_MULTITRACK_RECORDER)
+
+#define STATIC_KSNODETYPE_SYNTHESIZER                                  \
+       DEFINE_USB_TERMINAL_GUID(0x0713)
+DEFINE_GUIDSTRUCT("DFF220F3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SYNTHESIZER);
+#define KSNODETYPE_SYNTHESIZER DEFINE_GUIDNAMED(KSNODETYPE_SYNTHESIZER)
+
+#define STATIC_KSNODETYPE_SWSYNTH                                      \
+       0x423274A0L,0x8B81,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("423274A0-8B81-11D1-A050-0000F8004788",KSNODETYPE_SWSYNTH);
+#define KSNODETYPE_SWSYNTH DEFINE_GUIDNAMED(KSNODETYPE_SWSYNTH)
+
+#define STATIC_KSNODETYPE_SWMIDI                                       \
+       0xCB9BEFA0L,0xA251,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("CB9BEFA0-A251-11D1-A050-0000F8004788",KSNODETYPE_SWMIDI);
+#define KSNODETYPE_SWMIDI DEFINE_GUIDNAMED(KSNODETYPE_SWMIDI)
+
+#define STATIC_KSNODETYPE_DRM_DESCRAMBLE                               \
+       0xFFBB6E3FL,0xCCFE,0x4D84,0x90,0xD9,0x42,0x14,0x18,0xB0,0x3A,0x8E
+DEFINE_GUIDSTRUCT("FFBB6E3F-CCFE-4D84-90D9-421418B03A8E",KSNODETYPE_DRM_DESCRAMBLE);
+#define KSNODETYPE_DRM_DESCRAMBLE DEFINE_GUIDNAMED(KSNODETYPE_DRM_DESCRAMBLE)
+
+#define STATIC_KSCATEGORY_AUDIO                                                \
+       0x6994AD04L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("6994AD04-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_AUDIO);
+#define KSCATEGORY_AUDIO DEFINE_GUIDNAMED(KSCATEGORY_AUDIO)
+
+#define STATIC_KSCATEGORY_VIDEO                                                \
+       0x6994AD05L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("6994AD05-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_VIDEO);
+#define KSCATEGORY_VIDEO DEFINE_GUIDNAMED(KSCATEGORY_VIDEO)
+
+/* Added for Vista and later */
+#define STATIC_KSCATEGORY_REALTIME \
+    0xEB115FFCL, 0x10C8, 0x4964, 0x83, 0x1D, 0x6D, 0xCB, 0x02, 0xE6, 0xF2, 0x3F
+DEFINE_GUIDSTRUCT("EB115FFC-10C8-4964-831D-6DCB02E6F23F", KSCATEGORY_REALTIME);
+#define KSCATEGORY_REALTIME DEFINE_GUIDNAMED(KSCATEGORY_REALTIME)
+
+#define STATIC_KSCATEGORY_TEXT                                         \
+       0x6994AD06L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("6994AD06-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_TEXT);
+#define KSCATEGORY_TEXT DEFINE_GUIDNAMED(KSCATEGORY_TEXT)
+
+#define STATIC_KSCATEGORY_NETWORK                                      \
+       0x67C9CC3CL,0x69C4,0x11D2,0x87,0x59,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("67C9CC3C-69C4-11D2-8759-00A0C9223196",KSCATEGORY_NETWORK);
+#define KSCATEGORY_NETWORK DEFINE_GUIDNAMED(KSCATEGORY_NETWORK)
+
+#define STATIC_KSCATEGORY_TOPOLOGY                                     \
+       0xDDA54A40L,0x1E4C,0x11D1,0xA0,0x50,0x40,0x57,0x05,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("DDA54A40-1E4C-11D1-A050-405705C10000",KSCATEGORY_TOPOLOGY);
+#define KSCATEGORY_TOPOLOGY DEFINE_GUIDNAMED(KSCATEGORY_TOPOLOGY)
+
+#define STATIC_KSCATEGORY_VIRTUAL                                      \
+       0x3503EAC4L,0x1F26,0x11D1,0x8A,0xB0,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("3503EAC4-1F26-11D1-8AB0-00A0C9223196",KSCATEGORY_VIRTUAL);
+#define KSCATEGORY_VIRTUAL DEFINE_GUIDNAMED(KSCATEGORY_VIRTUAL)
+
+#define STATIC_KSCATEGORY_ACOUSTIC_ECHO_CANCEL                         \
+       0xBF963D80L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("BF963D80-C559-11D0-8A2B-00A0C9255AC1",KSCATEGORY_ACOUSTIC_ECHO_CANCEL);
+#define KSCATEGORY_ACOUSTIC_ECHO_CANCEL DEFINE_GUIDNAMED(KSCATEGORY_ACOUSTIC_ECHO_CANCEL)
+
+#define STATIC_KSCATEGORY_SYSAUDIO                                     \
+       0xA7C7A5B1L,0x5AF3,0x11D1,0x9C,0xED,0x00,0xA0,0x24,0xBF,0x04,0x07
+DEFINE_GUIDSTRUCT("A7C7A5B1-5AF3-11D1-9CED-00A024BF0407",KSCATEGORY_SYSAUDIO);
+#define KSCATEGORY_SYSAUDIO DEFINE_GUIDNAMED(KSCATEGORY_SYSAUDIO)
+
+#define STATIC_KSCATEGORY_WDMAUD                                       \
+       0x3E227E76L,0x690D,0x11D2,0x81,0x61,0x00,0x00,0xF8,0x77,0x5B,0xF1
+DEFINE_GUIDSTRUCT("3E227E76-690D-11D2-8161-0000F8775BF1",KSCATEGORY_WDMAUD);
+#define KSCATEGORY_WDMAUD DEFINE_GUIDNAMED(KSCATEGORY_WDMAUD)
+
+#define STATIC_KSCATEGORY_AUDIO_GFX                                    \
+       0x9BAF9572L,0x340C,0x11D3,0xAB,0xDC,0x00,0xA0,0xC9,0x0A,0xB1,0x6F
+DEFINE_GUIDSTRUCT("9BAF9572-340C-11D3-ABDC-00A0C90AB16F",KSCATEGORY_AUDIO_GFX);
+#define KSCATEGORY_AUDIO_GFX DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_GFX)
+
+#define STATIC_KSCATEGORY_AUDIO_SPLITTER                               \
+       0x9EA331FAL,0xB91B,0x45F8,0x92,0x85,0xBD,0x2B,0xC7,0x7A,0xFC,0xDE
+DEFINE_GUIDSTRUCT("9EA331FA-B91B-45F8-9285-BD2BC77AFCDE",KSCATEGORY_AUDIO_SPLITTER);
+#define KSCATEGORY_AUDIO_SPLITTER DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_SPLITTER)
+
+#define STATIC_KSCATEGORY_SYNTHESIZER          STATIC_KSNODETYPE_SYNTHESIZER
+#define KSCATEGORY_SYNTHESIZER                 KSNODETYPE_SYNTHESIZER
+
+#define STATIC_KSCATEGORY_DRM_DESCRAMBLE       STATIC_KSNODETYPE_DRM_DESCRAMBLE
+#define KSCATEGORY_DRM_DESCRAMBLE              KSNODETYPE_DRM_DESCRAMBLE
+
+#define STATIC_KSCATEGORY_AUDIO_DEVICE                                 \
+       0xFBF6F530L,0x07B9,0x11D2,0xA7,0x1E,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("FBF6F530-07B9-11D2-A71E-0000F8004788",KSCATEGORY_AUDIO_DEVICE);
+#define KSCATEGORY_AUDIO_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_DEVICE)
+
+#define STATIC_KSCATEGORY_PREFERRED_WAVEOUT_DEVICE                     \
+       0xD6C5066EL,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("D6C5066E-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_WAVEOUT_DEVICE);
+#define KSCATEGORY_PREFERRED_WAVEOUT_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_WAVEOUT_DEVICE)
+
+#define STATIC_KSCATEGORY_PREFERRED_WAVEIN_DEVICE                      \
+       0xD6C50671L,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("D6C50671-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_WAVEIN_DEVICE);
+#define KSCATEGORY_PREFERRED_WAVEIN_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_WAVEIN_DEVICE)
+
+#define STATIC_KSCATEGORY_PREFERRED_MIDIOUT_DEVICE                     \
+       0xD6C50674L,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("D6C50674-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_MIDIOUT_DEVICE);
+#define KSCATEGORY_PREFERRED_MIDIOUT_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_MIDIOUT_DEVICE)
+
+#define STATIC_KSCATEGORY_WDMAUD_USE_PIN_NAME                          \
+       0x47A4FA20L,0xA251,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
+DEFINE_GUIDSTRUCT("47A4FA20-A251-11D1-A050-0000F8004788",KSCATEGORY_WDMAUD_USE_PIN_NAME);
+#define KSCATEGORY_WDMAUD_USE_PIN_NAME DEFINE_GUIDNAMED(KSCATEGORY_WDMAUD_USE_PIN_NAME)
+
+#define STATIC_KSCATEGORY_ESCALANTE_PLATFORM_DRIVER                    \
+       0x74f3aea8L,0x9768,0x11d1,0x8e,0x07,0x00,0xa0,0xc9,0x5e,0xc2,0x2e
+DEFINE_GUIDSTRUCT("74f3aea8-9768-11d1-8e07-00a0c95ec22e",KSCATEGORY_ESCALANTE_PLATFORM_DRIVER);
+#define KSCATEGORY_ESCALANTE_PLATFORM_DRIVER DEFINE_GUIDNAMED(KSCATEGORY_ESCALANTE_PLATFORM_DRIVER)
+
+#define STATIC_KSDATAFORMAT_TYPE_VIDEO                                 \
+       0x73646976L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+DEFINE_GUIDSTRUCT("73646976-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_VIDEO);
+#define KSDATAFORMAT_TYPE_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_VIDEO)
+
+#define STATIC_KSDATAFORMAT_TYPE_AUDIO                                 \
+       0x73647561L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+DEFINE_GUIDSTRUCT("73647561-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_AUDIO);
+#define KSDATAFORMAT_TYPE_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_AUDIO)
+
+#define STATIC_KSDATAFORMAT_TYPE_TEXT                                  \
+       0x73747874L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+DEFINE_GUIDSTRUCT("73747874-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_TEXT);
+#define KSDATAFORMAT_TYPE_TEXT DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_TEXT)
+
+#if !defined(DEFINE_WAVEFORMATEX_GUID)
+#define DEFINE_WAVEFORMATEX_GUID(x)                                    \
+       (USHORT)(x),0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+#endif
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX                       \
+       0x00000000L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+DEFINE_GUIDSTRUCT("00000000-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_WAVEFORMATEX);
+#define KSDATAFORMAT_SUBTYPE_WAVEFORMATEX DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_WAVEFORMATEX)
+
+#define INIT_WAVEFORMATEX_GUID(Guid,x)                                 \
+{                                                                      \
+       *(Guid) = KSDATAFORMAT_SUBTYPE_WAVEFORMATEX;                    \
+       (Guid)->Data1 = (USHORT)(x);                                    \
+}
+
+#define EXTRACT_WAVEFORMATEX_ID(Guid)                                  \
+       (USHORT)((Guid)->Data1)
+
+#define IS_VALID_WAVEFORMATEX_GUID(Guid)                               \
+       (!memcmp(((PUSHORT)&KSDATAFORMAT_SUBTYPE_WAVEFORMATEX) + 1, ((PUSHORT)(Guid)) + 1,sizeof(GUID) - sizeof(USHORT)))
+
+#ifndef INIT_MMREG_MID
+#define INIT_MMREG_MID(guid,id)                                                \
+{                                                                      \
+       (guid)->Data1 = 0xd5a47fa7 + (USHORT)(id);                      \
+       (guid)->Data2 = 0x6d98;                                         \
+       (guid)->Data3 = 0x11d1;                                         \
+       (guid)->Data4[0] = 0xa2;                                        \
+       (guid)->Data4[1] = 0x1a;                                        \
+       (guid)->Data4[2] = 0x00;                                        \
+       (guid)->Data4[3] = 0xa0;                                        \
+       (guid)->Data4[4] = 0xc9;                                        \
+       (guid)->Data4[5] = 0x22;                                        \
+       (guid)->Data4[6] = 0x31;                                        \
+       (guid)->Data4[7] = 0x96;                                        \
+}
+#define EXTRACT_MMREG_MID(guid)                                                \
+       (USHORT)((guid)->Data1 - 0xd5a47fa7)
+#define DEFINE_MMREG_MID_GUID(id)                                      \
+       0xd5a47fa7+(USHORT)(id),0x6d98,0x11d1,0xa2,0x1a,0x00,0xa0,0xc9,0x22,0x31,0x96
+
+#define IS_COMPATIBLE_MMREG_MID(guid)                                  \
+       (((guid)->Data1 >= 0xd5a47fa7) &&                               \
+        ((guid)->Data1 < 0xd5a47fa7 + 0xffff) &&                       \
+        ((guid)->Data2 == 0x6d98) &&                                   \
+        ((guid)->Data3 == 0x11d1) &&                                   \
+        ((guid)->Data4[0] == 0xa2) &&                                  \
+        ((guid)->Data4[1] == 0x1a) &&                                  \
+        ((guid)->Data4[2] == 0x00) &&                                  \
+        ((guid)->Data4[3] == 0xa0) &&                                  \
+        ((guid)->Data4[4] == 0xc9) &&                                  \
+        ((guid)->Data4[5] == 0x22) &&                                  \
+        ((guid)->Data4[6] == 0x31) &&                                  \
+        ((guid)->Data4[7] == 0x96) )
+#endif /* INIT_MMREG_MID */
+
+#ifndef INIT_MMREG_PID
+#define INIT_MMREG_PID(guid,id)                                                \
+{                                                                      \
+       (guid)->Data1 = 0xe36dc2ac + (USHORT)(id);                      \
+       (guid)->Data2 = 0x6d9a;                                         \
+       (guid)->Data3 = 0x11d1;                                         \
+       (guid)->Data4[0] = 0xa2;                                        \
+       (guid)->Data4[1] = 0x1a;                                        \
+       (guid)->Data4[2] = 0x00;                                        \
+       (guid)->Data4[3] = 0xa0;                                        \
+       (guid)->Data4[4] = 0xc9;                                        \
+       (guid)->Data4[5] = 0x22;                                        \
+       (guid)->Data4[6] = 0x31;                                        \
+       (guid)->Data4[7] = 0x96;                                        \
+}
+#define EXTRACT_MMREG_PID(guid)                                                \
+       (USHORT)((guid)->Data1 - 0xe36dc2ac)
+#define DEFINE_MMREG_PID_GUID(id)                                      \
+       0xe36dc2ac+(USHORT)(id),0x6d9a,0x11d1,0xa2,0x1a,0x00,0xa0,0xc9,0x22,0x31,0x96
+
+#define IS_COMPATIBLE_MMREG_PID(guid)                                  \
+       (((guid)->Data1 >= 0xe36dc2ac) &&                               \
+        ((guid)->Data1 < 0xe36dc2ac + 0xffff) &&                       \
+        ((guid)->Data2 == 0x6d9a) &&                                   \
+        ((guid)->Data3 == 0x11d1) &&                                   \
+        ((guid)->Data4[0] == 0xa2) &&                                  \
+        ((guid)->Data4[1] == 0x1a) &&                                  \
+        ((guid)->Data4[2] == 0x00) &&                                  \
+        ((guid)->Data4[3] == 0xa0) &&                                  \
+        ((guid)->Data4[4] == 0xc9) &&                                  \
+        ((guid)->Data4[5] == 0x22) &&                                  \
+        ((guid)->Data4[6] == 0x31) &&                                  \
+        ((guid)->Data4[7] == 0x96) )
+#endif /* INIT_MMREG_PID */
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_ANALOG                             \
+       0x6dba3190L,0x67bd,0x11cf,0xa0,0xf7,0x00,0x20,0xaf,0xd1,0x56,0xe4
+DEFINE_GUIDSTRUCT("6dba3190-67bd-11cf-a0f7-0020afd156e4",KSDATAFORMAT_SUBTYPE_ANALOG);
+#define KSDATAFORMAT_SUBTYPE_ANALOG DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ANALOG)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_PCM                                        \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_PCM)
+DEFINE_GUIDSTRUCT("00000001-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_PCM);
+#define KSDATAFORMAT_SUBTYPE_PCM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_PCM)
+
+#ifdef _INC_MMREG
+#define STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT                         \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_IEEE_FLOAT)
+DEFINE_GUIDSTRUCT("00000003-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_IEEE_FLOAT);
+#define KSDATAFORMAT_SUBTYPE_IEEE_FLOAT DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_DRM                                        \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_DRM)
+DEFINE_GUIDSTRUCT("00000009-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_DRM);
+#define KSDATAFORMAT_SUBTYPE_DRM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DRM)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_ALAW                               \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_ALAW)
+DEFINE_GUIDSTRUCT("00000006-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_ALAW);
+#define KSDATAFORMAT_SUBTYPE_ALAW DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ALAW)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MULAW                              \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_MULAW)
+DEFINE_GUIDSTRUCT("00000007-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_MULAW);
+#define KSDATAFORMAT_SUBTYPE_MULAW DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MULAW)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_ADPCM                              \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_ADPCM)
+DEFINE_GUIDSTRUCT("00000002-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_ADPCM);
+#define KSDATAFORMAT_SUBTYPE_ADPCM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ADPCM)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG                               \
+       DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_MPEG)
+DEFINE_GUIDSTRUCT("00000050-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_MPEG);
+#define KSDATAFORMAT_SUBTYPE_MPEG DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG)
+#endif /* _INC_MMREG */
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_VC_ID                            \
+       0xAD98D184L,0xAAC3,0x11D0,0xA4,0x1C,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("AD98D184-AAC3-11D0-A41C-00A0C9223196",KSDATAFORMAT_SPECIFIER_VC_ID);
+#define KSDATAFORMAT_SPECIFIER_VC_ID DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VC_ID)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_WAVEFORMATEX                     \
+       0x05589f81L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
+DEFINE_GUIDSTRUCT("05589f81-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_WAVEFORMATEX);
+#define KSDATAFORMAT_SPECIFIER_WAVEFORMATEX DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DSOUND                           \
+       0x518590a2L,0xa184,0x11d0,0x85,0x22,0x00,0xc0,0x4f,0xd9,0xba,0xf3
+DEFINE_GUIDSTRUCT("518590a2-a184-11d0-8522-00c04fd9baf3",KSDATAFORMAT_SPECIFIER_DSOUND);
+#define KSDATAFORMAT_SPECIFIER_DSOUND DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DSOUND)
+
+#if defined(_INC_MMSYSTEM) || defined(_INC_MMREG)
+#if !defined(PACK_PRAGMAS_NOT_SUPPORTED)
+#include <pshpack1.h>
+#endif
+typedef struct {
+  KSDATAFORMAT DataFormat;
+  WAVEFORMATEX WaveFormatEx;
+} KSDATAFORMAT_WAVEFORMATEX,*PKSDATAFORMAT_WAVEFORMATEX;
+
+#ifndef _WAVEFORMATEXTENSIBLE_
+#define _WAVEFORMATEXTENSIBLE_
+typedef struct {
+  WAVEFORMATEX Format;
+  union {
+    WORD wValidBitsPerSample;
+    WORD wSamplesPerBlock;
+    WORD wReserved;
+  } Samples;
+  DWORD dwChannelMask;
+
+  GUID SubFormat;
+} WAVEFORMATEXTENSIBLE,*PWAVEFORMATEXTENSIBLE;
+#endif /* _WAVEFORMATEXTENSIBLE_ */
+
+#if !defined(WAVE_FORMAT_EXTENSIBLE)
+#define WAVE_FORMAT_EXTENSIBLE                 0xFFFE
+#endif
+
+typedef struct {
+  ULONG Flags;
+  ULONG Control;
+  WAVEFORMATEX WaveFormatEx;
+} KSDSOUND_BUFFERDESC,*PKSDSOUND_BUFFERDESC;
+
+typedef struct {
+  KSDATAFORMAT DataFormat;
+  KSDSOUND_BUFFERDESC BufferDesc;
+} KSDATAFORMAT_DSOUND,*PKSDATAFORMAT_DSOUND;
+
+#if !defined(PACK_PRAGMAS_NOT_SUPPORTED)
+#include <poppack.h>
+#endif
+#endif /* defined(_INC_MMSYSTEM) || defined(_INC_MMREG) */
+
+#define KSDSOUND_BUFFER_PRIMARY                        0x00000001
+#define KSDSOUND_BUFFER_STATIC                 0x00000002
+#define KSDSOUND_BUFFER_LOCHARDWARE            0x00000004
+#define KSDSOUND_BUFFER_LOCSOFTWARE            0x00000008
+
+#define KSDSOUND_BUFFER_CTRL_3D                        0x00000001
+#define KSDSOUND_BUFFER_CTRL_FREQUENCY         0x00000002
+#define KSDSOUND_BUFFER_CTRL_PAN               0x00000004
+#define KSDSOUND_BUFFER_CTRL_VOLUME            0x00000008
+#define KSDSOUND_BUFFER_CTRL_POSITIONNOTIFY    0x00000010
+
+typedef struct {
+  DWORDLONG PlayOffset;
+  DWORDLONG WriteOffset;
+} KSAUDIO_POSITION,*PKSAUDIO_POSITION;
+
+typedef struct _DS3DVECTOR {
+  __MINGW_EXTENSION union {
+    FLOAT x;
+    FLOAT dvX;
+  };
+  __MINGW_EXTENSION union {
+    FLOAT y;
+    FLOAT dvY;
+  };
+  __MINGW_EXTENSION union {
+    FLOAT z;
+    FLOAT dvZ;
+  };
+} DS3DVECTOR,*PDS3DVECTOR;
+
+#define STATIC_KSPROPSETID_DirectSound3DListener                       \
+       0x437b3414L,0xd060,0x11d0,0x85,0x83,0x00,0xc0,0x4f,0xd9,0xba,0xf3
+DEFINE_GUIDSTRUCT("437b3414-d060-11d0-8583-00c04fd9baf3",KSPROPSETID_DirectSound3DListener);
+#define KSPROPSETID_DirectSound3DListener DEFINE_GUIDNAMED(KSPROPSETID_DirectSound3DListener)
+
+typedef enum {
+  KSPROPERTY_DIRECTSOUND3DLISTENER_ALL,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_POSITION,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_VELOCITY,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_ORIENTATION,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_DISTANCEFACTOR,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_ROLLOFFFACTOR,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_DOPPLERFACTOR,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_BATCH,
+  KSPROPERTY_DIRECTSOUND3DLISTENER_ALLOCATION
+} KSPROPERTY_DIRECTSOUND3DLISTENER;
+
+typedef struct {
+  DS3DVECTOR Position;
+  DS3DVECTOR Velocity;
+  DS3DVECTOR OrientFront;
+  DS3DVECTOR OrientTop;
+  FLOAT DistanceFactor;
+  FLOAT RolloffFactor;
+  FLOAT DopplerFactor;
+} KSDS3D_LISTENER_ALL,*PKSDS3D_LISTENER_ALL;
+
+typedef struct {
+  DS3DVECTOR Front;
+  DS3DVECTOR Top;
+} KSDS3D_LISTENER_ORIENTATION,*PKSDS3D_LISTENER_ORIENTATION;
+
+#define STATIC_KSPROPSETID_DirectSound3DBuffer                         \
+       0x437b3411L,0xd060,0x11d0,0x85,0x83,0x00,0xc0,0x4f,0xd9,0xba,0xf3
+DEFINE_GUIDSTRUCT("437b3411-d060-11d0-8583-00c04fd9baf3",KSPROPSETID_DirectSound3DBuffer);
+#define KSPROPSETID_DirectSound3DBuffer DEFINE_GUIDNAMED(KSPROPSETID_DirectSound3DBuffer)
+
+typedef enum {
+  KSPROPERTY_DIRECTSOUND3DBUFFER_ALL,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_POSITION,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_VELOCITY,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEANGLES,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEORIENTATION,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEOUTSIDEVOLUME,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_MINDISTANCE,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_MAXDISTANCE,
+  KSPROPERTY_DIRECTSOUND3DBUFFER_MODE
+} KSPROPERTY_DIRECTSOUND3DBUFFER;
+
+typedef struct {
+  DS3DVECTOR Position;
+  DS3DVECTOR Velocity;
+  ULONG InsideConeAngle;
+  ULONG OutsideConeAngle;
+  DS3DVECTOR ConeOrientation;
+  LONG ConeOutsideVolume;
+  FLOAT MinDistance;
+  FLOAT MaxDistance;
+  ULONG Mode;
+} KSDS3D_BUFFER_ALL,*PKSDS3D_BUFFER_ALL;
+
+typedef struct {
+  ULONG InsideConeAngle;
+  ULONG OutsideConeAngle;
+} KSDS3D_BUFFER_CONE_ANGLES,*PKSDS3D_BUFFER_CONE_ANGLES;
+
+#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_HEADPHONE      (-1)
+#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_MIN            5
+#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_NARROW         10
+#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_WIDE           20
+#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_MAX            180
+
+#define KSDSOUND_3D_MODE_NORMAL                        0x00000000
+#define KSDSOUND_3D_MODE_HEADRELATIVE          0x00000001
+#define KSDSOUND_3D_MODE_DISABLE               0x00000002
+
+#define KSDSOUND_BUFFER_CTRL_HRTF_3D           0x40000000
+
+typedef struct {
+  ULONG Size;
+  ULONG Enabled;
+  WINBOOL SwapChannels;
+  WINBOOL ZeroAzimuth;
+  WINBOOL CrossFadeOutput;
+  ULONG FilterSize;
+} KSDS3D_HRTF_PARAMS_MSG,*PKSDS3D_HRTF_PARAMS_MSG;
+
+typedef enum {
+  FULL_FILTER,
+  LIGHT_FILTER,
+  KSDS3D_FILTER_QUALITY_COUNT
+} KSDS3D_HRTF_FILTER_QUALITY;
+
+typedef struct {
+  ULONG Size;
+  KSDS3D_HRTF_FILTER_QUALITY Quality;
+  FLOAT SampleRate;
+  ULONG MaxFilterSize;
+  ULONG FilterTransientMuteLength;
+  ULONG FilterOverlapBufferLength;
+  ULONG OutputOverlapBufferLength;
+  ULONG Reserved;
+} KSDS3D_HRTF_INIT_MSG,*PKSDS3D_HRTF_INIT_MSG;
+
+typedef enum {
+  FLOAT_COEFF,
+  SHORT_COEFF,
+  KSDS3D_COEFF_COUNT
+} KSDS3D_HRTF_COEFF_FORMAT;
+
+typedef enum {
+  DIRECT_FORM,
+  CASCADE_FORM,
+  KSDS3D_FILTER_METHOD_COUNT
+} KSDS3D_HRTF_FILTER_METHOD;
+
+typedef enum {
+  DS3D_HRTF_VERSION_1
+} KSDS3D_HRTF_FILTER_VERSION;
+
+typedef struct {
+  KSDS3D_HRTF_FILTER_METHOD FilterMethod;
+  KSDS3D_HRTF_COEFF_FORMAT CoeffFormat;
+  KSDS3D_HRTF_FILTER_VERSION Version;
+  ULONG Reserved;
+} KSDS3D_HRTF_FILTER_FORMAT_MSG,*PKSDS3D_HRTF_FILTER_FORMAT_MSG;
+
+#define STATIC_KSPROPSETID_Hrtf3d                                      \
+       0xb66decb0L,0xa083,0x11d0,0x85,0x1e,0x00,0xc0,0x4f,0xd9,0xba,0xf3
+DEFINE_GUIDSTRUCT("b66decb0-a083-11d0-851e-00c04fd9baf3",KSPROPSETID_Hrtf3d);
+#define KSPROPSETID_Hrtf3d DEFINE_GUIDNAMED(KSPROPSETID_Hrtf3d)
+
+typedef enum {
+  KSPROPERTY_HRTF3D_PARAMS = 0,
+  KSPROPERTY_HRTF3D_INITIALIZE,
+  KSPROPERTY_HRTF3D_FILTER_FORMAT
+} KSPROPERTY_HRTF3D;
+
+typedef struct {
+  LONG Channel;
+  FLOAT VolSmoothScale;
+  FLOAT TotalDryAttenuation;
+  FLOAT TotalWetAttenuation;
+  LONG SmoothFrequency;
+  LONG Delay;
+} KSDS3D_ITD_PARAMS,*PKSDS3D_ITD_PARAMS;
+
+typedef struct {
+  ULONG Enabled;
+  KSDS3D_ITD_PARAMS LeftParams;
+  KSDS3D_ITD_PARAMS RightParams;
+  ULONG Reserved;
+} KSDS3D_ITD_PARAMS_MSG,*PKSDS3D_ITD_PARAMS_MSG;
+
+#define STATIC_KSPROPSETID_Itd3d                                       \
+       0x6429f090L,0x9fd9,0x11d0,0xa7,0x5b,0x00,0xa0,0xc9,0x03,0x65,0xe3
+DEFINE_GUIDSTRUCT("6429f090-9fd9-11d0-a75b-00a0c90365e3",KSPROPSETID_Itd3d);
+#define KSPROPSETID_Itd3d DEFINE_GUIDNAMED(KSPROPSETID_Itd3d)
+
+typedef enum {
+  KSPROPERTY_ITD3D_PARAMS = 0
+} KSPROPERTY_ITD3D;
+
+typedef struct {
+  KSDATARANGE DataRange;
+  ULONG MaximumChannels;
+  ULONG MinimumBitsPerSample;
+  ULONG MaximumBitsPerSample;
+  ULONG MinimumSampleFrequency;
+  ULONG MaximumSampleFrequency;
+} KSDATARANGE_AUDIO,*PKSDATARANGE_AUDIO;
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_RIFF                               \
+       0x4995DAEEL,0x9EE6,0x11D0,0xA4,0x0E,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("4995DAEE-9EE6-11D0-A40E-00A0C9223196",KSDATAFORMAT_SUBTYPE_RIFF);
+#define KSDATAFORMAT_SUBTYPE_RIFF DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFF)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_RIFFWAVE                           \
+       0xe436eb8bL,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
+DEFINE_GUIDSTRUCT("e436eb8b-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_RIFFWAVE);
+#define KSDATAFORMAT_SUBTYPE_RIFFWAVE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFFWAVE)
+
+#define STATIC_KSPROPSETID_Bibliographic                               \
+       0x07BA150EL,0xE2B1,0x11D0,0xAC,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("07BA150E-E2B1-11D0-AC17-00A0C9223196",KSPROPSETID_Bibliographic);
+#define KSPROPSETID_Bibliographic DEFINE_GUIDNAMED(KSPROPSETID_Bibliographic)
+
+typedef enum {
+  KSPROPERTY_BIBLIOGRAPHIC_LEADER = 'RDL ',
+  KSPROPERTY_BIBLIOGRAPHIC_LCCN = '010 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ISBN = '020 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ISSN = '220 ',
+  KSPROPERTY_BIBLIOGRAPHIC_CATALOGINGSOURCE = '040 ',
+  KSPROPERTY_BIBLIOGRAPHIC_MAINPERSONALNAME = '001 ',
+  KSPROPERTY_BIBLIOGRAPHIC_MAINCORPORATEBODY = '011 ',
+  KSPROPERTY_BIBLIOGRAPHIC_MAINMEETINGNAME = '111 ',
+  KSPROPERTY_BIBLIOGRAPHIC_MAINUNIFORMTITLE = '031 ',
+  KSPROPERTY_BIBLIOGRAPHIC_UNIFORMTITLE = '042 ',
+  KSPROPERTY_BIBLIOGRAPHIC_TITLESTATEMENT = '542 ',
+  KSPROPERTY_BIBLIOGRAPHIC_VARYINGFORMTITLE = '642 ',
+  KSPROPERTY_BIBLIOGRAPHIC_PUBLICATION = '062 ',
+  KSPROPERTY_BIBLIOGRAPHIC_PHYSICALDESCRIPTION = '003 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYTITLE = '044 ',
+  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENT = '094 ',
+  KSPROPERTY_BIBLIOGRAPHIC_GENERALNOTE = '005 ',
+  KSPROPERTY_BIBLIOGRAPHIC_BIBLIOGRAPHYNOTE = '405 ',
+  KSPROPERTY_BIBLIOGRAPHIC_CONTENTSNOTE = '505 ',
+  KSPROPERTY_BIBLIOGRAPHIC_CREATIONCREDIT = '805 ',
+  KSPROPERTY_BIBLIOGRAPHIC_CITATION = '015 ',
+  KSPROPERTY_BIBLIOGRAPHIC_PARTICIPANT = '115 ',
+  KSPROPERTY_BIBLIOGRAPHIC_SUMMARY = '025 ',
+  KSPROPERTY_BIBLIOGRAPHIC_TARGETAUDIENCE = '125 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDFORMAVAILABLE = '035 ',
+  KSPROPERTY_BIBLIOGRAPHIC_SYSTEMDETAILS = '835 ',
+  KSPROPERTY_BIBLIOGRAPHIC_AWARDS = '685 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYPERSONALNAME = '006 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYTOPICALTERM = '056 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYGEOGRAPHIC = '156 ',
+  KSPROPERTY_BIBLIOGRAPHIC_INDEXTERMGENRE = '556 ',
+  KSPROPERTY_BIBLIOGRAPHIC_INDEXTERMCURRICULUM = '856 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYUNIFORMTITLE = '037 ',
+  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYRELATED = '047 ',
+  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENTPERSONALNAME = '008 ',
+  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENTUNIFORMTITLE = '038 '
+} KSPROPERTY_BIBLIOGRAPHIC;
+
+#define STATIC_KSPROPSETID_TopologyNode                                        \
+       0x45FFAAA1L,0x6E1B,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
+DEFINE_GUIDSTRUCT("45FFAAA1-6E1B-11D0-BCF2-444553540000",KSPROPSETID_TopologyNode);
+#define KSPROPSETID_TopologyNode DEFINE_GUIDNAMED(KSPROPSETID_TopologyNode)
+
+typedef enum {
+  KSPROPERTY_TOPOLOGYNODE_ENABLE = 1,
+  KSPROPERTY_TOPOLOGYNODE_RESET
+} KSPROPERTY_TOPOLOGYNODE;
+
+#define STATIC_KSPROPSETID_RtAudio                                     \
+       0xa855a48c,0x2f78,0x4729,0x90,0x51,0x19,0x68,0x74,0x6b,0x9e,0xef
+DEFINE_GUIDSTRUCT("A855A48C-2F78-4729-9051-1968746B9EEF",KSPROPSETID_RtAudio);
+#define KSPROPSETID_RtAudio DEFINE_GUIDNAMED(KSPROPSETID_RtAudio)
+
+typedef enum {
+  KSPROPERTY_RTAUDIO_GETPOSITIONFUNCTION,
+  /* Added for Vista and later */
+  KSPROPERTY_RTAUDIO_BUFFER,
+  KSPROPERTY_RTAUDIO_HWLATENCY,
+  KSPROPERTY_RTAUDIO_POSITIONREGISTER,
+  KSPROPERTY_RTAUDIO_CLOCKREGISTER,
+  KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION,
+  KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT,
+  KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT
+} KSPROPERTY_RTAUDIO;
+
+#define STATIC_KSPROPSETID_DrmAudioStream                              \
+       0x2f2c8ddd,0x4198,0x4fac,0xba,0x29,0x61,0xbb,0x5,0xb7,0xde,0x6
+DEFINE_GUIDSTRUCT("2F2C8DDD-4198-4fac-BA29-61BB05B7DE06",KSPROPSETID_DrmAudioStream);
+#define KSPROPSETID_DrmAudioStream DEFINE_GUIDNAMED(KSPROPSETID_DrmAudioStream)
+
+typedef enum {
+  KSPROPERTY_DRMAUDIOSTREAM_CONTENTID
+} KSPROPERTY_DRMAUDIOSTREAM;
+
+#define STATIC_KSPROPSETID_Audio                                       \
+       0x45FFAAA0L,0x6E1B,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
+DEFINE_GUIDSTRUCT("45FFAAA0-6E1B-11D0-BCF2-444553540000",KSPROPSETID_Audio);
+#define KSPROPSETID_Audio DEFINE_GUIDNAMED(KSPROPSETID_Audio)
+
+typedef enum {
+  KSPROPERTY_AUDIO_LATENCY = 1,
+  KSPROPERTY_AUDIO_COPY_PROTECTION,
+  KSPROPERTY_AUDIO_CHANNEL_CONFIG,
+  KSPROPERTY_AUDIO_VOLUMELEVEL,
+  KSPROPERTY_AUDIO_POSITION,
+  KSPROPERTY_AUDIO_DYNAMIC_RANGE,
+  KSPROPERTY_AUDIO_QUALITY,
+  KSPROPERTY_AUDIO_SAMPLING_RATE,
+  KSPROPERTY_AUDIO_DYNAMIC_SAMPLING_RATE,
+  KSPROPERTY_AUDIO_MIX_LEVEL_TABLE,
+  KSPROPERTY_AUDIO_MIX_LEVEL_CAPS,
+  KSPROPERTY_AUDIO_MUX_SOURCE,
+  KSPROPERTY_AUDIO_MUTE,
+  KSPROPERTY_AUDIO_BASS,
+  KSPROPERTY_AUDIO_MID,
+  KSPROPERTY_AUDIO_TREBLE,
+  KSPROPERTY_AUDIO_BASS_BOOST,
+  KSPROPERTY_AUDIO_EQ_LEVEL,
+  KSPROPERTY_AUDIO_NUM_EQ_BANDS,
+  KSPROPERTY_AUDIO_EQ_BANDS,
+  KSPROPERTY_AUDIO_AGC,
+  KSPROPERTY_AUDIO_DELAY,
+  KSPROPERTY_AUDIO_LOUDNESS,
+  KSPROPERTY_AUDIO_WIDE_MODE,
+  KSPROPERTY_AUDIO_WIDENESS,
+  KSPROPERTY_AUDIO_REVERB_LEVEL,
+  KSPROPERTY_AUDIO_CHORUS_LEVEL,
+  KSPROPERTY_AUDIO_DEV_SPECIFIC,
+  KSPROPERTY_AUDIO_DEMUX_DEST,
+  KSPROPERTY_AUDIO_STEREO_ENHANCE,
+  KSPROPERTY_AUDIO_MANUFACTURE_GUID,
+  KSPROPERTY_AUDIO_PRODUCT_GUID,
+  KSPROPERTY_AUDIO_CPU_RESOURCES,
+  KSPROPERTY_AUDIO_STEREO_SPEAKER_GEOMETRY,
+  KSPROPERTY_AUDIO_SURROUND_ENCODE,
+  KSPROPERTY_AUDIO_3D_INTERFACE,
+  KSPROPERTY_AUDIO_PEAKMETER,
+  KSPROPERTY_AUDIO_ALGORITHM_INSTANCE,
+  KSPROPERTY_AUDIO_FILTER_STATE,
+  KSPROPERTY_AUDIO_PREFERRED_STATUS
+} KSPROPERTY_AUDIO;
+
+#define KSAUDIO_QUALITY_WORST                  0x0
+#define KSAUDIO_QUALITY_PC                     0x1
+#define KSAUDIO_QUALITY_BASIC                  0x2
+#define KSAUDIO_QUALITY_ADVANCED               0x3
+
+#define KSAUDIO_CPU_RESOURCES_NOT_HOST_CPU     0x00000000
+#define KSAUDIO_CPU_RESOURCES_HOST_CPU         0x7FFFFFFF
+
+typedef struct {
+  WINBOOL fCopyrighted;
+  WINBOOL fOriginal;
+} KSAUDIO_COPY_PROTECTION,*PKSAUDIO_COPY_PROTECTION;
+
+typedef struct {
+  LONG ActiveSpeakerPositions;
+} KSAUDIO_CHANNEL_CONFIG,*PKSAUDIO_CHANNEL_CONFIG;
+
+#define SPEAKER_FRONT_LEFT             0x1
+#define SPEAKER_FRONT_RIGHT            0x2
+#define SPEAKER_FRONT_CENTER           0x4
+#define SPEAKER_LOW_FREQUENCY          0x8
+#define SPEAKER_BACK_LEFT              0x10
+#define SPEAKER_BACK_RIGHT             0x20
+#define SPEAKER_FRONT_LEFT_OF_CENTER   0x40
+#define SPEAKER_FRONT_RIGHT_OF_CENTER  0x80
+#define SPEAKER_BACK_CENTER            0x100
+#define SPEAKER_SIDE_LEFT              0x200
+#define SPEAKER_SIDE_RIGHT             0x400
+#define SPEAKER_TOP_CENTER             0x800
+#define SPEAKER_TOP_FRONT_LEFT         0x1000
+#define SPEAKER_TOP_FRONT_CENTER       0x2000
+#define SPEAKER_TOP_FRONT_RIGHT                0x4000
+#define SPEAKER_TOP_BACK_LEFT          0x8000
+#define SPEAKER_TOP_BACK_CENTER                0x10000
+#define SPEAKER_TOP_BACK_RIGHT         0x20000
+
+#define SPEAKER_RESERVED               0x7FFC0000
+
+#define SPEAKER_ALL                    0x80000000
+
+#define KSAUDIO_SPEAKER_DIRECTOUT      0
+#define KSAUDIO_SPEAKER_MONO           (SPEAKER_FRONT_CENTER)
+#define KSAUDIO_SPEAKER_STEREO         (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)
+#define KSAUDIO_SPEAKER_QUAD           (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |             \
+                                        SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT)
+#define KSAUDIO_SPEAKER_SURROUND       (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |             \
+                                        SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER)
+#define KSAUDIO_SPEAKER_5POINT1                (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |             \
+                                        SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |         \
+                                        SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT)
+#define KSAUDIO_SPEAKER_7POINT1                (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |             \
+                                        SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |         \
+                                        SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |               \
+                                        SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER)
+#define KSAUDIO_SPEAKER_5POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |           \
+                                         SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |        \
+                                         SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT)
+#define KSAUDIO_SPEAKER_7POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |           \
+                                         SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |        \
+                                         SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |              \
+                                         SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT)
+
+#define KSAUDIO_SPEAKER_5POINT1_BACK   KSAUDIO_SPEAKER_5POINT1
+#define KSAUDIO_SPEAKER_7POINT1_WIDE   KSAUDIO_SPEAKER_7POINT1
+
+#define KSAUDIO_SPEAKER_GROUND_FRONT_LEFT      SPEAKER_FRONT_LEFT
+#define KSAUDIO_SPEAKER_GROUND_FRONT_CENTER    SPEAKER_FRONT_CENTER
+#define KSAUDIO_SPEAKER_GROUND_FRONT_RIGHT     SPEAKER_FRONT_RIGHT
+#define KSAUDIO_SPEAKER_GROUND_REAR_LEFT       SPEAKER_BACK_LEFT
+#define KSAUDIO_SPEAKER_GROUND_REAR_RIGHT      SPEAKER_BACK_RIGHT
+#define KSAUDIO_SPEAKER_TOP_MIDDLE             SPEAKER_TOP_CENTER
+#define KSAUDIO_SPEAKER_SUPER_WOOFER           SPEAKER_LOW_FREQUENCY
+
+typedef struct {
+  ULONG QuietCompression;
+  ULONG LoudCompression;
+} KSAUDIO_DYNAMIC_RANGE,*PKSAUDIO_DYNAMIC_RANGE;
+
+typedef struct {
+  WINBOOL Mute;
+  LONG Level;
+} KSAUDIO_MIXLEVEL,*PKSAUDIO_MIXLEVEL;
+
+typedef struct {
+  WINBOOL Mute;
+  LONG Minimum;
+  LONG Maximum;
+  LONG Reset;
+} KSAUDIO_MIX_CAPS,*PKSAUDIO_MIX_CAPS;
+
+typedef struct {
+  ULONG InputChannels;
+  ULONG OutputChannels;
+  KSAUDIO_MIX_CAPS Capabilities[1];
+} KSAUDIO_MIXCAP_TABLE,*PKSAUDIO_MIXCAP_TABLE;
+
+typedef enum {
+  SE_TECH_NONE,
+  SE_TECH_ANALOG_DEVICES_PHAT,
+  SE_TECH_CREATIVE,
+  SE_TECH_NATIONAL_SEMI,
+  SE_TECH_YAMAHA_YMERSION,
+  SE_TECH_BBE,
+  SE_TECH_CRYSTAL_SEMI,
+  SE_TECH_QSOUND_QXPANDER,
+  SE_TECH_SPATIALIZER,
+  SE_TECH_SRS,
+  SE_TECH_PLATFORM_TECH,
+  SE_TECH_AKM,
+  SE_TECH_AUREAL,
+  SE_TECH_AZTECH,
+  SE_TECH_BINAURA,
+  SE_TECH_ESS_TECH,
+  SE_TECH_HARMAN_VMAX,
+  SE_TECH_NVIDEA,
+  SE_TECH_PHILIPS_INCREDIBLE,
+  SE_TECH_TEXAS_INST,
+  SE_TECH_VLSI_TECH
+} SE_TECHNIQUE;
+
+typedef struct {
+  SE_TECHNIQUE Technique;
+  ULONG Center;
+  ULONG Depth;
+  ULONG Reserved;
+} KSAUDIO_STEREO_ENHANCE,*PKSAUDIO_STEREO_ENHANCE;
+
+typedef enum {
+  KSPROPERTY_SYSAUDIO_NORMAL_DEFAULT = 0,
+  KSPROPERTY_SYSAUDIO_PLAYBACK_DEFAULT,
+  KSPROPERTY_SYSAUDIO_RECORD_DEFAULT,
+  KSPROPERTY_SYSAUDIO_MIDI_DEFAULT,
+  KSPROPERTY_SYSAUDIO_MIXER_DEFAULT
+} KSPROPERTY_SYSAUDIO_DEFAULT_TYPE;
+
+typedef struct {
+  WINBOOL Enable;
+  KSPROPERTY_SYSAUDIO_DEFAULT_TYPE DeviceType;
+  ULONG Flags;
+  ULONG Reserved;
+} KSAUDIO_PREFERRED_STATUS,*PKSAUDIO_PREFERRED_STATUS;
+
+#define STATIC_KSNODETYPE_DAC                                          \
+       0x507AE360L,0xC554,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("507AE360-C554-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DAC);
+#define KSNODETYPE_DAC DEFINE_GUIDNAMED(KSNODETYPE_DAC)
+
+#define STATIC_KSNODETYPE_ADC                                          \
+       0x4D837FE0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("4D837FE0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_ADC);
+#define KSNODETYPE_ADC DEFINE_GUIDNAMED(KSNODETYPE_ADC)
+
+#define STATIC_KSNODETYPE_SRC                                          \
+       0x9DB7B9E0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("9DB7B9E0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SRC);
+#define KSNODETYPE_SRC DEFINE_GUIDNAMED(KSNODETYPE_SRC)
+
+#define STATIC_KSNODETYPE_SUPERMIX                                     \
+       0xE573ADC0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("E573ADC0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SUPERMIX);
+#define KSNODETYPE_SUPERMIX DEFINE_GUIDNAMED(KSNODETYPE_SUPERMIX)
+
+#define STATIC_KSNODETYPE_MUX                                          \
+       0x2CEAF780L,0xC556,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("2CEAF780-C556-11D0-8A2B-00A0C9255AC1",KSNODETYPE_MUX);
+#define KSNODETYPE_MUX DEFINE_GUIDNAMED(KSNODETYPE_MUX)
+
+#define STATIC_KSNODETYPE_DEMUX                                                \
+       0xC0EB67D4L,0xE807,0x11D0,0x95,0x8A,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("C0EB67D4-E807-11D0-958A-00C04FB925D3",KSNODETYPE_DEMUX);
+#define KSNODETYPE_DEMUX DEFINE_GUIDNAMED(KSNODETYPE_DEMUX)
+
+#define STATIC_KSNODETYPE_SUM                                          \
+       0xDA441A60L,0xC556,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("DA441A60-C556-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SUM);
+#define KSNODETYPE_SUM DEFINE_GUIDNAMED(KSNODETYPE_SUM)
+
+#define STATIC_KSNODETYPE_MUTE                                         \
+       0x02B223C0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("02B223C0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_MUTE);
+#define KSNODETYPE_MUTE DEFINE_GUIDNAMED(KSNODETYPE_MUTE)
+
+#define STATIC_KSNODETYPE_VOLUME                                       \
+       0x3A5ACC00L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("3A5ACC00-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_VOLUME);
+#define KSNODETYPE_VOLUME DEFINE_GUIDNAMED(KSNODETYPE_VOLUME)
+
+#define STATIC_KSNODETYPE_TONE                                         \
+       0x7607E580L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("7607E580-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_TONE);
+#define KSNODETYPE_TONE DEFINE_GUIDNAMED(KSNODETYPE_TONE)
+
+#define STATIC_KSNODETYPE_EQUALIZER                                    \
+       0x9D41B4A0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("9D41B4A0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_EQUALIZER);
+#define KSNODETYPE_EQUALIZER DEFINE_GUIDNAMED(KSNODETYPE_EQUALIZER)
+
+#define STATIC_KSNODETYPE_AGC                                          \
+       0xE88C9BA0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("E88C9BA0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_AGC);
+#define KSNODETYPE_AGC DEFINE_GUIDNAMED(KSNODETYPE_AGC)
+
+#define STATIC_KSNODETYPE_NOISE_SUPPRESS                               \
+       0xe07f903f,0x62fd,0x4e60,0x8c,0xdd,0xde,0xa7,0x23,0x66,0x65,0xb5
+DEFINE_GUIDSTRUCT("E07F903F-62FD-4e60-8CDD-DEA7236665B5",KSNODETYPE_NOISE_SUPPRESS);
+#define KSNODETYPE_NOISE_SUPPRESS DEFINE_GUIDNAMED(KSNODETYPE_NOISE_SUPPRESS)
+
+#define STATIC_KSNODETYPE_DELAY                                                \
+       0x144981E0L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("144981E0-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DELAY);
+#define KSNODETYPE_DELAY DEFINE_GUIDNAMED(KSNODETYPE_DELAY)
+
+#define STATIC_KSNODETYPE_LOUDNESS                                     \
+       0x41887440L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("41887440-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_LOUDNESS);
+#define KSNODETYPE_LOUDNESS DEFINE_GUIDNAMED(KSNODETYPE_LOUDNESS)
+
+#define STATIC_KSNODETYPE_PROLOGIC_DECODER                             \
+       0x831C2C80L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("831C2C80-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_PROLOGIC_DECODER);
+#define KSNODETYPE_PROLOGIC_DECODER DEFINE_GUIDNAMED(KSNODETYPE_PROLOGIC_DECODER)
+
+#define STATIC_KSNODETYPE_STEREO_WIDE                                  \
+       0xA9E69800L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("A9E69800-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_STEREO_WIDE);
+#define KSNODETYPE_STEREO_WIDE DEFINE_GUIDNAMED(KSNODETYPE_STEREO_WIDE)
+
+#define STATIC_KSNODETYPE_STEREO_ENHANCE                               \
+       0xAF6878ACL,0xE83F,0x11D0,0x95,0x8A,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("AF6878AC-E83F-11D0-958A-00C04FB925D3",KSNODETYPE_STEREO_ENHANCE);
+#define KSNODETYPE_STEREO_ENHANCE DEFINE_GUIDNAMED(KSNODETYPE_STEREO_ENHANCE)
+
+#define STATIC_KSNODETYPE_REVERB                                       \
+       0xEF0328E0L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("EF0328E0-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_REVERB);
+#define KSNODETYPE_REVERB DEFINE_GUIDNAMED(KSNODETYPE_REVERB)
+
+#define STATIC_KSNODETYPE_CHORUS                                       \
+       0x20173F20L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("20173F20-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_CHORUS);
+#define KSNODETYPE_CHORUS DEFINE_GUIDNAMED(KSNODETYPE_CHORUS)
+
+#define STATIC_KSNODETYPE_3D_EFFECTS                                   \
+       0x55515860L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("55515860-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_3D_EFFECTS);
+#define KSNODETYPE_3D_EFFECTS DEFINE_GUIDNAMED(KSNODETYPE_3D_EFFECTS)
+
+#define STATIC_KSNODETYPE_ACOUSTIC_ECHO_CANCEL STATIC_KSCATEGORY_ACOUSTIC_ECHO_CANCEL
+#define KSNODETYPE_ACOUSTIC_ECHO_CANCEL KSCATEGORY_ACOUSTIC_ECHO_CANCEL
+
+#define STATIC_KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL         \
+       0x1c22c56dL,0x9879,0x4f5b,0xa3,0x89,0x27,0x99,0x6d,0xdc,0x28,0x10
+DEFINE_GUIDSTRUCT("1C22C56D-9879-4f5b-A389-27996DDC2810",KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL);
+#define KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL)
+
+#define STATIC_KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS               \
+       0x5ab0882eL,0x7274,0x4516,0x87,0x7d,0x4e,0xee,0x99,0xba,0x4f,0xd0
+DEFINE_GUIDSTRUCT("5AB0882E-7274-4516-877D-4EEE99BA4FD0",KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS);
+#define KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS)
+
+#define STATIC_KSALGORITHMINSTANCE_SYSTEM_AGC                          \
+       0x950e55b9L,0x877c,0x4c67,0xbe,0x8,0xe4,0x7b,0x56,0x11,0x13,0xa
+DEFINE_GUIDSTRUCT("950E55B9-877C-4c67-BE08-E47B5611130A",KSALGORITHMINSTANCE_SYSTEM_AGC);
+#define KSALGORITHMINSTANCE_SYSTEM_AGC DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_AGC)
+
+#define STATIC_KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR   \
+       0xB6F5A0A0L,0x9E61,0x4F8C,0x91,0xE3,0x76,0xCF,0xF,0x3C,0x47,0x1F
+DEFINE_GUIDSTRUCT("B6F5A0A0-9E61-4f8c-91E3-76CF0F3C471F",KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR);
+#define KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR)
+
+#define STATIC_KSNODETYPE_MICROPHONE_ARRAY_PROCESSOR STATIC_KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR
+#define KSNODETYPE_MICROPHONE_ARRAY_PROCESSOR KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR
+
+#define STATIC_KSNODETYPE_DEV_SPECIFIC                                 \
+       0x941C7AC0L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
+DEFINE_GUIDSTRUCT("941C7AC0-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DEV_SPECIFIC);
+#define KSNODETYPE_DEV_SPECIFIC DEFINE_GUIDNAMED(KSNODETYPE_DEV_SPECIFIC)
+
+#define STATIC_KSNODETYPE_PROLOGIC_ENCODER                             \
+       0x8074C5B2L,0x3C66,0x11D2,0xB4,0x5A,0x30,0x78,0x30,0x2C,0x20,0x30
+DEFINE_GUIDSTRUCT("8074C5B2-3C66-11D2-B45A-3078302C2030",KSNODETYPE_PROLOGIC_ENCODER);
+#define KSNODETYPE_PROLOGIC_ENCODER DEFINE_GUIDNAMED(KSNODETYPE_PROLOGIC_ENCODER)
+#define KSNODETYPE_SURROUND_ENCODER KSNODETYPE_PROLOGIC_ENCODER
+
+#define STATIC_KSNODETYPE_PEAKMETER                                    \
+       0xa085651eL,0x5f0d,0x4b36,0xa8,0x69,0xd1,0x95,0xd6,0xab,0x4b,0x9e
+DEFINE_GUIDSTRUCT("A085651E-5F0D-4b36-A869-D195D6AB4B9E",KSNODETYPE_PEAKMETER);
+#define KSNODETYPE_PEAKMETER DEFINE_GUIDNAMED(KSNODETYPE_PEAKMETER)
+
+#define STATIC_KSAUDFNAME_BASS                                         \
+       0x185FEDE0L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE0-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_BASS);
+#define KSAUDFNAME_BASS DEFINE_GUIDNAMED(KSAUDFNAME_BASS)
+
+#define STATIC_KSAUDFNAME_TREBLE                                       \
+       0x185FEDE1L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE1-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_TREBLE);
+#define KSAUDFNAME_TREBLE DEFINE_GUIDNAMED(KSAUDFNAME_TREBLE)
+
+#define STATIC_KSAUDFNAME_3D_STEREO                                    \
+       0x185FEDE2L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE2-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_3D_STEREO);
+#define KSAUDFNAME_3D_STEREO DEFINE_GUIDNAMED(KSAUDFNAME_3D_STEREO)
+
+#define STATIC_KSAUDFNAME_MASTER_VOLUME                                        \
+       0x185FEDE3L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE3-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MASTER_VOLUME);
+#define KSAUDFNAME_MASTER_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MASTER_VOLUME)
+
+#define STATIC_KSAUDFNAME_MASTER_MUTE                                  \
+       0x185FEDE4L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE4-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MASTER_MUTE);
+#define KSAUDFNAME_MASTER_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MASTER_MUTE)
+
+#define STATIC_KSAUDFNAME_WAVE_VOLUME                                  \
+       0x185FEDE5L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE5-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_VOLUME);
+#define KSAUDFNAME_WAVE_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_VOLUME)
+
+#define STATIC_KSAUDFNAME_WAVE_MUTE                                    \
+       0x185FEDE6L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE6-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_MUTE);
+#define KSAUDFNAME_WAVE_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_MUTE)
+
+#define STATIC_KSAUDFNAME_MIDI_VOLUME                                  \
+       0x185FEDE7L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE7-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_VOLUME);
+#define KSAUDFNAME_MIDI_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_VOLUME)
+
+#define STATIC_KSAUDFNAME_MIDI_MUTE                                    \
+       0x185FEDE8L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE8-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_MUTE);
+#define KSAUDFNAME_MIDI_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_MUTE)
+
+#define STATIC_KSAUDFNAME_CD_VOLUME                                    \
+       0x185FEDE9L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDE9-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_VOLUME);
+#define KSAUDFNAME_CD_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_CD_VOLUME)
+
+#define STATIC_KSAUDFNAME_CD_MUTE                                      \
+       0x185FEDEAL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDEA-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_MUTE);
+#define KSAUDFNAME_CD_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_CD_MUTE)
+
+#define STATIC_KSAUDFNAME_LINE_VOLUME                                  \
+       0x185FEDEBL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDEB-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_VOLUME);
+#define KSAUDFNAME_LINE_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_LINE_VOLUME)
+
+#define STATIC_KSAUDFNAME_LINE_MUTE                                    \
+       0x185FEDECL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDEC-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_MUTE);
+#define KSAUDFNAME_LINE_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_LINE_MUTE)
+
+#define STATIC_KSAUDFNAME_MIC_VOLUME                                   \
+       0x185FEDEDL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDED-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_VOLUME);
+#define KSAUDFNAME_MIC_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIC_VOLUME)
+
+#define STATIC_KSAUDFNAME_MIC_MUTE                                     \
+       0x185FEDEEL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDEE-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_MUTE);
+#define KSAUDFNAME_MIC_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MIC_MUTE)
+
+#define STATIC_KSAUDFNAME_RECORDING_SOURCE                             \
+       0x185FEDEFL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDEF-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_RECORDING_SOURCE);
+#define KSAUDFNAME_RECORDING_SOURCE DEFINE_GUIDNAMED(KSAUDFNAME_RECORDING_SOURCE)
+
+#define STATIC_KSAUDFNAME_PC_SPEAKER_VOLUME                            \
+       0x185FEDF0L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF0-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER_VOLUME);
+#define KSAUDFNAME_PC_SPEAKER_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER_VOLUME)
+
+#define STATIC_KSAUDFNAME_PC_SPEAKER_MUTE                              \
+       0x185FEDF1L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF1-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER_MUTE);
+#define KSAUDFNAME_PC_SPEAKER_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER_MUTE)
+
+#define STATIC_KSAUDFNAME_MIDI_IN_VOLUME                               \
+       0x185FEDF2L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF2-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_IN_VOLUME);
+#define KSAUDFNAME_MIDI_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_IN_VOLUME)
+
+#define STATIC_KSAUDFNAME_CD_IN_VOLUME                                 \
+       0x185FEDF3L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF3-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_IN_VOLUME);
+#define KSAUDFNAME_CD_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_CD_IN_VOLUME)
+
+#define STATIC_KSAUDFNAME_LINE_IN_VOLUME                               \
+       0x185FEDF4L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF4-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_IN_VOLUME);
+#define KSAUDFNAME_LINE_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_LINE_IN_VOLUME)
+
+#define STATIC_KSAUDFNAME_MIC_IN_VOLUME                                        \
+       0x185FEDF5L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF5-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_IN_VOLUME);
+#define KSAUDFNAME_MIC_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIC_IN_VOLUME)
+
+#define STATIC_KSAUDFNAME_WAVE_IN_VOLUME                               \
+       0x185FEDF6L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF6-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_IN_VOLUME);
+#define KSAUDFNAME_WAVE_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_IN_VOLUME)
+
+#define STATIC_KSAUDFNAME_VOLUME_CONTROL                               \
+       0x185FEDF7L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF7-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_VOLUME_CONTROL);
+#define KSAUDFNAME_VOLUME_CONTROL DEFINE_GUIDNAMED(KSAUDFNAME_VOLUME_CONTROL)
+
+#define STATIC_KSAUDFNAME_MIDI                                         \
+       0x185FEDF8L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF8-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI);
+#define KSAUDFNAME_MIDI DEFINE_GUIDNAMED(KSAUDFNAME_MIDI)
+
+#define STATIC_KSAUDFNAME_LINE_IN                                      \
+       0x185FEDF9L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDF9-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_IN);
+#define KSAUDFNAME_LINE_IN DEFINE_GUIDNAMED(KSAUDFNAME_LINE_IN)
+
+#define STATIC_KSAUDFNAME_RECORDING_CONTROL                            \
+       0x185FEDFAL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFA-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_RECORDING_CONTROL);
+#define KSAUDFNAME_RECORDING_CONTROL DEFINE_GUIDNAMED(KSAUDFNAME_RECORDING_CONTROL)
+
+#define STATIC_KSAUDFNAME_CD_AUDIO                                     \
+       0x185FEDFBL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFB-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_AUDIO);
+#define KSAUDFNAME_CD_AUDIO DEFINE_GUIDNAMED(KSAUDFNAME_CD_AUDIO)
+
+#define STATIC_KSAUDFNAME_AUX_VOLUME                                   \
+       0x185FEDFCL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFC-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX_VOLUME);
+#define KSAUDFNAME_AUX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_AUX_VOLUME)
+
+#define STATIC_KSAUDFNAME_AUX_MUTE                                     \
+       0x185FEDFDL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFD-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX_MUTE);
+#define KSAUDFNAME_AUX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_AUX_MUTE)
+
+#define STATIC_KSAUDFNAME_AUX                                          \
+       0x185FEDFEL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFE-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX);
+#define KSAUDFNAME_AUX DEFINE_GUIDNAMED(KSAUDFNAME_AUX)
+
+#define STATIC_KSAUDFNAME_PC_SPEAKER                                   \
+       0x185FEDFFL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEDFF-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER);
+#define KSAUDFNAME_PC_SPEAKER DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER)
+
+#define STATIC_KSAUDFNAME_WAVE_OUT_MIX                                 \
+       0x185FEE00L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("185FEE00-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_OUT_MIX);
+#define KSAUDFNAME_WAVE_OUT_MIX DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_OUT_MIX)
+
+#define STATIC_KSAUDFNAME_MONO_OUT                                     \
+       0xf9b41dc3L,0x96e2,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("F9B41DC3-96E2-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT);
+#define KSAUDFNAME_MONO_OUT DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT)
+
+#define STATIC_KSAUDFNAME_STEREO_MIX                                   \
+       0xdff077L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("00DFF077-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX);
+#define KSAUDFNAME_STEREO_MIX DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX)
+
+#define STATIC_KSAUDFNAME_MONO_MIX                                     \
+       0xdff078L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("00DFF078-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX);
+#define KSAUDFNAME_MONO_MIX DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX)
+
+#define STATIC_KSAUDFNAME_MONO_OUT_VOLUME                              \
+       0x1ad247ebL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("1AD247EB-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT_VOLUME);
+#define KSAUDFNAME_MONO_OUT_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT_VOLUME)
+
+#define STATIC_KSAUDFNAME_MONO_OUT_MUTE                                        \
+       0x1ad247ecL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("1AD247EC-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT_MUTE);
+#define KSAUDFNAME_MONO_OUT_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT_MUTE)
+
+#define STATIC_KSAUDFNAME_STEREO_MIX_VOLUME                            \
+       0x1ad247edL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("1AD247ED-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX_VOLUME);
+#define KSAUDFNAME_STEREO_MIX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX_VOLUME)
+
+#define STATIC_KSAUDFNAME_STEREO_MIX_MUTE                              \
+       0x22b0eafdL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("22B0EAFD-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX_MUTE);
+#define KSAUDFNAME_STEREO_MIX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX_MUTE)
+
+#define STATIC_KSAUDFNAME_MONO_MIX_VOLUME                              \
+       0x22b0eafeL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("22B0EAFE-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX_VOLUME);
+#define KSAUDFNAME_MONO_MIX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX_VOLUME)
+
+#define STATIC_KSAUDFNAME_MONO_MIX_MUTE                                        \
+       0x2bc31d69L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("2BC31D69-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX_MUTE);
+#define KSAUDFNAME_MONO_MIX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX_MUTE)
+
+#define STATIC_KSAUDFNAME_MICROPHONE_BOOST                             \
+       0x2bc31d6aL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("2BC31D6A-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MICROPHONE_BOOST);
+#define KSAUDFNAME_MICROPHONE_BOOST DEFINE_GUIDNAMED(KSAUDFNAME_MICROPHONE_BOOST)
+
+#define STATIC_KSAUDFNAME_ALTERNATE_MICROPHONE                         \
+       0x2bc31d6bL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("2BC31D6B-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_ALTERNATE_MICROPHONE);
+#define KSAUDFNAME_ALTERNATE_MICROPHONE DEFINE_GUIDNAMED(KSAUDFNAME_ALTERNATE_MICROPHONE)
+
+#define STATIC_KSAUDFNAME_3D_DEPTH                                     \
+       0x63ff5747L,0x991f,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("63FF5747-991F-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_3D_DEPTH);
+#define KSAUDFNAME_3D_DEPTH DEFINE_GUIDNAMED(KSAUDFNAME_3D_DEPTH)
+
+#define STATIC_KSAUDFNAME_3D_CENTER                                    \
+       0x9f0670b4L,0x991f,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("9F0670B4-991F-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_3D_CENTER);
+#define KSAUDFNAME_3D_CENTER DEFINE_GUIDNAMED(KSAUDFNAME_3D_CENTER)
+
+#define STATIC_KSAUDFNAME_VIDEO_VOLUME                                 \
+       0x9b46e708L,0x992a,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("9B46E708-992A-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_VIDEO_VOLUME);
+#define KSAUDFNAME_VIDEO_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO_VOLUME)
+
+#define STATIC_KSAUDFNAME_VIDEO_MUTE                                   \
+       0x9b46e709L,0x992a,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("9B46E709-992A-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_VIDEO_MUTE);
+#define KSAUDFNAME_VIDEO_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO_MUTE)
+
+#define STATIC_KSAUDFNAME_VIDEO                                                \
+       0x915daec4L,0xa434,0x11d2,0xac,0x52,0x0,0xc0,0x4f,0x8e,0xfb,0x68
+DEFINE_GUIDSTRUCT("915DAEC4-A434-11d2-AC52-00C04F8EFB68",KSAUDFNAME_VIDEO);
+#define KSAUDFNAME_VIDEO DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO)
+
+#define STATIC_KSAUDFNAME_PEAKMETER                                    \
+       0x57e24340L,0xfc5b,0x4612,0xa5,0x62,0x72,0xb1,0x1a,0x29,0xdf,0xae
+DEFINE_GUIDSTRUCT("57E24340-FC5B-4612-A562-72B11A29DFAE",KSAUDFNAME_PEAKMETER);
+#define KSAUDFNAME_PEAKMETER DEFINE_GUIDNAMED(KSAUDFNAME_PEAKMETER)
+
+#define KSNODEPIN_STANDARD_IN          1
+#define KSNODEPIN_STANDARD_OUT         0
+
+#define KSNODEPIN_SUM_MUX_IN           1
+#define KSNODEPIN_SUM_MUX_OUT          0
+
+#define KSNODEPIN_DEMUX_IN             0
+#define KSNODEPIN_DEMUX_OUT            1
+
+#define KSNODEPIN_AEC_RENDER_IN                1
+#define KSNODEPIN_AEC_RENDER_OUT       0
+#define KSNODEPIN_AEC_CAPTURE_IN       2
+#define KSNODEPIN_AEC_CAPTURE_OUT      3
+
+#define STATIC_KSMETHODSETID_Wavetable                                 \
+       0xDCEF31EBL,0xD907,0x11D0,0x95,0x83,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("DCEF31EB-D907-11D0-9583-00C04FB925D3",KSMETHODSETID_Wavetable);
+#define KSMETHODSETID_Wavetable DEFINE_GUIDNAMED(KSMETHODSETID_Wavetable)
+
+typedef enum {
+  KSMETHOD_WAVETABLE_WAVE_ALLOC,
+  KSMETHOD_WAVETABLE_WAVE_FREE,
+  KSMETHOD_WAVETABLE_WAVE_FIND,
+  KSMETHOD_WAVETABLE_WAVE_WRITE
+} KSMETHOD_WAVETABLE;
+
+typedef struct {
+  KSIDENTIFIER Identifier;
+  ULONG Size;
+  WINBOOL Looped;
+  ULONG LoopPoint;
+  WINBOOL InROM;
+  KSDATAFORMAT Format;
+} KSWAVETABLE_WAVE_DESC,*PKSWAVETABLE_WAVE_DESC;
+
+#define STATIC_KSPROPSETID_Acoustic_Echo_Cancel                                \
+       0xd7a4af8bL,0x3dc1,0x4902,0x91,0xea,0x8a,0x15,0xc9,0x0e,0x05,0xb2
+DEFINE_GUIDSTRUCT("D7A4AF8B-3DC1-4902-91EA-8A15C90E05B2",KSPROPSETID_Acoustic_Echo_Cancel);
+#define KSPROPSETID_Acoustic_Echo_Cancel DEFINE_GUIDNAMED(KSPROPSETID_Acoustic_Echo_Cancel)
+
+typedef enum {
+  KSPROPERTY_AEC_NOISE_FILL_ENABLE = 0,
+  KSPROPERTY_AEC_STATUS,
+  KSPROPERTY_AEC_MODE
+} KSPROPERTY_AEC;
+
+#define AEC_STATUS_FD_HISTORY_UNINITIALIZED            0x0
+#define AEC_STATUS_FD_HISTORY_CONTINUOUSLY_CONVERGED   0x1
+#define AEC_STATUS_FD_HISTORY_PREVIOUSLY_DIVERGED      0x2
+#define AEC_STATUS_FD_CURRENTLY_CONVERGED              0x8
+
+#define AEC_MODE_PASS_THROUGH                          0x0
+#define AEC_MODE_HALF_DUPLEX                           0x1
+#define AEC_MODE_FULL_DUPLEX                           0x2
+
+#define STATIC_KSPROPSETID_Wave                                                \
+       0x924e54b0L,0x630f,0x11cf,0xad,0xa7,0x08,0x00,0x3e,0x30,0x49,0x4a
+DEFINE_GUIDSTRUCT("924e54b0-630f-11cf-ada7-08003e30494a",KSPROPSETID_Wave);
+#define KSPROPSETID_Wave DEFINE_GUIDNAMED(KSPROPSETID_Wave)
+
+typedef enum {
+  KSPROPERTY_WAVE_COMPATIBLE_CAPABILITIES,
+  KSPROPERTY_WAVE_INPUT_CAPABILITIES,
+  KSPROPERTY_WAVE_OUTPUT_CAPABILITIES,
+  KSPROPERTY_WAVE_BUFFER,
+  KSPROPERTY_WAVE_FREQUENCY,
+  KSPROPERTY_WAVE_VOLUME,
+  KSPROPERTY_WAVE_PAN
+} KSPROPERTY_WAVE;
+
+typedef struct {
+  ULONG ulDeviceType;
+} KSWAVE_COMPATCAPS,*PKSWAVE_COMPATCAPS;
+
+#define KSWAVE_COMPATCAPS_INPUT                0x00000000
+#define KSWAVE_COMPATCAPS_OUTPUT       0x00000001
+
+typedef struct {
+  ULONG MaximumChannelsPerConnection;
+  ULONG MinimumBitsPerSample;
+  ULONG MaximumBitsPerSample;
+  ULONG MinimumSampleFrequency;
+  ULONG MaximumSampleFrequency;
+  ULONG TotalConnections;
+  ULONG ActiveConnections;
+} KSWAVE_INPUT_CAPABILITIES,*PKSWAVE_INPUT_CAPABILITIES;
+
+typedef struct {
+  ULONG MaximumChannelsPerConnection;
+  ULONG MinimumBitsPerSample;
+  ULONG MaximumBitsPerSample;
+  ULONG MinimumSampleFrequency;
+  ULONG MaximumSampleFrequency;
+  ULONG TotalConnections;
+  ULONG StaticConnections;
+  ULONG StreamingConnections;
+  ULONG ActiveConnections;
+  ULONG ActiveStaticConnections;
+  ULONG ActiveStreamingConnections;
+  ULONG Total3DConnections;
+  ULONG Static3DConnections;
+  ULONG Streaming3DConnections;
+  ULONG Active3DConnections;
+  ULONG ActiveStatic3DConnections;
+  ULONG ActiveStreaming3DConnections;
+  ULONG TotalSampleMemory;
+  ULONG FreeSampleMemory;
+  ULONG LargestFreeContiguousSampleMemory;
+} KSWAVE_OUTPUT_CAPABILITIES,*PKSWAVE_OUTPUT_CAPABILITIES;
+
+typedef struct {
+  LONG LeftAttenuation;
+  LONG RightAttenuation;
+} KSWAVE_VOLUME,*PKSWAVE_VOLUME;
+
+#define KSWAVE_BUFFER_ATTRIBUTEF_LOOPING       0x00000001
+#define KSWAVE_BUFFER_ATTRIBUTEF_STATIC                0x00000002
+
+typedef struct {
+  ULONG Attributes;
+  ULONG BufferSize;
+  PVOID BufferAddress;
+} KSWAVE_BUFFER,*PKSWAVE_BUFFER;
+
+#define STATIC_KSMUSIC_TECHNOLOGY_PORT                                 \
+       0x86C92E60L,0x62E8,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("86C92E60-62E8-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_PORT);
+#define KSMUSIC_TECHNOLOGY_PORT DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_PORT)
+
+#define STATIC_KSMUSIC_TECHNOLOGY_SQSYNTH                              \
+       0x0ECF4380L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("0ECF4380-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_SQSYNTH);
+#define KSMUSIC_TECHNOLOGY_SQSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_SQSYNTH)
+
+#define STATIC_KSMUSIC_TECHNOLOGY_FMSYNTH                              \
+       0x252C5C80L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("252C5C80-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_FMSYNTH);
+#define KSMUSIC_TECHNOLOGY_FMSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_FMSYNTH)
+
+#define STATIC_KSMUSIC_TECHNOLOGY_WAVETABLE                            \
+       0x394EC7C0L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("394EC7C0-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_WAVETABLE);
+#define KSMUSIC_TECHNOLOGY_WAVETABLE DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_WAVETABLE)
+
+#define STATIC_KSMUSIC_TECHNOLOGY_SWSYNTH                              \
+       0x37407736L,0x3620,0x11D1,0x85,0xD3,0x00,0x00,0xF8,0x75,0x43,0x80
+DEFINE_GUIDSTRUCT("37407736-3620-11D1-85D3-0000F8754380",KSMUSIC_TECHNOLOGY_SWSYNTH);
+#define KSMUSIC_TECHNOLOGY_SWSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_SWSYNTH)
+
+#define STATIC_KSPROPSETID_WaveTable                                   \
+       0x8539E660L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("8539E660-62E9-11CF-A5D6-28DB04C10000",KSPROPSETID_WaveTable);
+#define KSPROPSETID_WaveTable DEFINE_GUIDNAMED(KSPROPSETID_WaveTable)
+
+typedef enum {
+  KSPROPERTY_WAVETABLE_LOAD_SAMPLE,
+  KSPROPERTY_WAVETABLE_UNLOAD_SAMPLE,
+  KSPROPERTY_WAVETABLE_MEMORY,
+  KSPROPERTY_WAVETABLE_VERSION
+} KSPROPERTY_WAVETABLE;
+
+typedef struct {
+  KSDATARANGE DataRange;
+  GUID Technology;
+  ULONG Channels;
+  ULONG Notes;
+  ULONG ChannelMask;
+} KSDATARANGE_MUSIC,*PKSDATARANGE_MUSIC;
+
+#define STATIC_KSEVENTSETID_Cyclic                                     \
+       0x142C1AC0L,0x072A,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("142C1AC0-072A-11D0-A5D6-28DB04C10000",KSEVENTSETID_Cyclic);
+#define KSEVENTSETID_Cyclic DEFINE_GUIDNAMED(KSEVENTSETID_Cyclic)
+
+typedef enum {
+  KSEVENT_CYCLIC_TIME_INTERVAL
+} KSEVENT_CYCLIC_TIME;
+
+#define STATIC_KSPROPSETID_Cyclic                                      \
+       0x3FFEAEA0L,0x2BEE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("3FFEAEA0-2BEE-11CF-A5D6-28DB04C10000",KSPROPSETID_Cyclic);
+#define KSPROPSETID_Cyclic DEFINE_GUIDNAMED(KSPROPSETID_Cyclic)
+
+typedef enum {
+  KSPROPERTY_CYCLIC_POSITION
+} KSPROPERTY_CYCLIC;
+
+#define STATIC_KSEVENTSETID_AudioControlChange                         \
+       0xE85E9698L,0xFA2F,0x11D1,0x95,0xBD,0x00,0xC0,0x4F,0xB9,0x25,0xD3
+DEFINE_GUIDSTRUCT("E85E9698-FA2F-11D1-95BD-00C04FB925D3",KSEVENTSETID_AudioControlChange);
+#define KSEVENTSETID_AudioControlChange DEFINE_GUIDNAMED(KSEVENTSETID_AudioControlChange)
+
+typedef enum {
+  KSEVENT_CONTROL_CHANGE
+} KSEVENT_AUDIO_CONTROL_CHANGE;
+
+#define STATIC_KSEVENTSETID_LoopedStreaming                            \
+       0x4682B940L,0xC6EF,0x11D0,0x96,0xD8,0x00,0xAA,0x00,0x51,0xE5,0x1D
+DEFINE_GUIDSTRUCT("4682B940-C6EF-11D0-96D8-00AA0051E51D",KSEVENTSETID_LoopedStreaming);
+#define KSEVENTSETID_LoopedStreaming DEFINE_GUIDNAMED(KSEVENTSETID_LoopedStreaming)
+
+typedef enum {
+  KSEVENT_LOOPEDSTREAMING_POSITION
+} KSEVENT_LOOPEDSTREAMING;
+
+typedef struct {
+  KSEVENTDATA KsEventData;
+  DWORDLONG Position;
+} LOOPEDSTREAMING_POSITION_EVENT_DATA,*PLOOPEDSTREAMING_POSITION_EVENT_DATA;
+
+#define STATIC_KSPROPSETID_Sysaudio                                    \
+       0xCBE3FAA0L,0xCC75,0x11D0,0xB4,0x65,0x00,0x00,0x1A,0x18,0x18,0xE6
+DEFINE_GUIDSTRUCT("CBE3FAA0-CC75-11D0-B465-00001A1818E6",KSPROPSETID_Sysaudio);
+#define KSPROPSETID_Sysaudio DEFINE_GUIDNAMED(KSPROPSETID_Sysaudio)
+
+typedef enum {
+  KSPROPERTY_SYSAUDIO_DEVICE_COUNT = 1,
+  KSPROPERTY_SYSAUDIO_DEVICE_FRIENDLY_NAME = 2,
+  KSPROPERTY_SYSAUDIO_DEVICE_INSTANCE = 3,
+  KSPROPERTY_SYSAUDIO_DEVICE_INTERFACE_NAME = 4,
+  KSPROPERTY_SYSAUDIO_SELECT_GRAPH = 5,
+  KSPROPERTY_SYSAUDIO_CREATE_VIRTUAL_SOURCE = 6,
+  KSPROPERTY_SYSAUDIO_DEVICE_DEFAULT = 7,
+  KSPROPERTY_SYSAUDIO_INSTANCE_INFO = 14,
+  KSPROPERTY_SYSAUDIO_COMPONENT_ID = 16
+} KSPROPERTY_SYSAUDIO;
+
+typedef struct {
+  KSPROPERTY Property;
+  GUID PinCategory;
+  GUID PinName;
+} SYSAUDIO_CREATE_VIRTUAL_SOURCE,*PSYSAUDIO_CREATE_VIRTUAL_SOURCE;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG PinId;
+  ULONG NodeId;
+  ULONG Flags;
+  ULONG Reserved;
+} SYSAUDIO_SELECT_GRAPH,*PSYSAUDIO_SELECT_GRAPH;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Flags;
+  ULONG DeviceNumber;
+} SYSAUDIO_INSTANCE_INFO,*PSYSAUDIO_INSTANCE_INFO;
+
+#define SYSAUDIO_FLAGS_DONT_COMBINE_PINS       0x00000001
+
+#define STATIC_KSPROPSETID_Sysaudio_Pin                                        \
+       0xA3A53220L,0xC6E4,0x11D0,0xB4,0x65,0x00,0x00,0x1A,0x18,0x18,0xE6
+DEFINE_GUIDSTRUCT("A3A53220-C6E4-11D0-B465-00001A1818E6",KSPROPSETID_Sysaudio_Pin);
+#define KSPROPSETID_Sysaudio_Pin DEFINE_GUIDNAMED(KSPROPSETID_Sysaudio_Pin)
+
+typedef enum {
+  KSPROPERTY_SYSAUDIO_ATTACH_VIRTUAL_SOURCE = 1
+} KSPROPERTY_SYSAUDIO_PIN;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG MixerPinId;
+  ULONG Reserved;
+} SYSAUDIO_ATTACH_VIRTUAL_SOURCE,*PSYSAUDIO_ATTACH_VIRTUAL_SOURCE;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG NodeId;
+  ULONG Reserved;
+} KSNODEPROPERTY,*PKSNODEPROPERTY;
+
+typedef struct {
+  KSNODEPROPERTY NodeProperty;
+  LONG Channel;
+  ULONG Reserved;
+} KSNODEPROPERTY_AUDIO_CHANNEL,*PKSNODEPROPERTY_AUDIO_CHANNEL;
+
+typedef struct {
+  KSNODEPROPERTY NodeProperty;
+  ULONG DevSpecificId;
+  ULONG DeviceInfo;
+  ULONG Length;
+} KSNODEPROPERTY_AUDIO_DEV_SPECIFIC,*PKSNODEPROPERTY_AUDIO_DEV_SPECIFIC;
+
+typedef struct {
+  KSNODEPROPERTY NodeProperty;
+  PVOID ListenerId;
+#ifndef _WIN64
+  ULONG Reserved;
+#endif
+} KSNODEPROPERTY_AUDIO_3D_LISTENER,*PKSNODEPROPERTY_AUDIO_3D_LISTENER;
+
+typedef struct {
+  KSNODEPROPERTY NodeProperty;
+  PVOID AppContext;
+  ULONG Length;
+#ifndef _WIN64
+  ULONG Reserved;
+#endif
+} KSNODEPROPERTY_AUDIO_PROPERTY,*PKSNODEPROPERTY_AUDIO_PROPERTY;
+
+#define STATIC_KSPROPSETID_AudioGfx                                    \
+       0x79a9312eL,0x59ae,0x43b0,0xa3,0x50,0x8b,0x5,0x28,0x4c,0xab,0x24
+DEFINE_GUIDSTRUCT("79A9312E-59AE-43b0-A350-8B05284CAB24",KSPROPSETID_AudioGfx);
+#define KSPROPSETID_AudioGfx DEFINE_GUIDNAMED(KSPROPSETID_AudioGfx)
+
+typedef enum {
+  KSPROPERTY_AUDIOGFX_RENDERTARGETDEVICEID,
+  KSPROPERTY_AUDIOGFX_CAPTURETARGETDEVICEID
+} KSPROPERTY_AUDIOGFX;
+
+#define STATIC_KSPROPSETID_Linear                                      \
+       0x5A2FFE80L,0x16B9,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("5A2FFE80-16B9-11D0-A5D6-28DB04C10000",KSPROPSETID_Linear);
+#define KSPROPSETID_Linear DEFINE_GUIDNAMED(KSPROPSETID_Linear)
+
+typedef enum {
+  KSPROPERTY_LINEAR_POSITION
+} KSPROPERTY_LINEAR;
+
+#define STATIC_KSDATAFORMAT_TYPE_MUSIC                                 \
+       0xE725D360L,0x62CC,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("E725D360-62CC-11CF-A5D6-28DB04C10000",KSDATAFORMAT_TYPE_MUSIC);
+#define KSDATAFORMAT_TYPE_MUSIC DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MUSIC)
+
+#define STATIC_KSDATAFORMAT_TYPE_MIDI                                  \
+       0x7364696DL,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
+DEFINE_GUIDSTRUCT("7364696D-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_MIDI);
+#define KSDATAFORMAT_TYPE_MIDI DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MIDI)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MIDI                               \
+       0x1D262760L,0xE957,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("1D262760-E957-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SUBTYPE_MIDI);
+#define KSDATAFORMAT_SUBTYPE_MIDI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MIDI)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MIDI_BUS                           \
+       0x2CA15FA0L,0x6CFE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
+DEFINE_GUIDSTRUCT("2CA15FA0-6CFE-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SUBTYPE_MIDI_BUS);
+#define KSDATAFORMAT_SUBTYPE_MIDI_BUS DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MIDI_BUS)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_RIFFMIDI                           \
+       0x4995DAF0L,0x9EE6,0x11D0,0xA4,0x0E,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("4995DAF0-9EE6-11D0-A40E-00A0C9223196",KSDATAFORMAT_SUBTYPE_RIFFMIDI);
+#define KSDATAFORMAT_SUBTYPE_RIFFMIDI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFFMIDI)
+
+typedef struct {
+  ULONG TimeDeltaMs;
+
+  ULONG ByteCount;
+} KSMUSICFORMAT,*PKSMUSICFORMAT;
+
+#define STATIC_KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM            \
+       0x36523b11L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B11-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM);
+#define KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM)
+
+#define STATIC_KSDATAFORMAT_TYPE_STANDARD_PES_PACKET                   \
+       0x36523b12L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B12-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_PES_PACKET);
+#define KSDATAFORMAT_TYPE_STANDARD_PES_PACKET DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_PES_PACKET)
+
+#define STATIC_KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER                  \
+       0x36523b13L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B13-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER);
+#define KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO               \
+       0x36523b21L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B21-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO);
+#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO               \
+       0x36523b22L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B22-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO               \
+       0x36523b23L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B23-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO);
+#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO               \
+       0x36523b24L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B24-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO                 \
+       0x36523b25L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B25-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO              \
+       0x36523b31L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B31-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO);
+#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO              \
+       0x36523b32L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B32-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO              \
+       0x36523b33L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B33-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO);
+#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO              \
+       0x36523b34L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B34-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO                        \
+       0x36523b35L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
+DEFINE_GUIDSTRUCT("36523B35-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_DSS_VIDEO                          \
+       0xa0af4f81L,0xe163,0x11d0,0xba,0xd9,0x00,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("a0af4f81-e163-11d0-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_DSS_VIDEO);
+#define KSDATAFORMAT_SUBTYPE_DSS_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DSS_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_DSS_AUDIO                          \
+               0xa0af4f82L,0xe163,0x11d0,0xba,0xd9,0x00,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("a0af4f82-e163-11d0-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_DSS_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_DSS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DSS_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Packet                                \
+       0xe436eb80,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
+DEFINE_GUIDSTRUCT("e436eb80-524f-11ce-9F53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Packet);
+#define KSDATAFORMAT_SUBTYPE_MPEG1Packet DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Packet)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Payload                       \
+       0xe436eb81,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
+DEFINE_GUIDSTRUCT("e436eb81-524f-11ce-9F53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Payload);
+#define KSDATAFORMAT_SUBTYPE_MPEG1Payload DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Payload)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Video                         \
+       0xe436eb86,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
+DEFINE_GUIDSTRUCT("e436eb86-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Video);
+#define KSDATAFORMAT_SUBTYPE_MPEG1Video DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Video)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO                      \
+       0x05589f82L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
+DEFINE_GUIDSTRUCT("05589f82-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO);
+#define KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO)
+
+#define STATIC_KSDATAFORMAT_TYPE_MPEG2_PES                             \
+       0xe06d8020L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8020-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_PES);
+#define KSDATAFORMAT_TYPE_MPEG2_PES DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_PES)
+
+#define STATIC_KSDATAFORMAT_TYPE_MPEG2_PROGRAM                         \
+       0xe06d8022L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8022-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_PROGRAM);
+#define KSDATAFORMAT_TYPE_MPEG2_PROGRAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_PROGRAM)
+
+#define STATIC_KSDATAFORMAT_TYPE_MPEG2_TRANSPORT                       \
+       0xe06d8023L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8023-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_TRANSPORT);
+#define KSDATAFORMAT_TYPE_MPEG2_TRANSPORT DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_TRANSPORT)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO                                \
+       0xe06d8026L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8026-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO);
+#define KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO                      \
+       0xe06d80e3L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d80e3-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO);
+#define KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO)
+
+#define STATIC_KSPROPSETID_Mpeg2Vid                                    \
+       0xC8E11B60L,0x0CC9,0x11D0,0xBD,0x69,0x00,0x35,0x05,0xC1,0x03,0xA9
+DEFINE_GUIDSTRUCT("C8E11B60-0CC9-11D0-BD69-003505C103A9",KSPROPSETID_Mpeg2Vid);
+#define KSPROPSETID_Mpeg2Vid DEFINE_GUIDNAMED(KSPROPSETID_Mpeg2Vid)
+
+typedef enum {
+  KSPROPERTY_MPEG2VID_MODES,
+  KSPROPERTY_MPEG2VID_CUR_MODE,
+  KSPROPERTY_MPEG2VID_4_3_RECT,
+  KSPROPERTY_MPEG2VID_16_9_RECT,
+  KSPROPERTY_MPEG2VID_16_9_PANSCAN
+} KSPROPERTY_MPEG2VID;
+
+#define KSMPEGVIDMODE_PANSCAN  0x0001
+#define KSMPEGVIDMODE_LTRBOX   0x0002
+#define KSMPEGVIDMODE_SCALE    0x0004
+
+typedef struct _KSMPEGVID_RECT {
+  ULONG StartX;
+  ULONG StartY;
+  ULONG EndX;
+  ULONG EndY;
+} KSMPEGVID_RECT,*PKSMPEGVID_RECT;
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO                                \
+       0xe06d802bL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d802b-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO                      \
+       0xe06d80e5L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d80e5-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_LPCM_AUDIO                         \
+       0xe06d8032L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8032-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_LPCM_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_LPCM_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_LPCM_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_LPCM_AUDIO                       \
+       0xe06d80e6L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d80e6-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_LPCM_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_LPCM_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_LPCM_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_AC3_AUDIO                          \
+       0xe06d802cL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d802c-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_AC3_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_AC3_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_AC3_AUDIO                                \
+       0xe06d80e4L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d80e4-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_AC3_AUDIO);
+#define KSDATAFORMAT_SPECIFIER_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_AC3_AUDIO)
+
+#define STATIC_KSPROPSETID_AC3                                         \
+       0xBFABE720L,0x6E1F,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
+DEFINE_GUIDSTRUCT("BFABE720-6E1F-11D0-BCF2-444553540000",KSPROPSETID_AC3);
+#define KSPROPSETID_AC3 DEFINE_GUIDNAMED(KSPROPSETID_AC3)
+
+typedef enum {
+  KSPROPERTY_AC3_ERROR_CONCEALMENT = 1,
+  KSPROPERTY_AC3_ALTERNATE_AUDIO,
+  KSPROPERTY_AC3_DOWNMIX,
+  KSPROPERTY_AC3_BIT_STREAM_MODE,
+  KSPROPERTY_AC3_DIALOGUE_LEVEL,
+  KSPROPERTY_AC3_LANGUAGE_CODE,
+  KSPROPERTY_AC3_ROOM_TYPE
+} KSPROPERTY_AC3;
+
+typedef struct {
+  WINBOOL fRepeatPreviousBlock;
+  WINBOOL fErrorInCurrentBlock;
+} KSAC3_ERROR_CONCEALMENT,*PKSAC3_ERROR_CONCEALMENT;
+
+typedef struct {
+  WINBOOL fStereo;
+  ULONG DualMode;
+} KSAC3_ALTERNATE_AUDIO,*PKSAC3_ALTERNATE_AUDIO;
+
+#define KSAC3_ALTERNATE_AUDIO_1                1
+#define KSAC3_ALTERNATE_AUDIO_2                2
+#define KSAC3_ALTERNATE_AUDIO_BOTH     3
+
+typedef struct {
+  WINBOOL fDownMix;
+  WINBOOL fDolbySurround;
+} KSAC3_DOWNMIX,*PKSAC3_DOWNMIX;
+
+typedef struct {
+  LONG BitStreamMode;
+} KSAC3_BIT_STREAM_MODE,*PKSAC3_BIT_STREAM_MODE;
+
+#define KSAC3_SERVICE_MAIN_AUDIO       0
+#define KSAC3_SERVICE_NO_DIALOG                1
+#define KSAC3_SERVICE_VISUALLY_IMPAIRED        2
+#define KSAC3_SERVICE_HEARING_IMPAIRED 3
+#define KSAC3_SERVICE_DIALOG_ONLY      4
+#define KSAC3_SERVICE_COMMENTARY       5
+#define KSAC3_SERVICE_EMERGENCY_FLASH  6
+#define KSAC3_SERVICE_VOICE_OVER       7
+
+typedef struct {
+  ULONG DialogueLevel;
+} KSAC3_DIALOGUE_LEVEL,*PKSAC3_DIALOGUE_LEVEL;
+
+typedef struct {
+  WINBOOL fLargeRoom;
+} KSAC3_ROOM_TYPE,*PKSAC3_ROOM_TYPE;
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_DTS_AUDIO                          \
+       0xe06d8033L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8033-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_DTS_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_DTS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DTS_AUDIO)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_SDDS_AUDIO                         \
+       0xe06d8034L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d8034-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_SDDS_AUDIO);
+#define KSDATAFORMAT_SUBTYPE_SDDS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_SDDS_AUDIO)
+
+#define STATIC_KSPROPSETID_AudioDecoderOut                             \
+       0x6ca6e020L,0x43bd,0x11d0,0xbd,0x6a,0x00,0x35,0x05,0xc1,0x03,0xa9
+DEFINE_GUIDSTRUCT("6ca6e020-43bd-11d0-bd6a-003505c103a9",KSPROPSETID_AudioDecoderOut);
+#define KSPROPSETID_AudioDecoderOut DEFINE_GUIDNAMED(KSPROPSETID_AudioDecoderOut)
+
+typedef enum {
+  KSPROPERTY_AUDDECOUT_MODES,
+  KSPROPERTY_AUDDECOUT_CUR_MODE
+} KSPROPERTY_AUDDECOUT;
+
+#define KSAUDDECOUTMODE_STEREO_ANALOG  0x0001
+#define KSAUDDECOUTMODE_PCM_51         0x0002
+#define KSAUDDECOUTMODE_SPDIFF         0x0004
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_SUBPICTURE                         \
+       0xe06d802dL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
+DEFINE_GUIDSTRUCT("e06d802d-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_SUBPICTURE);
+#define KSDATAFORMAT_SUBTYPE_SUBPICTURE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_SUBPICTURE)
+
+#define STATIC_KSPROPSETID_DvdSubPic                                   \
+       0xac390460L,0x43af,0x11d0,0xbd,0x6a,0x00,0x35,0x05,0xc1,0x03,0xa9
+DEFINE_GUIDSTRUCT("ac390460-43af-11d0-bd6a-003505c103a9",KSPROPSETID_DvdSubPic);
+#define KSPROPSETID_DvdSubPic DEFINE_GUIDNAMED(KSPROPSETID_DvdSubPic)
+
+typedef enum {
+  KSPROPERTY_DVDSUBPIC_PALETTE,
+  KSPROPERTY_DVDSUBPIC_HLI,
+  KSPROPERTY_DVDSUBPIC_COMPOSIT_ON
+} KSPROPERTY_DVDSUBPIC;
+
+typedef struct _KS_DVD_YCrCb {
+  UCHAR Reserved;
+  UCHAR Y;
+  UCHAR Cr;
+  UCHAR Cb;
+} KS_DVD_YCrCb,*PKS_DVD_YCrCb;
+
+typedef struct _KS_DVD_YUV {
+  UCHAR Reserved;
+  UCHAR Y;
+  UCHAR V;
+  UCHAR U;
+} KS_DVD_YUV,*PKS_DVD_YUV;
+
+typedef struct _KSPROPERTY_SPPAL {
+  KS_DVD_YUV sppal[16];
+} KSPROPERTY_SPPAL,*PKSPROPERTY_SPPAL;
+
+typedef struct _KS_COLCON {
+  UCHAR emph1col:4;
+  UCHAR emph2col:4;
+  UCHAR backcol:4;
+  UCHAR patcol:4;
+  UCHAR emph1con:4;
+  UCHAR emph2con:4;
+  UCHAR backcon:4;
+  UCHAR patcon:4;
+} KS_COLCON,*PKS_COLCON;
+
+typedef struct _KSPROPERTY_SPHLI {
+  USHORT HLISS;
+  USHORT Reserved;
+  ULONG StartPTM;
+  ULONG EndPTM;
+  USHORT StartX;
+  USHORT StartY;
+  USHORT StopX;
+  USHORT StopY;
+  KS_COLCON ColCon;
+} KSPROPERTY_SPHLI,*PKSPROPERTY_SPHLI;
+
+typedef WINBOOL KSPROPERTY_COMPOSIT_ON,*PKSPROPERTY_COMPOSIT_ON;
+
+#define STATIC_KSPROPSETID_CopyProt                                    \
+       0x0E8A0A40L,0x6AEF,0x11D0,0x9E,0xD0,0x00,0xA0,0x24,0xCA,0x19,0xB3
+DEFINE_GUIDSTRUCT("0E8A0A40-6AEF-11D0-9ED0-00A024CA19B3",KSPROPSETID_CopyProt);
+#define KSPROPSETID_CopyProt DEFINE_GUIDNAMED(KSPROPSETID_CopyProt)
+
+typedef enum {
+  KSPROPERTY_DVDCOPY_CHLG_KEY = 0x01,
+  KSPROPERTY_DVDCOPY_DVD_KEY1,
+  KSPROPERTY_DVDCOPY_DEC_KEY2,
+  KSPROPERTY_DVDCOPY_TITLE_KEY,
+  KSPROPERTY_COPY_MACROVISION,
+  KSPROPERTY_DVDCOPY_REGION,
+  KSPROPERTY_DVDCOPY_SET_COPY_STATE,
+  KSPROPERTY_DVDCOPY_DISC_KEY = 0x80
+} KSPROPERTY_COPYPROT;
+
+typedef struct _KS_DVDCOPY_CHLGKEY {
+  BYTE ChlgKey[10];
+  BYTE Reserved[2];
+} KS_DVDCOPY_CHLGKEY,*PKS_DVDCOPY_CHLGKEY;
+
+typedef struct _KS_DVDCOPY_BUSKEY {
+  BYTE BusKey[5];
+  BYTE Reserved[1];
+} KS_DVDCOPY_BUSKEY,*PKS_DVDCOPY_BUSKEY;
+
+typedef struct _KS_DVDCOPY_DISCKEY {
+  BYTE DiscKey[2048];
+} KS_DVDCOPY_DISCKEY,*PKS_DVDCOPY_DISCKEY;
+
+typedef struct _KS_DVDCOPY_REGION {
+  UCHAR Reserved;
+  UCHAR RegionData;
+  UCHAR Reserved2[2];
+} KS_DVDCOPY_REGION,*PKS_DVDCOPY_REGION;
+
+typedef struct _KS_DVDCOPY_TITLEKEY {
+  ULONG KeyFlags;
+  ULONG ReservedNT[2];
+  UCHAR TitleKey[6];
+  UCHAR Reserved[2];
+} KS_DVDCOPY_TITLEKEY,*PKS_DVDCOPY_TITLEKEY;
+
+typedef struct _KS_COPY_MACROVISION {
+  ULONG MACROVISIONLevel;
+} KS_COPY_MACROVISION,*PKS_COPY_MACROVISION;
+
+typedef struct _KS_DVDCOPY_SET_COPY_STATE {
+  ULONG DVDCopyState;
+} KS_DVDCOPY_SET_COPY_STATE,*PKS_DVDCOPY_SET_COPY_STATE;
+
+typedef enum {
+  KS_DVDCOPYSTATE_INITIALIZE,
+  KS_DVDCOPYSTATE_INITIALIZE_TITLE,
+  KS_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED,
+  KS_DVDCOPYSTATE_AUTHENTICATION_REQUIRED,
+  KS_DVDCOPYSTATE_DONE
+} KS_DVDCOPYSTATE;
+
+typedef enum {
+  KS_MACROVISION_DISABLED,
+  KS_MACROVISION_LEVEL1,
+  KS_MACROVISION_LEVEL2,
+  KS_MACROVISION_LEVEL3
+} KS_COPY_MACROVISION_LEVEL,*PKS_COPY_MACROVISION_LEVEL;
+
+#define KS_DVD_CGMS_RESERVED_MASK      0x00000078
+
+#define KS_DVD_CGMS_COPY_PROTECT_MASK  0x00000018
+#define KS_DVD_CGMS_COPY_PERMITTED     0x00000000
+#define KS_DVD_CGMS_COPY_ONCE          0x00000010
+#define KS_DVD_CGMS_NO_COPY            0x00000018
+
+#define KS_DVD_COPYRIGHT_MASK          0x00000040
+#define KS_DVD_NOT_COPYRIGHTED         0x00000000
+#define KS_DVD_COPYRIGHTED             0x00000040
+
+#define KS_DVD_SECTOR_PROTECT_MASK     0x00000020
+#define KS_DVD_SECTOR_NOT_PROTECTED    0x00000000
+#define KS_DVD_SECTOR_PROTECTED                0x00000020
+
+#define STATIC_KSCATEGORY_TVTUNER                                      \
+       0xa799a800L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
+DEFINE_GUIDSTRUCT("a799a800-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_TVTUNER);
+#define KSCATEGORY_TVTUNER DEFINE_GUIDNAMED(KSCATEGORY_TVTUNER)
+
+#define STATIC_KSCATEGORY_CROSSBAR                                     \
+       0xa799a801L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
+DEFINE_GUIDSTRUCT("a799a801-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_CROSSBAR);
+#define KSCATEGORY_CROSSBAR DEFINE_GUIDNAMED(KSCATEGORY_CROSSBAR)
+
+#define STATIC_KSCATEGORY_TVAUDIO                                      \
+       0xa799a802L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
+DEFINE_GUIDSTRUCT("a799a802-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_TVAUDIO);
+#define KSCATEGORY_TVAUDIO DEFINE_GUIDNAMED(KSCATEGORY_TVAUDIO)
+
+#define STATIC_KSCATEGORY_VPMUX                                                \
+       0xa799a803L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
+DEFINE_GUIDSTRUCT("a799a803-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_VPMUX);
+#define KSCATEGORY_VPMUX DEFINE_GUIDNAMED(KSCATEGORY_VPMUX)
+
+#define STATIC_KSCATEGORY_VBICODEC                                     \
+       0x07dad660L,0x22f1,0x11d1,0xa9,0xf4,0x00,0xc0,0x4f,0xbb,0xde,0x8f
+DEFINE_GUIDSTRUCT("07dad660-22f1-11d1-a9f4-00c04fbbde8f",KSCATEGORY_VBICODEC);
+#define KSCATEGORY_VBICODEC DEFINE_GUIDNAMED(KSCATEGORY_VBICODEC)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_VPVideo                            \
+       0x5a9b6a40L,0x1a22,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("5a9b6a40-1a22-11d1-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_VPVideo);
+#define KSDATAFORMAT_SUBTYPE_VPVideo DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_VPVideo)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_VPVBI                              \
+       0x5a9b6a41L,0x1a22,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("5a9b6a41-1a22-11d1-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_VPVBI);
+#define KSDATAFORMAT_SUBTYPE_VPVBI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_VPVBI)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_VIDEOINFO                                \
+       0x05589f80L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
+DEFINE_GUIDSTRUCT("05589f80-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_VIDEOINFO);
+#define KSDATAFORMAT_SPECIFIER_VIDEOINFO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VIDEOINFO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_VIDEOINFO2                       \
+       0xf72a76A0L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("f72a76A0-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SPECIFIER_VIDEOINFO2);
+#define KSDATAFORMAT_SPECIFIER_VIDEOINFO2 DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VIDEOINFO2)
+
+#define STATIC_KSDATAFORMAT_TYPE_ANALOGVIDEO                           \
+       0x0482dde1L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
+DEFINE_GUIDSTRUCT("0482dde1-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_TYPE_ANALOGVIDEO);
+#define KSDATAFORMAT_TYPE_ANALOGVIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_ANALOGVIDEO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_ANALOGVIDEO                      \
+       0x0482dde0L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
+DEFINE_GUIDSTRUCT("0482dde0-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_SPECIFIER_ANALOGVIDEO);
+#define KSDATAFORMAT_SPECIFIER_ANALOGVIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_ANALOGVIDEO)
+
+#define STATIC_KSDATAFORMAT_TYPE_ANALOGAUDIO                           \
+       0x0482dee1L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
+DEFINE_GUIDSTRUCT("0482DEE1-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_TYPE_ANALOGAUDIO);
+#define KSDATAFORMAT_TYPE_ANALOGAUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_ANALOGAUDIO)
+
+#define STATIC_KSDATAFORMAT_SPECIFIER_VBI                              \
+       0xf72a76e0L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("f72a76e0-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SPECIFIER_VBI);
+#define KSDATAFORMAT_SPECIFIER_VBI DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VBI)
+
+#define STATIC_KSDATAFORMAT_TYPE_VBI                                   \
+       0xf72a76e1L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("f72a76e1-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_TYPE_VBI);
+#define KSDATAFORMAT_TYPE_VBI DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_VBI)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_RAW8                               \
+       0xca20d9a0,0x3e3e,0x11d1,0x9b,0xf9,0x0,0xc0,0x4f,0xbb,0xde,0xbf
+DEFINE_GUIDSTRUCT("ca20d9a0-3e3e-11d1-9bf9-00c04fbbdebf",KSDATAFORMAT_SUBTYPE_RAW8);
+#define KSDATAFORMAT_SUBTYPE_RAW8 DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RAW8)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_CC                                 \
+       0x33214cc1,0x11f,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
+DEFINE_GUIDSTRUCT("33214CC1-011F-11D2-B4B1-00A0D102CFBE",KSDATAFORMAT_SUBTYPE_CC);
+#define KSDATAFORMAT_SUBTYPE_CC DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_CC)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_NABTS                              \
+       0xf72a76e2L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("f72a76e2-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SUBTYPE_NABTS);
+#define KSDATAFORMAT_SUBTYPE_NABTS DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NABTS)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_TELETEXT                           \
+       0xf72a76e3L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("f72a76e3-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SUBTYPE_TELETEXT);
+#define KSDATAFORMAT_SUBTYPE_TELETEXT DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_TELETEXT)
+
+#define KS_BI_RGB              0L
+#define KS_BI_RLE8             1L
+#define KS_BI_RLE4             2L
+#define KS_BI_BITFIELDS                3L
+
+typedef struct tagKS_RGBQUAD {
+  BYTE rgbBlue;
+  BYTE rgbGreen;
+  BYTE rgbRed;
+  BYTE rgbReserved;
+} KS_RGBQUAD,*PKS_RGBQUAD;
+
+#define KS_iPALETTE_COLORS     256
+#define KS_iEGA_COLORS         16
+#define KS_iMASK_COLORS                3
+#define KS_iTRUECOLOR          16
+#define KS_iRED                        0
+#define KS_iGREEN              1
+#define KS_iBLUE               2
+#define KS_iPALETTE            8
+#define KS_iMAXBITS            8
+#define KS_SIZE_EGA_PALETTE    (KS_iEGA_COLORS *sizeof(KS_RGBQUAD))
+#define KS_SIZE_PALETTE                (KS_iPALETTE_COLORS *sizeof(KS_RGBQUAD))
+
+typedef struct tagKS_BITMAPINFOHEADER {
+  DWORD biSize;
+  LONG biWidth;
+  LONG biHeight;
+  WORD biPlanes;
+  WORD biBitCount;
+  DWORD biCompression;
+  DWORD biSizeImage;
+  LONG biXPelsPerMeter;
+  LONG biYPelsPerMeter;
+  DWORD biClrUsed;
+  DWORD biClrImportant;
+} KS_BITMAPINFOHEADER,*PKS_BITMAPINFOHEADER;
+
+typedef struct tag_KS_TRUECOLORINFO {
+  DWORD dwBitMasks[KS_iMASK_COLORS];
+  KS_RGBQUAD bmiColors[KS_iPALETTE_COLORS];
+} KS_TRUECOLORINFO,*PKS_TRUECOLORINFO;
+
+#define KS_WIDTHBYTES(bits)    ((DWORD)(((bits)+31) & (~31)) / 8)
+#define KS_DIBWIDTHBYTES(bi)   (DWORD)KS_WIDTHBYTES((DWORD)(bi).biWidth *(DWORD)(bi).biBitCount)
+#define KS__DIBSIZE(bi)                (KS_DIBWIDTHBYTES(bi) *(DWORD)(bi).biHeight)
+#define KS_DIBSIZE(bi)         ((bi).biHeight < 0 ? (-1)*(KS__DIBSIZE(bi)) : KS__DIBSIZE(bi))
+
+typedef LONGLONG REFERENCE_TIME;
+
+typedef struct tagKS_VIDEOINFOHEADER {
+  RECT rcSource;
+  RECT rcTarget;
+  DWORD dwBitRate;
+  DWORD dwBitErrorRate;
+  REFERENCE_TIME AvgTimePerFrame;
+  KS_BITMAPINFOHEADER bmiHeader;
+} KS_VIDEOINFOHEADER,*PKS_VIDEOINFOHEADER;
+
+typedef struct tagKS_VIDEOINFO {
+  RECT rcSource;
+  RECT rcTarget;
+  DWORD dwBitRate;
+  DWORD dwBitErrorRate;
+  REFERENCE_TIME AvgTimePerFrame;
+  KS_BITMAPINFOHEADER bmiHeader;
+  __MINGW_EXTENSION union {
+    KS_RGBQUAD bmiColors[KS_iPALETTE_COLORS];
+    DWORD dwBitMasks[KS_iMASK_COLORS];
+    KS_TRUECOLORINFO TrueColorInfo;
+  };
+} KS_VIDEOINFO,*PKS_VIDEOINFO;
+
+#define KS_SIZE_MASKS                  (KS_iMASK_COLORS *sizeof(DWORD))
+#define KS_SIZE_PREHEADER              (FIELD_OFFSET(KS_VIDEOINFOHEADER,bmiHeader))
+
+#define KS_SIZE_VIDEOHEADER(pbmi)      ((pbmi)->bmiHeader.biSize + KS_SIZE_PREHEADER)
+
+typedef struct tagKS_VBIINFOHEADER {
+  ULONG StartLine;
+  ULONG EndLine;
+  ULONG SamplingFrequency;
+  ULONG MinLineStartTime;
+  ULONG MaxLineStartTime;
+  ULONG ActualLineStartTime;
+  ULONG ActualLineEndTime;
+  ULONG VideoStandard;
+  ULONG SamplesPerLine;
+  ULONG StrideInBytes;
+  ULONG BufferSize;
+} KS_VBIINFOHEADER,*PKS_VBIINFOHEADER;
+
+#define KS_VBIDATARATE_NABTS           (5727272L)
+#define KS_VBIDATARATE_CC              (503493L)
+#define KS_VBISAMPLINGRATE_4X_NABTS    ((long)(4*KS_VBIDATARATE_NABTS))
+#define KS_VBISAMPLINGRATE_47X_NABTS   ((long)(27000000))
+#define KS_VBISAMPLINGRATE_5X_NABTS    ((long)(5*KS_VBIDATARATE_NABTS))
+
+#define KS_47NABTS_SCALER              (KS_VBISAMPLINGRATE_47X_NABTS/(double)KS_VBIDATARATE_NABTS)
+
+typedef struct tagKS_AnalogVideoInfo {
+  RECT rcSource;
+  RECT rcTarget;
+  DWORD dwActiveWidth;
+  DWORD dwActiveHeight;
+  REFERENCE_TIME AvgTimePerFrame;
+} KS_ANALOGVIDEOINFO,*PKS_ANALOGVIDEOINFO;
+
+#define KS_TVTUNER_CHANGE_BEGIN_TUNE   0x0001L
+#define KS_TVTUNER_CHANGE_END_TUNE     0x0002L
+
+typedef struct tagKS_TVTUNER_CHANGE_INFO {
+  DWORD dwFlags;
+  DWORD dwCountryCode;
+  DWORD dwAnalogVideoStandard;
+  DWORD dwChannel;
+} KS_TVTUNER_CHANGE_INFO,*PKS_TVTUNER_CHANGE_INFO;
+
+typedef enum {
+  KS_MPEG2Level_Low,
+  KS_MPEG2Level_Main,
+  KS_MPEG2Level_High1440,
+  KS_MPEG2Level_High
+} KS_MPEG2Level;
+
+typedef enum {
+  KS_MPEG2Profile_Simple,
+  KS_MPEG2Profile_Main,
+  KS_MPEG2Profile_SNRScalable,
+  KS_MPEG2Profile_SpatiallyScalable,
+  KS_MPEG2Profile_High
+} KS_MPEG2Profile;
+
+#define KS_INTERLACE_IsInterlaced              0x00000001
+#define KS_INTERLACE_1FieldPerSample           0x00000002
+#define KS_INTERLACE_Field1First               0x00000004
+#define KS_INTERLACE_UNUSED                    0x00000008
+#define KS_INTERLACE_FieldPatternMask          0x00000030
+#define KS_INTERLACE_FieldPatField1Only                0x00000000
+#define KS_INTERLACE_FieldPatField2Only                0x00000010
+#define KS_INTERLACE_FieldPatBothRegular       0x00000020
+#define KS_INTERLACE_FieldPatBothIrregular     0x00000030
+#define KS_INTERLACE_DisplayModeMask           0x000000c0
+#define KS_INTERLACE_DisplayModeBobOnly                0x00000000
+#define KS_INTERLACE_DisplayModeWeaveOnly      0x00000040
+#define KS_INTERLACE_DisplayModeBobOrWeave     0x00000080
+
+#define KS_MPEG2_DoPanScan                     0x00000001
+#define KS_MPEG2_DVDLine21Field1               0x00000002
+#define KS_MPEG2_DVDLine21Field2               0x00000004
+#define KS_MPEG2_SourceIsLetterboxed           0x00000008
+#define KS_MPEG2_FilmCameraMode                        0x00000010
+#define KS_MPEG2_LetterboxAnalogOut            0x00000020
+#define KS_MPEG2_DSS_UserData                  0x00000040
+#define KS_MPEG2_DVB_UserData                  0x00000080
+#define KS_MPEG2_27MhzTimebase                 0x00000100
+
+typedef struct tagKS_VIDEOINFOHEADER2 {
+  RECT rcSource;
+  RECT rcTarget;
+  DWORD dwBitRate;
+  DWORD dwBitErrorRate;
+  REFERENCE_TIME AvgTimePerFrame;
+  DWORD dwInterlaceFlags;
+  DWORD dwCopyProtectFlags;
+  DWORD dwPictAspectRatioX;
+  DWORD dwPictAspectRatioY;
+  DWORD dwReserved1;
+  DWORD dwReserved2;
+  KS_BITMAPINFOHEADER bmiHeader;
+} KS_VIDEOINFOHEADER2,*PKS_VIDEOINFOHEADER2;
+
+typedef struct tagKS_MPEG1VIDEOINFO {
+  KS_VIDEOINFOHEADER hdr;
+  DWORD dwStartTimeCode;
+  DWORD cbSequenceHeader;
+  BYTE bSequenceHeader[1];
+} KS_MPEG1VIDEOINFO,*PKS_MPEG1VIDEOINFO;
+
+#define KS_MAX_SIZE_MPEG1_SEQUENCE_INFO        140
+#define KS_SIZE_MPEG1VIDEOINFO(pv)     (FIELD_OFFSET(KS_MPEG1VIDEOINFO,bSequenceHeader[0]) + (pv)->cbSequenceHeader)
+#define KS_MPEG1_SEQUENCE_INFO(pv)     ((const BYTE *)(pv)->bSequenceHeader)
+
+typedef struct tagKS_MPEGVIDEOINFO2 {
+  KS_VIDEOINFOHEADER2 hdr;
+  DWORD dwStartTimeCode;
+  DWORD cbSequenceHeader;
+  DWORD dwProfile;
+  DWORD dwLevel;
+  DWORD dwFlags;
+  DWORD bSequenceHeader[1];
+} KS_MPEGVIDEOINFO2,*PKS_MPEGVIDEOINFO2;
+
+#define KS_SIZE_MPEGVIDEOINFO2(pv)     (FIELD_OFFSET(KS_MPEGVIDEOINFO2,bSequenceHeader[0]) + (pv)->cbSequenceHeader)
+#define KS_MPEG1_SEQUENCE_INFO(pv)     ((const BYTE *)(pv)->bSequenceHeader)
+
+#define KS_MPEGAUDIOINFO_27MhzTimebase 0x00000001
+
+typedef struct tagKS_MPEAUDIOINFO {
+  DWORD dwFlags;
+  DWORD dwReserved1;
+  DWORD dwReserved2;
+  DWORD dwReserved3;
+} KS_MPEGAUDIOINFO,*PKS_MPEGAUDIOINFO;
+
+typedef struct tagKS_DATAFORMAT_VIDEOINFOHEADER {
+  KSDATAFORMAT DataFormat;
+  KS_VIDEOINFOHEADER VideoInfoHeader;
+} KS_DATAFORMAT_VIDEOINFOHEADER,*PKS_DATAFORMAT_VIDEOINFOHEADER;
+
+typedef struct tagKS_DATAFORMAT_VIDEOINFOHEADER2 {
+  KSDATAFORMAT DataFormat;
+  KS_VIDEOINFOHEADER2 VideoInfoHeader2;
+} KS_DATAFORMAT_VIDEOINFOHEADER2,*PKS_DATAFORMAT_VIDEOINFOHEADER2;
+
+typedef struct tagKS_DATAFORMAT_VIDEOINFO_PALETTE {
+  KSDATAFORMAT DataFormat;
+  KS_VIDEOINFO VideoInfo;
+} KS_DATAFORMAT_VIDEOINFO_PALETTE,*PKS_DATAFORMAT_VIDEOINFO_PALETTE;
+
+typedef struct tagKS_DATAFORMAT_VBIINFOHEADER {
+  KSDATAFORMAT DataFormat;
+  KS_VBIINFOHEADER VBIInfoHeader;
+} KS_DATAFORMAT_VBIINFOHEADER,*PKS_DATAFORMAT_VBIINFOHEADER;
+
+typedef struct _KS_VIDEO_STREAM_CONFIG_CAPS {
+  GUID guid;
+  ULONG VideoStandard;
+  SIZE InputSize;
+  SIZE MinCroppingSize;
+  SIZE MaxCroppingSize;
+  int CropGranularityX;
+  int CropGranularityY;
+  int CropAlignX;
+  int CropAlignY;
+  SIZE MinOutputSize;
+  SIZE MaxOutputSize;
+  int OutputGranularityX;
+  int OutputGranularityY;
+  int StretchTapsX;
+  int StretchTapsY;
+  int ShrinkTapsX;
+  int ShrinkTapsY;
+  LONGLONG MinFrameInterval;
+  LONGLONG MaxFrameInterval;
+  LONG MinBitsPerSecond;
+  LONG MaxBitsPerSecond;
+} KS_VIDEO_STREAM_CONFIG_CAPS,*PKS_VIDEO_STREAM_CONFIG_CAPS;
+
+typedef struct tagKS_DATARANGE_VIDEO {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_VIDEOINFOHEADER VideoInfoHeader;
+} KS_DATARANGE_VIDEO,*PKS_DATARANGE_VIDEO;
+
+typedef struct tagKS_DATARANGE_VIDEO2 {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_VIDEOINFOHEADER2 VideoInfoHeader;
+} KS_DATARANGE_VIDEO2,*PKS_DATARANGE_VIDEO2;
+
+typedef struct tagKS_DATARANGE_MPEG1_VIDEO {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_MPEG1VIDEOINFO VideoInfoHeader;
+} KS_DATARANGE_MPEG1_VIDEO,*PKS_DATARANGE_MPEG1_VIDEO;
+
+typedef struct tagKS_DATARANGE_MPEG2_VIDEO {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_MPEGVIDEOINFO2 VideoInfoHeader;
+} KS_DATARANGE_MPEG2_VIDEO,*PKS_DATARANGE_MPEG2_VIDEO;
+
+typedef struct tagKS_DATARANGE_VIDEO_PALETTE {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_VIDEOINFO VideoInfo;
+} KS_DATARANGE_VIDEO_PALETTE,*PKS_DATARANGE_VIDEO_PALETTE;
+
+typedef struct tagKS_DATARANGE_VIDEO_VBI {
+  KSDATARANGE DataRange;
+  WINBOOL bFixedSizeSamples;
+  WINBOOL bTemporalCompression;
+  DWORD StreamDescriptionFlags;
+  DWORD MemoryAllocationFlags;
+  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
+  KS_VBIINFOHEADER VBIInfoHeader;
+} KS_DATARANGE_VIDEO_VBI,*PKS_DATARANGE_VIDEO_VBI;
+
+typedef struct tagKS_DATARANGE_ANALOGVIDEO {
+  KSDATARANGE DataRange;
+  KS_ANALOGVIDEOINFO AnalogVideoInfo;
+} KS_DATARANGE_ANALOGVIDEO,*PKS_DATARANGE_ANALOGVIDEO;
+
+#define KS_VIDEOSTREAM_PREVIEW         0x0001
+#define KS_VIDEOSTREAM_CAPTURE         0x0002
+#define KS_VIDEOSTREAM_VBI             0x0010
+#define KS_VIDEOSTREAM_NABTS           0x0020
+#define KS_VIDEOSTREAM_CC              0x0100
+#define KS_VIDEOSTREAM_EDS             0x0200
+#define KS_VIDEOSTREAM_TELETEXT                0x0400
+#define KS_VIDEOSTREAM_STILL           0x1000
+#define KS_VIDEOSTREAM_IS_VPE          0x8000
+
+#define KS_VIDEO_ALLOC_VPE_SYSTEM      0x0001
+#define KS_VIDEO_ALLOC_VPE_DISPLAY     0x0002
+#define KS_VIDEO_ALLOC_VPE_AGP         0x0004
+
+#define STATIC_KSPROPSETID_VBICAP_PROPERTIES                           \
+       0xf162c607,0x7b35,0x496f,0xad,0x7f,0x2d,0xca,0x3b,0x46,0xb7,0x18
+DEFINE_GUIDSTRUCT("F162C607-7B35-496f-AD7F-2DCA3B46B718",KSPROPSETID_VBICAP_PROPERTIES);
+#define KSPROPSETID_VBICAP_PROPERTIES DEFINE_GUIDNAMED(KSPROPSETID_VBICAP_PROPERTIES)
+
+typedef enum {
+  KSPROPERTY_VBICAP_PROPERTIES_PROTECTION = 0x01
+} KSPROPERTY_VBICAP;
+
+typedef struct _VBICAP_PROPERTIES_PROTECTION_S {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  ULONG Status;
+} VBICAP_PROPERTIES_PROTECTION_S,*PVBICAP_PROPERTIES_PROTECTION_S;
+
+#define KS_VBICAP_PROTECTION_MV_PRESENT                                0x0001L
+#define KS_VBICAP_PROTECTION_MV_HARDWARE                       0x0002L
+#define KS_VBICAP_PROTECTION_MV_DETECTED                       0x0004L
+
+#define KS_NABTS_GROUPID_ORIGINAL_CONTENT_BASE                 0x800
+#define KS_NABTS_GROUPID_ORIGINAL_CONTENT_ADVERTISER_BASE      0x810
+
+#define KS_NABTS_GROUPID_PRODUCTION_COMPANY_CONTENT_BASE       0x820
+#define KS_NABTS_GROUPID_PRODUCTION_COMPANY_ADVERTISER_BASE    0x830
+
+#define KS_NABTS_GROUPID_SYNDICATED_SHOW_CONTENT_BASE          0x840
+#define KS_NABTS_GROUPID_SYNDICATED_SHOW_ADVERTISER_BASE       0x850
+
+#define KS_NABTS_GROUPID_NETWORK_WIDE_CONTENT_BASE             0x860
+#define KS_NABTS_GROUPID_NETWORK_WIDE_ADVERTISER_BASE          0x870
+
+#define KS_NABTS_GROUPID_TELEVISION_STATION_CONTENT_BASE       0x880
+#define KS_NABTS_GROUPID_TELEVISION_STATION_ADVERTISER_BASE    0x890
+
+#define KS_NABTS_GROUPID_LOCAL_CABLE_SYSTEM_CONTENT_BASE       0x8A0
+#define KS_NABTS_GROUPID_LOCAL_CABLE_SYSTEM_ADVERTISER_BASE    0x8B0
+
+#define KS_NABTS_GROUPID_MICROSOFT_RESERVED_TEST_DATA_BASE     0x8F0
+
+#define STATIC_KSDATAFORMAT_TYPE_NABTS                                 \
+       0xe757bca0,0x39ac,0x11d1,0xa9,0xf5,0x0,0xc0,0x4f,0xbb,0xde,0x8f
+DEFINE_GUIDSTRUCT("E757BCA0-39AC-11d1-A9F5-00C04FBBDE8F",KSDATAFORMAT_TYPE_NABTS);
+#define KSDATAFORMAT_TYPE_NABTS DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_NABTS)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_NABTS_FEC                          \
+       0xe757bca1,0x39ac,0x11d1,0xa9,0xf5,0x0,0xc0,0x4f,0xbb,0xde,0x8f
+DEFINE_GUIDSTRUCT("E757BCA1-39AC-11d1-A9F5-00C04FBBDE8F",KSDATAFORMAT_SUBTYPE_NABTS_FEC);
+#define KSDATAFORMAT_SUBTYPE_NABTS_FEC DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NABTS_FEC)
+
+#define MAX_NABTS_VBI_LINES_PER_FIELD  11
+#define NABTS_LINES_PER_BUNDLE         16
+#define NABTS_PAYLOAD_PER_LINE         28
+#define NABTS_BYTES_PER_LINE           36
+
+typedef struct _NABTSFEC_BUFFER {
+  ULONG dataSize;
+  USHORT groupID;
+  USHORT Reserved;
+  UCHAR data[NABTS_LINES_PER_BUNDLE *NABTS_PAYLOAD_PER_LINE];
+} NABTSFEC_BUFFER,*PNABTSFEC_BUFFER;
+
+#define STATIC_KSPROPSETID_VBICodecFiltering                           \
+       0xcafeb0caL,0x8715,0x11d0,0xbd,0x6a,0x00,0x35,0xc0,0xed,0xba,0xbe
+DEFINE_GUIDSTRUCT("cafeb0ca-8715-11d0-bd6a-0035c0edbabe",KSPROPSETID_VBICodecFiltering);
+#define KSPROPSETID_VBICodecFiltering DEFINE_GUIDNAMED(KSPROPSETID_VBICodecFiltering)
+
+typedef enum {
+  KSPROPERTY_VBICODECFILTERING_SCANLINES_REQUESTED_BIT_ARRAY = 0x01,
+  KSPROPERTY_VBICODECFILTERING_SCANLINES_DISCOVERED_BIT_ARRAY,
+  KSPROPERTY_VBICODECFILTERING_SUBSTREAMS_REQUESTED_BIT_ARRAY,
+  KSPROPERTY_VBICODECFILTERING_SUBSTREAMS_DISCOVERED_BIT_ARRAY,
+  KSPROPERTY_VBICODECFILTERING_STATISTICS
+} KSPROPERTY_VBICODECFILTERING;
+
+typedef struct _VBICODECFILTERING_SCANLINES {
+  DWORD DwordBitArray[32];
+} VBICODECFILTERING_SCANLINES,*PVBICODECFILTERING_SCANLINES;
+
+typedef struct _VBICODECFILTERING_NABTS_SUBSTREAMS {
+  DWORD SubstreamMask[128];
+} VBICODECFILTERING_NABTS_SUBSTREAMS,*PVBICODECFILTERING_NABTS_SUBSTREAMS;
+
+typedef struct _VBICODECFILTERING_CC_SUBSTREAMS {
+  DWORD SubstreamMask;
+} VBICODECFILTERING_CC_SUBSTREAMS,*PVBICODECFILTERING_CC_SUBSTREAMS;
+
+#define KS_CC_SUBSTREAM_ODD            0x0001L
+#define KS_CC_SUBSTREAM_EVEN           0x0002L
+
+#define KS_CC_SUBSTREAM_FIELD1_MASK    0x00F0L
+#define KS_CC_SUBSTREAM_SERVICE_CC1    0x0010L
+#define KS_CC_SUBSTREAM_SERVICE_CC2    0x0020L
+#define KS_CC_SUBSTREAM_SERVICE_T1     0x0040L
+#define KS_CC_SUBSTREAM_SERVICE_T2     0x0080L
+
+#define KS_CC_SUBSTREAM_FIELD2_MASK    0x1F00L
+#define KS_CC_SUBSTREAM_SERVICE_CC3    0x0100L
+#define KS_CC_SUBSTREAM_SERVICE_CC4    0x0200L
+#define KS_CC_SUBSTREAM_SERVICE_T3     0x0400L
+#define KS_CC_SUBSTREAM_SERVICE_T4     0x0800L
+#define KS_CC_SUBSTREAM_SERVICE_XDS    0x1000L
+
+#define CC_MAX_HW_DECODE_LINES         12
+typedef struct _CC_BYTE_PAIR {
+  BYTE Decoded[2];
+  USHORT Reserved;
+} CC_BYTE_PAIR,*PCC_BYTE_PAIR;
+
+typedef struct _CC_HW_FIELD {
+  VBICODECFILTERING_SCANLINES ScanlinesRequested;
+  ULONG fieldFlags;
+  LONGLONG PictureNumber;
+  CC_BYTE_PAIR Lines[CC_MAX_HW_DECODE_LINES];
+} CC_HW_FIELD,*PCC_HW_FIELD;
+
+#ifndef PACK_PRAGMAS_NOT_SUPPORTED
+#include <pshpack1.h>
+#endif
+typedef struct _NABTS_BUFFER_LINE {
+  BYTE Confidence;
+  BYTE Bytes[NABTS_BYTES_PER_LINE];
+} NABTS_BUFFER_LINE,*PNABTS_BUFFER_LINE;
+
+#define NABTS_BUFFER_PICTURENUMBER_SUPPORT     1
+typedef struct _NABTS_BUFFER {
+  VBICODECFILTERING_SCANLINES ScanlinesRequested;
+  LONGLONG PictureNumber;
+  NABTS_BUFFER_LINE NabtsLines[MAX_NABTS_VBI_LINES_PER_FIELD];
+} NABTS_BUFFER,*PNABTS_BUFFER;
+#ifndef PACK_PRAGMAS_NOT_SUPPORTED
+#include <poppack.h>
+#endif
+
+#define WST_TVTUNER_CHANGE_BEGIN_TUNE  0x1000L
+#define WST_TVTUNER_CHANGE_END_TUNE    0x2000L
+
+#define MAX_WST_VBI_LINES_PER_FIELD    17
+#define WST_BYTES_PER_LINE             42
+
+typedef struct _WST_BUFFER_LINE {
+  BYTE Confidence;
+  BYTE Bytes[WST_BYTES_PER_LINE];
+} WST_BUFFER_LINE,*PWST_BUFFER_LINE;
+
+typedef struct _WST_BUFFER {
+  VBICODECFILTERING_SCANLINES ScanlinesRequested;
+  WST_BUFFER_LINE WstLines[MAX_WST_VBI_LINES_PER_FIELD];
+} WST_BUFFER,*PWST_BUFFER;
+
+typedef struct _VBICODECFILTERING_STATISTICS_COMMON {
+  DWORD InputSRBsProcessed;
+  DWORD OutputSRBsProcessed;
+  DWORD SRBsIgnored;
+  DWORD InputSRBsMissing;
+  DWORD OutputSRBsMissing;
+  DWORD OutputFailures;
+  DWORD InternalErrors;
+  DWORD ExternalErrors;
+  DWORD InputDiscontinuities;
+  DWORD DSPFailures;
+  DWORD TvTunerChanges;
+  DWORD VBIHeaderChanges;
+  DWORD LineConfidenceAvg;
+  DWORD BytesOutput;
+} VBICODECFILTERING_STATISTICS_COMMON,*PVBICODECFILTERING_STATISTICS_COMMON;
+
+typedef struct _VBICODECFILTERING_STATISTICS_COMMON_PIN {
+  DWORD SRBsProcessed;
+  DWORD SRBsIgnored;
+  DWORD SRBsMissing;
+  DWORD InternalErrors;
+  DWORD ExternalErrors;
+  DWORD Discontinuities;
+  DWORD LineConfidenceAvg;
+  DWORD BytesOutput;
+} VBICODECFILTERING_STATISTICS_COMMON_PIN,*PVBICODECFILTERING_STATISTICS_COMMON_PIN;
+
+typedef struct _VBICODECFILTERING_STATISTICS_NABTS {
+  VBICODECFILTERING_STATISTICS_COMMON Common;
+  DWORD FECBundleBadLines;
+  DWORD FECQueueOverflows;
+  DWORD FECCorrectedLines;
+  DWORD FECUncorrectableLines;
+  DWORD BundlesProcessed;
+  DWORD BundlesSent2IP;
+  DWORD FilteredLines;
+} VBICODECFILTERING_STATISTICS_NABTS,*PVBICODECFILTERING_STATISTICS_NABTS;
+
+typedef struct _VBICODECFILTERING_STATISTICS_NABTS_PIN {
+  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
+} VBICODECFILTERING_STATISTICS_NABTS_PIN,*PVBICODECFILTERING_STATISTICS_NABTS_PIN;
+
+typedef struct _VBICODECFILTERING_STATISTICS_CC {
+  VBICODECFILTERING_STATISTICS_COMMON Common;
+} VBICODECFILTERING_STATISTICS_CC,*PVBICODECFILTERING_STATISTICS_CC;
+
+typedef struct _VBICODECFILTERING_STATISTICS_CC_PIN {
+  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
+} VBICODECFILTERING_STATISTICS_CC_PIN,*PVBICODECFILTERING_STATISTICS_CC_PIN;
+
+typedef struct _VBICODECFILTERING_STATISTICS_TELETEXT {
+  VBICODECFILTERING_STATISTICS_COMMON Common;
+} VBICODECFILTERING_STATISTICS_TELETEXT,*PVBICODECFILTERING_STATISTICS_TELETEXT;
+
+typedef struct _VBICODECFILTERING_STATISTICS_TELETEXT_PIN {
+  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
+} VBICODECFILTERING_STATISTICS_TELETEXT_PIN,*PVBICODECFILTERING_STATISTICS_TELETEXT_PIN;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_SCANLINES Scanlines;
+} KSPROPERTY_VBICODECFILTERING_SCANLINES_S,*PKSPROPERTY_VBICODECFILTERING_SCANLINES_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_NABTS_SUBSTREAMS Substreams;
+} KSPROPERTY_VBICODECFILTERING_NABTS_SUBSTREAMS_S,*PKSPROPERTY_VBICODECFILTERING_NABTS_SUBSTREAMS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_CC_SUBSTREAMS Substreams;
+} KSPROPERTY_VBICODECFILTERING_CC_SUBSTREAMS_S,*PKSPROPERTY_VBICODECFILTERING_CC_SUBSTREAMS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_COMMON Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_COMMON_PIN Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_PIN_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_NABTS Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_NABTS_PIN Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_PIN_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_CC Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_CC_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_CC_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  VBICODECFILTERING_STATISTICS_CC_PIN Statistics;
+} KSPROPERTY_VBICODECFILTERING_STATISTICS_CC_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_CC_PIN_S;
+
+#define STATIC_PINNAME_VIDEO_CAPTURE                                   \
+       0xfb6c4281,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+#define STATIC_PINNAME_CAPTURE STATIC_PINNAME_VIDEO_CAPTURE
+DEFINE_GUIDSTRUCT("FB6C4281-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_CAPTURE);
+#define PINNAME_VIDEO_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_CAPTURE)
+#define PINNAME_CAPTURE PINNAME_VIDEO_CAPTURE
+
+#define STATIC_PINNAME_VIDEO_CC_CAPTURE                                        \
+       0x1aad8061,0x12d,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
+#define STATIC_PINNAME_CC_CAPTURE STATIC_PINNAME_VIDEO_CC_CAPTURE
+DEFINE_GUIDSTRUCT("1AAD8061-012D-11d2-B4B1-00A0D102CFBE",PINNAME_VIDEO_CC_CAPTURE);
+#define PINNAME_VIDEO_CC_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_CC_CAPTURE)
+
+#define STATIC_PINNAME_VIDEO_NABTS_CAPTURE                             \
+       0x29703660,0x498a,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
+#define STATIC_PINNAME_NABTS_CAPTURE STATIC_PINNAME_VIDEO_NABTS_CAPTURE
+DEFINE_GUIDSTRUCT("29703660-498A-11d2-B4B1-00A0D102CFBE",PINNAME_VIDEO_NABTS_CAPTURE);
+#define PINNAME_VIDEO_NABTS_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_NABTS_CAPTURE)
+
+#define STATIC_PINNAME_VIDEO_PREVIEW                                   \
+       0xfb6c4282,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+#define STATIC_PINNAME_PREVIEW STATIC_PINNAME_VIDEO_PREVIEW
+DEFINE_GUIDSTRUCT("FB6C4282-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_PREVIEW);
+#define PINNAME_VIDEO_PREVIEW DEFINE_GUIDNAMED(PINNAME_VIDEO_PREVIEW)
+#define PINNAME_PREVIEW PINNAME_VIDEO_PREVIEW
+
+#define STATIC_PINNAME_VIDEO_ANALOGVIDEOIN                             \
+       0xfb6c4283,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4283-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_ANALOGVIDEOIN);
+#define PINNAME_VIDEO_ANALOGVIDEOIN DEFINE_GUIDNAMED(PINNAME_VIDEO_ANALOGVIDEOIN)
+
+#define STATIC_PINNAME_VIDEO_VBI                                       \
+       0xfb6c4284,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4284-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VBI);
+#define PINNAME_VIDEO_VBI DEFINE_GUIDNAMED(PINNAME_VIDEO_VBI)
+
+#define STATIC_PINNAME_VIDEO_VIDEOPORT                                 \
+       0xfb6c4285,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4285-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VIDEOPORT);
+#define PINNAME_VIDEO_VIDEOPORT DEFINE_GUIDNAMED(PINNAME_VIDEO_VIDEOPORT)
+
+#define STATIC_PINNAME_VIDEO_NABTS                                     \
+       0xfb6c4286,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4286-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_NABTS);
+#define PINNAME_VIDEO_NABTS DEFINE_GUIDNAMED(PINNAME_VIDEO_NABTS)
+
+#define STATIC_PINNAME_VIDEO_EDS                                       \
+       0xfb6c4287,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4287-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_EDS);
+#define PINNAME_VIDEO_EDS DEFINE_GUIDNAMED(PINNAME_VIDEO_EDS)
+
+#define STATIC_PINNAME_VIDEO_TELETEXT                                  \
+       0xfb6c4288,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4288-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_TELETEXT);
+#define PINNAME_VIDEO_TELETEXT DEFINE_GUIDNAMED(PINNAME_VIDEO_TELETEXT)
+
+#define STATIC_PINNAME_VIDEO_CC                                                \
+       0xfb6c4289,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C4289-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_CC);
+#define PINNAME_VIDEO_CC DEFINE_GUIDNAMED(PINNAME_VIDEO_CC)
+
+#define STATIC_PINNAME_VIDEO_STILL                                     \
+       0xfb6c428A,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C428A-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_STILL);
+#define PINNAME_VIDEO_STILL DEFINE_GUIDNAMED(PINNAME_VIDEO_STILL)
+
+#define STATIC_PINNAME_VIDEO_TIMECODE                                  \
+       0xfb6c428B,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C428B-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_TIMECODE);
+#define PINNAME_VIDEO_TIMECODE DEFINE_GUIDNAMED(PINNAME_VIDEO_TIMECODE)
+
+#define STATIC_PINNAME_VIDEO_VIDEOPORT_VBI                             \
+       0xfb6c428C,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("FB6C428C-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VIDEOPORT_VBI);
+#define PINNAME_VIDEO_VIDEOPORT_VBI DEFINE_GUIDNAMED(PINNAME_VIDEO_VIDEOPORT_VBI)
+
+#define KS_VIDEO_FLAG_FRAME            0x0000L
+#define KS_VIDEO_FLAG_FIELD1           0x0001L
+#define KS_VIDEO_FLAG_FIELD2           0x0002L
+
+#define KS_VIDEO_FLAG_I_FRAME          0x0000L
+#define KS_VIDEO_FLAG_P_FRAME          0x0010L
+#define KS_VIDEO_FLAG_B_FRAME          0x0020L
+
+typedef struct tagKS_FRAME_INFO {
+  ULONG ExtendedHeaderSize;
+  DWORD dwFrameFlags;
+  LONGLONG PictureNumber;
+  LONGLONG DropCount;
+  HANDLE hDirectDraw;
+  HANDLE hSurfaceHandle;
+  RECT DirectDrawRect;
+
+  DWORD Reserved1;
+  DWORD Reserved2;
+  DWORD Reserved3;
+  DWORD Reserved4;
+} KS_FRAME_INFO,*PKS_FRAME_INFO;
+
+#define KS_VBI_FLAG_FIELD1             0x0001L
+#define KS_VBI_FLAG_FIELD2             0x0002L
+
+#define KS_VBI_FLAG_MV_PRESENT         0x0100L
+#define KS_VBI_FLAG_MV_HARDWARE                0x0200L
+#define KS_VBI_FLAG_MV_DETECTED                0x0400L
+
+#define KS_VBI_FLAG_TVTUNER_CHANGE     0x0010L
+#define KS_VBI_FLAG_VBIINFOHEADER_CHANGE 0x0020L
+
+typedef struct tagKS_VBI_FRAME_INFO {
+  ULONG ExtendedHeaderSize;
+  DWORD dwFrameFlags;
+  LONGLONG PictureNumber;
+  LONGLONG DropCount;
+  DWORD dwSamplingFrequency;
+  KS_TVTUNER_CHANGE_INFO TvTunerChangeInfo;
+  KS_VBIINFOHEADER VBIInfoHeader;
+} KS_VBI_FRAME_INFO,*PKS_VBI_FRAME_INFO;
+
+typedef enum
+{
+  KS_AnalogVideo_None = 0x00000000,
+  KS_AnalogVideo_NTSC_M = 0x00000001,
+  KS_AnalogVideo_NTSC_M_J = 0x00000002,
+  KS_AnalogVideo_NTSC_433 = 0x00000004,
+  KS_AnalogVideo_PAL_B = 0x00000010,
+  KS_AnalogVideo_PAL_D = 0x00000020,
+  KS_AnalogVideo_PAL_G = 0x00000040,
+  KS_AnalogVideo_PAL_H = 0x00000080,
+  KS_AnalogVideo_PAL_I = 0x00000100,
+  KS_AnalogVideo_PAL_M = 0x00000200,
+  KS_AnalogVideo_PAL_N = 0x00000400,
+  KS_AnalogVideo_PAL_60 = 0x00000800,
+  KS_AnalogVideo_SECAM_B = 0x00001000,
+  KS_AnalogVideo_SECAM_D = 0x00002000,
+  KS_AnalogVideo_SECAM_G = 0x00004000,
+  KS_AnalogVideo_SECAM_H = 0x00008000,
+  KS_AnalogVideo_SECAM_K = 0x00010000,
+  KS_AnalogVideo_SECAM_K1 = 0x00020000,
+  KS_AnalogVideo_SECAM_L = 0x00040000,
+  KS_AnalogVideo_SECAM_L1 = 0x00080000,
+  KS_AnalogVideo_PAL_N_COMBO = 0x00100000
+} KS_AnalogVideoStandard;
+
+#define KS_AnalogVideo_NTSC_Mask       0x00000007
+#define KS_AnalogVideo_PAL_Mask                0x00100FF0
+#define KS_AnalogVideo_SECAM_Mask      0x000FF000
+
+#define STATIC_PROPSETID_ALLOCATOR_CONTROL                             \
+       0x53171960,0x148e,0x11d2,0x99,0x79,0x0,0x0,0xc0,0xcc,0x16,0xba
+DEFINE_GUIDSTRUCT("53171960-148E-11d2-9979-0000C0CC16BA",PROPSETID_ALLOCATOR_CONTROL);
+#define PROPSETID_ALLOCATOR_CONTROL DEFINE_GUIDNAMED(PROPSETID_ALLOCATOR_CONTROL)
+
+typedef enum {
+  KSPROPERTY_ALLOCATOR_CONTROL_HONOR_COUNT,
+  KSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE,
+  KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS,
+  KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE
+} KSPROPERTY_ALLOCATOR_CONTROL;
+
+typedef struct {
+  ULONG CX;
+  ULONG CY;
+} KSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE_S,*PKSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE_S;
+
+typedef struct {
+  ULONG InterleavedCapSupported;
+} KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS_S,*PKSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS_S;
+
+typedef struct {
+  ULONG InterleavedCapPossible;
+} KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE_S,*PKSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE_S;
+
+#define STATIC_PROPSETID_VIDCAP_VIDEOPROCAMP                           \
+       0xC6E13360L,0x30AC,0x11d0,0xa1,0x8c,0x00,0xA0,0xC9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("C6E13360-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEOPROCAMP);
+#define PROPSETID_VIDCAP_VIDEOPROCAMP DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOPROCAMP)
+
+typedef enum {
+  KSPROPERTY_VIDEOPROCAMP_BRIGHTNESS,
+  KSPROPERTY_VIDEOPROCAMP_CONTRAST,
+  KSPROPERTY_VIDEOPROCAMP_HUE,
+  KSPROPERTY_VIDEOPROCAMP_SATURATION,
+  KSPROPERTY_VIDEOPROCAMP_SHARPNESS,
+  KSPROPERTY_VIDEOPROCAMP_GAMMA,
+  KSPROPERTY_VIDEOPROCAMP_COLORENABLE,
+  KSPROPERTY_VIDEOPROCAMP_WHITEBALANCE,
+  KSPROPERTY_VIDEOPROCAMP_BACKLIGHT_COMPENSATION,
+  KSPROPERTY_VIDEOPROCAMP_GAIN,
+  KSPROPERTY_VIDEOPROCAMP_DIGITAL_MULTIPLIER,
+  KSPROPERTY_VIDEOPROCAMP_DIGITAL_MULTIPLIER_LIMIT,
+  KSPROPERTY_VIDEOPROCAMP_WHITEBALANCE_COMPONENT,
+  KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY
+} KSPROPERTY_VIDCAP_VIDEOPROCAMP;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_VIDEOPROCAMP_S,*PKSPROPERTY_VIDEOPROCAMP_S;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_VIDEOPROCAMP_NODE_S,*PKSPROPERTY_VIDEOPROCAMP_NODE_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value1;
+  ULONG Flags;
+  ULONG Capabilities;
+  LONG Value2;
+} KSPROPERTY_VIDEOPROCAMP_S2,*PKSPROPERTY_VIDEOPROCAMP_S2;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  LONG Value1;
+  ULONG Flags;
+  ULONG Capabilities;
+  LONG Value2;
+} KSPROPERTY_VIDEOPROCAMP_NODE_S2,*PKSPROPERTY_VIDEOPROCAMP_NODE_S2;
+
+#define KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO     0X0001L
+#define KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL   0X0002L
+
+#define STATIC_PROPSETID_VIDCAP_SELECTOR                               \
+       0x1ABDAECA,0x68B6,0x4F83,0x93,0x71,0xB4,0x13,0x90,0x7C,0x7B,0x9F
+DEFINE_GUIDSTRUCT("1ABDAECA-68B6-4F83-9371-B413907C7B9F",PROPSETID_VIDCAP_SELECTOR);
+#define PROPSETID_VIDCAP_SELECTOR DEFINE_GUIDNAMED(PROPSETID_VIDCAP_SELECTOR)
+
+typedef enum {
+  KSPROPERTY_SELECTOR_SOURCE_NODE_ID,
+  KSPROPERTY_SELECTOR_NUM_SOURCES
+} KSPROPERTY_VIDCAP_SELECTOR,*PKSPROPERTY_VIDCAP_SELECTOR;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_SELECTOR_S,*PKSPROPERTY_SELECTOR_S;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_SELECTOR_NODE_S,*PKSPROPERTY_SELECTOR_NODE_S;
+
+#define STATIC_PROPSETID_TUNER                                         \
+       0x6a2e0605L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0605-28e4-11d0-a18c-00a0c9118956",PROPSETID_TUNER);
+#define PROPSETID_TUNER DEFINE_GUIDNAMED(PROPSETID_TUNER)
+
+typedef enum {
+  KSPROPERTY_TUNER_CAPS,
+  KSPROPERTY_TUNER_MODE_CAPS,
+  KSPROPERTY_TUNER_MODE,
+  KSPROPERTY_TUNER_STANDARD,
+  KSPROPERTY_TUNER_FREQUENCY,
+  KSPROPERTY_TUNER_INPUT,
+  KSPROPERTY_TUNER_STATUS,
+  KSPROPERTY_TUNER_IF_MEDIUM
+} KSPROPERTY_TUNER;
+
+typedef enum {
+  KSPROPERTY_TUNER_MODE_TV = 0X0001,
+  KSPROPERTY_TUNER_MODE_FM_RADIO = 0X0002,
+  KSPROPERTY_TUNER_MODE_AM_RADIO = 0X0004,
+  KSPROPERTY_TUNER_MODE_DSS = 0X0008,
+  KSPROPERTY_TUNER_MODE_ATSC = 0X0010
+} KSPROPERTY_TUNER_MODES;
+
+typedef enum {
+  KS_TUNER_TUNING_EXACT = 1,
+  KS_TUNER_TUNING_FINE,
+  KS_TUNER_TUNING_COARSE
+} KS_TUNER_TUNING_FLAGS;
+
+typedef enum {
+  KS_TUNER_STRATEGY_PLL = 0X01,
+  KS_TUNER_STRATEGY_SIGNAL_STRENGTH = 0X02,
+  KS_TUNER_STRATEGY_DRIVER_TUNES = 0X04
+} KS_TUNER_STRATEGY;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG ModesSupported;
+  KSPIN_MEDIUM VideoMedium;
+  KSPIN_MEDIUM TVAudioMedium;
+  KSPIN_MEDIUM RadioAudioMedium;
+} KSPROPERTY_TUNER_CAPS_S,*PKSPROPERTY_TUNER_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  KSPIN_MEDIUM IFMedium;
+} KSPROPERTY_TUNER_IF_MEDIUM_S,*PKSPROPERTY_TUNER_IF_MEDIUM_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Mode;
+  ULONG StandardsSupported;
+  ULONG MinFrequency;
+  ULONG MaxFrequency;
+  ULONG TuningGranularity;
+  ULONG NumberOfInputs;
+  ULONG SettlingTime;
+  ULONG Strategy;
+} KSPROPERTY_TUNER_MODE_CAPS_S,*PKSPROPERTY_TUNER_MODE_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Mode;
+} KSPROPERTY_TUNER_MODE_S,*PKSPROPERTY_TUNER_MODE_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Frequency;
+  ULONG LastFrequency;
+  ULONG TuningFlags;
+  ULONG VideoSubChannel;
+  ULONG AudioSubChannel;
+  ULONG Channel;
+  ULONG Country;
+} KSPROPERTY_TUNER_FREQUENCY_S,*PKSPROPERTY_TUNER_FREQUENCY_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Standard;
+} KSPROPERTY_TUNER_STANDARD_S,*PKSPROPERTY_TUNER_STANDARD_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG InputIndex;
+} KSPROPERTY_TUNER_INPUT_S,*PKSPROPERTY_TUNER_INPUT_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG CurrentFrequency;
+  ULONG PLLOffset;
+  ULONG SignalStrength;
+  ULONG Busy;
+} KSPROPERTY_TUNER_STATUS_S,*PKSPROPERTY_TUNER_STATUS_S;
+
+#define STATIC_EVENTSETID_TUNER                                                \
+       0x6a2e0606L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0606-28e4-11d0-a18c-00a0c9118956",EVENTSETID_TUNER);
+#define EVENTSETID_TUNER DEFINE_GUIDNAMED(EVENTSETID_TUNER)
+
+typedef enum {
+  KSEVENT_TUNER_CHANGED
+} KSEVENT_TUNER;
+
+#define STATIC_KSNODETYPE_VIDEO_STREAMING                              \
+       0xDFF229E1L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_STREAMING);
+#define KSNODETYPE_VIDEO_STREAMING DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_STREAMING)
+
+#define STATIC_KSNODETYPE_VIDEO_INPUT_TERMINAL                         \
+       0xDFF229E2L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_INPUT_TERMINAL);
+#define KSNODETYPE_VIDEO_INPUT_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_INPUT_TERMINAL)
+
+#define STATIC_KSNODETYPE_VIDEO_OUTPUT_TERMINAL                                \
+       0xDFF229E3L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_OUTPUT_TERMINAL);
+#define KSNODETYPE_VIDEO_OUTPUT_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_OUTPUT_TERMINAL)
+
+#define STATIC_KSNODETYPE_VIDEO_SELECTOR                               \
+       0xDFF229E4L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_SELECTOR);
+#define KSNODETYPE_VIDEO_SELECTOR DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_SELECTOR)
+
+#define STATIC_KSNODETYPE_VIDEO_PROCESSING                             \
+       0xDFF229E5L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_PROCESSING);
+#define KSNODETYPE_VIDEO_PROCESSING DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_PROCESSING)
+
+#define STATIC_KSNODETYPE_VIDEO_CAMERA_TERMINAL                                \
+       0xDFF229E6L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_CAMERA_TERMINAL);
+#define KSNODETYPE_VIDEO_CAMERA_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_CAMERA_TERMINAL)
+
+#define STATIC_KSNODETYPE_VIDEO_INPUT_MTT                              \
+       0xDFF229E7L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_INPUT_MTT);
+#define KSNODETYPE_VIDEO_INPUT_MTT DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_INPUT_MTT)
+
+#define STATIC_KSNODETYPE_VIDEO_OUTPUT_MTT                             \
+       0xDFF229E8L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("DFF229E8-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_OUTPUT_MTT);
+#define KSNODETYPE_VIDEO_OUTPUT_MTT DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_OUTPUT_MTT)
+
+#define STATIC_PROPSETID_VIDCAP_VIDEOENCODER                           \
+       0x6a2e0610L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0610-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_VIDEOENCODER);
+#define PROPSETID_VIDCAP_VIDEOENCODER DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOENCODER)
+
+typedef enum {
+  KSPROPERTY_VIDEOENCODER_CAPS,
+  KSPROPERTY_VIDEOENCODER_STANDARD,
+  KSPROPERTY_VIDEOENCODER_COPYPROTECTION,
+  KSPROPERTY_VIDEOENCODER_CC_ENABLE
+} KSPROPERTY_VIDCAP_VIDEOENCODER;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_VIDEOENCODER_S,*PKSPROPERTY_VIDEOENCODER_S;
+
+#define STATIC_PROPSETID_VIDCAP_VIDEODECODER                           \
+       0xC6E13350L,0x30AC,0x11d0,0xA1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("C6E13350-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEODECODER);
+#define PROPSETID_VIDCAP_VIDEODECODER DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEODECODER)
+
+typedef enum {
+  KSPROPERTY_VIDEODECODER_CAPS,
+  KSPROPERTY_VIDEODECODER_STANDARD,
+  KSPROPERTY_VIDEODECODER_STATUS,
+  KSPROPERTY_VIDEODECODER_OUTPUT_ENABLE,
+  KSPROPERTY_VIDEODECODER_VCR_TIMING
+} KSPROPERTY_VIDCAP_VIDEODECODER;
+
+typedef enum {
+  KS_VIDEODECODER_FLAGS_CAN_DISABLE_OUTPUT = 0X0001,
+  KS_VIDEODECODER_FLAGS_CAN_USE_VCR_LOCKING = 0X0002,
+  KS_VIDEODECODER_FLAGS_CAN_INDICATE_LOCKED = 0X0004
+} KS_VIDEODECODER_FLAGS;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StandardsSupported;
+  ULONG Capabilities;
+  ULONG SettlingTime;
+  ULONG HSyncPerVSync;
+} KSPROPERTY_VIDEODECODER_CAPS_S,*PKSPROPERTY_VIDEODECODER_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG NumberOfLines;
+  ULONG SignalLocked;
+} KSPROPERTY_VIDEODECODER_STATUS_S,*PKSPROPERTY_VIDEODECODER_STATUS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Value;
+} KSPROPERTY_VIDEODECODER_S,*PKSPROPERTY_VIDEODECODER_S;
+
+#define STATIC_EVENTSETID_VIDEODECODER                                 \
+       0x6a2e0621L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0621-28e4-11d0-a18c-00a0c9118956",EVENTSETID_VIDEODECODER);
+#define EVENTSETID_VIDEODECODER DEFINE_GUIDNAMED(EVENTSETID_VIDEODECODER)
+
+typedef enum {
+  KSEVENT_VIDEODECODER_CHANGED
+} KSEVENT_VIDEODECODER;
+
+#define STATIC_PROPSETID_VIDCAP_CAMERACONTROL                          \
+       0xC6E13370L,0x30AC,0x11d0,0xa1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("C6E13370-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_CAMERACONTROL);
+#define PROPSETID_VIDCAP_CAMERACONTROL DEFINE_GUIDNAMED(PROPSETID_VIDCAP_CAMERACONTROL)
+
+typedef enum {
+  KSPROPERTY_CAMERACONTROL_PAN,
+  KSPROPERTY_CAMERACONTROL_TILT,
+  KSPROPERTY_CAMERACONTROL_ROLL,
+  KSPROPERTY_CAMERACONTROL_ZOOM,
+  KSPROPERTY_CAMERACONTROL_EXPOSURE,
+  KSPROPERTY_CAMERACONTROL_IRIS,
+  KSPROPERTY_CAMERACONTROL_FOCUS,
+  KSPROPERTY_CAMERACONTROL_SCANMODE,
+  KSPROPERTY_CAMERACONTROL_PRIVACY,
+  KSPROPERTY_CAMERACONTROL_PANTILT,
+  KSPROPERTY_CAMERACONTROL_PAN_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_TILT_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_ROLL_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_ZOOM_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_EXPOSURE_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_IRIS_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_FOCUS_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_PANTILT_RELATIVE,
+  KSPROPERTY_CAMERACONTROL_FOCAL_LENGTH
+} KSPROPERTY_VIDCAP_CAMERACONTROL;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_CAMERACONTROL_S,*PKSPROPERTY_CAMERACONTROL_S;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  LONG Value;
+  ULONG Flags;
+  ULONG Capabilities;
+} KSPROPERTY_CAMERACONTROL_NODE_S,PKSPROPERTY_CAMERACONTROL_NODE_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG Value1;
+  ULONG Flags;
+  ULONG Capabilities;
+  LONG Value2;
+} KSPROPERTY_CAMERACONTROL_S2,*PKSPROPERTY_CAMERACONTROL_S2;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  LONG Value1;
+  ULONG Flags;
+  ULONG Capabilities;
+  LONG Value2;
+} KSPROPERTY_CAMERACONTROL_NODE_S2,*PKSPROPERTY_CAMERACONTROL_NODE_S2;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONG lOcularFocalLength;
+  LONG lObjectiveFocalLengthMin;
+  LONG lObjectiveFocalLengthMax;
+} KSPROPERTY_CAMERACONTROL_FOCAL_LENGTH_S,*PKSPROPERTY_CAMERACONTROL_FOCAL_LENGTH_S;
+
+typedef struct {
+  KSNODEPROPERTY NodeProperty;
+  LONG lOcularFocalLength;
+  LONG lObjectiveFocalLengthMin;
+  LONG lObjectiveFocalLengthMax;
+} KSPROPERTY_CAMERACONTROL_NODE_FOCAL_LENGTH_S,*PKSPROPERTY_CAMERACONTROL_NODE_FOCAL_LENGTH_S;
+
+#define KSPROPERTY_CAMERACONTROL_FLAGS_AUTO    0X0001L
+#define KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL  0X0002L
+
+#define KSPROPERTY_CAMERACONTROL_FLAGS_ABSOLUTE        0X0000L
+#define KSPROPERTY_CAMERACONTROL_FLAGS_RELATIVE        0X0010L
+
+#ifndef __EDevCtrl__
+#define __EDevCtrl__
+
+#define STATIC_PROPSETID_EXT_DEVICE                                    \
+       0xB5730A90L,0x1A2C,0x11cf,0x8c,0x23,0x00,0xAA,0x00,0x6B,0x68,0x14
+DEFINE_GUIDSTRUCT("B5730A90-1A2C-11cf-8C23-00AA006B6814",PROPSETID_EXT_DEVICE);
+#define PROPSETID_EXT_DEVICE DEFINE_GUIDNAMED(PROPSETID_EXT_DEVICE)
+
+typedef enum {
+  KSPROPERTY_EXTDEVICE_ID,
+  KSPROPERTY_EXTDEVICE_VERSION,
+  KSPROPERTY_EXTDEVICE_POWER_STATE,
+  KSPROPERTY_EXTDEVICE_PORT,
+  KSPROPERTY_EXTDEVICE_CAPABILITIES
+} KSPROPERTY_EXTDEVICE;
+
+typedef struct tagDEVCAPS{
+  LONG CanRecord;
+  LONG CanRecordStrobe;
+  LONG HasAudio;
+  LONG HasVideo;
+  LONG UsesFiles;
+  LONG CanSave;
+  LONG DeviceType;
+  LONG TCRead;
+  LONG TCWrite;
+  LONG CTLRead;
+  LONG IndexRead;
+  LONG Preroll;
+  LONG Postroll;
+  LONG SyncAcc;
+  LONG NormRate;
+  LONG CanPreview;
+  LONG CanMonitorSrc;
+  LONG CanTest;
+  LONG VideoIn;
+  LONG AudioIn;
+  LONG Calibrate;
+  LONG SeekType;
+  LONG SimulatedHardware;
+} DEVCAPS,*PDEVCAPS;
+
+typedef struct {
+  KSPROPERTY Property;
+  union {
+    DEVCAPS Capabilities;
+    ULONG DevPort;
+    ULONG PowerState;
+    WCHAR pawchString[MAX_PATH];
+    DWORD NodeUniqueID[2];
+  } u;
+} KSPROPERTY_EXTDEVICE_S,*PKSPROPERTY_EXTDEVICE_S;
+
+#define STATIC_PROPSETID_EXT_TRANSPORT                                 \
+       0xA03CD5F0L,0x3045,0x11cf,0x8c,0x44,0x00,0xAA,0x00,0x6B,0x68,0x14
+DEFINE_GUIDSTRUCT("A03CD5F0-3045-11cf-8C44-00AA006B6814",PROPSETID_EXT_TRANSPORT);
+#define PROPSETID_EXT_TRANSPORT DEFINE_GUIDNAMED(PROPSETID_EXT_TRANSPORT)
+
+typedef enum {
+  KSPROPERTY_EXTXPORT_CAPABILITIES,
+  KSPROPERTY_EXTXPORT_INPUT_SIGNAL_MODE,
+  KSPROPERTY_EXTXPORT_OUTPUT_SIGNAL_MODE,
+  KSPROPERTY_EXTXPORT_LOAD_MEDIUM,
+  KSPROPERTY_EXTXPORT_MEDIUM_INFO,
+  KSPROPERTY_EXTXPORT_STATE,
+  KSPROPERTY_EXTXPORT_STATE_NOTIFY,
+  KSPROPERTY_EXTXPORT_TIMECODE_SEARCH,
+  KSPROPERTY_EXTXPORT_ATN_SEARCH,
+  KSPROPERTY_EXTXPORT_RTC_SEARCH,
+  KSPROPERTY_RAW_AVC_CMD
+} KSPROPERTY_EXTXPORT;
+
+typedef struct tagTRANSPORTSTATUS {
+  LONG Mode;
+  LONG LastError;
+  LONG RecordInhibit;
+  LONG ServoLock;
+  LONG MediaPresent;
+  LONG MediaLength;
+  LONG MediaSize;
+  LONG MediaTrackCount;
+  LONG MediaTrackLength;
+  LONG MediaTrackSide;
+  LONG MediaType;
+  LONG LinkMode;
+  LONG NotifyOn;
+} TRANSPORTSTATUS,*PTRANSPORTSTATUS;
+
+typedef struct tagTRANSPORTBASICPARMS {
+  LONG TimeFormat;
+  LONG TimeReference;
+  LONG Superimpose;
+  LONG EndStopAction;
+  LONG RecordFormat;
+  LONG StepFrames;
+  LONG SetpField;
+  LONG Preroll;
+  LONG RecPreroll;
+  LONG Postroll;
+  LONG EditDelay;
+  LONG PlayTCDelay;
+  LONG RecTCDelay;
+  LONG EditField;
+  LONG FrameServo;
+  LONG ColorFrameServo;
+  LONG ServoRef;
+  LONG WarnGenlock;
+  LONG SetTracking;
+  TCHAR VolumeName[40];
+  LONG Ballistic[20];
+  LONG Speed;
+  LONG CounterFormat;
+  LONG TunerChannel;
+  LONG TunerNumber;
+  LONG TimerEvent;
+  LONG TimerStartDay;
+  LONG TimerStartTime;
+  LONG TimerStopDay;
+  LONG TimerStopTime;
+} TRANSPORTBASICPARMS,*PTRANSPORTBASICPARMS;
+
+typedef struct tagTRANSPORTVIDEOPARMS {
+  LONG OutputMode;
+  LONG Input;
+} TRANSPORTVIDEOPARMS,*PTRANSPORTVIDEOPARMS;
+
+typedef struct tagTRANSPORTAUDIOPARMS {
+  LONG EnableOutput;
+  LONG EnableRecord;
+  LONG EnableSelsync;
+  LONG Input;
+  LONG MonitorSource;
+} TRANSPORTAUDIOPARMS,*PTRANSPORTAUDIOPARMS;
+
+typedef struct {
+  WINBOOL MediaPresent;
+  ULONG MediaType;
+  WINBOOL RecordInhibit;
+} MEDIUM_INFO,*PMEDIUM_INFO;
+
+typedef struct {
+  ULONG Mode;
+  ULONG State;
+} TRANSPORT_STATE,*PTRANSPORT_STATE;
+
+typedef struct {
+  KSPROPERTY Property;
+  union {
+    ULONG Capabilities;
+    ULONG SignalMode;
+    ULONG LoadMedium;
+    MEDIUM_INFO MediumInfo;
+    TRANSPORT_STATE XPrtState;
+    struct {
+      BYTE frame;
+      BYTE second;
+      BYTE minute;
+      BYTE hour;
+    } Timecode;
+    DWORD dwTimecode;
+    DWORD dwAbsTrackNumber;
+    struct {
+      ULONG PayloadSize;
+      BYTE Payload[512];
+    } RawAVC;
+  } u;
+} KSPROPERTY_EXTXPORT_S,*PKSPROPERTY_EXTXPORT_S;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  union {
+    ULONG Capabilities;
+    ULONG SignalMode;
+    ULONG LoadMedium;
+    MEDIUM_INFO MediumInfo;
+    TRANSPORT_STATE XPrtState;
+    struct {
+      BYTE frame;
+      BYTE second;
+      BYTE minute;
+      BYTE hour;
+    } Timecode;
+    DWORD dwTimecode;
+    DWORD dwAbsTrackNumber;
+    struct {
+      ULONG PayloadSize;
+      BYTE Payload[512];
+    } RawAVC;
+  } u;
+} KSPROPERTY_EXTXPORT_NODE_S,*PKSPROPERTY_EXTXPORT_NODE_S;
+
+#define STATIC_PROPSETID_TIMECODE_READER                               \
+       0x9B496CE1L,0x811B,0x11cf,0x8C,0x77,0x00,0xAA,0x00,0x6B,0x68,0x14
+DEFINE_GUIDSTRUCT("9B496CE1-811B-11cf-8C77-00AA006B6814",PROPSETID_TIMECODE_READER);
+#define PROPSETID_TIMECODE_READER DEFINE_GUIDNAMED(PROPSETID_TIMECODE_READER)
+
+typedef enum {
+  KSPROPERTY_TIMECODE_READER,
+  KSPROPERTY_ATN_READER,
+  KSPROPERTY_RTC_READER
+} KSPROPERTY_TIMECODE;
+
+#ifndef TIMECODE_DEFINED
+#define TIMECODE_DEFINED
+typedef union _timecode {
+  struct {
+    WORD wFrameRate;
+    WORD wFrameFract;
+    DWORD dwFrames;
+  };
+  DWORDLONG qw;
+} TIMECODE;
+typedef TIMECODE *PTIMECODE;
+
+typedef struct tagTIMECODE_SAMPLE {
+  LONGLONG qwTick;
+  TIMECODE timecode;
+  DWORD dwUser;
+  DWORD dwFlags;
+} TIMECODE_SAMPLE;
+
+typedef TIMECODE_SAMPLE *PTIMECODE_SAMPLE;
+#endif /* TIMECODE_DEFINED */
+
+typedef struct {
+  KSPROPERTY Property;
+  TIMECODE_SAMPLE TimecodeSamp;
+} KSPROPERTY_TIMECODE_S,*PKSPROPERTY_TIMECODE_S;
+
+typedef struct {
+  KSP_NODE NodeProperty;
+  TIMECODE_SAMPLE TimecodeSamp;
+} KSPROPERTY_TIMECODE_NODE_S,*PKSPROPERTY_TIMECODE_NODE_S;
+
+#define STATIC_KSEVENTSETID_EXTDEV_Command                             \
+       0x109c7988L,0xb3cb,0x11d2,0xb4,0x8e,0x00,0x60,0x97,0xb3,0x39,0x1b
+DEFINE_GUIDSTRUCT("109c7988-b3cb-11d2-b48e-006097b3391b",KSEVENTSETID_EXTDEV_Command);
+#define KSEVENTSETID_EXTDEV_Command DEFINE_GUIDNAMED(KSEVENTSETID_EXTDEV_Command)
+
+typedef enum {
+  KSEVENT_EXTDEV_COMMAND_NOTIFY_INTERIM_READY,
+  KSEVENT_EXTDEV_COMMAND_CONTROL_INTERIM_READY,
+  KSEVENT_EXTDEV_COMMAND_BUSRESET,
+  KSEVENT_EXTDEV_TIMECODE_UPDATE,
+  KSEVENT_EXTDEV_OPERATION_MODE_UPDATE,
+  KSEVENT_EXTDEV_TRANSPORT_STATE_UPDATE,
+  KSEVENT_EXTDEV_NOTIFY_REMOVAL,
+  KSEVENT_EXTDEV_NOTIFY_MEDIUM_CHANGE
+} KSEVENT_DEVCMD;
+#endif /* __EDevCtrl__ */
+
+#define STATIC_PROPSETID_VIDCAP_CROSSBAR                               \
+       0x6a2e0640L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0640-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_CROSSBAR);
+#define PROPSETID_VIDCAP_CROSSBAR DEFINE_GUIDNAMED(PROPSETID_VIDCAP_CROSSBAR)
+
+typedef enum {
+  KSPROPERTY_CROSSBAR_CAPS,
+  KSPROPERTY_CROSSBAR_PININFO,
+  KSPROPERTY_CROSSBAR_CAN_ROUTE,
+  KSPROPERTY_CROSSBAR_ROUTE
+} KSPROPERTY_VIDCAP_CROSSBAR;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG NumberOfInputs;
+  ULONG NumberOfOutputs;
+} KSPROPERTY_CROSSBAR_CAPS_S,*PKSPROPERTY_CROSSBAR_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  KSPIN_DATAFLOW Direction;
+  ULONG Index;
+  ULONG PinType;
+  ULONG RelatedPinIndex;
+  KSPIN_MEDIUM Medium;
+} KSPROPERTY_CROSSBAR_PININFO_S,*PKSPROPERTY_CROSSBAR_PININFO_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG IndexInputPin;
+  ULONG IndexOutputPin;
+  ULONG CanRoute;
+} KSPROPERTY_CROSSBAR_ROUTE_S,*PKSPROPERTY_CROSSBAR_ROUTE_S;
+
+#define STATIC_EVENTSETID_CROSSBAR                                     \
+       0x6a2e0641L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0641-28e4-11d0-a18c-00a0c9118956",EVENTSETID_CROSSBAR);
+#define EVENTSETID_CROSSBAR DEFINE_GUIDNAMED(EVENTSETID_CROSSBAR)
+
+typedef enum {
+  KSEVENT_CROSSBAR_CHANGED
+} KSEVENT_CROSSBAR;
+
+typedef enum {
+  KS_PhysConn_Video_Tuner = 1,
+  KS_PhysConn_Video_Composite,
+  KS_PhysConn_Video_SVideo,
+  KS_PhysConn_Video_RGB,
+  KS_PhysConn_Video_YRYBY,
+  KS_PhysConn_Video_SerialDigital,
+  KS_PhysConn_Video_ParallelDigital,
+  KS_PhysConn_Video_SCSI,
+  KS_PhysConn_Video_AUX,
+  KS_PhysConn_Video_1394,
+  KS_PhysConn_Video_USB,
+  KS_PhysConn_Video_VideoDecoder,
+  KS_PhysConn_Video_VideoEncoder,
+  KS_PhysConn_Video_SCART,
+  KS_PhysConn_Audio_Tuner = 4096,
+  KS_PhysConn_Audio_Line,
+  KS_PhysConn_Audio_Mic,
+  KS_PhysConn_Audio_AESDigital,
+  KS_PhysConn_Audio_SPDIFDigital,
+  KS_PhysConn_Audio_SCSI,
+  KS_PhysConn_Audio_AUX,
+  KS_PhysConn_Audio_1394,
+  KS_PhysConn_Audio_USB,
+  KS_PhysConn_Audio_AudioDecoder
+} KS_PhysicalConnectorType;
+
+#define STATIC_PROPSETID_VIDCAP_TVAUDIO                                        \
+       0x6a2e0650L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0650-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_TVAUDIO);
+#define PROPSETID_VIDCAP_TVAUDIO DEFINE_GUIDNAMED(PROPSETID_VIDCAP_TVAUDIO)
+
+typedef enum {
+  KSPROPERTY_TVAUDIO_CAPS,
+  KSPROPERTY_TVAUDIO_MODE,
+  KSPROPERTY_TVAUDIO_CURRENTLY_AVAILABLE_MODES
+} KSPROPERTY_VIDCAP_TVAUDIO;
+
+#define KS_TVAUDIO_MODE_MONO   0x0001
+#define KS_TVAUDIO_MODE_STEREO 0x0002
+#define KS_TVAUDIO_MODE_LANG_A 0x0010
+#define KS_TVAUDIO_MODE_LANG_B 0x0020
+#define KS_TVAUDIO_MODE_LANG_C 0x0040
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Capabilities;
+  KSPIN_MEDIUM InputMedium;
+  KSPIN_MEDIUM OutputMedium;
+} KSPROPERTY_TVAUDIO_CAPS_S,*PKSPROPERTY_TVAUDIO_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG Mode;
+} KSPROPERTY_TVAUDIO_S,*PKSPROPERTY_TVAUDIO_S;
+
+#define STATIC_KSEVENTSETID_VIDCAP_TVAUDIO                             \
+       0x6a2e0651L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0651-28e4-11d0-a18c-00a0c9118956",KSEVENTSETID_VIDCAP_TVAUDIO);
+#define KSEVENTSETID_VIDCAP_TVAUDIO DEFINE_GUIDNAMED(KSEVENTSETID_VIDCAP_TVAUDIO)
+
+typedef enum {
+  KSEVENT_TVAUDIO_CHANGED
+} KSEVENT_TVAUDIO;
+
+#define STATIC_PROPSETID_VIDCAP_VIDEOCOMPRESSION                       \
+       0xC6E13343L,0x30AC,0x11d0,0xA1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("C6E13343-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEOCOMPRESSION);
+#define PROPSETID_VIDCAP_VIDEOCOMPRESSION DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOCOMPRESSION)
+
+typedef enum {
+  KSPROPERTY_VIDEOCOMPRESSION_GETINFO,
+  KSPROPERTY_VIDEOCOMPRESSION_KEYFRAME_RATE,
+  KSPROPERTY_VIDEOCOMPRESSION_PFRAMES_PER_KEYFRAME,
+  KSPROPERTY_VIDEOCOMPRESSION_QUALITY,
+  KSPROPERTY_VIDEOCOMPRESSION_OVERRIDE_KEYFRAME,
+  KSPROPERTY_VIDEOCOMPRESSION_OVERRIDE_FRAME_SIZE,
+  KSPROPERTY_VIDEOCOMPRESSION_WINDOWSIZE
+} KSPROPERTY_VIDCAP_VIDEOCOMPRESSION;
+
+typedef enum {
+  KS_CompressionCaps_CanQuality = 1,
+  KS_CompressionCaps_CanCrunch = 2,
+  KS_CompressionCaps_CanKeyFrame = 4,
+  KS_CompressionCaps_CanBFrame = 8,
+  KS_CompressionCaps_CanWindow = 0x10
+} KS_CompressionCaps;
+
+typedef enum {
+  KS_StreamingHint_FrameInterval = 0x0100,
+  KS_StreamingHint_KeyFrameRate = 0x0200,
+  KS_StreamingHint_PFrameRate = 0x0400,
+  KS_StreamingHint_CompQuality = 0x0800,
+  KS_StreamingHint_CompWindowSize = 0x1000
+} KS_VideoStreamingHints;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  LONG DefaultKeyFrameRate;
+  LONG DefaultPFrameRate;
+  LONG DefaultQuality;
+  LONG NumberOfQualitySettings;
+  LONG Capabilities;
+} KSPROPERTY_VIDEOCOMPRESSION_GETINFO_S,*PKSPROPERTY_VIDEOCOMPRESSION_GETINFO_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  LONG Value;
+} KSPROPERTY_VIDEOCOMPRESSION_S,*PKSPROPERTY_VIDEOCOMPRESSION_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  LONG Value;
+  ULONG Flags;
+} KSPROPERTY_VIDEOCOMPRESSION_S1,*PKSPROPERTY_VIDEOCOMPRESSION_S1;
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_OVERLAY                            \
+       0xe436eb7fL,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
+DEFINE_GUIDSTRUCT("e436eb7f-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_OVERLAY);
+#define KSDATAFORMAT_SUBTYPE_OVERLAY DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_OVERLAY)
+
+#define STATIC_KSPROPSETID_OverlayUpdate                               \
+       0x490EA5CFL,0x7681,0x11D1,0xA2,0x1C,0x00,0xA0,0xC9,0x22,0x31,0x96
+DEFINE_GUIDSTRUCT("490EA5CF-7681-11D1-A21C-00A0C9223196",KSPROPSETID_OverlayUpdate);
+#define KSPROPSETID_OverlayUpdate DEFINE_GUIDNAMED(KSPROPSETID_OverlayUpdate)
+
+typedef enum {
+  KSPROPERTY_OVERLAYUPDATE_INTERESTS,
+  KSPROPERTY_OVERLAYUPDATE_CLIPLIST = 0x1,
+  KSPROPERTY_OVERLAYUPDATE_PALETTE = 0x2,
+  KSPROPERTY_OVERLAYUPDATE_COLORKEY = 0x4,
+  KSPROPERTY_OVERLAYUPDATE_VIDEOPOSITION = 0x8,
+  KSPROPERTY_OVERLAYUPDATE_DISPLAYCHANGE = 0x10,
+  KSPROPERTY_OVERLAYUPDATE_COLORREF = 0x10000000
+} KSPROPERTY_OVERLAYUPDATE;
+
+typedef struct {
+  ULONG PelsWidth;
+  ULONG PelsHeight;
+  ULONG BitsPerPel;
+  WCHAR DeviceID[1];
+} KSDISPLAYCHANGE,*PKSDISPLAYCHANGE;
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_INTERESTS(Handler)                \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_INTERESTS,     \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(ULONG),                          \
+                               NULL, NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_PALETTE(Handler)          \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_PALETTE,       \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               0,                                      \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_COLORKEY(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_COLORKEY,      \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(COLORKEY),                       \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_CLIPLIST(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_CLIPLIST,      \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               2 *sizeof(RECT) + sizeof(RGNDATAHEADER),\
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_VIDEOPOSITION(Handler)    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_VIDEOPOSITION, \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               2 *sizeof(RECT),                        \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_DISPLAYCHANGE(Handler)    \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_DISPLAYCHANGE, \
+                               NULL,                                   \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(KSDISPLAYCHANGE),                \
+                               (Handler),                              \
+                               NULL, 0, NULL, NULL, 0)
+
+#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_COLORREF(Handler)         \
+       DEFINE_KSPROPERTY_ITEM(                                         \
+                               KSPROPERTY_OVERLAYUPDATE_COLORREF,      \
+                               (Handler),                              \
+                               sizeof(KSPROPERTY),                     \
+                               sizeof(COLORREF),                       \
+                               NULL,                                   \
+                               NULL, 0, NULL, NULL, 0)
+
+#define STATIC_PROPSETID_VIDCAP_VIDEOCONTROL                           \
+       0x6a2e0670L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("6a2e0670-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_VIDEOCONTROL);
+#define PROPSETID_VIDCAP_VIDEOCONTROL DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOCONTROL)
+
+typedef enum {
+  KSPROPERTY_VIDEOCONTROL_CAPS,
+  KSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE,
+  KSPROPERTY_VIDEOCONTROL_FRAME_RATES,
+  KSPROPERTY_VIDEOCONTROL_MODE
+} KSPROPERTY_VIDCAP_VIDEOCONTROL;
+
+typedef enum {
+  KS_VideoControlFlag_FlipHorizontal = 0x0001,
+  KS_VideoControlFlag_FlipVertical = 0x0002,
+  KS_Obsolete_VideoControlFlag_ExternalTriggerEnable = 0x0010,
+  KS_Obsolete_VideoControlFlag_Trigger = 0x0020,
+  KS_VideoControlFlag_ExternalTriggerEnable = 0x0004,
+  KS_VideoControlFlag_Trigger = 0x0008
+} KS_VideoControlFlags;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  ULONG VideoControlCaps;
+} KSPROPERTY_VIDEOCONTROL_CAPS_S,*PKSPROPERTY_VIDEOCONTROL_CAPS_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  LONG Mode;
+} KSPROPERTY_VIDEOCONTROL_MODE_S,*PKSPROPERTY_VIDEOCONTROL_MODE_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  ULONG RangeIndex;
+  SIZE Dimensions;
+  LONGLONG CurrentActualFrameRate;
+  LONGLONG CurrentMaxAvailableFrameRate;
+} KSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE_S,*PKSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE_S;
+
+typedef struct {
+  KSPROPERTY Property;
+  ULONG StreamIndex;
+  ULONG RangeIndex;
+  SIZE Dimensions;
+} KSPROPERTY_VIDEOCONTROL_FRAME_RATES_S,*PKSPROPERTY_VIDEOCONTROL_FRAME_RATES_S;
+
+#define STATIC_PROPSETID_VIDCAP_DROPPEDFRAMES                          \
+       0xC6E13344L,0x30AC,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
+DEFINE_GUIDSTRUCT("C6E13344-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_DROPPEDFRAMES);
+#define PROPSETID_VIDCAP_DROPPEDFRAMES DEFINE_GUIDNAMED(PROPSETID_VIDCAP_DROPPEDFRAMES)
+
+typedef enum {
+  KSPROPERTY_DROPPEDFRAMES_CURRENT
+} KSPROPERTY_VIDCAP_DROPPEDFRAMES;
+
+typedef struct {
+  KSPROPERTY Property;
+  LONGLONG PictureNumber;
+  LONGLONG DropCount;
+  ULONG AverageFrameSize;
+} KSPROPERTY_DROPPEDFRAMES_CURRENT_S,*PKSPROPERTY_DROPPEDFRAMES_CURRENT_S;
+
+#define STATIC_KSPROPSETID_VPConfig                                    \
+       0xbc29a660L,0x30e3,0x11d0,0x9e,0x69,0x00,0xc0,0x4f,0xd7,0xc1,0x5b
+DEFINE_GUIDSTRUCT("bc29a660-30e3-11d0-9e69-00c04fd7c15b",KSPROPSETID_VPConfig);
+#define KSPROPSETID_VPConfig DEFINE_GUIDNAMED(KSPROPSETID_VPConfig)
+
+#define STATIC_KSPROPSETID_VPVBIConfig                                 \
+       0xec529b00L,0x1a1f,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("ec529b00-1a1f-11d1-bad9-00609744111a",KSPROPSETID_VPVBIConfig);
+#define KSPROPSETID_VPVBIConfig DEFINE_GUIDNAMED(KSPROPSETID_VPVBIConfig)
+
+typedef enum {
+  KSPROPERTY_VPCONFIG_NUMCONNECTINFO,
+  KSPROPERTY_VPCONFIG_GETCONNECTINFO,
+  KSPROPERTY_VPCONFIG_SETCONNECTINFO,
+  KSPROPERTY_VPCONFIG_VPDATAINFO,
+  KSPROPERTY_VPCONFIG_MAXPIXELRATE,
+  KSPROPERTY_VPCONFIG_INFORMVPINPUT,
+  KSPROPERTY_VPCONFIG_NUMVIDEOFORMAT,
+  KSPROPERTY_VPCONFIG_GETVIDEOFORMAT,
+  KSPROPERTY_VPCONFIG_SETVIDEOFORMAT,
+  KSPROPERTY_VPCONFIG_INVERTPOLARITY,
+  KSPROPERTY_VPCONFIG_DECIMATIONCAPABILITY,
+  KSPROPERTY_VPCONFIG_SCALEFACTOR,
+  KSPROPERTY_VPCONFIG_DDRAWHANDLE,
+  KSPROPERTY_VPCONFIG_VIDEOPORTID,
+  KSPROPERTY_VPCONFIG_DDRAWSURFACEHANDLE,
+  KSPROPERTY_VPCONFIG_SURFACEPARAMS
+} KSPROPERTY_VPCONFIG;
+
+#define STATIC_CLSID_KsIBasicAudioInterfaceHandler                     \
+       0xb9f8ac3e,0x0f71,0x11d2,0xb7,0x2c,0x00,0xc0,0x4f,0xb6,0xbd,0x3d
+DEFINE_GUIDSTRUCT("b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d",CLSID_KsIBasicAudioInterfaceHandler);
+#define CLSID_KsIBasicAudioInterfaceHandler DEFINE_GUIDNAMED(CLSID_KsIBasicAudioInterfaceHandler)
+
+#ifdef __IVPType__
+typedef struct {
+  AMVPSIZE Size;
+  DWORD MaxPixelsPerSecond;
+  DWORD Reserved;
+} KSVPMAXPIXELRATE,*PKSVPMAXPIXELRATE;
+
+typedef struct {
+  KSPROPERTY Property;
+  AMVPSIZE Size;
+} KSVPSIZE_PROP,*PKSVPSIZE_PROP;
+
+typedef struct {
+  DWORD dwPitch;
+  DWORD dwXOrigin;
+  DWORD dwYOrigin;
+} KSVPSURFACEPARAMS,*PKSVPSURFACEPARAMS;
+#else /* __IVPType__ */
+
+#ifndef __DDRAW_INCLUDED__
+#define DDPF_FOURCC 0x00000004l
+
+typedef struct _DDPIXELFORMAT
+{
+  DWORD dwSize;
+  DWORD dwFlags;
+  DWORD dwFourCC;
+  __MINGW_EXTENSION union
+  {
+    DWORD dwRGBBitCount;
+    DWORD dwYUVBitCount;
+    DWORD dwZBufferBitDepth;
+    DWORD dwAlphaBitDepth;
+  };
+  __MINGW_EXTENSION union
+  {
+    DWORD dwRBitMask;
+    DWORD dwYBitMask;
+  };
+  __MINGW_EXTENSION union
+  {
+    DWORD dwGBitMask;
+    DWORD dwUBitMask;
+  };
+  __MINGW_EXTENSION union
+  {
+    DWORD dwBBitMask;
+    DWORD dwVBitMask;
+  };
+  __MINGW_EXTENSION union
+  {
+    DWORD dwRGBAlphaBitMask;
+    DWORD dwYUVAlphaBitMask;
+    DWORD dwRGBZBitMask;
+    DWORD dwYUVZBitMask;
+  };
+} DDPIXELFORMAT,*LPDDPIXELFORMAT;
+#endif /* __DDRAW_INCLUDED__ */
+
+#ifndef __DVP_INCLUDED__
+typedef struct _DDVIDEOPORTCONNECT {
+  DWORD dwSize;
+  DWORD dwPortWidth;
+  GUID guidTypeID;
+  DWORD dwFlags;
+  ULONG_PTR dwReserved1;
+} DDVIDEOPORTCONNECT,*LPDDVIDEOPORTCONNECT;
+
+#define DDVPTYPE_E_HREFH_VREFH                                         \
+       0x54F39980L,0xDA60,0x11CF,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8
+
+#define DDVPTYPE_E_HREFL_VREFL                                         \
+       0xE09C77E0L,0xDA60,0x11CF,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8
+#endif /* __DVP_INCLUDED__ */
+
+typedef enum
+{
+  KS_PixAspectRatio_NTSC4x3,
+  KS_PixAspectRatio_NTSC16x9,
+  KS_PixAspectRatio_PAL4x3,
+  KS_PixAspectRatio_PAL16x9
+} KS_AMPixAspectRatio;
+
+typedef enum
+{
+  KS_AMVP_DO_NOT_CARE,
+  KS_AMVP_BEST_BANDWIDTH,
+  KS_AMVP_INPUT_SAME_AS_OUTPUT
+} KS_AMVP_SELECTFORMATBY;
+
+typedef enum
+{
+  KS_AMVP_MODE_WEAVE,
+  KS_AMVP_MODE_BOBINTERLEAVED,
+  KS_AMVP_MODE_BOBNONINTERLEAVED,
+  KS_AMVP_MODE_SKIPEVEN,
+  KS_AMVP_MODE_SKIPODD
+} KS_AMVP_MODE;
+
+typedef struct tagKS_AMVPDIMINFO
+{
+  DWORD dwFieldWidth;
+  DWORD dwFieldHeight;
+  DWORD dwVBIWidth;
+  DWORD dwVBIHeight;
+  RECT rcValidRegion;
+} KS_AMVPDIMINFO,*PKS_AMVPDIMINFO;
+
+typedef struct tagKS_AMVPDATAINFO
+{
+  DWORD dwSize;
+  DWORD dwMicrosecondsPerField;
+  KS_AMVPDIMINFO amvpDimInfo;
+  DWORD dwPictAspectRatioX;
+  DWORD dwPictAspectRatioY;
+  WINBOOL bEnableDoubleClock;
+  WINBOOL bEnableVACT;
+  WINBOOL bDataIsInterlaced;
+  LONG lHalfLinesOdd;
+  WINBOOL bFieldPolarityInverted;
+  DWORD dwNumLinesInVREF;
+  LONG lHalfLinesEven;
+  DWORD dwReserved1;
+} KS_AMVPDATAINFO,*PKS_AMVPDATAINFO;
+
+typedef struct tagKS_AMVPSIZE
+{
+  DWORD dwWidth;
+  DWORD dwHeight;
+} KS_AMVPSIZE,*PKS_AMVPSIZE;
+
+typedef struct {
+  KS_AMVPSIZE Size;
+  DWORD MaxPixelsPerSecond;
+  DWORD Reserved;
+} KSVPMAXPIXELRATE,*PKSVPMAXPIXELRATE;
+
+typedef struct {
+  KSPROPERTY Property;
+  KS_AMVPSIZE Size;
+} KSVPSIZE_PROP,*PKSVPSIZE_PROP;
+
+typedef struct {
+  DWORD dwPitch;
+  DWORD dwXOrigin;
+  DWORD dwYOrigin;
+} KSVPSURFACEPARAMS,*PKSVPSURFACEPARAMS;
+#endif /* __IVPType__ */
+
+#define STATIC_KSEVENTSETID_VPNotify                                   \
+       0x20c5598eL,0xd3c8,0x11d0,0x8d,0xfc,0x00,0xc0,0x4f,0xd7,0xc0,0x8b
+DEFINE_GUIDSTRUCT("20c5598e-d3c8-11d0-8dfc-00c04fd7c08b",KSEVENTSETID_VPNotify);
+#define KSEVENTSETID_VPNotify DEFINE_GUIDNAMED(KSEVENTSETID_VPNotify)
+
+typedef enum {
+  KSEVENT_VPNOTIFY_FORMATCHANGE
+} KSEVENT_VPNOTIFY;
+
+#define STATIC_KSEVENTSETID_VIDCAPTOSTI                                        \
+       0xdb47de20,0xf628,0x11d1,0xba,0x41,0x0,0xa0,0xc9,0xd,0x2b,0x5
+DEFINE_GUIDSTRUCT("DB47DE20-F628-11d1-BA41-00A0C90D2B05",KSEVENTSETID_VIDCAPTOSTI);
+#define KSEVENTSETID_VIDCAPNotify DEFINE_GUIDNAMED(KSEVENTSETID_VIDCAPTOSTI)
+
+typedef enum {
+  KSEVENT_VIDCAPTOSTI_EXT_TRIGGER,
+  KSEVENT_VIDCAP_AUTO_UPDATE,
+  KSEVENT_VIDCAP_SEARCH
+} KSEVENT_VIDCAPTOSTI;
+
+typedef enum {
+  KSPROPERTY_EXTENSION_UNIT_INFO,
+  KSPROPERTY_EXTENSION_UNIT_CONTROL,
+  KSPROPERTY_EXTENSION_UNIT_PASS_THROUGH = 0xffff
+} KSPROPERTY_EXTENSION_UNIT,*PKSPROPERTY_EXTENSION_UNIT;
+
+#define STATIC_KSEVENTSETID_VPVBINotify                                        \
+       0xec529b01L,0x1a1f,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
+DEFINE_GUIDSTRUCT("ec529b01-1a1f-11d1-bad9-00609744111a",KSEVENTSETID_VPVBINotify);
+#define KSEVENTSETID_VPVBINotify DEFINE_GUIDNAMED(KSEVENTSETID_VPVBINotify)
+
+typedef enum {
+  KSEVENT_VPVBINOTIFY_FORMATCHANGE
+} KSEVENT_VPVBINOTIFY;
+
+#define STATIC_KSDATAFORMAT_TYPE_AUXLine21Data                         \
+       0x670aea80L,0x3a82,0x11d0,0xb7,0x9b,0x00,0xaa,0x00,0x37,0x67,0xa7
+DEFINE_GUIDSTRUCT("670aea80-3a82-11d0-b79b-00aa003767a7",KSDATAFORMAT_TYPE_AUXLine21Data);
+#define KSDATAFORMAT_TYPE_AUXLine21Data DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_AUXLine21Data)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_Line21_BytePair                    \
+       0x6e8d4a22L,0x310c,0x11d0,0xb7,0x9a,0x00,0xaa,0x00,0x37,0x67,0xa7
+DEFINE_GUIDSTRUCT("6e8d4a22-310c-11d0-b79a-00aa003767a7",KSDATAFORMAT_SUBTYPE_Line21_BytePair);
+#define KSDATAFORMAT_SUBTYPE_Line21_BytePair DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_Line21_BytePair)
+
+#define STATIC_KSDATAFORMAT_SUBTYPE_Line21_GOPPacket                   \
+       0x6e8d4a23L,0x310c,0x11d0,0xb7,0x9a,0x00,0xaa,0x00,0x37,0x67,0xa7
+DEFINE_GUIDSTRUCT("6e8d4a23-310c-11d0-b79a-00aa003767a7",KSDATAFORMAT_SUBTYPE_Line21_GOPPacket);
+#define KSDATAFORMAT_SUBTYPE_Line21_GOPPacket DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_Line21_GOPPacket)
+
+typedef struct _KSGOP_USERDATA {
+  ULONG sc;
+  ULONG reserved1;
+  BYTE cFields;
+  CHAR l21Data[3];
+} KSGOP_USERDATA,*PKSGOP_USERDATA;
+
+#define STATIC_KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK                    \
+       0xed0b916a,0x044d,0x11d1,0xaa,0x78,0x00,0xc0,0x4f,0xc3,0x1d,0x60
+DEFINE_GUIDSTRUCT("ed0b916a-044d-11d1-aa78-00c04fc31d60",KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK);
+#define KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK)
+
+#define KS_AM_UseNewCSSKey                     0x1
+
+#define STATIC_KSPROPSETID_TSRateChange                                        \
+       0xa503c5c0,0x1d1d,0x11d1,0xad,0x80,0x44,0x45,0x53,0x54,0x0,0x0
+DEFINE_GUIDSTRUCT("A503C5C0-1D1D-11D1-AD80-444553540000",KSPROPSETID_TSRateChange);
+#define KSPROPSETID_TSRateChange DEFINE_GUIDNAMED(KSPROPSETID_TSRateChange)
+
+typedef enum {
+  KS_AM_RATE_SimpleRateChange = 1,
+  KS_AM_RATE_ExactRateChange = 2,
+  KS_AM_RATE_MaxFullDataRate = 3,
+  KS_AM_RATE_Step = 4
+} KS_AM_PROPERTY_TS_RATE_CHANGE;
+
+typedef struct {
+  REFERENCE_TIME StartTime;
+  LONG Rate;
+} KS_AM_SimpleRateChange,*PKS_AM_SimpleRateChange;
+
+typedef struct {
+  REFERENCE_TIME OutputZeroTime;
+  LONG Rate;
+} KS_AM_ExactRateChange,*PKS_AM_ExactRateChange;
+
+typedef LONG KS_AM_MaxFullDataRate;
+typedef DWORD KS_AM_Step;
+
+#define STATIC_KSCATEGORY_ENCODER                                      \
+       0x19689bf6,0xc384,0x48fd,0xad,0x51,0x90,0xe5,0x8c,0x79,0xf7,0xb
+DEFINE_GUIDSTRUCT("19689BF6-C384-48fd-AD51-90E58C79F70B",KSCATEGORY_ENCODER);
+#define KSCATEGORY_ENCODER DEFINE_GUIDNAMED(KSCATEGORY_ENCODER)
+
+#define STATIC_KSCATEGORY_MULTIPLEXER                                  \
+       0x7a5de1d3,0x1a1,0x452c,0xb4,0x81,0x4f,0xa2,0xb9,0x62,0x71,0xe8
+DEFINE_GUIDSTRUCT("7A5DE1D3-01A1-452c-B481-4FA2B96271E8",KSCATEGORY_MULTIPLEXER);
+#define KSCATEGORY_MULTIPLEXER DEFINE_GUIDNAMED(KSCATEGORY_MULTIPLEXER)
+
+#ifndef __ENCODER_API_GUIDS__
+#define __ENCODER_API_GUIDS__
+
+#define STATIC_ENCAPIPARAM_BITRATE                                     \
+       0x49cc4c43,0xca83,0x4ad4,0xa9,0xaf,0xf3,0x69,0x6a,0xf6,0x66,0xdf
+DEFINE_GUIDSTRUCT("49CC4C43-CA83-4ad4-A9AF-F3696AF666DF",ENCAPIPARAM_BITRATE);
+#define ENCAPIPARAM_BITRATE DEFINE_GUIDNAMED(ENCAPIPARAM_BITRATE)
+
+#define STATIC_ENCAPIPARAM_PEAK_BITRATE                                        \
+       0x703f16a9,0x3d48,0x44a1,0xb0,0x77,0x1,0x8d,0xff,0x91,0x5d,0x19
+DEFINE_GUIDSTRUCT("703F16A9-3D48-44a1-B077-018DFF915D19",ENCAPIPARAM_PEAK_BITRATE);
+#define ENCAPIPARAM_PEAK_BITRATE DEFINE_GUIDNAMED(ENCAPIPARAM_PEAK_BITRATE)
+
+#define STATIC_ENCAPIPARAM_BITRATE_MODE                                        \
+       0xee5fb25c,0xc713,0x40d1,0x9d,0x58,0xc0,0xd7,0x24,0x1e,0x25,0xf
+DEFINE_GUIDSTRUCT("EE5FB25C-C713-40d1-9D58-C0D7241E250F",ENCAPIPARAM_BITRATE_MODE);
+#define ENCAPIPARAM_BITRATE_MODE DEFINE_GUIDNAMED(ENCAPIPARAM_BITRATE_MODE)
+
+#define STATIC_CODECAPI_CHANGELISTS                                    \
+       0x62b12acf,0xf6b0,0x47d9,0x94,0x56,0x96,0xf2,0x2c,0x4e,0x0b,0x9d
+DEFINE_GUIDSTRUCT("62B12ACF-F6B0-47D9-9456-96F22C4E0B9D",CODECAPI_CHANGELISTS);
+#define CODECAPI_CHANGELISTS DEFINE_GUIDNAMED(CODECAPI_CHANGELISTS)
+
+#define STATIC_CODECAPI_VIDEO_ENCODER                                  \
+       0x7112e8e1,0x3d03,0x47ef,0x8e,0x60,0x03,0xf1,0xcf,0x53,0x73,0x01
+DEFINE_GUIDSTRUCT("7112E8E1-3D03-47EF-8E60-03F1CF537301",CODECAPI_VIDEO_ENCODER);
+#define CODECAPI_VIDEO_ENCODER DEFINE_GUIDNAMED(CODECAPI_VIDEO_ENCODER)
+
+#define STATIC_CODECAPI_AUDIO_ENCODER                                  \
+       0xb9d19a3e,0xf897,0x429c,0xbc,0x46,0x81,0x38,0xb7,0x27,0x2b,0x2d
+DEFINE_GUIDSTRUCT("B9D19A3E-F897-429C-BC46-8138B7272B2D",CODECAPI_AUDIO_ENCODER);
+#define CODECAPI_AUDIO_ENCODER DEFINE_GUIDNAMED(CODECAPI_AUDIO_ENCODER)
+
+#define STATIC_CODECAPI_SETALLDEFAULTS                                 \
+       0x6c5e6a7c,0xacf8,0x4f55,0xa9,0x99,0x1a,0x62,0x81,0x09,0x05,0x1b
+DEFINE_GUIDSTRUCT("6C5E6A7C-ACF8-4F55-A999-1A628109051B",CODECAPI_SETALLDEFAULTS);
+#define CODECAPI_SETALLDEFAULTS DEFINE_GUIDNAMED(CODECAPI_SETALLDEFAULTS)
+
+#define STATIC_CODECAPI_ALLSETTINGS                                    \
+       0x6a577e92,0x83e1,0x4113,0xad,0xc2,0x4f,0xce,0xc3,0x2f,0x83,0xa1
+DEFINE_GUIDSTRUCT("6A577E92-83E1-4113-ADC2-4FCEC32F83A1",CODECAPI_ALLSETTINGS);
+#define CODECAPI_ALLSETTINGS DEFINE_GUIDNAMED(CODECAPI_ALLSETTINGS)
+
+#define STATIC_CODECAPI_SUPPORTSEVENTS                                 \
+       0x0581af97,0x7693,0x4dbd,0x9d,0xca,0x3f,0x9e,0xbd,0x65,0x85,0xa1
+DEFINE_GUIDSTRUCT("0581AF97-7693-4DBD-9DCA-3F9EBD6585A1",CODECAPI_SUPPORTSEVENTS);
+#define CODECAPI_SUPPORTSEVENTS DEFINE_GUIDNAMED(CODECAPI_SUPPORTSEVENTS)
+
+#define STATIC_CODECAPI_CURRENTCHANGELIST                              \
+       0x1cb14e83,0x7d72,0x4657,0x83,0xfd,0x47,0xa2,0xc5,0xb9,0xd1,0x3d
+DEFINE_GUIDSTRUCT("1CB14E83-7D72-4657-83FD-47A2C5B9D13D",CODECAPI_CURRENTCHANGELIST);
+#define CODECAPI_CURRENTCHANGELIST DEFINE_GUIDNAMED(CODECAPI_CURRENTCHANGELIST)
+#endif /* __ENCODER_API_GUIDS__ */
+
+#ifndef __ENCODER_API_DEFINES__
+#define __ENCODER_API_DEFINES__
+typedef enum {
+  ConstantBitRate = 0,
+  VariableBitRateAverage,
+  VariableBitRatePeak
+} VIDEOENCODER_BITRATE_MODE;
+#endif /* __ENCODER_API_DEFINES__ */
+
+#define STATIC_KSPROPSETID_Jack\
+    0x4509f757, 0x2d46, 0x4637, 0x8e, 0x62, 0xce, 0x7d, 0xb9, 0x44, 0xf5, 0x7b
+DEFINE_GUIDSTRUCT("4509F757-2D46-4637-8E62-CE7DB944F57B", KSPROPSETID_Jack);
+#define KSPROPSETID_Jack DEFINE_GUIDNAMED(KSPROPSETID_Jack)
+
+typedef enum {
+    KSPROPERTY_JACK_DESCRIPTION = 1,
+    KSPROPERTY_JACK_DESCRIPTION2,
+    KSPROPERTY_JACK_SINK_INFO
+} KSPROPERTY_JACK;
+
+typedef enum
+{
+    eConnTypeUnknown,
+    eConnType3Point5mm,
+    eConnTypeQuarter,
+    eConnTypeAtapiInternal,
+    eConnTypeRCA,
+    eConnTypeOptical,
+    eConnTypeOtherDigital,
+    eConnTypeOtherAnalog,
+    eConnTypeMultichannelAnalogDIN,
+    eConnTypeXlrProfessional,
+    eConnTypeRJ11Modem,
+    eConnTypeCombination
+} EPcxConnectionType;
+
+typedef enum
+{
+    eGeoLocRear = 0x1,
+    eGeoLocFront,
+    eGeoLocLeft,
+    eGeoLocRight,
+    eGeoLocTop,
+    eGeoLocBottom,
+    eGeoLocRearPanel,
+    eGeoLocRiser,
+    eGeoLocInsideMobileLid,
+    eGeoLocDrivebay,
+    eGeoLocHDMI,
+    eGeoLocOutsideMobileLid,
+    eGeoLocATAPI,
+    eGeoLocReserved5,
+    eGeoLocReserved6,
+    EPcxGeoLocation_enum_count
+} EPcxGeoLocation;
+
+typedef enum
+{
+    eGenLocPrimaryBox = 0,
+    eGenLocInternal,
+    eGenLocSeparate,
+    eGenLocOther,
+    EPcxGenLocation_enum_count
+} EPcxGenLocation;
+
+typedef enum
+{
+    ePortConnJack = 0,
+    ePortConnIntegratedDevice,
+    ePortConnBothIntegratedAndJack,
+    ePortConnUnknown
+} EPxcPortConnection;
+
+typedef struct 
+{
+    DWORD                 ChannelMapping;
+    COLORREF              Color;
+    EPcxConnectionType    ConnectionType;
+    EPcxGeoLocation       GeoLocation;
+    EPcxGenLocation       GenLocation;
+    EPxcPortConnection    PortConnection;
+    BOOL                  IsConnected;
+} KSJACK_DESCRIPTION, *PKSJACK_DESCRIPTION;
+
+typedef enum 
+{
+    KSJACK_SINK_CONNECTIONTYPE_HDMI = 0,           
+    KSJACK_SINK_CONNECTIONTYPE_DISPLAYPORT,         
+} KSJACK_SINK_CONNECTIONTYPE;
+
+#define MAX_SINK_DESCRIPTION_NAME_LENGTH 32
+typedef struct _tagKSJACK_SINK_INFORMATION
+{
+  KSJACK_SINK_CONNECTIONTYPE ConnType;              
+  WORD  ManufacturerId;                            
+  WORD  ProductId;                                  
+  WORD  AudioLatency;                               
+  BOOL  HDCPCapable;                                
+  BOOL  AICapable;                                  
+  UCHAR SinkDescriptionLength;                      
+  WCHAR SinkDescription[MAX_SINK_DESCRIPTION_NAME_LENGTH];
+  LUID  PortId;                                 
+}  KSJACK_SINK_INFORMATION, *PKSJACK_SINK_INFORMATION;
+
+#define JACKDESC2_PRESENCE_DETECT_CAPABILITY       0x00000001 
+#define JACKDESC2_DYNAMIC_FORMAT_CHANGE_CAPABILITY 0x00000002
+
+typedef struct _tagKSJACK_DESCRIPTION2
+{
+  DWORD              DeviceStateInfo;
+  DWORD              JackCapabilities;
+} KSJACK_DESCRIPTION2, *PKSJACK_DESCRIPTION2;
+
+/* Additional structs for Windows Vista and later */
+typedef struct _tagKSRTAUDIO_BUFFER_PROPERTY {
+    KSPROPERTY  Property;
+    PVOID       BaseAddress;
+    ULONG       RequestedBufferSize;
+} KSRTAUDIO_BUFFER_PROPERTY, *PKSRTAUDIO_BUFFER_PROPERTY;
+
+typedef struct _tagKSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION {
+    KSPROPERTY  Property;
+    PVOID       BaseAddress;
+    ULONG       RequestedBufferSize;
+    ULONG       NotificationCount;
+} KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION, *PKSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION;
+
+typedef struct _tagKSRTAUDIO_BUFFER {
+    PVOID   BufferAddress;
+    ULONG   ActualBufferSize;
+    BOOL    CallMemoryBarrier;
+} KSRTAUDIO_BUFFER, *PKSRTAUDIO_BUFFER;
+
+typedef struct _tagKSRTAUDIO_HWLATENCY {
+    ULONG   FifoSize;
+    ULONG   ChipsetDelay;
+    ULONG   CodecDelay;
+} KSRTAUDIO_HWLATENCY, *PKSRTAUDIO_HWLATENCY;
+
+typedef struct _tagKSRTAUDIO_HWREGISTER_PROPERTY {
+    KSPROPERTY  Property;
+    PVOID       BaseAddress;
+} KSRTAUDIO_HWREGISTER_PROPERTY, *PKSRTAUDIO_HWREGISTER_PROPERTY;
+
+typedef struct _tagKSRTAUDIO_HWREGISTER {
+    PVOID       Register;
+    ULONG       Width;
+    ULONGLONG   Numerator;
+    ULONGLONG   Denominator;
+    ULONG       Accuracy;
+} KSRTAUDIO_HWREGISTER, *PKSRTAUDIO_HWREGISTER;
+
+typedef struct _tagKSRTAUDIO_NOTIFICATION_EVENT_PROPERTY {
+    KSPROPERTY  Property;
+    HANDLE      NotificationEvent;
+} KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY, *PKSRTAUDIO_NOTIFICATION_EVENT_PROPERTY;
+
+
+#endif /* _KSMEDIA_ */
+
diff --git a/portaudio/src/hostapi/wasapi/pa_win_wasapi.c b/portaudio/src/hostapi/wasapi/pa_win_wasapi.c
new file mode 100644 (file)
index 0000000..c32bf9d
--- /dev/null
@@ -0,0 +1,5738 @@
+/*
+ * Portable Audio I/O Library WASAPI implementation
+ * Copyright (c) 2006-2010 David Viens, Dmitry Kostjuchenko
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup hostapi_src
+ @brief WASAPI implementation of support for a host API.
+ @note pa_wasapi currently requires minimum VC 2005, and the latest Vista SDK
+*/
+
+#include <windows.h>
+#include <stdio.h>
+#include <process.h>
+#include <assert.h>
+
+// WinRT
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
+       #define PA_WINRT
+       #define INITGUID
+#endif
+
+// WASAPI
+#include <mmreg.h>  // must be before other Wasapi headers
+#if (defined(_MSC_VER) && (_MSC_VER >= 1400)) || defined(__MINGW64_VERSION_MAJOR)
+       #include <Avrt.h>
+       #define COBJMACROS
+       #include <Audioclient.h>
+       #include <endpointvolume.h>
+       #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
+       #include <mmdeviceapi.h>
+       #include <functiondiscoverykeys_devpkey.h>
+    #include <devicetopology.h>        // Used to get IKsJackDescription interface
+       #undef INITGUID
+#endif
+#ifndef __MWERKS__
+       #include <malloc.h>
+       #include <memory.h>
+#endif
+
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_win_wasapi.h"
+#include "pa_debugprint.h"
+#include "pa_ringbuffer.h"
+#include "pa_win_coinitialize.h"
+
+#if !defined(NTDDI_VERSION)
+    #undef WINVER
+    #undef _WIN32_WINNT
+    #define WINVER       0x0600 // VISTA
+       #define _WIN32_WINNT WINVER
+
+       #ifndef _AVRT_ //<< fix MinGW dummy compile by defining missing type: AVRT_PRIORITY
+        typedef enum _AVRT_PRIORITY
+        {
+            AVRT_PRIORITY_LOW = -1,
+            AVRT_PRIORITY_NORMAL,
+            AVRT_PRIORITY_HIGH,
+            AVRT_PRIORITY_CRITICAL
+        } AVRT_PRIORITY, *PAVRT_PRIORITY;
+       #endif
+
+       #include <basetyps.h> // << for IID/CLSID
+    #include <rpcsal.h>
+    #include <sal.h>
+
+       #ifndef __LPCGUID_DEFINED__
+               #define __LPCGUID_DEFINED__
+               typedef const GUID *LPCGUID;
+       #endif
+
+    #ifndef PROPERTYKEY_DEFINED
+        #define PROPERTYKEY_DEFINED
+        typedef struct _tagpropertykey
+        {
+            GUID fmtid;
+            DWORD pid;
+        }      PROPERTYKEY;
+    #endif
+
+    #ifdef __midl_proxy
+        #define __MIDL_CONST
+    #else
+        #define __MIDL_CONST const
+    #endif
+
+    #ifdef WIN64
+        #include <wtypes.h>
+        typedef LONG NTSTATUS;
+        #define FASTCALL
+        #include <oleidl.h>
+        #include <objidl.h>
+     #else
+        typedef struct _BYTE_BLOB
+        {
+            unsigned long clSize;
+            unsigned char abData[ 1 ];
+        }      BYTE_BLOB;
+        typedef /* [unique] */  __RPC_unique_pointer BYTE_BLOB *UP_BYTE_BLOB;
+        typedef LONGLONG REFERENCE_TIME;
+        #define NONAMELESSUNION
+    #endif
+    
+    #ifndef WAVE_FORMAT_IEEE_FLOAT
+        #define WAVE_FORMAT_IEEE_FLOAT 0x0003 // 32-bit floating-point
+    #endif    
+    
+    #ifndef __MINGW_EXTENSION
+        #if defined(__GNUC__) || defined(__GNUG__)
+            #define __MINGW_EXTENSION __extension__
+        #else
+            #define __MINGW_EXTENSION
+        #endif
+    #endif 
+
+    #include <sdkddkver.h>
+    #include <propkeydef.h>
+    #define COBJMACROS
+    #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
+    #include <audioclient.h>
+    #include <mmdeviceapi.h>
+    #include <endpointvolume.h>
+    #include <functiondiscoverykeys.h>
+       #include <devicetopology.h>     // Used to get IKsJackDescription interface
+    #undef INITGUID
+
+#endif // NTDDI_VERSION
+
+// Missing declarations for WinRT
+#ifdef PA_WINRT
+
+       #define DEVICE_STATE_ACTIVE 0x00000001
+
+       typedef enum _EDataFlow
+       {       
+               eRender                                 = 0,
+               eCapture                                = ( eRender + 1 ) ,
+               eAll                                    = ( eCapture + 1 ) ,
+               EDataFlow_enum_count    = ( eAll + 1 )
+       }
+       EDataFlow;
+
+       typedef enum _EndpointFormFactor
+       {       
+               RemoteNetworkDevice                     = 0,
+               Speakers                                        = ( RemoteNetworkDevice + 1 ) ,
+               LineLevel                                       = ( Speakers + 1 ) ,
+               Headphones                                      = ( LineLevel + 1 ) ,
+               Microphone                                      = ( Headphones + 1 ) ,
+               Headset                                         = ( Microphone + 1 ) ,
+               Handset                                         = ( Headset + 1 ) ,
+               UnknownDigitalPassthrough       = ( Handset + 1 ) ,
+               SPDIF                                           = ( UnknownDigitalPassthrough + 1 ) ,
+               HDMI                                            = ( SPDIF + 1 ) ,
+               UnknownFormFactor                       = ( HDMI + 1 ) 
+       }       
+       EndpointFormFactor;
+
+#endif
+
+#ifndef GUID_SECT
+    #define GUID_SECT
+#endif
+
+#define __DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define __DEFINE_IID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const IID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define __DEFINE_CLSID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const CLSID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define PA_DEFINE_CLSID(className, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+    __DEFINE_CLSID(pa_CLSID_##className, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
+#define PA_DEFINE_IID(interfaceName, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+    __DEFINE_IID(pa_IID_##interfaceName, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
+
+// "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"
+PA_DEFINE_IID(IAudioClient,         1cb9ad4c, dbfa, 4c32, b1, 78, c2, f5, 68, a7, 03, b2);
+// "726778CD-F60A-4EDA-82DE-E47610CD78AA"
+PA_DEFINE_IID(IAudioClient2,        726778cd, f60a, 4eda, 82, de, e4, 76, 10, cd, 78, aa);
+// "1BE09788-6894-4089-8586-9A2A6C265AC5"
+PA_DEFINE_IID(IMMEndpoint,          1be09788, 6894, 4089, 85, 86, 9a, 2a, 6c, 26, 5a, c5);
+// "A95664D2-9614-4F35-A746-DE8DB63617E6"
+PA_DEFINE_IID(IMMDeviceEnumerator,  a95664d2, 9614, 4f35, a7, 46, de, 8d, b6, 36, 17, e6);
+// "BCDE0395-E52F-467C-8E3D-C4579291692E"
+PA_DEFINE_CLSID(IMMDeviceEnumerator,bcde0395, e52f, 467c, 8e, 3d, c4, 57, 92, 91, 69, 2e);
+// "F294ACFC-3146-4483-A7BF-ADDCA7C260E2"
+PA_DEFINE_IID(IAudioRenderClient,   f294acfc, 3146, 4483, a7, bf, ad, dc, a7, c2, 60, e2);
+// "C8ADBD64-E71E-48a0-A4DE-185C395CD317"
+PA_DEFINE_IID(IAudioCaptureClient,  c8adbd64, e71e, 48a0, a4, de, 18, 5c, 39, 5c, d3, 17);
+// *2A07407E-6497-4A18-9787-32F79BD0D98F*  Or this??
+PA_DEFINE_IID(IDeviceTopology,      2A07407E, 6497, 4A18, 97, 87, 32, f7, 9b, d0, d9, 8f);
+// *AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9*
+PA_DEFINE_IID(IPart,                AE2DE0E4, 5BCA, 4F2D, aa, 46, 5d, 13, f8, fd, b3, a9);
+// *4509F757-2D46-4637-8E62-CE7DB944F57B*
+PA_DEFINE_IID(IKsJackDescription,   4509F757, 2D46, 4637, 8e, 62, ce, 7d, b9, 44, f5, 7b);
+
+// Media formats:
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_PCM,        0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_ADPCM,      0x00000002, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+
+#ifdef __IAudioClient2_INTERFACE_DEFINED__
+typedef enum _pa_AUDCLNT_STREAMOPTIONS { 
+       pa_AUDCLNT_STREAMOPTIONS_NONE          = 0x00,
+       pa_AUDCLNT_STREAMOPTIONS_RAW           = 0x01,
+       pa_AUDCLNT_STREAMOPTIONS_MATCH_FORMAT  = 0x02
+} pa_AUDCLNT_STREAMOPTIONS;
+typedef struct _pa_AudioClientProperties {
+       UINT32                   cbSize;
+       BOOL                     bIsOffload;
+       AUDIO_STREAM_CATEGORY    eCategory;
+       pa_AUDCLNT_STREAMOPTIONS Options;
+} pa_AudioClientProperties;
+#define PA_AUDIOCLIENTPROPERTIES_SIZE_CATEGORY (sizeof(pa_AudioClientProperties) - sizeof(pa_AUDCLNT_STREAMOPTIONS))
+#define PA_AUDIOCLIENTPROPERTIES_SIZE_OPTIONS   sizeof(pa_AudioClientProperties)
+#endif // __IAudioClient2_INTERFACE_DEFINED__
+
+/* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
+       #define CREATE_THREAD(PROC) (HANDLE)_beginthreadex( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
+       #define PA_THREAD_FUNC static unsigned WINAPI
+       #define PA_THREAD_ID unsigned
+#else
+       #define CREATE_THREAD(PROC) CreateThread( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
+       #define PA_THREAD_FUNC static DWORD WINAPI
+       #define PA_THREAD_ID DWORD
+#endif
+
+// Thread function forward decl.
+PA_THREAD_FUNC ProcThreadEvent(void *param);
+PA_THREAD_FUNC ProcThreadPoll(void *param);
+
+// Availabe from Windows 7
+#ifndef AUDCLNT_E_BUFFER_ERROR
+       #define AUDCLNT_E_BUFFER_ERROR AUDCLNT_ERR(0x018)
+#endif
+#ifndef AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
+       #define AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED AUDCLNT_ERR(0x019)
+#endif
+#ifndef AUDCLNT_E_INVALID_DEVICE_PERIOD
+       #define AUDCLNT_E_INVALID_DEVICE_PERIOD AUDCLNT_ERR(0x020)
+#endif
+
+#define MAX_STR_LEN 512
+
+enum { S_INPUT = 0, S_OUTPUT = 1, S_COUNT = 2, S_FULLDUPLEX = 0 };
+
+// Number of packets which compose single contignous buffer. With trial and error it was calculated
+// that WASAPI Input sub-system uses 6 packets per whole buffer. Please provide more information
+// or corrections if available.
+enum { WASAPI_PACKETS_PER_INPUT_BUFFER = 6 };
+
+#define STATIC_ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
+
+#define PRINT(x) PA_DEBUG(x);
+
+#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+    PaUtil_SetLastHostErrorInfo( paWASAPI, errorCode, errorText )
+
+#define PA_WASAPI__IS_FULLDUPLEX(STREAM) ((STREAM)->in.clientProc && (STREAM)->out.clientProc)
+
+#ifndef IF_FAILED_JUMP
+#define IF_FAILED_JUMP(hr, label) if(FAILED(hr)) goto label;
+#endif
+
+#ifndef IF_FAILED_INTERNAL_ERROR_JUMP
+#define IF_FAILED_INTERNAL_ERROR_JUMP(hr, error, label) if(FAILED(hr)) { error = paInternalError; goto label; }
+#endif
+
+#define SAFE_CLOSE(h) if ((h) != NULL) { CloseHandle((h)); (h) = NULL; }
+#define SAFE_RELEASE(punk) if ((punk) != NULL) { (punk)->lpVtbl->Release((punk)); (punk) = NULL; }
+
+// Mixer function
+typedef void (*MixMonoToStereoF) (void *__to, void *__from, UINT32 count);
+
+// AVRT is the new "multimedia schedulling stuff"
+#ifndef PA_WINRT
+typedef BOOL   (WINAPI *FAvRtCreateThreadOrderingGroup)  (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER);
+typedef BOOL   (WINAPI *FAvRtDeleteThreadOrderingGroup)  (HANDLE);
+typedef BOOL   (WINAPI *FAvRtWaitOnThreadOrderingGroup)  (HANDLE);
+typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics)   (LPCSTR,LPDWORD);
+typedef BOOL   (WINAPI *FAvRevertMmThreadCharacteristics)(HANDLE);
+typedef BOOL   (WINAPI *FAvSetMmThreadPriority)          (HANDLE,AVRT_PRIORITY);
+static HMODULE hDInputDLL = 0;
+FAvRtCreateThreadOrderingGroup   pAvRtCreateThreadOrderingGroup = NULL;
+FAvRtDeleteThreadOrderingGroup   pAvRtDeleteThreadOrderingGroup = NULL;
+FAvRtWaitOnThreadOrderingGroup   pAvRtWaitOnThreadOrderingGroup = NULL;
+FAvSetMmThreadCharacteristics    pAvSetMmThreadCharacteristics = NULL;
+FAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
+FAvSetMmThreadPriority           pAvSetMmThreadPriority = NULL;
+#endif
+
+#define _GetProc(fun, type, name)  {                                                        \
+                                        fun = (type) GetProcAddress(hDInputDLL,name);       \
+                                        if (fun == NULL) {                                  \
+                                            PRINT(("GetProcAddr failed for %s" ,name));     \
+                                            return FALSE;                                   \
+                                        }                                                   \
+                                    }                                                       \
+
+// ------------------------------------------------------------------------------------------
+/* prototypes for functions declared in this file */
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+// dummy entry point for other compilers and sdks
+// currently built using RC1 SDK (5600)
+//#if _MSC_VER < 1400
+//PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+//{
+    //return paNoError;
+//}
+//#else
+
+// ------------------------------------------------------------------------------------------
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+// ------------------------------------------------------------------------------------------
+/*
+ These are fields that can be gathered from IDevice and IAudioDevice PRIOR to Initialize, and
+ done in first pass i assume that neither of these will cause the Driver to "load", but again,
+ who knows how they implement their stuff
+ */
+typedef struct PaWasapiDeviceInfo
+{
+    // Device
+#ifndef PA_WINRT
+    IMMDevice *device;
+#endif
+
+       // from GetId
+    WCHAR szDeviceID[MAX_STR_LEN];
+
+       // from GetState
+    DWORD state;
+
+    // Fields filled from IAudioDevice (_prior_ to Initialize)
+    // from GetDevicePeriod(
+    REFERENCE_TIME DefaultDevicePeriod;
+    REFERENCE_TIME MinimumDevicePeriod;
+
+       // Default format (setup through Control Panel by user)
+       WAVEFORMATEXTENSIBLE DefaultFormat;
+
+    // Fields filled from IMMEndpoint'sGetDataFlow
+    EDataFlow flow;
+
+       // Formfactor
+       EndpointFormFactor formFactor;
+}
+PaWasapiDeviceInfo;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiHostApiRepresentation - host api datastructure specific to this implementation */
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface       callbackStreamInterface;
+    PaUtilStreamInterface       blockingStreamInterface;
+
+    PaUtilAllocationGroup      *allocations;
+
+    /* implementation specific data goes here */
+
+    PaWinUtilComInitializationResult comInitializationResult;
+
+    //in case we later need the synch
+#ifndef PA_WINRT
+    IMMDeviceEnumerator *enumerator;
+#endif
+
+    //this is the REAL number of devices, whether they are usefull to PA or not!
+    UINT32 deviceCount;
+
+    WCHAR defaultRenderer [MAX_STR_LEN];
+    WCHAR defaultCapturer [MAX_STR_LEN];
+
+    PaWasapiDeviceInfo *devInfo;
+
+       // Is true when WOW64 Vista/7 Workaround is needed
+       BOOL useWOW64Workaround;
+}
+PaWasapiHostApiRepresentation;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiAudioClientParams - audio client parameters */
+typedef struct PaWasapiAudioClientParams
+{
+       PaWasapiDeviceInfo *device_info;
+       PaStreamParameters  stream_params;
+       PaWasapiStreamInfo  wasapi_params;
+       UINT32              frames_per_buffer;
+       double              sample_rate;
+       BOOL                blocking;
+       BOOL                full_duplex;
+       BOOL                wow64_workaround;
+}
+PaWasapiAudioClientParams;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiStream - a stream data structure specifically for this implementation */
+typedef struct PaWasapiSubStream
+{
+    IAudioClient        *clientParent;
+#ifndef PA_WINRT
+       IStream                         *clientStream;
+#endif
+       IAudioClient            *clientProc;
+
+    WAVEFORMATEXTENSIBLE wavex;
+    UINT32               bufferSize;
+    REFERENCE_TIME       deviceLatency;
+    REFERENCE_TIME       period;
+       double                           latencySeconds;
+    UINT32                              framesPerHostCallback;
+       AUDCLNT_SHAREMODE    shareMode;
+       UINT32               streamFlags; // AUDCLNT_STREAMFLAGS_EVENTCALLBACK, ...
+       UINT32               flags;
+       PaWasapiAudioClientParams params; //!< parameters
+
+       // Buffers
+       UINT32               buffers;                   //!< number of buffers used (from host side)
+       UINT32               framesPerBuffer;   //!< number of frames per 1 buffer
+       BOOL                 userBufferAndHostMatch;
+
+       // Used for Mono >> Stereo workaround, if driver does not support it
+       // (in Exclusive mode WASAPI usually refuses to operate with Mono (1-ch)
+       void                *monoBuffer;         //!< pointer to buffer
+       UINT32               monoBufferSize; //!< buffer size in bytes
+       MixMonoToStereoF     monoMixer;          //!< pointer to mixer function
+
+       PaUtilRingBuffer    *tailBuffer;       //!< buffer with trailing sample for blocking mode operations (only for Input)
+       void                *tailBufferMemory; //!< tail buffer memory region
+}
+PaWasapiSubStream;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiHostProcessor - redirects processing data */
+typedef struct PaWasapiHostProcessor
+{
+    PaWasapiHostProcessorCallback processor;
+    void *userData;
+}
+PaWasapiHostProcessor;
+
+// ------------------------------------------------------------------------------------------
+typedef struct PaWasapiStream
+{
+       /* IMPLEMENT ME: rename this */
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer      cpuLoadMeasurer;
+    PaUtilBufferProcessor      bufferProcessor;
+
+    // input
+       PaWasapiSubStream          in;
+    IAudioCaptureClient       *captureClientParent;
+#ifndef PA_WINRT
+       IStream                   *captureClientStream;
+#endif
+       IAudioCaptureClient       *captureClient;
+    IAudioEndpointVolume      *inVol;
+
+       // output
+       PaWasapiSubStream          out;
+    IAudioRenderClient        *renderClientParent;
+#ifndef PA_WINRT
+       IStream                   *renderClientStream;
+#endif
+       IAudioRenderClient        *renderClient;
+       IAudioEndpointVolume      *outVol;
+
+       // event handles for event-driven processing mode
+       HANDLE event[S_COUNT];
+
+       // buffer mode
+       PaUtilHostBufferSizeMode bufferMode;
+
+       // must be volatile to avoid race condition on user query while
+       // thread is being started
+    volatile BOOL running;
+
+    PA_THREAD_ID dwThreadId;
+    HANDLE hThread;
+       HANDLE hCloseRequest;
+       HANDLE hThreadStart;        //!< signalled by thread on start
+       HANDLE hThreadExit;         //!< signalled by thread on exit
+       HANDLE hBlockingOpStreamRD;
+       HANDLE hBlockingOpStreamWR;
+
+    // Host callback Output overrider
+       PaWasapiHostProcessor hostProcessOverrideOutput;
+
+    // Host callback Input overrider
+       PaWasapiHostProcessor hostProcessOverrideInput;
+
+       // Defines blocking/callback interface used
+       BOOL bBlocking;
+
+       // Av Task (MM thread management)
+       HANDLE hAvTask;
+
+       // Thread priority level
+       PaWasapiThreadPriority nThreadPriority;
+}
+PaWasapiStream;
+
+// COM marshaling
+static HRESULT MarshalSubStreamComPointers(PaWasapiSubStream *substream);
+static HRESULT MarshalStreamComPointers(PaWasapiStream *stream);
+static HRESULT UnmarshalSubStreamComPointers(PaWasapiSubStream *substream);
+static HRESULT UnmarshalStreamComPointers(PaWasapiStream *stream);
+static void ReleaseUnmarshaledSubComPointers(PaWasapiSubStream *substream);
+static void ReleaseUnmarshaledComPointers(PaWasapiStream *stream);
+
+// Local stream methods
+static void _StreamOnStop(PaWasapiStream *stream);
+static void _StreamFinish(PaWasapiStream *stream);
+static void _StreamCleanup(PaWasapiStream *stream);
+static HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
+static HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
+static void *PaWasapi_ReallocateMemory(void *ptr, size_t size);
+static void PaWasapi_FreeMemory(void *ptr);
+
+// Local statics
+
+// ------------------------------------------------------------------------------------------
+#define LogHostError(HRES) __LogHostError(HRES, __FUNCTION__, __FILE__, __LINE__)
+static HRESULT __LogHostError(HRESULT res, const char *func, const char *file, int line)
+{
+    const char *text = NULL;
+    switch (res)
+       {
+       case S_OK: return res;
+       case E_POINTER                              :text ="E_POINTER"; break;
+       case E_INVALIDARG                           :text ="E_INVALIDARG"; break;
+
+       case AUDCLNT_E_NOT_INITIALIZED              :text ="AUDCLNT_E_NOT_INITIALIZED"; break;
+       case AUDCLNT_E_ALREADY_INITIALIZED          :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break;
+       case AUDCLNT_E_WRONG_ENDPOINT_TYPE          :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
+       case AUDCLNT_E_DEVICE_INVALIDATED           :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break;
+       case AUDCLNT_E_NOT_STOPPED                  :text ="AUDCLNT_E_NOT_STOPPED"; break;
+       case AUDCLNT_E_BUFFER_TOO_LARGE             :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break;
+       case AUDCLNT_E_OUT_OF_ORDER                 :text ="AUDCLNT_E_OUT_OF_ORDER"; break;
+       case AUDCLNT_E_UNSUPPORTED_FORMAT           :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
+       case AUDCLNT_E_INVALID_SIZE                 :text ="AUDCLNT_E_INVALID_SIZE"; break;
+       case AUDCLNT_E_DEVICE_IN_USE                :text ="AUDCLNT_E_DEVICE_IN_USE"; break;
+       case AUDCLNT_E_BUFFER_OPERATION_PENDING     :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
+       case AUDCLNT_E_THREAD_NOT_REGISTERED        :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
+       case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED   :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
+       case AUDCLNT_E_ENDPOINT_CREATE_FAILED       :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
+       case AUDCLNT_E_SERVICE_NOT_RUNNING          :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
+       case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED     :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
+       case AUDCLNT_E_EXCLUSIVE_MODE_ONLY          :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
+       case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
+       case AUDCLNT_E_EVENTHANDLE_NOT_SET          :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
+       case AUDCLNT_E_INCORRECT_BUFFER_SIZE        :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
+       case AUDCLNT_E_BUFFER_SIZE_ERROR            :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
+       case AUDCLNT_E_CPUUSAGE_EXCEEDED            :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break;
+       case AUDCLNT_E_BUFFER_ERROR                                     :text ="AUDCLNT_E_BUFFER_ERROR"; break;
+       case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED          :text ="AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; break;
+       case AUDCLNT_E_INVALID_DEVICE_PERIOD            :text ="AUDCLNT_E_INVALID_DEVICE_PERIOD"; break;
+
+       case AUDCLNT_S_BUFFER_EMPTY                 :text ="AUDCLNT_S_BUFFER_EMPTY"; break;
+       case AUDCLNT_S_THREAD_ALREADY_REGISTERED    :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
+       case AUDCLNT_S_POSITION_STALLED                         :text ="AUDCLNT_S_POSITION_STALLED"; break;
+
+       // other windows common errors:
+       case CO_E_NOTINITIALIZED                    :text ="CO_E_NOTINITIALIZED: you must call CoInitialize() before Pa_OpenStream()"; break;
+
+       default:
+               text = "UNKNOWN ERROR";
+    }
+       PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", res, text, func, file, line));
+       PA_SKELETON_SET_LAST_HOST_ERROR(res, text);
+       return res;
+}
+
+// ------------------------------------------------------------------------------------------
+#define LogPaError(PAERR) __LogPaError(PAERR, __FUNCTION__, __FILE__, __LINE__)
+static PaError __LogPaError(PaError err, const char *func, const char *file, int line)
+{
+       if (err == paNoError)
+               return err;
+       PRINT(("WASAPI ERROR PAERROR: %i : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", err, Pa_GetErrorText(err), func, file, line));
+       return err;
+}
+
+// ------------------------------------------------------------------------------------------
+/*! \class ThreadSleepScheduler
+           Allows to emulate thread sleep of less than 1 millisecond under Windows. Scheduler
+                  calculates number of times the thread must run untill next sleep of 1 millisecond.
+                  It does not make thread sleeping for real number of microseconds but rather controls
+                  how many of imaginary microseconds the thread task can allow thread to sleep.
+*/
+typedef struct ThreadIdleScheduler
+{
+       UINT32 m_idle_microseconds; //!< number of microseconds to sleep
+       UINT32 m_next_sleep;        //!< next sleep round
+       UINT32 m_i;                                     //!< current round iterator position
+       UINT32 m_resolution;            //!< resolution in number of milliseconds
+}
+ThreadIdleScheduler;
+//! Setup scheduler.
+static void ThreadIdleScheduler_Setup(ThreadIdleScheduler *sched, UINT32 resolution, UINT32 microseconds)
+{
+       assert(microseconds != 0);
+       assert(resolution != 0);
+       assert((resolution * 1000) >= microseconds);
+
+       memset(sched, 0, sizeof(*sched));
+
+       sched->m_idle_microseconds = microseconds;
+       sched->m_resolution        = resolution;
+       sched->m_next_sleep        = (resolution * 1000) / microseconds;
+}
+//! Iterate and check if can sleep.
+static UINT32 ThreadIdleScheduler_NextSleep(ThreadIdleScheduler *sched)
+{
+       // advance and check if thread can sleep
+       if (++ sched->m_i == sched->m_next_sleep)
+       {
+               sched->m_i = 0;
+               return sched->m_resolution;
+       }
+       return 0;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static double nano100ToMillis(REFERENCE_TIME ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return ((double)ref)*0.0001;
+}*/
+
+// ------------------------------------------------------------------------------------------
+static double nano100ToSeconds(REFERENCE_TIME ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return ((double)ref)*0.0000001;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static REFERENCE_TIME MillisTonano100(double ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return (REFERENCE_TIME)(ref/0.0001);
+}*/
+
+// ------------------------------------------------------------------------------------------
+static REFERENCE_TIME SecondsTonano100(double ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return (REFERENCE_TIME)(ref/0.0000001);
+}
+
+// ------------------------------------------------------------------------------------------
+// Makes Hns period from frames and sample rate
+static REFERENCE_TIME MakeHnsPeriod(UINT32 nFrames, DWORD nSamplesPerSec)
+{
+       return (REFERENCE_TIME)((10000.0 * 1000 / nSamplesPerSec * nFrames) + 0.5);
+}
+
+// ------------------------------------------------------------------------------------------
+// Converts PaSampleFormat to bits per sample value
+static WORD PaSampleFormatToBitsPerSample(PaSampleFormat format_id)
+{
+       switch (format_id & ~paNonInterleaved)
+       {
+               case paFloat32:
+               case paInt32: return 32;
+               case paInt24: return 24;
+               case paInt16: return 16;
+               case paInt8:
+               case paUInt8: return 8;
+       }
+       return 0;
+}
+
+// ------------------------------------------------------------------------------------------
+// Converts PaSampleFormat to bits per sample value
+/*static WORD PaSampleFormatToBytesPerSample(PaSampleFormat format_id)
+{
+       return PaSampleFormatToBitsPerSample(format_id) >> 3; // 'bits/8'
+}*/
+
+// ------------------------------------------------------------------------------------------
+// Converts Hns period into number of frames
+static UINT32 MakeFramesFromHns(REFERENCE_TIME hnsPeriod, UINT32 nSamplesPerSec)
+{
+    UINT32 nFrames = (UINT32)( // frames =
+        1.0 * hnsPeriod *              // hns *
+        nSamplesPerSec /               // (frames / s) /
+        1000 /                                 // (ms / s) /
+        10000                                  // (hns / s) /
+        + 0.5                                  // rounding
+    );
+       return nFrames;
+}
+
+// Aligning function type
+typedef UINT32 (*ALIGN_FUNC) (UINT32 v, UINT32 align);
+
+// ------------------------------------------------------------------------------------------
+// Aligns 'v' backwards
+static UINT32 ALIGN_BWD(UINT32 v, UINT32 align)
+{
+       return ((v - (align ? v % align : 0)));
+}
+
+// ------------------------------------------------------------------------------------------
+// Aligns 'v' forward
+static UINT32 ALIGN_FWD(UINT32 v, UINT32 align)
+{
+       UINT32 remainder = (align ? (v % align) : 0);
+       if (remainder == 0)
+               return v;
+       return v + (align - remainder);
+}
+
+// ------------------------------------------------------------------------------------------
+// Get next value power of 2
+UINT32 ALIGN_NEXT_POW2(UINT32 v)
+{
+       UINT32 v2 = 1;
+       while (v > (v2 <<= 1)) { }
+       v = v2;
+       return v;
+}
+
+// ------------------------------------------------------------------------------------------
+// Aligns WASAPI buffer to 128 byte packet boundary. HD Audio will fail to play if buffer
+// is misaligned. This problem was solved in Windows 7 were AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
+// is thrown although we must align for Vista anyway.
+static UINT32 AlignFramesPerBuffer(UINT32 nFrames, UINT32 nSamplesPerSec, UINT32 nBlockAlign,
+                                                                  ALIGN_FUNC pAlignFunc)
+{
+#define HDA_PACKET_SIZE (128)
+
+       long frame_bytes = nFrames * nBlockAlign;
+       long packets;
+       (void)nSamplesPerSec;
+
+       // align to packet size
+       frame_bytes  = pAlignFunc(frame_bytes, HDA_PACKET_SIZE); // use ALIGN_FWD if bigger but safer period is more desired
+
+       // atlest 1 frame must be available
+       if (frame_bytes < HDA_PACKET_SIZE)
+               frame_bytes = HDA_PACKET_SIZE;
+
+       nFrames      = frame_bytes / nBlockAlign;
+       packets      = frame_bytes / HDA_PACKET_SIZE;
+
+       frame_bytes = packets * HDA_PACKET_SIZE;
+       nFrames     = frame_bytes / nBlockAlign;
+
+       return nFrames;
+
+#undef HDA_PACKET_SIZE
+}
+
+// ------------------------------------------------------------------------------------------
+static UINT32 GetFramesSleepTime(UINT32 nFrames, UINT32 nSamplesPerSec)
+{
+       REFERENCE_TIME nDuration;
+       if (nSamplesPerSec == 0)
+               return 0;
+#define REFTIMES_PER_SEC  10000000
+#define REFTIMES_PER_MILLISEC  10000
+       // Calculate the actual duration of the allocated buffer.
+       nDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * nFrames / nSamplesPerSec);
+       return (UINT32)(nDuration/REFTIMES_PER_MILLISEC/2);
+}
+
+// ------------------------------------------------------------------------------------------
+static UINT32 GetFramesSleepTimeMicroseconds(UINT32 nFrames, UINT32 nSamplesPerSec)
+{
+       REFERENCE_TIME nDuration;
+       if (nSamplesPerSec == 0)
+               return 0;
+#define REFTIMES_PER_SEC  10000000
+#define REFTIMES_PER_MILLISEC  10000
+       // Calculate the actual duration of the allocated buffer.
+       nDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * nFrames / nSamplesPerSec);
+       return (UINT32)(nDuration/10/2);
+}
+
+// ------------------------------------------------------------------------------------------
+#ifndef PA_WINRT
+static BOOL SetupAVRT()
+{
+    hDInputDLL = LoadLibraryA("avrt.dll");
+    if (hDInputDLL == NULL)
+        return FALSE;
+
+    _GetProc(pAvRtCreateThreadOrderingGroup,  FAvRtCreateThreadOrderingGroup,  "AvRtCreateThreadOrderingGroup");
+    _GetProc(pAvRtDeleteThreadOrderingGroup,  FAvRtDeleteThreadOrderingGroup,  "AvRtDeleteThreadOrderingGroup");
+    _GetProc(pAvRtWaitOnThreadOrderingGroup,  FAvRtWaitOnThreadOrderingGroup,  "AvRtWaitOnThreadOrderingGroup");
+    _GetProc(pAvSetMmThreadCharacteristics,   FAvSetMmThreadCharacteristics,   "AvSetMmThreadCharacteristicsA");
+       _GetProc(pAvRevertMmThreadCharacteristics,FAvRevertMmThreadCharacteristics,"AvRevertMmThreadCharacteristics");
+    _GetProc(pAvSetMmThreadPriority,          FAvSetMmThreadPriority,          "AvSetMmThreadPriority");
+
+       return pAvRtCreateThreadOrderingGroup &&
+               pAvRtDeleteThreadOrderingGroup &&
+               pAvRtWaitOnThreadOrderingGroup &&
+               pAvSetMmThreadCharacteristics &&
+               pAvRevertMmThreadCharacteristics &&
+               pAvSetMmThreadPriority;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+static void CloseAVRT()
+{
+#ifndef PA_WINRT
+       if (hDInputDLL != NULL)
+               FreeLibrary(hDInputDLL);
+       hDInputDLL = NULL;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+static BOOL IsWow64()
+{
+#ifndef PA_WINRT
+
+       // http://msdn.microsoft.com/en-us/library/ms684139(VS.85).aspx
+
+       typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
+       LPFN_ISWOW64PROCESS fnIsWow64Process;
+
+    BOOL bIsWow64 = FALSE;
+
+    // IsWow64Process is not available on all supported versions of Windows.
+    // Use GetModuleHandle to get a handle to the DLL that contains the function
+    // and GetProcAddress to get a pointer to the function if available.
+
+    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
+        GetModuleHandleA("kernel32"), "IsWow64Process");
+
+    if (fnIsWow64Process == NULL)
+               return FALSE;
+
+    if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
+               return FALSE;
+
+    return bIsWow64;
+
+#else
+
+       return FALSE;
+
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+typedef enum EWindowsVersion
+{
+       WINDOWS_UNKNOWN = 0,
+       WINDOWS_VISTA_SERVER2008,
+       WINDOWS_7_SERVER2008R2,
+       WINDOWS_8_SERVER2012,
+       WINDOWS_8_1_SERVER2012R2,
+       WINDOWS_10_SERVER2016,
+       WINDOWS_FUTURE
+}
+EWindowsVersion;
+// Alternative way for checking Windows version (allows to check version on Windows 8.1 and up)
+#ifndef PA_WINRT
+static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
+{
+       typedef ULONGLONG (NTAPI *LPFN_VERSETCONDITIONMASK)(ULONGLONG ConditionMask, DWORD TypeMask, BYTE Condition);
+       typedef BOOL (WINAPI *LPFN_VERIFYVERSIONINFO)(LPOSVERSIONINFOEXA lpVersionInformation, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
+
+       LPFN_VERSETCONDITIONMASK fnVerSetConditionMask;
+       LPFN_VERIFYVERSIONINFO fnVerifyVersionInfo;
+       OSVERSIONINFOEXA osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
+       DWORDLONG dwlConditionMask;
+
+       fnVerSetConditionMask = (LPFN_VERSETCONDITIONMASK)GetProcAddress(GetModuleHandleA("kernel32"), "VerSetConditionMask");
+       fnVerifyVersionInfo = (LPFN_VERIFYVERSIONINFO)GetProcAddress(GetModuleHandleA("kernel32"), "VerifyVersionInfoA");
+
+       if ((fnVerSetConditionMask == NULL) || (fnVerifyVersionInfo == NULL))
+               return FALSE;
+
+       dwlConditionMask = fnVerSetConditionMask(
+               fnVerSetConditionMask(
+                       fnVerSetConditionMask(
+                               0, VER_MAJORVERSION,     VER_GREATER_EQUAL),
+                                  VER_MINORVERSION,     VER_GREATER_EQUAL),
+                                  VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
+
+       osvi.dwMajorVersion    = wMajorVersion;
+       osvi.dwMinorVersion    = wMinorVersion;
+       osvi.wServicePackMajor = wServicePackMajor;
+
+       return (fnVerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE);
+}
+#endif
+// Get Windows version
+static EWindowsVersion GetWindowsVersion()
+{
+#ifndef PA_WINRT
+       static EWindowsVersion version = WINDOWS_UNKNOWN;
+
+       if (version == WINDOWS_UNKNOWN)
+       {
+               DWORD dwVersion = 0;
+               DWORD dwMajorVersion = 0;
+               DWORD dwMinorVersion = 0;
+               DWORD dwBuild = 0;
+
+               typedef DWORD (WINAPI *LPFN_GETVERSION)(VOID);
+               LPFN_GETVERSION fnGetVersion;
+
+               fnGetVersion = (LPFN_GETVERSION)GetProcAddress(GetModuleHandleA("kernel32"), "GetVersion");
+               if (fnGetVersion != NULL)
+               {
+                       PRINT(("WASAPI: getting Windows version with GetVersion()\n"));
+
+                       dwVersion = fnGetVersion();
+
+                       // Get the Windows version
+                       dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
+                       dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
+
+                       // Get the build number
+                       if (dwVersion < 0x80000000)
+                               dwBuild = (DWORD)(HIWORD(dwVersion));
+
+                       switch (dwMajorVersion)
+                       {
+                       case 0:
+                       case 1:
+                       case 2:
+                       case 3:
+                       case 4:
+                       case 5:
+                               break; // skip lower
+                       case 6:
+                               switch (dwMinorVersion)
+                               {
+                               case 0:  version = WINDOWS_VISTA_SERVER2008;    break;
+                               case 1:  version = WINDOWS_7_SERVER2008R2;              break;
+                               case 2:  version = WINDOWS_8_SERVER2012;                break;
+                               case 3:  version = WINDOWS_8_1_SERVER2012R2;    break;
+                               default: version = WINDOWS_FUTURE;                              break;
+                               }
+                               break;
+                       case 10:
+                               switch (dwMinorVersion)
+                               {
+                               case 0:  version = WINDOWS_10_SERVER2016;               break;
+                               default: version = WINDOWS_FUTURE;                              break;
+                               }
+                               break;
+                       default:
+                               version = WINDOWS_FUTURE;
+                               break;
+                       }
+               }
+               else
+               {
+                       PRINT(("WASAPI: getting Windows version with VerifyVersionInfo()\n"));
+
+                       if (IsWindowsVersionOrGreater(10, 0, 0))
+                               version = WINDOWS_10_SERVER2016;
+                       else
+                       if (IsWindowsVersionOrGreater(6, 3, 0))
+                               version = WINDOWS_8_1_SERVER2012R2;
+                       else
+                       if (IsWindowsVersionOrGreater(6, 2, 0))
+                               version = WINDOWS_8_SERVER2012;
+                       else
+                       if (IsWindowsVersionOrGreater(6, 1, 0))
+                               version = WINDOWS_7_SERVER2008R2;
+                       else
+                       if (IsWindowsVersionOrGreater(6, 0, 0))
+                               version = WINDOWS_VISTA_SERVER2008;
+                       else
+                               version = WINDOWS_FUTURE;
+               }
+
+               PRINT(("WASAPI: Windows version = %d\n", version));
+       }
+
+       return version;
+#else
+       return WINDOWS_8_SERVER2012;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+static BOOL UseWOW64Workaround()
+{
+       // note: WOW64 bug is common to Windows Vista x64, thus we fall back to safe Poll-driven
+       //       method. Windows 7 x64 seems has WOW64 bug fixed.
+
+       return (IsWow64() && (GetWindowsVersion() == WINDOWS_VISTA_SERVER2008));
+}
+
+// ------------------------------------------------------------------------------------------
+static UINT32 GetAudioClientVersion()
+{
+       if (GetWindowsVersion() >= WINDOWS_10_SERVER2016)
+               return 3;
+       else
+       if (GetWindowsVersion() >= WINDOWS_8_SERVER2012)
+               return 2;
+
+       return 1;
+}
+
+// ------------------------------------------------------------------------------------------
+static const IID *GetAudioClientIID()
+{
+       static const IID *cli_iid = NULL;
+       if (cli_iid == NULL)
+       {
+               UINT32 cli_version = GetAudioClientVersion();
+               if (cli_version <= 1)
+               {
+                       cli_iid = &pa_IID_IAudioClient;
+               }
+               else
+               {
+                       switch (cli_version)
+                       {
+                       case 3:  cli_iid = &pa_IID_IAudioClient2; cli_version = 2; break; // use IAudioClient2 for Windows 10+ until IAudioClient3 functions are required
+                       default: cli_iid = &pa_IID_IAudioClient2; cli_version = 2; break;
+                       }
+               }
+
+               PRINT(("WASAPI: IAudioClient version = %d\n", cli_version));
+       }
+
+       return cli_iid;
+}
+
+// ------------------------------------------------------------------------------------------
+typedef enum EMixerDir { MIX_DIR__1TO2, MIX_DIR__2TO1, MIX_DIR__2TO1_L } EMixerDir;
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(TYPE)\
+       TYPE * __restrict to   = __to;\
+       TYPE * __restrict from = __from;\
+       TYPE * __restrict end  = from + count;\
+       while (from != end)\
+       {\
+               *to ++ = *from;\
+               *to ++ = *from;\
+               ++ from;\
+       }
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(TYPE)\
+       TYPE * __restrict to   = (TYPE *)__to;\
+       TYPE * __restrict from = (TYPE *)__from;\
+       TYPE * __restrict end  = to + count;\
+       while (to != end)\
+       {\
+               *to ++ = (TYPE)((float)(from[0] + from[1]) * 0.5f);\
+               from += 2;\
+       }
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(TYPE)\
+       TYPE * __restrict to   = (TYPE *)__to;\
+       TYPE * __restrict from = (TYPE *)__from;\
+       TYPE * __restrict end  = to + count;\
+       while (to != end)\
+       {\
+               *to ++ = (TYPE)(((INT32)from[0] + (INT32)from[1]) >> 1);\
+               from += 2;\
+       }
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(TYPE)\
+       TYPE * __restrict to   = (TYPE *)__to;\
+       TYPE * __restrict from = (TYPE *)__from;\
+       TYPE * __restrict end  = to + count;\
+       while (to != end)\
+       {\
+               *to ++ = (TYPE)(((INT64)from[0] + (INT64)from[1]) >> 1);\
+               from += 2;\
+       }
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(TYPE)\
+       TYPE * __restrict to   = (TYPE *)__to;\
+       TYPE * __restrict from = (TYPE *)__from;\
+       TYPE * __restrict end  = to + count;\
+       while (to != end)\
+       {\
+               *to ++ = from[0];\
+               from += 2;\
+       }
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_1TO2_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(BYTE); }
+static void _MixMonoToStereo_1TO2_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(short); }
+static void _MixMonoToStereo_1TO2_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_1TO2_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); }
+static void _MixMonoToStereo_1TO2_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(float); }
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_2TO1_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(BYTE); }
+static void _MixMonoToStereo_2TO1_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(short); }
+static void _MixMonoToStereo_2TO1_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_2TO1_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(int); }
+static void _MixMonoToStereo_2TO1_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(float); }
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_2TO1_8_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(BYTE); }
+static void _MixMonoToStereo_2TO1_16_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(short); }
+static void _MixMonoToStereo_2TO1_24_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_2TO1_32_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); }
+static void _MixMonoToStereo_2TO1_32f_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(float); }
+
+// ------------------------------------------------------------------------------------------
+static MixMonoToStereoF _GetMonoToStereoMixer(PaSampleFormat format, EMixerDir dir)
+{
+       switch (dir)
+       {
+       case MIX_DIR__1TO2:
+               switch (format & ~paNonInterleaved)
+               {
+               case paUInt8:   return _MixMonoToStereo_1TO2_8;
+               case paInt16:   return _MixMonoToStereo_1TO2_16;
+               case paInt24:   return _MixMonoToStereo_1TO2_24;
+               case paInt32:   return _MixMonoToStereo_1TO2_32;
+               case paFloat32: return _MixMonoToStereo_1TO2_32f;
+               }
+               break;
+
+       case MIX_DIR__2TO1:
+               switch (format & ~paNonInterleaved)
+               {
+               case paUInt8:   return _MixMonoToStereo_2TO1_8;
+               case paInt16:   return _MixMonoToStereo_2TO1_16;
+               case paInt24:   return _MixMonoToStereo_2TO1_24;
+               case paInt32:   return _MixMonoToStereo_2TO1_32;
+               case paFloat32: return _MixMonoToStereo_2TO1_32f;
+               }
+               break;
+
+       case MIX_DIR__2TO1_L:
+               switch (format & ~paNonInterleaved)
+               {
+               case paUInt8:   return _MixMonoToStereo_2TO1_8_L;
+               case paInt16:   return _MixMonoToStereo_2TO1_16_L;
+               case paInt24:   return _MixMonoToStereo_2TO1_24_L;
+               case paInt32:   return _MixMonoToStereo_2TO1_32_L;
+               case paFloat32: return _MixMonoToStereo_2TO1_32f_L;
+               }
+               break;
+       }
+
+       return NULL;
+}
+
+// ------------------------------------------------------------------------------------------
+#ifdef PA_WINRT
+typedef struct PaActivateAudioInterfaceCompletionHandler
+{
+       IActivateAudioInterfaceCompletionHandler parent;
+       volatile LONG refs;
+       volatile LONG done;
+       struct
+       {
+               const IID *iid;
+               void **obj;
+       }
+       in;
+       struct
+       {
+               HRESULT hr;
+       }
+       out;
+}
+PaActivateAudioInterfaceCompletionHandler;
+
+static HRESULT (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_QueryInterface)( 
+    IActivateAudioInterfaceCompletionHandler *This, REFIID riid, void **ppvObject)
+{
+       PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
+
+       // From MSDN:
+       // "The IAgileObject interface is a marker interface that indicates that an object 
+       //  is free threaded and can be called from any apartment."
+       if (IsEqualIID(riid, &IID_IUnknown) || 
+               IsEqualIID(riid, &IID_IAgileObject))
+       {
+               IActivateAudioInterfaceCompletionHandler_AddRef((IActivateAudioInterfaceCompletionHandler *)handler);
+               (*ppvObject) = handler;
+               return S_OK;
+       }
+
+       return E_NOINTERFACE;
+}
+        
+static ULONG (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_AddRef)( 
+    IActivateAudioInterfaceCompletionHandler *This)
+{
+       PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
+
+       return InterlockedIncrement(&handler->refs);
+}
+        
+static ULONG (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_Release)( 
+    IActivateAudioInterfaceCompletionHandler *This)
+{
+       PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
+       ULONG refs;
+
+       if ((refs = InterlockedDecrement(&handler->refs)) == 0)
+       {
+               PaUtil_FreeMemory(handler->parent.lpVtbl);
+               PaUtil_FreeMemory(handler);
+       }
+
+       return refs;
+}
+        
+static HRESULT (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_ActivateCompleted)( 
+    IActivateAudioInterfaceCompletionHandler *This, IActivateAudioInterfaceAsyncOperation *activateOperation)
+{
+       PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
+
+    HRESULT hr = S_OK;
+    HRESULT hrActivateResult = S_OK;
+    IUnknown *punkAudioInterface = NULL;
+    // Check for a successful activation result
+    hr = IActivateAudioInterfaceAsyncOperation_GetActivateResult(activateOperation, &hrActivateResult, &punkAudioInterface);
+    if (SUCCEEDED(hr) && SUCCEEDED(hrActivateResult))
+    {
+        // Get pointer to the requested audio interface
+        IUnknown_QueryInterface(punkAudioInterface, handler->in.iid, handler->in.obj);
+        if ((*handler->in.obj) == NULL)
+            hrActivateResult = E_FAIL;
+       }
+       SAFE_RELEASE(punkAudioInterface);
+
+       if (SUCCEEDED(hr))
+               handler->out.hr = hrActivateResult;
+       else
+               handler->out.hr = hr;
+       
+       // Got client object, stop busy waiting in ActivateAudioInterface
+       InterlockedExchange(&handler->done, TRUE);
+
+       return hr;
+}
+
+static IActivateAudioInterfaceCompletionHandler *CreateActivateAudioInterfaceCompletionHandler(const IID *iid, void **obj)
+{
+       PaActivateAudioInterfaceCompletionHandler *handler = PaUtil_AllocateMemory(sizeof(PaActivateAudioInterfaceCompletionHandler));
+       ZeroMemory(handler, sizeof(*handler));
+       handler->parent.lpVtbl = PaUtil_AllocateMemory(sizeof(*handler->parent.lpVtbl));
+       handler->parent.lpVtbl->QueryInterface    = &PaActivateAudioInterfaceCompletionHandler_QueryInterface;
+       handler->parent.lpVtbl->AddRef            = &PaActivateAudioInterfaceCompletionHandler_AddRef;
+       handler->parent.lpVtbl->Release           = &PaActivateAudioInterfaceCompletionHandler_Release;
+       handler->parent.lpVtbl->ActivateCompleted = &PaActivateAudioInterfaceCompletionHandler_ActivateCompleted;
+       handler->refs = 1;
+       handler->in.iid = iid;
+       handler->in.obj = obj;
+       return (IActivateAudioInterfaceCompletionHandler *)handler;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+#ifdef PA_WINRT
+static HRESULT ActivateAudioInterface_WINRT(const PaWasapiDeviceInfo *deviceInfo, const IID *iid, void **obj)
+{
+#define PA_WASAPI_DEVICE_PATH_LEN 64
+       
+       PaError result = paNoError;
+       HRESULT hr = S_OK;
+       IActivateAudioInterfaceAsyncOperation *asyncOp = NULL;
+       IActivateAudioInterfaceCompletionHandler *handler = CreateActivateAudioInterfaceCompletionHandler(iid, obj);
+       PaActivateAudioInterfaceCompletionHandler *handlerImpl = (PaActivateAudioInterfaceCompletionHandler *)handler;
+       OLECHAR devicePath[PA_WASAPI_DEVICE_PATH_LEN] = { 0 };
+
+       // Get device path in form L"{DEVICE_GUID}"
+       switch (deviceInfo->flow)
+       {
+       case eRender:
+               StringFromGUID2(&DEVINTERFACE_AUDIO_RENDER, devicePath, PA_WASAPI_DEVICE_PATH_LEN - 1);
+               break;
+       case eCapture:
+               StringFromGUID2(&DEVINTERFACE_AUDIO_CAPTURE, devicePath, PA_WASAPI_DEVICE_PATH_LEN - 1);
+               break;
+       default:
+               return S_FALSE;
+       }       
+
+       // Async operation will call back to IActivateAudioInterfaceCompletionHandler::ActivateCompleted 
+       // which must be an agile interface implementation
+    hr = ActivateAudioInterfaceAsync(devicePath, iid, NULL, handler, &asyncOp);
+    IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+       // Wait in busy loop for async operation to complete
+       // Use Interlocked API here to ensure that ->done variable is read every time through the loop
+       while (SUCCEEDED(hr) && !InterlockedOr(&handlerImpl->done, 0))
+       {
+               Sleep(1);
+       }
+
+       hr = handlerImpl->out.hr;
+
+error:
+
+       SAFE_RELEASE(asyncOp);
+       SAFE_RELEASE(handler);
+
+    return hr;
+       
+#undef PA_WASAPI_DEVICE_PATH_LEN
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+static HRESULT ActivateAudioInterface(const PaWasapiDeviceInfo *deviceInfo, IAudioClient **client)
+{
+#ifndef PA_WINRT
+       return IMMDevice_Activate(deviceInfo->device, GetAudioClientIID(), CLSCTX_ALL, NULL, (void **)client);
+#else
+       return ActivateAudioInterface_WINRT(deviceInfo, GetAudioClientIID(), (void **)client);
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+#ifdef PA_WINRT
+static DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds, BOOL bAlertable)
+{
+       SetEvent(hObjectToSignal);
+       return WaitForSingleObjectEx(hObjectToWaitOn, dwMilliseconds, bAlertable);
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaWasapiHostApiRepresentation *paWasapi;
+    PaDeviceInfo *deviceInfoArray;
+    HRESULT hr = S_OK;
+       UINT i;
+#ifndef PA_WINRT
+    IMMDeviceCollection* pEndPoints = NULL;
+#else
+       WAVEFORMATEX *mixFormat;
+#endif
+
+#ifndef PA_WINRT
+    if (!SetupAVRT())
+       {
+        PRINT(("WASAPI: No AVRT! (not VISTA?)"));
+        return paNoError;
+    }
+#endif
+
+    paWasapi = (PaWasapiHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaWasapiHostApiRepresentation) );
+    if (paWasapi == NULL)
+       {
+        result = paInsufficientMemory;
+        goto error;
+    }
+       
+    memset( paWasapi, 0, sizeof(PaWasapiHostApiRepresentation) ); /* ensure all fields are zeroed. especially paWasapi->allocations */
+
+    result = PaWinUtil_CoInitialize( paWASAPI, &paWasapi->comInitializationResult );
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    paWasapi->allocations = PaUtil_CreateAllocationGroup();
+    if (paWasapi->allocations == NULL)
+       {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi                             = &paWasapi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion              = 1;
+    (*hostApi)->info.type                               = paWASAPI;
+    (*hostApi)->info.name                               = "Windows WASAPI";
+    (*hostApi)->info.deviceCount                = 0;
+    (*hostApi)->info.defaultInputDevice         = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+
+#ifndef PA_WINRT
+    paWasapi->enumerator = NULL;
+    hr = CoCreateInstance(&pa_CLSID_IMMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER,
+             &pa_IID_IMMDeviceEnumerator, (void **)&paWasapi->enumerator);
+    
+       // We need to set the result to a value otherwise we will return paNoError
+       // [IF_FAILED_JUMP(hResult, error);]
+       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+    // getting default device ids in the eMultimedia "role"
+    {
+        {
+            IMMDevice *defaultRenderer = NULL;
+            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eRender, eMultimedia, &defaultRenderer);
+            if (hr != S_OK)
+                       {
+                               if (hr != E_NOTFOUND) {
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       // [IF_FAILED_JUMP(hResult, error);]
+                                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                               }
+                       }
+                       else
+                       {
+                               WCHAR *pszDeviceId = NULL;
+                               hr = IMMDevice_GetId(defaultRenderer, &pszDeviceId);
+                               // We need to set the result to a value otherwise we will return paNoError
+                               // [IF_FAILED_JUMP(hResult, error);]
+                               IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                               wcsncpy(paWasapi->defaultRenderer, pszDeviceId, MAX_STR_LEN-1);
+                               CoTaskMemFree(pszDeviceId);
+                               IMMDevice_Release(defaultRenderer);
+                       }
+        }
+
+        {
+            IMMDevice *defaultCapturer = NULL;
+            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eCapture, eMultimedia, &defaultCapturer);
+            if (hr != S_OK)
+                       {
+                               if (hr != E_NOTFOUND) {
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       // [IF_FAILED_JUMP(hResult, error);]
+                                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                               }
+                       }
+                       else
+                       {
+                               WCHAR *pszDeviceId = NULL;
+                               hr = IMMDevice_GetId(defaultCapturer, &pszDeviceId);
+                               // We need to set the result to a value otherwise we will return paNoError
+                               // [IF_FAILED_JUMP(hResult, error);]
+                               IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                               wcsncpy(paWasapi->defaultCapturer, pszDeviceId, MAX_STR_LEN-1);
+                               CoTaskMemFree(pszDeviceId);
+                               IMMDevice_Release(defaultCapturer);
+                       }
+        }
+    }
+
+    hr = IMMDeviceEnumerator_EnumAudioEndpoints(paWasapi->enumerator, eAll, DEVICE_STATE_ACTIVE, &pEndPoints);
+       // We need to set the result to a value otherwise we will return paNoError
+       // [IF_FAILED_JUMP(hResult, error);]
+       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+    hr = IMMDeviceCollection_GetCount(pEndPoints, &paWasapi->deviceCount);
+       // We need to set the result to a value otherwise we will return paNoError
+       // [IF_FAILED_JUMP(hResult, error);]
+       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+#else
+       paWasapi->deviceCount = 2;
+#endif
+
+    paWasapi->devInfo = (PaWasapiDeviceInfo *)PaUtil_AllocateMemory(sizeof(PaWasapiDeviceInfo) * paWasapi->deviceCount);
+    if (paWasapi->devInfo == NULL)
+       {
+        result = paInsufficientMemory;
+        goto error;
+    }
+       for (i = 0; i < paWasapi->deviceCount; ++i)
+               memset(&paWasapi->devInfo[i], 0, sizeof(PaWasapiDeviceInfo));
+
+    if (paWasapi->deviceCount > 0)
+    {
+        (*hostApi)->deviceInfos = (PaDeviceInfo **)PaUtil_GroupAllocateMemory(
+                paWasapi->allocations, sizeof(PaDeviceInfo *) * paWasapi->deviceCount);
+        if ((*hostApi)->deviceInfos == NULL)
+               {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaDeviceInfo *)PaUtil_GroupAllocateMemory(
+                paWasapi->allocations, sizeof(PaDeviceInfo) * paWasapi->deviceCount);
+        if (deviceInfoArray == NULL)
+               {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for (i = 0; i < paWasapi->deviceCount; ++i)
+               {
+            PaDeviceInfo *deviceInfo  = &deviceInfoArray[i];
+            deviceInfo->structVersion = 2;
+            deviceInfo->hostApi       = hostApiIndex;
+
+                       PA_DEBUG(("WASAPI: device idx: %02d\n", i));
+                       PA_DEBUG(("WASAPI: ---------------\n"));
+
+               #ifndef PA_WINRT
+            hr = IMMDeviceCollection_Item(pEndPoints, i, &paWasapi->devInfo[i].device);
+                       // We need to set the result to a value otherwise we will return paNoError
+                       // [IF_FAILED_JUMP(hResult, error);]
+                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+            // getting ID
+            {
+                WCHAR *pszDeviceId = NULL;
+                hr = IMMDevice_GetId(paWasapi->devInfo[i].device, &pszDeviceId);
+                               // We need to set the result to a value otherwise we will return paNoError
+                               // [IF_FAILED_JUMP(hr, error);]
+                               IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                wcsncpy(paWasapi->devInfo[i].szDeviceID, pszDeviceId, MAX_STR_LEN-1);
+                CoTaskMemFree(pszDeviceId);
+
+                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer) == 0)
+                               {// we found the default input!
+                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+                }
+                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer) == 0)
+                               {// we found the default output!
+                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+                }
+            }
+
+            hr = IMMDevice_GetState(paWasapi->devInfo[i].device, &paWasapi->devInfo[i].state);
+                       // We need to set the result to a value otherwise we will return paNoError
+                       // [IF_FAILED_JUMP(hResult, error);]
+                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+            if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE)
+                       {
+                PRINT(("WASAPI device: %d is not currently available (state:%d)\n", i, paWasapi->devInfo[i].state));
+            }
+
+            {
+                IPropertyStore *pProperty;
+                hr = IMMDevice_OpenPropertyStore(paWasapi->devInfo[i].device, STGM_READ, &pProperty);
+                               // We need to set the result to a value otherwise we will return paNoError
+                               // [IF_FAILED_JUMP(hResult, error);]
+                               IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+                // "Friendly" Name
+                {
+                                       char *deviceName;
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_Device_FriendlyName, &value);
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       // [IF_FAILED_JUMP(hResult, error);]
+                                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                    deviceInfo->name = NULL;
+                    deviceName = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, MAX_STR_LEN + 1);
+                    if (deviceName == NULL)
+                                       {
+                        result = paInsufficientMemory;
+                        goto error;
+                    }
+                                       if (value.pwszVal)
+                                               WideCharToMultiByte(CP_UTF8, 0, value.pwszVal, (int)wcslen(value.pwszVal), deviceName, MAX_STR_LEN - 1, 0, 0);
+                                       else
+                                               _snprintf(deviceName, MAX_STR_LEN - 1, "baddev%d", i);
+                    deviceInfo->name = deviceName;
+                    PropVariantClear(&value);
+                                       PA_DEBUG(("WASAPI:%d| name[%s]\n", i, deviceInfo->name));
+                }
+
+                // Default format
+                {
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEngine_DeviceFormat, &value);
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       // [IF_FAILED_JUMP(hResult, error);]
+                                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                                       memcpy(&paWasapi->devInfo[i].DefaultFormat, value.blob.pBlobData, min(sizeof(paWasapi->devInfo[i].DefaultFormat), value.blob.cbSize));
+                    // cleanup
+                    PropVariantClear(&value);
+                }
+
+                // Formfactor
+                {
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEndpoint_FormFactor, &value);
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       // [IF_FAILED_JUMP(hResult, error);]
+                                       IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                                       // set
+                                       #if defined(DUMMYUNIONNAME) && defined(NONAMELESSUNION)
+                                               // avoid breaking strict-aliasing rules in such line: (EndpointFormFactor)(*((UINT *)(((WORD *)&value.wReserved3)+1)));
+                                               UINT v;
+                                               memcpy(&v, (((WORD *)&value.wReserved3)+1), sizeof(v));
+                                               paWasapi->devInfo[i].formFactor = (EndpointFormFactor)v;
+                                       #else
+                                               paWasapi->devInfo[i].formFactor = (EndpointFormFactor)value.uintVal;
+                                       #endif
+                                       PA_DEBUG(("WASAPI:%d| form-factor[%d]\n", i, paWasapi->devInfo[i].formFactor));
+                    // cleanup
+                    PropVariantClear(&value);
+                }
+
+                               SAFE_RELEASE(pProperty);
+            }
+                       
+            // Endpoint data
+            {
+                IMMEndpoint *endpoint = NULL;
+                hr = IMMDevice_QueryInterface(paWasapi->devInfo[i].device, &pa_IID_IMMEndpoint, (void **)&endpoint);
+                if (SUCCEEDED(hr))
+                               {
+                    hr = IMMEndpoint_GetDataFlow(endpoint, &paWasapi->devInfo[i].flow);
+                    SAFE_RELEASE(endpoint);
+                }
+            }
+               #endif
+
+            // Getting a temporary IAudioClient for more fields
+            // we make sure NOT to call Initialize yet!
+            {
+                       #ifdef PA_WINRT
+                               // Set flow as ActivateAudioInterface depends on it and selects corresponding 
+                               // direction for the Audio Client
+                               paWasapi->devInfo[i].flow = (i == 0 ? eRender : eCapture);
+                       #endif
+
+                               // Create temp Audio Client instance to query additional details
+                IAudioClient *tmpClient = NULL;
+                hr = ActivateAudioInterface(&paWasapi->devInfo[i], &tmpClient);
+                               // We need to set the result to a value otherwise we will return paNoError
+                               // [IF_FAILED_JUMP(hResult, error);]
+                               IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+                               // Get latency
+                hr = IAudioClient_GetDevicePeriod(tmpClient,
+                    &paWasapi->devInfo[i].DefaultDevicePeriod,
+                    &paWasapi->devInfo[i].MinimumDevicePeriod);
+                               if (FAILED(hr))
+                               {
+                                       PA_DEBUG(("WASAPI:%d| failed getting min/default periods by IAudioClient::GetDevicePeriod() with error[%08X], will use 30000/100000 hns\n", i, (UINT32)hr));
+
+                                       // assign WASAPI common values
+                                       paWasapi->devInfo[i].DefaultDevicePeriod = 100000;
+                                       paWasapi->devInfo[i].MinimumDevicePeriod = 30000;
+
+                                       // ignore error, let continue further without failing with paInternalError
+                                       hr = S_OK;
+                               }
+                               
+                       #ifdef PA_WINRT
+                               // Get mix format which will treat as default device format
+                               hr = IAudioClient_GetMixFormat(tmpClient, &mixFormat);
+                               if (SUCCEEDED(hr))
+                               {
+                                       // Default device
+                                       if (i == 0)
+                                               (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+                                       else
+                                               (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+
+                                       // State
+                                       paWasapi->devInfo[i].state = DEVICE_STATE_ACTIVE;
+
+                                       // Default format
+                                       memcpy(&paWasapi->devInfo[i].DefaultFormat, mixFormat, min(sizeof(paWasapi->devInfo[i].DefaultFormat), sizeof(*mixFormat)));
+                                       CoTaskMemFree(mixFormat);
+
+                                       // Form-factor
+                                       paWasapi->devInfo[i].formFactor = UnknownFormFactor;
+
+                                       // Name
+                    deviceInfo->name = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, MAX_STR_LEN + 1);
+                    if (deviceInfo->name == NULL)
+                                       {
+                                               SAFE_RELEASE(tmpClient);
+                        result = paInsufficientMemory;
+                        goto error;
+                    }
+                                       _snprintf((char *)deviceInfo->name, MAX_STR_LEN - 1, "WASAPI_%s:%d", (i == 0 ? "Output" : "Input"), i);
+                                       PA_DEBUG(("WASAPI:%d| name[%s]\n", i, deviceInfo->name));
+                               }
+                       #endif
+
+                               // Release tmp client
+                               SAFE_RELEASE(tmpClient);
+
+                               if (hr != S_OK)
+                               {
+                                       //davidv: this happened with my hardware, previously for that same device in DirectSound:
+                                       //Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f}
+                                       //so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat
+                                       LogHostError(hr);
+                                       // We need to set the result to a value otherwise we will return paNoError
+                                       result = paInternalError;
+                                       goto error;
+                               }
+            }
+                       
+            // we can now fill in portaudio device data
+            deviceInfo->maxInputChannels  = 0;
+            deviceInfo->maxOutputChannels = 0;
+                       deviceInfo->defaultSampleRate = paWasapi->devInfo[i].DefaultFormat.Format.nSamplesPerSec;
+            switch (paWasapi->devInfo[i].flow)
+                       {
+                       case eRender: {
+                deviceInfo->maxOutputChannels           = paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
+                deviceInfo->defaultHighOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
+                deviceInfo->defaultLowOutputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
+                               PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
+                                       deviceInfo->maxOutputChannels, (float)deviceInfo->defaultHighOutputLatency, (float)deviceInfo->defaultLowOutputLatency));
+                               break;}
+                       case eCapture: {
+                deviceInfo->maxInputChannels           = paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
+                deviceInfo->defaultHighInputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
+                deviceInfo->defaultLowInputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
+                               PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
+                                       deviceInfo->maxInputChannels, (float)deviceInfo->defaultHighInputLatency, (float)deviceInfo->defaultLowInputLatency));
+                               break; }
+            default:
+                PRINT(("WASAPI:%d| bad Data Flow!\n", i));
+                               // We need to set the result to a value otherwise we will return paNoError
+                               result = paInternalError;
+                //continue; // do not skip from list, allow to initialize
+                                break;
+            }
+
+            (*hostApi)->deviceInfos[i] = deviceInfo;
+            ++(*hostApi)->info.deviceCount;
+        }
+    }
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+
+       // findout if platform workaround is required
+       paWasapi->useWOW64Workaround = UseWOW64Workaround();
+
+#ifndef PA_WINRT
+    SAFE_RELEASE(pEndPoints);
+#endif
+
+       PRINT(("WASAPI: initialized ok\n"));
+
+    return paNoError;
+
+error:
+
+       PRINT(("WASAPI: failed %s error[%d|%s]\n", __FUNCTION__, result, Pa_GetErrorText(result)));
+
+#ifndef PA_WINRT
+    SAFE_RELEASE(pEndPoints);
+#endif
+
+       Terminate((PaUtilHostApiRepresentation *)paWasapi);
+
+       // Safety if error was not set so that we do not think initialize was a success
+       if (result == paNoError) {
+               result = paInternalError;
+       }
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static void Terminate( PaUtilHostApiRepresentation *hostApi )
+{
+       UINT i;
+    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+       if (paWasapi == NULL)
+               return;
+
+       // Release IMMDeviceEnumerator
+#ifndef PA_WINRT
+    SAFE_RELEASE(paWasapi->enumerator);
+#endif
+
+       // Release device info bound objects and device info itself
+    for (i = 0; i < paWasapi->deviceCount; ++i)
+       {
+        PaWasapiDeviceInfo *info = &paWasapi->devInfo[i];
+       #ifndef PA_WINRT
+        SAFE_RELEASE(info->device);
+       #else
+               (void)info;
+       #endif
+    }
+    PaUtil_FreeMemory(paWasapi->devInfo);
+
+    if (paWasapi->allocations)
+       {
+        PaUtil_FreeAllAllocations(paWasapi->allocations);
+        PaUtil_DestroyAllocationGroup(paWasapi->allocations);
+    }
+
+    PaWinUtil_CoUninitialize( paWASAPI, &paWasapi->comInitializationResult );
+
+    PaUtil_FreeMemory(paWasapi);
+
+       // Close AVRT
+       CloseAVRT();
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiHostApiRepresentation *_GetHostApi(PaError *_error)
+{
+       PaError error;
+
+       PaUtilHostApiRepresentation *pApi;
+       if ((error = PaUtil_GetHostApiRepresentation(&pApi, paWASAPI)) != paNoError)
+       {
+               if (_error != NULL)
+                       (*_error) = error;
+
+               return NULL;
+       }
+       return (PaWasapiHostApiRepresentation *)pApi;
+}
+
+// ------------------------------------------------------------------------------------------
+int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int nFormatSize, PaDeviceIndex nDevice )
+{
+       PaError ret;
+       PaWasapiHostApiRepresentation *paWasapi;
+       UINT32 size;
+       PaDeviceIndex index;
+
+       if (pFormat == NULL)
+               return paBadBufferPtr;
+       if (nFormatSize <= 0)
+               return paBufferTooSmall;
+
+       // Get API
+       paWasapi = _GetHostApi(&ret);
+       if (paWasapi == NULL)
+               return ret;
+
+       // Get device index
+       ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+       // Validate index
+       if ((UINT32)index >= paWasapi->deviceCount)
+               return paInvalidDevice;
+
+       size = min(nFormatSize, (UINT32)sizeof(paWasapi->devInfo[ index ].DefaultFormat));
+       memcpy(pFormat, &paWasapi->devInfo[ index ].DefaultFormat, size);
+
+       return size;
+}
+
+// ------------------------------------------------------------------------------------------
+int PaWasapi_GetDeviceRole( PaDeviceIndex nDevice )
+{
+       PaError ret;
+       PaDeviceIndex index;
+
+       // Get API
+       PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+       if (paWasapi == NULL)
+               return paNotInitialized;
+
+       // Get device index
+       ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+       // Validate index
+       if ((UINT32)index >= paWasapi->deviceCount)
+               return paInvalidDevice;
+
+       return paWasapi->devInfo[ index ].formFactor;
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *nInput, unsigned int *nOutput )
+{
+    PaWasapiStream *stream = (PaWasapiStream *)pStream;
+       if (stream == NULL)
+               return paBadStreamPtr;
+
+       if (nInput != NULL)
+               (*nInput) = stream->in.framesPerHostCallback;
+
+       if (nOutput != NULL)
+               (*nOutput) = stream->out.framesPerHostCallback;
+
+       return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static void LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in)
+{
+    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
+       switch (old->wFormatTag)
+       {
+       case WAVE_FORMAT_EXTENSIBLE: {
+
+               PRINT(("wFormatTag     =WAVE_FORMAT_EXTENSIBLE\n"));
+
+               if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+               {
+                       PRINT(("SubFormat      =KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n"));
+               }
+               else
+               if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
+               {
+                       PRINT(("SubFormat      =KSDATAFORMAT_SUBTYPE_PCM\n"));
+               }
+               else
+               {
+                       PRINT(("SubFormat      =CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n",
+                                                                               in->SubFormat.Data1,
+                                                                               in->SubFormat.Data2,
+                                                                               in->SubFormat.Data3,
+                                                                               (int)in->SubFormat.Data4[0],
+                                                                               (int)in->SubFormat.Data4[1],
+                                                                               (int)in->SubFormat.Data4[2],
+                                                                               (int)in->SubFormat.Data4[3],
+                                                                               (int)in->SubFormat.Data4[4],
+                                                                               (int)in->SubFormat.Data4[5],
+                                                                               (int)in->SubFormat.Data4[6],
+                                                                               (int)in->SubFormat.Data4[7]));
+               }
+               PRINT(("Samples.wValidBitsPerSample =%d\n",  in->Samples.wValidBitsPerSample));
+               PRINT(("dwChannelMask  =0x%X\n",in->dwChannelMask));
+
+               break; }
+
+       case WAVE_FORMAT_PCM:        PRINT(("wFormatTag     =WAVE_FORMAT_PCM\n")); break;
+       case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag     =WAVE_FORMAT_IEEE_FLOAT\n")); break;
+       default: 
+               PRINT(("wFormatTag     =UNKNOWN(%d)\n",old->wFormatTag)); break;
+       }
+
+       PRINT(("nChannels      =%d\n",old->nChannels));
+       PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec));
+       PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec));
+       PRINT(("nBlockAlign    =%d\n",old->nBlockAlign));
+       PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample));
+       PRINT(("cbSize         =%d\n",old->cbSize));
+}
+
+// ------------------------------------------------------------------------------------------
+static PaSampleFormat WaveToPaFormat(const WAVEFORMATEXTENSIBLE *in)
+{
+    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
+
+    switch (old->wFormatTag)
+       {
+    case WAVE_FORMAT_EXTENSIBLE: {
+        if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+               {
+            if (in->Samples.wValidBitsPerSample == 32)
+                return paFloat32;
+        }
+        else
+               if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
+               {
+            switch (old->wBitsPerSample)
+                       {
+                case 32: return paInt32;
+                case 24: return paInt24;
+                case  8: return paUInt8;
+                case 16: return paInt16;
+            }
+        }
+               break; }
+
+    case WAVE_FORMAT_IEEE_FLOAT:
+               return paFloat32;
+
+    case WAVE_FORMAT_PCM: {
+        switch (old->wBitsPerSample)
+               {
+            case 32: return paInt32;
+            case 24: return paInt24;
+            case  8: return paUInt8;
+            case 16: return paInt16;
+        }
+               break; }
+    }
+
+    return paCustomFormat;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError MakeWaveFormatFromParams(WAVEFORMATEXTENSIBLE *wavex, const PaStreamParameters *params,
+                                                                       double sampleRate)
+{
+       WORD bitsPerSample;
+       WAVEFORMATEX *old;
+       DWORD channelMask = 0;
+       PaWasapiStreamInfo *streamInfo = (PaWasapiStreamInfo *)params->hostApiSpecificStreamInfo;
+
+       // Get user assigned channel mask
+       if ((streamInfo != NULL) && (streamInfo->flags & paWinWasapiUseChannelMask))
+               channelMask = streamInfo->channelMask;
+
+       // Convert PaSampleFormat to bits per sample
+       if ((bitsPerSample = PaSampleFormatToBitsPerSample(params->sampleFormat)) == 0)
+               return paSampleFormatNotSupported;
+
+    memset(wavex, 0, sizeof(*wavex));
+
+    old                                         = (WAVEFORMATEX *)wavex;
+    old->nChannels       = (WORD)params->channelCount;
+    old->nSamplesPerSec  = (DWORD)sampleRate;
+       if ((old->wBitsPerSample = bitsPerSample) > 16)
+       {
+               old->wBitsPerSample = 32; // 20 or 24 bits must go in 32 bit containers (ints)
+       }
+    old->nBlockAlign     = (old->nChannels * (old->wBitsPerSample/8));
+    old->nAvgBytesPerSec = (old->nSamplesPerSec * old->nBlockAlign);
+
+    // WAVEFORMATEX
+    if ((params->channelCount <= 2) && ((bitsPerSample == 16) || (bitsPerSample == 8)))
+       {
+        old->cbSize            = 0;
+        old->wFormatTag        = WAVE_FORMAT_PCM;
+    }
+    // WAVEFORMATEXTENSIBLE
+    else
+       {
+        old->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+        old->cbSize            = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
+
+        if ((params->sampleFormat & ~paNonInterleaved) == paFloat32)
+            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+        else
+            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+
+        wavex->Samples.wValidBitsPerSample = bitsPerSample; //no extra padding!
+
+               // Set channel mask
+               if (channelMask != 0)
+               {
+                       wavex->dwChannelMask = channelMask;
+               }
+               else
+               {
+                       switch (params->channelCount)
+                       {
+                       case 1:  wavex->dwChannelMask = PAWIN_SPEAKER_MONO; break;
+                       case 2:  wavex->dwChannelMask = PAWIN_SPEAKER_STEREO; break;
+                       case 3:  wavex->dwChannelMask = PAWIN_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY; break;
+                       case 4:  wavex->dwChannelMask = PAWIN_SPEAKER_QUAD; break;
+                       case 5:  wavex->dwChannelMask = PAWIN_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY; break;
+#ifdef PAWIN_SPEAKER_5POINT1_SURROUND
+                       case 6:  wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1_SURROUND; break;
+#else
+                       case 6:  wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1; break;
+#endif
+#ifdef PAWIN_SPEAKER_5POINT1_SURROUND
+                       case 7:  wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1_SURROUND|SPEAKER_BACK_CENTER; break;
+#else
+                       case 7:  wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1|SPEAKER_BACK_CENTER; break;
+#endif 
+#ifdef PAWIN_SPEAKER_7POINT1_SURROUND
+                       case 8:  wavex->dwChannelMask = PAWIN_SPEAKER_7POINT1_SURROUND; break;
+#else
+                       case 8:  wavex->dwChannelMask = PAWIN_SPEAKER_7POINT1; break;
+#endif
+
+                       default: wavex->dwChannelMask = 0;
+                       }
+               }
+       }
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static void wasapiFillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount)
+{
+    PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat ));
+    PA_DEBUG(( "sampleRate = %f\n" , sampleRate ));
+    PA_DEBUG(( "chanelCount = %d\n", channelCount ));
+
+    pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+    pwfext->Format.nChannels = (WORD)channelCount;
+    pwfext->Format.nSamplesPerSec = (DWORD)sampleRate;
+    if(channelCount == 1)
+        pwfext->dwChannelMask = PAWIN_SPEAKER_DIRECTOUT;
+    else
+        pwfext->dwChannelMask = PAWIN_SPEAKER_STEREO;
+    if(sampleFormat == paFloat32)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 32;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+    }
+    else if(sampleFormat == paInt32)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 32;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    else if(sampleFormat == paInt24)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32; // 24-bit in 32-bit int container
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 24;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    else if(sampleFormat == paInt16)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 2);
+        pwfext->Format.wBitsPerSample = 16;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 16;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign;
+}*/
+
+// ------------------------------------------------------------------------------------------
+static PaError GetClosestFormat(IAudioClient *myClient, double sampleRate,
+       const PaStreamParameters *_params, AUDCLNT_SHAREMODE shareMode, WAVEFORMATEXTENSIBLE *outWavex,
+       BOOL output)
+{
+       PaError answer                   = paInvalidSampleRate;
+       WAVEFORMATEX *sharedClosestMatch = NULL;
+       HRESULT hr                       = !S_OK;
+       PaStreamParameters params       = (*_params);
+       (void)output;
+
+       /* It was not noticed that 24-bit Input producing no output while device accepts this format.
+          To fix this issue let's ask for 32-bits and let PA converters convert host 32-bit data
+          to 24-bit for user-space. The bug concerns Vista, if Windows 7 supports 24-bits for Input
+          please report to PortAudio developers to exclude Windows 7.
+       */
+       /*if ((params.sampleFormat == paInt24) && (output == FALSE))
+               params.sampleFormat = paFloat32;*/ // <<< The silence was due to missing Int32_To_Int24_Dither implementation
+
+    MakeWaveFormatFromParams(outWavex, &params, sampleRate);
+
+       hr = IAudioClient_IsFormatSupported(myClient, shareMode, &outWavex->Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+       if (hr == S_OK)
+               answer = paFormatIsSupported;
+    else
+       if (sharedClosestMatch)
+       {
+               WORD bitsPerSample;
+        WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)sharedClosestMatch;
+
+               GUID subf_guid = GUID_NULL;
+               if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
+               {
+                       memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEXTENSIBLE));
+                       subf_guid = ext->SubFormat;
+               }
+               else
+                       memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEX));
+
+        CoTaskMemFree(sharedClosestMatch);
+
+               // Make supported by default
+               answer = paFormatIsSupported;
+
+               // Validate SampleRate
+               if ((DWORD)sampleRate != outWavex->Format.nSamplesPerSec)
+                       return paInvalidSampleRate;
+
+               // Validate Channel count
+               if ((WORD)params.channelCount != outWavex->Format.nChannels)
+               {
+                       // If mono, then driver does not support 1 channel, we use internal workaround
+                       // of tiny software mixing functionality, e.g. we provide to user buffer 1 channel
+                       // but then mix into 2 for device buffer
+                       if ((params.channelCount == 1) && (outWavex->Format.nChannels == 2))
+                               return paFormatIsSupported;
+                       else
+                               return paInvalidChannelCount;
+               }
+
+               // Validate Sample format
+               if ((bitsPerSample = PaSampleFormatToBitsPerSample(params.sampleFormat)) == 0)
+                       return paSampleFormatNotSupported;
+
+               // Validate Sample format: bit size (WASAPI does not limit 'bit size')
+               //if (bitsPerSample != outWavex->Format.wBitsPerSample)
+               //      return paSampleFormatNotSupported;
+
+               // Validate Sample format: paFloat32 (WASAPI does not limit 'bit type')
+               //if ((params->sampleFormat == paFloat32) && (subf_guid != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+               //      return paSampleFormatNotSupported;
+
+               // Validate Sample format: paInt32 (WASAPI does not limit 'bit type')
+               //if ((params->sampleFormat == paInt32) && (subf_guid != KSDATAFORMAT_SUBTYPE_PCM))
+               //      return paSampleFormatNotSupported;
+       }
+       else
+       {
+               static const int BestToWorst[] = { paFloat32, paInt24, paInt16 };
+               int i;
+
+               // Try combination stereo and we will use built-in mono-stereo mixer then
+               if (params.channelCount == 1)
+               {
+                       WAVEFORMATEXTENSIBLE stereo = { 0 };
+
+                       PaStreamParameters stereo_params = params;
+                       stereo_params.channelCount = 2;
+
+                       MakeWaveFormatFromParams(&stereo, &stereo_params, sampleRate);
+
+                       hr = IAudioClient_IsFormatSupported(myClient, shareMode, &stereo.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+                       if (hr == S_OK)
+                       {
+                               memcpy(outWavex, &stereo, sizeof(WAVEFORMATEXTENSIBLE));
+                               CoTaskMemFree(sharedClosestMatch);
+                               return (answer = paFormatIsSupported);
+                       }
+
+                       // Try selecting suitable sample type
+                       for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
+                       {
+                               WAVEFORMATEXTENSIBLE sample = { 0 };
+
+                               PaStreamParameters sample_params = stereo_params;
+                               sample_params.sampleFormat = BestToWorst[i];
+
+                               MakeWaveFormatFromParams(&sample, &sample_params, sampleRate);
+
+                               hr = IAudioClient_IsFormatSupported(myClient, shareMode, &sample.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+                               if (hr == S_OK)
+                               {
+                                       memcpy(outWavex, &sample, sizeof(WAVEFORMATEXTENSIBLE));
+                                       CoTaskMemFree(sharedClosestMatch);
+                                       return (answer = paFormatIsSupported);
+                               }
+                       }
+               }
+
+               // Try selecting suitable sample type
+               for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
+               {
+                       WAVEFORMATEXTENSIBLE spfmt = { 0 };
+
+                       PaStreamParameters spfmt_params = params;
+                       spfmt_params.sampleFormat = BestToWorst[i];
+
+                       MakeWaveFormatFromParams(&spfmt, &spfmt_params, sampleRate);
+
+                       hr = IAudioClient_IsFormatSupported(myClient, shareMode, &spfmt.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+                       if (hr == S_OK)
+                       {
+                               memcpy(outWavex, &spfmt, sizeof(WAVEFORMATEXTENSIBLE));
+                               CoTaskMemFree(sharedClosestMatch);
+                               answer = paFormatIsSupported;
+                               break;
+                       }
+               }
+
+               // Nothing helped
+               LogHostError(hr);
+       }
+
+       return answer;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamParamsValid(struct PaUtilHostApiRepresentation *hostApi,
+                                   const  PaStreamParameters *inputParameters,
+                                   const  PaStreamParameters *outputParameters,
+                                   double sampleRate)
+{
+       if (hostApi == NULL)
+               return paHostApiNotFound;
+       if ((UINT32)sampleRate == 0)
+               return paInvalidSampleRate;
+
+       if (inputParameters != NULL)
+    {
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+               if (inputParameters->sampleFormat & paCustomFormat)
+            return paSampleFormatNotSupported;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if (inputParameters->device == paUseHostApiSpecificDeviceSpecification)
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if (inputParameters->channelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels)
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if (inputParameters->hostApiSpecificStreamInfo)
+               {
+                       PaWasapiStreamInfo *inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
+               if ((inputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
+                   (inputStreamInfo->version != 1) ||
+                (inputStreamInfo->hostApiType != paWASAPI))
+               {
+                   return paIncompatibleHostApiSpecificStreamInfo;
+               }
+               }
+
+        return paNoError;
+    }
+
+    if (outputParameters != NULL)
+    {
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if (outputParameters->sampleFormat & paCustomFormat)
+            return paSampleFormatNotSupported;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if (outputParameters->device == paUseHostApiSpecificDeviceSpecification)
+            return paInvalidDevice;
+
+        /* check that output device can support outputChannelCount */
+        if (outputParameters->channelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels)
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if(outputParameters->hostApiSpecificStreamInfo)
+        {
+                       PaWasapiStreamInfo *outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
+               if ((outputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
+                   (outputStreamInfo->version != 1) ||
+                (outputStreamInfo->hostApiType != paWASAPI))
+               {
+                   return paIncompatibleHostApiSpecificStreamInfo;
+               }
+        }
+
+               return paNoError;
+    }
+
+       return (inputParameters || outputParameters ? paNoError : paInternalError);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const  PaStreamParameters *inputParameters,
+                                  const  PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+       IAudioClient *tmpClient = NULL;
+       PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+       PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
+
+       // Validate PaStreamParameters
+       PaError error;
+       if ((error = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
+               return error;
+
+    if (inputParameters != NULL)
+    {
+               WAVEFORMATEXTENSIBLE wavex;
+               HRESULT hr;
+               PaError answer;
+               AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
+               inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
+
+               if (inputStreamInfo && (inputStreamInfo->flags & paWinWasapiExclusive))
+                       shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
+
+               hr = ActivateAudioInterface(&paWasapi->devInfo[inputParameters->device], &tmpClient);
+               if (hr != S_OK)
+               {
+                       LogHostError(hr);
+                       return paInvalidDevice;
+               }
+
+               answer = GetClosestFormat(tmpClient, sampleRate, inputParameters, shareMode, &wavex, FALSE);
+               SAFE_RELEASE(tmpClient);
+
+               if (answer != paFormatIsSupported)
+                       return answer;
+    }
+
+    if (outputParameters != NULL)
+    {
+               HRESULT hr;
+               WAVEFORMATEXTENSIBLE wavex;
+               PaError answer;
+               AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
+        outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
+
+               if (outputStreamInfo && (outputStreamInfo->flags & paWinWasapiExclusive))
+                       shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
+
+               hr = ActivateAudioInterface(&paWasapi->devInfo[outputParameters->device], &tmpClient);
+               if (hr != S_OK)
+               {
+                       LogHostError(hr);
+                       return paInvalidDevice;
+               }
+
+               answer = GetClosestFormat(tmpClient, sampleRate, outputParameters, shareMode, &wavex, TRUE);
+               SAFE_RELEASE(tmpClient);
+
+               if (answer != paFormatIsSupported)
+                       return answer;
+    }
+
+    return paFormatIsSupported;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaUint32 PaUtil_GetFramesPerHostBuffer(PaUint32 userFramesPerBuffer, PaTime suggestedLatency, double sampleRate, PaUint32 TimerJitterMs)
+{
+       PaUint32 frames = userFramesPerBuffer + max( userFramesPerBuffer, (PaUint32)(suggestedLatency * sampleRate) );
+    frames += (PaUint32)((sampleRate * 0.001) * TimerJitterMs);
+       return frames;
+}
+
+// ------------------------------------------------------------------------------------------
+static void _RecalculateBuffersCount(PaWasapiSubStream *sub, UINT32 userFramesPerBuffer, UINT32 framesPerLatency, BOOL fullDuplex)
+{
+       // Count buffers (must be at least 1)
+       sub->buffers = (userFramesPerBuffer ? framesPerLatency / userFramesPerBuffer : 0);
+       if (sub->buffers == 0)
+               sub->buffers = 1;
+
+       // Determine amount of buffers used:
+       // - Full-duplex mode will lead to period difference, thus only 1.
+       // - Input mode, only 1, as WASAPI allows extraction of only 1 packet.
+       // - For Shared mode we use double buffering.
+       if ((sub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) || fullDuplex)
+       {
+               // Exclusive mode does not allow >1 buffers be used for Event interface, e.g. GetBuffer
+               // call must acquire max buffer size and it all must be processed.
+               if (sub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)
+                       sub->userBufferAndHostMatch = 1;
+
+               // Use paUtilBoundedHostBufferSize because exclusive mode will starve and produce
+               // bad quality of audio
+               sub->buffers = 1;
+       }
+}
+
+// ------------------------------------------------------------------------------------------
+static void _CalculateAlignedPeriod(PaWasapiSubStream *pSub, UINT32 *nFramesPerLatency,
+                                                                       ALIGN_FUNC pAlignFunc)
+{
+       // Align frames to HD Audio packet size of 128 bytes for Exclusive mode only.
+       // Not aligning on Windows Vista will cause Event timeout, although Windows 7 will
+       // return AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED error to realign buffer. Aligning is necessary
+       // for Exclusive mode only! when audio data is feeded directly to hardware.
+       if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
+       {
+               (*nFramesPerLatency) = AlignFramesPerBuffer((*nFramesPerLatency),
+                       pSub->wavex.Format.nSamplesPerSec, pSub->wavex.Format.nBlockAlign, pAlignFunc);
+       }
+
+       // Calculate period
+       pSub->period = MakeHnsPeriod((*nFramesPerLatency), pSub->wavex.Format.nSamplesPerSec);
+}
+
+// ------------------------------------------------------------------------------------------
+static HRESULT CreateAudioClient(PaWasapiStream *pStream, PaWasapiSubStream *pSub, BOOL output, PaError *pa_error)
+{
+       PaError error;
+    HRESULT hr;
+
+       const PaWasapiDeviceInfo *pInfo  = pSub->params.device_info;
+       const PaStreamParameters *params = &pSub->params.stream_params;
+       UINT32 framesPerLatency          = pSub->params.frames_per_buffer;
+       double sampleRate                = pSub->params.sample_rate;
+       //BOOL blocking                    = pSub->params.blocking;
+       BOOL fullDuplex                  = pSub->params.full_duplex;
+
+       const UINT32 userFramesPerBuffer = framesPerLatency;
+    IAudioClient *audioClient       = NULL;
+
+       // Assume default failure due to some reason
+       (*pa_error) = paInvalidDevice;
+
+       // Validate parameters
+    if (!pSub || !pInfo || !params)
+       {
+               (*pa_error) = paBadStreamPtr;
+        return E_POINTER;
+       }
+       if ((UINT32)sampleRate == 0)
+       {
+               (*pa_error) = paInvalidSampleRate;
+        return E_INVALIDARG;
+       }
+
+    // Get the audio client
+    hr = ActivateAudioInterface(pInfo, &audioClient);
+       if (hr != S_OK)
+       {
+               (*pa_error) = paInsufficientMemory;
+               LogHostError(hr);
+               goto done;
+       }
+
+       // Get closest format
+       if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
+       {
+               (*pa_error) = error;
+               LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+               goto done; // fail, format not supported
+       }
+
+       // Check for Mono <<>> Stereo workaround
+       if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
+       {
+               /*if (blocking)
+               {
+                       LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+                       goto done; // fail, blocking mode not supported
+               }*/
+
+               // select mixer
+               pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1_L));
+               if (pSub->monoMixer == NULL)
+               {
+                       (*pa_error) = paInvalidChannelCount;
+                       LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+                       goto done; // fail, no mixer for format
+               }
+       }
+
+#if 0
+       // Add suggestd latency
+       framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
+#else
+       // Calculate host buffer size
+       if ((pSub->shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE) &&
+               (!pSub->streamFlags || ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
+       {
+               framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
+                       params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
+                       (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
+       }
+       else
+       {
+               REFERENCE_TIME overall;
+
+               // Work 1:1 with user buffer (only polling allows to use >1)
+               framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
+
+               // Use Polling if overall latency is > 5ms as it allows to use 100% CPU in a callback,
+               // or user specified latency parameter
+               overall = MakeHnsPeriod(framesPerLatency, pSub->wavex.Format.nSamplesPerSec);
+               if ((overall >= (106667*2)/*21.33ms*/) || ((INT32)(params->suggestedLatency*100000.0) != 0/*0.01 msec granularity*/))
+               {
+                       framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
+                               params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
+                               (streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
+
+                       // Use Polling interface
+                       pSub->streamFlags &= ~AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
+                       PRINT(("WASAPI: CreateAudioClient: forcing POLL mode\n"));
+               }
+       }
+#endif
+
+       // For full-duplex output resize buffer to be the same as for input
+       if (output && fullDuplex)
+               framesPerLatency = pStream->in.framesPerHostCallback;
+
+       // Avoid 0 frames
+       if (framesPerLatency == 0)
+               framesPerLatency = MakeFramesFromHns(pInfo->DefaultDevicePeriod, pSub->wavex.Format.nSamplesPerSec);
+
+       // Exclusive Input stream renders data in 6 packets, we must set then the size of
+       // single packet, total buffer size, e.g. required latency will be PacketSize * 6
+       if (!output && (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE))
+       {
+               // Do it only for Polling mode
+               if ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)
+               {
+                       framesPerLatency /= WASAPI_PACKETS_PER_INPUT_BUFFER;
+               }
+       }
+
+       // Calculate aligned period
+       _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+
+       /*! Enforce min/max period for device in Shared mode to avoid bad audio quality.
+        Avoid doing so for Exclusive mode as alignment will suffer.
+       */
+       if (pSub->shareMode == AUDCLNT_SHAREMODE_SHARED)
+       {
+               if (pSub->period < pInfo->DefaultDevicePeriod)
+               {
+                       pSub->period = pInfo->DefaultDevicePeriod;
+                       // Recalculate aligned period
+                       framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+                       _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+               }
+       }
+       else
+       {
+               if (pSub->period < pInfo->MinimumDevicePeriod)
+               {
+                       pSub->period = pInfo->MinimumDevicePeriod;
+                       // Recalculate aligned period
+                       framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+                       _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_FWD);
+               }
+       }
+
+       /*! Windows 7 does not allow to set latency lower than minimal device period and will
+           return error: AUDCLNT_E_INVALID_DEVICE_PERIOD. Under Vista we enforce the same behavior
+           manually for unified behavior on all platforms.
+       */
+       {
+               /*!     AUDCLNT_E_BUFFER_SIZE_ERROR: Applies to Windows 7 and later.
+                       Indicates that the buffer duration value requested by an exclusive-mode client is
+                       out of range. The requested duration value for pull mode must not be greater than
+                       500 milliseconds; for push mode the duration value must not be greater than 2 seconds.
+               */
+               if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
+               {
+                       static const REFERENCE_TIME MAX_BUFFER_EVENT_DURATION = 500  * 10000;
+                       static const REFERENCE_TIME MAX_BUFFER_POLL_DURATION  = 2000 * 10000;
+
+                       if (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)      // pull mode, max 500ms
+                       {
+                               if (pSub->period > MAX_BUFFER_EVENT_DURATION)
+                               {
+                                       pSub->period = MAX_BUFFER_EVENT_DURATION;
+                                       // Recalculate aligned period
+                                       framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+                                       _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+                               }
+                       }
+                       else                                                                                                            // push mode, max 2000ms
+                       {
+                               if (pSub->period > MAX_BUFFER_POLL_DURATION)
+                               {
+                                       pSub->period = MAX_BUFFER_POLL_DURATION;
+                                       // Recalculate aligned period
+                                       framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+                                       _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+                               }
+                       }
+               }
+       }
+
+       // Set Raw mode (applicable only to IAudioClient2)
+#ifdef __IAudioClient2_INTERFACE_DEFINED__
+       if (GetAudioClientVersion() >= 2)
+       {
+               pa_AudioClientProperties audioProps = { 0 };
+               audioProps.cbSize     = sizeof(pa_AudioClientProperties);
+               audioProps.bIsOffload = FALSE;
+               audioProps.eCategory  = (AUDIO_STREAM_CATEGORY)pSub->params.wasapi_params.streamCategory;
+               switch (pSub->params.wasapi_params.streamOption)
+               {
+               case eStreamOptionRaw:
+                       if (GetWindowsVersion() >= WINDOWS_8_1_SERVER2012R2)
+                               audioProps.Options = pa_AUDCLNT_STREAMOPTIONS_RAW;
+                       break;
+               case eStreamOptionMatchFormat:
+                       if (GetWindowsVersion() >= WINDOWS_10_SERVER2016)
+                               audioProps.Options = pa_AUDCLNT_STREAMOPTIONS_MATCH_FORMAT;
+                       break;
+               }
+
+               hr = IAudioClient2_SetClientProperties((IAudioClient2 *)audioClient, (AudioClientProperties *)&audioProps);
+               if (hr != S_OK)
+               {
+                       PRINT(("WASAPI: IAudioClient2_SetClientProperties(Category = %d, Options = %d) failed with error = %08X\n", audioProps.eCategory, audioProps.Options, (UINT32)hr));
+               }
+               else
+               {
+                       PRINT(("WASAPI: IAudioClient2 set properties: IsOffload = %d, Category = %d, Options = %d\n", audioProps.bIsOffload, audioProps.eCategory, audioProps.Options));
+               }
+       }
+#endif
+
+       // Open the stream and associate it with an audio session
+    hr = IAudioClient_Initialize(audioClient,
+        pSub->shareMode,
+        pSub->streamFlags,
+               pSub->period,
+               (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+               &pSub->wavex.Format,
+        NULL);
+
+       /*! WASAPI is tricky on large device buffer, sometimes 2000ms can be allocated sometimes
+           less. There is no known guaranteed level thus we make subsequent tries by decreasing
+               buffer by 100ms per try.
+       */
+       while ((hr == E_OUTOFMEMORY) && (pSub->period > (100 * 10000)))
+       {
+               PRINT(("WASAPI: CreateAudioClient: decreasing buffer size to %d milliseconds\n", (pSub->period / 10000)));
+
+               // Decrease by 100ms and try again
+               pSub->period -= (100 * 10000);
+
+               // Recalculate aligned period
+               framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+               _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = ActivateAudioInterface(pInfo, &audioClient);
+       if (hr != S_OK)
+               {
+                       (*pa_error) = paInsufficientMemory;
+                       LogHostError(hr);
+                       goto done;
+               }
+
+               // Open the stream and associate it with an audio session
+               hr = IAudioClient_Initialize(audioClient,
+                       pSub->shareMode,
+                       pSub->streamFlags,
+                       pSub->period,
+                       (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+                       &pSub->wavex.Format,
+                       NULL);
+       }
+
+       /*! WASAPI buffer size failure. Fallback to using default size.
+       */
+       if (hr == AUDCLNT_E_BUFFER_SIZE_ERROR)
+       {
+               // Use default
+               pSub->period = pInfo->DefaultDevicePeriod;
+
+               PRINT(("WASAPI: CreateAudioClient: correcting buffer size to device default\n"));
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = ActivateAudioInterface(pInfo, &audioClient);
+       if (hr != S_OK)
+               {
+                       (*pa_error) = paInsufficientMemory;
+                       LogHostError(hr);
+                       goto done;
+               }
+
+               // Open the stream and associate it with an audio session
+               hr = IAudioClient_Initialize(audioClient,
+                       pSub->shareMode,
+                       pSub->streamFlags,
+                       pSub->period,
+                       (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+                       &pSub->wavex.Format,
+                       NULL);
+       }
+
+    /*! If the requested buffer size is not aligned. Can be triggered by Windows 7 and up.
+           Should not be be triggered ever as we do align buffers always with _CalculateAlignedPeriod.
+       */
+    if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
+    {
+               UINT32 frames = 0;
+
+        // Get the next aligned frame
+        hr = IAudioClient_GetBufferSize(audioClient, &frames);
+               if (hr != S_OK)
+               {
+                       (*pa_error) = paInvalidDevice;
+                       LogHostError(hr);
+                       goto done;
+               }
+
+               PRINT(("WASAPI: CreateAudioClient: aligning buffer size to % frames\n", frames));
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = ActivateAudioInterface(pInfo, &audioClient);
+       if (hr != S_OK)
+               {
+                       (*pa_error) = paInsufficientMemory;
+                       LogHostError(hr);
+                       goto done;
+               }
+
+               // Get closest format
+               if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
+               {
+                       (*pa_error) = error;
+                       LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT); // fail, format not supported
+                       goto done;
+               }
+
+               // Check for Mono >> Stereo workaround
+               if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
+               {
+                       /*if (blocking)
+                       {
+                               LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+                               goto done; // fail, blocking mode not supported
+                       }*/
+
+                       // Select mixer
+                       pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1_L));
+                       if (pSub->monoMixer == NULL)
+                       {
+                               (*pa_error) = paInvalidChannelCount;
+                               LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+                               goto done; // fail, no mixer for format
+                       }
+               }
+
+               // Calculate period
+               pSub->period = MakeHnsPeriod(frames, pSub->wavex.Format.nSamplesPerSec);
+
+        // Open the stream and associate it with an audio session
+        hr = IAudioClient_Initialize(audioClient,
+            pSub->shareMode,
+            pSub->streamFlags,
+                       pSub->period,
+                       (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+            &pSub->wavex.Format,
+            NULL);
+       if (hr != S_OK)
+               {
+                       (*pa_error) = paInvalidDevice;
+                       LogHostError(hr);
+                       goto done;
+               }
+    }
+    else
+       if (hr != S_OK)
+    {
+               (*pa_error) = paInvalidDevice;
+               LogHostError(hr);
+               goto done;
+    }
+
+    // Set client
+       pSub->clientParent = audioClient;
+    IAudioClient_AddRef(pSub->clientParent);
+
+       // Recalculate buffers count
+       _RecalculateBuffersCount(pSub,
+               userFramesPerBuffer,
+               MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec),
+               fullDuplex);
+
+       // No error, client is succesfully created
+       (*pa_error) = paNoError;
+
+done:
+
+    // Clean up
+    SAFE_RELEASE(audioClient);
+    return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ActivateAudioClientOutput(PaWasapiStream *stream)
+{
+       HRESULT hr;
+       PaError result;
+
+       UINT32 maxBufferSize   = 0;
+       PaTime buffer_latency  = 0;
+       UINT32 framesPerBuffer = stream->out.params.frames_per_buffer;
+
+       // Create Audio client
+       hr = CreateAudioClient(stream, &stream->out, TRUE, &result);
+    if (hr != S_OK)
+       {
+               LogPaError(result);
+               goto error;
+    }
+       LogWAVEFORMATEXTENSIBLE(&stream->out.wavex);
+
+       // Activate volume
+       stream->outVol = NULL;
+    /*hr = info->device->Activate(
+        __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
+        (void**)&stream->outVol);
+    if (hr != S_OK)
+        return paInvalidDevice;*/
+
+    // Get max possible buffer size to check if it is not less than that we request
+    hr = IAudioClient_GetBufferSize(stream->out.clientParent, &maxBufferSize);
+    if (hr != S_OK)
+       {
+               LogHostError(hr);
+               LogPaError(result = paInvalidDevice);
+               goto error;
+       }
+
+    // Correct buffer to max size if it maxed out result of GetBufferSize
+       stream->out.bufferSize = maxBufferSize;
+
+       // Get interface latency (actually uneeded as we calculate latency from the size
+       // of maxBufferSize).
+    hr = IAudioClient_GetStreamLatency(stream->out.clientParent, &stream->out.deviceLatency);
+    if (hr != S_OK)
+       {
+               LogHostError(hr);
+               LogPaError(result = paInvalidDevice);
+               goto error;
+       }
+       //stream->out.latencySeconds = nano100ToSeconds(stream->out.deviceLatency);
+
+    // Number of frames that are required at each period
+       stream->out.framesPerHostCallback = maxBufferSize;
+
+       // Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
+       stream->out.framesPerBuffer =
+               (stream->out.userBufferAndHostMatch ? stream->out.framesPerHostCallback : framesPerBuffer);
+
+       // Calculate buffer latency
+       buffer_latency = (PaTime)maxBufferSize / stream->out.wavex.Format.nSamplesPerSec;
+
+       // Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
+       stream->out.latencySeconds = buffer_latency;
+
+       PRINT(("WASAPI::OpenStream(output): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->out.framesPerHostCallback, (float)(stream->out.latencySeconds*1000.0f), (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->out.params.wow64_workaround ? "YES" : "NO"), (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
+
+       return paNoError;
+
+error:
+
+       return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ActivateAudioClientInput(PaWasapiStream *stream)
+{
+       HRESULT hr;
+       PaError result;
+
+       UINT32 maxBufferSize   = 0;
+       PaTime buffer_latency  = 0;
+       UINT32 framesPerBuffer = stream->in.params.frames_per_buffer;
+
+       // Create Audio client
+       hr = CreateAudioClient(stream, &stream->in, FALSE, &result);
+    if (hr != S_OK)
+       {
+               LogPaError(result);
+               goto error;
+    }
+       LogWAVEFORMATEXTENSIBLE(&stream->in.wavex);
+
+       // Create volume mgr
+       stream->inVol = NULL;
+    /*hr = info->device->Activate(
+        __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
+        (void**)&stream->inVol);
+    if (hr != S_OK)
+        return paInvalidDevice;*/
+
+    // Get max possible buffer size to check if it is not less than that we request
+    hr = IAudioClient_GetBufferSize(stream->in.clientParent, &maxBufferSize);
+    if (hr != S_OK)
+       {
+               LogHostError(hr);
+               LogPaError(result = paInvalidDevice);
+               goto error;
+       }
+
+    // Correct buffer to max size if it maxed out result of GetBufferSize
+       stream->in.bufferSize = maxBufferSize;
+
+       // Get interface latency (actually uneeded as we calculate latency from the size
+       // of maxBufferSize).
+    hr = IAudioClient_GetStreamLatency(stream->in.clientParent, &stream->in.deviceLatency);
+    if (hr != S_OK)
+       {
+               LogHostError(hr);
+               LogPaError(result = paInvalidDevice);
+               goto error;
+       }
+       //stream->in.latencySeconds = nano100ToSeconds(stream->in.deviceLatency);
+
+    // Number of frames that are required at each period
+       stream->in.framesPerHostCallback = maxBufferSize;
+
+       // Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
+       stream->in.framesPerBuffer =
+               (stream->in.userBufferAndHostMatch ? stream->in.framesPerHostCallback : framesPerBuffer);
+
+       // Calculate buffer latency
+       buffer_latency = (PaTime)maxBufferSize / stream->in.wavex.Format.nSamplesPerSec;
+
+       // Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
+       stream->in.latencySeconds = buffer_latency;
+
+       PRINT(("WASAPI::OpenStream(input): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->in.framesPerHostCallback, (float)(stream->in.latencySeconds*1000.0f), (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->in.params.wow64_workaround ? "YES" : "NO"), (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
+
+       return paNoError;
+
+error:
+
+       return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+       HRESULT hr;
+    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+    PaWasapiStream *stream = NULL;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+       PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
+       PaWasapiDeviceInfo *info = NULL;
+       ULONG framesPerHostCallback;
+       PaUtilHostBufferSizeMode bufferMode;
+       const BOOL fullDuplex = ((inputParameters != NULL) && (outputParameters != NULL));
+
+       // validate PaStreamParameters
+       if ((result = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
+               return LogPaError(result);
+
+    // Validate platform specific flags
+    if ((streamFlags & paPlatformSpecificFlags) != 0)
+       {
+               LogPaError(result = paInvalidFlag); /* unexpected platform specific flag */
+               goto error;
+       }
+
+       // Allocate memory for PaWasapiStream
+    if ((stream = (PaWasapiStream *)PaUtil_AllocateMemory(sizeof(PaWasapiStream))) == NULL)
+       {
+        LogPaError(result = paInsufficientMemory);
+        goto error;
+    }
+
+       // Default thread priority is Audio: for exclusive mode we will use Pro Audio.
+       stream->nThreadPriority = eThreadPriorityAudio;
+
+       // Set default number of frames: paFramesPerBufferUnspecified
+       if (framesPerBuffer == paFramesPerBufferUnspecified)
+       {
+               UINT32 framesPerBufferIn  = 0, framesPerBufferOut = 0;
+               if (inputParameters != NULL)
+               {
+                       info = &paWasapi->devInfo[inputParameters->device];
+                       framesPerBufferIn = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
+               }
+               if (outputParameters != NULL)
+               {
+                       info = &paWasapi->devInfo[outputParameters->device];
+                       framesPerBufferOut = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
+               }
+               // choosing maximum default size
+               framesPerBuffer = max(framesPerBufferIn, framesPerBufferOut);
+       }
+       if (framesPerBuffer == 0)
+               framesPerBuffer = ((UINT32)sampleRate / 100) * 2;
+
+       // Try create device: Input
+       if (inputParameters != NULL)
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        info              = &paWasapi->devInfo[inputParameters->device];
+
+               // default Shared Mode
+               stream->in.shareMode = AUDCLNT_SHAREMODE_SHARED;
+
+               // PaWasapiStreamInfo
+               if (inputParameters->hostApiSpecificStreamInfo != NULL)
+               {
+                       memcpy(&stream->in.params.wasapi_params, inputParameters->hostApiSpecificStreamInfo, min(sizeof(stream->in.params.wasapi_params), ((PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo)->size));
+                       stream->in.params.wasapi_params.size = sizeof(stream->in.params.wasapi_params);
+
+                       stream->in.params.stream_params.hostApiSpecificStreamInfo = &stream->in.params.wasapi_params;
+                       inputStreamInfo = &stream->in.params.wasapi_params;
+
+                       stream->in.flags = inputStreamInfo->flags;
+
+                       // Exclusive Mode
+                       if (inputStreamInfo->flags & paWinWasapiExclusive)
+                       {
+                               // Boost thread priority
+                               stream->nThreadPriority = eThreadPriorityProAudio;
+                               // Make Exclusive
+                               stream->in.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
+                       }
+
+                       // explicit thread priority level
+                       if (inputStreamInfo->flags & paWinWasapiThreadPriority)
+                       {
+                               if ((inputStreamInfo->threadPriority > eThreadPriorityNone) &&
+                                       (inputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
+                                       stream->nThreadPriority = inputStreamInfo->threadPriority;
+                       }
+               }
+
+               // Choose processing mode
+               stream->in.streamFlags = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
+               if (paWasapi->useWOW64Workaround)
+                       stream->in.streamFlags = 0; // polling interface
+               else
+               if (streamCallback == NULL)
+                       stream->in.streamFlags = 0; // polling interface
+               else
+               if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiPolling))
+                       stream->in.streamFlags = 0; // polling interface
+               else
+               if (fullDuplex)
+                       stream->in.streamFlags = 0; // polling interface is implemented for full-duplex mode also
+
+               // Fill parameters for Audio Client creation
+               stream->in.params.device_info       = info;
+               stream->in.params.stream_params     = (*inputParameters);
+               stream->in.params.frames_per_buffer = framesPerBuffer;
+               stream->in.params.sample_rate       = sampleRate;
+               stream->in.params.blocking          = (streamCallback == NULL);
+               stream->in.params.full_duplex       = fullDuplex;
+               stream->in.params.wow64_workaround  = paWasapi->useWOW64Workaround;
+
+               // Create and activate audio client
+               hr = ActivateAudioClientInput(stream);
+        if (hr != S_OK)
+               {
+                       LogPaError(result = paInvalidDevice);
+                       goto error;
+        }
+
+               // Get closest format
+        hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->in.wavex), inputSampleFormat );
+
+        // Set user-side custom host processor
+        if ((inputStreamInfo != NULL) &&
+            (inputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
+        {
+            stream->hostProcessOverrideInput.processor = inputStreamInfo->hostProcessorInput;
+            stream->hostProcessOverrideInput.userData = userData;
+        }
+
+               // Only get IAudioCaptureClient input once here instead of getting it at multiple places based on the use
+               hr = IAudioClient_GetService(stream->in.clientParent, &pa_IID_IAudioCaptureClient, (void **)&stream->captureClientParent);
+               if (hr != S_OK)
+               {
+                       LogHostError(hr);
+                       LogPaError(result = paUnanticipatedHostError);
+                       goto error;
+               }
+
+               // Create ring buffer for blocking mode (It is needed because we fetch Input packets, not frames,
+               // and thus we have to save partial packet if such remains unread)
+               if (stream->in.params.blocking == TRUE)
+               {
+                       UINT32 bufferFrames = ALIGN_NEXT_POW2((stream->in.framesPerHostCallback / WASAPI_PACKETS_PER_INPUT_BUFFER) * 2);
+                       UINT32 frameSize    = stream->in.wavex.Format.nBlockAlign;
+
+                       // buffer
+                       if ((stream->in.tailBuffer = PaUtil_AllocateMemory(sizeof(PaUtilRingBuffer))) == NULL)
+                       {
+                               LogPaError(result = paInsufficientMemory);
+                               goto error;
+                       }
+                       memset(stream->in.tailBuffer, 0, sizeof(PaUtilRingBuffer));
+
+                       // buffer memory region
+                       stream->in.tailBufferMemory = PaUtil_AllocateMemory(frameSize * bufferFrames);
+                       if (stream->in.tailBufferMemory == NULL)
+                       {
+                               LogPaError(result = paInsufficientMemory);
+                               goto error;
+                       }
+
+                       // initialize
+                       if (PaUtil_InitializeRingBuffer(stream->in.tailBuffer, frameSize, bufferFrames, stream->in.tailBufferMemory) != 0)
+                       {
+                               LogPaError(result = paInternalError);
+                               goto error;
+                       }
+               }
+       }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */
+    }
+
+       // Try create device: Output
+    if (outputParameters != NULL)
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+               info               = &paWasapi->devInfo[outputParameters->device];
+
+               // default Shared Mode
+               stream->out.shareMode = AUDCLNT_SHAREMODE_SHARED;
+
+               // set PaWasapiStreamInfo
+               if (outputParameters->hostApiSpecificStreamInfo != NULL)
+               {
+                       memcpy(&stream->out.params.wasapi_params, outputParameters->hostApiSpecificStreamInfo, min(sizeof(stream->out.params.wasapi_params), ((PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo)->size));
+                       stream->out.params.wasapi_params.size = sizeof(stream->out.params.wasapi_params);
+
+                       stream->out.params.stream_params.hostApiSpecificStreamInfo = &stream->out.params.wasapi_params;
+                       outputStreamInfo = &stream->out.params.wasapi_params;
+
+                       stream->out.flags = outputStreamInfo->flags;
+
+                       // Exclusive Mode
+                       if (outputStreamInfo->flags & paWinWasapiExclusive)
+                       {
+                               // Boost thread priority
+                               stream->nThreadPriority = eThreadPriorityProAudio;
+                               // Make Exclusive
+                               stream->out.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
+                       }
+
+                       // explicit thread priority level
+                       if (outputStreamInfo->flags & paWinWasapiThreadPriority)
+                       {
+                               if ((outputStreamInfo->threadPriority > eThreadPriorityNone) &&
+                                       (outputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
+                                       stream->nThreadPriority = outputStreamInfo->threadPriority;
+                       }
+               }
+
+               // Choose processing mode
+               stream->out.streamFlags = (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
+               if (paWasapi->useWOW64Workaround)
+                       stream->out.streamFlags = 0; // polling interface
+               else
+               if (streamCallback == NULL)
+                       stream->out.streamFlags = 0; // polling interface
+               else
+               if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiPolling))
+                       stream->out.streamFlags = 0; // polling interface
+               else
+               if (fullDuplex)
+                       stream->out.streamFlags = 0; // polling interface is implemented for full-duplex mode also
+
+               // Fill parameters for Audio Client creation
+               stream->out.params.device_info       = info;
+               stream->out.params.stream_params     = (*outputParameters);
+               stream->out.params.frames_per_buffer = framesPerBuffer;
+               stream->out.params.sample_rate       = sampleRate;
+               stream->out.params.blocking          = (streamCallback == NULL);
+               stream->out.params.full_duplex       = fullDuplex;
+               stream->out.params.wow64_workaround  = paWasapi->useWOW64Workaround;
+
+               // Create and activate audio client
+               hr = ActivateAudioClientOutput(stream);
+        if (hr != S_OK)
+               {
+                       LogPaError(result = paInvalidDevice);
+                       goto error;
+        }
+
+               // Get closest format
+        hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->out.wavex), outputSampleFormat );
+
+        // Set user-side custom host processor
+        if ((outputStreamInfo != NULL) &&
+            (outputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
+        {
+            stream->hostProcessOverrideOutput.processor = outputStreamInfo->hostProcessorOutput;
+            stream->hostProcessOverrideOutput.userData = userData;
+        }
+
+               // Only get IAudioCaptureClient output once here instead of getting it at multiple places based on the use
+               hr = IAudioClient_GetService(stream->out.clientParent, &pa_IID_IAudioRenderClient, (void **)&stream->renderClientParent);
+               if (hr != S_OK)
+               {
+                       LogHostError(hr);
+                       LogPaError(result = paUnanticipatedHostError);
+                       goto error;
+               }
+       }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */
+    }
+
+       // log full-duplex
+       if (fullDuplex)
+               PRINT(("WASAPI::OpenStream: full-duplex mode\n"));
+
+       // paWinWasapiPolling must be on/or not on both streams
+       if ((inputParameters != NULL) && (outputParameters != NULL))
+       {
+               if ((inputStreamInfo != NULL) && (outputStreamInfo != NULL))
+               {
+                       if (((inputStreamInfo->flags & paWinWasapiPolling) &&
+                               !(outputStreamInfo->flags & paWinWasapiPolling))
+                               ||
+                               (!(inputStreamInfo->flags & paWinWasapiPolling) &&
+                                (outputStreamInfo->flags & paWinWasapiPolling)))
+                       {
+                               LogPaError(result = paInvalidFlag);
+                               goto error;
+                       }
+               }
+       }
+
+       // Initialize stream representation
+    if (streamCallback)
+    {
+               stream->bBlocking = FALSE;
+        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
+                                              &paWasapi->callbackStreamInterface,
+                                                                                         streamCallback, userData);
+    }
+    else
+    {
+               stream->bBlocking = TRUE;
+        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
+                                              &paWasapi->blockingStreamInterface,
+                                                                                         streamCallback, userData);
+    }
+
+       // Initialize CPU measurer
+    PaUtil_InitializeCpuLoadMeasurer(&stream->cpuLoadMeasurer, sampleRate);
+
+       if (outputParameters && inputParameters)
+       {
+               // serious problem #1 - No, Not a problem, especially concerning Exclusive mode.
+               // Input device in exclusive mode somehow is getting large buffer always, thus we
+               // adjust Output latency to reflect it, thus period will differ but playback will be
+               // normal.
+               /*if (stream->in.period != stream->out.period)
+               {
+                       PRINT(("WASAPI: OpenStream: period discrepancy\n"));
+                       LogPaError(result = paBadIODeviceCombination);
+                       goto error;
+               }*/
+
+               // serious problem #2 - No, Not a problem, as framesPerHostCallback take into account
+               // sample size while it is not a problem for PA full-duplex, we must care of
+               // preriod only!
+               /*if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback)
+               {
+                       PRINT(("WASAPI: OpenStream: framesPerHostCallback discrepancy\n"));
+                       goto error;
+               }*/
+       }
+
+       // Calculate frames per host for processor
+       framesPerHostCallback = (outputParameters ? stream->out.framesPerBuffer : stream->in.framesPerBuffer);
+
+       // Choose correct mode of buffer processing:
+       // Exclusive/Shared non paWinWasapiPolling mode: paUtilFixedHostBufferSize - always fixed
+       // Exclusive/Shared paWinWasapiPolling mode: paUtilBoundedHostBufferSize - may vary for Exclusive or Full-duplex
+       bufferMode = paUtilFixedHostBufferSize;
+       if (inputParameters) // !!! WASAPI IAudioCaptureClient::GetBuffer extracts not number of frames but 1 packet, thus we always must adapt
+               bufferMode = paUtilBoundedHostBufferSize;
+       else
+       if (outputParameters)
+       {
+               if ((stream->out.buffers == 1) &&
+                       (!stream->out.streamFlags || ((stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
+                       bufferMode = paUtilBoundedHostBufferSize;
+       }
+       stream->bufferMode = bufferMode;
+
+    // Initialize buffer processor
+    result =  PaUtil_InitializeBufferProcessor(
+               &stream->bufferProcessor,
+        inputChannelCount,
+               inputSampleFormat,
+               hostInputSampleFormat,
+        outputChannelCount,
+               outputSampleFormat,
+               hostOutputSampleFormat,
+        sampleRate,
+               streamFlags,
+               framesPerBuffer,
+        framesPerHostCallback,
+               bufferMode,
+        streamCallback,
+               userData);
+    if (result != paNoError)
+       {
+               LogPaError(result);
+        goto error;
+       }
+
+       // Set Input latency
+    stream->streamRepresentation.streamInfo.inputLatency =
+            ((double)PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) / sampleRate)
+                       + ((inputParameters)?stream->in.latencySeconds : 0);
+
+       // Set Output latency
+    stream->streamRepresentation.streamInfo.outputLatency =
+            ((double)PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) / sampleRate)
+                       + ((outputParameters)?stream->out.latencySeconds : 0);
+
+       // Set SR
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    (*s) = (PaStream *)stream;
+    return result;
+
+error:
+
+    if (stream != NULL)
+               CloseStream(stream);
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+       // abort active stream
+       if (IsStreamActive(s))
+       {
+               result = AbortStream(s);
+       }
+
+    SAFE_RELEASE(stream->captureClientParent);
+    SAFE_RELEASE(stream->renderClientParent);
+    SAFE_RELEASE(stream->out.clientParent);
+    SAFE_RELEASE(stream->in.clientParent);
+       SAFE_RELEASE(stream->inVol);
+       SAFE_RELEASE(stream->outVol);
+
+       CloseHandle(stream->event[S_INPUT]);
+       CloseHandle(stream->event[S_OUTPUT]);
+
+       _StreamCleanup(stream);
+
+       PaWasapi_FreeMemory(stream->in.monoBuffer);
+       PaWasapi_FreeMemory(stream->out.monoBuffer);
+
+       PaUtil_FreeMemory(stream->in.tailBuffer);
+       PaUtil_FreeMemory(stream->in.tailBufferMemory);
+
+       PaUtil_FreeMemory(stream->out.tailBuffer);
+       PaUtil_FreeMemory(stream->out.tailBufferMemory);
+
+    PaUtil_TerminateBufferProcessor(&stream->bufferProcessor);
+    PaUtil_TerminateStreamRepresentation(&stream->streamRepresentation);
+    PaUtil_FreeMemory(stream);
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT UnmarshalSubStreamComPointers(PaWasapiSubStream *substream) 
+{
+#ifndef PA_WINRT
+       HRESULT hResult = S_OK;
+       HRESULT hFirstBadResult = S_OK;
+       substream->clientProc = NULL;
+
+       // IAudioClient
+       hResult = CoGetInterfaceAndReleaseStream(substream->clientStream, GetAudioClientIID(), (LPVOID*)&substream->clientProc);
+       substream->clientStream = NULL;
+       if (hResult != S_OK) 
+       {
+               hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+       }
+
+       return hFirstBadResult;
+
+#else
+       (void)substream;
+       return S_OK;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT UnmarshalStreamComPointers(PaWasapiStream *stream) 
+{
+#ifndef PA_WINRT
+       HRESULT hResult = S_OK;
+       HRESULT hFirstBadResult = S_OK;
+       stream->captureClient = NULL;
+       stream->renderClient = NULL;
+       stream->in.clientProc = NULL;
+       stream->out.clientProc = NULL;
+
+       if (NULL != stream->in.clientParent) 
+       {
+               // SubStream pointers
+               hResult = UnmarshalSubStreamComPointers(&stream->in);
+               if (hResult != S_OK) 
+               {
+                       hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+               }
+
+               // IAudioCaptureClient
+               hResult = CoGetInterfaceAndReleaseStream(stream->captureClientStream, &pa_IID_IAudioCaptureClient, (LPVOID*)&stream->captureClient);
+               stream->captureClientStream = NULL;
+               if (hResult != S_OK) 
+               {
+                       hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+               }
+       }
+
+       if (NULL != stream->out.clientParent) 
+       {
+               // SubStream pointers
+               hResult = UnmarshalSubStreamComPointers(&stream->out);
+               if (hResult != S_OK) 
+               {
+                       hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+               }
+
+               // IAudioRenderClient
+               hResult = CoGetInterfaceAndReleaseStream(stream->renderClientStream, &pa_IID_IAudioRenderClient, (LPVOID*)&stream->renderClient);
+               stream->renderClientStream = NULL;
+               if (hResult != S_OK) 
+               {
+                       hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+               }
+       }
+
+       return hFirstBadResult;
+#else
+       if (stream->in.clientParent != NULL)
+       {
+               stream->in.clientProc = stream->in.clientParent;
+               IAudioClient_AddRef(stream->in.clientParent);
+       }
+
+       if (stream->out.clientParent != NULL)
+       {
+               stream->out.clientProc = stream->out.clientParent;
+               IAudioClient_AddRef(stream->out.clientParent);
+       }
+
+       if (stream->renderClientParent != NULL)
+       {
+               stream->renderClient = stream->renderClientParent;
+               IAudioRenderClient_AddRef(stream->renderClientParent);
+       }
+
+       if (stream->captureClientParent != NULL)
+       {
+               stream->captureClient = stream->captureClientParent;
+               IAudioCaptureClient_AddRef(stream->captureClientParent);
+       }
+
+       return S_OK;
+#endif
+}
+
+// -----------------------------------------------------------------------------------------
+void ReleaseUnmarshaledSubComPointers(PaWasapiSubStream *substream) 
+{
+       SAFE_RELEASE(substream->clientProc);
+}
+
+// -----------------------------------------------------------------------------------------
+void ReleaseUnmarshaledComPointers(PaWasapiStream *stream) 
+{
+       // Release AudioClient services first
+       SAFE_RELEASE(stream->captureClient);
+       SAFE_RELEASE(stream->renderClient);
+
+       // Release AudioClients
+       ReleaseUnmarshaledSubComPointers(&stream->in);
+       ReleaseUnmarshaledSubComPointers(&stream->out);
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT MarshalSubStreamComPointers(PaWasapiSubStream *substream) 
+{
+#ifndef PA_WINRT
+       HRESULT hResult;
+       substream->clientStream = NULL;
+
+       // IAudioClient
+       hResult = CoMarshalInterThreadInterfaceInStream(GetAudioClientIID(), (LPUNKNOWN)substream->clientParent, &substream->clientStream);
+       if (hResult != S_OK)
+               goto marshal_sub_error;
+
+       return hResult;
+
+       // If marshaling error occurred, make sure to release everything.
+marshal_sub_error:
+
+       UnmarshalSubStreamComPointers(substream);
+       ReleaseUnmarshaledSubComPointers(substream);
+       return hResult;
+#else
+       (void)substream;
+       return S_OK;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT MarshalStreamComPointers(PaWasapiStream *stream) 
+{
+#ifndef PA_WINRT
+       HRESULT hResult = S_OK;
+       stream->captureClientStream = NULL;
+       stream->in.clientStream = NULL;
+       stream->renderClientStream = NULL;
+       stream->out.clientStream = NULL;
+
+       if (NULL != stream->in.clientParent) 
+       {
+               // SubStream pointers
+               hResult = MarshalSubStreamComPointers(&stream->in);
+               if (hResult != S_OK) 
+                       goto marshal_error;
+
+               // IAudioCaptureClient
+               hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioCaptureClient, (LPUNKNOWN)stream->captureClientParent, &stream->captureClientStream);
+               if (hResult != S_OK) 
+                       goto marshal_error;
+       }
+
+       if (NULL != stream->out.clientParent) 
+       {
+               // SubStream pointers
+               hResult = MarshalSubStreamComPointers(&stream->out);
+               if (hResult != S_OK) 
+                       goto marshal_error;
+
+               // IAudioRenderClient
+               hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioRenderClient, (LPUNKNOWN)stream->renderClientParent, &stream->renderClientStream);
+               if (hResult != S_OK) 
+                       goto marshal_error;
+       }
+
+       return hResult;
+
+       // If marshaling error occurred, make sure to release everything.
+marshal_error:
+
+       UnmarshalStreamComPointers(stream);
+       ReleaseUnmarshaledComPointers(stream);
+       return hResult;
+#else
+       (void)stream;
+       return S_OK;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError StartStream( PaStream *s )
+{
+       HRESULT hr;
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+       PaError result = paNoError;
+
+       // check if stream is active already
+       if (IsStreamActive(s))
+               return paStreamIsNotStopped;
+
+    PaUtil_ResetBufferProcessor(&stream->bufferProcessor);
+
+       // Cleanup handles (may be necessary if stream was stopped by itself due to error)
+       _StreamCleanup(stream);
+
+       // Create close event
+       if ((stream->hCloseRequest = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) 
+       {
+               result = paInsufficientMemory;
+               goto start_error;
+       }
+
+       // Create thread
+       if (!stream->bBlocking)
+       {
+               // Create thread events
+               stream->hThreadStart = CreateEvent(NULL, TRUE, FALSE, NULL);
+               stream->hThreadExit  = CreateEvent(NULL, TRUE, FALSE, NULL);
+               if ((stream->hThreadStart == NULL) || (stream->hThreadExit == NULL))
+               {
+                       result = paInsufficientMemory;
+                       goto start_error;
+               }
+
+               // Marshal WASAPI interface pointers for safe use in thread created below.
+               if ((hr = MarshalStreamComPointers(stream)) != S_OK) 
+               {
+                       PRINT(("Failed marshaling stream COM pointers."));
+                       result = paUnanticipatedHostError;
+                       goto nonblocking_start_error;
+               }
+
+               if ((stream->in.clientParent  && (stream->in.streamFlags  & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) ||
+                       (stream->out.clientParent && (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)))
+               {
+                       if ((stream->hThread = CREATE_THREAD(ProcThreadEvent)) == NULL) 
+                       {
+                               PRINT(("Failed creating thread: ProcThreadEvent."));
+                               result = paUnanticipatedHostError;
+                               goto nonblocking_start_error;
+                       }
+               }
+               else
+               {
+                       if ((stream->hThread = CREATE_THREAD(ProcThreadPoll)) == NULL) 
+                       {
+                               PRINT(("Failed creating thread: ProcThreadPoll."));
+                               result = paUnanticipatedHostError;
+                               goto nonblocking_start_error;
+                       }
+               }
+
+               // Wait for thread to start
+               if (WaitForSingleObject(stream->hThreadStart, 60*1000) == WAIT_TIMEOUT) 
+               {
+                       PRINT(("Failed starting thread: timeout."));
+                       result = paUnanticipatedHostError;
+                       goto nonblocking_start_error;
+               }
+       }
+       else
+       {
+               // Create blocking operation events (non-signaled event means - blocking operation is pending)
+               if (stream->out.clientParent != NULL) 
+               {
+                       if ((stream->hBlockingOpStreamWR = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) 
+                       {
+                               result = paInsufficientMemory;
+                               goto start_error;
+                       }
+               }
+               if (stream->in.clientParent != NULL) 
+               {
+                       if ((stream->hBlockingOpStreamRD = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) 
+                       {
+                               result = paInsufficientMemory;
+                               goto start_error;
+                       }
+               }
+
+               // Initialize event & start INPUT stream
+               if (stream->in.clientParent != NULL)
+               {
+                       if ((hr = IAudioClient_Start(stream->in.clientParent)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               result = paUnanticipatedHostError;
+                               goto start_error;
+                       }
+               }
+
+               // Initialize event & start OUTPUT stream
+               if (stream->out.clientParent != NULL)
+               {
+                       // Start
+                       if ((hr = IAudioClient_Start(stream->out.clientParent)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               result = paUnanticipatedHostError;
+                               goto start_error;
+                       }
+               }
+
+               // Set parent to working pointers to use shared functions.
+               stream->captureClient  = stream->captureClientParent;
+               stream->renderClient   = stream->renderClientParent;
+               stream->in.clientProc  = stream->in.clientParent;
+               stream->out.clientProc = stream->out.clientParent;
+
+               // Signal: stream running.
+               stream->running = TRUE;
+       }
+
+    return result;
+
+nonblocking_start_error:
+
+       // Set hThreadExit event to prevent blocking during cleanup
+       SetEvent(stream->hThreadExit);
+       UnmarshalStreamComPointers(stream);
+       ReleaseUnmarshaledComPointers(stream);
+
+start_error:
+
+       StopStream(s);
+       return result;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamFinish(PaWasapiStream *stream)
+{
+       // Issue command to thread to stop processing and wait for thread exit
+       if (!stream->bBlocking)
+       {
+               SignalObjectAndWait(stream->hCloseRequest, stream->hThreadExit, INFINITE, FALSE);
+       }
+       else
+       // Blocking mode does not own thread
+       {
+               // Signal close event and wait for each of 2 blocking operations to complete
+               if (stream->out.clientParent)
+                       SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamWR, INFINITE, TRUE);
+               if (stream->out.clientParent)
+                       SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamRD, INFINITE, TRUE);
+
+               // Process stop
+               _StreamOnStop(stream);
+       }
+
+       // Cleanup handles
+       _StreamCleanup(stream);
+
+    stream->running = FALSE;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamCleanup(PaWasapiStream *stream)
+{
+       // Close thread handles to allow restart
+       SAFE_CLOSE(stream->hThread);
+       SAFE_CLOSE(stream->hThreadStart);
+       SAFE_CLOSE(stream->hThreadExit);
+       SAFE_CLOSE(stream->hCloseRequest);
+       SAFE_CLOSE(stream->hBlockingOpStreamRD);
+       SAFE_CLOSE(stream->hBlockingOpStreamWR);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError StopStream( PaStream *s )
+{
+       // Finish stream
+       _StreamFinish((PaWasapiStream *)s);
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError AbortStream( PaStream *s )
+{
+       // Finish stream
+       _StreamFinish((PaWasapiStream *)s);
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamStopped( PaStream *s )
+{
+       return !((PaWasapiStream *)s)->running;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamActive( PaStream *s )
+{
+    return ((PaWasapiStream *)s)->running;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    return PaUtil_GetTime();
+}
+
+// ------------------------------------------------------------------------------------------
+static double GetStreamCpuLoad( PaStream* s )
+{
+       return PaUtil_GetCpuLoad(&((PaWasapiStream *)s)->cpuLoadMeasurer);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ReadStream( PaStream* s, void *_buffer, unsigned long frames )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+       HRESULT hr = S_OK;
+       BYTE *user_buffer = (BYTE *)_buffer;
+       BYTE *wasapi_buffer = NULL;
+       DWORD flags = 0;
+       UINT32 i, available, sleep = 0;
+       unsigned long processed;
+       ThreadIdleScheduler sched;
+
+       // validate
+       if (!stream->running)
+               return paStreamIsStopped;
+       if (stream->captureClient == NULL)
+               return paBadStreamPtr;
+
+       // Notify blocking op has begun
+       ResetEvent(stream->hBlockingOpStreamRD);
+
+       // Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
+       // 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
+       ThreadIdleScheduler_Setup(&sched, 1, 250/* microseconds */);
+
+    // Make a local copy of the user buffer pointer(s), this is necessary
+       // because PaUtil_CopyOutput() advances these pointers every time it is called
+    if (!stream->bufferProcessor.userInputIsInterleaved)
+    {
+               user_buffer = (BYTE *)alloca(sizeof(BYTE *) * stream->bufferProcessor.inputChannelCount);
+        if (user_buffer == NULL)
+            return paInsufficientMemory;
+
+        for (i = 0; i < stream->bufferProcessor.inputChannelCount; ++i)
+            ((BYTE **)user_buffer)[i] = ((BYTE **)_buffer)[i];
+    }
+
+       // Findout if there are tail frames, flush them all before reading hardware
+       if ((available = PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer)) != 0)
+       {
+               ring_buffer_size_t buf1_size = 0, buf2_size = 0, read, desired;
+               void *buf1 = NULL, *buf2 = NULL;
+
+               // Limit desired to amount of requested frames
+               desired = available;
+               if ((UINT32)desired > frames)
+                       desired = frames;
+               
+               // Get pointers to read regions
+               read = PaUtil_GetRingBufferReadRegions(stream->in.tailBuffer, desired, &buf1, &buf1_size, &buf2, &buf2_size);
+
+               if (buf1 != NULL)
+               {
+                       // Register available frames to processor
+                       PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf1_size);
+
+                       // Register host buffer pointer to processor
+                       PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf1, stream->bufferProcessor.inputChannelCount);
+
+                       // Copy user data to host buffer (with conversion if applicable)
+                       processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf1_size);
+                       frames -= processed;
+               }
+
+               if (buf2 != NULL)
+               {
+                       // Register available frames to processor
+                       PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf2_size);
+
+                       // Register host buffer pointer to processor
+                       PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf2, stream->bufferProcessor.inputChannelCount);
+
+                       // Copy user data to host buffer (with conversion if applicable)
+                       processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf2_size);
+                       frames -= processed;
+               }
+
+               // Advance
+               PaUtil_AdvanceRingBufferReadIndex(stream->in.tailBuffer, read);
+       }
+
+       // Read hardware
+       while (frames != 0)
+       {
+               // Check if blocking call must be interrupted
+               if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
+                       break;
+
+               // Get available frames (must be finding out available frames before call to IAudioCaptureClient_GetBuffer
+               // othervise audio glitches will occur inExclusive mode as it seems that WASAPI has some scheduling/
+               // processing problems when such busy polling with IAudioCaptureClient_GetBuffer occurs)
+               if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
+               {
+                       LogHostError(hr);
+                       return paUnanticipatedHostError;
+               }
+
+               // Wait for more frames to become available
+               if (available == 0)
+               {
+                       // Exclusive mode may require latency of 1 millisecond, thus we shall sleep
+                       // around 500 microseconds (emulated) to collect packets in time
+                       if (stream->in.shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE)
+                       {
+                               UINT32 sleep_frames = (frames < stream->in.framesPerHostCallback ? frames : stream->in.framesPerHostCallback);
+
+                               sleep  = GetFramesSleepTime(sleep_frames, stream->in.wavex.Format.nSamplesPerSec);
+                               sleep /= 4; // wait only for 1/4 of the buffer
+
+                               // WASAPI input provides packets, thus expiring packet will result in bad audio
+                               // limit waiting time to 2 seconds (will always work for smallest buffer in Shared)
+                               if (sleep > 2)
+                                       sleep = 2;
+
+                               // Avoid busy waiting, schedule next 1 millesecond wait
+                               if (sleep == 0)
+                                       sleep = ThreadIdleScheduler_NextSleep(&sched);
+                       }
+                       else
+                       {
+                               if ((sleep = ThreadIdleScheduler_NextSleep(&sched)) != 0)
+                               {
+                                       Sleep(sleep);
+                                       sleep = 0;
+                               }
+                       }
+
+                       continue;
+               }
+
+               // Get the available data in the shared buffer.
+               if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &wasapi_buffer, &available, &flags, NULL, NULL)) != S_OK)
+               {
+                       // Buffer size is too small, waiting
+                       if (hr != AUDCLNT_S_BUFFER_EMPTY)
+                       {
+                               LogHostError(hr);
+                               goto end;
+                       }
+
+                       continue;
+               }
+
+               // Register available frames to processor
+        PaUtil_SetInputFrameCount(&stream->bufferProcessor, available);
+
+               // Register host buffer pointer to processor
+        PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, wasapi_buffer, stream->bufferProcessor.inputChannelCount);
+
+               // Copy user data to host buffer (with conversion if applicable)
+               processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, frames);
+               frames -= processed;
+
+               // Save tail into buffer
+               if ((frames == 0) && (available > processed))
+               {
+                       UINT32 bytes_processed = processed * stream->in.wavex.Format.nBlockAlign;
+                       UINT32 frames_to_save  = available - processed;
+
+                       PaUtil_WriteRingBuffer(stream->in.tailBuffer, wasapi_buffer + bytes_processed, frames_to_save);
+               }
+
+               // Release host buffer
+               if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, available)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto end;
+               }
+       }
+
+end:
+
+       // Notify blocking op has ended
+       SetEvent(stream->hBlockingOpStreamRD);
+
+       return (hr != S_OK ? paUnanticipatedHostError : paNoError);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError WriteStream( PaStream* s, const void *_buffer, unsigned long frames )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+       //UINT32 frames;
+       const BYTE *user_buffer = (const BYTE *)_buffer;
+       BYTE *wasapi_buffer;
+       HRESULT hr = S_OK;
+       UINT32 i, available, sleep = 0;
+       unsigned long processed;
+       ThreadIdleScheduler sched;
+
+       // validate
+       if (!stream->running)
+               return paStreamIsStopped;
+       if (stream->renderClient == NULL)
+               return paBadStreamPtr;
+
+       // Notify blocking op has begun
+       ResetEvent(stream->hBlockingOpStreamWR);
+
+       // Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
+       // 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
+       ThreadIdleScheduler_Setup(&sched, 1, 500/* microseconds */);
+
+    // Make a local copy of the user buffer pointer(s), this is necessary
+       // because PaUtil_CopyOutput() advances these pointers every time it is called
+    if (!stream->bufferProcessor.userOutputIsInterleaved)
+    {
+        user_buffer = (const BYTE *)alloca(sizeof(const BYTE *) * stream->bufferProcessor.outputChannelCount);
+        if (user_buffer == NULL)
+            return paInsufficientMemory;
+
+        for (i = 0; i < stream->bufferProcessor.outputChannelCount; ++i)
+            ((const BYTE **)user_buffer)[i] = ((const BYTE **)_buffer)[i];
+    }
+
+       // Blocking (potentially, untill 'frames' are consumed) loop
+       while (frames != 0)
+       {
+               // Check if blocking call must be interrupted
+               if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
+                       break;
+
+               // Get frames available
+               if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto end;
+               }
+
+               // Wait for more frames to become available
+               if (available == 0)
+               {
+                       UINT32 sleep_frames = (frames < stream->out.framesPerHostCallback ? frames : stream->out.framesPerHostCallback);
+
+                       sleep  = GetFramesSleepTime(sleep_frames, stream->out.wavex.Format.nSamplesPerSec);
+                       sleep /= 2; // wait only for half of the buffer
+
+                       // Avoid busy waiting, schedule next 1 millesecond wait
+                       if (sleep == 0)
+                               sleep = ThreadIdleScheduler_NextSleep(&sched);
+
+                       continue;
+               }
+
+               // Keep in 'frmaes' range
+               if (available > frames)
+                       available = frames;
+
+               // Get pointer to host buffer
+               if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, available, &wasapi_buffer)) != S_OK)
+               {
+                       // Buffer size is too big, waiting
+                       if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
+                               continue;
+
+                       LogHostError(hr);
+                       goto end;
+               }
+
+               // Keep waiting again (on Vista it was noticed that WASAPI could SOMETIMES return NULL pointer 
+               // to buffer without returning AUDCLNT_E_BUFFER_TOO_LARGE instead)
+               if (wasapi_buffer == NULL)
+                       continue;
+
+               // Register available frames to processor
+        PaUtil_SetOutputFrameCount(&stream->bufferProcessor, available);
+
+               // Register host buffer pointer to processor
+        PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, 0, wasapi_buffer,        stream->bufferProcessor.outputChannelCount);
+
+               // Copy user data to host buffer (with conversion if applicable), this call will advance
+               // pointer 'user_buffer' to consumed portion of data
+               processed = PaUtil_CopyOutput(&stream->bufferProcessor, (const void **)&user_buffer, frames);
+               frames -= processed;
+
+               // Release host buffer
+               if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, available, 0)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto end;
+               }
+       }
+
+end:
+
+       // Notify blocking op has ended
+       SetEvent(stream->hBlockingOpStreamWR);
+
+       return (hr != S_OK ? paUnanticipatedHostError : paNoError);
+}
+
+unsigned long PaUtil_GetOutputFrameCount( PaUtilBufferProcessor* bp )
+{
+       return bp->hostOutputFrameCount[0];
+}
+
+// ------------------------------------------------------------------------------------------
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+       HRESULT hr;
+       UINT32  available = 0;
+
+       // validate
+       if (!stream->running)
+               return paStreamIsStopped;
+       if (stream->captureClient == NULL)
+               return paBadStreamPtr;
+
+       // available in hardware buffer
+       if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
+       {
+               LogHostError(hr);
+               return paUnanticipatedHostError;
+       }
+
+       // available in software tail buffer
+       available += PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer);
+
+    return available;
+}
+
+// ------------------------------------------------------------------------------------------
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+       HRESULT hr;
+       UINT32  available = 0;
+
+       // validate
+       if (!stream->running)
+               return paStreamIsStopped;
+       if (stream->renderClient == NULL)
+               return paBadStreamPtr;
+
+       if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
+       {
+               LogHostError(hr);
+               return paUnanticipatedHostError;
+       }
+
+       return (signed long)available;
+}
+
+
+// ------------------------------------------------------------------------------------------
+static void WaspiHostProcessingLoop( void *inputBuffer,  long inputFrames,
+                                     void *outputBuffer, long outputFrames,
+                                     void *userData )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)userData;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+       PaStreamCallbackFlags flags = 0;
+    int callbackResult;
+    unsigned long framesProcessed;
+       HRESULT hr;
+       UINT32 pending;
+
+    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+    /*
+               Pa_GetStreamTime:
+            - generate timing information
+            - handle buffer slips
+    */
+       timeInfo.currentTime = PaUtil_GetTime();
+       // Query input latency
+       if (stream->in.clientProc != NULL)
+       {
+               PaTime pending_time;
+               if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, &pending)) == S_OK)
+                       pending_time = (PaTime)pending / (PaTime)stream->in.wavex.Format.nSamplesPerSec;
+               else
+                       pending_time = (PaTime)stream->in.latencySeconds;
+
+               timeInfo.inputBufferAdcTime = timeInfo.currentTime + pending_time;
+       }
+       // Query output current latency
+       if (stream->out.clientProc != NULL)
+       {
+               PaTime pending_time;
+               if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &pending)) == S_OK)
+                       pending_time = (PaTime)pending / (PaTime)stream->out.wavex.Format.nSamplesPerSec;
+               else
+                       pending_time = (PaTime)stream->out.latencySeconds;
+
+               timeInfo.outputBufferDacTime = timeInfo.currentTime + pending_time;
+       }
+
+    /*
+        If you need to byte swap or shift inputBuffer to convert it into a
+        portaudio format, do it here.
+    */
+
+    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, flags );
+
+    /*
+        depending on whether the host buffers are interleaved, non-interleaved
+        or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),
+        PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.
+    */
+
+    if (stream->bufferProcessor.inputChannelCount > 0)
+    {
+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames );
+        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
+            0, /* first channel of inputBuffer is channel 0 */
+            inputBuffer,
+            0 ); /* 0 - use inputChannelCount passed to init buffer processor */
+    }
+
+    if (stream->bufferProcessor.outputChannelCount > 0)
+    {
+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames);
+        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
+            0, /* first channel of outputBuffer is channel 0 */
+            outputBuffer,
+            0 ); /* 0 - use outputChannelCount passed to init buffer processor */
+    }
+
+    /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()
+        in general you would pass paContinue for normal operation, and
+        paComplete to drain the buffer processor's internal output buffer.
+        You can check whether the buffer processor's output buffer is empty
+        using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )
+    */
+    callbackResult = paContinue;
+    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+
+    /*
+        If you need to byte swap or shift outputBuffer to convert it to
+        host format, do it here.
+    */
+
+       PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+    if (callbackResult == paContinue)
+    {
+        /* nothing special to do */
+    }
+    else
+       if (callbackResult == paAbort)
+    {
+               // stop stream
+        SetEvent(stream->hCloseRequest);
+    }
+    else
+    {
+               // stop stream
+        SetEvent(stream->hCloseRequest);
+    }
+}
+
+// ------------------------------------------------------------------------------------------
+HANDLE MMCSS_activate(const char *name)
+{
+#ifndef PA_WINRT
+    DWORD task_idx = 0;
+    HANDLE hTask = pAvSetMmThreadCharacteristics(name, &task_idx);
+    if (hTask == NULL)
+       {
+        PRINT(("WASAPI: AvSetMmThreadCharacteristics failed!\n"));
+    }
+
+    /*BOOL priority_ok = pAvSetMmThreadPriority(hTask, AVRT_PRIORITY_NORMAL);
+    if (priority_ok == FALSE)
+       {
+        PRINT(("WASAPI: AvSetMmThreadPriority failed!\n"));
+    }*/
+
+       // debug
+    {
+        int    cur_priority              = GetThreadPriority(GetCurrentThread());
+        DWORD  cur_priority_class = GetPriorityClass(GetCurrentProcess());
+               PRINT(("WASAPI: thread[ priority-0x%X class-0x%X ]\n", cur_priority, cur_priority_class));
+    }
+
+       return hTask;
+#else
+       (void)name;
+       return NULL;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+void MMCSS_deactivate(HANDLE hTask)
+{
+       if (!hTask)
+               return;
+
+#ifndef PA_WINRT
+       if (pAvRevertMmThreadCharacteristics(hTask) == FALSE)
+       {
+        PRINT(("WASAPI: AvRevertMmThreadCharacteristics failed!\n"));
+    }
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_ThreadPriorityBoost(void **hTask, PaWasapiThreadPriority nPriorityClass)
+{
+       static const char *mmcs_name[] =
+       {
+               NULL,
+               "Audio",
+               "Capture",
+               "Distribution",
+               "Games",
+               "Playback",
+               "Pro Audio",
+               "Window Manager"
+       };
+       HANDLE task;
+
+       if (hTask == NULL)
+               return paUnanticipatedHostError;
+
+       if ((UINT32)nPriorityClass >= STATIC_ARRAY_SIZE(mmcs_name))
+               return paUnanticipatedHostError;
+
+       task = MMCSS_activate(mmcs_name[nPriorityClass]);
+       if (task == NULL)
+               return paUnanticipatedHostError;
+
+       (*hTask) = task;
+       return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_ThreadPriorityRevert(void *hTask)
+{
+       if (hTask == NULL)
+               return paUnanticipatedHostError;
+
+       MMCSS_deactivate((HANDLE)hTask);
+
+       return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+// Described at:
+// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
+
+PaError PaWasapi_GetJackCount(PaDeviceIndex nDevice, int *jcount)
+{
+#ifndef PA_WINRT
+       PaError ret;
+       HRESULT hr = S_OK;
+       PaDeviceIndex index;
+    IDeviceTopology *pDeviceTopology = NULL;
+    IConnector *pConnFrom = NULL;
+    IConnector *pConnTo = NULL;
+    IPart *pPart = NULL;
+    IKsJackDescription *pJackDesc = NULL;
+       UINT jackCount = 0;
+
+       PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+       if (paWasapi == NULL)
+               return paNotInitialized;
+
+       // Get device index.
+       ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+       // Validate index.
+       if ((UINT32)index >= paWasapi->deviceCount)
+               return paInvalidDevice;
+
+       // Get the endpoint device's IDeviceTopology interface.
+       hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
+               CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
+       IF_FAILED_JUMP(hr, error);
+
+    // The device topology for an endpoint device always contains just one connector (connector number 0).
+       hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
+       IF_FAILED_JUMP(hr, error);
+
+    // Step across the connection to the jack on the adapter.
+       hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
+    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
+    {
+        // The adapter device is not currently active.
+        hr = E_NOINTERFACE;
+    }
+       IF_FAILED_JUMP(hr, error);
+
+       // Get the connector's IPart interface.
+       hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
+       IF_FAILED_JUMP(hr, error);
+
+       // Activate the connector's IKsJackDescription interface.
+       hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
+       IF_FAILED_JUMP(hr, error);
+
+       // Return jack count for this device.
+       hr = IKsJackDescription_GetJackCount(pJackDesc, &jackCount);
+       IF_FAILED_JUMP(hr, error);
+
+       // Set.
+       (*jcount) = jackCount;
+
+       // Ok.
+       ret = paNoError;
+
+error:
+
+       SAFE_RELEASE(pDeviceTopology);
+       SAFE_RELEASE(pConnFrom);
+       SAFE_RELEASE(pConnTo);
+       SAFE_RELEASE(pPart);
+       SAFE_RELEASE(pJackDesc);
+
+       LogHostError(hr);
+       return paNoError;
+#else
+       (void)nDevice;
+       (void)jcount;
+       return paUnanticipatedHostError;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+#ifndef PA_WINRT
+static PaWasapiJackConnectionType ConvertJackConnectionTypeWASAPIToPA(int connType)
+{
+       switch (connType)
+       {
+               case eConnTypeUnknown:                  return eJackConnTypeUnknown;
+#ifdef _KS_
+               case eConnType3Point5mm:                return eJackConnType3Point5mm;
+#else
+               case eConnTypeEighth:               return eJackConnType3Point5mm;
+#endif
+               case eConnTypeQuarter:                  return eJackConnTypeQuarter;
+               case eConnTypeAtapiInternal:    return eJackConnTypeAtapiInternal;
+               case eConnTypeRCA:                              return eJackConnTypeRCA;
+               case eConnTypeOptical:                  return eJackConnTypeOptical;
+               case eConnTypeOtherDigital:             return eJackConnTypeOtherDigital;
+               case eConnTypeOtherAnalog:              return eJackConnTypeOtherAnalog;
+               case eConnTypeMultichannelAnalogDIN: return eJackConnTypeMultichannelAnalogDIN;
+               case eConnTypeXlrProfessional:  return eJackConnTypeXlrProfessional;
+               case eConnTypeRJ11Modem:                return eJackConnTypeRJ11Modem;
+               case eConnTypeCombination:              return eJackConnTypeCombination;
+       }
+       return eJackConnTypeUnknown;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+#ifndef PA_WINRT
+static PaWasapiJackGeoLocation ConvertJackGeoLocationWASAPIToPA(int geoLoc)
+{
+       switch (geoLoc)
+       {
+       case eGeoLocRear:                               return eJackGeoLocRear;
+       case eGeoLocFront:                              return eJackGeoLocFront;
+       case eGeoLocLeft:                               return eJackGeoLocLeft;
+       case eGeoLocRight:                              return eJackGeoLocRight;
+       case eGeoLocTop:                                return eJackGeoLocTop;
+       case eGeoLocBottom:                             return eJackGeoLocBottom;
+#ifdef _KS_
+       case eGeoLocRearPanel:                  return eJackGeoLocRearPanel;
+#else
+       case eGeoLocRearOPanel:         return eJackGeoLocRearPanel;
+#endif
+       case eGeoLocRiser:                              return eJackGeoLocRiser;
+       case eGeoLocInsideMobileLid:    return eJackGeoLocInsideMobileLid;
+       case eGeoLocDrivebay:                   return eJackGeoLocDrivebay;
+       case eGeoLocHDMI:                               return eJackGeoLocHDMI;
+       case eGeoLocOutsideMobileLid:   return eJackGeoLocOutsideMobileLid;
+       case eGeoLocATAPI:                              return eJackGeoLocATAPI;
+       }
+       return eJackGeoLocUnk;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+#ifndef PA_WINRT
+static PaWasapiJackGenLocation ConvertJackGenLocationWASAPIToPA(int genLoc)
+{
+       switch (genLoc)
+       {
+       case eGenLocPrimaryBox: return eJackGenLocPrimaryBox;
+       case eGenLocInternal:   return eJackGenLocInternal;
+#ifdef _KS_
+       case eGenLocSeparate:   return eJackGenLocSeparate;
+#else
+       case eGenLocSeperate:   return eJackGenLocSeparate;
+#endif
+       case eGenLocOther:              return eJackGenLocOther;
+       }
+       return eJackGenLocPrimaryBox;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+#ifndef PA_WINRT
+static PaWasapiJackPortConnection ConvertJackPortConnectionWASAPIToPA(int portConn)
+{
+       switch (portConn)
+       {
+       case ePortConnJack:                                     return eJackPortConnJack;
+       case ePortConnIntegratedDevice:         return eJackPortConnIntegratedDevice;
+       case ePortConnBothIntegratedAndJack:return eJackPortConnBothIntegratedAndJack;
+       case ePortConnUnknown:                          return eJackPortConnUnknown;
+       }
+       return eJackPortConnJack;
+}
+#endif
+
+// ------------------------------------------------------------------------------------------
+// Described at:
+// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
+
+PaError PaWasapi_GetJackDescription(PaDeviceIndex nDevice, int jindex, PaWasapiJackDescription *pJackDescription)
+{
+#ifndef PA_WINRT
+       PaError ret;
+       HRESULT hr = S_OK;
+       PaDeviceIndex index;
+    IDeviceTopology *pDeviceTopology = NULL;
+    IConnector *pConnFrom = NULL;
+    IConnector *pConnTo = NULL;
+    IPart *pPart = NULL;
+    IKsJackDescription *pJackDesc = NULL;
+       KSJACK_DESCRIPTION jack = { 0 };
+
+       PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+       if (paWasapi == NULL)
+               return paNotInitialized;
+
+       // Get device index.
+       ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+       // Validate index.
+       if ((UINT32)index >= paWasapi->deviceCount)
+               return paInvalidDevice;
+
+       // Get the endpoint device's IDeviceTopology interface.
+       hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
+               CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
+       IF_FAILED_JUMP(hr, error);
+
+    // The device topology for an endpoint device always contains just one connector (connector number 0).
+       hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
+       IF_FAILED_JUMP(hr, error);
+
+    // Step across the connection to the jack on the adapter.
+       hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
+    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
+    {
+        // The adapter device is not currently active.
+        hr = E_NOINTERFACE;
+    }
+       IF_FAILED_JUMP(hr, error);
+
+       // Get the connector's IPart interface.
+       hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
+       IF_FAILED_JUMP(hr, error);
+
+       // Activate the connector's IKsJackDescription interface.
+       hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
+       IF_FAILED_JUMP(hr, error);
+
+       // Test to return jack description struct for index 0.
+       hr = IKsJackDescription_GetJackDescription(pJackDesc, jindex, &jack);
+       IF_FAILED_JUMP(hr, error);
+
+       // Convert WASAPI values to PA format.
+       pJackDescription->channelMapping = jack.ChannelMapping;
+       pJackDescription->color          = jack.Color;
+       pJackDescription->connectionType = ConvertJackConnectionTypeWASAPIToPA(jack.ConnectionType);
+       pJackDescription->genLocation    = ConvertJackGenLocationWASAPIToPA(jack.GenLocation);
+       pJackDescription->geoLocation    = ConvertJackGeoLocationWASAPIToPA(jack.GeoLocation);
+       pJackDescription->isConnected    = jack.IsConnected;
+       pJackDescription->portConnection = ConvertJackPortConnectionWASAPIToPA(jack.PortConnection);
+
+       // Ok.
+       ret = paNoError;
+
+error:
+
+       SAFE_RELEASE(pDeviceTopology);
+       SAFE_RELEASE(pConnFrom);
+       SAFE_RELEASE(pConnTo);
+       SAFE_RELEASE(pPart);
+       SAFE_RELEASE(pJackDesc);
+
+       LogHostError(hr);
+       return ret;
+
+#else
+       (void)nDevice;
+       (void)jindex;
+       (void)pJackDescription;
+       return paUnanticipatedHostError;
+#endif
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
+{
+       HRESULT hr;
+       UINT32 frames  = stream->out.framesPerHostCallback,
+                  padding = 0;
+
+       (*available) = 0;
+
+       // get read position
+       if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding)) != S_OK)
+               return LogHostError(hr);
+
+       // get available
+       frames -= padding;
+
+       // set
+       (*available) = frames;
+       return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
+{
+       HRESULT hr;
+
+       (*available) = 0;
+
+       // GetCurrentPadding() has opposite meaning to Output stream 
+       if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, available)) != S_OK)
+               return LogHostError(hr);
+
+       return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT ProcessOutputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor, UINT32 frames)
+{
+       HRESULT hr;
+       BYTE *data = NULL;
+
+       // Get buffer
+       if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
+       {
+               if (stream->out.shareMode == AUDCLNT_SHAREMODE_SHARED)
+               {
+                       // Using GetCurrentPadding to overcome AUDCLNT_E_BUFFER_TOO_LARGE in
+                       // shared mode results in no sound in Event-driven mode (MSDN does not
+                       // document this, or is it WASAPI bug?), thus we better
+                       // try to acquire buffer next time when GetBuffer allows to do so.
+#if 0
+                       // Get Read position
+                       UINT32 padding = 0;
+                       hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding);
+                       if (hr != S_OK)
+                               return LogHostError(hr);
+
+                       // Get frames to write
+                       frames -= padding;
+                       if (frames == 0)
+                               return S_OK;
+
+                       if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
+                               return LogHostError(hr);
+#else
+                       if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
+                               return S_OK; // be silent in shared mode, try again next time
+#endif
+               }
+               else
+                       return LogHostError(hr);
+       }
+
+       // Process data
+       if (stream->out.monoMixer != NULL)
+       {
+               // expand buffer
+               UINT32 mono_frames_size = frames * (stream->out.wavex.Format.wBitsPerSample / 8);
+               if (mono_frames_size > stream->out.monoBufferSize)
+                       stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+
+               // process
+               processor[S_OUTPUT].processor(NULL, 0, (BYTE *)stream->out.monoBuffer, frames, processor[S_OUTPUT].userData);
+
+               // mix 1 to 2 channels
+               stream->out.monoMixer(data, stream->out.monoBuffer, frames);
+       }
+       else
+       {
+               processor[S_OUTPUT].processor(NULL, 0, data, frames, processor[S_OUTPUT].userData);
+       }
+
+       // Release buffer
+       if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, frames, 0)) != S_OK)
+               LogHostError(hr);
+
+       return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT ProcessInputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor)
+{
+       HRESULT hr = S_OK;
+       UINT32 frames;
+       BYTE *data = NULL;
+       DWORD flags = 0;
+
+       for (;;)
+       {
+               // Check if blocking call must be interrupted
+               if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
+                       break;
+
+               // Findout if any frames available
+               frames = 0;
+               if ((hr = _PollGetInputFramesAvailable(stream, &frames)) != S_OK)
+                       return hr;
+
+               // Empty/consumed buffer
+               if (frames == 0)
+                       break;
+
+               // Get the available data in the shared buffer.
+               if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &data, &frames, &flags, NULL, NULL)) != S_OK)
+               {
+                       if (hr == AUDCLNT_S_BUFFER_EMPTY)
+                       {
+                               hr = S_OK;
+                               break; // Empty/consumed buffer
+                       }
+
+                       return LogHostError(hr);
+                       break;
+               }
+
+               // Detect silence
+               // if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
+               //      data = NULL;
+
+               // Process data
+               if (stream->in.monoMixer != NULL)
+               {
+                       // expand buffer
+                       UINT32 mono_frames_size = frames * (stream->in.wavex.Format.wBitsPerSample / 8);
+                       if (mono_frames_size > stream->in.monoBufferSize)
+                               stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+
+                       // mix 1 to 2 channels
+                       stream->in.monoMixer(stream->in.monoBuffer, data, frames);
+
+                       // process
+                       processor[S_INPUT].processor((BYTE *)stream->in.monoBuffer, frames, NULL, 0, processor[S_INPUT].userData);
+               }
+               else
+               {
+                       processor[S_INPUT].processor(data, frames, NULL, 0, processor[S_INPUT].userData);
+               }
+
+               // Release buffer
+               if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, frames)) != S_OK)
+                       return LogHostError(hr);
+
+               //break;
+       }
+
+       return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamOnStop(PaWasapiStream *stream)
+{
+       // Stop INPUT/OUTPUT clients
+       if (!stream->bBlocking) 
+       {
+               if (stream->in.clientProc != NULL)
+                       IAudioClient_Stop(stream->in.clientProc);
+               if (stream->out.clientProc != NULL)
+                       IAudioClient_Stop(stream->out.clientProc);
+       } 
+       else 
+       {
+               if (stream->in.clientParent != NULL)
+                       IAudioClient_Stop(stream->in.clientParent);
+               if (stream->out.clientParent != NULL)
+                       IAudioClient_Stop(stream->out.clientParent);
+       }
+
+       // Restore thread priority
+       if (stream->hAvTask != NULL)
+       {
+               PaWasapi_ThreadPriorityRevert(stream->hAvTask);
+               stream->hAvTask = NULL;
+       }
+
+    // Notify
+    if (stream->streamRepresentation.streamFinishedCallback != NULL)
+        stream->streamRepresentation.streamFinishedCallback(stream->streamRepresentation.userData);
+}
+
+// ------------------------------------------------------------------------------------------
+PA_THREAD_FUNC ProcThreadEvent(void *param)
+{
+    PaWasapiHostProcessor processor[S_COUNT];
+       HRESULT hr;
+       DWORD dwResult;
+    PaWasapiStream *stream = (PaWasapiStream *)param;
+       PaWasapiHostProcessor defaultProcessor;
+       BOOL set_event[S_COUNT] = { FALSE, FALSE };
+       BOOL bWaitAllEvents = FALSE;
+       BOOL bThreadComInitialized = FALSE;
+
+       /*
+       If COM is already initialized CoInitialize will either return
+       FALSE, or RPC_E_CHANGED_MODE if it was initialized in a different
+       threading mode. In either case we shouldn't consider it an error
+       but we need to be careful to not call CoUninitialize() if 
+       RPC_E_CHANGED_MODE was returned.
+       */
+       hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+       if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
+       {
+               PRINT(("WASAPI: failed ProcThreadEvent CoInitialize"));
+               return (UINT32)paUnanticipatedHostError;
+       }
+       if (hr != RPC_E_CHANGED_MODE)
+               bThreadComInitialized = TRUE;
+
+       // Unmarshal stream pointers for safe COM operation
+       hr = UnmarshalStreamComPointers(stream);
+       if (hr != S_OK) {
+               PRINT(("Error unmarshaling stream COM pointers. HRESULT: %i\n", hr));
+               goto thread_end;
+       }
+
+       // Waiting on all events in case of Full-Duplex/Exclusive mode.
+       if ((stream->in.clientProc != NULL) && (stream->out.clientProc != NULL))
+       {
+               bWaitAllEvents = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) &&
+                       (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE);
+       }
+
+    // Setup data processors
+    defaultProcessor.processor = WaspiHostProcessingLoop;
+    defaultProcessor.userData  = stream;
+    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
+    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
+
+       // Boost thread priority
+       PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
+
+       // Create events
+       if (stream->event[S_OUTPUT] == NULL)
+       {
+               stream->event[S_OUTPUT] = CreateEvent(NULL, FALSE, FALSE, NULL);
+               set_event[S_OUTPUT] = TRUE;
+       }
+       if (stream->event[S_INPUT] == NULL)
+       {
+               stream->event[S_INPUT]  = CreateEvent(NULL, FALSE, FALSE, NULL);
+               set_event[S_INPUT] = TRUE;
+       }
+       if ((stream->event[S_OUTPUT] == NULL) || (stream->event[S_INPUT] == NULL))
+       {
+               PRINT(("WASAPI Thread: failed creating Input/Output event handle\n"));
+               goto thread_error;
+       }
+
+       // Initialize event & start INPUT stream
+       if (stream->in.clientProc)
+       {
+               // Create & set handle
+               if (set_event[S_INPUT])
+               {
+                       if ((hr = IAudioClient_SetEventHandle(stream->in.clientProc, stream->event[S_INPUT])) != S_OK)
+                       {
+                               LogHostError(hr);
+                               goto thread_error;
+                       }
+               }
+
+               // Start
+               if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto thread_error;
+               }
+       }
+
+       // Initialize event & start OUTPUT stream
+       if (stream->out.clientProc)
+       {
+               // Create & set handle
+               if (set_event[S_OUTPUT])
+               {
+                       if ((hr = IAudioClient_SetEventHandle(stream->out.clientProc, stream->event[S_OUTPUT])) != S_OK)
+                       {
+                               LogHostError(hr);
+                               goto thread_error;
+                       }
+               }
+
+               // Preload buffer before start
+               if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto thread_error;
+               }
+
+               // Start
+               if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto thread_error;
+               }
+
+       }
+
+       // Signal: stream running
+       stream->running = TRUE;
+
+       // Notify: thread started
+       SetEvent(stream->hThreadStart);
+
+       // Processing Loop
+       for (;;)
+    {
+           // 10 sec timeout (on timeout stream will auto-stop when processed by WAIT_TIMEOUT case)
+        dwResult = WaitForMultipleObjects(S_COUNT, stream->event, bWaitAllEvents, 10*1000);
+
+               // Check for close event (after wait for buffers to avoid any calls to user
+               // callback when hCloseRequest was set)
+               if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
+                       break;
+
+               // Process S_INPUT/S_OUTPUT
+               switch (dwResult)
+               {
+               case WAIT_TIMEOUT: {
+                       PRINT(("WASAPI Thread: WAIT_TIMEOUT - probably bad audio driver or Vista x64 bug: use paWinWasapiPolling instead\n"));
+                       goto thread_end;
+                       break; }
+
+               // Input stream
+               case WAIT_OBJECT_0 + S_INPUT: {
+
+            if (stream->captureClient == NULL)
+                break;
+
+                       if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               goto thread_error;
+                       }
+
+                       break; }
+
+               // Output stream
+               case WAIT_OBJECT_0 + S_OUTPUT: {
+
+            if (stream->renderClient == NULL)
+                break;
+
+                       if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               goto thread_error;
+                       }
+
+                       break; }
+               }
+       }
+
+thread_end:
+
+       // Process stop
+       _StreamOnStop(stream);
+
+       // Release unmarshaled COM pointers
+       ReleaseUnmarshaledComPointers(stream);
+
+       // Cleanup COM for this thread
+       if (bThreadComInitialized == TRUE)
+               CoUninitialize();
+
+       // Notify: not running
+       stream->running = FALSE;
+
+       // Notify: thread exited
+       SetEvent(stream->hThreadExit);
+
+       return 0;
+
+thread_error:
+
+       // Prevent deadlocking in Pa_StreamStart
+       SetEvent(stream->hThreadStart);
+
+       // Exit
+       goto thread_end;
+}
+
+// ------------------------------------------------------------------------------------------
+PA_THREAD_FUNC ProcThreadPoll(void *param)
+{
+    PaWasapiHostProcessor processor[S_COUNT];
+       HRESULT hr;
+    PaWasapiStream *stream = (PaWasapiStream *)param;
+       PaWasapiHostProcessor defaultProcessor;
+       INT32 i;
+       ThreadIdleScheduler scheduler;
+
+       // Calculate the actual duration of the allocated buffer.
+       DWORD sleep_ms     = 0;
+       DWORD sleep_ms_in;
+       DWORD sleep_ms_out;
+
+       BOOL bThreadComInitialized = FALSE;
+
+       /*
+       If COM is already initialized CoInitialize will either return
+       FALSE, or RPC_E_CHANGED_MODE if it was initialized in a different
+       threading mode. In either case we shouldn't consider it an error
+       but we need to be careful to not call CoUninitialize() if 
+       RPC_E_CHANGED_MODE was returned.
+       */
+       hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+       if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
+       {
+               PRINT(("WASAPI: failed ProcThreadPoll CoInitialize"));
+               return (UINT32)paUnanticipatedHostError;
+       }
+       if (hr != RPC_E_CHANGED_MODE)
+               bThreadComInitialized = TRUE;
+
+       // Unmarshal stream pointers for safe COM operation
+       hr = UnmarshalStreamComPointers(stream);
+       if (hr != S_OK) 
+       {
+               PRINT(("Error unmarshaling stream COM pointers. HRESULT: %i\n", hr));
+               return 0;
+       }
+
+       // Calculate timeout for next polling attempt.
+       sleep_ms_in  = GetFramesSleepTime(stream->in.framesPerHostCallback/WASAPI_PACKETS_PER_INPUT_BUFFER, stream->in.wavex.Format.nSamplesPerSec);
+       sleep_ms_out = GetFramesSleepTime(stream->out.framesPerBuffer, stream->out.wavex.Format.nSamplesPerSec);
+
+       // WASAPI Input packets tend to expire very easily, let's limit sleep time to 2 milliseconds
+       // for all cases. Please propose better solution if any.
+       if (sleep_ms_in > 2)
+               sleep_ms_in = 2;
+
+       // Adjust polling time for non-paUtilFixedHostBufferSize. Input stream is not adjustable as it is being
+       // polled according its packet length.
+       if (stream->bufferMode != paUtilFixedHostBufferSize)
+       {
+               //sleep_ms_in = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->in.wavex.Format.nSamplesPerSec);
+               sleep_ms_out = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->out.wavex.Format.nSamplesPerSec);
+       }
+
+       // Choose smallest
+       if ((sleep_ms_in != 0) && (sleep_ms_out != 0))
+               sleep_ms = min(sleep_ms_in, sleep_ms_out);
+       else
+       {
+               sleep_ms = (sleep_ms_in ? sleep_ms_in : sleep_ms_out);
+       }
+       // Make sure not 0, othervise use ThreadIdleScheduler
+       if (sleep_ms == 0)
+       {
+               sleep_ms_in  = GetFramesSleepTimeMicroseconds(stream->in.framesPerHostCallback/WASAPI_PACKETS_PER_INPUT_BUFFER, stream->in.wavex.Format.nSamplesPerSec);
+               sleep_ms_out = GetFramesSleepTimeMicroseconds(stream->bufferProcessor.framesPerUserBuffer, stream->out.wavex.Format.nSamplesPerSec);
+
+               // Choose smallest
+               if ((sleep_ms_in != 0) && (sleep_ms_out != 0))
+                       sleep_ms = min(sleep_ms_in, sleep_ms_out);
+               else
+               {
+                       sleep_ms = (sleep_ms_in ? sleep_ms_in : sleep_ms_out);
+               }
+
+               // Setup thread sleep scheduler
+               ThreadIdleScheduler_Setup(&scheduler, 1, sleep_ms/* microseconds here */);
+               sleep_ms = 0;
+       }
+
+    // Setup data processors
+    defaultProcessor.processor = WaspiHostProcessingLoop;
+    defaultProcessor.userData  = stream;
+    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
+    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
+
+       // Boost thread priority
+       PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
+
+       // Initialize event & start INPUT stream
+       if (stream->in.clientProc)
+       {
+               if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto thread_error;
+               }
+       }
+
+       // Initialize event & start OUTPUT stream
+       if (stream->out.clientProc)
+       {
+               // Preload buffer (obligatory, othervise ->Start() will fail), avoid processing
+               // when in full-duplex mode as it requires input processing as well
+               if (!PA_WASAPI__IS_FULLDUPLEX(stream))
+               {
+                       UINT32 frames = 0;
+                       if ((hr = _PollGetOutputFramesAvailable(stream, &frames)) == S_OK)
+            {
+                               if (stream->bufferMode == paUtilFixedHostBufferSize)
+                               {
+                                       if (frames >= stream->out.framesPerBuffer)
+                                       {
+                                               frames = stream->out.framesPerBuffer;
+
+                                               if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+                                               {
+                                                       LogHostError(hr); // not fatal, just log
+                                               }
+                                       }
+                               }
+                               else
+                               {
+                                       if (frames != 0)
+                                       {
+                                               if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+                                               {
+                                                       LogHostError(hr); // not fatal, just log
+                                               }
+                                       }
+                               }
+            }
+            else
+                       {
+                               LogHostError(hr); // not fatal, just log
+                       }
+               }
+
+               // Start
+               if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
+               {
+                       LogHostError(hr);
+                       goto thread_error;
+               }
+       }
+
+       // Signal: stream running
+       stream->running = TRUE;
+
+       // Notify: thread started
+       SetEvent(stream->hThreadStart);
+
+       if (!PA_WASAPI__IS_FULLDUPLEX(stream))
+       {
+               // Processing Loop
+               UINT32 next_sleep = sleep_ms;
+               while (WaitForSingleObject(stream->hCloseRequest, next_sleep) == WAIT_TIMEOUT)
+               {
+                       // Get next sleep time
+                       if (sleep_ms == 0)
+                       {
+                               next_sleep = ThreadIdleScheduler_NextSleep(&scheduler);
+                       }
+
+                       for (i = 0; i < S_COUNT; ++i)
+                       {
+                               // Process S_INPUT/S_OUTPUT
+                               switch (i)
+                               {
+                               // Input stream
+                               case S_INPUT: {
+
+                                       if (stream->captureClient == NULL)
+                                               break;
+
+                                       if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
+                                       {
+                                               LogHostError(hr);
+                                               goto thread_error;
+                                       }
+
+                                       break; }
+
+                               // Output stream
+                               case S_OUTPUT: {
+
+                                       UINT32 frames;
+                                       if (stream->renderClient == NULL)
+                                               break;
+
+                                       // get available frames
+                                       if ((hr = _PollGetOutputFramesAvailable(stream, &frames)) != S_OK)
+                                       {
+                                               LogHostError(hr);
+                                               goto thread_error;
+                                       }
+
+                                       // output
+                                       if (stream->bufferMode == paUtilFixedHostBufferSize)
+                                       {
+                                               while (frames >= stream->out.framesPerBuffer)
+                                               {
+                                                       if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+                                                       {
+                                                               LogHostError(hr);
+                                                               goto thread_error;
+                                                       }
+
+                                                       frames -= stream->out.framesPerBuffer;
+                                               }
+                                       }
+                                       else
+                                       {
+                                               if (frames != 0)
+                                               {
+                                                       if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+                                                       {
+                                                               LogHostError(hr);
+                                                               goto thread_error;
+                                                       }
+                                               }
+                                       }
+
+                                       break; }
+                               }
+                       }
+               }
+       }
+       else
+       {
+#if 0
+               // Processing Loop
+               while (WaitForSingleObject(stream->hCloseRequest, 1) == WAIT_TIMEOUT)
+               {
+                       UINT32 i_frames = 0, i_processed = 0;
+                       BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
+                       DWORD i_flags = 0;
+                       UINT32 o_frames = 0;
+
+                       // get host input buffer
+                       if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
+                       {
+                               if (hr == AUDCLNT_S_BUFFER_EMPTY)
+                                       continue; // no data in capture buffer
+
+                               LogHostError(hr);
+                               break;
+                       }
+
+                       // get available frames
+                       if ((hr = _PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
+                       {
+                               // release input buffer
+                               IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+
+                               LogHostError(hr);
+                               break;
+                       }
+
+                       // process equal ammount of frames
+                       if (o_frames >= i_frames)
+                       {
+                               // process input ammount of frames
+                               UINT32 o_processed = i_frames;
+
+                               // get host output buffer
+                               if ((hr = IAudioRenderClient_GetBuffer(stream->procRCClient, o_processed, &o_data)) == S_OK)
+                               {
+                                       // processed amount of i_frames
+                                       i_processed = i_frames;
+                                       o_data_host = o_data;
+
+                                       // convert output mono
+                                       if (stream->out.monoMixer)
+                                       {
+                                               UINT32 mono_frames_size = o_processed * (stream->out.wavex.Format.wBitsPerSample / 8);
+                                               // expand buffer
+                                               if (mono_frames_size > stream->out.monoBufferSize)
+                                               {
+                                                       stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+                                                       if (stream->out.monoBuffer == NULL)
+                                                       {
+                                                               // release input buffer
+                                                               IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+                                                               // release output buffer
+                                                               IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+                                                               LogPaError(paInsufficientMemory);
+                                                               break;
+                                                       }
+                                               }
+
+                                               // replace buffer pointer
+                                               o_data = (BYTE *)stream->out.monoBuffer;
+                                       }
+
+                                       // convert input mono
+                                       if (stream->in.monoMixer)
+                                       {
+                                               UINT32 mono_frames_size = i_processed * (stream->in.wavex.Format.wBitsPerSample / 8);
+                                               // expand buffer
+                                               if (mono_frames_size > stream->in.monoBufferSize)
+                                               {
+                                                       stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+                                                       if (stream->in.monoBuffer == NULL)
+                                                       {
+                                                               // release input buffer
+                                                               IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+                                                               // release output buffer
+                                                               IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+                                                               LogPaError(paInsufficientMemory);
+                                                               break;
+                                                       }
+                                               }
+
+                                               // mix 2 to 1 input channels
+                                               stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
+
+                                               // replace buffer pointer
+                                               i_data = (BYTE *)stream->in.monoBuffer;
+                                       }
+
+                                       // process
+                                       processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
+
+                                       // mix 1 to 2 output channels
+                                       if (stream->out.monoBuffer)
+                                               stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
+
+                                       // release host output buffer
+                                       if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, o_processed, 0)) != S_OK)
+                                               LogHostError(hr);
+                               }
+                               else
+                               {
+                                       if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
+                                               LogHostError(hr); // be silent in shared mode, try again next time
+                               }
+                       }
+
+                       // release host input buffer
+                       if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, i_processed)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               break;
+                       }
+               }
+#else
+               // Processing Loop
+               UINT32 next_sleep = sleep_ms;
+               while (WaitForSingleObject(stream->hCloseRequest, next_sleep) == WAIT_TIMEOUT)
+               {
+                       UINT32 i_frames = 0, i_processed = 0;
+                       BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
+                       DWORD i_flags = 0;
+                       UINT32 o_frames = 0;
+
+                       // Get next sleep time
+                       if (sleep_ms == 0)
+                       {
+                               next_sleep = ThreadIdleScheduler_NextSleep(&scheduler);
+                       }
+
+                       // get available frames
+                       if ((hr = _PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
+                       {
+                               LogHostError(hr);
+                               break;
+                       }
+
+                       while (o_frames != 0)
+                       {
+                               // get host input buffer
+                               if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
+                               {
+                                       if (hr == AUDCLNT_S_BUFFER_EMPTY)
+                                               break; // no data in capture buffer
+
+                                       LogHostError(hr);
+                                       break;
+                               }
+
+                               // process equal ammount of frames
+                               if (o_frames >= i_frames)
+                               {
+                                       // process input ammount of frames
+                                       UINT32 o_processed = i_frames;
+
+                                       // get host output buffer
+                                       if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, o_processed, &o_data)) == S_OK)
+                                       {
+                                               // processed amount of i_frames
+                                               i_processed = i_frames;
+                                               o_data_host = o_data;
+
+                                               // convert output mono
+                                               if (stream->out.monoMixer)
+                                               {
+                                                       UINT32 mono_frames_size = o_processed * (stream->out.wavex.Format.wBitsPerSample / 8);
+                                                       // expand buffer
+                                                       if (mono_frames_size > stream->out.monoBufferSize)
+                                                       {
+                                                               stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+                                                               if (stream->out.monoBuffer == NULL)
+                                                               {
+                                                                       // release input buffer
+                                                                       IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+                                                                       // release output buffer
+                                                                       IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+                                                                       LogPaError(paInsufficientMemory);
+                                                                       goto thread_error;
+                                                               }
+                                                       }
+
+                                                       // replace buffer pointer
+                                                       o_data = (BYTE *)stream->out.monoBuffer;
+                                               }
+
+                                               // convert input mono
+                                               if (stream->in.monoMixer)
+                                               {
+                                                       UINT32 mono_frames_size = i_processed * (stream->in.wavex.Format.wBitsPerSample / 8);
+                                                       // expand buffer
+                                                       if (mono_frames_size > stream->in.monoBufferSize)
+                                                       {
+                                                               stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+                                                               if (stream->in.monoBuffer == NULL)
+                                                               {
+                                                                       // release input buffer
+                                                                       IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+                                                                       // release output buffer
+                                                                       IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+                                                                       LogPaError(paInsufficientMemory);
+                                                                       goto thread_error;
+                                                               }
+                                                       }
+
+                                                       // mix 2 to 1 input channels
+                                                       stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
+
+                                                       // replace buffer pointer
+                                                       i_data = (BYTE *)stream->in.monoBuffer;
+                                               }
+
+                                               // process
+                                               processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
+
+                                               // mix 1 to 2 output channels
+                                               if (stream->out.monoBuffer)
+                                                       stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
+
+                                               // release host output buffer
+                                               if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, o_processed, 0)) != S_OK)
+                                                       LogHostError(hr);
+
+                                               o_frames -= o_processed;
+                                       }
+                                       else
+                                       {
+                                               if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
+                                                       LogHostError(hr); // be silent in shared mode, try again next time
+                                       }
+                               }
+                               else
+                               {
+                                       i_processed = 0;
+                                       goto fd_release_buffer_in;
+                               }
+
+fd_release_buffer_in:
+
+                               // release host input buffer
+                               if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, i_processed)) != S_OK)
+                               {
+                                       LogHostError(hr);
+                                       break;
+                               }
+
+                               // break processing, input hasn't been accumulated yet
+                               if (i_processed == 0)
+                                       break;
+                       }
+               }
+#endif
+       }
+
+thread_end:
+
+       // Process stop
+       _StreamOnStop(stream);
+
+       // Release unmarshaled COM pointers
+       ReleaseUnmarshaledComPointers(stream);
+
+       // Cleanup COM for this thread
+       if (bThreadComInitialized == TRUE)
+               CoUninitialize();
+
+       // Notify: not running
+       stream->running = FALSE;
+
+       // Notify: thread exited
+       SetEvent(stream->hThreadExit);
+
+       return 0;
+
+thread_error:
+
+       // Prevent deadlocking in Pa_StreamStart
+       SetEvent(stream->hThreadStart);
+
+       // Exit
+       goto thread_end;
+}
+
+// ------------------------------------------------------------------------------------------
+void *PaWasapi_ReallocateMemory(void *ptr, size_t size)
+{
+       return realloc(ptr, size);
+}
+
+// ------------------------------------------------------------------------------------------
+void PaWasapi_FreeMemory(void *ptr)
+{
+       free(ptr);
+}
+
+//#endif //VC 2005
+
+
+
+
+#if 0
+                       if(bFirst) {
+                               float masteur;
+                               hr = stream->outVol->GetMasterVolumeLevelScalar(&masteur);
+                               if (hr != S_OK)
+                                       LogHostError(hr);
+                               float chan1, chan2;
+                               hr = stream->outVol->GetChannelVolumeLevelScalar(0, &chan1);
+                               if (hr != S_OK)
+                                       LogHostError(hr);
+                               hr = stream->outVol->GetChannelVolumeLevelScalar(1, &chan2);
+                               if (hr != S_OK)
+                                       LogHostError(hr);
+
+                               BOOL bMute;
+                               hr = stream->outVol->GetMute(&bMute);
+                               if (hr != S_OK)
+                                       LogHostError(hr);
+
+                               stream->outVol->SetMasterVolumeLevelScalar(0.5, NULL);
+                               stream->outVol->SetChannelVolumeLevelScalar(0, 0.5, NULL);
+                               stream->outVol->SetChannelVolumeLevelScalar(1, 0.5, NULL);
+                               stream->outVol->SetMute(FALSE, NULL);
+                               bFirst = FALSE;
+                       }
+#endif
diff --git a/portaudio/src/hostapi/wdmks/pa_win_wdmks.c b/portaudio/src/hostapi/wdmks/pa_win_wdmks.c
new file mode 100644 (file)
index 0000000..a3b8be5
--- /dev/null
@@ -0,0 +1,6794 @@
+/*
+* $Id$
+* PortAudio Windows WDM-KS interface
+*
+* Author: Andrew Baldwin, Robert Bielik (WaveRT)
+* Based on the Open Source API proposed by Ross Bencina
+* Copyright (c) 1999-2004 Andrew Baldwin, Ross Bencina, Phil Burk
+*
+* Permission is hereby granted, free of charge, to any person obtaining
+* a copy of this software and associated documentation files
+* (the "Software"), to deal in the Software without restriction,
+* including without limitation the rights to use, copy, modify, merge,
+* publish, distribute, sublicense, and/or sell copies of the Software,
+* and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be
+* included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+/*
+* The text above constitutes the entire PortAudio license; however, 
+* the PortAudio community also makes the following non-binding requests:
+*
+* Any person wishing to distribute modifications to the Software is
+* requested to send the modifications to the original developer so that
+* they can be incorporated into the canonical version. It is also 
+* requested that these non-binding requests be included along with the 
+* license above.
+*/
+
+/** @file
+@ingroup hostapi_src
+@brief Portaudio WDM-KS host API.
+
+@note This is the implementation of the Portaudio host API using the
+Windows WDM/Kernel Streaming API in order to enable very low latency
+playback and recording on all modern Windows platforms (e.g. 2K, XP, Vista, Win7)
+Note: This API accesses the device drivers below the usual KMIXER
+component which is normally used to enable multi-client mixing and
+format conversion. That means that it will lock out all other users
+of a device for the duration of active stream using those devices
+*/
+
+#include <stdio.h>
+
+#if (defined(_WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment( lib, "setupapi.lib" )
+#endif
+
+/* Debugging/tracing support */
+
+#define PA_LOGE_
+#define PA_LOGL_
+
+#ifdef __GNUC__
+#include <initguid.h>
+#define _WIN32_WINNT 0x0501
+#define WINVER 0x0501
+#endif
+
+#include <stdlib.h>
+#include <string.h> /* strlen() */
+#include <assert.h>
+#include <wchar.h>  /* iswspace() */
+
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "portaudio.h"
+#include "pa_debugprint.h"
+#include "pa_memorybarrier.h"
+#include "pa_ringbuffer.h"
+#include "pa_trace.h"
+#include "pa_win_waveformat.h"
+
+#include "pa_win_wdmks.h"
+
+#ifndef DRV_QUERYDEVICEINTERFACE
+#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)
+#endif
+#ifndef DRV_QUERYDEVICEINTERFACESIZE
+#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
+#endif
+
+#include <windows.h>
+#include <mmsystem.h>
+#ifndef __GNUC__ /* Fix for ticket #257: MinGW-w64: Inclusion of <winioctl.h> triggers multiple redefinition errors. */
+#include <winioctl.h>
+#endif
+#include <process.h>
+
+#include <math.h>
+
+#ifdef _MSC_VER
+#define snprintf _snprintf
+#define vsnprintf _vsnprintf
+#endif
+
+/* The PA_HP_TRACE macro is used in RT parts, so it can be switched off without affecting
+the rest of the debug tracing */
+#if 1
+#define PA_HP_TRACE(x)  PaUtil_AddHighSpeedLogMessage x ;
+#else
+#define PA_HP_TRACE(x)
+#endif
+
+/* A define that selects whether the resulting pin names are chosen from pin category
+instead of the available pin names, who sometimes can be quite cheesy, like "Volume control".
+Default is to use the pin category.
+*/
+#ifndef PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES
+#define PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES  1
+#endif
+
+#ifdef __GNUC__
+#undef PA_LOGE_
+#define PA_LOGE_ PA_DEBUG(("%s {\n",__FUNCTION__))
+#undef PA_LOGL_
+#define PA_LOGL_ PA_DEBUG(("} %s\n",__FUNCTION__))
+/* These defines are set in order to allow the WIndows DirectX
+* headers to compile with a GCC compiler such as MinGW
+* NOTE: The headers may generate a few warning in GCC, but
+* they should compile */
+#define _INC_MMSYSTEM
+#define _INC_MMREG
+#define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
+#define DEFINE_GUID_THUNK(name,guid) DEFINE_GUID(name,guid)
+#define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK( n, STATIC_##n )
+#if !defined( DEFINE_WAVEFORMATEX_GUID )
+#define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
+#endif
+#define  WAVE_FORMAT_ADPCM      0x0002
+#define  WAVE_FORMAT_IEEE_FLOAT 0x0003
+#define  WAVE_FORMAT_ALAW       0x0006
+#define  WAVE_FORMAT_MULAW      0x0007
+#define  WAVE_FORMAT_MPEG       0x0050
+#define  WAVE_FORMAT_DRM        0x0009
+#define DYNAMIC_GUID_THUNK(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define DYNAMIC_GUID(data) DYNAMIC_GUID_THUNK(data)
+#endif
+
+/* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
+#define CREATE_THREAD_FUNCTION (HANDLE)_beginthreadex
+#define PA_THREAD_FUNC static unsigned WINAPI
+#else
+#define CREATE_THREAD_FUNCTION CreateThread
+#define PA_THREAD_FUNC static DWORD WINAPI
+#endif
+
+#if defined(_MSC_VER)
+#define NOMMIDS
+#define DYNAMIC_GUID(data) {data}
+#define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
+#undef DEFINE_GUID
+#define DEFINE_GUID(n,...) EXTERN_C const GUID n = {__VA_ARGS__}
+#define DEFINE_GUID_THUNK(n,...) DEFINE_GUID(n,__VA_ARGS__)
+#define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n)
+#endif
+
+#include <setupapi.h>
+#include <winioctl.h>
+
+#ifndef EXTERN_C
+#define EXTERN_C extern
+#endif
+
+#if defined(__GNUC__)
+
+/* For MinGW we reference mingw-include files supplied with WASAPI */
+#define WINBOOL BOOL
+
+#include "../wasapi/mingw-include/ks.h"
+#include "../wasapi/mingw-include/ksmedia.h"
+
+#else
+
+#include <mmreg.h>
+#include <ks.h>
+
+/* Note that Windows SDK V6.0A or later is needed for WaveRT specific structs to be present in
+   ksmedia.h. Also make sure that the SDK include path is before other include paths (that may contain
+   an "old" ksmedia.h), so the proper ksmedia.h is used */
+#include <ksmedia.h>
+
+#endif
+
+#include <assert.h>
+#include <stdio.h>
+
+/* These next definitions allow the use of the KSUSER DLL */
+typedef /*KSDDKAPI*/ DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE);
+extern HMODULE      DllKsUser;
+extern KSCREATEPIN* FunctionKsCreatePin;
+
+/* These definitions allows the use of AVRT.DLL on Vista and later OSs */
+typedef enum _PA_AVRT_PRIORITY
+{
+    PA_AVRT_PRIORITY_LOW = -1,
+    PA_AVRT_PRIORITY_NORMAL,
+    PA_AVRT_PRIORITY_HIGH,
+    PA_AVRT_PRIORITY_CRITICAL
+} PA_AVRT_PRIORITY, *PPA_AVRT_PRIORITY;
+
+typedef struct
+{
+    HINSTANCE hInstance;
+
+    HANDLE  (WINAPI *AvSetMmThreadCharacteristics) (LPCSTR, LPDWORD);
+    BOOL    (WINAPI *AvRevertMmThreadCharacteristics) (HANDLE);
+    BOOL    (WINAPI *AvSetMmThreadPriority) (HANDLE, PA_AVRT_PRIORITY);
+} PaWinWDMKSAvRtEntryPoints;
+
+static PaWinWDMKSAvRtEntryPoints paWinWDMKSAvRtEntryPoints = {0};
+
+/* An unspecified channel count (-1) is not treated correctly, so we replace it with
+* an arbitrarily large number */ 
+#define MAXIMUM_NUMBER_OF_CHANNELS 256
+
+/* Forward definition to break circular type reference between pin and filter */
+struct __PaWinWdmFilter;
+typedef struct __PaWinWdmFilter PaWinWdmFilter;
+
+struct __PaWinWdmPin;
+typedef struct __PaWinWdmPin PaWinWdmPin;
+
+struct __PaWinWdmStream;
+typedef struct __PaWinWdmStream PaWinWdmStream;
+
+/* Function prototype for getting audio position */
+typedef PaError (*FunctionGetPinAudioPosition)(PaWinWdmPin*, unsigned long*);
+
+/* Function prototype for memory barrier */
+typedef void (*FunctionMemoryBarrier)(void);
+
+struct __PaProcessThreadInfo;
+typedef struct __PaProcessThreadInfo PaProcessThreadInfo;
+
+typedef PaError (*FunctionPinHandler)(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+
+typedef enum __PaStreamStartEnum
+{
+    StreamStart_kOk,
+    StreamStart_kFailed,
+    StreamStart_kCnt
+} PaStreamStartEnum;
+
+/* Multiplexed input structure.
+*  Very often several physical inputs are multiplexed through a MUX node (represented in the topology filter) */
+typedef struct __PaWinWdmMuxedInput
+{
+    wchar_t                     friendlyName[MAX_PATH];
+    ULONG                       muxPinId;
+    ULONG                       muxNodeId;
+    ULONG                       endpointPinId;
+} PaWinWdmMuxedInput;
+
+/* The Pin structure
+* A pin is an input or output node, e.g. for audio flow */
+struct __PaWinWdmPin
+{
+    HANDLE                      handle;
+    PaWinWdmMuxedInput**        inputs;
+    unsigned                    inputCount;
+    wchar_t                     friendlyName[MAX_PATH];
+
+    PaWinWdmFilter*             parentFilter;
+    PaWDMKSSubType              pinKsSubType;
+    unsigned long               pinId;
+    unsigned long               endpointPinId;  /* For output pins */
+    KSPIN_CONNECT*              pinConnect;
+    unsigned long               pinConnectSize;
+    KSDATAFORMAT_WAVEFORMATEX*  ksDataFormatWfx;
+    KSPIN_COMMUNICATION         communication;
+    KSDATARANGE*                dataRanges;
+    KSMULTIPLE_ITEM*            dataRangesItem;
+    KSPIN_DATAFLOW              dataFlow;
+    KSPIN_CINSTANCES            instances;
+    unsigned long               frameSize;
+    int                         maxChannels;
+    unsigned long               formats;
+    int                         defaultSampleRate;
+    ULONG                       *positionRegister;  /* WaveRT */
+    ULONG                       hwLatency;          /* WaveRT */
+    FunctionMemoryBarrier       fnMemBarrier;       /* WaveRT */
+    FunctionGetPinAudioPosition fnAudioPosition;    /* WaveRT */
+    FunctionPinHandler          fnEventHandler;
+    FunctionPinHandler          fnSubmitHandler;
+};
+
+/* The Filter structure
+* A filter has a number of pins and a "friendly name" */
+struct __PaWinWdmFilter
+{
+    HANDLE         handle;
+    PaWinWDMKSDeviceInfo    devInfo;  /* This will hold information that is exposed in PaDeviceInfo */
+
+    DWORD            deviceNode;
+    int            pinCount;
+    PaWinWdmPin**  pins;
+    PaWinWdmFilter*  topologyFilter;
+    wchar_t          friendlyName[MAX_PATH];
+    int              validPinCount;
+    int            usageCount;
+    KSMULTIPLE_ITEM* connections;
+    KSMULTIPLE_ITEM* nodes;
+    int              filterRefCount;
+};
+
+
+typedef struct __PaWinWdmDeviceInfo
+{
+    PaDeviceInfo    inheritedDeviceInfo;
+    char            compositeName[MAX_PATH];   /* Composite name consists of pin name + device name in utf8 */
+    PaWinWdmFilter* filter;
+    unsigned long   pin;
+    int             muxPosition;    /* Used only for input devices */
+    int             endpointPinId;
+}
+PaWinWdmDeviceInfo;
+
+/* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */
+typedef struct __PaWinWdmHostApiRepresentation
+{
+    PaUtilHostApiRepresentation  inheritedHostApiRep;
+    PaUtilStreamInterface        callbackStreamInterface;
+    PaUtilStreamInterface        blockingStreamInterface;
+
+    PaUtilAllocationGroup*       allocations;
+    int                          deviceCount;
+}
+PaWinWdmHostApiRepresentation;
+
+typedef struct __DATAPACKET
+{
+    KSSTREAM_HEADER  Header;
+    OVERLAPPED       Signal;
+} DATAPACKET;
+
+typedef struct __PaIOPacket
+{
+    DATAPACKET*     packet;
+    unsigned        startByte;
+    unsigned        lengthBytes;
+} PaIOPacket;
+
+typedef struct __PaWinWdmIOInfo
+{
+    PaWinWdmPin*        pPin;
+    char*               hostBuffer;
+    unsigned            hostBufferSize;
+    unsigned            framesPerBuffer;
+    unsigned            bytesPerFrame;
+    unsigned            bytesPerSample;
+    unsigned            noOfPackets;    /* Only used in WaveCyclic */
+    HANDLE              *events;        /* noOfPackets handles (WaveCyclic) 1 (WaveRT) */
+    DATAPACKET          *packets;       /* noOfPackets packets (WaveCyclic) 2 (WaveRT) */
+    /* WaveRT polled mode */
+    unsigned            lastPosition; 
+    unsigned            pollCntr;
+} PaWinWdmIOInfo;
+
+/* PaWinWdmStream - a stream data structure specifically for this implementation */
+struct __PaWinWdmStream
+{
+    PaUtilStreamRepresentation  streamRepresentation;
+    PaWDMKSSpecificStreamInfo   hostApiStreamInfo;    /* This holds info that is exposed through PaStreamInfo */
+    PaUtilCpuLoadMeasurer       cpuLoadMeasurer;
+    PaUtilBufferProcessor       bufferProcessor;
+
+#if PA_TRACE_REALTIME_EVENTS
+    LogHandle                   hLog;
+#endif
+
+    PaUtilAllocationGroup*      allocGroup;
+    PaWinWdmIOInfo              capture;
+    PaWinWdmIOInfo              render;
+    int                         streamStarted;
+    int                         streamActive;
+    int                         streamStop;
+    int                         streamAbort;
+    int                         oldProcessPriority;
+    HANDLE                      streamThread;
+    HANDLE                      eventAbort;
+    HANDLE                      eventStreamStart[StreamStart_kCnt];        /* 0 = OK, 1 = Failed */
+    PaError                     threadResult;
+    PaStreamFlags               streamFlags;
+
+    /* Capture ring buffer */
+    PaUtilRingBuffer            ringBuffer;
+    char*                       ringBufferData;
+
+    /* These values handle the case where the user wants to use fewer
+    * channels than the device has */
+    int                         userInputChannels;
+    int                         deviceInputChannels;
+    int                         userOutputChannels;
+    int                         deviceOutputChannels;
+};
+
+/* Gather all processing variables in a struct */
+struct __PaProcessThreadInfo 
+{
+    PaWinWdmStream              *stream;
+    PaStreamCallbackTimeInfo    ti;
+    PaStreamCallbackFlags       underover;
+    int                         cbResult;
+    volatile int                pending;
+    volatile int                priming;
+    volatile int                pinsStarted;
+    unsigned long               timeout;
+    unsigned                    captureHead;
+    unsigned                    captureTail;
+    unsigned                    renderHead;
+    unsigned                    renderTail;
+    PaIOPacket                  capturePackets[4];
+    PaIOPacket                  renderPackets[4];
+};
+
+/* Used for transferring device infos during scanning / rescanning */
+typedef struct __PaWinWDMScanDeviceInfosResults
+{ 
+    PaDeviceInfo **deviceInfos;
+    PaDeviceIndex defaultInputDevice;
+    PaDeviceIndex defaultOutputDevice;
+} PaWinWDMScanDeviceInfosResults;
+
+static const unsigned cPacketsArrayMask = 3;
+
+HMODULE      DllKsUser = NULL;
+KSCREATEPIN* FunctionKsCreatePin = NULL;
+
+/* prototypes for functions declared in this file */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+    PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/* Low level I/O functions */
+static PaError WdmSyncIoctl(HANDLE handle,
+                            unsigned long ioctlNumber,
+                            void* inBuffer,
+                            unsigned long inBufferCount,
+                            void* outBuffer,
+                            unsigned long outBufferCount,
+                            unsigned long* bytesReturned);
+
+static PaError WdmGetPropertySimple(HANDLE handle,
+                                    const GUID* const guidPropertySet,
+                                    unsigned long property,
+                                    void* value,
+                                    unsigned long valueCount);
+
+static PaError WdmSetPropertySimple(HANDLE handle,
+                                    const GUID* const guidPropertySet,
+                                    unsigned long property,
+                                    void* value,
+                                    unsigned long valueCount,
+                                    void* instance,
+                                    unsigned long instanceCount);
+
+static PaError WdmGetPinPropertySimple(HANDLE  handle,
+                                       unsigned long pinId,
+                                       const GUID* const guidPropertySet,
+                                       unsigned long property,
+                                       void* value,
+                                       unsigned long valueCount,
+                                       unsigned long* byteCount);
+
+static PaError WdmGetPinPropertyMulti(HANDLE  handle,
+                                      unsigned long pinId,
+                                      const GUID* const guidPropertySet,
+                                      unsigned long property,
+                                      KSMULTIPLE_ITEM** ksMultipleItem);
+
+static PaError WdmGetPropertyMulti(HANDLE handle,
+                                   const GUID* const guidPropertySet,
+                                   unsigned long property,
+                                   KSMULTIPLE_ITEM** ksMultipleItem);
+
+static PaError WdmSetMuxNodeProperty(HANDLE handle,
+                                     ULONG nodeId,
+                                     ULONG pinId);
+
+
+/** Pin management functions */
+static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error);
+static void PinFree(PaWinWdmPin* pin);
+static void PinClose(PaWinWdmPin* pin);
+static PaError PinInstantiate(PaWinWdmPin* pin);
+/*static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state); NOT USED */
+static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state);
+static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format);
+static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format);
+/* WaveRT support */
+static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult);
+static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier);
+static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin);
+static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);
+static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);
+static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay);
+static PaError PinGetAudioPositionMemoryMapped(PaWinWdmPin* pPin, ULONG* pPosition);
+static PaError PinGetAudioPositionViaIOCTLRead(PaWinWdmPin* pPin, ULONG* pPosition);
+static PaError PinGetAudioPositionViaIOCTLWrite(PaWinWdmPin* pPin, ULONG* pPosition);
+
+/* Filter management functions */
+static PaWinWdmFilter* FilterNew(PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error);
+static PaError FilterInitializePins(PaWinWdmFilter* filter);
+static void FilterFree(PaWinWdmFilter* filter);
+static void FilterAddRef(PaWinWdmFilter* filter);
+static PaWinWdmPin* FilterCreatePin(
+                                    PaWinWdmFilter* filter,
+                                    int pinId,
+                                    const WAVEFORMATEX* wfex,
+                                    PaError* error);
+static PaError FilterUse(PaWinWdmFilter* filter);
+static void FilterRelease(PaWinWdmFilter* filter);
+
+/* Hot plug functions */
+static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,
+                            const PaWinWdmDeviceInfo* pDev2);
+
+/* Interface functions */
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported(
+struct PaUtilHostApiRepresentation *hostApi,
+    const PaStreamParameters *inputParameters,
+    const PaStreamParameters *outputParameters,
+    double sampleRate );
+
+static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void **newDeviceInfos, int *newDeviceCount );
+static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *deviceInfos, int deviceCount );
+static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *deviceInfos, int deviceCount );
+
+static PaError OpenStream(
+struct PaUtilHostApiRepresentation *hostApi,
+    PaStream** s,
+    const PaStreamParameters *inputParameters,
+    const PaStreamParameters *outputParameters,
+    double sampleRate,
+    unsigned long framesPerBuffer,
+    PaStreamFlags streamFlags,
+    PaStreamCallback *streamCallback,
+    void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream(
+                          PaStream* stream,
+                          void *buffer,
+                          unsigned long frames );
+static PaError WriteStream(
+                           PaStream* stream,
+                           const void *buffer,
+                           unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+/* Utility functions */
+static unsigned long GetWfexSize(const WAVEFORMATEX* wfex);
+static PaWinWdmFilter** BuildFilterList(int* filterCount, int* noOfPaDevices, PaError* result);
+static BOOL PinWrite(HANDLE h, DATAPACKET* p);
+static BOOL PinRead(HANDLE h, DATAPACKET* p);
+static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples);
+static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples);
+PA_THREAD_FUNC ProcessingThread(void*);
+
+/* Pin handler functions */
+static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+
+static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+
+static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+
+static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
+
+/* Function bodies */
+
+#if defined(_DEBUG) && defined(PA_ENABLE_DEBUG_OUTPUT)
+#define PA_WDMKS_SET_TREF
+static PaTime tRef = 0;
+
+static void PaWinWdmDebugPrintf(const char* fmt, ...)
+{
+    va_list list;
+    char buffer[1024];
+    PaTime t = PaUtil_GetTime() - tRef;
+    va_start(list, fmt);
+    _vsnprintf(buffer, 1023, fmt, list);
+    va_end(list);
+    PaUtil_DebugPrint("%6.3lf: %s", t, buffer);
+}
+
+#ifdef PA_DEBUG
+#undef PA_DEBUG
+#define PA_DEBUG(x)    PaWinWdmDebugPrintf x ;
+#endif
+#endif
+
+static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,
+                            const PaWinWdmDeviceInfo* pDev2)
+{
+    if (pDev1 == NULL || pDev2 == NULL)
+        return FALSE;
+
+    if (pDev1 == pDev2)
+        return TRUE;
+
+    if (strcmp(pDev1->compositeName, pDev2->compositeName) == 0)
+        return TRUE;
+
+    return FALSE;
+}
+
+static BOOL IsEarlierThanVista()
+{
+/*
+NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
+versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
+Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
+is is faster, for now we just disable the deprecation warning.
+See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
+See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
+*/
+#pragma warning (disable : 4996) /* use of GetVersionEx */
+
+    OSVERSIONINFO osvi;
+    osvi.dwOSVersionInfoSize = sizeof(osvi);
+    if (GetVersionEx(&osvi) && osvi.dwMajorVersion<6)
+    {
+        return TRUE;
+    }
+    return FALSE;
+
+#pragma warning (default : 4996)
+}
+
+
+
+static void MemoryBarrierDummy(void)
+{
+    /* Do nothing */
+}
+
+static void MemoryBarrierRead(void)
+{
+    PaUtil_ReadMemoryBarrier();
+}
+
+static void MemoryBarrierWrite(void)
+{
+    PaUtil_WriteMemoryBarrier();
+}
+
+static unsigned long GetWfexSize(const WAVEFORMATEX* wfex)
+{
+    if( wfex->wFormatTag == WAVE_FORMAT_PCM )
+    {
+        return sizeof( WAVEFORMATEX );
+    }
+    else
+    {
+        return (sizeof( WAVEFORMATEX ) + wfex->cbSize);
+    }
+}
+
+static void PaWinWDM_SetLastErrorInfo(long errCode, const char* fmt, ...)
+{
+    va_list list;
+    char buffer[1024];
+    va_start(list, fmt);
+    _vsnprintf(buffer, 1023, fmt, list);
+    va_end(list);
+    PaUtil_SetLastHostErrorInfo(paWDMKS, errCode, buffer);
+}
+
+/*
+Low level pin/filter access functions
+*/
+static PaError WdmSyncIoctl(
+                            HANDLE handle,
+                            unsigned long ioctlNumber,
+                            void* inBuffer,
+                            unsigned long inBufferCount,
+                            void* outBuffer,
+                            unsigned long outBufferCount,
+                            unsigned long* bytesReturned)
+{
+    PaError result = paNoError;
+    unsigned long dummyBytesReturned = 0;
+    BOOL bRes;
+
+    if( !bytesReturned )
+    {
+        /* Use a dummy as the caller hasn't supplied one */
+        bytesReturned = &dummyBytesReturned;
+    }
+
+    bRes = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount, outBuffer, outBufferCount, bytesReturned, NULL);
+    if (!bRes)
+    {
+        unsigned long error = GetLastError();
+        if ( !(((error == ERROR_INSUFFICIENT_BUFFER ) || ( error == ERROR_MORE_DATA )) && 
+            ( ioctlNumber == IOCTL_KS_PROPERTY ) &&
+            ( outBufferCount == 0 ) ) ) 
+        {
+            KSPROPERTY* ksProperty = (KSPROPERTY*)inBuffer;
+
+            PaWinWDM_SetLastErrorInfo(result, "WdmSyncIoctl: DeviceIoControl GLE = 0x%08X (prop_set = {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, prop_id = %u)",
+                error,
+                ksProperty->Set.Data1, ksProperty->Set.Data2, ksProperty->Set.Data3,
+                ksProperty->Set.Data4[0], ksProperty->Set.Data4[1],
+                ksProperty->Set.Data4[2], ksProperty->Set.Data4[3],
+                ksProperty->Set.Data4[4], ksProperty->Set.Data4[5],
+                ksProperty->Set.Data4[6], ksProperty->Set.Data4[7],
+                ksProperty->Id
+                );
+            result = paUnanticipatedHostError;
+        }
+    }
+    return result;
+}
+
+static PaError WdmGetPropertySimple(HANDLE handle,
+                                    const GUID* const guidPropertySet,
+                                    unsigned long property,
+                                    void* value,
+                                    unsigned long valueCount)
+{
+    PaError result;
+    KSPROPERTY ksProperty;
+
+    ksProperty.Set = *guidPropertySet;
+    ksProperty.Id = property;
+    ksProperty.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksProperty,
+        sizeof(KSPROPERTY),
+        value,
+        valueCount,
+        NULL);
+
+    return result;
+}
+
+static PaError WdmSetPropertySimple(
+                                    HANDLE handle,
+                                    const GUID* const guidPropertySet,
+                                    unsigned long property,
+                                    void* value,
+                                    unsigned long valueCount,
+                                    void* instance,
+                                    unsigned long instanceCount)
+{
+    PaError result;
+    KSPROPERTY* ksProperty;
+    unsigned long propertyCount  = 0;
+
+    propertyCount = sizeof(KSPROPERTY) + instanceCount;
+    ksProperty = (KSPROPERTY*)_alloca( propertyCount );
+    if( !ksProperty )
+    {
+        return paInsufficientMemory;
+    }
+
+    ksProperty->Set = *guidPropertySet;
+    ksProperty->Id = property;
+    ksProperty->Flags = KSPROPERTY_TYPE_SET;
+
+    if( instance )
+    {
+        memcpy((void*)((char*)ksProperty + sizeof(KSPROPERTY)), instance, instanceCount);
+    }
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        ksProperty,
+        propertyCount,
+        value,
+        valueCount,
+        NULL);
+
+    return result;
+}
+
+static PaError WdmGetPinPropertySimple(
+                                       HANDLE  handle,
+                                       unsigned long pinId,
+                                       const GUID* const guidPropertySet,
+                                       unsigned long property,
+                                       void* value,
+                                       unsigned long valueCount,
+                                       unsigned long *byteCount)
+{
+    PaError result;
+
+    KSP_PIN ksPProp;
+    ksPProp.Property.Set = *guidPropertySet;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksPProp,
+        sizeof(KSP_PIN),
+        value,
+        valueCount,
+        byteCount);
+
+    return result;
+}
+
+static PaError WdmGetPinPropertyMulti(
+                                      HANDLE handle,
+                                      unsigned long pinId,
+                                      const GUID* const guidPropertySet,
+                                      unsigned long property,
+                                      KSMULTIPLE_ITEM** ksMultipleItem)
+{
+    PaError result;
+    unsigned long multipleItemSize = 0;
+    KSP_PIN ksPProp;
+
+    ksPProp.Property.Set = *guidPropertySet;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksPProp.Property,
+        sizeof(KSP_PIN),
+        NULL,
+        0,
+        &multipleItemSize);
+    if( result != paNoError )
+    {
+        return result;
+    }
+
+    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
+    if( !*ksMultipleItem )
+    {
+        return paInsufficientMemory;
+    }
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksPProp,
+        sizeof(KSP_PIN),
+        (void*)*ksMultipleItem,
+        multipleItemSize,
+        NULL);
+
+    if( result != paNoError )
+    {
+        PaUtil_FreeMemory( ksMultipleItem );
+    }
+
+    return result;
+}
+
+static PaError WdmGetPropertyMulti(HANDLE handle,
+                                   const GUID* const guidPropertySet,
+                                   unsigned long property,
+                                   KSMULTIPLE_ITEM** ksMultipleItem)
+{
+    PaError result;
+    unsigned long multipleItemSize = 0;
+    KSPROPERTY ksProp;
+
+    ksProp.Set = *guidPropertySet;
+    ksProp.Id = property;
+    ksProp.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksProp,
+        sizeof(KSPROPERTY),
+        NULL,
+        0,
+        &multipleItemSize);
+    if( result != paNoError )
+    {
+        return result;
+    }
+
+    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
+    if( !*ksMultipleItem )
+    {
+        return paInsufficientMemory;
+    }
+
+    result = WdmSyncIoctl(
+        handle,
+        IOCTL_KS_PROPERTY,
+        &ksProp,
+        sizeof(KSPROPERTY),
+        (void*)*ksMultipleItem,
+        multipleItemSize,
+        NULL);
+
+    if( result != paNoError )
+    {
+        PaUtil_FreeMemory( ksMultipleItem );
+    }
+
+    return result;
+}
+
+static PaError WdmSetMuxNodeProperty(HANDLE handle,
+                                     ULONG nodeId,
+                                     ULONG pinId)
+{
+    PaError result = paNoError;
+    KSNODEPROPERTY prop;
+    prop.Property.Set = KSPROPSETID_Audio;
+    prop.Property.Id = KSPROPERTY_AUDIO_MUX_SOURCE;
+    prop.Property.Flags = KSPROPERTY_TYPE_SET | KSPROPERTY_TYPE_TOPOLOGY;
+    prop.NodeId = nodeId;
+    prop.Reserved = 0;
+
+    result = WdmSyncIoctl(handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSNODEPROPERTY), &pinId, sizeof(ULONG), NULL);
+
+    return result;
+}
+
+/* Used when traversing topology for outputs */
+static const KSTOPOLOGY_CONNECTION* GetConnectionTo(const KSTOPOLOGY_CONNECTION* pFrom, PaWinWdmFilter* filter, int muxIdx)
+{
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* retval = NULL;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    (void)muxIdx;
+    PA_DEBUG(("GetConnectionTo: Checking %u connections... (pFrom = %p)", filter->connections->Count, pFrom));
+    for (i = 0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        if (pConn == pFrom)
+            continue;
+
+        if (pConn->FromNode == pFrom->ToNode)
+        {
+            retval = pConn;
+            break;
+        }
+    }
+    PA_DEBUG(("GetConnectionTo: Returning %p\n", retval));
+    return retval;
+}
+
+/* Used when traversing topology for inputs */
+static const KSTOPOLOGY_CONNECTION* GetConnectionFrom(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter, int muxIdx)
+{
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* retval = NULL;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    int muxCntr = 0;
+    PA_DEBUG(("GetConnectionFrom: Checking %u connections... (pTo = %p)\n", filter->connections->Count, pTo));
+    for (i = 0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        if (pConn == pTo)
+            continue;
+
+        if (pConn->ToNode == pTo->FromNode)
+        {
+            if (muxIdx >= 0)
+            {
+                if (muxCntr < muxIdx)
+                {
+                    ++muxCntr;
+                    continue;
+                }
+            }
+            retval = pConn;
+            break;
+        }
+    }
+    PA_DEBUG(("GetConnectionFrom: Returning %p\n", retval));
+    return retval;
+}
+
+static ULONG GetNumberOfConnectionsTo(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter)
+{
+    ULONG retval = 0;
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    PA_DEBUG(("GetNumberOfConnectionsTo: Checking %u connections...\n", filter->connections->Count));
+    for (i = 0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        if (pConn->ToNode == pTo->FromNode &&
+            (pTo->FromNode != KSFILTER_NODE || pConn->ToNodePin == pTo->FromNodePin))
+        {
+            ++retval;
+        }
+    }
+    PA_DEBUG(("GetNumberOfConnectionsTo: Returning %d\n", retval));
+    return retval;
+}
+
+typedef const KSTOPOLOGY_CONNECTION *(*TFnGetConnection)(const KSTOPOLOGY_CONNECTION*, PaWinWdmFilter*, int);
+
+static const KSTOPOLOGY_CONNECTION* FindStartConnectionFrom(ULONG startPin, PaWinWdmFilter* filter)
+{
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    PA_DEBUG(("FindStartConnectionFrom: Startpin %u, Checking %u connections...\n", startPin, filter->connections->Count));
+    for (i = 0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        if (pConn->ToNode == KSFILTER_NODE && pConn->ToNodePin == startPin)
+        {
+            PA_DEBUG(("FindStartConnectionFrom: returning %p\n", pConn));
+            return pConn;
+        }
+    }
+
+    PA_DEBUG(("FindStartConnectionFrom: returning NULL\n"));
+    assert(FALSE);
+    return 0;
+}
+
+static const KSTOPOLOGY_CONNECTION* FindStartConnectionTo(ULONG startPin, PaWinWdmFilter* filter)
+{
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    PA_DEBUG(("FindStartConnectionTo: Startpin %u, Checking %u connections...\n", startPin, filter->connections->Count));
+    for (i = 0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        if (pConn->FromNode == KSFILTER_NODE && pConn->FromNodePin == startPin)
+        {
+            PA_DEBUG(("FindStartConnectionTo: returning %p\n", pConn));
+            return pConn;
+        }
+    }
+
+    PA_DEBUG(("FindStartConnectionTo: returning NULL\n"));
+    assert(FALSE);
+    return 0;
+}
+
+static ULONG GetConnectedPin(ULONG startPin, BOOL forward, PaWinWdmFilter* filter, int muxPosition, ULONG *muxInputPinId, ULONG *muxNodeId)
+{
+    int limit=1000;
+    const KSTOPOLOGY_CONNECTION *conn = NULL; 
+    TFnGetConnection fnGetConnection = forward ? GetConnectionTo : GetConnectionFrom ;
+    PA_LOGE_;
+    while (1)
+    {
+        limit--;
+        if (limit == 0) {
+           PA_DEBUG(("GetConnectedPin: LOOP LIMIT REACHED\n"));
+           break;
+        }
+
+        if (conn == NULL)
+        {
+            conn = forward ? FindStartConnectionTo(startPin, filter) : FindStartConnectionFrom(startPin, filter);
+        }
+        else
+        {
+            conn = fnGetConnection(conn, filter, -1);
+        }
+
+        /* Handling case of erroneous connection list */
+        if (conn == NULL)
+        {
+            break;
+        }
+
+        if (forward ? conn->ToNode == KSFILTER_NODE : conn->FromNode == KSFILTER_NODE)
+        {
+            return forward ? conn->ToNodePin : conn->FromNodePin;
+        }
+        else
+        {
+            PA_DEBUG(("GetConnectedPin: count=%d, forward=%d, muxPosition=%d\n", filter->nodes->Count, forward, muxPosition));
+            if (filter->nodes->Count > 0 && !forward && muxPosition >= 0)
+            {
+                const GUID* nodes = (const GUID*)(filter->nodes + 1);
+                if (IsEqualGUID(&nodes[conn->FromNode], &KSNODETYPE_MUX))
+                {
+                    ULONG nConn = GetNumberOfConnectionsTo(conn, filter);
+                    conn = fnGetConnection(conn, filter, muxPosition);
+                    if (conn == NULL)
+                    {
+                        break;
+                    }
+                    if (muxInputPinId != 0)
+                    {
+                        *muxInputPinId = conn->ToNodePin;
+                    }
+                    if (muxNodeId != 0)
+                    {
+                        *muxNodeId = conn->ToNode;
+                    }
+                }
+            }
+        }
+    }
+    PA_LOGL_;
+    return KSFILTER_NODE;
+}
+
+static void DumpConnectionsAndNodes(PaWinWdmFilter* filter)
+{
+    unsigned i;
+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
+    const GUID* nodes = (const GUID*)(filter->nodes + 1);
+
+    PA_LOGE_;
+    PA_DEBUG(("DumpConnectionsAndNodes: connections=%d, nodes=%d\n", filter->connections->Count, filter->nodes->Count));
+
+    for (i=0; i < filter->connections->Count; ++i)
+    {
+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
+        PA_DEBUG(("  Connection: %u - FromNode=%u,FromPin=%u -> ToNode=%u,ToPin=%u\n", 
+            i,
+            pConn->FromNode, pConn->FromNodePin,
+            pConn->ToNode, pConn->ToNodePin
+            ));
+    }
+
+    for (i=0; i < filter->nodes->Count; ++i)
+    {
+        const GUID* pConn = nodes + i;
+        PA_DEBUG(("  Node: %d - {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
+            i,
+            pConn->Data1, pConn->Data2, pConn->Data3,
+            pConn->Data4[0], pConn->Data4[1],
+            pConn->Data4[2], pConn->Data4[3],
+            pConn->Data4[4], pConn->Data4[5],
+            pConn->Data4[6], pConn->Data4[7]
+        ));
+    }
+    PA_LOGL_;
+
+}
+
+typedef struct __PaUsbTerminalGUIDToName 
+{
+    USHORT     usbGUID;
+    wchar_t    name[64];
+} PaUsbTerminalGUIDToName;
+
+static const PaUsbTerminalGUIDToName kNames[] =
+{
+    /* Types copied from: http://msdn.microsoft.com/en-us/library/ff537742(v=vs.85).aspx */
+    /* Input terminal types */
+    { 0x0201, L"Microphone" },
+    { 0x0202, L"Desktop Microphone" },
+    { 0x0203, L"Personal Microphone" },
+    { 0x0204, L"Omni Directional Microphone" },
+    { 0x0205, L"Microphone Array" },
+    { 0x0206, L"Processing Microphone Array" },
+    /* Output terminal types */
+    { 0x0301, L"Speakers" },
+    { 0x0302, L"Headphones" },
+    { 0x0303, L"Head Mounted Display Audio" },
+    { 0x0304, L"Desktop Speaker" },
+    { 0x0305, L"Room Speaker" },
+    { 0x0306, L"Communication Speaker" },
+    { 0x0307, L"LFE Speakers" },
+    /* External terminal types */
+    { 0x0601, L"Analog" },
+    { 0x0602, L"Digital" },
+    { 0x0603, L"Line" },
+    { 0x0604, L"Audio" },
+    { 0x0605, L"SPDIF" },
+};
+
+static const unsigned kNamesCnt = sizeof(kNames)/sizeof(PaUsbTerminalGUIDToName);
+
+static int PaUsbTerminalGUIDToNameCmp(const void* lhs, const void* rhs)
+{
+    const PaUsbTerminalGUIDToName* pL = (const PaUsbTerminalGUIDToName*)lhs;
+    const PaUsbTerminalGUIDToName* pR = (const PaUsbTerminalGUIDToName*)rhs;
+    return ((int)(pL->usbGUID) - (int)(pR->usbGUID));
+}
+
+static PaError GetNameFromCategory(const GUID* pGUID, BOOL input, wchar_t* name, unsigned length)
+{
+    PaError result = paUnanticipatedHostError;
+    USHORT usbTerminalGUID = (USHORT)(pGUID->Data1 - 0xDFF219E0);
+
+    PA_LOGE_;
+    if (input && usbTerminalGUID >= 0x301 && usbTerminalGUID < 0x400)
+    {
+        /* Output terminal name for an input !? Set it to Line! */
+        usbTerminalGUID = 0x603;
+    }
+    if (!input && usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x300)
+    {
+        /* Input terminal name for an output !? Set it to Line! */
+        usbTerminalGUID = 0x603;
+    }
+    if (usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x713)
+    {
+        PaUsbTerminalGUIDToName s = { usbTerminalGUID };
+        const PaUsbTerminalGUIDToName* ptr = bsearch(
+            &s,
+            kNames,
+            kNamesCnt,
+            sizeof(PaUsbTerminalGUIDToName),
+            PaUsbTerminalGUIDToNameCmp
+            );
+        if (ptr != 0)
+        {
+            PA_DEBUG(("GetNameFromCategory: USB GUID %04X -> '%S'\n", usbTerminalGUID, ptr->name));
+
+            if (name != NULL && length > 0)
+            {
+                int n = _snwprintf(name, length, L"%s", ptr->name);
+                if (usbTerminalGUID >= 0x601 && usbTerminalGUID < 0x700)
+                {
+                    _snwprintf(name + n, length - n, L" %s", (input ? L"In":L"Out"));
+                }
+            }
+            result = paNoError;
+        }
+    }
+    else
+    {
+        PaWinWDM_SetLastErrorInfo(result, "GetNameFromCategory: usbTerminalGUID = %04X ", usbTerminalGUID);
+    }
+    PA_LOGL_;
+    return result;
+}
+
+static BOOL IsFrequencyWithinRange(const KSDATARANGE_AUDIO* range, int frequency)
+{
+    if (frequency < (int)range->MinimumSampleFrequency)
+        return FALSE;
+    if (frequency > (int)range->MaximumSampleFrequency)
+        return FALSE;
+    return TRUE;
+}
+
+static BOOL IsBitsWithinRange(const KSDATARANGE_AUDIO* range, int noOfBits)
+{
+    if (noOfBits < (int)range->MinimumBitsPerSample)
+        return FALSE;
+    if (noOfBits > (int)range->MaximumBitsPerSample)
+        return FALSE;
+    return TRUE;
+}
+
+/* Note: Somewhat different order compared to WMME implementation, as we want to focus on fidelity first */
+static const int defaultSampleRateSearchOrder[] =
+{ 44100, 48000, 88200, 96000, 192000, 32000, 24000, 22050, 16000, 12000, 11025, 9600, 8000 };
+static const int defaultSampleRateSearchOrderCount = sizeof(defaultSampleRateSearchOrder)/sizeof(defaultSampleRateSearchOrder[0]);
+
+static int DefaultSampleFrequencyIndex(const KSDATARANGE_AUDIO* range)
+{
+    int i;
+
+    for(i=0; i < defaultSampleRateSearchOrderCount; ++i)
+    {
+        int currentFrequency = defaultSampleRateSearchOrder[i];
+
+        if (IsFrequencyWithinRange(range, currentFrequency))
+        {
+            return i;
+        }
+    }
+
+    return -1;
+}
+
+/*
+Create a new pin object belonging to a filter
+The pin object holds all the configuration information about the pin
+before it is opened, and then the handle of the pin after is opened
+*/
+static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error)
+{
+    PaWinWdmPin* pin;
+    PaError result;
+    unsigned long i;
+    KSMULTIPLE_ITEM* item = NULL;
+    KSIDENTIFIER* identifier;
+    KSDATARANGE* dataRange;
+    const ULONG streamingId = (parentFilter->devInfo.streamingType == Type_kWaveRT) ? KSINTERFACE_STANDARD_LOOPED_STREAMING : KSINTERFACE_STANDARD_STREAMING;
+    int defaultSampleRateIndex = defaultSampleRateSearchOrderCount;
+
+    PA_LOGE_;
+    PA_DEBUG(("PinNew: Creating pin %d:\n",pinId));
+
+    /* Allocate the new PIN object */
+    pin = (PaWinWdmPin*)PaUtil_AllocateMemory( sizeof(PaWinWdmPin) );
+    if( !pin )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Zero the pin object */
+    /* memset( (void*)pin, 0, sizeof(PaWinWdmPin) ); */
+
+    pin->parentFilter = parentFilter;
+    pin->pinId = pinId;
+
+    /* Allocate a connect structure */
+    pin->pinConnectSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX);
+    pin->pinConnect = (KSPIN_CONNECT*)PaUtil_AllocateMemory( pin->pinConnectSize );
+    if( !pin->pinConnect )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Configure the connect structure with default values */
+    pin->pinConnect->Interface.Set               = KSINTERFACESETID_Standard;
+    pin->pinConnect->Interface.Id                = streamingId;
+    pin->pinConnect->Interface.Flags             = 0;
+    pin->pinConnect->Medium.Set                  = KSMEDIUMSETID_Standard;
+    pin->pinConnect->Medium.Id                   = KSMEDIUM_TYPE_ANYINSTANCE;
+    pin->pinConnect->Medium.Flags                = 0;
+    pin->pinConnect->PinId                       = pinId;
+    pin->pinConnect->PinToHandle                 = NULL;
+    pin->pinConnect->Priority.PriorityClass      = KSPRIORITY_NORMAL;
+    pin->pinConnect->Priority.PrioritySubClass   = 1;
+    pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)(pin->pinConnect + 1);
+    pin->ksDataFormatWfx->DataFormat.FormatSize  = sizeof(KSDATAFORMAT_WAVEFORMATEX);
+    pin->ksDataFormatWfx->DataFormat.Flags       = 0;
+    pin->ksDataFormatWfx->DataFormat.Reserved    = 0;
+    pin->ksDataFormatWfx->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;
+    pin->ksDataFormatWfx->DataFormat.SubFormat   = KSDATAFORMAT_SUBTYPE_PCM;
+    pin->ksDataFormatWfx->DataFormat.Specifier   = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;
+
+    pin->frameSize = 0; /* Unknown until we instantiate pin */
+
+    /* Get the COMMUNICATION property */
+    result = WdmGetPinPropertySimple(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_COMMUNICATION,
+        &pin->communication,
+        sizeof(KSPIN_COMMUNICATION),
+        NULL);
+    if( result != paNoError )
+        goto error;
+
+    if( /*(pin->communication != KSPIN_COMMUNICATION_SOURCE) &&*/
+        (pin->communication != KSPIN_COMMUNICATION_SINK) &&
+        (pin->communication != KSPIN_COMMUNICATION_BOTH) )
+    {
+        PA_DEBUG(("PinNew: Not source/sink\n"));
+        result = paInvalidDevice;
+        goto error;
+    }
+
+    /* Get dataflow information */
+    result = WdmGetPinPropertySimple(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_DATAFLOW,
+        &pin->dataFlow,
+        sizeof(KSPIN_DATAFLOW),
+        NULL);
+
+    if( result != paNoError )
+        goto error;
+
+    /* Get the INTERFACE property list */
+    result = WdmGetPinPropertyMulti(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_INTERFACES,
+        &item);
+
+    if( result != paNoError )
+        goto error;
+
+    identifier = (KSIDENTIFIER*)(item+1);
+
+    /* Check that at least one interface is STANDARD_STREAMING */
+    result = paUnanticipatedHostError;
+    for( i = 0; i < item->Count; i++ )
+    {
+        if( IsEqualGUID(&identifier[i].Set, &KSINTERFACESETID_Standard) && ( identifier[i].Id == streamingId ) )
+        {
+            result = paNoError;
+            break;
+        }
+    }
+
+    if( result != paNoError )
+    {
+        PA_DEBUG(("PinNew: No %s streaming\n", streamingId==KSINTERFACE_STANDARD_LOOPED_STREAMING?"looped":"standard"));
+        goto error;
+    }
+
+    /* Don't need interfaces any more */
+    PaUtil_FreeMemory( item );
+    item = NULL;
+
+    /* Get the MEDIUM properties list */
+    result = WdmGetPinPropertyMulti(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_MEDIUMS,
+        &item);
+
+    if( result != paNoError )
+        goto error;
+
+    identifier = (KSIDENTIFIER*)(item+1); /* Not actually necessary... */
+
+    /* Check that at least one medium is STANDARD_DEVIO */
+    result = paUnanticipatedHostError;
+    for( i = 0; i < item->Count; i++ )
+    {
+        if( IsEqualGUID(&identifier[i].Set, &KSMEDIUMSETID_Standard) && ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) )
+        {
+            result = paNoError;
+            break;
+        }
+    }
+
+    if( result != paNoError )
+    {
+        PA_DEBUG(("No standard devio\n"));
+        goto error;
+    }
+    /* Don't need mediums any more */
+    PaUtil_FreeMemory( item );
+    item = NULL;
+
+    /* Get DATARANGES */
+    result = WdmGetPinPropertyMulti(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_DATARANGES,
+        &pin->dataRangesItem);
+
+    if( result != paNoError )
+        goto error;
+
+    pin->dataRanges = (KSDATARANGE*)(pin->dataRangesItem +1);
+
+    /* Check that at least one datarange supports audio */
+    result = paUnanticipatedHostError;
+    dataRange = pin->dataRanges;
+    pin->maxChannels = 0;
+    pin->defaultSampleRate = 0;
+    pin->formats = 0;
+    PA_DEBUG(("PinNew: Checking %u no of dataranges...\n", pin->dataRangesItem->Count));
+    for( i = 0; i < pin->dataRangesItem->Count; i++)
+    {
+        PA_DEBUG(("PinNew: DR major format %x\n",*(unsigned long*)(&(dataRange->MajorFormat))));
+        /* Check that subformat is WAVEFORMATEX, PCM or WILDCARD */
+        if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) ||
+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) ||
+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_WILDCARD) ||
+            IsEqualGUID(&dataRange->MajorFormat, &KSDATAFORMAT_TYPE_AUDIO) )
+        {
+            int defaultIndex;
+            result = paNoError;
+            /* Record the maximum possible channels with this pin */
+            if( ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels == (ULONG) -1 )
+            {
+                pin->maxChannels = MAXIMUM_NUMBER_OF_CHANNELS;
+            }
+            else if( (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels > pin->maxChannels )
+            {
+                pin->maxChannels = (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels;
+            }
+            PA_DEBUG(("PinNew: MaxChannel: %d\n",pin->maxChannels));
+
+            /* Record the formats (bit depths) that are supported */
+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 8) )
+            {
+                pin->formats |= paInt8;
+                PA_DEBUG(("PinNew: Format PCM 8 bit supported\n"));
+            }
+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 16) )
+            {
+                pin->formats |= paInt16;
+                PA_DEBUG(("PinNew: Format PCM 16 bit supported\n"));
+            }
+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 24) )
+            {
+                pin->formats |= paInt24;
+                PA_DEBUG(("PinNew: Format PCM 24 bit supported\n"));
+            }
+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 32) )
+            {
+                if (IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+                {
+                    pin->formats |= paFloat32;
+                    PA_DEBUG(("PinNew: Format IEEE float 32 bit supported\n"));
+                }
+                else
+                {
+                    pin->formats |= paInt32;
+                    PA_DEBUG(("PinNew: Format PCM 32 bit supported\n"));
+                }
+            }
+
+            defaultIndex = DefaultSampleFrequencyIndex((KSDATARANGE_AUDIO*)dataRange);
+            if (defaultIndex >= 0 && defaultIndex < defaultSampleRateIndex)
+            {
+                defaultSampleRateIndex = defaultIndex;
+            }
+        }
+        dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
+    }
+
+    if( result != paNoError )
+        goto error;
+
+    /* If none of the frequencies searched for are present, there's something seriously wrong */
+    if (defaultSampleRateIndex == defaultSampleRateSearchOrderCount)
+    {
+        PA_DEBUG(("PinNew: No default sample rate found, skipping pin!\n"));
+        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "PinNew: No default sample rate found");
+        result = paUnanticipatedHostError;
+        goto error;
+    }
+
+    /* Set the default sample rate */
+    pin->defaultSampleRate = defaultSampleRateSearchOrder[defaultSampleRateIndex];
+    PA_DEBUG(("PinNew: Default sample rate = %d Hz\n", pin->defaultSampleRate));
+
+    /* Get instance information */
+    result = WdmGetPinPropertySimple(
+        parentFilter->handle,
+        pinId,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_CINSTANCES,
+        &pin->instances,
+        sizeof(KSPIN_CINSTANCES),
+        NULL);
+
+    if( result != paNoError )
+        goto error;
+
+    /* If WaveRT, check if pin supports notification mode */
+    if (parentFilter->devInfo.streamingType == Type_kWaveRT)
+    {
+        BOOL bSupportsNotification = FALSE;
+        if (PinQueryNotificationSupport(pin, &bSupportsNotification) == paNoError)
+        {
+            pin->pinKsSubType = bSupportsNotification ? SubType_kNotification : SubType_kPolled;
+        }
+    }
+
+    /* Query pin name (which means we need to traverse to non IRP pin, via physical connection to topology filter pin, through
+    its nodes to the endpoint pin, and get that ones name... phew...) */
+    PA_DEBUG(("PinNew: Finding topology pin...\n"));
+
+    {
+        ULONG topoPinId = GetConnectedPin(pinId, (pin->dataFlow == KSPIN_DATAFLOW_IN), parentFilter, -1, NULL, NULL);
+        const wchar_t kInputName[] = L"Input";
+        const wchar_t kOutputName[] = L"Output";
+
+        if (topoPinId != KSFILTER_NODE)
+        {
+            /* Get physical connection for topo pin */
+            unsigned long cbBytes = 0;
+            PA_DEBUG(("PinNew: Getting physical connection...\n"));
+            result = WdmGetPinPropertySimple(parentFilter->handle,
+                topoPinId,
+                &KSPROPSETID_Pin,
+                KSPROPERTY_PIN_PHYSICALCONNECTION,
+                0,
+                0,
+                &cbBytes
+                );
+
+            if (result != paNoError)
+            {
+                /* No physical connection -> there is no topology filter! So we get the name of the pin! */
+                PA_DEBUG(("PinNew: No physical connection! Getting the pin name\n"));
+                result = WdmGetPinPropertySimple(parentFilter->handle,
+                    topoPinId,
+                    &KSPROPSETID_Pin,
+                    KSPROPERTY_PIN_NAME,
+                    pin->friendlyName,
+                    MAX_PATH,
+                    NULL);
+                if (result != paNoError)
+                {
+                    GUID category = {0};
+
+                    /* Get pin category information */
+                    result = WdmGetPinPropertySimple(parentFilter->handle,
+                        topoPinId,
+                        &KSPROPSETID_Pin,
+                        KSPROPERTY_PIN_CATEGORY,
+                        &category,
+                        sizeof(GUID),
+                        NULL);
+
+                    if (result == paNoError)
+                    {
+                        result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);
+                    }
+                }
+
+                /* Make sure pin gets a name here... */
+                if (wcslen(pin->friendlyName) == 0)
+                {
+                    wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);
+#ifdef UNICODE
+                    PA_DEBUG(("PinNew: Setting pin friendly name to '%s'\n", pin->friendlyName));
+#else
+                    PA_DEBUG(("PinNew: Setting pin friendly name to '%S'\n", pin->friendlyName));
+#endif
+                }
+
+                /* This is then == the endpoint pin */
+                pin->endpointPinId = (pin->dataFlow == KSPIN_DATAFLOW_IN) ? pinId : topoPinId;
+            }
+            else
+            {
+                KSPIN_PHYSICALCONNECTION* pc = (KSPIN_PHYSICALCONNECTION*)PaUtil_AllocateMemory(cbBytes + 2);
+                ULONG pcPin;
+                wchar_t symbLinkName[MAX_PATH];
+                PA_DEBUG(("PinNew: Physical connection found!\n"));
+                if (pc == NULL)
+                {
+                    result = paInsufficientMemory;
+                    goto error;
+                }
+                result = WdmGetPinPropertySimple(parentFilter->handle,
+                    topoPinId,
+                    &KSPROPSETID_Pin,
+                    KSPROPERTY_PIN_PHYSICALCONNECTION,
+                    pc,
+                    cbBytes,
+                    NULL
+                    );
+
+                pcPin = pc->Pin;
+                wcsncpy(symbLinkName, pc->SymbolicLinkName, MAX_PATH);
+                PaUtil_FreeMemory( pc );
+
+                if (result != paNoError)
+                {
+                    /* Shouldn't happen, but fail if it does */
+                    PA_DEBUG(("PinNew: failed to retrieve physical connection!\n"));
+                    goto error;
+                }
+
+                if (symbLinkName[1] == TEXT('?'))
+                {
+                    symbLinkName[1] = TEXT('\\');
+                }
+
+                if (pin->parentFilter->topologyFilter == NULL)
+                {
+                    PA_DEBUG(("PinNew: Creating topology filter '%S'\n", symbLinkName));
+
+                    pin->parentFilter->topologyFilter = FilterNew(Type_kNotUsed, 0, symbLinkName, L"", &result);
+                    if (pin->parentFilter->topologyFilter == NULL)
+                    {
+                        PA_DEBUG(("PinNew: Failed creating topology filter\n"));
+                        result = paUnanticipatedHostError;
+                        PaWinWDM_SetLastErrorInfo(result, "Failed to create topology filter '%S'", symbLinkName);
+                        goto error;
+                    }
+
+                    /* Copy info so we have it in device info */
+                    wcsncpy(pin->parentFilter->devInfo.topologyPath, symbLinkName, MAX_PATH);
+                }
+                else
+                {
+                    /* Must be the same */
+                    assert(wcscmp(symbLinkName, pin->parentFilter->topologyFilter->devInfo.filterPath) == 0);
+                }
+
+                PA_DEBUG(("PinNew: Opening topology filter..."));
+
+                result = FilterUse(pin->parentFilter->topologyFilter);
+                if (result == paNoError)
+                {
+                    unsigned long endpointPinId;
+
+                    if (pin->dataFlow == KSPIN_DATAFLOW_IN)
+                    {
+                        /* The "endpointPinId" is what WASAPI looks at for pin names */
+                        GUID category = {0};
+
+                        PA_DEBUG(("PinNew: Checking for output endpoint pin id...\n"));
+
+                        endpointPinId = GetConnectedPin(pcPin, TRUE, pin->parentFilter->topologyFilter, -1, NULL, NULL);
+
+                        if (endpointPinId == KSFILTER_NODE)
+                        {
+                            result = paUnanticipatedHostError;
+                            PaWinWDM_SetLastErrorInfo(result, "Failed to get endpoint pin ID on topology filter!");
+                            goto error;
+                        }
+
+                        PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));
+
+                        /* Get pin category information */
+                        result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                            endpointPinId,
+                            &KSPROPSETID_Pin,
+                            KSPROPERTY_PIN_CATEGORY,
+                            &category,
+                            sizeof(GUID),
+                            NULL);
+
+                        if (result == paNoError)
+                        {
+#if !PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES
+                            wchar_t pinName[MAX_PATH];
+
+                            PA_DEBUG(("PinNew: Getting pin name property..."));
+
+                            /* Ok, try pin name also, and favor that if available */
+                            result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                                endpointPinId,
+                                &KSPROPSETID_Pin,
+                                KSPROPERTY_PIN_NAME,
+                                pinName,
+                                MAX_PATH,
+                                NULL);
+
+                            if (result == paNoError && wcslen(pinName)>0)
+                            {
+                                wcsncpy(pin->friendlyName, pinName, MAX_PATH);
+                            }
+                            else
+#endif
+                            {
+                                result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);
+                            }
+                        }
+
+                        /* Make sure we get a name for the pin */
+                        if (wcslen(pin->friendlyName) == 0)
+                        {
+                            wcscpy(pin->friendlyName, kOutputName);
+                        }
+#ifdef UNICODE
+                        PA_DEBUG(("PinNew: Pin name '%s'\n", pin->friendlyName));
+#else
+                        PA_DEBUG(("PinNew: Pin name '%S'\n", pin->friendlyName));
+#endif                                
+
+                        /* Set endpoint pin ID (this is the topology INPUT pin, since portmixer will always traverse the
+                        filter in audio streaming direction, see http://msdn.microsoft.com/en-us/library/windows/hardware/ff536331(v=vs.85).aspx
+                        for more information)
+                        */
+                        pin->endpointPinId = pcPin;
+                    }
+                    else
+                    {
+                        unsigned muxCount = 0;
+                        int muxPos = 0;
+                        /* Max 64 multiplexer inputs... sanity check :) */
+                        for (i = 0; i < 64; ++i)
+                        {
+                            ULONG muxNodeIdTest = (unsigned)-1;
+                            PA_DEBUG(("PinNew: Checking for input endpoint pin id (%d)...\n", i));
+
+                            endpointPinId = GetConnectedPin(pcPin,
+                                FALSE,
+                                pin->parentFilter->topologyFilter,
+                                (int)i,
+                                NULL,
+                                &muxNodeIdTest);
+
+                            if (endpointPinId == KSFILTER_NODE)
+                            {
+                                /* We're done */
+                                PA_DEBUG(("PinNew: Done with inputs.\n", endpointPinId));
+                                break;
+                            }
+                            else
+                            {
+                                /* The "endpointPinId" is what WASAPI looks at for pin names */
+                                GUID category = {0};
+
+                                PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));
+
+                                /* Get pin category information */
+                                result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                                    endpointPinId,
+                                    &KSPROPSETID_Pin,
+                                    KSPROPERTY_PIN_CATEGORY,
+                                    &category,
+                                    sizeof(GUID),
+                                    NULL);
+
+                                if (result == paNoError)
+                                {
+                                    if (muxNodeIdTest == (unsigned)-1)
+                                    {
+                                        /* Ok, try pin name, and favor that if available */
+                                        result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                                            endpointPinId,
+                                            &KSPROPSETID_Pin,
+                                            KSPROPERTY_PIN_NAME,
+                                            pin->friendlyName,
+                                            MAX_PATH,
+                                            NULL);
+
+                                        if (result != paNoError)
+                                        {
+                                            result = GetNameFromCategory(&category, TRUE, pin->friendlyName, MAX_PATH);
+                                        }
+                                        break;
+                                    }
+                                    else
+                                    {
+                                        result = GetNameFromCategory(&category, TRUE, NULL, 0);
+
+                                        if (result == paNoError)
+                                        {
+                                            ++muxCount;
+                                        }
+                                    }
+                                }
+                                else
+                                {
+                                    PA_DEBUG(("PinNew: Failed to get pin category"));
+                                }
+                            }
+                        }
+
+                        if (muxCount == 0)
+                        {
+                            pin->endpointPinId = endpointPinId;
+                            /* Make sure we get a name for the pin */
+                            if (wcslen(pin->friendlyName) == 0)
+                            {
+                                wcscpy(pin->friendlyName, kInputName);
+                            }
+#ifdef UNICODE
+                            PA_DEBUG(("PinNew: Input friendly name '%s'\n", pin->friendlyName));
+#else
+                            PA_DEBUG(("PinNew: Input friendly name '%S'\n", pin->friendlyName));
+#endif
+                        }
+                        else // muxCount > 0
+                        {
+                            PA_DEBUG(("PinNew: Setting up %u inputs\n", muxCount));
+
+                            /* Now we redo the operation once known how many multiplexer positions there are */
+                            pin->inputs = (PaWinWdmMuxedInput**)PaUtil_AllocateMemory(muxCount * sizeof(PaWinWdmMuxedInput*));
+                            if (pin->inputs == NULL)
+                            {
+                                FilterRelease(pin->parentFilter->topologyFilter);
+                                result = paInsufficientMemory;
+                                goto error;
+                            }
+                            pin->inputCount = muxCount;
+
+                            for (i = 0; i < muxCount; ++muxPos)
+                            {
+                                PA_DEBUG(("PinNew: Setting up input %u...\n", i));
+
+                                if (pin->inputs[i] == NULL)
+                                {
+                                    pin->inputs[i] = (PaWinWdmMuxedInput*)PaUtil_AllocateMemory(sizeof(PaWinWdmMuxedInput));
+                                    if (pin->inputs[i] == NULL)
+                                    {
+                                        FilterRelease(pin->parentFilter->topologyFilter);
+                                        result = paInsufficientMemory;
+                                        goto error;
+                                    }
+                                }
+
+                                endpointPinId = GetConnectedPin(pcPin,
+                                    FALSE,
+                                    pin->parentFilter->topologyFilter,
+                                    muxPos,
+                                    &pin->inputs[i]->muxPinId, 
+                                    &pin->inputs[i]->muxNodeId);
+
+                                if (endpointPinId != KSFILTER_NODE)
+                                {
+                                    /* The "endpointPinId" is what WASAPI looks at for pin names */
+                                    GUID category = {0};
+
+                                    /* Set input endpoint ID */
+                                    pin->inputs[i]->endpointPinId = endpointPinId;
+
+                                    /* Get pin category information */
+                                    result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                                        endpointPinId,
+                                        &KSPROPSETID_Pin,
+                                        KSPROPERTY_PIN_CATEGORY,
+                                        &category,
+                                        sizeof(GUID),
+                                        NULL);
+
+                                    if (result == paNoError)
+                                    {
+                                        /* Try pin name first, and if that is not defined, use category instead */
+                                        result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
+                                            endpointPinId,
+                                            &KSPROPSETID_Pin,
+                                            KSPROPERTY_PIN_NAME,
+                                            pin->inputs[i]->friendlyName,
+                                            MAX_PATH,
+                                            NULL);
+
+                                        if (result != paNoError)
+                                        {
+                                            result = GetNameFromCategory(&category, TRUE, pin->inputs[i]->friendlyName, MAX_PATH);
+                                            if (result != paNoError)
+                                            {
+                                                /* Only specify name, let name hash in ScanDeviceInfos fix postfix enumerators */
+                                                wcscpy(pin->inputs[i]->friendlyName, kInputName);
+                                            }
+                                        }
+#ifdef UNICODE
+                                        PA_DEBUG(("PinNew: Input (%u) friendly name '%s'\n", i, pin->inputs[i]->friendlyName));
+#else
+                                        PA_DEBUG(("PinNew: Input (%u) friendly name '%S'\n", i, pin->inputs[i]->friendlyName));
+#endif
+                                        ++i;
+                                    }
+                                }
+                                else
+                                {
+                                    /* Should never come here! */
+                                    assert(FALSE);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        else
+        {
+            PA_DEBUG(("PinNew: No topology pin id found. Bad...\n"));
+            /* No TOPO pin id ??? This is bad. Ok, so we just say it is an input or output... */
+            wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);
+        }
+    }
+
+    /* Release topology filter if it has been used */
+    if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)
+    {
+        PA_DEBUG(("PinNew: Releasing topology filter...\n"));
+        FilterRelease(pin->parentFilter->topologyFilter);
+    }
+
+    /* Success */
+    *error = paNoError;
+    PA_DEBUG(("Pin created successfully\n"));
+    PA_LOGL_;
+    return pin;
+
+error:
+    PA_DEBUG(("PinNew: Error %d\n", result));
+    /*
+    Error cleanup
+    */
+
+    if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)
+    {
+        FilterRelease(pin->parentFilter->topologyFilter);
+    }
+
+    PaUtil_FreeMemory( item );
+    PinFree(pin);
+
+    *error = result;
+    PA_LOGL_;
+    return NULL;
+}
+
+/*
+Safely free all resources associated with the pin
+*/
+static void PinFree(PaWinWdmPin* pin)
+{
+    unsigned i;
+    PA_LOGE_;
+    if( pin )
+    {
+        PinClose(pin);
+        if( pin->pinConnect )
+        {
+            PaUtil_FreeMemory( pin->pinConnect );
+        }
+        if( pin->dataRangesItem )
+        {
+            PaUtil_FreeMemory( pin->dataRangesItem );
+        }
+        if( pin->inputs )
+        {
+            for (i = 0; i < pin->inputCount; ++i)
+            {
+                PaUtil_FreeMemory( pin->inputs[i] );
+            }
+            PaUtil_FreeMemory( pin->inputs );
+        }
+        PaUtil_FreeMemory( pin );
+    }
+    PA_LOGL_;
+}
+
+/*
+If the pin handle is open, close it
+*/
+static void PinClose(PaWinWdmPin* pin)
+{
+    PA_LOGE_;
+    if( pin == NULL )
+    {
+        PA_DEBUG(("Closing NULL pin!"));
+        PA_LOGL_;
+        return;
+    }
+    if( pin->handle != NULL )
+    {
+        PinSetState( pin, KSSTATE_PAUSE );
+        PinSetState( pin, KSSTATE_STOP );
+        CloseHandle( pin->handle );
+        pin->handle = NULL;
+        FilterRelease(pin->parentFilter);
+    }
+    PA_LOGL_;
+}
+
+/*
+Set the state of this (instantiated) pin
+*/
+static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state)
+{
+    PaError result = paNoError;
+    KSPROPERTY prop;
+
+    PA_LOGE_;
+    prop.Set = KSPROPSETID_Connection;
+    prop.Id  = KSPROPERTY_CONNECTION_STATE;
+    prop.Flags = KSPROPERTY_TYPE_SET;
+
+    if( pin == NULL )
+        return paInternalError;
+    if( pin->handle == NULL )
+        return paInternalError;
+
+    result = WdmSyncIoctl(pin->handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSPROPERTY), &state, sizeof(KSSTATE), NULL);
+
+    PA_LOGL_;
+    return result;
+}
+
+static PaError PinInstantiate(PaWinWdmPin* pin)
+{
+    PaError result;
+    unsigned long createResult;
+    KSALLOCATOR_FRAMING ksaf;
+    KSALLOCATOR_FRAMING_EX ksafex;
+
+    PA_LOGE_;
+
+    if( pin == NULL )
+        return paInternalError;
+    if(!pin->pinConnect)
+        return paInternalError;
+
+    FilterUse(pin->parentFilter);
+
+    createResult = FunctionKsCreatePin(
+        pin->parentFilter->handle,
+        pin->pinConnect,
+        GENERIC_WRITE | GENERIC_READ,
+        &pin->handle
+        );
+
+    PA_DEBUG(("Pin create result = 0x%08x\n",createResult));
+    if( createResult != ERROR_SUCCESS )
+    {
+        FilterRelease(pin->parentFilter);
+        pin->handle = NULL;
+        switch (createResult)
+        {
+        case ERROR_INVALID_PARAMETER:
+            /* First case when pin actually don't support the format */
+            return paSampleFormatNotSupported;
+        case ERROR_BAD_COMMAND:
+            /* Case when pin is occupied (by another application) */
+            return paDeviceUnavailable;
+        default:
+            /* All other cases */
+            return paInvalidDevice;
+        }
+    }
+
+    if (pin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
+    {
+        /* Framing size query only valid for WaveCyclic devices */
+        result = WdmGetPropertySimple(
+            pin->handle,
+            &KSPROPSETID_Connection,
+            KSPROPERTY_CONNECTION_ALLOCATORFRAMING,
+            &ksaf,
+            sizeof(ksaf));
+
+        if( result != paNoError )
+        {
+            result = WdmGetPropertySimple(
+                pin->handle,
+                &KSPROPSETID_Connection,
+                KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,
+                &ksafex,
+                sizeof(ksafex));
+            if( result == paNoError )
+            {
+                pin->frameSize = ksafex.FramingItem[0].FramingRange.Range.MinFrameSize;
+            }
+        }
+        else
+        {
+            pin->frameSize = ksaf.FrameSize;
+        }
+    }
+
+    PA_LOGL_;
+
+    return paNoError;
+}
+
+static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format)
+{
+    unsigned long size;
+    void* newConnect;
+
+    PA_LOGE_;
+
+    if( pin == NULL )
+        return paInternalError;
+    if( format == NULL )
+        return paInternalError;
+
+    size = GetWfexSize(format) + sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX) - sizeof(WAVEFORMATEX);
+
+    if( pin->pinConnectSize != size )
+    {
+        newConnect = PaUtil_AllocateMemory( size );
+        if( newConnect == NULL )
+            return paInsufficientMemory;
+        memcpy( newConnect, (void*)pin->pinConnect, min(pin->pinConnectSize,size) );
+        PaUtil_FreeMemory( pin->pinConnect );
+        pin->pinConnect = (KSPIN_CONNECT*)newConnect;
+        pin->pinConnectSize = size;
+        pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)((KSPIN_CONNECT*)newConnect + 1);
+        pin->ksDataFormatWfx->DataFormat.FormatSize = size - sizeof(KSPIN_CONNECT);
+    }
+
+    memcpy( (void*)&(pin->ksDataFormatWfx->WaveFormatEx), format, GetWfexSize(format) );
+    pin->ksDataFormatWfx->DataFormat.SampleSize = (unsigned short)(format->nChannels * (format->wBitsPerSample / 8));
+
+    PA_LOGL_;
+
+    return paNoError;
+}
+
+static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format)
+{
+    KSDATARANGE_AUDIO* dataRange;
+    unsigned long count;
+    GUID guid = DYNAMIC_GUID( DEFINE_WAVEFORMATEX_GUID(format->wFormatTag) );
+    PaError result = paInvalidDevice;
+    const WAVEFORMATEXTENSIBLE* pFormatExt = (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) ? (const WAVEFORMATEXTENSIBLE*)format : 0;
+
+    PA_LOGE_;
+
+    if( pFormatExt != 0 )
+    {
+        guid = pFormatExt->SubFormat;
+    }
+    dataRange = (KSDATARANGE_AUDIO*)pin->dataRanges;
+    for(count = 0;
+        count<pin->dataRangesItem->Count;
+        count++, 
+        dataRange = (KSDATARANGE_AUDIO*)( ((char*)dataRange) + dataRange->DataRange.FormatSize)) /* Need to update dataRange here, due to 'continue' !! */
+    {
+        /* Check major format*/
+        if (!(IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_AUDIO) ||
+            IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_WILDCARD)))
+        {
+            continue;
+        }
+
+        /* This is an audio or wildcard datarange... */
+        if (! (IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_WILDCARD) ||
+            IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_PCM) ||
+            IsEqualGUID(&(dataRange->DataRange.SubFormat), &guid) ))
+        {
+            continue;
+        }
+
+        /* Check specifier... */
+        if (! (IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WILDCARD) ||
+            IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)) )
+        {
+            continue;
+        }
+
+        PA_DEBUG(("Pin:%x, DataRange:%d\n",(void*)pin,count));
+        PA_DEBUG(("\tFormatSize:%d, SampleSize:%d\n",dataRange->DataRange.FormatSize,dataRange->DataRange.SampleSize));
+        PA_DEBUG(("\tMaxChannels:%d\n",dataRange->MaximumChannels));
+        PA_DEBUG(("\tBits:%d-%d\n",dataRange->MinimumBitsPerSample,dataRange->MaximumBitsPerSample));
+        PA_DEBUG(("\tSampleRate:%d-%d\n",dataRange->MinimumSampleFrequency,dataRange->MaximumSampleFrequency));
+
+        if( dataRange->MaximumChannels != (ULONG)-1 && 
+            dataRange->MaximumChannels < format->nChannels )
+        {
+            result = paInvalidChannelCount;
+            continue;
+        }
+
+        if (pFormatExt != 0)
+        {
+            if (!IsBitsWithinRange(dataRange, pFormatExt->Samples.wValidBitsPerSample))
+            {
+                result = paSampleFormatNotSupported;
+                continue;
+            }
+        }
+        else
+        {
+            if (!IsBitsWithinRange(dataRange, format->wBitsPerSample))
+            {
+                result = paSampleFormatNotSupported;
+                continue;
+            }
+        }
+
+        if (!IsFrequencyWithinRange(dataRange, format->nSamplesPerSec))
+        {
+            result = paInvalidSampleRate;
+            continue;
+        }
+
+        /* Success! */
+        result = paNoError;
+        break;
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult)
+{
+    PaError result = paNoError;
+    KSPROPERTY propIn;
+
+    PA_LOGE_;
+
+    propIn.Set = KSPROPSETID_RtAudio;
+    propIn.Id = 8; /* = KSPROPERTY_RTAUDIO_QUERY_NOTIFICATION_SUPPORT */
+    propIn.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
+        &propIn,
+        sizeof(KSPROPERTY),
+        pbResult,
+        sizeof(BOOL),
+        NULL);
+
+    if (result != paNoError) 
+    {
+        PA_DEBUG(("Failed PinQueryNotificationSupport\n"));
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+static PaError PinGetBufferWithNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
+{
+    PaError result = paNoError;
+    KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION propIn;
+    KSRTAUDIO_BUFFER propOut;
+
+    PA_LOGE_;
+
+    propIn.BaseAddress = 0;
+    propIn.NotificationCount = 2;
+    propIn.RequestedBufferSize = *pRequestedBufSize;
+    propIn.Property.Set = KSPROPSETID_RtAudio;
+    propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION;
+    propIn.Property.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
+        &propIn,
+        sizeof(KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION),
+        &propOut,
+        sizeof(KSRTAUDIO_BUFFER),
+        NULL);
+
+    if (result == paNoError) 
+    {
+        *pBuffer = propOut.BufferAddress;
+        *pRequestedBufSize = propOut.ActualBufferSize;
+        *pbCallMemBarrier = propOut.CallMemoryBarrier;
+    }
+    else 
+    {
+        PA_DEBUG(("Failed to get buffer with notification\n"));
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+static PaError PinGetBufferWithoutNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
+{
+    PaError result = paNoError;
+    KSRTAUDIO_BUFFER_PROPERTY propIn;
+    KSRTAUDIO_BUFFER propOut;
+
+    PA_LOGE_;
+
+    propIn.BaseAddress = NULL;
+    propIn.RequestedBufferSize = *pRequestedBufSize;
+    propIn.Property.Set = KSPROPSETID_RtAudio;
+    propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER;
+    propIn.Property.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
+        &propIn,
+        sizeof(KSRTAUDIO_BUFFER_PROPERTY),
+        &propOut,
+        sizeof(KSRTAUDIO_BUFFER),
+        NULL);
+
+    if (result == paNoError)
+    {
+        *pBuffer = propOut.BufferAddress;
+        *pRequestedBufSize = propOut.ActualBufferSize;
+        *pbCallMemBarrier = propOut.CallMemoryBarrier;
+    }
+    else 
+    {
+        PA_DEBUG(("Failed to get buffer without notification\n"));
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+/* greatest common divisor - PGCD in French */
+static unsigned long PaWinWDMGCD( unsigned long a, unsigned long b )
+{
+    return (b==0) ? a : PaWinWDMGCD( b, a%b);
+}
+
+
+/* This function will handle getting the cyclic buffer from a WaveRT driver. Certain WaveRT drivers needs to have
+requested buffer size on multiples of 128 bytes:
+
+*/
+static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
+{
+    PaError result = paNoError;
+    int limit = 1000;
+    PA_LOGE_;
+
+    while (1)
+    {
+        limit--;
+        if (limit == 0) {
+           PA_DEBUG(("PinGetBuffer: LOOP LIMIT REACHED\n"));
+           break;
+        }
+
+        if (pPin->pinKsSubType != SubType_kPolled)
+        {
+            /* In case of unknown (or notification), we try both modes */
+            result = PinGetBufferWithNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);
+            if (result == paNoError)
+            {
+                PA_DEBUG(("PinGetBuffer: SubType_kNotification\n"));
+                pPin->pinKsSubType = SubType_kNotification;
+                break;
+            }
+        }
+
+        result = PinGetBufferWithoutNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);
+        if (result == paNoError)
+        {
+            PA_DEBUG(("PinGetBuffer: SubType_kPolled\n"));
+            pPin->pinKsSubType = SubType_kPolled;
+            break;
+        }
+
+        /* Check if requested size is on a 128 byte boundary */
+        if (((*pRequestedBufSize) % 128UL) == 0)
+        {
+            PA_DEBUG(("Buffer size on 128 byte boundary, still fails :(\n"));
+            /* Ok, can't do much more */
+            break;
+        }
+        else
+        {
+            /* Compute LCM so we know which sizes are on a 128 byte boundary */
+            const unsigned gcd = PaWinWDMGCD(128UL, pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign);
+            const unsigned lcm = (128UL * pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign) / gcd;
+            DWORD dwOldSize = *pRequestedBufSize;
+
+            /* Align size to (next larger) LCM byte boundary, and then we try again. Note that LCM is not necessarily a
+            power of 2. */
+            *pRequestedBufSize = ((*pRequestedBufSize + lcm - 1) / lcm) * lcm;
+
+            PA_DEBUG(("Adjusting buffer size from %u to %u bytes (128 byte boundary, LCM=%u)\n", dwOldSize, *pRequestedBufSize, lcm));
+        }
+    }
+
+    PA_LOGL_;
+
+    return result;
+}
+
+static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin) 
+{
+    PaError result = paNoError;
+    KSRTAUDIO_HWREGISTER_PROPERTY propIn;
+    KSRTAUDIO_HWREGISTER propOut;
+
+    PA_LOGE_;
+
+    propIn.BaseAddress = NULL;
+    propIn.Property.Set = KSPROPSETID_RtAudio;
+    propIn.Property.Id = KSPROPERTY_RTAUDIO_POSITIONREGISTER;
+    propIn.Property.Flags = KSPROPERTY_TYPE_SET;
+
+    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
+        &propIn,
+        sizeof(KSRTAUDIO_HWREGISTER_PROPERTY),
+        &propOut,
+        sizeof(KSRTAUDIO_HWREGISTER),
+        NULL);
+
+    if (result == paNoError) 
+    {
+        pPin->positionRegister = (ULONG*)propOut.Register;
+    }
+    else
+    {
+        PA_DEBUG(("Failed to register position register\n"));
+    }
+
+    PA_LOGL_;
+
+    return result;
+}
+
+static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle) 
+{
+    PaError result = paNoError;
+    KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;
+
+    PA_LOGE_;
+
+    prop.NotificationEvent = handle;
+    prop.Property.Set = KSPROPSETID_RtAudio;
+    prop.Property.Id = KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT;
+    prop.Property.Flags = KSPROPERTY_TYPE_SET;
+
+    result = WdmSyncIoctl(pPin->handle,
+        IOCTL_KS_PROPERTY,
+        &prop,
+        sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
+        &prop,
+        sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
+        NULL);
+
+    if (result != paNoError) {
+        PA_DEBUG(("Failed to register notification handle 0x%08X\n", handle));
+    }
+
+    PA_LOGL_;
+
+    return result;
+}
+
+static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle) 
+{
+    PaError result = paNoError;
+    KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;
+
+    PA_LOGE_;
+
+    if (handle != NULL)
+    {
+        prop.NotificationEvent = handle;
+        prop.Property.Set = KSPROPSETID_RtAudio;
+        prop.Property.Id = KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT;
+        prop.Property.Flags = KSPROPERTY_TYPE_SET;
+
+        result = WdmSyncIoctl(pPin->handle,
+            IOCTL_KS_PROPERTY,
+            &prop,
+            sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
+            &prop,
+            sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
+            NULL);
+
+        if (result != paNoError) {
+            PA_DEBUG(("Failed to unregister notification handle 0x%08X\n", handle));
+        }
+    }
+    PA_LOGL_;
+
+    return result;
+}
+
+static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay)
+{
+    PaError result = paNoError;
+    KSPROPERTY propIn;
+    KSRTAUDIO_HWLATENCY propOut;
+
+    PA_LOGE_;
+
+    propIn.Set = KSPROPSETID_RtAudio;
+    propIn.Id = KSPROPERTY_RTAUDIO_HWLATENCY;
+    propIn.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
+        &propIn,
+        sizeof(KSPROPERTY),
+        &propOut,
+        sizeof(KSRTAUDIO_HWLATENCY),
+        NULL);
+
+    if (result == paNoError)
+    {
+        *pFifoSize = propOut.FifoSize;
+        *pChipsetDelay = propOut.ChipsetDelay;
+        *pCodecDelay = propOut.CodecDelay;
+    }
+    else
+    {
+        PA_DEBUG(("Failed to retrieve hardware FIFO size!\n"));
+    }
+
+    PA_LOGL_;
+
+    return result;
+}
+
+/* This one is used for WaveRT */
+static PaError PinGetAudioPositionMemoryMapped(PaWinWdmPin* pPin, ULONG* pPosition)
+{
+    *pPosition = (*pPin->positionRegister);
+    return paNoError;
+}
+
+/* This one also, but in case the driver hasn't implemented memory mapped access to the position register */
+static PaError PinGetAudioPositionViaIOCTLRead(PaWinWdmPin* pPin, ULONG* pPosition)
+{
+    PaError result = paNoError;
+    KSPROPERTY propIn;
+    KSAUDIO_POSITION propOut;
+
+    PA_LOGE_;
+
+    propIn.Set = KSPROPSETID_Audio;
+    propIn.Id = KSPROPERTY_AUDIO_POSITION;
+    propIn.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle,
+        IOCTL_KS_PROPERTY,
+        &propIn, sizeof(KSPROPERTY),
+        &propOut, sizeof(KSAUDIO_POSITION),
+        NULL);
+
+    if (result == paNoError)
+    {
+        *pPosition = (ULONG)(propOut.PlayOffset);
+    }
+    else
+    {
+        PA_DEBUG(("Failed to get audio play position!\n"));
+    }
+
+    PA_LOGL_;
+
+    return result;
+
+}
+
+/* This one also, but in case the driver hasn't implemented memory mapped access to the position register */
+static PaError PinGetAudioPositionViaIOCTLWrite(PaWinWdmPin* pPin, ULONG* pPosition)
+{
+    PaError result = paNoError;
+    KSPROPERTY propIn;
+    KSAUDIO_POSITION propOut;
+
+    PA_LOGE_;
+
+    propIn.Set = KSPROPSETID_Audio;
+    propIn.Id = KSPROPERTY_AUDIO_POSITION;
+    propIn.Flags = KSPROPERTY_TYPE_GET;
+
+    result = WdmSyncIoctl(pPin->handle,
+        IOCTL_KS_PROPERTY,
+        &propIn, sizeof(KSPROPERTY),
+        &propOut, sizeof(KSAUDIO_POSITION),
+        NULL);
+
+    if (result == paNoError)
+    {
+        *pPosition = (ULONG)(propOut.WriteOffset);
+    }
+    else
+    {
+        PA_DEBUG(("Failed to get audio write position!\n"));
+    }
+
+    PA_LOGL_;
+
+    return result;
+
+}
+
+/***********************************************************************************************/
+
+/**
+* Create a new filter object. 
+*/
+static PaWinWdmFilter* FilterNew( PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error )
+{
+    PaWinWdmFilter* filter = 0;
+    PaError result;
+
+    /* Allocate the new filter object */
+    filter = (PaWinWdmFilter*)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter) );
+    if( !filter )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    PA_DEBUG(("FilterNew: Creating filter '%S'\n", friendlyName));
+
+    /* Set type flag */
+    filter->devInfo.streamingType = type;
+
+    /* Store device node */
+    filter->deviceNode = devNode;
+
+    /* Zero the filter object - done by AllocateMemory */
+    /* memset( (void*)filter, 0, sizeof(PaWinWdmFilter) ); */
+
+    /* Copy the filter name */
+    wcsncpy(filter->devInfo.filterPath, filterName, MAX_PATH);
+
+    /* Copy the friendly name */
+    wcsncpy(filter->friendlyName, friendlyName, MAX_PATH);
+
+    PA_DEBUG(("FilterNew: Opening filter...\n", friendlyName));
+
+    /* Open the filter handle */
+    result = FilterUse(filter);
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    /* Get pin count */
+    result = WdmGetPinPropertySimple
+        (
+        filter->handle,
+        0,
+        &KSPROPSETID_Pin,
+        KSPROPERTY_PIN_CTYPES,
+        &filter->pinCount,
+        sizeof(filter->pinCount),
+        NULL);
+
+    if( result != paNoError)
+    {
+        goto error;
+    }
+
+    /* Get connections & nodes for filter */
+    result = WdmGetPropertyMulti(
+        filter->handle,
+        &KSPROPSETID_Topology,
+        KSPROPERTY_TOPOLOGY_CONNECTIONS,
+        &filter->connections);
+
+    if( result != paNoError)
+    {
+        goto error;
+    }
+
+    result = WdmGetPropertyMulti(
+        filter->handle,
+        &KSPROPSETID_Topology,
+        KSPROPERTY_TOPOLOGY_NODES,
+        &filter->nodes);
+
+    if( result != paNoError)
+    {
+        goto error;
+    }
+
+    /* For debugging purposes */
+    DumpConnectionsAndNodes(filter);
+
+    /* Get product GUID (it might not be supported) */
+    {
+        KSCOMPONENTID compId;
+        if (WdmGetPropertySimple(filter->handle, &KSPROPSETID_General, KSPROPERTY_GENERAL_COMPONENTID, &compId, sizeof(KSCOMPONENTID)) == paNoError)
+        {
+            filter->devInfo.deviceProductGuid = compId.Product;
+        }
+    }
+
+    /* This section is not executed for topology filters */
+    if (type != Type_kNotUsed)
+    {
+        /* Initialize the pins */
+        result = FilterInitializePins(filter);
+
+        if( result != paNoError)
+        {
+            goto error;
+        }
+    }
+
+    /* Close the filter handle for now
+    * It will be opened later when needed */
+    FilterRelease(filter);
+
+    *error = paNoError;
+    return filter;
+
+error:
+    PA_DEBUG(("FilterNew: Error %d\n", result));
+    /*
+    Error cleanup
+    */
+    FilterFree(filter);
+
+    *error = result;
+    return NULL;
+}
+
+/**
+* Add reference to filter
+*/
+static void FilterAddRef( PaWinWdmFilter* filter )
+{
+    if (filter != 0)
+    {
+        filter->filterRefCount++;
+    }
+}
+
+
+/**
+* Initialize the pins of the filter. This is separated from FilterNew because this might fail if there is another
+* process using the pin(s).
+*/
+PaError FilterInitializePins( PaWinWdmFilter* filter )
+{
+    PaError result = paNoError;
+    int pinId;
+
+    if (filter->devInfo.streamingType == Type_kNotUsed)
+        return paNoError;
+
+    if (filter->pins != NULL)
+        return paNoError;   
+
+    /* Allocate pointer array to hold the pins */
+    filter->pins = (PaWinWdmPin**)PaUtil_AllocateMemory( sizeof(PaWinWdmPin*) * filter->pinCount );
+    if( !filter->pins )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Create all the pins we can */
+    for(pinId = 0; pinId < filter->pinCount; pinId++)
+    {
+        /* Create the pin with this Id */
+        PaWinWdmPin* newPin;
+        newPin = PinNew(filter, pinId, &result);
+        if( result == paInsufficientMemory )
+            goto error;
+        if( newPin != NULL )
+        {
+            filter->pins[pinId] = newPin;
+            ++filter->validPinCount;
+        }
+    }
+
+    if (filter->validPinCount == 0)
+    {
+        result = paDeviceUnavailable;
+        goto error;
+    }
+
+    return paNoError;
+
+error:
+
+    if (filter->pins)
+    {
+        for (pinId = 0; pinId < filter->pinCount; ++pinId)
+        {
+            if (filter->pins[pinId])
+            {
+                PinFree(filter->pins[pinId]);
+                filter->pins[pinId] = 0;
+            }
+        }
+        PaUtil_FreeMemory( filter->pins );
+        filter->pins = 0;
+    }
+
+    return result;
+}
+
+
+/**
+* Free a previously created filter
+*/
+static void FilterFree(PaWinWdmFilter* filter)
+{
+    PA_LOGL_;
+    if( filter )
+    {
+        if (--filter->filterRefCount > 0)
+        {
+            /* Ok, a stream has a ref count to this filter */
+            return;
+        }
+
+        if ( filter->topologyFilter )
+        {
+            FilterFree(filter->topologyFilter);
+            filter->topologyFilter = 0;
+        }
+        if ( filter->pins )
+        {
+            int pinId;
+            for( pinId = 0; pinId < filter->pinCount; pinId++ )
+                PinFree(filter->pins[pinId]);
+            PaUtil_FreeMemory( filter->pins );
+            filter->pins = 0;
+        }
+        if( filter->connections )
+        {
+            PaUtil_FreeMemory(filter->connections);
+            filter->connections = 0;
+        }
+        if( filter->nodes )
+        {
+            PaUtil_FreeMemory(filter->nodes);
+            filter->nodes = 0;
+        }
+        if( filter->handle )
+            CloseHandle( filter->handle );
+        PaUtil_FreeMemory( filter );
+    }
+    PA_LOGE_;
+}
+
+/**
+* Reopen the filter handle if necessary so it can be used
+**/
+static PaError FilterUse(PaWinWdmFilter* filter)
+{
+    assert( filter );
+
+    PA_LOGE_;
+    if( filter->handle == NULL )
+    {
+        /* Open the filter */
+        filter->handle = CreateFileW(
+            filter->devInfo.filterPath,
+            GENERIC_READ | GENERIC_WRITE,
+            0,
+            NULL,
+            OPEN_EXISTING,
+            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
+            NULL);
+
+        if( filter->handle == NULL )
+        {
+            return paDeviceUnavailable;
+        }
+    }
+    filter->usageCount++;
+    PA_LOGL_;
+    return paNoError;
+}
+
+/**
+* Release the filter handle if nobody is using it
+**/
+static void FilterRelease(PaWinWdmFilter* filter)
+{
+    assert( filter );
+    assert( filter->usageCount > 0 );
+
+    PA_LOGE_;
+    /* Check first topology filter, if used */
+    if (filter->topologyFilter != NULL && filter->topologyFilter->handle != NULL)
+    {
+        FilterRelease(filter->topologyFilter);
+    }
+
+    filter->usageCount--;
+    if( filter->usageCount == 0 )
+    {
+        if( filter->handle != NULL )
+        {
+            CloseHandle( filter->handle );
+            filter->handle = NULL;
+        }
+    }
+    PA_LOGL_;
+}
+
+/**
+* Create a render or playback pin using the supplied format
+**/
+static PaWinWdmPin* FilterCreatePin(PaWinWdmFilter* filter,
+                                    int pinId,
+                                    const WAVEFORMATEX* wfex,
+                                    PaError* error)
+{
+    PaError result = paNoError;
+    PaWinWdmPin* pin = NULL;
+    assert( filter );
+    assert( pinId < filter->pinCount );
+    pin = filter->pins[pinId];
+    assert( pin );
+    result = PinSetFormat(pin,wfex);
+    if( result == paNoError )
+    {
+        result = PinInstantiate(pin);
+    }
+    *error = result;
+    return result == paNoError ? pin : 0;
+}
+
+static const wchar_t kUsbPrefix[] = L"\\\\?\\USB";
+
+static BOOL IsUSBDevice(const wchar_t* devicePath)
+{
+    /* Alex Lessard pointed out that different devices might present the device path with
+       lower case letters. */
+    return (_wcsnicmp(devicePath, kUsbPrefix, sizeof(kUsbPrefix)/sizeof(kUsbPrefix[0]) ) == 0);
+}
+
+/* This should make it more language tolerant, I hope... */
+static const wchar_t kUsbNamePrefix[] = L"USB Audio";
+
+static BOOL IsNameUSBAudioDevice(const wchar_t* friendlyName)
+{
+    return (_wcsnicmp(friendlyName, kUsbNamePrefix, sizeof(kUsbNamePrefix)/sizeof(kUsbNamePrefix[0])) == 0);
+}
+
+typedef enum _tag_EAlias
+{
+    Alias_kRender   = (1<<0),
+    Alias_kCapture  = (1<<1),
+    Alias_kRealtime = (1<<2),
+} EAlias;
+
+/* Trim whitespace from string */
+static void TrimString(wchar_t* str, size_t length)
+{
+    wchar_t* s = str;
+    wchar_t* e = 0;
+
+    /* Find start of string */
+    while (iswspace(*s)) ++s;
+    e=s+min(length,wcslen(s))-1;
+
+    /* Find end of string */
+    while(e>s && iswspace(*e)) --e;
+    ++e;
+
+    length = e - s;
+    memmove(str, s, length * sizeof(wchar_t));
+    str[length] = 0;
+}
+
+/**
+* Build the list of available filters
+* Use the SetupDi API to enumerate all devices in the KSCATEGORY_AUDIO which 
+* have a KSCATEGORY_RENDER or KSCATEGORY_CAPTURE alias. For each of these 
+* devices initialise a PaWinWdmFilter structure by calling our NewFilter() 
+* function. We enumerate devices twice, once to count how many there are, 
+* and once to initialize the PaWinWdmFilter structures.
+*
+* Vista and later: Also check KSCATEGORY_REALTIME for WaveRT devices.
+*/
+//PaError BuildFilterList( PaWinWdmHostApiRepresentation* wdmHostApi, int* noOfPaDevices )
+PaWinWdmFilter** BuildFilterList( int* pFilterCount, int* pNoOfPaDevices, PaError* pResult )
+{
+    PaWinWdmFilter** ppFilters = NULL;
+    HDEVINFO handle = NULL;
+    int device;
+    int invalidDevices;
+    int slot;
+    SP_DEVICE_INTERFACE_DATA interfaceData;
+    SP_DEVICE_INTERFACE_DATA aliasData;
+    SP_DEVINFO_DATA devInfoData;
+    int noError;
+    const int sizeInterface = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR));
+    unsigned char interfaceDetailsArray[sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR))];
+    SP_DEVICE_INTERFACE_DETAIL_DATA_W* devInterfaceDetails = (SP_DEVICE_INTERFACE_DETAIL_DATA_W*)interfaceDetailsArray;
+    const GUID* category = (const GUID*)&KSCATEGORY_AUDIO;
+    const GUID* alias_render = (const GUID*)&KSCATEGORY_RENDER;
+    const GUID* alias_capture = (const GUID*)&KSCATEGORY_CAPTURE;
+    const GUID* category_realtime = (const GUID*)&KSCATEGORY_REALTIME;
+    DWORD aliasFlags;
+    PaWDMKSType streamingType;
+    int filterCount = 0;
+    int noOfPaDevices = 0;
+
+    PA_LOGE_;
+
+    assert(pFilterCount != NULL);
+    assert(pNoOfPaDevices != NULL);
+    assert(pResult != NULL);
+
+    devInterfaceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
+    *pFilterCount = 0;
+    *pNoOfPaDevices = 0;
+
+    /* Open a handle to search for devices (filters) */
+    handle = SetupDiGetClassDevs(category,NULL,NULL,DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
+    if( handle == INVALID_HANDLE_VALUE )
+    {
+        *pResult = paUnanticipatedHostError;
+        return NULL;
+    }
+    PA_DEBUG(("Setup called\n"));
+
+    /* First let's count the number of devices so we can allocate a list */
+    invalidDevices = 0;
+    for( device = 0;;device++ )
+    {
+        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+        interfaceData.Reserved = 0;
+        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+        aliasData.Reserved = 0;
+        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
+        PA_DEBUG(("Enum called\n"));
+        if( !noError )
+            break; /* No more devices */
+
+        /* Check this one has the render or capture alias */
+        aliasFlags = 0;
+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
+        PA_DEBUG(("noError = %d\n",noError));
+        if(noError)
+        {
+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
+            {
+                PA_DEBUG(("Device %d has render alias\n",device));
+                aliasFlags |= Alias_kRender; /* Has render alias */
+            }
+            else
+            {
+                PA_DEBUG(("Device %d has no render alias\n",device));
+            }
+        }
+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
+        if(noError)
+        {
+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
+            {
+                PA_DEBUG(("Device %d has capture alias\n",device));
+                aliasFlags |= Alias_kCapture; /* Has capture alias */
+            }
+            else
+            {
+                PA_DEBUG(("Device %d has no capture alias\n",device));
+            }
+        }
+        if(!aliasFlags)
+            invalidDevices++; /* This was not a valid capture or render audio device */
+    }
+    /* Remember how many there are */
+    filterCount = device-invalidDevices;
+
+    PA_DEBUG(("Interfaces found: %d\n",device-invalidDevices));
+
+    /* Now allocate the list of pointers to devices */
+    ppFilters  = (PaWinWdmFilter**)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter*) * filterCount);
+    if( ppFilters == 0 )
+    {
+        if(handle != NULL)
+            SetupDiDestroyDeviceInfoList(handle);
+        *pResult = paInsufficientMemory;
+        return NULL;
+    }
+
+    /* Now create filter objects for each interface found */
+    slot = 0;
+    for( device = 0;;device++ )
+    {
+        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+        interfaceData.Reserved = 0;
+        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+        aliasData.Reserved = 0;
+        devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
+        devInfoData.Reserved = 0;
+        streamingType = Type_kWaveCyclic;
+
+        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
+        if( !noError )
+            break; /* No more devices */
+
+        /* Check this one has the render or capture alias */
+        aliasFlags = 0;
+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
+        if(noError)
+        {
+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
+            {
+                PA_DEBUG(("Device %d has render alias\n",device));
+                aliasFlags |= Alias_kRender; /* Has render alias */
+            }
+        }
+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
+        if(noError)
+        {
+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
+            {
+                PA_DEBUG(("Device %d has capture alias\n",device));
+                aliasFlags |= Alias_kCapture; /* Has capture alias */
+            }
+        }
+        if(!aliasFlags)
+        {
+            continue; /* This was not a valid capture or render audio device */
+        }
+        else
+        {
+            /* Check if filter is WaveRT, if not it is a WaveCyclic */
+            noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,category_realtime,&aliasData);
+            if (noError)
+            {
+                PA_DEBUG(("Device %d has realtime alias\n",device));
+                aliasFlags |= Alias_kRealtime;
+                streamingType = Type_kWaveRT;
+            }
+        }
+
+        noError = SetupDiGetDeviceInterfaceDetailW(handle,&interfaceData,devInterfaceDetails,sizeInterface,NULL,&devInfoData);
+        if( noError )
+        {
+            DWORD type;
+            WCHAR friendlyName[MAX_PATH] = {0};
+            DWORD sizeFriendlyName;
+            PaWinWdmFilter* newFilter = 0;
+
+            PaError result = paNoError;
+            /* Try to get the "friendly name" for this interface */
+            sizeFriendlyName = sizeof(friendlyName);
+
+            if (IsEarlierThanVista() && IsUSBDevice(devInterfaceDetails->DevicePath))
+            {
+                /* XP and USB audio device needs to look elsewhere, otherwise it'll only be a "USB Audio Device". Not
+                very literate. */
+                if (!SetupDiGetDeviceRegistryPropertyW(handle,
+                    &devInfoData,
+                    SPDRP_LOCATION_INFORMATION, 
+                    &type,
+                    (BYTE*)friendlyName,
+                    sizeof(friendlyName),
+                    NULL))
+                {
+                    friendlyName[0] = 0;
+                }
+            }
+
+            if (friendlyName[0] == 0 || IsNameUSBAudioDevice(friendlyName))
+            {
+                /* Fix contributed by Ben Allison
+                * Removed KEY_SET_VALUE from flags on following call
+                * as its causes failure when running without admin rights
+                * and it was not required */
+                HKEY hkey=SetupDiOpenDeviceInterfaceRegKey(handle,&interfaceData,0,KEY_QUERY_VALUE);
+                if(hkey!=INVALID_HANDLE_VALUE)
+                {
+                    noError = RegQueryValueExW(hkey,L"FriendlyName",0,&type,(BYTE*)friendlyName,&sizeFriendlyName);
+                    if( noError == ERROR_SUCCESS )
+                    {
+                        PA_DEBUG(("Interface %d, Name: %s\n",device,friendlyName));
+                        RegCloseKey(hkey);
+                    }
+                    else
+                    {
+                        friendlyName[0] = 0;
+                    }
+                }
+            }
+
+            TrimString(friendlyName, sizeFriendlyName);
+
+            newFilter = FilterNew(streamingType, 
+                devInfoData.DevInst,
+                devInterfaceDetails->DevicePath,
+                friendlyName,
+                &result);
+
+            if( result == paNoError )
+            {
+                int pin;
+                unsigned filterIOs = 0;
+
+                /* Increment number of "devices" */
+                for (pin = 0; pin < newFilter->pinCount; ++pin)
+                {
+                    PaWinWdmPin* pPin = newFilter->pins[pin];
+                    if (pPin == NULL)
+                        continue;
+
+                    filterIOs += max(1, pPin->inputCount);
+                }
+
+                noOfPaDevices += filterIOs;
+
+                PA_DEBUG(("Filter (%s) created with %d valid pins (total I/Os: %u)\n", ((newFilter->devInfo.streamingType==Type_kWaveRT)?"WaveRT":"WaveCyclic"), newFilter->validPinCount, filterIOs));
+
+                assert(slot < filterCount);
+
+                ppFilters[slot] = newFilter;
+
+                slot++;
+            }
+            else
+            {
+                PA_DEBUG(("Filter NOT created\n"));
+                /* As there are now less filters than we initially thought
+                * we must reduce the count by one */
+                filterCount--;
+            }
+        }
+    }
+
+    /* Clean up */
+    if(handle != NULL)
+        SetupDiDestroyDeviceInfoList(handle);
+
+    *pFilterCount = filterCount;
+    *pNoOfPaDevices = noOfPaDevices;
+
+    return ppFilters;
+}
+
+typedef struct PaNameHashIndex
+{
+    unsigned index;
+    unsigned count;
+    ULONG    hash;
+    struct PaNameHashIndex *next;
+} PaNameHashIndex;
+
+typedef struct PaNameHashObject
+{
+    PaNameHashIndex* list;
+    PaUtilAllocationGroup* allocGroup;
+} PaNameHashObject;
+
+static ULONG GetNameHash(const wchar_t* str, const BOOL input)
+{
+    /* This is to make sure that a name that exists as both input & output won't get the same hash value */
+    const ULONG fnv_prime = (input ? 0x811C9DD7 : 0x811FEB0B);
+    ULONG hash = 0;
+    for(; *str != 0; str++)
+    {
+        hash *= fnv_prime;
+        hash ^= (*str);
+    }
+    assert(hash != 0);
+    return hash;
+}
+
+static PaError CreateHashEntry(PaNameHashObject* obj, const wchar_t* name, const BOOL input)
+{
+    ULONG hash = GetNameHash(name, input); 
+    PaNameHashIndex * pLast = NULL;
+    PaNameHashIndex * p = obj->list;
+    while (p != 0)
+    {
+        if (p->hash == hash)
+        {
+            break;
+        }
+        pLast = p;
+        p = p->next;
+    }
+    if (p == NULL)
+    {
+        p = (PaNameHashIndex*)PaUtil_GroupAllocateMemory(obj->allocGroup, sizeof(PaNameHashIndex));
+        if (p == NULL)
+        {
+            return paInsufficientMemory;
+        }
+        p->hash = hash;
+        p->count = 1;
+        if (pLast != 0)
+        {
+            assert(pLast->next == 0);
+            pLast->next = p;
+        }
+        if (obj->list == 0)
+        {
+            obj->list = p;
+        }
+    }
+    else
+    {
+        ++p->count;
+    }
+    return paNoError;
+}
+
+static PaError InitNameHashObject(PaNameHashObject* obj, PaWinWdmFilter* pFilter)
+{
+    int i;
+
+    obj->allocGroup = PaUtil_CreateAllocationGroup();
+    if (obj->allocGroup == NULL)
+    {
+        return paInsufficientMemory;
+    }
+
+    for (i = 0; i < pFilter->pinCount; ++i)
+    {
+        unsigned m;
+        PaWinWdmPin* pin = pFilter->pins[i];
+
+        if (pin == NULL)
+            continue;
+
+        for (m = 0; m < max(1, pin->inputCount); ++m)
+        {
+            const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);
+            const wchar_t* name = (pin->inputs == NULL) ? pin->friendlyName : pin->inputs[m]->friendlyName;
+
+            PaError result = CreateHashEntry(obj, name, isInput);
+
+            if (result != paNoError)
+            {
+                return result;
+            }
+        }
+    }
+    return paNoError;
+}
+
+static void DeinitNameHashObject(PaNameHashObject* obj)
+{
+    assert(obj != 0);
+    PaUtil_FreeAllAllocations(obj->allocGroup);
+    PaUtil_DestroyAllocationGroup(obj->allocGroup);
+    memset(obj, 0, sizeof(PaNameHashObject));
+}
+
+static unsigned GetNameIndex(PaNameHashObject* obj, const wchar_t* name, const BOOL input)
+{
+    ULONG hash = GetNameHash(name, input); 
+    PaNameHashIndex* p = obj->list;
+    while (p != NULL)
+    {
+        if (p->hash == hash)
+        {
+            if (p->count > 1)
+            {
+                return (++p->index);
+            }
+            else
+            {
+                return 0;
+            }
+        }
+
+        p = p->next;
+    }
+    // Should never get here!!
+    assert(FALSE);
+    return 0;
+}
+
+static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex hostApiIndex, void **scanResults, int *newDeviceCount )
+{
+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+    PaError result = paNoError;
+    PaWinWdmFilter** ppFilters = 0;
+    PaWinWDMScanDeviceInfosResults *outArgument = 0;
+    int filterCount = 0;
+    int totalDeviceCount = 0;
+    int idxDevice = 0;
+    DWORD defaultInDevPathSize = 0;
+    DWORD defaultOutDevPathSize = 0;
+    wchar_t* defaultInDevPath = 0;
+    wchar_t* defaultOutDevPath = 0;
+
+    ppFilters = BuildFilterList( &filterCount, &totalDeviceCount, &result );
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    // Get hold of default device paths for capture & playback
+    if( waveInMessage(0, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR)&defaultInDevPathSize, 0 ) == MMSYSERR_NOERROR )
+    {
+        defaultInDevPath = (wchar_t *)PaUtil_AllocateMemory((defaultInDevPathSize + 1) * sizeof(wchar_t));
+        waveInMessage(0, DRV_QUERYDEVICEINTERFACE, (DWORD_PTR)defaultInDevPath, defaultInDevPathSize);
+    }
+    if( waveOutMessage(0, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR)&defaultOutDevPathSize, 0 ) == MMSYSERR_NOERROR )
+    {
+        defaultOutDevPath = (wchar_t *)PaUtil_AllocateMemory((defaultOutDevPathSize + 1) * sizeof(wchar_t));
+        waveOutMessage(0, DRV_QUERYDEVICEINTERFACE, (DWORD_PTR)defaultOutDevPath, defaultOutDevPathSize);
+    }
+
+    if( totalDeviceCount > 0 )
+    {
+        PaWinWdmDeviceInfo *deviceInfoArray = 0;
+        int idxFilter;
+        int i;
+        unsigned devIsDefaultIn = 0, devIsDefaultOut = 0;
+
+        /* Allocate the out param for all the info we need */
+        outArgument = (PaWinWDMScanDeviceInfosResults *) PaUtil_GroupAllocateMemory(
+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults) );
+        if( !outArgument )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        outArgument->defaultInputDevice  = paNoDevice;
+        outArgument->defaultOutputDevice = paNoDevice;
+
+        outArgument->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+            wdmHostApi->allocations, sizeof(PaDeviceInfo*) * totalDeviceCount );
+        if( !outArgument->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaWinWdmDeviceInfo*)PaUtil_GroupAllocateMemory(
+            wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo) * totalDeviceCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* Make sure all items in array */
+        for( i = 0 ; i < totalDeviceCount; ++i )
+        {
+            PaDeviceInfo *deviceInfo  = &deviceInfoArray[i].inheritedDeviceInfo;
+            deviceInfo->structVersion = 2;
+            deviceInfo->hostApi       = hostApiIndex;
+            deviceInfo->name          = 0;
+            outArgument->deviceInfos[ i ] = deviceInfo;
+        }
+
+        idxDevice = 0;
+        for (idxFilter = 0; idxFilter < filterCount; ++idxFilter)
+        {
+            PaNameHashObject nameHash = {0};
+            PaWinWdmFilter* pFilter = ppFilters[idxFilter];
+            if( pFilter == NULL )
+                continue;
+
+            if (InitNameHashObject(&nameHash, pFilter) != paNoError)
+            {
+                DeinitNameHashObject(&nameHash);
+                continue;
+            }
+
+            devIsDefaultIn = (defaultInDevPath && (_wcsicmp(pFilter->devInfo.filterPath, defaultInDevPath) == 0));
+            devIsDefaultOut = (defaultOutDevPath && (_wcsicmp(pFilter->devInfo.filterPath, defaultOutDevPath) == 0));
+
+            for (i = 0; i < pFilter->pinCount; ++i)
+            {
+                unsigned m;
+                ULONG nameIndex = 0;
+                ULONG nameIndexHash = 0;
+                PaWinWdmPin* pin = pFilter->pins[i];
+
+                if (pin == NULL)
+                    continue;
+
+                for (m = 0; m < max(1, pin->inputCount); ++m)
+                {
+                    PaWinWdmDeviceInfo *wdmDeviceInfo = (PaWinWdmDeviceInfo *)outArgument->deviceInfos[idxDevice];
+                    PaDeviceInfo *deviceInfo = &wdmDeviceInfo->inheritedDeviceInfo;
+                    wchar_t localCompositeName[MAX_PATH];
+                    unsigned nameIndex = 0;
+                    const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);
+
+                    wdmDeviceInfo->filter = pFilter;
+
+                    deviceInfo->structVersion = 2;
+                    deviceInfo->hostApi = hostApiIndex;
+                    deviceInfo->name = wdmDeviceInfo->compositeName;
+                    /* deviceInfo->hostApiSpecificDeviceInfo = &pFilter->devInfo; */
+
+                    wdmDeviceInfo->pin = pin->pinId;
+
+                    /* Get the name of the "device" */
+                    if (pin->inputs == NULL)
+                    {
+                        wcsncpy(localCompositeName, pin->friendlyName, MAX_PATH);
+                        wdmDeviceInfo->muxPosition = -1;
+                        wdmDeviceInfo->endpointPinId = pin->endpointPinId;
+                    }
+                    else
+                    {
+                        PaWinWdmMuxedInput* input = pin->inputs[m];
+                        wcsncpy(localCompositeName, input->friendlyName, MAX_PATH);
+                        wdmDeviceInfo->muxPosition = (int)m;
+                        wdmDeviceInfo->endpointPinId = input->endpointPinId;
+                    }
+
+                    {
+                        /* Get base length */
+                        size_t n = wcslen(localCompositeName);
+
+                        /* Check if there are more entries with same name (which might very well be the case), if there
+                        are, the name will be postfixed with an index. */
+                        nameIndex = GetNameIndex(&nameHash, localCompositeName, isInput);
+                        if (nameIndex > 0)
+                        {
+                            /* This name has multiple instances, so we post fix with a number */
+                            n += _snwprintf(localCompositeName + n, MAX_PATH - n, L" %u", nameIndex);
+                        }
+                        /* Postfix with filter name */
+                        _snwprintf(localCompositeName + n, MAX_PATH - n, L" (%s)", pFilter->friendlyName);
+                    }
+
+                    /* Convert wide char string to utf-8 */
+                    WideCharToMultiByte(CP_UTF8, 0, localCompositeName, -1, wdmDeviceInfo->compositeName, MAX_PATH, NULL, NULL);
+
+                    /* NB! WDM/KS has no concept of a full-duplex device, each pin is either an input or an output */
+                    if (isInput)
+                    {
+                        /* INPUT ! */
+                        deviceInfo->maxInputChannels  = pin->maxChannels;
+                        deviceInfo->maxOutputChannels = 0;
+
+                        /* RoBi NB: Due to the fact that input audio endpoints in Vista (& later OSs) can be the same device, but with
+                           different input mux settings, there might be a discrepancy between the default input device chosen, and
+                           that which will be used by Portaudio. Not much to do about that unfortunately.
+                        */
+                        if ((defaultInDevPath == 0 || devIsDefaultIn) &&
+                             outArgument->defaultInputDevice == paNoDevice)
+                        {
+                            outArgument->defaultInputDevice = idxDevice;
+                        }
+                    }
+                    else
+                    {
+                        /* OUTPUT ! */
+                        deviceInfo->maxInputChannels  = 0;
+                        deviceInfo->maxOutputChannels = pin->maxChannels;
+
+                        if ((defaultOutDevPath == 0 || devIsDefaultOut) &&
+                            outArgument->defaultOutputDevice == paNoDevice)
+                        {
+                            outArgument->defaultOutputDevice = idxDevice;
+                        }
+                    }
+
+                    /* These low values are not very useful because
+                    * a) The lowest latency we end up with can depend on many factors such
+                    *    as the device buffer sizes/granularities, sample rate, channels and format
+                    * b) We cannot know the device buffer sizes until we try to open/use it at
+                    *    a particular setting
+                    * So: we give 512x48000Hz frames as the default low input latency
+                    **/
+                    switch (pFilter->devInfo.streamingType)
+                    {
+                    case Type_kWaveCyclic:
+                        if (IsEarlierThanVista())
+                        {
+                            /* XP doesn't tolerate low latency, unless the Process Priority Class is set to REALTIME_PRIORITY_CLASS 
+                            through SetPriorityClass, then 10 ms is quite feasible. However, one should then bear in mind that ALL of
+                            the process is running in REALTIME_PRIORITY_CLASS, which might not be appropriate for an application with
+                            a GUI . In this case it is advisable to separate the audio engine in another process and use IPC to communicate
+                            with it. */
+                            deviceInfo->defaultLowInputLatency = 0.02;
+                            deviceInfo->defaultLowOutputLatency = 0.02;
+                        }
+                        else
+                        {
+                            /* This is a conservative estimate. Most WaveCyclic drivers will limit the available latency, but f.i. my Edirol
+                            PCR-A30 can reach 3 ms latency easily... */
+                            deviceInfo->defaultLowInputLatency = 0.01;
+                            deviceInfo->defaultLowOutputLatency = 0.01;
+                        }
+                        deviceInfo->defaultHighInputLatency = (4096.0/48000.0);
+                        deviceInfo->defaultHighOutputLatency = (4096.0/48000.0);
+                        deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);
+                        break;
+                    case Type_kWaveRT:
+                        /* This is also a conservative estimate, based on WaveRT polled mode. In polled mode, the latency will be dictated
+                        by the buffer size given by the driver. */
+                        deviceInfo->defaultLowInputLatency = 0.01;
+                        deviceInfo->defaultLowOutputLatency = 0.01;
+                        deviceInfo->defaultHighInputLatency = 0.04;
+                        deviceInfo->defaultHighOutputLatency = 0.04;
+                        deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);
+                        break;
+                    default:
+                        assert(0);
+                        break;
+                    }
+
+                    /* Add reference to filter */
+                    FilterAddRef(wdmDeviceInfo->filter);
+
+                    assert(idxDevice < totalDeviceCount);
+                    ++idxDevice;
+                }
+            }
+
+            /* If no one has add ref'd the filter, drop it */
+            if (pFilter->filterRefCount == 0)
+            {
+                FilterFree(pFilter);
+            }
+
+            /* Deinitialize name hash object */
+            DeinitNameHashObject(&nameHash);
+        }
+    }
+
+    *scanResults = outArgument;
+    *newDeviceCount = idxDevice;
+    return result;
+
+error:
+    result = DisposeDeviceInfos(hostApi, outArgument, totalDeviceCount);
+
+    return result;
+}
+
+static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *scanResults, int deviceCount )
+{
+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+
+    hostApi->info.deviceCount = 0;
+    hostApi->info.defaultInputDevice = paNoDevice;
+    hostApi->info.defaultOutputDevice = paNoDevice;
+
+    /* Free any old memory which might be in the device info */
+    if( hostApi->deviceInfos )
+    {
+        PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(
+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));
+        localScanResults->deviceInfos = hostApi->deviceInfos;
+
+        DisposeDeviceInfos(hostApi, &localScanResults, hostApi->info.deviceCount);
+
+        hostApi->deviceInfos = NULL;
+    }
+
+    if( scanResults != NULL )
+    {
+        PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;
+
+        if( deviceCount > 0 )
+        {
+            /* use the array allocated in ScanDeviceInfos() as our deviceInfos */
+            hostApi->deviceInfos = scanDeviceInfosResults->deviceInfos;
+
+            hostApi->info.defaultInputDevice = scanDeviceInfosResults->defaultInputDevice;
+            hostApi->info.defaultOutputDevice = scanDeviceInfosResults->defaultOutputDevice;
+
+            hostApi->info.deviceCount = deviceCount;
+        }
+
+        PaUtil_GroupFreeMemory( wdmHostApi->allocations, scanDeviceInfosResults );
+    }
+
+    return paNoError;
+
+}
+
+static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *scanResults, int deviceCount )
+{
+    PaWinWdmHostApiRepresentation *winDsHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+
+    if( scanResults != NULL )
+    {
+        PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;
+
+        if( scanDeviceInfosResults->deviceInfos )
+        {
+            int i;
+            for (i = 0; i < deviceCount; ++i)
+            {
+                PaWinWdmDeviceInfo* pDevice = (PaWinWdmDeviceInfo*)scanDeviceInfosResults->deviceInfos[i];
+                if (pDevice->filter != 0)
+                {
+                    FilterFree(pDevice->filter);
+                }
+            }
+
+            PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos[0] ); /* all device info structs are allocated in a block so we can destroy them here */
+            PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos );
+        }
+
+        PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults );
+    }
+
+    return paNoError;
+
+}
+
+PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int deviceCount = 0;
+    void *scanResults = 0;
+    PaWinWdmHostApiRepresentation *wdmHostApi = NULL;
+
+    PA_LOGE_;
+
+#ifdef PA_WDMKS_SET_TREF
+    tRef = PaUtil_GetTime();
+#endif
+
+    /*
+    Attempt to load the KSUSER.DLL without which we cannot create pins
+    We will unload this on termination
+    */
+    if(DllKsUser == NULL)
+    {
+        DllKsUser = LoadLibrary(TEXT("ksuser.dll"));
+        if(DllKsUser == NULL)
+            goto error;
+    }
+    FunctionKsCreatePin = (KSCREATEPIN*)GetProcAddress(DllKsUser, "KsCreatePin");
+    if(FunctionKsCreatePin == NULL)
+        goto error;
+
+    /* Attempt to load AVRT.DLL, if we can't, then we'll just use time critical prio instead... */
+    if(paWinWDMKSAvRtEntryPoints.hInstance == NULL)
+    {
+        paWinWDMKSAvRtEntryPoints.hInstance = LoadLibrary(TEXT("avrt.dll"));
+        if (paWinWDMKSAvRtEntryPoints.hInstance != NULL)
+        {
+            paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics =
+                (HANDLE(WINAPI*)(LPCSTR,LPDWORD))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance,"AvSetMmThreadCharacteristicsA");
+            paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics =
+                (BOOL(WINAPI*)(HANDLE))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvRevertMmThreadCharacteristics");
+            paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority =
+                (BOOL(WINAPI*)(HANDLE,PA_AVRT_PRIORITY))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvSetMmThreadPriority");
+        }
+    }
+
+    wdmHostApi = (PaWinWdmHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWdmHostApiRepresentation) );
+    if( !wdmHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    wdmHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !wdmHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi = &wdmHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paWDMKS;
+    (*hostApi)->info.name = "Windows WDM-KS";
+
+    /* these are all updated by CommitDeviceInfos() */
+    (*hostApi)->info.deviceCount = 0;
+    (*hostApi)->info.defaultInputDevice = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+    (*hostApi)->deviceInfos = 0;
+
+    result = ScanDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, &scanResults, &deviceCount);
+    if (result != paNoError)
+    {
+        goto error;
+    }
+
+    CommitDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, scanResults, deviceCount);
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+    /* In preparation for hotplug
+    (*hostApi)->ScanDeviceInfos = ScanDeviceInfos;
+    (*hostApi)->CommitDeviceInfos = CommitDeviceInfos;
+    (*hostApi)->DisposeDeviceInfos = DisposeDeviceInfos;
+    */
+    PaUtil_InitializeStreamInterface( &wdmHostApi->callbackStreamInterface, CloseStream, StartStream,
+        StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+        GetStreamTime, GetStreamCpuLoad,
+        PaUtil_DummyRead, PaUtil_DummyWrite,
+        PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &wdmHostApi->blockingStreamInterface, CloseStream, StartStream,
+        StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+        GetStreamTime, PaUtil_DummyGetCpuLoad,
+        ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    PA_LOGL_;
+    return result;
+
+error:
+    Terminate( (PaUtilHostApiRepresentation*)wdmHostApi );
+
+    PA_LOGL_;
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+    PA_LOGE_;
+
+    /* Do not unload the libraries */
+    if( DllKsUser != NULL )
+    {
+        FreeLibrary( DllKsUser );
+        DllKsUser = NULL;
+    }
+
+    if( paWinWDMKSAvRtEntryPoints.hInstance != NULL )
+    {
+        FreeLibrary( paWinWDMKSAvRtEntryPoints.hInstance );
+        paWinWDMKSAvRtEntryPoints.hInstance = NULL;
+    }
+
+    if( wdmHostApi)
+    {
+        PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(
+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));
+        localScanResults->deviceInfos = hostApi->deviceInfos;
+        DisposeDeviceInfos(hostApi, localScanResults, hostApi->info.deviceCount);
+
+        if( wdmHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( wdmHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( wdmHostApi->allocations );
+        }
+        PaUtil_FreeMemory( wdmHostApi );
+    }
+    PA_LOGL_;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                 const PaStreamParameters *inputParameters,
+                                 const PaStreamParameters *outputParameters,
+                                 double sampleRate )
+{
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+    PaWinWdmFilter* pFilter;
+    int result = paFormatIsSupported;
+    WAVEFORMATEXTENSIBLE wfx;
+    PaWinWaveFormatChannelMask channelMask;
+
+    PA_LOGE_;
+
+    if( inputParameters )
+    {
+        PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
+        PaWinWdmPin* pin;
+        unsigned fmt;
+        unsigned long testFormat = 0;
+        unsigned validBits = 0;
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+        this implementation doesn't support any custom sample formats */
+        if( inputSampleFormat & paCustomFormat )
+        {
+            PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom input format not supported");
+            return paSampleFormatNotSupported;
+        }
+
+        /* unless alternate device specification is supported, reject the use of
+        paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");
+            return paInvalidDevice;
+        }
+
+        /* check that input device can support inputChannelCount */
+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "IsFormatSupported: Invalid input channel count");
+            return paInvalidChannelCount;
+        }
+
+        /* validate inputStreamInfo */
+        if( inputParameters->hostApiSpecificStreamInfo )
+        {
+            PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+        }
+
+        pFilter = pDeviceInfo->filter;
+        pin = pFilter->pins[pDeviceInfo->pin];
+
+        /* Find out the testing format */
+        for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)
+        {
+            if ((fmt & pin->formats) != 0)
+            {
+                /* Found a matching format! */
+                testFormat = fmt;
+                break;
+            }
+        }
+        if (testFormat == 0)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: no testformat found!");
+            return paUnanticipatedHostError;
+        }
+
+        /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and
+        valid bits = 24 (instead of 24 bit samples) */
+        if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)
+        {
+            PA_DEBUG(("IsFormatSupported (capture): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));
+            testFormat = paInt32;
+            validBits = 24;
+        }
+
+        /* Check that the input format is supported */
+        channelMask = PaWin_DefaultChannelMask(inputChannelCount);
+        PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
+            inputChannelCount, 
+            testFormat,
+            PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
+            sampleRate,
+            channelMask );
+        if (validBits != 0)
+        {
+            wfx.Samples.wValidBitsPerSample = validBits;
+        }
+
+        result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
+        if( result != paNoError )
+        {
+            /* Try a WAVE_FORMAT_PCM instead */
+            PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
+                inputChannelCount, 
+                testFormat,
+                PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
+                sampleRate);
+
+            if (validBits != 0)
+            {
+                wfx.Samples.wValidBitsPerSample = validBits;
+            }
+
+            result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
+            if( result != paNoError )
+            {
+                PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: sr=%u,ch=%u,bits=%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);
+                return result;
+            }
+        }
+    }
+    else
+    {
+        inputChannelCount = 0;
+    }
+
+    if( outputParameters )
+    {
+        PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
+        PaWinWdmPin* pin;
+        unsigned fmt;
+        unsigned long testFormat = 0;
+        unsigned validBits = 0;
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* all standard sample formats are supported by the buffer adapter,
+        this implementation doesn't support any custom sample formats */
+        if( outputSampleFormat & paCustomFormat )
+        {
+            PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom output format not supported");
+            return paSampleFormatNotSupported;
+        }
+
+        /* unless alternate device specification is supported, reject the use of
+        paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");
+            return paInvalidDevice;
+        }
+
+        /* check that output device can support outputChannelCount */
+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");
+            return paInvalidChannelCount;
+        }
+
+        /* validate outputStreamInfo */
+        if( outputParameters->hostApiSpecificStreamInfo )
+        {
+            PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");
+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+        }
+
+        pFilter = pDeviceInfo->filter;
+        pin = pFilter->pins[pDeviceInfo->pin];
+
+        /* Find out the testing format */
+        for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)
+        {
+            if ((fmt & pin->formats) != 0)
+            {
+                /* Found a matching format! */
+                testFormat = fmt;
+                break;
+            }
+        }
+        if (testFormat == 0)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: no testformat found!");
+            return paUnanticipatedHostError;
+        }
+
+        /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and
+        valid bits = 24 (instead of 24 bit samples) */
+        if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)
+        {
+            PA_DEBUG(("IsFormatSupported (render): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));
+            testFormat = paInt32;
+            validBits = 24;
+        }
+
+        /* Check that the output format is supported */
+        channelMask = PaWin_DefaultChannelMask(outputChannelCount);
+        PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
+            outputChannelCount, 
+            testFormat,
+            PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
+            sampleRate,
+            channelMask );
+
+        if (validBits != 0)
+        {
+            wfx.Samples.wValidBitsPerSample = validBits;
+        }
+
+        result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
+        if( result != paNoError )
+        {
+            /* Try a WAVE_FORMAT_PCM instead */
+            PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
+                outputChannelCount, 
+                testFormat,
+                PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
+                sampleRate);
+
+            if (validBits != 0)
+            {
+                wfx.Samples.wValidBitsPerSample = validBits;
+            }
+
+            result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
+            if( result != paNoError )
+            {
+                PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: %u,%u,%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);
+                return result;
+            }
+        }
+
+    }
+    else
+    {
+        outputChannelCount = 0;
+    }
+
+    /*
+    IMPLEMENT ME:
+
+    - if a full duplex stream is requested, check that the combination
+    of input and output parameters is supported if necessary
+
+    - check that the device supports sampleRate
+
+    Because the buffer adapter handles conversion between all standard
+    sample formats, the following checks are only required if paCustomFormat
+    is implemented, or under some other unusual conditions.
+
+    - check that input device can support inputSampleFormat, or that
+    we have the capability to convert from inputSampleFormat to
+    a native format
+
+    - check that output device can support outputSampleFormat, or that
+    we have the capability to convert from outputSampleFormat to
+    a native format
+    */
+    if((inputChannelCount == 0)&&(outputChannelCount == 0))
+    {
+        PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "No input or output channels defined");
+        result = paSampleFormatNotSupported; /* Not right error */
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+static void ResetStreamEvents(PaWinWdmStream* stream) 
+{
+    unsigned i;
+    ResetEvent(stream->eventAbort);
+    ResetEvent(stream->eventStreamStart[StreamStart_kOk]);
+    ResetEvent(stream->eventStreamStart[StreamStart_kFailed]);
+
+    for (i=0; i<stream->capture.noOfPackets; ++i)
+    {
+        if (stream->capture.events && stream->capture.events[i])
+        {
+            ResetEvent(stream->capture.events[i]);
+        }
+    }
+
+    for (i=0; i<stream->render.noOfPackets; ++i)
+    {
+        if (stream->render.events && stream->render.events[i])
+        {
+            ResetEvent(stream->render.events[i]);
+        }
+    }
+}
+
+static void CloseStreamEvents(PaWinWdmStream* stream) 
+{
+    unsigned i;
+    PaWinWdmIOInfo* ios[2] = { &stream->capture, &stream->render };
+
+    if (stream->eventAbort)
+    {
+        CloseHandle(stream->eventAbort);
+        stream->eventAbort = 0;
+    }
+    if (stream->eventStreamStart[StreamStart_kOk])
+    {
+        CloseHandle(stream->eventStreamStart[StreamStart_kOk]);
+    }
+    if (stream->eventStreamStart[StreamStart_kFailed])
+    {
+        CloseHandle(stream->eventStreamStart[StreamStart_kFailed]);
+    }
+
+    for (i = 0; i < 2; ++i)
+    {
+        unsigned j;
+        /* Unregister notification handles for WaveRT */
+        if (ios[i]->pPin && ios[i]->pPin->parentFilter->devInfo.streamingType == Type_kWaveRT &&
+            ios[i]->pPin->pinKsSubType == SubType_kNotification &&
+            ios[i]->events != 0)
+        {
+            PinUnregisterNotificationHandle(ios[i]->pPin, ios[i]->events[0]);
+        }
+
+        for (j=0; j < ios[i]->noOfPackets; ++j)
+        {
+            if (ios[i]->events && ios[i]->events[j])
+            {
+                CloseHandle(ios[i]->events[j]);
+                ios[i]->events[j] = 0;
+            }
+        }
+    }
+}
+
+static unsigned NextPowerOf2(unsigned val)
+{
+    val--;
+    val = (val >> 1) | val;
+    val = (val >> 2) | val;
+    val = (val >> 4) | val;
+    val = (val >> 8) | val;
+    val = (val >> 16) | val;
+    return ++val;
+}
+
+static PaError ValidateSpecificStreamParameters(
+    const PaStreamParameters *streamParameters,
+    const PaWinWDMKSInfo *streamInfo,
+    unsigned isInput)
+{
+    if( streamInfo )
+    {
+        if( streamInfo->size != sizeof( PaWinWDMKSInfo )
+            || streamInfo->version != 1 )
+        {
+            PA_DEBUG(("Stream parameters: size or version not correct"));
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        if (!!(streamInfo->flags & ~(paWinWDMKSOverrideFramesize | paWinWDMKSUseGivenChannelMask)))
+        {
+            PA_DEBUG(("Stream parameters: non supported flags set"));
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        if (streamInfo->noOfPackets != 0 &&
+            (streamInfo->noOfPackets < 2 || streamInfo->noOfPackets > 8))
+        {
+            PA_DEBUG(("Stream parameters: noOfPackets %u out of range [2,8]", streamInfo->noOfPackets));
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        if (streamInfo->flags & paWinWDMKSUseGivenChannelMask)
+        {
+            if (isInput)
+            {
+                PA_DEBUG(("Stream parameters: Channels mask setting not supported for input stream"));
+                return paIncompatibleHostApiSpecificStreamInfo;
+            }
+
+            if (streamInfo->channelMask & PAWIN_SPEAKER_RESERVED)
+            {
+                PA_DEBUG(("Stream parameters: Given channels mask 0x%08X not supported", streamInfo->channelMask));
+                return paIncompatibleHostApiSpecificStreamInfo;
+            }
+        }
+
+    }
+
+    return paNoError;
+}
+
+
+
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                          PaStream** s,
+                          const PaStreamParameters *inputParameters,
+                          const PaStreamParameters *outputParameters,
+                          double sampleRate,
+                          unsigned long framesPerUserBuffer,
+                          PaStreamFlags streamFlags,
+                          PaStreamCallback *streamCallback,
+                          void *userData )
+{
+    PaError result = paNoError;
+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
+    PaWinWdmStream *stream = 0;
+    /* unsigned long framesPerHostBuffer; these may not be equivalent for all implementations */
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+    int userInputChannels,userOutputChannels;
+    WAVEFORMATEXTENSIBLE wfx;
+
+    PA_LOGE_;
+    PA_DEBUG(("OpenStream:sampleRate = %f\n",sampleRate));
+    PA_DEBUG(("OpenStream:framesPerBuffer = %lu\n",framesPerUserBuffer));
+
+    if( inputParameters )
+    {
+        userInputChannels = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+        paUseHostApiSpecificDeviceSpecification */
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(in) not supported");
+            return paInvalidDevice;
+        }
+
+        /* check that input device can support stream->userInputChannels */
+        if( userInputChannels > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid input channel count");
+            return paInvalidChannelCount;
+        }
+
+        /* validate inputStreamInfo */
+        result = ValidateSpecificStreamParameters(inputParameters, inputParameters->hostApiSpecificStreamInfo, 1 );
+        if(result != paNoError)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (in)");
+            return result; /* this implementation doesn't use custom stream info */
+        }
+    }
+    else
+    {
+        userInputChannels = 0;
+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Supress 'uninitialised var' warnings. */
+    }
+
+    if( outputParameters )
+    {
+        userOutputChannels = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+
+        /* unless alternate device specification is supported, reject the use of
+        paUseHostApiSpecificDeviceSpecification */
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(out) not supported");
+            return paInvalidDevice;
+        }
+
+        /* check that output device can support stream->userInputChannels */
+        if( userOutputChannels > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+        {
+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");
+            return paInvalidChannelCount;
+        }
+
+        /* validate outputStreamInfo */
+        result = ValidateSpecificStreamParameters( outputParameters, outputParameters->hostApiSpecificStreamInfo, 0 );
+        if (result != paNoError)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (out)");
+            return result; /* this implementation doesn't use custom stream info */
+        }
+    }
+    else
+    {
+        userOutputChannels = 0;
+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Supress 'uninitialized var' warnings. */
+    }
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+    {
+        PaWinWDM_SetLastErrorInfo(paInvalidFlag, "Invalid flag supplied");
+        return paInvalidFlag; /* unexpected platform specific flag */
+    }
+
+    stream = (PaWinWdmStream*)PaUtil_AllocateMemory( sizeof(PaWinWdmStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Create allocation group */
+    stream->allocGroup = PaUtil_CreateAllocationGroup();
+    if( !stream->allocGroup )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    /* Zero the stream object */
+    /* memset((void*)stream,0,sizeof(PaWinWdmStream)); */
+
+    if( streamCallback )
+    {
+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+            &wdmHostApi->callbackStreamInterface, streamCallback, userData );
+    }
+    else
+    {
+        /* PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+        &wdmHostApi->blockingStreamInterface, streamCallback, userData ); */
+
+        /* We don't support the blocking API yet */
+        PA_DEBUG(("Blocking API not supported yet!\n"));
+        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Blocking API not supported yet");
+        result = paUnanticipatedHostError;
+        goto error;
+    }
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+    /* Instantiate the input pin if necessary */
+    if(userInputChannels > 0)
+    {
+        PaWinWdmFilter* pFilter;
+        PaWinWdmDeviceInfo* pDeviceInfo;
+        PaWinWdmPin* pPin;
+        unsigned validBitsPerSample = 0;
+        PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userInputChannels );
+
+        result = paSampleFormatNotSupported;
+        pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
+        pFilter = pDeviceInfo->filter;
+        pPin = pFilter->pins[pDeviceInfo->pin];
+
+        stream->userInputChannels = userInputChannels;
+
+        hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, inputSampleFormat );
+        if (hostInputSampleFormat == paSampleFormatNotSupported)
+        {
+            result = paUnanticipatedHostError;
+            PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (input)", pPin->formats, inputSampleFormat);
+            goto error;
+        }
+        else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostInputSampleFormat == paInt24)
+        {
+            /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a
+            128 byte boundary (see PinGetBuffer) */
+            hostInputSampleFormat = paInt32;
+            /* But we'll tell the driver that it's 24 bit in 32 bit container */
+            validBitsPerSample = 24;
+        }
+
+        while (hostInputSampleFormat <= paUInt8)
+        {
+            unsigned channelsToProbe = stream->userInputChannels;
+            /* Some or all KS devices can only handle the exact number of channels
+            * they specify. But PortAudio clients expect to be able to
+            * at least specify mono I/O on a multi-channel device
+            * If this is the case, then we will do the channel mapping internally
+            * The following loop tests this case
+            **/
+            while (1)
+            {
+                PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
+                    channelsToProbe, 
+                    hostInputSampleFormat,
+                    PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),
+                    sampleRate,
+                    channelMask );
+                stream->capture.bytesPerFrame = wfx.Format.nBlockAlign;
+                if (validBitsPerSample != 0)
+                {
+                    wfx.Samples.wValidBitsPerSample = validBitsPerSample;
+                }
+                stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);
+                stream->deviceInputChannels = channelsToProbe;
+
+                if( result != paNoError && result != paDeviceUnavailable )
+                {
+                    /* Try a WAVE_FORMAT_PCM instead */
+                    PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
+                        channelsToProbe, 
+                        hostInputSampleFormat,
+                        PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),
+                        sampleRate);
+                    if (validBitsPerSample != 0)
+                    {
+                        wfx.Samples.wValidBitsPerSample = validBitsPerSample;
+                    }
+                    stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);
+                }
+
+                if (result == paDeviceUnavailable) goto occupied;
+
+                if (result == paNoError)
+                {
+                    /* We're done */
+                    break;
+                }
+
+                if (channelsToProbe < (unsigned)pPin->maxChannels)
+                {
+                    /* Go to next multiple of 2 */
+                    channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);
+                    continue;
+                }
+
+                break;
+            }
+
+            if (result == paNoError)
+            {
+                /* We're done */
+                break;
+            }
+
+            /* Go to next format in line with lower resolution */
+            hostInputSampleFormat <<= 1;
+        }
+
+        if(stream->capture.pPin == NULL)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "Failed to create capture pin: sr=%u,ch=%u,bits=%u,align=%u",
+                wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);
+            goto error;
+        }
+
+        /* Select correct mux input on MUX node of topology filter */
+        if (pDeviceInfo->muxPosition >= 0)
+        {
+            assert(pPin->parentFilter->topologyFilter != NULL);
+
+            result = FilterUse(pPin->parentFilter->topologyFilter);
+            if (result != paNoError)
+            {
+                PaWinWDM_SetLastErrorInfo(result, "Failed to open topology filter");
+                goto error;
+            }
+
+            result = WdmSetMuxNodeProperty(pPin->parentFilter->topologyFilter->handle,
+                pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId,
+                pPin->inputs[pDeviceInfo->muxPosition]->muxPinId);
+
+            FilterRelease(pPin->parentFilter->topologyFilter);
+
+            if(result != paNoError)
+            {
+                PaWinWDM_SetLastErrorInfo(result, "Failed to set topology mux node");
+                goto error;
+            }
+        }
+
+        stream->capture.bytesPerSample = stream->capture.bytesPerFrame / stream->deviceInputChannels;
+        stream->capture.pPin->frameSize /= stream->capture.bytesPerFrame;
+        PA_DEBUG(("Capture pin frames: %d\n",stream->capture.pPin->frameSize));
+    }
+    else
+    {
+        stream->capture.pPin = NULL;
+        stream->capture.bytesPerFrame = 0;
+    }
+
+    /* Instantiate the output pin if necessary */
+    if(userOutputChannels > 0)
+    {
+        PaWinWdmFilter* pFilter;
+        PaWinWdmDeviceInfo* pDeviceInfo;
+        PaWinWdmPin* pPin;
+        PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)(outputParameters->hostApiSpecificStreamInfo);
+        unsigned validBitsPerSample = 0;
+        PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userOutputChannels );
+        if (pInfo && (pInfo->flags & paWinWDMKSUseGivenChannelMask))
+        {
+            PA_DEBUG(("Using channelMask 0x%08X instead of default 0x%08X\n",
+                pInfo->channelMask,
+                channelMask));
+            channelMask = pInfo->channelMask;
+        }
+
+        result = paSampleFormatNotSupported;
+        pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
+        pFilter = pDeviceInfo->filter;
+        pPin = pFilter->pins[pDeviceInfo->pin];
+
+        stream->userOutputChannels = userOutputChannels;
+
+        hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, outputSampleFormat );
+        if (hostOutputSampleFormat == paSampleFormatNotSupported)
+        {
+            result = paUnanticipatedHostError;
+            PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (output)", pPin->formats, hostOutputSampleFormat);
+            goto error;
+        }
+        else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostOutputSampleFormat == paInt24)
+        {
+            /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a
+            128 byte boundary (see PinGetBuffer) */
+            hostOutputSampleFormat = paInt32;
+            /* But we'll tell the driver that it's 24 bit in 32 bit container */
+            validBitsPerSample = 24;
+        }
+
+        while (hostOutputSampleFormat <= paUInt8)
+        {
+            unsigned channelsToProbe = stream->userOutputChannels;
+            /* Some or all KS devices can only handle the exact number of channels
+            * they specify. But PortAudio clients expect to be able to
+            * at least specify mono I/O on a multi-channel device
+            * If this is the case, then we will do the channel mapping internally
+            * The following loop tests this case
+            **/
+            while (1)
+            {
+                PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
+                    channelsToProbe, 
+                    hostOutputSampleFormat,
+                    PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),
+                    sampleRate,
+                    channelMask );
+                stream->render.bytesPerFrame = wfx.Format.nBlockAlign;
+                if (validBitsPerSample != 0)
+                {
+                    wfx.Samples.wValidBitsPerSample = validBitsPerSample;
+                }
+                stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);
+                stream->deviceOutputChannels = channelsToProbe;
+
+                if( result != paNoError && result != paDeviceUnavailable )
+                {
+                    PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
+                        channelsToProbe, 
+                        hostOutputSampleFormat,
+                        PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),
+                        sampleRate);
+                    if (validBitsPerSample != 0)
+                    {
+                        wfx.Samples.wValidBitsPerSample = validBitsPerSample;
+                    }
+                    stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);
+                }
+
+                if (result == paDeviceUnavailable) goto occupied;
+
+                if (result == paNoError)
+                {
+                    /* We're done */
+                    break;
+                }
+
+                if (channelsToProbe < (unsigned)pPin->maxChannels)
+                {
+                    /* Go to next multiple of 2 */
+                    channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);
+                    continue;
+                }
+
+                break;
+            };
+
+            if (result == paNoError)
+            {
+                /* We're done */
+                break;
+            }
+
+            /* Go to next format in line with lower resolution */
+            hostOutputSampleFormat <<= 1;
+        }
+
+        if(stream->render.pPin == NULL)
+        {
+            PaWinWDM_SetLastErrorInfo(result, "Failed to create render pin: sr=%u,ch=%u,bits=%u,align=%u",
+                wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);
+            goto error;
+        }
+
+        stream->render.bytesPerSample = stream->render.bytesPerFrame / stream->deviceOutputChannels;
+        stream->render.pPin->frameSize /= stream->render.bytesPerFrame;
+        PA_DEBUG(("Render pin frames: %d\n",stream->render.pPin->frameSize));
+    }
+    else
+    {
+        stream->render.pPin = NULL;
+        stream->render.bytesPerFrame = 0;
+    }
+
+    /* Calculate the framesPerHostXxxxBuffer size based upon the suggested latency values */
+    /* Record the buffer length */
+    if(inputParameters)
+    {
+        /* Calculate the frames from the user's value - add a bit to round up */
+        stream->capture.framesPerBuffer = (unsigned long)((inputParameters->suggestedLatency*sampleRate)+0.0001);
+        if(stream->capture.framesPerBuffer > (unsigned long)sampleRate)
+        { /* Upper limit is 1 second */
+            stream->capture.framesPerBuffer = (unsigned long)sampleRate;
+        }
+        else if(stream->capture.framesPerBuffer < stream->capture.pPin->frameSize)
+        {
+            stream->capture.framesPerBuffer = stream->capture.pPin->frameSize;
+        }
+        PA_DEBUG(("Input frames chosen:%ld\n",stream->capture.framesPerBuffer));
+
+        /* Setup number of packets to use */
+        stream->capture.noOfPackets = 2;
+
+        if (inputParameters->hostApiSpecificStreamInfo)
+        {
+            PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)inputParameters->hostApiSpecificStreamInfo;
+
+            if (stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&
+                pInfo->noOfPackets != 0)
+            {
+                stream->capture.noOfPackets = pInfo->noOfPackets;
+            }
+        }
+    }
+
+    if(outputParameters)
+    {
+        /* Calculate the frames from the user's value - add a bit to round up */
+        stream->render.framesPerBuffer = (unsigned long)((outputParameters->suggestedLatency*sampleRate)+0.0001);
+        if(stream->render.framesPerBuffer > (unsigned long)sampleRate)
+        { /* Upper limit is 1 second */
+            stream->render.framesPerBuffer = (unsigned long)sampleRate;
+        }
+        else if(stream->render.framesPerBuffer < stream->render.pPin->frameSize)
+        {
+            stream->render.framesPerBuffer = stream->render.pPin->frameSize;
+        }
+        PA_DEBUG(("Output frames chosen:%ld\n",stream->render.framesPerBuffer));
+
+        /* Setup number of packets to use */
+        stream->render.noOfPackets = 2;
+
+        if (outputParameters->hostApiSpecificStreamInfo)
+        {
+            PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)outputParameters->hostApiSpecificStreamInfo;
+
+            if (stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&
+                pInfo->noOfPackets != 0)
+            {
+                stream->render.noOfPackets = pInfo->noOfPackets;
+            }
+        }
+    }
+
+    /* Host buffer size is bound to the largest of the input and output frame sizes */
+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+        stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,
+        stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,
+        sampleRate, streamFlags, framesPerUserBuffer,
+        max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer), 
+        paUtilBoundedHostBufferSize,
+        streamCallback, userData );
+    if( result != paNoError )
+    {
+        PaWinWDM_SetLastErrorInfo(result, "PaUtil_InitializeBufferProcessor failed: ich=%u, isf=%u, hisf=%u, och=%u, osf=%u, hosf=%u, sr=%lf, flags=0x%X, fpub=%u, fphb=%u",
+            stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,
+            stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,
+            sampleRate, streamFlags, framesPerUserBuffer,
+            max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer));
+        goto error;
+    }
+
+    /* Allocate/get all the buffers for host I/O */
+    if (stream->userInputChannels > 0)
+    {
+        stream->streamRepresentation.streamInfo.inputLatency = stream->capture.framesPerBuffer / sampleRate;
+
+        switch (stream->capture.pPin->parentFilter->devInfo.streamingType)
+        {
+        case Type_kWaveCyclic:
+            {
+                unsigned size = stream->capture.noOfPackets * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
+                /* Allocate input host buffer */
+                stream->capture.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);
+                PA_DEBUG(("Input buffer allocated (size = %u)\n", size));
+                if( !stream->capture.hostBuffer )
+                {
+                    PA_DEBUG(("Cannot allocate host input buffer!\n"));
+                    PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate input buffer");
+                    result = paInsufficientMemory;
+                    goto error;
+                }
+                stream->capture.hostBufferSize = size;
+                PA_DEBUG(("Input buffer start = %p (size=%u)\n",stream->capture.hostBuffer, stream->capture.hostBufferSize));
+                stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveCyclic;
+                stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveCyclic;
+            }
+            break;
+        case Type_kWaveRT:
+            {
+                const DWORD dwTotalSize = 2 * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
+                DWORD dwRequestedSize = dwTotalSize;
+                BOOL bCallMemoryBarrier = FALSE;
+                ULONG hwFifoLatency = 0;
+                ULONG dummy;
+                result = PinGetBuffer(stream->capture.pPin, (void**)&stream->capture.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);
+                if (!result) 
+                {
+                    PA_DEBUG(("Input buffer start = %p, size = %u\n", stream->capture.hostBuffer, dwRequestedSize));
+                    if (dwRequestedSize != dwTotalSize)
+                    {
+                        PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));
+                        /* Recalculate to what the driver has given us */
+                        stream->capture.framesPerBuffer = dwRequestedSize / (2 * stream->capture.bytesPerFrame);
+                    }
+                    stream->capture.hostBufferSize = dwRequestedSize;
+
+                    if (stream->capture.pPin->pinKsSubType == SubType_kPolled)
+                    {
+                        stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTPolled;
+                        stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTPolled;
+                    }
+                    else
+                    {
+                        stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTEvent;
+                        stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTEvent;
+                    }
+
+                    stream->capture.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierRead : MemoryBarrierDummy;
+                }
+                else 
+                {
+                    PA_DEBUG(("Failed to get input buffer (WaveRT)\n"));
+                    PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get input buffer (WaveRT)");
+                    result = paUnanticipatedHostError;
+                    goto error;
+                }
+
+                /* Get latency */
+                result = PinGetHwLatency(stream->capture.pPin, &hwFifoLatency, &dummy, &dummy);
+                if (result == paNoError)
+                {
+                    stream->capture.pPin->hwLatency = hwFifoLatency;
+
+                    /* Add HW latency into total input latency */
+                    stream->streamRepresentation.streamInfo.inputLatency += ((hwFifoLatency / stream->capture.bytesPerFrame) / sampleRate);
+                }
+                else
+                {
+                    PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));
+                    stream->capture.pPin->hwLatency = 0;
+                }
+            }
+            break;
+        default:
+            /* Undefined wave type!! */
+            assert(0);
+            result = paInternalError;
+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
+            goto error;
+        }
+    }
+    else 
+    {
+        stream->capture.hostBuffer = 0;
+    }
+
+    if (stream->userOutputChannels > 0)
+    {
+        stream->streamRepresentation.streamInfo.outputLatency = stream->render.framesPerBuffer / sampleRate;
+
+        switch (stream->render.pPin->parentFilter->devInfo.streamingType)
+        {
+        case Type_kWaveCyclic:
+            {
+                unsigned size = stream->render.noOfPackets * stream->render.framesPerBuffer * stream->render.bytesPerFrame;
+                /* Allocate output device buffer */
+                stream->render.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);
+                PA_DEBUG(("Output buffer allocated (size = %u)\n", size));
+                if( !stream->render.hostBuffer )
+                {
+                    PA_DEBUG(("Cannot allocate host output buffer!\n"));
+                    PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate output buffer");
+                    result = paInsufficientMemory;
+                    goto error;
+                }
+                stream->render.hostBufferSize = size;
+                PA_DEBUG(("Output buffer start = %p (size=%u)\n",stream->render.hostBuffer, stream->render.hostBufferSize));
+
+                stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveCyclic;
+                stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveCyclic;
+            }
+            break;
+        case Type_kWaveRT:
+            {
+                const DWORD dwTotalSize = 2 * stream->render.framesPerBuffer * stream->render.bytesPerFrame;
+                DWORD dwRequestedSize = dwTotalSize;
+                BOOL bCallMemoryBarrier = FALSE;
+                ULONG hwFifoLatency = 0;
+                ULONG dummy;
+                result = PinGetBuffer(stream->render.pPin, (void**)&stream->render.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);
+                if (!result) 
+                {
+                    PA_DEBUG(("Output buffer start = %p, size = %u, membarrier = %u\n", stream->render.hostBuffer, dwRequestedSize, bCallMemoryBarrier));
+                    if (dwRequestedSize != dwTotalSize)
+                    {
+                        PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));
+                        /* Recalculate to what the driver has given us */
+                        stream->render.framesPerBuffer = dwRequestedSize / (2 * stream->render.bytesPerFrame);
+                    }
+                    stream->render.hostBufferSize = dwRequestedSize;
+
+                    if (stream->render.pPin->pinKsSubType == SubType_kPolled)
+                    {
+                        stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTPolled;
+                        stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTPolled;
+                    }
+                    else
+                    {
+                        stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTEvent;
+                        stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTEvent;
+                    }
+
+                    stream->render.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierWrite : MemoryBarrierDummy;
+                }
+                else 
+                {
+                    PA_DEBUG(("Failed to get output buffer (with notification)\n"));
+                    PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get output buffer (with notification)");
+                    result = paUnanticipatedHostError;
+                    goto error;
+                }
+
+                /* Get latency */
+                result = PinGetHwLatency(stream->render.pPin, &hwFifoLatency, &dummy, &dummy);
+                if (result == paNoError)
+                {
+                    stream->render.pPin->hwLatency = hwFifoLatency;
+
+                    /* Add HW latency into total output latency */
+                    stream->streamRepresentation.streamInfo.outputLatency += ((hwFifoLatency / stream->render.bytesPerFrame) / sampleRate);
+                }
+                else
+                {
+                    PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));
+                    stream->render.pPin->hwLatency = 0;
+                }
+            }
+            break;
+        default:
+            /* Undefined wave type!! */
+            assert(0);
+            result = paInternalError;
+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
+            goto error;
+        }
+    }
+    else 
+    {
+        stream->render.hostBuffer = 0;
+    }
+
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    PA_DEBUG(("BytesPerInputFrame = %d\n",stream->capture.bytesPerFrame));
+    PA_DEBUG(("BytesPerOutputFrame = %d\n",stream->render.bytesPerFrame));
+
+    /* memset(stream->hostBuffer,0,size); */
+
+    /* Abort */
+    stream->eventAbort          = CreateEvent(NULL, TRUE, FALSE, NULL);
+    if (stream->eventAbort == 0)
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    stream->eventStreamStart[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
+    if (stream->eventStreamStart[0] == 0)
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    stream->eventStreamStart[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
+    if (stream->eventStreamStart[1] == 0)
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    if(stream->userInputChannels > 0)
+    {
+        const unsigned bufferSizeInBytes = stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
+        const unsigned ringBufferFrameSize = NextPowerOf2( 1024 + 2 * max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer) );
+
+        stream->capture.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(HANDLE));
+        if (stream->capture.events == NULL)
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        stream->capture.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(DATAPACKET));
+        if (stream->capture.packets == NULL)
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        switch(stream->capture.pPin->parentFilter->devInfo.streamingType)
+        {
+        case Type_kWaveCyclic:
+            {
+                /* WaveCyclic case */
+                unsigned i;
+                for (i = 0; i < stream->capture.noOfPackets; ++i)
+                {
+                    /* Set up the packets */
+                    DATAPACKET *p = stream->capture.packets + i;
+
+                    /* Record event */
+                    stream->capture.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
+
+                    p->Signal.hEvent = stream->capture.events[i];
+                    p->Header.Data = stream->capture.hostBuffer + (i*bufferSizeInBytes);
+                    p->Header.FrameExtent = bufferSizeInBytes;
+                    p->Header.DataUsed = 0;
+                    p->Header.Size = sizeof(p->Header);
+                    p->Header.PresentationTime.Numerator = 1;
+                    p->Header.PresentationTime.Denominator = 1;
+                }
+            }
+            break;
+        case Type_kWaveRT:
+            {
+                /* Set up the "packets" */
+                DATAPACKET *p = stream->capture.packets + 0;
+
+                /* Record event: WaveRT has a single event for 2 notification per buffer */
+                stream->capture.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
+
+                p->Header.Data = stream->capture.hostBuffer;
+                p->Header.FrameExtent = bufferSizeInBytes;
+                p->Header.DataUsed = 0;
+                p->Header.Size = sizeof(p->Header);
+                p->Header.PresentationTime.Numerator = 1;
+                p->Header.PresentationTime.Denominator = 1;
+
+                ++p;
+                p->Header.Data = stream->capture.hostBuffer + bufferSizeInBytes;
+                p->Header.FrameExtent = bufferSizeInBytes;
+                p->Header.DataUsed = 0;
+                p->Header.Size = sizeof(p->Header);
+                p->Header.PresentationTime.Numerator = 1;
+                p->Header.PresentationTime.Denominator = 1;
+
+                if (stream->capture.pPin->pinKsSubType == SubType_kNotification)
+                {
+                    result = PinRegisterNotificationHandle(stream->capture.pPin, stream->capture.events[0]);
+
+                    if (result != paNoError)
+                    {
+                        PA_DEBUG(("Failed to register capture notification handle\n"));
+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register capture notification handle");
+                        result = paUnanticipatedHostError;
+                        goto error;
+                    }
+                }
+
+                result = PinRegisterPositionRegister(stream->capture.pPin);
+
+                if (result != paNoError)
+                {
+                    unsigned long pos = 0xdeadc0de;
+                    PA_DEBUG(("Failed to register capture position register, using PinGetAudioPositionViaIOCTLWrite\n"));
+                    stream->capture.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTLWrite;
+                    /* Test position function */
+                    result = (stream->capture.pPin->fnAudioPosition)(stream->capture.pPin, &pos);
+                    if (result != paNoError || pos != 0x0)
+                    {
+                        PA_DEBUG(("Failed to read capture position register (IOCTL)\n"));
+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read capture position register (IOCTL)");
+                        result = paUnanticipatedHostError;
+                        goto error;
+                    }                
+                }
+                else
+                {
+                    stream->capture.pPin->fnAudioPosition = PinGetAudioPositionMemoryMapped;
+                }
+            }
+            break;
+        default:
+            /* Undefined wave type!! */
+            assert(0);
+            result = paInternalError;
+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
+            goto error;
+        }
+
+        /* Setup the input ring buffer here */
+        stream->ringBufferData = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, ringBufferFrameSize * stream->capture.bytesPerFrame);
+        if (stream->ringBufferData == NULL)
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        PaUtil_InitializeRingBuffer(&stream->ringBuffer, stream->capture.bytesPerFrame, ringBufferFrameSize, stream->ringBufferData);
+    }
+    if(stream->userOutputChannels > 0)
+    {
+        const unsigned bufferSizeInBytes = stream->render.framesPerBuffer * stream->render.bytesPerFrame;
+
+        stream->render.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(HANDLE));
+        if (stream->render.events == NULL)
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        stream->render.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(DATAPACKET));
+        if (stream->render.packets == NULL)
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        switch(stream->render.pPin->parentFilter->devInfo.streamingType)
+        {
+        case Type_kWaveCyclic:
+            {
+                /* WaveCyclic case */
+                unsigned i;
+                for (i = 0; i < stream->render.noOfPackets; ++i)
+                {
+                    /* Set up the packets */
+                    DATAPACKET *p = stream->render.packets + i;
+
+                    /* Playback event */
+                    stream->render.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
+
+                    /* In this case, we just use the packets as ptr to the device buffer */
+                    p->Signal.hEvent = stream->render.events[i];
+                    p->Header.Data = stream->render.hostBuffer + (i*bufferSizeInBytes);
+                    p->Header.FrameExtent = bufferSizeInBytes;
+                    p->Header.DataUsed = bufferSizeInBytes;
+                    p->Header.Size = sizeof(p->Header);
+                    p->Header.PresentationTime.Numerator = 1;
+                    p->Header.PresentationTime.Denominator = 1;
+                }
+            }
+            break;
+        case Type_kWaveRT:
+            {
+                /* WaveRT case */
+
+                /* Set up the "packets" */
+                DATAPACKET *p = stream->render.packets;
+
+                /* The only playback event */
+                stream->render.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
+
+                /* In this case, we just use the packets as ptr to the device buffer */
+                p->Header.Data = stream->render.hostBuffer;
+                p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
+                p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
+                p->Header.Size = sizeof(p->Header);
+                p->Header.PresentationTime.Numerator = 1;
+                p->Header.PresentationTime.Denominator = 1;
+
+                ++p;
+                p->Header.Data = stream->render.hostBuffer + stream->render.framesPerBuffer*stream->render.bytesPerFrame;
+                p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
+                p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
+                p->Header.Size = sizeof(p->Header);
+                p->Header.PresentationTime.Numerator = 1;
+                p->Header.PresentationTime.Denominator = 1;
+
+                if (stream->render.pPin->pinKsSubType == SubType_kNotification)
+                {
+                    result = PinRegisterNotificationHandle(stream->render.pPin, stream->render.events[0]);
+
+                    if (result != paNoError)
+                    {
+                        PA_DEBUG(("Failed to register rendering notification handle\n"));
+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register rendering notification handle");
+                        result = paUnanticipatedHostError;
+                        goto error;
+                    }
+                }
+
+                result = PinRegisterPositionRegister(stream->render.pPin);
+
+                if (result != paNoError)
+                {
+                    unsigned long pos = 0xdeadc0de;
+                    PA_DEBUG(("Failed to register rendering position register, using PinGetAudioPositionViaIOCTLRead\n"));
+                    stream->render.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTLRead;
+                    /* Test position function */
+                    result = (stream->render.pPin->fnAudioPosition)(stream->render.pPin, &pos);
+                    if (result != paNoError || pos != 0x0)
+                    {
+                        PA_DEBUG(("Failed to read render position register (IOCTL)\n"));
+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read render position register (IOCTL)");
+                        result = paUnanticipatedHostError;
+                        goto error;
+                    }
+                }
+                else
+                {
+                    stream->render.pPin->fnAudioPosition = PinGetAudioPositionMemoryMapped;
+                }
+            }
+            break;
+        default:
+            /* Undefined wave type!! */
+            assert(0);
+            result = paInternalError;
+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
+            goto error;
+        }
+    }
+
+    stream->streamStarted = 0;
+    stream->streamActive = 0;
+    stream->streamStop = 0;
+    stream->streamAbort = 0;
+    stream->streamFlags = streamFlags;
+    stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
+
+    /* Increase ref count on filters in use, so that a CommitDeviceInfos won't delete them */
+    if (stream->capture.pPin != 0)
+    {
+        FilterAddRef(stream->capture.pPin->parentFilter);
+    }
+    if (stream->render.pPin != 0)
+    {
+        FilterAddRef(stream->render.pPin->parentFilter);
+    }
+
+    /* Ok, now update our host API specific stream info */
+    if (stream->userInputChannels)
+    {
+        PaWinWdmDeviceInfo *pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
+
+        stream->hostApiStreamInfo.input.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), inputParameters->device);
+        stream->hostApiStreamInfo.input.channels = stream->deviceInputChannels;
+        stream->hostApiStreamInfo.input.muxNodeId = -1;
+        if (stream->capture.pPin->inputs)
+        {
+            stream->hostApiStreamInfo.input.muxNodeId = stream->capture.pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId;
+        }
+        stream->hostApiStreamInfo.input.endpointPinId = pDeviceInfo->endpointPinId;
+        stream->hostApiStreamInfo.input.framesPerHostBuffer = stream->capture.framesPerBuffer;
+        stream->hostApiStreamInfo.input.streamingSubType = stream->capture.pPin->pinKsSubType;
+    }
+    else
+    {
+        stream->hostApiStreamInfo.input.device = paNoDevice;
+    }
+    if (stream->userOutputChannels)
+    {
+        stream->hostApiStreamInfo.output.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), outputParameters->device);
+        stream->hostApiStreamInfo.output.channels = stream->deviceOutputChannels;
+        stream->hostApiStreamInfo.output.framesPerHostBuffer = stream->render.framesPerBuffer;
+        stream->hostApiStreamInfo.output.endpointPinId = stream->render.pPin->endpointPinId;
+        stream->hostApiStreamInfo.output.streamingSubType = stream->render.pPin->pinKsSubType;
+    }
+    else
+    {
+        stream->hostApiStreamInfo.output.device = paNoDevice;
+    }
+    /*stream->streamRepresentation.streamInfo.hostApiTypeId = paWDMKS;
+    stream->streamRepresentation.streamInfo.hostApiSpecificStreamInfo = &stream->hostApiStreamInfo;*/
+    stream->streamRepresentation.streamInfo.structVersion = 2;
+
+    *s = (PaStream*)stream;
+
+    PA_LOGL_;
+    return result;
+
+occupied:
+    /* Ok, someone else is hogging the pin, bail out */
+    assert (result == paDeviceUnavailable);
+    PaWinWDM_SetLastErrorInfo(result, "Device is occupied");
+
+error:
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+    CloseStreamEvents(stream);
+
+    if (stream->allocGroup)
+    {
+        PaUtil_FreeAllAllocations(stream->allocGroup);
+        PaUtil_DestroyAllocationGroup(stream->allocGroup);
+        stream->allocGroup = 0;
+    }
+
+    if(stream->render.pPin)
+        PinClose(stream->render.pPin);
+    if(stream->capture.pPin)
+        PinClose(stream->capture.pPin);
+
+    PaUtil_FreeMemory( stream );
+
+    PA_LOGL_;
+    return result;
+}
+
+/*
+When CloseStream() is called, the multi-api layer ensures that
+the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+
+    assert(!stream->streamStarted);
+    assert(!stream->streamActive);
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+    CloseStreamEvents(stream);
+
+    if (stream->allocGroup)
+    {
+        PaUtil_FreeAllAllocations(stream->allocGroup);
+        PaUtil_DestroyAllocationGroup(stream->allocGroup);
+        stream->allocGroup = 0;
+    }
+
+    if(stream->render.pPin)
+    {
+        PinClose(stream->render.pPin);
+    }
+    if(stream->capture.pPin)
+    {
+        PinClose(stream->capture.pPin);
+    }
+
+    if (stream->render.pPin)
+    {
+        FilterFree(stream->render.pPin->parentFilter);
+    }
+    if (stream->capture.pPin)
+    {
+        FilterFree(stream->capture.pPin->parentFilter);
+    }
+
+    PaUtil_FreeMemory( stream );
+
+    PA_LOGL_;
+    return result;
+}
+
+/*
+Write the supplied packet to the pin
+Asynchronous
+Should return paNoError on success
+*/
+static PaError PinWrite(HANDLE h, DATAPACKET* p)
+{
+    PaError result = paNoError;
+    unsigned long cbReturned = 0;
+    BOOL fRes = DeviceIoControl(h,
+        IOCTL_KS_WRITE_STREAM,
+        NULL,
+        0,
+        &p->Header,
+        p->Header.Size,
+        &cbReturned,
+        &p->Signal);
+    if (!fRes)
+    {
+        unsigned long error = GetLastError();
+        if (error != ERROR_IO_PENDING)
+        {
+            result = paInternalError;
+        }
+    }
+    return result;
+}
+
+/*
+Read to the supplied packet from the pin
+Asynchronous
+Should return paNoError on success
+*/
+static PaError PinRead(HANDLE h, DATAPACKET* p)
+{
+    PaError result = paNoError;
+    unsigned long cbReturned = 0;
+    BOOL fRes = DeviceIoControl(h,
+        IOCTL_KS_READ_STREAM,
+        NULL,
+        0,
+        &p->Header,
+        p->Header.Size,
+        &cbReturned,
+        &p->Signal);
+    if (!fRes)
+    {
+        unsigned long error = GetLastError();
+        if (error != ERROR_IO_PENDING)
+        {
+            result = paInternalError;
+        }
+    }
+    return result;
+}
+
+/*
+Copy the first interleaved channel of 16 bit data to the other channels
+*/
+static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples)
+{
+    unsigned short* data = (unsigned short*)buffer;
+    int channel;
+    unsigned short sourceSample;
+    while( samples-- )
+    {
+        sourceSample = *data++;
+        channel = channels-1;
+        while( channel-- )
+        {
+            *data++ = sourceSample;
+        }
+    }
+}
+
+/*
+Copy the first interleaved channel of 24 bit data to the other channels
+*/
+static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples)
+{
+    unsigned char* data = (unsigned char*)buffer;
+    int channel;
+    unsigned char sourceSample[3];
+    while( samples-- )
+    {
+        sourceSample[0] = data[0];
+        sourceSample[1] = data[1];
+        sourceSample[2] = data[2];
+        data += 3;
+        channel = channels-1;
+        while( channel-- )
+        {
+            data[0] = sourceSample[0];
+            data[1] = sourceSample[1];
+            data[2] = sourceSample[2];
+            data += 3;
+        }
+    }
+}
+
+/*
+Copy the first interleaved channel of 32 bit data to the other channels
+*/
+static void DuplicateFirstChannelInt32(void* buffer, int channels, int samples)
+{
+    unsigned long* data = (unsigned long*)buffer;
+    int channel;
+    unsigned long sourceSample;
+    while( samples-- )
+    {
+        sourceSample = *data++;
+        channel = channels-1;
+        while( channel-- )
+        {
+            *data++ = sourceSample;
+        }
+    }
+}
+
+/*
+Increase the priority of the calling thread to RT 
+*/
+static HANDLE BumpThreadPriority() 
+{
+    HANDLE hThread = GetCurrentThread();
+    DWORD dwTask = 0;
+    HANDLE hAVRT = NULL;
+
+    /* If we have access to AVRT.DLL (Vista and later), use it */
+    if (paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics != NULL) 
+    {
+        hAVRT = paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics("Pro Audio", &dwTask);
+        if (hAVRT != NULL && hAVRT != INVALID_HANDLE_VALUE) 
+        {
+            BOOL bret = paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_CRITICAL);
+            if (!bret)
+            {
+                PA_DEBUG(("Set mm thread prio to critical failed!\n"));
+            }
+            else
+            {
+                return hAVRT;
+            }
+        }
+        else
+        {
+            PA_DEBUG(("Set mm thread characteristic to 'Pro Audio' failed, reverting to SetThreadPriority\n"));
+        }
+    }
+
+    /* For XP and earlier, or if AvSetMmThreadCharacteristics fails (MMCSS disabled ?) */
+    if (timeBeginPeriod(1) != TIMERR_NOERROR) {
+        PA_DEBUG(("timeBeginPeriod(1) failed!\n"));
+    }
+
+    if (!SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL)) {
+        PA_DEBUG(("SetThreadPriority failed!\n"));
+    }
+
+    return hAVRT;
+}
+
+/*
+Decrease the priority of the calling thread to normal
+*/
+static void DropThreadPriority(HANDLE hAVRT)
+{
+    HANDLE hThread = GetCurrentThread();
+
+    if (hAVRT != NULL) 
+    {
+        paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_NORMAL);
+        paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics(hAVRT);
+        return;
+    }
+
+    SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL);
+    timeEndPeriod(1);
+}
+
+static PaError PreparePinForStart(PaWinWdmPin* pin)
+{
+    PaError result;
+    result = PinSetState(pin, KSSTATE_ACQUIRE);
+    if (result != paNoError)
+    {
+        goto error;
+    }
+    result = PinSetState(pin, KSSTATE_PAUSE);
+    if (result != paNoError)
+    {
+        goto error;
+    }
+    return result;
+
+error:
+    PinSetState(pin, KSSTATE_STOP);
+    return result;
+}
+
+static PaError PreparePinsForStart(PaProcessThreadInfo* pInfo)
+{
+    PaError result = paNoError;
+    /* Submit buffers */
+    if (pInfo->stream->capture.pPin)
+    {
+        if ((result = PreparePinForStart(pInfo->stream->capture.pPin)) != paNoError)
+        {
+            goto error;
+        }
+
+        if (pInfo->stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
+        {
+            unsigned i;
+            for(i=0; i < pInfo->stream->capture.noOfPackets; ++i)
+            {
+                if ((result = PinRead(pInfo->stream->capture.pPin->handle, pInfo->stream->capture.packets + i)) != paNoError)
+                {
+                    goto error;
+                }
+                ++pInfo->pending;
+            }
+        }
+        else
+        {
+            pInfo->pending = 2;
+        }
+    }
+
+    if(pInfo->stream->render.pPin)
+    {
+        if ((result = PreparePinForStart(pInfo->stream->render.pPin)) != paNoError)
+        {
+            goto error;
+        }
+
+        pInfo->priming += pInfo->stream->render.noOfPackets;
+        ++pInfo->pending;
+        SetEvent(pInfo->stream->render.events[0]);
+        if (pInfo->stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic) 
+        {
+            unsigned i;
+            for(i=1; i < pInfo->stream->render.noOfPackets; ++i)
+            {
+                SetEvent(pInfo->stream->render.events[i]);
+                ++pInfo->pending;
+            }
+        }
+    }
+
+error:
+    PA_DEBUG(("PreparePinsForStart = %d\n", result));
+    return result;
+}
+
+static PaError StartPin(PaWinWdmPin* pin)
+{
+    return PinSetState(pin, KSSTATE_RUN);
+}
+
+static PaError StartPins(PaProcessThreadInfo* pInfo)
+{
+    PaError result = paNoError;
+    /* Start the pins as synced as possible */
+    if (pInfo->stream->capture.pPin)
+    {
+        result = StartPin(pInfo->stream->capture.pPin);
+    }
+    if(pInfo->stream->render.pPin)
+    {
+        result = StartPin(pInfo->stream->render.pPin);
+    }
+    PA_DEBUG(("StartPins = %d\n", result));
+    return result;
+}
+
+
+static PaError StopPin(PaWinWdmPin* pin)
+{
+    PinSetState(pin, KSSTATE_PAUSE);
+    PinSetState(pin, KSSTATE_STOP);
+    return paNoError;
+}
+
+
+static PaError StopPins(PaProcessThreadInfo* pInfo)
+{
+    PaError result = paNoError;
+    if(pInfo->stream->render.pPin)
+    {
+        StopPin(pInfo->stream->render.pPin);
+    }
+    if(pInfo->stream->capture.pPin)
+    {
+        StopPin(pInfo->stream->capture.pPin);
+    }
+    return result;
+}
+
+typedef void (*TSetInputFrameCount)(PaUtilBufferProcessor*, unsigned long);
+typedef void (*TSetInputChannel)(PaUtilBufferProcessor*, unsigned int, void *, unsigned int);
+static const TSetInputFrameCount fnSetInputFrameCount[2] = { PaUtil_SetInputFrameCount, PaUtil_Set2ndInputFrameCount };
+static const TSetInputChannel fnSetInputChannel[2] = { PaUtil_SetInputChannel, PaUtil_Set2ndInputChannel };
+
+static PaError PaDoProcessing(PaProcessThreadInfo* pInfo)
+{
+    PaError result = paNoError;
+    int i, framesProcessed = 0, doChannelCopy = 0;
+    ring_buffer_size_t inputFramesAvailable = PaUtil_GetRingBufferReadAvailable(&pInfo->stream->ringBuffer);
+
+    /* Do necessary buffer processing (which will invoke user callback if necessary) */
+    if (pInfo->cbResult == paContinue &&
+        (pInfo->renderHead != pInfo->renderTail || inputFramesAvailable))
+    {
+        unsigned processFullDuplex = pInfo->stream->capture.pPin && pInfo->stream->render.pPin && (!pInfo->priming);
+
+        PA_HP_TRACE((pInfo->stream->hLog, "DoProcessing: InputFrames=%u", inputFramesAvailable));
+
+        PaUtil_BeginCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer );
+
+        pInfo->ti.currentTime = PaUtil_GetTime();
+
+        PaUtil_BeginBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->ti, pInfo->underover);
+        pInfo->underover = 0; /* Reset the (under|over)flow status */
+
+        if (pInfo->renderTail != pInfo->renderHead)
+        {
+            DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
+
+            assert(packet != 0);
+            assert(packet->Header.Data != 0);
+
+            PaUtil_SetOutputFrameCount(&pInfo->stream->bufferProcessor, pInfo->stream->render.framesPerBuffer);
+
+            for(i=0;i<pInfo->stream->userOutputChannels;i++)
+            {
+                /* Only write the user output channels. Leave the rest blank */
+                PaUtil_SetOutputChannel(&pInfo->stream->bufferProcessor,
+                    i,
+                    ((unsigned char*)(packet->Header.Data))+(i*pInfo->stream->render.bytesPerSample),
+                    pInfo->stream->deviceOutputChannels);
+            }
+
+            /* We will do a copy to the other channels after the data has been written */
+            doChannelCopy = ( pInfo->stream->userOutputChannels == 1 );
+        }
+
+        if (inputFramesAvailable && (!pInfo->stream->userOutputChannels || inputFramesAvailable >= (int)pInfo->stream->render.framesPerBuffer))
+        {
+            unsigned wrapCntr = 0;
+            void* data[2] = {0};
+            ring_buffer_size_t size[2] = {0};
+
+            /* If full-duplex, we just extract output buffer number of frames */
+            if (pInfo->stream->userOutputChannels)
+            {
+                inputFramesAvailable = min(inputFramesAvailable, (int)pInfo->stream->render.framesPerBuffer);
+            }
+
+            inputFramesAvailable = PaUtil_GetRingBufferReadRegions(&pInfo->stream->ringBuffer,
+                inputFramesAvailable,
+                &data[0],
+                &size[0],
+                &data[1],
+                &size[1]);
+
+            for (wrapCntr = 0; wrapCntr < 2; ++wrapCntr)
+            {
+                if (size[wrapCntr] == 0)
+                    break;
+
+                fnSetInputFrameCount[wrapCntr](&pInfo->stream->bufferProcessor, size[wrapCntr]);
+                for(i=0;i<pInfo->stream->userInputChannels;i++)
+                {
+                    /* Only read as many channels as the user wants */
+                    fnSetInputChannel[wrapCntr](&pInfo->stream->bufferProcessor,
+                        i,
+                        ((unsigned char*)(data[wrapCntr]))+(i*pInfo->stream->capture.bytesPerSample),
+                        pInfo->stream->deviceInputChannels);
+                }
+            }
+        }
+        else
+        {
+            /* We haven't consumed anything from the ring buffer... */
+            inputFramesAvailable = 0;
+            /* If we have full-duplex, this is at startup, so mark no-input! */
+            if (pInfo->stream->userOutputChannels>0 && pInfo->stream->userInputChannels>0)
+            {
+                PA_HP_TRACE((pInfo->stream->hLog, "Input startup, marking no input."));
+                PaUtil_SetNoInput(&pInfo->stream->bufferProcessor);
+            }
+        }
+
+        if (processFullDuplex) /* full duplex */
+        {
+            /* Only call the EndBufferProcessing function when the total input frames == total output frames */
+            const unsigned long totalInputFrameCount = pInfo->stream->bufferProcessor.hostInputFrameCount[0] + pInfo->stream->bufferProcessor.hostInputFrameCount[1];
+            const unsigned long totalOutputFrameCount = pInfo->stream->bufferProcessor.hostOutputFrameCount[0] + pInfo->stream->bufferProcessor.hostOutputFrameCount[1];
+
+            if(totalInputFrameCount == totalOutputFrameCount && totalOutputFrameCount != 0)
+            {
+                framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);
+            }
+            else
+            {
+                framesProcessed = 0;
+            }
+        }
+        else 
+        {
+            framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);
+        }
+
+        PA_HP_TRACE((pInfo->stream->hLog, "Frames processed: %u %s", framesProcessed, (pInfo->priming ? "(priming)":"")));
+
+        if( doChannelCopy )
+        {
+            DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
+            /* Copy the first output channel to the other channels */
+            switch (pInfo->stream->render.bytesPerSample)
+            {
+            case 2:
+                DuplicateFirstChannelInt16(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
+                break;
+            case 3:
+                DuplicateFirstChannelInt24(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
+                break;
+            case 4:
+                DuplicateFirstChannelInt32(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
+                break;
+            default:
+                assert(0); /* Unsupported format! */
+                break;
+            }
+        }
+        PaUtil_EndCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer, framesProcessed );
+
+        if (inputFramesAvailable)
+        {
+            PaUtil_AdvanceRingBufferReadIndex(&pInfo->stream->ringBuffer, inputFramesAvailable);
+        }
+
+        if (pInfo->renderTail != pInfo->renderHead)
+        {
+            if (!pInfo->stream->streamStop)
+            {
+                result = pInfo->stream->render.pPin->fnSubmitHandler(pInfo, pInfo->renderTail);
+                if (result != paNoError)
+                {
+                    PA_HP_TRACE((pInfo->stream->hLog, "Capture submit handler failed with result %d", result));
+                    return result;
+                }
+            }
+            pInfo->renderTail++;
+            if (!pInfo->pinsStarted && pInfo->priming == 0)
+            {
+                /* We start the pins here to allow "prime time" */
+                if ((result = StartPins(pInfo)) == paNoError)
+                {
+                    PA_HP_TRACE((pInfo->stream->hLog, "Starting pins!"));
+                    pInfo->pinsStarted = 1;
+                }
+            }
+        }
+    }
+
+    return result;
+}
+
+static VOID CALLBACK TimerAPCWaveRTPolledMode(
+    LPVOID lpArgToCompletionRoutine,
+    DWORD dwTimerLowValue,
+    DWORD dwTimerHighValue)
+{
+    HANDLE* pHandles = (HANDLE*)lpArgToCompletionRoutine;
+    if (pHandles[0]) SetEvent(pHandles[0]);
+    if (pHandles[1]) SetEvent(pHandles[1]);
+}
+
+static DWORD GetCurrentTimeInMillisecs()
+{
+    return timeGetTime();
+}
+
+PA_THREAD_FUNC ProcessingThread(void* pParam)
+{
+    PaError result = paNoError;
+    HANDLE hAVRT = NULL;
+    HANDLE hTimer = NULL;
+    HANDLE *handleArray = NULL;
+    HANDLE timerEventHandles[2] = {0};
+    unsigned noOfHandles = 0;
+    unsigned captureEvents = 0;
+    unsigned renderEvents = 0;
+    unsigned timerPeriod = 0;
+    DWORD timeStamp[2] = {0};
+
+    PaProcessThreadInfo info;
+    memset(&info, 0, sizeof(PaProcessThreadInfo));
+    info.stream = (PaWinWdmStream*)pParam;
+
+    info.stream->threadResult = paNoError;
+
+    PA_LOGE_;
+
+    info.ti.inputBufferAdcTime = 0.0;
+    info.ti.currentTime = 0.0;
+    info.ti.outputBufferDacTime = 0.0;
+
+    PA_DEBUG(("In  buffer len: %.3f ms\n",(2000*info.stream->capture.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));
+    PA_DEBUG(("Out buffer len: %.3f ms\n",(2000*info.stream->render.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));
+    info.timeout = (DWORD)max(
+        (2000*info.stream->render.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5),
+        (2000*info.stream->capture.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5));
+    info.timeout = max(info.timeout*8, 100);
+    timerPeriod = info.timeout;
+    PA_DEBUG(("Timeout = %ld ms\n",info.timeout));
+
+    /* Allocate handle array */
+    handleArray = (HANDLE*)PaUtil_AllocateMemory((info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1) * sizeof(HANDLE));
+
+    /* Setup handle array for WFMO */
+    if (info.stream->capture.pPin != 0)
+    {
+        handleArray[noOfHandles++] = info.stream->capture.events[0];
+        if (info.stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
+        {
+            unsigned i;
+            for(i=1; i < info.stream->capture.noOfPackets; ++i)
+            {
+                handleArray[noOfHandles++] = info.stream->capture.events[i];
+            }
+        }
+        captureEvents = noOfHandles;
+        renderEvents = noOfHandles;
+    }
+
+    if (info.stream->render.pPin != 0)
+    {
+        handleArray[noOfHandles++] = info.stream->render.events[0];
+        if (info.stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
+        {
+            unsigned i;
+            for(i=1; i < info.stream->render.noOfPackets; ++i)
+            {
+                handleArray[noOfHandles++] = info.stream->render.events[i];
+            }
+        }
+        renderEvents = noOfHandles;
+    }
+    handleArray[noOfHandles++] = info.stream->eventAbort;
+    assert(noOfHandles <= (info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1));
+
+    /* Prepare render and capture pins */
+    if ((result = PreparePinsForStart(&info)) != paNoError) 
+    {
+        PA_DEBUG(("Failed to prepare device(s)!\n"));
+        goto error;
+    }
+
+    /* Init high speed logger */
+    if (PaUtil_InitializeHighSpeedLog(&info.stream->hLog, 1000000) != paNoError)
+    {
+        PA_DEBUG(("Failed to init high speed logger!\n"));
+        goto error;
+    }
+
+    /* Heighten priority here */
+    hAVRT = BumpThreadPriority();
+
+    /* If input only, we start the pins immediately */
+    if (info.stream->render.pPin == 0)
+    {
+        if ((result = StartPins(&info)) != paNoError)
+        {
+            PA_DEBUG(("Failed to start device(s)!\n"));
+            goto error;
+        }
+        info.pinsStarted = 1;
+    }
+
+    /* Handle WaveRT polled mode */
+    {
+        const unsigned fs = (unsigned)info.stream->streamRepresentation.streamInfo.sampleRate;
+        if (info.stream->capture.pPin != 0 && info.stream->capture.pPin->pinKsSubType == SubType_kPolled)
+        {
+            timerEventHandles[0] = info.stream->capture.events[0];
+            timerPeriod = min(timerPeriod, (1000*info.stream->capture.framesPerBuffer)/fs);
+        }
+
+        if (info.stream->render.pPin != 0 && info.stream->render.pPin->pinKsSubType == SubType_kPolled)
+        {
+            timerEventHandles[1] = info.stream->render.events[0];
+            timerPeriod = min(timerPeriod, (1000*info.stream->render.framesPerBuffer)/fs);
+        }
+
+        if (timerEventHandles[0] || timerEventHandles[1])
+        {
+            LARGE_INTEGER dueTime = {0};
+
+            timerPeriod=max(timerPeriod/5,1);
+            PA_DEBUG(("Timer event handles=0x%04X,0x%04X period=%u ms", timerEventHandles[0], timerEventHandles[1], timerPeriod));
+            hTimer = CreateWaitableTimer(0, FALSE, NULL);
+            if (hTimer == NULL)
+            {
+                result = paUnanticipatedHostError;
+                goto error;
+            }
+            /* invoke first timeout immediately */
+            if (!SetWaitableTimer(hTimer, &dueTime, timerPeriod, TimerAPCWaveRTPolledMode, timerEventHandles, FALSE))
+            {
+                result = paUnanticipatedHostError;
+                goto error;
+            }
+            PA_DEBUG(("Waitable timer started, period = %u ms\n", timerPeriod));
+        }
+    }
+
+    /* Mark stream as active */
+    info.stream->streamActive = 1;
+    info.stream->threadResult = paNoError;
+
+    /* Up and running... */
+    SetEvent(info.stream->eventStreamStart[StreamStart_kOk]);
+
+    /* Take timestamp here */
+    timeStamp[0] = timeStamp[1] = GetCurrentTimeInMillisecs();
+
+    while(!info.stream->streamAbort)
+    {
+        unsigned doProcessing = 1;
+        unsigned wait = WaitForMultipleObjects(noOfHandles, handleArray, FALSE, 0);
+        unsigned eventSignalled = wait - WAIT_OBJECT_0;
+        DWORD dwCurrentTime = 0;
+
+        if (wait == WAIT_FAILED) 
+        {
+            PA_DEBUG(("Wait failed = %ld! \n",wait));
+            break;
+        }
+        if (wait == WAIT_TIMEOUT)
+        {
+            wait = WaitForMultipleObjectsEx(noOfHandles, handleArray, FALSE, 50, TRUE);
+            eventSignalled = wait - WAIT_OBJECT_0;
+        }
+        else
+        {
+            if (eventSignalled < captureEvents)
+            {
+                if (PaUtil_GetRingBufferWriteAvailable(&info.stream->ringBuffer) == 0)
+                {
+                    PA_HP_TRACE((info.stream->hLog, "!!!!! Input overflow !!!!!"));
+                    info.underover |= paInputOverflow;
+                }
+            }
+            else if (eventSignalled < renderEvents)
+            {
+                if (!info.priming && info.renderHead - info.renderTail > 1)
+                {
+                    PA_HP_TRACE((info.stream->hLog, "!!!!! Output underflow !!!!!"));
+                    info.underover |= paOutputUnderflow;
+                }
+            }
+        }
+
+        /* Get event time */
+        dwCurrentTime = GetCurrentTimeInMillisecs();
+
+        /* Since we can mix capture/render devices between WaveCyclic, WaveRT polled and WaveRT notification (3x3 combinations), 
+        we can't rely on the timeout of WFMO to check for device timeouts, we need to keep tally. */
+        if (info.stream->capture.pPin && (dwCurrentTime - timeStamp[0]) >= info.timeout)
+        {
+            PA_DEBUG(("Timeout for capture device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[0])));
+            result = paTimedOut;
+            break;
+        }
+        if (info.stream->render.pPin && (dwCurrentTime - timeStamp[1]) >= info.timeout)
+        {
+            PA_DEBUG(("Timeout for render device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[1])));
+            result = paTimedOut;
+            break;
+        }
+
+        if (wait == WAIT_IO_COMPLETION)
+        {
+            /* Waitable timer has fired! */
+            PA_HP_TRACE((info.stream->hLog, "WAIT_IO_COMPLETION"));
+            continue;
+        }
+
+        if (wait == WAIT_TIMEOUT)
+        {
+            continue;
+        }
+        else
+        {
+            if (eventSignalled < captureEvents)
+            {
+                if (info.stream->capture.pPin->fnEventHandler(&info, eventSignalled) == paNoError)
+                {
+                    timeStamp[0] = dwCurrentTime;
+
+                    /* Since we use the ring buffer, we can submit the buffers directly */
+                    if (!info.stream->streamStop)
+                    {
+                        result = info.stream->capture.pPin->fnSubmitHandler(&info, info.captureTail);
+                        if (result != paNoError)
+                        {
+                            PA_HP_TRACE((info.stream->hLog, "Capture submit handler failed with result %d", result));
+                            break;
+                        }
+                    }
+                    ++info.captureTail;
+                    /* If full-duplex, let _only_ render event trigger processing. We still need the stream stop
+                    handling working, so let that be processed anyways... */
+                    if (info.stream->userOutputChannels > 0)
+                    {
+                        doProcessing = 0;
+                    }
+                }
+            }
+            else if (eventSignalled < renderEvents)
+            {
+                timeStamp[1] = dwCurrentTime;
+                eventSignalled -= captureEvents;
+                info.stream->render.pPin->fnEventHandler(&info, eventSignalled);
+            }
+            else
+            {
+                assert(info.stream->streamAbort);
+                PA_HP_TRACE((info.stream->hLog, "Stream abort!"));
+                continue;
+            }
+        }
+
+        /* Handle processing */
+        if (doProcessing)
+        {
+            result = PaDoProcessing(&info);
+            if (result != paNoError)
+            {
+                PA_HP_TRACE((info.stream->hLog, "PaDoProcessing failed!"));
+                break;
+            }
+        }
+
+        if(info.stream->streamStop && info.cbResult != paComplete)
+        {
+            PA_HP_TRACE((info.stream->hLog, "Stream stop! pending=%d",info.pending));
+            info.cbResult = paComplete; /* Stop, but play remaining buffers */
+        }
+
+        if(info.pending<=0)
+        {
+            PA_HP_TRACE((info.stream->hLog, "pending==0 finished..."));
+            break;
+        }
+        if((!info.stream->render.pPin)&&(info.cbResult!=paContinue))
+        {
+            PA_HP_TRACE((info.stream->hLog, "record only cbResult=%d...",info.cbResult));
+            break;
+        }
+    }
+
+    PA_DEBUG(("Finished processing loop\n"));
+
+    info.stream->threadResult = result;
+    goto bailout;
+
+error:
+    PA_DEBUG(("Error starting processing thread\n"));
+    /* Set the "error" event together with result */
+    info.stream->threadResult = result;
+    SetEvent(info.stream->eventStreamStart[StreamStart_kFailed]);
+
+bailout:
+    if (hTimer)
+    {
+        PA_DEBUG(("Waitable timer stopped\n", timerPeriod));
+        CancelWaitableTimer(hTimer);
+        CloseHandle(hTimer);
+        hTimer = 0;
+    }
+
+    if (info.pinsStarted)
+    {
+        StopPins(&info);
+    }
+
+    /* Lower prio here */
+    DropThreadPriority(hAVRT);
+
+    if (handleArray != NULL)
+    {
+        PaUtil_FreeMemory(handleArray);
+    }
+
+#if PA_TRACE_REALTIME_EVENTS
+    if (info.stream->hLog)
+    {
+        PA_DEBUG(("Dumping highspeed trace...\n"));
+        PaUtil_DumpHighSpeedLog(info.stream->hLog, "hp_trace.log");
+        PaUtil_DiscardHighSpeedLog(info.stream->hLog);
+        info.stream->hLog = 0;
+    }
+#endif
+    info.stream->streamActive = 0;
+
+    if((!info.stream->streamStop)&&(!info.stream->streamAbort))
+    {
+        /* Invoke the user stream finished callback */
+        /* Only do it from here if not being stopped/aborted by user */
+        if( info.stream->streamRepresentation.streamFinishedCallback != 0 )
+            info.stream->streamRepresentation.streamFinishedCallback( info.stream->streamRepresentation.userData );
+    }
+    info.stream->streamStop = 0;
+    info.stream->streamAbort = 0;
+
+    PA_LOGL_;
+    return 0;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+
+    if (stream->streamThread != NULL)
+    {
+        return paStreamIsNotStopped;
+    }
+
+    stream->streamStop = 0;
+    stream->streamAbort = 0;
+
+    ResetStreamEvents(stream);
+
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    stream->oldProcessPriority = GetPriorityClass(GetCurrentProcess());
+    /* Uncomment the following line to enable dynamic boosting of the process
+    * priority to real time for best low latency support
+    * Disabled by default because RT processes can easily block the OS */
+    /*ret = SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);
+    PA_DEBUG(("Class ret = %d;",ret));*/
+
+    stream->streamThread = CREATE_THREAD_FUNCTION (NULL, 0, ProcessingThread, stream, CREATE_SUSPENDED, NULL);
+    if(stream->streamThread == NULL)
+    {
+        result = paInsufficientMemory;
+        goto end;
+    }
+    ResumeThread(stream->streamThread);
+
+    switch (WaitForMultipleObjects(2, stream->eventStreamStart, FALSE, 5000))
+    {
+    case WAIT_OBJECT_0 + StreamStart_kOk:
+        PA_DEBUG(("Processing thread started!\n"));
+        result = paNoError;
+        /* streamActive is set in processing thread */
+        stream->streamStarted = 1;
+        break;
+    case WAIT_OBJECT_0 + StreamStart_kFailed:
+        PA_DEBUG(("Processing thread start failed! (result=%d)\n", stream->threadResult));
+        result = stream->threadResult;
+        /* Wait for the stream to really exit */
+        WaitForSingleObject(stream->streamThread, 200);
+        CloseHandle(stream->streamThread);
+        stream->streamThread = 0;
+        break;
+    case WAIT_TIMEOUT:
+    default:
+        result = paTimedOut;
+        PaWinWDM_SetLastErrorInfo(result, "Failed to start processing thread (timeout)!");
+        break;
+    }
+
+end:
+    PA_LOGL_;
+    return result;
+}
+
+
+static PaError StopStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+    BOOL doCb = FALSE;
+
+    PA_LOGE_;
+
+    if(stream->streamActive)
+    {
+        DWORD dwExitCode;
+        doCb = TRUE;
+        stream->streamStop = 1;
+        if (GetExitCodeThread(stream->streamThread, &dwExitCode) && dwExitCode == STILL_ACTIVE)
+        {
+            if (WaitForSingleObject(stream->streamThread, INFINITE) != WAIT_OBJECT_0)
+            {
+                PA_DEBUG(("StopStream: stream thread terminated\n"));
+                TerminateThread(stream->streamThread, -1);
+                result = paTimedOut;
+            }
+        }
+        else
+        {
+            PA_DEBUG(("StopStream: GECT says not active, but streamActive is not false ??"));
+            result = paUnanticipatedHostError;
+            PaWinWDM_SetLastErrorInfo(result, "StopStream: GECT says not active, but streamActive = %d", stream->streamActive);
+        }
+    }
+    else
+    {
+        if (stream->threadResult != paNoError)
+        {
+            PA_DEBUG(("StopStream: Stream not active (%d)\n", stream->threadResult));
+            result = stream->threadResult;
+            stream->threadResult = paNoError;
+        }
+    }
+
+    if (stream->streamThread != NULL)
+    {
+        CloseHandle(stream->streamThread);
+        stream->streamThread = 0;
+    }
+    stream->streamStarted = 0;
+    stream->streamActive = 0;
+
+    if(doCb)
+    {
+        /* Do user callback now after all state has been reset */
+        /* This means it should be safe for the called function */
+        /* to invoke e.g. StartStream */
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+
+    PA_LOGL_;
+    return result;
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+    int doCb = 0;
+
+    PA_LOGE_;
+
+    if(stream->streamActive)
+    {
+        doCb = 1;
+        stream->streamAbort = 1;
+        SetEvent(stream->eventAbort); /* Signal immediately */
+        if (WaitForSingleObject(stream->streamThread, 10000) != WAIT_OBJECT_0)
+        {
+            TerminateThread(stream->streamThread, -1);
+            result = paTimedOut;
+
+            PA_DEBUG(("AbortStream: stream thread terminated\n"));
+        }
+        assert(!stream->streamActive);
+    }
+    CloseHandle(stream->streamThread);
+    stream->streamThread = NULL;
+    stream->streamStarted = 0;
+
+    if(doCb)
+    {
+        /* Do user callback now after all state has been reset */
+        /* This means it should be safe for the called function */
+        /* to invoke e.g. StartStream */
+        if( stream->streamRepresentation.streamFinishedCallback != 0 )
+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+
+    stream->streamActive = 0;
+    stream->streamStarted = 0;
+
+    PA_LOGL_;
+    return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+    int result = 0;
+
+    PA_LOGE_;
+
+    if(!stream->streamStarted)
+        result = 1;
+
+    PA_LOGL_;
+    return result;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+    int result = 0;
+
+    PA_LOGE_;
+
+    if(stream->streamActive)
+        result = 1;
+
+    PA_LOGL_;
+    return result;
+}
+
+
+static PaTime GetStreamTime( PaStream* s )
+{
+    PA_LOGE_;
+    PA_LOGL_;
+    (void)s;
+    return PaUtil_GetTime();
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+    double result;
+    PA_LOGE_;
+    result = PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+    PA_LOGL_;
+    return result;
+}
+
+
+/*
+As separate stream interfaces are used for blocking and callback
+streams, the following functions can be guaranteed to only be called
+for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+                          void *buffer,
+                          unsigned long frames )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    PA_LOGL_;
+    return paInternalError;
+}
+
+
+static PaError WriteStream( PaStream* s,
+                           const void *buffer,
+                           unsigned long frames )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+
+    /* suppress unused variable warnings */
+    (void) buffer;
+    (void) frames;
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    PA_LOGL_;
+    return paInternalError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    PA_LOGL_;
+    return 0;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaWinWdmStream *stream = (PaWinWdmStream*)s;
+
+    PA_LOGE_;
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    PA_LOGL_;
+    return 0;
+}
+
+/***************************************************************************************/
+/* Event and submit handlers for WaveCyclic                                            */
+/***************************************************************************************/
+
+static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    PaError result = paNoError;
+    ring_buffer_size_t frameCount;
+    DATAPACKET* packet = pInfo->stream->capture.packets + eventIndex;
+
+    assert( eventIndex < pInfo->stream->capture.noOfPackets );
+
+    if (packet->Header.DataUsed == 0)
+    {
+        PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture bogus event (no data): idx=%u", eventIndex));
+
+        /* Bogus event, reset! This is to handle the behavior of this USB mic: http://shop.xtz.se/measurement-system/microphone-to-dirac-live-room-correction-suite 
+           on startup of streaming, where it erroneously sets the event without the corresponding buffer being filled (DataUsed == 0) */
+        ResetEvent(packet->Signal.hEvent);
+
+        result = -1;    /* Only need this to be NOT paNoError */
+    }
+    else
+    {
+        pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;
+
+        frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pInfo->stream->capture.framesPerBuffer);
+
+        PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture event: idx=%u (frames=%u)", eventIndex, frameCount));
+        ++pInfo->captureHead;
+    }
+
+    --pInfo->pending; /* This needs to be done in either case */
+    return result;
+}
+
+static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    PaError result = paNoError;
+    DATAPACKET* packet = pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet;
+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
+    assert(packet != 0);
+    PA_HP_TRACE((pInfo->stream->hLog, "Capture submit: %u", eventIndex));
+    packet->Header.DataUsed = 0; /* Reset for reuse */
+    ResetEvent(packet->Signal.hEvent);
+    result = PinRead(pInfo->stream->capture.pPin->handle, packet);
+    ++pInfo->pending;
+    return result;
+}
+
+static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    assert( eventIndex < pInfo->stream->render.noOfPackets );
+
+    pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask].packet = pInfo->stream->render.packets + eventIndex;
+    PA_HP_TRACE((pInfo->stream->hLog, "<<< Render event : idx=%u head=%u", eventIndex, pInfo->renderHead));
+    ++pInfo->renderHead;
+    --pInfo->pending;
+    return paNoError;
+}
+
+static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    PaError result = paNoError;
+    DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
+    assert(packet != 0);
+
+    PA_HP_TRACE((pInfo->stream->hLog, "Render submit : %u idx=%u", pInfo->renderTail, (unsigned)(packet - pInfo->stream->render.packets)));
+    ResetEvent(packet->Signal.hEvent);
+    result = PinWrite(pInfo->stream->render.pPin->handle, packet);
+    /* Reset event, just in case we have an analogous situation to capture (see PaPinCaptureSubmitHandler_WaveCyclic) */
+    ++pInfo->pending;
+    if (pInfo->priming)
+    {
+        --pInfo->priming;
+    }
+    return result;
+}
+
+/***************************************************************************************/
+/* Event and submit handlers for WaveRT                                                */
+/***************************************************************************************/
+
+static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    unsigned long pos;
+    unsigned realInBuf;
+    unsigned frameCount;
+    PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;
+    const unsigned halfInputBuffer = pCapture->hostBufferSize >> 1;
+    PaWinWdmPin* pin = pCapture->pPin;
+    DATAPACKET* packet = 0;
+
+    /* Get hold of current ADC position */
+    pin->fnAudioPosition(pin, &pos);
+    /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from
+    where it should be, i.e. at beginning or half buffer position. Why? No idea.)  */
+
+    pos %= pCapture->hostBufferSize;
+    /* Then realInBuf will point to "other" half of double buffer */
+    realInBuf = pos < halfInputBuffer ? 1U : 0U;
+
+    packet = pInfo->stream->capture.packets + realInBuf;
+
+    /* Call barrier (or dummy) */
+    pin->fnMemBarrier();
+
+    /* Put it in queue */
+    frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pCapture->framesPerBuffer);
+
+    pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;
+
+    PA_HP_TRACE((pInfo->stream->hLog, "Capture event (WaveRT): idx=%u head=%u (pos = %4.1lf%%, frames=%u)", realInBuf, pInfo->captureHead, (pos * 100.0 / pCapture->hostBufferSize), frameCount));
+
+    ++pInfo->captureHead;
+    --pInfo->pending;
+
+    return paNoError;
+}
+
+static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    unsigned long pos;
+    unsigned bytesToRead;
+    PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;
+    const unsigned halfInputBuffer = pCapture->hostBufferSize>>1;
+    PaWinWdmPin* pin = pInfo->stream->capture.pPin;
+
+    /* Get hold of current ADC position */
+    pin->fnAudioPosition(pin, &pos);
+    /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from
+    where it should be, i.e. at beginning or half buffer position. Why? No idea.)  */
+    /* Compensate for HW FIFO to get to last read buffer position */
+    pos += pin->hwLatency;
+    pos %= pCapture->hostBufferSize;
+    /* Need to align position on frame boundary */
+    pos &= ~(pCapture->bytesPerFrame - 1);
+
+    /* Call barrier (or dummy) */
+    pin->fnMemBarrier();
+
+    /* Put it in "queue" */
+    bytesToRead = (pCapture->hostBufferSize + pos - pCapture->lastPosition) % pCapture->hostBufferSize;
+    if (bytesToRead > 0)
+    {
+        unsigned frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer,
+            pCapture->hostBuffer + pCapture->lastPosition,
+            bytesToRead / pCapture->bytesPerFrame);
+
+        pCapture->lastPosition = (pCapture->lastPosition + frameCount * pCapture->bytesPerFrame) % pCapture->hostBufferSize;
+
+        PA_HP_TRACE((pInfo->stream->hLog, "Capture event (WaveRTPolled): pos = %4.1lf%%, framesRead=%u", (pos * 100.0 / pCapture->hostBufferSize), frameCount));
+        ++pInfo->captureHead;
+        --pInfo->pending;
+    }
+    return paNoError;
+}
+
+static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
+    ++pInfo->pending;
+    return paNoError;
+}
+
+static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
+    ++pInfo->pending;
+    return paNoError;
+}
+
+static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    unsigned long pos;
+    unsigned realOutBuf;
+    PaWinWdmIOInfo* pRender = &pInfo->stream->render;
+    const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;
+    PaWinWdmPin* pin = pInfo->stream->render.pPin;
+    PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];
+
+    /* Get hold of current DAC position */
+    pin->fnAudioPosition(pin, &pos);
+    /* Compensate for HW FIFO to get to last read buffer position */
+    pos += pin->hwLatency;
+    /* Wrap it */
+    pos %= pRender->hostBufferSize;
+    /* And align it, not sure its really needed though */
+    pos &= ~(pRender->bytesPerFrame - 1);
+    /* Then realOutBuf will point to "other" half of double buffer */
+    realOutBuf = pos < halfOutputBuffer ? 1U : 0U;
+
+    if (pInfo->priming)
+    {
+        realOutBuf = pInfo->renderHead & 0x1;
+    }
+    ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
+    ioPacket->startByte = realOutBuf * halfOutputBuffer;
+    ioPacket->lengthBytes = halfOutputBuffer;
+
+    PA_HP_TRACE((pInfo->stream->hLog, "Render event (WaveRT) : idx=%u head=%u (pos = %4.1lf%%)", realOutBuf, pInfo->renderHead, (pos * 100.0 / pRender->hostBufferSize) ));
+
+    ++pInfo->renderHead;
+    --pInfo->pending;
+    return paNoError;
+}
+
+static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    unsigned long pos;
+    unsigned realOutBuf;
+    unsigned bytesToWrite;
+
+    PaWinWdmIOInfo* pRender = &pInfo->stream->render;
+    const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;
+    PaWinWdmPin* pin = pInfo->stream->render.pPin;
+    PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];
+
+    /* Get hold of current DAC position */
+    pin->fnAudioPosition(pin, &pos);
+    /* Compensate for HW FIFO to get to last read buffer position */
+    pos += pin->hwLatency;
+    /* Wrap it */
+    pos %= pRender->hostBufferSize;
+    /* And align it, not sure its really needed though */
+    pos &= ~(pRender->bytesPerFrame - 1);
+
+    if (pInfo->priming)
+    {
+        realOutBuf = pInfo->renderHead & 0x1;
+        ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
+        ioPacket->startByte = realOutBuf * halfOutputBuffer;
+        ioPacket->lengthBytes = halfOutputBuffer;
+        ++pInfo->renderHead;
+        --pInfo->pending;
+    }
+    else
+    {
+        bytesToWrite = (pRender->hostBufferSize + pos - pRender->lastPosition) % pRender->hostBufferSize;
+        ++pRender->pollCntr;
+        if (bytesToWrite >= halfOutputBuffer)
+        {
+            realOutBuf = (pos < halfOutputBuffer) ? 1U : 0U;
+            ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
+            pRender->lastPosition = realOutBuf ? 0U : halfOutputBuffer;
+            ioPacket->startByte = realOutBuf * halfOutputBuffer;
+            ioPacket->lengthBytes = halfOutputBuffer;
+            ++pInfo->renderHead;
+            --pInfo->pending;
+            PA_HP_TRACE((pInfo->stream->hLog, "Render event (WaveRTPolled) : idx=%u head=%u (pos = %4.1lf%%, cnt=%u)", realOutBuf, pInfo->renderHead, (pos * 100.0 / pRender->hostBufferSize), pRender->pollCntr));
+            pRender->pollCntr = 0;
+        }
+    }
+    return paNoError;
+}
+
+static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    PaWinWdmPin* pin = pInfo->stream->render.pPin;
+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
+    /* Call barrier (if needed) */
+    pin->fnMemBarrier();
+    PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRT) : submit=%u", pInfo->renderTail));
+    ++pInfo->pending;
+    if (pInfo->priming)
+    {
+        --pInfo->priming;
+        if (pInfo->priming)
+        {
+            PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));
+            SetEvent(pInfo->stream->render.events[0]);
+        }
+    }
+    return paNoError;
+}
+
+static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
+{
+    PaWinWdmPin* pin = pInfo->stream->render.pPin;
+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
+    /* Call barrier (if needed) */
+    pin->fnMemBarrier();
+    PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRTPolled) : submit=%u", pInfo->renderTail));
+    ++pInfo->pending;
+    if (pInfo->priming)
+    {
+        --pInfo->priming;
+        if (pInfo->priming)
+        {
+            PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));
+            SetEvent(pInfo->stream->render.events[0]);
+        }
+    }
+    return paNoError;
+}
diff --git a/portaudio/src/hostapi/wmme/pa_win_wmme.c b/portaudio/src/hostapi/wmme/pa_win_wmme.c
new file mode 100644 (file)
index 0000000..422c867
--- /dev/null
@@ -0,0 +1,4055 @@
+/*
+ * $Id$
+ * pa_win_wmme.c
+ * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)       
+ *                                                                                         
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Authors: Ross Bencina and Phil Burk
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/* Modification History:
+ PLB = Phil Burk
+ JM = Julien Maillard
+ RDB = Ross Bencina
+ PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer)
+ PLB20010413 - check for excessive numbers of channels
+ PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC
+               including conditional inclusion of memory.h,
+               and explicit typecasting on memory allocation
+ PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory
+ PLB20010816 - pass process instead of thread to SetPriorityClass()
+ PLB20010927 - use number of frames instead of real-time for CPULoad calculation.
+ JM20020118 - prevent hung thread when buffers underflow.
+ PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount
+ RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init
+ RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices
+               refactoring, renaming and fixed a few edge case bugs
+ RDB20020531 - converted to V19 framework
+ ** NOTE  maintanance history is now stored in CVS **
+*/
+
+/** @file
+    @ingroup hostapi_src
+
+    @brief Win32 host API implementation for the Windows MultiMedia Extensions (WMME) audio API.
+*/
+
+/*
+    How it works:
+
+    For both callback and blocking read/write streams we open the MME devices
+    in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever
+    it has finished with a buffer (either filled it for input, or played it
+    for output). Where necessary, we block waiting for Event objects using
+    WaitMultipleObjects().
+
+    When implementing a PA callback stream, we set up a high priority thread
+    which waits on the MME buffer Events and drains/fills the buffers when
+    they are ready.
+
+    When implementing a PA blocking read/write stream, we simply wait on these
+    Events (when necessary) inside the ReadStream() and WriteStream() functions.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <math.h>
+#include <windows.h>
+#include <mmsystem.h>
+#ifndef UNDER_CE
+#include <process.h>
+#endif
+#include <assert.h>
+/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */
+#ifndef __MWERKS__
+#include <malloc.h>
+#include <memory.h>
+#endif /* __MWERKS__ */
+
+#include "portaudio.h"
+#include "pa_trace.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_debugprint.h"
+
+#include "pa_win_wmme.h"
+#include "pa_win_waveformat.h"
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+#include "pa_win_wdmks_utils.h"
+#ifndef DRV_QUERYDEVICEINTERFACE
+#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)
+#endif
+#ifndef DRV_QUERYDEVICEINTERFACESIZE
+#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
+#endif
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+/* use CreateThread for CYGWIN, _beginthreadex for all others */
+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
+#define CREATE_THREAD (HANDLE)_beginthreadex( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
+#define PA_THREAD_FUNC static unsigned WINAPI
+#define PA_THREAD_ID unsigned
+#else
+#define CREATE_THREAD CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
+#define PA_THREAD_FUNC static DWORD WINAPI
+#define PA_THREAD_ID DWORD
+#endif
+#if (defined(_WIN32_WCE))
+#pragma comment(lib, "Coredll.lib")
+#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment(lib, "winmm.lib")
+#endif
+
+/*
+ provided in newer platform sdks
+ */
+#ifndef DWORD_PTR
+    #if defined(_WIN64)
+        #define DWORD_PTR unsigned __int64
+    #else
+        #define DWORD_PTR unsigned long
+    #endif
+#endif
+
+/************************************************* Constants ********/
+
+#define PA_MME_USE_HIGH_DEFAULT_LATENCY_    (0)  /* For debugging glitches. */
+
+#if PA_MME_USE_HIGH_DEFAULT_LATENCY_
+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_                             (0.4)
+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                       (4)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_               (4)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_               (4)
+ #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_       (16)
+ #define PA_MME_MAX_HOST_BUFFER_SECS_                                          (0.3)       /* Do not exceed unless user buffer exceeds */
+ #define PA_MME_MAX_HOST_BUFFER_BYTES_                                         (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
+#else
+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_                             (0.2)
+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                       (2)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_               (3)         /* always use at least 3 input buffers for full duplex */
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_               (2)
+ #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_       (16)
+ #define PA_MME_MAX_HOST_BUFFER_SECS_                                          (0.1)       /* Do not exceed unless user buffer exceeds */
+ #define PA_MME_MAX_HOST_BUFFER_BYTES_                                         (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
+#endif
+
+/* Use higher latency for NT because it is even worse at real-time
+   operation than Win9x.
+*/
+#define PA_MME_WIN_NT_DEFAULT_LATENCY_                              (0.4)
+
+/* Default low latency for WDM based systems. This is based on a rough
+   survey of workable latency settings using patest_wmme_find_best_latency_params.c.
+   See pdf attached to ticket 185 for a graph of the survey results:
+   http://www.portaudio.com/trac/ticket/185
+   
+   Workable latencies varied between 40ms and ~80ms on different systems (different
+   combinations of hardware, 32 and 64 bit, WinXP, Vista and Win7. We didn't
+   get enough Vista results to know if Vista has systemically worse latency.
+   For now we choose a safe value across all Windows versions here.
+*/
+#define PA_MME_WIN_WDM_DEFAULT_LATENCY_                             (0.090)
+
+
+/* When client suggestedLatency could result in many host buffers, we aim to have around 8, 
+   based off Windows documentation that suggests that the kmixer uses 8 buffers. This choice
+   is somewhat arbitrary here, since we havn't observed significant stability degredation 
+   with using either more, or less buffers.     
+*/
+#define PA_MME_TARGET_HOST_BUFFER_COUNT_    8
+
+#define PA_MME_MIN_TIMEOUT_MSEC_        (1000)
+
+static const char constInputMapperSuffix_[] = " - Input";
+static const char constOutputMapperSuffix_[] = " - Output";
+
+/********************************************************************/
+
+/* Copy null-terminated TCHAR string to explicit char string using UTF8 encoding */
+static char *CopyTCharStringToUtf8CString(char *destination, size_t destLengthBytes, const TCHAR *source)
+{
+#if !defined(_UNICODE) && !defined(UNICODE)
+    return strcpy(destination, source);
+#else
+    /* The cbMultiByte parameter ["destLengthBytes" below] is:
+    """
+    Size, in bytes, of the buffer indicated by lpMultiByteStr ["destination" below]. 
+    If this parameter is set to 0, the function returns the required buffer 
+    size for lpMultiByteStr and makes no use of the output parameter itself.
+    """
+    Source: WideCharToMultiByte at MSDN:
+    http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx
+    */
+    int intDestLengthBytes; /* cbMultiByte */
+    /* intDestLengthBytes is an int, destLengthBytes is a size_t. Ensure that we don't overflow
+    intDestLengthBytes by only using at most INT_MAX bytes of destination buffer.
+    */
+    if (destLengthBytes < INT_MAX)
+    {
+#pragma warning (disable : 4267) /* "conversion from 'size_t' to 'int', possible loss of data" */
+        intDestLengthBytes = (int)destLengthBytes; /* destLengthBytes is guaranteed < INT_MAX here */
+#pragma warning (default : 4267)
+    }
+    else
+    {
+        intDestLengthBytes = INT_MAX;
+    }
+    
+    if (WideCharToMultiByte(CP_UTF8, 0, source, -1, destination, /*cbMultiByte=*/intDestLengthBytes, NULL, NULL) == 0)
+        return NULL;
+    return destination;
+#endif
+}
+
+/* returns required length (in bytes) of destination buffer when 
+   converting TCHAR string to UTF8 bytes, not including the terminating null. */
+static size_t TCharStringLen(const TCHAR *str)
+{
+#if !defined(_UNICODE) && !defined(UNICODE)
+    return strlen(str);
+#else
+    return WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);      
+#endif
+}
+
+/********************************************************************/
+
+typedef struct PaWinMmeStream PaWinMmeStream;     /* forward declaration */
+
+/* prototypes for functions declared in this file */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** stream,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+
+/* macros for setting last host error information */
+
+#ifdef UNICODE
+
+#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
+    {                                                                   \
+        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                     \
+        char mmeErrorText[ MAXERRORLENGTH ];                            \
+        waveInGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH );   \
+        WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
+            mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL );  \
+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \
+    }
+
+#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
+    {                                                                   \
+        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                     \
+        char mmeErrorText[ MAXERRORLENGTH ];                            \
+        waveOutGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH );  \
+        WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
+            mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL );  \
+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \
+    }
+    
+#else /* !UNICODE */
+
+#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
+    {                                                                   \
+        char mmeErrorText[ MAXERRORLENGTH ];                            \
+        waveInGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH );   \
+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \
+    }
+
+#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
+    {                                                                   \
+        char mmeErrorText[ MAXERRORLENGTH ];                            \
+        waveOutGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH );  \
+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \
+    }
+
+#endif /* UNICODE */
+
+
+static void PaMme_SetLastSystemError( DWORD errorCode )
+{
+    char *lpMsgBuf;
+    FormatMessage(
+        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+        NULL,
+        errorCode,
+        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+        (LPTSTR) &lpMsgBuf,
+        0,
+        NULL
+    );
+    PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf );
+    LocalFree( lpMsgBuf );
+}
+
+#define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \
+    PaMme_SetLastSystemError( errorCode )
+
+
+/* PaError returning wrappers for some commonly used win32 functions
+    note that we allow passing a null ptr to have no effect.
+*/
+
+static PaError CreateEventWithPaError( HANDLE *handle,
+        LPSECURITY_ATTRIBUTES lpEventAttributes,
+        BOOL bManualReset,
+        BOOL bInitialState,
+        LPCTSTR lpName )
+{
+    PaError result = paNoError;
+
+    *handle = NULL;
+    
+    *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName );
+    if( *handle == NULL )
+    {
+        result = paUnanticipatedHostError;
+        PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+    }
+
+    return result;
+}
+
+
+static PaError ResetEventWithPaError( HANDLE handle )
+{
+    PaError result = paNoError;
+
+    if( handle )
+    {
+        if( ResetEvent( handle ) == 0 )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+        }
+    }
+
+    return result;
+}
+
+
+static PaError CloseHandleWithPaError( HANDLE handle )
+{
+    PaError result = paNoError;
+    
+    if( handle )
+    {
+        if( CloseHandle( handle ) == 0 )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+        }
+    }
+    
+    return result;
+}
+
+
+/* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+    
+    int inputDeviceCount, outputDeviceCount;
+
+    /** winMmeDeviceIds is an array of WinMme device ids.
+        fields in the range [0, inputDeviceCount) are input device ids,
+        and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output
+        device ids.
+     */ 
+    UINT *winMmeDeviceIds;
+}
+PaWinMmeHostApiRepresentation;
+
+
+typedef struct
+{
+    PaDeviceInfo inheritedDeviceInfo;
+    DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */
+    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
+    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
+}
+PaWinMmeDeviceInfo;
+
+
+/*************************************************************************
+ * Returns recommended device ID.
+ * On the PC, the recommended device can be specified by the user by
+ * setting an environment variable. For example, to use device #1.
+ *
+ *    set PA_RECOMMENDED_OUTPUT_DEVICE=1
+ *
+ * The user should first determine the available device ID by using
+ * the supplied application "pa_devs".
+ */
+#define PA_ENV_BUF_SIZE_  (32)
+#define PA_REC_IN_DEV_ENV_NAME_  ("PA_RECOMMENDED_INPUT_DEVICE")
+#define PA_REC_OUT_DEV_ENV_NAME_  ("PA_RECOMMENDED_OUTPUT_DEVICE")
+static PaDeviceIndex GetEnvDefaultDeviceID( char *envName )
+{
+    PaDeviceIndex recommendedIndex = paNoDevice;
+    DWORD   hresult;
+    char    envbuf[PA_ENV_BUF_SIZE_];
+
+#ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */
+
+    /* Let user determine default device by setting environment variable. */
+    hresult = GetEnvironmentVariableA( envName, envbuf, PA_ENV_BUF_SIZE_ );
+    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) )
+    {
+        recommendedIndex = atoi( envbuf );
+    }
+#endif
+
+    return recommendedIndex;
+}
+
+
+static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi )
+{
+    PaDeviceIndex device;
+
+    /* input */
+    device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ );
+    if( device != paNoDevice &&
+            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
+            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 )
+    {
+        hostApi->inheritedHostApiRep.info.defaultInputDevice = device;
+    }
+
+    /* output */
+    device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ );
+    if( device != paNoDevice &&
+            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
+            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 )
+    {
+        hostApi->inheritedHostApiRep.info.defaultOutputDevice = device;
+    }
+}
+
+
+/** Convert external PA ID to a windows multimedia device ID
+*/
+static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device )
+{
+    assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount );
+
+    return hostApi->winMmeDeviceIds[ device ];
+}
+
+
+static int SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( PaSampleFormat sampleFormat, unsigned long winMmeSpecificFlags )
+{
+    int waveFormatTag = 0;
+
+    if( winMmeSpecificFlags & paWinMmeWaveFormatDolbyAc3Spdif )
+        waveFormatTag = PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF;
+    else if( winMmeSpecificFlags & paWinMmeWaveFormatWmaSpdif )
+        waveFormatTag = PAWIN_WAVE_FORMAT_WMA_SPDIF;
+    else
+        waveFormatTag = PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat );
+
+    return waveFormatTag;
+}
+
+
+static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
+{
+    MMRESULT mmresult;
+    
+    switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
+    {
+        case MMSYSERR_NOERROR:
+            return paNoError;
+        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
+            return paDeviceUnavailable;
+        case MMSYSERR_NODRIVER:            /* No device driver is present. */
+            return paDeviceUnavailable;
+        case MMSYSERR_NOMEM:       /* Unable to allocate or lock memory. */
+            return paInsufficientMemory;
+        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
+            return paSampleFormatNotSupported;
+                    
+        case MMSYSERR_BADDEVICEID:     /* Specified device identifier is out of range. */
+            /* falls through */
+        default:
+            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+            return paUnanticipatedHostError;
+    }
+}
+
+
+static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
+{
+    MMRESULT mmresult;
+    
+    switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
+    {
+        case MMSYSERR_NOERROR:
+            return paNoError;
+        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
+            return paDeviceUnavailable;
+        case MMSYSERR_NODRIVER:            /* No device driver is present. */
+            return paDeviceUnavailable;
+        case MMSYSERR_NOMEM:       /* Unable to allocate or lock memory. */
+            return paInsufficientMemory;
+        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
+            return paSampleFormatNotSupported;
+                    
+        case MMSYSERR_BADDEVICEID:     /* Specified device identifier is out of range. */
+            /* falls through */
+        default:
+            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+            return paUnanticipatedHostError;
+    }
+}
+
+
+static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,
+        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),
+        int winMmeDeviceId, int channels, double sampleRate, unsigned long winMmeSpecificFlags )
+{
+    PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;
+    PaWinWaveFormat waveFormat;
+    PaSampleFormat sampleFormat;
+    int waveFormatTag;
+    
+    /* @todo at the moment we only query with 16 bit sample format and directout speaker config*/
+
+    sampleFormat = paInt16;
+    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );
+
+    if( waveFormatTag == PaWin_SampleFormatToLinearWaveFormatTag( paInt16 ) ){
+    
+        /* attempt bypass querying the device for linear formats */
+
+        if( sampleRate == 11025.0
+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){
+
+            return paNoError;
+        }
+
+        if( sampleRate == 22050.0
+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){
+
+            return paNoError;
+        }
+
+        if( sampleRate == 44100.0
+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){
+
+            return paNoError;
+        }
+    }
+
+
+    /* first, attempt to query the device using WAVEFORMATEXTENSIBLE, 
+       if this fails we fall back to WAVEFORMATEX */
+
+    PaWin_InitializeWaveFormatExtensible( &waveFormat, channels, sampleFormat, waveFormatTag,
+            sampleRate, PAWIN_SPEAKER_DIRECTOUT );
+
+    if( waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat ) == paNoError )
+        return paNoError;
+
+    PaWin_InitializeWaveFormatEx( &waveFormat, channels, sampleFormat, waveFormatTag, sampleRate );
+
+    return waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat );
+}
+
+
+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */
+static double defaultSampleRateSearchOrder_[] =
+    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
+        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
+
+static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId,
+        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels )
+{
+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+    int i;
+    
+    deviceInfo->defaultSampleRate = 0.;
+
+    for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
+    {
+        double sampleRate = defaultSampleRateSearchOrder_[ i ]; 
+        PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate, 0 );
+        if( paerror == paNoError )
+        {
+            deviceInfo->defaultSampleRate = sampleRate;
+            break;
+        }
+    }
+}
+
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+static int QueryWaveInKSFilterMaxChannels( int waveInDeviceId, int *maxChannels )
+{
+    void *devicePath;
+    DWORD devicePathSize;
+    int result = 0;
+
+    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
+            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
+        return 0;
+
+    devicePath = PaUtil_AllocateMemory( devicePathSize );
+    if( !devicePath )
+        return 0;
+
+    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
+    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACE,
+            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
+    {
+        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 1  );
+        if( count > 0 )
+        {
+            *maxChannels = count;
+            result = 1;
+        }
+    }
+
+    PaUtil_FreeMemory( devicePath );
+
+    return result;
+}
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+
+static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
+        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )
+{
+    PaError result = paNoError;
+    char *deviceName; /* non-const ptr */
+    MMRESULT mmresult;
+    WAVEINCAPS wic;
+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+    size_t len;
+    
+    *success = 0;
+
+    mmresult = waveInGetDevCaps( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPS ) );
+    if( mmresult == MMSYSERR_NOMEM )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    else if( mmresult != MMSYSERR_NOERROR )
+    {
+        /* instead of returning paUnanticipatedHostError we return
+            paNoError, but leave success set as 0. This allows
+            Pa_Initialize to just ignore this device, without failing
+            the entire initialisation process.
+        */
+        return paNoError;
+    }           
+
+    /* NOTE: the WAVEOUTCAPS.szPname is a null-terminated array of 32 characters,
+        so we are limited to displaying only the first 31 characters of the device name. */
+    if( winMmeInputDeviceId == WAVE_MAPPER )
+    {
+        len = TCharStringLen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_);
+        /* Append I/O suffix to WAVE_MAPPER device. */
+        deviceName = (char*)PaUtil_GroupAllocateMemory(
+                    winMmeHostApi->allocations,
+                    (long)len );
+        if( !deviceName )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        CopyTCharStringToUtf8CString( deviceName, len, wic.szPname );
+        strcat( deviceName, constInputMapperSuffix_ );
+    }
+    else
+    {
+        len = TCharStringLen( wic.szPname ) + 1;
+        deviceName = (char*)PaUtil_GroupAllocateMemory(
+                    winMmeHostApi->allocations,
+                    (long)len );
+        if( !deviceName )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        CopyTCharStringToUtf8CString( deviceName, len, wic.szPname  );
+    }
+    deviceInfo->name = deviceName;
+
+    if( wic.wChannels == 0xFFFF || wic.wChannels < 1 || wic.wChannels > 255 ){
+        /* For Windows versions using WDM (possibly Windows 98 ME and later)
+         * the kernel mixer sits between the application and the driver. As a result,
+         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
+         * When this happens we assume the device is stereo and set a flag
+         * so that other channel counts can be tried with OpenStream -- i.e. when
+         * device*ChannelCountIsKnown is false, OpenStream will try whatever
+         * channel count you supply.
+         * see also InitializeOutputDeviceInfo() below.
+     */
+
+        PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", wic.wChannels ));
+        deviceInfo->maxInputChannels = 2;
+        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 0;
+    }else{
+        deviceInfo->maxInputChannels = wic.wChannels;
+        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
+    }
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+    winMmeDeviceInfo->deviceInputChannelCountIsKnown = 
+            QueryWaveInKSFilterMaxChannels( winMmeInputDeviceId, &deviceInfo->maxInputChannels );
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+    winMmeDeviceInfo->dwFormats = wic.dwFormats;
+
+    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,
+            QueryInputWaveFormatEx, deviceInfo->maxInputChannels );
+
+    *success = 1;
+    
+error:
+    return result;
+}
+
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+static int QueryWaveOutKSFilterMaxChannels( int waveOutDeviceId, int *maxChannels )
+{
+    void *devicePath;
+    DWORD devicePathSize;
+    int result = 0;
+
+    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
+            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
+        return 0;
+
+    devicePath = PaUtil_AllocateMemory( devicePathSize );
+    if( !devicePath )
+        return 0;
+
+    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
+    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACE,
+            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
+    {
+        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 0  );
+        if( count > 0 )
+        {
+            *maxChannels = count;
+            result = 1;
+        }
+    }
+
+    PaUtil_FreeMemory( devicePath );
+
+    return result;
+}
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+
+static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
+        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )
+{
+    PaError result = paNoError;
+    char *deviceName; /* non-const ptr */
+    MMRESULT mmresult;
+    WAVEOUTCAPS woc;
+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+    size_t len;
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+    int wdmksDeviceOutputChannelCountIsKnown;
+#endif
+
+    *success = 0;
+
+    mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) );
+    if( mmresult == MMSYSERR_NOMEM )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    else if( mmresult != MMSYSERR_NOERROR )
+    {
+        /* instead of returning paUnanticipatedHostError we return
+            paNoError, but leave success set as 0. This allows
+            Pa_Initialize to just ignore this device, without failing
+            the entire initialisation process.
+        */
+        return paNoError;
+    }
+
+    /* NOTE: the WAVEOUTCAPS.szPname is a null-terminated array of 32 characters,
+        so we are limited to displaying only the first 31 characters of the device name. */
+    if( winMmeOutputDeviceId == WAVE_MAPPER )
+    {
+        /* Append I/O suffix to WAVE_MAPPER device. */
+        len = TCharStringLen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_);
+        deviceName = (char*)PaUtil_GroupAllocateMemory(
+                    winMmeHostApi->allocations, 
+                    (long)len );
+        if( !deviceName )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        CopyTCharStringToUtf8CString( deviceName, len, woc.szPname );
+        strcat( deviceName, constOutputMapperSuffix_ );
+    }
+    else
+    {
+        len = TCharStringLen( woc.szPname ) + 1;
+        deviceName = (char*)PaUtil_GroupAllocateMemory(
+                    winMmeHostApi->allocations, 
+                    (long)len );
+        if( !deviceName )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+        CopyTCharStringToUtf8CString( deviceName, len, woc.szPname );
+    }
+    deviceInfo->name = deviceName;
+
+    if( woc.wChannels == 0xFFFF || woc.wChannels < 1 || woc.wChannels > 255 ){
+        /* For Windows versions using WDM (possibly Windows 98 ME and later)
+         * the kernel mixer sits between the application and the driver. As a result,
+         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
+         * When this happens we assume the device is stereo and set a flag
+         * so that other channel counts can be tried with OpenStream -- i.e. when
+         * device*ChannelCountIsKnown is false, OpenStream will try whatever
+         * channel count you supply.
+         * see also InitializeInputDeviceInfo() above.
+     */
+
+        PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", woc.wChannels ));
+        deviceInfo->maxOutputChannels = 2;
+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 0;
+    }else{
+        deviceInfo->maxOutputChannels = woc.wChannels;
+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+    }
+
+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
+    wdmksDeviceOutputChannelCountIsKnown = QueryWaveOutKSFilterMaxChannels( 
+            winMmeOutputDeviceId, &deviceInfo->maxOutputChannels );
+    if( wdmksDeviceOutputChannelCountIsKnown && !winMmeDeviceInfo->deviceOutputChannelCountIsKnown )
+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
+
+    winMmeDeviceInfo->dwFormats = woc.dwFormats;
+
+    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,
+            QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels );
+
+    *success = 1;
+    
+error:
+    return result;
+}
+
+
+static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency )
+{
+/*
+NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
+versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
+Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
+is is faster, for now we just disable the deprecation warning.
+See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
+See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
+*/
+#pragma warning (disable : 4996) /* use of GetVersionEx */
+
+    OSVERSIONINFO osvi;
+    osvi.dwOSVersionInfoSize = sizeof( osvi );
+    GetVersionEx( &osvi );
+
+    /* Check for NT */
+    if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
+    {
+        *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_;
+    }
+    else if(osvi.dwMajorVersion >= 5)
+    {
+        *defaultLowLatency  = PA_MME_WIN_WDM_DEFAULT_LATENCY_;
+    }
+    else
+    {
+        *defaultLowLatency  = PA_MME_WIN_9X_DEFAULT_LATENCY_;
+    }     
+
+    *defaultHighLatency = *defaultLowLatency * 2;
+
+#pragma warning (default : 4996)
+}
+
+
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    int i;
+    PaWinMmeHostApiRepresentation *winMmeHostApi;
+    int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount;
+    PaWinMmeDeviceInfo *deviceInfoArray;
+    int deviceInfoInitializationSucceeded;
+    PaTime defaultLowLatency, defaultHighLatency;
+    DWORD waveInPreferredDevice, waveOutPreferredDevice;
+    DWORD preferredDeviceStatusFlags;
+
+    winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );
+    if( !winMmeHostApi )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    winMmeHostApi->allocations = PaUtil_CreateAllocationGroup();
+    if( !winMmeHostApi->allocations )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi = &winMmeHostApi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paMME;
+    (*hostApi)->info.name = "MME";
+
+    
+    /* initialise device counts and default devices under the assumption that
+        there are no devices. These values are incremented below if and when
+        devices are successfully initialized.
+    */
+    (*hostApi)->info.deviceCount = 0;
+    (*hostApi)->info.defaultInputDevice = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+    winMmeHostApi->inputDeviceCount = 0;
+    winMmeHostApi->outputDeviceCount = 0;
+
+#if !defined(DRVM_MAPPER_PREFERRED_GET)
+/* DRVM_MAPPER_PREFERRED_GET is defined in mmddk.h but we avoid a dependency on the DDK by defining it here */
+#define DRVM_MAPPER_PREFERRED_GET    (0x2000+21)
+#endif
+
+    /* the following calls assume that if wave*Message fails the preferred device parameter won't be modified */
+    preferredDeviceStatusFlags = 0;
+    waveInPreferredDevice = -1;
+    waveInMessage( (HWAVEIN)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveInPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );
+
+    preferredDeviceStatusFlags = 0;
+    waveOutPreferredDevice = -1;
+    waveOutMessage( (HWAVEOUT)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveOutPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );
+
+    maximumPossibleDeviceCount = 0;
+
+    inputDeviceCount = waveInGetNumDevs();
+    if( inputDeviceCount > 0 )
+        maximumPossibleDeviceCount += inputDeviceCount + 1;    /* assume there is a WAVE_MAPPER */
+
+    outputDeviceCount = waveOutGetNumDevs();
+    if( outputDeviceCount > 0 )
+        maximumPossibleDeviceCount += outputDeviceCount + 1;   /* assume there is a WAVE_MAPPER */
+
+
+    if( maximumPossibleDeviceCount > 0 ){
+
+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+                winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount );
+        if( !(*hostApi)->deviceInfos )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory(
+                winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount );
+        if( !deviceInfoArray )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory(
+                winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount );
+        if( !winMmeHostApi->winMmeDeviceIds )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency );
+
+        if( inputDeviceCount > 0 ){
+            /* -1 is the WAVE_MAPPER */
+            for( i = -1; i < inputDeviceCount; ++i ){
+                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
+                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
+                deviceInfo->structVersion = 2;
+                deviceInfo->hostApi = hostApiIndex;
+
+                deviceInfo->maxInputChannels = 0;
+                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
+                deviceInfo->maxOutputChannels = 0;
+                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+
+                deviceInfo->defaultLowInputLatency = defaultLowLatency;
+                deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+                deviceInfo->defaultHighInputLatency = defaultHighLatency;
+                deviceInfo->defaultHighOutputLatency = defaultHighLatency;
+
+                result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
+                        winMmeDeviceId, &deviceInfoInitializationSucceeded );
+                if( result != paNoError )
+                    goto error;
+
+                if( deviceInfoInitializationSucceeded ){
+                    if( (*hostApi)->info.defaultInputDevice == paNoDevice ){
+                        /* if there is currently no default device, use the first one available */
+                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+                    
+                    }else if( winMmeDeviceId == waveInPreferredDevice ){
+                        /* set the default device to the system preferred device */
+                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+                    }
+
+                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
+                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+
+                    winMmeHostApi->inputDeviceCount++;
+                    (*hostApi)->info.deviceCount++;
+                }
+            }
+        }
+
+        if( outputDeviceCount > 0 ){
+            /* -1 is the WAVE_MAPPER */
+            for( i = -1; i < outputDeviceCount; ++i ){
+                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
+                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
+                deviceInfo->structVersion = 2;
+                deviceInfo->hostApi = hostApiIndex;
+
+                deviceInfo->maxInputChannels = 0;
+                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
+                deviceInfo->maxOutputChannels = 0;
+                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
+
+                deviceInfo->defaultLowInputLatency = defaultLowLatency;
+                deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+                deviceInfo->defaultHighInputLatency = defaultHighLatency;
+                deviceInfo->defaultHighOutputLatency = defaultHighLatency; 
+
+                result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
+                        winMmeDeviceId, &deviceInfoInitializationSucceeded );
+                if( result != paNoError )
+                    goto error;
+
+                if( deviceInfoInitializationSucceeded ){
+                    if( (*hostApi)->info.defaultOutputDevice == paNoDevice ){
+                        /* if there is currently no default device, use the first one available */
+                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+
+                    }else if( winMmeDeviceId == waveOutPreferredDevice ){
+                        /* set the default device to the system preferred device */
+                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+                    }
+
+                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
+                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+
+                    winMmeHostApi->outputDeviceCount++;
+                    (*hostApi)->info.deviceCount++;
+                }
+            }
+        }
+    }
+    
+    InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+    return result;
+
+error:
+    if( winMmeHostApi )
+    {
+        if( winMmeHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
+        }
+        
+        PaUtil_FreeMemory( winMmeHostApi );
+    }
+
+    return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+
+    if( winMmeHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( winMmeHostApi );
+}
+
+
+static PaError IsInputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
+{
+    PaError result = paNoError;
+
+    if( channelCount > 0
+            && deviceInfo->deviceInputChannelCountIsKnown
+            && channelCount > deviceInfo->inheritedDeviceInfo.maxInputChannels ){
+
+        result = paInvalidChannelCount; 
+    }
+
+    return result;
+}
+
+static PaError IsOutputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
+{
+    PaError result = paNoError;
+
+    if( channelCount > 0
+            && deviceInfo->deviceOutputChannelCountIsKnown
+            && channelCount > deviceInfo->inheritedDeviceInfo.maxOutputChannels ){
+
+        result = paInvalidChannelCount; 
+    }
+
+    return result;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
+    int inputChannelCount, outputChannelCount;
+    int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
+    UINT winMmeInputDeviceId, winMmeOutputDeviceId;
+    unsigned int i;
+    PaError paerror;
+
+    /* The calls to QueryFormatSupported below are intended to detect invalid
+        sample rates. If we assume that the channel count and format are OK,
+        then the only thing that could fail is the sample rate. This isn't
+        strictly true, but I can't think of a better way to test that the
+        sample rate is valid.
+    */  
+    
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        inputStreamInfo = inputParameters->hostApiSpecificStreamInfo;
+        
+        /* all standard sample formats are supported by the buffer adapter,
+             this implementation doesn't support any custom sample formats */
+        if( inputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+
+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification
+                && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+        {
+            inputMultipleDeviceChannelCount = 0;
+            for( i=0; i< inputStreamInfo->deviceCount; ++i )
+            {
+                inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount;
+                    
+                inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];
+
+                /* check that input device can support inputChannelCount */
+                if( inputStreamInfo->devices[i].channelCount < 1 )
+                    return paInvalidChannelCount;
+
+                paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, 
+                        inputStreamInfo->devices[i].channelCount );
+                if( paerror != paNoError )
+                    return paerror;
+
+                /* test for valid sample rate, see comment above */
+                winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );
+                paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, 
+                        winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate, 
+                        ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
+                if( paerror != paNoError )
+                    return paInvalidSampleRate;
+            }
+                
+            if( inputMultipleDeviceChannelCount != inputChannelCount )
+                return paIncompatibleHostApiSpecificStreamInfo;                  
+        }
+        else
+        {
+            if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */
+
+            inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];
+
+            /* check that input device can support inputChannelCount */
+            paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, inputChannelCount );
+            if( paerror != paNoError )
+                return paerror;
+
+            /* test for valid sample rate, see comment above */
+            winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );
+            paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, 
+                    winMmeInputDeviceId, inputChannelCount, sampleRate,
+                    ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
+            if( paerror != paNoError )
+                return paInvalidSampleRate;
+        }
+    }
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        outputStreamInfo = outputParameters->hostApiSpecificStreamInfo;
+
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if( outputSampleFormat & paCustomFormat )
+            return paSampleFormatNotSupported;
+
+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification
+                && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+        {
+            outputMultipleDeviceChannelCount = 0;
+            for( i=0; i< outputStreamInfo->deviceCount; ++i )
+            {
+                outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount;
+                    
+                outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];
+
+                /* check that output device can support outputChannelCount */
+                if( outputStreamInfo->devices[i].channelCount < 1 )
+                    return paInvalidChannelCount;
+
+                paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, 
+                        outputStreamInfo->devices[i].channelCount );
+                if( paerror != paNoError )
+                    return paerror;
+
+                /* test for valid sample rate, see comment above */
+                winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );
+                paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, 
+                        winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate,
+                        ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
+                if( paerror != paNoError )
+                    return paInvalidSampleRate;
+            }
+                
+            if( outputMultipleDeviceChannelCount != outputChannelCount )
+                return paIncompatibleHostApiSpecificStreamInfo;            
+        }
+        else
+        {
+            if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */
+
+            outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];
+
+            /* check that output device can support outputChannelCount */
+            paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, outputChannelCount );
+            if( paerror != paNoError )
+                return paerror;
+
+            /* test for valid sample rate, see comment above */
+            winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );
+            paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, 
+                    winMmeOutputDeviceId, outputChannelCount, sampleRate,
+                    ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
+            if( paerror != paNoError )
+                return paInvalidSampleRate;
+        }
+    }
+    
+    /*
+            - if a full duplex stream is requested, check that the combination
+                of input and output parameters is supported
+
+            - check that the device supports sampleRate
+
+            for mme all we can do is test that the input and output devices
+            support the requested sample rate and number of channels. we
+            cannot test for full duplex compatibility.
+    */                                             
+
+    return paFormatIsSupported;
+}
+
+
+static unsigned long ComputeHostBufferCountForFixedBufferSizeFrames(
+        unsigned long suggestedLatencyFrames,
+        unsigned long hostBufferSizeFrames,
+        unsigned long minimumBufferCount )
+{
+    /* Calculate the number of buffers of length hostFramesPerBuffer 
+       that fit in suggestedLatencyFrames, rounding up to the next integer.
+
+       The value (hostBufferSizeFrames - 1) below is to ensure the buffer count is rounded up.
+    */
+    unsigned long resultBufferCount = ((suggestedLatencyFrames + (hostBufferSizeFrames - 1)) / hostBufferSizeFrames);
+
+    /* We always need one extra buffer for processing while the rest are queued/playing.
+       i.e. latency is framesPerBuffer * (bufferCount - 1)
+    */
+    resultBufferCount += 1;
+
+    if( resultBufferCount < minimumBufferCount ) /* clamp to minimum buffer count */
+        resultBufferCount = minimumBufferCount;
+
+    return resultBufferCount;
+}
+
+
+static unsigned long ComputeHostBufferSizeGivenHardUpperLimit( 
+        unsigned long userFramesPerBuffer,
+        unsigned long absoluteMaximumBufferSizeFrames )
+{
+    static unsigned long primes_[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 
+            29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 0 }; /* zero terminated */
+
+    unsigned long result = userFramesPerBuffer;
+    int i;
+
+    assert( absoluteMaximumBufferSizeFrames > 67 ); /* assume maximum is large and we're only factoring by small primes */
+
+    /* search for the largest integer factor of userFramesPerBuffer less 
+       than or equal to absoluteMaximumBufferSizeFrames */
+
+    /* repeatedly divide by smallest prime factors until a buffer size 
+       smaller than absoluteMaximumBufferSizeFrames is found */
+    while( result > absoluteMaximumBufferSizeFrames ){
+
+        /* search for the smallest prime factor of result */
+        for( i=0; primes_[i] != 0; ++i ) 
+        {
+            unsigned long p = primes_[i];
+            unsigned long divided = result / p;
+            if( divided*p == result )
+            {
+                result = divided;
+                break; /* continue with outer while loop */
+            }
+        }
+        if( primes_[i] == 0 )
+        { /* loop failed to find a prime factor, return an approximate result */
+            unsigned long d = (userFramesPerBuffer + (absoluteMaximumBufferSizeFrames-1))
+                    / absoluteMaximumBufferSizeFrames;
+            return userFramesPerBuffer / d;
+        }
+    }
+
+    return result;
+}
+
+
+static PaError SelectHostBufferSizeFramesAndHostBufferCount(
+        unsigned long suggestedLatencyFrames,
+        unsigned long userFramesPerBuffer,
+        unsigned long minimumBufferCount,
+        unsigned long preferredMaximumBufferSizeFrames, /* try not to exceed this. for example, don't exceed when coalescing buffers */
+        unsigned long absoluteMaximumBufferSizeFrames,  /* never exceed this, a hard limit */
+        unsigned long *hostBufferSizeFrames,
+        unsigned long *hostBufferCount )
+{
+    unsigned long effectiveUserFramesPerBuffer;
+    unsigned long numberOfUserBuffersPerHostBuffer;
+
+
+    if( userFramesPerBuffer == paFramesPerBufferUnspecified ){
+
+        effectiveUserFramesPerBuffer = PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_;
+
+    }else{
+
+        if( userFramesPerBuffer > absoluteMaximumBufferSizeFrames ){
+
+            /* user has requested a user buffer that's larger than absoluteMaximumBufferSizeFrames.
+               try to choose a buffer size that is equal or smaller than absoluteMaximumBufferSizeFrames
+               but is also an integer factor of userFramesPerBuffer, so as to distribute computation evenly.
+               the buffer processor will handle the block adaption between host and user buffer sizes.
+               see http://www.portaudio.com/trac/ticket/189 for discussion.
+            */
+
+            effectiveUserFramesPerBuffer = ComputeHostBufferSizeGivenHardUpperLimit( userFramesPerBuffer, absoluteMaximumBufferSizeFrames );
+            assert( effectiveUserFramesPerBuffer <= absoluteMaximumBufferSizeFrames );
+
+            /* try to ensure that duration of host buffering is at least as 
+                large as duration of user buffer. */
+            if( suggestedLatencyFrames < userFramesPerBuffer )
+                suggestedLatencyFrames = userFramesPerBuffer; 
+
+        }else{
+
+            effectiveUserFramesPerBuffer = userFramesPerBuffer;
+        }
+    }
+                        
+    /* compute a host buffer count based on suggestedLatencyFrames and our granularity */
+
+    *hostBufferSizeFrames = effectiveUserFramesPerBuffer;
+
+    *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
+            suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );
+
+    if( *hostBufferSizeFrames >= userFramesPerBuffer )
+    {
+        /*
+            If there are too many host buffers we would like to coalesce 
+            them by packing an integer number of user buffers into each host buffer.
+            We try to coalesce such that hostBufferCount will lie between 
+            PA_MME_TARGET_HOST_BUFFER_COUNT_ and (PA_MME_TARGET_HOST_BUFFER_COUNT_*2)-1.
+            We limit coalescing to avoid exceeding either absoluteMaximumBufferSizeFrames and
+            preferredMaximumBufferSizeFrames. 
+
+            First, compute a coalescing factor: the number of user buffers per host buffer.
+            The goal is to achieve PA_MME_TARGET_HOST_BUFFER_COUNT_ total buffer count.
+            Since our latency is computed based on (*hostBufferCount - 1) we compute a
+            coalescing factor based on (*hostBufferCount - 1) and (PA_MME_TARGET_HOST_BUFFER_COUNT_-1).
+
+            The + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2) term below is intended to round up.
+        */
+        numberOfUserBuffersPerHostBuffer = ((*hostBufferCount - 1) + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2)) / (PA_MME_TARGET_HOST_BUFFER_COUNT_ - 1);
+        
+        if( numberOfUserBuffersPerHostBuffer > 1 )
+        {
+            unsigned long maxCoalescedBufferSizeFrames = (absoluteMaximumBufferSizeFrames < preferredMaximumBufferSizeFrames) /* minimum of our limits */
+                            ? absoluteMaximumBufferSizeFrames
+                            : preferredMaximumBufferSizeFrames;
+
+            unsigned long maxUserBuffersPerHostBuffer = maxCoalescedBufferSizeFrames / effectiveUserFramesPerBuffer; /* don't coalesce more than this */
+
+            if( numberOfUserBuffersPerHostBuffer > maxUserBuffersPerHostBuffer )
+                numberOfUserBuffersPerHostBuffer = maxUserBuffersPerHostBuffer;
+
+            *hostBufferSizeFrames = effectiveUserFramesPerBuffer * numberOfUserBuffersPerHostBuffer;
+
+            /* recompute hostBufferCount to approximate suggestedLatencyFrames now that hostBufferSizeFrames is larger */
+            *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
+                    suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );
+        }
+    }
+
+    return paNoError;
+}
+
+
+static PaError CalculateMaxHostSampleFrameSizeBytes(
+        int channelCount,
+        PaSampleFormat hostSampleFormat,
+        const PaWinMmeStreamInfo *streamInfo,
+        int *hostSampleFrameSizeBytes )
+{
+    unsigned int i;
+    /* PA WMME streams may aggregate multiple WMME devices. When the stream addresses 
+       more than one device in a single direction, maxDeviceChannelCount is the maximum 
+       number of channels used by a single device.
+    */
+    int maxDeviceChannelCount = channelCount;
+    int hostSampleSizeBytes = Pa_GetSampleSize( hostSampleFormat );
+    if( hostSampleSizeBytes < 0 )
+    {
+        return hostSampleSizeBytes; /* the value of hostSampleSize here is an error code, not a sample size */
+    }
+
+    if( streamInfo && ( streamInfo->flags & paWinMmeUseMultipleDevices ) )
+    {
+        maxDeviceChannelCount = streamInfo->devices[0].channelCount;
+        for( i=1; i< streamInfo->deviceCount; ++i )
+        {
+            if( streamInfo->devices[i].channelCount > maxDeviceChannelCount )
+                maxDeviceChannelCount = streamInfo->devices[i].channelCount;
+        }
+    }
+
+    *hostSampleFrameSizeBytes = hostSampleSizeBytes * maxDeviceChannelCount;
+
+    return paNoError;
+}
+
+
+/* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount,
+   framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values
+   of the other parameters.
+*/
+
+static PaError CalculateBufferSettings(
+        unsigned long *hostFramesPerInputBuffer, unsigned long *hostInputBufferCount,
+        unsigned long *hostFramesPerOutputBuffer, unsigned long *hostOutputBufferCount,
+        int inputChannelCount, PaSampleFormat hostInputSampleFormat,
+        PaTime suggestedInputLatency, const PaWinMmeStreamInfo *inputStreamInfo,
+        int outputChannelCount, PaSampleFormat hostOutputSampleFormat,
+        PaTime suggestedOutputLatency, const PaWinMmeStreamInfo *outputStreamInfo,
+        double sampleRate, unsigned long userFramesPerBuffer )
+{
+    PaError result = paNoError;
+    
+    if( inputChannelCount > 0 ) /* stream has input */
+    {
+        int hostInputFrameSizeBytes;
+        result = CalculateMaxHostSampleFrameSizeBytes( 
+                inputChannelCount, hostInputSampleFormat, inputStreamInfo, &hostInputFrameSizeBytes );
+        if( result != paNoError )
+            goto error;
+
+        if( inputStreamInfo
+                && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+        {
+            /* input - using low level latency parameters if provided */
+
+            if( inputStreamInfo->bufferCount <= 0
+                    || inputStreamInfo->framesPerBuffer <= 0 )
+            {
+                result = paIncompatibleHostApiSpecificStreamInfo;
+                goto error;
+            }
+
+            *hostFramesPerInputBuffer = inputStreamInfo->framesPerBuffer;
+            *hostInputBufferCount = inputStreamInfo->bufferCount;
+        }
+        else
+        {
+            /* input - not using low level latency parameters, so compute 
+               hostFramesPerInputBuffer and hostInputBufferCount
+               based on userFramesPerBuffer and suggestedInputLatency. */
+
+            unsigned long minimumBufferCount = (outputChannelCount > 0)
+                    ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_
+                    : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_;
+
+            result = SelectHostBufferSizeFramesAndHostBufferCount(
+                    (unsigned long)(suggestedInputLatency * sampleRate), /* (truncate) */
+                    userFramesPerBuffer,
+                    minimumBufferCount,
+                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */
+                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostInputFrameSizeBytes),  /* in frames. a hard limit. note truncation due to 
+                                                                                division is intentional here to limit max bytes */
+                    hostFramesPerInputBuffer,
+                    hostInputBufferCount );
+            if( result != paNoError )
+                goto error;
+        }
+    }
+    else
+    {
+        *hostFramesPerInputBuffer = 0;
+        *hostInputBufferCount = 0;
+    }
+
+    if( outputChannelCount > 0 ) /* stream has output */
+    {
+        if( outputStreamInfo
+                && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+        {
+            /* output - using low level latency parameters */
+
+            if( outputStreamInfo->bufferCount <= 0
+                    || outputStreamInfo->framesPerBuffer <= 0 )
+            {
+                result = paIncompatibleHostApiSpecificStreamInfo;
+                goto error;
+            }
+
+            *hostFramesPerOutputBuffer = outputStreamInfo->framesPerBuffer;
+            *hostOutputBufferCount = outputStreamInfo->bufferCount;
+
+            if( inputChannelCount > 0 ) /* full duplex */
+            {
+                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */
+
+                if( *hostFramesPerInputBuffer != *hostFramesPerOutputBuffer )
+                {
+                    if( inputStreamInfo
+                            && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+                    { 
+                        /* a custom StreamInfo was used for specifying both input
+                            and output buffer sizes. We require that the larger buffer size
+                            must be a multiple of the smaller buffer size */
+
+                        if( *hostFramesPerInputBuffer < *hostFramesPerOutputBuffer )
+                        {
+                            if( *hostFramesPerOutputBuffer % *hostFramesPerInputBuffer != 0 )
+                            {
+                                result = paIncompatibleHostApiSpecificStreamInfo;
+                                goto error;
+                            }
+                        }
+                        else
+                        {
+                            assert( *hostFramesPerInputBuffer > *hostFramesPerOutputBuffer );
+                            if( *hostFramesPerInputBuffer % *hostFramesPerOutputBuffer != 0 )
+                            {
+                                result = paIncompatibleHostApiSpecificStreamInfo;
+                                goto error;
+                            }
+                        }                        
+                    }
+                    else
+                    {
+                        /* a custom StreamInfo was not used for specifying the input buffer size,
+                            so use the output buffer size, and approximately the suggested input latency. */
+
+                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;
+
+                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
+                                (unsigned long)(suggestedInputLatency * sampleRate), 
+                                *hostFramesPerInputBuffer, 
+                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );
+                    }
+                }
+            }
+        }
+        else
+        {
+            /* output - no low level latency parameters, so compute hostFramesPerOutputBuffer and hostOutputBufferCount
+                based on userFramesPerBuffer and suggestedOutputLatency. */
+
+            int hostOutputFrameSizeBytes;
+            result = CalculateMaxHostSampleFrameSizeBytes( 
+                    outputChannelCount, hostOutputSampleFormat, outputStreamInfo, &hostOutputFrameSizeBytes );
+            if( result != paNoError )
+                goto error;
+
+            /* compute the output buffer size and count */
+
+            result = SelectHostBufferSizeFramesAndHostBufferCount(
+                    (unsigned long)(suggestedOutputLatency * sampleRate), /* (truncate) */
+                    userFramesPerBuffer,
+                    PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_,
+                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */
+                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostOutputFrameSizeBytes),  /* in frames. a hard limit. note truncation due to 
+                                                                                 division is intentional here to limit max bytes */
+                    hostFramesPerOutputBuffer,
+                    hostOutputBufferCount );
+            if( result != paNoError )
+                goto error;
+
+            if( inputChannelCount > 0 ) /* full duplex */
+            {
+                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */
+
+                /* ensure that both input and output buffer sizes are the same.
+                    if they don't match at this stage, choose the smallest one
+                    and use that for input and output and recompute the corresponding
+                    buffer count accordingly.
+                */
+
+                if( *hostFramesPerOutputBuffer != *hostFramesPerInputBuffer )
+                {
+                    if( hostFramesPerInputBuffer < hostFramesPerOutputBuffer )
+                    {
+                        *hostFramesPerOutputBuffer = *hostFramesPerInputBuffer;
+
+                        *hostOutputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
+                                (unsigned long)(suggestedOutputLatency * sampleRate), 
+                                *hostOutputBufferCount, 
+                                PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ );
+                    }
+                    else
+                    {
+                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;
+
+                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(
+                                (unsigned long)(suggestedInputLatency * sampleRate), 
+                                *hostFramesPerInputBuffer, 
+                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );
+                    }
+                }   
+            }
+        }
+    }
+    else
+    {
+        *hostFramesPerOutputBuffer = 0;
+        *hostOutputBufferCount = 0;
+    }
+
+error:
+    return result;
+}
+
+
+typedef struct
+{
+    HANDLE bufferEvent;
+    void *waveHandles;
+    unsigned int deviceCount;
+    /* unsigned int channelCount; */
+    WAVEHDR **waveHeaders;                  /* waveHeaders[device][buffer] */
+    unsigned int bufferCount;
+    unsigned int currentBufferIndex;
+    unsigned int framesPerBuffer;
+    unsigned int framesUsedInCurrentBuffer;
+}PaWinMmeSingleDirectionHandlesAndBuffers;
+
+/* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */
+
+static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );
+static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
+        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+        unsigned long winMmeSpecificFlags,
+        unsigned long bytesPerHostSample,
+        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
+        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput );
+static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );
+static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+        unsigned long hostBufferCount,
+        PaSampleFormat hostSampleFormat,
+        unsigned long framesPerHostBuffer,
+        PaWinMmeDeviceAndChannelCount *devices,
+        int isInput );
+static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput );
+
+
+static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+    handlesAndBuffers->bufferEvent = 0;
+    handlesAndBuffers->waveHandles = 0;
+    handlesAndBuffers->deviceCount = 0;
+    handlesAndBuffers->waveHeaders = 0;
+    handlesAndBuffers->bufferCount = 0;
+}    
+
+static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
+        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+        unsigned long winMmeSpecificFlags,
+        unsigned long bytesPerHostSample,
+        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
+        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput )
+{
+    PaError result;
+    MMRESULT mmresult;
+    signed int i, j;
+    PaSampleFormat sampleFormat;
+    int waveFormatTag;
+
+    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
+        has already been called to zero some fields */       
+
+    result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL );
+    if( result != paNoError ) goto error;
+
+    if( isInput )
+        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount );
+    else
+        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount );
+    if( !handlesAndBuffers->waveHandles )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    handlesAndBuffers->deviceCount = deviceCount;
+
+    for( i = 0; i < (signed int)deviceCount; ++i )
+    {
+        if( isInput )
+            ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0;
+        else
+            ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;
+    }
+
+    /* @todo at the moment we only use 16 bit sample format */
+    sampleFormat = paInt16;
+    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );
+
+    for( i = 0; i < (signed int)deviceCount; ++i )
+    {
+        PaWinWaveFormat waveFormat;
+        UINT winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );
+    
+        /* @todo: consider providing a flag or #define to not try waveformat extensible 
+           this could just initialize j to 1 the first time round. */
+
+        for( j = 0; j < 2; ++j )
+        {
+            switch(j){
+                case 0:     
+                    /* first, attempt to open the device using WAVEFORMATEXTENSIBLE, 
+                        if this fails we fall back to WAVEFORMATEX */
+
+                    PaWin_InitializeWaveFormatExtensible( &waveFormat, devices[i].channelCount, 
+                            sampleFormat, waveFormatTag, sampleRate, channelMask );
+                    break;
+                
+                case 1:
+                    /* retry with WAVEFORMATEX */
+
+                    PaWin_InitializeWaveFormatEx( &waveFormat, devices[i].channelCount, 
+                            sampleFormat, waveFormatTag, sampleRate );
+                    break;
+            }
+
+            /* REVIEW: consider not firing an event for input when a full duplex
+                stream is being used. this would probably depend on the
+                neverDropInput flag. */
+
+            if( isInput )
+            {
+                mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, 
+                                    (WAVEFORMATEX*)&waveFormat,
+                               (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
+            }
+            else
+            {
+                mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, 
+                                    (WAVEFORMATEX*)&waveFormat,
+                                (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
+            }
+
+            if( mmresult == MMSYSERR_NOERROR )
+            {
+                break; /* success */
+            }
+            else if( j == 0 )
+            {
+                continue; /* try again with WAVEFORMATEX */
+            }
+            else
+            {
+                switch( mmresult )
+                {
+                    case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
+                        result = paDeviceUnavailable;
+                        break;
+                    case MMSYSERR_NODRIVER:        /* No device driver is present. */
+                        result = paDeviceUnavailable;
+                        break;
+                    case MMSYSERR_NOMEM:           /* Unable to allocate or lock memory. */
+                        result = paInsufficientMemory;
+                        break;
+
+                    case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
+                        /* falls through */
+
+                    case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
+                                                    /* This can also occur if we try to open the device with an unsupported
+                                                     * number of channels. This is attempted when device*ChannelCountIsKnown is
+                                                     * set to 0. 
+                                                     */
+                        /* falls through */
+                    default:
+                        result = paUnanticipatedHostError;
+                        if( isInput )
+                        {
+                            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                        }
+                        else
+                        {
+                            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                        }
+                }
+                goto error;
+            }
+        }
+    }
+
+    return result;
+
+error:
+    TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ );
+
+    return result;
+}
+
+
+static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError )
+{
+    PaError result = paNoError;
+    MMRESULT mmresult;
+    signed int i;
+    
+    if( handlesAndBuffers->waveHandles )
+    {
+        for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i )
+        {
+            if( isInput )
+            {
+                if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] )
+                    mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] );
+                else
+                    mmresult = MMSYSERR_NOERROR;
+            }
+            else
+            {
+                if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] )
+                    mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] );
+                else
+                    mmresult = MMSYSERR_NOERROR;
+            }
+
+            if( mmresult != MMSYSERR_NOERROR &&
+                !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */
+            {
+                result = paUnanticipatedHostError;
+                if( isInput )
+                {
+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                }
+                else
+                {
+                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                }
+                /* note that we don't break here, we try to continue closing devices */
+            }
+        }
+
+        PaUtil_FreeMemory( handlesAndBuffers->waveHandles );
+        handlesAndBuffers->waveHandles = 0;
+    }
+
+    if( handlesAndBuffers->bufferEvent )
+    {
+        result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent );
+        handlesAndBuffers->bufferEvent = 0;
+    }
+    
+    return result;
+}
+
+
+static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+        unsigned long hostBufferCount,
+        PaSampleFormat hostSampleFormat,
+        unsigned long framesPerHostBuffer,
+        PaWinMmeDeviceAndChannelCount *devices,
+        int isInput )
+{
+    PaError result = paNoError;
+    MMRESULT mmresult;
+    WAVEHDR *deviceWaveHeaders;
+    signed int i, j;
+
+    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
+        has already been called to zero some fields */
+        
+
+    /* allocate an array of pointers to arrays of wave headers, one array of
+        wave headers per device */
+    handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount );
+    if( !handlesAndBuffers->waveHeaders )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+    
+    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
+        handlesAndBuffers->waveHeaders[i] = 0;
+
+    handlesAndBuffers->bufferCount = hostBufferCount;
+
+    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
+    {
+        int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) *
+                framesPerHostBuffer * devices[i].channelCount;
+        if( bufferBytes < 0 )
+        {
+            result = paInternalError;
+            goto error;
+        }
+
+        /* Allocate an array of wave headers for device i */
+        deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount );
+        if( !deviceWaveHeaders )
+        {
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for( j=0; j < (signed int)hostBufferCount; ++j )
+            deviceWaveHeaders[j].lpData = 0;
+
+        handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders;
+
+        /* Allocate a buffer for each wave header */
+        for( j=0; j < (signed int)hostBufferCount; ++j )
+        {
+            deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes );
+            if( !deviceWaveHeaders[j].lpData )
+            {
+                result = paInsufficientMemory;
+                goto error;
+            }
+            deviceWaveHeaders[j].dwBufferLength = bufferBytes;
+            deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */
+
+            if( isInput )
+            {
+                mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+                if( mmresult != MMSYSERR_NOERROR )
+                {
+                    result = paUnanticipatedHostError;
+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                    goto error;
+                }
+            }
+            else /* output */
+            {
+                mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+                if( mmresult != MMSYSERR_NOERROR )
+                {
+                    result = paUnanticipatedHostError;
+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                    goto error;
+                }
+            }
+            deviceWaveHeaders[j].dwUser = devices[i].channelCount;
+        }
+    }
+
+    return result;
+
+error:
+    TerminateWaveHeaders( handlesAndBuffers, isInput );
+    
+    return result;
+}
+
+
+static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput )
+{
+    signed int i, j;
+    WAVEHDR *deviceWaveHeaders;
+    
+    if( handlesAndBuffers->waveHeaders )
+    {
+        for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i )
+        {
+            deviceWaveHeaders = handlesAndBuffers->waveHeaders[i];  /* wave headers for device i */
+            if( deviceWaveHeaders )
+            {
+                for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j )
+                {
+                    if( deviceWaveHeaders[j].lpData )
+                    {
+                        if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF )
+                        {
+                            if( isInput )
+                                waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+                            else
+                                waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+                        }
+
+                        PaUtil_FreeMemory( deviceWaveHeaders[j].lpData );
+                    }
+                }
+
+                PaUtil_FreeMemory( deviceWaveHeaders );
+            }
+        }
+
+        PaUtil_FreeMemory( handlesAndBuffers->waveHeaders );
+        handlesAndBuffers->waveHeaders = 0;
+    }
+}
+
+
+
+/* PaWinMmeStream - a stream data structure specifically for this implementation */
+/* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */
+struct PaWinMmeStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+
+    int primeStreamUsingCallback;
+
+    PaWinMmeSingleDirectionHandlesAndBuffers input;
+    PaWinMmeSingleDirectionHandlesAndBuffers output;
+
+    /* Processing thread management -------------- */
+    HANDLE abortEvent;
+    HANDLE processingThread;
+    PA_THREAD_ID processingThreadId;
+
+    char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */
+    int processingThreadPriority;
+    int highThreadPriority;
+    int throttledThreadPriority;
+    unsigned long throttledSleepMsecs;
+
+    int isStopped;
+    volatile int isActive;
+    volatile int stopProcessing; /* stop thread once existing buffers have been returned */
+    volatile int abortProcessing; /* stop thread immediately */
+
+    DWORD allBuffersDurationMs; /* used to calculate timeouts */
+};
+
+/* updates deviceCount if PaWinMmeUseMultipleDevices is used */
+
+static PaError ValidateWinMmeSpecificStreamInfo(
+        const PaStreamParameters *streamParameters,
+        const PaWinMmeStreamInfo *streamInfo,
+        unsigned long *winMmeSpecificFlags,
+        char *throttleProcessingThreadOnOverload,
+        unsigned long *deviceCount )
+{
+    if( streamInfo )
+    {
+        if( streamInfo->size != sizeof( PaWinMmeStreamInfo )
+                || streamInfo->version != 1 )
+        {
+            return paIncompatibleHostApiSpecificStreamInfo;
+        }
+
+        *winMmeSpecificFlags = streamInfo->flags;
+
+        if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )
+            *throttleProcessingThreadOnOverload = 0;
+            
+        if( streamInfo->flags & paWinMmeUseMultipleDevices )
+        {
+            if( streamParameters->device != paUseHostApiSpecificDeviceSpecification )
+                return paInvalidDevice;
+    
+            *deviceCount = streamInfo->deviceCount;
+        }      
+    }
+
+    return paNoError;
+}
+
+static PaError RetrieveDevicesFromStreamParameters(
+        struct PaUtilHostApiRepresentation *hostApi,
+        const PaStreamParameters *streamParameters,
+        const PaWinMmeStreamInfo *streamInfo,
+        PaWinMmeDeviceAndChannelCount *devices,
+        unsigned long deviceCount )
+{
+    PaError result = paNoError;
+    unsigned int i;
+    int totalChannelCount;
+    PaDeviceIndex hostApiDevice;
+    
+    if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices )
+    {
+        totalChannelCount = 0;
+        for( i=0; i < deviceCount; ++i )
+        {
+            /* validate that the device number is within range */
+            result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice,
+                            streamInfo->devices[i].device, hostApi );
+            if( result != paNoError )
+                return result;
+            
+            devices[i].device = hostApiDevice;
+            devices[i].channelCount = streamInfo->devices[i].channelCount;
+    
+            totalChannelCount += devices[i].channelCount;
+        }
+    
+        if( totalChannelCount != streamParameters->channelCount )
+        {
+            /* channelCount must match total channels specified by multiple devices */
+            return paInvalidChannelCount; /* REVIEW use of this error code */
+        }
+    }  
+    else
+    {          
+        devices[0].device = streamParameters->device;
+        devices[0].channelCount = streamParameters->channelCount;
+    }
+
+    return result;
+}
+
+static PaError ValidateInputChannelCounts(
+        struct PaUtilHostApiRepresentation *hostApi,
+        PaWinMmeDeviceAndChannelCount *devices,
+        unsigned long deviceCount )
+{
+    unsigned int i;
+    PaWinMmeDeviceInfo *inputDeviceInfo;
+    PaError paerror;
+
+    for( i=0; i < deviceCount; ++i )
+    {
+        if( devices[i].channelCount < 1 )
+            return paInvalidChannelCount;
+
+        inputDeviceInfo = 
+                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];
+
+        paerror = IsInputChannelCountSupported( inputDeviceInfo, devices[i].channelCount );
+        if( paerror != paNoError )
+            return paerror;
+    }
+
+    return paNoError;
+}
+
+static PaError ValidateOutputChannelCounts(
+        struct PaUtilHostApiRepresentation *hostApi,
+        PaWinMmeDeviceAndChannelCount *devices,
+        unsigned long deviceCount )
+{
+    unsigned int i;
+    PaWinMmeDeviceInfo *outputDeviceInfo;
+    PaError paerror;
+
+    for( i=0; i < deviceCount; ++i )
+    {
+        if( devices[i].channelCount < 1 )
+            return paInvalidChannelCount;
+
+        outputDeviceInfo = 
+                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];
+
+        paerror = IsOutputChannelCountSupported( outputDeviceInfo, devices[i].channelCount );
+        if( paerror != paNoError )
+            return paerror;
+    }
+
+    return paNoError;
+}
+
+
+/* the following macros are intended to improve the readability of the following code */
+#define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles )
+#define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles )
+#define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles )
+#define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) )
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result;
+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+    PaWinMmeStream *stream = 0;
+    int bufferProcessorIsInitialized = 0;
+    int streamRepresentationIsInitialized = 0;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    double suggestedInputLatency, suggestedOutputLatency;
+    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
+    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
+    unsigned long framesPerHostInputBuffer;
+    unsigned long hostInputBufferCount;
+    unsigned long framesPerHostOutputBuffer;
+    unsigned long hostOutputBufferCount;
+    unsigned long framesPerBufferProcessorCall;
+    PaWinMmeDeviceAndChannelCount *inputDevices = 0;  /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
+    unsigned long winMmeSpecificInputFlags = 0;
+    unsigned long inputDeviceCount = 0;            
+    PaWinMmeDeviceAndChannelCount *outputDevices = 0;
+    unsigned long winMmeSpecificOutputFlags = 0;
+    unsigned long outputDeviceCount = 0;                /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
+    char throttleProcessingThreadOnOverload = 1;
+
+    
+    if( inputParameters )
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+        suggestedInputLatency = inputParameters->suggestedLatency;
+
+        inputDeviceCount = 1;
+
+        /* validate input hostApiSpecificStreamInfo */
+        inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,
+                &winMmeSpecificInputFlags,
+                &throttleProcessingThreadOnOverload,
+                &inputDeviceCount );
+        if( result != paNoError ) return result;
+
+        inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount );
+        if( !inputDevices ) return paInsufficientMemory;
+
+        result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount );
+        if( result != paNoError ) return result;
+
+        result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount );
+        if( result != paNoError ) return result;
+
+        hostInputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );
+
+        if( inputDeviceCount != 1 ){
+            /* always use direct speakers when using multi-device multichannel mode */
+            inputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           
+        }
+        else
+        {
+            if( inputStreamInfo && inputStreamInfo->flags & paWinMmeUseChannelMask )
+                inputChannelMask = inputStreamInfo->channelMask;
+            else
+                inputChannelMask = PaWin_DefaultChannelMask( inputDevices[0].channelCount );
+        }
+    }
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = 0;
+        suggestedInputLatency = 0.;
+        inputStreamInfo = 0;
+        hostInputSampleFormat = 0;
+    }
+
+
+    if( outputParameters )
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+        suggestedOutputLatency = outputParameters->suggestedLatency;
+
+        outputDeviceCount = 1;
+
+        /* validate output hostApiSpecificStreamInfo */
+        outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+        result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,
+                &winMmeSpecificOutputFlags,
+                &throttleProcessingThreadOnOverload,
+                &outputDeviceCount );
+        if( result != paNoError ) return result;
+
+        outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount );
+        if( !outputDevices ) return paInsufficientMemory;
+
+        result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount );
+        if( result != paNoError ) return result;
+
+        result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount );
+        if( result != paNoError ) return result;
+
+        hostOutputSampleFormat =
+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );
+
+        if( outputDeviceCount != 1 ){
+            /* always use direct speakers when using multi-device multichannel mode */
+            outputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           
+        }
+        else
+        {
+            if( outputStreamInfo && outputStreamInfo->flags & paWinMmeUseChannelMask )
+                outputChannelMask = outputStreamInfo->channelMask;
+            else
+                outputChannelMask = PaWin_DefaultChannelMask( outputDevices[0].channelCount );
+        }
+    }
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = 0;
+        outputStreamInfo = 0;
+        hostOutputSampleFormat = 0;
+        suggestedOutputLatency = 0.;
+    }
+
+
+    /*
+        IMPLEMENT ME:
+            - alter sampleRate to a close allowable rate if possible / necessary
+    */
+
+
+    /* validate platform specific flags */
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag; /* unexpected platform specific flag */
+
+
+    /* always disable clipping and dithering if we are outputting a raw spdif stream */
+    if( (winMmeSpecificOutputFlags & paWinMmeWaveFormatDolbyAc3Spdif)
+            || (winMmeSpecificOutputFlags & paWinMmeWaveFormatWmaSpdif) ){
+
+        streamFlags = streamFlags | paClipOff | paDitherOff;
+    }
+
+
+    result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,
+                &framesPerHostOutputBuffer, &hostOutputBufferCount,
+                inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,
+                outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo,
+                sampleRate, framesPerBuffer );
+    if( result != paNoError ) goto error;
+
+
+    stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) );
+    if( !stream )
+    {
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    InitializeSingleDirectionHandlesAndBuffers( &stream->input );
+    InitializeSingleDirectionHandlesAndBuffers( &stream->output );
+
+    stream->abortEvent = 0;
+    stream->processingThread = 0;
+
+    stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload;
+
+    PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+                                           ( (streamCallback)
+                                            ? &winMmeHostApi->callbackStreamInterface
+                                            : &winMmeHostApi->blockingStreamInterface ),
+                                           streamCallback, userData );
+    streamRepresentationIsInitialized = 1;
+
+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+    if( inputParameters && outputParameters ) /* full duplex */
+    {
+        if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
+        {
+            assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
+
+            framesPerBufferProcessorCall = framesPerHostInputBuffer;
+        }
+        else
+        {
+            assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
+            
+            framesPerBufferProcessorCall = framesPerHostOutputBuffer;
+        }
+    }
+    else if( inputParameters )
+    {
+        framesPerBufferProcessorCall = framesPerHostInputBuffer;
+    }
+    else if( outputParameters )
+    {
+        framesPerBufferProcessorCall = framesPerHostOutputBuffer;
+    }
+
+    stream->input.framesPerBuffer = framesPerHostInputBuffer;
+    stream->output.framesPerBuffer = framesPerHostOutputBuffer;
+
+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+                    sampleRate, streamFlags, framesPerBuffer,
+                    framesPerBufferProcessorCall, paUtilFixedHostBufferSize,
+                    streamCallback, userData );
+    if( result != paNoError ) goto error;
+    
+    bufferProcessorIsInitialized = 1;
+
+    /* stream info input latency is the minimum buffering latency (unlike suggested and default which are *maximums*) */
+    stream->streamRepresentation.streamInfo.inputLatency =
+            (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
+                + framesPerHostInputBuffer) / sampleRate;
+    stream->streamRepresentation.streamInfo.outputLatency =
+            (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
+                + (framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate;
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0;
+
+    /* time to sleep when throttling due to >100% cpu usage.
+        -a quater of a buffer's duration */
+    stream->throttledSleepMsecs =
+            (unsigned long)(stream->bufferProcessor.framesPerHostBuffer *
+             stream->bufferProcessor.samplePeriod * .25 * 1000);
+
+    stream->isStopped = 1;
+    stream->isActive = 0;
+
+
+    /* for maximum compatibility with multi-device multichannel drivers,
+        we first open all devices, then we prepare all buffers, finally
+        we start all devices ( in StartStream() ). teardown in reverse order.
+    */
+
+    if( inputParameters )
+    {
+        result = InitializeWaveHandles( winMmeHostApi, &stream->input,
+                winMmeSpecificInputFlags,
+                stream->bufferProcessor.bytesPerHostInputSample, sampleRate,
+                inputDevices, inputDeviceCount, inputChannelMask, 1 /* isInput */ );
+        if( result != paNoError ) goto error;
+    }
+    
+    if( outputParameters )
+    {
+        result = InitializeWaveHandles( winMmeHostApi, &stream->output,
+                winMmeSpecificOutputFlags,
+                stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,
+                outputDevices, outputDeviceCount, outputChannelMask, 0 /* isInput */ );
+        if( result != paNoError ) goto error;
+    }
+
+    if( inputParameters )
+    {
+        result = InitializeWaveHeaders( &stream->input, hostInputBufferCount,
+                hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ );
+        if( result != paNoError ) goto error;
+    }
+
+    if( outputParameters )
+    {
+        result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount,
+                hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ );
+        if( result != paNoError ) goto error;
+
+        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate);
+    }
+    else
+    {
+        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate);
+    }
+
+    
+    if( streamCallback )
+    {
+        /* abort event is only needed for callback streams */
+        result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL );
+        if( result != paNoError ) goto error;
+    }
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+
+    if( stream )
+    {
+        if( stream->abortEvent )
+            CloseHandle( stream->abortEvent );
+            
+        TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
+        TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
+
+        TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ );
+        TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ );
+
+        if( bufferProcessorIsInitialized )
+            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+        if( streamRepresentationIsInitialized )
+            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+        PaUtil_FreeMemory( stream );
+    }
+
+    return result;
+}
+
+
+/* return non-zero if all current buffers are done */
+static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex )
+{
+    unsigned int i;
+    
+    for( i=0; i < deviceCount; ++i )
+    {
+        if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) )
+        {
+            return 0;
+        }         
+    }
+
+    return 1;
+}
+
+static int CurrentInputBuffersAreDone( PaWinMmeStream *stream )
+{
+    return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex );
+}
+
+static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream )
+{
+    return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex );
+}
+
+
+/* return non-zero if any buffers are queued */
+static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+    unsigned int i, j;
+
+    if( handlesAndBuffers->waveHandles )
+    {
+        for( i=0; i < handlesAndBuffers->bufferCount; ++i )
+        {
+            for( j=0; j < handlesAndBuffers->deviceCount; ++j )
+            {
+                if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) )
+                {
+                    return 0;
+                }
+            }
+        }
+    }
+
+    return 1;
+}
+
+
+#define PA_CIRCULAR_INCREMENT_( current, max )\
+    ( (((current) + 1) >= (max)) ? (0) : (current+1) )
+
+#define PA_CIRCULAR_DECREMENT_( current, max )\
+    ( ((current) == 0) ? ((max)-1) : (current-1) )
+    
+
+static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+    signed long result = 0;
+    unsigned int i;
+    
+    if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) )
+    {
+        /* we could calculate the following in O(1) if we kept track of the
+            last done buffer */
+        result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer;
+
+        i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount );
+        while( i != handlesAndBuffers->currentBufferIndex )
+        {
+            if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) )
+            {
+                result += handlesAndBuffers->framesPerBuffer;
+                i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount );
+            }
+            else
+                break;
+        }
+    }
+
+    return result;
+}
+
+
+static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )
+{
+    PaError result = paNoError;
+    MMRESULT mmresult;
+    unsigned int i;
+
+    for( i=0; i < stream->input.deviceCount; ++i )
+    {
+        stream->input.waveHeaders[i][ stream->input.currentBufferIndex ].dwFlags &= ~WHDR_DONE;
+        mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],
+                                    &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],
+                                    sizeof(WAVEHDR) );
+        if( mmresult != MMSYSERR_NOERROR )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+        }
+    }
+
+    stream->input.currentBufferIndex =
+            PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount );
+
+    stream->input.framesUsedInCurrentBuffer = 0;
+
+    return result;
+}
+
+
+static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream )
+{
+    PaError result = paNoError;
+    MMRESULT mmresult;
+    unsigned int i;
+
+    for( i=0; i < stream->output.deviceCount; ++i )
+    {
+        mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i],
+                                 &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ],
+                                 sizeof(WAVEHDR) );
+        if( mmresult != MMSYSERR_NOERROR )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+        }
+    }
+
+    stream->output.currentBufferIndex =
+            PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
+
+    stream->output.framesUsedInCurrentBuffer = 0;
+    
+    return result;
+}
+
+
+/* requeue all but the most recent input with the driver. Used for catching
+    up after a total input buffer underrun */
+static PaError CatchUpInputBuffers( PaWinMmeStream *stream )
+{
+    PaError result = paNoError;
+    unsigned int i;
+    
+    for( i=0; i < stream->input.bufferCount - 1; ++i )
+    {
+        result = AdvanceToNextInputBuffer( stream );
+        if( result != paNoError )
+            break;
+    }
+
+    return result;
+}
+
+
+/* take the most recent output and duplicate it to all other output buffers
+    and requeue them. Used for catching up after a total output buffer underrun.
+*/
+static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )
+{
+    PaError result = paNoError;
+    unsigned int i, j;
+    unsigned int previousBufferIndex =
+            PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
+
+    for( i=0; i < stream->output.bufferCount - 1; ++i )
+    {
+        for( j=0; j < stream->output.deviceCount; ++j )
+        {
+            if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData
+                    != stream->output.waveHeaders[j][ previousBufferIndex ].lpData )
+            {
+                CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData,
+                            stream->output.waveHeaders[j][ previousBufferIndex ].lpData,
+                            stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength );
+            }
+        }
+
+        result = AdvanceToNextOutputBuffer( stream );
+        if( result != paNoError )
+            break;
+    }
+
+    return result;
+}
+
+
+PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream *)pArg;
+    HANDLE events[3];
+    int eventCount = 0;
+    DWORD result = paNoError;
+    DWORD waitResult;
+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+    int hostBuffersAvailable;
+    signed int hostInputBufferIndex, hostOutputBufferIndex;
+    PaStreamCallbackFlags statusFlags;
+    int callbackResult;
+    int done = 0;
+    unsigned int channel, i;
+    unsigned long framesProcessed;
+    
+    /* prepare event array for call to WaitForMultipleObjects() */
+    if( stream->input.bufferEvent )
+        events[eventCount++] = stream->input.bufferEvent;
+    if( stream->output.bufferEvent )
+        events[eventCount++] = stream->output.bufferEvent;
+    events[eventCount++] = stream->abortEvent;
+
+    statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */
+    
+    /* loop until something causes us to stop */
+    do{
+        /* wait for MME to signal that a buffer is available, or for
+            the PA abort event to be signaled.
+
+          When this indicates that one or more buffers are available
+          NoBuffersAreQueued() and Current*BuffersAreDone are used below to
+          poll for additional done buffers. NoBuffersAreQueued() will fail
+          to identify an underrun/overflow if the driver doesn't mark all done
+          buffers prior to signalling the event. Some drivers do this
+          (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a
+          huge problem, it just means that we won't always be able to detect
+          underflow/overflow.
+        */
+        waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout );
+        if( waitResult == WAIT_FAILED )
+        {
+            result = paUnanticipatedHostError;
+            /** @todo FIXME/REVIEW: can't return host error info from an asyncronous thread. see http://www.portaudio.com/trac/ticket/143 */
+            done = 1;
+        }
+        else if( waitResult == WAIT_TIMEOUT )
+        {
+            /* if a timeout is encountered, continue */
+        }
+
+        if( stream->abortProcessing )
+        {
+            /* Pa_AbortStream() has been called, stop processing immediately */
+            done = 1;
+        }
+        else if( stream->stopProcessing )
+        {
+            /* Pa_StopStream() has been called or the user callback returned
+                non-zero, processing will continue until all output buffers
+                are marked as done. The stream will stop immediately if it
+                is input-only.
+            */
+
+            if( PA_IS_OUTPUT_STREAM_(stream) )
+            {
+                if( NoBuffersAreQueued( &stream->output ) )
+                    done = 1; /* Will cause thread to return. */
+            }
+            else
+            {
+                /* input only stream */
+                done = 1; /* Will cause thread to return. */
+            }
+        }
+        else
+        {
+            hostBuffersAvailable = 1;
+
+            /* process all available host buffers */
+            do
+            {
+                hostInputBufferIndex = -1;
+                hostOutputBufferIndex = -1;
+                
+                if( PA_IS_INPUT_STREAM_(stream) )
+                {
+                    if( CurrentInputBuffersAreDone( stream ) )
+                    {
+                        if( NoBuffersAreQueued( &stream->input ) )
+                        {
+                            /** @todo
+                               if all of the other buffers are also ready then
+                               we discard all but the most recent. This is an
+                               input buffer overflow. FIXME: these buffers should
+                               be passed to the callback in a paNeverDropInput
+                               stream. http://www.portaudio.com/trac/ticket/142
+
+                               note that it is also possible for an input overflow
+                               to happen while the callback is processing a buffer.
+                               that is handled further down.
+                            */
+                            result = CatchUpInputBuffers( stream );
+                            if( result != paNoError )
+                                done = 1;
+
+                            statusFlags |= paInputOverflow;
+                        }
+
+                        hostInputBufferIndex = stream->input.currentBufferIndex;
+                    }
+                }
+
+                if( PA_IS_OUTPUT_STREAM_(stream) )
+                {
+                    if( CurrentOutputBuffersAreDone( stream ) )
+                    {
+                        /* ok, we have an output buffer */
+                        
+                        if( NoBuffersAreQueued( &stream->output ) )
+                        {
+                            /*
+                            if all of the other buffers are also ready, catch up by copying
+                            the most recently generated buffer into all but one of the output
+                            buffers.
+
+                            note that this catch up code only handles the case where all
+                            buffers have been played out due to this thread not having
+                            woken up at all. a more common case occurs when this thread
+                            is woken up, processes one buffer, but takes too long, and as
+                            a result all the other buffers have become un-queued. that
+                            case is handled further down.
+                            */
+
+                            result = CatchUpOutputBuffers( stream );
+                            if( result != paNoError )
+                                done = 1;
+
+                            statusFlags |= paOutputUnderflow;
+                        }
+
+                        hostOutputBufferIndex = stream->output.currentBufferIndex;
+                    }
+                }
+
+               
+                if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) ||
+                        (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) )
+                {
+                    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */
+
+
+                    if( PA_IS_OUTPUT_STREAM_(stream) )
+                    {
+                        /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime
+                            from the current wave out position */
+                        MMTIME mmtime;
+                        double timeBeforeGetPosition, timeAfterGetPosition;
+                        double time;
+                        long framesInBufferRing;               
+                        long writePosition;
+                        long playbackPosition;
+                        HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0];
+                        
+                        mmtime.wType = TIME_SAMPLES;
+                        timeBeforeGetPosition = PaUtil_GetTime();
+                        waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) );
+                        timeAfterGetPosition = PaUtil_GetTime();
+
+                        timeInfo.currentTime = timeAfterGetPosition;
+
+                        /* approximate time at which wave out position was measured
+                            as half way between timeBeforeGetPosition and timeAfterGetPosition */
+                        time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5;
+                        
+                        framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer;
+                        playbackPosition = mmtime.u.sample % framesInBufferRing;
+
+                        writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer
+                                + stream->output.framesUsedInCurrentBuffer;
+                       
+                        if( playbackPosition >= writePosition ){
+                            timeInfo.outputBufferDacTime =
+                                    time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod );
+                        }else{
+                            timeInfo.outputBufferDacTime =
+                                    time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod );
+                        }
+                    }
+
+
+                    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags  );
+
+                    /* reset status flags once they have been passed to the buffer processor */
+                    statusFlags = 0;
+
+                    if( PA_IS_INPUT_STREAM_(stream) )
+                    {
+                        PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+
+                        channel = 0;
+                        for( i=0; i<stream->input.deviceCount; ++i )
+                        {
+                             /* we have stored the number of channels in the buffer in dwUser */
+                            int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+                            
+                            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
+                                    stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
+                                        stream->input.framesUsedInCurrentBuffer * channelCount *
+                                        stream->bufferProcessor.bytesPerHostInputSample,
+                                    channelCount );
+                                    
+
+                            channel += channelCount;
+                        }
+                    }
+
+                    if( PA_IS_OUTPUT_STREAM_(stream) )
+                    {
+                        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+                        
+                        channel = 0;
+                        for( i=0; i<stream->output.deviceCount; ++i )
+                        {
+                            /* we have stored the number of channels in the buffer in dwUser */
+                            int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+                            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+                                    stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+                                        stream->output.framesUsedInCurrentBuffer * channelCount *
+                                        stream->bufferProcessor.bytesPerHostOutputSample,
+                                    channelCount );
+
+                            channel += channelCount;
+                        }
+                    }
+
+                    callbackResult = paContinue;
+                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+
+                    stream->input.framesUsedInCurrentBuffer += framesProcessed;
+                    stream->output.framesUsedInCurrentBuffer += framesProcessed;
+
+                    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+                    if( callbackResult == paContinue )
+                    {
+                        /* nothing special to do */
+                    }
+                    else if( callbackResult == paAbort )
+                    {
+                        stream->abortProcessing = 1;
+                        done = 1;
+                        /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort 
+                            see: http://www.portaudio.com/trac/ticket/141
+                        */
+                        result = paNoError;
+                    }
+                    else
+                    {
+                        /* User callback has asked us to stop with paComplete or other non-zero value */
+                        stream->stopProcessing = 1; /* stop once currently queued audio has finished */
+                        result = paNoError;
+                    }
+
+
+                    if( PA_IS_INPUT_STREAM_(stream)
+                            && stream->stopProcessing == 0 && stream->abortProcessing == 0
+                            && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
+                    {
+                        if( NoBuffersAreQueued( &stream->input ) )
+                        {
+                            /** @todo need to handle PaNeverDropInput here where necessary */
+                            result = CatchUpInputBuffers( stream );
+                            if( result != paNoError )
+                                done = 1;
+
+                            statusFlags |= paInputOverflow;
+                        }
+
+                        result = AdvanceToNextInputBuffer( stream );
+                        if( result != paNoError )
+                            done = 1;
+                    }
+
+                    
+                    if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing )
+                    {
+                        if( stream->stopProcessing &&
+                                stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer )
+                        {
+                            /* zero remaining samples in output output buffer and flush */
+
+                            stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor,
+                                    stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+                            /* we send the entire buffer to the output devices, but we could
+                                just send a partial buffer, rather than zeroing the unused
+                                samples.
+                            */
+                        }
+
+                        if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
+                        {
+                            /* check for underflow before enquing the just-generated buffer,
+                                but recover from underflow after enquing it. This ensures
+                                that the most recent audio segment is repeated */
+                            int outputUnderflow = NoBuffersAreQueued( &stream->output );
+
+                            result = AdvanceToNextOutputBuffer( stream );
+                            if( result != paNoError )
+                                done = 1;
+
+                            if( outputUnderflow && !done && !stream->stopProcessing )
+                            {
+                                /* Recover from underflow in the case where the
+                                    underflow occured while processing the buffer
+                                    we just finished */
+
+                                result = CatchUpOutputBuffers( stream );
+                                if( result != paNoError )
+                                    done = 1;
+
+                                statusFlags |= paOutputUnderflow;
+                            }
+                        }
+                    }
+                    
+                    if( stream->throttleProcessingThreadOnOverload != 0 )
+                    {
+                        if( stream->stopProcessing || stream->abortProcessing )
+                        {
+                            if( stream->processingThreadPriority != stream->highThreadPriority )
+                            {
+                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );
+                                stream->processingThreadPriority = stream->highThreadPriority;
+                            }
+                        }
+                        else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. )
+                        {
+                            if( stream->processingThreadPriority != stream->throttledThreadPriority )
+                            {
+                                SetThreadPriority( stream->processingThread, stream->throttledThreadPriority );
+                                stream->processingThreadPriority = stream->throttledThreadPriority;
+                            }
+
+                            /* sleep to give other processes a go */
+                            Sleep( stream->throttledSleepMsecs );
+                        }
+                        else
+                        {
+                            if( stream->processingThreadPriority != stream->highThreadPriority )
+                            {
+                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );
+                                stream->processingThreadPriority = stream->highThreadPriority;
+                            }
+                        }
+                    }
+                }
+                else
+                {
+                    hostBuffersAvailable = 0;
+                }
+            }
+            while( hostBuffersAvailable &&
+                    stream->stopProcessing == 0 &&
+                    stream->abortProcessing == 0 &&
+                    !done );
+        }
+    }
+    while( !done );
+
+    stream->isActive = 0;
+
+    if( stream->streamRepresentation.streamFinishedCallback != 0 )
+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+    
+    return result;
+}
+
+
+/*
+    When CloseStream() is called, the multi-api layer ensures that
+    the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+    PaError result;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+    result = CloseHandleWithPaError( stream->abortEvent );
+    if( result != paNoError ) goto error;
+    
+    TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
+    TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
+
+    TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ );
+    TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ );
+    
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+    PaUtil_FreeMemory( stream );
+
+error:
+    /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */
+    return result;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    MMRESULT mmresult;
+    unsigned int i, j;
+    int callbackResult;
+    unsigned int channel;
+    unsigned long framesProcessed;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */
+    
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+    
+    if( PA_IS_INPUT_STREAM_(stream) )
+    {
+        for( i=0; i<stream->input.bufferCount; ++i )
+        {
+            for( j=0; j<stream->input.deviceCount; ++j )
+            {
+                stream->input.waveHeaders[j][i].dwFlags &= ~WHDR_DONE;
+                mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );
+                if( mmresult != MMSYSERR_NOERROR )
+                {
+                    result = paUnanticipatedHostError;
+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                    goto error;
+                }
+            }
+        }
+        stream->input.currentBufferIndex = 0;
+        stream->input.framesUsedInCurrentBuffer = 0;
+    }
+
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+    {
+        for( i=0; i<stream->output.deviceCount; ++i )
+        {
+            if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
+            {
+                result = paUnanticipatedHostError;
+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                goto error;
+            }
+        }
+
+        for( i=0; i<stream->output.bufferCount; ++i )
+        {
+            if( stream->primeStreamUsingCallback )
+            {
+
+                stream->output.framesUsedInCurrentBuffer = 0;
+                do{
+
+                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor,
+                            &timeInfo,
+                            paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0));
+
+                    if( stream->input.bufferCount > 0 )
+                        PaUtil_SetNoInput( &stream->bufferProcessor );
+
+                    PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+
+                    channel = 0;
+                    for( j=0; j<stream->output.deviceCount; ++j )
+                    {
+                        /* we have stored the number of channels in the buffer in dwUser */
+                        int channelCount = (int)stream->output.waveHeaders[j][i].dwUser;
+
+                        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+                                stream->output.waveHeaders[j][i].lpData +
+                                stream->output.framesUsedInCurrentBuffer * channelCount *
+                                stream->bufferProcessor.bytesPerHostOutputSample,
+                                channelCount );
+
+                        /* we have stored the number of channels in the buffer in dwUser */
+                        channel += channelCount;
+                    }
+
+                    callbackResult = paContinue;
+                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+                    stream->output.framesUsedInCurrentBuffer += framesProcessed;
+
+                    if( callbackResult != paContinue )
+                    {
+                        /** @todo fix this, what do we do if callback result is non-zero during stream
+                            priming?
+
+                            for complete: play out primed waveHeaders as usual
+                            for abort: clean up immediately.
+                       */
+                    }
+
+                }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer );
+
+            }
+            else
+            {
+                for( j=0; j<stream->output.deviceCount; ++j )
+                {
+                    ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength );
+                }
+            }   
+
+            /* we queue all channels of a single buffer frame (accross all
+                devices, because some multidevice multichannel drivers work
+                better this way */
+            for( j=0; j<stream->output.deviceCount; ++j )
+            {
+                mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) );
+                if( mmresult != MMSYSERR_NOERROR )
+                {
+                    result = paUnanticipatedHostError;
+                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                    goto error;
+                }
+            }
+        }
+        stream->output.currentBufferIndex = 0;
+        stream->output.framesUsedInCurrentBuffer = 0;
+    }
+
+
+    stream->isStopped = 0;
+    stream->isActive = 1;
+    stream->stopProcessing = 0;
+    stream->abortProcessing = 0;
+
+    result = ResetEventWithPaError( stream->input.bufferEvent );
+    if( result != paNoError ) goto error;
+
+    result = ResetEventWithPaError( stream->output.bufferEvent );
+    if( result != paNoError ) goto error;
+    
+    
+    if( stream->streamRepresentation.streamCallback )
+    {
+        /* callback stream */
+
+        result = ResetEventWithPaError( stream->abortEvent );
+        if( result != paNoError ) goto error;
+
+        /* Create thread that waits for audio buffers to be ready for processing. */
+        stream->processingThread = CREATE_THREAD;
+        if( !stream->processingThread )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+            goto error;
+        }
+
+        /** @todo could have mme specific stream parameters to allow the user
+            to set the callback thread priorities */
+        stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL;
+        stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL;
+
+        if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) )
+        {
+            result = paUnanticipatedHostError;
+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+            goto error;
+        }
+        stream->processingThreadPriority = stream->highThreadPriority;
+    }
+    else
+    {
+        /* blocking read/write stream */
+
+    }
+
+    if( PA_IS_INPUT_STREAM_(stream) )
+    {
+        for( i=0; i < stream->input.deviceCount; ++i )
+        {
+            mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] );
+            PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult));
+            if( mmresult != MMSYSERR_NOERROR )
+            {
+                result = paUnanticipatedHostError;
+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                goto error;
+            }
+        }
+    }
+
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+    {
+        for( i=0; i < stream->output.deviceCount; ++i )
+        {
+            if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
+            {
+                result = paUnanticipatedHostError;
+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                goto error;
+            }
+        }
+    }
+
+    return result;
+
+error:
+    /** @todo FIXME: implement recovery as best we can
+    This should involve rolling back to a state as-if this function had never been called
+    */
+    return result;
+}
+
+
+static PaError StopStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    int timeout;
+    DWORD waitResult;
+    MMRESULT mmresult;
+    signed int hostOutputBufferIndex;
+    unsigned int channel, waitCount, i;                  
+    
+    /** @todo
+        REVIEW: the error checking in this function needs review. the basic
+        idea is to return from this function in a known state - for example
+        there is no point avoiding calling waveInReset just because
+        the thread times out.
+    */
+
+    if( stream->processingThread )
+    {
+        /* callback stream */
+
+        /* Tell processing thread to stop generating more data and to let current data play out. */
+        stream->stopProcessing = 1;
+
+        /* Calculate timeOut longer than longest time it could take to return all buffers. */
+        timeout = (int)(stream->allBuffersDurationMs * 1.5);
+        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+            timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+
+        PA_DEBUG(("WinMME StopStream: waiting for background thread.\n"));
+
+        waitResult = WaitForSingleObject( stream->processingThread, timeout );
+        if( waitResult == WAIT_TIMEOUT )
+        {
+            /* try to abort */
+            stream->abortProcessing = 1;
+            SetEvent( stream->abortEvent );
+            waitResult = WaitForSingleObject( stream->processingThread, timeout );
+            if( waitResult == WAIT_TIMEOUT )
+            {
+                PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n"));
+                result = paTimedOut;
+            }
+        }
+
+        CloseHandle( stream->processingThread );
+        stream->processingThread = NULL;
+    }
+    else
+    {
+        /* blocking read / write stream */
+
+        if( PA_IS_OUTPUT_STREAM_(stream) )
+        {
+            if( stream->output.framesUsedInCurrentBuffer > 0 )
+            {
+                /* there are still unqueued frames in the current buffer, so flush them */
+
+                hostOutputBufferIndex = stream->output.currentBufferIndex;
+
+                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+                
+                channel = 0;
+                for( i=0; i<stream->output.deviceCount; ++i )
+                {
+                    /* we have stored the number of channels in the buffer in dwUser */
+                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+                                stream->output.framesUsedInCurrentBuffer * channelCount *
+                                stream->bufferProcessor.bytesPerHostOutputSample,
+                            channelCount );
+
+                    channel += channelCount;
+                }
+
+                PaUtil_ZeroOutput( &stream->bufferProcessor,
+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+                /* we send the entire buffer to the output devices, but we could
+                    just send a partial buffer, rather than zeroing the unused
+                    samples.
+                */
+                AdvanceToNextOutputBuffer( stream );
+            }
+            
+
+            timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1;
+            if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+                timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+
+            waitCount = 0;
+            while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount )
+            {
+                /* wait for MME to signal that a buffer is available */
+                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
+                if( waitResult == WAIT_FAILED )
+                {
+                    break;
+                }
+                else if( waitResult == WAIT_TIMEOUT )
+                {
+                    /* keep waiting */
+                }
+
+                ++waitCount;
+            }
+        }
+    }
+
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+    {
+        for( i =0; i < stream->output.deviceCount; ++i )
+        {
+            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
+            if( mmresult != MMSYSERR_NOERROR )
+            {
+                result = paUnanticipatedHostError;
+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+            }
+        }
+    }
+
+    if( PA_IS_INPUT_STREAM_(stream) )
+    {
+        for( i=0; i < stream->input.deviceCount; ++i )
+        {
+            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
+            if( mmresult != MMSYSERR_NOERROR )
+            {
+                result = paUnanticipatedHostError;
+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+            }
+        }
+    }
+
+    stream->isStopped = 1;
+    stream->isActive = 0;
+
+    return result;
+}
+
+
+static PaError AbortStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    int timeout;
+    DWORD waitResult;
+    MMRESULT mmresult;
+    unsigned int i;
+    
+    /** @todo
+        REVIEW: the error checking in this function needs review. the basic
+        idea is to return from this function in a known state - for example
+        there is no point avoiding calling waveInReset just because
+        the thread times out.
+    */
+
+    if( stream->processingThread )
+    {
+        /* callback stream */
+        
+        /* Tell processing thread to abort immediately */
+        stream->abortProcessing = 1;
+        SetEvent( stream->abortEvent );
+    }
+
+
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+    {
+        for( i =0; i < stream->output.deviceCount; ++i )
+        {
+            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
+            if( mmresult != MMSYSERR_NOERROR )
+            {
+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                return paUnanticipatedHostError;
+            }
+        }
+    }
+
+    if( PA_IS_INPUT_STREAM_(stream) )
+    {
+        for( i=0; i < stream->input.deviceCount; ++i )
+        {
+            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
+            if( mmresult != MMSYSERR_NOERROR )
+            {
+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                return paUnanticipatedHostError;
+            }
+        }
+    }
+
+
+    if( stream->processingThread )
+    {
+        /* callback stream */
+        
+        PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n"));
+
+        /* Calculate timeOut longer than longest time it could take to return all buffers. */
+        timeout = (int)(stream->allBuffersDurationMs * 1.5);
+        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+            timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+            
+        waitResult = WaitForSingleObject( stream->processingThread, timeout );
+        if( waitResult == WAIT_TIMEOUT )
+        {
+            PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n"));
+            return paTimedOut;
+        }
+
+        CloseHandle( stream->processingThread );
+        stream->processingThread = NULL;
+    }
+
+    stream->isStopped = 1;
+    stream->isActive = 0;
+
+    return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+    return stream->isStopped;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+    return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    (void) s; /* unused parameter */
+    
+    return PaUtil_GetTime();
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+    As separate stream interfaces are used for blocking and callback
+    streams, the following functions can be guaranteed to only be called
+    for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
+{
+    PaError result = paNoError;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    void *userBuffer;
+    unsigned long framesRead = 0;
+    unsigned long framesProcessed;
+    signed int hostInputBufferIndex;
+    DWORD waitResult;
+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+    unsigned int channel, i;
+    
+    if( PA_IS_INPUT_STREAM_(stream) )
+    {
+        /* make a local copy of the user buffer pointer(s). this is necessary
+            because PaUtil_CopyInput() advances these pointers every time
+            it is called.
+        */
+        if( stream->bufferProcessor.userInputIsInterleaved )
+        {
+            userBuffer = buffer;
+        }
+        else
+        {
+            userBuffer = (void*)alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
+            if( !userBuffer )
+                return paInsufficientMemory;
+            for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )
+                ((void**)userBuffer)[i] = ((void**)buffer)[i];
+        }
+        
+        do{
+            if( CurrentInputBuffersAreDone( stream ) )
+            {
+                if( NoBuffersAreQueued( &stream->input ) )
+                {
+                    /** @todo REVIEW: consider what to do if the input overflows.
+                        do we requeue all of the buffers? should we be running
+                        a thread to make sure they are always queued? 
+                        see: http://www.portaudio.com/trac/ticket/117
+                        */
+
+                    result = paInputOverflowed;
+                }
+
+                hostInputBufferIndex = stream->input.currentBufferIndex;
+
+                PaUtil_SetInputFrameCount( &stream->bufferProcessor,
+                        stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer );
+                
+                channel = 0;
+                for( i=0; i<stream->input.deviceCount; ++i )
+                {
+                    /* we have stored the number of channels in the buffer in dwUser */
+                    int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+
+                    PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
+                            stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
+                                stream->input.framesUsedInCurrentBuffer * channelCount *
+                                stream->bufferProcessor.bytesPerHostInputSample,
+                            channelCount );
+
+                    channel += channelCount;
+                }
+                
+                framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead );
+
+                stream->input.framesUsedInCurrentBuffer += framesProcessed;
+                if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
+                {
+                    result = AdvanceToNextInputBuffer( stream );
+                    if( result != paNoError )
+                        break;
+                }
+
+                framesRead += framesProcessed;      
+
+            }else{
+                /* wait for MME to signal that a buffer is available */
+                waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout );
+                if( waitResult == WAIT_FAILED )
+                {
+                    result = paUnanticipatedHostError;
+                    break;
+                }
+                else if( waitResult == WAIT_TIMEOUT )
+                {
+                    /* if a timeout is encountered, continue,
+                        perhaps we should give up eventually
+                    */
+                }         
+            }
+        }while( framesRead < frames );
+    }
+    else
+    {
+        result = paCanNotReadFromAnOutputOnlyStream;
+    }
+
+    return result;
+}
+
+
+static PaError WriteStream( PaStream* s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    PaError result = paNoError;
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    const void *userBuffer;
+    unsigned long framesWritten = 0;
+    unsigned long framesProcessed;
+    signed int hostOutputBufferIndex;
+    DWORD waitResult;
+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+    unsigned int channel, i;
+
+        
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+    {
+        /* make a local copy of the user buffer pointer(s). this is necessary
+            because PaUtil_CopyOutput() advances these pointers every time
+            it is called.
+        */
+        if( stream->bufferProcessor.userOutputIsInterleaved )
+        {
+            userBuffer = buffer;
+        }
+        else
+        {
+            userBuffer = (const void*)alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
+            if( !userBuffer )
+                return paInsufficientMemory;
+            for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )
+                ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
+        }
+
+        do{
+            if( CurrentOutputBuffersAreDone( stream ) )
+            {
+                if( NoBuffersAreQueued( &stream->output ) )
+                {
+                    /** @todo REVIEW: consider what to do if the output
+                    underflows. do we requeue all the existing buffers with
+                    zeros? should we run a separate thread to keep the buffers
+                    enqueued at all times? 
+                    see: http://www.portaudio.com/trac/ticket/117
+                    */
+
+                    result = paOutputUnderflowed;
+                }
+
+                hostOutputBufferIndex = stream->output.currentBufferIndex;
+
+                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+                
+                channel = 0;
+                for( i=0; i<stream->output.deviceCount; ++i )
+                {
+                    /* we have stored the number of channels in the buffer in dwUser */
+                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+                                stream->output.framesUsedInCurrentBuffer * channelCount *
+                                stream->bufferProcessor.bytesPerHostOutputSample,
+                            channelCount );
+
+                    channel += channelCount;
+                }
+                
+                framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten );
+
+                stream->output.framesUsedInCurrentBuffer += framesProcessed;
+                if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
+                {
+                    result = AdvanceToNextOutputBuffer( stream );
+                    if( result != paNoError )
+                        break;
+                }
+
+                framesWritten += framesProcessed;
+            }
+            else
+            {
+                /* wait for MME to signal that a buffer is available */
+                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
+                if( waitResult == WAIT_FAILED )
+                {
+                    result = paUnanticipatedHostError;
+                    break;
+                }
+                else if( waitResult == WAIT_TIMEOUT )
+                {
+                    /* if a timeout is encountered, continue,
+                        perhaps we should give up eventually
+                    */
+                }             
+            }        
+        }while( framesWritten < frames );
+    }
+    else
+    {
+        result = paCanNotWriteToAnInputOnlyStream;
+    }
+    
+    return result;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    
+    if( PA_IS_INPUT_STREAM_(stream) )
+        return GetAvailableFrames( &stream->input );
+    else
+        return paCanNotReadFromAnOutputOnlyStream;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaWinMmeStream *stream = (PaWinMmeStream*)s;
+    
+    if( PA_IS_OUTPUT_STREAM_(stream) )
+        return GetAvailableFrames( &stream->output );
+    else
+        return paCanNotWriteToAnInputOnlyStream;
+}
+
+
+/* NOTE: the following functions are MME-stream specific, and are called directly
+    by client code. We need to check for many more error conditions here because
+    we don't have the benefit of pa_front.c's parameter checking.
+*/
+
+static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s )
+{
+    PaError result;
+    PaUtilHostApiRepresentation *hostApi;
+    PaWinMmeHostApiRepresentation *winMmeHostApi;
+    
+    result = PaUtil_ValidateStreamPointer( s );
+    if( result != paNoError )
+        return result;
+
+    result = PaUtil_GetHostApiRepresentation( &hostApi, paMME );
+    if( result != paNoError )
+        return result;
+
+    winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+    
+    /* note, the following would be easier if there was a generic way of testing
+        that a stream belongs to a specific host API */
+    
+    if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface
+            || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface )
+    {
+        /* s is a WinMME stream */
+        *stream = (PaWinMmeStream *)s;
+        return paNoError;
+    }
+    else
+    {
+        return paIncompatibleStreamHostApi;
+    }
+}
+
+
+int PaWinMME_GetStreamInputHandleCount( PaStream* s )
+{
+    PaWinMmeStream *stream;
+    PaError result = GetWinMMEStreamPointer( &stream, s );
+
+    if( result == paNoError )
+        return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0;
+    else
+        return result;
+}
+
+
+HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex )
+{
+    PaWinMmeStream *stream;
+    PaError result = GetWinMMEStreamPointer( &stream, s );
+
+    if( result == paNoError
+            && PA_IS_INPUT_STREAM_(stream)
+            && handleIndex >= 0
+            && (unsigned int)handleIndex < stream->input.deviceCount )
+        return ((HWAVEIN*)stream->input.waveHandles)[handleIndex];
+    else
+        return 0;
+}
+
+
+int PaWinMME_GetStreamOutputHandleCount( PaStream* s)
+{
+    PaWinMmeStream *stream;
+    PaError result = GetWinMMEStreamPointer( &stream, s );
+
+    if( result == paNoError )
+        return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0;
+    else
+        return result;
+}
+
+
+HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex )
+{
+    PaWinMmeStream *stream;
+    PaError result = GetWinMMEStreamPointer( &stream, s );
+
+    if( result == paNoError
+            && PA_IS_OUTPUT_STREAM_(stream)
+            && handleIndex >= 0
+            && (unsigned int)handleIndex < stream->output.deviceCount )
+        return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex];
+    else
+        return 0;
+}
diff --git a/portaudio/src/os/unix/pa_unix_hostapis.c b/portaudio/src/os/unix/pa_unix_hostapis.c
new file mode 100644 (file)
index 0000000..a9b4a05
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library UNIX initialization table
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+
+#include "pa_hostapi.h"
+
+PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+/* Added for IRIX, Pieter, oct 2, 2003: */
+PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+/* Linux AudioScience HPI */
+PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+/** Note that on Linux, ALSA is placed before OSS so that the former is preferred over the latter.
+ */
+
+PaUtilHostApiInitializer *paHostApiInitializers[] =
+    {
+#ifdef __linux__
+
+#if PA_USE_ALSA
+        PaAlsa_Initialize,
+#endif
+
+#if PA_USE_OSS
+        PaOSS_Initialize,
+#endif
+
+#else   /* __linux__ */
+
+#if PA_USE_OSS
+        PaOSS_Initialize,
+#endif
+
+#if PA_USE_ALSA
+        PaAlsa_Initialize,
+#endif
+
+#endif  /* __linux__ */
+
+#if PA_USE_JACK
+        PaJack_Initialize,
+#endif
+                    /* Added for IRIX, Pieter, oct 2, 2003: */
+#if PA_USE_SGI 
+        PaSGI_Initialize,
+#endif
+
+#if PA_USE_ASIHPI
+        PaAsiHpi_Initialize,
+#endif
+
+#if PA_USE_COREAUDIO
+        PaMacCore_Initialize,
+#endif
+
+#if PA_USE_SKELETON
+        PaSkeleton_Initialize,
+#endif
+
+        0   /* NULL terminated array */
+    };
diff --git a/portaudio/src/os/unix/pa_unix_util.c b/portaudio/src/os/unix/pa_unix_util.c
new file mode 100644 (file)
index 0000000..17664ea
--- /dev/null
@@ -0,0 +1,710 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * UNIX platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/time.h>
+#include <assert.h>
+#include <string.h> /* For memset */
+#include <math.h>
+#include <errno.h>
+
+#if defined(__APPLE__) && !defined(HAVE_MACH_ABSOLUTE_TIME)
+#define HAVE_MACH_ABSOLUTE_TIME
+#endif
+#ifdef HAVE_MACH_ABSOLUTE_TIME
+#include <mach/mach_time.h>
+#endif
+
+#include "pa_util.h"
+#include "pa_unix_util.h"
+#include "pa_debugprint.h"
+
+/*
+   Track memory allocations to avoid leaks.
+ */
+
+#if PA_TRACK_MEMORY
+static int numAllocations_ = 0;
+#endif
+
+
+void *PaUtil_AllocateMemory( long size )
+{
+    void *result = malloc( size );
+
+#if PA_TRACK_MEMORY
+    if( result != NULL ) numAllocations_ += 1;
+#endif
+    return result;
+}
+
+
+void PaUtil_FreeMemory( void *block )
+{
+    if( block != NULL )
+    {
+        free( block );
+#if PA_TRACK_MEMORY
+        numAllocations_ -= 1;
+#endif
+
+    }
+}
+
+
+int PaUtil_CountCurrentlyAllocatedBlocks( void )
+{
+#if PA_TRACK_MEMORY
+    return numAllocations_;
+#else
+    return 0;
+#endif
+}
+
+
+void Pa_Sleep( long msec )
+{
+#ifdef HAVE_NANOSLEEP
+    struct timespec req = {0}, rem = {0};
+    PaTime time = msec / 1.e3;
+    req.tv_sec = (time_t)time;
+    assert(time - req.tv_sec < 1.0);
+    req.tv_nsec = (long)((time - req.tv_sec) * 1.e9);
+    nanosleep(&req, &rem);
+    /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */
+#else
+    while( msec > 999 )     /* For OpenBSD and IRIX, argument */
+        {                   /* to usleep must be < 1000000.   */
+        usleep( 999000 );
+        msec -= 999;
+        }
+    usleep( msec * 1000 );
+#endif
+}
+
+#ifdef HAVE_MACH_ABSOLUTE_TIME
+/*
+    Discussion on the CoreAudio mailing list suggests that calling
+    gettimeofday (or anything else in the BSD layer) is not real-time
+    safe, so we use mach_absolute_time on OSX. This implementation is 
+    based on these two links:
+
+    Technical Q&A QA1398 - Mach Absolute Time Units
+    http://developer.apple.com/mac/library/qa/qa2004/qa1398.html
+
+    Tutorial: Performance and Time.
+    http://www.macresearch.org/tutorial_performance_and_time
+*/
+
+/* Scaler to convert the result of mach_absolute_time to seconds */
+static double machSecondsConversionScaler_ = 0.0; 
+#endif
+
+void PaUtil_InitializeClock( void )
+{
+#ifdef HAVE_MACH_ABSOLUTE_TIME
+    mach_timebase_info_data_t info;
+    kern_return_t err = mach_timebase_info( &info );
+    if( err == 0  )
+        machSecondsConversionScaler_ = 1e-9 * (double) info.numer / (double) info.denom;
+#endif
+}
+
+
+PaTime PaUtil_GetTime( void )
+{
+#ifdef HAVE_MACH_ABSOLUTE_TIME
+    return mach_absolute_time() * machSecondsConversionScaler_;
+#elif defined(HAVE_CLOCK_GETTIME)
+    struct timespec tp;
+    clock_gettime(CLOCK_REALTIME, &tp);
+    return (PaTime)(tp.tv_sec + tp.tv_nsec * 1e-9);
+#else
+    struct timeval tv;
+    gettimeofday( &tv, NULL );
+    return (PaTime) tv.tv_usec * 1e-6 + tv.tv_sec;
+#endif
+}
+
+PaError PaUtil_InitializeThreading( PaUtilThreading *threading )
+{
+    (void) paUtilErr_;
+    return paNoError;
+}
+
+void PaUtil_TerminateThreading( PaUtilThreading *threading )
+{
+}
+
+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data )
+{
+    pthread_create( &threading->callbackThread, NULL, threadRoutine, data );
+    return paNoError;
+}
+
+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult )
+{
+    PaError result = paNoError;
+    void *pret;
+
+    if( exitResult )
+        *exitResult = paNoError;
+
+    /* If pthread_cancel is not supported (Android platform) whole this function can lead to indefinite waiting if 
+       working thread (callbackThread) has'n received any stop signals from outside, please keep 
+       this in mind when considering using PaUtil_CancelThreading
+    */
+#ifdef PTHREAD_CANCELED
+    /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
+    if( !wait )
+        pthread_cancel( threading->callbackThread );   /* XXX: Safe to call this if the thread has exited on its own? */
+#endif
+    pthread_join( threading->callbackThread, &pret );
+
+#ifdef PTHREAD_CANCELED
+    if( pret && PTHREAD_CANCELED != pret )
+#else
+    /* !wait means the thread may have been canceled */
+    if( pret && wait )
+#endif
+    {
+        if( exitResult )
+            *exitResult = *(PaError *) pret;
+        free( pret );
+    }
+
+    return result;
+}
+
+/* Threading */
+/* paUnixMainThread 
+ * We have to be a bit careful with defining this global variable,
+ * as explained below. */
+#ifdef __APPLE__
+/* apple/gcc has a "problem" with global vars and dynamic libs.
+   Initializing it seems to fix the problem.
+   Described a bit in this thread:
+   http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html
+*/
+pthread_t paUnixMainThread = 0;
+#else
+/*pthreads are opaque. We don't know that asigning it an int value
+  always makes sense, so we don't initialize it unless we have to.*/
+pthread_t paUnixMainThread = 0;
+#endif
+
+PaError PaUnixThreading_Initialize()
+{
+    paUnixMainThread = pthread_self();
+    return paNoError;
+}
+
+static PaError BoostPriority( PaUnixThread* self )
+{
+    PaError result = paNoError;
+    struct sched_param spm = { 0 };
+    /* Priority should only matter between contending FIFO threads? */
+    spm.sched_priority = 1;
+
+    assert( self );
+
+    if( pthread_setschedparam( self->thread, SCHED_FIFO, &spm ) != 0 )
+    {
+        PA_UNLESS( errno == EPERM, paInternalError );  /* Lack permission to raise priority */
+        PA_DEBUG(( "Failed bumping priority\n" ));
+        result = 0;
+    }
+    else
+    {
+        result = 1; /* Success */
+    }
+error:
+    return result;
+}
+
+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,
+        int rtSched )
+{
+    PaError result = paNoError;
+    pthread_attr_t attr;
+    int started = 0;
+
+    memset( self, 0, sizeof (PaUnixThread) );
+    PaUnixMutex_Initialize( &self->mtx );
+    PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 );
+
+    self->parentWaiting = 0 != waitForChild;
+
+    /* Spawn thread */
+
+/* Temporarily disabled since we should test during configuration for presence of required mman.h header */
+#if 0
+#if defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1)
+    if( rtSched )
+    {
+        if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 )
+        {
+            int savedErrno = errno;             /* In case errno gets overwritten */
+            assert( savedErrno != EINVAL );     /* Most likely a programmer error */
+            PA_UNLESS( (savedErrno == EPERM), paInternalError );
+            PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ ));
+        }
+        else
+            PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ ));
+    }
+#endif
+#endif
+
+    PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
+    /* Priority relative to other processes */
+    PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );   
+
+    PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError );
+    started = 1;
+
+    if( rtSched )
+    {
+#if 0
+        if( self->useWatchdog )
+        {
+            int err;
+            struct sched_param wdSpm = { 0 };
+            /* Launch watchdog, watchdog sets callback thread priority */
+            int prio = PA_MIN( self->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) );
+            wdSpm.sched_priority = prio;
+
+            PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
+            PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError );
+            PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );
+            PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError );
+            PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError );
+            if( (err = pthread_create( &self->watchdogThread, &attr, &WatchdogFunc, self )) )
+            {
+                PA_UNLESS( err == EPERM, paInternalError );
+                /* Permission error, go on without realtime privileges */
+                PA_DEBUG(( "Failed bumping priority\n" ));
+            }
+            else
+            {
+                int policy;
+                self->watchdogRunning = 1;
+                PA_ENSURE_SYSTEM( pthread_getschedparam( self->watchdogThread, &policy, &wdSpm ), 0 );
+                /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */
+                if( wdSpm.sched_priority != prio )
+                {
+                    PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority ));
+                    PA_ENSURE( paInternalError );
+                }
+            }
+        }
+        else
+#endif
+            PA_ENSURE( BoostPriority( self ) );
+
+        {
+            int policy;
+            struct sched_param spm;
+            pthread_getschedparam(self->thread, &policy, &spm);
+        }
+    }
+    
+    if( self->parentWaiting )
+    {
+        PaTime till;
+        struct timespec ts;
+        int res = 0;
+        PaTime now;
+
+        PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+
+        /* Wait for stream to be started */
+        now = PaUtil_GetTime();
+        till = now + waitForChild;
+
+        while( self->parentWaiting && !res )
+        {
+            if( waitForChild > 0 )
+            {
+                ts.tv_sec = (time_t) floor( till );
+                ts.tv_nsec = (long) ((till - floor( till )) * 1e9);
+                res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts );
+            }
+            else
+            {
+                res = pthread_cond_wait( &self->cond, &self->mtx.mtx );
+            }
+        }
+
+        PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
+
+        PA_UNLESS( !res || ETIMEDOUT == res, paInternalError );
+        PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now ));
+        if( ETIMEDOUT == res )
+        {
+            PA_ENSURE( paTimedOut );
+        }
+    }
+
+end:
+    return result;
+error:
+    if( started )
+    {
+        PaUnixThread_Terminate( self, 0, NULL );
+    }
+
+    goto end;
+}
+
+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult )
+{
+    PaError result = paNoError;
+    void* pret;
+
+    if( exitResult )
+    {
+        *exitResult = paNoError;
+    }
+#if 0
+    if( watchdogExitResult )
+        *watchdogExitResult = paNoError;
+
+    if( th->watchdogRunning )
+    {
+        pthread_cancel( th->watchdogThread );
+        PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 );
+
+        if( pret && pret != PTHREAD_CANCELED )
+        {
+            if( watchdogExitResult )
+                *watchdogExitResult = *(PaError *) pret;
+            free( pret );
+        }
+    }
+#endif
+
+    /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
+    /* TODO: Make join time out */
+    self->stopRequested = wait;
+    if( !wait )
+    {
+        PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread ));
+        /* XXX: Safe to call this if the thread has exited on its own? */
+#ifdef PTHREAD_CANCELED
+        pthread_cancel( self->thread );
+#endif
+    }
+    PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread ));
+    PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 );
+
+#ifdef PTHREAD_CANCELED
+    if( pret && PTHREAD_CANCELED != pret )
+#else
+    /* !wait means the thread may have been canceled */
+    if( pret && wait )
+#endif
+    {
+        if( exitResult )
+        {
+            *exitResult = *(PaError*)pret;
+        }
+        free( pret );
+    }
+
+error:
+    PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError );
+    PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 );
+
+    return result;
+}
+
+PaError PaUnixThread_PrepareNotify( PaUnixThread* self )
+{
+    PaError result = paNoError;
+    PA_UNLESS( self->parentWaiting, paInternalError );
+
+    PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+    self->locked = 1;
+
+error:
+    return result;
+}
+
+PaError PaUnixThread_NotifyParent( PaUnixThread* self )
+{
+    PaError result = paNoError;
+    PA_UNLESS( self->parentWaiting, paInternalError );
+
+    if( !self->locked )
+    {
+        PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+        self->locked = 1;
+    }
+    self->parentWaiting = 0;
+    pthread_cond_signal( &self->cond );
+    PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
+    self->locked = 0;
+
+error:
+    return result;
+}
+
+int PaUnixThread_StopRequested( PaUnixThread* self )
+{
+    return self->stopRequested;
+}
+
+PaError PaUnixMutex_Initialize( PaUnixMutex* self )
+{
+    PaError result = paNoError;
+    PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 );
+    return result;
+}
+
+PaError PaUnixMutex_Terminate( PaUnixMutex* self )
+{
+    PaError result = paNoError;
+    PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 );
+    return result;
+}
+
+/** Lock mutex.
+ *
+ * We're disabling thread cancellation while the thread is holding a lock, so mutexes are 
+ * properly unlocked at termination time.
+ */
+PaError PaUnixMutex_Lock( PaUnixMutex* self )
+{
+    PaError result = paNoError;
+    
+#ifdef PTHREAD_CANCEL
+       int oldState;
+    PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 );
+#endif
+    PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 );
+
+error:
+    return result;
+}
+
+/** Unlock mutex.
+ *
+ * Thread cancellation is enabled again after the mutex is properly unlocked.
+ */
+PaError PaUnixMutex_Unlock( PaUnixMutex* self )
+{
+    PaError result = paNoError;
+
+    PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 );
+#ifdef PTHREAD_CANCEL
+       int oldState;
+    PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 );
+#endif
+
+error:
+    return result;
+}
+
+
+#if 0
+static void OnWatchdogExit( void *userData )
+{
+    PaAlsaThreading *th = (PaAlsaThreading *) userData;
+    struct sched_param spm = { 0 };
+    assert( th );
+
+    PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 );    /* Lower before exiting */
+    PA_DEBUG(( "Watchdog exiting\n" ));
+}
+
+static void *WatchdogFunc( void *userData )
+{
+    PaError result = paNoError, *pres = NULL;
+    int err;
+    PaAlsaThreading *th = (PaAlsaThreading *) userData;
+    unsigned intervalMsec = 500;
+    const PaTime maxSeconds = 3.;   /* Max seconds between callbacks */
+    PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed;
+    double cpuLoad, avgCpuLoad = 0.;
+    int throttled = 0;
+
+    assert( th );
+
+    /* Execute OnWatchdogExit when exiting */
+    pthread_cleanup_push( &OnWatchdogExit, th );
+
+    /* Boost priority of callback thread */
+    PA_ENSURE( result = BoostPriority( th ) );
+    if( !result )
+    {
+        /* Boost failed, might as well exit */
+        pthread_exit( NULL );
+    }
+
+    cpuTimeThen = th->callbackCpuTime;
+    {
+        int policy;
+        struct sched_param spm = { 0 };
+        pthread_getschedparam( pthread_self(), &policy, &spm );
+        PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority ));
+    }
+
+    while( 1 )
+    {
+        double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff;
+        
+        /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */
+        pthread_testcancel();
+        Pa_Sleep( intervalMsec );
+        pthread_testcancel();
+
+        if( PaUtil_GetTime() - th->callbackTime > maxSeconds )
+        {
+            PA_DEBUG(( "Watchdog: Terminating callback thread\n" ));
+            /* Tell thread to terminate */
+            err = pthread_kill( th->callbackThread, SIGKILL );
+            pthread_exit( NULL );
+        }
+
+        PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) ));
+
+        /* Check if we should throttle, or unthrottle :P */
+        cpuTimeNow = th->callbackCpuTime;
+        cpuTimeElapsed = cpuTimeNow - cpuTimeThen;
+        cpuTimeThen = cpuTimeNow;
+
+        timeNow = PaUtil_GetTime();
+        timeElapsed = timeNow - timeThen;
+        timeThen = timeNow;
+        cpuLoad = cpuTimeElapsed / timeElapsed;
+        avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1;
+        /*
+        if( throttled )
+            PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed ));
+            */
+        if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 )
+        {
+            static int policy;
+            static struct sched_param spm = { 0 };
+            static const struct sched_param defaultSpm = { 0 };
+            PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority ));
+
+            pthread_getschedparam( th->callbackThread, &policy, &spm );
+            if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) )
+            {
+                throttled = 1;
+            }
+            else
+                PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) ));
+
+            /* Give other processes a go, before raising priority again */
+            PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime ));
+            Pa_Sleep( th->throttledSleepTime );
+
+            /* Reset callback priority */
+            if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 )
+            {
+                PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) ));
+            }
+
+            if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 )
+                intervalMsec = 50;
+            else
+                intervalMsec = 100;
+
+            /*
+            lowpassCoeff = .97;
+            lowpassCoeff1 = .99999 - lowpassCoeff;
+            */
+        }
+        else if( throttled && avgCpuLoad < .8 )
+        {
+            intervalMsec = 500;
+            throttled = 0;
+
+            /*
+            lowpassCoeff = .9;
+            lowpassCoeff1 = .99999 - lowpassCoeff;
+            */
+        }
+    }
+
+    pthread_cleanup_pop( 1 );   /* Execute cleanup on exit */
+
+error:
+    /* Shouldn't get here in the normal case */
+
+    /* Pass on error code */
+    pres = malloc( sizeof (PaError) );
+    *pres = result;
+    
+    pthread_exit( pres );
+}
+
+static void CallbackUpdate( PaAlsaThreading *th )
+{
+    th->callbackTime = PaUtil_GetTime();
+    th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer );
+}
+
+/*
+static void *CanaryFunc( void *userData )
+{
+    const unsigned intervalMsec = 1000;
+    PaUtilThreading *th = (PaUtilThreading *) userData;
+
+    while( 1 )
+    {
+        th->canaryTime = PaUtil_GetTime();
+
+        pthread_testcancel();
+        Pa_Sleep( intervalMsec );
+    }
+
+    pthread_exit( NULL );
+}
+*/
+#endif
diff --git a/portaudio/src/os/unix/pa_unix_util.h b/portaudio/src/os/unix/pa_unix_util.h
new file mode 100644 (file)
index 0000000..d73c99c
--- /dev/null
@@ -0,0 +1,224 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * UNIX platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+
+#ifndef PA_UNIX_UTIL_H
+#define PA_UNIX_UTIL_H
+
+#include "pa_cpuload.h"
+#include <assert.h>
+#include <pthread.h>
+#include <signal.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#define PA_MIN(x,y) ( (x) < (y) ? (x) : (y) )
+#define PA_MAX(x,y) ( (x) > (y) ? (x) : (y) )
+
+/* Utilize GCC branch prediction for error tests */
+#if defined __GNUC__ && __GNUC__ >= 3
+#define UNLIKELY(expr) __builtin_expect( (expr), 0 )
+#else
+#define UNLIKELY(expr) (expr)
+#endif
+
+#define STRINGIZE_HELPER(expr) #expr
+#define STRINGIZE(expr) STRINGIZE_HELPER(expr)
+
+#define PA_UNLESS(expr, code) \
+    do { \
+        if( UNLIKELY( (expr) == 0 ) ) \
+        { \
+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = (code); \
+            goto error; \
+        } \
+    } while (0);
+
+static PaError paUtilErr_;          /* Used with PA_ENSURE */
+
+/* Check PaError */
+#define PA_ENSURE(expr) \
+    do { \
+        if( UNLIKELY( (paUtilErr_ = (expr)) < paNoError ) ) \
+        { \
+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+            result = paUtilErr_; \
+            goto error; \
+        } \
+    } while (0);
+
+#define PA_ASSERT_CALL(expr, success) \
+    paUtilErr_ = (expr); \
+    assert( success == paUtilErr_ );
+
+#define PA_ENSURE_SYSTEM(expr, success) \
+    do { \
+        if( UNLIKELY( (paUtilErr_ = (expr)) != success ) ) \
+        { \
+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+            if( pthread_equal(pthread_self(), paUnixMainThread) ) \
+            { \
+                PaUtil_SetLastHostErrorInfo( paALSA, paUtilErr_, strerror( paUtilErr_ ) ); \
+            } \
+            PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
+            result = paUnanticipatedHostError; \
+            goto error; \
+        } \
+    } while( 0 );
+
+typedef struct {
+    pthread_t callbackThread;
+} PaUtilThreading;
+
+PaError PaUtil_InitializeThreading( PaUtilThreading *threading );
+void PaUtil_TerminateThreading( PaUtilThreading *threading );
+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data );
+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult );
+
+/* State accessed by utility functions */
+
+/*
+void PaUnix_SetRealtimeScheduling( int rt );
+
+void PaUtil_InitializeThreading( PaUtilThreading *th, PaUtilCpuLoadMeasurer *clm );
+
+PaError PaUtil_CreateCallbackThread( PaUtilThreading *th, void *(*CallbackThreadFunc)( void * ), PaStream *s );
+
+PaError PaUtil_KillCallbackThread( PaUtilThreading *th, PaError *exitResult );
+
+void PaUtil_CallbackUpdate( PaUtilThreading *th );
+*/
+
+extern pthread_t paUnixMainThread;
+
+typedef struct
+{
+    pthread_mutex_t mtx;
+} PaUnixMutex;
+
+PaError PaUnixMutex_Initialize( PaUnixMutex* self );
+PaError PaUnixMutex_Terminate( PaUnixMutex* self );
+PaError PaUnixMutex_Lock( PaUnixMutex* self );
+PaError PaUnixMutex_Unlock( PaUnixMutex* self );
+
+typedef struct
+{
+    pthread_t thread;
+    int parentWaiting;
+    int stopRequested;
+    int locked;
+    PaUnixMutex mtx;
+    pthread_cond_t cond;
+    volatile sig_atomic_t stopRequest;
+} PaUnixThread;
+
+/** Initialize global threading state.
+ */
+PaError PaUnixThreading_Initialize();
+
+/** Perish, passing on eventual error code.
+ *
+ * A thin wrapper around pthread_exit, will automatically pass on any error code to the joining thread.
+ * If the result indicates an error, i.e. it is not equal to paNoError, this function will automatically
+ * allocate a pointer so the error is passed on with pthread_exit. If the result indicates that all is
+ * well however, only a NULL pointer will be handed to pthread_exit. Thus, the joining thread should
+ * check whether a non-NULL result pointer is obtained from pthread_join and make sure to free it.
+ * @param result: The error code to pass on to the joining thread.
+ */
+#define PaUnixThreading_EXIT(result) \
+    do { \
+        PaError* pres = NULL; \
+        if( paNoError != (result) ) \
+        { \
+            pres = malloc( sizeof (PaError) ); \
+            *pres = (result); \
+        } \
+        pthread_exit( pres ); \
+    } while (0);
+
+/** Spawn a thread.
+ *
+ * Intended for spawning the callback thread from the main thread. This function can even block (for a certain
+ * time or indefinitely) untill notified by the callback thread (using PaUnixThread_NotifyParent), which can be
+ * useful in order to make sure that callback has commenced before returning from Pa_StartStream.
+ * @param threadFunc: The function to be executed in the child thread.
+ * @param waitForChild: If not 0, wait for child thread to call PaUnixThread_NotifyParent. Less than 0 means
+ * wait for ever, greater than 0 wait for the specified time.
+ * @param rtSched: Enable realtime scheduling?
+ * @return: If timed out waiting on child, paTimedOut.
+ */
+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,
+        int rtSched );
+
+/** Terminate thread.
+ *
+ * @param wait: If true, request that background thread stop and wait untill it does, else cancel it.
+ * @param exitResult: If non-null this will upon return contain the exit status of the thread.
+ */
+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult );
+
+/** Prepare to notify waiting parent thread.
+ *
+ * An internal lock must be held before the parent is notified in PaUnixThread_NotifyParent, call this to
+ * acquire it beforehand.
+ * @return: If parent is not waiting, paInternalError.
+ */
+PaError PaUnixThread_PrepareNotify( PaUnixThread* self );
+
+/** Notify waiting parent thread.
+ *
+ * @return: If parent timed out waiting, paTimedOut. If parent was never waiting, paInternalError.
+ */
+PaError PaUnixThread_NotifyParent( PaUnixThread* self );
+
+/** Has the parent thread requested this thread to stop?
+ */
+int PaUnixThread_StopRequested( PaUnixThread* self );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif
diff --git a/portaudio/src/os/win/pa_win_coinitialize.c b/portaudio/src/os/win/pa_win_coinitialize.c
new file mode 100644 (file)
index 0000000..c4c6dde
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * Microsoft COM initialization routines
+ * Copyright (c) 1999-2011 Ross Bencina, Dmitry Kostjuchenko
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2011 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ @brief Microsoft COM initialization routines.
+*/
+
+#include <windows.h>
+#include <objbase.h>
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_debugprint.h"
+
+#include "pa_win_coinitialize.h"
+
+
+#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) && !defined(_WIN32_WCE) && !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)) /* MSC version 6 and above */
+#pragma comment( lib, "ole32.lib" )
+#endif
+
+
+/* use some special bit patterns here to try to guard against uninitialized memory errors */
+#define PAWINUTIL_COM_INITIALIZED       (0xb38f)
+#define PAWINUTIL_COM_NOT_INITIALIZED   (0xf1cd)
+
+
+PaError PaWinUtil_CoInitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult )
+{
+    HRESULT hr;
+
+    comInitializationResult->state = PAWINUTIL_COM_NOT_INITIALIZED;
+
+    /*
+        If COM is already initialized CoInitialize will either return
+        FALSE, or RPC_E_CHANGED_MODE if it was initialised in a different
+        threading mode. In either case we shouldn't consider it an error
+        but we need to be careful to not call CoUninitialize() if 
+        RPC_E_CHANGED_MODE was returned.
+    */
+
+#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY != WINAPI_FAMILY_APP)
+    hr = CoInitialize(0); /* use legacy-safe equivalent to CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) */
+#else
+       hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+#endif
+    if( FAILED(hr) && hr != RPC_E_CHANGED_MODE )
+    {
+        PA_DEBUG(("CoInitialize(0) failed. hr=%d\n", hr));
+
+        if( hr == E_OUTOFMEMORY )
+            return paInsufficientMemory;
+
+        {
+            char *lpMsgBuf;
+            FormatMessage(
+                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+                NULL,
+                hr,
+                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                (LPTSTR) &lpMsgBuf,
+                0,
+                NULL
+            );
+            PaUtil_SetLastHostErrorInfo( hostApiType, hr, lpMsgBuf );
+            LocalFree( lpMsgBuf );
+        }
+
+        return paUnanticipatedHostError;
+    }
+
+    if( hr != RPC_E_CHANGED_MODE )
+    {
+        comInitializationResult->state = PAWINUTIL_COM_INITIALIZED;
+
+        /*
+            Memorize calling thread id and report warning on Uninitialize if 
+            calling thread is different as CoInitialize must match CoUninitialize 
+            in the same thread.
+        */
+        comInitializationResult->initializingThreadId = GetCurrentThreadId();
+    }
+
+    return paNoError;
+}
+
+
+void PaWinUtil_CoUninitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult )
+{
+    if( comInitializationResult->state != PAWINUTIL_COM_NOT_INITIALIZED
+            && comInitializationResult->state != PAWINUTIL_COM_INITIALIZED ){
+    
+        PA_DEBUG(("ERROR: PaWinUtil_CoUninitialize called without calling PaWinUtil_CoInitialize\n"));
+    }
+
+    if( comInitializationResult->state == PAWINUTIL_COM_INITIALIZED )
+    {
+        DWORD currentThreadId = GetCurrentThreadId();
+               if( comInitializationResult->initializingThreadId != currentThreadId )
+               {
+                       PA_DEBUG(("ERROR: failed PaWinUtil_CoUninitialize calling thread[%d] does not match initializing thread[%d]\n",
+                               currentThreadId, comInitializationResult->initializingThreadId));
+               }
+               else
+               {
+                       CoUninitialize();
+
+            comInitializationResult->state = PAWINUTIL_COM_NOT_INITIALIZED;
+               }
+    }
+}
\ No newline at end of file
diff --git a/portaudio/src/os/win/pa_win_coinitialize.h b/portaudio/src/os/win/pa_win_coinitialize.h
new file mode 100644 (file)
index 0000000..687ab83
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Microsoft COM initialization routines
+ * Copyright (c) 1999-2011 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ @brief Microsoft COM initialization routines.
+*/
+
+#ifndef PA_WIN_COINITIALIZE_H
+#define PA_WIN_COINITIALIZE_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/**
+ @brief Data type used to hold the result of an attempt to initialize COM
+    using PaWinUtil_CoInitialize. Must be retained between a call to 
+    PaWinUtil_CoInitialize and a matching call to PaWinUtil_CoUninitialize.
+*/
+typedef struct PaWinUtilComInitializationResult{
+    int state;
+    int initializingThreadId;
+} PaWinUtilComInitializationResult;
+
+
+/**
+ @brief Initialize Microsoft COM subsystem on the current thread.
+
+ @param hostApiType the host API type id of the caller. Used for error reporting.
+
+ @param comInitializationResult An output parameter. The value pointed to by 
+        this parameter stores information required by PaWinUtil_CoUninitialize 
+        to correctly uninitialize COM. The value should be retained and later 
+        passed to PaWinUtil_CoUninitialize.
+
+ If PaWinUtil_CoInitialize returns paNoError, the caller must later call
+ PaWinUtil_CoUninitialize once.
+*/
+PaError PaWinUtil_CoInitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult );
+
+
+/**
+ @brief Uninitialize the Microsoft COM subsystem on the current thread using 
+ the result of a previous call to PaWinUtil_CoInitialize. Must be called on the same
+ thread as PaWinUtil_CoInitialize.
+
+ @param hostApiType the host API type id of the caller. Used for error reporting.
+
+ @param comInitializationResult An input parameter. A pointer to a value previously
+ initialized by a call to PaWinUtil_CoInitialize.
+*/
+void PaWinUtil_CoUninitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_WIN_COINITIALIZE_H */
diff --git a/portaudio/src/os/win/pa_win_hostapis.c b/portaudio/src/os/win/pa_win_hostapis.c
new file mode 100644 (file)
index 0000000..9c9927a
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library Windows initialization table
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+    @brief Win32 host API initialization function table.
+*/
+
+/* This is needed to make this source file depend on CMake option changes
+   and at the same time make it transparent for clients not using CMake.
+*/
+#ifdef PORTAUDIO_CMAKE_GENERATED
+#include "options_cmake.h"
+#endif
+
+#include "pa_hostapi.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+
+PaUtilHostApiInitializer *paHostApiInitializers[] =
+    {
+
+#if PA_USE_WMME
+        PaWinMme_Initialize,
+#endif
+
+#if PA_USE_DS
+        PaWinDs_Initialize,
+#endif
+
+#if PA_USE_ASIO
+        PaAsio_Initialize,
+#endif
+
+#if PA_USE_WASAPI
+               PaWasapi_Initialize,
+#endif
+
+#if PA_USE_WDMKS
+        PaWinWdm_Initialize,
+#endif
+
+#if PA_USE_SKELETON
+        PaSkeleton_Initialize, /* just for testing. last in list so it isn't marked as default. */
+#endif
+
+        0   /* NULL terminated array */
+    };
+
+
diff --git a/portaudio/src/os/win/pa_win_util.c b/portaudio/src/os/win/pa_win_util.c
new file mode 100644 (file)
index 0000000..1cd3525
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * $Id$
+ * Portable Audio I/O Library
+ * Win32 platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2008 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ @brief Win32 implementation of platform-specific PaUtil support functions.
+*/
+#include <windows.h>
+
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
+       #include <sys/timeb.h> /* for _ftime_s() */
+#else
+       #include <mmsystem.h> /* for timeGetTime() */
+       #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) && !defined(_WIN32_WCE) /* MSC version 6 and above */
+       #pragma comment( lib, "winmm.lib" )
+       #endif
+#endif
+
+#include "pa_util.h"
+
+/*
+   Track memory allocations to avoid leaks.
+ */
+
+#if PA_TRACK_MEMORY
+static int numAllocations_ = 0;
+#endif
+
+
+void *PaUtil_AllocateMemory( long size )
+{
+    void *result = GlobalAlloc( GPTR, size );
+
+#if PA_TRACK_MEMORY
+    if( result != NULL ) numAllocations_ += 1;
+#endif
+    return result;
+}
+
+
+void PaUtil_FreeMemory( void *block )
+{
+    if( block != NULL )
+    {
+        GlobalFree( block );
+#if PA_TRACK_MEMORY
+        numAllocations_ -= 1;
+#endif
+
+    }
+}
+
+
+int PaUtil_CountCurrentlyAllocatedBlocks( void )
+{
+#if PA_TRACK_MEMORY
+    return numAllocations_;
+#else
+    return 0;
+#endif
+}
+
+
+void Pa_Sleep( long msec )
+{
+    Sleep( msec );
+}
+
+static int usePerformanceCounter_;
+static double secondsPerTick_;
+
+void PaUtil_InitializeClock( void )
+{
+    LARGE_INTEGER ticksPerSecond;
+
+    if( QueryPerformanceFrequency( &ticksPerSecond ) != 0 )
+    {
+        usePerformanceCounter_ = 1;
+        secondsPerTick_ = 1.0 / (double)ticksPerSecond.QuadPart;
+    }
+    else
+    {
+        usePerformanceCounter_ = 0;
+    }
+}
+
+
+double PaUtil_GetTime( void )
+{
+    LARGE_INTEGER time;
+
+    if( usePerformanceCounter_ )
+    {
+        /*
+            Note: QueryPerformanceCounter has a known issue where it can skip forward
+            by a few seconds (!) due to a hardware bug on some PCI-ISA bridge hardware.
+            This is documented here:
+            http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323&
+
+            The work-arounds are not very paletable and involve querying GetTickCount 
+            at every time step.
+
+            Using rdtsc is not a good option on multi-core systems.
+
+            For now we just use QueryPerformanceCounter(). It's good, most of the time.
+        */
+        QueryPerformanceCounter( &time );
+        return time.QuadPart * secondsPerTick_;
+    }
+    else
+    {
+#ifndef UNDER_CE
+       #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
+        return GetTickCount64() * .001;
+       #else
+        return timeGetTime() * .001;
+       #endif
+#else
+        return GetTickCount() * .001;
+#endif                
+    }
+}
diff --git a/portaudio/src/os/win/pa_win_waveformat.c b/portaudio/src/os/win/pa_win_waveformat.c
new file mode 100644 (file)
index 0000000..bd5addd
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Windows WAVEFORMAT* data structure utilities
+ * portaudio.h should be included before this file.
+ *
+ * Copyright (c) 2007 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+#include <windows.h>
+#include <mmsystem.h>
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
+    #include <mmreg.h> /* for WAVEFORMATEX */
+#endif
+
+#include "portaudio.h"
+#include "pa_win_waveformat.h"
+
+
+#if !defined(WAVE_FORMAT_EXTENSIBLE)
+#define  WAVE_FORMAT_EXTENSIBLE         0xFFFE
+#endif
+
+
+static GUID pawin_ksDataFormatSubtypeGuidBase = 
+       { (USHORT)(WAVE_FORMAT_PCM), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 };
+
+
+int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat )
+{
+    if( sampleFormat == paFloat32 )
+        return PAWIN_WAVE_FORMAT_IEEE_FLOAT;
+    
+    return PAWIN_WAVE_FORMAT_PCM;
+}
+
+
+void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, 
+               int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate )
+{
+       WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
+    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
+       unsigned long bytesPerFrame = numChannels * bytesPerSample;
+       
+    waveFormatEx->wFormatTag = waveFormatTag;
+       waveFormatEx->nChannels = (WORD)numChannels;
+       waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
+       waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
+       waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
+       waveFormatEx->wBitsPerSample = bytesPerSample * 8;
+       waveFormatEx->cbSize = 0;
+}
+
+
+void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, 
+               int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
+               PaWinWaveFormatChannelMask channelMask )
+{
+       WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
+    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
+       unsigned long bytesPerFrame = numChannels * bytesPerSample;
+    GUID guid;
+
+       waveFormatEx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+       waveFormatEx->nChannels = (WORD)numChannels;
+       waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
+       waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
+       waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
+       waveFormatEx->wBitsPerSample = bytesPerSample * 8;
+       waveFormatEx->cbSize = 22;
+
+       *((WORD*)&waveFormat->fields[PAWIN_INDEXOF_WVALIDBITSPERSAMPLE]) =
+                       waveFormatEx->wBitsPerSample;
+
+       *((DWORD*)&waveFormat->fields[PAWIN_INDEXOF_DWCHANNELMASK]) = channelMask;
+               
+    guid = pawin_ksDataFormatSubtypeGuidBase;
+    guid.Data1 = (USHORT)waveFormatTag;
+    *((GUID*)&waveFormat->fields[PAWIN_INDEXOF_SUBFORMAT]) = guid;
+}
+
+PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels )
+{
+       switch( numChannels ){
+               case 1:
+                       return PAWIN_SPEAKER_MONO;
+               case 2:
+                       return PAWIN_SPEAKER_STEREO; 
+               case 3:
+            return PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_FRONT_RIGHT;
+               case 4:
+                       return PAWIN_SPEAKER_QUAD;
+               case 5:
+            return PAWIN_SPEAKER_QUAD | PAWIN_SPEAKER_FRONT_CENTER;
+               case 6:
+            /* The meaning of the PAWIN_SPEAKER_5POINT1 flag has changed over time:
+                http://msdn2.microsoft.com/en-us/library/aa474707.aspx
+               We use PAWIN_SPEAKER_5POINT1 (not PAWIN_SPEAKER_5POINT1_SURROUND)
+               because on some cards (eg Audigy) PAWIN_SPEAKER_5POINT1_SURROUND 
+               results in a virtual mixdown placing the rear output in the 
+               front _and_ rear speakers.
+            */
+                       return PAWIN_SPEAKER_5POINT1; 
+        /* case 7: */
+               case 8:
+            /* RoBi: PAWIN_SPEAKER_7POINT1_SURROUND fits normal surround sound setups better than PAWIN_SPEAKER_7POINT1, f.i. NVidia HDMI Audio
+               output is silent on channels 5&6 with NVidia drivers, and channel 7&8 with Micrsoft HD Audio driver using PAWIN_SPEAKER_7POINT1. 
+               With PAWIN_SPEAKER_7POINT1_SURROUND both setups work OK. */
+                       return PAWIN_SPEAKER_7POINT1_SURROUND;
+       }
+
+    /* Apparently some Audigy drivers will output silence 
+       if the direct-out constant (0) is used. So this is not ideal.    
+
+       RoBi 2012-12-19: Also, NVidia driver seem to output garbage instead. Again not very ideal.
+    */
+       return  PAWIN_SPEAKER_DIRECTOUT;
+
+    /* Note that Alec Rogers proposed the following as an alternate method to 
+        generate the default channel mask, however it doesn't seem to be an improvement
+        over the above, since some drivers will matrix outputs mapping to non-present
+        speakers accross multiple physical speakers.
+
+        if(nChannels==1) {
+            pwfFormat->dwChannelMask = SPEAKER_FRONT_CENTER;
+        }
+        else {
+            pwfFormat->dwChannelMask = 0;
+            for(i=0; i<nChannels; i++)
+                pwfFormat->dwChannelMask = (pwfFormat->dwChannelMask << 1) | 0x1;
+        }
+    */
+}
diff --git a/portaudio/src/os/win/pa_win_wdmks_utils.c b/portaudio/src/os/win/pa_win_wdmks_utils.c
new file mode 100644 (file)
index 0000000..4bd067a
--- /dev/null
@@ -0,0 +1,309 @@
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Windows WDM KS utilities
+ *
+ * Copyright (c) 1999 - 2007 Andrew Baldwin, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+#include <windows.h>
+#include <mmreg.h>
+#ifndef WAVE_FORMAT_IEEE_FLOAT
+    #define WAVE_FORMAT_IEEE_FLOAT 0x0003   // MinGW32 does not define this
+#endif    
+#ifndef _WAVEFORMATEXTENSIBLE_
+    #define _WAVEFORMATEXTENSIBLE_          // MinGW32 does not define this
+#endif
+#ifndef _INC_MMREG
+    #define _INC_MMREG                      // for STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
+#endif
+#include <winioctl.h>                                          // MinGW32 does not define this automatically
+
+#if defined(__GNUC__)
+
+#include "../../hostapi/wasapi/mingw-include/ks.h"
+#include "../../hostapi/wasapi/mingw-include/ksmedia.h"
+
+#else
+
+#include <ks.h>
+#include <ksmedia.h>
+
+#endif
+
+#include <stdio.h>                          // just for some development printfs
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_win_wdmks_utils.h"
+
+
+/* PortAudio-local instances of GUIDs previously sourced from ksguid.lib */
+
+/* GUID KSDATAFORMAT_TYPE_AUDIO */
+static const GUID pa_KSDATAFORMAT_TYPE_AUDIO = { STATIC_KSDATAFORMAT_TYPE_AUDIO };
+
+/* GUID KSDATAFORMAT_SUBTYPE_IEEE_FLOAT */
+static const GUID pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT };
+
+/* GUID KSDATAFORMAT_SUBTYPE_PCM */
+static const GUID pa_KSDATAFORMAT_SUBTYPE_PCM = { STATIC_KSDATAFORMAT_SUBTYPE_PCM };
+
+/* GUID KSDATAFORMAT_SUBTYPE_WAVEFORMATEX */
+static const GUID pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX = { STATIC_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX };
+
+/* GUID KSMEDIUMSETID_Standard */
+static const GUID pa_KSMEDIUMSETID_Standard = { STATIC_KSMEDIUMSETID_Standard };
+
+/* GUID KSINTERFACESETID_Standard */
+static const GUID pa_KSINTERFACESETID_Standard = { STATIC_KSINTERFACESETID_Standard };
+
+/* GUID KSPROPSETID_Pin */
+static const GUID pa_KSPROPSETID_Pin = { STATIC_KSPROPSETID_Pin };
+
+#define pa_IS_VALID_WAVEFORMATEX_GUID(Guid)\
+    (!memcmp(((PUSHORT)&pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX) + 1, ((PUSHORT)(Guid)) + 1, sizeof(GUID) - sizeof(USHORT)))
+
+
+static PaError WdmGetPinPropertySimple(
+    HANDLE  handle,
+    unsigned long pinId,
+    unsigned long property,
+    void* value,
+    unsigned long valueSize )
+{
+    DWORD bytesReturned;
+    KSP_PIN ksPProp;
+    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
+            value, valueSize, &bytesReturned, NULL ) == 0 || bytesReturned != valueSize )
+    {
+        return paUnanticipatedHostError;
+    }
+    else
+    {
+        return paNoError;
+    }
+}
+
+
+static PaError WdmGetPinPropertyMulti(
+    HANDLE handle,
+    unsigned long pinId,
+    unsigned long property,
+    KSMULTIPLE_ITEM** ksMultipleItem)
+{
+    unsigned long multipleItemSize = 0;
+    KSP_PIN ksPProp;
+    DWORD bytesReturned;
+
+    *ksMultipleItem = 0;
+
+    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp.Property,
+            sizeof(KSP_PIN), NULL, 0, &multipleItemSize, NULL ) == 0 && GetLastError() != ERROR_MORE_DATA )
+    {
+        return paUnanticipatedHostError;
+    }
+
+    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
+    if( !*ksMultipleItem )
+    {
+        return paInsufficientMemory;
+    }
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
+            (void*)*ksMultipleItem,  multipleItemSize, &bytesReturned, NULL ) == 0 || bytesReturned != multipleItemSize )
+    {
+        PaUtil_FreeMemory( ksMultipleItem );
+        return paUnanticipatedHostError;
+    }
+
+    return paNoError;
+}
+
+
+static int GetKSFilterPinCount( HANDLE deviceHandle )
+{
+    DWORD result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, 0, KSPROPERTY_PIN_CTYPES, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return 0;
+    }
+}
+
+
+static KSPIN_COMMUNICATION GetKSFilterPinPropertyCommunication( HANDLE deviceHandle, int pinId )
+{
+    KSPIN_COMMUNICATION result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_COMMUNICATION, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return KSPIN_COMMUNICATION_NONE;
+    }
+}
+
+
+static KSPIN_DATAFLOW GetKSFilterPinPropertyDataflow( HANDLE deviceHandle, int pinId )
+{
+    KSPIN_DATAFLOW result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_DATAFLOW, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return (KSPIN_DATAFLOW)0;
+    }
+}
+
+
+static int KSFilterPinPropertyIdentifiersInclude( 
+        HANDLE deviceHandle, int pinId, unsigned long property, const GUID *identifierSet, unsigned long identifierId  )
+{
+    KSMULTIPLE_ITEM* item = NULL;
+    KSIDENTIFIER* identifier;
+    int i;
+    int result = 0;
+
+    if( WdmGetPinPropertyMulti( deviceHandle, pinId, property, &item) != paNoError )
+        return 0;
+    
+    identifier = (KSIDENTIFIER*)(item+1);
+
+    for( i = 0; i < (int)item->Count; i++ )
+    {
+        if( !memcmp( (void*)&identifier[i].Set, (void*)identifierSet, sizeof( GUID ) ) &&
+           ( identifier[i].Id == identifierId ) )
+        {
+            result = 1;
+            break;
+        }
+    }
+
+    PaUtil_FreeMemory( item );
+
+    return result;
+}
+
+
+/* return the maximum channel count supported by any pin on the device. 
+   if isInput is non-zero we query input pins, otherwise output pins.
+*/
+int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput )
+{
+    HANDLE deviceHandle;
+       ULONG i;
+    int pinCount, pinId;
+    int result = 0;
+    KSPIN_DATAFLOW requiredDataflowDirection = (isInput ? KSPIN_DATAFLOW_OUT : KSPIN_DATAFLOW_IN );
+    
+    if( !wcharDevicePath )
+        return 0;
+
+    deviceHandle = CreateFileW( (LPCWSTR)wcharDevicePath, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
+    if( deviceHandle == INVALID_HANDLE_VALUE )
+        return 0;
+
+    pinCount = GetKSFilterPinCount( deviceHandle );
+    for( pinId = 0; pinId < pinCount; ++pinId )
+    {
+        KSPIN_COMMUNICATION communication = GetKSFilterPinPropertyCommunication( deviceHandle, pinId );
+        KSPIN_DATAFLOW dataflow = GetKSFilterPinPropertyDataflow( deviceHandle, pinId );
+        if( ( dataflow == requiredDataflowDirection ) &&
+                (( communication == KSPIN_COMMUNICATION_SINK) ||
+                 ( communication == KSPIN_COMMUNICATION_BOTH)) 
+             && ( KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_STREAMING )
+                || KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_LOOPED_STREAMING ) )
+             && KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_MEDIUMS, &pa_KSMEDIUMSETID_Standard, KSMEDIUM_STANDARD_DEVIO ) )
+         {
+            KSMULTIPLE_ITEM* item = NULL;
+            if( WdmGetPinPropertyMulti( deviceHandle, pinId, KSPROPERTY_PIN_DATARANGES, &item ) == paNoError )
+            {
+                KSDATARANGE *dataRange = (KSDATARANGE*)(item+1);
+
+                for( i=0; i < item->Count; ++i ){
+
+                    if( pa_IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat)
+                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID) ) == 0
+                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID) ) == 0
+                            || ( ( memcmp( (void*)&dataRange->MajorFormat, (void*)&pa_KSDATAFORMAT_TYPE_AUDIO, sizeof(GUID) ) == 0 )
+                                && ( memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof(GUID) ) == 0 ) ) )
+                    {
+                        KSDATARANGE_AUDIO *dataRangeAudio = (KSDATARANGE_AUDIO*)dataRange;
+                        
+                        /*
+                        printf( ">>> %d %d %d %d %S\n", isInput, dataflow, communication, dataRangeAudio->MaximumChannels, devicePath );
+                       
+                        if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WAVEFORMATEX\n" );
+                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_DSOUND, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_DSOUND\n" );
+                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WILDCARD, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WILDCARD\n" );
+                        else
+                            printf( "\tspecifier: ?\n" );
+                        */
+
+                        /*
+                            We assume that very high values for MaximumChannels are not useful and indicate
+                            that the driver isn't prepared to tell us the real number of channels which it supports.
+                        */
+                        if( dataRangeAudio->MaximumChannels  < 0xFFFFUL && (int)dataRangeAudio->MaximumChannels > result )
+                            result = (int)dataRangeAudio->MaximumChannels;
+                    }
+                    
+                    dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
+                }
+
+                PaUtil_FreeMemory( item );
+            }
+        }
+    }
+    
+    CloseHandle( deviceHandle );
+    return result;
+}
diff --git a/portaudio/src/os/win/pa_win_wdmks_utils.h b/portaudio/src/os/win/pa_win_wdmks_utils.h
new file mode 100644 (file)
index 0000000..b8e923a
--- /dev/null
@@ -0,0 +1,65 @@
+#ifndef PA_WIN_WDMKS_UTILS_H
+#define PA_WIN_WDMKS_UTILS_H
+
+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Windows WDM KS utilities
+ *
+ * Copyright (c) 1999 - 2007 Ross Bencina, Andrew Baldwin
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @brief Utilities for working with the Windows WDM KS API
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+    Query for the maximum number of channels supported by any pin of the
+    specified device. Returns 0 if the query fails for any reason.
+
+    @param wcharDevicePath A system level PnP interface path, supplied as a WCHAR unicode string.
+    Declard as void* to avoid introducing a dependency on wchar_t here.
+
+    @param isInput A flag specifying whether to query for input (non-zero) or output (zero) channels.
+*/
+int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* PA_WIN_WDMKS_UTILS_H */
\ No newline at end of file
diff --git a/portaudio/src/os/win/pa_x86_plain_converters.c b/portaudio/src/os/win/pa_x86_plain_converters.c
new file mode 100644 (file)
index 0000000..cebd8a3
--- /dev/null
@@ -0,0 +1,1218 @@
+/*
+ * Plain Intel IA32 assembly implementations of PortAudio sample converter functions.
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+*/
+
+#include "pa_x86_plain_converters.h"
+
+#include "pa_converters.h"
+#include "pa_dither.h"
+
+/*
+    the main reason these versions are faster than the equivalent C versions
+    is that float -> int casting is expensive in C on x86 because the rounding
+    mode needs to be changed for every cast. these versions only set
+    the rounding mode once outside the loop.
+
+    small additional speed gains are made by the way that clamping is
+    implemented.
+
+TODO:
+    o- inline dither code
+    o- implement Dither only (no-clip) versions
+    o- implement int8 and uint8 versions
+    o- test thouroughly
+
+    o- the packed 24 bit functions could benefit from unrolling and avoiding
+        byte and word sized register access.
+*/
+
+/* -------------------------------------------------------------------------- */
+
+/*
+#define PA_CLIP_( val, min, max )\
+    { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); }
+*/
+
+/*
+    the following notes were used to determine whether a floating point
+    value should be saturated (ie >1 or <-1) by loading it into an integer
+    register. these should be rewritten so that they make sense.
+
+    an ieee floating point value
+
+    1.xxxxxxxxxxxxxxxxxxxx?
+
+
+    is less than  or equal to 1 and greater than or equal to -1 either:
+
+        if the mantissa is 0 and the unbiased exponent is 0
+
+        OR
+
+        if the unbiased exponent < 0
+
+    this translates to:
+
+        if the mantissa is 0 and the biased exponent is 7F
+
+        or
+
+        if the biased exponent is less than 7F
+
+
+    therefore the value is greater than 1 or less than -1 if
+
+        the mantissa is not 0 and the biased exponent is 7F
+
+        or
+
+        if the biased exponent is greater than 7F
+
+
+    in other words, if we mask out the sign bit, the value is
+    greater than 1 or less than -1 if its integer representation is greater than:
+
+    0 01111111 0000 0000 0000 0000 0000 000
+
+    0011 1111 1000 0000 0000 0000 0000 0000 => 0x3F800000
+*/
+
+#if defined(_WIN64) || defined(_WIN32_WCE) || defined(__GNUC__)
+
+/*
+       -EMT64/AMD64 uses different asm
+       -VC2005 doesnt allow _WIN64 with inline assembly either!
+ */
+void PaUtil_InitializeX86PlainConverters( void )
+{
+}
+
+#else
+
+/* -------------------------------------------------------------------------- */
+
+static const short fpuControlWord_ = 0x033F; /*round to nearest, 64 bit precision, all exceptions masked*/
+static const double int32Scaler_ = 0x7FFFFFFF;
+static const double ditheredInt32Scaler_ = 0x7FFFFFFE;
+static const double int24Scaler_ = 0x7FFFFF;
+static const double ditheredInt24Scaler_ = 0x7FFFFE;
+static const double int16Scaler_ = 0x7FFF;
+static const double ditheredInt16Scaler_ = 0x7FFE;
+
+#define PA_DITHER_BITS_   (15)
+/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */
+#define PA_FLOAT_DITHER_SCALE_  (1.0F / ((1<<PA_DITHER_BITS_)-1))
+static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
+#define PA_DITHER_SHIFT_  ((32 - PA_DITHER_BITS_) + 1)
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    signed long *dest =  (signed long*)destinationBuffer;
+    (void)ditherGenerator; // unused parameter
+
+    while( count-- )
+    {
+        // REVIEW
+        double scaled = *src * 0x7FFFFFFF;
+        *dest = (signed long) scaled;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+*/
+
+    short savedFpuControlWord;
+
+    (void) ditherGenerator; /* unused parameter */
+
+
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32 and int32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+    
+        mov     edi, destinationBuffer
+        
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int32Scaler_             // stack:  (int)0x7FFFFFFF
+
+    Float32_To_Int32_loop:
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFFFFFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFFFFFF, (int)0x7FFFFFFF
+        /*
+            note: we could store to a temporary qword here which would cause
+            wraparound distortion instead of int indefinite 0x10. that would
+            be more work, and given that not enabling clipping is only advisable
+            when you know that your signal isn't going to clip it isn't worth it.
+        */
+        fistp   dword ptr [edi]         // pop st(0) into dest, stack:  (int)0x7FFFFFFF
+
+        add     edi, ebx                // increment destination ptr
+        //lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int32_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    signed long *dest =  (signed long*)destinationBuffer;
+    (void) ditherGenerator; // unused parameter
+
+    while( count-- )
+    {
+        // REVIEW
+        double scaled = *src * 0x7FFFFFFF;
+        PA_CLIP_( scaled, -2147483648., 2147483647.  );
+        *dest = (signed long) scaled;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+*/
+
+    short savedFpuControlWord;
+
+    (void) ditherGenerator; /* unused parameter */
+
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32 and int32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+    
+        mov     edi, destinationBuffer
+        
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int32Scaler_             // stack:  (int)0x7FFFFFFF
+
+    Float32_To_Int32_Clip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int32_Clip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFFFFFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFFFFFF, (int)0x7FFFFFFF
+        fistp   dword ptr [edi]         // pop st(0) into dest, stack:  (int)0x7FFFFFFF
+        jmp     Float32_To_Int32_Clip_stored
+    
+    Float32_To_Int32_Clip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     edx, 0x7FFFFFFF         // convert to maximum range integers
+        mov     dword ptr [edi], edx
+
+    Float32_To_Int32_Clip_stored:
+
+        //add     edi, ebx                // increment destination ptr
+        lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int32_Clip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+    /*
+    float *src = (float*)sourceBuffer;
+    signed long *dest =  (signed long*)destinationBuffer;
+
+    while( count-- )
+    {
+        // REVIEW
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        // use smaller scaler to prevent overflow when we add the dither
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        PA_CLIP_( dithered, -2147483648., 2147483647.  );
+        *dest = (signed long) dithered;
+
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+    */
+
+    short savedFpuControlWord;
+
+    // spill storage:
+    signed long sourceByteStride;
+    signed long highpassedDither;
+
+    // dither state:
+    unsigned long ditherPrevious = ditherGenerator->previous;
+    unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+    unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+                    
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32 and int32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+    
+        mov     edi, destinationBuffer
+        
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     ditheredInt32Scaler_    // stack:  int scaler
+
+    Float32_To_Int32_DitherClip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int32_DitherClip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, int scaler
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*(int scaler), int scaler
+
+        /*
+        // call PaUtil_GenerateFloatTriangularDither with C calling convention
+        mov     sourceByteStride, eax   // save eax
+        mov     sourceEnd, ecx          // save ecx
+        push    ditherGenerator         // pass ditherGenerator parameter on stack
+           call    PaUtil_GenerateFloatTriangularDither  // stack:  dither, value*(int scaler), int scaler
+           pop     edx                     // clear parameter off stack
+        mov     ecx, sourceEnd          // restore ecx
+        mov     eax, sourceByteStride   // restore eax
+        */
+
+    // generate dither
+        mov     sourceByteStride, eax   // save eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed1
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     ditherRandSeed1, eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed2
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     edx, ditherRandSeed1
+        shr     edx, PA_DITHER_SHIFT_
+        mov     ditherRandSeed2, eax
+        shr     eax, PA_DITHER_SHIFT_
+        //add     eax, edx                // eax -> current
+        lea     eax, [eax+edx]
+        mov     edx, ditherPrevious
+        neg     edx
+        lea     edx, [eax+edx]          // highpass = current - previous
+        mov     highpassedDither, edx
+        mov     ditherPrevious, eax     // previous = current
+        mov     eax, sourceByteStride   // restore eax
+        fild    highpassedDither
+        fmul    const_float_dither_scale_
+    // end generate dither, dither signal in st(0)
+    
+        faddp   st(1), st(0)            // stack: dither + value*(int scaler), int scaler
+        fistp   dword ptr [edi]         // pop st(0) into dest, stack:  int scaler
+        jmp     Float32_To_Int32_DitherClip_stored
+    
+    Float32_To_Int32_DitherClip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     edx, 0x7FFFFFFF         // convert to maximum range integers
+        mov     dword ptr [edi], edx
+
+    Float32_To_Int32_DitherClip_stored:
+
+        //add     edi, ebx              // increment destination ptr
+        lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int32_DitherClip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+
+    ditherGenerator->previous = ditherPrevious;
+    ditherGenerator->randSeed1 = ditherRandSeed1;
+    ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    signed long temp;
+
+    (void) ditherGenerator; // unused parameter
+    
+    while( count-- )
+    {
+        // convert to 32 bit and drop the low 8 bits
+        double scaled = *src * 0x7FFFFFFF;
+        temp = (signed long) scaled;
+
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+*/
+
+    short savedFpuControlWord;
+    
+    signed long tempInt32;
+
+    (void) ditherGenerator; /* unused parameter */
+                 
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 3                  // sizeof int24
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int24Scaler_             // stack:  (int)0x7FFFFF
+
+    Float32_To_Int24_loop:
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFFFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFFFF, (int)0x7FFFFF
+        fistp   tempInt32               // pop st(0) into tempInt32, stack:  (int)0x7FFFFF
+        mov     edx, tempInt32
+
+        mov     byte ptr [edi], DL
+        shr     edx, 8
+        //mov     byte ptr [edi+1], DL
+        //mov     byte ptr [edi+2], DH
+        mov     word ptr [edi+1], DX
+
+        //add     edi, ebx                // increment destination ptr
+        lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int24_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    signed long temp;
+
+    (void) ditherGenerator; // unused parameter
+    
+    while( count-- )
+    {
+        // convert to 32 bit and drop the low 8 bits
+        double scaled = *src * 0x7FFFFFFF;
+        PA_CLIP_( scaled, -2147483648., 2147483647.  );
+        temp = (signed long) scaled;
+
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+*/
+
+    short savedFpuControlWord;
+    
+    signed long tempInt32;
+
+    (void) ditherGenerator; /* unused parameter */
+                 
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 3                  // sizeof int24
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int24Scaler_             // stack:  (int)0x7FFFFF
+
+    Float32_To_Int24_Clip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int24_Clip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFFFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFFFF, (int)0x7FFFFF
+        fistp   tempInt32               // pop st(0) into tempInt32, stack:  (int)0x7FFFFF
+        mov     edx, tempInt32
+        jmp     Float32_To_Int24_Clip_store
+    
+    Float32_To_Int24_Clip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     edx, 0x7FFFFF           // convert to maximum range integers
+
+    Float32_To_Int24_Clip_store:
+
+        mov     byte ptr [edi], DL
+        shr     edx, 8
+        //mov     byte ptr [edi+1], DL
+        //mov     byte ptr [edi+2], DH
+        mov     word ptr [edi+1], DX
+
+        //add     edi, ebx                // increment destination ptr
+        lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int24_Clip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    unsigned char *dest = (unsigned char*)destinationBuffer;
+    signed long temp;
+    
+    while( count-- )
+    {
+        // convert to 32 bit and drop the low 8 bits
+
+        // FIXME: the dither amplitude here appears to be too small by 8 bits
+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        // use smaller scaler to prevent overflow when we add the dither
+        double dithered = ((double)*src * (2147483646.0)) + dither;
+        PA_CLIP_( dithered, -2147483648., 2147483647.  );
+        
+        temp = (signed long) dithered;
+
+        dest[0] = (unsigned char)(temp >> 8);
+        dest[1] = (unsigned char)(temp >> 16);
+        dest[2] = (unsigned char)(temp >> 24);
+
+        src += sourceStride;
+        dest += destinationStride * 3;
+    }
+*/
+
+    short savedFpuControlWord;
+
+    // spill storage:
+    signed long sourceByteStride;
+    signed long highpassedDither;
+
+    // dither state:
+    unsigned long ditherPrevious = ditherGenerator->previous;
+    unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+    unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+    
+    signed long tempInt32;
+                 
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 3                  // sizeof int24
+        mov     ebx, destinationStride
+        imul    ebx, edx
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     ditheredInt24Scaler_    // stack:  int scaler
+
+    Float32_To_Int24_DitherClip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int24_DitherClip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, int scaler
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*(int scaler), int scaler
+
+    /*
+        // call PaUtil_GenerateFloatTriangularDither with C calling convention
+        mov     sourceByteStride, eax   // save eax
+        mov     sourceEnd, ecx          // save ecx
+        push    ditherGenerator         // pass ditherGenerator parameter on stack
+           call    PaUtil_GenerateFloatTriangularDither  // stack:  dither, value*(int scaler), int scaler
+           pop     edx                     // clear parameter off stack
+        mov     ecx, sourceEnd          // restore ecx
+        mov     eax, sourceByteStride   // restore eax
+    */
+    
+    // generate dither
+        mov     sourceByteStride, eax   // save eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed1
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     ditherRandSeed1, eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed2
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     edx, ditherRandSeed1
+        shr     edx, PA_DITHER_SHIFT_
+        mov     ditherRandSeed2, eax
+        shr     eax, PA_DITHER_SHIFT_
+        //add     eax, edx                // eax -> current
+        lea     eax, [eax+edx]
+        mov     edx, ditherPrevious
+        neg     edx
+        lea     edx, [eax+edx]          // highpass = current - previous
+        mov     highpassedDither, edx
+        mov     ditherPrevious, eax     // previous = current
+        mov     eax, sourceByteStride   // restore eax
+        fild    highpassedDither
+        fmul    const_float_dither_scale_
+    // end generate dither, dither signal in st(0)
+
+        faddp   st(1), st(0)            // stack: dither * value*(int scaler), int scaler
+        fistp   tempInt32               // pop st(0) into tempInt32, stack:  int scaler
+        mov     edx, tempInt32
+        jmp     Float32_To_Int24_DitherClip_store
+    
+    Float32_To_Int24_DitherClip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     edx, 0x7FFFFF           // convert to maximum range integers
+
+    Float32_To_Int24_DitherClip_store:
+
+        mov     byte ptr [edi], DL
+        shr     edx, 8
+        //mov     byte ptr [edi+1], DL
+        //mov     byte ptr [edi+2], DH
+        mov     word ptr [edi+1], DX
+
+        //add     edi, ebx                // increment destination ptr
+        lea     edi, [edi+ebx]
+
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int24_DitherClip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+
+    ditherGenerator->previous = ditherPrevious;
+    ditherGenerator->randSeed1 = ditherRandSeed1;
+    ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    signed short *dest =  (signed short*)destinationBuffer;
+    (void)ditherGenerator; // unused parameter
+
+    while( count-- )
+    {
+
+        short samp = (short) (*src * (32767.0f));
+        *dest = samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+*/
+
+    short savedFpuControlWord;
+   
+    (void) ditherGenerator; /* unused parameter */
+
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx                // source byte stride
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi                // source end ptr = count * source byte stride + source ptr
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 2                  // sizeof int16
+        mov     ebx, destinationStride
+        imul    ebx, edx                // destination byte stride
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int16Scaler_            // stack:  (int)0x7FFF
+
+    Float32_To_Int16_loop:
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFF, (int)0x7FFF
+        fistp   word ptr [edi]          // store scaled int into dest, stack:  (int)0x7FFF
+
+        add     edi, ebx                // increment destination ptr
+        //lea     edi, [edi+ebx]
+        
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int16_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_Clip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    signed short *dest =  (signed short*)destinationBuffer;
+    (void)ditherGenerator; // unused parameter
+
+    while( count-- )
+    {
+        long samp = (signed long) (*src * (32767.0f));
+        PA_CLIP_( samp, -0x8000, 0x7FFF );
+        *dest = (signed short) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+*/
+
+    short savedFpuControlWord;
+   
+    (void) ditherGenerator; /* unused parameter */
+
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx                // source byte stride
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi                // source end ptr = count * source byte stride + source ptr
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 2                  // sizeof int16
+        mov     ebx, destinationStride
+        imul    ebx, edx                // destination byte stride
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     int16Scaler_            // stack:  (int)0x7FFF
+
+    Float32_To_Int16_Clip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int16_Clip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, (int)0x7FFF
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*0x7FFF, (int)0x7FFF
+        fistp   word ptr [edi]          // store scaled int into dest, stack:  (int)0x7FFF
+        jmp     Float32_To_Int16_Clip_stored
+    
+    Float32_To_Int16_Clip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     dx, 0x7FFF              // convert to maximum range integers
+        mov     word ptr [edi], dx      // store clamped into into dest
+
+    Float32_To_Int16_Clip_stored:
+
+        add     edi, ebx                // increment destination ptr
+        //lea     edi, [edi+ebx]
+        
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int16_Clip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_DitherClip(
+    void *destinationBuffer, signed int destinationStride,
+    void *sourceBuffer, signed int sourceStride,
+    unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+    float *src = (float*)sourceBuffer;
+    signed short *dest =  (signed short*)destinationBuffer;
+    (void)ditherGenerator; // unused parameter
+
+    while( count-- )
+    {
+
+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+        // use smaller scaler to prevent overflow when we add the dither 
+        float dithered = (*src * (32766.0f)) + dither;
+        signed long samp = (signed long) dithered;
+        PA_CLIP_( samp, -0x8000, 0x7FFF );
+        *dest = (signed short) samp;
+
+        src += sourceStride;
+        dest += destinationStride;
+    }
+*/
+
+    short savedFpuControlWord;
+
+    // spill storage:
+    signed long sourceByteStride;
+    signed long highpassedDither;
+
+    // dither state:
+    unsigned long ditherPrevious = ditherGenerator->previous;
+    unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+    unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+
+    __asm{
+        // esi -> source ptr
+        // eax -> source byte stride
+        // edi -> destination ptr
+        // ebx -> destination byte stride
+        // ecx -> source end ptr
+        // edx -> temp
+
+        mov     esi, sourceBuffer
+
+        mov     edx, 4                  // sizeof float32
+        mov     eax, sourceStride
+        imul    eax, edx                // source byte stride
+
+        mov     ecx, count
+        imul    ecx, eax
+        add     ecx, esi                // source end ptr = count * source byte stride + source ptr
+
+        mov     edi, destinationBuffer
+
+        mov     edx, 2                  // sizeof int16
+        mov     ebx, destinationStride
+        imul    ebx, edx                // destination byte stride
+
+        fwait
+        fstcw   savedFpuControlWord
+        fldcw   fpuControlWord_
+
+        fld     ditheredInt16Scaler_    // stack:  int scaler
+
+    Float32_To_Int16_DitherClip_loop:
+
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+
+        and     edx, 0x7FFFFFFF         // mask off sign
+        cmp     edx, 0x3F800000         // greater than 1.0 or less than -1.0
+
+        jg      Float32_To_Int16_DitherClip_clamp
+
+        // load unscaled value into st(0)
+        fld     dword ptr [esi]         // stack:  value, int scaler
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        fmul    st(0), st(1)            // st(0) *= st(1), stack:  value*(int scaler), int scaler
+
+        /*
+        // call PaUtil_GenerateFloatTriangularDither with C calling convention
+        mov     sourceByteStride, eax   // save eax
+        mov     sourceEnd, ecx          // save ecx
+        push    ditherGenerator         // pass ditherGenerator parameter on stack
+           call    PaUtil_GenerateFloatTriangularDither  // stack:  dither, value*(int scaler), int scaler
+           pop     edx                     // clear parameter off stack
+        mov     ecx, sourceEnd          // restore ecx
+        mov     eax, sourceByteStride   // restore eax
+        */
+
+    // generate dither
+        mov     sourceByteStride, eax   // save eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed1
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     ditherRandSeed1, eax
+        mov     edx, 196314165
+        mov     eax, ditherRandSeed2
+        mul     edx                     // eax:edx = eax * 196314165
+        //add     eax, 907633515
+        lea     eax, [eax+907633515]
+        mov     edx, ditherRandSeed1
+        shr     edx, PA_DITHER_SHIFT_
+        mov     ditherRandSeed2, eax
+        shr     eax, PA_DITHER_SHIFT_
+        //add     eax, edx                // eax -> current
+        lea     eax, [eax+edx]            // current = randSeed1>>x + randSeed2>>x
+        mov     edx, ditherPrevious
+        neg     edx
+        lea     edx, [eax+edx]          // highpass = current - previous
+        mov     highpassedDither, edx
+        mov     ditherPrevious, eax     // previous = current
+        mov     eax, sourceByteStride   // restore eax
+        fild    highpassedDither
+        fmul    const_float_dither_scale_
+    // end generate dither, dither signal in st(0)
+        
+        faddp   st(1), st(0)            // stack: dither * value*(int scaler), int scaler
+        fistp   word ptr [edi]          // store scaled int into dest, stack:  int scaler
+        jmp     Float32_To_Int16_DitherClip_stored
+    
+    Float32_To_Int16_DitherClip_clamp:
+        mov     edx, dword ptr [esi]    // load floating point value into integer register
+        shr     edx, 31                 // move sign bit into bit 0
+        add     esi, eax                // increment source ptr
+        //lea     esi, [esi+eax]
+        add     dx, 0x7FFF              // convert to maximum range integers
+        mov     word ptr [edi], dx      // store clamped into into dest
+
+    Float32_To_Int16_DitherClip_stored:
+
+        add     edi, ebx                // increment destination ptr
+        //lea     edi, [edi+ebx]
+        
+        cmp     esi, ecx                // has src ptr reached end?
+        jne     Float32_To_Int16_DitherClip_loop
+
+        ffree   st(0)
+        fincstp
+
+        fwait
+        fnclex
+        fldcw   savedFpuControlWord
+    }
+
+    ditherGenerator->previous = ditherPrevious;
+    ditherGenerator->randSeed1 = ditherRandSeed1;
+    ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+void PaUtil_InitializeX86PlainConverters( void )
+{
+    paConverters.Float32_To_Int32 = Float32_To_Int32;
+    paConverters.Float32_To_Int32_Clip = Float32_To_Int32_Clip;
+    paConverters.Float32_To_Int32_DitherClip = Float32_To_Int32_DitherClip;
+
+    paConverters.Float32_To_Int24 = Float32_To_Int24;
+    paConverters.Float32_To_Int24_Clip = Float32_To_Int24_Clip;
+    paConverters.Float32_To_Int24_DitherClip = Float32_To_Int24_DitherClip;
+    
+    paConverters.Float32_To_Int16 = Float32_To_Int16;
+    paConverters.Float32_To_Int16_Clip = Float32_To_Int16_Clip;
+    paConverters.Float32_To_Int16_DitherClip = Float32_To_Int16_DitherClip;
+}
+
+#endif
+
+/* -------------------------------------------------------------------------- */
diff --git a/portaudio/src/os/win/pa_x86_plain_converters.h b/portaudio/src/os/win/pa_x86_plain_converters.h
new file mode 100644 (file)
index 0000000..1623115
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Plain Intel IA32 assembly implementations of PortAudio sample converter functions.
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+*/
+
+#ifndef PA_X86_PLAIN_CONVERTERS_H
+#define PA_X86_PLAIN_CONVERTERS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/**
+ @brief Install optimized converter functions suitable for all IA32 processors
+
+ It is recommended to call PaUtil_InitializeX86PlainConverters prior to calling Pa_Initialize
+*/
+void PaUtil_InitializeX86PlainConverters( void );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_X86_PLAIN_CONVERTERS_H */
diff --git a/portmidi/CHANGELOG.txt b/portmidi/CHANGELOG.txt
new file mode 100644 (file)
index 0000000..c2a083a
--- /dev/null
@@ -0,0 +1,192 @@
+/* CHANGELOG FOR PORTMIDI
+ *
+ * 19Oct09 Roger Dannenberg
+ * - Changes dynamic library names from portmidi_d to portmidi to
+ *   be backward-compatible with programs expecting a library by
+ *   the old name.
+ *
+ * 04Oct09 Roger Dannenberg
+ * - Converted to using Cmake.
+ * - Renamed static and dynamic library files to portmidi_s and portmidi_d
+ * - Eliminated VC9 and VC8 files (went back to simply test.vcproj, etc.,
+ *   use Cmake to switch from the provided VC9 files to VC8 or other)
+ * - Many small changes to prepare for 64-bit architectures (but only 
+ *   tested on 32-bit machines)
+ *
+ * 16Jun09 Roger Dannenberg
+ * - Started using Microsoft Visual C++ Version 9 (Express). Converted
+ * all *-VC9.vcproj file to *.vcproj and renamed old project files to 
+ * *-VC8.proj. Previously, output from VC9 went to special VC9 files,
+ * that breaks any program or script looking for output in release or
+ * debug files, so now both compiler version output to the same folders.
+ * Now, debug version uses static linking with debug DLL runtime, and 
+ * release version uses static linking with statically linked runtime.
+ * Converted to Inno Setup and worked on scripts to make things build
+ * properly, especially pmdefaults.
+ *
+ * 02Jan09 Roger Dannenberg
+ * - Created Java interface and wrote PmDefaults application to set
+ *   values for Pm_GetDefaultInputDeviceID() and 
+ *   Pm_GetDefaultOutputDeviceID(). Other fixes.
+ *
+ * 19Jun08 Roger Dannenberg and Austin Sung
+ * - Removed USE_DLL_FOR_CLEANUP -- Windows 2000 through Vista seem to be
+ *   fixed now, and can recover if MIDI ports are left open
+ * - Various other minor patches
+ *
+ * 17Jan07 Roger Dannenberg
+ * - Lots more help for Common Lisp user in pm_cl
+ * - Minor fix to eliminate a compiler warning
+ * - Went back to single library in OS X for both portmidi and porttime
+ *
+ * 16Jan07 Roger Dannenberg
+ * - OOPS! fixed bug where short messages all had zero data
+ * - Makefile.osx static library build now makes universal (i386 + ppc)
+ *    binaries
+ *
+ * 15Jan07 Roger Dannenberg
+ *  - multiple rewrites of sysex handling code to take care of 
+ *     error-handling, embedded messages, message filtering,
+ *     driver bugs, and host limitations.
+ *  - fixed windows to use dwBufferLength rather than 
+ *     dwBytesRecorded for long buffer output (fix by Nigel Brown)
+ *  - Win32 MME code always appends an extra zero to long buffer
+ *     output to work around a problem with earlier versions of Midi Yoke
+ *  - Added mm, a command line Midi Monitor to pm_test suite
+ *  - Revised copyright notice to match PortAudio/MIT license (requests 
+ *     are moved out of the license proper and into a separate paragraph)
+ *
+ * 18Oct06 Roger Dannenberg
+ *  - replace FIFO in pmutil with Light Pipe-based multiprocessor-safe alg.
+ *  - replace FIFO in portmidi.c with PmQueue from pmutil
+ *
+ * 07Oct06 cpr & Roger Dannenberg
+ *  - overhaul of CoreMIDI input to handle running status and multiple
+ *  -    messages per packet, with additional error detection
+ *  - added Leigh Smith and Rick Taube support for Common Lisp and
+ *  -    dynamic link libraries in OSX
+ *  - initialize static global seq = NULL in pmlinuxalsa.c
+ *
+ * 05Sep06 Sebastien Frippiat
+ *  - check if (ALSA) seq exists before closing it in pm_linuxalsa_term()
+ *
+ * 05Sep06 Andreas Micheler and Cecilio
+ *  - fixed memory leak by freeing someo objects in pm_winmm_term()
+ *  - and another leak by freeing descriptors in Pm_Terminate()
+ *
+ * 23Aug06 RBD
+ *  - various minor fixes
+ *
+ * 04Nov05 Olivier Tristan
+ *  - changes to OS X to properly retrieve real device name on CoreMidi
+ *
+ * 19Jul05 Roger Dannenberg
+ *  - included pmBufferMaxSize in Pm_GetErrorText()
+ *
+ * 23Mar05 Torgier Strand Henriksen
+ *  - cleaner termination of porttime thread under Linux
+ *
+ * 15Nov04 Ben Allison
+ *  - sysex output now uses one buffer/message and reallocates buffer
+ *  -    if needed
+ *  - filters expanded for many message types and channels
+ *  - detailed changes are as follows:
+ *  ------------- in pmwinmm.c --------------
+ *  - new #define symbol: OUTPUT_BYTES_PER_BUFFER
+ *  - change SYSEX_BYTES_PER_BUFFER to 1024
+ *  - added MIDIHDR_BUFFER_LENGTH(x) to correctly count midihdr buffer length
+ *  - change MIDIHDR_SIZE(x) to (MIDIHDR_BUFFER_LENGTH(x) + sizeof(MIDIHDR))
+ *  - change allocate_buffer to use new MIDIHDR_BUFFER_LENGTH macro
+ *  - new macros for MIDIHDR_SYSEX_SIZE and MIDIHDR_SYSEX_BUFFER_LENGTH 
+ *  -    similar to above, but counts appropriately for sysex messages
+ *  - added the following members to midiwinmm_struct for sysex data:
+ *  -    LPMIDIHDR *sysex_buffers;   ** pool of buffers for sysex data **
+ *  -    int num_sysex_buffers;      ** how many sysex buffers **
+ *  -    int next_sysex_buffer;      ** index of next sysexbuffer to send **
+ *  -    HANDLE sysex_buffer_signal; ** to wait for free sysex buffer **
+ *  - duplicated allocate_buffer, alocate_buffers and get_free_output_buffer 
+ *  -    into equivalent sysex_buffer form
+ *  - changed winmm_in_open to initialize new midiwinmm_struct members and 
+ *  -    to use the new allocate_sysex_buffer() function instead of 
+ *  -    allocate_buffer()
+ *  - changed winmm_out_open to initialize new members, create sysex buffer 
+ *  -    signal, and allocate 2 sysex buffers
+ *  - changed winmm_out_delete to free sysex buffers and shut down the sysex
+ *  -    buffer signal
+ *  - create new function resize_sysex_buffer which resizes m->hdr to the 
+ *  -    passed size, and corrects the midiwinmm_struct accordingly.
+ *  - changed winmm_write_byte to use new resize_sysex_buffer function,
+ *  -    if resize fails, write current buffer to output and continue
+ *  - changed winmm_out_callback to use buffer_signal or sysex_buffer_signal
+ *  -    depending on which buffer was finished
+ *  ------------- in portmidi.h --------------
+ *  - added pmBufferMaxSize to PmError to indicate that the buffer would be
+ *  -    too large for the underlying API
+ *  - added additional filters
+ *  - added prototype, documentation, and helper macro for Pm_SetChannelMask
+ *  ------------- in portmidi.c --------------
+ *  - added pm_status_filtered() and pm_realtime_filtered() functions to
+ *       separate filtering logic from buffer logic in pm_read_short
+ *  - added Pm_SetChannelMask function
+ *  - added pm_channel_filtered() function
+ *  ------------- in pminternal.h --------------
+ *  - added member to PortMidiStream for channel mask
+ *
+ * 25May04 RBD
+ *  - removed support for MIDI THRU
+ *  - moved filtering from Pm_Read to pm_enqueue to avoid buffer ovfl
+ *  - extensive work on Mac OS X port, especially sysex and error handling
+ *
+ * 18May04 RBD
+ *  - removed side-effects from assert() calls. Now you can disable assert().
+ *  - no longer check pm_hosterror everywhere, fixing a bug where an open
+ *    failure could cause a write not to work on a previously opened port
+ *    until you call Pm_GetHostErrorText().
+ * 16May04 RBD and Chris Roberts
+ *  - Some documentation wordsmithing in portmidi.h
+ *  - Dynamically allocate port descriptor structures
+ *  - Fixed parameter error in midiInPrepareBuffer and midiInAddBuffer.
+ *
+ * 09Oct03 RBD
+ *  - Changed Thru handling. Now the client does all the work and the client
+ *    must poll or read to keep thru messages flowing.
+ *
+ * 31May03 RBD
+ *  - Fixed various bugs.
+ *  - Added linux ALSA support with help from Clemens Ladisch
+ *  - Added Mac OS X support, implemented by Jon Parise, updated and 
+ *       integrated by Andrew Zeldis and Zico Kolter
+ *  - Added latency program to build histogram of system latency using PortTime.
+ *
+ * 30Jun02 RBD Extensive rewrite of sysex handling. It works now.
+ *             Extensive reworking of error reporting and error text -- no
+ *             longer use dictionary call to delete data; instead, Pm_Open
+ *             and Pm_Close clean up before returning an error code, and 
+ *             error text is saved in a system-independent location.
+ *             Wrote sysex.c to test sysex message handling.
+ *
+ * 15Jun02 BCT changes:
+ *  - Added pmHostError text handling.
+ *  - For robustness, check PortMidi stream args not NULL.
+ *  - Re-C-ANSI-fied code (changed many C++ comments to C style)
+ *  - Reorganized code in pmwinmm according to input/output functionality (made
+ *    cleanup handling easier to reason about)
+ *  - Fixed Pm_Write calls (portmidi.h says these should not return length but Pm_Error)
+ *  - Cleaned up memory handling (now system specific data deleted via dictionary
+ *    call in PortMidi, allows client to query host errors).
+ *  - Added explicit asserts to verify various aspects of pmwinmm implementation behaves as
+ *    logic implies it should. Specifically: verified callback routines not reentrant and
+ *    all verified status for all unchecked Win32 MMedia API calls perform successfully
+ *  - Moved portmidi initialization and clean-up routines into DLL to fix Win32 MMedia API 
+ *    bug (i.e. if devices not explicitly closed, must reboot to debug application further).
+ *    With this change, clients no longer need explicitly call Pm_Initialize, Pm_Terminate, or
+ *    explicitly Pm_Close open devices when using WinMM version of PortMidi.
+ *
+ * 23Jan02 RBD Fixed bug in pmwinmm.c thru handling
+ *
+ * 21Jan02 RBD Added tests in Pm_OpenInput() and Pm_OpenOutput() to prevent 
+ *               opening an input as output and vice versa.
+ *             Added comments and documentation.
+ *             Implemented Pm_Terminate().
+ *
+ */
diff --git a/portmidi/CMakeLists.txt b/portmidi/CMakeLists.txt
new file mode 100644 (file)
index 0000000..febf84a
--- /dev/null
@@ -0,0 +1,20 @@
+
+add_library(
+    portmidi SHARED
+
+    pm_common/pminternal.h
+    pm_common/pmutil.c
+    pm_common/pmutil.h
+    pm_common/portmidi.c
+    pm_common/portmidi.h
+
+    pm_win/pmwin.c
+    pm_win/pmwinmm.c
+    pm_win/pmwinmm.h
+
+    porttime/porttime.c
+    porttime/porttime.h
+    porttime/ptwinmm.c
+)
+
+target_link_libraries(portmidi winmm)
diff --git a/portmidi/README.txt b/portmidi/README.txt
new file mode 100644 (file)
index 0000000..18d951e
--- /dev/null
@@ -0,0 +1,84 @@
+README for PortMidi
+
+Roger B. Dannenberg
+
+VERSION: please use "svn info" to get info.
+
+Documentation for PortMidi is found in pm_common/portmidi.h.
+
+Additional documentation:
+  - Windows: see pm_win/README_WIN.txt and pm_win/debugging_dlls.txt
+  - Linux: see pm_linux/README_LINUX.txt
+  - Mac OSX: see pm_mac/README_MAC.txt
+  - Common Lisp: see pm_cl/README_CL.txt
+  - Eclipse: see portmidi_cdt.zip (this was contributed as is; the dlls here
+        are now -- Sep 09 -- out of date. What is really needed is a script
+        to generate this release automatically so we can maintain it.)
+  - C-Sharp: see pm_csharp.zip (also contributed as is)
+
+---------- some notes on the design of PortMidi ----------
+
+POINTERS VS DEVICE NUMBERS
+
+When you open a MIDI port, PortMidi allocates a structure to
+maintain the state of the open device. Since every device is
+also listed in a table, you might think it would be simpler to
+use the table index rather than a pointer to identify a device.
+This would also help with error checking (it's hard to make
+sure a pointer is valid). PortMidi's design parallels that of
+PortAudio.
+
+ERROR HANDLING
+
+Error handling turned out to be much more complicated than expected.
+PortMidi functions return error codes that the caller can check.
+In addition, errors may occur asynchronously due to MIDI input.
+However, for Windows, there are virtually no errors that can
+occur if the code is correct and not passing bogus values. One
+exception is an error that the system is out of memory, but my
+guess is that one is unlikely to recover gracefully from that.
+Therefore, all errors in callbacks are guarded by assert(), which
+means not guarded at all in release configurations.
+
+Ordinarily, the caller checks for an error code. If the error is
+system-dependent, pmHostError is returned and the caller can
+call Pm_GetHostErrorText to get a text description of the error.
+
+Host error codes are system-specific and are recorded in the
+system-specific data allocated for each open MIDI port.
+However, if an error occurs on open or close,
+we cannot store the error with the device because there will be
+no device data (assuming PortMidi cleans up after devices that
+are not open). For open and close, we will convert the error
+to text, copy it to a global string, and set pm_hosterror, a
+global flag.
+
+Similarly, whenever a Read or Write operation returns pmHostError,
+the corresponding error string is copied to a global string
+and pm_hosterror is set. This makes getting error strings
+simple and uniform, although it does cost a string copy and some
+overhead even if the user does not want to look at the error data.
+
+The system-specific Read, Write, Poll, etc. implementations should
+check for asynchronous errors and return immediately if one is
+found so that these get reported. This happens in the Mac OS X
+code, where lots of things are happening in callbacks, but again,
+in Windows, there are no error codes recorded in callbacks.
+
+DEBUGGING
+
+If you are building a console application for research, we suggest
+compiling with the option PM_CHECK_ERRORS. This will insert a
+check for error return values at the end of each PortMidi
+function. If an error is encountered, a text message is printed
+using printf(), the user is asked to type ENTER, and then exit(-1)
+is called to clean up and terminate the program.
+
+You should not use PM_CHECK_ERRORS if printf() does not work
+(e.g. this is not a console application under Windows, or there
+is no visible console on some other OS), and you should not use
+PM_CHECK_ERRORS if you intend to recover from errors rather than
+abruptly terminate the program.
+
+The Windows version (and perhaps others) also offers a DEBUG
+compile-time option. See README_WIN.txt.
diff --git a/portmidi/license.txt b/portmidi/license.txt
new file mode 100644 (file)
index 0000000..c757b37
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * PortMidi Portable Real-Time MIDI Library
+ *
+ * license.txt -- a copy of the PortMidi copyright notice and license information
+ *
+ * Latest version available at: http://sourceforge.net/projects/portmedia
+ *
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ * Copyright (c) 2001-2009 Roger B. Dannenberg
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortMidi license; however, 
+ * the PortMusic community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
diff --git a/portmidi/portmidi.vcproj b/portmidi/portmidi.vcproj
deleted file mode 100644 (file)
index fbb0170..0000000
+++ /dev/null
@@ -1,243 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="portmidi"
-       ProjectGUID="{91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}"
-       RootNamespace="portmidi"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories=".\pm_common,.\pm_win,.\porttime"
-                               PreprocessorDefinitions="_DEBUG;_MD;_CONSOLE;_LIB;WIN32"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="3"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/portmidi.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\portmidi.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories=".\pm_common,.\pm_win,.\porttime"
-                               PreprocessorDefinitions="NDEBUG;_MD;_CONSOLE;_LIB;WIN32"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/portmidi.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\portmidi.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\pm_common\pmutil.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_win\pmwin.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_win\pmwinmm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_common\portmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\porttime\porttime.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\porttime\ptwinmm.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\pm_common\pminternal.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_common\pmutil.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_win\pmwinmm.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pm_common\portmidi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\porttime\porttime.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/portmidi/portmidi.vcxproj b/portmidi/portmidi.vcxproj
deleted file mode 100644 (file)
index fd3322e..0000000
+++ /dev/null
@@ -1,235 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}</ProjectGuid>
-    <RootNamespace>portmidi</RootNamespace>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>.\pm_common;.\pm_win;.\porttime;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MD;_CONSOLE;_LIB;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/portmidi.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\portmidi.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>.\pm_common;.\pm_win;.\porttime;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MD;_CONSOLE;_LIB;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/portmidi.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\portmidi.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>.\pm_common;.\pm_win;.\porttime;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MD;_CONSOLE;_LIB;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/portmidi.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\portmidi.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>.\pm_common;.\pm_win;.\porttime;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MD;_CONSOLE;_LIB;WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/portmidi.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\portmidi.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="pm_common\pmutil.c" />
-    <ClCompile Include="pm_win\pmwin.c" />
-    <ClCompile Include="pm_win\pmwinmm.c" />
-    <ClCompile Include="pm_common\portmidi.c" />
-    <ClCompile Include="porttime\porttime.c" />
-    <ClCompile Include="porttime\ptwinmm.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="pm_common\pminternal.h" />
-    <ClInclude Include="pm_common\pmutil.h" />
-    <ClInclude Include="pm_win\pmwinmm.h" />
-    <ClInclude Include="pm_common\portmidi.h" />
-    <ClInclude Include="porttime\porttime.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/portmidi/portmidi.vcxproj.filters b/portmidi/portmidi.vcxproj.filters
deleted file mode 100644 (file)
index 88d2e59..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{c966fa0f-c04b-4e20-a38c-56044533b464}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{251417e9-fcb1-4ffe-adcd-af4e412b35f3}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="pm_common\pmutil.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pm_win\pmwin.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pm_win\pmwinmm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="pm_common\portmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="porttime\porttime.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="porttime\ptwinmm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="pm_common\pminternal.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="pm_common\pmutil.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="pm_win\pmwinmm.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="pm_common\portmidi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="porttime\porttime.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/portmidi/portmidi.vcxproj.user b/portmidi/portmidi.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/portmidi/porttime/ptlinux.c b/portmidi/porttime/ptlinux.c
deleted file mode 100644 (file)
index 768dd48..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/* ptlinux.c -- portable timer implementation for linux */
-
-
-/* IMPLEMENTATION NOTES (by Mark Nelson): 
-
-Unlike Windows, Linux has no system call to request a periodic callback,
-so if Pt_Start() receives a callback parameter, it must create a thread
-that wakes up periodically and calls the provided callback function.
-If running as superuser, use setpriority() to renice thread to -20.  
-One could also set the timer thread to a real-time priority (SCHED_FIFO
-and SCHED_RR), but this is dangerous for This is necessary because  
-if the callback hangs it'll never return. A more serious reason
-is that the current scheduler implementation busy-waits instead 
-of sleeping when realtime threads request a sleep of <=2ms (as a way 
-to get around the 10ms granularity), which means the thread would never 
-let anyone else on the CPU.
-
-CHANGE LOG
-
-18-Jul-03 Roger Dannenberg -- Simplified code to set priority of timer
-            thread. Simplified implementation notes. 
-
-*/
-/* stdlib, stdio, unistd, and sys/types were added because they appeared
- * in a Gentoo patch, but I'm not sure why they are needed. -RBD
- */
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include "porttime.h"
-#include "sys/time.h"
-#include "sys/resource.h"
-#include "sys/timeb.h"
-#include "pthread.h"
-
-#define TRUE 1
-#define FALSE 0
-
-static int time_started_flag = FALSE;
-static struct timeb time_offset = {0, 0, 0, 0};
-static pthread_t pt_thread_pid;
-static int pt_thread_created = FALSE;
-
-/* note that this is static data -- we only need one copy */
-typedef struct {
-    int id;
-    int resolution;
-    PtCallback *callback;
-    void *userData;
-} pt_callback_parameters;
-
-static int pt_callback_proc_id = 0;
-
-static void *Pt_CallbackProc(void *p)
-{
-    pt_callback_parameters *parameters = (pt_callback_parameters *) p;
-    int mytime = 1;
-    /* to kill a process, just increment the pt_callback_proc_id */
-    /* printf("pt_callback_proc_id %d, id %d\n", pt_callback_proc_id,
-           parameters->id); */
-    if (geteuid() == 0) setpriority(PRIO_PROCESS, 0, -20);
-    while (pt_callback_proc_id == parameters->id) {
-        /* wait for a multiple of resolution ms */
-        struct timeval timeout;
-        int delay = mytime++ * parameters->resolution - Pt_Time();
-        if (delay < 0) delay = 0;
-        timeout.tv_sec = 0;
-        timeout.tv_usec = delay * 1000;
-        select(0, NULL, NULL, NULL, &timeout);
-        (*(parameters->callback))(Pt_Time(), parameters->userData);
-    }
-    /* printf("Pt_CallbackProc exiting\n"); */
-    // free(parameters);
-    return NULL;
-}
-
-
-PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
-{
-    if (time_started_flag) return ptNoError;
-    ftime(&time_offset); /* need this set before process runs */
-    if (callback) {
-        int res;
-        pt_callback_parameters *parms = (pt_callback_parameters *) 
-            malloc(sizeof(pt_callback_parameters));
-        if (!parms) return ptInsufficientMemory;
-        parms->id = pt_callback_proc_id;
-        parms->resolution = resolution;
-        parms->callback = callback;
-        parms->userData = userData;
-        res = pthread_create(&pt_thread_pid, NULL, 
-                             Pt_CallbackProc, parms);
-        if (res != 0) return ptHostError;
-        pt_thread_created = TRUE;
-    }
-    time_started_flag = TRUE;
-    return ptNoError;
-}
-
-
-PtError Pt_Stop()
-{
-    /* printf("Pt_Stop called\n"); */
-    pt_callback_proc_id++;
-    if (pt_thread_created) {
-        pthread_join(pt_thread_pid, NULL);
-        pt_thread_created = FALSE;
-    }
-    time_started_flag = FALSE;
-    return ptNoError;
-}
-
-
-int Pt_Started()
-{
-    return time_started_flag;
-}
-
-
-PtTimestamp Pt_Time()
-{
-    long seconds, milliseconds;
-    struct timeb now;
-    ftime(&now);
-    seconds = now.time - time_offset.time;
-    milliseconds = now.millitm - time_offset.millitm;
-    return seconds * 1000 + milliseconds;
-}
-
-
-void Pt_Sleep(int32_t duration)
-{
-    usleep(duration * 1000);
-}
-
-
-
diff --git a/portmidi/porttime/ptmacosx_cf.c b/portmidi/porttime/ptmacosx_cf.c
deleted file mode 100644 (file)
index 3eb0de1..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-/* ptmacosx.c -- portable timer implementation for mac os x */
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <pthread.h>
-#include <CoreFoundation/CoreFoundation.h>
-
-#import <mach/mach.h>
-#import <mach/mach_error.h>
-#import <mach/mach_time.h>
-#import <mach/clock.h>
-
-#include "porttime.h"
-
-#define THREAD_IMPORTANCE 30
-#define LONG_TIME 1000000000.0
-
-static int time_started_flag = FALSE;
-static CFAbsoluteTime startTime = 0.0;
-static CFRunLoopRef timerRunLoop;
-
-typedef struct {
-    int resolution;
-    PtCallback *callback;
-    void *userData;
-} PtThreadParams;
-
-
-void Pt_CFTimerCallback(CFRunLoopTimerRef timer, void *info)
-{
-    PtThreadParams *params = (PtThreadParams*)info;
-    (*params->callback)(Pt_Time(), params->userData);
-}
-
-static void* Pt_Thread(void *p)
-{
-    CFTimeInterval timerInterval;
-    CFRunLoopTimerContext timerContext;
-    CFRunLoopTimerRef timer;
-    PtThreadParams *params = (PtThreadParams*)p;
-    //CFTimeInterval timeout;
-
-    /* raise the thread's priority */
-    kern_return_t error;
-    thread_extended_policy_data_t extendedPolicy;
-    thread_precedence_policy_data_t precedencePolicy;
-
-    extendedPolicy.timeshare = 0;
-    error = thread_policy_set(mach_thread_self(), THREAD_EXTENDED_POLICY,
-                              (thread_policy_t)&extendedPolicy,
-                              THREAD_EXTENDED_POLICY_COUNT);
-    if (error != KERN_SUCCESS) {
-        mach_error("Couldn't set thread timeshare policy", error);
-    }
-
-    precedencePolicy.importance = THREAD_IMPORTANCE;
-    error = thread_policy_set(mach_thread_self(), THREAD_PRECEDENCE_POLICY,
-                              (thread_policy_t)&precedencePolicy,
-                              THREAD_PRECEDENCE_POLICY_COUNT);
-    if (error != KERN_SUCCESS) {
-        mach_error("Couldn't set thread precedence policy", error);
-    }
-
-    /* set up the timer context */
-    timerContext.version = 0;
-    timerContext.info = params;
-    timerContext.retain = NULL;
-    timerContext.release = NULL;
-    timerContext.copyDescription = NULL;
-
-    /* create a new timer */
-    timerInterval = (double)params->resolution / 1000.0;
-    timer = CFRunLoopTimerCreate(NULL, startTime+timerInterval, timerInterval,
-                                 0, 0, Pt_CFTimerCallback, &timerContext);
-
-    timerRunLoop = CFRunLoopGetCurrent();
-    CFRunLoopAddTimer(timerRunLoop, timer, CFSTR("PtTimeMode"));
-
-    /* run until we're told to stop by Pt_Stop() */
-    CFRunLoopRunInMode(CFSTR("PtTimeMode"), LONG_TIME, false);
-    
-    CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, CFSTR("PtTimeMode"));
-    CFRelease(timer);
-    free(params);
-
-    return NULL;
-}
-
-PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
-{
-    PtThreadParams *params = (PtThreadParams*)malloc(sizeof(PtThreadParams));
-    pthread_t pthread_id;
-
-    printf("Pt_Start() called\n");
-
-    // /* make sure we're not already playing */
-    if (time_started_flag) return ptAlreadyStarted;
-    startTime = CFAbsoluteTimeGetCurrent();
-
-    if (callback) {
-    
-        params->resolution = resolution;
-        params->callback = callback;
-        params->userData = userData;
-    
-        pthread_create(&pthread_id, NULL, Pt_Thread, params);
-    }
-
-    time_started_flag = TRUE;
-    return ptNoError;
-}
-
-
-PtError Pt_Stop()
-{
-    printf("Pt_Stop called\n");
-
-    CFRunLoopStop(timerRunLoop);
-    time_started_flag = FALSE;
-    return ptNoError;
-}
-
-
-int Pt_Started()
-{
-    return time_started_flag;
-}
-
-
-PtTimestamp Pt_Time()
-{
-    CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
-    return (PtTimestamp) ((now - startTime) * 1000.0);
-}
-
-
-void Pt_Sleep(int32_t duration)
-{
-    usleep(duration * 1000);
-}
diff --git a/portmidi/porttime/ptmacosx_mach.c b/portmidi/porttime/ptmacosx_mach.c
deleted file mode 100644 (file)
index c23210e..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/* ptmacosx.c -- portable timer implementation for mac os x */
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <CoreAudio/HostTime.h>
-
-#import <mach/mach.h>
-#import <mach/mach_error.h>
-#import <mach/mach_time.h>
-#import <mach/clock.h>
-#include <unistd.h>
-
-#include "porttime.h"
-#include "sys/time.h"
-#include "pthread.h"
-
-#define NSEC_PER_MSEC 1000000
-#define THREAD_IMPORTANCE 30
-
-static int time_started_flag = FALSE;
-static UInt64 start_time;
-static pthread_t pt_thread_pid;
-
-/* note that this is static data -- we only need one copy */
-typedef struct {
-    int id;
-    int resolution;
-    PtCallback *callback;
-    void *userData;
-} pt_callback_parameters;
-
-static int pt_callback_proc_id = 0;
-
-static void *Pt_CallbackProc(void *p)
-{
-    pt_callback_parameters *parameters = (pt_callback_parameters *) p;
-    int mytime = 1;
-
-    kern_return_t error;
-    thread_extended_policy_data_t extendedPolicy;
-    thread_precedence_policy_data_t precedencePolicy;
-
-    extendedPolicy.timeshare = 0;
-    error = thread_policy_set(mach_thread_self(), THREAD_EXTENDED_POLICY,
-                              (thread_policy_t)&extendedPolicy,
-                              THREAD_EXTENDED_POLICY_COUNT);
-    if (error != KERN_SUCCESS) {
-        mach_error("Couldn't set thread timeshare policy", error);
-    }
-
-    precedencePolicy.importance = THREAD_IMPORTANCE;
-    error = thread_policy_set(mach_thread_self(), THREAD_PRECEDENCE_POLICY,
-                              (thread_policy_t)&precedencePolicy,
-                              THREAD_PRECEDENCE_POLICY_COUNT);
-    if (error != KERN_SUCCESS) {
-        mach_error("Couldn't set thread precedence policy", error);
-    }
-    
-    
-    /* to kill a process, just increment the pt_callback_proc_id */
-    /* printf("pt_callback_proc_id %d, id %d\n", pt_callback_proc_id, parameters->id); */
-    while (pt_callback_proc_id == parameters->id) {
-        /* wait for a multiple of resolution ms */
-        UInt64 wait_time;
-        int delay = mytime++ * parameters->resolution - Pt_Time();
-       PtTimestamp timestamp;
-        if (delay < 0) delay = 0;
-        wait_time = AudioConvertNanosToHostTime((UInt64)delay * NSEC_PER_MSEC);
-        wait_time += AudioGetCurrentHostTime();
-        error = mach_wait_until(wait_time);
-       timestamp = Pt_Time();
-        (*(parameters->callback))(timestamp, parameters->userData);
-    }
-    free(parameters);
-    return NULL;
-}
-
-
-PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
-{
-    if (time_started_flag) return ptAlreadyStarted;
-    start_time = AudioGetCurrentHostTime();
-    
-    if (callback) {
-        int res;
-        pt_callback_parameters *parms;
-
-        parms = (pt_callback_parameters *) malloc(sizeof(pt_callback_parameters));
-        if (!parms) return ptInsufficientMemory;
-        parms->id = pt_callback_proc_id;
-        parms->resolution = resolution;
-        parms->callback = callback;
-        parms->userData = userData;
-        res = pthread_create(&pt_thread_pid, NULL, Pt_CallbackProc, parms);
-        if (res != 0) return ptHostError;
-    }
-    
-    time_started_flag = TRUE;
-    return ptNoError;
-}
-
-
-PtError Pt_Stop()
-{
-    /* printf("Pt_Stop called\n"); */
-    pt_callback_proc_id++;
-    pthread_join(pt_thread_pid, NULL);
-    time_started_flag = FALSE;
-    return ptNoError;
-}
-
-
-int Pt_Started()
-{
-    return time_started_flag;
-}
-
-
-PtTimestamp Pt_Time()
-{
-    UInt64 clock_time, nsec_time;
-    clock_time = AudioGetCurrentHostTime() - start_time;
-    nsec_time = AudioConvertHostTimeToNanos(clock_time);
-    return (PtTimestamp)(nsec_time / NSEC_PER_MSEC);
-}
-
-
-void Pt_Sleep(int32_t duration)
-{
-    usleep(duration * 1000);
-}
index cd04b04..e7746a9 100644 (file)
@@ -13,6 +13,8 @@ add_executable(
     ../interface/dumb_c.c
     ../timidity/common.c
     ../timidity/controls.c
+    ../timidity/decode.c
+    ../timidity/dls.cpp
     ../timidity/envelope.c
     ../timidity/filter.c
     ../timidity/freq.c
@@ -25,15 +27,23 @@ add_executable(
     ../timidity/sbkconv.c
     ../timidity/sffile.c
     ../timidity/sfitem.c
+    ../timidity/sfz.cpp
     ../timidity/smplfile.c
     ../timidity/tables.c
     ../timidity/version.c
+    ../timidity/w32_libFLAC_dll.c
+    ../timidity/w32_libmpg123_dll.c
+    ../timidity/w32g_vorbis_dll.c
+    ../timidity/w32g_vorbisfile_dll.c
+
 
     OpenDlg.h
     resource.h
     ../libarc/arc.h
     ../timidity/common.h
     ../timidity/controls.h
+    ../timidity/decode.h
+    ../timidity/dls.h
     ../timidity/envelope.h
     ../timidity/filter.h
     ../timidity/instrum.h
@@ -48,6 +58,7 @@ add_executable(
     ../timidity/sffile.h
     ../timidity/sfitem.h
     ../timidity/sflayer.h
+    ../timidity/sfz.h
     ../timidity/tables.h
     ../timidity/timidity.h
     ../timidity/wrd.h
index 7c4088f..fb33c03 100644 (file)
@@ -38,10 +38,6 @@ void CreateSoundFontTree(HWND hDlg, LPCSTR x_sf_filename_)
 
        //TreeView_DeleteAllItems(hTree);
 
-       if (_stricmp(PathFindExtension(x_sf_filename_), ".sf2")) {
-               return;
-       }
-
        for (x_bank = 0; x_bank <= 127; x_bank++) {
                for (x_preset = 0; x_preset <= 127; x_preset++) {
                        x_cfg_info.m_str[x_bank][x_preset] = NULL;
index cd973e2..dae4ce8 100644 (file)
@@ -8,8 +8,8 @@
 #define IDB_BITMAP1                     104
 #define IDB_TREEICON                    104
 #define IDC_TREE1                       1001
-#define IDC_EDIT1                       1002
 #define IDC_EDSFNAME                    1002
+#define IDC_EDSFLABEL                   1003
 #define ID_FILE_OPENSOUNDFONT           40001
 #define ID_FILE_QUIT                    40002
 #define ID_FILE_SAVETIMIDITYCONFIGFILE  40003
 #define IDM_OPT_APPEND_COMMENT          40010
 #define IDM_OPT_APPEND_FSPACES          40011
 #define IDM_OPT_KEEP_FULLPATH           40012
+#define IDM_OPT_PREPEND_BASEDIR         40013
 
 // Next default values for new objects
 // 
 #ifdef APSTUDIO_INVOKED
 #ifndef APSTUDIO_READONLY_SYMBOLS
 #define _APS_NEXT_RESOURCE_VALUE        105
-#define _APS_NEXT_COMMAND_VALUE         40013
-#define _APS_NEXT_CONTROL_VALUE         1003
+#define _APS_NEXT_COMMAND_VALUE         40014
+#define _APS_NEXT_CONTROL_VALUE         1004
 #define _APS_NEXT_SYMED_VALUE           101
 #endif
 #endif
index 8e7f62b..e6088fb 100644 (file)
@@ -23,11 +23,12 @@ BEGIN
                MENUITEM "Append first spaces(&P)", IDM_OPT_APPEND_FSPACES
                MENUITEM SEPARATOR
                MENUITEM "Keep original full-path(&K)", IDM_OPT_KEEP_FULLPATH
+               MENUITEM "Prepend ""dir ${basedir}""(&D)", IDM_OPT_PREPEND_BASEDIR
        END
 END
 
 101 DIALOGEX 0, 0, 255, 195
-STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU
+STYLE WS_OVERLAPPEDWINDOW
 EXSTYLE WS_EX_ACCEPTFILES
 CAPTION "Soundfont Viewer 1.01"
 MENU IDR_MENU1
@@ -35,7 +36,7 @@ LANGUAGE LANG_JAPANESE, 0x1
 FONT 9, "MS UI Gothic", FW_NORMAL, 0, 128
 BEGIN
        CONTROL         "", IDC_TREE1, WC_TREEVIEW, WS_TABSTOP | WS_HSCROLL | WS_BORDER | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT, 0, 0, 255, 182
-       LTEXT           "Soundfont Path", -1, 0, 183, 56, 12, SS_LEFT
+       LTEXT           "Soundfont Path", IDC_EDSFLABEL, 0, 183, 56, 12, SS_LEFT
        EDITTEXT        IDC_EDSFNAME, 57, 183, 198, 12, NOT WS_BORDER | ES_AUTOHSCROLL | ES_READONLY
 END
 
index d32a77f..27738b3 100644 (file)
@@ -3,6 +3,7 @@
 #define _CRT_SECURE_NO_WARNINGS
 #pragma warning(disable:4530) // \83A\83\93\83\8f\83C\83\93\83\83Z\83}\83\93\83e\83B\83N\83X\82ª\96³\8cø
 #include <windows.h>
+#include <windowsx.h>
 #include <commctrl.h>
 #include "resource.h"
 #pragma comment(lib, "shlwapi.lib")
@@ -80,14 +81,13 @@ extern "C" void InsertDrum(int bank, int preset, int note, const char *str, cons
        }
 }
 
-void SFView_ExportConfigFile(char *outFileName, int outListEnable, int outComment, int outSpace, int keepFullPath)
+void SFView_ExportConfigFile(char *outFileName, int outListEnable, int outComment, int outSpace, int keepFullPath, int prependBaseDir)
 {
        FILE *fp = fopen(outFileName, "w");
+       if (!outListEnable && prependBaseDir)
+               fprintf(fp, "dir \"${basedir}\"\n");
        for (std::map< int, std::map< int, sfvSFInst > >::iterator it =  g_sfInst.begin(); it != g_sfInst.end(); ++it) {
-               if (outListEnable)
-                       fprintf(fp, "bank %d\n", (*it).first);
-               else
-                       fprintf(fp, "bank %d\n", (*it).first);
+               fprintf(fp, "bank %d\n", (*it).first);
                for (std::map< int, sfvSFInst >::iterator itc = (*it).second.begin(); itc != (*it).second.end(); ++itc) {
                        const char *file = (*itc).second.str.c_str();
                        const int program = (*itc).first;
@@ -152,8 +152,8 @@ void ExportFile(HWND hDlg, bool bExportList)
 {
        MENUITEMINFO mii = { sizeof(MENUITEMINFO) };
        HMENU hMenu = GetMenu(hDlg);
-       CONST UINT menuIDs[] = { IDM_OPT_APPEND_COMMENT, IDM_OPT_APPEND_FSPACES, IDM_OPT_KEEP_FULLPATH };
-       BOOL states[] = { FALSE, FALSE, FALSE };
+       CONST UINT menuIDs[] = { IDM_OPT_APPEND_COMMENT, IDM_OPT_APPEND_FSPACES, IDM_OPT_KEEP_FULLPATH, IDM_OPT_PREPEND_BASEDIR};
+       BOOL states[] = { FALSE, FALSE, FALSE, FALSE };
        CMyFileDialog fd;
        fd.setSaveDlgDefaultSetting();
        fd.setTitle("Export filename ..");
@@ -172,13 +172,15 @@ void ExportFile(HWND hDlg, bool bExportList)
                fd.setDefaultExt("cfg");
                fd.setFilter("TiMidity++ Config File (*.cfg)\0*.cfg\0\0");
        }
-       if (fd.Execute()) {
-               SFView_ExportConfigFile((char*)fd.getFile(0),
-                                       (int)bExportList,
-                                       (int)states[0],
-                                       (int)states[1],
-                                       (int)states[2]);
-       }
+    if (fd.Execute()) {
+        SFView_ExportConfigFile((char*)fd.getFile(0),
+            (int)bExportList,
+            (int)states[0],
+            (int)states[1],
+            (int)states[2],
+            (int)states[3]
+        );
+    }
 }
 
 HIMAGELIST g_hil = NULL;
@@ -188,8 +190,8 @@ LRESULT DlgMainProc_INITDIALOG(HWND hDlg, WPARAM wParam, LPARAM lParam)
 {
        MENUITEMINFO mii = { sizeof(MENUITEMINFO) };
        HMENU hMenu = GetMenu(hDlg);
-       CONST UINT menuIDs[] = { IDM_OPT_APPEND_COMMENT, IDM_OPT_APPEND_FSPACES, IDM_OPT_KEEP_FULLPATH };
-       CONST UINT states[] = { MFS_UNCHECKED, MFS_UNCHECKED, MFS_CHECKED };
+       CONST UINT menuIDs[] = { IDM_OPT_APPEND_COMMENT, IDM_OPT_APPEND_FSPACES, IDM_OPT_KEEP_FULLPATH, IDM_OPT_PREPEND_BASEDIR};
+       CONST UINT states[] = { MFS_CHECKED, MFS_UNCHECKED, MFS_UNCHECKED, MFS_CHECKED };
 
        if (__argc == 2) {
                ResetSoundFontTree(hDlg);
@@ -276,6 +278,7 @@ LRESULT DlgMainProc_COMMAND(HWND hDlg, WPARAM wParam, LPARAM lParam)
        case IDM_OPT_APPEND_COMMENT:
        case IDM_OPT_APPEND_FSPACES:
        case IDM_OPT_KEEP_FULLPATH:
+    case IDM_OPT_PREPEND_BASEDIR:
                hMenu = GetMenu(hDlg);
                mii.fMask = MIIM_STATE | MIIM_ID;
                GetMenuItemInfo(hMenu, LOWORD(wParam), FALSE, &mii);
@@ -297,6 +300,43 @@ LRESULT DlgMainProc_CLOSE(HWND hDlg, WPARAM wParam, LPARAM lParam)
        return TRUE;
 }
 
+LRESULT DlgMainProc_SIZE(HWND hDlg, WPARAM wParam, LPARAM lParam)
+{
+    if (wParam != SC_MINIMIZE) {
+        SetWindowPos(
+            GetDlgItem(hDlg, IDC_TREE1),
+            NULL,
+            0,
+            0,
+            GET_X_LPARAM(lParam),
+            GET_Y_LPARAM(lParam) - 17,
+            SWP_NOACTIVATE | SWP_NOZORDER
+        );
+
+        SetWindowPos(
+            GetDlgItem(hDlg, IDC_EDSFLABEL),
+            NULL,
+            0,
+            GET_Y_LPARAM(lParam) - 16,
+            99,
+            16,
+            SWP_NOACTIVATE | SWP_NOZORDER
+        );
+
+        SetWindowPos(
+            GetDlgItem(hDlg, IDC_EDSFNAME),
+            NULL,
+            100,
+            GET_Y_LPARAM(lParam) - 16,
+            GET_X_LPARAM(lParam) - 100,
+            16,
+            SWP_NOACTIVATE | SWP_NOZORDER
+        );
+    }
+
+    return TRUE;
+}
+
 LRESULT CALLBACK DlgMainProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
 {
 #define SET_MYWINMSG(VN) case WM_ ## VN: return DlgMainProc_## VN(hDlg, wParam, lParam);
@@ -305,6 +345,7 @@ LRESULT CALLBACK DlgMainProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
                SET_MYWINMSG(DROPFILES);
                SET_MYWINMSG(COMMAND);
                SET_MYWINMSG(CLOSE);
+               SET_MYWINMSG(SIZE);
        }
 #undef  SET_MYWINMSG
        return FALSE;
diff --git a/sfviewer/sfviewer.vcxproj b/sfviewer/sfviewer.vcxproj
deleted file mode 100644 (file)
index 24425a0..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>sfviewer</RootNamespace>
-    <ProjectName>sf_view_gui</ProjectName>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>_DEBUG;_MD;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;__W32__;CFG_FOR_SF;SF2VIEWER_GUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>_DEBUG;_MD;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;__W32__;CFG_FOR_SF;SF2VIEWER_GUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>NDEBUG;_MD;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;__W32__;CFG_FOR_SF;SF2VIEWER_GUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>false</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>NDEBUG;_MD;WIN32;_CONSOLE;_WINDOWS;HAVE_CONFIG_H;__W32__;CFG_FOR_SF;SF2VIEWER_GUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\libarc\arc.h" />
-    <ClInclude Include="..\sf_view_gui\OpenDlg.h" />
-    <ClInclude Include="..\sf_view_gui\resource.h" />
-    <ClInclude Include="..\timidity\common.h" />
-    <ClInclude Include="..\timidity\controls.h" />
-    <ClInclude Include="..\timidity\filter.h" />
-    <ClInclude Include="..\timidity\instrum.h" />
-    <ClInclude Include="..\timidity\mt19937ar.h" />
-    <ClInclude Include="..\timidity\myini.h" />
-    <ClInclude Include="..\timidity\output.h" />
-    <ClInclude Include="..\timidity\playmidi.h" />
-    <ClInclude Include="..\timidity\quantity.h" />
-    <ClInclude Include="..\timidity\readmidi.h" />
-    <ClInclude Include="..\timidity\resample.h" />
-    <ClInclude Include="..\timidity\reverb.h" />
-    <ClInclude Include="..\timidity\sffile.h" />
-    <ClInclude Include="..\timidity\sfitem.h" />
-    <ClInclude Include="..\timidity\sflayer.h" />
-    <ClInclude Include="..\timidity\tables.h" />
-    <ClInclude Include="..\timidity\timidity.h" />
-    <ClInclude Include="..\timidity\wrd.h" />
-    <ClInclude Include="..\utils\mblock.h" />
-    <ClInclude Include="..\utils\support.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\sf_view_gui\mysndfont.c" />
-    <ClCompile Include="..\sf_view_gui\OpenDlg.cpp" />
-    <ClCompile Include="..\sf_view_gui\sfview_main.cpp">
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">CompileAsCpp</CompileAs>
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">CompileAsCpp</CompileAs>
-    </ClCompile>
-    <ClCompile Include="..\timidity\common.c" />
-    <ClCompile Include="..\timidity\controls.c" />
-    <ClCompile Include="..\timidity\filter.c" />
-    <ClCompile Include="..\timidity\freq.c" />
-    <ClCompile Include="..\timidity\instrum.c" />
-    <ClCompile Include="..\timidity\mt19937ar.c" />
-    <ClCompile Include="..\timidity\myini.c" />
-    <ClCompile Include="..\timidity\quantity.c" />
-    <ClCompile Include="..\timidity\resample.c" />
-    <ClCompile Include="..\timidity\sbkconv.c" />
-    <ClCompile Include="..\timidity\sffile.c" />
-    <ClCompile Include="..\timidity\sfitem.c" />
-    <ClCompile Include="..\timidity\smplfile.c" />
-    <ClCompile Include="..\timidity\tables.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\sf_view_gui\bitmap1.bmp" />
-    <None Include="..\sf_view_gui\icon1.ico" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\sf_view_gui\sfview_dlg.rc" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/sfviewer/sfviewer.vcxproj.filters b/sfviewer/sfviewer.vcxproj.filters
deleted file mode 100644 (file)
index d53ad83..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
-      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
-    </Filter>
-    <Filter Include="Source Files\timidity">
-      <UniqueIdentifier>{f680707d-2a89-4910-9095-bddecae42202}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Header Files\timidity">
-      <UniqueIdentifier>{8bafd6d4-af63-4587-974a-65459d193319}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Header Files\libarc">
-      <UniqueIdentifier>{094700e9-2521-45ee-b89d-6bf56e38d67a}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Header Files\utils">
-      <UniqueIdentifier>{6539ebf7-0a92-4893-b2ed-6c5bc2da68f0}</UniqueIdentifier>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\sf_view_gui\resource.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\sf_view_gui\OpenDlg.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\common.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\controls.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\filter.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\instrum.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mt19937ar.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\myini.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\output.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\playmidi.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\readmidi.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\resample.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\reverb.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sffile.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sfitem.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sflayer.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\tables.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\timidity.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\wrd.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\libarc\arc.h">
-      <Filter>Header Files\libarc</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\mblock.h">
-      <Filter>Header Files\utils</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\quantity.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\utils\support.h">
-      <Filter>Header Files\utils</Filter>
-    </ClInclude>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\sf_view_gui\sfview_main.cpp">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\sf_view_gui\mysndfont.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\sf_view_gui\OpenDlg.cpp">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\common.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\controls.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\filter.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\freq.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\instrum.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mt19937ar.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\myini.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\quantity.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\resample.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sbkconv.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sffile.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sfitem.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smplfile.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\tables.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\sf_view_gui\bitmap1.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\sf_view_gui\icon1.ico">
-      <Filter>Resource Files</Filter>
-    </None>
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\sf_view_gui\sfview_dlg.rc">
-      <Filter>Resource Files</Filter>
-    </ResourceCompile>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/sfviewer/sfviewer.vcxproj.user b/sfviewer/sfviewer.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/speex/CMakeLists.txt b/speex/CMakeLists.txt
new file mode 100644 (file)
index 0000000..dacce86
--- /dev/null
@@ -0,0 +1,70 @@
+
+add_definitions(
+    -DHAVE_CONFIG_H
+)
+
+add_library(
+    speex SHARED
+
+    bits.c
+    cb_search.c
+    exc_10_16_table.c
+    exc_10_32_table.c
+    exc_20_32_table.c
+    exc_5_256_table.c
+    exc_5_64_table.c
+    exc_8_128_table.c
+    filters.c
+    gain_table.c
+    gain_table_lbr.c
+    hexc_10_32_table.c
+    hexc_table.c
+    high_lsp_tables.c
+    lpc.c
+    lsp.c
+    lsp_tables_nb.c
+    ltp.c
+    modes.c
+    modes_wb.c
+    nb_celp.c
+    quant_lsp.c
+    sb_celp.c
+    speex.c
+    speex_callbacks.c
+    speex_header.c
+    stereo.c
+    vbr.c
+    vq.c
+    window.c
+    
+    config.h
+    arch.h
+    cb_search.h
+    cb_search_sse.h
+    filters.h
+    filters_sse.h
+    fixed_debug.h
+    fixed_generic.h
+    lpc.h
+    lsp.h
+    ltp.h
+    ltp_sse.h
+    math_approx.h
+    modes.h
+    nb_celp.h
+    os_support.h
+    quant_lsp.h
+    sb_celp.h
+    stack_alloc.h
+    vbr.h
+    vq.h
+    vq_sse.h
+    speex.h
+    speex_bits.h
+    speex_callbacks.h
+    speex_header.h
+    speex_stereo.h
+    speex_types.h
+
+    libspeex.def
+)
diff --git a/speex/libspeex.def b/speex/libspeex.def
new file mode 100644 (file)
index 0000000..b0724f0
--- /dev/null
@@ -0,0 +1,74 @@
+EXPORTS
+
+
+;
+;      speex.h
+;
+speex_encoder_init
+speex_encoder_destroy
+speex_encode
+speex_encode_int
+speex_encoder_ctl
+speex_decoder_init
+speex_decoder_destroy
+speex_decode
+speex_decode_int
+speex_decoder_ctl
+speex_mode_query
+speex_lib_ctl
+speex_lib_get_mode
+
+;
+;      speex_bits.h
+;
+speex_bits_init
+speex_bits_init_buffer
+speex_bits_set_bit_buffer
+speex_bits_destroy
+speex_bits_reset
+speex_bits_rewind
+speex_bits_read_from
+speex_bits_read_whole_bytes
+speex_bits_write
+speex_bits_write_whole_bytes
+speex_bits_pack
+speex_bits_unpack_signed
+speex_bits_unpack_unsigned
+speex_bits_nbytes
+speex_bits_peek_unsigned
+speex_bits_peek
+speex_bits_advance
+speex_bits_remaining
+speex_bits_insert_terminator
+
+;
+;      speex_callbacks.h
+;
+speex_inband_handler
+speex_std_mode_request_handler
+speex_std_high_mode_request_handler
+speex_std_char_handler
+speex_default_user_handler
+speex_std_low_mode_request_handler
+speex_std_vbr_request_handler
+speex_std_enh_request_handler
+speex_std_vbr_quality_request_handler
+
+;
+;      speex_header.h
+;
+speex_init_header
+speex_header_to_packet
+speex_packet_to_header
+
+;
+;      speex_stereo.h
+;
+speex_stereo_state_init
+speex_stereo_state_reset
+speex_stereo_state_destroy
+speex_encode_stereo
+speex_encode_stereo_int
+speex_decode_stereo
+speex_decode_stereo_int
+speex_std_stereo_request_handler
diff --git a/speex/libspeex.vcproj b/speex/libspeex.vcproj
deleted file mode 100644 (file)
index 829fa1d..0000000
+++ /dev/null
@@ -1,430 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="8.00"
-       Name="libspeex"
-       ProjectGUID="{E972C52F-9E85-4D65-B19C-031E511E9DB4}"
-       RootNamespace="libspeex"
-       Keyword="Win32Proj"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-                       IntermediateDirectory="Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="../"
-                               PreprocessorDefinitions="WIN32;_DEBUG;_LIB;HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="3"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               WarningLevel="4"
-                               Detect64BitPortabilityProblems="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\libspeex.lib"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-                       IntermediateDirectory="Release"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               AdditionalIncludeDirectories="../"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_LIB;HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               WarningLevel="4"
-                               Detect64BitPortabilityProblems="true"
-                               DebugInformationFormat="3"
-                               CompileAs="1"
-                               DisableSpecificWarnings="4244;4305;4311;4100;4127"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Release\libspeex.lib"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;odl;idl;hpj;bat;asm;asmx"
-                       UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
-                       >
-                       <File
-                               RelativePath="bits.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="cb_search.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_10_16_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_10_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_20_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_5_256_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_5_64_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="exc_8_128_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="filters.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="gain_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="gain_table_lbr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="hexc_10_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="hexc_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="high_lsp_tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="lpc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="lsp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="lsp_tables_nb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="ltp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="modes.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="modes_wb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="nb_celp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="quant_lsp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="sb_celp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_callbacks.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_header.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="stereo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="vbr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="vq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="window.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl;inc;xsd"
-                       UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
-                       >
-                       <File
-                               RelativePath="arch.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="cb_search.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="cb_search_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="filters.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="filters_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="fixed_debug.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="fixed_generic.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="lpc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="lsp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="ltp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="ltp_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="math_approx.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="modes.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="nb_celp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="os_support.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="quant_lsp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="sb_celp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="stack_alloc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="vbr.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="vq.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="vq_sse.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Resource Files"
-                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
-                       UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
-                       >
-               </Filter>
-               <Filter
-                       Name="Public Header Files"
-                       Filter="h"
-                       >
-                       <File
-                               RelativePath="speex.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_bits.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_callbacks.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_header.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_stereo.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="speex_types.h"
-                               >
-                       </File>
-               </Filter>
-               <File
-                       RelativePath="..\..\config.h"
-                       >
-               </File>
-               <File
-                       RelativePath="..\..\libspeex.def"
-                       >
-               </File>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/speex/libspeex.vcxproj b/speex/libspeex.vcxproj
deleted file mode 100644 (file)
index 855bc63..0000000
+++ /dev/null
@@ -1,260 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{E972C52F-9E85-4D65-B19C-031E511E9DB4}</ProjectGuid>
-    <RootNamespace>libspeex</RootNamespace>
-    <Keyword>Win32Proj</Keyword>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\libspeex.lib</OutputFile>
-      <IgnoreSpecificDefaultLibraries>
-      </IgnoreSpecificDefaultLibraries>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;_DEBUG;_LIB;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Debug\libspeex.lib</OutputFile>
-      <IgnoreSpecificDefaultLibraries>
-      </IgnoreSpecificDefaultLibraries>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <AdditionalIncludeDirectories>../;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <DisableSpecificWarnings>4244;4305;4311;4100;4127;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Release\libspeex.lib</OutputFile>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <AdditionalIncludeDirectories>../;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;NDEBUG;_LIB;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <DisableSpecificWarnings>4244;4305;4311;4100;4127;%(DisableSpecificWarnings)</DisableSpecificWarnings>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Lib>
-      <OutputFile>../Release\libspeex.lib</OutputFile>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="bits.c" />
-    <ClCompile Include="cb_search.c" />
-    <ClCompile Include="exc_10_16_table.c" />
-    <ClCompile Include="exc_10_32_table.c" />
-    <ClCompile Include="exc_20_32_table.c" />
-    <ClCompile Include="exc_5_256_table.c" />
-    <ClCompile Include="exc_5_64_table.c" />
-    <ClCompile Include="exc_8_128_table.c" />
-    <ClCompile Include="filters.c" />
-    <ClCompile Include="gain_table.c" />
-    <ClCompile Include="gain_table_lbr.c" />
-    <ClCompile Include="hexc_10_32_table.c" />
-    <ClCompile Include="hexc_table.c" />
-    <ClCompile Include="high_lsp_tables.c" />
-    <ClCompile Include="lpc.c" />
-    <ClCompile Include="lsp.c" />
-    <ClCompile Include="lsp_tables_nb.c" />
-    <ClCompile Include="ltp.c" />
-    <ClCompile Include="modes.c" />
-    <ClCompile Include="modes_wb.c" />
-    <ClCompile Include="nb_celp.c" />
-    <ClCompile Include="quant_lsp.c" />
-    <ClCompile Include="sb_celp.c" />
-    <ClCompile Include="speex.c" />
-    <ClCompile Include="speex_callbacks.c" />
-    <ClCompile Include="speex_header.c" />
-    <ClCompile Include="stereo.c" />
-    <ClCompile Include="vbr.c" />
-    <ClCompile Include="vq.c" />
-    <ClCompile Include="window.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="arch.h" />
-    <ClInclude Include="cb_search.h" />
-    <ClInclude Include="cb_search_sse.h" />
-    <ClInclude Include="filters.h" />
-    <ClInclude Include="filters_sse.h" />
-    <ClInclude Include="fixed_debug.h" />
-    <ClInclude Include="fixed_generic.h" />
-    <ClInclude Include="lpc.h" />
-    <ClInclude Include="lsp.h" />
-    <ClInclude Include="ltp.h" />
-    <ClInclude Include="ltp_sse.h" />
-    <ClInclude Include="math_approx.h" />
-    <ClInclude Include="modes.h" />
-    <ClInclude Include="nb_celp.h" />
-    <ClInclude Include="os_support.h" />
-    <ClInclude Include="quant_lsp.h" />
-    <ClInclude Include="sb_celp.h" />
-    <ClInclude Include="stack_alloc.h" />
-    <ClInclude Include="vbr.h" />
-    <ClInclude Include="vq.h" />
-    <ClInclude Include="vq_sse.h" />
-    <ClInclude Include="speex.h" />
-    <ClInclude Include="speex_bits.h" />
-    <ClInclude Include="speex_callbacks.h" />
-    <ClInclude Include="speex_header.h" />
-    <ClInclude Include="speex_stereo.h" />
-    <ClInclude Include="speex_types.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\..\libspeex.def" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/speex/libspeex.vcxproj.filters b/speex/libspeex.vcxproj.filters
deleted file mode 100644 (file)
index 28f0617..0000000
+++ /dev/null
@@ -1,202 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;odl;idl;hpj;bat;asm;asmx</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx</Extensions>
-    </Filter>
-    <Filter Include="Public Header Files">
-      <UniqueIdentifier>{bd2d091b-5be3-41db-b84d-b863410c1328}</UniqueIdentifier>
-      <Extensions>h</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="bits.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="cb_search.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_10_16_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_10_32_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_20_32_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_5_256_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_5_64_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="exc_8_128_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="filters.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="gain_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="gain_table_lbr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="hexc_10_32_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="hexc_table.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="high_lsp_tables.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="lpc.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="lsp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="lsp_tables_nb.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="ltp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="modes.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="modes_wb.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="nb_celp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="quant_lsp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sb_celp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="speex.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="speex_callbacks.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="speex_header.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="stereo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="vbr.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="vq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="window.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="arch.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="cb_search.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="cb_search_sse.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="filters.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="filters_sse.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="fixed_debug.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="fixed_generic.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="lpc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="lsp.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="ltp.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="ltp_sse.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="math_approx.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="modes.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="nb_celp.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="os_support.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="quant_lsp.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sb_celp.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="stack_alloc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="vbr.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="vq.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="vq_sse.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex_bits.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex_callbacks.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex_header.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex_stereo.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="speex_types.h">
-      <Filter>Public Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\..\libspeex.def" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/speex/libspeex.vcxproj.user b/speex/libspeex.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
index 3611d95..6b74b0c 100644 (file)
@@ -68,7 +68,6 @@ static inline void *speex_alloc_scratch (int size)
 
 /** Speex wrapper for realloc. To do your own dynamic allocation, all you need to do is replace this function, speex_alloc and speex_free */
 #ifndef OVERRIDE_SPEEX_REALLOC
-extern void *realloc(void *ptr, int size);
 static inline void *speex_realloc (void *ptr, int size)
 {
    return realloc(ptr, size);
diff --git a/speex/speex.vcproj b/speex/speex.vcproj
deleted file mode 100644 (file)
index d04d430..0000000
+++ /dev/null
@@ -1,420 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="libspeex"
-       ProjectGUID="{2D650C28-16E9-41A2-860B-CC3DEEC69C43}"
-       RootNamespace="speex"
-       Keyword="ManagedCProj"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="2"
-                       CharacterSet="1"
-                       ManagedExtensions="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               PreprocessorDefinitions="WIN32;_DEBUG"
-                               RuntimeLibrary="3"
-                               UsePrecompiledHeader="2"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               DebugInformationFormat="3"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="$(NoInherit)"
-                               LinkIncremental="2"
-                               GenerateDebugInformation="true"
-                               AssemblyDebug="1"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       CharacterSet="2"
-                       ManagedExtensions="0"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="../;%(AdditionalIncludeDirectories)"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_LIB;HAVE_CONFIG_H;"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               UsePrecompiledHeader="0"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               DebugInformationFormat="3"
-                               DisableSpecificWarnings="4244;4305;4311;4100;4127;"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Header Files"
-                       >
-                       <File
-                               RelativePath=".\arch.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\cb_search.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\cb_search_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\filters.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\filters_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\fixed_debug.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\fixed_generic.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lpc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lsp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\ltp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\ltp_sse.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\math_approx.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\modes.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\nb_celp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\os_support.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\quant_lsp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sb_celp.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\stack_alloc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vbr.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vq.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vq_sse.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Public Header Files"
-                       >
-                       <File
-                               RelativePath=".\speex.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_bits.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_callbacks.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_header.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_stereo.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_types.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Source Files"
-                       >
-                       <File
-                               RelativePath=".\bits.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\cb_search.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_10_16_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_10_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_20_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_5_256_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_5_64_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\exc_8_128_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\filters.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\gain_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\gain_table_lbr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\hexc_10_32_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\hexc_table.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\high_lsp_tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lpc.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lsp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lsp_tables_nb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\ltp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\modes.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\modes_wb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\nb_celp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\quant_lsp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sb_celp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_callbacks.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_header.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\stereo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vbr.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\window.c"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/tim41-readme.txt b/tim41-readme.txt
new file mode 100644 (file)
index 0000000..9932aff
--- /dev/null
@@ -0,0 +1,538 @@
+TiMidity++ 41 version
+=====================
+
+Fork of TiMidity++ <http://timidity.sourceforge.net/>, based on UnkoTim215 <http://jbbs.shitaraba.net/bbs/read.cgi/computer/42137/1499269478/86>.
+
+Source code is available at <https://osdn.net/projects/timidity41/scm/git/timidity41/>.
+
+
+License
+=======
+
+TiMidity++
+----------
+
+TiMidity++ -- MIDI to WAVE converter and player
+Copyright (C) 1999-2008 Masanao Izumo <iz@onicos.co.jp>
+Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+twsyn_bridge
+------------
+
+Imported from UnkoTim213.
+
+From _unko.txt:
+
+> ▲以下はGPLではない
+> twsyn_bridge (timidityソース/SDKVSTは使用してないので▲他付属物と同じ
+>      twsyn_bridge_host.c twsyn_bridge_host.h はGPLでもいいけど
+
+and
+
+> ▲他付属物は
+> 全く無保証のフリーです。自由に再配布/修正することができます。
+> ってことで
+
+
+BladeMP3EncDLL
+--------------
+
+       Blade DLL Interface for LAME.
+
+       Copyright (c) 1999 - 2002 A.L. Faber
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this library; if not, write to the
+Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA  02111-1307, USA.
+
+
+LAME
+----
+
+     LAME MP3 encoding engine
+
+     Copyright (c) 1999-2000 Mark Taylor
+     Copyright (c) 2000-2005 Takehiro Tominaga
+     Copyright (c) 2000-2017 Robert Hegemann
+     Copyright (c) 2000-2005 Gabriel Bouvigne
+     Copyright (c) 2000-2004 Alexander Leidinger
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this library; if not, write to the
+Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+
+
+libFLAC
+-------
+
+libFLAC - Free Lossless Audio Codec library
+Copyright (C) 2000-2009  Josh Coalson
+Copyright (C) 2011-2013  Xiph.Org Foundation
+
+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.
+
+
+libmpg123
+---------
+
+Main message, to include in "About ..." boxes, etc:
+
+       Copyright (c) 1995-2013 by Michael Hipp and others,
+       free software under the terms of the LGPL v2.1
+
+There is an attempt to cover the actual list of authors in the AUTHORS file.
+Project maintainer since 2006 is Thomas Orgis and many people have contributed
+since the Michael Hipp era, but he stays the initial source and it would
+be impractical to count them all individually, so it's "and others".
+Source files contain the phrase "the mpg123 project" to the same effect
+in their license boilerplate; especially those that were added after
+maintainership changed. The person mainly responsible for the first version
+is usually named in the phrase "initially written by ...".
+
+All files in the distribution that don't carry a license note on their own are
+licensed under the terms of the LGPL 2.1; exceptions may apply, especially to
+files not in the official distribution but in the revision control repository.
+
+
+libOgg
+------
+
+Copyright (c) 2002, Xiph.org Foundation
+
+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.
+
+
+libOggFLAC
+----------
+
+libOggFLAC - Free Lossless Audio Codec + Ogg library
+Copyright (C) 2002,2003  Josh Coalson
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this library; if not, write to the
+Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA  02111-1307, USA.
+
+
+libunimod
+---------
+
+     MikMod sound library
+(c) 1998, 1999 Miodrag Vallat and others - see file AUTHORS for
+complete list.
+
+This library is free software; you can redistribute it and/or modify
+it under the terms of the GNU Library General Public License as
+published by the Free Software Foundation; either version 2 of
+the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307, USA.
+
+
+libvorbis
+---------
+
+Copyright (c) 2002-2015 Xiph.org Foundation
+
+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.
+
+
+MT19937
+-------
+
+Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
+All rights reserved.                          
+
+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 names of its contributors may not 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.
+
+
+Any feedback is very welcome.
+http://www.math.keio.ac.jp/matumoto/emt.html
+email: matumoto@math.keio.ac.jp
+
+
+Opus
+----
+
+Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,
+                    Jean-Marc Valin, Timothy B. Terriberry,
+                    CSIRO, Gregory Maxwell, Mark Borgerding,
+                    Erik de Castro Lopo
+
+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 Internet Society, IETF or IETF Trust, nor the
+names of specific 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.
+
+Opus is subject to the royalty-free patent licenses which are
+specified at:
+
+Xiph.Org Foundation:
+https://datatracker.ietf.org/ipr/1524/
+
+Microsoft Corporation:
+https://datatracker.ietf.org/ipr/1914/
+
+Broadcom Corporation:
+https://datatracker.ietf.org/ipr/1526/
+
+
+PDCurses
+--------
+
+The core package is in the public domain, but small portions of PDCurses 
+are subject to copyright under various licenses.  Each directory 
+contains a README file, with a section titled "Distribution Status" 
+which describes the status of the files in that directory.
+
+If you use PDCurses in an application, an acknowledgement would be 
+appreciated, but is not mandatory. If you make corrections or 
+enhancements to PDCurses, please forward them to the current maintainer 
+for the benefit of other users.
+
+This software is provided AS IS with NO WARRANTY whatsoever.
+
+William McBrine <wmcbrine@users.sf.net>
+
+
+PortAudio
+---------
+
+PortAudio Portable Real-Time Audio Library
+PortAudio API Header File
+Latest version available at: http://www.portaudio.com/
+
+Copyright (c) 1999-2002 Ross Bencina and Phil Burk
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files
+(the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+The text above constitutes the entire PortAudio license; however, 
+the PortAudio community also makes the following non-binding requests:
+
+Any person wishing to distribute modifications to the Software is
+requested to send the modifications to the original developer so that
+they can be incorporated into the canonical version. It is also 
+requested that these non-binding requests be included along with the 
+license above.
+
+
+PortMidi
+--------
+
+/*
+ * PortMidi Portable Real-Time MIDI Library
+ *
+ * license.txt -- a copy of the PortMidi copyright notice and license information
+ *
+ * Latest version available at: http://sourceforge.net/projects/portmedia
+ *
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ * Copyright (c) 2001-2009 Roger B. Dannenberg
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortMidi license; however, 
+ * the PortMusic community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+
+speex
+-----
+
+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.
+
+
+kiss fft
+--------
+
+Copyright (c) 2003-2010 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.
+
+
+WASAPI backend (wasapi_a.c)
+---------------------------
+
+WASAPI backend is based on <https://github.com/Microsoft/Windows-classic-samples/tree/master/Samples/Win7Samples/multimedia/audio/RenderExclusiveEventDriven>,
+which is distributed under the MIT License:
+
+----
+The MIT License (MIT)
+
+Copyright (c) Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Portions of this repo are provided under the SIL Open Font License.
+See the LICENSE file in individual samples for additional details
+----
diff --git a/tim_cui/tim_cui.vcproj b/tim_cui/tim_cui.vcproj
deleted file mode 100644 (file)
index 9024bac..0000000
+++ /dev/null
@@ -1,930 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="tim_cui"
-       ProjectGUID="{2B113C99-C484-4724-8918-169A495ADF9B}"
-       RootNamespace="tim_cui"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Debug/timidity.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;%(AdditionalIncludeDirectories)"
-                               PreprocessorDefinitions="_DEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="3"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/timidity.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib comctl32.lib winmm.lib wsock32.lib"
-                               OutputFile="../Debug/timidity.exe"
-                               LinkIncremental="2"
-                               SuppressStartupBanner="true"
-                               IgnoreDefaultLibraryNames="LIBCMT.lib;libc.lib;"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile=".\Debug/timidity.pdb"
-                               SubSystem="1"
-                               LargeAddressAware="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                               AdditionalManifestFiles="..\interface\w32g_visualstyle.manifest"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Release/timidity.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;%(AdditionalIncludeDirectories)"
-                               PreprocessorDefinitions="NDEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/timidity.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib comctl32.lib winmm.lib wsock32.lib"
-                               OutputFile="../Release/timidity.exe"
-                               LinkIncremental="1"
-                               SuppressStartupBanner="true"
-                               AdditionalLibraryDirectories="../release"
-                               IgnoreDefaultLibraryNames="LIBCMT.lib;libc.lib;"
-                               ProgramDatabaseFile=".\Release/timidity.pdb"
-                               SubSystem="1"
-                               LargeAddressAware="2"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="2"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                               AdditionalManifestFiles="..\interface\w32g_visualstyle.manifest"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-               <ProjectReference
-                       ReferencedProjectIdentifier="{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-                       RelativePathToProject=".\libarc\libarc.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{2D650C28-16E9-41A2-860B-CC3DEEC69C43}"
-                       RelativePathToProject=".\speex\speex.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-                       RelativePathToProject=".\libunimod\libunimod.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{CC07EA59-8D54-4C51-9C49-728EFFED7832}"
-                       RelativePathToProject=".\pdcurses\pdcurses.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}"
-                       RelativePathToProject=".\portmidi\portmidi.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-                       RelativePathToProject=".\utils\utils.vcproj"
-               />
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath="..\interface\ncurs_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\npsyn_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\portmidisyn_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_npipe.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_winmm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timidity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\winsyn_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\wrdt_wcon.c"
-                               >
-                       </File>
-                       <Filter
-                               Name="interface"
-                               >
-                               <File
-                                       RelativePath="..\interface\dumb_c.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\vt100.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\vt100_c.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\VTPrsTbl.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\wrdt_dumb.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\wrdt_tty.c"
-                                       >
-                               </File>
-                       </Filter>
-                       <Filter
-                               Name="timidity"
-                               >
-                               <File
-                                       RelativePath="..\timidity\aiff_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\ao_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\aq.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\au_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\audio_cnv.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\benchmark_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\common.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\controls.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\decode.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\effect.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\envelope.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\filter.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\flac_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\freq.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\gogo_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\instrum.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\int_synth.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\lame_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\list_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\loadtab.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\m2m.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mfi.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mfnode.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\midi_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\miditrace.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mix.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mod.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mod2midi.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\modmid_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mt19937ar.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\myini.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\npipe_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\optcode.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\opus_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\oscillator.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\output.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\playmidi.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\portaudio_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\quantity.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\raw_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\rcp.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\readmidi.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\recache.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\resample.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sbkconv.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sffile.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sfitem.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\smfconv.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\smplfile.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sndfont.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sndfontini.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\speex_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\tables.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\thread.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\version.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\voice_effect.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\volumecalc_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\vorbis_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_gogo.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_soundspec.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wasapi_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wave_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wdmks_a.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wrd_read.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wrdt.c"
-                                       >
-                               </File>
-                       </Filter>
-                       <Filter
-                               Name="timw32g"
-                               >
-                               <File
-                                       RelativePath="..\timidity\w32_libFLAC_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_libmpg123_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_libOggFLAC_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_portaudio_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32g_ogg_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32g_opus_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32g_vorbis_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32g_vorbisenc_dll.c"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32g_vorbisfile_dll.c"
-                                       >
-                               </File>
-                       </Filter>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timidity.h"
-                               >
-                       </File>
-                       <Filter
-                               Name="interface"
-                               >
-                               <File
-                                       RelativePath="..\interface\gtk_h.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\mac_c.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\mac_mag.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\mac_wrdwindow.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\motif.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\configs\msc-config.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\server_defs.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\soundspec.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\vt100.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\VTparse.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\w32g_utl.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\x_mag.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\x_sherry.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\x_wrdwindow.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\xaw.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\interface\xskin.h"
-                                       >
-                               </File>
-                       </Filter>
-                       <Filter
-                               Name="timidity"
-                               >
-                               <File
-                                       RelativePath="..\timidity\aenc.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\aq.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\audio_cnv.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\audriv.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\common.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\controls.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\dlutils.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\effect.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\envelope.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\filter.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\freq.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\gogo_a.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\instrum.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\int_synth.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\LameEnc.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\loadsndfontini.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mac_com.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mac_main.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mfnode.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\miditrace.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mix.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mod.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mod2midi.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\mt19937ar.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\myini.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\optcode.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\oscillator.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\output.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\playmidi.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\portaudio_a.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\pragmapack.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\quantity.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\readmidi.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\recache.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\resample.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sffile.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sfitem.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sflayer.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\smfconv.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sndfontini.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\sysdep.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\tables.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\thread.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\voice_effect.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\vstwrapper.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_a.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_gogo.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\w32_soundspec.h"
-                                       >
-                               </File>
-                               <File
-                                       RelativePath="..\timidity\wrd.h"
-                                       >
-                               </File>
-                       </Filter>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/tim_cui/tim_cui.vcxproj b/tim_cui/tim_cui.vcxproj
deleted file mode 100644 (file)
index 05215c4..0000000
+++ /dev/null
@@ -1,507 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{2B113C99-C484-4724-8918-169A495ADF9B}</ProjectGuid>
-    <RootNamespace>tim_cui</RootNamespace>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">timidity</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">timidity</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">timidity_x64</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)lib\amd64;$(VCInstallDir)atlmfc\lib\amd64;$(WindowsSdkDir)lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">timidity_x64</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Debug/timidity.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>LIBCMTD.lib;libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/timidity.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <LargeAddressAware>true</LargeAddressAware>
-    </Link>
-    <Manifest>
-      <AdditionalManifestFiles>%(AdditionalManifestFiles)</AdditionalManifestFiles>
-    </Manifest>
-    <PostBuildEvent>
-      <Command>
-      </Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Debug/timidity.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>libcd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/timidity.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <LargeAddressAware>true</LargeAddressAware>
-    </Link>
-    <Manifest>
-      <AdditionalManifestFiles>%(AdditionalManifestFiles)</AdditionalManifestFiles>
-    </Manifest>
-    <PostBuildEvent>
-      <Command>
-      </Command>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Release/timidity.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level2</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <AdditionalLibraryDirectories>../release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <IgnoreSpecificDefaultLibraries>LIBCMT.lib;libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <ProgramDatabaseFile>.\Release/timidity.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <LargeAddressAware>true</LargeAddressAware>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <EnableUAC>true</EnableUAC>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-    </Link>
-    <Manifest>
-      <AdditionalManifestFiles>%(AdditionalManifestFiles)</AdditionalManifestFiles>
-    </Manifest>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Release/timidity.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\portaudio\pa_common;..\pdcurses;..\pdcurses\win32;..\portmidi\pm_common;..\portmidi\porttime;..\..\include;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MD;_CONSOLE;WIN32;HAVE_CONFIG_H;TIM_CUI;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <AdditionalLibraryDirectories>../release;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <IgnoreSpecificDefaultLibraries>LIBCMT.lib;libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <ProgramDatabaseFile>.\Release/timidity.pdb</ProgramDatabaseFile>
-      <SubSystem>Console</SubSystem>
-      <LargeAddressAware>true</LargeAddressAware>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <EnableUAC>true</EnableUAC>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-    </Link>
-    <Manifest>
-      <AdditionalManifestFiles>%(AdditionalManifestFiles)</AdditionalManifestFiles>
-    </Manifest>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\interface\dumb_c.c" />
-    <ClCompile Include="..\interface\ncurs_c.c" />
-    <ClCompile Include="..\interface\npsyn_c.c" />
-    <ClCompile Include="..\interface\portmidisyn_c.c" />
-    <ClCompile Include="..\interface\rtsyn_common.c" />
-    <ClCompile Include="..\interface\rtsyn_npipe.c" />
-    <ClCompile Include="..\interface\rtsyn_winmm.c" />
-    <ClCompile Include="..\interface\vt100.c" />
-    <ClCompile Include="..\interface\vt100_c.c" />
-    <ClCompile Include="..\interface\VTPrsTbl.c" />
-    <ClCompile Include="..\interface\wrdt_dumb.c" />
-    <ClCompile Include="..\interface\wrdt_tty.c" />
-    <ClCompile Include="..\interface\wrdt_wcon.c" />
-    <ClCompile Include="..\timidity\aiff_a.c" />
-    <ClCompile Include="..\timidity\ao_a.c" />
-    <ClCompile Include="..\timidity\aq.c" />
-    <ClCompile Include="..\timidity\audio_cnv.c" />
-    <ClCompile Include="..\timidity\au_a.c" />
-    <ClCompile Include="..\timidity\benchmark_a.c" />
-    <ClCompile Include="..\timidity\common.c" />
-    <ClCompile Include="..\timidity\controls.c" />
-    <ClCompile Include="..\timidity\decode.c" />
-    <ClCompile Include="..\timidity\effect.c" />
-    <ClCompile Include="..\timidity\envelope.c" />
-    <ClCompile Include="..\timidity\filter.c" />
-    <ClCompile Include="..\timidity\flac_a.c" />
-    <ClCompile Include="..\timidity\freq.c" />
-    <ClCompile Include="..\timidity\gogo_a.c" />
-    <ClCompile Include="..\timidity\instrum.c" />
-    <ClCompile Include="..\timidity\int_synth.c" />
-    <ClCompile Include="..\timidity\lame_a.c" />
-    <ClCompile Include="..\timidity\list_a.c" />
-    <ClCompile Include="..\timidity\loadtab.c" />
-    <ClCompile Include="..\timidity\m2m.c" />
-    <ClCompile Include="..\timidity\mfi.c" />
-    <ClCompile Include="..\timidity\mfnode.c" />
-    <ClCompile Include="..\timidity\miditrace.c" />
-    <ClCompile Include="..\timidity\mix.c" />
-    <ClCompile Include="..\timidity\mod.c" />
-    <ClCompile Include="..\timidity\mod2midi.c" />
-    <ClCompile Include="..\timidity\modmid_a.c" />
-    <ClCompile Include="..\timidity\mt19937ar.c" />
-    <ClCompile Include="..\timidity\myini.c" />
-    <ClCompile Include="..\timidity\npipe_a.c" />
-    <ClCompile Include="..\timidity\optcode.c" />
-    <ClCompile Include="..\timidity\opus_a.c" />
-    <ClCompile Include="..\timidity\oscillator.c" />
-    <ClCompile Include="..\timidity\output.c" />
-    <ClCompile Include="..\timidity\playmidi.c" />
-    <ClCompile Include="..\timidity\portaudio_a.c" />
-    <ClCompile Include="..\timidity\quantity.c" />
-    <ClCompile Include="..\timidity\raw_a.c" />
-    <ClCompile Include="..\timidity\rcp.c" />
-    <ClCompile Include="..\timidity\readmidi.c" />
-    <ClCompile Include="..\timidity\recache.c" />
-    <ClCompile Include="..\timidity\resample.c" />
-    <ClCompile Include="..\timidity\sbkconv.c" />
-    <ClCompile Include="..\timidity\sffile.c" />
-    <ClCompile Include="..\timidity\sfitem.c" />
-    <ClCompile Include="..\timidity\smfconv.c" />
-    <ClCompile Include="..\timidity\smplfile.c" />
-    <ClCompile Include="..\timidity\sndfont.c" />
-    <ClCompile Include="..\timidity\sndfontini.c" />
-    <ClCompile Include="..\timidity\speex_a.c" />
-    <ClCompile Include="..\timidity\tables.c" />
-    <ClCompile Include="..\timidity\thread.c" />
-    <ClCompile Include="..\timidity\timidity.c" />
-    <ClCompile Include="..\interface\winsyn_c.c" />
-    <ClCompile Include="..\timidity\version.c" />
-    <ClCompile Include="..\timidity\voice_effect.c" />
-    <ClCompile Include="..\timidity\volumecalc_a.c" />
-    <ClCompile Include="..\timidity\vorbis_a.c" />
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c" />
-    <ClCompile Include="..\timidity\w32g_opus_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisfile_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c" />
-    <ClCompile Include="..\timidity\w32_a.c" />
-    <ClCompile Include="..\timidity\w32_gogo.c" />
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_libmpg123_dll.c" />
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c" />
-    <ClCompile Include="..\timidity\w32_soundspec.c" />
-    <ClCompile Include="..\timidity\wasapi_a.c" />
-    <ClCompile Include="..\timidity\wave_a.c" />
-    <ClCompile Include="..\timidity\wdmks_a.c" />
-    <ClCompile Include="..\timidity\wrdt.c" />
-    <ClCompile Include="..\timidity\wrd_read.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\configs\msc-config.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\interface\gtk_h.h" />
-    <ClInclude Include="..\interface\mac_c.h" />
-    <ClInclude Include="..\interface\mac_mag.h" />
-    <ClInclude Include="..\interface\mac_wrdwindow.h" />
-    <ClInclude Include="..\interface\motif.h" />
-    <ClInclude Include="..\interface\rtsyn.h" />
-    <ClInclude Include="..\interface\server_defs.h" />
-    <ClInclude Include="..\interface\soundspec.h" />
-    <ClInclude Include="..\interface\vt100.h" />
-    <ClInclude Include="..\interface\VTparse.h" />
-    <ClInclude Include="..\interface\w32g_utl.h" />
-    <ClInclude Include="..\interface\xaw.h" />
-    <ClInclude Include="..\interface\xskin.h" />
-    <ClInclude Include="..\interface\x_mag.h" />
-    <ClInclude Include="..\interface\x_sherry.h" />
-    <ClInclude Include="..\interface\x_wrdwindow.h" />
-    <ClInclude Include="..\timidity\aenc.h" />
-    <ClInclude Include="..\timidity\aq.h" />
-    <ClInclude Include="..\timidity\audio_cnv.h" />
-    <ClInclude Include="..\timidity\audriv.h" />
-    <ClInclude Include="..\timidity\common.h" />
-    <ClInclude Include="..\timidity\controls.h" />
-    <ClInclude Include="..\timidity\dlutils.h" />
-    <ClInclude Include="..\timidity\filter.h" />
-    <ClInclude Include="..\timidity\freq.h" />
-    <ClInclude Include="..\timidity\gogo_a.h" />
-    <ClInclude Include="..\timidity\instrum.h" />
-    <ClInclude Include="..\timidity\int_synth.h" />
-    <ClInclude Include="..\timidity\LameEnc.h" />
-    <ClInclude Include="..\timidity\loadsndfontini.h" />
-    <ClInclude Include="..\timidity\mac_com.h" />
-    <ClInclude Include="..\timidity\mac_main.h" />
-    <ClInclude Include="..\timidity\mfnode.h" />
-    <ClInclude Include="..\timidity\miditrace.h" />
-    <ClInclude Include="..\timidity\mix.h" />
-    <ClInclude Include="..\timidity\mod.h" />
-    <ClInclude Include="..\timidity\mod2midi.h" />
-    <ClInclude Include="..\timidity\mt19937ar.h" />
-    <ClInclude Include="..\timidity\myini.h" />
-    <ClInclude Include="..\timidity\optcode.h" />
-    <ClInclude Include="..\timidity\oscillator.h" />
-    <ClInclude Include="..\timidity\output.h" />
-    <ClInclude Include="..\timidity\playmidi.h" />
-    <ClInclude Include="..\timidity\pragmapack.h" />
-    <ClInclude Include="..\timidity\readmidi.h" />
-    <ClInclude Include="..\timidity\recache.h" />
-    <ClInclude Include="..\timidity\resample.h" />
-    <ClInclude Include="..\timidity\reverb.h" />
-    <ClInclude Include="..\timidity\sffile.h" />
-    <ClInclude Include="..\timidity\sfitem.h" />
-    <ClInclude Include="..\timidity\sflayer.h" />
-    <ClInclude Include="..\timidity\smfconv.h" />
-    <ClInclude Include="..\timidity\sndfontini.h" />
-    <ClInclude Include="..\timidity\sysdep.h" />
-    <ClInclude Include="..\timidity\tables.h" />
-    <ClInclude Include="..\timidity\timidity.h" />
-    <ClInclude Include="..\timidity\voice_filter.h" />
-    <ClInclude Include="..\timidity\vstwrapper.h" />
-    <ClInclude Include="..\timidity\w32_a.h" />
-    <ClInclude Include="..\timidity\w32_gogo.h" />
-    <ClInclude Include="..\timidity\w32_soundspec.h" />
-    <ClInclude Include="..\timidity\wrd.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\libarc\libarc.vcxproj">
-      <Project>{11cdd90a-20e1-45af-879e-f355742b38b7}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\libunimod\libunimod.vcxproj">
-      <Project>{8dc8ade3-145a-4c63-80dd-0c93b6587b80}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\pdcurses\pdcurses.vcxproj">
-      <Project>{cc07ea59-8d54-4c51-9c49-728effed7832}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\portmidi\portmidi.vcxproj">
-      <Project>{91f771d3-b89c-408d-b42f-5eafbbce5cc5}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\speex\libspeex.vcxproj">
-      <Project>{e972c52f-9e85-4d65-b19c-031e511e9db4}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\utils\utils.vcxproj">
-      <Project>{b05f8aa0-6140-4335-ad39-e276d17002cb}</Project>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/tim_cui/tim_cui.vcxproj.filters b/tim_cui/tim_cui.vcxproj.filters
deleted file mode 100644 (file)
index 0812c44..0000000
+++ /dev/null
@@ -1,479 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{943393ea-7923-47f1-9dc5-a0ebe7763651}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{6aa605c3-a1e9-4e2f-b56c-ad4dfee01c76}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-    <Filter Include="Header Files\timidity">
-      <UniqueIdentifier>{168634bb-a8aa-405c-a0a5-541b1ca6f9f2}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Source Files\timidity">
-      <UniqueIdentifier>{6eb37e16-fa25-4a3b-99b6-574a1f2da5f9}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Header Files\interface">
-      <UniqueIdentifier>{b210792f-c713-44e9-93cd-63c28c97fa8d}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Source Files\interface">
-      <UniqueIdentifier>{db544158-fba8-46f3-b06d-d4565dd4f2c7}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Source Files\timw32g">
-      <UniqueIdentifier>{811c8a5b-9c21-451e-a0c2-8e3420d6ed1b}</UniqueIdentifier>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\interface\winsyn_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\wrdt_wcon.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\ncurs_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\npsyn_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\portmidisyn_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_npipe.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_winmm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\aiff_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrdt.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\aq.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\au_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\audio_cnv.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\common.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\controls.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\effect.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\filter.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\flac_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\freq.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\gogo_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\instrum.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\lame_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\list_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\loadtab.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\m2m.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfi.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfnode.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\miditrace.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mix.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod2midi.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\modmid_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mt19937ar.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\myini.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\optcode.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\output.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\playmidi.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\portaudio_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\quantity.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\raw_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\rcp.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\readmidi.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\recache.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\resample.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sbkconv.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sffile.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sfitem.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smfconv.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smplfile.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfont.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfontini.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\speex_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\tables.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\version.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\volumecalc_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\vorbis_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_gogo.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wave_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrd_read.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\dumb_c.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\wrdt_tty.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\vt100.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\vt100_c.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\VTPrsTbl.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\wrdt_dumb.c">
-      <Filter>Source Files\interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\npipe_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\envelope.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_opus_dll.c">
-      <Filter>Source Files\timw32g</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\opus_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\ao_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\thread.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\timidity.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\voice_effect.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\int_synth.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_soundspec.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\benchmark_a.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\oscillator.c">
-      <Filter>Source Files\timidity</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\timidity.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\rtsyn.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\aenc.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\wrd.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\aq.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\audio_cnv.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\audriv.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\common.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\controls.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\dlutils.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\filter.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\gogo_a.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\instrum.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\LameEnc.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\loadsndfontini.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mac_com.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mac_main.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mfnode.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\miditrace.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mix.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mod.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mod2midi.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\mt19937ar.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\myini.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\optcode.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\output.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\playmidi.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\pragmapack.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\readmidi.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\recache.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\resample.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\reverb.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sffile.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sfitem.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sflayer.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\smfconv.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sndfontini.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sysdep.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\tables.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\vstwrapper.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_a.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_gogo.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\gtk_h.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\xskin.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\mac_c.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\mac_mag.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\mac_wrdwindow.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\motif.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\configs\msc-config.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\server_defs.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\soundspec.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\vt100.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\VTparse.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_utl.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\x_mag.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\x_sherry.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\x_wrdwindow.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\xaw.h">
-      <Filter>Header Files\interface</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\voice_filter.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\int_synth.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\freq.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_soundspec.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\oscillator.h">
-      <Filter>Header Files\timidity</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/tim_cui/tim_cui.vcxproj.user b/tim_cui/tim_cui.vcxproj.user
deleted file mode 100644 (file)
index e5c8ed9..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LocalDebuggerCommand>$(TargetPath)</LocalDebuggerCommand>
-    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
-    <LocalDebuggerCommandArguments>C:\TIMIDITY\default.pls -c "C:\TIMIDITY\TIMIDITY-CUI.cfg" -in</LocalDebuggerCommandArguments>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LocalDebuggerCommandArguments>C:\TIMIDITY\default.pls -c "C:\TIMIDITY\TIMIDITY-CUI.cfg" -in</LocalDebuggerCommandArguments>
-    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
-    <LocalDebuggerCommand>C:\C\TiMidity++-c196\Release\timidity.exe</LocalDebuggerCommand>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/timidity.dsp b/timidity.dsp
deleted file mode 100644 (file)
index 31b3e66..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-# Microsoft Developer Studio Project File - Name="timidity" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Application" 0x0101
-
-CFG=timidity - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "timidity.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "timidity.mak" CFG="timidity - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "timidity - Win32 Release" ("Win32 (x86) Application" \97p)
-!MESSAGE "timidity - Win32 Debug" ("Win32 (x86) Application" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "timidity - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-
-!ELSEIF  "$(CFG)" == "timidity - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-
-!ENDIF 
-
-# Begin Target
-
-# Name "timidity - Win32 Release"
-# Name "timidity - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# End Group
-# End Target
-# End Project
index 9542f0f..49f922e 100644 (file)
@@ -1,6 +1,6 @@
 
 add_definitions(
-    [[-DDEFAULT_PATH=".\\"]]
+    [[-DDEFAULT_PATH="./"]]
 )
 
 # calcnewton
@@ -17,7 +17,48 @@ include_directories("${CMAKE_CURRENT_BINARY_DIR}")
 # timidity common
 
 set(
-    TIMIDITY_COMMON_SOURCES
+    TIMIDITY_INTERFACE_DEPENDENT_SOURCE
+
+    controls.c
+    flac_a.c
+    gogo_a.c
+    int_synth.c
+    lame_a.c
+    miditrace.c
+    npipe_a.c
+    opus_a.c
+    output.c
+    playmidi.c
+    portaudio_a.c
+    sndfontini.c
+    speex_a.c
+    thread.c
+    timer2.c
+    timidity.c
+    vorbis_a.c
+    wrdt.c
+    
+    controls.h
+    flac_a.h
+    gogo_a.h
+    int_synth.h
+    LameEnc.h
+    miditrace.h
+    output.h
+    portaudio_a.h
+    thread.h
+    timer2.h
+    timidity.h
+    vstwrapper.h
+    wrd.h
+
+    $<TARGET_OBJECTS:libarc>
+    $<TARGET_OBJECTS:libunimod>
+    $<TARGET_OBJECTS:utils>
+)
+
+add_library(
+    timidity_common OBJECT
 
     aiff_a.c
     ao_a.c
@@ -25,16 +66,13 @@ set(
     au_a.c
     audio_cnv.c
     common.c
-    controls.c
+    decode.c
+       dls.cpp
     effect.c
     envelope.c
     filter.c
-    flac_a.c
     freq.c
-    gogo_a.c
     instrum.c
-    int_synth.c
-    lame_a.c
     midi_a.c
     oscillator.c
     list_a.c
@@ -42,19 +80,13 @@ set(
     m2m.c
     mfi.c
     mfnode.c
-    miditrace.c
     mix.c
     mod.c
     mod2midi.c
     modmid_a.c
     mt19937ar.c
     myini.c
-    npipe_a.c
     optcode.c
-    opus_a.c
-    output.c
-    playmidi.c
-    portaudio_a.c
     quantity.c
     raw_a.c
     rcp.c
@@ -64,62 +96,55 @@ set(
     sbkconv.c
     sffile.c
     sfitem.c
+    sfz.cpp
     benchmark_a.c
     smfconv.c
     smplfile.c
     sndfont.c
-    sndfontini.c
-    speex_a.c
     tables.c
-    thread.c
-    timer2.c
-    timidity.c
     version.c
     voice_effect.c
     volumecalc_a.c
-    vorbis_a.c
     w32_a.c
     w32_gogo.c
     wasapi_a.c
     wave_a.c
     w32g_ogg_dll.c
     w32_portaudio_dll.c
+       w32_speex_dll.c
     w32g_vorbis_dll.c
     w32g_vorbisenc_dll.c
+    w32g_vorbisfile_dll.c
     w32g_opus_dll.c
     w32_libFLAC_dll.c
+    w32_libmpg123_dll.c
     w32_libOggFLAC_dll.c
+    wdmks_a.c
     wrd_read.c
-    wrdt.c
-    
+
     aenc.h
     aq.h
     audio_cnv.h
     audriv.h
     common.h
-    controls.h
+    decode.h
+       dls.h
     dlutils.h
     filter.h
     freq.h
-    gogo_a.h
     instrum.h
-    int_synth.h
-    LameEnc.h
     oscillator.h
     loadsndfontini.h
     mac_com.h
     mac_main.h
     mfnode.h
-    miditrace.h
     mix.h
     mod.h
     mod2midi.h
     mt19937ar.h
     myini.h
     optcode.h
-    output.h
     playmidi.h
-    portaudio_a.h
     pragmapack.h
     quantity.h
     readmidi.h
@@ -129,15 +154,12 @@ set(
     sffile.h
     sfitem.h
     sflayer.h
+    sfz.h
     smfconv.h
     sndfontini.h
     sysdep.h
     tables.h
-    thread.h
-    timer2.h
-    timidity.h
     voice_effect.h
-    vstwrapper.h
     w32_a.h
     w32_gogo.h
     w32_libFLAC_dll.h
@@ -147,20 +169,15 @@ set(
     w32_libOggFLAC_dll_g.h
     w32_libOggFLAC_dll_i.h
        wasapi_a.h
-    wrd.h
-
-    $<TARGET_OBJECTS:libarc>
-    $<TARGET_OBJECTS:libunimod>
-    $<TARGET_OBJECTS:utils>
+    wdmks_a.h
 )
 
 set(
     TIMIDITY_COMMON_LIBS
 
-    speex
-
     avrt
     comctl32
+    setupapi
     shlwapi
     winmm
     ws2_32
@@ -171,12 +188,13 @@ set(
 add_executable(
     timidity
 
-    ${TIMIDITY_COMMON_SOURCES}
+    ${TIMIDITY_INTERFACE_DEPENDENT_SOURCE}
     $<TARGET_OBJECTS:interface>
+    $<TARGET_OBJECTS:timidity_common>
 )
 
 add_dependencies(timidity UpdateTim41Version)
-target_compile_definitions(timidity PRIVATE -DIA_NCURSES)
+target_compile_definitions(timidity PRIVATE -DIA_NCURSES -DIA_VT100)
 target_link_libraries(timidity ${TIMIDITY_COMMON_LIBS} pdcurses)
 
 # twsynsrv
@@ -184,12 +202,13 @@ target_link_libraries(timidity ${TIMIDITY_COMMON_LIBS} pdcurses)
 add_executable(
     twsynsrv
 
-    ${TIMIDITY_COMMON_SOURCES}
+    ${TIMIDITY_INTERFACE_DEPENDENT_SOURCE}
     $<TARGET_OBJECTS:interface_synsrv>
+    $<TARGET_OBJECTS:timidity_common>
 )
 
 add_dependencies(twsynsrv UpdateTim41Version)
-target_compile_definitions(twsynsrv PRIVATE -DIA_WINSYN -DTWSYNSRV)
+target_compile_definitions(twsynsrv PRIVATE -DIA_NPSYN -DIA_PORTMIDISYN -DIA_WINSYN -DTWSYNSRV)
 target_link_libraries(twsynsrv ${TIMIDITY_COMMON_LIBS} pdcurses)
 
 # timw32g
@@ -197,8 +216,9 @@ target_link_libraries(twsynsrv ${TIMIDITY_COMMON_LIBS} pdcurses)
 add_executable(
     timw32g WIN32
 
-    ${TIMIDITY_COMMON_SOURCES}
+    ${TIMIDITY_INTERFACE_DEPENDENT_SOURCE}
     $<TARGET_OBJECTS:interface_w32g>
+    $<TARGET_OBJECTS:timidity_common>
 )
 
 add_dependencies(timw32g UpdateTim41Version)
@@ -211,11 +231,12 @@ DisableMSManifest(timw32g)
 add_executable(
     twsyng WIN32
 
-    ${TIMIDITY_COMMON_SOURCES}
+    ${TIMIDITY_INTERFACE_DEPENDENT_SOURCE}
     $<TARGET_OBJECTS:interface_w32gsyn>
+    $<TARGET_OBJECTS:timidity_common>
 )
 
 add_dependencies(twsyng UpdateTim41Version)
-target_compile_definitions(twsyng PRIVATE -DIA_W32G_SYN -D__W32G__ -DTWSYNG32)
+target_compile_definitions(twsyng PRIVATE -DIA_NPSYN -DIA_PORTMIDISYN -DIA_W32G_SYN -D__W32G__ -DTWSYNG32)
 target_link_libraries(twsyng ${TIMIDITY_COMMON_LIBS} pdcurses)
 DisableMSManifest(twsyng)
index 8d9c2bc..d90944c 100644 (file)
@@ -85,12 +85,6 @@ static uint32 bytes_output, next_bytes;
 static int already_warning_lseek;
 static int comm_chunk_offset, comm_chunk_size;
 
-///r
-#ifdef __W32G__
-extern char *w32g_output_dir;
-extern int w32g_auto_output_mode;
-#endif
-
 /*************************************************************************/
 
 static int write_u32(uint32 value)
index 5c0b526..5b5059e 100644 (file)
@@ -29,7 +29,7 @@
 #include <unistd.h>
 #endif /* HAVE_UNISTD_H */
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "controls.h"
 
index d563f02..9c29bbf 100644 (file)
@@ -46,8 +46,7 @@ int get_sample_size_for_sample_type(int data_type)
 
 void clear_sample_decode_result(SampleDecodeResult *sdr)
 {
-       int i;
-       for (i = 0; i < DECODE_MAX_CHANNELS; i++) {
+       for (int i = 0; i < DECODE_MAX_CHANNELS; i++) {
                if (sdr->data_alloced[i]) {
                        safe_free(sdr->data[i]);
                        sdr->data_alloced[i] = 0;
@@ -72,8 +71,6 @@ extern int load_vorbis_dll(void);     // w32g_vorbis_dll.c
 extern int load_vorbisfile_dll(void);  // w32g_vorbisfile_dll.c
 #endif
 
-static sample_t DummySampleData[128] = {0};;
-
 static size_t oggvorbis_read_callback(void *ptr, size_t size, size_t nmemb, void *datasource)
 {
     struct timidity_file *tf = (struct timidity_file *)datasource;
@@ -94,18 +91,12 @@ static long oggvorbis_tell_callback(void *datasource)
 
 SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
 {
-       int result;
-    SampleDecodeResult sdr = {0};
-    OggVorbis_File vf;
-       vorbis_info *info = NULL;
-       int64 total;
-       ptr_size_t data_length;
-       ptr_size_t current_size;
+       ctl->cmsg(CMSG_INFO, VERB_DEBUG, "decoding ogg vorbis file...");
 
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
+    SampleDecodeResult sdr = {.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
+    OggVorbis_File vf;
 
+#ifdef AU_VORBIS_DLL
     if (load_vorbis_dll() != 0) {
         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unable to load vorbis dll");
         return sdr;
@@ -116,17 +107,19 @@ SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
         return sdr;
     }
 #endif
-       vf.callbacks.read_func = &oggvorbis_read_callback;
-       vf.callbacks.seek_func = &oggvorbis_seek_callback;
-       vf.callbacks.tell_func = &oggvorbis_tell_callback;
-    result = ov_open_callbacks(tf, &vf, 0, 0, vf.callbacks);
+#endif
+
+    int result = ov_open_callbacks(
+        tf, &vf, 0, 0,
+        (ov_callbacks){.read_func = &oggvorbis_read_callback, .seek_func = &oggvorbis_seek_callback, .tell_func = &oggvorbis_tell_callback}
+    );
 
     if (result != 0) {
         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unable to open ogg vorbis data; ov_open_callbacks() failed");
         return sdr;
     }
 
-    info = ov_info(&vf, -1);
+    vorbis_info *info = ov_info(&vf, -1);
 
     if (!info) {
         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unable to read ogg vorbis info; ov_info() failed");
@@ -134,16 +127,23 @@ SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
     }
 
     sdr.channels = info->channels;
-    total = ov_pcm_total(&vf, -1);
+
+       if (sdr.channels < 1 || DECODE_MAX_CHANNELS < sdr.channels) {
+               ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "samples with more than %d channels are not supported", DECODE_MAX_CHANNELS);
+               goto cleanup;
+       }
+
+       sdr.sample_rate = info->rate;
+    int64 total = ov_pcm_total(&vf, -1);
 
     if (total < 0) {
         ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unable to get data length; ov_pcm_total() failed");
         goto cleanup;
     }
 
-    data_length = info->channels * sizeof(sample_t) * total;
+    ptr_size_t data_length = info->channels * sizeof(sample_t) * total;
        data_length = (data_length > 0 ? data_length : 4096);
-       current_size = 0;
+       ptr_size_t current_size = 0;
     sdr.data[0] = (sample_t *)safe_large_malloc(data_length);
        sdr.data_alloced[0] = 1;
 
@@ -161,8 +161,8 @@ SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
                current_size += ret;
 
                if (data_length - current_size < 512) {
-                       ptr_size_t new_data_length = data_length + data_length / 2;
-                       sdr.data[0] = (sample_t *)safe_large_realloc(sdr.data, new_data_length);
+                       ptr_size_t new_data_length = data_length + data_length / 2 + 128;
+                       sdr.data[0] = (sample_t *)safe_large_realloc(sdr.data[0], new_data_length);
                        data_length = new_data_length;
                }
     }
@@ -171,17 +171,16 @@ SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
        ov_clear(&vf);
 
        if (sdr.channels > 1) {
-               int i, j;
                // split data into multiple channels
                sample_t *single_data = sdr.data[0];
 
-               for (i = 0; i < sdr.channels; i++) {
+               for (int i = 0; i < sdr.channels; i++) {
                        sdr.data[i] = (sample_t *)safe_large_calloc((current_size / sdr.channels) + 128, sizeof(sample_t));
                        sdr.data_alloced[i] = 1;
                }
 
-               for (i = 0; i < current_size / sdr.channels; i++) {
-                       for (j = 0; j < sdr.channels; j++) {
+               for (int i = 0; i < current_size / sdr.channels; i++) {
+                       for (int j = 0; j < sdr.channels; j++) {
                                sdr.data[j][i] = single_data[i * sdr.channels + j];
                        }
                }
@@ -202,13 +201,8 @@ cleanup:
 
 SampleDecodeResult decode_oggvorbis(struct timidity_file *tf)
 {
-    SampleDecodeResult sdr = {0};
-
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "ogg vorbis decoder support is disabled");
-    return sdr;
+       return (SampleDecodeResult){.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
 }
 
 #endif // HAVE_LIBVORBIS
@@ -276,14 +270,13 @@ static FLAC__StreamDecoderTellStatus flac_tell_callback(const FLAC__StreamDecode
 
 static FLAC__StreamDecoderLengthStatus flac_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
 {
-       off_size_t prevpos;
        struct timidity_file *tf = ((FLACDecodeContext *)client_data)->input;
 
        if (!IS_URL_SEEK_SAFE(tf->url)) {
                return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
        }
 
-       prevpos = tf_seek(tf, 0, SEEK_END);
+       off_size_t prevpos = tf_seek(tf, 0, SEEK_END);
 
        if (prevpos == -1L) {
                return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
@@ -306,27 +299,25 @@ static FLAC__bool flac_eof_callback(const FLAC__StreamDecoder *decoder, void *cl
 
 static FLAC__StreamDecoderWriteStatus flac_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
 {
-       int i;
-       unsigned int j;
        FLACDecodeContext *context = (FLACDecodeContext *)client_data;
        SampleDecodeResult *sdr = context->output;
 
        if (context->current_size_in_samples + frame->header.blocksize + 128 > context->buffer_size_in_samples) {
                context->buffer_size_in_samples += context->buffer_size_in_samples / 2 + frame->header.blocksize + 128;
 
-               for (i = 0; i < sdr->channels; i++) {
+               for (int i = 0; i < sdr->channels; i++) {
                        sdr->data[i] = (sample_t *)safe_large_realloc(sdr->data[i], get_sample_size_for_sample_type(sdr->data_type) * context->buffer_size_in_samples);
                }
        }
 
-       for (i = 0; i < sdr->channels; i++) {
+       for (int i = 0; i < sdr->channels; i++) {
                switch (sdr->data_type) {
                case SAMPLE_TYPE_INT32:
                        memcpy(((FLAC__int32 *)sdr->data[i]) + context->current_size_in_samples, buffer[i], frame->header.blocksize * sizeof(FLAC__int32));
                        break;
 
                case SAMPLE_TYPE_INT16:
-                       for (j = 0; j < frame->header.blocksize; j++) {
+                       for (unsigned int j = 0; j < frame->header.blocksize; j++) {
                                sdr->data[i][context->current_size_in_samples + j] = (FLAC__int16)buffer[i][j];
                        }
                        break;
@@ -340,7 +331,6 @@ static FLAC__StreamDecoderWriteStatus flac_write_callback(const FLAC__StreamDeco
 // FIXME: not safe if called multiple times
 static void flac_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
 {
-       int i;
        FLACDecodeContext *context = (FLACDecodeContext *)client_data;
        SampleDecodeResult *sdr = context->output;
 
@@ -356,7 +346,7 @@ static void flac_metadata_callback(const FLAC__StreamDecoder *decoder, const FLA
                        sdr->channels = DECODE_MAX_CHANNELS;
                }
 
-               for (i = 0; i < sdr->channels; i++) {
+               for (int i = 0; i < sdr->channels; i++) {
                        sdr->data[i] = (sample_t *)safe_large_malloc(get_sample_size_for_sample_type(sdr->data_type) * context->buffer_size_in_samples);
                        sdr->data_alloced[i] = 1;
                }
@@ -369,18 +359,9 @@ static void flac_error_callback(const FLAC__StreamDecoder *decoder, FLAC__Stream
 }
 
 SampleDecodeResult decode_flac(struct timidity_file *tf)
-{      
-       int i;
-    SampleDecodeResult sdr = {0};
-       FLAC__StreamDecoder *decoder = NULL;
-       FLACDecodeContext context;
-       FLAC__StreamDecoderInitStatus init_status;
-
-       
+{
        ctl->cmsg(CMSG_INFO, VERB_DEBUG, "decoding FLAC file...");
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
+       SampleDecodeResult sdr = {.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
 
 #ifdef AU_FLAC_DLL
        if (g_load_libFLAC_dll() != 0) {
@@ -389,7 +370,7 @@ SampleDecodeResult decode_flac(struct timidity_file *tf)
        }
 #endif
 
-       decoder = FLAC__stream_decoder_new();
+       FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
 
        if (!decoder) {
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC__stream_decoder_new() failed");
@@ -398,10 +379,9 @@ SampleDecodeResult decode_flac(struct timidity_file *tf)
 
        FLAC__stream_decoder_set_md5_checking(decoder, TRUE);
 
-       context.input = tf;
-       context.output = &sdr;
+       FLACDecodeContext context = {tf, &sdr};
 
-       init_status = FLAC__stream_decoder_init_stream(
+       FLAC__StreamDecoderInitStatus init_status = FLAC__stream_decoder_init_stream(
                decoder,
                &flac_read_callback,
                &flac_seek_callback,
@@ -424,7 +404,7 @@ SampleDecodeResult decode_flac(struct timidity_file *tf)
                goto cleanup;
        }
 
-       for (i = 0; i < sdr.channels; i++) {
+       for (int i = 0; i < sdr.channels; i++) {
                memset(
                        (char *)sdr.data[i] + context.current_size_in_samples * get_sample_size_for_sample_type(sdr.data_type),
                        0,
@@ -449,13 +429,8 @@ cleanup:
 
 SampleDecodeResult decode_flac(struct timidity_file *tf)
 {
-    SampleDecodeResult sdr = {0};
-
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC decoder support is disabled");
-    return sdr;
+       return (SampleDecodeResult){.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
 }
 
 #endif // AU_FLAC
@@ -464,20 +439,6 @@ SampleDecodeResult decode_flac(struct timidity_file *tf)
 
 #include <mpg123.h>
 
-// from libmpg123/format.c
-static const long supported_rates[9] = {
-       8000, 11025, 12000,
-       16000, 22050, 24000,
-       32000, 44100, 48000
-};
-
-static const int supported_encodings[4] = {
-       MPG123_ENC_SIGNED_16,
-       MPG123_ENC_SIGNED_32,
-       MPG123_ENC_FLOAT_32,
-       MPG123_ENC_FLOAT_64
-};
-
 int load_mpg123_dll(void);
 
 static ssize_t mp3_read_callback(void *handle, void *buf, size_t count)
@@ -494,20 +455,8 @@ static off_t mp3_seek_callback(void *handle, off_t offset, int whence)
 
 SampleDecodeResult decode_mp3(struct timidity_file *tf)
 {
-       SampleDecodeResult sdr = {0};
-       mpg123_handle *mh = NULL;
-       int i, j;
-       long rate;
-       int channels;
-       int encoding;
-       size_t current_length = 0;
-       size_t buffer_size = 1024;
-
        ctl->cmsg(CMSG_INFO, VERB_DEBUG, "decoding mp3 file...");
-
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
+       SampleDecodeResult sdr = {.data[0] = DummySampleData,.data[1] = DummySampleData,.data_type = SAMPLE_TYPE_INT16};
 
        if (load_mpg123_dll() != 0) {
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unable to load libmpg123.dll");
@@ -519,7 +468,7 @@ SampleDecodeResult decode_mp3(struct timidity_file *tf)
                return sdr;
        }
 
-       mh = mpg123_new(NULL, NULL);
+       mpg123_handle *mh = mpg123_new(NULL, NULL);
 
        if (!mh) {
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "mpg123_new() failed");
@@ -531,8 +480,22 @@ SampleDecodeResult decode_mp3(struct timidity_file *tf)
                goto cleanup;
        }
 
-       for (i = 0; i < sizeof(supported_rates) / sizeof(supported_rates[0]); i++) {
-               for (j = 0; j < sizeof(supported_encodings) / sizeof(supported_encodings[0]); j++) {
+       // from libmpg123/format.c
+       static const long supported_rates[9] = {
+               8000, 11025, 12000,
+               16000, 22050, 24000,
+               32000, 44100, 48000
+       };
+
+       static const int supported_encodings[4] = {
+               MPG123_ENC_SIGNED_16,
+               MPG123_ENC_SIGNED_32,
+               MPG123_ENC_FLOAT_32,
+               MPG123_ENC_FLOAT_64
+       };
+
+       for (int i = 0; i < sizeof(supported_rates) / sizeof(supported_rates[0]); i++) {
+               for (int j = 0; j < sizeof(supported_encodings) / sizeof(supported_encodings[0]); j++) {
                        if (mpg123_format(mh, supported_rates[i], MPG123_STEREO | MPG123_MONO, supported_encodings[j]) != MPG123_OK) {
                                ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "mpg123_format() failed");
                                goto cleanup;
@@ -550,6 +513,9 @@ SampleDecodeResult decode_mp3(struct timidity_file *tf)
                goto cleanup;
        }
 
+       long rate;
+       int channels;
+       int encoding;
        if (mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK) {
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "mpg123_getformat() failed");
                goto cleanup;
@@ -596,17 +562,17 @@ SampleDecodeResult decode_mp3(struct timidity_file *tf)
                goto cleanup;
        }
 
+       size_t current_length = 0;
+       size_t buffer_size = 1024;
        sdr.data[0] = (sample_t *)safe_large_malloc(buffer_size);
        sdr.data_alloced[0] = 1;
 
        while (1) {
-               size_t decoded;
-               int err;
-
                buffer_size += buffer_size / 2 + 128;
                sdr.data[0] = (sample_t *)safe_large_realloc(sdr.data[0], buffer_size);
 
-               err = mpg123_read(mh, (unsigned char *)sdr.data[0] + current_length, buffer_size - current_length - 128, &decoded);
+               size_t decoded;
+               int err = mpg123_read(mh, (unsigned char *)sdr.data[0] + current_length, buffer_size - current_length - 128, &decoded);
                current_length += decoded;
 
                if (err == MPG123_DONE) {
@@ -626,13 +592,13 @@ SampleDecodeResult decode_mp3(struct timidity_file *tf)
                // split data into multiple channels
                sample_t *single_data = sdr.data[0];
 
-               for (i = 0; i < sdr.channels; i++) {
+               for (int i = 0; i < sdr.channels; i++) {
                        sdr.data[i] = (sample_t *)safe_large_calloc(current_length / sdr.channels + 128, 1);
                        sdr.data_alloced[i] = 1;
                }
 
-               for (i = 0; i < current_length / get_sample_size_for_sample_type(sdr.data_type) / sdr.channels; i++) {
-                       for (j = 0; j < sdr.channels; j++) {
+               for (int i = 0; i < current_length / get_sample_size_for_sample_type(sdr.data_type) / sdr.channels; i++) {
+                       for (int j = 0; j < sdr.channels; j++) {
                                memcpy(
                                        &sdr.data[j][i],
                                        (char *)single_data + (i * sdr.channels + j) * get_sample_size_for_sample_type(sdr.data_type),
@@ -652,23 +618,15 @@ cleanup:
        mpg123_delete(mh);
        // mpg123_exit();
        clear_sample_decode_result(&sdr);
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
-       return sdr;
+       return (SampleDecodeResult){.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
 }
 
 #else // HAVE_LIBMPG123
 
 SampleDecodeResult decode_mp3(struct timidity_file *tf)
 {
-    SampleDecodeResult sdr = {0};
-
-       sdr.data[0] = DummySampleData;
-       sdr.data[1] = DummySampleData;
-       sdr.data_type = SAMPLE_TYPE_INT16;
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "mp3 decoder support is disabled");
-    return sdr;
+       return (SampleDecodeResult){.data[0] = DummySampleData, .data[1] = DummySampleData, .data_type = SAMPLE_TYPE_INT16};
 }
 
 #endif // HAVE_LIBMPG123
index 5170b5b..cab46d1 100644 (file)
@@ -113,7 +113,7 @@ enum{
 #define FILTER_T FLOAT_T
 #endif
 
-#define FILTER_CF_NUM (24) // >= 8*3 (AVX
+#define FILTER_CF_NUM (40) // >= 8*3 (AVX
 #define FILTER_FB_NUM (25) // >= 8*3+1 (AVX
 #define FILTER_FB_L (0)
 #define FILTER_FB_R (FILTER_FB_NUM) 
index a212f56..83e54e1 100644 (file)
@@ -25,7 +25,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #ifdef __POCC__
 #include <sys/types.h>
 #endif //for off_t
index 28eb479..5805dc1 100644 (file)
@@ -28,7 +28,7 @@
 #ifdef __POCC__
 #include <sys/types.h>
 #endif //for off_t
-#include "interface.h"
+
 #include <stdio.h>
 #include <stdlib.h>
 
index 36153b8..ea1fafa 100644 (file)
@@ -23,7 +23,7 @@
 #ifndef ___INT_SYNTH_H_
 #define ___INT_SYNTH_H_
 
-#include "interface.h"
+
 #include "filter.h"
 
 
index e1d4abd..46a0b99 100644 (file)
@@ -3,7 +3,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include <stdio.h>
 #include <string.h>
 
index e0c951a..7261030 100644 (file)
@@ -27,7 +27,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 #include "instrum.h"
index b91e36d..ee31aea 100644 (file)
@@ -600,7 +600,7 @@ void shrink_huge_sample (Sample *sp)
     safe_free(sp->data);
     sp->data = new_data;
     sp->sample_rate = new_rate;
-       
+
     sp->data_length = (splen_t)new_data_length << FRACTION_BITS;
     sp->loop_start = loop_start * (1 << FRACTION_BITS);
     sp->loop_end = loop_end * (1 << FRACTION_BITS);
old mode 100755 (executable)
new mode 100644 (file)
index 41e518a..bc5ae2a
@@ -222,7 +222,7 @@ int32 imuldiv28(int32 a, int32 b) {
 /*****************************************************************************/
 #if (USE_X86_EXT_ASM || USE_X86_EXT_INTRIN || USE_X86_AMD_EXT_ASM || USE_X86_AMD_EXT_INTRIN)
 #ifdef __GNUC__
-inline void CPUID(int32 *regs, uint32 eax)
+void CPUID(int32 *regs, uint32 eax)
 {
        uint32 ebx,ecx,edx;
        __asm__ __volatile__ (
old mode 100755 (executable)
new mode 100644 (file)
index 0eee6e8..c1708f7
@@ -122,8 +122,8 @@ AVX2
 #undef USE_PENTIUM_4
 #endif
 
-#define USE_SSE // \83e\83X\83g\97p
-#define USE_SSE2 // \83e\83X\83g\97p
+//#define USE_SSE // \83e\83X\83g\97p
+//#define USE_SSE2 // \83e\83X\83g\97p
 //#define USE_SSE3 // \83e\83X\83g\97p
 //#define USE_SSSE3 // \83e\83X\83g\97p
 //#define USE_SSE41 // \83e\83X\83g\97p
@@ -832,7 +832,7 @@ LSU : Unalignment (use loadu/storeu
 #endif
 
 #if (USE_X86_EXT_INTRIN >= 1)
-#if !(defined(_MSC_VER) || defined(MSC_VER))
+#if !defined(_MSC_VER) || defined(__clang__)
 #define MM_EXTRACT_F32(reg,idx) _mm_cvtss_f32(_mm_shuffle_ps(reg,reg,idx))
 #define MM_EXTRACT_F64(reg,idx) _mm_cvtsd_f64(_mm_shuffle_pd(reg,reg,idx))
 #define MM_EXTRACT_I32(reg,idx) _mm_cvtsi128_si32(_mm_shuffle_epi32(reg,idx))
@@ -865,7 +865,6 @@ LSU : Unalignment (use loadu/storeu
 
 static TIMIDITY_FORCEINLINE __m256i mm256_i32gather_i32_impl(const int *base, __m256i offset, int scale)
 {
-       int i;
        ALIGN32 int32 buf[8];
        __m256i byte_offset = _mm256_mullo_epi32(offset, _mm256_set1_epi32(scale));
 #ifdef IX64CPU
@@ -890,7 +889,7 @@ static TIMIDITY_FORCEINLINE __m256i mm256_i32gather_i32_impl(const int *base, __
        __m256i pointers = _mm256_add_epi32(_mm256_set1_epi32((int32)base), byte_offset);
        _mm256_store_si256((__m256i *)buf, pointers);
 
-       for (i = 0; i < 8; i++) {
+       for (int i = 0; i < 8; i++) {
                buf[i] = *(const int *)buf[i];
        }
 #endif
@@ -903,7 +902,6 @@ static TIMIDITY_FORCEINLINE __m256i mm256_i32gather_i32_impl(const int *base, __
 
 static TIMIDITY_FORCEINLINE void mm256_i32scatter_i32_impl(void *base, __m256i offset, __m256i val, int scale)
 {
-       int i;
        ALIGN32 int32 buf[8];
        _mm256_store_si256((__m256i *)buf, val);
 
@@ -931,7 +929,7 @@ static TIMIDITY_FORCEINLINE void mm256_i32scatter_i32_impl(void *base, __m256i o
        ALIGN32 int32 *ptr[8];
        _mm256_store_si256((__m256i *)ptr, vptr);
 
-       for (i = 0; i < 8; i++) {
+       for (int i = 0; i < 8; i++) {
                *ptr[i] = buf[i];
        }
 #endif
@@ -948,7 +946,6 @@ static TIMIDITY_FORCEINLINE void mm256_i32scatter_i32_impl(void *base, __m256i o
 
 static TIMIDITY_FORCEINLINE __m128i mm_i32gather_i32_impl(const int *base, __m128i offset, int scale)
 {
-       int i;
        ALIGN16 int32 buf[4];
        __m128i byte_offset = _mm_mullo_epi32(offset, _mm_set1_epi32(scale));
 #ifdef IX64CPU
@@ -969,7 +966,7 @@ static TIMIDITY_FORCEINLINE __m128i mm_i32gather_i32_impl(const int *base, __m12
        __m128i pointers = _mm_add_epi32(_mm_set1_epi32((int32)base), byte_offset);
        _mm_store_si128((__m128i *)buf, pointers);
 
-       for (i = 0; i < 4; i++) {
+       for (int i = 0; i < 4; i++) {
                buf[i] = *(const int *)buf[i];
        }
 #endif
@@ -985,7 +982,6 @@ static TIMIDITY_FORCEINLINE __m128i mm_i32gather_i32_impl(const int *base, __m12
 
 static TIMIDITY_FORCEINLINE void mm_i32scatter_i32_impl(void *base, __m128i offset, __m128i val, int scale)
 {
-       int i;
        ALIGN16 int32 buf[4];
        _mm_store_si128((__m128i *)buf, val);
        {
@@ -1009,7 +1005,7 @@ static TIMIDITY_FORCEINLINE void mm_i32scatter_i32_impl(void *base, __m128i offs
        ALIGN16 int32 *ptr[4];
        _mm_store_si128((__m128i *)ptr, vptr);
 
-       for (i = 0; i < 4; i++) {
+       for (int i = 0; i < 4; i++) {
                *ptr[i] = buf[i];
        }
 #endif
index b994c1c..c44a439 100644 (file)
@@ -24,7 +24,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include <stdio.h>
 #include <string.h>
 
index df7a0cc..ce55cba 100644 (file)
@@ -31,7 +31,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #ifdef STDC_HEADERS
 #include <string.h>
 #include <ctype.h>
@@ -138,6 +138,7 @@ extern PlayMode portaudio_win_wdmks_play_mode;
 #endif
 extern PlayMode portaudio_win_ds_play_mode;
 extern PlayMode portaudio_win_wmme_play_mode;
+extern PlayMode portaudio_win_wasapi_play_mode;
 #endif
 #endif /* AU_PORTAUDIO */
 
index 1163ad0..a46aad9 100644 (file)
@@ -27,7 +27,7 @@
 #include <sys/types.h>
 #endif // for off_t
 #ifdef __W32__
-#include "interface.h"
+
 #endif
 #include <stdio.h>
 #ifdef HAVE_STDLIB_H
index 9fb67f0..27b73d9 100644 (file)
@@ -3,7 +3,7 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "output.h"
 
index e28b4c3..d27b7b5 100644 (file)
@@ -4983,7 +4983,7 @@ static void smf_time_signature(int32 at, struct timidity_file *tf, int len)
     c = tf_getc(tf);
     b = tf_getc(tf);
 
-    if(n == 0 || d == 0)
+    if(n == 0 || (uint8) d == 0)
     {
        ctl->cmsg(CMSG_WARNING, VERB_VERBOSE, "Invalid time signature");
        return;
index 7b2e394..112dab5 100644 (file)
@@ -33,7 +33,6 @@
 #include <strings.h>
 #endif
 
-#include "interface.h"
 #include "timidity.h"
 #include "common.h"
 #include "instrum.h"
old mode 100755 (executable)
new mode 100644 (file)
index dcf9273..f243076
@@ -1040,11 +1040,11 @@ static int AIFFGetMarkerPosition(int16 id, const AIFFMarkerData *markers, uint32
 static int import_oggvorbis_discriminant(char *sample_file)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       char buf[4];
 
        if (tf == NULL)
                return 1;
 
+       char buf[4];
        if (tf_read(buf, 1, 4, tf) != 4 || memcmp(buf, "OggS", 4) != 0) {
                close_file(tf);
                return 1;
@@ -1057,16 +1057,14 @@ static int import_oggvorbis_discriminant(char *sample_file)
 static int import_oggvorbis_load(char *sample_file, Instrument *inst)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       SampleDecodeResult sdr;
-       int ret;
 
        if (tf == NULL)
                return 1;
 
-       sdr = decode_oggvorbis(tf);
+       SampleDecodeResult sdr = decode_oggvorbis(tf);
        close_file(tf);
 
-       ret = make_instrument_from_sample_decode_result(inst, &sdr);
+       int ret = make_instrument_from_sample_decode_result(inst, &sdr);
        clear_sample_decode_result(&sdr);
        return ret;
 }
@@ -1076,11 +1074,11 @@ static int import_oggvorbis_load(char *sample_file, Instrument *inst)
 static int import_flac_discriminant(char *sample_file)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       char buf[4];
 
        if (tf == NULL)
                return 1;
 
+       char buf[4];
        if (tf_read(buf, 1, 4, tf) != 4 || memcmp(buf, "fLaC", 4) != 0) {
                close_file(tf);
                return 1;
@@ -1093,16 +1091,14 @@ static int import_flac_discriminant(char *sample_file)
 static int import_flac_load(char *sample_file, Instrument *inst)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       SampleDecodeResult sdr;
-       int ret;
 
        if (tf == NULL)
                return 1;
 
-       sdr = decode_flac(tf);
+       SampleDecodeResult sdr = decode_flac(tf);
        close_file(tf);
 
-       ret = make_instrument_from_sample_decode_result(inst, &sdr);
+       int ret = make_instrument_from_sample_decode_result(inst, &sdr);
        clear_sample_decode_result(&sdr);
        return ret;
 }
@@ -1112,11 +1108,11 @@ static int import_flac_load(char *sample_file, Instrument *inst)
 static int import_mp3_discriminant(char *sample_file)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       unsigned char buf[3] = {0};
 
        if (tf == NULL)
                return 1;
 
+       unsigned char buf[3] = {0};
        tf_read(buf, 1, 3, tf);
        close_file(tf);
 
@@ -1134,16 +1130,14 @@ static int import_mp3_discriminant(char *sample_file)
 static int import_mp3_load(char *sample_file, Instrument *inst)
 {
        struct timidity_file *tf = open_file(sample_file, 1, OF_NORMAL);
-       SampleDecodeResult sdr;
-       int ret;
 
        if (tf == NULL)
                return 1;
 
-       sdr = decode_mp3(tf);
+       SampleDecodeResult sdr = decode_mp3(tf);
        close_file(tf);
 
-       ret = make_instrument_from_sample_decode_result(inst, &sdr);
+       int ret = make_instrument_from_sample_decode_result(inst, &sdr);
        clear_sample_decode_result(&sdr);
        return ret;
 }
@@ -1549,7 +1543,6 @@ void free_pcm_sample_file(Instrument *ip)
 
 static int make_instrument_from_sample_decode_result(Instrument *inst, SampleDecodeResult *sdr)
 {
-       int i;
        if (sdr->channels == 0)
                return 1;
 
@@ -1558,7 +1551,7 @@ static int make_instrument_from_sample_decode_result(Instrument *inst, SampleDec
 
        initialize_sample(inst, (int)(sdr->data_length >> FRACTION_BITS), get_sample_size_for_sample_type(sdr->data_type), sdr->sample_rate);
 
-       for (i = 0; i < inst->samples; i++) {
+       for (int i = 0; i < inst->samples; i++) {
                Sample *s = &inst->sample[i];
                s->data = sdr->data[i];
                sdr->data[i] = NULL;
index 64b9dd4..42d6c8d 100644 (file)
@@ -60,7 +60,7 @@
 #include "filter.h"
 #include "freq.h"
 #include "resample.h"
-#include "interface.h"
+
 #include "sndfontini.h"
 #include "decode.h"
 
@@ -828,7 +828,6 @@ static Instrument *load_from_file(SFInsts *rec, InstList *ip)
                if (rec->version >= 4) {
                        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unsupported soundfont version: %d", rec->version);
                } else if (rec->version == 3) {
-                       struct timidity_file *ctf = NULL;
                        off_size_t length = sp->len / 2;
                        off_size_t start_offset = (sp->start - rec->samplepos) / 2;
             char *compressed_data = (char *)safe_large_malloc(length);
@@ -836,16 +835,16 @@ static Instrument *load_from_file(SFInsts *rec, InstList *ip)
                        tf_seek(tf, sp->start - start_offset, SEEK_SET);
             tf_read(compressed_data, length, 1, tf);
 
-            ctf = open_with_mem(compressed_data, length, OF_VERBOSE);
+            struct timidity_file *ctf = open_with_mem(compressed_data, length, OF_VERBOSE);
 
             if (ctf) {
                 SampleDecodeResult sdr = decode_oggvorbis(ctf);
                 close_file(ctf);
-                               
+
                                if (sdr.channels != 1) {
                                        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "error: sf3 contains multichannel sample");
                                }
-                               
+
                                sample->sample_type |= SF_SAMPLETYPE_MONO;
                 sample->data = sdr.data[0];
                 sample->data_alloced = sdr.data_alloced[0];
@@ -1636,7 +1635,7 @@ static void set_sample_info(SFInfo *sf, SampleList *vp, LayerTable *tbl)
 
     /* set data length */
     vp->v.data_length = vp->len + 1;
-       
+
        if (sf->version < 3) {
                /* fix loop position */
                if (vp->v.loop_end > vp->len + 1)
index 64f3b81..9cf12bc 100644 (file)
@@ -1,7 +1,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include "timidity.h"
 #include "instrum.h"
 #include "common.h"
index 3646ecf..ac9a6b5 100644 (file)
@@ -317,7 +317,7 @@ static int speex_output_open(const char *fname, const char *comment)
 {
   Speex_ctx *ctx;
   int fd;
-  
+
   {
        int flag = 0;
 #ifdef AU_VORBIS_DLL
old mode 100755 (executable)
new mode 100644 (file)
index 5b09949..27cfa96 100644 (file)
@@ -6,7 +6,7 @@
 #ifdef __POCC__
 #include <sys/types.h>
 #endif // for off_t
-#include "interface.h"
+
 #include <stdio.h>
 #ifdef HAVE_STDLIB_H
 #include <stdlib.h>
index 3368428..d458d52 100644 (file)
@@ -1,6 +1,6 @@
 /*
     TiMidity++ -- MIDI to WAVE converter and player
-    Copyright (C) 1999-2008 Masanao Izumo <iz@onicos.co.jp>
+    Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>
     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
 
     This program is free software; you can redistribute it and/or modify
 
 uint8 opt_normal_chorus_plus = 5; // chorusEX
 
-#if defined(__W32__)
 extern DWORD processPriority;
 DWORD processPriority = NORMAL_PRIORITY_CLASS; // \83v\83\8d\83Z\83X\82Ì\83v\83\89\83C\83I\83\8a\83e\83B
 #if defined(IA_W32G_SYN) || defined(WINDRV)
 DWORD syn_ThreadPriority = THREAD_PRIORITY_NORMAL;
 #else
-int PlayerThreadPriority = THREAD_PRIORITY_NORMAL;
 int GUIThreadPriority = THREAD_PRIORITY_NORMAL;
 #endif
-#endif
+int PlayerThreadPriority = THREAD_PRIORITY_NORMAL;
 
 /* option enums */
 enum {
@@ -1868,7 +1866,7 @@ static int set_gus_patchconf(const char *name, int line,
                }
        }
 #endif
-    else if(strcmp(pat, "%pat") == 0) /* pat extention */
+       else if(strcmp(pat, "%pat") == 0) /* pat extention */
        {
                tone->instype = 0; // pat
                tone->name = safe_strdup(pat);
@@ -5725,7 +5723,7 @@ static int parse_opt_h(const char *arg)
 #endif
 {
        static char *help_list[] = {
-"TiMidity++ %s (C) 1999-2004 Masanao Izumo <iz@onicos.co.jp>",
+"TiMidity++ %s (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>",
 "The original version (C) 1995 Tuukka Toivonen <tt@cgs.fi>",
 "TiMidity is free software and comes with ABSOLUTELY NO WARRANTY.",
 "",
@@ -7715,7 +7713,7 @@ static inline int parse_opt_v(const char *arg)
                                timidity_version, " ", arch_string, NLS,
                NLS,
 #endif
-               "Copyright (C) 1999-2004 Masanao Izumo <iz@onicos.co.jp>", NLS,
+               "Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>", NLS,
                "Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>", NLS,
                NLS,
 #ifdef __W32__
@@ -8015,8 +8013,8 @@ static inline void close_pager(FILE *fp)
 static void interesting_message(void)
 {
        printf(
-"TiMidity++ %s%s %s -- MIDI to WAVE converter and player" NLS
-"Copyright (C) 1999-2004 Masanao Izumo <iz@onicos.co.jp>" NLS
+"TiMidity++ %s%s -- MIDI to WAVE converter and player" NLS
+"Copyright (C) 1999-2018 Masanao Izumo <iz@onicos.co.jp>" NLS
 "Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>" NLS
                        NLS
 #ifdef __W32__
@@ -8828,7 +8826,7 @@ int main(int argc, char **argv)
        _CrtSetDbgFlag(CRTDEBUGFLAGS);
 #endif
        atexit(w32_exit);
-       
+
 #ifdef __W32__
        {
                HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
diff --git a/timidity/timidity.dsp b/timidity/timidity.dsp
deleted file mode 100644 (file)
index 39fbd20..0000000
+++ /dev/null
@@ -1,474 +0,0 @@
-# Microsoft Developer Studio Project File - Name="timidity" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Static Library" 0x0104
-
-CFG=timidity - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "timidity.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "timidity.mak" CFG="timidity - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "timidity - Win32 Release" ("Win32 (x86) Static Library" \97p)
-!MESSAGE "timidity - Win32 Debug" ("Win32 (x86) Static Library" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "timidity - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /I "..\gogo" /I "..\ogg" /D "NDEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /FD /c
-# SUBTRACT CPP /YX
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Release\timidity.lib"
-
-!ELSEIF  "$(CFG)" == "timidity - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /Zp16 /MTd /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /I "..\gogo" /I "..\ogg" /D "_DEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Debug\timidity.lib"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "timidity - Win32 Release"
-# Name "timidity - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\timidity\aiff_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\ao_a.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\aq.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\au_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audio_cnv.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\common.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\controls.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\effect.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\filter.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\flac_a.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\freq.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\gogo_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\instrum.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\int_synth.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\lame_a.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\list_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\loadtab.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\m2m.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\mfi.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mfnode.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\miditrace.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mix.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mod.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mod2midi.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\modmid_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\mt19937ar.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\myini.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\npipe_a.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\optcode.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\opus_a.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\oscillator.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\output.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\playmidi.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\quantity.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\raw_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\rcp.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\readmidi.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\recache.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\resample.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sbkconv.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sffile.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sfitem.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\smfconv.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\smplfile.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sndfont.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\sndfontini.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\speex_a.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\tables.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\thread.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\timidity.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\version.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\voice_effect.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\volumecalc_a.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\vorbis_a.c"
-
-!IF  "$(CFG)" == "timidity - Win32 Release"
-
-# ADD CPP /Zp16 /O2
-
-!ELSEIF  "$(CFG)" == "timidity - Win32 Debug"
-
-!ENDIF 
-
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32_gogo.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\wave_a.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\wrd_read.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\wrdt.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\timidity\aenc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\aq.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audio_cnv.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\audriv.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\common.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\controls.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\dlutils.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\filter.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\gogo_a.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\instrum.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_com.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mac_main.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mfnode.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\miditrace.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mix.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mod.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\mod2midi.h"
-# End Source File
-# Begin Source File
-
-SOURCE=.\mt19937ar.h
-# End Source File
-# Begin Source File
-
-SOURCE=.\optcode.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\output.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\playmidi.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\readmidi.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\recache.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\resample.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\reverb.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sffile.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sfitem.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\sflayer.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\smfconv.h"
-# End Source File
-# Begin Source File
-
-SOURCE=.\sysdep.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\tables.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\timidity.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32_gogo.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\wrd.h"
-# End Source File
-# End Group
-# End Target
-# End Project
diff --git a/timidity/timidity.vcproj b/timidity/timidity.vcproj
deleted file mode 100644 (file)
index 9f73d09..0000000
+++ /dev/null
@@ -1,701 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="timidity"
-       ProjectGUID="{45579E0F-6A19-4E8C-B638-945E0FB44D36}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\..\lame\dll"
-                               PreprocessorDefinitions="_DEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/timidity.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\timidity.lib"
-                               AdditionalLibraryDirectories="../dll;"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\..\lame\dll"
-                               PreprocessorDefinitions="NDEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/timidity.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="1"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\timidity.lib"
-                               AdditionalLibraryDirectories="../dll;"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\aiff_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\ao_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\aq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\au_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\audio_cnv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\benchmark_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\controls.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\decode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\envelope.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\filter.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\flac_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\freq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\gogo_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\instrum.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\int_synth.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\lame_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\list_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\loadtab.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\m2m.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mfi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mfnode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\midi_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\miditrace.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mix.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mod.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mod2midi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\modmid_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mt19937ar.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\myini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\npipe_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\optcode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\opus_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\oscillator.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\output.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\playmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="portaudio_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\quantity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\raw_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\rcp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\readmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\recache.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\resample.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sbkconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sffile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sfitem.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\smfconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\smplfile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sndfont.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sndfontini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\speex_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\thread.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timer2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timidity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\version.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\voice_effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\volumecalc_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vorbis_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_gogo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wasapi_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wave_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wdmks_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wrd_read.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wrdt.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\aenc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\aq.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\audio_cnv.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\audriv.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\common.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\controls.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\dlutils.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\effect.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\filter.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\freq.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\gogo_a.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\instrum.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\int_synth.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\LameEnc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\loadsndfontini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_com.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_main.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mfnode.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\miditrace.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mix.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mod.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mod2midi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mt19937ar.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\myini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\optcode.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\oscillator.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\output.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\playmidi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\portaudio_a.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\pragmapack.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\quantity.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\readmidi.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\recache.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\resample.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sffile.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sfitem.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sflayer.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\smfconv.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sndfontini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\sysdep.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\tables.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\thread.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timer2.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timidity.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\voice_effect.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\vstwrapper.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_a.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_gogo.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libFLAC_dll.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libFLAC_dll_g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libFLAC_dll_i.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libOggFLAC_dll.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libOggFLAC_dll_g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_libOggFLAC_dll_i.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_portaudio.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\w32_soundspec.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\wrd.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/timidity/timidity.vcxproj b/timidity/timidity.vcxproj
deleted file mode 100644 (file)
index 5246507..0000000
+++ /dev/null
@@ -1,386 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{45579E0F-6A19-4E8C-B638-945E0FB44D36}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)include;C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)\Include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)\Include;</IncludePath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib;$(DXSDK_DIR)Lib\x86;C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)atlmfc\lib\amd64;$(VCInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;$(FrameworkSDKDir)\lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib;$(DXSDK_DIR)\Lib\x86;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib\x64;$(FrameworkSDKDir)\lib;$(DXSDK_DIR)\ILib\x86;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <InlineFunctionExpansion>Disabled</InlineFunctionExpansion>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\timidity.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories);..\..\lame\dll</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\timidity.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories);..\..\lame\dll</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <AssemblerOutput>NoListing</AssemblerOutput>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\timidity.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreAllDefaultLibraries>
-      </IgnoreAllDefaultLibraries>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\rcpcv;..\libmpg123\include;%(AdditionalIncludeDirectories);..\..\lame\dll</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timidity.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\timidity.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreAllDefaultLibraries>
-      </IgnoreAllDefaultLibraries>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="aiff_a.c" />
-    <ClCompile Include="ao_a.c" />
-    <ClCompile Include="aq.c" />
-    <ClCompile Include="au_a.c" />
-    <ClCompile Include="audio_cnv.c" />
-    <ClCompile Include="common.c" />
-    <ClCompile Include="controls.c" />
-    <ClCompile Include="decode.c" />
-    <ClCompile Include="effect.c" />
-    <ClCompile Include="envelope.c" />
-    <ClCompile Include="filter.c" />
-    <ClCompile Include="flac_a.c" />
-    <ClCompile Include="freq.c" />
-    <ClCompile Include="gogo_a.c" />
-    <ClCompile Include="instrum.c" />
-    <ClCompile Include="int_synth.c" />
-    <ClCompile Include="lame_a.c" />
-    <ClCompile Include="midi_a.c" />
-    <ClCompile Include="oscillator.c" />
-    <ClCompile Include="list_a.c" />
-    <ClCompile Include="loadtab.c" />
-    <ClCompile Include="m2m.c" />
-    <ClCompile Include="mfi.c" />
-    <ClCompile Include="mfnode.c" />
-    <ClCompile Include="miditrace.c" />
-    <ClCompile Include="mix.c" />
-    <ClCompile Include="mod.c" />
-    <ClCompile Include="mod2midi.c" />
-    <ClCompile Include="modmid_a.c" />
-    <ClCompile Include="mt19937ar.c" />
-    <ClCompile Include="myini.c" />
-    <ClCompile Include="npipe_a.c" />
-    <ClCompile Include="optcode.c" />
-    <ClCompile Include="opus_a.c" />
-    <ClCompile Include="output.c" />
-    <ClCompile Include="playmidi.c" />
-    <ClCompile Include="portaudio_a.c" />
-    <ClCompile Include="quantity.c" />
-    <ClCompile Include="raw_a.c" />
-    <ClCompile Include="rcp.c" />
-    <ClCompile Include="readmidi.c" />
-    <ClCompile Include="recache.c" />
-    <ClCompile Include="resample.c" />
-    <ClCompile Include="sbkconv.c" />
-    <ClCompile Include="sffile.c" />
-    <ClCompile Include="sfitem.c" />
-    <ClCompile Include="benchmark_a.c" />
-    <ClCompile Include="smfconv.c" />
-    <ClCompile Include="smplfile.c" />
-    <ClCompile Include="sndfont.c" />
-    <ClCompile Include="sndfontini.c" />
-    <ClCompile Include="speex_a.c" />
-    <ClCompile Include="tables.c" />
-    <ClCompile Include="thread.c" />
-    <ClCompile Include="timer2.c" />
-    <ClCompile Include="timidity.c" />
-    <ClCompile Include="version.c" />
-    <ClCompile Include="voice_effect.c" />
-    <ClCompile Include="volumecalc_a.c" />
-    <ClCompile Include="vorbis_a.c" />
-    <ClCompile Include="w32_a.c" />
-    <ClCompile Include="w32_gogo.c" />
-    <ClCompile Include="wasapi_a.c" />
-    <ClCompile Include="wave_a.c" />
-    <ClCompile Include="wdmks_a.c" />
-    <ClCompile Include="wrd_read.c" />
-    <ClCompile Include="wrdt.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll.h" />
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll_g.h" />
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll_i.h" />
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll.h" />
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll_g.h" />
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll_i.h" />
-    <ClInclude Include="aenc.h" />
-    <ClInclude Include="aq.h" />
-    <ClInclude Include="audio_cnv.h" />
-    <ClInclude Include="audriv.h" />
-    <ClInclude Include="common.h" />
-    <ClInclude Include="controls.h" />
-    <ClInclude Include="dlutils.h" />
-    <ClInclude Include="filter.h" />
-    <ClInclude Include="freq.h" />
-    <ClInclude Include="gogo_a.h" />
-    <ClInclude Include="instrum.h" />
-    <ClInclude Include="int_synth.h" />
-    <ClInclude Include="LameEnc.h" />
-    <ClInclude Include="oscillator.h" />
-    <ClInclude Include="loadsndfontini.h" />
-    <ClInclude Include="mac_com.h" />
-    <ClInclude Include="mac_main.h" />
-    <ClInclude Include="mfnode.h" />
-    <ClInclude Include="miditrace.h" />
-    <ClInclude Include="mix.h" />
-    <ClInclude Include="mod.h" />
-    <ClInclude Include="mod2midi.h" />
-    <ClInclude Include="mt19937ar.h" />
-    <ClInclude Include="myini.h" />
-    <ClInclude Include="optcode.h" />
-    <ClInclude Include="output.h" />
-    <ClInclude Include="playmidi.h" />
-    <ClInclude Include="portaudio_a.h" />
-    <ClInclude Include="pragmapack.h" />
-    <ClInclude Include="quantity.h" />
-    <ClInclude Include="readmidi.h" />
-    <ClInclude Include="recache.h" />
-    <ClInclude Include="resample.h" />
-    <ClInclude Include="effect.h" />
-    <ClInclude Include="sffile.h" />
-    <ClInclude Include="sfitem.h" />
-    <ClInclude Include="sflayer.h" />
-    <ClInclude Include="smfconv.h" />
-    <ClInclude Include="sndfontini.h" />
-    <ClInclude Include="sysdep.h" />
-    <ClInclude Include="tables.h" />
-    <ClInclude Include="thread.h" />
-    <ClInclude Include="timer2.h" />
-    <ClInclude Include="timidity.h" />
-    <ClInclude Include="voice_effect.h" />
-    <ClInclude Include="vstwrapper.h" />
-    <ClInclude Include="w32_a.h" />
-    <ClInclude Include="w32_gogo.h" />
-    <ClInclude Include="wasapi_a.h" />
-    <ClInclude Include="wrd.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/timidity/timidity.vcxproj.filters b/timidity/timidity.vcxproj.filters
deleted file mode 100644 (file)
index 68486e2..0000000
+++ /dev/null
@@ -1,377 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{ac28c825-fe52-465e-850c-d9353759d21f}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{39bea0c8-3755-4640-b513-037bf5c60a24}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="aiff_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="aq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="au_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="audio_cnv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="controls.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="filter.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="flac_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="freq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="gogo_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="instrum.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="list_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="loadtab.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="m2m.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mfi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mfnode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="miditrace.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mix.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mod.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mod2midi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="modmid_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mt19937ar.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="optcode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="output.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="playmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="portaudio_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="quantity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="raw_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="rcp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="readmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="recache.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="resample.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sbkconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sffile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sfitem.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="smfconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="smplfile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sndfont.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="tables.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="timidity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="version.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="vorbis_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="w32_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="w32_gogo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="wave_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="wrd_read.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="wrdt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="lame_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="myini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="sndfontini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="volumecalc_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="speex_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="npipe_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="envelope.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="opus_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="ao_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="thread.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="voice_effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="int_synth.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="timer2.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="benchmark_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="oscillator.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="midi_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="aenc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="aq.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="audio_cnv.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="audriv.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="common.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="controls.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="dlutils.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="filter.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="gogo_a.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="instrum.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_com.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_main.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mfnode.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="miditrace.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mix.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mod.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mod2midi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mt19937ar.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="optcode.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="output.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="playmidi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="readmidi.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="recache.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="resample.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sffile.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sfitem.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sflayer.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="smfconv.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sysdep.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="tables.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="timidity.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="w32_gogo.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="wrd.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="LameEnc.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="loadsndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="myini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="pragmapack.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="sndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="vstwrapper.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="w32_a.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="portaudio_a.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll_g.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libFLAC_dll_i.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll_g.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\tim130601\src\timidity\w32_libOggFLAC_dll_i.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="thread.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="voice_effect.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="int_synth.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="voice_filter.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="freq.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="timer2.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="quantity.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="effect.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="oscillator.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/timidity/timidity.vcxproj.user b/timidity/timidity.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
index 54fd83b..e65dbed 100644 (file)
@@ -27,7 +27,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 #include "instrum.h"
index 153c803..b6e4cbc 100644 (file)
 
 #ifdef AU_VOLUME_CALC
 
-#if defined(IA_W32GUI) || defined(TWSYNG32)
-extern char *w32g_output_dir;
-extern int w32g_auto_output_mode;
-#endif
-
 static int open_output(void); /* 0=success, 1=warning, -1=fatal error */
 static void close_output(void);
 static int32 output_data(const uint8 *buf, size_t bytes);
index 606d14c..be99dff 100644 (file)
@@ -25,7 +25,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include <stdio.h>
 #include <string.h>
 
index 386e73b..3239f93 100644 (file)
@@ -28,7 +28,7 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include "interface.h"
+
 #include "timidity.h"
 
 #include <stdio.h>
@@ -47,7 +47,6 @@
 #include "instrum.h"
 #include "playmidi.h"
 #include "mblock.h"
-#include "interface.h"
 
 ///r
 #include "w32_a.h"
index 02fa51e..c27a725 100644 (file)
@@ -3,7 +3,7 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include "interface.h"
+
 #include "timidity.h"
 #include "common.h"
 
@@ -17,6 +17,7 @@
 #include <strings.h>
 #endif
 #include <windows.h>
+#include <mmsystem.h>
 
 ///r
 #define DEVLIST_MAX 20
index 874c766..deca733 100644 (file)
@@ -32,7 +32,7 @@
 #ifdef __POCC__
 #include <sys/types.h>
 #endif //for off_t
-#include "interface.h"
+
 
 #ifdef AU_GOGO_DLL
 
index 0be62a7..53f10bd 100644 (file)
@@ -3,7 +3,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include "common.h"
 
 #ifdef AU_FLAC_DLL
index 419c12e..5d11e8f 100644 (file)
@@ -365,10 +365,10 @@ extern void g_free_libFLAC_dll ( void );
 
        
 #else  /* defined(LEGACY_FLAC) */
-
-extern int g_load_libFLAC_dll(void);
-extern void g_free_libFLAC_dll(void);  
        
+extern int g_load_libFLAC_dll(void);
+extern void g_free_libFLAC_dll(void);
+
         extern const char * const *  *g_FLAC__StreamEncoderInitStatusString;
         extern const char * const *  *g_FLAC__StreamEncoderStateString;
         extern const char * const *  *g_FLAC__StreamDecoderStateString;
index d231f42..ff8dfc8 100644 (file)
 /* #define IGNORE_libFLAC_FLAC__stream_encoder_finish  /* */
 #define IGNORE_libFLAC_FLAC__stream_encoder_process  /* */
 /* #define IGNORE_libFLAC_FLAC__stream_encoder_process_interleaved  /* */
-#define IGNORE_libFLAC_FLAC__stream_decoder_new  /* */
+/* #define IGNORE_libFLAC_FLAC__stream_decoder_new  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_delete  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_set_read_callback  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_set_write_callback  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_reset  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_process_single  /* */
 #define IGNORE_libFLAC_FLAC__stream_decoder_process_until_end_of_metadata  /* */
-#define IGNORE_libFLAC_FLAC__stream_decoder_process_until_end_of_stream  /* */
+/* #define IGNORE_libFLAC_FLAC__stream_decoder_process_until_end_of_stream  /* */
 /* #define IGNORE_libFLAC_FLAC__seekable_stream_encoder_new  /* */
 /* #define IGNORE_libFLAC_FLAC__seekable_stream_encoder_delete  /* */
 /* #define IGNORE_libFLAC_FLAC__seekable_stream_encoder_set_verify  /* */
index 7a8af1b..7650bb6 100644 (file)
@@ -2,7 +2,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef AU_OGGFLAC_DLL
 
index e0a976a..4a672e7 100644 (file)
@@ -55,23 +55,23 @@ int load_mpg123_dll(void)
 
                mpg123_dll.mpg123_init = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_init");
                if (!mpg123_dll.mpg123_init) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_new = (type_mpg123_new)GetProcAddress(h_mpg123_dll, "mpg123_new");
+               mpg123_dll.mpg123_new = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_new");
                if (!mpg123_dll.mpg123_new) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_close = (type_mpg123_close)GetProcAddress(h_mpg123_dll, "mpg123_close");
+               mpg123_dll.mpg123_close = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_close");
                if (!mpg123_dll.mpg123_close) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_delete = (type_mpg123_delete)GetProcAddress(h_mpg123_dll, "mpg123_delete");
+               mpg123_dll.mpg123_delete = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_delete");
                if (!mpg123_dll.mpg123_delete) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_format_none = (type_mpg123_format_none)GetProcAddress(h_mpg123_dll, "mpg123_format_none");
+               mpg123_dll.mpg123_format_none = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_format_none");
                if (!mpg123_dll.mpg123_format_none) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_format = (type_mpg123_format)GetProcAddress(h_mpg123_dll, "mpg123_format");
+               mpg123_dll.mpg123_format = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_format");
                if (!mpg123_dll.mpg123_format) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_replace_reader_handle = (type_mpg123_replace_reader_handle)GetProcAddress(h_mpg123_dll, "mpg123_replace_reader_handle");
+               mpg123_dll.mpg123_replace_reader_handle = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_replace_reader_handle");
                if (!mpg123_dll.mpg123_replace_reader_handle) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_open_handle = (type_mpg123_open_handle)GetProcAddress(h_mpg123_dll, "mpg123_open_handle");
+               mpg123_dll.mpg123_open_handle = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_open_handle");
                if (!mpg123_dll.mpg123_open_handle) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_getformat = (type_mpg123_getformat)GetProcAddress(h_mpg123_dll, "mpg123_getformat");
+               mpg123_dll.mpg123_getformat = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_getformat");
                if (!mpg123_dll.mpg123_getformat) { free_mpg123_dll(); return -1; }
-               mpg123_dll.mpg123_read = (type_mpg123_read)GetProcAddress(h_mpg123_dll, "mpg123_read");
+               mpg123_dll.mpg123_read = (type_mpg123_init)GetProcAddress(h_mpg123_dll, "mpg123_read");
                if (!mpg123_dll.mpg123_read) { free_mpg123_dll(); return -1; }
        }
 
index 293af14..8cb0393 100644 (file)
@@ -21,7 +21,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef AU_PORTAUDIO_DLL
 
diff --git a/timidity/w32_speex_dll.c b/timidity/w32_speex_dll.c
new file mode 100644 (file)
index 0000000..7262fb0
--- /dev/null
@@ -0,0 +1,225 @@
+
+#pragma once
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#ifdef AU_SPEEX_DLL
+
+#include <string.h>
+
+#include <speex/speex.h>
+#include <speex/speex_header.h>
+#include <speex/speex_stereo.h>
+
+#include <windows.h>
+
+#ifdef speex_lib_get_mode
+#undef speex_lib_get_mode
+#endif
+
+int load_speex_dll(void);
+void free_speex_dll(void);
+
+static HANDLE h_speex_dll;
+
+typedef void (*type_speex_bits_init)(SpeexBits *bits);
+typedef void (*type_speex_bits_reset)(SpeexBits *bits);
+typedef int (*type_speex_bits_write)(SpeexBits *bits, char *bytes, int max_len);
+typedef void (*type_speex_bits_pack)(SpeexBits *bits, int data, int nbBits);
+typedef void (*type_speex_bits_destroy)(SpeexBits *bits);
+typedef void *(*type_speex_encoder_init)(const SpeexMode *mode);
+typedef void (*type_speex_encoder_destroy)(void *state);
+typedef int (*type_speex_encode)(void *state, float *in, SpeexBits *bits);
+typedef int (*type_speex_encoder_ctl)(void *state, int request, void *ptr);
+typedef const SpeexMode *(*type_speex_lib_get_mode)(int mode);
+typedef void (*type_speex_init_header)(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m);
+typedef char *(*type_speex_header_to_packet)(SpeexHeader *header, int *size);
+typedef void (*type_speex_encode_stereo)(float *data, int frame_size, SpeexBits *bits);
+typedef void (*type_speex_bits_insert_terminator)(SpeexBits *bits);
+
+static struct {
+       type_speex_bits_init speex_bits_init;
+       type_speex_bits_reset speex_bits_reset;
+       type_speex_bits_write speex_bits_write;
+       type_speex_bits_pack speex_bits_pack;
+       type_speex_bits_destroy speex_bits_destroy;
+       type_speex_encoder_init speex_encoder_init;
+       type_speex_encoder_destroy speex_encoder_destroy;
+       type_speex_encode speex_encode;
+       type_speex_encoder_ctl speex_encoder_ctl;
+       type_speex_lib_get_mode speex_lib_get_mode;
+       type_speex_init_header speex_init_header;
+       type_speex_header_to_packet speex_header_to_packet;
+       type_speex_encode_stereo speex_encode_stereo;
+       type_speex_bits_insert_terminator speex_bits_insert_terminator;
+} speex_dll;
+
+int load_speex_dll(void)
+{
+       if (!h_speex_dll) {
+               h_speex_dll = LoadLibrary(TEXT("speex.dll"));
+
+               if (!h_speex_dll) {
+                       h_speex_dll = LoadLibrary(TEXT("libspeex.dll"));
+               }
+
+               if (!h_speex_dll) {
+                       return -1;
+               }
+
+               speex_dll.speex_bits_init = (type_speex_bits_init)GetProcAddress(h_speex_dll, "speex_bits_init");
+               if (!speex_dll.speex_bits_init) { free_speex_dll(); return -1; }
+               speex_dll.speex_bits_reset = (type_speex_bits_reset)GetProcAddress(h_speex_dll, "speex_bits_reset");
+               if (!speex_dll.speex_bits_reset) { free_speex_dll(); return -1; }
+               speex_dll.speex_bits_write = (type_speex_bits_write)GetProcAddress(h_speex_dll, "speex_bits_write");
+               if (!speex_dll.speex_bits_write) { free_speex_dll(); return -1; }
+               speex_dll.speex_bits_pack = (type_speex_bits_pack)GetProcAddress(h_speex_dll, "speex_bits_pack");
+               if (!speex_dll.speex_bits_pack) { free_speex_dll(); return -1; }
+               speex_dll.speex_bits_destroy = (type_speex_bits_destroy)GetProcAddress(h_speex_dll, "speex_bits_destroy");
+               if (!speex_dll.speex_bits_destroy) { free_speex_dll(); return -1; }
+               speex_dll.speex_encoder_init = (type_speex_encoder_init)GetProcAddress(h_speex_dll, "speex_encoder_init");
+               if (!speex_dll.speex_encoder_init) { free_speex_dll(); return -1; }
+               speex_dll.speex_encoder_destroy = (type_speex_encoder_destroy)GetProcAddress(h_speex_dll, "speex_encoder_destroy");
+               if (!speex_dll.speex_encoder_destroy) { free_speex_dll(); return -1; }
+               speex_dll.speex_encode = (type_speex_encode)GetProcAddress(h_speex_dll, "speex_encode");
+               if (!speex_dll.speex_encode) { free_speex_dll(); return -1; }
+               speex_dll.speex_encoder_ctl = (type_speex_encoder_ctl)GetProcAddress(h_speex_dll, "speex_encoder_ctl");
+               if (!speex_dll.speex_encoder_ctl) { free_speex_dll(); return -1; }
+               speex_dll.speex_lib_get_mode = (type_speex_lib_get_mode)GetProcAddress(h_speex_dll, "speex_lib_get_mode");
+               if (!speex_dll.speex_lib_get_mode) { free_speex_dll(); return -1; }
+               speex_dll.speex_init_header = (type_speex_init_header)GetProcAddress(h_speex_dll, "speex_init_header");
+               if (!speex_dll.speex_init_header) { free_speex_dll(); return -1; }
+               speex_dll.speex_header_to_packet = (type_speex_header_to_packet)GetProcAddress(h_speex_dll, "speex_header_to_packet");
+               if (!speex_dll.speex_header_to_packet) { free_speex_dll(); return -1; }
+               speex_dll.speex_encode_stereo = (type_speex_encode_stereo)GetProcAddress(h_speex_dll, "speex_encode_stereo");
+               if (!speex_dll.speex_encode_stereo) { free_speex_dll(); return -1; }
+               speex_dll.speex_bits_insert_terminator = (type_speex_bits_insert_terminator)GetProcAddress(h_speex_dll, "speex_bits_insert_terminator");
+               if (!speex_dll.speex_bits_insert_terminator) { free_speex_dll(); return -1; }
+       }
+
+       return 0;
+}
+
+void free_speex_dll(void)
+{
+       memset(&speex_dll, 0, sizeof(speex_dll));
+
+       if (h_speex_dll) {
+               FreeLibrary(h_speex_dll);
+               h_speex_dll = NULL;
+       }
+}
+
+void speex_bits_init(SpeexBits *bits)
+{
+       if (speex_dll.speex_bits_init) {
+               (*speex_dll.speex_bits_init)(bits);
+       }
+}
+
+void speex_bits_reset(SpeexBits *bits)
+{
+       if (speex_dll.speex_bits_reset) {
+               (*speex_dll.speex_bits_reset)(bits);
+       }
+}
+
+int speex_bits_write(SpeexBits *bits, char *bytes, int max_len)
+{
+       if (speex_dll.speex_bits_write) {
+               return (*speex_dll.speex_bits_write)(bits, bytes, max_len);
+       } else {
+               return 0;
+       }
+}
+
+void speex_bits_pack(SpeexBits *bits, int data, int nbBits)
+{
+       if (speex_dll.speex_bits_pack) {
+               (*speex_dll.speex_bits_pack)(bits, data, nbBits);
+       }
+}
+
+void speex_bits_destroy(SpeexBits *bits)
+{
+       if (speex_dll.speex_bits_destroy) {
+               (*speex_dll.speex_bits_destroy)(bits);
+       }
+}
+
+void *speex_encoder_init(const SpeexMode *mode)
+{
+       if (speex_dll.speex_encoder_init) {
+               return (*speex_dll.speex_encoder_init)(mode);
+       } else {
+               return NULL;
+       }
+}
+
+void speex_encoder_destroy(void *state)
+{
+       if (speex_dll.speex_encoder_destroy) {
+               (*speex_dll.speex_encoder_destroy)(state);
+       }
+}
+
+int speex_encode(void *state, float *in, SpeexBits *bits)
+{
+       if (speex_dll.speex_encode) {
+               return (*speex_dll.speex_encode)(state, in, bits);
+       } else {
+               return 0;
+       }
+}
+
+int speex_encoder_ctl(void *state, int request, void *ptr)
+{
+       if (speex_dll.speex_encoder_ctl) {
+               return (*speex_dll.speex_encoder_ctl)(state, request, ptr);
+       } else {
+               return -1;
+       }
+}
+
+const SpeexMode *speex_lib_get_mode(int mode)
+{
+       if (speex_dll.speex_lib_get_mode) {
+               return (*speex_dll.speex_lib_get_mode)(mode);
+       } else {
+               return NULL;
+       }
+}
+
+void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m)
+{
+       if (speex_dll.speex_init_header) {
+               (*speex_dll.speex_init_header)(header, rate, nb_channels, m);
+       }
+}
+
+char *speex_header_to_packet(SpeexHeader *header, int *size)
+{
+       if (speex_dll.speex_header_to_packet) {
+               return (*speex_dll.speex_header_to_packet)(header, size);
+       } else {
+               return NULL;
+       }
+}
+
+void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits)
+{
+       if (speex_dll.speex_encode_stereo) {
+               (*speex_dll.speex_encode_stereo)(data, frame_size, bits);
+       }
+}
+
+void speex_bits_insert_terminator(SpeexBits *bits)
+{
+       if (speex_dll.speex_bits_insert_terminator) {
+               (*speex_dll.speex_bits_insert_terminator)(bits);
+       }
+}
+
+#endif
index 538fdf1..0410a9a 100644 (file)
@@ -25,8 +25,7 @@
 #ifdef HAVE_CONFIG_H\r
 #include "config.h"\r
 #endif /* HAVE_CONFIG_H */\r
-#include "interface.h"\r
-#include "common.h"\r
+\r
 \r
 \r
 #if defined(AU_VORBIS_DLL) || defined(AU_OPUS_DLL)\r
index 40575c6..eecf95c 100644 (file)
@@ -5,7 +5,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 
 #ifdef AU_OPUS_DLL
 
index 1d3c872..9ca901c 100644 (file)
@@ -25,7 +25,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include "common.h"
 
 
index 1c7734c..44e2c6c 100644 (file)
@@ -25,7 +25,7 @@
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
-#include "interface.h"
+
 #include "common.h"
 
 #ifndef VORBIS_DLL_INCLUDE_VORBISENC
index eced547..1887954 100644 (file)
@@ -64,9 +64,6 @@ Written by Starg.
 #ifdef AU_WASAPI
 
 
-#ifdef __W32__
-#include "interface.h"
-#endif
 #include <stdio.h>
 #include <stdlib.h>
 #ifndef NO_STRING_H
@@ -126,15 +123,13 @@ PlayMode dpm = {
 #include <windows.h>
 #include <winbase.h>
 #include <objbase.h>
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
 //#include <Avrt.h>
 #include <audioclient.h>
 #include <audiopolicy.h>
-//#define INITGUID
+#include <initguid.h>
 #include <mmdeviceapi.h>
 #include <functiondiscoverykeys_devpkey.h>
-//#undef INITGUID
-#endif
+#undef INITGUID
 
 const CLSID tim_CLSID_MMDeviceEnumerator = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}};
 const IID tim_IID_IMMDeviceEnumerator    = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}};
@@ -1004,8 +999,36 @@ int open_output(void)
                        goto error;
                hr = IAudioClient_Initialize(pAudioClient, ShareMode, StreamFlags, BufferDuration, Periodicity, (WAVEFORMATEX *)&wfe, NULL);
        }
-       if(FAILED(hr))
+       if(FAILED(hr)){
+               switch(hr){
+#define HANDLE_HRESULT(hresult) \
+       case hresult: \
+               ctl->cmsg(CMSG_ERROR, VERB_VERBOSE, "WASAPI: IAudioClient::Initialize() failed with HRESULT = %s", #hresult); \
+               break;
+
+                       HANDLE_HRESULT(AUDCLNT_E_ALREADY_INITIALIZED);
+                       HANDLE_HRESULT(AUDCLNT_E_WRONG_ENDPOINT_TYPE);
+                       HANDLE_HRESULT(AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED);
+                       HANDLE_HRESULT(AUDCLNT_E_BUFFER_SIZE_ERROR);
+                       HANDLE_HRESULT(AUDCLNT_E_CPUUSAGE_EXCEEDED);
+                       HANDLE_HRESULT(AUDCLNT_E_DEVICE_INVALIDATED);
+                       HANDLE_HRESULT(AUDCLNT_E_DEVICE_IN_USE);
+                       HANDLE_HRESULT(AUDCLNT_E_ENDPOINT_CREATE_FAILED);
+                       HANDLE_HRESULT(AUDCLNT_E_INVALID_DEVICE_PERIOD);
+                       HANDLE_HRESULT(AUDCLNT_E_UNSUPPORTED_FORMAT);
+                       HANDLE_HRESULT(AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED);
+                       HANDLE_HRESULT(AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL);
+                       HANDLE_HRESULT(AUDCLNT_E_SERVICE_NOT_RUNNING);
+                       HANDLE_HRESULT(E_OUTOFMEMORY);
+
+#undef HANDLE_HRESULT
+
+               default:
+                       ctl->cmsg(CMSG_ERROR, VERB_VERBOSE, "WASAPI: IAudioClient::Initialize() failed with HRESULT = 0x%X", hr);
+                       break;
+               }
                goto error;
+       }
        if(FAILED(IAudioClient_GetBufferSize(pAudioClient, &BufferFrames)))
                goto error;
        if(!IsPolling)
index 8b12611..8bd262f 100644 (file)
@@ -3,7 +3,6 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include "interface.h"
 #include "timidity.h"
 #include "common.h"
 
index 1b935da..fa45ad5 100644 (file)
@@ -253,19 +253,14 @@ static void output_buffer(uint8 *buff, size_t bytes)
 #define CINTERFACE
 #define COBJMACROS
 #include <windows.h>
-#ifndef __GNUC__ 
 #include <winioctl.h>
-#endif
 #include <winbase.h>
 #include <initguid.h>
 #include <objbase.h>
-#if defined(_MSC_VER) && (_MSC_VER >= 1200)
-#undef __cplusplus
 #include <SetupAPI.h>
 #include <mmreg.h>
 #include <ks.h>
 #include <ksmedia.h>
-#endif
 
 #define WAVE_FORMAT_UNKNOWN      0x0000
 #define WAVE_FORMAT_PCM          0x0001
@@ -305,47 +300,37 @@ DEFINE_GUIDSTRUCT("A855A48C-2F78-4729-9051-1968746B9EEF", KSPROPSETID_RtAudio);
 #define KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT 7
 #define KSPROPERTY_RTAUDIO_QUERY_NOTIFICATION_SUPPORT 8
 
-#ifndef KSRTAUDIO_BUFFER_PROPERTY
+#ifndef _MSC_VER
 typedef struct {
     KSPROPERTY  Property;
     PVOID       BaseAddress;
     ULONG       RequestedBufferSize;
 } KSRTAUDIO_BUFFER_PROPERTY, *PKSRTAUDIO_BUFFER_PROPERTY;
-#endif
 
-#ifndef KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION
 typedef struct {
     KSPROPERTY  Property;
     PVOID       BaseAddress;
     ULONG       RequestedBufferSize;
     ULONG       NotificationCount;
 } KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION, *PKSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION;
-#endif
 
-#ifndef KSRTAUDIO_BUFFER
 typedef struct {
     PVOID   BufferAddress;
     ULONG   ActualBufferSize;
     BOOL    CallMemoryBarrier;
 } KSRTAUDIO_BUFFER, *PKSRTAUDIO_BUFFER;
-#endif
 
-#ifndef KSRTAUDIO_HWLATENCY
 typedef struct {
     ULONG   FifoSize;
     ULONG   ChipsetDelay;
     ULONG   CodecDelay;
 } KSRTAUDIO_HWLATENCY, *PKSRTAUDIO_HWLATENCY;
-#endif
 
-#ifndef KSRTAUDIO_HWREGISTER_PROPERTY
 typedef struct {
     KSPROPERTY  Property;
     PVOID       BaseAddress;
 } KSRTAUDIO_HWREGISTER_PROPERTY, *PKSRTAUDIO_HWREGISTER_PROPERTY;
-#endif
 
-#ifndef KSRTAUDIO_HWREGISTER
 typedef struct {
     PVOID       Register;
     ULONG       Width;
@@ -353,9 +338,7 @@ typedef struct {
     ULONGLONG   Denominator;
     ULONG       Accuracy;
 } KSRTAUDIO_HWREGISTER, *PKSRTAUDIO_HWREGISTER;
-#endif
 
-#ifndef KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY
 typedef struct {
     KSPROPERTY  Property;
     HANDLE      NotificationEvent;
index be1852a..52ec3d9 100644 (file)
@@ -3,7 +3,6 @@
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 
-#include "interface.h"
 #include "timidity.h"
 #include "common.h"
 
index 0e0d81a..e111f07 100644 (file)
@@ -35,7 +35,7 @@
 #include "playmidi.h"
 #include "readmidi.h"
 #include "arc.h"
-#include "interface.h"
+
 
 /*
  * Remap WRD @COLOR(16)-@COLOR(23) to RGB plain number.
diff --git a/timidity_vs2008.sln b/timidity_vs2008.sln
deleted file mode 100644 (file)
index c4db267..0000000
+++ /dev/null
@@ -1,195 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 10.00
-# Visual C++ Express 2008
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cfgforsf", "cfgforsf\cfgforsf.vcproj", "{936F8415-4094-44C5-8640-8D710ECCABB6}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interface", "interface\interface.vcproj", "{248B20A6-9609-4A5B-AFAE-09C7572FCE54}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libarc", "libarc\libarc.vcproj", "{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libunimod", "libunimod\libunimod.vcproj", "{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nouse", "nouse\nouse.vcproj", "{99E98188-BE49-4367-9577-4681F1D50E9C}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timidity", "timidity\timidity.vcproj", "{45579E0F-6A19-4E8C-B638-945E0FB44D36}"
-       ProjectSection(ProjectDependencies) = postProject
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-               {4F65093E-E5C5-46C1-819D-0987086BF312} = {4F65093E-E5C5-46C1-819D-0987086BF312}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timw32g", "timw32g\timw32g.vcproj", "{76D0CE5A-A349-4022-8727-195719E4B93E}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36} = {45579E0F-6A19-4E8C-B638-945E0FB44D36}
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43} = {2D650C28-16E9-41A2-860B-CC3DEEC69C43}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54} = {248B20A6-9609-4A5B-AFAE-09C7572FCE54}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsyng", "twsyng\twsyng.vcproj", "{49D11476-D08C-43D6-8C7D-3820607E140F}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43} = {2D650C28-16E9-41A2-860B-CC3DEEC69C43}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54} = {248B20A6-9609-4A5B-AFAE-09C7572FCE54}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "utils", "utils\utils.vcproj", "{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "calcnewton", "calcnewton\calcnewton.vcproj", "{4F65093E-E5C5-46C1-819D-0987086BF312}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsynsrv", "twsynsrv\twsynsrv.vcproj", "{58F8555C-30C5-48AC-9C1C-680BDA52218D}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54} = {248B20A6-9609-4A5B-AFAE-09C7572FCE54}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspeex", "speex\speex.vcproj", "{2D650C28-16E9-41A2-860B-CC3DEEC69C43}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtim_dll", "kbtim\kbtim_dll.vcproj", "{9836482C-653B-4F2D-A210-CB021336DDAE}"
-       ProjectSection(ProjectDependencies) = postProject
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtim_kpi", "kbtim\kbtim_kpi.vcproj", "{407693E1-3071-436C-8F85-B3FAB646F67E}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "windrv", "windrv\windrv.vcproj", "{BCD294C0-DA3C-48A7-BAF4-8B96923E2693}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tim_cui", "tim_cui\tim_cui.vcproj", "{2B113C99-C484-4724-8918-169A495ADF9B}"
-       ProjectSection(ProjectDependencies) = postProject
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E} = {7D19161F-9206-4637-AFE6-C82951FFDD8E}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pdcurses", "pdcurses\pdcurses.vcproj", "{CC07EA59-8D54-4C51-9C49-728EFFED7832}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "portmidi", "portmidi\portmidi.vcproj", "{91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtimsetup", "kbtimsetup\kbtimsetup.vcproj", "{8A5B4912-F18C-481B-866D-845DC66DDAF5}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timdrvsetup", "timdrvsetup\timdrvsetup.vcproj", "{DB5B22F9-4721-460B-9770-2855CA33E232}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {B05F8AA0-6140-4335-AD39-E276D17002CB} = {B05F8AA0-6140-4335-AD39-E276D17002CB}
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80} = {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsyng_bridge", "twsyn_bridge\twsyn_bridge.vcproj", "{4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmpg123", "libmpg123\libmpg123.vcproj", "{7D19161F-9206-4637-AFE6-C82951FFDD8E}"
-EndProject
-Global
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution
-               Debug|Win32 = Debug|Win32
-               Release|Win32 = Release|Win32
-       EndGlobalSection
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Debug|Win32.ActiveCfg = Debug|Win32
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Release|Win32.ActiveCfg = Release|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|Win32.ActiveCfg = Debug|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|Win32.Build.0 = Debug|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|Win32.ActiveCfg = Release|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|Win32.Build.0 = Release|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|Win32.ActiveCfg = Debug|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|Win32.Build.0 = Debug|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|Win32.ActiveCfg = Release|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|Win32.Build.0 = Release|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|Win32.ActiveCfg = Debug|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|Win32.Build.0 = Debug|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|Win32.ActiveCfg = Release|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|Win32.Build.0 = Release|Win32
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Debug|Win32.ActiveCfg = Debug|Win32
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Release|Win32.ActiveCfg = Release|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|Win32.ActiveCfg = Debug|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|Win32.Build.0 = Debug|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|Win32.ActiveCfg = Release|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|Win32.Build.0 = Release|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|Win32.ActiveCfg = Debug|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|Win32.Build.0 = Debug|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|Win32.ActiveCfg = Release|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|Win32.Build.0 = Release|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|Win32.ActiveCfg = Debug|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|Win32.Build.0 = Debug|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|Win32.ActiveCfg = Release|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|Win32.Build.0 = Release|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|Win32.ActiveCfg = Debug|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|Win32.Build.0 = Debug|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|Win32.ActiveCfg = Release|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|Win32.Build.0 = Release|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|Win32.ActiveCfg = Debug|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|Win32.Build.0 = Debug|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|Win32.ActiveCfg = Release|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|Win32.Build.0 = Release|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|Win32.Build.0 = Debug|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|Win32.ActiveCfg = Release|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|Win32.Build.0 = Release|Win32
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43}.Debug|Win32.ActiveCfg = Debug|Win32
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43}.Debug|Win32.Build.0 = Debug|Win32
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43}.Release|Win32.ActiveCfg = Release|Win32
-               {2D650C28-16E9-41A2-860B-CC3DEEC69C43}.Release|Win32.Build.0 = Release|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|Win32.ActiveCfg = Debug|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|Win32.Build.0 = Debug|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|Win32.ActiveCfg = Release|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|Win32.Build.0 = Release|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|Win32.ActiveCfg = Debug|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|Win32.Build.0 = Debug|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|Win32.ActiveCfg = Release|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|Win32.Build.0 = Release|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|Win32.ActiveCfg = Debug|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|Win32.Build.0 = Debug|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|Win32.ActiveCfg = Release|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|Win32.Build.0 = Release|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|Win32.Build.0 = Debug|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|Win32.ActiveCfg = Release|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|Win32.Build.0 = Release|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|Win32.ActiveCfg = Debug|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|Win32.Build.0 = Debug|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|Win32.ActiveCfg = Release|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|Win32.Build.0 = Release|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|Win32.ActiveCfg = Debug|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|Win32.Build.0 = Debug|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|Win32.ActiveCfg = Release|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|Win32.Build.0 = Release|Win32
-               {8A5B4912-F18C-481B-866D-845DC66DDAF5}.Debug|Win32.ActiveCfg = Debug|Win32
-               {8A5B4912-F18C-481B-866D-845DC66DDAF5}.Debug|Win32.Build.0 = Debug|Win32
-               {8A5B4912-F18C-481B-866D-845DC66DDAF5}.Release|Win32.ActiveCfg = Release|Win32
-               {8A5B4912-F18C-481B-866D-845DC66DDAF5}.Release|Win32.Build.0 = Release|Win32
-               {DB5B22F9-4721-460B-9770-2855CA33E232}.Debug|Win32.ActiveCfg = Debug|Win32
-               {DB5B22F9-4721-460B-9770-2855CA33E232}.Debug|Win32.Build.0 = Debug|Win32
-               {DB5B22F9-4721-460B-9770-2855CA33E232}.Release|Win32.ActiveCfg = Release|Win32
-               {DB5B22F9-4721-460B-9770-2855CA33E232}.Release|Win32.Build.0 = Release|Win32
-               {4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}.Debug|Win32.ActiveCfg = Debug|Win32
-               {4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}.Debug|Win32.Build.0 = Debug|Win32
-               {4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}.Release|Win32.ActiveCfg = Release|Win32
-               {4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}.Release|Win32.Build.0 = Release|Win32
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E}.Debug|Win32.ActiveCfg = Debug|Win32
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E}.Debug|Win32.Build.0 = Debug|Win32
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E}.Release|Win32.ActiveCfg = Release|Win32
-               {7D19161F-9206-4637-AFE6-C82951FFDD8E}.Release|Win32.Build.0 = Release|Win32
-       EndGlobalSection
-       GlobalSection(SolutionProperties) = preSolution
-               HideSolutionNode = FALSE
-       EndGlobalSection
-EndGlobal
diff --git a/timidity_vs2010.sln b/timidity_vs2010.sln
deleted file mode 100644 (file)
index 58e6de3..0000000
+++ /dev/null
@@ -1,268 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 11.00
-# Visual C++ Express 2010
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cfgforsf", "cfgforsf\cfgforsf.vcxproj", "{936F8415-4094-44C5-8640-8D710ECCABB6}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interface", "interface\interface.vcxproj", "{248B20A6-9609-4A5B-AFAE-09C7572FCE54}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libunimod", "libunimod\libunimod.vcxproj", "{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nouse", "nouse\nouse.vcxproj", "{99E98188-BE49-4367-9577-4681F1D50E9C}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timidity", "timidity\timidity.vcxproj", "{45579E0F-6A19-4E8C-B638-945E0FB44D36}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timw32g", "timw32g\timw32g.vcxproj", "{76D0CE5A-A349-4022-8727-195719E4B93E}"
-       ProjectSection(ProjectDependencies) = postProject
-               {11CDD90A-20E1-45AF-879E-F355742B38B7} = {11CDD90A-20E1-45AF-879E-F355742B38B7}
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsyng", "twsyng\twsyng.vcxproj", "{49D11476-D08C-43D6-8C7D-3820607E140F}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "utils", "utils\utils.vcxproj", "{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "calcnewton", "calcnewton\calcnewton.vcxproj", "{4F65093E-E5C5-46C1-819D-0987086BF312}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsynsrv", "twsynsrv\twsynsrv.vcxproj", "{58F8555C-30C5-48AC-9C1C-680BDA52218D}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sf_view_gui", "sfviewer\sfviewer.vcxproj", "{B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtim_dll", "kbtim\kbtim_dll.vcxproj", "{9836482C-653B-4F2D-A210-CB021336DDAE}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtim_installer", "kbtim\kbtim_installer.vcxproj", "{40F9E631-03E7-4421-8335-1941FFA446E0}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtim_kpi", "kbtim\kbtim_kpi.vcxproj", "{407693E1-3071-436C-8F85-B3FAB646F67E}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kbtimsetup", "kbtimsetup\kbtimsetup.vcxproj", "{44A9C0E9-C1A4-469E-A947-BD50E4086BA7}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pdcurses", "pdcurses\pdcurses.vcxproj", "{CC07EA59-8D54-4C51-9C49-728EFFED7832}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "portmidi", "portmidi\portmidi.vcxproj", "{91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libarc", "libarc\libarc.vcxproj", "{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "windrv", "windrv\windrv.vcxproj", "{BCD294C0-DA3C-48A7-BAF4-8B96923E2693}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspeex", "speex\libspeex.vcxproj", "{E972C52F-9E85-4D65-B19C-031E511E9DB4}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tim_cui", "tim_cui\tim_cui.vcxproj", "{2B113C99-C484-4724-8918-169A495ADF9B}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D} = {D3CD5655-ECDB-41A2-A310-7B931E9E495D}
-       EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "timdrvsetup", "timdrvsetup\timdrvsetup.vcxproj", "{1A91001F-E3EF-4FC1-925B-C00013BB6C98}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twsyn_bridge", "twsyn_bridge\twsyn_bridge.vcxproj", "{D6D9295A-4A29-4753-88E9-A9D8B589A3D0}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmpg123", "libmpg123\libmpg123.vcxproj", "{D3CD5655-ECDB-41A2-A310-7B931E9E495D}"
-EndProject
-Global
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution
-               Debug|Win32 = Debug|Win32
-               Debug|x64 = Debug|x64
-               Release|Win32 = Release|Win32
-               Release|x64 = Release|x64
-       EndGlobalSection
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Debug|Win32.ActiveCfg = Debug|Win32
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Debug|x64.ActiveCfg = Debug|x64
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Release|Win32.ActiveCfg = Release|Win32
-               {936F8415-4094-44C5-8640-8D710ECCABB6}.Release|x64.ActiveCfg = Release|x64
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|Win32.ActiveCfg = Debug|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|Win32.Build.0 = Debug|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|x64.ActiveCfg = Debug|x64
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Debug|x64.Build.0 = Debug|x64
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|Win32.ActiveCfg = Release|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|Win32.Build.0 = Release|Win32
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|x64.ActiveCfg = Release|x64
-               {248B20A6-9609-4A5B-AFAE-09C7572FCE54}.Release|x64.Build.0 = Release|x64
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|Win32.ActiveCfg = Debug|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|Win32.Build.0 = Debug|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|x64.ActiveCfg = Debug|x64
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Debug|x64.Build.0 = Debug|x64
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|Win32.ActiveCfg = Release|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|Win32.Build.0 = Release|Win32
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|x64.ActiveCfg = Release|x64
-               {8DC8ADE3-145A-4C63-80DD-0C93B6587B80}.Release|x64.Build.0 = Release|x64
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Debug|Win32.ActiveCfg = Debug|Win32
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Debug|x64.ActiveCfg = Debug|x64
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Release|Win32.ActiveCfg = Release|Win32
-               {99E98188-BE49-4367-9577-4681F1D50E9C}.Release|x64.ActiveCfg = Release|x64
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|Win32.ActiveCfg = Debug|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|Win32.Build.0 = Debug|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|x64.ActiveCfg = Debug|x64
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Debug|x64.Build.0 = Debug|x64
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|Win32.ActiveCfg = Release|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|Win32.Build.0 = Release|Win32
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|x64.ActiveCfg = Release|x64
-               {45579E0F-6A19-4E8C-B638-945E0FB44D36}.Release|x64.Build.0 = Release|x64
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|Win32.ActiveCfg = Debug|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|Win32.Build.0 = Debug|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|x64.ActiveCfg = Debug|x64
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Debug|x64.Build.0 = Debug|x64
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|Win32.ActiveCfg = Release|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|Win32.Build.0 = Release|Win32
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|x64.ActiveCfg = Release|x64
-               {76D0CE5A-A349-4022-8727-195719E4B93E}.Release|x64.Build.0 = Release|x64
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|Win32.ActiveCfg = Debug|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|Win32.Build.0 = Debug|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|x64.ActiveCfg = Debug|x64
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Debug|x64.Build.0 = Debug|x64
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|Win32.ActiveCfg = Release|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|Win32.Build.0 = Release|Win32
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|x64.ActiveCfg = Release|x64
-               {49D11476-D08C-43D6-8C7D-3820607E140F}.Release|x64.Build.0 = Release|x64
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|Win32.ActiveCfg = Debug|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|Win32.Build.0 = Debug|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|x64.ActiveCfg = Debug|x64
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Debug|x64.Build.0 = Debug|x64
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|Win32.ActiveCfg = Release|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|Win32.Build.0 = Release|Win32
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|x64.ActiveCfg = Release|x64
-               {B05F8AA0-6140-4335-AD39-E276D17002CB}.Release|x64.Build.0 = Release|x64
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|Win32.ActiveCfg = Debug|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|Win32.Build.0 = Debug|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|x64.ActiveCfg = Debug|x64
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Debug|x64.Build.0 = Debug|x64
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|Win32.ActiveCfg = Release|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|Win32.Build.0 = Release|Win32
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|x64.ActiveCfg = Release|x64
-               {4F65093E-E5C5-46C1-819D-0987086BF312}.Release|x64.Build.0 = Release|x64
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|Win32.Build.0 = Debug|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|x64.ActiveCfg = Debug|x64
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Debug|x64.Build.0 = Debug|x64
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|Win32.ActiveCfg = Release|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|Win32.Build.0 = Release|Win32
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|x64.ActiveCfg = Release|x64
-               {58F8555C-30C5-48AC-9C1C-680BDA52218D}.Release|x64.Build.0 = Release|x64
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Debug|Win32.Build.0 = Debug|Win32
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Debug|x64.ActiveCfg = Debug|x64
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Debug|x64.Build.0 = Debug|x64
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Release|Win32.ActiveCfg = Release|Win32
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Release|Win32.Build.0 = Release|Win32
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Release|x64.ActiveCfg = Release|x64
-               {B5A5C0BF-E29B-4A63-8E41-D44A7F989B5D}.Release|x64.Build.0 = Release|x64
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|Win32.ActiveCfg = Debug|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|Win32.Build.0 = Debug|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|x64.ActiveCfg = Debug|x64
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Debug|x64.Build.0 = Debug|x64
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|Win32.ActiveCfg = Release|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|Win32.Build.0 = Release|Win32
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|x64.ActiveCfg = Release|x64
-               {9836482C-653B-4F2D-A210-CB021336DDAE}.Release|x64.Build.0 = Release|x64
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Debug|Win32.ActiveCfg = Debug|Win32
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Debug|Win32.Build.0 = Debug|Win32
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Debug|x64.ActiveCfg = Debug|x64
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Debug|x64.Build.0 = Debug|x64
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Release|Win32.ActiveCfg = Release|Win32
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Release|Win32.Build.0 = Release|Win32
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Release|x64.ActiveCfg = Release|x64
-               {40F9E631-03E7-4421-8335-1941FFA446E0}.Release|x64.Build.0 = Release|x64
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|Win32.ActiveCfg = Debug|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|Win32.Build.0 = Debug|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|x64.ActiveCfg = Debug|x64
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Debug|x64.Build.0 = Debug|x64
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|Win32.ActiveCfg = Release|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|Win32.Build.0 = Release|Win32
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|x64.ActiveCfg = Release|x64
-               {407693E1-3071-436C-8F85-B3FAB646F67E}.Release|x64.Build.0 = Release|x64
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Debug|Win32.ActiveCfg = Debug|Win32
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Debug|Win32.Build.0 = Debug|Win32
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Debug|x64.ActiveCfg = Debug|x64
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Debug|x64.Build.0 = Debug|x64
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Release|Win32.ActiveCfg = Release|Win32
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Release|Win32.Build.0 = Release|Win32
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Release|x64.ActiveCfg = Release|x64
-               {44A9C0E9-C1A4-469E-A947-BD50E4086BA7}.Release|x64.Build.0 = Release|x64
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|Win32.ActiveCfg = Debug|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|Win32.Build.0 = Debug|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|x64.ActiveCfg = Debug|x64
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Debug|x64.Build.0 = Debug|x64
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|Win32.ActiveCfg = Release|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|Win32.Build.0 = Release|Win32
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|x64.ActiveCfg = Release|x64
-               {CC07EA59-8D54-4C51-9C49-728EFFED7832}.Release|x64.Build.0 = Release|x64
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|Win32.ActiveCfg = Debug|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|Win32.Build.0 = Debug|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|x64.ActiveCfg = Debug|x64
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Debug|x64.Build.0 = Debug|x64
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|Win32.ActiveCfg = Release|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|Win32.Build.0 = Release|Win32
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|x64.ActiveCfg = Release|x64
-               {91F771D3-B89C-408D-B42F-5EAFBBCE5CC5}.Release|x64.Build.0 = Release|x64
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|Win32.ActiveCfg = Debug|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|Win32.Build.0 = Debug|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|x64.ActiveCfg = Debug|x64
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Debug|x64.Build.0 = Debug|x64
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|Win32.ActiveCfg = Release|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|Win32.Build.0 = Release|Win32
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|x64.ActiveCfg = Release|x64
-               {11CDD90A-20E1-45AF-879E-F355742B38B7}.Release|x64.Build.0 = Release|x64
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|Win32.ActiveCfg = Debug|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|Win32.Build.0 = Debug|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|x64.ActiveCfg = Debug|x64
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Debug|x64.Build.0 = Debug|x64
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|Win32.ActiveCfg = Release|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|Win32.Build.0 = Release|Win32
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|x64.ActiveCfg = Release|x64
-               {BCD294C0-DA3C-48A7-BAF4-8B96923E2693}.Release|x64.Build.0 = Release|x64
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Debug|Win32.ActiveCfg = Debug|Win32
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Debug|Win32.Build.0 = Debug|Win32
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Debug|x64.ActiveCfg = Debug|x64
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Debug|x64.Build.0 = Debug|x64
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Release|Win32.ActiveCfg = Release|Win32
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Release|Win32.Build.0 = Release|Win32
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Release|x64.ActiveCfg = Release|x64
-               {E972C52F-9E85-4D65-B19C-031E511E9DB4}.Release|x64.Build.0 = Release|x64
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|Win32.Build.0 = Debug|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|x64.ActiveCfg = Debug|x64
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Debug|x64.Build.0 = Debug|x64
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|Win32.ActiveCfg = Release|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|Win32.Build.0 = Release|Win32
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|x64.ActiveCfg = Release|x64
-               {2B113C99-C484-4724-8918-169A495ADF9B}.Release|x64.Build.0 = Release|x64
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Debug|Win32.ActiveCfg = Debug|Win32
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Debug|Win32.Build.0 = Debug|Win32
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Debug|x64.ActiveCfg = Debug|x64
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Debug|x64.Build.0 = Debug|x64
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Release|Win32.ActiveCfg = Release|Win32
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Release|Win32.Build.0 = Release|Win32
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Release|x64.ActiveCfg = Release|x64
-               {1A91001F-E3EF-4FC1-925B-C00013BB6C98}.Release|x64.Build.0 = Release|x64
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Debug|Win32.ActiveCfg = Debug|Win32
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Debug|Win32.Build.0 = Debug|Win32
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Debug|x64.ActiveCfg = Debug|x64
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Debug|x64.Build.0 = Debug|x64
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Release|Win32.ActiveCfg = Release|Win32
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Release|Win32.Build.0 = Release|Win32
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Release|x64.ActiveCfg = Release|x64
-               {D6D9295A-4A29-4753-88E9-A9D8B589A3D0}.Release|x64.Build.0 = Release|x64
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Debug|Win32.Build.0 = Debug|Win32
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Debug|x64.ActiveCfg = Debug|x64
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Release|Win32.ActiveCfg = Release|Win32
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Release|Win32.Build.0 = Release|Win32
-               {D3CD5655-ECDB-41A2-A310-7B931E9E495D}.Release|x64.ActiveCfg = Release|x64
-       EndGlobalSection
-       GlobalSection(SolutionProperties) = preSolution
-               HideSolutionNode = FALSE
-       EndGlobalSection
-EndGlobal
diff --git a/timidity_vs6.dsw b/timidity_vs6.dsw
deleted file mode 100644 (file)
index fb7be56..0000000
+++ /dev/null
@@ -1,200 +0,0 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00
-# \8cx\8d\90\82±\82ÌÜ°¸½Íß°½ Ì§²Ù \82ð\95Ò\8fW\82Ü\82½\82Í\8dí\8f\9c\82µ\82È\82¢\82Å\82­\82¾\82³\82¢!
-
-###############################################################################
-
-Project: "cfgforsf"=".\cfgforsf\cfgforsf.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "interface"=".\interface\interface.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "kbtim_dll"=".\kbtim\kbtim_dll.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "kbtim_installer"=".\kbtim\kbtim_installer.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "kbtim_kpi"=".\kbtim\kbtim_kpi.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "libarc"=".\libarc\libarc.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "libunimod"=".\libunimod\libunimod.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "nouse"=".\nouse\nouse.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "timidity"=".\timidity\timidity.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "timw32g"=".\timw32g\timw32g.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-    Begin Project Dependency
-    Project_Dep_Name interface
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name libarc
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name libunimod
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name nouse
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name timidity
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name utils
-    End Project Dependency
-}}}
-
-###############################################################################
-
-Project: "timw32gd"=".\timw32gd\timw32gd.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Project: "twsyng"=".\twsyng\twsyng.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-    Begin Project Dependency
-    Project_Dep_Name interface
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name timidity
-    End Project Dependency
-    Begin Project Dependency
-    Project_Dep_Name utils
-    End Project Dependency
-}}}
-
-###############################################################################
-
-Project: "utils"=".\utils\utils.dsp" - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
diff --git a/timw32g/timw32g.dsp b/timw32g/timw32g.dsp
deleted file mode 100644 (file)
index 5b44acf..0000000
+++ /dev/null
@@ -1,269 +0,0 @@
-# Microsoft Developer Studio Project File - Name="timw32g" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Application" 0x0101
-
-CFG=timw32g - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "timw32g.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "timw32g.mak" CFG="timw32g - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "timw32g - Win32 Release" ("Win32 (x86) Application" \97p)
-!MESSAGE "timw32g - Win32 Debug" ("Win32 (x86) Application" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "timw32g - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /D "TW32G" /D "NDEBUG" /D "_WINDOWS" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /FD /c
-# SUBTRACT CPP /YX
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 comctl32.lib comdlg32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"../Release/timw32g.exe"
-
-!ELSEIF  "$(CFG)" == "timw32g - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /MT /W3 /Gm /GX /ZI /Od /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /D "TW32G" /D "_WINDOWS" /D "_DEBUG" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /FR /YX /FD /GZ /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 comctl32.lib comdlg32.lib libcmtd.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libcd.lib" /out:"../Debug/timw32g.exe" /pdbtype:sept
-# SUBTRACT LINK32 /nodefaultlib
-
-!ENDIF 
-
-# Begin Target
-
-# Name "timw32g - Win32 Release"
-# Name "timw32g - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\interface\w32g_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_dib.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ini.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_mag.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_ogg_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_playlist.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_pref.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subwin.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subwin2.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_subwin3.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ut2.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_vorbis_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_vorbisenc_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\wrdt_w32g.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\config.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g.h"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_dib.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_mag.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_pref.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_rec.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_res.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subwin.h"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_tracer.h
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ut2.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_wrd.h"
-# End Source File
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# Begin Source File
-
-SOURCE="..\interface\w32g_btn.bmp"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_icon.ico"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_res.rc"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_sleep.bmp"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subbtn.bmp"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_tracer.bmp
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_tracer_mask.bmp
-# End Source File
-# End Group
-# Begin Source File
-
-SOURCE=..\Release\utils.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\libarc.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\libunimod.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\timidity.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\interface.lib
-# End Source File
-# End Target
-# End Project
diff --git a/timw32g/timw32g.vcproj b/timw32g/timw32g.vcproj
deleted file mode 100644 (file)
index 04c4909..0000000
+++ /dev/null
@@ -1,508 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="timw32g"
-       ProjectGUID="{76D0CE5A-A349-4022-8727-195719E4B93E}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Debug/timw32g.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;%(AdditionalIncludeDirectories)"
-                               PreprocessorDefinitions="W32GUI_DEBUG;TW32G;_WINDOWS;_DEBUG;WIN32;HAVE_CONFIG_H;_MT;"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/timw32g.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib comctl32.lib libcmtd.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib"
-                               OutputFile="../Debug/timw32g.exe"
-                               LinkIncremental="2"
-                               SuppressStartupBanner="true"
-                               IgnoreDefaultLibraryNames="msvcrtd.lib;libcd.lib;"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile=".\Debug/timw32g.pdb"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Release/timw32g.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;%(AdditionalIncludeDirectories)"
-                               PreprocessorDefinitions="TW32G;NDEBUG;_WINDOWS;WIN32;HAVE_CONFIG_H;_MT;"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/timw32g.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="1"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)"
-                               ResourceOutputFileName="$(IntDir)/$(InputName).res"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib comctl32.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib"
-                               OutputFile="..\Release\timw32g.exe"
-                               LinkIncremental="1"
-                               SuppressStartupBanner="true"
-                               AdditionalLibraryDirectories="../dll;"
-                               IgnoreDefaultLibraryNames="msvcrt.lib;libc.lib;"
-                               ProgramDatabaseFile=".\Release/timw32g.pdb"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="2"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-               <ProjectReference
-                       ReferencedProjectIdentifier="{248B20A6-9609-4A5B-AFAE-09C7572FCE54}"
-                       RelativePathToProject=".\interface\interface.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-                       RelativePathToProject=".\libarc\libarc.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{2D650C28-16E9-41A2-860B-CC3DEEC69C43}"
-                       RelativePathToProject=".\speex\speex.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-                       RelativePathToProject=".\libunimod\libunimod.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{45579E0F-6A19-4E8C-B638-945E0FB44D36}"
-                       RelativePathToProject=".\timidity\timidity.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-                       RelativePathToProject=".\utils\utils.vcproj"
-               />
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libmpg123_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_portaudio_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_dib.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_i.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_int_synth_editor.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_mag.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_ogg_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_opus_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_playlist.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_soundspec.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin3.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ut2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbis_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisenc_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisfile_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\wrdt_w32g.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\configs\msc-interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\soundspec.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll_g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll_i.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll_g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll_i.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_dib.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_int_synth_editor.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_mag.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_rec.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_res.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_tracer.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ut2.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_wrd.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Resource Files"
-                       Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-                       <File
-                               RelativePath="..\interface\w32g_btn.bmp"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_icon.ico"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_res.rc"
-                               >
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface;$(NoInherit)"
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface;$(NoInherit)"
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_sleep.bmp"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subbtn.bmp"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_tracer.bmp"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_tracer_mask.bmp"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/timw32g/timw32g.vcxproj b/timw32g/timw32g.vcxproj
deleted file mode 100644 (file)
index c5d687f..0000000
+++ /dev/null
@@ -1,428 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{76D0CE5A-A349-4022-8727-195719E4B93E}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)\Include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)\Include;</IncludePath>
-    <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;$(DXSDK_DIR)\Include;</IncludePath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib;$(DXSDK_DIR)\ILib\x86;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)atlmfc\lib\amd64;$(VCInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;$(FrameworkSDKDir)\lib\x64;$(WindowsSdkDir)\lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib;$(DXSDK_DIR)\ILib\x86;</LibraryPath>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(VCInstallDir)atlmfc\lib\amd64;$(VCInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;$(FrameworkSDKDir)\lib\x64;$(WindowsSdkDir)\lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">timw32g_c220</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">timw32g_x64_c220</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(ProjectName)_x64</TargetName>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Debug/timw32g.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>W32GUI_DEBUG;TW32G;_WINDOWS;_DEBUG;WIN32;HAVE_CONFIG_H;_MT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>false</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timw32g.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <ErrorReporting>None</ErrorReporting>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>msvcrtd.lib;libcd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/timw32g.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-      <EnableUAC>true</EnableUAC>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Debug/timw32g.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;W32GUI_DEBUG;TW32G;_WINDOWS;_DEBUG;WIN32;HAVE_CONFIG_H;_MT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>false</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/timw32g.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <ErrorReporting>None</ErrorReporting>
-      <EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Precise</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;libcmtd.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>msvcrtd.lib;libcd.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/timw32g.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-      <EnableUAC>true</EnableUAC>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Release/timw32g.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>TW32G;NDEBUG;_WINDOWS;WIN32;HAVE_CONFIG_H;_MT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timw32g.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <OpenMPSupport>false</OpenMPSupport>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <AssemblerOutput>NoListing</AssemblerOutput>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>msvcrt.lib;libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <ProgramDatabaseFile>.\Release/timw32g.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <EnableUAC>true</EnableUAC>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Release/timw32g.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;TW32G;NDEBUG;_WINDOWS;WIN32;HAVE_CONFIG_H;_MT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/timw32g.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <OpenMPSupport>false</OpenMPSupport>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;comctl32.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <ProgramDatabaseFile>.\Release/timw32g_x64.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <EnableUAC>true</EnableUAC>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalLibraryDirectories>../dll;</AdditionalLibraryDirectories>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\interface\w32g_c.c" />
-    <ClCompile Include="..\interface\w32g_dib.c" />
-    <ClCompile Include="..\interface\w32g_i.c" />
-    <ClCompile Include="..\interface\w32g_ini.c" />
-    <ClCompile Include="..\interface\w32g_int_synth_editor.c" />
-    <ClCompile Include="..\interface\w32g_mag.c" />
-    <ClCompile Include="..\interface\w32g_playlist.c" />
-    <ClCompile Include="..\interface\w32g_pref.c" />
-    <ClCompile Include="..\interface\w32g_subwin.c" />
-    <ClCompile Include="..\interface\w32g_subwin2.c" />
-    <ClCompile Include="..\interface\w32g_subwin3.c" />
-    <ClCompile Include="..\interface\w32g_ut2.c" />
-    <ClCompile Include="..\interface\w32g_utl.c" />
-    <ClCompile Include="..\interface\w32g_soundspec.c" />
-    <ClCompile Include="..\interface\wrdt_w32g.c" />
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisfile_dll.c" />
-    <ClCompile Include="..\timidity\w32_libmpg123_dll.c" />
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c" />
-    <ClCompile Include="..\timidity\w32g_opus_dll.c" />
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\configs\msc-interface.h" />
-    <ClInclude Include="..\interface\soundspec.h" />
-    <ClInclude Include="..\interface\w32g.h" />
-    <ClInclude Include="..\interface\w32g_dib.h" />
-    <ClInclude Include="..\interface\w32g_int_synth_editor.h" />
-    <ClInclude Include="..\interface\w32g_mag.h" />
-    <ClInclude Include="..\interface\w32g_pref.h" />
-    <ClInclude Include="..\interface\w32g_rec.h" />
-    <ClInclude Include="..\interface\w32g_res.h" />
-    <ClInclude Include="..\interface\w32g_subwin.h" />
-    <ClInclude Include="..\interface\w32g_tracer.h" />
-    <ClInclude Include="..\interface\w32g_ut2.h" />
-    <ClInclude Include="..\interface\w32g_utl.h" />
-    <ClInclude Include="..\interface\w32g_wrd.h" />
-    <ClInclude Include="..\timidity\w32_libFLAC_dll.h" />
-    <ClInclude Include="..\timidity\w32_libFLAC_dll_g.h" />
-    <ClInclude Include="..\timidity\w32_libFLAC_dll_i.h" />
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll.h" />
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll_g.h" />
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll_i.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\interface\w32g_btn.bmp" />
-    <None Include="..\interface\w32g_icon.ico" />
-    <None Include="..\interface\w32g_sleep.bmp" />
-    <None Include="..\interface\w32g_subbtn.bmp" />
-    <None Include="..\interface\w32g_tracer.bmp" />
-    <None Include="..\interface\w32g_tracer_mask.bmp" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\interface\w32g_res.rc">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\interface\interface.vcxproj">
-      <Project>{248b20a6-9609-4a5b-afae-09c7572fce54}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\libarc\libarc.vcxproj">
-      <Project>{11cdd90a-20e1-45af-879e-f355742b38b7}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\libunimod\libunimod.vcxproj">
-      <Project>{8dc8ade3-145a-4c63-80dd-0c93b6587b80}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\speex\libspeex.vcxproj">
-      <Project>{e972c52f-9e85-4d65-b19c-031e511e9db4}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\timidity\timidity.vcxproj">
-      <Project>{45579e0f-6a19-4e8c-b638-945e0fb44d36}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\utils\utils.vcxproj">
-      <Project>{b05f8aa0-6140-4335-ad39-e276d17002cb}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/timw32g/timw32g.vcxproj.filters b/timw32g/timw32g.vcxproj.filters
deleted file mode 100644 (file)
index a2e299c..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{82b77fff-d962-4b20-bbd2-1003fed6756b}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{1beea308-2608-447b-b3f6-f6fcd7845ada}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{1c9cabff-885e-4d0a-8a80-9bcec7081d0b}</UniqueIdentifier>
-      <Extensions>ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_dib.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_i.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_mag.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_playlist.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_pref.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin2.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin3.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ut2.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_utl.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\wrdt_w32g.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_soundspec.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_opus_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\configs\msc-interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_dib.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_mag.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_rec.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_res.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_subwin.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_tracer.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_wrd.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_utl.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_ut2.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g_pref.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\w32g.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libFLAC_dll.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libFLAC_dll_g.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libFLAC_dll_i.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll_g.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\w32_libOggFLAC_dll_i.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\soundspec.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="..\interface\w32g_btn.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\interface\w32g_icon.ico">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\interface\w32g_sleep.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\interface\w32g_subbtn.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\interface\w32g_tracer.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-    <None Include="..\interface\w32g_tracer_mask.bmp">
-      <Filter>Resource Files</Filter>
-    </None>
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\interface\w32g_res.rc">
-      <Filter>Resource Files</Filter>
-    </ResourceCompile>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/timw32g/timw32g.vcxproj.user b/timw32g/timw32g.vcxproj.user
deleted file mode 100644 (file)
index 6d502df..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LocalDebuggerCommand>$(TargetPath)</LocalDebuggerCommand>
-    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/timw32gd/timw32gd.dsp b/timw32gd/timw32gd.dsp
deleted file mode 100644 (file)
index 5d4b6b1..0000000
+++ /dev/null
@@ -1,239 +0,0 @@
-# Microsoft Developer Studio Project File - Name="timw32gd" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Application" 0x0101
-
-CFG=timw32gd - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "timw32gd.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "timw32gd.mak" CFG="timw32gd - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "timw32gd - Win32 Release" ("Win32 (x86) Application" \97p)
-!MESSAGE "timw32gd - Win32 Debug" ("Win32 (x86) Application" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "timw32gd - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /GX /O2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 comctl32.lib winmm.lib comdlg32.lib kernel32.lib user32.lib gdi32.lib winspool.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"../Release/timw32gd.exe"
-
-!ELSEIF  "$(CFG)" == "timw32gd - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /Zp16 /MTd /W3 /Gm /GX /ZI /Od /Ob0 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /D "W32GUI_DEBUG" /YX /FD /GZ /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 libcmtd.lib comctl32.lib winmm.lib comdlg32.lib kernel32.lib user32.lib gdi32.lib winspool.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib wsock32.lib /nologo /subsystem:windows /profile /debug /machine:I386 /nodefaultlib:"libc.lib" /nodefaultlib:"LIBCD" /out:"../Debug/timw32gd.exe"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "timw32gd - Win32 Release"
-# Name "timw32gd - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\interface\w32g_c.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_dib.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_i.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ini.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_mag.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\w32g_ogg_dll.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_playlist.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_pref.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subwin.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_subwin2.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_subwin3.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ut2.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.c"
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\w32g_vorbis_dll.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\timidity\w32g_vorbisenc_dll.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\wrdt_w32g.c
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\config.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\config_w32vc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface_w32vc.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_pref.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_rec.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_res.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_subwin.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ut2.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.h"
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\w32g_wrd.h
-# End Source File
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# Begin Source File
-
-SOURCE="..\interface\w32g_res.rc"
-# End Source File
-# End Group
-# Begin Source File
-
-SOURCE=..\Debug\utils.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Debug\libarc.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Debug\libunimod.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Debug\timidity.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Debug\interface.lib
-# End Source File
-# End Target
-# End Project
diff --git a/timw32gd/timw32gd.vcproj b/timw32gd/timw32gd.vcproj
deleted file mode 100644 (file)
index 7876665..0000000
+++ /dev/null
@@ -1,673 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="timw32gd"
-       ProjectGUID="{2323F6B3-6319-430F-A38C-AC8A13F664C6}"
-       TargetFrameworkVersion="0"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory=".\Release"
-                       IntermediateDirectory=".\Release"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Release/timw32gd.tlb"
-                               HeaderFileName=""
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="2"
-                               InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include"
-                               PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;HAVE_CONFIG_H;_MT"
-                               StringPooling="true"
-                               RuntimeLibrary="0"
-                               EnableFunctionLevelLinking="true"
-                               PrecompiledHeaderFile=".\Release/timw32gd.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="comctl32.lib winmm.lib odbc32.lib odbccp32.lib"
-                               OutputFile="../Release/timw32gd.exe"
-                               LinkIncremental="1"
-                               SuppressStartupBanner="true"
-                               IgnoreDefaultLibraryNames="libc.lib"
-                               ProgramDatabaseFile=".\Release/timw32gd.pdb"
-                               SubSystem="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                               SuppressStartupBanner="true"
-                               OutputFile=".\Release/timw32gd.bsc"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory=".\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Debug/timw32gd.tlb"
-                               HeaderFileName=""
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include"
-                               PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;HAVE_CONFIG_H;_MT;W32GUI_DEBUG"
-                               MinimalRebuild="true"
-                               BasicRuntimeChecks="3"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="5"
-                               PrecompiledHeaderFile=".\Debug/timw32gd.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="libcmtd.lib comctl32.lib winmm.lib odbc32.lib odbccp32.lib wsock32.lib"
-                               OutputFile="../Debug/timw32gd.exe"
-                               LinkIncremental="2"
-                               SuppressStartupBanner="true"
-                               IgnoreDefaultLibraryNames="libc.lib,LIBCD"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile=".\Debug/timw32gd.pdb"
-                               SubSystem="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                               SuppressStartupBanner="true"
-                               OutputFile=".\Debug/timw32gd.bsc"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath="..\interface\w32g_c.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_dib.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_i.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ini.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_mag.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_ogg_dll.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_playlist.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin2.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin3.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ut2.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbis_dll.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisenc_dll.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-                       <File
-                               RelativePath="..\interface\wrdt_w32g.c"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCCLCompilerTool"
-                                               AdditionalIncludeDirectories=""
-                                               PreprocessorDefinitions=""
-                                       />
-                               </FileConfiguration>
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\config_w32vc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface_w32vc.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_rec.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_res.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_subwin.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ut2.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_wrd.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Resource Files"
-                       Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-                       <File
-                               RelativePath="..\interface\w32g_res.rc"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               PreprocessorDefinitions=""
-                                               AdditionalIncludeDirectories="\C\TiMidity++-2.12.0-pre1b\interface"
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               PreprocessorDefinitions=""
-                                               AdditionalIncludeDirectories="\C\TiMidity++-2.12.0-pre1b\interface"
-                                       />
-                               </FileConfiguration>
-                       </File>
-               </Filter>
-               <File
-                       RelativePath="..\Debug\interface.lib"
-                       >
-               </File>
-               <File
-                       RelativePath="..\Debug\libarc.lib"
-                       >
-               </File>
-               <File
-                       RelativePath="..\Debug\libunimod.lib"
-                       >
-               </File>
-               <File
-                       RelativePath="..\Debug\timidity.lib"
-                       >
-               </File>
-               <File
-                       RelativePath="..\Debug\utils.lib"
-                       >
-               </File>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/timw32gd/timw32gd.vcxproj b/timw32gd/timw32gd.vcxproj
deleted file mode 100644 (file)
index ed37d8b..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{2323F6B3-6319-430F-A38C-AC8A13F664C6}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Release/timw32gd.tlb</TypeLibraryName>
-      <HeaderFileName>
-      </HeaderFileName>
-    </Midl>
-    <ClCompile>
-      <Optimization>MaxSpeed</Optimization>
-      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;WIN32;_WINDOWS;HAVE_CONFIG_H;_MT;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderOutputFile>.\Release/timw32gd.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>comctl32.lib;winmm.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>../Release/timw32gd.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>libc.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <ProgramDatabaseFile>.\Release/timw32gd.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-    <Bscmake>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <OutputFile>.\Release/timw32gd.bsc</OutputFile>
-    </Bscmake>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Debug/timw32gd.tlb</TypeLibraryName>
-      <HeaderFileName>
-      </HeaderFileName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;WIN32;_WINDOWS;HAVE_CONFIG_H;_MT;W32GUI_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MinimalRebuild>true</MinimalRebuild>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <PrecompiledHeaderOutputFile>.\Debug/timw32gd.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level3</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>libcmtd.lib;comctl32.lib;winmm.lib;odbc32.lib;odbccp32.lib;wsock32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>../Debug/timw32gd.exe</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <IgnoreSpecificDefaultLibraries>libc.lib;LIBCD;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/timw32gd.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <TargetMachine>MachineX86</TargetMachine>
-    </Link>
-    <Bscmake>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <OutputFile>.\Debug/timw32gd.bsc</OutputFile>
-    </Bscmake>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\interface\w32g_c.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_dib.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_i.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ini.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_mag.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_playlist.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_pref.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin2.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_subwin3.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ut2.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_utl.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ClCompile Include="..\interface\wrdt_w32g.c">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\config_w32vc.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\interface_w32vc.h" />
-    <ClInclude Include="..\interface\w32g.h" />
-    <ClInclude Include="..\interface\w32g_pref.h" />
-    <ClInclude Include="..\interface\w32g_rec.h" />
-    <ClInclude Include="..\interface\w32g_res.h" />
-    <ClInclude Include="..\interface\w32g_subwin.h" />
-    <ClInclude Include="..\interface\w32g_ut2.h" />
-    <ClInclude Include="..\interface\w32g_utl.h" />
-    <ClInclude Include="..\interface\w32g_wrd.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\interface\w32g_res.rc">
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\C\TiMidity++-2.12.0-pre1b\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\C\TiMidity++-2.12.0-pre1b\interface;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <Library Include="..\Debug\interface.lib" />
-    <Library Include="..\Debug\libarc.lib" />
-    <Library Include="..\Debug\libunimod.lib" />
-    <Library Include="..\Debug\timidity.lib" />
-    <Library Include="..\Debug\utils.lib" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/twsyn_bridge/CMakeLists.txt b/twsyn_bridge/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0ce6bf2
--- /dev/null
@@ -0,0 +1,19 @@
+
+add_executable(
+       twsyn_bridge WIN32
+
+       twsyn_bridge_exe.c
+
+       twsyn_bridge_common.h
+       twsyn_bridge_exe_res.h
+
+       twsyn_bridge_exe.rc
+)
+
+if(${CMAKE_SIZEOF_VOID_P} EQUAL 8)
+    set_target_properties(twsyn_bridge PROPERTIES OUTPUT_NAME "twsyn_bridge_x64")
+else()
+    set_target_properties(twsyn_bridge PROPERTIES OUTPUT_NAME "twsyn_bridge_x86")
+endif()
+
+target_link_libraries(twsyn_bridge shlwapi winmm)
diff --git a/twsyn_bridge/twsyn_bridge.vcproj b/twsyn_bridge/twsyn_bridge.vcproj
deleted file mode 100644 (file)
index fe0dc18..0000000
+++ /dev/null
@@ -1,199 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="twsyng_bridge"
-       ProjectGUID="{4D6B6788-F7B8-4FFB-B15F-DC5C665ABB5C}"
-       RootNamespace="twsyng_bridge"
-       TargetFrameworkVersion="196613"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;"
-                               MinimalRebuild="true"
-                               BasicRuntimeChecks="3"
-                               RuntimeLibrary="3"
-                               WarningLevel="3"
-                               DebugInformationFormat="4"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="winmm.lib"
-                               OutputFile="$(OutDir)\$(ProjectName)_x86.exe"
-                               GenerateDebugInformation="true"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="1"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_WINDOW"
-                               RuntimeLibrary="2"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               WarningLevel="3"
-                               DebugInformationFormat="3"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="winmm.lib"
-                               OutputFile="$(OutDir)\$(ProjectName)_x86.exe"
-                               LinkIncremental="2"
-                               GenerateDebugInformation="false"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               TargetMachine="1"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <File
-                       RelativePath=".\twsyng_bridge_common.h"
-                       >
-               </File>
-               <File
-                       RelativePath=".\twsyng_bridge_exe.c"
-                       >
-               </File>
-               <File
-                       RelativePath=".\twsyng_bridge_exe.h"
-                       >
-               </File>
-               <File
-                       RelativePath=".\twsyng_bridge_exe.rc"
-                       >
-               </File>
-               <File
-                       RelativePath=".\twsyng_bridge_exe_res.h"
-                       >
-               </File>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/twsyn_bridge/twsyn_bridge.vcxproj b/twsyn_bridge/twsyn_bridge.vcxproj
deleted file mode 100644 (file)
index 587b670..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{D6D9295A-4A29-4753-88E9-A9D8B589A3D0}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>twsyng_run</RootNamespace>
-    <ProjectName>twsyn_bridge</ProjectName>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>$(ProjectName)_x86</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>$(ProjectName)_x64</TargetName>
-    <OutDir>$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir>$(Platform)$(Configuration)\</IntDir>
-    <LibraryPath>$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>$(ProjectName)_x86</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>$(ProjectName)_x64</TargetName>
-    <OutDir>$(SolutionDir)$(Configuration)\</OutDir>
-    <LibraryPath>$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level3</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;USE_BRIDGE;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalDependencies>winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level3</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>_WIN64;WIN32;USE_BRIDGE;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalDependencies>winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level3</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>Full</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;USE_BRIDGE;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalDependencies>winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level3</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>Full</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>_WIN64;WIN32;USE_BRIDGE;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <FloatingPointModel>Fast</FloatingPointModel>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <SubSystem>Windows</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <LargeAddressAware>true</LargeAddressAware>
-      <AdditionalDependencies>winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="twsyn_bridge_common.h" />
-    <ClInclude Include="twsyn_bridge_exe_res.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="twsyn_bridge_exe.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="twsyn_bridge_exe.rc" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
index cb094cf..ac9aa81 100644 (file)
@@ -27,6 +27,8 @@
 #include "twsyn_bridge_host.h"
 #pragma hdrstop
 
+int opt_use_twsyn_bridge = 0;
+
 // bridge
 static DWORD PrcsId = 0;
 static DWORD PrcsVer = 0;
diff --git a/twsyng/twsyng.dsp b/twsyng/twsyng.dsp
deleted file mode 100644 (file)
index 4df2bc2..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-# Microsoft Developer Studio Project File - Name="twsyng" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Application" 0x0101
-
-CFG=twsyng - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "twsyng.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "twsyng.mak" CFG="twsyng - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "twsyng - Win32 Release" ("Win32 (x86) Application" \97p)
-!MESSAGE "twsyng - Win32 Debug" ("Win32 (x86) Application" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "twsyng - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /D "TWSYNG32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib /nologo /subsystem:windows /machine:I386 /out:"../Release/twsyng.exe"
-
-!ELSEIF  "$(CFG)" == "twsyng - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /I "..\..\include" /D "TWSYNG32" /D "WIN32" /D "__DEBUG" /D "_WINDOWS" /D "_MBCS" /D "HAVE_CONFIG_H" /D "_MT" /YX /FD /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib /nologo /subsystem:windows /profile /debug /machine:I386 /out:"../Debug/twsyng.exe"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "twsyng - Win32 Release"
-# Name "twsyng - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE=..\interface\rtsyn_common.c
-# End Source File
-# Begin Source File
-
-SOURCE=..\interface\rtsyn_winmm.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_ini.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_ogg_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_pref.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_syn.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\w32g_utl.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_vorbis_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\timidity\w32g_vorbisenc_dll.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\interface\winsyn_c.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# Begin Source File
-
-SOURCE="..\interface\w32g_res.rc"
-# End Source File
-# End Group
-# Begin Source File
-
-SOURCE=..\Release\utils.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\libarc.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\libunimod.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\timidity.lib
-# End Source File
-# Begin Source File
-
-SOURCE=..\Release\interface.lib
-# End Source File
-# End Target
-# End Project
diff --git a/twsyng/twsyng.vcproj b/twsyng/twsyng.vcproj
deleted file mode 100644 (file)
index 1e9e5ba..0000000
+++ /dev/null
@@ -1,651 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="twsyng"
-       ProjectGUID="{49D11476-D08C-43D6-8C7D-3820607E140F}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Release/twsyng.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\libmpg123\include,..\twsyn_bridge,..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include,..\portaudio\pa_common"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/twsyng.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib"
-                               OutputFile="..\Release\twsyng.exe"
-                               LinkIncremental="1"
-                               SuppressStartupBanner="true"
-                               ProgramDatabaseFile=".\Release/twsyng.pdb"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="2"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               MkTypLibCompatible="true"
-                               SuppressStartupBanner="true"
-                               TargetEnvironment="1"
-                               TypeLibraryName=".\Debug/twsyng.tlb"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\twsyn_bridge,..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include,..\portaudio\pa_common"
-                               PreprocessorDefinitions="WIN32;__DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/twsyng.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="setupapi.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib"
-                               OutputFile="../Debug/twsyng.exe"
-                               LinkIncremental="2"
-                               SuppressStartupBanner="true"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile=".\Debug/twsyng.pdb"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-               <ProjectReference
-                       ReferencedProjectIdentifier="{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-                       RelativePathToProject=".\libarc\libarc.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-                       RelativePathToProject=".\libunimod\libunimod.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-                       RelativePathToProject=".\utils\utils.vcproj"
-               />
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath="..\timidity\aiff_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\aq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\au_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\audio_cnv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\controls.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\decode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\envelope.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\filter.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\flac_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\freq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\gogo_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\instrum.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\int_synth.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\lame_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\list_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\loadtab.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\m2m.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mfi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mfnode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\miditrace.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mix.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mod.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mod2midi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\modmid_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mt19937ar.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\myini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\optcode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\opus_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\oscillator.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\output.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\playmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\portaudio_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\quantity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\raw_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\rcp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\readmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\recache.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\resample.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_winmm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sbkconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sffile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sfitem.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\smfconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\smplfile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfont.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfontini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\speex_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\thread.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timer2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timidity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\twsyn_bridge\twsyn_bridge_host.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\version.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\voice_effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\volumecalc_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\vorbis_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_gogo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libmpg123_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_portaudio_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_int_synth_editor.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_ogg_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_opus_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_soundspec.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_syn.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbis_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisenc_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisfile_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wasapi_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wave_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wdmks_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\winsyn_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wrd_read.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wrdt.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Resource Files"
-                       Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-                       <File
-                               RelativePath="..\interface\w32g_res.rc"
-                               >
-                               <FileConfiguration
-                                       Name="Release|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               AdditionalIncludeDirectories="\PROJECT\tmidity\interface;$(NoInherit)"
-                                       />
-                               </FileConfiguration>
-                               <FileConfiguration
-                                       Name="Debug|Win32"
-                                       >
-                                       <Tool
-                                               Name="VCResourceCompilerTool"
-                                               AdditionalIncludeDirectories="\PROJECT\tmidity\interface;$(NoInherit)"
-                                       />
-                               </FileConfiguration>
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\int_synth.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\loadsndfontini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\configs\msc-twsyn-interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\myini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\oscillator.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfontini.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\thread.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\voice_effect.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\vstwrapper.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/twsyng/twsyng.vcxproj b/twsyng/twsyng.vcxproj
deleted file mode 100644 (file)
index 6fe30ce..0000000
+++ /dev/null
@@ -1,430 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{49D11476-D08C-43D6-8C7D-3820607E140F}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">twsyng_c220</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">twsyng_x64_c220</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)lib\amd64;$(VCInstallDir)atlmfc\lib\amd64;$(WindowsSdkDir)lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(ProjectName)_x64</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Release/twsyng.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\twsyn_bridge;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/twsyng.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level2</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <ProgramDatabaseFile>.\Release/twsyng.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <EnableUAC>true</EnableUAC>
-      <LargeAddressAware>true</LargeAddressAware>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <IgnoreSpecificDefaultLibraries>msvcrt.lib;libc.lib;</IgnoreSpecificDefaultLibraries>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <Midl>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Release/twsyng.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\twsyn_bridge;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/twsyng.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <ProgramDatabaseFile>.\Release/twsyng.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <EnableUAC>true</EnableUAC>
-      <LargeAddressAware>true</LargeAddressAware>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetEnvironment>Win32</TargetEnvironment>
-      <TypeLibraryName>.\Debug/twsyng.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\twsyn_bridge;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;__DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/twsyng.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalOptions>/MACHINE:I386 %(AdditionalOptions)</AdditionalOptions>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/twsyng.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <Midl>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <MkTypLibCompatible>true</MkTypLibCompatible>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TypeLibraryName>.\Debug/twsyng.tlb</TypeLibraryName>
-    </Midl>
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\twsyn_bridge;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libspeex;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;_DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/twsyng.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>Level1</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-    </ResourceCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>.\Debug/twsyng.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\interface\w32g_int_synth_editor.c" />
-    <ClCompile Include="..\interface\w32g_soundspec.c" />
-    <ClCompile Include="..\timidity\aiff_a.c" />
-    <ClCompile Include="..\timidity\ao_a.c" />
-    <ClCompile Include="..\timidity\aq.c" />
-    <ClCompile Include="..\timidity\au_a.c" />
-    <ClCompile Include="..\timidity\audio_cnv.c" />
-    <ClCompile Include="..\timidity\common.c" />
-    <ClCompile Include="..\timidity\controls.c" />
-    <ClCompile Include="..\timidity\decode.c" />
-    <ClCompile Include="..\timidity\effect.c" />
-    <ClCompile Include="..\timidity\envelope.c" />
-    <ClCompile Include="..\timidity\filter.c" />
-    <ClCompile Include="..\timidity\flac_a.c" />
-    <ClCompile Include="..\timidity\freq.c" />
-    <ClCompile Include="..\timidity\gogo_a.c" />
-    <ClCompile Include="..\timidity\instrum.c" />
-    <ClCompile Include="..\timidity\int_synth.c" />
-    <ClCompile Include="..\timidity\lame_a.c" />
-    <ClCompile Include="..\timidity\list_a.c" />
-    <ClCompile Include="..\timidity\loadtab.c" />
-    <ClCompile Include="..\timidity\m2m.c" />
-    <ClCompile Include="..\timidity\mfi.c" />
-    <ClCompile Include="..\timidity\mfnode.c" />
-    <ClCompile Include="..\timidity\miditrace.c" />
-    <ClCompile Include="..\timidity\mix.c" />
-    <ClCompile Include="..\timidity\mod.c" />
-    <ClCompile Include="..\timidity\mod2midi.c" />
-    <ClCompile Include="..\timidity\modmid_a.c" />
-    <ClCompile Include="..\timidity\mt19937ar.c" />
-    <ClCompile Include="..\timidity\myini.c" />
-    <ClCompile Include="..\timidity\optcode.c" />
-    <ClCompile Include="..\timidity\opus_a.c" />
-    <ClCompile Include="..\timidity\oscillator.c" />
-    <ClCompile Include="..\timidity\output.c" />
-    <ClCompile Include="..\timidity\playmidi.c" />
-    <ClCompile Include="..\timidity\portaudio_a.c" />
-    <ClCompile Include="..\timidity\quantity.c" />
-    <ClCompile Include="..\timidity\raw_a.c" />
-    <ClCompile Include="..\timidity\rcp.c" />
-    <ClCompile Include="..\timidity\readmidi.c" />
-    <ClCompile Include="..\timidity\recache.c" />
-    <ClCompile Include="..\timidity\resample.c" />
-    <ClCompile Include="..\interface\rtsyn_common.c" />
-    <ClCompile Include="..\interface\rtsyn_winmm.c" />
-    <ClCompile Include="..\timidity\sbkconv.c" />
-    <ClCompile Include="..\timidity\sffile.c" />
-    <ClCompile Include="..\timidity\sfitem.c" />
-    <ClCompile Include="..\timidity\smfconv.c" />
-    <ClCompile Include="..\timidity\smplfile.c" />
-    <ClCompile Include="..\timidity\sndfont.c" />
-    <ClCompile Include="..\timidity\sndfontini.c" />
-    <ClCompile Include="..\timidity\tables.c" />
-    <ClCompile Include="..\timidity\thread.c" />
-    <ClCompile Include="..\timidity\timidity.c" />
-    <ClCompile Include="..\timidity\version.c" />
-    <ClCompile Include="..\timidity\voice_effect.c" />
-    <ClCompile Include="..\timidity\vorbis_a.c" />
-    <ClCompile Include="..\timidity\w32g_opus_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisfile_dll.c" />
-    <ClCompile Include="..\timidity\w32_a.c" />
-    <ClCompile Include="..\timidity\w32_gogo.c" />
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_libmpg123_dll.c" />
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c" />
-    <ClCompile Include="..\interface\w32g_ini.c" />
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c" />
-    <ClCompile Include="..\interface\w32g_pref.c" />
-    <ClCompile Include="..\interface\w32g_syn.c" />
-    <ClCompile Include="..\interface\w32g_utl.c" />
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c" />
-    <ClCompile Include="..\timidity\wasapi_a.c" />
-    <ClCompile Include="..\timidity\wave_a.c" />
-    <ClCompile Include="..\interface\winsyn_c.c" />
-    <ClCompile Include="..\timidity\wdmks_a.c" />
-    <ClCompile Include="..\timidity\wrd_read.c" />
-    <ClCompile Include="..\timidity\wrdt.c" />
-    <ClCompile Include="..\twsyn_bridge\twsyn_bridge_host.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\interface\w32g_res.rc">
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">\PROJECT\tmidity\interface</AdditionalIncludeDirectories>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\interface\soundspec.h" />
-    <ClInclude Include="..\timidity\int_synth.h" />
-    <ClInclude Include="..\timidity\loadsndfontini.h" />
-    <ClInclude Include="..\timidity\myini.h" />
-    <ClInclude Include="..\timidity\oscillator.h" />
-    <ClInclude Include="..\timidity\sndfontini.h" />
-    <ClInclude Include="..\timidity\thread.h" />
-    <ClInclude Include="..\timidity\voice_effect.h" />
-    <ClInclude Include="..\timidity\voice_filter.h" />
-    <ClInclude Include="..\timidity\vstwrapper.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\interface\interface.vcxproj">
-      <Project>{248b20a6-9609-4a5b-afae-09c7572fce54}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\libarc\libarc.vcxproj">
-      <Project>{11cdd90a-20e1-45af-879e-f355742b38b7}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\libunimod\libunimod.vcxproj">
-      <Project>{8dc8ade3-145a-4c63-80dd-0c93b6587b80}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\speex\libspeex.vcxproj">
-      <Project>{e972c52f-9e85-4d65-b19c-031e511e9db4}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\utils\utils.vcxproj">
-      <Project>{b05f8aa0-6140-4335-ad39-e276d17002cb}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/twsyng/twsyng.vcxproj.filters b/twsyng/twsyng.vcxproj.filters
deleted file mode 100644 (file)
index 4e04d06..0000000
+++ /dev/null
@@ -1,278 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{c718b868-0da3-4ec6-b42e-02792a47fb0a}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{3828f33f-9ad8-4fb7-a20f-b0df9caa3f29}</UniqueIdentifier>
-      <Extensions>ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{784123c5-91a0-440e-a385-643c7db24083}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\aiff_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\aq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\au_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\audio_cnv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\controls.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\filter.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\flac_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\freq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\gogo_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\instrum.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\list_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\loadtab.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\m2m.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfnode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\miditrace.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mix.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod2midi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\modmid_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mt19937ar.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\optcode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\output.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\playmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\portaudio_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\quantity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\raw_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\rcp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\readmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\recache.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\resample.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_winmm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sbkconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sffile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sfitem.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smfconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smplfile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfont.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\tables.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\timidity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\version.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\vorbis_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_gogo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_pref.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_syn.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_utl.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wave_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\winsyn_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrd_read.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrdt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\myini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfontini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_soundspec.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\envelope.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\opus_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_opus_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\ao_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\thread.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\voice_effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\int_synth.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\oscillator.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="..\interface\w32g_res.rc">
-      <Filter>Resource Files</Filter>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\loadsndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\myini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\vstwrapper.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\thread.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\voice_effect.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\voice_filter.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\int_synth.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\oscillator.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface\soundspec.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/twsyng/twsyng.vcxproj.user b/twsyng/twsyng.vcxproj.user
deleted file mode 100644 (file)
index df96e65..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LocalDebuggerCommand>$(TargetPath)</LocalDebuggerCommand>
-    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LocalDebuggerCommand>C:\TIMIDITY\twsyng.exe</LocalDebuggerCommand>
-    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/twsynsrv/twsynsrv.vcproj b/twsynsrv/twsynsrv.vcproj
deleted file mode 100644 (file)
index 1deedff..0000000
+++ /dev/null
@@ -1,556 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="twsynsrv"
-       ProjectGUID="{58F8555C-30C5-48AC-9C1C-680BDA52218D}"
-       Keyword="Win32Proj"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include,..\portaudio\pa_common"
-                               PreprocessorDefinitions="WIN32;__DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="true"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/twsynsrv.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               BrowseInformation="1"
-                               WarningLevel="3"
-                               Detect64BitPortabilityProblems="false"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="setupapi.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib"
-                               OutputFile="../Debug/twsynsrv.exe"
-                               LinkIncremental="2"
-                               GenerateDebugInformation="true"
-                               ProgramDatabaseFile="$(OutDir)/twsynsrv.pdb"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="0"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="1"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\libmpg123\include;..\interface,..\libarc,..\libunimod,..\timidity,..\utils,..,..\..\include,..\portaudio\pa_common"
-                               PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV;"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/twsynsrv.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               Detect64BitPortabilityProblems="false"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLinkerTool"
-                               AdditionalDependencies="setupapi.lib odbc32.lib odbccp32.lib winmm.lib wsock32.lib comctl32.lib"
-                               OutputFile="..\Release\twsynsrv.exe"
-                               LinkIncremental="1"
-                               GenerateDebugInformation="false"
-                               SubSystem="2"
-                               LargeAddressAware="2"
-                               OptimizeReferences="2"
-                               EnableCOMDATFolding="2"
-                               RandomizedBaseAddress="1"
-                               DataExecutionPrevention="2"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCManifestTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCAppVerifierTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-               <ProjectReference
-                       ReferencedProjectIdentifier="{248B20A6-9609-4A5B-AFAE-09C7572FCE54}"
-                       RelativePathToProject=".\interface\interface.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{11CDD90A-20E1-45AF-879E-F355742B38B7}"
-                       RelativePathToProject=".\libarc\libarc.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{8DC8ADE3-145A-4C63-80DD-0C93B6587B80}"
-                       RelativePathToProject=".\libunimod\libunimod.vcproj"
-               />
-               <ProjectReference
-                       ReferencedProjectIdentifier="{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-                       RelativePathToProject=".\utils\utils.vcproj"
-               />
-       </References>
-       <Files>
-               <Filter
-                       Name="\83\\81[\83\83t\83@\83C\83\8b"
-                       Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"
-                       >
-                       <File
-                               RelativePath="..\timidity\aiff_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\aq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\au_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\audio_cnv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\controls.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\decode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\envelope.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\filter.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\flac_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\freq.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\gogo_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\instrum.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\int_synth.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\list_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\loadtab.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\m2m.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mfi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mfnode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\miditrace.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mix.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mod.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mod2midi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\modmid_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\mt19937ar.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\myini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\optcode.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\oscillator.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\output.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\playmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\portaudio_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\quantity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\raw_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\rcp.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\readmidi.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\recache.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\resample.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_common.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\rtsyn_winmm.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sbkconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sffile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sfitem.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\smfconv.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\smplfile.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfont.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\sndfontini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\tables.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\thread.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timer2.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\timidity.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\version.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\voice_effect.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\vorbis_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_gogo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libmpg123_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_libOggFLAC_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32_portaudio_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_ini.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_ogg_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_pref.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_syn.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\w32g_utl.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbis_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisenc_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\w32g_vorbisfile_dll.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wasapi_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wave_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wdmks_a.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface\winsyn_c.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wrd_read.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\timidity\wrdt.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="\83w\83b\83_\81\83t\83@\83C\83\8b"
-                       Filter="h;hpp;hxx;hm;inl;inc"
-                       >
-                       <File
-                               RelativePath="..\config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\interface.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\configs\msc-config.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath="..\configs\msc-twsyn-interface.h"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="\83\8a\83\\81[\83\83t\83@\83C\83\8b"
-                       Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-                       >
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/twsynsrv/twsynsrv.vcxproj b/twsynsrv/twsynsrv.vcxproj
deleted file mode 100644 (file)
index 0f6c5c7..0000000
+++ /dev/null
@@ -1,359 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{58F8555C-30C5-48AC-9C1C-680BDA52218D}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">twsynsrv_x64</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(VCInstallDir)lib\amd64;$(VCInstallDir)atlmfc\lib\amd64;$(WindowsSdkDir)lib\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64;</LibraryPath>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(ProjectName)_x64</TargetName>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;__DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/twsynsrv.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <BrowseInformation>true</BrowseInformation>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>false</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>$(OutDir)twsynsrv.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;__DEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/twsynsrv.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <BrowseInformation>true</BrowseInformation>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>$(OutDir)twsynsrv.pdb</ProgramDatabaseFile>
-      <SubSystem>Windows</SubSystem>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>
-      </DataExecutionPrevention>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/twsynsrv.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>Level2</WarningLevel>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
-      <SubSystem>Windows</SubSystem>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-      <IgnoreSpecificDefaultLibraries>msvcrt.lib;libc.lib;</IgnoreSpecificDefaultLibraries>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;..\..\include;..\portaudio\pa_common;..\libmpg123\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;WIN32;NDEBUG;_WINDOWS;HAVE_CONFIG_H;_MT;TWSYNG32;TWSYNSRV;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>true</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/twsynsrv.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>setupapi.lib;odbc32.lib;odbccp32.lib;winmm.lib;wsock32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>$(TargetPath)</OutputFile>
-      <GenerateDebugInformation>false</GenerateDebugInformation>
-      <SubSystem>Windows</SubSystem>
-      <OptimizeReferences>true</OptimizeReferences>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <RandomizedBaseAddress>false</RandomizedBaseAddress>
-      <DataExecutionPrevention>true</DataExecutionPrevention>
-      <LargeAddressAware>true</LargeAddressAware>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\aiff_a.c" />
-    <ClCompile Include="..\timidity\aq.c" />
-    <ClCompile Include="..\timidity\au_a.c" />
-    <ClCompile Include="..\timidity\audio_cnv.c" />
-    <ClCompile Include="..\timidity\common.c" />
-    <ClCompile Include="..\timidity\controls.c" />
-    <ClCompile Include="..\timidity\decode.c" />
-    <ClCompile Include="..\timidity\effect.c" />
-    <ClCompile Include="..\timidity\envelope.c" />
-    <ClCompile Include="..\timidity\filter.c" />
-    <ClCompile Include="..\timidity\flac_a.c" />
-    <ClCompile Include="..\timidity\freq.c" />
-    <ClCompile Include="..\timidity\gogo_a.c" />
-    <ClCompile Include="..\timidity\instrum.c" />
-    <ClCompile Include="..\timidity\int_synth.c" />
-    <ClCompile Include="..\timidity\list_a.c" />
-    <ClCompile Include="..\timidity\loadtab.c" />
-    <ClCompile Include="..\timidity\m2m.c" />
-    <ClCompile Include="..\timidity\mfi.c" />
-    <ClCompile Include="..\timidity\mfnode.c" />
-    <ClCompile Include="..\timidity\miditrace.c" />
-    <ClCompile Include="..\timidity\mix.c" />
-    <ClCompile Include="..\timidity\mod.c" />
-    <ClCompile Include="..\timidity\mod2midi.c" />
-    <ClCompile Include="..\timidity\modmid_a.c" />
-    <ClCompile Include="..\timidity\mt19937ar.c" />
-    <ClCompile Include="..\timidity\myini.c" />
-    <ClCompile Include="..\timidity\optcode.c" />
-    <ClCompile Include="..\timidity\oscillator.c" />
-    <ClCompile Include="..\timidity\output.c" />
-    <ClCompile Include="..\timidity\playmidi.c" />
-    <ClCompile Include="..\timidity\portaudio_a.c" />
-    <ClCompile Include="..\timidity\quantity.c" />
-    <ClCompile Include="..\timidity\raw_a.c" />
-    <ClCompile Include="..\timidity\rcp.c" />
-    <ClCompile Include="..\timidity\readmidi.c" />
-    <ClCompile Include="..\timidity\recache.c" />
-    <ClCompile Include="..\timidity\resample.c" />
-    <ClCompile Include="..\interface\rtsyn_common.c" />
-    <ClCompile Include="..\interface\rtsyn_winmm.c" />
-    <ClCompile Include="..\timidity\sbkconv.c" />
-    <ClCompile Include="..\timidity\sffile.c" />
-    <ClCompile Include="..\timidity\sfitem.c" />
-    <ClCompile Include="..\timidity\smfconv.c" />
-    <ClCompile Include="..\timidity\smplfile.c" />
-    <ClCompile Include="..\timidity\sndfont.c" />
-    <ClCompile Include="..\timidity\sndfontini.c" />
-    <ClCompile Include="..\timidity\tables.c" />
-    <ClCompile Include="..\timidity\thread.c" />
-    <ClCompile Include="..\timidity\timidity.c" />
-    <ClCompile Include="..\timidity\version.c" />
-    <ClCompile Include="..\timidity\voice_effect.c" />
-    <ClCompile Include="..\timidity\vorbis_a.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisfile_dll.c" />
-    <ClCompile Include="..\timidity\w32_a.c" />
-    <ClCompile Include="..\timidity\w32_gogo.c" />
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_libmpg123_dll.c" />
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c" />
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c" />
-    <ClCompile Include="..\interface\w32g_ini.c" />
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c" />
-    <ClCompile Include="..\interface\w32g_pref.c" />
-    <ClCompile Include="..\interface\w32g_syn.c" />
-    <ClCompile Include="..\interface\w32g_utl.c" />
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c" />
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c" />
-    <ClCompile Include="..\timidity\wasapi_a.c" />
-    <ClCompile Include="..\timidity\wave_a.c" />
-    <ClCompile Include="..\interface\winsyn_c.c" />
-    <ClCompile Include="..\timidity\wdmks_a.c" />
-    <ClCompile Include="..\timidity\wrd_read.c" />
-    <ClCompile Include="..\timidity\wrdt.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h" />
-    <ClInclude Include="..\interface.h" />
-    <ClInclude Include="..\configs\msc-config.h" />
-    <ClInclude Include="..\configs\msc-twsyn-interface.h" />
-    <ClInclude Include="..\timidity\int_synth.h" />
-    <ClInclude Include="..\timidity\loadsndfontini.h" />
-    <ClInclude Include="..\timidity\myini.h" />
-    <ClInclude Include="..\timidity\oscillator.h" />
-    <ClInclude Include="..\timidity\pragmapack.h" />
-    <ClInclude Include="..\timidity\sndfontini.h" />
-    <ClInclude Include="..\timidity\thread.h" />
-    <ClInclude Include="..\timidity\voice_effect.h" />
-    <ClInclude Include="..\timidity\voice_filter.h" />
-    <ClInclude Include="..\timidity\vstwrapper.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\interface\interface.vcxproj">
-      <Project>{248b20a6-9609-4a5b-afae-09c7572fce54}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\libarc\libarc.vcxproj">
-      <Project>{11cdd90a-20e1-45af-879e-f355742b38b7}</Project>
-    </ProjectReference>
-    <ProjectReference Include="..\libunimod\libunimod.vcxproj">
-      <Project>{8dc8ade3-145a-4c63-80dd-0c93b6587b80}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-    <ProjectReference Include="..\utils\utils.vcxproj">
-      <Project>{b05f8aa0-6140-4335-ad39-e276d17002cb}</Project>
-      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/twsynsrv/twsynsrv.vcxproj.filters b/twsynsrv/twsynsrv.vcxproj.filters
deleted file mode 100644 (file)
index e021edf..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{eee666bc-0a6c-42ca-a9c6-b56144784b74}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl;inc</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{ece96794-ebae-4cc3-add2-bfb4eaa675ad}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
-    </Filter>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{c0b49561-6bc8-4f6f-ad01-1295b84bf2df}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\timidity\aiff_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\aq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\au_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\audio_cnv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\controls.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\filter.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\flac_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\freq.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\gogo_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\instrum.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\list_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\loadtab.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\m2m.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mfnode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\miditrace.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mix.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mod2midi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\modmid_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\mt19937ar.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\optcode.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\output.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\playmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\portaudio_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\quantity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\raw_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\rcp.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\readmidi.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\recache.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\resample.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_common.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\rtsyn_winmm.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sbkconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sffile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sfitem.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smfconv.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\smplfile.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfont.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\tables.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\timidity.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\version.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\vorbis_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_gogo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_libOggFLAC_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32_portaudio_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_ini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_ogg_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_pref.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_syn.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\w32g_utl.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbis_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\w32g_vorbisenc_dll.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wave_a.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\interface\winsyn_c.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrd_read.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\wrdt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\myini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\sndfontini.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\envelope.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\thread.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\voice_effect.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\int_synth.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\timidity\oscillator.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\configs\msc-config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\configs\msc-twsyn-interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\loadsndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\myini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\pragmapack.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\sndfontini.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\vstwrapper.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\thread.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\voice_effect.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\voice_filter.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\int_synth.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\timidity\oscillator.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/twsynsrv/twsynsrv.vcxproj.user b/twsynsrv/twsynsrv.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4f4ee8d
--- /dev/null
@@ -0,0 +1,31 @@
+
+add_library(
+    utils OBJECT
+
+    bitset.c
+    fft.c
+    fft4g.c
+    getaddrinfo.c
+    getopt.c
+    mblock.c
+    memb.c
+    net.c
+    nkflib.c
+    readdir_win.c
+    strtab.c
+    support.c
+    timer.c
+
+    bitset.h
+    fft.h
+    mac_readdir.h
+    mac_util.h
+    mblock.h
+    memb.h
+    net.h
+    nkflib.h
+    readdir.h
+    strtab.h
+    support.h
+    timer.h
+)
diff --git a/utils/utils.dsp b/utils/utils.dsp
deleted file mode 100644 (file)
index d65ea90..0000000
+++ /dev/null
@@ -1,192 +0,0 @@
-# Microsoft Developer Studio Project File - Name="utils" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** \95Ò\8fW\82µ\82È\82¢\82Å\82­\82¾\82³\82¢ **
-
-# TARGTYPE "Win32 (x86) Static Library" 0x0104
-
-CFG=utils - Win32 Debug
-!MESSAGE \82±\82ê\82Í\97L\8cø\82ÈÒ²¸Ì§²Ù\82Å\82Í\82 \82è\82Ü\82¹\82ñ\81\82±\82ÌÌßÛ¼Þª¸Ä\82ðËÞÙÄÞ\82·\82é\82½\82ß\82É\82Í NMAKE \82ð\8eg\97p\82µ\82Ä\82­\82¾\82³\82¢\81B
-!MESSAGE [Ò²¸Ì§²Ù\82Ì´¸½Îß°Ä] ºÏÝÄÞ\82ð\8eg\97p\82µ\82Ä\8eÀ\8ds\82µ\82Ä\82­\82¾\82³\82¢
-!MESSAGE 
-!MESSAGE NMAKE /f "utils.mak".
-!MESSAGE 
-!MESSAGE NMAKE \82Ì\8eÀ\8ds\8e\9e\82É\8d\\90¬\82ð\8ew\92è\82Å\82«\82Ü\82·
-!MESSAGE ºÏÝÄޠײÝ\8fã\82ÅϸÛ\82Ì\90Ý\92è\82ð\92è\8b`\82µ\82Ü\82·\81B\97á:
-!MESSAGE 
-!MESSAGE NMAKE /f "utils.mak" CFG="utils - Win32 Debug"
-!MESSAGE 
-!MESSAGE \91I\91ð\89Â\94\\82ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE 
-!MESSAGE "utils - Win32 Release" ("Win32 (x86) Static Library" \97p)
-!MESSAGE "utils - Win32 Debug" ("Win32 (x86) Static Library" \97p)
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "utils - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
-# ADD CPP /nologo /Zp16 /MT /W3 /GX /O2 /Ob2 /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /I ".." /D "NDEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Release\utils.lib"
-
-!ELSEIF  "$(CFG)" == "utils - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\.." /I ".." /I "..\interface" /I "..\libarc" /I "..\libunimod" /I "..\timidity" /I "..\utils" /D "_DEBUG" /D "_MT" /D "_WINDOWS" /D "_LIB" /D "WIN32" /D "_MBCS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /i "..\interface" /i "..\libarc" /i "..\libunimod" /i "..\timidity" /i "..\utils" /i ".." /i "timidity" /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LIB32=link.exe -lib
-# ADD BASE LIB32 /nologo
-# ADD LIB32 /nologo /out:"../Debug\utils.lib"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "utils - Win32 Release"
-# Name "utils - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE="..\utils\bitset.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\fft.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\fft4g.c"
-# End Source File
-# Begin Source File
-
-SOURCE=.\getaddrinfo.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\getopt.c
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mblock.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\memb.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\net.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\nkflib.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\readdir_win.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\strtab.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\support.c"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\timer.c"
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE="..\utils\bitset.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\fft.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mac_readdir.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mac_util.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\mblock.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\memb.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\net.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\nkflib.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\readdir.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\strtab.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\support.h"
-# End Source File
-# Begin Source File
-
-SOURCE="..\utils\timer.h"
-# End Source File
-# End Group
-# End Target
-# End Project
diff --git a/utils/utils.vcproj b/utils/utils.vcproj
deleted file mode 100644 (file)
index fdb9ce4..0000000
+++ /dev/null
@@ -1,304 +0,0 @@
-<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-       ProjectType="Visual C++"
-       Version="9.00"
-       Name="utils"
-       ProjectGUID="{B05F8AA0-6140-4335-AD39-E276D17002CB}"
-       TargetFrameworkVersion="131072"
-       >
-       <Platforms>
-               <Platform
-                       Name="Win32"
-               />
-       </Platforms>
-       <ToolFiles>
-       </ToolFiles>
-       <Configurations>
-               <Configuration
-                       Name="Debug|Win32"
-                       OutputDirectory="..\Debug"
-                       IntermediateDirectory=".\Debug"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="0"
-                               AdditionalIncludeDirectories="..\..,..,..\interface,..\libarc,..\libunimod,..\timidity,..\utils"
-                               PreprocessorDefinitions="_DEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               MinimalRebuild="true"
-                               ExceptionHandling="0"
-                               BasicRuntimeChecks="3"
-                               SmallerTypeCheck="true"
-                               RuntimeLibrary="1"
-                               StructMemberAlignment="4"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               UsePrecompiledHeader="0"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Debug/utils.pch"
-                               AssemblerListingLocation=".\Debug/"
-                               ObjectFile=".\Debug/"
-                               ProgramDataBaseFileName=".\Debug/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               DebugInformationFormat="4"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="_DEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;timidity"
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               OutputFile="../Debug\utils.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-               <Configuration
-                       Name="Release|Win32"
-                       OutputDirectory="..\Release\"
-                       IntermediateDirectory=".\Release\"
-                       ConfigurationType="4"
-                       InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC70.vsprops"
-                       UseOfMFC="0"
-                       ATLMinimizesCRunTimeLibraryUsage="false"
-                       CharacterSet="2"
-                       WholeProgramOptimization="1"
-                       >
-                       <Tool
-                               Name="VCPreBuildEventTool"
-                       />
-                       <Tool
-                               Name="VCCustomBuildTool"
-                       />
-                       <Tool
-                               Name="VCXMLDataGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCWebServiceProxyGeneratorTool"
-                       />
-                       <Tool
-                               Name="VCMIDLTool"
-                       />
-                       <Tool
-                               Name="VCCLCompilerTool"
-                               Optimization="3"
-                               InlineFunctionExpansion="2"
-                               EnableIntrinsicFunctions="true"
-                               FavorSizeOrSpeed="1"
-                               OmitFramePointers="true"
-                               EnableFiberSafeOptimizations="true"
-                               AdditionalIncludeDirectories="..\interface,..\libarc,..\libunimod,..\timidity,..\utils,.."
-                               PreprocessorDefinitions="NDEBUG,_MT,_WINDOWS,_LIB,WIN32,HAVE_CONFIG_H"
-                               StringPooling="true"
-                               ExceptionHandling="0"
-                               RuntimeLibrary="0"
-                               StructMemberAlignment="5"
-                               BufferSecurityCheck="false"
-                               EnableFunctionLevelLinking="true"
-                               EnableEnhancedInstructionSet="2"
-                               FloatingPointModel="2"
-                               PrecompiledHeaderThrough="..\config.h"
-                               PrecompiledHeaderFile=".\Release/utils.pch"
-                               AssemblerListingLocation=".\Release/"
-                               ObjectFile=".\Release/"
-                               ProgramDataBaseFileName=".\Release/"
-                               WarningLevel="3"
-                               SuppressStartupBanner="true"
-                               CompileAs="1"
-                       />
-                       <Tool
-                               Name="VCManagedResourceCompilerTool"
-                       />
-                       <Tool
-                               Name="VCResourceCompilerTool"
-                               PreprocessorDefinitions="NDEBUG"
-                               Culture="1041"
-                               AdditionalIncludeDirectories="..\interface;..\libarc;..\libunimod;..\timidity;..\utils;.."
-                       />
-                       <Tool
-                               Name="VCPreLinkEventTool"
-                       />
-                       <Tool
-                               Name="VCLibrarianTool"
-                               AdditionalOptions="/LTCG"
-                               OutputFile="../Release\utils.lib"
-                               SuppressStartupBanner="true"
-                       />
-                       <Tool
-                               Name="VCALinkTool"
-                       />
-                       <Tool
-                               Name="VCXDCMakeTool"
-                       />
-                       <Tool
-                               Name="VCBscMakeTool"
-                       />
-                       <Tool
-                               Name="VCFxCopTool"
-                       />
-                       <Tool
-                               Name="VCPostBuildEventTool"
-                       />
-               </Configuration>
-       </Configurations>
-       <References>
-       </References>
-       <Files>
-               <Filter
-                       Name="Source Files"
-                       Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-                       >
-                       <File
-                               RelativePath=".\bitset.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\fft.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\fft4g.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\getaddrinfo.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\getopt.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mblock.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\memb.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\net.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\nkflib.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\readdir_win.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\strtab.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\support.c"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timer.c"
-                               >
-                       </File>
-               </Filter>
-               <Filter
-                       Name="Header Files"
-                       Filter="h;hpp;hxx;hm;inl"
-                       >
-                       <File
-                               RelativePath=".\bitset.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\fft.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_readdir.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mac_util.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\mblock.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\memb.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\net.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\nkflib.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\readdir.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\strtab.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\support.h"
-                               >
-                       </File>
-                       <File
-                               RelativePath=".\timer.h"
-                               >
-                       </File>
-               </Filter>
-       </Files>
-       <Globals>
-       </Globals>
-</VisualStudioProject>
diff --git a/utils/utils.vcxproj b/utils/utils.vcxproj
deleted file mode 100644 (file)
index bcfe1c8..0000000
+++ /dev/null
@@ -1,274 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{B05F8AA0-6140-4335-AD39-E276D17002CB}</ProjectGuid>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <WholeProgramOptimization>true</WholeProgramOptimization>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseOfMfc>false</UseOfMfc>
-    <CharacterSet>MultiByte</CharacterSet>
-    <PlatformToolset>Windows7.1SDK</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-    <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC70.props" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\</IntDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
-    <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib\amd64;$(WindowsSdkDir)lib\x64;</LibraryPath>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\..;..;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <MinimalRebuild>true</MinimalRebuild>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/utils.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;timidity;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\utils.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>..\..;..;..\interface;..\libarc;..\libunimod;..\timidity;..\utils;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;_DEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Debug/utils.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
-      <ObjectFileName>.\Debug/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
-      <CompileAs>CompileAsC</CompileAs>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;timidity;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <OutputFile>../Debug\utils.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetMachine>MachineX64</TargetMachine>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>16Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/utils.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <CallingConvention>Cdecl</CallingConvention>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\utils.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>_WIN64;NDEBUG;_MT;_WINDOWS;_LIB;WIN32;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <StringPooling>true</StringPooling>
-      <ExceptionHandling>
-      </ExceptionHandling>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-      <StructMemberAlignment>8Bytes</StructMemberAlignment>
-      <BufferSecurityCheck>false</BufferSecurityCheck>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <PrecompiledHeaderFile>..\config.h</PrecompiledHeaderFile>
-      <PrecompiledHeaderOutputFile>.\Release/utils.pch</PrecompiledHeaderOutputFile>
-      <AssemblerListingLocation>.\Release/</AssemblerListingLocation>
-      <ObjectFileName>.\Release/</ObjectFileName>
-      <ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
-      <WarningLevel>TurnOffAllWarnings</WarningLevel>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <CompileAs>CompileAsC</CompileAs>
-      <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
-      <Optimization>Full</Optimization>
-      <EnableFiberSafeOptimizations>false</EnableFiberSafeOptimizations>
-      <CallingConvention>Cdecl</CallingConvention>
-      <MultiProcessorCompilation>true</MultiProcessorCompilation>
-      <FloatingPointModel>Fast</FloatingPointModel>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <Culture>0x0411</Culture>
-      <AdditionalIncludeDirectories>..\interface;..\libarc;..\libunimod;..\timidity;..\utils;..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-    </ResourceCompile>
-    <Lib>
-      <AdditionalOptions>/LTCG %(AdditionalOptions)</AdditionalOptions>
-      <OutputFile>../Release\utils.lib</OutputFile>
-      <SuppressStartupBanner>true</SuppressStartupBanner>
-      <TargetMachine>MachineX64</TargetMachine>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="bitset.c" />
-    <ClCompile Include="fft.c" />
-    <ClCompile Include="fft4g.c" />
-    <ClCompile Include="getaddrinfo.c" />
-    <ClCompile Include="getopt.c" />
-    <ClCompile Include="mblock.c" />
-    <ClCompile Include="memb.c" />
-    <ClCompile Include="net.c" />
-    <ClCompile Include="nkflib.c" />
-    <ClCompile Include="readdir_win.c" />
-    <ClCompile Include="strtab.c" />
-    <ClCompile Include="support.c" />
-    <ClCompile Include="timer.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="bitset.h" />
-    <ClInclude Include="fft.h" />
-    <ClInclude Include="mac_readdir.h" />
-    <ClInclude Include="mac_util.h" />
-    <ClInclude Include="mblock.h" />
-    <ClInclude Include="memb.h" />
-    <ClInclude Include="net.h" />
-    <ClInclude Include="nkflib.h" />
-    <ClInclude Include="readdir.h" />
-    <ClInclude Include="strtab.h" />
-    <ClInclude Include="support.h" />
-    <ClInclude Include="timer.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/utils/utils.vcxproj.filters b/utils/utils.vcxproj.filters
deleted file mode 100644 (file)
index 4a856cf..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{c07bc53b-1063-440a-b247-f4d1d6a0f7e5}</UniqueIdentifier>
-      <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{620d8ad3-0f34-4333-ba18-b8f91045b829}</UniqueIdentifier>
-      <Extensions>h;hpp;hxx;hm;inl</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="bitset.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="fft.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="fft4g.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="getopt.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="mblock.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="memb.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="nkflib.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="strtab.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="support.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="timer.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="readdir_win.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="getaddrinfo.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="net.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="bitset.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="fft.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_readdir.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mac_util.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="mblock.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="memb.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="net.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="nkflib.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="readdir.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="strtab.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="support.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="timer.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/utils/utils.vcxproj.user b/utils/utils.vcxproj.user
deleted file mode 100644 (file)
index ace9a86..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-</Project>
\ No newline at end of file
diff --git a/version.h b/version.h
deleted file mode 100644 (file)
index 60bfffa..0000000
--- a/version.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-    TiMidity++ -- MIDI to WAVE converter and player
-    Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
-    Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-*/
-
-#ifndef ___VERSION_H_
-#define ___VERSION_H_
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef VERSION
-#define VERSION "2.14.0"
-#endif
-#ifndef TIMID_VERSION
-#define TIMID_VERSION "current"
-#endif
-#ifndef PACKAGE_NAME
-#define PACKAGE_NAME "TiMidity++"
-#endif
-#ifndef PACKAGE_VERSION
-#define PACKAGE_VERSION TIMID_VERSION
-#endif
-#ifndef PACKAGE_STRING
-#define PACKAGE_STRING PACKAGE_NAME " " VERSION
-#endif
-
-#endif /* !___VERSION_H_ */
-
diff --git a/version.h.in b/version.h.in
new file mode 100644 (file)
index 0000000..affc4cf
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+TiMidity++ -- MIDI to WAVE converter and player
+Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
+Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+*/
+
+#ifndef ___VERSION_H_
+#define ___VERSION_H_
+
+#define TIMID_VERSION "${tim41VersionStr}"
+#define TIMID_VERSION4_COMMA ${tim41Version4Comma}
+#define TIMID_VERSION_RESSTR "${tim41Version4Comma}\0"
+
+#endif /* !___VERSION_H_ */
diff --git a/vorbis/AUTHORS b/vorbis/AUTHORS
new file mode 100644 (file)
index 0000000..0da1036
--- /dev/null
@@ -0,0 +1,3 @@
+Monty <monty@xiph.org>
+
+and the rest of the Xiph.org Foundation.
diff --git a/vorbis/CMakeLists.txt b/vorbis/CMakeLists.txt
new file mode 100644 (file)
index 0000000..2b9a646
--- /dev/null
@@ -0,0 +1,83 @@
+
+include_directories(lib)
+
+add_library(
+    vorbis SHARED
+
+    include/vorbis/codec.h
+    include/vorbis/vorbisenc.h
+    include/vorbis/vorbisfile.h
+
+    lib/analysis.c
+    lib/backends.h
+    lib/barkmel.c
+    lib/bitrate.c
+    lib/bitrate.h
+    lib/block.c
+    lib/codebook.c
+    lib/codebook.h
+    lib/codec_internal.h
+    lib/envelope.c
+    lib/envelope.h
+    lib/floor0.c
+    lib/floor1.c
+    lib/highlevel.h
+    lib/info.c
+    lib/lookup.c
+    lib/lookup.h
+    lib/lookups.pl
+    lib/lookup_data.h
+    lib/lpc.c
+    lib/lpc.h
+    lib/lsp.c
+    lib/lsp.h
+    lib/mapping0.c
+    lib/masking.h
+    lib/mdct.c
+    lib/mdct.h
+    lib/misc.h
+    lib/os.h
+    lib/psy.c
+    lib/psy.h
+    lib/registry.c
+    lib/registry.h
+    lib/res0.c
+    lib/scales.h
+    lib/sharedbook.c
+    lib/smallft.c
+    lib/smallft.h
+    lib/synthesis.c
+    lib/vorbisenc.c
+    lib/vorbisfile.c
+    lib/window.c
+    lib/window.h
+    lib/books/coupled/res_books_51.h
+    lib/books/coupled/res_books_stereo.h
+    lib/books/floor/floor_books.h
+    lib/books/uncoupled/res_books_uncoupled.h
+    lib/modes/floor_all.h
+    lib/modes/psych_11.h
+    lib/modes/psych_16.h
+    lib/modes/psych_44.h
+    lib/modes/psych_8.h
+    lib/modes/residue_16.h
+    lib/modes/residue_44.h
+    lib/modes/residue_44p51.h
+    lib/modes/residue_44u.h
+    lib/modes/residue_8.h
+    lib/modes/setup_11.h
+    lib/modes/setup_16.h
+    lib/modes/setup_22.h
+    lib/modes/setup_32.h
+    lib/modes/setup_44.h
+    lib/modes/setup_44p51.h
+    lib/modes/setup_44u.h
+    lib/modes/setup_8.h
+    lib/modes/setup_X.h
+
+    win32/vorbis.def
+    win32/vorbisenc.def
+    win32/vorbisfile.def
+)
+
+target_link_libraries(vorbis ogg)
diff --git a/vorbis/COPYING b/vorbis/COPYING
new file mode 100644 (file)
index 0000000..8f1d18c
--- /dev/null
@@ -0,0 +1,28 @@
+Copyright (c) 2002-2015 Xiph.org Foundation
+
+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.
diff --git a/vorbis/README b/vorbis/README
new file mode 100644 (file)
index 0000000..343be9a
--- /dev/null
@@ -0,0 +1,134 @@
+********************************************************************
+*                                                                  *
+* 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-2015             *
+* by the Xiph.org Foundation, http://www.xiph.org/                 *
+*                                                                  *
+********************************************************************
+
+Vorbis is a general purpose audio and music encoding format
+contemporary to MPEG-4's AAC and TwinVQ, the next generation beyond
+MPEG audio layer 3. Unlike the MPEG sponsored formats (and other
+proprietary formats such as RealAudio G2 and Windows' flavor of the
+month), the Vorbis CODEC specification belongs to the public domain.
+All the technical details are published and documented, and any
+software entity may make full use of the format without license 
+fee, royalty or patent concerns.
+
+This package contains:
+
+* libvorbis, a BSD-style license software implementation of
+  the Vorbis specification by the Xiph.Org Foundation 
+  (http://www.xiph.org/) 
+
+* libvorbisfile, a BSD-style license convenience library
+  built on Vorbis designed to simplify common uses
+
+* libvorbisenc, a BSD-style license library that provides a simple,
+  programmatic encoding setup interface 
+
+* example code making use of libogg, libvorbis, libvorbisfile and
+  libvorbisenc
+
+WHAT'S HERE:
+
+This source distribution includes libvorbis and an example
+encoder/player to demonstrate use of libvorbis as well as
+documentation on the Ogg Vorbis audio coding format.
+
+You'll need libogg (distributed separately) to compile this library.
+A more comprehensive set of utilities is available in the vorbis-tools
+package.
+
+Directory:
+
+./lib                  The source for the libraries, a BSD-license implementation
+               of the public domain Ogg Vorbis audio encoding format.
+
+./include       Library API headers
+
+./debian        Rules/spec files for building Debian .deb packages
+
+./doc           Vorbis documentation
+
+./examples     Example code illustrating programmatic use of libvorbis, 
+               libvorbisfile and libvorbisenc
+
+./mac          Codewarrior project files and build tweaks for MacOS.
+
+./macosx       Project files for MacOS X.
+
+./win32                Win32 projects files and build automation
+
+./vq           Internal utilities for training/building new LSP/residue 
+               and auxiliary codebooks.
+
+CONTACT:
+
+The Ogg homepage is located at 'http://www.xiph.org/ogg/'.
+Vorbis's homepage is located at 'http://www.xiph.org/vorbis/'.
+Up to date technical documents, contact information, source code and
+pre-built utilities may be found there.
+
+The user website for Ogg Vorbis software and audio is http://vorbis.com/
+
+BUILDING FROM TRUNK:
+
+Development source is under subversion revision control at 
+https://svn.xiph.org/trunk/vorbis/. You will also need the 
+newest versions of autoconf, automake, libtool and pkg-config in
+order to compile Vorbis from development source. A configure script
+is provided for you in the source tarball distributions.
+
+  [update or checkout latest source]
+  ./autogen.sh
+  make
+
+and as root if desired:
+
+  make install
+
+This will install the Vorbis libraries (static and shared) into
+/usr/local/lib, includes into /usr/local/include and API manpages
+(once we write some) into /usr/local/man.
+
+Documentation building requires xsltproc and pdfxmltex.
+
+BUILDING FROM TARBALL DISTRIBUTIONS:
+
+  ./configure
+  make
+
+and optionally (as root):
+  make install
+
+BUILDING RPMS:
+
+after normal configuring:
+
+  make dist
+  rpm -ta libvorbis-<version>.tar.gz
+
+BUILDING ON MACOS 9:
+
+Vorbis on MacOS 9 is built using Metroworks CodeWarrior.  To build it, 
+first verify that the Ogg libraries are already built following the
+instructions in the Ogg module README.  Open vorbis/mac/libvorbis.mcp,
+switch to the "Targets" pane, select everything, and make the project.
+Do the same thing to build libvorbisenc.mcp, and libvorbisfile.mcp (in
+that order).  In vorbis/mac/Output you will now have both debug and final
+versions of Vorbis shared libraries to link your projects against.
+
+To build a project using Ogg Vorbis, add access paths to your
+CodeWarrior project for the ogg/include, ogg/mac/Output,
+vorbis/include, and vorbis/mac/Output folders.  Be sure that
+"interpret DOS and Unix paths" is turned on in your project; it can
+be found in the "access paths" pane in your project settings.  Now
+simply add the shared libraries you need to your project (OggLib and
+VorbisLib at least) and #include "ogg/ogg.h" and "vorbis/codec.h"
+wherever you need to access Ogg and Vorbis functionality.
+
similarity index 86%
rename from vorbis/codec.h
rename to vorbis/include/vorbis/codec.h
index 8329fed..42aa291 100644 (file)
@@ -6,12 +6,11 @@
  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
  *                                                                  *
  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001             *
- * by the XIPHOPHORUS Company http://www.xiph.org/                  *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
 
  ********************************************************************
 
  function: libvorbis codec headers
- last mod: $Id: codec.h,v 1.45 2003/09/05 22:34:46 giles Exp $
 
  ********************************************************************/
 
@@ -32,14 +31,14 @@ typedef struct vorbis_info{
 
   /* The below bitrate declarations are *hints*.
      Combinations of the three values carry the following implications:
-     
-     all three set to the same value: 
+
+     all three set to the same value:
        implies a fixed rate bitstream
-     only nominal set: 
-       implies a VBR stream that averages the nominal bitrate.  No hard 
+     only nominal set:
+       implies a VBR stream that averages the nominal bitrate.  No hard
        upper/lower limit
-     upper and or lower set: 
-       implies a VBR bitstream that obeys the bitrate limits. nominal 
+     upper and or lower set:
+       implies a VBR bitstream that obeys the bitrate limits. nominal
        may also be set to give a nominal rate.
      none set:
        the coder does not care to speculate.
@@ -87,9 +86,9 @@ typedef struct vorbis_dsp_state{
 
 typedef struct vorbis_block{
   /* necessary stream state for linking to the framing abstraction */
-  float  **pcm;       /* this is a pointer into local storage */ 
+  float  **pcm;       /* this is a pointer into local storage */
   oggpack_buffer opb;
-  
+
   long  lW;
   long  W;
   long  nW;
@@ -121,7 +120,7 @@ typedef struct vorbis_block{
 
 /* vorbis_block is a single block of data to be processed as part of
 the analysis/synthesis stream; it belongs to a specific logical
-bitstream, but is independant from other vorbis_blocks belonging to
+bitstream, but is independent from other vorbis_blocks belonging to
 that logical bitstream. *************************************************/
 
 struct alloc_chain{
@@ -166,28 +165,30 @@ extern void     vorbis_info_init(vorbis_info *vi);
 extern void     vorbis_info_clear(vorbis_info *vi);
 extern int      vorbis_info_blocksize(vorbis_info *vi,int zo);
 extern void     vorbis_comment_init(vorbis_comment *vc);
-extern void     vorbis_comment_add(vorbis_comment *vc, char *comment); 
-extern void     vorbis_comment_add_tag(vorbis_comment *vc, 
-                                      char *tag, char *contents);
-extern char    *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
-extern int      vorbis_comment_query_count(vorbis_comment *vc, char *tag);
+extern void     vorbis_comment_add(vorbis_comment *vc, const char *comment);
+extern void     vorbis_comment_add_tag(vorbis_comment *vc,
+                                       const char *tag, const char *contents);
+extern char    *vorbis_comment_query(vorbis_comment *vc, const char *tag, int count);
+extern int      vorbis_comment_query_count(vorbis_comment *vc, const char *tag);
 extern void     vorbis_comment_clear(vorbis_comment *vc);
 
 extern int      vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
 extern int      vorbis_block_clear(vorbis_block *vb);
 extern void     vorbis_dsp_clear(vorbis_dsp_state *v);
 extern double   vorbis_granule_time(vorbis_dsp_state *v,
-                                   ogg_int64_t granulepos);
+                                    ogg_int64_t granulepos);
+
+extern const char *vorbis_version_string(void);
 
 /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
 
 extern int      vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
 extern int      vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
 extern int      vorbis_analysis_headerout(vorbis_dsp_state *v,
-                                         vorbis_comment *vc,
-                                         ogg_packet *op,
-                                         ogg_packet *op_comm,
-                                         ogg_packet *op_code);
+                                          vorbis_comment *vc,
+                                          ogg_packet *op,
+                                          ogg_packet *op_comm,
+                                          ogg_packet *op_code);
 extern float  **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
 extern int      vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
 extern int      vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
@@ -195,11 +196,12 @@ extern int      vorbis_analysis(vorbis_block *vb,ogg_packet *op);
 
 extern int      vorbis_bitrate_addblock(vorbis_block *vb);
 extern int      vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
-                                          ogg_packet *op);
+                                           ogg_packet *op);
 
 /* Vorbis PRIMITIVES: synthesis layer *******************************/
+extern int      vorbis_synthesis_idheader(ogg_packet *op);
 extern int      vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
-                                         ogg_packet *op);
+                                          ogg_packet *op);
 
 extern int      vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
 extern int      vorbis_synthesis_restart(vorbis_dsp_state *v);
@@ -216,7 +218,7 @@ extern int      vorbis_synthesis_halfrate_p(vorbis_info *v);
 
 /* Vorbis ERRORS and return codes ***********************************/
 
-#define OV_FALSE      -1  
+#define OV_FALSE      -1
 #define OV_EOF        -2
 #define OV_HOLE       -3
 
diff --git a/vorbis/include/vorbis/vorbisenc.h b/vorbis/include/vorbis/vorbisenc.h
new file mode 100644 (file)
index 0000000..55f3b4a
--- /dev/null
@@ -0,0 +1,435 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2001             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: vorbis encode-engine setup
+
+ ********************************************************************/
+
+/** \file
+ * Libvorbisenc is a convenient API for setting up an encoding
+ * environment using libvorbis. Libvorbisenc encapsulates the
+ * actions needed to set up the encoder properly.
+ */
+
+#ifndef _OV_ENC_H_
+#define _OV_ENC_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "codec.h"
+
+/**
+ * This is the primary function within libvorbisenc for setting up managed
+ * bitrate modes.
+ *
+ * Before this function is called, the \ref vorbis_info
+ * struct should be initialized by using vorbis_info_init() from the libvorbis
+ * API.  After encoding, vorbis_info_clear() should be called.
+ *
+ * The max_bitrate, nominal_bitrate, and min_bitrate settings are used to set
+ * constraints for the encoded file.  This function uses these settings to
+ * select the appropriate encoding mode and set it up.
+ *
+ * \param vi               Pointer to an initialized \ref vorbis_info struct.
+ * \param channels         The number of channels to be encoded.
+ * \param rate             The sampling rate of the source audio.
+ * \param max_bitrate      Desired maximum bitrate (limit). -1 indicates unset.
+ * \param nominal_bitrate  Desired average, or central, bitrate. -1 indicates unset.
+ * \param min_bitrate      Desired minimum bitrate. -1 indicates unset.
+ *
+ * \return Zero for success, and negative values for failure.
+ *
+ * \retval 0          Success.
+ * \retval OV_EFAULT  Internal logic fault; indicates a bug or heap/stack corruption.
+ * \retval OV_EINVAL  Invalid setup request, eg, out of range argument.
+ * \retval OV_EIMPL   Unimplemented mode; unable to comply with bitrate request.
+ */
+extern int vorbis_encode_init(vorbis_info *vi,
+                              long channels,
+                              long rate,
+
+                              long max_bitrate,
+                              long nominal_bitrate,
+                              long min_bitrate);
+
+/**
+ * This function performs step-one of a three-step bitrate-managed encode
+ * setup.  It functions similarly to the one-step setup performed by \ref
+ * vorbis_encode_init but allows an application to make further encode setup
+ * tweaks using \ref vorbis_encode_ctl before finally calling \ref
+ * vorbis_encode_setup_init to complete the setup process.
+ *
+ * Before this function is called, the \ref vorbis_info struct should be
+ * initialized by using vorbis_info_init() from the libvorbis API.  After
+ * encoding, vorbis_info_clear() should be called.
+ *
+ * The max_bitrate, nominal_bitrate, and min_bitrate settings are used to set
+ * constraints for the encoded file.  This function uses these settings to
+ * select the appropriate encoding mode and set it up.
+ *
+ * \param vi                Pointer to an initialized vorbis_info struct.
+ * \param channels          The number of channels to be encoded.
+ * \param rate              The sampling rate of the source audio.
+ * \param max_bitrate       Desired maximum bitrate (limit). -1 indicates unset.
+ * \param nominal_bitrate   Desired average, or central, bitrate. -1 indicates unset.
+ * \param min_bitrate       Desired minimum bitrate. -1 indicates unset.
+ *
+ * \return Zero for success, and negative for failure.
+ *
+ * \retval 0           Success
+ * \retval OV_EFAULT   Internal logic fault; indicates a bug or heap/stack corruption.
+ * \retval OV_EINVAL   Invalid setup request, eg, out of range argument.
+ * \retval OV_EIMPL    Unimplemented mode; unable to comply with bitrate request.
+ */
+extern int vorbis_encode_setup_managed(vorbis_info *vi,
+                                       long channels,
+                                       long rate,
+
+                                       long max_bitrate,
+                                       long nominal_bitrate,
+                                       long min_bitrate);
+
+/**
+ * This function performs step-one of a three-step variable bitrate
+ * (quality-based) encode setup.  It functions similarly to the one-step setup
+ * performed by \ref vorbis_encode_init_vbr() but allows an application to
+ * make further encode setup tweaks using \ref vorbis_encode_ctl() before
+ * finally calling \ref vorbis_encode_setup_init to complete the setup
+ * process.
+ *
+ * Before this function is called, the \ref vorbis_info struct should be
+ * initialized by using \ref vorbis_info_init() from the libvorbis API.  After
+ * encoding, vorbis_info_clear() should be called.
+ *
+ * \param vi        Pointer to an initialized vorbis_info struct.
+ * \param channels  The number of channels to be encoded.
+ * \param rate      The sampling rate of the source audio.
+ * \param quality   Desired quality level, currently from -0.1 to 1.0 (lo to hi).
+ *
+ * \return Zero for success, and negative values for failure.
+ *
+ * \retval  0          Success
+ * \retval  OV_EFAULT  Internal logic fault; indicates a bug or heap/stack corruption.
+ * \retval  OV_EINVAL  Invalid setup request, eg, out of range argument.
+ * \retval  OV_EIMPL   Unimplemented mode; unable to comply with quality level request.
+ */
+extern int vorbis_encode_setup_vbr(vorbis_info *vi,
+                                  long channels,
+                                  long rate,
+
+                                  float quality
+                                  );
+
+/**
+ * This is the primary function within libvorbisenc for setting up variable
+ * bitrate ("quality" based) modes.
+ *
+ *
+ * Before this function is called, the vorbis_info struct should be
+ * initialized by using vorbis_info_init() from the libvorbis API. After
+ * encoding, vorbis_info_clear() should be called.
+ *
+ * \param vi           Pointer to an initialized vorbis_info struct.
+ * \param channels     The number of channels to be encoded.
+ * \param rate         The sampling rate of the source audio.
+ * \param base_quality Desired quality level, currently from -0.1 to 1.0 (lo to hi).
+ *
+ *
+ * \return Zero for success, or a negative number for failure.
+ *
+ * \retval 0           Success
+ * \retval OV_EFAULT   Internal logic fault; indicates a bug or heap/stack corruption.
+ * \retval OV_EINVAL   Invalid setup request, eg, out of range argument.
+ * \retval OV_EIMPL    Unimplemented mode; unable to comply with quality level request.
+ */
+extern int vorbis_encode_init_vbr(vorbis_info *vi,
+                                  long channels,
+                                  long rate,
+
+                                  float base_quality
+                                  );
+
+/**
+ * This function performs the last stage of three-step encoding setup, as
+ * described in the API overview under managed bitrate modes.
+ *
+ * Before this function is called, the \ref vorbis_info struct should be
+ * initialized by using vorbis_info_init() from the libvorbis API, one of
+ * \ref vorbis_encode_setup_managed() or \ref vorbis_encode_setup_vbr() called to
+ * initialize the high-level encoding setup, and \ref vorbis_encode_ctl()
+ * called if necessary to make encoding setup changes.
+ * vorbis_encode_setup_init() finalizes the highlevel encoding structure into
+ * a complete encoding setup after which the application may make no further
+ * setup changes.
+ *
+ * After encoding, vorbis_info_clear() should be called.
+ *
+ * \param vi Pointer to an initialized \ref vorbis_info struct.
+ *
+ * \return Zero for success, and negative values for failure.
+ *
+ * \retval  0           Success.
+ * \retval  OV_EFAULT  Internal logic fault; indicates a bug or heap/stack corruption.
+ *
+ * \retval OV_EINVAL   Attempt to use vorbis_encode_setup_init() without first
+ * calling one of vorbis_encode_setup_managed() or vorbis_encode_setup_vbr() to
+ * initialize the high-level encoding setup
+ *
+ */
+extern int vorbis_encode_setup_init(vorbis_info *vi);
+
+/**
+ * This function implements a generic interface to miscellaneous encoder
+ * settings similar to the classic UNIX 'ioctl()' system call.  Applications
+ * may use vorbis_encode_ctl() to query or set bitrate management or quality
+ * mode details by using one of several \e request arguments detailed below.
+ * vorbis_encode_ctl() must be called after one of
+ * vorbis_encode_setup_managed() or vorbis_encode_setup_vbr().  When used
+ * to modify settings, \ref vorbis_encode_ctl() must be called before \ref
+ * vorbis_encode_setup_init().
+ *
+ * \param vi      Pointer to an initialized vorbis_info struct.
+ *
+ * \param number Specifies the desired action; See \ref encctlcodes "the list
+ * of available requests".
+ *
+ * \param arg void * pointing to a data structure matching the request
+ * argument.
+ *
+ * \retval 0          Success. Any further return information (such as the result of a
+ * query) is placed into the storage pointed to by *arg.
+ *
+ * \retval OV_EINVAL  Invalid argument, or an attempt to modify a setting after
+ * calling vorbis_encode_setup_init().
+ *
+ * \retval OV_EIMPL   Unimplemented or unknown request
+ */
+extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
+
+/**
+ * \deprecated This is a deprecated interface. Please use vorbis_encode_ctl()
+ * with the \ref ovectl_ratemanage2_arg struct and \ref
+ * OV_ECTL_RATEMANAGE2_GET and \ref OV_ECTL_RATEMANAGE2_SET calls in new code.
+ *
+ * The \ref ovectl_ratemanage_arg structure is used with vorbis_encode_ctl()
+ * and the \ref OV_ECTL_RATEMANAGE_GET, \ref OV_ECTL_RATEMANAGE_SET, \ref
+ * OV_ECTL_RATEMANAGE_AVG, \ref OV_ECTL_RATEMANAGE_HARD calls in order to
+ * query and modify specifics of the encoder's bitrate management
+ * configuration.
+*/
+struct ovectl_ratemanage_arg {
+  int    management_active; /**< nonzero if bitrate management is active*/
+/** hard lower limit (in kilobits per second) below which the stream bitrate
+    will never be allowed for any given bitrate_hard_window seconds of time.*/
+  long   bitrate_hard_min;
+/** hard upper limit (in kilobits per second) above which the stream bitrate
+    will never be allowed for any given bitrate_hard_window seconds of time.*/
+  long   bitrate_hard_max;
+/** the window period (in seconds) used to regulate the hard bitrate minimum
+    and maximum*/
+  double bitrate_hard_window;
+/** soft lower limit (in kilobits per second) below which the average bitrate
+    tracker will start nudging the bitrate higher.*/
+  long   bitrate_av_lo;
+/** soft upper limit (in kilobits per second) above which the average bitrate
+    tracker will start nudging the bitrate lower.*/
+  long   bitrate_av_hi;
+/** the window period (in seconds) used to regulate the average bitrate
+    minimum and maximum.*/
+  double bitrate_av_window;
+/** Regulates the relative centering of the average and hard windows; in
+    libvorbis 1.0 and 1.0.1, the hard window regulation overlapped but
+    followed the average window regulation. In libvorbis 1.1 a bit-reservoir
+    interface replaces the old windowing interface; the older windowing
+    interface is simulated and this field has no effect.*/
+  double bitrate_av_window_center;
+};
+
+/**
+ * \name struct ovectl_ratemanage2_arg
+ *
+ * The ovectl_ratemanage2_arg structure is used with vorbis_encode_ctl() and
+ * the OV_ECTL_RATEMANAGE2_GET and OV_ECTL_RATEMANAGE2_SET calls in order to
+ * query and modify specifics of the encoder's bitrate management
+ * configuration.
+ *
+*/
+struct ovectl_ratemanage2_arg {
+  int    management_active; /**< nonzero if bitrate management is active */
+/** Lower allowed bitrate limit in kilobits per second */
+  long   bitrate_limit_min_kbps;
+/** Upper allowed bitrate limit in kilobits per second */
+  long   bitrate_limit_max_kbps;
+  long   bitrate_limit_reservoir_bits; /**<Size of the bitrate reservoir in bits */
+/** Regulates the bitrate reservoir's preferred fill level in a range from 0.0
+ * to 1.0; 0.0 tries to bank bits to buffer against future bitrate spikes, 1.0
+ * buffers against future sudden drops in instantaneous bitrate. Default is
+ * 0.1
+ */
+  double bitrate_limit_reservoir_bias;
+/** Average bitrate setting in kilobits per second */
+  long   bitrate_average_kbps;
+/** Slew rate limit setting for average bitrate adjustment; sets the minimum
+ *  time in seconds the bitrate tracker may swing from one extreme to the
+ *  other when boosting or damping average bitrate.
+ */
+  double bitrate_average_damping;
+};
+
+
+/**
+ * \name vorbis_encode_ctl() codes
+ *
+ * \anchor encctlcodes
+ *
+ * These values are passed as the \c number parameter of vorbis_encode_ctl().
+ * The type of the referent of that function's \c arg pointer depends on these
+ * codes.
+ */
+/*@{*/
+
+/**
+ * Query the current encoder bitrate management setting.
+ *
+ *Argument: <tt>struct ovectl_ratemanage2_arg *</tt>
+ *
+ * Used to query the current encoder bitrate management setting. Also used to
+ * initialize fields of an ovectl_ratemanage2_arg structure for use with
+ * \ref OV_ECTL_RATEMANAGE2_SET.
+ */
+#define OV_ECTL_RATEMANAGE2_GET      0x14
+
+/**
+ * Set the current encoder bitrate management settings.
+ *
+ * Argument: <tt>struct ovectl_ratemanage2_arg *</tt>
+ *
+ * Used to set the current encoder bitrate management settings to the values
+ * listed in the ovectl_ratemanage2_arg. Passing a NULL pointer will disable
+ * bitrate management.
+*/
+#define OV_ECTL_RATEMANAGE2_SET      0x15
+
+/**
+ * Returns the current encoder hard-lowpass setting (kHz) in the double
+ * pointed to by arg.
+ *
+ * Argument: <tt>double *</tt>
+*/
+#define OV_ECTL_LOWPASS_GET          0x20
+
+/**
+ *  Sets the encoder hard-lowpass to the value (kHz) pointed to by arg. Valid
+ *  lowpass settings range from 2 to 99.
+ *
+ * Argument: <tt>double *</tt>
+*/
+#define OV_ECTL_LOWPASS_SET          0x21
+
+/**
+ *  Returns the current encoder impulse block setting in the double pointed
+ *  to by arg.
+ *
+ * Argument: <tt>double *</tt>
+*/
+#define OV_ECTL_IBLOCK_GET           0x30
+
+/**
+ *  Sets the impulse block bias to the the value pointed to by arg.
+ *
+ * Argument: <tt>double *</tt>
+ *
+ *  Valid range is -15.0 to 0.0 [default]. A negative impulse block bias will
+ *  direct to encoder to use more bits when incoding short blocks that contain
+ *  strong impulses, thus improving the accuracy of impulse encoding.
+ */
+#define OV_ECTL_IBLOCK_SET           0x31
+
+/**
+ *  Returns the current encoder coupling setting in the int pointed
+ *  to by arg.
+ *
+ * Argument: <tt>int *</tt>
+*/
+#define OV_ECTL_COUPLING_GET         0x40
+
+/**
+ *  Enables/disables channel coupling in multichannel encoding according to arg.
+ *
+ * Argument: <tt>int *</tt>
+ *
+ *  Zero disables channel coupling for multichannel inputs, nonzer enables
+ *  channel coupling.  Setting has no effect on monophonic encoding or
+ *  multichannel counts that do not offer coupling.  At present, coupling is
+ *  available for stereo and 5.1 encoding.
+ */
+#define OV_ECTL_COUPLING_SET         0x41
+
+  /* deprecated rate management supported only for compatibility */
+
+/**
+ * Old interface to querying bitrate management settings.
+ *
+ * Deprecated after move to bit-reservoir style management in 1.1 rendered
+ * this interface partially obsolete.
+
+ * \deprecated Please use \ref OV_ECTL_RATEMANAGE2_GET instead.
+ *
+ * Argument: <tt>struct ovectl_ratemanage_arg *</tt>
+ */
+#define OV_ECTL_RATEMANAGE_GET       0x10
+/**
+ * Old interface to modifying bitrate management settings.
+ *
+ *  deprecated after move to bit-reservoir style management in 1.1 rendered
+ *  this interface partially obsolete.
+ *
+ * \deprecated Please use \ref OV_ECTL_RATEMANAGE2_SET instead.
+ *
+ * Argument: <tt>struct ovectl_ratemanage_arg *</tt>
+ */
+#define OV_ECTL_RATEMANAGE_SET       0x11
+/**
+ * Old interface to setting average-bitrate encoding mode.
+ *
+ * Deprecated after move to bit-reservoir style management in 1.1 rendered
+ * this interface partially obsolete.
+ *
+ *  \deprecated Please use \ref OV_ECTL_RATEMANAGE2_SET instead.
+ *
+ * Argument: <tt>struct ovectl_ratemanage_arg *</tt>
+ */
+#define OV_ECTL_RATEMANAGE_AVG       0x12
+/**
+ * Old interface to setting bounded-bitrate encoding modes.
+ *
+ * deprecated after move to bit-reservoir style management in 1.1 rendered
+ * this interface partially obsolete.
+ *
+ *  \deprecated Please use \ref OV_ECTL_RATEMANAGE2_SET instead.
+ *
+ * Argument: <tt>struct ovectl_ratemanage_arg *</tt>
+ */
+#define OV_ECTL_RATEMANAGE_HARD      0x13
+
+/*@}*/
+
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
similarity index 59%
rename from vorbis/vorbisfile.h
rename to vorbis/include/vorbis/vorbisfile.h
index 71ca86f..5662611 100644 (file)
@@ -5,13 +5,12 @@
  * 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-2001             *
- * by the XIPHOPHORUS Company http://www.xiph.org/                  *
+ * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
  *                                                                  *
  ********************************************************************
 
  function: stdio-based convenience library for opening/seeking/decoding
- last mod: $Id: vorbisfile.h,v 1.20 2003/08/18 05:34:01 xiphmont Exp $
 
  ********************************************************************/
 
@@ -27,11 +26,11 @@ extern "C"
 #include "codec.h"
 
 /* The function prototypes for the callbacks are basically the same as for
- * the stdio functions fread, fseek, fclose, ftell. 
+ * the stdio functions fread, fseek, fclose, ftell.
  * The one difference is that the FILE * arguments have been replaced with
  * a void * - this is to be used as a pointer to whatever internal data these
  * functions might need. In the stdio case, it's just a FILE * cast to a void *
- * 
+ *
  * If you use other functions, check the docs for these functions and return
  * the right values. For seek_func(), you *MUST* return -1 if the stream is
  * unseekable
@@ -43,6 +42,65 @@ typedef struct {
   long   (*tell_func)  (void *datasource);
 } ov_callbacks;
 
+#ifndef OV_EXCLUDE_STATIC_CALLBACKS
+
+/* a few sets of convenient callbacks, especially for use under
+ * Windows where ov_open_callbacks() should always be used instead of
+ * ov_open() to avoid problems with incompatible crt.o version linking
+ * issues. */
+
+static int _ov_header_fseek_wrap(FILE *f,ogg_int64_t off,int whence){
+  if(f==NULL)return(-1);
+
+#ifdef __MINGW32__
+  return fseeko64(f,off,whence);
+#elif defined (_WIN32)
+  return _fseeki64(f,off,whence);
+#else
+  return fseek(f,off,whence);
+#endif
+}
+
+/* These structs below (OV_CALLBACKS_DEFAULT etc) are defined here as
+ * static data. That means that every file which includes this header
+ * will get its own copy of these structs whether it uses them or
+ * not unless it #defines OV_EXCLUDE_STATIC_CALLBACKS.
+ * These static symbols are essential on platforms such as Windows on
+ * which several different versions of stdio support may be linked to
+ * by different DLLs, and we need to be certain we know which one
+ * we're using (the same one as the main application).
+ */
+
+static ov_callbacks OV_CALLBACKS_DEFAULT = {
+  (size_t (*)(void *, size_t, size_t, void *))  fread,
+  (int (*)(void *, ogg_int64_t, int))           _ov_header_fseek_wrap,
+  (int (*)(void *))                             fclose,
+  (long (*)(void *))                            ftell
+};
+
+static ov_callbacks OV_CALLBACKS_NOCLOSE = {
+  (size_t (*)(void *, size_t, size_t, void *))  fread,
+  (int (*)(void *, ogg_int64_t, int))           _ov_header_fseek_wrap,
+  (int (*)(void *))                             NULL,
+  (long (*)(void *))                            ftell
+};
+
+static ov_callbacks OV_CALLBACKS_STREAMONLY = {
+  (size_t (*)(void *, size_t, size_t, void *))  fread,
+  (int (*)(void *, ogg_int64_t, int))           NULL,
+  (int (*)(void *))                             fclose,
+  (long (*)(void *))                            NULL
+};
+
+static ov_callbacks OV_CALLBACKS_STREAMONLY_NOCLOSE = {
+  (size_t (*)(void *, size_t, size_t, void *))  fread,
+  (int (*)(void *, ogg_int64_t, int))           NULL,
+  (int (*)(void *))                             NULL,
+  (long (*)(void *))                            NULL
+};
+
+#endif
+
 #define  NOTOPEN   0
 #define  PARTOPEN  1
 #define  OPENED    2
@@ -54,7 +112,7 @@ typedef struct OggVorbis_File {
   int              seekable;
   ogg_int64_t      offset;
   ogg_int64_t      end;
-  ogg_sync_state   oy; 
+  ogg_sync_state   oy;
 
   /* If the FILE handle isn't seekable (eg, a pipe), only the current
      stream appears */
@@ -63,8 +121,8 @@ typedef struct OggVorbis_File {
   ogg_int64_t     *dataoffsets;
   long            *serialnos;
   ogg_int64_t     *pcmlengths; /* overloaded to maintain binary
-                                 compatability; x2 size, stores both
-                                 beginning and end values */
+                                  compatibility; x2 size, stores both
+                                  beginning and end values */
   vorbis_info     *vi;
   vorbis_comment  *vc;
 
@@ -86,14 +144,16 @@ typedef struct OggVorbis_File {
 
 } OggVorbis_File;
 
+
 extern int ov_clear(OggVorbis_File *vf);
-extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
+extern int ov_fopen(const char *path,OggVorbis_File *vf);
+extern int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes);
 extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
-               char *initial, long ibytes, ov_callbacks callbacks);
+                const char *initial, long ibytes, ov_callbacks callbacks);
 
-extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
+extern int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes);
 extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
-               char *initial, long ibytes, ov_callbacks callbacks);
+                const char *initial, long ibytes, ov_callbacks callbacks);
 extern int ov_test_open(OggVorbis_File *vf);
 
 extern long ov_bitrate(OggVorbis_File *vf,int i);
@@ -126,9 +186,12 @@ extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
 extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
 
 extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
-                         int *bitstream);
+                          int *bitstream);
+extern long ov_read_filter(OggVorbis_File *vf,char *buffer,int length,
+                          int bigendianp,int word,int sgned,int *bitstream,
+                          void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param);
 extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
-                   int bigendianp,int word,int sgned,int *bitstream);
+                    int bigendianp,int word,int sgned,int *bitstream);
 extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
 
 extern int ov_halfrate(OggVorbis_File *vf,int flag);
@@ -140,4 +203,3 @@ extern int ov_halfrate_p(OggVorbis_File *vf);
 
 #endif
 
-
diff --git a/vorbis/lib/analysis.c b/vorbis/lib/analysis.c
new file mode 100644 (file)
index 0000000..0e11a16
--- /dev/null
@@ -0,0 +1,119 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: single-block PCM analysis mode dispatch
+
+ ********************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "scales.h"
+#include "os.h"
+#include "misc.h"
+
+/* decides between modes, dispatches to the appropriate mapping. */
+int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
+  int ret,i;
+  vorbis_block_internal *vbi=vb->internal;
+
+  vb->glue_bits=0;
+  vb->time_bits=0;
+  vb->floor_bits=0;
+  vb->res_bits=0;
+
+  /* first things first.  Make sure encode is ready */
+  for(i=0;i<PACKETBLOBS;i++)
+    oggpack_reset(vbi->packetblob[i]);
+
+  /* we only have one mapping type (0), and we let the mapping code
+     itself figure out what soft mode to use.  This allows easier
+     bitrate management */
+
+  if((ret=_mapping_P[0]->forward(vb)))
+    return(ret);
+
+  if(op){
+    if(vorbis_bitrate_managed(vb))
+      /* The app is using a bitmanaged mode... but not using the
+         bitrate management interface. */
+      return(OV_EINVAL);
+
+    op->packet=oggpack_get_buffer(&vb->opb);
+    op->bytes=oggpack_bytes(&vb->opb);
+    op->b_o_s=0;
+    op->e_o_s=vb->eofflag;
+    op->granulepos=vb->granulepos;
+    op->packetno=vb->sequence; /* for sake of completeness */
+  }
+  return(0);
+}
+
+#ifdef ANALYSIS
+int analysis_noisy=1;
+
+/* there was no great place to put this.... */
+void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
+  int j;
+  FILE *of;
+  char buffer[80];
+
+  sprintf(buffer,"%s_%d.m",base,i);
+  of=fopen(buffer,"w");
+
+  if(!of)perror("failed to open data dump file");
+
+  for(j=0;j<n;j++){
+    if(bark){
+      float b=toBARK((4000.f*j/n)+.25);
+      fprintf(of,"%f ",b);
+    }else
+      if(off!=0)
+        fprintf(of,"%f ",(double)(j+off)/8000.);
+      else
+        fprintf(of,"%f ",(double)j);
+
+    if(dB){
+      float val;
+      if(v[j]==0.)
+        val=-140.;
+      else
+        val=todB(v+j);
+      fprintf(of,"%f\n",val);
+    }else{
+      fprintf(of,"%f\n",v[j]);
+    }
+  }
+  fclose(of);
+}
+
+void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
+                      ogg_int64_t off){
+  if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
+}
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
diff --git a/vorbis/lib/backends.h b/vorbis/lib/backends.h
new file mode 100644 (file)
index 0000000..22809d4
--- /dev/null
@@ -0,0 +1,143 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: libvorbis backend and mapping structures; needed for
+           static mode headers
+
+ ********************************************************************/
+
+/* this is exposed up here because we need it for static modes.
+   Lookups for each backend aren't exposed because there's no reason
+   to do so */
+
+#ifndef _vorbis_backend_h_
+#define _vorbis_backend_h_
+
+#include "codec_internal.h"
+
+/* this would all be simpler/shorter with templates, but.... */
+/* Floor backend generic *****************************************/
+typedef struct{
+  void                   (*pack)  (vorbis_info_floor *,oggpack_buffer *);
+  vorbis_info_floor     *(*unpack)(vorbis_info *,oggpack_buffer *);
+  vorbis_look_floor     *(*look)  (vorbis_dsp_state *,vorbis_info_floor *);
+  void (*free_info) (vorbis_info_floor *);
+  void (*free_look) (vorbis_look_floor *);
+  void *(*inverse1)  (struct vorbis_block *,vorbis_look_floor *);
+  int   (*inverse2)  (struct vorbis_block *,vorbis_look_floor *,
+                     void *buffer,float *);
+} vorbis_func_floor;
+
+typedef struct{
+  int   order;
+  long  rate;
+  long  barkmap;
+
+  int   ampbits;
+  int   ampdB;
+
+  int   numbooks; /* <= 16 */
+  int   books[16];
+
+  float lessthan;     /* encode-only config setting hacks for libvorbis */
+  float greaterthan;  /* encode-only config setting hacks for libvorbis */
+
+} vorbis_info_floor0;
+
+
+#define VIF_POSIT 63
+#define VIF_CLASS 16
+#define VIF_PARTS 31
+typedef struct{
+  int   partitions;                /* 0 to 31 */
+  int   partitionclass[VIF_PARTS]; /* 0 to 15 */
+
+  int   class_dim[VIF_CLASS];        /* 1 to 8 */
+  int   class_subs[VIF_CLASS];       /* 0,1,2,3 (bits: 1<<n poss) */
+  int   class_book[VIF_CLASS];       /* subs ^ dim entries */
+  int   class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
+
+
+  int   mult;                      /* 1 2 3 or 4 */
+  int   postlist[VIF_POSIT+2];    /* first two implicit */
+
+
+  /* encode side analysis parameters */
+  float maxover;
+  float maxunder;
+  float maxerr;
+
+  float twofitweight;
+  float twofitatten;
+
+  int   n;
+
+} vorbis_info_floor1;
+
+/* Residue backend generic *****************************************/
+typedef struct{
+  void                 (*pack)  (vorbis_info_residue *,oggpack_buffer *);
+  vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
+  vorbis_look_residue *(*look)  (vorbis_dsp_state *,
+                                 vorbis_info_residue *);
+  void (*free_info)    (vorbis_info_residue *);
+  void (*free_look)    (vorbis_look_residue *);
+  long **(*class)      (struct vorbis_block *,vorbis_look_residue *,
+                        int **,int *,int);
+  int  (*forward)      (oggpack_buffer *,struct vorbis_block *,
+                        vorbis_look_residue *,
+                        int **,int *,int,long **,int);
+  int  (*inverse)      (struct vorbis_block *,vorbis_look_residue *,
+                        float **,int *,int);
+} vorbis_func_residue;
+
+typedef struct vorbis_info_residue0{
+/* block-partitioned VQ coded straight residue */
+  long  begin;
+  long  end;
+
+  /* first stage (lossless partitioning) */
+  int    grouping;         /* group n vectors per partition */
+  int    partitions;       /* possible codebooks for a partition */
+  int    partvals;         /* partitions ^ groupbook dim */
+  int    groupbook;        /* huffbook for partitioning */
+  int    secondstages[64]; /* expanded out to pointers in lookup */
+  int    booklist[512];    /* list of second stage books */
+
+  const int classmetric1[64];
+  const int classmetric2[64];
+} vorbis_info_residue0;
+
+/* Mapping backend generic *****************************************/
+typedef struct{
+  void                 (*pack)  (vorbis_info *,vorbis_info_mapping *,
+                                 oggpack_buffer *);
+  vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
+  void (*free_info)    (vorbis_info_mapping *);
+  int  (*forward)      (struct vorbis_block *vb);
+  int  (*inverse)      (struct vorbis_block *vb,vorbis_info_mapping *);
+} vorbis_func_mapping;
+
+typedef struct vorbis_info_mapping0{
+  int   submaps;  /* <= 16 */
+  int   chmuxlist[256];   /* up to 256 channels in a Vorbis stream */
+
+  int   floorsubmap[16];   /* [mux] submap to floors */
+  int   residuesubmap[16]; /* [mux] submap to residue */
+
+  int   coupling_steps;
+  int   coupling_mag[256];
+  int   coupling_ang[256];
+
+} vorbis_info_mapping0;
+
+#endif
diff --git a/vorbis/lib/barkmel.c b/vorbis/lib/barkmel.c
new file mode 100644 (file)
index 0000000..4b19935
--- /dev/null
@@ -0,0 +1,63 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: bark scale utility
+
+ ********************************************************************/
+
+#include <stdio.h>
+#include "scales.h"
+int main(){
+  int i;
+  double rate;
+  for(i=64;i<32000;i*=2){
+    rate=48000.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=44100.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=32000.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=22050.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=16000.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=11025.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+    rate=8000.f;
+    fprintf(stderr,"rate=%gHz, block=%d, f(1)=%.2gHz bark(1)=%.2g (of %.2g)\n\n",
+            rate,i,rate/2 / (i/2),toBARK(rate/2 /(i/2)),toBARK(rate/2));
+
+
+  }
+  {
+    float i;
+    int j;
+    for(i=0.,j=0;i<28;i+=1,j++){
+      fprintf(stderr,"(%d) bark=%f %gHz (%d of 128)\n",
+              j,i,fromBARK(i),(int)(fromBARK(i)/22050.*128.));
+    }
+  }
+  return(0);
+}
+
diff --git a/vorbis/lib/bitrate.c b/vorbis/lib/bitrate.c
new file mode 100644 (file)
index 0000000..9605514
--- /dev/null
@@ -0,0 +1,252 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: bitrate tracking and management
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "os.h"
+#include "misc.h"
+#include "bitrate.h"
+
+/* compute bitrate tracking setup  */
+void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
+  codec_setup_info *ci=vi->codec_setup;
+  bitrate_manager_info *bi=&ci->bi;
+
+  memset(bm,0,sizeof(*bm));
+
+  if(bi && (bi->reservoir_bits>0)){
+    long ratesamples=vi->rate;
+    int  halfsamples=ci->blocksizes[0]>>1;
+
+    bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
+    bm->managed=1;
+
+    bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
+    bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
+    bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
+
+    bm->avgfloat=PACKETBLOBS/2;
+
+    /* not a necessary fix, but one that leads to a more balanced
+       typical initialization */
+    {
+      long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
+      bm->minmax_reservoir=desired_fill;
+      bm->avg_reservoir=desired_fill;
+    }
+
+  }
+}
+
+void vorbis_bitrate_clear(bitrate_manager_state *bm){
+  memset(bm,0,sizeof(*bm));
+  return;
+}
+
+int vorbis_bitrate_managed(vorbis_block *vb){
+  vorbis_dsp_state      *vd=vb->vd;
+  private_state         *b=vd->backend_state;
+  bitrate_manager_state *bm=&b->bms;
+
+  if(bm && bm->managed)return(1);
+  return(0);
+}
+
+/* finish taking in the block we just processed */
+int vorbis_bitrate_addblock(vorbis_block *vb){
+  vorbis_block_internal *vbi=vb->internal;
+  vorbis_dsp_state      *vd=vb->vd;
+  private_state         *b=vd->backend_state;
+  bitrate_manager_state *bm=&b->bms;
+  vorbis_info           *vi=vd->vi;
+  codec_setup_info      *ci=vi->codec_setup;
+  bitrate_manager_info  *bi=&ci->bi;
+
+  int  choice=rint(bm->avgfloat);
+  long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+  long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
+  long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
+  int  samples=ci->blocksizes[vb->W]>>1;
+  long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
+  if(!bm->managed){
+    /* not a bitrate managed stream, but for API simplicity, we'll
+       buffer the packet to keep the code path clean */
+
+    if(bm->vb)return(-1); /* one has been submitted without
+                             being claimed */
+    bm->vb=vb;
+    return(0);
+  }
+
+  bm->vb=vb;
+
+  /* look ahead for avg floater */
+  if(bm->avg_bitsper>0){
+    double slew=0.;
+    long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
+    double slewlimit= 15./bi->slew_damp;
+
+    /* choosing a new floater:
+       if we're over target, we slew down
+       if we're under target, we slew up
+
+       choose slew as follows: look through packetblobs of this frame
+       and set slew as the first in the appropriate direction that
+       gives us the slew we want.  This may mean no slew if delta is
+       already favorable.
+
+       Then limit slew to slew max */
+
+    if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
+      while(choice>0 && this_bits>avg_target_bits &&
+            bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
+        choice--;
+        this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+      }
+    }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
+      while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
+            bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
+        choice++;
+        this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+      }
+    }
+
+    slew=rint(choice-bm->avgfloat)/samples*vi->rate;
+    if(slew<-slewlimit)slew=-slewlimit;
+    if(slew>slewlimit)slew=slewlimit;
+    choice=rint(bm->avgfloat+= slew/vi->rate*samples);
+    this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+  }
+
+
+
+  /* enforce min(if used) on the current floater (if used) */
+  if(bm->min_bitsper>0){
+    /* do we need to force the bitrate up? */
+    if(this_bits<min_target_bits){
+      while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
+        choice++;
+        if(choice>=PACKETBLOBS)break;
+        this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+      }
+    }
+  }
+
+  /* enforce max (if used) on the current floater (if used) */
+  if(bm->max_bitsper>0){
+    /* do we need to force the bitrate down? */
+    if(this_bits>max_target_bits){
+      while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
+        choice--;
+        if(choice<0)break;
+        this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+      }
+    }
+  }
+
+  /* Choice of packetblobs now made based on floater, and min/max
+     requirements. Now boundary check extreme choices */
+
+  if(choice<0){
+    /* choosing a smaller packetblob is insufficient to trim bitrate.
+       frame will need to be truncated */
+    long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
+    bm->choice=choice=0;
+
+    if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
+
+      oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
+      this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+    }
+  }else{
+    long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
+    if(choice>=PACKETBLOBS)
+      choice=PACKETBLOBS-1;
+
+    bm->choice=choice;
+
+    /* prop up bitrate according to demand. pad this frame out with zeroes */
+    minsize-=oggpack_bytes(vbi->packetblob[choice]);
+    while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
+    this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
+
+  }
+
+  /* now we have the final packet and the final packet size.  Update statistics */
+  /* min and max reservoir */
+  if(bm->min_bitsper>0 || bm->max_bitsper>0){
+
+    if(max_target_bits>0 && this_bits>max_target_bits){
+      bm->minmax_reservoir+=(this_bits-max_target_bits);
+    }else if(min_target_bits>0 && this_bits<min_target_bits){
+      bm->minmax_reservoir+=(this_bits-min_target_bits);
+    }else{
+      /* inbetween; we want to take reservoir toward but not past desired_fill */
+      if(bm->minmax_reservoir>desired_fill){
+        if(max_target_bits>0){ /* logical bulletproofing against initialization state */
+          bm->minmax_reservoir+=(this_bits-max_target_bits);
+          if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
+        }else{
+          bm->minmax_reservoir=desired_fill;
+        }
+      }else{
+        if(min_target_bits>0){ /* logical bulletproofing against initialization state */
+          bm->minmax_reservoir+=(this_bits-min_target_bits);
+          if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
+        }else{
+          bm->minmax_reservoir=desired_fill;
+        }
+      }
+    }
+  }
+
+  /* avg reservoir */
+  if(bm->avg_bitsper>0){
+    long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
+    bm->avg_reservoir+=this_bits-avg_target_bits;
+  }
+
+  return(0);
+}
+
+int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
+  private_state         *b=vd->backend_state;
+  bitrate_manager_state *bm=&b->bms;
+  vorbis_block          *vb=bm->vb;
+  int                    choice=PACKETBLOBS/2;
+  if(!vb)return 0;
+
+  if(op){
+    vorbis_block_internal *vbi=vb->internal;
+
+    if(vorbis_bitrate_managed(vb))
+      choice=bm->choice;
+
+    op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
+    op->bytes=oggpack_bytes(vbi->packetblob[choice]);
+    op->b_o_s=0;
+    op->e_o_s=vb->eofflag;
+    op->granulepos=vb->granulepos;
+    op->packetno=vb->sequence; /* for sake of completeness */
+  }
+
+  bm->vb=0;
+  return(1);
+}
diff --git a/vorbis/lib/bitrate.h b/vorbis/lib/bitrate.h
new file mode 100644 (file)
index 0000000..655a68c
--- /dev/null
@@ -0,0 +1,58 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: bitrate tracking and management
+
+ ********************************************************************/
+
+#ifndef _V_BITRATE_H_
+#define _V_BITRATE_H_
+
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "os.h"
+
+/* encode side bitrate tracking */
+typedef struct bitrate_manager_state {
+  int            managed;
+
+  long           avg_reservoir;
+  long           minmax_reservoir;
+  long           avg_bitsper;
+  long           min_bitsper;
+  long           max_bitsper;
+
+  long           short_per_long;
+  double         avgfloat;
+
+  vorbis_block  *vb;
+  int            choice;
+} bitrate_manager_state;
+
+typedef struct bitrate_manager_info{
+  long           avg_rate;
+  long           min_rate;
+  long           max_rate;
+  long           reservoir_bits;
+  double         reservoir_bias;
+
+  double         slew_damp;
+
+} bitrate_manager_info;
+
+extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
+extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
+extern int vorbis_bitrate_managed(vorbis_block *vb);
+extern int vorbis_bitrate_addblock(vorbis_block *vb);
+extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
+
+#endif
diff --git a/vorbis/lib/block.c b/vorbis/lib/block.c
new file mode 100644 (file)
index 0000000..db245b3
--- /dev/null
@@ -0,0 +1,1046 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: PCM data vector blocking, windowing and dis/reassembly
+
+ Handle windowing, overlap-add, etc of the PCM vectors.  This is made
+ more amusing by Vorbis' current two allowed block sizes.
+
+ ********************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+
+#include "window.h"
+#include "mdct.h"
+#include "lpc.h"
+#include "registry.h"
+#include "misc.h"
+
+/* pcm accumulator examples (not exhaustive):
+
+ <-------------- lW ---------------->
+                   <--------------- W ---------------->
+:            .....|.....       _______________         |
+:        .'''     |     '''_---      |       |\        |
+:.....'''         |_____--- '''......|       | \_______|
+:.................|__________________|_______|__|______|
+                  |<------ Sl ------>|      > Sr <     |endW
+                  |beginSl           |endSl  |  |endSr
+                  |beginW            |endlW  |beginSr
+
+
+                      |< lW >|
+                   <--------------- W ---------------->
+                  |   |  ..  ______________            |
+                  |   | '  `/        |     ---_        |
+                  |___.'___/`.       |         ---_____|
+                  |_______|__|_______|_________________|
+                  |      >|Sl|<      |<------ Sr ----->|endW
+                  |       |  |endSl  |beginSr          |endSr
+                  |beginW |  |endlW
+                  mult[0] |beginSl                     mult[n]
+
+ <-------------- lW ----------------->
+                          |<--W-->|
+:            ..............  ___  |   |
+:        .'''             |`/   \ |   |
+:.....'''                 |/`....\|...|
+:.........................|___|___|___|
+                          |Sl |Sr |endW
+                          |   |   |endSr
+                          |   |beginSr
+                          |   |endSl
+                          |beginSl
+                          |beginW
+*/
+
+/* block abstraction setup *********************************************/
+
+#ifndef WORD_ALIGN
+#define WORD_ALIGN 8
+#endif
+
+int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
+  int i;
+  memset(vb,0,sizeof(*vb));
+  vb->vd=v;
+  vb->localalloc=0;
+  vb->localstore=NULL;
+  if(v->analysisp){
+    vorbis_block_internal *vbi=
+      vb->internal=_ogg_calloc(1,sizeof(vorbis_block_internal));
+    vbi->ampmax=-9999;
+
+    for(i=0;i<PACKETBLOBS;i++){
+      if(i==PACKETBLOBS/2){
+        vbi->packetblob[i]=&vb->opb;
+      }else{
+        vbi->packetblob[i]=
+          _ogg_calloc(1,sizeof(oggpack_buffer));
+      }
+      oggpack_writeinit(vbi->packetblob[i]);
+    }
+  }
+
+  return(0);
+}
+
+void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
+  bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
+  if(bytes+vb->localtop>vb->localalloc){
+    /* can't just _ogg_realloc... there are outstanding pointers */
+    if(vb->localstore){
+      struct alloc_chain *link=_ogg_malloc(sizeof(*link));
+      vb->totaluse+=vb->localtop;
+      link->next=vb->reap;
+      link->ptr=vb->localstore;
+      vb->reap=link;
+    }
+    /* highly conservative */
+    vb->localalloc=bytes;
+    vb->localstore=_ogg_malloc(vb->localalloc);
+    vb->localtop=0;
+  }
+  {
+    void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
+    vb->localtop+=bytes;
+    return ret;
+  }
+}
+
+/* reap the chain, pull the ripcord */
+void _vorbis_block_ripcord(vorbis_block *vb){
+  /* reap the chain */
+  struct alloc_chain *reap=vb->reap;
+  while(reap){
+    struct alloc_chain *next=reap->next;
+    _ogg_free(reap->ptr);
+    memset(reap,0,sizeof(*reap));
+    _ogg_free(reap);
+    reap=next;
+  }
+  /* consolidate storage */
+  if(vb->totaluse){
+    vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
+    vb->localalloc+=vb->totaluse;
+    vb->totaluse=0;
+  }
+
+  /* pull the ripcord */
+  vb->localtop=0;
+  vb->reap=NULL;
+}
+
+int vorbis_block_clear(vorbis_block *vb){
+  int i;
+  vorbis_block_internal *vbi=vb->internal;
+
+  _vorbis_block_ripcord(vb);
+  if(vb->localstore)_ogg_free(vb->localstore);
+
+  if(vbi){
+    for(i=0;i<PACKETBLOBS;i++){
+      oggpack_writeclear(vbi->packetblob[i]);
+      if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
+    }
+    _ogg_free(vbi);
+  }
+  memset(vb,0,sizeof(*vb));
+  return(0);
+}
+
+/* Analysis side code, but directly related to blocking.  Thus it's
+   here and not in analysis.c (which is for analysis transforms only).
+   The init is here because some of it is shared */
+
+static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
+  int i;
+  codec_setup_info *ci=vi->codec_setup;
+  private_state *b=NULL;
+  int hs;
+
+  if(ci==NULL||
+     ci->modes<=0||
+     ci->blocksizes[0]<64||
+     ci->blocksizes[1]<ci->blocksizes[0]){
+    return 1;
+  }
+  hs=ci->halfrate_flag;
+
+  memset(v,0,sizeof(*v));
+  b=v->backend_state=_ogg_calloc(1,sizeof(*b));
+
+  v->vi=vi;
+  b->modebits=ov_ilog(ci->modes-1);
+
+  b->transform[0]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
+  b->transform[1]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
+
+  /* MDCT is tranform 0 */
+
+  b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
+  b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
+  mdct_init(b->transform[0][0],ci->blocksizes[0]>>hs);
+  mdct_init(b->transform[1][0],ci->blocksizes[1]>>hs);
+
+  /* Vorbis I uses only window type 0 */
+  /* note that the correct computation below is technically:
+       b->window[0]=ov_ilog(ci->blocksizes[0]-1)-6;
+       b->window[1]=ov_ilog(ci->blocksizes[1]-1)-6;
+    but since blocksizes are always powers of two,
+    the below is equivalent.
+   */
+  b->window[0]=ov_ilog(ci->blocksizes[0])-7;
+  b->window[1]=ov_ilog(ci->blocksizes[1])-7;
+
+  if(encp){ /* encode/decode differ here */
+
+    /* analysis always needs an fft */
+    drft_init(&b->fft_look[0],ci->blocksizes[0]);
+    drft_init(&b->fft_look[1],ci->blocksizes[1]);
+
+    /* finish the codebooks */
+    if(!ci->fullbooks){
+      ci->fullbooks=_ogg_calloc(ci->books,sizeof(*ci->fullbooks));
+      for(i=0;i<ci->books;i++)
+        vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
+    }
+
+    b->psy=_ogg_calloc(ci->psys,sizeof(*b->psy));
+    for(i=0;i<ci->psys;i++){
+      _vp_psy_init(b->psy+i,
+                   ci->psy_param[i],
+                   &ci->psy_g_param,
+                   ci->blocksizes[ci->psy_param[i]->blockflag]/2,
+                   vi->rate);
+    }
+
+    v->analysisp=1;
+  }else{
+    /* finish the codebooks */
+    if(!ci->fullbooks){
+      ci->fullbooks=_ogg_calloc(ci->books,sizeof(*ci->fullbooks));
+      for(i=0;i<ci->books;i++){
+        if(ci->book_param[i]==NULL)
+          goto abort_books;
+        if(vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]))
+          goto abort_books;
+        /* decode codebooks are now standalone after init */
+        vorbis_staticbook_destroy(ci->book_param[i]);
+        ci->book_param[i]=NULL;
+      }
+    }
+  }
+
+  /* initialize the storage vectors. blocksize[1] is small for encode,
+     but the correct size for decode */
+  v->pcm_storage=ci->blocksizes[1];
+  v->pcm=_ogg_malloc(vi->channels*sizeof(*v->pcm));
+  v->pcmret=_ogg_malloc(vi->channels*sizeof(*v->pcmret));
+  {
+    int i;
+    for(i=0;i<vi->channels;i++)
+      v->pcm[i]=_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
+  }
+
+  /* all 1 (large block) or 0 (small block) */
+  /* explicitly set for the sake of clarity */
+  v->lW=0; /* previous window size */
+  v->W=0;  /* current window size */
+
+  /* all vector indexes */
+  v->centerW=ci->blocksizes[1]/2;
+
+  v->pcm_current=v->centerW;
+
+  /* initialize all the backend lookups */
+  b->flr=_ogg_calloc(ci->floors,sizeof(*b->flr));
+  b->residue=_ogg_calloc(ci->residues,sizeof(*b->residue));
+
+  for(i=0;i<ci->floors;i++)
+    b->flr[i]=_floor_P[ci->floor_type[i]]->
+      look(v,ci->floor_param[i]);
+
+  for(i=0;i<ci->residues;i++)
+    b->residue[i]=_residue_P[ci->residue_type[i]]->
+      look(v,ci->residue_param[i]);
+
+  return 0;
+ abort_books:
+  for(i=0;i<ci->books;i++){
+    if(ci->book_param[i]!=NULL){
+      vorbis_staticbook_destroy(ci->book_param[i]);
+      ci->book_param[i]=NULL;
+    }
+  }
+  vorbis_dsp_clear(v);
+  return -1;
+}
+
+/* arbitrary settings and spec-mandated numbers get filled in here */
+int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
+  private_state *b=NULL;
+
+  if(_vds_shared_init(v,vi,1))return 1;
+  b=v->backend_state;
+  b->psy_g_look=_vp_global_look(vi);
+
+  /* Initialize the envelope state storage */
+  b->ve=_ogg_calloc(1,sizeof(*b->ve));
+  _ve_envelope_init(b->ve,vi);
+
+  vorbis_bitrate_init(vi,&b->bms);
+
+  /* compressed audio packets start after the headers
+     with sequence number 3 */
+  v->sequence=3;
+
+  return(0);
+}
+
+void vorbis_dsp_clear(vorbis_dsp_state *v){
+  int i;
+  if(v){
+    vorbis_info *vi=v->vi;
+    codec_setup_info *ci=(vi?vi->codec_setup:NULL);
+    private_state *b=v->backend_state;
+
+    if(b){
+
+      if(b->ve){
+        _ve_envelope_clear(b->ve);
+        _ogg_free(b->ve);
+      }
+
+      if(b->transform[0]){
+        mdct_clear(b->transform[0][0]);
+        _ogg_free(b->transform[0][0]);
+        _ogg_free(b->transform[0]);
+      }
+      if(b->transform[1]){
+        mdct_clear(b->transform[1][0]);
+        _ogg_free(b->transform[1][0]);
+        _ogg_free(b->transform[1]);
+      }
+
+      if(b->flr){
+        if(ci)
+          for(i=0;i<ci->floors;i++)
+            _floor_P[ci->floor_type[i]]->
+              free_look(b->flr[i]);
+        _ogg_free(b->flr);
+      }
+      if(b->residue){
+        if(ci)
+          for(i=0;i<ci->residues;i++)
+            _residue_P[ci->residue_type[i]]->
+              free_look(b->residue[i]);
+        _ogg_free(b->residue);
+      }
+      if(b->psy){
+        if(ci)
+          for(i=0;i<ci->psys;i++)
+            _vp_psy_clear(b->psy+i);
+        _ogg_free(b->psy);
+      }
+
+      if(b->psy_g_look)_vp_global_free(b->psy_g_look);
+      vorbis_bitrate_clear(&b->bms);
+
+      drft_clear(&b->fft_look[0]);
+      drft_clear(&b->fft_look[1]);
+
+    }
+
+    if(v->pcm){
+      if(vi)
+        for(i=0;i<vi->channels;i++)
+          if(v->pcm[i])_ogg_free(v->pcm[i]);
+      _ogg_free(v->pcm);
+      if(v->pcmret)_ogg_free(v->pcmret);
+    }
+
+    if(b){
+      /* free header, header1, header2 */
+      if(b->header)_ogg_free(b->header);
+      if(b->header1)_ogg_free(b->header1);
+      if(b->header2)_ogg_free(b->header2);
+      _ogg_free(b);
+    }
+
+    memset(v,0,sizeof(*v));
+  }
+}
+
+float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
+  int i;
+  vorbis_info *vi=v->vi;
+  private_state *b=v->backend_state;
+
+  /* free header, header1, header2 */
+  if(b->header)_ogg_free(b->header);b->header=NULL;
+  if(b->header1)_ogg_free(b->header1);b->header1=NULL;
+  if(b->header2)_ogg_free(b->header2);b->header2=NULL;
+
+  /* Do we have enough storage space for the requested buffer? If not,
+     expand the PCM (and envelope) storage */
+
+  if(v->pcm_current+vals>=v->pcm_storage){
+    v->pcm_storage=v->pcm_current+vals*2;
+
+    for(i=0;i<vi->channels;i++){
+      v->pcm[i]=_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
+    }
+  }
+
+  for(i=0;i<vi->channels;i++)
+    v->pcmret[i]=v->pcm[i]+v->pcm_current;
+
+  return(v->pcmret);
+}
+
+static void _preextrapolate_helper(vorbis_dsp_state *v){
+  int i;
+  int order=16;
+  float *lpc=alloca(order*sizeof(*lpc));
+  float *work=alloca(v->pcm_current*sizeof(*work));
+  long j;
+  v->preextrapolate=1;
+
+  if(v->pcm_current-v->centerW>order*2){ /* safety */
+    for(i=0;i<v->vi->channels;i++){
+      /* need to run the extrapolation in reverse! */
+      for(j=0;j<v->pcm_current;j++)
+        work[j]=v->pcm[i][v->pcm_current-j-1];
+
+      /* prime as above */
+      vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
+
+#if 0
+      if(v->vi->channels==2){
+        if(i==0)
+          _analysis_output("predataL",0,work,v->pcm_current-v->centerW,0,0,0);
+        else
+          _analysis_output("predataR",0,work,v->pcm_current-v->centerW,0,0,0);
+      }else{
+        _analysis_output("predata",0,work,v->pcm_current-v->centerW,0,0,0);
+      }
+#endif
+
+      /* run the predictor filter */
+      vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
+                         order,
+                         work+v->pcm_current-v->centerW,
+                         v->centerW);
+
+      for(j=0;j<v->pcm_current;j++)
+        v->pcm[i][v->pcm_current-j-1]=work[j];
+
+    }
+  }
+}
+
+
+/* call with val<=0 to set eof */
+
+int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+
+  if(vals<=0){
+    int order=32;
+    int i;
+    float *lpc=alloca(order*sizeof(*lpc));
+
+    /* if it wasn't done earlier (very short sample) */
+    if(!v->preextrapolate)
+      _preextrapolate_helper(v);
+
+    /* We're encoding the end of the stream.  Just make sure we have
+       [at least] a few full blocks of zeroes at the end. */
+    /* actually, we don't want zeroes; that could drop a large
+       amplitude off a cliff, creating spread spectrum noise that will
+       suck to encode.  Extrapolate for the sake of cleanliness. */
+
+    vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
+    v->eofflag=v->pcm_current;
+    v->pcm_current+=ci->blocksizes[1]*3;
+
+    for(i=0;i<vi->channels;i++){
+      if(v->eofflag>order*2){
+        /* extrapolate with LPC to fill in */
+        long n;
+
+        /* make a predictor filter */
+        n=v->eofflag;
+        if(n>ci->blocksizes[1])n=ci->blocksizes[1];
+        vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
+
+        /* run the predictor filter */
+        vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
+                           v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
+      }else{
+        /* not enough data to extrapolate (unlikely to happen due to
+           guarding the overlap, but bulletproof in case that
+           assumtion goes away). zeroes will do. */
+        memset(v->pcm[i]+v->eofflag,0,
+               (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
+
+      }
+    }
+  }else{
+
+    if(v->pcm_current+vals>v->pcm_storage)
+      return(OV_EINVAL);
+
+    v->pcm_current+=vals;
+
+    /* we may want to reverse extrapolate the beginning of a stream
+       too... in case we're beginning on a cliff! */
+    /* clumsy, but simple.  It only runs once, so simple is good. */
+    if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
+      _preextrapolate_helper(v);
+
+  }
+  return(0);
+}
+
+/* do the deltas, envelope shaping, pre-echo and determine the size of
+   the next block on which to continue analysis */
+int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
+  int i;
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  private_state *b=v->backend_state;
+  vorbis_look_psy_global *g=b->psy_g_look;
+  long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
+  vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
+
+  /* check to see if we're started... */
+  if(!v->preextrapolate)return(0);
+
+  /* check to see if we're done... */
+  if(v->eofflag==-1)return(0);
+
+  /* By our invariant, we have lW, W and centerW set.  Search for
+     the next boundary so we can determine nW (the next window size)
+     which lets us compute the shape of the current block's window */
+
+  /* we do an envelope search even on a single blocksize; we may still
+     be throwing more bits at impulses, and envelope search handles
+     marking impulses too. */
+  {
+    long bp=_ve_envelope_search(v);
+    if(bp==-1){
+
+      if(v->eofflag==0)return(0); /* not enough data currently to search for a
+                                     full long block */
+      v->nW=0;
+    }else{
+
+      if(ci->blocksizes[0]==ci->blocksizes[1])
+        v->nW=0;
+      else
+        v->nW=bp;
+    }
+  }
+
+  centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
+
+  {
+    /* center of next block + next block maximum right side. */
+
+    long blockbound=centerNext+ci->blocksizes[v->nW]/2;
+    if(v->pcm_current<blockbound)return(0); /* not enough data yet;
+                                               although this check is
+                                               less strict that the
+                                               _ve_envelope_search,
+                                               the search is not run
+                                               if we only use one
+                                               block size */
+
+
+  }
+
+  /* fill in the block.  Note that for a short window, lW and nW are *short*
+     regardless of actual settings in the stream */
+
+  _vorbis_block_ripcord(vb);
+  vb->lW=v->lW;
+  vb->W=v->W;
+  vb->nW=v->nW;
+
+  if(v->W){
+    if(!v->lW || !v->nW){
+      vbi->blocktype=BLOCKTYPE_TRANSITION;
+      /*fprintf(stderr,"-");*/
+    }else{
+      vbi->blocktype=BLOCKTYPE_LONG;
+      /*fprintf(stderr,"_");*/
+    }
+  }else{
+    if(_ve_envelope_mark(v)){
+      vbi->blocktype=BLOCKTYPE_IMPULSE;
+      /*fprintf(stderr,"|");*/
+
+    }else{
+      vbi->blocktype=BLOCKTYPE_PADDING;
+      /*fprintf(stderr,".");*/
+
+    }
+  }
+
+  vb->vd=v;
+  vb->sequence=v->sequence++;
+  vb->granulepos=v->granulepos;
+  vb->pcmend=ci->blocksizes[v->W];
+
+  /* copy the vectors; this uses the local storage in vb */
+
+  /* this tracks 'strongest peak' for later psychoacoustics */
+  /* moved to the global psy state; clean this mess up */
+  if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
+  g->ampmax=_vp_ampmax_decay(g->ampmax,v);
+  vbi->ampmax=g->ampmax;
+
+  vb->pcm=_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
+  vbi->pcmdelay=_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
+  for(i=0;i<vi->channels;i++){
+    vbi->pcmdelay[i]=
+      _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
+    memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
+    vb->pcm[i]=vbi->pcmdelay[i]+beginW;
+
+    /* before we added the delay
+       vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
+       memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
+    */
+
+  }
+
+  /* handle eof detection: eof==0 means that we've not yet received EOF
+                           eof>0  marks the last 'real' sample in pcm[]
+                           eof<0  'no more to do'; doesn't get here */
+
+  if(v->eofflag){
+    if(v->centerW>=v->eofflag){
+      v->eofflag=-1;
+      vb->eofflag=1;
+      return(1);
+    }
+  }
+
+  /* advance storage vectors and clean up */
+  {
+    int new_centerNext=ci->blocksizes[1]/2;
+    int movementW=centerNext-new_centerNext;
+
+    if(movementW>0){
+
+      _ve_envelope_shift(b->ve,movementW);
+      v->pcm_current-=movementW;
+
+      for(i=0;i<vi->channels;i++)
+        memmove(v->pcm[i],v->pcm[i]+movementW,
+                v->pcm_current*sizeof(*v->pcm[i]));
+
+
+      v->lW=v->W;
+      v->W=v->nW;
+      v->centerW=new_centerNext;
+
+      if(v->eofflag){
+        v->eofflag-=movementW;
+        if(v->eofflag<=0)v->eofflag=-1;
+        /* do not add padding to end of stream! */
+        if(v->centerW>=v->eofflag){
+          v->granulepos+=movementW-(v->centerW-v->eofflag);
+        }else{
+          v->granulepos+=movementW;
+        }
+      }else{
+        v->granulepos+=movementW;
+      }
+    }
+  }
+
+  /* done */
+  return(1);
+}
+
+int vorbis_synthesis_restart(vorbis_dsp_state *v){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci;
+  int hs;
+
+  if(!v->backend_state)return -1;
+  if(!vi)return -1;
+  ci=vi->codec_setup;
+  if(!ci)return -1;
+  hs=ci->halfrate_flag;
+
+  v->centerW=ci->blocksizes[1]>>(hs+1);
+  v->pcm_current=v->centerW>>hs;
+
+  v->pcm_returned=-1;
+  v->granulepos=-1;
+  v->sequence=-1;
+  v->eofflag=0;
+  ((private_state *)(v->backend_state))->sample_count=-1;
+
+  return(0);
+}
+
+int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
+  if(_vds_shared_init(v,vi,0)){
+    vorbis_dsp_clear(v);
+    return 1;
+  }
+  vorbis_synthesis_restart(v);
+  return 0;
+}
+
+/* Unlike in analysis, the window is only partially applied for each
+   block.  The time domain envelope is not yet handled at the point of
+   calling (as it relies on the previous block). */
+
+int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  private_state *b=v->backend_state;
+  int hs=ci->halfrate_flag;
+  int i,j;
+
+  if(!vb)return(OV_EINVAL);
+  if(v->pcm_current>v->pcm_returned  && v->pcm_returned!=-1)return(OV_EINVAL);
+
+  v->lW=v->W;
+  v->W=vb->W;
+  v->nW=-1;
+
+  if((v->sequence==-1)||
+     (v->sequence+1 != vb->sequence)){
+    v->granulepos=-1; /* out of sequence; lose count */
+    b->sample_count=-1;
+  }
+
+  v->sequence=vb->sequence;
+
+  if(vb->pcm){  /* no pcm to process if vorbis_synthesis_trackonly
+                   was called on block */
+    int n=ci->blocksizes[v->W]>>(hs+1);
+    int n0=ci->blocksizes[0]>>(hs+1);
+    int n1=ci->blocksizes[1]>>(hs+1);
+
+    int thisCenter;
+    int prevCenter;
+
+    v->glue_bits+=vb->glue_bits;
+    v->time_bits+=vb->time_bits;
+    v->floor_bits+=vb->floor_bits;
+    v->res_bits+=vb->res_bits;
+
+    if(v->centerW){
+      thisCenter=n1;
+      prevCenter=0;
+    }else{
+      thisCenter=0;
+      prevCenter=n1;
+    }
+
+    /* v->pcm is now used like a two-stage double buffer.  We don't want
+       to have to constantly shift *or* adjust memory usage.  Don't
+       accept a new block until the old is shifted out */
+
+    for(j=0;j<vi->channels;j++){
+      /* the overlap/add section */
+      if(v->lW){
+        if(v->W){
+          /* large/large */
+          const float *w=_vorbis_window_get(b->window[1]-hs);
+          float *pcm=v->pcm[j]+prevCenter;
+          float *p=vb->pcm[j];
+          for(i=0;i<n1;i++)
+            pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
+        }else{
+          /* large/small */
+          const float *w=_vorbis_window_get(b->window[0]-hs);
+          float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
+          float *p=vb->pcm[j];
+          for(i=0;i<n0;i++)
+            pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
+        }
+      }else{
+        if(v->W){
+          /* small/large */
+          const float *w=_vorbis_window_get(b->window[0]-hs);
+          float *pcm=v->pcm[j]+prevCenter;
+          float *p=vb->pcm[j]+n1/2-n0/2;
+          for(i=0;i<n0;i++)
+            pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
+          for(;i<n1/2+n0/2;i++)
+            pcm[i]=p[i];
+        }else{
+          /* small/small */
+          const float *w=_vorbis_window_get(b->window[0]-hs);
+          float *pcm=v->pcm[j]+prevCenter;
+          float *p=vb->pcm[j];
+          for(i=0;i<n0;i++)
+            pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
+        }
+      }
+
+      /* the copy section */
+      {
+        float *pcm=v->pcm[j]+thisCenter;
+        float *p=vb->pcm[j]+n;
+        for(i=0;i<n;i++)
+          pcm[i]=p[i];
+      }
+    }
+
+    if(v->centerW)
+      v->centerW=0;
+    else
+      v->centerW=n1;
+
+    /* deal with initial packet state; we do this using the explicit
+       pcm_returned==-1 flag otherwise we're sensitive to first block
+       being short or long */
+
+    if(v->pcm_returned==-1){
+      v->pcm_returned=thisCenter;
+      v->pcm_current=thisCenter;
+    }else{
+      v->pcm_returned=prevCenter;
+      v->pcm_current=prevCenter+
+        ((ci->blocksizes[v->lW]/4+
+        ci->blocksizes[v->W]/4)>>hs);
+    }
+
+  }
+
+  /* track the frame number... This is for convenience, but also
+     making sure our last packet doesn't end with added padding.  If
+     the last packet is partial, the number of samples we'll have to
+     return will be past the vb->granulepos.
+
+     This is not foolproof!  It will be confused if we begin
+     decoding at the last page after a seek or hole.  In that case,
+     we don't have a starting point to judge where the last frame
+     is.  For this reason, vorbisfile will always try to make sure
+     it reads the last two marked pages in proper sequence */
+
+  if(b->sample_count==-1){
+    b->sample_count=0;
+  }else{
+    b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
+  }
+
+  if(v->granulepos==-1){
+    if(vb->granulepos!=-1){ /* only set if we have a position to set to */
+
+      v->granulepos=vb->granulepos;
+
+      /* is this a short page? */
+      if(b->sample_count>v->granulepos){
+        /* corner case; if this is both the first and last audio page,
+           then spec says the end is cut, not beginning */
+       long extra=b->sample_count-vb->granulepos;
+
+        /* we use ogg_int64_t for granule positions because a
+           uint64 isn't universally available.  Unfortunately,
+           that means granposes can be 'negative' and result in
+           extra being negative */
+        if(extra<0)
+          extra=0;
+
+        if(vb->eofflag){
+          /* trim the end */
+          /* no preceding granulepos; assume we started at zero (we'd
+             have to in a short single-page stream) */
+          /* granulepos could be -1 due to a seek, but that would result
+             in a long count, not short count */
+
+          /* Guard against corrupt/malicious frames that set EOP and
+             a backdated granpos; don't rewind more samples than we
+             actually have */
+          if(extra > (v->pcm_current - v->pcm_returned)<<hs)
+            extra = (v->pcm_current - v->pcm_returned)<<hs;
+
+          v->pcm_current-=extra>>hs;
+        }else{
+          /* trim the beginning */
+          v->pcm_returned+=extra>>hs;
+          if(v->pcm_returned>v->pcm_current)
+            v->pcm_returned=v->pcm_current;
+        }
+
+      }
+
+    }
+  }else{
+    v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
+    if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
+
+      if(v->granulepos>vb->granulepos){
+        long extra=v->granulepos-vb->granulepos;
+
+        if(extra)
+          if(vb->eofflag){
+            /* partial last frame.  Strip the extra samples off */
+
+            /* Guard against corrupt/malicious frames that set EOP and
+               a backdated granpos; don't rewind more samples than we
+               actually have */
+            if(extra > (v->pcm_current - v->pcm_returned)<<hs)
+              extra = (v->pcm_current - v->pcm_returned)<<hs;
+
+            /* we use ogg_int64_t for granule positions because a
+               uint64 isn't universally available.  Unfortunately,
+               that means granposes can be 'negative' and result in
+               extra being negative */
+            if(extra<0)
+              extra=0;
+
+            v->pcm_current-=extra>>hs;
+          } /* else {Shouldn't happen *unless* the bitstream is out of
+               spec.  Either way, believe the bitstream } */
+      } /* else {Shouldn't happen *unless* the bitstream is out of
+           spec.  Either way, believe the bitstream } */
+      v->granulepos=vb->granulepos;
+    }
+  }
+
+  /* Update, cleanup */
+
+  if(vb->eofflag)v->eofflag=1;
+  return(0);
+
+}
+
+/* pcm==NULL indicates we just want the pending samples, no more */
+int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
+  vorbis_info *vi=v->vi;
+
+  if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
+    if(pcm){
+      int i;
+      for(i=0;i<vi->channels;i++)
+        v->pcmret[i]=v->pcm[i]+v->pcm_returned;
+      *pcm=v->pcmret;
+    }
+    return(v->pcm_current-v->pcm_returned);
+  }
+  return(0);
+}
+
+int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
+  if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
+  v->pcm_returned+=n;
+  return(0);
+}
+
+/* intended for use with a specific vorbisfile feature; we want access
+   to the [usually synthetic/postextrapolated] buffer and lapping at
+   the end of a decode cycle, specifically, a half-short-block worth.
+   This funtion works like pcmout above, except it will also expose
+   this implicit buffer data not normally decoded. */
+int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  int hs=ci->halfrate_flag;
+
+  int n=ci->blocksizes[v->W]>>(hs+1);
+  int n0=ci->blocksizes[0]>>(hs+1);
+  int n1=ci->blocksizes[1]>>(hs+1);
+  int i,j;
+
+  if(v->pcm_returned<0)return 0;
+
+  /* our returned data ends at pcm_returned; because the synthesis pcm
+     buffer is a two-fragment ring, that means our data block may be
+     fragmented by buffering, wrapping or a short block not filling
+     out a buffer.  To simplify things, we unfragment if it's at all
+     possibly needed. Otherwise, we'd need to call lapout more than
+     once as well as hold additional dsp state.  Opt for
+     simplicity. */
+
+  /* centerW was advanced by blockin; it would be the center of the
+     *next* block */
+  if(v->centerW==n1){
+    /* the data buffer wraps; swap the halves */
+    /* slow, sure, small */
+    for(j=0;j<vi->channels;j++){
+      float *p=v->pcm[j];
+      for(i=0;i<n1;i++){
+        float temp=p[i];
+        p[i]=p[i+n1];
+        p[i+n1]=temp;
+      }
+    }
+
+    v->pcm_current-=n1;
+    v->pcm_returned-=n1;
+    v->centerW=0;
+  }
+
+  /* solidify buffer into contiguous space */
+  if((v->lW^v->W)==1){
+    /* long/short or short/long */
+    for(j=0;j<vi->channels;j++){
+      float *s=v->pcm[j];
+      float *d=v->pcm[j]+(n1-n0)/2;
+      for(i=(n1+n0)/2-1;i>=0;--i)
+        d[i]=s[i];
+    }
+    v->pcm_returned+=(n1-n0)/2;
+    v->pcm_current+=(n1-n0)/2;
+  }else{
+    if(v->lW==0){
+      /* short/short */
+      for(j=0;j<vi->channels;j++){
+        float *s=v->pcm[j];
+        float *d=v->pcm[j]+n1-n0;
+        for(i=n0-1;i>=0;--i)
+          d[i]=s[i];
+      }
+      v->pcm_returned+=n1-n0;
+      v->pcm_current+=n1-n0;
+    }
+  }
+
+  if(pcm){
+    int i;
+    for(i=0;i<vi->channels;i++)
+      v->pcmret[i]=v->pcm[i]+v->pcm_returned;
+    *pcm=v->pcmret;
+  }
+
+  return(n1+n-v->pcm_returned);
+
+}
+
+const float *vorbis_window(vorbis_dsp_state *v,int W){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  int hs=ci->halfrate_flag;
+  private_state *b=v->backend_state;
+
+  if(b->window[W]-1<0)return NULL;
+  return _vorbis_window_get(b->window[W]-hs);
+}
diff --git a/vorbis/lib/books/coupled/res_books_51.h b/vorbis/lib/books/coupled/res_books_51.h
new file mode 100644 (file)
index 0000000..47df4b2
--- /dev/null
@@ -0,0 +1,12273 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+ *
+ * function: static codebooks for 5.1 surround
+ *
+ ********************************************************************/
+
+static const long _vq_quantlist__44p0_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p0_l0_0[] = {
+        1, 3, 4, 7, 7, 8, 8, 9, 9, 9,10,10,10, 5, 6, 5,
+        8, 7, 9, 8, 9, 9,10, 9,11,10, 5, 5, 7, 7, 8, 8,
+        9, 9, 9, 9,10,10,11, 8, 9, 8,10, 9,10, 9,10, 9,
+       11,10,11,10, 8, 8, 9, 9,10, 9,10, 9,11,10,11,10,
+       11,10,11,11,11,11,11,11,11,11,11,11,11,11,10,11,
+       11,11,12,11,11,11,11,11,11,10,12,12,12,12,12,12,
+       12,11,12,12,12,11,11,11,12,12,12,12,12,12,12,11,
+       12,11,12,11,11,13,12,12,12,13,12,12,12,12,11,12,
+       11,11,13,13,13,12,12,12,12,12,12,11,11,11,10,13,
+       13,13,12,13,12,13,11,13,10,12,11,11,13,13,12,13,
+       12,12,12,12,11,12,11,11,11,
+};
+
+static const static_codebook _44p0_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p0_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p0_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p0_l0_1[] = {
+        1, 4, 4, 6, 6, 5, 5, 5, 7, 5, 5, 5, 5, 6, 7, 7,
+        6, 7, 7, 7, 6, 7, 7, 7, 7,
+};
+
+static const static_codebook _44p0_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p0_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p0_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p0_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p0_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p0_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p0_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p0_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p0_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p0_long[] = {
+        2, 3, 6, 7,10,14,16, 3, 2, 5, 7,11,14,17, 6, 5,
+        5, 7,10,12,14, 7, 7, 6, 6, 7, 9,13,10,11, 9, 6,
+        6, 9,11,15,15,13,10, 9,10,12,18,18,16,14,12,13,
+       16,
+};
+
+static const static_codebook _huff_book__44p0_long = {
+       2, 49,
+       (char *)_huff_lengthlist__44p0_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p0_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p0_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p0_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p2_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p2_0[] = {
+        1, 5, 5, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0,12,12, 0,
+        8, 8, 0, 9, 9, 0,12,12, 0, 8, 8, 0, 6, 6, 0,11,
+       11, 0,12,12, 0,12,12, 0,15,15, 0,11,11, 0,12,12,
+        0,15,15, 0,12,12, 0, 5, 5, 0, 5, 5, 0, 6, 6, 0,
+        7, 7, 0,11,11, 0, 6, 6, 0, 7, 7, 0,10,11, 0, 6,
+        6, 0, 7, 7, 0,11,11, 0,12,12, 0,11,11, 0,15,15,
+        0,10,10, 0,12,12, 0,15,15, 0,12,12, 0, 6, 6, 0,
+       12,12, 0,12,12, 0,12,12, 0,15,15, 0,11,11, 0,12,
+       12, 0,15,15, 0,12,12, 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,
+        0, 0, 0, 8, 8, 0,12,12, 0,12,12, 0,12,12, 0,15,
+       15, 0,12,12, 0,11,12, 0,15,16, 0,11,11, 0, 6, 6,
+        0,11,12, 0,12,12, 0,12,12, 0,16,15, 0,12,12, 0,
+       13,12, 0,15,14, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44p0_p2_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p2_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p0_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p2_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p2_1[] = {
+        1, 3, 3, 0, 9, 9, 0, 9, 9, 0,10,10, 0, 9, 9, 0,
+       10,10, 0,10,10, 0, 9, 9, 0,10,10, 0, 7, 7, 0, 7,
+        7, 0, 6, 6, 0, 8, 8, 0, 7, 7, 0, 8, 8, 0, 8, 9,
+        0, 8, 8, 0, 8, 8, 0, 7, 7, 0, 9, 9, 0, 8, 8, 0,
+       10,10, 0, 9, 9, 0,10,10, 0,10,10, 0, 9, 9, 0,10,
+       10, 0, 9, 9, 0,11,11, 0,11,11, 0,12,12, 0,11,11,
+        0,12,12, 0,13,13, 0,12,12, 0,13,12, 0, 8, 8, 0,
+       12,12, 0,12,12, 0,13,13, 0,12,12, 0,13,13, 0,13,
+       13, 0,13,13, 0,13,13, 0, 7, 7, 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, 9, 9, 0,11,11, 0,12,12, 0,13,13, 0,12,
+       12, 0,13,13, 0,13,13, 0,12,12, 0,12,12, 0, 8, 8,
+        0,12,12, 0,12,12, 0,13,13, 0,13,13, 0,13,14, 0,
+       14,13, 0,13,13, 0,13,13, 0, 7, 7, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p0_p2_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p2_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p0_p2_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p3_0[] = {
+        1, 6, 6, 7, 8, 8, 7, 8, 8, 7, 9, 9,10,12,11, 9,
+        8, 8, 7, 9, 9,11,12,12, 9, 9, 9, 6, 7, 7,10,11,
+       11,10,11,11,10,11,11,13,13,14,12,12,12,11,11,11,
+       14,14,14,12,12,12, 6, 5, 5, 9, 6, 5, 9, 6, 6, 9,
+        7, 7,12,10,10,11, 6, 6,10, 7, 7,13,10,10,12, 7,
+        7, 7, 8, 8,12,10,10,12,10,10,11,10,10,15,13,13,
+       13, 9, 9,12,11,11,16,13,13,15,11,11, 8, 7, 7,12,
+       12,12,12,11,11,12,11,11,14,14,14,14,12,12,12,12,
+       12,16,15,15,14,12,12, 0,10,10, 0,12,12, 0,12,12,
+        0,11,11, 0,14,14, 0,11,11, 0,12,12, 0,15,15, 0,
+       11,11, 8, 8, 8,13,11,11,13,10,10,13,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,14,10,10, 9, 7, 7,
+       13,11,11,13,11,11,12,11,11,16,14,14,14,12,12,13,
+       12,12,15,14,14,15,13,12, 0,11,11, 0,12,12, 0,12,
+       12, 0,12,12, 0,15,15, 0,12,12, 0,13,12, 0,14,15,
+        0,12,12,
+};
+
+static const static_codebook _44p0_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p3_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p0_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p3_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p0_p3_1[] = {
+        2, 4, 4, 8, 8,10,12,12,11,11, 9,11,11,12,13,11,
+       12,12,11,11,11,12,12,12,12,10,13,12,13,13,11,12,
+       12,13,13,11,12,12,13,13,11,12,13,13,13,11,13,13,
+       13,13,10,13,13,12,13,11,12,12,14,14,11,13,12,12,
+       12,11,12,12,13,13,11,13,13,12,12,11,13,13,13,13,
+       11,12,12,13,13,11,13,13,12,12,11,12,12,13,13,11,
+       13,13,12,12,11,13,13,13,13,11,12,12,14,14,11,13,
+       13,12,12,11,12,12,13,13,11,13,13,12,12,11,10,10,
+       10,10,12,10,10,11,11,11, 8, 8,11,11,13,10,10,10,
+       10,12,10,10,10,10,13,11,11,11,11,13,10,10,11,11,
+       13,11,11,12,12,13,11,11,11,11,13,11,11,12,12,13,
+       11,11,12,12,13,10,10,11,11,13,11,11,11,11,13,11,
+       10,11,11,13,11,11,11,11,13,11,11,11,11,13,10,10,
+       11,11,13,11,11,11,11,12,10,11,11,11,13,11,11,11,
+       11,13,11,11,11,11,13,10,10,11,11,13,11,11,11,11,
+       13,11,11,11,11,13,11,11,11,11,11,10,10,10,10,12,
+       10,10, 9, 9,12,12,12,11,11,13,12,12, 9, 9,13,12,
+       12,10,10,12,12,12,12,12,13,13,13,14,14,13,12,12,
+       11,11,13,13,13,12,12,13,12,12,11,11,13,12,13,11,
+       11,13,13,13,14,14,13,12,12,10,10,13,13,13,11,11,
+       13,12,12,10,10,13,13,13,11,11,13,13,13,14,14,13,
+       12,12,10,10,13,13,13,11,11,13,12,13,10,10,13,13,
+       13,11,11,13,13,13,14,14,13,12,12,10,10,13,13,13,
+       11,11,13,13,12,10,10,14,12,12, 8, 8,14,12,12, 9,
+        9,14,11,11, 9, 9,14,12,12, 8, 8,14,11,11, 7, 7,
+       14,13,13,10,10,15,12,12,10,10,15,13,13,10,10,15,
+       12,12, 9, 9,15,13,13,10,10,15,13,13,10,10,15,12,
+       12,10,10,15,13,13,10,10,14,12,12, 9, 9,14,13,13,
+        9, 9,14,13,13, 9, 9,15,12,12, 9, 9,15,13,13, 9,
+        9,14,12,12, 9, 9,14,13,13, 9, 9,14,13,13, 9, 9,
+       15,12,12, 9, 9,14,13,13, 9, 9,14,12,12, 9, 9,14,
+       13,13, 9, 9,13,12,12, 8, 8,13,13,13, 8, 8,14,13,
+       13, 9, 9,13,13,13, 7, 7,14,13,13, 8, 8,14,14,14,
+       10,10,14,14,14,11,11,14,14,14, 9, 9,14,14,14,10,
+       10,14,14,14, 9, 9,14,14,14,10, 9,15,14,14,11,11,
+       14,14,14, 9, 9,14,14,14,10,10,14,14,14, 9, 9,14,
+       14,14, 9, 9,15,14,14,11,11,14,14,14, 8, 8,14,14,
+       14, 9, 9,14,14,14, 8, 8,14,14,14, 9, 9,15,14,14,
+       11,11,14,14,14, 8, 8,14,14,14, 9, 9,14,14,14, 8,
+        8,12,12,12,13,13,16,15,15,11,11,16,15,16,12,12,
+       17,16,16,11,11,17,15,15,12,11,16,16,16,12,13,16,
+       15,15,13,13,16,16,16,12,12,16,16,15,13,13,16,16,
+       16,12,12,16,16,16,13,13,17,16,16,14,14,17,17,16,
+       12,12,17,16,16,13,13,17,17,16,12,13,16,16,17,13,
+       12,17,16,16,14,13,17,16,16,12,12,17,16,16,12,12,
+       17,16,17,12,12,17,17,17,13,13,16,16,16,13,14,17,
+       17,16,12,12,16,16,16,13,13,17,17,17,12,12,13,14,
+       14,10,10,16,14,14,12,12,16,15,15,14,14,16,14,14,
+       12,12,15,14,14,13,13,17,15,15,14,13,16,16,15,15,
+       15,16,15,15,14,14,16,15,15,14,14,17,15,15,14,14,
+       16,15,15,14,14,16,16,15,15,15,17,15,15,13,13,16,
+       15,15,14,14,17,15,15,13,13,17,15,15,14,14,16,15,
+       15,15,15,16,14,14,13,13,16,15,15,14,14,16,14,14,
+       13,13,17,15,15,14,14,16,16,15,15,15,17,14,14,13,
+       13,16,15,15,14,14,17,14,14,13,13,13,11,11,10,10,
+       16,14,14,13,13,15,14,14,13,13,16,14,14,12,12,16,
+       14,14,12,12,15,15,15,14,14,16,14,14,14,14,16,15,
+       14,14,14,16,14,14,14,14,16,15,15,14,13,16,15,15,
+       14,14,16,14,14,14,14,17,15,15,14,14,16,14,14,14,
+       14,16,15,15,13,14,16,15,15,14,14,16,14,14,14,14,
+       16,15,15,13,13,16,14,14,13,13,16,15,15,13,13,16,
+       15,15,14,14,16,14,14,14,14,17,15,15,13,13,16,15,
+       14,13,13,17,15,15,13,13,14,14,14, 9, 9,14,14,14,
+       17,17,14,15,15,18,18,14,14,14,18,19,14,14,14,18,
+       18,15,15,15,19,18,15,16,15,18,20,15,15,15,18,19,
+       15,15,15,19,19,15,15,15,18,20,15,15,15,18,19,15,
+       15,16,20,18,15,15,15,18,18,15,15,15,19,19,15,15,
+       15,18,19,15,15,15,18,19,15,15,15,19,19,14,15,14,
+       19,19,15,15,15,20,19,15,14,14,19,18,14,15,15,18,
+       19,15,15,16,20,20,14,14,14,18,19,15,15,15,19,18,
+       14,14,14,18,18,14,12,12, 9, 9,13,14,14,18,18,14,
+       13,13,18,19,14,14,14,18,18,14,14,14,18,18,15,15,
+       15,19,19,15,14,14,19,18,14,15,15,19,18,15,14,14,
+       18,18,15,15,15,19,18,14,15,15,19,19,15,14,14,19,
+       18,14,15,15,19,18,15,14,14,19,18,14,15,15,19,18,
+       15,15,15,21,18,15,14,14,19,18,14,15,15,18,19,14,
+       15,14,20,19,14,15,15,18,19,14,15,15,19,19,15,14,
+       14,19,20,14,15,15,18,18,14,14,14,19,19,14,15,15,
+       19,18,12,12,12,13,13,16,15,15,11,11,16,15,15,12,
+       12,16,16,16,11,11,16,15,15,11,11,16,16,16,13,13,
+       17,16,16,13,13,17,17,17,12,12,16,16,16,13,13,17,
+       16,17,13,12,15,16,16,12,12,16,15,15,13,13,17,16,
+       16,12,12,16,16,15,12,12,16,16,16,12,12,17,17,16,
+       13,12,16,16,16,13,13,17,16,16,12,12,17,16,16,12,
+       12,17,17,16,12,12,16,17,16,12,12,17,15,15,13,13,
+       17,16,16,12,12,16,16,16,12,12,16,16,16,12,12,13,
+       13,13, 9, 9,15,14,14,13,13,16,15,14,14,14,16,14,
+       14,13,13,15,14,14,13,13,17,15,15,14,14,16,15,15,
+       15,15,16,15,15,14,14,16,15,15,15,15,17,15,15,14,
+       14,16,15,15,14,14,16,15,15,15,15,17,14,15,14,14,
+       16,15,15,14,14,17,15,15,13,14,17,15,15,14,14,16,
+       15,15,15,15,17,14,14,13,13,16,15,15,14,14,17,14,
+       14,13,13,17,15,15,14,14,16,15,16,15,15,17,14,14,
+       13,13,16,15,15,14,14,18,14,14,13,13,13,11,11,11,
+       11,15,14,14,12,12,15,14,14,13,13,16,14,14,12,12,
+       16,13,14,12,12,16,15,15,13,13,16,14,14,14,14,16,
+       15,15,13,13,16,14,14,13,13,16,14,15,13,13,15,15,
+       15,13,13,16,14,14,14,13,16,14,14,13,13,16,14,14,
+       13,13,16,15,15,13,13,16,15,15,13,13,16,14,14,14,
+       14,16,15,15,12,12,16,14,14,13,13,16,15,15,12,12,
+       16,15,15,13,13,16,14,14,14,14,17,15,14,12,12,16,
+       14,14,13,13,16,15,15,12,12,14,14,14, 8, 8,14,14,
+       14,17,18,14,15,15,17,18,14,14,14,17,18,14,14,14,
+       18,18,14,15,15,18,18,14,16,15,19,19,15,15,15,18,
+       19,15,16,15,20,19,15,15,15,18,18,14,15,15,18,19,
+       15,16,16,20,19,15,15,15,19,17,14,15,15,20,18,14,
+       15,15,18,18,14,15,15,18,19,14,15,15,19,20,14,14,
+       14,18,18,14,15,15,18,19,14,14,14,18,19,14,15,15,
+       19,18,15,16,16,20,21,14,14,15,19,19,14,15,15,19,
+       19,14,14,14,19,18,13,12,12, 9, 9,13,14,14,18,19,
+       14,14,14,18,19,14,14,14,18,18,14,14,14,18,18,14,
+       15,15,19,19,15,14,14,19,18,15,15,15,19,19,15,14,
+       14,19,20,14,15,15,18,19,14,15,15,20,18,15,14,14,
+       18,18,14,15,15,18,18,14,14,14,19,19,14,15,15,18,
+       18,14,15,15,19,18,15,14,14,19,19,14,15,15,19,18,
+       15,14,14,19,18,14,14,15,18,19,14,15,15,19,18,15,
+       14,14,18,19,14,15,14,19,20,14,14,14,19,19,14,15,
+       15,19,19,12,12,12,13,13,16,16,16,11,11,16,16,16,
+       12,12,17,16,16,11,11,17,15,15,11,11,16,16,16,13,
+       13,17,15,16,13,13,16,16,16,12,12,17,16,16,13,13,
+       17,17,16,12,12,17,17,16,13,13,17,16,16,13,13,17,
+       17,17,12,12,17,16,16,13,13,17,17,17,12,12,16,16,
+       16,12,12,17,15,15,13,13,17,16,16,11,11,17,16,16,
+       12,12,16,16,16,11,11,16,17,16,12,12,17,16,16,13,
+       13,17,17,16,12,12,17,17,16,12,12,17,16,16,11,11,
+       13,14,14, 9, 9,16,14,14,13,13,16,14,15,14,14,16,
+       14,14,12,12,16,14,14,13,13,17,15,15,14,14,16,15,
+       15,15,15,17,15,15,14,14,16,15,15,14,14,17,15,15,
+       14,14,16,15,15,14,14,16,15,15,15,16,17,14,15,14,
+       14,16,15,15,14,14,17,15,15,14,14,16,15,15,14,14,
+       16,15,15,15,15,17,14,14,13,13,16,15,15,14,14,16,
+       14,14,13,13,17,15,15,14,14,16,16,15,15,15,17,14,
+       14,13,13,16,15,15,14,14,17,14,14,13,13,13,11,11,
+       10,10,16,14,14,12,12,15,13,13,13,12,16,14,14,11,
+       11,16,14,14,11,11,16,14,15,13,14,16,14,14,13,13,
+       16,15,15,13,13,16,14,14,13,13,16,15,15,13,13,16,
+       15,15,13,13,17,14,14,14,14,17,15,15,13,13,16,14,
+       15,13,13,16,15,15,13,13,16,15,15,13,13,16,14,14,
+       13,13,17,15,15,12,12,16,14,14,12,12,16,15,15,12,
+       12,16,15,15,13,13,16,14,14,13,13,17,15,15,12,12,
+       17,14,14,12,12,16,15,15,12,12,13,14,14, 8, 8,13,
+       14,14,18,18,13,15,15,17,18,14,14,14,18,19,14,14,
+       14,19,18,14,15,15,19,18,15,15,16,21,18,15,15,15,
+       19,19,14,16,16,19,19,14,15,15,18,19,14,15,15,19,
+       20,14,16,16,19,18,15,15,15,18,19,14,15,15,19,18,
+       15,15,15,18,18,15,15,15,20,18,15,16,16,20,19,14,
+       15,14,18,19,14,15,16,19,20,14,15,15,19,18,15,15,
+       15,19,18,15,16,16,20,19,15,14,14,18,18,14,15,15,
+       19,19,14,15,15,18,18,13,12,12, 8, 8,13,14,14,19,
+       18,14,13,13,20,18,14,14,14,19,18,14,13,13,18,19,
+       14,15,15,20,19,15,14,14,19,19,14,15,15,19,18,15,
+       14,14,20,20,15,15,15,19,18,14,15,15,19,18,15,14,
+       14,19,18,14,15,15,20,19,14,14,14,20,19,14,15,15,
+       19,18,15,15,15,18,18,15,14,14,18,18,14,15,15,19,
+       19,14,14,14,19,19,14,15,15,19,19,15,15,15,19,18,
+       15,14,14,20,19,15,15,15,19,19,14,14,14,20,19,14,
+       15,15,20,20,12,12,12,13,13,17,16,16,11,11,16,16,
+       15,12,12,17,16,16,11,11,17,15,15,11,11,17,17,17,
+       13,13,17,16,16,13,13,17,17,17,12,12,17,16,16,13,
+       13,17,17,16,12,13,16,17,16,13,13,17,16,15,13,13,
+       17,16,16,12,12,17,16,16,12,13,17,16,17,12,12,17,
+       17,17,12,12,17,16,15,13,13,17,16,16,12,12,17,16,
+       16,12,12,17,16,16,11,11,16,16,16,12,12,17,15,15,
+       13,13,17,16,15,11,11,16,16,16,12,12,17,16,16,11,
+       11,13,14,14, 9, 9,16,14,14,13,13,16,14,15,14,14,
+       16,14,14,12,12,16,14,14,13,13,17,15,15,14,15,16,
+       15,15,15,15,17,15,15,14,14,16,15,15,15,14,16,15,
+       15,14,14,16,15,15,14,14,16,15,16,15,15,17,15,14,
+       14,14,16,15,15,14,14,17,15,15,13,13,16,15,15,14,
+       14,16,16,16,15,15,17,14,14,13,13,16,15,15,14,14,
+       18,14,15,13,13,16,15,15,14,14,16,16,15,15,15,16,
+       14,14,13,13,16,15,15,14,14,17,14,15,13,13,13,11,
+       11,10,10,15,14,14,12,12,15,14,14,13,13,16,14,14,
+       12,12,16,13,14,12,12,16,14,15,14,13,16,14,14,14,
+       14,16,15,15,13,13,16,14,14,13,13,16,15,15,13,13,
+       15,15,15,13,13,16,14,14,14,14,17,15,15,13,13,16,
+       14,14,13,13,16,15,15,13,13,16,15,15,13,13,16,14,
+       14,13,13,17,15,15,12,12,16,14,14,12,12,16,14,15,
+       12,12,16,15,15,13,13,16,14,14,13,13,17,15,15,12,
+       12,16,14,14,12,12,16,15,15,12,12,14,14,14, 8, 8,
+       14,14,14,17,17,14,15,15,18,18,14,14,14,18,17,14,
+       14,14,18,18,14,15,15,18,20,15,16,15,19,18,15,15,
+       15,19,18,15,15,16,19,18,15,15,15,18,18,14,15,15,
+       18,18,15,16,16,18,19,15,15,15,18,18,15,15,15,19,
+       20,15,15,15,18,18,15,15,15,18,18,15,16,16,19,19,
+       15,14,15,19,19,15,15,15,19,20,14,14,15,18,18,15,
+       15,15,19,19,15,16,16,19,19,15,15,14,18,19,15,15,
+       15,20,20,15,15,14,18,18,13,12,12, 8, 8,13,14,14,
+       18,18,14,14,14,18,18,14,14,14,18,20,14,14,14,18,
+       18,14,15,15,19,18,15,14,14,18,19,15,15,15,18,19,
+       15,14,14,18,19,15,15,15,18,18,14,15,14,18,19,15,
+       14,14,21,19,15,15,15,19,18,14,14,14,19,18,14,15,
+       15,19,18,15,15,15,20,19,15,14,14,20,18,14,15,15,
+       18,19,14,14,14,19,18,14,15,15,18,19,15,15,15,18,
+       19,15,14,14,19,19,15,15,15,19,19,14,14,14,19,20,
+       14,15,15,18,19,
+};
+
+static const static_codebook _44p0_p3_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p0_p3_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p0_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_p4_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p0_p4_0[] = {
+        2, 6, 6,14,14, 6, 8, 8,14,14, 7, 7, 7,14,14, 0,
+       13,13,15,16, 0,13,13,15,15, 7, 8, 8,15,15, 9,10,
+       10,16,16, 9, 8, 8,14,15, 0,13,13,17,17, 0,13,13,
+       16,16, 8, 8, 8,15,15,12,11,11,16,16, 9, 8, 8,14,
+       14, 0,13,13,17,17, 0,13,13,15,15, 0,14,14,16,16,
+        0, 0, 0,18,19, 0,12,12,16,15, 0,16,16, 0,20, 0,
+       14,14,16,16, 0,14,14,17,17, 0, 0, 0,19,19, 0,12,
+       12,15,15, 0,18,17,21,21, 0,14,14,16,16, 5, 7, 7,
+       12,13, 9,10, 9,14,14,11,10,10,14,14, 0, 0, 0,18,
+       17, 0,20,21,18,18, 9,10,10,14,14,12,12,12,17,16,
+       12,10,10,14,14, 0,20,20,18,17, 0,21,21,17,17,11,
+       10,10,14,14,15,13,13,18,18,13,11,11,14,14, 0,20,
+        0,18,18, 0,20,21,18,17, 0,21, 0,18,19, 0, 0, 0,
+        0,21, 0,21,20,16,17, 0, 0, 0,21,21, 0, 0, 0,20,
+       18, 0,20, 0,17,18, 0, 0, 0, 0, 0, 0, 0,20,16,17,
+        0, 0, 0,20, 0, 0, 0, 0,18,18, 6, 6, 6,13,13, 8,
+        5, 5,11,11, 9, 6, 6,13,13, 0, 9, 9,12,12, 0,10,
+       10,14,14, 9, 7, 7,13,13,12, 9, 9,13,13,10, 6, 6,
+       13,13, 0,10,10,14,14, 0,10,10,13,13, 9, 7, 7,13,
+       13,13,10,10,13,13,11, 6, 6,13,13, 0,10,10,15,15,
+        0,10,10,13,13, 0,12,11,15,15, 0,20,19,17,16, 0,
+        9, 9,13,13, 0,13,13,20,19, 0,11,11,13,13, 0,11,
+       11,15,15, 0,20,19,17,17, 0,10,10,13,13, 0,14,15,
+        0,21, 0,12,12,13,13, 0,10,10,12,12, 0,11,11,15,
+       15, 0,11,11,15,15, 0,15,15,20,20, 0,16,16, 0, 0,
+        0,11,11,15,15, 0,14,14,17,17, 0,11,11,15,15, 0,
+       15,15,20,21, 0,16,16,21,21, 0,12,12,15,15, 0,15,
+       15,18,20, 0,11,11,16,15, 0,15,15,21,21, 0,16,16,
+        0,21, 0,16,16, 0, 0, 0, 0, 0, 0, 0, 0,14,14,21,
+       21, 0,17,18, 0, 0, 0,16,17,20, 0, 0,16,16, 0, 0,
+        0, 0, 0, 0, 0, 0,15,15,20,20, 0,19,18, 0,21, 0,
+       18,17, 0, 0, 0,10,10,11,11, 0,10,10,10,10, 0,11,
+       11,12,12, 0,11,11, 9, 9, 0,13,13,12,12, 0,11,11,
+       12,12, 0,13,13,12,12, 0,10,10,12,12, 0,12,12,13,
+       13, 0,12,12,12,12, 0,11,11,12,12, 0,13,13,12,12,
+        0,10,10,12,12, 0,13,13,13,13, 0,12,12,12,12, 0,
+       14,13,13,13, 0,19,21,15,15, 0,12,11,12,12, 0,16,
+       15,19,19, 0,13,13,11,11, 0,13,13,13,13, 0, 0,21,
+       15,16, 0,12,12,12,12, 0,16,16,19,21, 0,13,13,12,
+       12, 7, 7, 7,16,16,11, 9, 9,16,16,12, 9, 9,16,16,
+        0,13,13,16,16, 0,14,14,17,16,11, 9, 9,16,16,14,
+       12,11,17,17,13, 8, 9,15,15, 0,13,13,19,19, 0,13,
+       13,16,15,12,10,10,17,17,15,12,12,19,18,14, 9, 9,
+       17,16, 0,14,14,18, 0, 0,14,13,16,16, 0,14,15,18,
+       17, 0,21, 0,19,21, 0,12,12,16,16, 0,16,16, 0, 0,
+        0,14,14,16,16, 0,14,14,18,18, 0, 0,21,20, 0, 0,
+       13,13,16,17, 0,18,18, 0, 0, 0,15,14,17,16, 8, 7,
+        7,14,14,11,10,10,15,15,13,10,10,15,15, 0,21,20,
+       19,19, 0,21, 0,17,18,11,10,10,15,16,14,12,12,18,
+       18,14,11,11,15,14, 0,21,20,18,19, 0, 0,21,18,18,
+       12,11,11,16,16,16,14,14,18,20,14,11,11,16,15, 0,
+       20,20,19,19, 0, 0,20,18,18, 0,21, 0,18,19, 0, 0,
+        0, 0, 0, 0,20,20,17,18, 0, 0, 0,20,20, 0, 0, 0,
+       19,19, 0, 0, 0,20,18, 0, 0, 0, 0, 0, 0, 0,21,18,
+       18, 0,21,21, 0,21, 0, 0, 0,19,20,11, 9, 9,14,14,
+       13,10,10,14,14,13,11,11,15,15, 0,13,13,13,13, 0,
+       14,14,16,16,13,11,11,15,15,16,12,12,15,15,14,10,
+       10,14,14, 0,14,14,16,16, 0,14,14,15,15,13,10,10,
+       15,15,17,13,14,15,16,15,10,10,15,15, 0,14,14,17,
+       16, 0,14,14,15,15, 0,15,15,17,17, 0, 0,21,18,18,
+        0,13,13,15,15, 0,16,16,21,20, 0,14,14,15,14, 0,
+       15,14,16,17, 0, 0,20,20,19, 0,13,13,15,15, 0,19,
+       18, 0, 0, 0,15,15,15,15, 0,11,11,14,14, 0,12,12,
+       16,16, 0,12,12,16,16, 0,15,16,21,21, 0,16,17,21,
+        0, 0,12,12,17,16, 0,14,14,18,19, 0,11,11,16,16,
+        0,15,15,20,21, 0,16,16,21, 0, 0,12,12,17,16, 0,
+       15,15,19,19, 0,12,12,16,17, 0,16,15, 0, 0, 0,16,
+       16, 0, 0, 0,17,17, 0,21, 0, 0, 0, 0, 0, 0,14,15,
+       20, 0, 0,17,17, 0, 0, 0,17,17, 0, 0, 0,17,16, 0,
+        0, 0, 0, 0, 0, 0, 0,15,15, 0, 0, 0,18,18, 0, 0,
+        0,18,17, 0, 0, 0,11,11,14,14, 0,12,12,15,15, 0,
+       12,12,15,15, 0,13,13,14,14, 0,14,14,17,17, 0,12,
+       12,16,16, 0,14,14,16,16, 0,11,11,15,15, 0,13,13,
+       16,17, 0,13,13,16,16, 0,12,12,15,15, 0,14,14,17,
+       16, 0,11,11,15,15, 0,14,14,17,17, 0,13,13,16,16,
+        0,15,15,17,18, 0,21,20,20,21, 0,12,12,15,15, 0,
+       16,16,20,21, 0,14,14,15,15, 0,14,14,17,17, 0, 0,
+        0,18,19, 0,12,13,15,15, 0,18,17,21, 0, 0,14,15,
+       15,15, 8, 8, 8,16,16,12,10,10,16,16,13, 9, 9,16,
+       16, 0,14,14,18,17, 0,14,14,16,17,12,10,10,18,17,
+       14,12,11,18,18,14, 9, 9,16,16, 0,13,13,18,18, 0,
+       13,13,17,16,12, 9, 9,16,17,17,13,13,17,17,14, 9,
+        9,15,15, 0,14,14,20,19, 0,13,13,16,16, 0,15,15,
+       19,18, 0, 0, 0,20,19, 0,12,13,17,17, 0,16,16,20,
+        0, 0,14,14,16,17, 0,14,14,19,18, 0, 0, 0,20,20,
+        0,13,13,16,16, 0,18,17, 0, 0, 0,15,15,16,16, 9,
+        7, 7,14,14,12,10,10,15,15,13,10,10,15,15, 0,21,
+        0,18,19, 0,20,21,19,18,12,10,10,16,15,15,13,13,
+       18,18,14,11,11,15,15, 0, 0, 0,19,18, 0, 0,21,18,
+       18,13,11,11,15,15,16,14,14,17,19,15,11,11,15,15,
+        0,21,21,20,18, 0, 0,21,18,18, 0, 0,21,21,19, 0,
+        0, 0, 0, 0, 0,19,20,18,17, 0, 0, 0,21,21, 0,21,
+        0,20,18, 0, 0,21,19,19, 0, 0, 0, 0, 0, 0,20,21,
+       17,17, 0, 0, 0, 0, 0, 0,21, 0,18,20, 0,10,10,14,
+       14, 0,11,11,15,15, 0,11,11,15,15, 0,14,14,15,15,
+        0,15,15,16,16, 0,11,12,16,16, 0,13,13,16,16, 0,
+       11,11,15,15, 0,14,14,17,17, 0,14,14,15,15, 0,11,
+       11,16,15, 0,14,14,15,15, 0,11,11,15,15, 0,15,15,
+       17,17, 0,14,14,15,15, 0,16,16,18,18, 0, 0, 0,20,
+       19, 0,14,13,16,15, 0,17,17,21, 0, 0,15,15,15,15,
+        0,16,15,17,16, 0,20, 0,20,18, 0,13,14,15,15, 0,
+       19,18, 0,21, 0,15,15,15,15, 0,11,11,14,14, 0,12,
+       12,16,16, 0,12,12,16,16, 0,16,15,20,21, 0,17,16,
+        0, 0, 0,12,12,16,16, 0,14,14,18,18, 0,11,11,16,
+       16, 0,15,15,21,20, 0,16,16, 0, 0, 0,12,12,16,17,
+        0,15,14,19,19, 0,11,12,16,16, 0,15,15,21, 0, 0,
+       16,16, 0, 0, 0,16,17, 0, 0, 0, 0, 0, 0, 0, 0,15,
+       15,21, 0, 0,17,17, 0, 0, 0,17,17, 0, 0, 0,17,16,
+        0, 0, 0, 0, 0, 0, 0, 0,15,15, 0,20, 0,19,20, 0,
+        0, 0,17,17, 0, 0, 0,12,12,15,15, 0,12,12,15,15,
+        0,12,12,16,16, 0,13,13,15,15, 0,15,15,17,17, 0,
+       13,13,17,16, 0,14,14,17,17, 0,11,11,16,16, 0,14,
+       14,17,17, 0,13,13,16,16, 0,12,12,16,16, 0,15,15,
+       16,17, 0,11,11,15,16, 0,14,14,17,17, 0,13,14,16,
+       16, 0,15,15,18,18, 0,21,20,20,19, 0,13,13,16,17,
+        0,16,16, 0, 0, 0,14,14,16,16, 0,15,15,18,18, 0,
+        0, 0,20,19, 0,13,13,16,16, 0,17,17, 0, 0, 0,14,
+       14,16,16, 0,11,11,16,16, 0,13,13,18,17, 0,13,13,
+       17,17, 0,16,16,17,17, 0,16,16,17,18, 0,12,12,17,
+       17, 0,15,15,18,18, 0,12,12,16,16, 0,16,16,19,19,
+        0,15,15,16,17, 0,12,12,17,17, 0,17,17,18,18, 0,
+       12,12,17,17, 0,16,16,19,19, 0,15,16,17,17, 0,16,
+       16,18,17, 0, 0, 0,21,21, 0,13,13,16,16, 0,17,17,
+        0,20, 0,15,15,16,17, 0,16,16,19,18, 0, 0,21,20,
+       21, 0,14,14,17,16, 0,20, 0, 0, 0, 0,15,16,16,17,
+        0, 9, 9,14,14, 0,13,13,16,16, 0,14,14,15,15, 0,
+        0,20,19,19, 0, 0, 0,19,19, 0,12,12,15,15, 0,15,
+       16,19,18, 0,14,14,15,15, 0,21, 0,18,18, 0,20, 0,
+       17,18, 0,13,13,16,16, 0,17,17,17,19, 0,14,14,16,
+       15, 0,21,20,20,19, 0, 0, 0,19,19, 0, 0, 0,19,18,
+        0, 0, 0, 0, 0, 0,20,20,17,18, 0, 0, 0,21,21, 0,
+        0, 0,18,18, 0,21, 0,18,19, 0, 0, 0, 0, 0, 0,20,
+       21,18,18, 0, 0, 0,20,21, 0, 0, 0,19,19, 0,18,18,
+       15,15, 0,20,21,17,17, 0,19,21,17,17, 0, 0, 0,17,
+       18, 0, 0, 0,20,19, 0,19,19,17,17, 0, 0, 0,18,18,
+        0,19,20,16,17, 0, 0,21,20,20, 0,19,20,19,18, 0,
+       19,20,16,16, 0, 0, 0,18,19, 0,19,20,17,17, 0, 0,
+       21, 0,20, 0,21,21,17,19, 0,20, 0,19,20, 0, 0, 0,
+       20, 0, 0,19,18,17,16, 0, 0, 0, 0, 0, 0, 0,20,17,
+       17, 0,20,21,18,20, 0, 0, 0, 0,21, 0,19,20,17,17,
+        0, 0, 0, 0, 0, 0,20,21,17,17, 0,11,11,14,14, 0,
+       13,13,16,17, 0,13,13,16,16, 0,17,17, 0,21, 0,18,
+       17,21, 0, 0,13,13,16,16, 0,15,15,18,18, 0,12,12,
+       16,16, 0,17,16,21, 0, 0,17,17, 0, 0, 0,12,12,17,
+       17, 0,17,17,19,21, 0,13,12,16,16, 0,17,17, 0, 0,
+        0,17,17, 0, 0, 0,18,17, 0,21, 0, 0, 0, 0, 0, 0,
+       15,15,20, 0, 0,20,18, 0, 0, 0,17,18, 0, 0, 0,16,
+       17, 0, 0, 0, 0, 0, 0, 0, 0,15,15, 0, 0, 0,19,19,
+        0, 0, 0,18,18, 0, 0, 0,14,14,18,18, 0,16,16, 0,
+       21, 0,16,16,21,21, 0,17,17, 0,20, 0,17,17,20, 0,
+        0,16,15, 0, 0, 0,20,20, 0, 0, 0,15,15,20,20, 0,
+       17,17,21, 0, 0,17,18,20,20, 0,15,15,20,20, 0,18,
+       18, 0, 0, 0,15,15,19,20, 0,17,18, 0, 0, 0,17,17,
+       20,20, 0,18,17,21, 0, 0, 0, 0, 0,21, 0,15,15,20,
+       20, 0,19,19, 0, 0, 0,17,17,21, 0, 0,17,17, 0, 0,
+        0, 0, 0,21, 0, 0,15,15,19,19, 0,20,21, 0, 0, 0,
+       18,17,21,21, 0,12,12,16,16, 0,14,14,17,17, 0,13,
+       13,17,18, 0,16,16,18,17, 0,16,16,18,18, 0,13,13,
+       18,18, 0,15,16,19,18, 0,13,13,16,16, 0,16,16,20,
+       18, 0,16,16,17,17, 0,12,13,17,17, 0,17,16,18,18,
+        0,12,12,16,16, 0,17,16,20,19, 0,16,16,16,16, 0,
+       16,17,18,20, 0, 0, 0,21,20, 0,14,14,17,16, 0,19,
+       18, 0,20, 0,16,16,17,16, 0,16,16,17,18, 0, 0,21,
+       21,21, 0,14,14,16,16, 0,20,20,21, 0, 0,16,16,16,
+       16, 0,10,10,14,14, 0,14,14,15,16, 0,14,14,15,15,
+        0, 0,21,18,18, 0, 0,21,18,19, 0,13,13,16,16, 0,
+       16,16,18,18, 0,14,14,15,15, 0,21, 0,18,18, 0,21,
+        0,18,18, 0,13,13,16,16, 0,17,17,19,20, 0,14,14,
+       15,15, 0, 0, 0,18,20, 0, 0,21,18,18, 0, 0,21,19,
+       18, 0, 0, 0, 0, 0, 0,20,21,18,17, 0, 0, 0,21,21,
+        0, 0, 0,19,19, 0,21, 0,18,19, 0, 0, 0, 0, 0, 0,
+       21,20,17,17, 0, 0,21,20, 0, 0, 0, 0,19,19, 0,19,
+       20,15,16, 0, 0,20,18,17, 0,20,21,17,18, 0,21, 0,
+       18,18, 0, 0, 0,19,19, 0,20,20,17,18, 0, 0, 0,18,
+       19, 0,20,20,18,17, 0, 0, 0, 0,20, 0, 0,21,17,18,
+        0,20,21,17,17, 0, 0, 0,18,18, 0,19,19,17,17, 0,
+        0, 0,21,21, 0,20,20,17,17, 0, 0, 0,21,19, 0, 0,
+        0,20,19, 0,21,20,17,18, 0, 0, 0, 0, 0, 0, 0,20,
+       18,17, 0,21,20,18,18, 0, 0, 0,20,21, 0,20,20,17,
+       17, 0, 0, 0, 0, 0, 0,20, 0,17,17, 0,11,11,13,14,
+        0,13,13,16,16, 0,13,13,16,16, 0,17,17, 0, 0, 0,
+       17,18, 0, 0, 0,13,13,16,16, 0,15,16,18,18, 0,13,
+       13,16,17, 0,16,17,20, 0, 0,17,18,20, 0, 0,13,13,
+       17,17, 0,16,16,20,21, 0,13,13,16,16, 0,17,17,21,
+        0, 0,17,18, 0, 0, 0,17,18, 0,21, 0, 0, 0, 0, 0,
+        0,15,15,20, 0, 0,19,19, 0, 0, 0,17,17, 0, 0, 0,
+       18,17,21,20, 0, 0, 0, 0, 0, 0,16,16,20,21, 0,21,
+       20, 0,21, 0,19,21, 0, 0, 0,15,15, 0, 0, 0,16,17,
+        0,19, 0,16,16, 0, 0, 0,17,17, 0, 0, 0,19,18, 0,
+        0, 0,16,16,20,20, 0,20,18,21, 0, 0,15,15,21,21,
+        0,18,18, 0, 0, 0,18,19, 0, 0, 0,16,15, 0,21, 0,
+       20,19, 0, 0, 0,16,16, 0, 0, 0,20,18, 0,21, 0,17,
+       18,21, 0, 0,18,19, 0, 0, 0, 0, 0, 0, 0, 0,16,16,
+       20,20, 0,19,20, 0, 0, 0,17,17, 0, 0, 0,18,17,20,
+       21, 0, 0, 0, 0, 0, 0,16,16, 0,20, 0,20,22, 0, 0,
+        0,18,18, 0,22,
+};
+
+static const static_codebook _44p0_p4_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p0_p4_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p0_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p4_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p0_p4_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p0_p4_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p0_p4_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p0_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_p5_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p5_0[] = {
+        1, 6, 6, 6, 8, 8, 7, 8, 8, 7, 9, 8,10,11,11, 9,
+        8, 8, 7, 8, 8,11,11,11, 9, 8, 8, 6, 7, 7,10,10,
+       10,10,10,10,10,10,10,14,13,13,12,11,11,10,10,10,
+       14,14,13,13,11,11, 6, 6, 6, 8, 5, 5, 8, 7, 7, 8,
+        7, 7,11, 9, 9, 9, 7, 7, 8, 7, 7,12,10,10,10, 7,
+        7, 7, 8, 8,12,11,11,12,10,10,11,10,10,14,13,13,
+       13,10,10,11,10,11,16,14,14,13,10,10, 7, 8, 7,12,
+       12,12,12,11,11,12,11,11,16,14,15,13,12,12,11,11,
+       11,17,15,14,14,13,13,10, 9, 9,13,11,11,13,11,11,
+       12,11,11,16,14,13,14,11,11,12,11,11,16,15,14,14,
+       11,11, 7, 8, 8,12,11,11,12,10,10,12,10,10,16,14,
+       13,13,11,11,12,10,10,16,14,14,13,10,10, 8, 8, 8,
+       12,12,12,12,11,11,12,11,11,16,14,15,14,12,12,12,
+       11,11,16,15,15,14,12,12,10,10,10,13,11,11,13,11,
+       11,12,12,12,16,14,14,14,11,11,12,11,11,17,14,15,
+       14,11,11,
+};
+
+static const static_codebook _44p0_p5_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p5_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p0_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p5_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p5_1[] = {
+        2, 7, 7, 7, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 8,
+        7, 7, 8, 8, 8, 9, 9, 9, 9, 7, 7, 6, 6, 6, 9, 7,
+        7, 9, 7, 7, 9, 8, 8,10, 8, 8,10, 8, 8,10, 8, 8,
+       10, 8, 8,10, 8, 8, 7, 6, 6, 9, 6, 6, 9, 6, 6, 9,
+        7, 7,10, 8, 8, 9, 6, 6, 9, 7, 7,10, 8, 8, 9, 7,
+        7, 7, 8, 8,11, 9, 9,11, 9, 9,11, 9, 9,12, 9, 9,
+       12, 8, 8,12, 9, 9,12,10, 9,12, 8, 8, 8, 7, 7,10,
+        9, 9,11, 9, 9,11, 9, 9,11,11,10,11, 9, 9,11,10,
+        9,11,10,11,11, 9, 9,10, 8, 8,11, 9, 9,11, 9, 9,
+       11, 9, 9,11,10,10,11, 9, 9,11, 9, 9,11,10,10,11,
+        9, 9, 9, 8, 8,12, 9, 9,12, 9, 9,11, 9, 9,12, 9,
+        9,12, 8, 8,12, 9, 9,12, 9, 9,12, 8, 8, 9, 7, 7,
+       11, 9,10,11,10, 9,11, 9, 9,11,11,11,11, 9, 9,11,
+       10,10,11,11,11,11, 9, 9,10, 9, 9,11, 9, 9,11,10,
+       10,11,10, 9,11,10,10,11, 9, 9,11,10,10,11,10,11,
+       11, 9, 9,
+};
+
+static const static_codebook _44p0_p5_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p5_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p0_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p0_p6_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p0_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p0_p6_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p0_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p0_p6_1[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p0_p6_1[] = {
+        1, 3, 2, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+       11,12,12,12,14,14,14,15,15,
+};
+
+static const static_codebook _44p0_p6_1 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p0_p6_1,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p0_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p0_p6_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p0_p6_2[] = {
+        3, 4, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p0_p6_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p0_p6_2,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p0_p6_2,
+       0
+};
+
+static const char _huff_lengthlist__44p0_short[] = {
+        3, 3, 7, 8,10,13,16, 3, 2, 5, 7, 9,13,16, 6, 4,
+        4, 6,10,14,15, 7, 5, 5, 7,10,13,14, 9, 8, 9, 9,
+        9,11,13,12,11,12, 9, 7, 8,11,14,12,10, 6, 5, 7,
+       10,
+};
+
+static const static_codebook _huff_book__44p0_short = {
+       2, 49,
+       (char *)_huff_lengthlist__44p0_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p1_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p1_l0_0[] = {
+        1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 4, 6, 5,
+        8, 6, 9, 8,10, 9,10,10,11,10, 5, 5, 6, 6, 8, 8,
+        9, 9,10,10,10,10,11, 7, 8, 8, 9, 8,10, 9,10, 9,
+       11,10,11,10, 7, 8, 8, 8,10, 9,10,10,10,10,11,10,
+       11, 9,10,10,11,11,11,11,12,11,12,11,12,11, 9,10,
+       10,11,11,11,11,11,11,11,12,11,12,11,11,11,12,12,
+       12,12,12,12,12,12,12,11,11,12,11,12,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,13,12,13,12,12,12,12,
+       12,12,12,12,12,13,13,13,13,12,13,12,12,12,12,12,
+       13,13,12,13,12,13,12,13,12,12,12,12,13,13,13,13,
+       13,13,12,12,12,12,12,11,12,
+};
+
+static const static_codebook _44p1_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p1_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p1_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p1_l0_1[] = {
+        1, 4, 4, 6, 6, 5, 5, 5, 6, 6, 5, 6, 5, 6, 6, 6,
+        6, 7, 7, 7, 6, 7, 6, 7, 7,
+};
+
+static const static_codebook _44p1_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p1_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p1_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p1_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p1_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p1_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p1_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p1_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p1_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p1_long[] = {
+        3, 3, 7, 7, 9,13,16, 3, 2, 4, 6,10,13,17, 7, 4,
+        4, 6, 9,12,14, 7, 6, 6, 5, 7, 9,12,10,10, 9, 6,
+        6, 9,12,14,14,13, 9, 8,10,11,18,18,15,13,11,10,
+       11,
+};
+
+static const static_codebook _huff_book__44p1_long = {
+       2, 49,
+       (char *)_huff_lengthlist__44p1_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p1_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p1_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p1_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p2_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p2_0[] = {
+        1, 4, 4, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0,12,12, 0,
+        8, 8, 0, 9, 9, 0,12,12, 0, 8, 8, 0, 6, 6, 0,11,
+       11, 0,11,11, 0,12,12, 0,14,14, 0,11,11, 0,12,12,
+        0,14,14, 0,11,11, 0, 6, 6, 0, 6, 5, 0, 7, 6, 0,
+        7, 7, 0,10,10, 0, 6, 6, 0, 7, 7, 0,10,10, 0, 7,
+        7, 0, 7, 7, 0,10,10, 0,11,11, 0,11,11, 0,14,14,
+        0,10,10, 0,12,12, 0,14,14, 0,12,12, 0, 6, 6, 0,
+       11,11, 0,11,11, 0,12,12, 0,14,14, 0,11,11, 0,12,
+       12, 0,15,15, 0,11,11, 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,
+        0, 0, 0, 8, 8, 0,11,11, 0,11,11, 0,12,12, 0,15,
+       15, 0,12,12, 0,11,11, 0,15,15, 0,11,11, 0, 6, 6,
+        0,11,11, 0,12,12, 0,12,12, 0,15,15, 0,11,11, 0,
+       12,12, 0,14,14, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44p1_p2_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p2_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p1_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p2_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p2_1[] = {
+        1, 3, 3, 0, 8, 8, 0, 8, 8, 0,10,10, 0, 9, 9, 0,
+       10,10, 0,10,10, 0, 9, 9, 0,10,10, 0, 7, 7, 0, 7,
+        7, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 9, 9,
+        0, 8, 8, 0, 8, 8, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0,
+       10,10, 0, 9, 9, 0, 9, 9, 0,10,10, 0, 9, 9, 0,10,
+       10, 0, 8, 8, 0,11,11, 0,11,11, 0,12,12, 0,11,11,
+        0,12,12, 0,12,12, 0,12,12, 0,12,12, 0, 8, 8, 0,
+       11,11, 0,11,11, 0,13,12, 0,12,12, 0,13,12, 0,13,
+       13, 0,12,12, 0,13,13, 0, 7, 7, 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, 8, 8, 0,11,11, 0,11,11, 0,13,12, 0,12,
+       12, 0,12,12, 0,12,12, 0,11,11, 0,12,12, 0, 8, 8,
+        0,12,12, 0,12,12, 0,13,13, 0,12,12, 0,13,13, 0,
+       13,13, 0,12,13, 0,13,13, 0, 7, 7, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p1_p2_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p2_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p1_p2_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p3_0[] = {
+        1, 6, 6, 6, 7, 7, 7, 8, 8, 7, 8, 8,10,11,11, 9,
+        8, 8, 7, 9, 9,11,12,12, 9, 8, 8, 6, 7, 7, 9,11,
+       11,10,11,11,10,11,11,13,13,13,11,12,12,10,11,11,
+       13,14,14,12,12,12, 6, 6, 6, 8, 6, 6, 8, 6, 6, 9,
+        7, 7,12,10,10,10, 6, 6, 9, 7, 7,12,10,10,11, 7,
+        6, 7, 8, 8,12,10,10,12,10,10,11,10,10,15,13,13,
+       13,10,10,12,11,11,15,13,13,14,11,11, 8, 7, 7,12,
+       11,11,12,11,11,11,11,11,14,14,14,13,12,12,12,11,
+       11,16,15,15,14,12,12, 0,10,10, 0,11,11, 0,12,12,
+        0,11,11, 0,14,14, 0,11,11, 0,11,11, 0,15,15, 0,
+       11,11, 7, 8, 8,13,10,10,12,10,10,12,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,14,10,10, 8, 7, 7,
+       12,11,11,13,11,11,12,11,11,15,14,14,14,12,12,13,
+       12,12,15,14,14,15,12,12, 0,11,11, 0,12,12, 0,12,
+       12, 0,12,12, 0,15,15, 0,12,12, 0,12,12, 0,15,14,
+        0,12,12,
+};
+
+static const static_codebook _44p1_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p3_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p1_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p3_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p1_p3_1[] = {
+        2, 3, 4, 7, 7,10,12,12,12,12,10,11,11,13,13,11,
+       12,12,11,11,12,12,12,12,12,11,13,13,13,13,12,12,
+       12,13,14,12,13,13,13,13,12,13,13,13,13,12,13,13,
+       13,13,11,13,13,13,13,12,12,12,14,14,12,13,13,12,
+       12,12,12,13,13,13,12,13,13,13,13,12,13,13,13,13,
+       12,12,12,14,14,12,13,13,12,12,12,13,13,13,13,12,
+       13,13,12,12,12,13,13,13,13,12,12,12,14,14,12,13,
+       13,12,12,12,13,13,13,13,12,13,13,12,12,10,10,11,
+       10,10,11,11,11,11,11,11, 9, 9,10,10,12,11,11,10,
+       10,12,10,10,10,10,13,12,12,12,12,13,11,11,11,11,
+       13,12,12,12,12,13,11,11,11,11,13,12,12,12,12,13,
+       12,12,12,12,13,11,11,11,11,13,12,12,12,12,13,11,
+       11,11,11,13,12,12,11,11,13,12,12,11,11,13,11,11,
+       11,11,13,12,12,11,11,13,11,11,11,11,13,12,12,11,
+       11,13,12,12,11,11,13,11,11,11,11,13,12,12,11,11,
+       13,11,11,11,11,13,12,12,11,11,11,11,11,10,10,11,
+       11,11, 9, 9,11,12,12,11,11,12,12,12, 9, 9,13,13,
+       13,10,10,13,13,13,11,11,13,13,13,14,14,13,13,13,
+       11,10,13,13,14,12,12,13,13,13,11,11,13,13,13,11,
+       11,13,13,13,14,14,13,13,13,10,10,13,13,13,11,11,
+       13,13,13,10,10,13,14,13,11,11,13,14,14,14,14,13,
+       13,13,10,10,13,14,14,11,11,13,13,13,10,10,13,14,
+       14,11,11,13,13,13,14,14,14,13,13,10,10,13,14,14,
+       11,11,13,13,13,10,10,14,12,12, 9, 9,14,12,12, 9,
+        9,14,11,11, 9, 9,14,12,12, 8, 8,14,11,11, 7, 7,
+       15,13,13,10,10,15,12,12,10,10,15,13,13,10,10,15,
+       12,12,10,10,15,13,13,10,10,15,13,13,10,10,15,12,
+       12,10,10,15,13,13,10,10,15,12,12,10,10,15,13,13,
+       10,10,15,13,13,10,10,15,12,12,10,10,15,13,13, 9,
+        9,15,12,12, 9, 9,14,13,13, 9, 9,15,13,13,10,10,
+       15,12,12,10,10,15,13,13, 9, 9,15,12,12, 9, 9,15,
+       13,13, 9, 9,13,12,12, 9, 9,13,13,13, 8, 8,13,13,
+       13, 9, 9,13,13,13, 7, 7,14,13,13, 8, 8,14,14,14,
+       10,10,15,14,14,11,11,14,14,14, 9, 9,15,14,14,10,
+       10,15,14,14, 9, 9,14,14,14,10,10,15,14,14,11,11,
+       15,14,14, 9, 9,14,14,14,10,10,14,14,14, 9, 9,15,
+       14,15,10,10,15,14,14,11,11,14,14,14, 9, 9,14,14,
+       14, 9, 9,14,14,14, 8, 8,15,14,14,10,10,15,14,14,
+       11,11,14,14,14, 9, 9,15,14,14, 9, 9,14,14,14, 8,
+        8,12,12,12,13,13,16,16,16,11,11,17,16,16,12,12,
+       17,16,16,11,11,17,16,16,11,11,17,17,16,13,13,17,
+       16,16,13,13,18,17,16,12,12,17,16,16,13,13,17,16,
+       17,12,12,18,17,17,13,13,17,16,16,14,14,18,17,17,
+       12,12,18,16,16,13,13,17,17,17,13,12,17,17,17,13,
+       13,17,16,16,13,13,18,17,17,12,12,17,16,16,13,12,
+       17,17,17,12,12,18,17,17,13,13,18,16,16,14,14,18,
+       17,17,12,12,17,17,17,13,13,18,17,18,12,12,13,14,
+       14,10,10,16,14,14,13,13,17,15,15,14,14,17,14,14,
+       12,13,16,14,14,13,13,17,15,15,14,14,16,16,16,15,
+       15,17,15,15,14,14,17,16,16,14,15,17,15,15,14,14,
+       17,15,16,14,14,17,16,16,15,15,17,15,15,13,13,17,
+       15,15,14,14,18,15,15,13,14,17,15,15,14,14,16,16,
+       16,15,15,17,15,15,13,13,17,15,15,14,14,17,15,15,
+       13,13,17,15,15,14,14,16,16,16,15,15,17,15,15,13,
+       13,17,15,15,14,14,18,15,15,13,13,13,11,11,10,10,
+       16,14,14,13,12,16,14,14,13,13,16,15,14,12,12,16,
+       14,14,12,12,16,15,15,14,14,16,14,14,14,14,17,15,
+       15,13,13,16,15,15,14,14,17,15,15,13,14,17,15,15,
+       14,14,17,15,14,14,14,17,15,15,13,13,17,15,15,14,
+       14,17,15,15,13,13,17,15,15,14,14,17,14,14,14,14,
+       17,15,15,13,13,17,15,15,13,13,17,15,15,13,13,17,
+       15,15,14,14,17,15,15,14,14,17,15,15,13,13,17,15,
+       15,13,13,17,15,15,13,13,14,14,15, 8, 8,14,14,14,
+       19,19,14,15,15,18,19,14,14,14,19,18,14,14,14,19,
+       19,15,15,15,19,18,15,16,16,19,19,15,15,15,19,19,
+       15,16,16,20,19,15,15,15,19,19,15,15,15,19,19,16,
+       16,16,20,19,15,15,15,19,18,15,16,16,20,19,15,15,
+       15,18,18,15,15,15,19,20,15,16,16,19,19,15,15,15,
+       20,19,15,15,15,20,19,15,15,15,19,18,15,15,15,19,
+       19,15,16,16,19,20,15,15,15,19,19,15,15,15,19,20,
+       15,15,15,19,19,14,12,12, 9, 9,14,14,14,19,19,14,
+       14,14,19,19,14,14,15,20,19,15,14,14,18,19,15,15,
+       15,19,19,15,15,14,20,19,15,15,15,20,19,15,15,14,
+       20,19,15,15,15,20,19,15,15,15,19,20,15,14,14,19,
+       20,15,15,15,20,20,15,14,14,20,19,15,15,15,19,19,
+       15,15,15,19,19,15,14,14,19,19,15,15,15,19,20,15,
+       15,15,20,20,15,15,15,19,19,15,15,15,20,19,16,14,
+       14,19,19,15,15,15,20,19,15,14,15,20,19,14,15,15,
+       20,19,12,12,12,13,13,16,16,16,11,11,16,16,16,12,
+       12,17,16,16,11,11,17,15,16,11,11,17,17,17,13,13,
+       18,16,17,13,13,18,17,17,13,12,17,16,17,13,13,17,
+       17,17,13,13,16,16,16,12,12,17,16,16,13,13,17,16,
+       16,12,12,17,16,16,12,13,17,17,17,12,12,17,17,17,
+       13,13,18,16,16,13,13,18,17,17,12,12,18,17,17,12,
+       12,17,17,17,12,12,17,17,17,12,12,17,16,16,13,13,
+       17,17,17,12,12,17,16,16,12,12,17,17,17,12,12,13,
+       14,14, 9, 9,16,14,14,13,13,16,15,15,14,14,17,14,
+       14,13,13,16,14,14,13,13,17,15,15,15,15,16,16,16,
+       15,15,17,15,15,14,14,17,15,15,15,15,17,15,15,14,
+       14,17,15,15,14,14,16,16,16,15,15,17,15,15,14,14,
+       17,15,15,14,14,17,15,15,14,14,17,15,15,14,14,16,
+       16,16,15,15,18,15,15,14,13,17,15,15,14,14,17,15,
+       15,13,13,17,15,15,14,14,16,16,16,15,15,17,15,15,
+       14,13,17,15,15,14,14,17,15,15,13,13,13,11,11,11,
+       11,16,14,14,12,12,16,14,14,13,13,16,15,14,12,12,
+       17,14,14,12,12,17,15,15,13,13,17,14,14,14,14,17,
+       15,15,13,13,17,14,15,14,13,17,15,15,13,13,16,15,
+       15,13,13,16,14,14,14,14,17,15,15,13,13,16,14,14,
+       13,13,16,15,15,13,13,17,15,15,13,13,17,14,14,14,
+       14,17,15,15,12,12,17,15,15,13,13,17,15,15,12,12,
+       16,15,15,13,13,17,14,14,13,14,17,15,15,12,12,17,
+       14,14,13,13,17,15,15,12,12,14,14,14, 8, 8,14,14,
+       14,18,18,14,15,15,19,19,14,14,14,19,19,14,15,14,
+       18,19,15,15,15,18,19,15,16,16,20,20,15,15,15,19,
+       20,15,16,16,19,20,15,15,15,19,20,15,15,16,19,19,
+       15,16,16,20,20,15,15,15,20,19,15,16,16,20,19,15,
+       15,15,19,20,15,15,15,19,19,15,16,16,20,19,15,15,
+       15,19,19,15,16,15,20,19,15,15,15,19,19,15,15,15,
+       19,20,15,16,16,20,20,15,15,15,19,19,15,15,15,20,
+       20,15,15,15,19,19,14,12,12, 9, 9,14,14,14,18,18,
+       14,14,14,19,20,14,14,14,18,18,14,14,14,18,19,15,
+       15,15,19,20,15,14,14,19,19,15,15,15,19,19,15,14,
+       15,19,19,15,15,15,18,20,15,15,15,19,19,15,14,14,
+       19,19,15,15,15,20,19,15,15,14,20,20,15,15,15,19,
+       19,15,15,15,19,19,15,14,14,19,19,15,15,15,19,19,
+       15,14,14,19,20,14,15,15,19,19,15,15,15,19,19,15,
+       14,14,20,19,15,15,15,19,19,15,14,14,20,19,15,15,
+       15,19,19,13,12,12,13,13,17,17,16,11,11,16,16,16,
+       12,12,17,17,16,11,11,17,16,16,11,11,17,17,17,13,
+       13,17,16,16,13,13,18,17,17,12,12,17,16,16,13,13,
+       18,17,17,12,12,18,17,17,13,13,18,16,17,13,13,17,
+       17,17,12,12,18,17,17,13,13,18,17,17,12,12,17,16,
+       17,12,12,17,16,16,13,13,17,16,16,11,11,17,16,16,
+       12,12,17,17,17,11,11,17,17,17,12,12,18,16,16,13,
+       13,18,17,17,12,11,17,16,16,12,12,18,17,17,11,11,
+       13,14,14, 9, 9,16,14,14,13,13,16,15,15,14,14,17,
+       14,14,12,12,16,14,14,13,13,17,15,15,14,14,17,16,
+       16,15,16,18,15,15,14,14,17,15,15,14,14,17,15,15,
+       14,14,18,15,15,14,14,16,16,16,15,16,18,15,15,14,
+       14,17,16,15,14,14,18,15,15,14,14,17,15,15,14,14,
+       17,16,16,15,15,18,14,15,13,13,17,15,15,14,14,18,
+       15,15,13,13,17,15,15,14,14,17,16,15,15,15,17,15,
+       15,13,13,17,15,15,14,14,18,15,15,13,13,13,11,11,
+       10,10,16,14,14,12,12,16,14,14,12,12,17,14,15,11,
+       11,17,14,14,11,11,17,15,15,13,13,17,14,14,14,13,
+       17,15,15,13,13,16,15,15,13,13,17,15,15,13,13,17,
+       15,15,13,13,17,14,14,14,14,17,15,15,13,13,17,14,
+       15,13,13,16,15,15,13,13,17,15,15,13,13,17,14,14,
+       13,13,17,15,15,12,12,16,14,14,12,12,17,15,15,12,
+       12,17,15,15,13,13,17,14,14,13,13,17,15,15,12,12,
+       17,14,14,12,12,17,15,15,12,12,13,15,14, 8, 8,14,
+       14,14,19,19,14,15,15,18,19,14,14,14,18,19,14,15,
+       14,19,19,15,16,15,19,19,15,16,16,19,20,15,15,15,
+       19,19,15,16,16,19,19,15,16,16,19,19,15,15,15,19,
+       19,15,16,16,20,20,15,15,15,19,19,15,15,15,19,19,
+       15,15,15,19,19,15,15,15,19,19,15,16,16,20,19,15,
+       15,15,19,19,15,15,15,19,19,15,15,15,19,19,15,16,
+       15,19,19,15,16,16,21,19,15,15,15,20,20,15,15,15,
+       20,21,15,15,15,19,20,14,12,12, 8, 8,14,14,14,19,
+       19,14,13,13,19,19,14,14,14,19,19,14,13,14,19,19,
+       15,15,15,20,20,15,14,14,20,19,15,15,15,19,20,15,
+       14,14,19,20,15,15,15,20,19,15,15,15,19,20,15,14,
+       14,20,20,15,15,15,20,19,15,14,14,19,19,15,15,15,
+       19,19,15,15,15,20,19,15,14,14,21,19,15,15,15,20,
+       21,15,14,14,21,19,15,15,15,19,19,15,15,15,20,20,
+       15,14,14,19,21,15,15,15,19,19,15,14,14,19,20,15,
+       15,15,19,19,13,12,12,13,13,17,16,16,11,11,17,16,
+       15,12,12,18,16,16,11,11,17,16,16,11,11,18,17,17,
+       13,13,18,16,16,13,13,17,17,17,12,13,18,17,16,13,
+       13,18,17,17,13,13,17,17,17,13,13,17,16,16,13,13,
+       18,16,17,12,12,17,16,16,13,12,17,17,17,12,12,18,
+       17,17,13,12,18,16,16,13,13,18,17,17,12,12,17,16,
+       16,12,12,17,17,17,11,11,17,16,16,12,12,17,16,16,
+       13,13,17,16,16,11,11,17,16,16,12,12,17,17,17,11,
+       11,13,14,14, 9, 9,16,14,14,13,13,16,15,15,14,14,
+       17,14,14,12,12,16,14,14,13,13,17,15,15,14,14,17,
+       15,16,15,15,17,15,15,14,14,17,15,16,14,15,18,15,
+       15,14,14,17,15,15,14,14,16,16,16,15,15,18,15,15,
+       13,14,17,15,15,14,14,18,15,15,14,14,17,15,15,14,
+       14,17,16,16,15,15,17,15,15,13,13,17,15,15,14,14,
+       18,15,15,13,13,17,15,15,14,14,17,16,16,15,15,17,
+       15,15,13,13,17,15,15,14,14,18,15,15,13,13,13,11,
+       11,10,10,16,14,14,12,12,16,14,14,13,13,17,14,14,
+       11,11,17,14,14,12,12,17,15,15,14,14,17,14,14,14,
+       14,17,15,15,13,13,17,15,14,13,13,16,15,15,13,13,
+       16,15,15,13,13,17,14,14,14,14,17,15,15,13,13,17,
+       14,14,13,13,16,15,15,13,13,16,15,15,13,13,17,14,
+       14,13,13,17,15,15,12,12,17,14,14,12,12,16,15,15,
+       12,12,17,15,15,13,13,17,14,14,13,13,17,15,15,12,
+       12,17,14,14,12,12,16,15,15,12,12,14,14,14, 8, 8,
+       14,14,14,18,18,14,15,15,19,18,14,14,14,18,18,14,
+       14,14,18,19,15,16,15,19,19,15,17,16,20,20,15,15,
+       15,19,19,15,16,16,19,19,15,15,15,19,19,15,16,15,
+       18,19,15,16,16,20,20,15,15,15,19,19,15,16,16,19,
+       20,15,15,15,19,19,15,15,16,19,19,15,16,16,20,20,
+       15,15,15,19,19,15,15,15,19,20,15,15,15,19,19,15,
+       15,15,19,19,15,16,16,20,20,15,15,15,19,20,15,16,
+       16,20,20,15,15,15,19,19,13,12,12, 8, 8,14,14,14,
+       19,20,14,14,14,19,19,14,14,14,18,19,14,14,14,19,
+       20,15,15,15,19,20,15,14,14,21,20,15,15,15,20,20,
+       15,15,14,19,19,15,15,15,19,19,15,15,15,19,19,15,
+       14,14,19,20,15,15,15,19,20,15,14,14,19,19,15,15,
+       15,19,19,15,15,15,19,19,16,14,14,19,19,15,15,15,
+       20,20,15,14,14,21,19,15,15,15,19,19,15,15,15,19,
+       20,16,14,14,19,20,15,15,15,19,19,15,14,14,19,19,
+       15,15,15,20,19,
+};
+
+static const static_codebook _44p1_p3_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p1_p3_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p1_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_p4_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p1_p4_0[] = {
+        2, 6, 6,14,14, 6, 7, 7,14,14, 7, 7, 7,14,14, 0,
+       13,13,16,16, 0,13,13,15,14, 7, 8, 8,15,15, 9,10,
+       10,16,16, 9, 8, 8,15,15, 0,13,13,17,16, 0,13,13,
+       15,16, 8, 8, 8,15,15,12,11,11,16,16, 9, 8, 8,14,
+       14, 0,13,13,17,18, 0,13,13,15,15, 0,14,14,16,16,
+        0, 0, 0,19,18, 0,12,12,16,15, 0,15,16, 0,20, 0,
+       14,14,16,16, 0,14,14,17,17, 0, 0, 0,19,18, 0,12,
+       12,15,15, 0,17,17, 0,20, 0,14,14,16,16, 5, 6, 7,
+       12,12, 9, 9, 9,14,14,10,10,10,14,14, 0,21,21,18,
+       17, 0,20,20,18,17, 9,10,10,14,14,12,12,12,16,16,
+       12,10,10,14,14, 0,20,19,18,17, 0, 0,20,17,18,11,
+       10,10,14,14,14,13,13,18,18,13,11,11,14,14, 0,20,
+       20,17,18, 0,21,21,17,17, 0,21, 0,18,18, 0, 0, 0,
+        0, 0, 0,20,19,16,17, 0, 0, 0,19,19, 0, 0, 0,18,
+       18, 0,21,21,18,18, 0, 0, 0, 0, 0, 0,20,20,16,17,
+        0, 0, 0,21,21, 0, 0, 0,18,19, 6, 6, 6,13,12, 8,
+        6, 6,11,11, 8, 6, 6,13,13, 0, 9, 9,11,11, 0,11,
+       10,14,14, 9, 7, 7,13,13,11, 9, 9,13,13,10, 6, 6,
+       13,13, 0,10,10,14,15, 0,10,10,13,13, 9, 7, 7,13,
+       13,13,10, 9,13,13,10, 6, 6,13,13, 0,10,10,15,14,
+        0,10,10,13,13, 0,11,11,15,15, 0,19,20,17,17, 0,
+        9, 9,13,13, 0,13,13,20,20, 0,11,11,13,13, 0,11,
+       11,15,15, 0,19,19,17,17, 0,10,10,13,13, 0,15,15,
+       20,20, 0,12,12,13,13, 0,10,10,12,12, 0,11,11,15,
+       15, 0,11,11,15,15, 0,15,15,20, 0, 0,16,16, 0,21,
+        0,11,11,15,15, 0,14,14,18,17, 0,11,11,15,15, 0,
+       15,16,19,20, 0,16,16,21,21, 0,12,12,15,15, 0,15,
+       14,18,18, 0,11,11,16,16, 0,15,15,21,21, 0,16,15,
+        0, 0, 0,16,16,21, 0, 0, 0, 0, 0, 0, 0,14,14,20,
+       20, 0,18,18, 0, 0, 0,16,17,21, 0, 0,16,16,21,21,
+        0, 0, 0, 0, 0, 0,15,15,21,21, 0,20,19, 0,21, 0,
+       17,17, 0, 0, 0,10,10,12,11, 0,10,10,10,11, 0,11,
+       11,12,12, 0,11,11, 9, 9, 0,13,13,11,12, 0,11,11,
+       12,12, 0,13,13,12,12, 0,10,10,12,12, 0,12,12,13,
+       13, 0,12,12,12,12, 0,11,11,12,12, 0,13,13,12,12,
+        0,10,10,12,12, 0,13,13,14,14, 0,12,12,12,12, 0,
+       14,14,14,13, 0,19,20,15,15, 0,12,11,12,12, 0,15,
+       15,21,20, 0,13,13,11,11, 0,13,13,13,13, 0,19, 0,
+       15,15, 0,12,12,12,12, 0,17,16,19, 0, 0,13,13,12,
+       12, 7, 7, 7,16,16,11, 9, 9,15,15,12, 9, 9,16,16,
+        0,13,13,15,14, 0,14,14,17,16,10, 9, 9,16,16,14,
+       11,11,17,16,12, 9, 8,15,15, 0,13,13,18,18, 0,13,
+       13,15,15,12,10,10,18,17,15,12,12,17,17,14, 9, 9,
+       16,16, 0,13,13,18,19, 0,14,13,17,16, 0,14,14,18,
+       18, 0, 0, 0,20,21, 0,12,12,16,16, 0,16,16,20,21,
+        0,14,14,17,16, 0,14,14,18,19, 0, 0, 0,19,21, 0,
+       13,13,17,17, 0,17,17, 0,21, 0,15,15,16,16, 8, 7,
+        7,14,14,11,10,10,15,15,12,10,10,15,15, 0,20,20,
+       18,18, 0, 0, 0,17,17,11,10,10,16,16,14,12,12,18,
+       17,14,11,11,15,15, 0,20,21,18,18, 0, 0,19,18,17,
+       12,10,10,16,16,17,14,14,19,19,14,11,11,15,15, 0,
+       21,21,19,19, 0,21,20,19,18, 0,21, 0,18,19, 0, 0,
+        0, 0, 0, 0,20,20,18,17, 0,21, 0, 0, 0, 0, 0, 0,
+       19,18, 0, 0, 0,18,19, 0, 0, 0, 0, 0, 0, 0,21,17,
+       18, 0, 0, 0, 0,21, 0, 0,21,18,19,11, 9, 9,14,14,
+       13,10,10,13,13,13,11,11,15,15, 0,13,13,12,12, 0,
+       15,15,16,16,13,10,10,15,15,16,12,12,15,15,15,10,
+       10,15,15, 0,14,13,16,15, 0,14,13,15,15,13,10,10,
+       15,15,18,14,14,15,15,15,10,10,14,15, 0,14,14,16,
+       16, 0,14,14,16,15, 0,15,15,17,16, 0,21, 0,18,18,
+        0,12,13,15,15, 0,16,16, 0, 0, 0,14,14,15,15, 0,
+       15,15,16,16, 0,21,20,18,18, 0,13,13,15,15, 0,19,
+       18, 0, 0, 0,15,15,15,15, 0,11,11,13,13, 0,12,12,
+       16,16, 0,12,12,16,16, 0,15,16,20, 0, 0,16,17, 0,
+        0, 0,12,12,16,16, 0,14,14,18,18, 0,11,11,16,17,
+        0,15,15,20, 0, 0,16,16, 0, 0, 0,12,12,16,16, 0,
+       15,15,19,19, 0,11,11,17,17, 0,16,16,21, 0, 0,16,
+       16, 0, 0, 0,17,17,20,20, 0, 0, 0, 0, 0, 0,15,15,
+       20, 0, 0,17,18, 0, 0, 0,17,17, 0, 0, 0,16,16, 0,
+       21, 0, 0, 0, 0, 0, 0,15,15,21, 0, 0,19,18, 0, 0,
+        0,18,17, 0, 0, 0,11,11,14,14, 0,11,11,15,15, 0,
+       12,12,16,16, 0,13,13,14,14, 0,14,14,17,17, 0,12,
+       12,16,16, 0,14,14,16,16, 0,11,11,16,15, 0,13,13,
+       16,17, 0,13,13,16,16, 0,12,12,15,16, 0,15,14,16,
+       16, 0,11,11,15,15, 0,14,14,17,17, 0,13,13,16,16,
+        0,15,14,18,18, 0,21, 0,19,19, 0,13,13,15,15, 0,
+       16,16,20,20, 0,14,14,16,15, 0,14,14,17,17, 0,21,
+        0,20,18, 0,13,13,15,15, 0,17,17, 0, 0, 0,14,14,
+       16,15, 8, 8, 8,16,16,12, 9, 9,16,16,13, 9, 9,16,
+       16, 0,14,14,18,17, 0,14,14,16,17,12,10,10,18,17,
+       14,11,11,18,18,14, 9, 9,16,16, 0,13,13,18,18, 0,
+       13,13,17,16,12, 9, 9,16,17,17,13,13,16,16,14, 9,
+        9,15,15, 0,14,14,20,20, 0,13,13,15,15, 0,15,14,
+       18,18, 0, 0, 0,20,21, 0,12,13,16,17, 0,16,16,20,
+       21, 0,14,14,16,17, 0,14,14,18,17, 0, 0, 0,20,21,
+        0,13,13,16,16, 0,19,17, 0,21, 0,14,15,16,16, 8,
+        7, 7,14,13,12,10,10,15,15,13,10,10,15,15, 0,21,
+       21,18,19, 0,20,21,18,18,12,10,10,16,15,15,12,12,
+       17,17,14,11,11,15,15, 0,21,21,19,18, 0, 0,21,17,
+       18,13,11,11,15,15,16,13,13,18,19,15,11,11,15,14,
+        0,21, 0,19,19, 0, 0,21,18,18, 0, 0,21,19,19, 0,
+        0, 0, 0, 0, 0,20,19,17,17, 0, 0, 0,21, 0, 0,21,
+        0,18,19, 0, 0,20,20,19, 0, 0, 0, 0, 0, 0,21,20,
+       18,17, 0, 0, 0, 0,20, 0, 0, 0,18,19, 0,10,10,15,
+       14, 0,11,11,14,14, 0,11,11,15,16, 0,14,14,15,15,
+        0,15,15,16,16, 0,11,11,16,16, 0,14,13,16,16, 0,
+       11,11,15,15, 0,14,14,16,16, 0,14,14,15,15, 0,11,
+       11,15,15, 0,13,13,15,15, 0,11,11,15,15, 0,15,15,
+       18,17, 0,14,14,15,15, 0,15,16,18,18, 0, 0, 0,20,
+       20, 0,14,13,16,15, 0,17,17,21, 0, 0,15,15,15,15,
+        0,16,15,17,17, 0, 0, 0,19,19, 0,13,13,15,15, 0,
+       20,19, 0, 0, 0,15,15,15,15, 0,11,11,13,13, 0,12,
+       12,16,16, 0,12,12,16,16, 0,15,15,21,21, 0,17,16,
+        0, 0, 0,12,12,16,16, 0,14,14,17,17, 0,11,11,16,
+       16, 0,15,15, 0, 0, 0,16,16,21, 0, 0,12,12,17,16,
+        0,14,15,20,20, 0,11,11,16,16, 0,15,15, 0,20, 0,
+       16,16, 0,21, 0,16,17,21, 0, 0, 0, 0, 0, 0, 0,15,
+       15, 0,21, 0,18,18, 0, 0, 0,17,16, 0, 0, 0,17,17,
+       21, 0, 0, 0, 0, 0, 0, 0,15,15, 0,20, 0,19,20,21,
+        0, 0,17,18, 0, 0, 0,12,12,15,15, 0,12,12,15,15,
+        0,12,12,16,16, 0,13,13,15,15, 0,15,15,17,17, 0,
+       13,12,17,16, 0,14,14,17,16, 0,11,11,16,16, 0,14,
+       14,17,17, 0,14,14,17,17, 0,12,12,16,16, 0,15,15,
+       17,17, 0,11,11,16,16, 0,14,14,17,17, 0,14,14,16,
+       16, 0,15,15,18,17, 0, 0, 0,19, 0, 0,13,13,16,16,
+        0,16,16, 0,21, 0,14,14,16,16, 0,15,15,18,17, 0,
+        0, 0,19,19, 0,13,13,16,16, 0,18,17, 0,21, 0,14,
+       15,16,16, 0,11,11,16,16, 0,13,13,17,17, 0,13,13,
+       17,17, 0,16,16,16,17, 0,16,16,18,18, 0,12,12,17,
+       17, 0,16,15,18,17, 0,12,12,16,16, 0,16,15,19,19,
+        0,16,15,17,17, 0,12,12,17,18, 0,16,16,18,18, 0,
+       12,12,16,16, 0,16,16,19,19, 0,15,16,17,17, 0,15,
+       16,18,18, 0, 0, 0,20,20, 0,13,13,16,16, 0,18,18,
+       21,20, 0,15,15,16,16, 0,16,16,19,18, 0, 0, 0,19,
+       20, 0,14,14,17,17, 0,19,19, 0,21, 0,15,16,16,16,
+        0, 9, 9,14,14, 0,13,13,15,15, 0,14,14,15,15, 0,
+        0,21,19,19, 0, 0,21,18,18, 0,12,12,15,15, 0,15,
+       15,18,18, 0,14,13,15,15, 0,21,21,18,19, 0,21,20,
+       18,18, 0,13,13,16,16, 0,17,17,18,19, 0,14,14,15,
+       15, 0, 0,21,19,19, 0,21,20,18,19, 0,20,20,19,19,
+        0, 0, 0, 0, 0, 0,19,20,17,17, 0, 0, 0,21,21, 0,
+       21, 0,18,20, 0,21, 0,18,21, 0, 0, 0, 0, 0, 0,21,
+       21,19,18, 0, 0, 0, 0, 0, 0, 0, 0,19,19, 0,18,18,
+       15,15, 0,18,20,17,16, 0,20, 0,17,17, 0,21, 0,17,
+       17, 0,21,20,19,20, 0,19,19,16,16, 0,21,21,17,18,
+        0,19,19,17,17, 0,20,21,21,21, 0,20,20,18,18, 0,
+       19,19,16,16, 0, 0,21,18,19, 0,18,19,16,17, 0,21,
+       21,19,20, 0,21,19,18,18, 0,21,20,19,21, 0, 0, 0,
+       20,21, 0,19,19,17,16, 0, 0, 0, 0, 0, 0,21,20,17,
+       17, 0,20,21,19,18, 0, 0, 0, 0,21, 0,19,18,16,17,
+        0, 0, 0, 0, 0, 0,20,20,17,17, 0,11,11,14,14, 0,
+       13,13,16,16, 0,13,13,16,16, 0,17,17,21, 0, 0,17,
+       18, 0, 0, 0,12,12,16,16, 0,15,15,17,18, 0,12,12,
+       16,16, 0,16,16, 0,20, 0,17,17, 0,21, 0,12,12,17,
+       17, 0,16,16,19,20, 0,12,12,17,17, 0,17,17, 0,20,
+        0,17,17, 0, 0, 0,17,17,21, 0, 0, 0, 0, 0, 0, 0,
+       15,15, 0,20, 0,19,19, 0, 0, 0,18,18, 0, 0, 0,17,
+       17, 0, 0, 0, 0, 0, 0, 0, 0,15,15, 0, 0, 0,20,19,
+        0, 0, 0,19,18, 0, 0, 0,14,14,21,19, 0,16,16,20,
+       21, 0,16,16,20,20, 0,17,17,20, 0, 0,17,17,20,20,
+        0,15,15,20,20, 0,19,18,20, 0, 0,15,15,20,20, 0,
+       17,18,21,20, 0,17,17,20,21, 0,15,15,19,19, 0,19,
+       18,21,21, 0,15,15,19,20, 0,17,18, 0, 0, 0,17,17,
+       20,20, 0,17,18,20,21, 0, 0, 0, 0, 0, 0,15,15,20,
+       20, 0,19,19, 0, 0, 0,17,17,19,21, 0,17,17, 0,21,
+        0, 0, 0, 0,21, 0,15,15,20,19, 0, 0,20, 0, 0, 0,
+       17,17,21,20, 0,12,12,16,16, 0,14,14,17,17, 0,13,
+       13,17,17, 0,16,16,17,18, 0,17,16,18,18, 0,13,13,
+       18,17, 0,15,16,19,18, 0,13,13,16,16, 0,16,16,19,
+       19, 0,16,16,17,17, 0,13,12,17,17, 0,16,16,18,17,
+        0,12,12,16,16, 0,17,17,19,18, 0,16,15,16,16, 0,
+       16,17,18,19, 0, 0, 0,20,20, 0,14,14,17,16, 0,18,
+       18,21, 0, 0,16,16,16,16, 0,16,16,18,17, 0, 0,21,
+       21,21, 0,14,14,16,16, 0,21,20,21, 0, 0,16,16,16,
+       16, 0,10,10,14,14, 0,14,14,15,16, 0,14,14,15,15,
+        0, 0,21,18,18, 0, 0,21,18,19, 0,13,13,16,16, 0,
+       16,16,18,17, 0,14,14,15,15, 0,20, 0,18,18, 0,21,
+        0,18,17, 0,13,13,16,15, 0,17,17,19,19, 0,14,14,
+       15,15, 0,20,20,18,19, 0, 0, 0,18,17, 0, 0,21,18,
+       18, 0, 0, 0, 0, 0, 0,20,21,18,17, 0, 0, 0, 0, 0,
+        0, 0, 0,19,19, 0, 0,21,18,18, 0, 0, 0, 0, 0, 0,
+       21, 0,18,17, 0, 0, 0, 0,21, 0, 0, 0,19,20, 0,19,
+       19,16,16, 0, 0,21,18,17, 0,21, 0,18,18, 0,20, 0,
+       19,18, 0,21,20,19,19, 0,21,19,17,18, 0, 0,21,19,
+       19, 0,21,19,18,18, 0,21, 0,20,18, 0, 0,21,18,18,
+        0,20,21,17,17, 0,21, 0,18,18, 0,21,19,17,17, 0,
+       21, 0, 0,20, 0, 0,20,17,18, 0, 0, 0,19,20, 0, 0,
+        0,20,19, 0,19,21,17,18, 0,21, 0, 0, 0, 0,21,21,
+       18,17, 0, 0,21,18,18, 0, 0, 0, 0,21, 0,20,19,16,
+       17, 0, 0, 0, 0, 0, 0,21,20,17,17, 0,11,11,13,13,
+        0,13,13,16,16, 0,13,13,16,16, 0,17,17, 0,21, 0,
+       18,19,21, 0, 0,12,12,16,16, 0,15,15,19,18, 0,13,
+       13,16,16, 0,16,17,21,19, 0,17,17,21,21, 0,13,13,
+       16,16, 0,16,16,20,18, 0,13,13,16,16, 0,17,17, 0,
+        0, 0,18,18, 0, 0, 0,18,17, 0,20, 0, 0, 0, 0, 0,
+        0,15,15,21,21, 0,19,18, 0, 0, 0,17,17,21,21, 0,
+       17,17, 0, 0, 0, 0, 0, 0, 0, 0,15,15,20,21, 0,20,
+       20, 0, 0, 0,19,19, 0, 0, 0,14,15,21,19, 0,16,16,
+        0,21, 0,17,16,21,21, 0,17,18,21,20, 0,18,18, 0,
+       21, 0,16,16, 0,20, 0,19,19, 0, 0, 0,16,15, 0,20,
+        0,18,18, 0, 0, 0,17,17, 0,21, 0,16,16,20,20, 0,
+       20,19, 0, 0, 0,15,16,21,22, 0,18,18, 0, 0, 0,18,
+       17, 0, 0, 0,18,18, 0, 0, 0, 0, 0, 0, 0, 0,16,16,
+       21,20, 0,19,20, 0, 0, 0,18,17,21, 0, 0,17,18, 0,
+        0, 0, 0, 0, 0, 0, 0,16,16, 0,20, 0, 0,20, 0, 0,
+        0,18,18,22, 0,
+};
+
+static const static_codebook _44p1_p4_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p1_p4_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p1_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p4_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p1_p4_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p1_p4_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p1_p4_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p1_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_p5_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p5_0[] = {
+        1, 6, 6, 7, 8, 8, 7, 8, 8, 7, 9, 8,10,11,11, 9,
+        8, 8, 7, 8, 8,11,11,11, 9, 8, 8, 6, 7, 7,10,10,
+       10,10,10,10,10,10,10,14,13,13,12,11,11,10,10,10,
+       14,14,13,12,11,11, 6, 6, 6, 8, 5, 5, 8, 7, 7, 9,
+        7, 7,11,10,10, 9, 7, 7, 9, 7, 7,12,10,10,10, 7,
+        7, 7, 8, 8,12,11,10,12,10,10,11,10,10,15,13,13,
+       13,10,10,11,10,10,17,14,13,13,10,10, 7, 7, 7,12,
+       11,12,12,11,11,12,11,11,16,14,14,13,12,12,12,11,
+       11,17,15,14,14,12,12,10, 9, 9,13,11,11,13,11,11,
+       13,11,11,17,14,13,14,11,11,12,11,11,16,15,14,14,
+       11,11, 7, 8, 8,12,11,11,12,10,10,12,10,10,15,13,
+       13,14,11,10,12,10,10,16,14,14,14,10,10, 8, 7, 7,
+       12,11,11,12,11,11,12,11,11,17,14,14,14,12,12,12,
+       11,11,16,15,15,14,12,12,10,10,10,13,11,11,13,11,
+       11,13,11,12,16,14,14,14,11,11,13,12,11,16,15,15,
+       14,11,11,
+};
+
+static const static_codebook _44p1_p5_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p5_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p1_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p5_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p5_1[] = {
+        2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 8, 8,
+        7, 7, 8, 8, 8, 9, 8, 8, 9, 7, 7, 6, 6, 6, 9, 8,
+        7, 9, 7, 7, 9, 8, 8,10, 8, 8,10, 8, 8,10, 8, 8,
+       10, 8, 8,10, 8, 8, 7, 6, 6, 9, 6, 6, 9, 7, 7, 9,
+        7, 7,10, 8, 8, 9, 6, 6, 9, 7, 7,10, 8, 8, 9, 7,
+        7, 7, 8, 8,11, 9, 9,11, 9, 9,11, 8, 9,12, 9, 9,
+       12, 8, 8,11, 9, 9,12, 9, 9,12, 8, 8, 8, 7, 7,10,
+        9, 9,10,10, 9,10, 9, 9,11,10,10,11, 9, 9,11, 9,
+        9,11,10,11,11, 9, 9,10, 8, 8,11, 9, 9,10, 9, 9,
+       11, 9, 9,11,10,10,11, 9, 9,11, 9, 9,11,10,10,11,
+        9, 9, 9, 8, 8,11, 9, 9,12, 9, 9,11, 9, 9,12, 9,
+        9,12, 8, 8,12, 9, 9,12, 9, 9,12, 8, 8, 9, 7, 7,
+       11, 9, 9,11,10,10,11, 9, 9,11,11,11,11, 9, 9,11,
+       10,10,11,11,11,11, 9, 9,10, 9, 9,11, 9, 9,11,10,
+       10,11, 9, 9,11,10,10,11, 9, 9,11, 9,10,11,10,10,
+       11, 9, 9,
+};
+
+static const static_codebook _44p1_p5_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p5_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p1_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p1_p6_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p1_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p1_p6_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p1_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p1_p6_1[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p1_p6_1[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,13,14,16,16,16,16,
+};
+
+static const static_codebook _44p1_p6_1 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p1_p6_1,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p1_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p1_p6_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p1_p6_2[] = {
+        3, 4, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p1_p6_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p1_p6_2,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p1_p6_2,
+       0
+};
+
+static const char _huff_lengthlist__44p1_short[] = {
+        4, 5, 7, 8,10,13,14, 4, 2, 4, 6, 8,11,12, 7, 4,
+        3, 5, 8,12,14, 8, 5, 4, 4, 8,12,12, 9, 7, 7, 7,
+        9,10,11,13,11,11, 9, 7, 8,10,13,11,10, 6, 5, 7,
+        9,
+};
+
+static const static_codebook _huff_book__44p1_short = {
+       2, 49,
+       (char *)_huff_lengthlist__44p1_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p2_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p2_l0_0[] = {
+        1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 4, 6, 5,
+        8, 7, 9, 8,10, 9,11,10,11,11, 4, 5, 6, 7, 8, 8,
+        9, 9,10,10,10,10,11, 8, 9, 8,10, 8,10, 9,11,10,
+       11,11,11,11, 8, 8, 9, 8,10, 9,10,10,11,11,11,11,
+       11, 9,10,10,11,11,11,11,11,11,12,11,12,11, 9,10,
+       10,10,11,11,11,11,11,11,12,11,12,10,11,11,12,11,
+       12,12,12,12,12,12,12,12,10,11,11,11,11,12,12,12,
+       13,12,12,12,12,11,12,12,12,12,13,13,12,12,12,12,
+       12,12,11,12,12,12,12,13,13,12,13,12,12,12,12,12,
+       13,13,13,13,13,13,12,13,12,13,12,12,12,13,13,13,
+       13,13,13,13,12,13,12,12,12,
+};
+
+static const static_codebook _44p2_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p2_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p2_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p2_l0_1[] = {
+        2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
+        5, 6, 6, 6, 5, 6, 5, 6, 6,
+};
+
+static const static_codebook _44p2_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p2_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p2_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p2_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p2_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p2_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p2_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p2_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p2_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p2_long[] = {
+        3, 4, 9, 8, 8,10,13,16, 4, 2, 9, 5, 7,10,14,18,
+        9, 7, 6, 5, 7, 9,12,16, 7, 5, 5, 3, 5, 8,11,13,
+        8, 7, 7, 5, 5, 7, 9,11,10,10, 9, 8, 6, 6, 8,10,
+       13,14,13,11, 9, 8, 9,10,17,18,16,14,11,10,10,10,
+};
+
+static const static_codebook _huff_book__44p2_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p2_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p2_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p2_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p2_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p2_p2_0[] = {
+        1, 4, 4, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+       10,10, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 0, 0, 0, 0, 0,
+        0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0,
+        0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,11,11, 0, 0,
+        0, 0, 0, 0, 0, 0,10,10, 0, 0, 0,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0,
+        6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 8, 8, 0, 0, 0, 0,
+        0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0,
+        0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
+        0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,
+        8, 8, 0, 0, 0, 9, 9, 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,
+        0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
+        0, 0,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0,
+        0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+       11,11, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,11,10, 0, 0, 0, 0, 0,
+        0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0,11,11, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+        0, 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0,11,11, 0, 0,
+        0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,11,11, 0, 0, 0,
+        0, 0, 0, 0, 0,10,10, 0, 0, 0,13,13, 0, 0, 0, 0,
+        0, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,12,
+        0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,13,13, 0,
+        0, 0, 0, 0, 0, 0, 0,12,12, 0, 0, 0,13,13, 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, 0, 0, 0, 0, 0, 0, 0, 0, 6,
+        6, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,11,11,
+        0, 0, 0,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
+        0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,11, 0, 0,
+        0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,13,13, 0, 0, 0,
+        0, 0, 0, 0, 0,12,12, 0, 0, 0,13,13, 0, 0, 0, 0,
+        0, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,12,
+        0, 0, 0,13,13, 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, 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, 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,
+        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, 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, 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, 0, 0, 0, 0, 0,
+        0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0,11,11, 0,
+        0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,13,13, 0, 0,
+        0, 0, 0, 0, 0, 0,12,12, 0, 0, 0,13,13, 0, 0, 0,
+        0, 0, 0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,10,
+       10, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,14,13,
+        0, 0, 0, 0, 0, 0, 0, 0,13,12, 0, 0, 0,13,13, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+        6, 6, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,11,
+       11, 0, 0, 0,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0,
+        0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,12,12, 0,
+        0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,13,13, 0, 0,
+        0, 0, 0, 0, 0, 0,12,12, 0, 0, 0,12,12, 0, 0, 0,
+        0, 0, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,
+       12, 0, 0, 0,13,13, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 0, 0, 0,12,12,
+        0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,12,12, 0,
+        0, 0, 0, 0, 0, 0, 0,11,11, 0, 0, 0,14,14, 0, 0,
+        0, 0, 0, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,
+       12,12, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0,12,
+       12, 0, 0, 0, 0, 0, 0, 0, 0,11,11, 0, 0, 0,14,13,
+        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, 0, 0, 0, 0, 0, 0, 0,
+        0, 7, 7, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+       11,11, 0, 0, 0,12,12, 0, 0, 0,13,13, 0, 0, 0, 0,
+        0, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,12,
+        0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0,12,12, 0,
+        0, 0, 0, 0, 0, 0, 0,12,12, 0, 0, 0,14,14, 0, 0,
+        0, 0, 0, 0, 0, 0,14,14, 0, 0, 0, 0, 0, 0, 0, 0,
+       12,12, 0, 0, 0,13,13, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0,
+        0, 0, 0, 0, 0,
+};
+
+static const static_codebook _44p2_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p2_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p2_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p3_0[] = {
+        1, 5, 5, 6, 7, 7, 0, 8, 8, 6, 9, 9, 8,11,11, 0,
+        8, 8, 0, 9, 9, 0,12,12, 0, 8, 8, 5, 7, 7, 7,10,
+       10, 0,12,12, 8,11,11, 9,12,12, 0,11,12, 0,12,12,
+        0,15,15, 0,12,12, 0, 6, 6, 0, 6, 6, 0, 7, 7, 0,
+        7, 7, 0,10,10, 0, 7, 7, 0, 8, 8, 0,11,11, 0, 7,
+        7, 6, 7, 7,10, 9, 9, 0,11,10,10, 9, 9,12,12,12,
+        0,10,10, 0,11,11, 0,13,13, 0,11,11, 7, 6, 6,10,
+       10,10, 0,11,11,11,11,11,12,12,12, 0,11,11, 0,12,
+       12, 0,15,15, 0,11,11, 0,11,11, 0,11,11, 0,12,12,
+        0,12,12, 0,14,14, 0,12,12, 0,12,12, 0,15,15, 0,
+       11,11, 0, 8, 8, 0,10,10, 0,11,11, 0,11,11, 0,12,
+       12, 0,12,12, 0,11,11, 0,15,15, 0,11,11, 0, 6, 6,
+        0,10,10, 0,12,12, 0,10,10, 0,13,13, 0,12,12, 0,
+       13,13, 0,14,14, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44p2_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p2_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p3_1[] = {
+        2, 3, 3, 0, 8, 8, 0, 8, 8, 0, 9, 9, 0, 9, 9, 0,
+        9, 9, 0, 9, 9, 0, 9, 9, 0, 8, 8, 0, 6, 6, 0, 7,
+        7, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8,
+        0, 8, 8, 0, 8, 8, 0, 6, 6, 0, 6, 6, 0, 6, 6, 0,
+        8, 8, 0, 9, 9, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0, 6,
+        6, 0, 8, 8, 0, 9, 9, 0, 9, 9, 0,10,10, 0,10,10,
+        0,10,10, 0,10,10, 0,11,11, 0, 9, 9, 0, 7, 7, 0,
+       10,10, 0,10,10, 0,12,11, 0,12,12, 0,11,11, 0,11,
+       11, 0,12,12, 0,10,10, 0, 7, 7, 0,10,10, 0,10,10,
+        0,12,12, 0,11,12, 0,11,11, 0,11,11, 0,11,11, 0,
+       10,10, 0, 8, 8, 0, 9, 9, 0, 9, 9, 0,10,10, 0,10,
+       10, 0,10, 9, 0,10,10, 0,10,10, 0, 9, 9, 0, 6, 6,
+        0,10,10, 0,10,10, 0,11,11, 0,12,12, 0,11,11, 0,
+       11,11, 0,12,12, 0,11,11, 0, 7, 7, 0, 9, 9, 0, 9,
+        9, 0,11,11, 0,11,11, 0,10,10, 0,10,10, 0,11,11,
+        0, 9, 9,
+};
+
+static const static_codebook _44p2_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p2_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p4_0[] = {
+        1, 6, 6, 6, 7, 7, 7, 8, 8, 7, 8, 8,10,11,11, 9,
+        8, 8, 7, 8, 8,11,11,11, 9, 8, 8, 6, 7, 7, 9,11,
+       11, 9,11,11,10,11,11,12,13,13,11,12,12,10,11,11,
+       13,14,14,12,12,12, 6, 6, 6, 8, 6, 6, 8, 7, 7, 9,
+        7, 7,11,10,10,10, 6, 6, 9, 7, 7,12,10,10,11, 6,
+        7, 7, 7, 7,11,10,10,12,10,10,11,10,10,14,13,13,
+       13,10,10,12,11,11,15,13,13,14,10,10, 8, 7, 7,12,
+       11,11,12,11,11,11,11,11,14,14,14,13,12,12,12,11,
+       11,15,15,15,13,12,12, 0,10,10, 0,11,11, 0,11,11,
+        0,11,11, 0,14,14, 0,11,11, 0,11,11, 0,15,15, 0,
+       11,11, 7, 8, 8,12,10,10,12,10,10,12,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,14,10,10, 8, 7, 7,
+       12,11,11,12,11,11,12,11,11,16,14,14,14,12,12,13,
+       12,12,15,14,14,15,12,12, 0,11,11, 0,12,12, 0,12,
+       12, 0,12,12, 0,15,15, 0,12,12, 0,12,12, 0,14,14,
+        0,12,12,
+};
+
+static const static_codebook _44p2_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p2_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p2_p4_1[] = {
+        3, 4, 4, 8, 8,11, 9, 9,12,12,11,10,10,12,12,12,
+       10,10,11,11,12,12,12,12,12,12,11,11,13,13,12,12,
+       12,13,13,12,10,10,12,12,12,11,11,13,13,12,13,13,
+       13,13,12,11,11,13,13,12,12,12,13,13,12,10,10,12,
+       12,12,11,11,13,13,12,13,13,12,12,12,11,11,13,13,
+       12,13,13,13,13,12,11,11,12,12,12,11,11,12,12,12,
+       13,13,12,12,12,13,13,13,13,12,13,13,13,13,13,13,
+       13,12,12,12,13,13,13,13,12,13,13,12,12,11, 8, 8,
+       10,10,12,11,11,11,11,12,10,10,10,10,13,11,11,10,
+       10,13,11,11,10,10,13,12,12,12,12,13,11,11,11,11,
+       13,12,12,11,11,13,12,12,11,11,13,12,12,12,11,13,
+       12,12,12,12,13,11,11,11,11,13,12,12,11,11,13,11,
+       12,11,11,13,12,12,11,11,14,12,12,11,11,13,11,11,
+       11,11,14,12,12,11,11,13,11,12,10,10,14,12,12,11,
+       11,14,12,12,11,11,14,11,11,11,11,14,12,12,11,11,
+       13,12,12,11,11,14,12,12,11,11,11, 8, 8,10,10,12,
+        7, 7,10,10,12, 9, 9,11,11,13, 9, 9, 9, 9,13,13,
+       13,10,10,13, 9, 9,12,12,13,13,13,12,12,13, 9, 8,
+       11,11,13,10,10,12,12,14,13,13,11,11,13, 9, 9,11,
+       11,13,13,13,12,12,13, 9, 9,10,10,13,10,10,11,11,
+       13,13,13,10,10,14,10,10,11,11,14,14,14,12,12,13,
+        9, 9,10,10,13,10,10,11,11,14,13,14,10,10,14,14,
+       14,11,12,14,14,14,14,14,14,13,13,10,10,13,14,14,
+       11,11,14,14,14,10,10,14, 9, 9, 9, 9,14, 9, 9, 9,
+        9,14,10,10, 9, 9,14,10,10, 8, 8,14,11,11, 8, 8,
+       15,11,11,10,10,15,12,12,10,10,15,10,10,10,10,15,
+       11,11,10,10,15,13,13,10,10,15,11,11,10,10,15,12,
+       12,10,10,15,10,10,10,10,15,11,11,10,10,15,13,13,
+       10,10,15,11,11,10,10,15,12,12,10,10,15,11,11, 9,
+        9,15,11,11, 9, 9,15,13,13, 9, 9,15,13,13,10,10,
+       15,12,12,10,10,15,13,13,10,10,15,13,12, 9, 9,15,
+       13,13, 9, 9,14,12,12, 9, 9,14,13,13, 9, 9,14,13,
+       13, 9, 9,14,13,13, 7, 7,14,13,13, 8, 8,15,14,14,
+       10,10,15,14,14,10,10,15,14,14,10,10,15,14,14,10,
+       10,15,14,14, 9, 9,15,14,14,10,10,15,14,14,10,10,
+       14,14,14, 9, 9,15,14,14,10,10,14,14,14, 9, 9,15,
+       14,14,10,10,15,14,14,10,10,14,14,14, 9, 9,14,14,
+       14, 9, 9,14,14,14, 8, 8,15,14,14,10,10,15,14,14,
+       11,11,15,14,14, 9, 9,15,14,14, 9, 9,14,14,14, 8,
+        8,13, 9, 9,12,12,17,11,11,12,12,17,12,12,12,12,
+       17,12,12,11,11,18,15,15,12,12,17,12,12,12,12,17,
+       14,15,13,13,17,12,12,12,12,17,13,13,12,13,17,15,
+       15,12,12,18,13,13,13,13,18,15,15,13,13,18,12,12,
+       12,12,18,13,13,13,13,18,15,15,12,12,18,13,13,12,
+       12,18,15,15,13,13,18,13,13,12,12,17,13,13,12,12,
+       17,15,15,12,12,18,15,15,13,13,18,15,15,13,14,18,
+       15,16,12,12,18,15,15,12,12,18,16,16,12,12,13, 8,
+        8,10,10,14,15,14,11,11,14,15,15,12,12,15,14,14,
+       12,11,15,15,15,12,12,15,15,15,12,12,15,15,15,13,
+       13,15,15,15,12,12,15,15,15,13,13,15,15,15,13,13,
+       15,15,15,13,13,15,15,16,13,13,15,15,15,12,12,15,
+       15,15,13,13,15,15,15,13,13,15,15,15,13,13,15,15,
+       15,13,13,15,15,14,12,12,15,15,15,12,12,16,15,14,
+       12,12,16,15,15,13,13,16,16,16,13,13,16,15,15,12,
+       12,15,15,15,13,13,15,15,15,12,12,13,12,12,10,10,
+       14,14,14,11,11,15,14,14,12,12,15,14,14,11,11,15,
+       14,14,11,11,15,15,15,13,13,15,14,14,13,13,15,15,
+       15,12,12,15,14,15,13,13,16,15,15,12,12,15,15,15,
+       13,13,16,14,14,13,13,15,15,15,12,12,15,15,15,13,
+       13,16,15,15,12,12,16,15,15,12,12,16,14,14,13,13,
+       15,15,15,11,11,15,15,15,12,12,16,15,15,11,11,16,
+       15,15,13,13,16,14,15,14,14,16,15,15,12,12,16,15,
+       14,12,12,16,15,15,12,12,14,10,10, 9, 9,14,11,11,
+       12,12,14,12,12,13,13,14,12,12,12,12,15,14,14,13,
+       13,15,13,13,14,14,15,14,14,15,15,15,12,12,13,13,
+       15,13,13,14,14,15,14,14,13,13,15,13,13,13,14,15,
+       14,14,15,15,15,12,12,13,13,15,13,13,14,14,15,14,
+       14,13,13,15,13,13,14,14,15,14,14,15,15,15,13,13,
+       12,12,15,13,13,13,13,15,14,14,13,12,15,15,15,14,
+       15,15,15,14,20,20,15,14,14,13,13,15,14,14,13,13,
+       15,14,14,13,13,14,12,12, 9, 9,14,14,14,12,12,14,
+       13,13,12,13,14,14,14,12,12,15,14,14,12,12,15,14,
+       14,14,13,15,14,14,14,14,15,14,14,13,13,15,14,14,
+       13,13,15,15,15,14,14,15,14,14,13,13,15,14,14,14,
+       14,15,14,14,13,13,15,14,14,13,13,15,15,15,15,14,
+       15,15,15,13,13,15,14,14,14,14,15,14,14,13,13,15,
+       14,14,13,13,14,15,15,14,14,15,15,15,14,14,15,14,
+       14,14,14,15,15,15,14,14,15,14,14,13,14,15,15,15,
+       14,14,13,10,10,12,12,17,11,11,12,12,17,12,12,12,
+       12,17,12,12,11,11,17,15,15,12,11,18,13,13,13,13,
+       18,15,15,13,13,17,12,12,12,12,18,13,13,13,13,17,
+       15,15,12,12,17,12,12,12,12,17,15,15,13,13,17,12,
+       12,12,12,17,13,13,12,12,17,15,15,12,12,18,14,13,
+       12,12,18,15,15,13,13,18,13,13,12,12,18,13,13,12,
+       12,18,16,16,12,12,18,16,16,12,12,18,15,15,13,13,
+       18,16,16,12,12,17,15,15,12,12,17,16,16,12,12,13,
+        8, 8,10,10,14,14,15,12,12,14,15,15,12,12,15,14,
+       14,12,12,15,15,14,12,12,15,15,15,13,13,15,15,15,
+       13,13,15,15,15,12,12,16,15,15,13,13,16,15,15,13,
+       13,15,15,15,12,12,15,15,15,14,14,15,15,15,12,12,
+       15,15,15,13,13,16,15,15,13,13,15,15,15,13,13,16,
+       15,15,13,13,15,15,14,12,12,15,15,15,12,12,16,14,
+       15,13,13,16,15,15,13,13,15,16,15,13,13,16,15,14,
+       13,13,16,15,15,13,13,16,15,15,13,13,13,12,12,11,
+       11,14,14,14,11,11,14,14,14,12,12,15,14,14,11,11,
+       16,14,14,11,11,15,15,15,12,13,16,14,14,13,13,15,
+       15,15,12,12,15,14,14,13,13,16,15,15,12,12,15,15,
+       15,12,12,15,14,14,13,13,15,15,15,12,12,15,14,14,
+       12,12,16,15,15,12,12,16,15,15,12,12,16,14,14,13,
+       13,15,15,15,11,11,15,15,14,12,12,16,15,15,11,11,
+       16,15,15,12,12,16,14,14,13,13,16,15,15,11,11,16,
+       14,14,12,12,16,15,15,11,11,14,10,10, 9, 9,14,11,
+       11,12,12,14,12,12,13,14,14,12,12,12,12,14,14,14,
+       13,13,15,13,13,14,14,15,14,14,15,15,15,12,12,13,
+       13,15,13,13,14,14,15,15,15,14,14,15,13,13,14,14,
+       15,15,15,15,15,15,12,12,13,13,15,13,13,14,14,15,
+       14,14,13,13,15,13,13,14,14,15,14,14,15,15,15,12,
+       12,13,13,15,13,13,13,13,14,14,14,13,13,15,15,15,
+       14,15,15,15,15,21,19,15,14,14,13,13,15,14,14,14,
+       14,14,14,14,13,13,14,12,12, 9, 9,14,14,14,12,12,
+       14,14,13,13,13,14,14,14,12,12,14,14,14,12,12,15,
+       14,14,13,13,15,14,14,14,14,15,14,14,13,13,15,14,
+       14,13,13,15,15,15,15,15,15,14,14,13,13,15,14,14,
+       14,14,15,14,14,13,13,15,14,14,13,13,14,15,15,15,
+       15,15,14,15,13,13,15,14,14,14,14,15,14,14,13,13,
+       15,14,14,13,13,14,15,15,14,14,15,15,15,14,14,15,
+       14,14,14,14,15,15,15,15,15,15,14,14,14,13,14,15,
+       15,14,14,13,10,10,12,12,18,12,12,12,12,17,12,12,
+       12,12,18,13,13,11,11,18,15,14,11,11,17,13,13,13,
+       13,18,15,15,12,12,18,12,12,12,12,17,13,13,12,12,
+       18,15,15,12,12,18,13,13,13,12,18,15,15,13,13,18,
+       13,13,12,12,18,13,13,12,12,18,15,15,12,12,17,13,
+       13,12,12,17,15,15,12,12,17,12,12,11,11,17,13,13,
+       11,11,17,15,15,11,11,18,16,16,12,12,18,15,15,13,
+       13,18,15,15,11,11,17,15,15,12,12,18,15,15,11,11,
+       13, 8, 8,10,10,14,14,14,11,11,15,15,15,12,12,15,
+       14,14,11,11,16,14,14,12,12,15,15,15,12,12,15,15,
+       15,13,13,15,15,15,12,12,15,15,15,12,12,16,15,15,
+       13,13,15,15,15,12,12,15,15,15,13,13,16,15,15,12,
+       12,15,15,15,12,12,16,15,15,13,13,16,15,15,12,12,
+       15,15,15,13,13,15,14,14,12,12,15,15,15,12,12,16,
+       15,14,12,12,16,15,15,13,13,16,16,16,13,13,16,14,
+       15,13,13,15,15,15,13,13,16,15,15,12,12,13,12,12,
+       10,10,14,14,14,11,11,15,14,14,12,12,15,14,14,11,
+       11,16,14,14,11,11,15,14,15,12,12,15,14,14,13,13,
+       15,15,15,12,12,15,14,14,12,12,15,14,15,12,12,15,
+       15,15,12,12,16,14,14,13,13,15,15,15,11,12,16,14,
+       14,12,12,16,15,15,12,12,15,15,15,12,12,16,14,14,
+       12,12,15,15,15,11,11,15,14,14,11,12,15,15,14,11,
+       11,16,15,15,12,12,16,14,14,13,13,16,15,15,11,11,
+       16,14,14,12,12,16,15,15,11,11,13,10,10, 8, 8,14,
+       12,12,12,12,14,12,12,13,13,14,12,12,12,12,14,14,
+       14,13,13,15,13,13,14,14,15,15,14,15,15,15,13,13,
+       13,13,15,13,13,14,14,15,14,15,14,14,15,13,13,13,
+       13,15,15,15,15,15,15,12,12,13,12,15,13,13,14,14,
+       15,14,14,13,13,15,13,13,14,13,15,15,15,16,16,15,
+       13,13,12,12,15,13,13,13,13,14,14,14,12,12,15,15,
+       15,14,14,15,15,15,20,20,15,14,14,13,13,15,15,14,
+       14,14,15,14,14,13,13,13,12,12, 9, 9,14,13,13,12,
+       12,14,13,13,12,12,14,14,14,12,12,14,14,14,13,13,
+       15,14,14,13,13,15,14,14,14,14,15,15,14,12,12,15,
+       14,14,13,13,15,14,15,14,15,15,14,14,13,13,15,14,
+       14,14,14,15,14,14,12,12,15,14,14,13,13,14,15,14,
+       15,14,15,14,14,13,13,15,14,14,14,14,15,14,14,12,
+       12,15,14,14,13,13,15,15,15,14,14,15,15,15,14,14,
+       16,14,14,14,14,15,15,15,14,14,15,14,14,14,14,14,
+       15,15,14,14,13,13,13,12,13,17,15,15,12,12,17,15,
+       15,12,12,18,15,15,11,11,17,16,16,11,11,18,16,16,
+       13,13,18,17,16,13,13,18,16,16,12,12,18,16,16,12,
+       12,18,17,17,12,12,17,16,16,12,13,17,16,16,12,13,
+       17,16,16,12,12,17,16,16,12,12,18,17,16,12,12,18,
+       16,16,12,12,17,16,17,12,12,18,15,15,11,11,18,15,
+       15,12,12,17,17,17,11,11,17,17,17,12,12,17,16,16,
+       13,13,18,16,16,11,11,18,16,16,12,12,18,17,16,11,
+       11,14,14,14,10,10,16,15,14,11,11,16,15,15,12,12,
+       16,14,14,12,12,17,14,14,13,13,17,15,15,13,13,17,
+       15,15,14,14,16,15,15,12,12,16,15,15,13,13,18,15,
+       15,14,14,16,15,15,12,12,16,15,15,14,14,16,15,15,
+       12,12,16,15,15,13,13,17,15,15,13,13,17,15,15,13,
+       13,17,15,15,14,14,16,14,14,12,12,17,15,15,12,12,
+       18,15,15,13,13,17,15,15,14,14,17,16,16,15,15,17,
+       15,14,13,13,17,15,15,14,14,17,15,15,13,13,14,12,
+       12,11,11,15,14,14,12,12,16,14,14,12,12,16,14,14,
+       11,11,17,14,14,12,12,16,15,14,13,13,16,14,14,13,
+       13,16,15,15,12,12,16,14,14,13,13,17,15,15,13,13,
+       16,15,15,13,13,17,14,14,13,13,16,15,15,12,12,16,
+       14,14,12,12,16,15,15,12,12,17,15,15,12,12,17,14,
+       14,13,13,16,15,15,12,12,16,14,14,12,12,16,15,15,
+       12,12,17,15,15,13,13,17,14,14,13,13,17,15,15,12,
+       12,17,14,14,12,12,17,15,15,12,12,14,14,14, 8, 8,
+       14,14,14,13,13,14,15,15,14,14,14,14,14,14,14,15,
+       15,15,19,19,15,15,15,14,14,15,15,16,20,19,15,15,
+       15,14,14,15,16,16,15,15,15,15,15,19,19,15,15,15,
+       14,14,15,16,16,19,20,15,15,15,14,14,15,15,15,15,
+       15,15,15,15,19,19,15,15,15,15,15,15,15,16,19,20,
+       15,14,15,14,14,15,15,15,15,15,15,15,15,20,19,15,
+       15,15,21,19,15,16,16,20,20,15,15,14,19,19,15,15,
+       16,20,21,15,15,15,20,19,13,12,12, 9, 9,14,14,14,
+       12,12,14,13,13,13,13,14,14,14,13,13,15,14,14,20,
+       19,15,14,14,14,13,15,14,14,19,19,15,15,14,13,13,
+       15,14,14,14,14,15,15,15,19,20,15,14,14,13,13,15,
+       14,14,20,19,14,15,14,13,13,15,14,14,14,13,15,15,
+       15,19,20,15,15,14,14,14,15,14,14,21,19,15,15,15,
+       13,13,15,14,14,14,14,14,15,15,20,20,15,15,15,21,
+       20,15,14,14,19,20,15,15,15,20,20,15,14,14,19,20,
+       15,15,15,21,19,
+};
+
+static const static_codebook _44p2_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p2_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p2_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p2_p5_0[] = {
+        2, 6, 6,14,14, 6, 7, 7,14,14, 7, 7, 7,15,15, 0,
+       13,13,16,16, 0,13,13,15,15, 7, 8, 8,15,15, 9,10,
+       10,17,16, 9, 8, 8,15,15, 0,13,13,18,17, 0,13,13,
+       16,16, 8, 8, 8,15,15,12,11,11,16,17, 9, 8, 8,14,
+       14, 0,13,13,18,17, 0,13,13,16,15, 0,14,14,18,17,
+        0,20,22,18,20, 0,12,12,16,16, 0,16,16,22,20, 0,
+       14,14,16,16, 0,14,14,17,17, 0,22,22,22,19, 0,12,
+       13,16,16, 0,17,17, 0, 0, 0,15,15,16,16, 5, 7, 7,
+       13,13, 9, 9, 9,15,14,10,10,10,14,14, 0,21,21,18,
+       17, 0,21,22,18,17, 9,10,10,14,14,12,12,12,17,17,
+       12,10,10,14,14, 0,19,21,18,17, 0,20,22,18,18,11,
+       10,10,14,14,14,13,13,18,17,12,11,11,14,14, 0,22,
+       19,17,18, 0,20, 0,18,17, 0,22,21,17,17, 0, 0, 0,
+        0, 0, 0,20,22,17,17, 0,22, 0,21,19, 0,22, 0,18,
+       18, 0, 0,22,18,19, 0, 0, 0, 0, 0, 0,19,21,17,17,
+        0, 0, 0,20,20, 0, 0, 0,18,18, 6, 6, 6,13,12, 8,
+        6, 6,11,11, 8, 6, 6,13,13, 0, 9, 9,11,11, 0,11,
+       11,14,14, 9, 7, 7,13,13,11, 9, 9,13,13,10, 6, 6,
+       13,13, 0,10,10,14,14, 0,10,10,13,13, 9, 7, 7,13,
+       14,13, 9, 9,13,13,10, 6, 6,13,12, 0,11,11,15,15,
+        0,10,10,13,13, 0,12,12,15,15, 0,19, 0,17,17, 0,
+        9, 9,13,13, 0,13,14,19,20, 0,11,11,13,13, 0,11,
+       11,14,14, 0,19,20,17,18, 0,10,10,13,13, 0,15,15,
+       21,19, 0,12,12,13,13, 0,10,10,12,13, 0,11,11,15,
+       15, 0,11,11,15,15, 0,15,15,22, 0, 0,16,17,22, 0,
+        0,11,11,15,15, 0,14,14,18,17, 0,11,11,15,16, 0,
+       15,15,22,21, 0,16,16, 0,20, 0,12,12,16,15, 0,15,
+       14,19,19, 0,11,11,16,16, 0,15,15,21, 0, 0,16,15,
+        0, 0, 0,16,16,22,21, 0, 0, 0, 0, 0, 0,15,15,20,
+       20, 0,18,18, 0, 0, 0,16,17, 0, 0, 0,17,17, 0,22,
+        0, 0, 0, 0, 0, 0,15,15,21,22, 0,20,18, 0, 0, 0,
+       18,17,22, 0, 0,10,10,12,11, 0,10,10,10,10, 0,11,
+       11,12,12, 0,11,11, 9, 9, 0,13,13,12,12, 0,11,11,
+       12,12, 0,13,13,12,12, 0,10,10,12,12, 0,13,12,13,
+       13, 0,12,12,12,12, 0,11,11,12,12, 0,13,13,12,12,
+        0,10,10,12,12, 0,13,13,13,14, 0,12,12,12,12, 0,
+       13,14,14,14, 0,20,21,15,15, 0,12,11,12,12, 0,15,
+       16,20,22, 0,13,12,11,11, 0,13,13,14,13, 0,20, 0,
+       16,15, 0,12,12,12,12, 0,16,16,22,21, 0,13,13,12,
+       12, 6, 7, 7,16,16,11, 9, 9,15,15,12, 9, 9,16,16,
+        0,13,13,14,14, 0,14,14,16,17,10, 9, 9,16,16,14,
+       12,12,16,16,12, 9, 9,15,15, 0,13,13,18,18, 0,13,
+       13,15,16,12,10,10,17,18,15,12,12,17,17,13, 9, 9,
+       16,16, 0,13,13,17,18, 0,14,14,16,16, 0,15,15,18,
+       18, 0,22, 0,20,20, 0,12,12,16,16, 0,16,16,20,22,
+        0,14,14,16,16, 0,15,14,18,18, 0, 0,22,19,21, 0,
+       13,13,16,17, 0,17,17,22,22, 0,15,15,16,16, 7, 7,
+        7,14,14,11,10,10,15,15,12,10,10,15,14, 0,22, 0,
+       18,18, 0, 0,21,17,18,11,10,10,15,15,14,12,12,17,
+       17,14,11,11,15,15, 0,22,20,18,18, 0, 0,20,18,17,
+       12,10,10,16,16,17,14,14,19,18,14,11,11,15,15, 0,
+       21,22,19,19, 0,21,22,18,18, 0,22, 0,19,21, 0, 0,
+        0, 0, 0, 0,22,22,18,17, 0, 0, 0,21,20, 0,22,22,
+       20,19, 0, 0,22,20,20, 0, 0, 0, 0, 0, 0,20,21,17,
+       17, 0, 0,22,21,21, 0, 0, 0,18,18,10, 9, 9,14,14,
+       13,10,10,13,13,13,10,11,14,14, 0,13,13,12,12, 0,
+       15,15,16,16,13,10,10,15,15,15,12,12,14,14,15,10,
+       10,14,15, 0,14,14,16,15, 0,14,14,15,15,13,10,10,
+       15,15,18,13,13,15,15,15,10,10,14,15, 0,14,14,16,
+       16, 0,14,14,15,15, 0,15,15,16,16, 0,22, 0,18,18,
+        0,12,13,14,14, 0,17,17,22, 0, 0,14,14,14,14, 0,
+       15,15,16,16, 0,22, 0,18,17, 0,13,13,14,14, 0,19,
+       18,21,22, 0,15,15,14,14, 0,11,11,13,13, 0,12,12,
+       16,16, 0,12,12,16,16, 0,15,16,21, 0, 0,16,17, 0,
+       22, 0,12,12,16,16, 0,14,14,17,18, 0,11,11,16,16,
+        0,15,15,21,22, 0,16,16, 0, 0, 0,12,12,16,16, 0,
+       15,15, 0,19, 0,12,12,16,17, 0,16,16,22, 0, 0,16,
+       16, 0,22, 0,17,17, 0,22, 0, 0, 0, 0, 0, 0,15,15,
+       20,19, 0,18,18, 0, 0, 0,17,18, 0, 0, 0,17,17, 0,
+        0, 0, 0, 0, 0, 0, 0,15,15, 0,22, 0,20,18, 0, 0,
+        0,18,18,22,22, 0,11,11,14,14, 0,12,12,14,14, 0,
+       12,12,15,15, 0,13,13,14,14, 0,14,14,17,16, 0,12,
+       12,16,16, 0,14,14,16,16, 0,11,11,15,15, 0,13,13,
+       16,16, 0,13,13,15,15, 0,12,12,15,15, 0,15,14,16,
+       16, 0,11,11,15,15, 0,14,14,17,17, 0,13,13,15,15,
+        0,15,15,17,17, 0, 0, 0,19,18, 0,13,12,15,15, 0,
+       16,16, 0, 0, 0,14,14,15,15, 0,14,14,16,17, 0,22,
+        0,18,18, 0,13,13,15,15, 0,17,17, 0, 0, 0,14,14,
+       15,15, 8, 8, 8,16,16,12,10,10,16,16,13, 9, 9,16,
+       16, 0,14,14,17,17, 0,14,14,17,16,12,10,10,18,17,
+       14,11,11,18,18,14, 9,10,16,16, 0,13,13,18,19, 0,
+       14,13,16,16,12, 9, 9,16,16,17,13,13,17,17,14, 9,
+        9,15,15, 0,14,14,19,20, 0,13,13,15,15, 0,15,15,
+       18,19, 0, 0,22,22,22, 0,13,13,17,17, 0,16,16,19,
+       21, 0,14,14,16,16, 0,14,14,18,18, 0, 0, 0, 0, 0,
+        0,13,13,16,16, 0,18,18, 0, 0, 0,15,15,16,16, 8,
+        7, 7,14,14,12,10,10,15,15,13,10,10,15,14, 0,22,
+        0,18,18, 0,22, 0,18,18,12,10,10,16,15,15,12,12,
+       17,17,14,11,11,15,15, 0,20,21,19,18, 0, 0, 0,17,
+       18,13,11,11,15,15,16,13,13,18,18,15,11,11,14,14,
+        0,22,21,19,19, 0,21,22,18,18, 0,22,22,20,18, 0,
+        0, 0, 0, 0, 0,22,19,17,17, 0, 0, 0,22,21, 0, 0,
+       22,19,17, 0, 0,22,19,19, 0, 0, 0, 0, 0, 0,22,21,
+       18,17, 0, 0, 0,22, 0, 0, 0, 0,19,19, 0,10,10,14,
+       14, 0,11,11,15,14, 0,11,11,15,15, 0,14,14,15,14,
+        0,15,15,16,16, 0,11,11,16,16, 0,13,13,16,16, 0,
+       11,11,15,15, 0,14,14,17,16, 0,14,14,15,15, 0,11,
+       11,16,16, 0,14,13,15,15, 0,11,11,15,15, 0,15,15,
+       17,17, 0,14,14,15,14, 0,16,16,17,17, 0, 0,22,18,
+       18, 0,13,13,15,15, 0,17,17,22, 0, 0,15,15,15,14,
+        0,15,16,16,17, 0, 0,22,18,19, 0,13,13,15,15, 0,
+       20,18,21, 0, 0,15,15,14,14, 0,11,11,13,13, 0,12,
+       12,16,16, 0,12,12,16,15, 0,15,16,22,22, 0,17,17,
+        0, 0, 0,12,12,16,16, 0,14,14,18,18, 0,11,11,16,
+       16, 0,15,16,22,20, 0,16,16, 0,22, 0,12,12,16,16,
+        0,15,15,18,20, 0,11,11,16,16, 0,15,15, 0, 0, 0,
+       16,16, 0, 0, 0,17,17,22, 0, 0, 0, 0, 0, 0, 0,15,
+       15, 0,21, 0,18,18, 0, 0, 0,17,16, 0, 0, 0,17,17,
+       22,22, 0, 0, 0, 0, 0, 0,15,15,21, 0, 0,20,22, 0,
+        0, 0,18,18, 0, 0, 0,12,12,15,15, 0,12,12,15,15,
+        0,12,12,16,16, 0,13,13,15,15, 0,15,15,17,17, 0,
+       13,12,16,16, 0,14,14,16,16, 0,12,11,16,16, 0,14,
+       14,17,17, 0,14,14,16,16, 0,12,12,16,16, 0,15,15,
+       17,16, 0,11,11,15,16, 0,14,14,17,17, 0,14,14,16,
+       16, 0,15,15,18,18, 0, 0, 0,22,19, 0,13,13,15,16,
+        0,16,17, 0, 0, 0,14,14,16,16, 0,15,15,18,17, 0,
+        0, 0,20,20, 0,13,13,16,15, 0,17,17,22,22, 0,14,
+       14,15,15, 0,11,11,16,16, 0,13,13,16,17, 0,13,13,
+       17,18, 0,16,16,17,17, 0,17,17,18,18, 0,12,12,17,
+       17, 0,16,15,18,18, 0,12,12,16,16, 0,16,16,18,18,
+        0,15,15,17,17, 0,12,12,17,17, 0,16,16,19,18, 0,
+       12,12,16,17, 0,16,16,19,19, 0,15,16,16,17, 0,16,
+       16,19,17, 0, 0, 0,20,22, 0,13,13,16,16, 0,19,18,
+       21, 0, 0,15,15,16,16, 0,16,16,18,18, 0, 0, 0,22,
+       21, 0,14,14,16,16, 0,21,19,21,22, 0,16,16,16,16,
+        0, 9, 9,14,14, 0,13,13,15,15, 0,14,14,15,15, 0,
+        0,20,18,19, 0, 0,22,18,18, 0,12,12,15,15, 0,15,
+       15,17,18, 0,14,13,14,14, 0,20, 0,18,18, 0,21, 0,
+       18,17, 0,13,13,15,16, 0,17,17,18,18, 0,14,14,15,
+       15, 0,22,22,20,19, 0,20,21,18,18, 0,20,22,19,19,
+        0, 0, 0, 0, 0, 0,20,20,17,17, 0, 0,22,22,21, 0,
+       22, 0,18,18, 0,20,22,19,19, 0, 0, 0, 0, 0, 0,21,
+       21,17,18, 0, 0, 0,21,20, 0, 0,22,19,18, 0,18,18,
+       15,15, 0,22,21,17,16, 0, 0,22,17,17, 0,20,22,18,
+       18, 0, 0,22,20,20, 0,21,19,16,16, 0,21,21,18,18,
+        0,19,19,17,17, 0, 0,22,19,19, 0,22,20,17,17, 0,
+       21,19,16,16, 0,22,22,19,18, 0,19,20,16,16, 0,22,
+       21,19,21, 0,21,22,17,18, 0,21,20,18,18, 0, 0, 0,
+       19,20, 0,20,19,16,16, 0,22,22, 0, 0, 0,21,21,17,
+       16, 0,22,20,19,18, 0, 0, 0,20,20, 0,20,19,16,16,
+        0, 0, 0, 0, 0, 0,21,22,17,17, 0,11,11,13,13, 0,
+       13,13,15,16, 0,13,13,16,16, 0,17,18,21, 0, 0,17,
+       18, 0, 0, 0,12,12,15,16, 0,15,15,19,18, 0,12,12,
+       16,16, 0,17,17,22, 0, 0,17,17, 0,22, 0,12,12,17,
+       16, 0,16,16,19,20, 0,12,12,16,16, 0,17,17, 0, 0,
+        0,17,17, 0,21, 0,17,16,22, 0, 0, 0, 0, 0, 0, 0,
+       15,15,20,22, 0,20,18, 0, 0, 0,18,18, 0, 0, 0,17,
+       17,21, 0, 0, 0, 0, 0, 0, 0,15,15,21,22, 0,19,20,
+       22, 0, 0,19,18, 0, 0, 0,14,14,18,18, 0,16,16,22,
+       20, 0,16,16,22,19, 0,17,17,20,22, 0,19,19, 0, 0,
+        0,15,15,20, 0, 0,18,21, 0,20, 0,15,15,21,20, 0,
+       18,17, 0, 0, 0,17,17, 0,22, 0,15,15,19,19, 0,19,
+       18, 0, 0, 0,15,15,20, 0, 0,18,18,22,22, 0,17,17,
+        0,20, 0,18,18, 0, 0, 0, 0,22, 0, 0, 0,15,15,19,
+       20, 0,20,19, 0, 0, 0,17,17,20,21, 0,17,18,20,22,
+        0, 0, 0, 0,22, 0,15,15,20,20, 0,22,20, 0, 0, 0,
+       17,18,20, 0, 0,12,12,17,16, 0,14,14,17,17, 0,13,
+       13,17,17, 0,16,16,18,18, 0,17,16,17,17, 0,13,13,
+       17,17, 0,15,16,18,18, 0,13,13,16,16, 0,16,16,18,
+       18, 0,16,16,17,16, 0,13,13,16,16, 0,17,17,18,17,
+        0,12,12,15,16, 0,17,17,19,19, 0,16,16,16,16, 0,
+       16,17,19,18, 0, 0, 0,21,22, 0,14,14,16,16, 0,18,
+       18, 0,22, 0,16,16,16,16, 0,16,16,18,17, 0, 0, 0,
+       21,20, 0,14,14,16,16, 0,21,22,22, 0, 0,16,16,16,
+       16, 0, 9, 9,14,13, 0,13,14,15,16, 0,14,13,15,14,
+        0,22, 0,18,18, 0,21, 0,17,18, 0,13,13,15,15, 0,
+       15,16,18,17, 0,14,14,15,14, 0,20,22,18,18, 0,22,
+       21,17,17, 0,13,13,15,15, 0,17,17,19,19, 0,14,14,
+       14,14, 0, 0,22,18,18, 0, 0,22,17,17, 0, 0,22,19,
+       20, 0, 0, 0, 0, 0, 0,21,20,17,16, 0, 0, 0,21,22,
+        0, 0, 0,18,19, 0, 0, 0,18,18, 0, 0, 0, 0, 0, 0,
+       22, 0,17,17, 0, 0, 0,20,22, 0, 0, 0,18,19, 0,18,
+       19,16,16, 0,22,20,17,17, 0,22,22,17,18, 0,22,22,
+       18,17, 0, 0,22,18,19, 0,20,20,17,18, 0, 0,22,19,
+       18, 0,22,22,17,17, 0,22, 0,19,19, 0, 0,22,18,18,
+        0,20,22,17,17, 0, 0,22,18,18, 0,19,20,17,17, 0,
+       22, 0,20,19, 0,22,21,17,17, 0, 0, 0,18,18, 0, 0,
+        0,22,19, 0,20, 0,17,17, 0,22, 0, 0,22, 0, 0,20,
+       17,18, 0,22, 0,19,19, 0, 0, 0, 0,19, 0,19,21,17,
+       17, 0, 0, 0, 0, 0, 0,20,21,17,16, 0,11,11,13,13,
+        0,13,13,16,16, 0,13,13,15,16, 0,17,17,21,22, 0,
+       17,18, 0, 0, 0,12,12,16,16, 0,15,15,18,18, 0,13,
+       13,16,16, 0,17,16,21,21, 0,17,17, 0, 0, 0,13,13,
+       16,16, 0,16,16,19,18, 0,13,13,16,16, 0,17,17, 0,
+       22, 0,17,18,20,22, 0,17,18, 0, 0, 0, 0, 0, 0, 0,
+        0,15,15,20, 0, 0,18,19, 0, 0, 0,17,17, 0, 0, 0,
+       18,17,22, 0, 0, 0, 0, 0, 0, 0,15,16,21,20, 0,20,
+       20, 0, 0, 0,18,19, 0, 0, 0,15,15,22,22, 0,17,16,
+       20,22, 0,17,17,20,22, 0,18,18, 0,21, 0,19,18, 0,
+        0, 0,16,16,20,20, 0,19,19,22, 0, 0,15,16,21,22,
+        0,18,19,22, 0, 0,17,18, 0, 0, 0,16,16,22, 0, 0,
+       19,19, 0,21, 0,15,16,20, 0, 0,18,18, 0,22, 0,18,
+       17, 0, 0, 0,18,18, 0, 0, 0, 0, 0, 0, 0, 0,16,16,
+       22,21, 0,20,21, 0, 0, 0,17,18,22, 0, 0,18,18, 0,
+        0, 0, 0, 0, 0, 0, 0,16,16,20,19, 0,22,21, 0, 0,
+        0,18,18,22,22,
+};
+
+static const static_codebook _44p2_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p2_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p2_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p2_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p2_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p2_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p2_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p6_0[] = {
+        1, 7, 7, 7, 8, 8, 7, 8, 8, 7, 9, 9,10,11,11, 9,
+        8, 8, 7, 8, 9,11,11,11, 9, 8, 8, 6, 7, 7,10,10,
+       10,10,10,10,10,10,10,14,14,14,12,11,11,10,11,11,
+       15,14,14,13,11,11, 6, 6, 6, 8, 5, 5, 8, 7, 7, 8,
+        7, 7,11,10,10, 9, 7, 7, 9, 7, 7,12,10,10,10, 7,
+        7, 6, 8, 7,12,10,10,12,10,10,11,10,10,15,14,13,
+       13,10,10,11,10,10,16,14,14,14,10,10, 7, 7, 7,12,
+       11,11,12,11,11,11,11,11,16,14,14,13,12,12,11,11,
+       11,17,15,15,14,12,12,10, 9, 9,13,11,11,13,11,11,
+       12,11,11,16,14,13,14,11,11,12,11,11,17,15,14,14,
+       11,11, 7, 8, 8,12,11,11,12,10,10,12,10,10,16,13,
+       14,13,10,10,11,10,10,17,14,14,14,10,10, 7, 7, 7,
+       12,11,11,12,11,11,12,11,11,15,14,15,14,12,12,12,
+       11,11,17,15,15,14,12,12,10,10, 9,13,11,11,13,11,
+       11,13,11,11,16,14,14,14,11,11,13,11,11,16,15,15,
+       15,11,11,
+};
+
+static const static_codebook _44p2_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p2_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p6_1[] = {
+        2, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 8,
+        7, 7, 8, 8, 8, 9, 9, 9, 9, 8, 8, 6, 7, 7, 9, 8,
+        8, 9, 7, 7, 9, 8, 8,10, 8, 8,10, 8, 8,10, 8, 8,
+       10, 8, 9,10, 8, 8, 7, 6, 6, 8, 6, 6, 9, 6, 6, 9,
+        7, 7,10, 8, 8, 9, 6, 6, 9, 7, 7,10, 9, 8, 9, 7,
+        7, 7, 7, 7,11, 8, 8,11, 9, 9,10, 9, 9,12, 9, 9,
+       12, 8, 8,11, 9, 9,12, 9, 9,12, 8, 8, 8, 7, 7,10,
+        9, 9,10, 9, 9,10, 9, 9,11,10,11,11, 9, 9,11, 9,
+        9,11,11,11,11, 9, 9,10, 8, 8,11, 9, 9,10, 9, 9,
+       11, 9, 9,11,10,10,11, 9, 9,11, 9, 9,12,10,10,11,
+        9, 9, 8, 8, 8,11, 9, 9,12, 9, 9,11, 9, 9,12, 9,
+        9,12, 8, 8,12, 9, 9,12, 9,10,12, 8, 8, 9, 7, 7,
+       11, 9, 9,11,10,10,11, 9, 9,11,11,11,11, 9, 9,11,
+       10,10,12,11,11,11, 9,10,10, 9, 9,11, 9, 9,11,10,
+       10,11,10,10,11,11,11,11, 9, 9,11, 9,10,11,11,11,
+       11, 9, 9,
+};
+
+static const static_codebook _44p2_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p2_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p2_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p2_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p2_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p2_p7_1[] = {
+        1, 9, 9, 6, 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,
+};
+
+static const static_codebook _44p2_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p2_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p2_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p2_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p2_p7_2[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p2_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p2_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p2_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p2_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p2_p7_3[] = {
+        3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p2_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p2_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p2_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p2_short[] = {
+        4, 4,12, 9, 8,12,15,17, 4, 2,11, 6, 5, 9,13,15,
+       11, 7, 8, 7, 7,10,14,13, 8, 5, 7, 5, 5, 8,12,12,
+        8, 4, 7, 4, 3, 6,11,12,11, 8, 9, 7, 6, 8,11,12,
+       15,13,14,12, 9, 7,10,13,16,12,17,12, 7, 5, 8,11,
+};
+
+static const static_codebook _huff_book__44p2_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p2_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p3_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p3_l0_0[] = {
+        1, 4, 4, 8, 8, 8, 8, 9, 9,10,10,10,10, 4, 6, 5,
+        8, 7, 9, 9, 9, 9,10, 9,11, 9, 4, 5, 6, 7, 8, 9,
+        9, 9, 9, 9,10, 9,10, 8, 9, 8, 9, 8,10, 9,11, 9,
+       12,10,12,10, 8, 8, 9, 8, 9, 9,10, 9,11,10,12,10,
+       12, 9,10,10,11,10,12,11,12,11,12,12,12,12, 9,10,
+       10,11,11,11,11,11,12,12,12,12,12,10,11,11,12,12,
+       12,12,12,12,12,12,12,12,10,11,11,12,12,12,12,12,
+       12,12,12,12,12,11,12,12,12,12,12,13,12,13,12,13,
+       12,12,11,12,12,12,12,12,12,13,12,12,12,12,12,12,
+       12,12,13,13,12,13,12,13,12,13,12,12,12,13,12,13,
+       12,13,12,13,12,13,12,12,12,
+};
+
+static const static_codebook _44p3_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p3_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p3_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p3_l0_1[] = {
+        3, 4, 4, 5, 5, 4, 4, 5, 5, 5, 4, 5, 4, 5, 5, 5,
+        5, 6, 5, 6, 5, 6, 5, 6, 5,
+};
+
+static const static_codebook _44p3_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p3_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p3_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p3_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p3_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p3_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p3_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p3_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p3_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p3_long[] = {
+        3, 4,13, 9, 9,12,15,17, 4, 2,18, 5, 7,10,14,18,
+       11, 8, 6, 5, 6, 8,11,14, 8, 5, 5, 3, 5, 8,11,13,
+        9, 6, 7, 5, 5, 7, 9,10,11,10, 9, 8, 6, 6, 8,10,
+       14,14,11,11, 9, 8, 9,10,17,17,14,13,10, 9,10,10,
+};
+
+static const static_codebook _huff_book__44p3_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p3_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p3_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p3_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p3_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p3_p2_0[] = {
+        3, 7, 7, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,
+       11,11, 0, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0,
+        0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,12,12, 0, 0,
+        0, 0, 0, 0, 0, 0,11,11, 0, 0, 0,12,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0,
+        5, 5, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5,
+        0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0,
+        0, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0, 0, 7, 7, 0, 0,
+        0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,
+        8, 8, 0, 0, 0, 9, 9, 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,
+        0, 0, 0, 0, 0, 0, 0, 0,11,11, 0, 0, 0, 9, 9, 0,
+        0, 0,10,10, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0,
+        0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+       10,10, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+        0, 0, 0,11,12, 0, 0, 0, 0, 0, 0, 0, 0,11,11, 0,
+        0, 0,12,12, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+        0, 0, 9, 9, 0, 0, 0, 7, 7, 0, 0, 0, 8, 8, 0, 0,
+        0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0,
+        0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+        5, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 7, 7,
+        0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0,
+        0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0,
+        0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
+        0, 0, 0,10,10, 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, 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, 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,
+        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, 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, 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, 0, 0, 0, 0, 0,
+        0, 0, 0, 9, 9, 0, 0, 0, 7, 7, 0, 0, 0, 8, 8, 0,
+        0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0,
+        0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 7,
+        7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,11,11,
+        0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+        5, 5, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 7,
+        7, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0,
+        0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0,
+        0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9,
+        9, 0, 0, 0,11,11, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0,
+        0, 0, 0, 0,10,10, 0, 0, 0, 9, 9, 0, 0, 0,10,10,
+        0, 0, 0,11,12, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0,11,11, 0, 0,
+        0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,
+        9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,11,
+       11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,12,12,
+        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, 0, 0, 0, 0, 0, 0, 0,
+        0, 7, 7, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0,
+        9, 9, 0, 0, 0,10,10, 0, 0, 0,12,12, 0, 0, 0, 0,
+        0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
+        0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 0, 0,
+        0, 0, 0, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,
+       10,10, 0, 0, 0,11,11, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0,
+        0, 0, 0, 0, 0,
+};
+
+static const static_codebook _44p3_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p3_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p3_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p3_0[] = {
+        1, 5, 5, 5, 8, 8, 0, 8, 8, 6, 9, 9, 8,10,10, 0,
+        8, 8, 0, 9, 9, 0,12,12, 0, 8, 8, 4, 7, 7, 6,10,
+       10, 0,12,12, 7,11,11, 9,12,12, 0,12,12, 0,13,13,
+        0,15,15, 0,12,12, 0, 7, 7, 0, 7, 7, 0, 8, 8, 0,
+        8, 8, 0,10,10, 0, 7, 7, 0, 8, 8, 0,11,11, 0, 7,
+        7, 5, 7, 7, 9, 9, 9, 0,11,10, 9, 9, 9,11,12,12,
+        0,10,10, 0,11,11, 0,13,13, 0,11,11, 6, 7, 7, 9,
+       10,10, 0,12,12,10,11,11,11,12,12, 0,12,12, 0,13,
+       13, 0,15,15, 0,12,12, 0,10,10, 0,11,11, 0,11,11,
+        0,12,12, 0,13,13, 0,11,11, 0,12,12, 0,15,15, 0,
+       11,11, 0, 8, 8, 0,10,10, 0,12,12, 0,11,11, 0,12,
+       12, 0,12,12, 0,12,12, 0,15,15, 0,11,11, 0, 7, 7,
+        0,10,10, 0,12,12, 0,10,10, 0,12,13, 0,12,12, 0,
+       13,13, 0,14,14, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44p3_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p3_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p3_1[] = {
+        3, 4, 4, 0, 8, 8, 0, 8, 8, 0, 9, 9, 0,10,10, 0,
+        8, 8, 0, 9, 9, 0,10,10, 0, 8, 8, 0, 7, 7, 0, 8,
+        8, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8,
+        0, 8, 8, 0, 8, 8, 0, 7, 7, 0, 6, 6, 0, 7, 7, 0,
+        7, 7, 0,10,10, 0, 6, 6, 0, 7, 7, 0,10,10, 0, 6,
+        5, 0, 8, 8, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0, 9, 9,
+        0, 7, 7, 0, 8, 8, 0, 9, 9, 0, 7, 7, 0, 6, 6, 0,
+        9,10, 0,10,10, 0,10,10, 0,11,11, 0, 9, 9, 0,10,
+       10, 0,11,11, 0, 9, 9, 0, 8, 8, 0, 8, 8, 0, 8, 8,
+        0, 9, 9, 0, 9, 9, 0, 8, 8, 0, 8, 8, 0, 9, 9, 0,
+        7, 7, 0, 8, 8, 0, 7, 7, 0, 7, 7, 0, 8, 8, 0, 9,
+        9, 0, 7, 7, 0, 7, 7, 0, 9, 9, 0, 6, 6, 0, 6, 6,
+        0,10,10, 0,10,10, 0,10,10, 0,12,12, 0, 9, 9, 0,
+       10,10, 0,12,12, 0, 9, 9, 0, 8, 8, 0, 7, 7, 0, 8,
+        8, 0, 8, 8, 0, 9, 9, 0, 7, 7, 0, 8, 8, 0, 9, 9,
+        0, 7, 7,
+};
+
+static const static_codebook _44p3_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p3_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p4_0[] = {
+        1, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8,10,11,11, 9,
+        8, 8, 8, 8, 8,11,11,11,10, 8, 8, 5, 7, 7, 9,11,
+       11,10,11,11,10,11,11,12,13,14,11,12,12,10,11,11,
+       13,14,14,12,12,12, 5, 6, 6, 8, 6, 6, 8, 7, 7, 8,
+        7, 7,11,10,10,10, 7, 7, 9, 7, 7,12,11,11,11, 7,
+        7, 7, 7, 7,11,10,10,12,10,10,11,10,10,15,13,13,
+       13,10,10,12,11,11,15,13,13,14,11,11, 7, 7, 7,11,
+       11,11,12,11,11,12,11,11,14,14,14,14,12,12,12,12,
+       12,16,15,15,14,12,12, 0,10,10, 0,11,11, 0,11,12,
+        0,11,11, 0,14,14, 0,11,11, 0,12,12, 0,15,15, 0,
+       11,11, 8, 8, 8,12,10,10,12,10,10,13,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,14,10,10, 8, 7, 7,
+       12,11,11,13,11,11,12,11,11,15,14,14,14,12,12,13,
+       12,12,15,14,14,15,12,12, 0,11,11, 0,12,12, 0,12,
+       12, 0,12,12, 0,15,15, 0,12,12, 0,13,13, 0,14,15,
+        0,12,12,
+};
+
+static const static_codebook _44p3_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p3_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p3_p4_1[] = {
+        3, 4, 5, 8, 8,12,10,10,12,12,12,10,10,12,12,13,
+       11,11,12,12,13,12,12,12,12,13,10,10,13,13,13,13,
+       13,13,13,13,10,10,13,13,13,11,11,13,13,14,13,13,
+       12,12,13,10,10,13,13,13,13,13,13,13,13,10,10,12,
+       12,13,11,11,13,13,13,13,13,12,12,13,12,12,13,13,
+       13,13,13,13,13,14,11,11,12,12,14,12,12,13,12,14,
+       14,14,12,12,13,14,14,13,13,14,13,13,13,13,14,14,
+       14,12,12,14,13,13,13,13,14,14,14,12,12,12, 8, 8,
+       11,11,12,12,12,11,11,12,11,11,10,10,13,12,12,10,
+       10,13,12,12,10,10,13,12,12,12,12,14,12,12,12,12,
+       13,13,13,11,11,14,12,12,11,11,14,12,12,12,12,14,
+       12,12,12,12,13,12,12,12,12,13,13,13,11,11,14,12,
+       12,11,11,14,12,12,12,12,14,13,13,12,12,14,12,12,
+       12,11,14,13,13,11,11,14,13,12,11,11,14,13,13,11,
+       11,14,13,13,12,12,14,12,12,12,12,15,13,13,12,12,
+       14,12,12,11,11,14,13,13,11,11,12, 9, 9,10,10,12,
+        7, 7,11,11,12, 9, 9,12,12,13,10,10,10,10,14,14,
+       14,11,11,13, 9, 9,12,12,14,14,14,12,12,13, 8, 8,
+       11,11,14, 9, 9,12,12,14,14,14,11,11,13, 9, 9,12,
+       12,14,14,14,12,12,14, 8, 8,11,11,14, 9, 9,12,12,
+       14,14,14,11,11,14,10,10,12,12,14,14,14,13,13,14,
+        9, 9,11,11,14,10,10,12,12,14,14,14,11,11,14,14,
+       15,12,12,15,14,14,14,14,15,14,14,11,11,14,14,14,
+       12,12,14,14,14,11,11,14,11,11,10,10,14,10,10,10,
+       10,14,10,10,10,10,15,11,11, 9, 9,14,12,12, 9, 9,
+       15,11,11,11,11,15,13,13,11,11,15,10,10,10,10,15,
+       11,11,10,10,15,13,13,11,11,15,11,11,11,11,15,13,
+       13,11,11,15,10,10,10,10,15,11,11,10,10,15,13,13,
+       11,11,15,12,12,11,11,15,13,13,11,11,15,11,11,10,
+       10,15,12,12,10,10,15,13,13,10,10,15,14,14,11,11,
+       15,13,13,11,11,15,14,14,10,11,15,13,13,10,10,15,
+       13,14,10,10,14,13,13,10,10,14,13,13,10,10,14,13,
+       13,10,10,14,13,13, 9, 9,14,14,14, 9, 9,15,14,14,
+       11,11,15,14,14,10,10,15,14,14,10,10,15,14,14,11,
+       11,15,14,14,10,10,15,14,14,11,11,15,14,14,10,10,
+       14,14,14,10,10,15,14,14,10,10,14,14,14,10,10,15,
+       14,14,11,11,15,14,14,11,11,14,14,14,10,10,15,14,
+       14,10,10,14,14,14, 9, 9,15,15,15,11,11,15,14,14,
+       12,12,15,15,14,10,10,15,14,14,10,10,14,15,15, 9,
+        9,14,10,10,12,12,17, 9, 9,12,12,17,10,10,13,13,
+       17,11,11,12,12,18,14,14,12,12,17,10,10,13,13,17,
+       14,14,12,12,17, 9, 9,12,12,17,11,11,12,12,17,14,
+       14,12,12,18,10,10,13,13,18,14,14,13,13,18, 9, 9,
+       12,12,18,10,10,13,13,18,14,14,12,12,18,11,11,13,
+       13,18,14,14,13,13,18,10,10,12,12,17,11,11,12,12,
+       17,14,14,12,12,18,15,15,13,13,18,14,14,14,14,18,
+       15,15,12,12,18,14,14,12,12,18,15,15,12,12,13, 7,
+        7,11,11,14,15,15,11,11,14,15,15,12,12,14,15,15,
+       11,11,15,15,15,11,11,14,15,15,12,12,14,15,15,12,
+       12,14,15,15,11,11,14,15,15,11,11,15,15,15,12,12,
+       14,15,15,12,12,14,15,15,12,12,14,15,15,11,11,14,
+       15,15,11,11,15,15,15,12,12,15,15,15,12,12,14,15,
+       15,12,12,14,15,14,12,12,14,15,15,11,11,15,14,14,
+       12,12,15,15,15,12,12,15,16,16,12,12,15,15,15,12,
+       12,15,15,15,12,12,15,15,15,12,12,13,13,13,11,10,
+       14,14,15,11,11,14,14,14,12,12,15,14,14,10,10,15,
+       15,15,11,11,14,15,15,12,12,14,14,14,11,11,14,15,
+       15,11,11,14,15,15,12,12,15,15,15,11,11,14,15,15,
+       12,12,14,14,14,12,12,14,15,15,11,11,14,15,15,12,
+       12,15,15,15,11,11,15,15,15,12,12,15,14,14,12,12,
+       14,15,15,11,11,14,15,15,11,11,15,15,15,10,10,15,
+       15,16,12,12,15,15,15,14,14,15,15,15,11,11,15,15,
+       15,12,12,15,15,15,11,11,14,11,11,10,10,15, 9, 9,
+       12,12,15,10,10,12,12,15,11,11,11,11,15,14,14,12,
+       12,15,10,10,13,13,15,14,14,12,12,15, 9, 9,12,12,
+       15,10,10,13,13,15,13,13,12,11,15,10,10,12,12,15,
+       14,14,12,12,15, 9, 9,11,11,15,11,11,12,12,15,13,
+       13,11,11,15,11,11,13,13,15,13,14,13,14,15,11,11,
+       11,11,15,11,11,12,12,15,14,14,11,11,15,14,14,13,
+       13,15,14,14,20,20,15,14,14,12,12,15,14,14,12,12,
+       15,14,14,11,11,14,13,13,10,10,14,13,13,12,12,14,
+       14,13,12,12,15,14,14,12,12,15,14,14,11,11,15,14,
+       14,12,12,15,14,14,13,13,15,14,14,12,11,15,14,14,
+       11,11,15,14,14,13,13,15,14,14,12,12,15,14,14,13,
+       13,15,14,14,12,11,15,14,14,12,12,15,14,14,13,13,
+       15,14,14,13,13,15,14,14,12,12,15,14,14,12,12,15,
+       14,14,12,12,15,15,15,13,13,15,15,15,13,13,15,14,
+       14,13,13,15,15,15,13,13,15,14,15,12,12,15,15,15,
+       13,13,14,10,10,12,13,17, 9, 9,12,12,17,10,10,13,
+       13,17,11,11,12,12,18,14,14,12,12,18,10,10,13,13,
+       18,14,14,12,12,17, 9, 9,12,12,18,10,11,13,13,18,
+       14,14,12,12,17,10,10,12,12,17,14,14,12,12,17, 9,
+        9,12,12,17,11,11,12,12,17,14,14,12,12,18,11,11,
+       12,12,18,14,14,13,13,18,11,11,12,12,18,11,11,12,
+       12,18,14,14,12,12,18,15,15,12,12,18,14,14,13,13,
+       18,15,15,12,12,17,14,14,12,12,17,15,15,12,12,13,
+        7, 7,11,11,14,15,15,11,11,14,15,15,11,11,14,15,
+       14,12,12,15,15,15,12,11,14,15,15,12,12,14,15,15,
+       12,12,14,15,15,11,11,14,15,15,11,11,15,15,15,13,
+       13,14,15,15,11,11,14,15,15,13,12,14,15,15,11,11,
+       14,15,15,11,11,15,15,15,13,13,14,15,15,12,12,15,
+       15,15,12,12,15,15,15,11,11,15,15,15,11,11,15,15,
+       15,12,12,15,15,15,13,13,15,16,16,12,12,15,15,15,
+       12,13,15,15,15,12,12,15,15,15,12,12,13,13,13,11,
+       11,14,14,14,11,11,14,14,14,12,12,14,14,14,10,10,
+       15,14,14,11,11,14,15,15,12,12,14,14,14,12,12,14,
+       15,15,11,11,14,15,14,12,12,15,14,14,11,11,14,15,
+       15,12,12,14,14,14,11,11,14,15,15,11,11,14,14,14,
+       12,12,15,15,14,11,11,15,15,15,12,12,15,14,14,12,
+       12,14,15,15,11,11,14,15,14,11,11,15,15,15,10,10,
+       15,15,15,12,12,15,14,14,14,13,15,15,15,11,11,15,
+       15,15,11,11,15,15,15,10,10,14,11,11,10,10,15, 9,
+        9,12,12,15,10,10,12,12,15,11,11,11,11,15,14,14,
+       12,12,15,10,10,13,13,15,13,13,12,12,15, 9, 9,12,
+       12,15,11,11,13,13,15,14,14,12,12,15,10,10,13,13,
+       15,13,14,12,12,15, 9, 9,12,12,15,10,10,13,13,15,
+       13,13,11,11,15,11,11,13,13,15,14,14,13,13,15,10,
+       10,11,11,15,11,11,12,12,15,14,14,11,11,15,14,14,
+       13,13,15,14,14,21,20,15,14,14,11,11,15,14,14,12,
+       12,15,14,14,11,11,14,13,13,10,10,14,13,13,11,11,
+       15,14,14,12,12,15,14,14,12,12,14,14,14,12,12,15,
+       14,14,12,12,15,14,14,13,13,14,14,14,11,11,15,14,
+       14,11,11,15,14,14,13,13,15,14,14,12,12,15,14,14,
+       13,13,14,14,14,11,11,15,14,14,11,11,14,14,14,13,
+       13,15,14,14,12,12,15,14,14,12,12,15,14,14,12,12,
+       15,14,14,12,12,14,14,14,13,13,15,15,15,13,13,16,
+       14,14,12,13,15,15,15,13,13,15,14,14,12,12,15,15,
+       15,13,13,15,11,11,13,12,18,10,10,12,12,17,11,11,
+       12,12,18,12,12,11,11,18,14,14,12,12,18,11,11,13,
+       13,17,14,14,12,12,18,10,10,12,12,18,12,12,12,12,
+       18,14,15,12,12,18,11,11,13,13,18,14,14,12,12,17,
+       10,10,12,12,18,11,11,12,12,18,15,14,12,12,17,12,
+       12,12,12,17,14,14,12,12,17,11,11,11,11,17,12,12,
+       12,11,17,15,15,11,11,18,15,15,12,12,18,14,15,13,
+       13,18,15,15,11,11,17,15,15,12,12,18,15,15,11,11,
+       14, 9, 9,11,11,14,15,15,11,11,15,15,15,11,11,15,
+       15,15,12,11,15,15,15,12,12,15,15,15,11,11,15,15,
+       15,13,13,14,15,15,11,11,15,15,15,11,11,15,15,15,
+       13,13,15,15,15,11,11,15,15,15,13,13,15,15,15,11,
+       11,15,15,15,11,11,15,15,15,13,13,15,15,15,12,12,
+       15,15,15,13,13,15,15,14,11,11,15,15,15,12,12,15,
+       15,15,12,12,16,15,15,13,13,15,16,16,13,13,16,15,
+       15,12,12,15,15,15,13,12,15,15,15,12,12,13,12,12,
+       11,11,14,14,14,11,11,14,14,14,12,12,15,14,14,11,
+       11,15,14,14,12,12,15,14,14,12,12,15,14,14,12,12,
+       14,15,15,11,11,15,14,14,12,12,15,14,14,11,11,15,
+       14,14,12,12,15,14,14,12,12,14,15,15,11,11,15,14,
+       14,12,12,15,14,14,11,11,15,15,15,12,12,15,14,14,
+       12,12,15,15,15,11,11,15,14,14,11,11,15,14,15,11,
+       11,15,15,15,12,12,15,14,14,13,13,16,15,15,11,11,
+       15,14,14,12,12,15,15,15,11,11,14,11,11, 9, 9,15,
+       10,10,12,12,14,11,11,12,12,15,12,12,12,12,15,14,
+       14,13,13,15,11,11,13,13,15,14,14,13,13,15,10,10,
+       12,12,15,12,12,13,13,15,14,14,13,13,15,11,11,12,
+       12,15,14,14,13,13,14,10,10,12,12,15,12,12,13,13,
+       15,14,14,12,12,15,12,12,13,13,15,14,14,15,15,15,
+       11,11,12,12,15,12,12,12,13,15,14,14,12,12,15,15,
+       15,14,14,15,14,14,20,20,15,14,14,12,12,15,14,14,
+       13,13,15,14,14,12,12,14,13,13,10,10,14,13,13,11,
+       11,14,13,13,12,12,14,14,14,12,12,15,14,14,13,13,
+       15,14,14,12,12,14,14,14,14,14,14,14,14,11,11,15,
+       14,14,12,12,15,14,14,14,14,15,14,14,12,12,14,14,
+       14,14,14,14,14,14,11,11,15,14,14,12,12,14,14,14,
+       14,14,15,14,14,12,12,15,14,14,13,13,15,14,14,12,
+       12,15,14,14,12,12,14,14,14,14,13,15,15,15,14,14,
+       15,14,14,13,13,15,15,15,14,14,15,14,14,13,13,15,
+       15,15,13,13,14,13,13,13,13,18,15,15,12,12,18,15,
+       15,13,12,18,15,16,11,11,18,16,17,12,12,18,15,15,
+       13,13,18,17,17,12,12,18,15,15,12,12,17,15,15,12,
+       12,18,17,17,12,12,18,15,15,13,13,18,16,17,12,12,
+       17,15,15,12,12,18,15,15,12,12,18,16,17,11,12,18,
+       16,16,12,12,17,16,17,12,12,18,15,15,11,11,18,15,
+       15,12,12,18,17,17,11,11,17,17,17,12,12,18,16,16,
+       13,13,18,17,17,11,11,18,16,16,12,12,18,17,17,11,
+       11,15,14,14,11,11,16,15,15,11,11,16,15,15,12,12,
+       16,15,15,12,12,17,15,15,14,13,16,15,15,12,12,17,
+       15,15,14,14,16,15,15,11,11,16,15,15,12,12,18,15,
+       15,13,13,16,15,15,11,11,17,15,15,14,14,16,15,15,
+       11,11,16,15,15,12,12,17,15,15,13,13,16,15,15,12,
+       12,17,16,15,14,14,16,14,15,12,12,16,15,15,12,12,
+       18,15,15,13,13,17,15,15,14,14,17,16,16,15,15,17,
+       15,15,13,13,17,15,15,14,14,18,15,15,13,13,15,12,
+       13,11,11,15,14,14,12,12,16,14,14,12,12,16,14,14,
+       12,12,16,14,14,12,12,16,14,14,13,12,17,14,14,13,
+       13,16,15,15,12,12,16,14,14,12,12,17,14,14,12,12,
+       16,14,14,12,12,17,14,14,13,13,15,15,15,12,12,16,
+       14,14,12,12,17,14,14,12,12,17,15,15,12,12,17,14,
+       14,13,13,16,15,15,12,12,16,14,14,12,12,17,15,15,
+       12,12,18,15,15,13,13,17,14,14,13,13,17,15,15,12,
+       12,17,14,14,12,12,17,15,15,12,12,14,15,15, 9, 9,
+       15,15,15,12,12,15,15,15,13,13,15,15,15,14,14,15,
+       15,15,19,19,15,15,16,13,13,15,15,16,19,20,15,15,
+       15,13,12,15,16,16,14,14,15,15,15,19,19,15,15,15,
+       13,13,15,16,15,20,19,14,15,15,13,13,15,15,15,14,
+       14,15,15,15,19,19,15,15,15,14,14,15,16,16,19,20,
+       15,15,15,14,14,15,15,15,14,14,15,15,15,19,19,15,
+       15,15,20,19,15,16,16,20,19,15,15,15,19,19,15,16,
+       16,20,20,15,15,15,19,20,14,13,13,10,10,14,14,14,
+       11,11,14,14,14,12,12,15,14,14,13,13,15,14,14,19,
+       20,15,14,14,12,12,14,14,14,20,19,14,14,14,11,11,
+       15,14,14,12,12,15,14,14,20,20,15,14,14,12,12,14,
+       14,14,20,19,14,14,14,11,11,15,14,14,12,12,15,14,
+       14,19,20,15,14,14,13,13,15,14,14,22,19,15,15,14,
+       12,12,15,14,14,13,13,14,15,15,22,20,15,15,15,20,
+       20,15,14,14,21,20,15,15,15,20,21,15,14,14,20,20,
+       14,15,15,20,20,
+};
+
+static const static_codebook _44p3_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p3_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p3_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p3_p5_0[] = {
+        2, 6, 6,14,14, 6, 7, 7,14,14, 7, 7, 7,15,15, 0,
+       12,12,15,15, 0,13,13,15,15, 7, 8, 8,15,15,10,10,
+       10,16,16, 9, 8, 8,15,15, 0,13,13,18,17, 0,13,13,
+       16,16, 8, 8, 8,15,15,12,11,11,16,16, 9, 8, 8,15,
+       15, 0,13,13,18,18, 0,13,13,16,16, 0,14,14,17,17,
+        0,20, 0,19,20, 0,12,12,16,16, 0,16,16,20,22, 0,
+       14,14,16,16, 0,14,14,17,17, 0,20,22,20,19, 0,13,
+       13,15,16, 0,17,18, 0,21, 0,15,15,16,16, 5, 7, 7,
+       13,13, 8, 9, 9,14,14,10,10,10,14,14, 0,20,22,18,
+       18, 0,22,21,18,17, 9,10,10,14,14,12,12,12,17,17,
+       12,10,10,14,14, 0, 0,20,17,17, 0,22,21,17,18,11,
+       10,10,14,14,14,13,13,18,18,12,11,11,14,14, 0,22,
+       21,18,19, 0,20, 0,17,17, 0,22, 0,18,18, 0, 0, 0,
+        0, 0, 0,20,20,17,17, 0,22, 0,22,21, 0,21, 0,19,
+       18, 0,22,22,18,18, 0, 0, 0, 0, 0, 0,21, 0,17,17,
+        0,22, 0,20,20, 0, 0, 0,19,18, 6, 6, 6,12,12, 8,
+        6, 6,10,10, 8, 6, 6,13,12, 0,10,10,11,11, 0,11,
+       11,13,13, 8, 7, 7,13,13,11, 9, 9,13,13,10, 6, 6,
+       12,12, 0,10,10,14,14, 0,10,10,13,13, 9, 7, 7,13,
+       13,12,10,10,13,13,10, 6, 6,12,12, 0,11,11,15,15,
+        0,10,10,13,13, 0,12,12,15,14, 0,19,20,16,17, 0,
+        9, 9,13,13, 0,14,14,20,21, 0,12,11,13,12, 0,12,
+       12,15,14, 0,20,19,17,17, 0,10,10,12,13, 0,15,15,
+       22,21, 0,12,12,12,13, 0,10,10,12,12, 0,11,11,15,
+       15, 0,11,11,15,15, 0,15,15,22,22, 0,16,17, 0, 0,
+        0,11,11,15,15, 0,14,14,18,18, 0,11,11,16,16, 0,
+       16,15, 0,21, 0,16,16, 0, 0, 0,12,12,15,15, 0,14,
+       14,19,19, 0,11,11,15,15, 0,15,15,22, 0, 0,16,16,
+       22, 0, 0,16,16, 0,21, 0, 0, 0, 0, 0, 0,15,15,19,
+       20, 0,18,18, 0, 0, 0,17,17, 0, 0, 0,17,17, 0, 0,
+        0, 0, 0, 0, 0, 0,16,15,22,21, 0,20,20, 0, 0, 0,
+       18,18, 0, 0, 0,10,10,12,12, 0,10,10,11,11, 0,11,
+       11,12,12, 0,11,11, 9, 9, 0,13,12,12,12, 0,11,11,
+       13,13, 0,13,13,12,12, 0,10,10,12,12, 0,13,12,13,
+       13, 0,12,12,12,12, 0,11,11,13,13, 0,13,13,12,12,
+        0,10,10,12,12, 0,13,13,14,13, 0,12,12,12,12, 0,
+       14,13,13,14, 0,20,21,15,15, 0,11,11,12,12, 0,15,
+       16,20,20, 0,12,13,10,10, 0,13,13,14,13, 0,20,20,
+       15,15, 0,11,11,12,12, 0,16,17,21,21, 0,13,13,11,
+       11, 6, 7, 7,16,15,11, 9, 9,14,15,12, 9, 9,16,16,
+        0,13,13,15,15, 0,14,14,17,17,10, 9, 9,16,16,14,
+       12,12,16,16,12, 9, 9,15,15, 0,13,13,17,18, 0,13,
+       13,15,15,12,10,10,17,17,15,12,12,17,17,13, 9, 9,
+       16,16, 0,13,13,18,19, 0,14,14,16,16, 0,15,15,18,
+       18, 0, 0, 0,20,19, 0,12,12,17,16, 0,16,17, 0,21,
+        0,14,15,16,16, 0,15,15,18,18, 0, 0,22,19,21, 0,
+       13,13,16,16, 0,18,17,22,22, 0,15,15,16,16, 7, 7,
+        7,13,13,11,10,10,15,15,12,10,10,14,14, 0,21, 0,
+       18,17, 0,21,22,18,18,11,10,10,15,15,14,12,12,17,
+       17,14,11,11,14,14, 0,21,20,18,18, 0,22,21,18,17,
+       12,11,10,16,16,16,14,14,17,19,14,11,11,15,15, 0,
+        0,22,19,19, 0,21,22,18,18, 0,21, 0,18,19, 0, 0,
+        0,22, 0, 0,22,21,17,17, 0, 0, 0,20,22, 0, 0,21,
+       18,18, 0, 0, 0,19,20, 0, 0, 0, 0, 0, 0, 0,21,17,
+       17, 0, 0, 0,22,21, 0, 0, 0,19,19,10, 9, 9,14,13,
+       13,10,10,12,12,13,10,10,14,14, 0,13,13,12,12, 0,
+       15,14,16,15,13,10,10,14,14,15,12,12,14,14,15,10,
+       10,14,14, 0,14,14,15,15, 0,14,13,14,14,13,10,10,
+       15,15,17,13,13,15,15,14,10,10,14,14, 0,14,14,15,
+       16, 0,14,14,15,15, 0,15,15,16,16, 0,21,22,17,18,
+        0,12,12,14,14, 0,17,17,20,21, 0,14,14,14,14, 0,
+       15,15,16,16, 0,21,22,18,18, 0,13,13,14,14, 0,18,
+       18,22, 0, 0,15,15,14,14, 0,11,11,13,13, 0,12,12,
+       16,15, 0,12,12,16,16, 0,16,16, 0, 0, 0,16,17, 0,
+       22, 0,12,12,16,16, 0,14,14,17,18, 0,11,11,16,16,
+        0,15,15, 0,21, 0,16,16,21,22, 0,12,12,16,16, 0,
+       15,15,19,19, 0,12,12,17,16, 0,16,16,21,22, 0,16,
+       16, 0, 0, 0,17,17, 0,22, 0, 0, 0, 0, 0, 0,15,15,
+       19,20, 0,17,19, 0, 0, 0,17,17,22, 0, 0,17,17, 0,
+       22, 0, 0, 0, 0, 0, 0,15,15,21, 0, 0,19,20, 0, 0,
+        0,19,18,22, 0, 0,11,12,14,14, 0,11,11,14,14, 0,
+       12,12,15,15, 0,13,13,13,13, 0,14,14,16,16, 0,12,
+       12,15,15, 0,14,14,16,15, 0,11,11,15,15, 0,13,13,
+       16,16, 0,13,13,15,15, 0,12,12,15,15, 0,15,14,16,
+       16, 0,11,11,15,15, 0,14,14,17,17, 0,13,13,15,15,
+        0,15,15,16,16, 0, 0, 0,18,18, 0,12,12,14,14, 0,
+       16,16,22, 0, 0,14,14,15,15, 0,15,15,16,17, 0,21,
+       22,18,18, 0,13,13,15,14, 0,18,17,22, 0, 0,14,14,
+       15,15, 8, 8, 8,16,15,12,10,10,16,15,12,10,10,16,
+       16, 0,14,14,16,17, 0,14,14,17,16,12,10,10,17,18,
+       14,12,12,18,18,14,10,10,16,16, 0,14,14,18,18, 0,
+       14,14,16,16,12, 9, 9,16,16,17,13,13,16,17,14, 9,
+        9,15,15, 0,14,14,18,19, 0,13,13,15,15, 0,15,15,
+       18,19, 0, 0, 0,22,21, 0,13,13,16,16, 0,16,16,22,
+        0, 0,15,15,16,16, 0,14,14,18,17, 0, 0, 0,20, 0,
+        0,13,13,16,16, 0,18,18, 0, 0, 0,15,15,16,16, 8,
+        7, 7,13,13,12,10,10,15,15,12,10,10,14,14, 0,22,
+       22,19,18, 0, 0, 0,18,18,12,10,10,15,15,14,13,13,
+       17,17,14,11,11,15,15, 0,19,20,18,18, 0,22,21,17,
+       18,13,11,11,15,15,16,13,13,18,18,14,11,11,14,15,
+        0,22,21,20,19, 0,22,21,17,17, 0, 0,22,19,18, 0,
+        0, 0, 0, 0, 0,22,20,17,17, 0, 0, 0,21,20, 0, 0,
+        0,19,17, 0, 0,22,19,19, 0, 0, 0, 0, 0, 0,22,20,
+       18,17, 0, 0, 0, 0, 0, 0, 0, 0,18,18, 0,10,10,14,
+       14, 0,11,11,14,14, 0,11,11,15,15, 0,14,14,14,14,
+        0,15,15,16,16, 0,11,11,16,16, 0,13,13,16,16, 0,
+       11,11,15,15, 0,14,14,16,16, 0,14,14,15,15, 0,11,
+       11,15,15, 0,13,13,15,15, 0,10,10,15,15, 0,15,15,
+       17,17, 0,14,14,14,14, 0,16,16,16,16, 0, 0,22,19,
+       19, 0,13,13,14,14, 0,17,17, 0, 0, 0,15,15,14,14,
+        0,16,16,17,17, 0, 0,22,18,18, 0,13,13,14,14, 0,
+       21,18, 0, 0, 0,15,15,14,14, 0,11,11,13,13, 0,12,
+       12,15,15, 0,12,12,16,15, 0,16,16, 0, 0, 0,17,17,
+       22,22, 0,12,12,16,16, 0,14,14,18,18, 0,11,12,16,
+       16, 0,15,16, 0,21, 0,16,16,22,21, 0,12,12,16,16,
+        0,15,15,19,20, 0,11,12,16,16, 0,15,15,20,22, 0,
+       16,16, 0,22, 0,17,17,22, 0, 0, 0, 0, 0, 0, 0,15,
+       15,21,22, 0,19,18, 0, 0, 0,17,17, 0, 0, 0,17,17,
+        0,22, 0, 0, 0, 0, 0, 0,16,15,22, 0, 0,19,19, 0,
+        0, 0,17,18, 0, 0, 0,12,12,15,15, 0,12,12,15,15,
+        0,12,12,15,15, 0,13,13,14,14, 0,15,15,16,17, 0,
+       12,12,16,16, 0,14,14,16,16, 0,12,11,15,16, 0,14,
+       14,16,17, 0,14,14,16,16, 0,13,12,16,16, 0,15,15,
+       16,16, 0,11,11,15,15, 0,14,14,16,16, 0,14,14,15,
+       15, 0,15,15,18,17, 0, 0,22, 0,20, 0,13,13,15,15,
+        0,16,17,22,22, 0,14,14,15,15, 0,15,15,17,18, 0,
+       20, 0,19,19, 0,13,13,15,15, 0,18,18,22, 0, 0,14,
+       14,15,15, 0,11,11,16,16, 0,14,14,17,16, 0,13,13,
+       17,17, 0,16,16,17,17, 0,17,17,18,19, 0,12,12,16,
+       17, 0,15,15,18,18, 0,12,12,16,16, 0,16,16,19,18,
+        0,16,16,17,16, 0,12,13,17,17, 0,17,16,18,17, 0,
+       13,12,16,16, 0,16,16,18,19, 0,16,16,16,17, 0,16,
+       16,18,18, 0,22, 0,22,22, 0,13,13,16,16, 0,19,18,
+       22,20, 0,16,15,16,16, 0,16,17,18,18, 0, 0, 0,22,
+       20, 0,14,14,16,16, 0,19,19, 0, 0, 0,16,16,16,16,
+        0, 9, 9,13,13, 0,13,13,15,15, 0,14,14,15,15, 0,
+        0,22,17,18, 0,22, 0,18,19, 0,12,12,15,15, 0,15,
+       16,17,17, 0,14,14,14,14, 0,22, 0,18,18, 0,21,22,
+       17,17, 0,13,13,15,15, 0,17,17,17,18, 0,14,14,15,
+       15, 0,22,21,21,19, 0,20,21,17,17, 0,21,21,19,18,
+        0, 0, 0, 0, 0, 0,21,21,17,17, 0, 0, 0,22,22, 0,
+        0,22,19,18, 0, 0,21,19,18, 0, 0, 0, 0,22, 0,19,
+       20,17,17, 0, 0, 0, 0,22, 0, 0, 0,19,18, 0,19,19,
+       15,16, 0,21,19,16,17, 0, 0,21,17,17, 0, 0,22,17,
+       17, 0,22,22,18,19, 0,20,20,16,16, 0, 0,22,18,18,
+        0,20,19,16,17, 0,22,21,20,19, 0, 0,21,17,17, 0,
+       21,20,17,17, 0, 0, 0,18,18, 0,19,19,17,16, 0,22,
+        0,19,19, 0,21,22,17,18, 0, 0,22,19,18, 0, 0, 0,
+       19,20, 0,19,19,16,16, 0,22,22,22, 0, 0,20,22,16,
+       16, 0,22,20,18,19, 0, 0, 0,20,19, 0,20,20,16,16,
+        0, 0, 0, 0, 0, 0,22,20,17,16, 0,11,11,13,13, 0,
+       14,13,15,15, 0,13,13,16,15, 0,18,17,21, 0, 0,18,
+       18,21, 0, 0,12,12,15,15, 0,15,16,17,18, 0,12,12,
+       15,15, 0,17,17,22,20, 0,17,18,22, 0, 0,12,12,17,
+       16, 0,16,17,19,19, 0,13,13,16,16, 0,17,17, 0,22,
+        0,17,17, 0,21, 0,18,18,20,22, 0, 0, 0, 0, 0, 0,
+       15,15,21,20, 0,20,19, 0, 0, 0,18,18,22, 0, 0,17,
+       17,22, 0, 0, 0, 0, 0, 0, 0,15,16,20,22, 0,20,21,
+        0, 0, 0,19,18, 0, 0, 0,15,15,19,19, 0,17,16,20,
+       20, 0,16,17,20,21, 0,18,17, 0, 0, 0,19,19, 0, 0,
+        0,15,15,21,19, 0,19,19, 0, 0, 0,15,15,22,22, 0,
+       18,18, 0,22, 0,17,18,22,21, 0,15,15,20,19, 0,19,
+       19, 0, 0, 0,15,15,20,22, 0,18,19,20, 0, 0,18,17,
+       21,21, 0,18,18,19,22, 0, 0, 0, 0, 0, 0,15,15,20,
+       19, 0,19,19, 0, 0, 0,18,18,21,22, 0,18,18,22, 0,
+        0, 0, 0, 0, 0, 0,15,15,19,20, 0,21,21, 0, 0, 0,
+       17,17,20,20, 0,12,12,17,17, 0,14,14,16,17, 0,13,
+       14,17,17, 0,16,16,17,17, 0,17,17,17,19, 0,13,13,
+       17,17, 0,16,16,18,18, 0,13,13,16,16, 0,16,16,18,
+       18, 0,16,16,17,17, 0,13,13,17,17, 0,17,17,18,17,
+        0,12,12,15,16, 0,17,18,19,20, 0,16,16,16,16, 0,
+       17,16,18,19, 0, 0,22,21,22, 0,14,14,16,16, 0,19,
+       19, 0, 0, 0,16,16,16,16, 0,16,16,18,17, 0, 0,22,
+       21,21, 0,14,14,16,16, 0,22,20,22, 0, 0,16,16,15,
+       15, 0, 9, 9,13,13, 0,14,14,15,15, 0,14,14,14,14,
+        0,22,22,18,18, 0, 0,22,18,18, 0,12,12,15,15, 0,
+       16,16,18,17, 0,14,14,14,14, 0,20,21,18,18, 0,22,
+       21,17,17, 0,13,13,15,15, 0,17,17,18,18, 0,14,14,
+       14,14, 0, 0,21,18,19, 0, 0,22,17,17, 0,22,22,19,
+       18, 0, 0, 0, 0, 0, 0,19,21,17,17, 0, 0, 0,22,20,
+        0, 0,21,18,19, 0, 0,22,18,18, 0, 0, 0, 0,22, 0,
+       20,22,17,17, 0, 0, 0,20,22, 0, 0, 0,18,18, 0,19,
+       21,16,16, 0,20,22,16,17, 0,20, 0,17,17, 0,22, 0,
+       18,17, 0,21, 0,18,19, 0,20,20,17,17, 0,22, 0,18,
+       18, 0,21,20,17,17, 0, 0,20,20,19, 0, 0,21,18,17,
+        0,21,21,17,17, 0,22, 0,18,17, 0,19,19,17,17, 0,
+        0,22,20,21, 0, 0,21,17,17, 0,22, 0,18,18, 0, 0,
+        0,20,22, 0,20,19,16,16, 0, 0, 0, 0, 0, 0,22,22,
+       17,17, 0,22, 0,18,19, 0, 0, 0,21,20, 0,19,21,16,
+       17, 0, 0, 0, 0, 0, 0,22,22,17,16, 0,11,11,13,13,
+        0,13,13,15,15, 0,13,13,15,15, 0,17,17,22,21, 0,
+       18,18,22, 0, 0,12,13,16,15, 0,15,16,18,18, 0,13,
+       13,16,16, 0,17,17, 0,22, 0,17,17,22,22, 0,13,13,
+       16,16, 0,16,16,19,18, 0,13,13,16,16, 0,18,17, 0,
+       20, 0,18,17,20, 0, 0,17,17,21, 0, 0, 0, 0, 0, 0,
+        0,15,15,21,22, 0,19,20, 0, 0, 0,18,18, 0, 0, 0,
+       18,17, 0, 0, 0, 0, 0, 0, 0, 0,16,16,22,22, 0,20,
+       20, 0, 0, 0,21,19, 0, 0, 0,15,15,20,19, 0,16,16,
+       22,20, 0,17,17, 0,22, 0,18,18, 0,22, 0,19,17, 0,
+        0, 0,15,16,22,20, 0,18,19, 0, 0, 0,16,16,22,20,
+        0,18,18, 0,22, 0,18,18,22, 0, 0,16,16,21,20, 0,
+       19,20, 0,22, 0,16,16, 0,22, 0,18,18, 0,22, 0,18,
+       18, 0,21, 0,19,18, 0,22, 0, 0, 0, 0, 0, 0,16,16,
+       21,20, 0,20, 0, 0, 0, 0,18,18,21, 0, 0,18,18, 0,
+        0, 0, 0, 0, 0, 0, 0,16,16,21,19, 0, 0, 0, 0, 0,
+        0,18,18, 0,21,
+};
+
+static const static_codebook _44p3_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p3_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p3_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p3_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p3_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p3_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p3_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p6_0[] = {
+        1, 6, 6, 7, 7, 7, 7, 8, 8, 7, 9, 9,11,11,11, 9,
+        8, 8, 8, 9, 9,12,11,11, 9, 8, 8, 6, 7, 7,10,11,
+       10,10,10,10,11,11,10,14,13,14,12,11,11,11,11,11,
+       15,14,14,13,12,12, 5, 6, 6, 8, 5, 5, 8, 7, 7, 8,
+        8, 8,12,10,10, 9, 7, 7, 9, 7, 8,12,10,10,10, 7,
+        7, 7, 8, 8,12,10,10,12,10,10,11,10,10,15,13,13,
+       13,10,10,11,10,10,16,13,14,14,10,10, 7, 7, 7,12,
+       11,11,12,11,11,11,11,11,16,15,15,14,12,12,12,11,
+       11,16,15,16,14,12,12,10, 9, 9,14,11,11,13,11,11,
+       12,11,11,16,14,14,14,11,11,12,11,11,17,15,15,14,
+       11,11, 7, 8, 8,12,11,11,12,10,10,12,10,10,16,14,
+       13,14,10,10,12,10,10,17,14,14,14,10,10, 8, 7, 7,
+       13,11,11,12,11,11,12,11,11,16,15,14,14,12,12,12,
+       11,11,16,15,14,15,12,12,11,10,10,13,11,11,13,12,
+       11,13,11,11,17,14,14,14,11,11,13,11,11,17,14,15,
+       14,11,11,
+};
+
+static const static_codebook _44p3_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p3_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p6_1[] = {
+        2, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
+        7, 7, 8, 8, 8, 9, 9, 9, 9, 7, 8, 6, 7, 7, 8, 8,
+        8, 8, 8, 8, 9, 8, 8,10, 9, 9,10, 8, 8,10, 8, 8,
+       10, 9, 9,10, 8, 8, 6, 6, 6, 8, 6, 6, 8, 7, 7, 8,
+        7, 7,10, 8, 8, 9, 7, 7, 9, 7, 7,10, 8, 9, 9, 7,
+        7, 7, 7, 7,10, 8, 8,11, 8, 8,10, 8, 8,12, 9, 9,
+       12, 8, 8,11, 9, 9,12, 9, 9,11, 8, 8, 7, 7, 7,10,
+        9, 9,10, 9, 9,10, 9, 9,11,10,10,10, 9, 9,11, 9,
+        9,11,10,10,11, 9, 9, 9, 8, 8,10, 9, 9,10, 9, 9,
+       11, 9, 9,11,10,10,11, 9, 9,11, 9, 9,11,10,10,11,
+        9, 9, 8, 8, 8,11, 9, 9,11, 9, 9,11, 9, 9,12, 9,
+        9,12, 8, 8,12, 9, 9,12, 9, 9,12, 8, 8, 8, 7, 7,
+       10, 9, 9,10, 9, 9,11, 9, 9,11,11,11,11, 9, 9,11,
+       10,10,11,11,11,11, 9, 9,10, 9, 9,11, 9, 9,11, 9,
+       10,11,10, 9,11,10,10,11, 9, 9,11, 9,10,11,10,10,
+       11, 9, 9,
+};
+
+static const static_codebook _44p3_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p3_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p3_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p3_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p3_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p3_p7_1[] = {
+        1, 9, 9, 6, 9, 9, 5, 9, 9, 8, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,
+};
+
+static const static_codebook _44p3_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p3_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p3_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p3_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p3_p7_2[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p3_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p3_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p3_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p3_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p3_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p3_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p3_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p3_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p3_short[] = {
+        4, 5,16, 9, 9,12,17,18, 4, 2,18, 6, 5, 9,13,15,
+       10, 7, 7, 6, 7, 9,13,13, 8, 5, 6, 5, 5, 7,11,12,
+        8, 4, 7, 4, 3, 6,10,12,11, 8, 9, 7, 6, 8,11,12,
+       15,13,13,11, 9, 7,10,12,16,12,16,12, 6, 5, 8,11,
+};
+
+static const static_codebook _huff_book__44p3_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p3_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p4_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p4_l0_0[] = {
+        1, 4, 4, 8, 8, 9, 8, 9, 9,10,10,10,10, 4, 6, 5,
+        8, 7, 9, 9, 9, 9,10, 9,10,10, 4, 5, 6, 7, 8, 9,
+        9, 9, 9, 9,10, 9,10, 8, 9, 8, 9, 8,10, 9,11, 9,
+       12,10,11,10, 8, 8, 9, 8, 9, 9,10, 9,11,10,11,10,
+       12, 9,10,10,11,10,11,11,12,11,12,12,12,12, 9,10,
+       10,11,11,11,11,11,12,12,12,12,12,10,11,11,12,12,
+       12,12,12,12,12,12,12,12,10,11,11,12,12,12,12,12,
+       12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,13,
+       12,12,11,12,11,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,13,12,12,12,12,12,12,11,13,12,12,
+       12,13,12,12,12,12,12,12,12,
+};
+
+static const static_codebook _44p4_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p4_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p4_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p4_l0_1[] = {
+        3, 4, 4, 5, 5, 4, 4, 5, 5, 5, 4, 5, 4, 5, 5, 5,
+        5, 6, 5, 6, 5, 6, 5, 6, 5,
+};
+
+static const static_codebook _44p4_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p4_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p4_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p4_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p4_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p4_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p4_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p4_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p4_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p4_long[] = {
+        3, 5,13, 9, 9,12,16,18, 4, 2,20, 6, 7,10,15,20,
+       10, 7, 5, 5, 6, 8,10,13, 8, 5, 5, 3, 5, 7,10,11,
+        9, 7, 6, 5, 5, 7, 9, 9,11,10, 8, 7, 6, 6, 8, 8,
+       15,15,10,10, 9, 7, 8, 9,17,19,13,12,10, 8, 9, 9,
+};
+
+static const static_codebook _huff_book__44p4_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p4_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p4_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44p4_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p4_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p4_p2_0[] = {
+        3, 9, 9, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+       12,12, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 0, 0, 0, 0, 0,
+        0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0,
+        0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,12,12, 0, 0,
+        0, 0, 0, 0, 0, 0,11,11, 0, 0, 0,12,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0,
+        5, 5, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5,
+        0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0,
+        0, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 7, 7, 0, 0,
+        0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,
+        7, 7, 0, 0, 0, 9, 9, 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,
+        0, 0, 0, 0, 0, 0, 0, 0,11,11, 0, 0, 0, 9, 9, 0,
+        0, 0,10,10, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0,
+        0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+       10,10, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+        0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0,11,11, 0,
+        0, 0,12,12, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+        0, 0, 9, 9, 0, 0, 0, 7, 7, 0, 0, 0, 8, 8, 0, 0,
+        0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0,
+        0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+        5, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 7, 7,
+        0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0,
+        0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0,
+        0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0,
+        0, 0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
+        0, 0, 0,10,10, 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, 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, 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,
+        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, 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, 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, 0, 0, 0, 0, 0,
+        0, 0, 0, 9, 9, 0, 0, 0, 7, 7, 0, 0, 0, 8, 8, 0,
+        0, 0,10,11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0,
+        0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 7,
+        7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0,11,11,
+        0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+        5, 5, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 7,
+        7, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+        0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 0,
+        0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0,
+        0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+        0, 0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9,
+        9, 0, 0, 0,11,11, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0,
+        0, 0, 0, 0,10,10, 0, 0, 0, 9, 9, 0, 0, 0,10,10,
+        0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0,
+        0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
+        0, 0, 0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,
+        9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,11,
+       11, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0,12,12,
+        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, 0, 0, 0, 0, 0, 0, 0,
+        0, 7, 7, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0, 0, 0,
+        9, 9, 0, 0, 0,10,10, 0, 0, 0,12,12, 0, 0, 0, 0,
+        0, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
+        0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0,10,10, 0,
+        0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
+        0, 0, 0, 0, 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0,
+       10,10, 0, 0, 0,11,11, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0, 0,
+        0, 0, 0, 0, 0,
+};
+
+static const static_codebook _44p4_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p4_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p4_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p3_0[] = {
+        1, 6, 6, 5, 7, 8, 0, 8, 8, 6, 9, 9, 7,10,10, 0,
+        8, 8, 0, 9, 9, 0,12,12, 0, 8, 8, 4, 7, 7, 6,10,
+       10, 0,12,12, 7,11,11, 8,12,12, 0,12,12, 0,13,12,
+        0,15,15, 0,12,12, 0, 7, 7, 0, 7, 7, 0, 7, 7, 0,
+        8, 8, 0,10,10, 0, 7, 7, 0, 8, 8, 0,11,11, 0, 7,
+        7, 5, 7, 7, 8, 9, 9, 0,10,10, 8, 9, 9,11,11,11,
+        0,10, 9, 0,11,11, 0,13,13, 0,10,10, 6, 7, 7, 8,
+       10,10, 0,12,12, 9,10,10,10,12,12, 0,12,12, 0,12,
+       12, 0,15,15, 0,12,12, 0,10,10, 0,11,11, 0,11,11,
+        0,11,11, 0,13,13, 0,11,11, 0,11,11, 0,15,15, 0,
+       10,10, 0, 8, 8, 0,10,10, 0,12,12, 0,11,11, 0,12,
+       12, 0,12,12, 0,12,12, 0,15,15, 0,11,11, 0, 7, 7,
+        0,10,10, 0,12,12, 0,10,10, 0,12,12, 0,12,12, 0,
+       13,13, 0,14,14, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44p4_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p4_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p3_1[] = {
+        3, 5, 5, 0, 8, 8, 0, 8, 8, 0, 9, 9, 0,10,10, 0,
+        8, 8, 0, 8, 8, 0,10,10, 0, 8, 8, 0, 7, 7, 0, 8,
+        8, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8,
+        0, 8, 8, 0, 8, 8, 0, 7, 7, 0, 6, 6, 0, 7, 7, 0,
+        7, 7, 0,10,10, 0, 6, 6, 0, 7, 7, 0,10,10, 0, 5,
+        5, 0, 8, 8, 0, 7, 7, 0, 8, 8, 0, 8, 8, 0, 9, 9,
+        0, 7, 7, 0, 8, 8, 0, 9, 9, 0, 7, 7, 0, 6, 6, 0,
+        9,10, 0,10,10, 0,10,10, 0,11,11, 0, 9, 9, 0,10,
+       10, 0,11,11, 0, 9, 9, 0, 8, 8, 0, 8, 8, 0, 8, 8,
+        0, 9, 9, 0, 9, 9, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0,
+        7, 7, 0, 8, 8, 0, 7, 7, 0, 7, 7, 0, 8, 8, 0, 9,
+        9, 0, 7, 7, 0, 7, 7, 0, 8, 8, 0, 6, 6, 0, 6, 6,
+        0,10,10, 0,10,10, 0,10,10, 0,12,12, 0, 9, 9, 0,
+       10,10, 0,12,12, 0, 9, 9, 0, 8, 8, 0, 7, 7, 0, 7,
+        7, 0, 8, 8, 0, 9, 9, 0, 7, 7, 0, 8, 8, 0, 9, 9,
+        0, 6, 6,
+};
+
+static const static_codebook _44p4_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p4_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p4_0[] = {
+        1, 6, 6, 6, 7, 7, 7, 8, 8, 7, 8, 8,10,11,11, 9,
+        8, 8, 8, 8, 8,11,11,12, 9, 8, 8, 5, 7, 7, 9,11,
+       11,10,11,11,10,11,11,12,14,14,11,12,12,10,12,12,
+       13,14,14,12,12,12, 5, 6, 6, 7, 6, 6, 8, 7, 7, 8,
+        7, 7,11,10,10,10, 7, 7, 9, 8, 8,12,11,11,10, 7,
+        7, 7, 7, 7,11,10,10,12,10,10,11,10,10,15,13,13,
+       13,10,10,12,11,11,15,13,13,14,11,11, 7, 7, 7,11,
+       11,11,12,11,11,12,11,11,14,14,14,13,12,12,12,12,
+       12,16,15,15,14,12,12, 0,10,10, 0,11,11, 0,12,12,
+        0,11,11, 0,14,14, 0,11,11, 0,12,12, 0,15,15, 0,
+       11,11, 7, 8, 8,12,11,10,12,10,10,12,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,14,10,10, 8, 7, 7,
+       12,11,11,12,11,11,12,11,11,15,14,14,14,12,12,13,
+       12,12,15,14,14,15,13,13, 0,11,11, 0,12,12, 0,12,
+       12, 0,12,12, 0,15,15, 0,12,12, 0,13,13, 0,15,14,
+        0,12,12,
+};
+
+static const static_codebook _44p4_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p4_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p4_p4_1[] = {
+        4, 5, 5, 9, 9,12, 9, 9,12,12,12,10,10,13,13,13,
+       11,11,12,12,13,13,13,12,12,13,10,10,13,13,13,13,
+       13,13,13,13,10,10,13,12,13,11,11,13,13,13,14,14,
+       13,12,13,10,10,13,13,12,13,13,13,13,13,10,10,12,
+       12,13,11,11,13,13,13,14,14,12,12,13,12,12,13,13,
+       13,13,13,13,13,13,11,11,12,12,13,11,11,13,13,13,
+       14,14,12,12,13,14,14,13,13,14,13,13,14,14,14,14,
+       14,12,12,13,14,14,13,13,14,14,14,12,12,12, 8, 8,
+       12,12,13,12,12,11,11,13,11,11,11,11,14,12,12,11,
+       11,14,12,12,10,11,14,12,12,12,12,14,12,12,12,12,
+       13,13,13,11,11,14,12,12,11,11,14,12,12,12,12,14,
+       12,12,12,12,14,12,12,12,12,14,13,13,11,11,14,12,
+       12,11,11,14,12,12,12,12,14,13,13,12,12,14,12,12,
+       12,12,14,13,13,11,11,14,12,12,11,11,14,13,13,11,
+       11,15,13,13,12,12,14,12,12,12,12,15,13,13,12,12,
+       14,12,12,11,11,15,13,13,11,11,12, 9, 9,11,11,13,
+        7, 7,11,11,13, 8, 8,12,12,14,10,10,10,10,14,14,
+       14,11,11,14, 8, 8,12,12,14,14,14,12,12,14, 7, 7,
+       11,11,14, 9, 9,12,12,14,14,14,11,11,14, 8, 8,12,
+       12,14,14,14,12,12,14, 7, 7,11,11,14, 9, 9,12,12,
+       14,14,14,11,11,14,10,10,12,12,14,14,14,13,13,14,
+        9, 9,11,11,14,10,10,12,11,15,14,14,11,11,14,15,
+       15,12,12,15,14,14,14,14,15,14,14,11,11,15,14,14,
+       12,12,15,14,14,11,11,14,11,11,10,10,15,10,10,10,
+       10,15,10,10,10,10,15,11,11, 9, 9,15,12,13, 9, 9,
+       15,11,11,11,11,15,13,13,11,11,15,10,10,10,10,15,
+       11,11,10,10,15,13,13,11,11,15,11,11,11,11,15,13,
+       13,11,11,15,10,10,10,10,15,11,11,10,10,15,13,13,
+       10,11,15,12,12,11,11,15,13,13,11,10,15,11,11,10,
+       10,15,11,12,10, 9,15,13,13,10,10,15,14,14,11,11,
+       15,13,13,11,11,15,14,14,10,10,15,13,13,10,10,15,
+       14,14,10,10,14,13,13,10,10,15,13,13,10,10,15,13,
+       13,10,10,14,14,14, 8, 9,15,14,14, 9, 9,15,14,14,
+       11,11,15,14,14,10,10,15,14,14,10,10,15,14,14,11,
+       11,15,14,14,10,10,15,14,14,11,11,15,14,14,10,10,
+       15,14,14,10,10,15,14,14,10,10,15,14,14, 9, 9,15,
+       14,14,11,11,15,14,14,11,11,15,14,14,10,10,15,14,
+       14,10,10,14,14,14, 9, 9,15,15,15,11,11,15,14,14,
+       12,12,15,15,15,10,10,15,14,15,10,10,15,15,15, 9,
+        9,15,10,10,13,13,17, 8, 8,12,12,17,10, 9,13,13,
+       18,11,11,12,12,18,14,14,12,12,17, 9, 9,13,13,17,
+       13,13,12,12,18, 8, 8,12,12,18,10,10,12,12,18,14,
+       14,12,12,18,10,10,13,13,18,13,13,13,13,18, 9, 9,
+       12,12,18,10,10,13,13,18,14,14,12,12,18,11,11,13,
+       13,18,14,14,13,13,18,10,10,12,12,17,11,11,12,12,
+       18,14,14,12,12,18,14,14,13,13,18,14,14,13,13,19,
+       14,15,12,12,18,14,14,12,12,18,15,15,12,12,13, 7,
+        7,11,11,14,15,15,11,11,14,16,15,11,11,14,15,15,
+       11,11,14,15,15,11,11,14,15,15,11,12,14,15,15,12,
+       12,13,15,15,11,11,14,15,15,11,11,15,15,15,12,12,
+       14,15,15,12,12,14,16,16,12,12,14,15,15,11,11,14,
+       15,15,11,11,15,15,15,12,12,15,15,15,12,12,14,15,
+       15,12,12,14,15,15,11,11,14,15,15,11,11,15,14,15,
+       12,12,15,15,15,12,12,15,16,16,12,12,15,15,15,12,
+       12,14,15,15,12,12,15,15,15,12,12,13,13,13,11,11,
+       14,14,15,11,11,14,14,14,12,12,14,15,15,10,10,15,
+       15,15,11,11,14,15,15,12,12,14,14,14,11,11,14,15,
+       15,11,11,14,15,15,12,12,15,15,15,11,11,14,15,15,
+       12,12,14,14,15,11,11,14,15,15,11,11,14,15,15,12,
+       12,15,15,15,11,11,15,15,15,12,12,14,15,15,12,12,
+       14,15,15,10,10,14,15,15,11,11,15,15,15,10,10,15,
+       15,15,12,12,15,15,15,14,14,15,15,15,11,11,15,15,
+       15,11,11,15,15,15,11,11,14,10,10,10,10,15, 9, 9,
+       12,11,15,10,10,12,12,15,11,11,11,11,15,13,13,12,
+       12,16,10,10,12,12,15,13,13,12,12,15, 9, 9,11,11,
+       15,10,10,13,12,15,13,13,11,11,15,10,10,12,12,15,
+       13,13,12,12,15, 9, 9,11,11,15,10,10,12,12,15,13,
+       13,11,11,15,11,11,12,12,15,13,13,13,13,15,10,10,
+       11,11,15,11,11,12,12,15,13,14,11,11,15,14,14,13,
+       13,16,14,14,20,19,15,14,14,11,11,15,13,14,12,12,
+       15,14,14,11,11,14,13,13,10,10,14,14,13,11,11,15,
+       13,14,12,12,15,14,14,12,12,15,14,14,11,11,15,14,
+       14,12,12,15,15,14,13,13,15,14,14,11,11,15,14,14,
+       11,11,15,14,14,13,13,15,14,14,12,12,15,14,14,13,
+       13,15,14,14,11,11,15,14,14,11,11,15,14,14,13,13,
+       15,14,14,12,12,15,14,14,12,12,15,14,14,12,12,15,
+       14,14,11,11,15,15,15,12,12,15,15,15,13,13,16,14,
+       14,12,12,15,15,15,13,13,15,15,15,12,12,15,15,15,
+       12,12,14,10,10,13,13,17, 9, 9,12,12,17, 9, 9,13,
+       13,17,11,11,12,12,18,14,14,12,12,18,10,10,13,13,
+       18,14,13,12,12,18, 9, 9,12,12,18,10,10,12,13,18,
+       14,14,12,12,17, 9, 9,12,12,17,13,14,12,12,17, 9,
+        9,12,12,17,10,10,12,12,17,14,14,11,11,18,11,11,
+       12,12,18,14,14,12,13,18,10,10,12,12,18,11,11,12,
+       12,18,14,14,11,11,18,15,15,12,12,18,14,14,13,13,
+       18,14,15,12,12,17,14,14,12,12,17,15,15,12,12,13,
+        7, 7,11,11,14,15,15,11,11,14,15,15,11,11,14,15,
+       15,11,11,14,15,15,11,11,14,15,15,11,11,14,15,15,
+       12,12,14,15,15,11,11,14,15,15,11,11,15,15,15,12,
+       12,14,15,15,11,11,14,15,15,12,12,14,15,15,11,11,
+       15,15,15,11,11,15,15,15,12,12,14,15,15,12,12,14,
+       15,16,12,12,14,15,15,11,11,14,15,15,11,11,15,15,
+       15,12,12,15,15,15,12,12,15,16,16,12,12,15,15,15,
+       12,12,15,15,15,12,12,15,15,15,12,12,13,13,13,12,
+       12,14,14,14,11,11,14,14,14,12,12,14,14,14,10,10,
+       15,15,15,11,11,14,15,15,12,12,14,14,14,11,11,14,
+       15,15,11,11,14,14,14,12,12,15,15,14,11,11,14,15,
+       15,12,12,14,14,14,11,11,14,15,15,11,11,14,14,14,
+       11,11,15,14,14,10,10,14,15,15,12,12,14,14,14,12,
+       12,14,15,15,10,10,14,15,15,11,11,15,15,15,10,10,
+       15,15,15,12,12,15,14,14,13,13,15,15,15,10,10,15,
+       14,14,11,11,15,15,15,10,10,14,10,10,10,10,14, 9,
+        9,12,12,15,10,10,12,12,14,11,11,11,11,15,13,14,
+       12,12,15,10,10,13,13,15,13,13,12,12,15, 9, 9,12,
+       12,15,10,10,13,13,15,13,14,11,11,15,10,10,12,12,
+       15,13,13,12,12,15, 9, 9,11,11,15,10,10,12,12,15,
+       13,13,11,11,15,11,11,12,12,15,13,13,13,13,15,10,
+       10,11,11,15,11,11,12,12,15,14,14,11,11,15,14,14,
+       13,13,15,14,14,20,19,15,14,14,11,11,15,14,14,12,
+       12,15,14,14,11,11,14,13,13,11,11,15,13,13,11,11,
+       15,14,13,12,12,15,14,14,11,12,15,14,14,11,11,15,
+       14,14,12,12,14,14,14,13,13,15,14,14,11,11,15,14,
+       14,11,11,15,14,14,13,13,15,14,14,12,12,15,14,14,
+       13,13,14,14,14,11,11,15,14,14,11,11,15,14,14,13,
+       13,15,14,14,12,12,15,14,14,12,12,15,14,14,12,12,
+       15,14,14,11,11,14,14,14,12,12,15,15,15,13,13,16,
+       14,14,12,12,15,15,15,13,13,15,14,14,12,12,15,15,
+       15,12,12,15,11,11,13,13,18,10,10,12,12,17,11,11,
+       12,12,18,12,12,11,11,18,14,14,12,12,18,10,10,13,
+       13,18,14,14,12,12,18,10,10,12,12,18,11,11,12,12,
+       18,14,14,12,12,18,11,11,12,13,18,14,14,12,12,18,
+       10,10,12,12,18,11,11,12,12,18,14,14,11,11,18,11,
+       11,12,12,18,14,14,12,12,17,10,10,11,11,17,12,12,
+       11,11,17,14,14,11,11,18,15,15,12,12,18,14,14,13,
+       13,18,15,15,11,11,18,15,14,12,12,18,15,15,11,11,
+       14, 8, 8,11,11,14,15,15,10,10,14,15,15,11,11,14,
+       15,15,11,11,15,15,15,12,12,15,15,15,11,11,15,15,
+       15,12,12,14,15,15,10,10,15,15,15,11,11,15,15,15,
+       12,12,15,15,15,11,11,15,15,15,13,13,14,15,15,10,
+       10,15,15,15,11,11,15,15,15,12,12,15,15,15,12,12,
+       15,16,16,12,12,15,14,14,11,11,15,15,15,11,11,15,
+       15,15,12,12,16,15,15,13,13,15,16,16,13,13,16,15,
+       15,12,12,15,15,15,12,12,15,15,15,12,12,14,13,13,
+       11,11,14,14,14,11,11,14,14,14,12,12,15,14,14,11,
+       11,15,15,14,11,11,15,14,14,12,12,15,14,14,12,12,
+       14,15,15,11,11,15,14,14,12,12,15,14,14,11,11,15,
+       14,15,12,12,15,14,14,12,12,14,15,15,11,11,15,14,
+       14,11,11,15,14,14,11,11,15,15,14,12,12,15,14,14,
+       12,12,15,15,15,10,11,15,14,14,11,11,15,15,15,10,
+       10,15,15,15,12,12,16,14,14,13,13,15,15,15,11,11,
+       15,14,14,11,11,15,15,15,11,11,14,11,11, 9, 9,14,
+       10,10,12,12,15,11,11,12,12,15,12,12,12,12,15,14,
+       14,13,13,15,11,11,12,12,15,14,14,13,13,14,10,10,
+       12,12,15,11,11,13,13,15,14,14,12,12,15,10,10,12,
+       12,14,14,14,13,13,14,10,10,11,11,15,11,11,12,12,
+       15,14,14,12,12,15,12,12,13,13,15,14,14,14,14,15,
+       11,11,11,11,15,12,11,12,12,15,14,14,11,11,15,15,
+       15,13,14,15,14,14,20,19,15,14,14,12,12,15,14,14,
+       13,13,15,14,14,12,12,14,13,13,10,10,14,13,13,11,
+       11,14,13,13,11,11,15,14,14,12,12,15,14,14,12,12,
+       15,14,14,12,11,14,14,14,13,13,15,14,14,11,11,15,
+       14,14,11,11,15,14,14,14,14,15,14,14,11,12,15,14,
+       14,13,13,14,14,14,11,11,15,14,14,11,11,15,14,14,
+       14,14,15,14,14,12,12,15,14,14,13,13,15,14,14,11,
+       11,14,14,14,12,12,15,14,14,13,13,15,15,15,13,13,
+       15,14,14,13,13,15,15,15,13,13,15,14,14,13,13,15,
+       15,15,13,13,15,14,14,13,13,18,15,15,12,12,18,15,
+       15,12,12,18,16,16,11,11,18,17,17,12,12,18,15,15,
+       13,13,18,17,17,12,12,18,15,15,12,12,18,15,16,12,
+       12,18,17,17,12,12,18,15,15,13,12,17,16,17,12,12,
+       17,15,15,11,12,18,15,15,12,12,18,17,17,11,11,18,
+       16,16,12,12,18,17,16,12,12,18,15,15,11,11,18,15,
+       15,12,12,18,17,17,11,11,18,17,17,12,12,18,16,16,
+       13,13,18,17,17,11,11,17,16,16,11,11,18,17,17,11,
+       11,15,15,15,11,11,16,15,15,11,11,16,15,15,11,11,
+       16,15,15,12,12,17,15,15,14,14,16,15,15,11,11,17,
+       15,15,14,14,16,15,15,11,11,16,15,15,12,12,18,15,
+       15,13,13,16,15,15,11,11,17,15,15,14,14,16,15,15,
+       11,11,16,15,15,12,12,17,15,15,13,13,16,15,15,12,
+       12,17,16,15,14,14,16,15,15,11,11,16,15,15,12,12,
+       18,15,15,13,13,17,15,15,14,14,17,16,16,15,15,18,
+       14,15,13,13,18,15,15,14,14,18,15,15,13,13,15,13,
+       13,12,12,15,14,14,12,12,16,14,14,12,12,16,14,14,
+       12,12,17,14,15,12,12,16,14,14,12,12,17,14,14,13,
+       13,16,15,15,12,12,16,14,14,12,12,17,14,14,12,12,
+       16,14,14,12,12,17,14,14,13,13,15,15,15,11,11,16,
+       14,14,12,12,17,14,14,12,12,16,15,15,12,12,17,14,
+       14,13,12,16,15,15,11,11,16,14,14,12,12,17,15,15,
+       11,11,17,15,15,13,13,17,14,14,13,13,18,15,15,12,
+       12,17,14,14,12,12,17,15,15,12,12,14,15,15, 9, 9,
+       14,15,15,12,12,15,16,15,13,13,15,15,15,14,14,15,
+       15,15,21,19,15,15,15,13,13,15,15,15,19,19,15,15,
+       15,12,12,15,16,16,14,14,15,15,15,19,19,15,16,15,
+       13,13,15,16,16,19,20,15,15,15,12,13,15,16,16,14,
+       14,15,15,15,20,19,15,15,15,14,14,15,16,16,19,19,
+       15,15,15,14,13,15,15,15,14,14,15,15,15,19,19,15,
+       16,16,20,19,15,17,16,21,20,15,15,15,20,19,15,16,
+       16,20,20,15,15,15,19,20,14,13,13,10,10,14,14,14,
+       11,11,14,14,14,12,12,15,14,14,13,13,15,15,14,20,
+       20,15,14,14,12,12,14,14,14,19,19,15,14,14,11,11,
+       15,14,14,12,12,15,14,14,20,19,15,14,14,12,12,14,
+       14,14,20,20,14,14,14,11,11,15,14,14,12,12,15,14,
+       14,20,21,15,14,14,13,13,15,14,14,20,20,15,14,14,
+       12,12,15,14,14,13,13,14,15,15,20,20,15,15,15,20,
+       19,15,14,14,20,19,15,15,15,20,20,15,14,14,21,20,
+       15,15,15,20,20,
+};
+
+static const static_codebook _44p4_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p4_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p4_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p4_p5_0[] = {
+        1, 7, 6,15,15, 7, 8, 8,15,15, 8, 8, 8,15,15, 0,
+       13,13,16,16, 0,14,14,16,16, 7, 9, 9,16,16,10,11,
+       11,17,17,10, 8, 8,15,16, 0,14,14,18,18, 0,14,14,
+       16,16, 9, 9, 9,16,16,12,11,11,17,17,10, 9, 9,15,
+       15, 0,14,14,19,19, 0,14,14,16,16, 0,15,15,18,17,
+        0, 0, 0,20,20, 0,13,13,16,16, 0,17,17,22,20, 0,
+       15,15,17,17, 0,15,15,18,18, 0,22,21,20,21, 0,13,
+       13,16,16, 0,18,18, 0,22, 0,15,15,17,17, 6, 7, 7,
+       13,13, 9,10,10,15,15,11,10,10,15,15, 0,21,22,18,
+       18, 0, 0, 0,18,18,10,10,10,15,15,12,13,13,17,17,
+       12,11,11,15,15, 0,22,22,18,18, 0, 0,21,18,18,12,
+       11,11,15,15,15,14,14,18,18,13,11,11,15,15, 0, 0,
+       21,18,19, 0,21,22,18,19, 0,22, 0,18,19, 0, 0, 0,
+        0, 0, 0,21,21,18,18, 0,22, 0, 0,21, 0, 0, 0,19,
+       18, 0, 0, 0,18,19, 0, 0, 0, 0, 0, 0,20,20,18,17,
+        0, 0,22, 0,21, 0, 0, 0,19,19, 6, 6, 6,13,13, 8,
+        6, 6,11,11, 9, 7, 7,13,13, 0,10,10,11,11, 0,12,
+       12,14,14, 9, 8, 8,14,14,12,10,10,13,13,10, 7, 7,
+       13,13, 0,11,11,15,15, 0,11,11,13,13, 9, 8, 8,14,
+       14,13,10,10,13,14,11, 7, 7,13,13, 0,11,11,15,15,
+        0,11,11,13,13, 0,12,12,15,15, 0,21,21,17,17, 0,
+       10,10,13,13, 0,14,14,20,20, 0,12,12,13,13, 0,12,
+       12,15,15, 0,21,22,17,18, 0,10,10,13,13, 0,16,16,
+       20,21, 0,12,12,13,13, 0,11,11,13,13, 0,12,12,16,
+       16, 0,12,12,16,16, 0,16,16, 0,21, 0,17,18, 0, 0,
+        0,12,12,15,15, 0,15,15,18,18, 0,12,12,16,16, 0,
+       16,16,21,22, 0,17,17,22,21, 0,12,12,16,16, 0,15,
+       15,19,19, 0,12,12,16,16, 0,16,16,22,22, 0,17,16,
+       22, 0, 0,17,18, 0, 0, 0, 0, 0, 0, 0, 0,15,15,21,
+       20, 0,19,20, 0,22, 0,18,18, 0, 0, 0,18,17, 0, 0,
+        0, 0, 0, 0, 0, 0,16,16,22,21, 0,20,20, 0,22, 0,
+       20,19, 0, 0, 0,11,11,12,12, 0,10,10,11,11, 0,11,
+       11,12,12, 0,12,12,10,10, 0,13,13,12,12, 0,11,11,
+       13,13, 0,13,13,12,12, 0,10,10,12,12, 0,13,13,14,
+       13, 0,12,12,12,12, 0,12,12,13,13, 0,14,14,13,13,
+        0,10,10,12,12, 0,13,13,14,14, 0,13,12,12,12, 0,
+       14,14,14,14, 0,21,21,16,16, 0,12,12,12,12, 0,16,
+       16,20,21, 0,13,13,11,11, 0,14,14,14,14, 0,20,20,
+       16,15, 0,12,12,12,12, 0,17,17,20,20, 0,13,13,11,
+       11, 7, 8, 8,16,16,11,10,10,15,15,12,10,10,17,17,
+        0,14,14,16,15, 0,15,15,17,17,11, 9, 9,16,16,14,
+       12,12,17,17,13, 9, 9,16,15, 0,14,14,19,18, 0,14,
+       14,16,16,12,10,10,17,18,16,13,13,17,18,14,10,10,
+       16,16, 0,14,14,19,19, 0,14,15,17,17, 0,15,15,18,
+       19, 0, 0, 0,20,20, 0,13,13,17,17, 0,17,18, 0,22,
+        0,15,15,16,17, 0,15,15,18,18, 0, 0, 0,20,21, 0,
+       14,14,17,17, 0,19,18, 0, 0, 0,16,16,17,17, 8, 7,
+        7,14,14,12,11,11,15,15,13,11,11,15,15, 0, 0, 0,
+       18,19, 0,21,20,18,18,12,10,11,15,16,14,13,13,18,
+       18,14,11,11,15,15, 0,20,20,19,18, 0,20, 0,18,18,
+       13,11,11,16,16,17,15,15,19,19,14,12,12,15,15, 0,
+       21, 0,18,20, 0,22,22,18,19, 0,22,22,19,19, 0, 0,
+        0, 0, 0, 0,21,22,19,18, 0, 0, 0, 0,21, 0, 0, 0,
+       19,19, 0, 0,22,20,20, 0, 0, 0, 0, 0, 0,22, 0,18,
+       18, 0, 0, 0, 0,22, 0, 0, 0,19,20,11,10,10,14,14,
+       14,11,11,13,13,14,11,11,15,15, 0,14,13,12,12, 0,
+       15,15,16,16,13,11,11,15,15,16,13,13,15,15,15,10,
+       10,14,15, 0,14,14,16,16, 0,14,14,15,15,13,11,11,
+       15,15,18,14,14,15,15,15,10,10,15,14, 0,14,14,16,
+       16, 0,14,14,15,15, 0,15,15,17,16, 0,21,22,18,18,
+        0,13,13,14,14, 0,18,17,20,21, 0,15,15,14,14, 0,
+       15,16,16,17, 0, 0, 0,19,18, 0,13,13,15,14, 0,19,
+       19, 0, 0, 0,15,15,14,14, 0,12,12,14,13, 0,13,13,
+       16,16, 0,12,12,16,16, 0,16,16,22, 0, 0,17,18, 0,
+       22, 0,13,13,16,16, 0,15,15,18,18, 0,12,12,16,16,
+        0,16,16,22,22, 0,17,17, 0, 0, 0,13,13,17,17, 0,
+       16,16,19,20, 0,12,12,17,17, 0,17,17,22, 0, 0,17,
+       17,22,21, 0,18,18, 0, 0, 0, 0, 0, 0, 0, 0,16,16,
+       21,21, 0,19,19, 0, 0, 0,18,18, 0,22, 0,18,18, 0,
+       22, 0, 0, 0, 0, 0, 0,16,16,22, 0, 0,20,20, 0, 0,
+        0,19,18, 0, 0, 0,12,12,15,15, 0,12,12,15,14, 0,
+       13,13,15,15, 0,14,14,14,14, 0,15,15,16,16, 0,13,
+       13,15,16, 0,15,15,16,16, 0,12,12,15,15, 0,14,14,
+       16,16, 0,14,14,15,15, 0,13,13,15,16, 0,15,15,16,
+       16, 0,12,12,15,15, 0,15,15,17,17, 0,14,14,15,15,
+        0,15,15,17,17, 0,21,21,19,19, 0,13,13,14,14, 0,
+       17,17,22, 0, 0,14,14,15,15, 0,15,15,17,17, 0,22,
+        0,18,20, 0,13,13,15,15, 0,18,18, 0,22, 0,15,15,
+       14,15, 8, 8, 8,17,16,12,10,10,16,16,13,10,10,17,
+       16, 0,15,15,17,17, 0,15,15,17,17,12,11,11,18,18,
+       15,12,12,18,18,15,10,10,16,17, 0,14,14,18,18, 0,
+       14,14,17,17,13,10,10,16,16,17,14,14,17,17,15,10,
+       10,16,15, 0,15,15,19,20, 0,14,14,15,16, 0,16,16,
+       19,19, 0, 0, 0,21,22, 0,13,13,17,17, 0,18,17, 0,
+       21, 0,15,15,17,17, 0,15,15,18,19, 0, 0,22, 0,21,
+        0,13,13,16,17, 0,19,19, 0,22, 0,16,15,16,16, 9,
+        8, 8,14,14,12,11,11,15,15,13,11,11,15,15, 0,21,
+       20,19,18, 0, 0, 0,19,18,12,11,11,16,15,15,13,13,
+       17,18,14,11,11,15,15, 0,22,22,19,18, 0,22,21,18,
+       18,14,11,11,15,15,17,14,14,18,18,15,12,12,15,15,
+        0,22,22,20,19, 0, 0,21,18,18, 0, 0,22,20,20, 0,
+        0, 0, 0, 0, 0,20,21,18,18, 0, 0, 0,21,21, 0, 0,
+        0,20,19, 0,22,21,19,19, 0, 0, 0, 0, 0, 0, 0,22,
+       17,18, 0, 0,22, 0,22, 0,22, 0,19,19, 0,11,11,15,
+       15, 0,11,11,14,14, 0,12,12,15,15, 0,15,15,14,14,
+        0,16,16,16,16, 0,12,12,16,16, 0,14,14,16,16, 0,
+       11,11,15,15, 0,15,15,17,17, 0,15,15,15,15, 0,12,
+       12,16,16, 0,14,14,15,15, 0,11,11,15,15, 0,15,15,
+       17,17, 0,15,15,14,15, 0,16,16,17,17, 0, 0, 0,19,
+       19, 0,14,14,15,15, 0,18,18,21, 0, 0,15,15,14,15,
+        0,16,16,17,17, 0,21, 0,19,19, 0,14,14,15,15, 0,
+       20,20,22, 0, 0,16,15,14,14, 0,12,12,13,13, 0,12,
+       12,16,16, 0,12,12,16,16, 0,16,16,22,21, 0,18,17,
+       21, 0, 0,13,13,16,16, 0,15,15,18,19, 0,12,12,16,
+       16, 0,16,17,22, 0, 0,17,17, 0,22, 0,13,13,17,16,
+        0,15,15,19,19, 0,12,12,16,16, 0,16,16,21,20, 0,
+       17,16,22, 0, 0,18,18,22,21, 0, 0, 0, 0, 0, 0,15,
+       16,21,21, 0,19,19, 0, 0, 0,18,17, 0, 0, 0,18,18,
+       21, 0, 0, 0, 0, 0, 0, 0,16,16,22,22, 0,20,21, 0,
+        0, 0,18,19, 0,22, 0,13,13,16,16, 0,12,12,15,15,
+        0,13,13,16,16, 0,14,14,15,15, 0,15,15,17,17, 0,
+       13,13,17,16, 0,15,15,17,17, 0,12,12,16,16, 0,15,
+       15,17,17, 0,14,14,16,16, 0,13,13,16,17, 0,15,15,
+       17,17, 0,12,12,16,16, 0,14,14,17,17, 0,14,14,16,
+       16, 0,16,16,17,17, 0,21, 0,21,19, 0,13,13,16,16,
+        0,17,17, 0, 0, 0,15,15,16,16, 0,16,15,18,18, 0,
+       22, 0,20,20, 0,13,13,15,15, 0,18,18, 0, 0, 0,15,
+       15,15,15, 0,12,12,17,17, 0,14,14,17,17, 0,14,14,
+       17,17, 0,17,17,18,17, 0,17,17,19,18, 0,13,13,17,
+       17, 0,16,16,18,18, 0,13,13,16,16, 0,17,17,19,19,
+        0,16,16,17,17, 0,13,13,18,18, 0,17,17,18,18, 0,
+       13,13,17,17, 0,17,17,19,19, 0,16,17,17,17, 0,17,
+       17,19,19, 0,21, 0,21,19, 0,14,14,16,16, 0,20,19,
+        0,21, 0,16,16,16,16, 0,17,18,19,19, 0, 0, 0, 0,
+       21, 0,15,15,16,17, 0,21,20, 0, 0, 0,17,18,16,17,
+        0, 9, 9,14,14, 0,14,14,15,16, 0,14,14,15,15, 0,
+        0, 0,18,18, 0,21, 0,18,19, 0,12,12,15,15, 0,16,
+       16,17,17, 0,14,14,14,14, 0,22, 0,19,18, 0,22, 0,
+       17,18, 0,14,14,16,15, 0,18,18,19,18, 0,14,15,15,
+       15, 0, 0,21,20,20, 0, 0, 0,18,18, 0,21,21,19,19,
+        0, 0, 0, 0, 0, 0,21,21,18,18, 0,22, 0,20,20, 0,
+       22, 0,19,19, 0,22, 0,19,20, 0, 0, 0, 0, 0, 0, 0,
+       21,17,18, 0, 0, 0,22,22, 0, 0, 0,19,18, 0,18,20,
+       16,16, 0,21,20,17,17, 0, 0,21,18,18, 0,22,21,18,
+       18, 0, 0,22,19,19, 0,20,20,17,17, 0, 0, 0,18,18,
+        0,19,20,17,17, 0,22, 0,19,21, 0,22,21,18,18, 0,
+       20,19,17,18, 0, 0, 0,19,19, 0,20,20,17,17, 0,22,
+       22,21,21, 0,20, 0,18,18, 0,22,22,18,18, 0, 0, 0,
+       20,22, 0,20,20,16,16, 0, 0, 0,21, 0, 0,21,20,16,
+       17, 0,22, 0,19,20, 0, 0, 0,21,20, 0,19,21,17,17,
+        0, 0, 0, 0, 0, 0,21,21,17,17, 0,12,12,13,13, 0,
+       14,14,16,16, 0,14,14,16,16, 0,18,18, 0, 0, 0,19,
+       18,22, 0, 0,13,13,16,16, 0,16,16,18,18, 0,13,13,
+       16,16, 0,17,18,21, 0, 0,18,18,21, 0, 0,13,13,16,
+       16, 0,17,17,19,20, 0,13,13,16,17, 0,18,18,21, 0,
+        0,18,18,21, 0, 0,18,19, 0,21, 0, 0, 0, 0, 0, 0,
+       16,16,21,20, 0,20,20, 0, 0, 0,18,19, 0, 0, 0,18,
+       18, 0, 0, 0, 0, 0, 0, 0, 0,16,16, 0,21, 0,22,22,
+        0, 0, 0,19,19, 0, 0, 0,16,16,19,20, 0,17,16,22,
+       21, 0,17,17,21,20, 0,19,18, 0,22, 0,19,19,22,22,
+        0,16,15,22,22, 0,19,19, 0,21, 0,15,15,20,20, 0,
+       18,19, 0,21, 0,18,18,22,22, 0,16,16,21,20, 0,20,
+       19,21,22, 0,16,15,20,20, 0,19,19, 0,22, 0,18,18,
+       21, 0, 0,19,18,21,22, 0, 0, 0, 0, 0, 0,16,16,19,
+       21, 0,20,22, 0,22, 0,18,18,20,21, 0,19,18, 0,22,
+        0, 0, 0,22, 0, 0,16,16,20,20, 0,21,21, 0, 0, 0,
+       18,18,21, 0, 0,12,12,17,17, 0,15,14,17,17, 0,14,
+       14,18,18, 0,17,17,17,18, 0,18,18,18,18, 0,13,13,
+       18,18, 0,16,17,19,18, 0,13,13,16,17, 0,17,17,18,
+       19, 0,17,17,17,17, 0,13,13,17,17, 0,17,18,18,18,
+        0,13,13,16,16, 0,18,18,19,20, 0,16,17,17,16, 0,
+       17,18,19,18, 0, 0, 0,22,21, 0,15,15,16,16, 0,20,
+       20,21,22, 0,17,17,16,16, 0,16,17,18,18, 0, 0, 0,
+       21,21, 0,15,15,16,16, 0,21,20, 0, 0, 0,17,17,16,
+       16, 0,10,10,14,14, 0,14,14,15,15, 0,14,14,15,15,
+        0,22, 0,18,18, 0, 0, 0,19,19, 0,13,13,15,16, 0,
+       17,16,18,18, 0,14,14,15,15, 0,21,21,19,18, 0,22,
+       21,18,17, 0,14,14,15,15, 0,18,18,19,18, 0,15,15,
+       14,14, 0,22,21,19,19, 0,22,21,17,18, 0, 0, 0,19,
+       19, 0, 0, 0, 0, 0, 0,20,22,17,17, 0, 0,22,22,20,
+        0, 0, 0,19,18, 0,21,22,19,18, 0, 0, 0, 0, 0, 0,
+       22,22,17,18, 0, 0, 0,21,22, 0, 0, 0,19,18, 0,20,
+       20,17,17, 0,21,21,17,18, 0,21,22,18,18, 0,21, 0,
+       18,18, 0,22, 0,19,19, 0,19,21,18,18, 0, 0,22,18,
+       18, 0,22,21,17,17, 0,22, 0,20,20, 0, 0, 0,18,18,
+        0,22,21,18,18, 0,21, 0,19,19, 0,20,21,17,17, 0,
+        0,22,22,20, 0,21,22,17,17, 0, 0,21,19,18, 0, 0,
+        0,21,21, 0,21,20,16,17, 0, 0, 0, 0, 0, 0,21, 0,
+       17,17, 0,21, 0,19,20, 0, 0, 0,20,22, 0,20,20,17,
+       17, 0, 0, 0, 0, 0, 0,21,21,17,17, 0,12,12,13,13,
+        0,14,14,16,16, 0,14,14,16,16, 0,18,18,21, 0, 0,
+       19,19,22, 0, 0,13,13,16,16, 0,16,16,18,18, 0,13,
+       13,16,16, 0,18,18,21,22, 0,18,18, 0,22, 0,13,13,
+       16,16, 0,17,17,20,18, 0,13,13,16,16, 0,19,18, 0,
+       22, 0,18,18,22,21, 0,18,19, 0, 0, 0, 0, 0, 0, 0,
+        0,16,16,21,21, 0,21,21, 0, 0, 0,18,19, 0, 0, 0,
+       19,19,21, 0, 0, 0, 0, 0, 0, 0,16,16, 0,21, 0,20,
+       20, 0, 0, 0,20,20, 0, 0, 0,16,16,21,20, 0,18,17,
+       21,22, 0,17,18, 0,21, 0,18,19,22,22, 0,19,19, 0,
+       22, 0,16,17,21,22, 0,20,19, 0, 0, 0,16,16,20,21,
+        0,19,19, 0, 0, 0,19,19, 0,22, 0,17,17,21,21, 0,
+       19,20, 0, 0, 0,16,16, 0,20, 0,19,20, 0,21, 0,18,
+       18, 0,22, 0,19,20,22,22, 0, 0, 0, 0,22, 0,17,17,
+        0,21, 0,21,21, 0, 0, 0,18,19,23,21, 0,20,19, 0,
+        0, 0, 0, 0, 0, 0, 0,17,17, 0,20, 0, 0, 0, 0, 0,
+        0,19,19,23,22,
+};
+
+static const static_codebook _44p4_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p4_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p4_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p4_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p4_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p4_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p4_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p6_0[] = {
+        1, 7, 7, 7, 8, 8, 7, 8, 8, 7, 9, 9,11,11,11, 9,
+        8, 8, 8, 9, 9,12,11,12, 9, 8, 8, 6, 7, 7,10,11,
+       11,10,10,10,11,11,11,14,14,14,12,11,12,11,11,11,
+       15,15,14,13,12,12, 5, 6, 6, 8, 5, 5, 8, 7, 7, 8,
+        7, 7,12,10,10,10, 7, 6, 9, 8, 8,12,10,10,10, 6,
+        6, 7, 8, 8,12,10,10,12,10,10,11,10,10,16,14,14,
+       13,10,10,12,10,10,15,14,14,14,10,10, 7, 7, 7,13,
+       11,11,13,11,11,12,11,11,16,14,14,14,12,12,12,11,
+       11,18,15,15,14,12,12,10, 9,10,14,11,11,13,11,11,
+       12,11,11,17,14,14,14,11,11,13,11,11,16,15,15,14,
+       11,11, 7, 8, 8,13,11,11,12,10,10,12,10,10,16,14,
+       13,13,10,10,12,10,10,17,14,14,14,10,10, 8, 7, 7,
+       12,11,11,13,11,11,12,11,11,16,15,14,14,12,12,12,
+       11,11,16,15,15,14,12,12,11,10,10,14,11,11,13,11,
+       11,13,11,11,17,14,14,14,11,11,13,11,11,18,14,15,
+       15,11,10,
+};
+
+static const static_codebook _44p4_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p4_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p6_1[] = {
+        2, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
+        7, 7, 8, 8, 8, 9, 9, 9, 9, 8, 8, 6, 7, 7, 8, 8,
+        8, 8, 8, 8, 9, 8, 8, 9, 8, 9, 9, 8, 8,10, 8, 8,
+       10, 9, 9,10, 8, 8, 6, 6, 6, 8, 6, 6, 8, 7, 7, 8,
+        7, 7,10, 8, 8, 9, 7, 7, 9, 7, 7,10, 8, 8, 9, 7,
+        7, 7, 7, 7,10, 8, 8,11, 9, 9,10, 9, 9,11, 9, 9,
+       11, 8, 8,11, 9, 9,12, 9, 9,12, 8, 8, 7, 7, 7,10,
+        9, 9,10, 9, 9,10, 9, 9,11,10,10,10, 9, 9,11, 9,
+       10,11,10,11,10, 9, 9, 9, 8, 8,10, 9, 9,10, 9, 9,
+       11, 9, 9,11,10,10,11, 9, 9,11, 9, 9,11,10,10,11,
+        9, 9, 8, 8, 8,11, 9, 9,11, 9, 9,11, 9, 9,12, 9,
+        9,12, 8, 8,11, 9, 9,12, 9, 9,12, 8, 8, 8, 7, 7,
+       10, 9, 9,10, 9, 9,10, 9, 9,11,11,11,11, 9, 9,11,
+       10,10,11,11,11,11, 9, 9,10, 9, 9,11, 9, 9,11, 9,
+       10,11,10,10,11,10,10,11, 9, 9,11,10,10,11,10,10,
+       11, 9, 9,
+};
+
+static const static_codebook _44p4_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p4_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p4_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p4_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p4_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p4_p7_1[] = {
+        1, 9, 9, 7, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8,
+        9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 7, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 6, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 5, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 5,10, 9,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,
+};
+
+static const static_codebook _44p4_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p4_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p4_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p4_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p4_p7_2[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p4_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p4_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p4_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p4_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p4_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p4_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p4_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p4_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p4_short[] = {
+        3, 5,16, 9, 9,13,18,21, 4, 2,21, 6, 6,10,15,21,
+       16,19, 6, 5, 7,10,13,16, 8, 6, 5, 4, 4, 8,13,16,
+        8, 5, 6, 4, 4, 7,12,15,13,10, 9, 7, 7, 9,13,16,
+       18,15,13,12, 9, 7,10,14,21,18,13,13, 7, 5, 8,12,
+};
+
+static const static_codebook _huff_book__44p4_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p4_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p5_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p5_l0_0[] = {
+        1, 4, 4, 8, 8,10,10,10,10, 9, 8,11,11, 4, 6, 5,
+        8, 6,10,10,10,10,10, 9,10, 9, 4, 5, 6, 6, 9,10,
+       10,10,10, 9,10, 9,10, 8, 9, 8, 9, 8, 9, 9,10, 9,
+       11,10,12,10, 8, 8, 9, 8, 9, 9, 9, 9,10,10,11,10,
+       12, 9,10,10,11,10,11,10,12,11,12,11,13,11, 9,10,
+       10,10,11,10,11,11,12,11,12,11,12,11,12,12,12,12,
+       13,12,13,12,13,12,13,13,11,12,12,12,12,12,12,12,
+       13,13,13,13,13,12,12,12,13,13,13,13,13,13,13,13,
+       13,13,12,13,12,13,13,13,13,13,13,13,13,13,13,12,
+       13,13,13,14,14,13,13,13,13,13,13,13,12,13,12,13,
+       13,13,13,13,13,13,13,13,13,
+};
+
+static const static_codebook _44p5_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p5_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p5_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p5_l0_1[] = {
+        4, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 4, 4, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p5_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p5_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p5_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44p5_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p5_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p5_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p5_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44p5_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p5_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p5_long[] = {
+        3, 7,12,14,14,16,18,19, 6, 2, 4, 6, 8, 9,12,14,
+       12, 3, 3, 5, 7, 8,11,13,13, 6, 4, 5, 7, 8,10,11,
+       14, 8, 7, 7, 7, 7, 9,10,15, 9, 8, 7, 7, 6, 8, 9,
+       17,11,11,10, 9, 8, 9, 9,19,14,13,11,10, 9, 9, 9,
+};
+
+static const static_codebook _huff_book__44p5_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p5_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p5_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p1_0[] = {
+        2, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 5, 7, 8, 8, 9,
+       10, 8, 9,10, 8, 9,10, 9,10,12,10,11,11, 8,10,10,
+       10,11,11, 9,11,11, 5, 8, 7, 8, 9, 9, 8,10, 9, 8,
+       10,10, 9,11,11,10,11,11, 8,10, 9,10,11,11, 9,12,
+       10, 5, 8, 8, 7, 9,10, 8,10, 9, 7, 9, 9, 9,10,11,
+        9,11,11, 8,10, 9,10,11,11,10,11,11, 7, 9, 9, 9,
+       10,11, 9,11,11, 9, 9,11,10,10,13,11,11,12, 9,11,
+       11,11,12,13,11,13,12, 7, 9, 9, 9,11,11, 9,11,10,
+        9,11,10,10,11,12,11,13,12, 9,11,11,11,12,13,11,
+       13,11, 5, 8, 8, 8, 9,10, 7,10, 9, 8, 9,10,10,11,
+       11,10,11,11, 7, 9, 9, 9,11,11, 9,11,10, 7, 9, 9,
+        9,10,11, 9,11,11, 9,11,11,11,11,13,11,13,12, 9,
+       10,11,11,12,13,10,12,11, 7, 9, 9, 9,11,11, 9,11,
+       10, 9,11,11,11,12,13,11,13,12, 9,11, 9,11,12,11,
+       10,13,10,
+};
+
+static const static_codebook _44p5_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p5_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p5_p2_0[] = {
+        4, 6, 6, 9, 9, 6, 7, 8,10,10, 6, 8, 7,10,10, 8,
+       10,10,12,13, 8,10,10,13,12, 6, 7, 8,10,10, 7, 8,
+        9,10,11, 8, 9, 9,11,11,10,10,11,12,14,10,11,11,
+       14,13, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 9, 8,11,
+       10,10,11,11,13,14,10,11,10,14,12, 9,10,10,12,12,
+       10,10,11,12,13,10,11,11,13,13,12,12,13,12,15,13,
+       14,13,15,14, 9,10,10,12,12,10,11,11,13,13,10,11,
+       10,13,12,13,13,14,14,15,12,13,12,15,12, 6, 7, 8,
+       10,11, 8, 9,10,11,12, 8, 9, 9,11,12,10,11,12,13,
+       14,10,11,11,14,13, 8, 9,10,11,12, 9,10,11,12,13,
+        9,10,11,12,13,11,12,13,13,15,12,12,13,15,14, 8,
+        9, 9,12,12, 9,10,11,12,13, 9,10,10,13,12,12,12,
+       13,14,15,11,12,12,14,14,11,11,12,13,14,11,12,13,
+       13,15,12,13,13,14,15,14,13,15,14,16,14,15,15,16,
+       16,11,12,11,14,13,12,13,13,15,14,11,13,12,14,13,
+       14,15,15,15,16,13,14,14,16,14, 6, 8, 7,11,10, 8,
+        9, 9,11,12, 8,10, 9,12,11,10,11,11,13,14,10,12,
+       11,14,13, 8, 9, 9,12,12, 9,10,10,12,13, 9,11,10,
+       13,12,11,12,12,13,14,12,13,12,15,14, 8,10, 9,12,
+       11, 9,11,10,13,12, 9,11,10,13,12,12,13,12,14,15,
+       11,13,12,15,13,11,11,12,13,14,11,12,13,13,15,12,
+       13,13,14,15,13,14,14,14,16,14,15,15,16,16,11,12,
+       11,14,13,12,13,13,15,14,11,13,12,15,13,14,15,15,
+       16,16,13,15,13,16,14, 9,10,11,12,14,11,11,12,13,
+       15,11,12,12,13,14,13,14,15,15,17,13,14,14,15,16,
+       11,11,12,13,15,12,12,13,14,16,12,13,13,14,15,14,
+       14,16,15,17,15,15,15,16,17,11,12,12,14,14,12,13,
+       13,15,16,12,13,13,15,15,15,15,15,16,17,14,15,15,
+       16,16,14,14,15,15,17,14,15,15,15,17,15,15,16,16,
+       17,16,16,17,16,18,17,17,17,18,18,14,15,14,16,16,
+       15,15,16,17,17,14,15,15,17,16,17,17,17,18,18,16,
+       16,16,17,17, 9,11,10,14,12,11,12,12,14,13,11,12,
+       11,15,13,13,14,14,16,15,13,15,14,17,15,11,12,12,
+       15,14,12,13,13,15,15,12,13,13,15,15,14,15,15,16,
+       16,15,15,15,17,16,11,12,11,15,13,12,13,13,15,14,
+       12,13,12,16,14,15,15,15,17,16,14,15,14,17,15,14,
+       14,15,16,16,14,15,15,16,16,15,16,15,17,17,16,16,
+       16,17,17,17,17,17,18,17,14,15,14,16,15,15,15,15,
+       17,16,15,15,15,17,15,17,17,17,18,18,16,17,16,18,
+       16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,11,
+       10,11,11,13,14,10,12,11,14,13, 7, 9, 9,11,12, 9,
+       10,10,12,13, 9,10,10,13,13,11,11,12,13,15,11,12,
+       12,15,14, 8, 9, 9,12,11, 9,11,10,13,13, 9,11,10,
+       13,12,12,13,12,14,15,11,13,12,15,13,10,11,12,13,
+       14,11,12,12,13,15,12,12,13,14,15,13,13,14,14,16,
+       14,15,15,16,16,11,12,11,14,13,12,13,13,15,14,11,
+       13,12,15,13,14,15,15,15,16,13,14,14,16,14, 7, 9,
+        9,11,12, 9,10,11,12,13, 9,10,10,13,12,11,12,12,
+       14,15,11,12,12,15,14, 9, 9,11,11,13,10,10,12,12,
+       14,10,11,12,13,14,12,12,13,14,16,12,13,13,15,15,
+        9,11,10,13,13,10,12,12,13,14,10,12,11,14,13,12,
+       13,13,15,16,12,13,13,15,14,11,11,13,13,15,12,12,
+       14,13,16,13,13,13,14,15,14,14,15,14,17,15,15,15,
+       16,16,12,13,12,15,14,13,14,14,15,15,12,14,13,16,
+       14,15,15,16,16,17,14,15,14,17,15, 7, 9, 9,12,11,
+        9,10,10,12,13, 9,11,10,13,12,11,12,12,14,14,11,
+       13,12,15,14, 9,10,10,13,12,10,10,11,12,13,10,12,
+       11,14,13,12,12,13,13,15,12,14,13,16,15, 9,10,10,
+       13,12,11,11,12,13,13,10,12,10,14,12,13,13,13,15,
+       15,12,13,12,15,13,11,12,12,14,14,12,12,13,14,15,
+       13,14,13,15,15,14,13,15,13,16,15,16,15,17,16,12,
+       13,12,14,14,13,14,14,15,15,12,13,12,15,14,15,15,
+       16,16,17,14,15,13,16,13,10,11,12,13,14,11,12,13,
+       14,15,12,13,13,15,15,14,14,15,15,17,14,15,15,16,
+       16,12,12,13,12,15,12,12,14,13,16,13,13,14,14,16,
+       14,14,16,15,17,15,15,16,16,17,12,13,13,15,15,13,
+       14,14,16,16,13,14,13,16,15,15,16,16,17,17,14,15,
+       15,17,16,14,14,15,14,17,15,15,16,15,17,15,15,16,
+       15,17,16,16,17,16,18,17,17,17,17,18,14,15,15,17,
+       16,15,16,16,17,17,15,16,15,17,16,17,17,17,18,18,
+       16,17,16,18,17,10,12,11,14,14,12,13,13,15,15,12,
+       13,12,15,14,14,15,15,16,16,14,15,15,17,16,11,13,
+       12,15,14,12,13,13,15,15,13,14,13,16,14,15,15,15,
+       16,16,15,16,15,17,16,12,13,13,15,15,13,14,14,16,
+       16,12,14,13,16,15,15,16,16,17,17,15,16,15,17,16,
+       14,15,15,16,16,14,15,15,16,16,15,16,16,17,16,16,
+       16,16,16,17,17,18,17,18,17,14,15,15,17,16,15,16,
+       16,17,17,15,16,15,17,16,17,17,18,18,18,16,17,16,
+       18,16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,
+       11,10,11,12,13,14,10,11,11,14,13, 8, 9, 9,11,12,
+        9,10,11,12,13, 9,10,11,13,13,11,12,13,13,15,12,
+       12,12,15,14, 7, 9, 9,12,11, 9,10,10,13,13, 9,10,
+       10,13,12,11,12,12,14,15,11,12,11,15,13,11,11,12,
+       13,14,11,12,13,13,15,12,13,13,14,15,13,14,14,14,
+       16,14,15,15,16,16,10,12,11,14,13,12,13,12,14,14,
+       11,12,12,15,13,14,15,15,16,16,13,14,13,16,14, 7,
+        9, 9,11,12, 9,10,11,12,13, 9,10,10,13,12,11,12,
+       13,14,15,11,12,12,14,14, 9,10,10,12,13,10,10,12,
+       12,14,11,12,11,13,13,12,12,14,13,15,13,13,13,15,
+       15, 9,10,10,12,13,10,11,12,13,14,10,11,10,13,12,
+       13,13,14,15,16,12,13,12,15,13,12,13,13,14,14,12,
+       12,13,14,15,13,14,14,15,15,14,13,15,13,16,15,16,
+       15,17,16,11,12,12,14,14,13,13,14,15,15,12,13,12,
+       15,14,15,15,16,16,17,14,14,13,16,13, 7, 9, 9,12,
+       11, 9,10,10,12,13, 9,11,10,13,12,11,12,12,14,15,
+       11,12,12,15,14, 9,10,11,13,13,10,11,12,13,14,10,
+       12,12,14,13,12,13,13,14,16,12,13,13,16,15, 9,11,
+        9,13,11,10,12,11,13,13,10,12,10,14,12,12,13,13,
+       15,15,12,13,12,16,14,12,12,13,14,15,12,13,14,14,
+       15,13,14,14,15,15,14,14,15,15,17,15,16,15,17,16,
+       11,13,11,15,13,13,14,13,15,14,12,14,12,16,13,15,
+       15,15,16,16,14,15,14,17,14,10,11,12,14,14,12,12,
+       13,14,15,12,13,13,15,15,14,15,15,16,17,14,15,15,
+       16,16,12,12,13,15,15,13,13,14,15,16,13,14,14,16,
+       16,15,15,16,16,17,15,16,16,17,17,11,12,13,14,15,
+       13,13,14,15,16,12,13,13,15,15,15,15,16,16,17,15,
+       15,15,16,16,14,15,15,16,17,15,15,16,16,17,15,16,
+       16,17,17,16,16,17,16,18,17,17,17,18,18,14,15,15,
+       16,16,15,16,16,16,17,15,15,15,16,16,17,17,17,18,
+       18,16,16,16,17,16,10,12,11,14,13,12,13,13,15,15,
+       11,13,12,15,14,14,15,15,16,16,14,15,14,17,15,12,
+       13,13,15,15,13,13,14,16,16,13,14,14,16,16,15,15,
+       15,16,17,15,16,16,17,17,12,13,12,15,12,13,14,13,
+       16,14,12,14,12,16,13,15,16,15,17,16,14,16,14,17,
+       15,14,15,15,16,17,15,15,16,17,17,15,16,16,17,17,
+       16,16,17,17,18,17,18,17,18,18,14,15,14,17,14,15,
+       16,15,17,15,15,16,15,17,15,17,17,17,18,17,16,17,
+       16,18,16, 9,11,11,14,14,11,12,12,14,14,11,12,12,
+       15,14,13,14,14,16,16,13,15,14,16,16,10,11,12,14,
+       14,11,12,13,15,15,12,13,13,15,15,13,14,15,16,17,
+       14,15,15,17,16,11,12,12,15,14,12,13,13,15,15,12,
+       13,13,15,15,14,15,15,16,16,14,15,15,17,16,12,13,
+       14,15,16,13,14,14,15,16,13,14,15,16,16,15,15,16,
+       16,18,16,16,16,18,17,14,14,14,16,15,15,15,15,17,
+       16,14,15,15,17,16,16,17,17,18,17,16,16,16,18,16,
+       10,12,12,14,14,11,12,13,15,15,12,13,13,15,15,13,
+       14,15,16,17,14,15,15,17,16,11,12,13,14,15,12,12,
+       14,15,16,13,13,14,15,16,14,14,15,16,17,15,15,16,
+       17,17,12,13,13,15,15,13,14,14,16,16,13,14,13,16,
+       15,15,16,15,17,17,15,16,15,17,16,13,13,15,14,17,
+       14,13,16,15,17,15,14,16,15,17,15,15,17,16,18,16,
+       16,17,17,18,14,15,15,17,16,15,16,16,17,17,15,16,
+       15,17,16,17,17,17,18,18,16,17,16,18,17,10,12,11,
+       14,14,11,12,13,15,15,12,13,12,15,15,14,15,15,16,
+       16,14,15,15,17,16,11,12,12,15,15,12,13,13,15,15,
+       13,14,13,16,15,14,15,15,16,16,15,16,15,17,16,11,
+       13,13,15,15,13,14,14,15,15,12,14,13,16,15,15,16,
+       15,17,17,15,16,15,17,16,13,15,14,16,16,14,15,14,
+       16,16,15,16,15,17,16,15,16,16,16,17,16,17,16,18,
+       17,14,15,15,16,16,15,16,16,17,17,15,15,15,17,16,
+       17,17,17,18,18,16,16,16,18,16,12,13,13,15,16,13,
+       14,14,15,16,13,14,14,16,16,15,15,16,16,18,15,16,
+       16,17,17,13,13,14,15,16,14,14,15,15,17,14,15,15,
+       16,17,15,15,17,16,18,16,16,17,17,17,13,14,14,16,
+       16,14,15,15,17,17,14,15,14,17,16,16,17,16,17,18,
+       16,17,16,18,17,15,15,16,14,17,16,15,17,14,18,16,
+       16,16,15,18,16,16,18,15,19,18,18,18,17,19,15,16,
+       16,18,17,16,17,17,18,17,16,17,16,18,17,18,18,18,
+       19,19,17,18,16,18,17,11,12,12,15,15,13,13,14,15,
+       16,13,14,13,16,15,15,16,16,16,17,15,16,16,17,16,
+       12,14,13,16,15,13,13,14,15,16,14,15,14,17,15,15,
+       15,16,16,17,16,17,16,18,17,12,13,14,15,16,14,15,
+       15,16,16,13,14,13,16,15,16,16,16,17,17,15,16,15,
+       17,15,15,16,15,17,16,15,15,15,16,16,16,17,16,18,
+       16,16,15,16,15,17,17,18,17,18,17,15,15,16,17,17,
+       16,16,17,17,17,15,16,15,17,16,18,18,18,18,18,16,
+       17,16,18,15, 9,11,11,14,14,11,12,12,14,15,10,12,
+       12,15,14,13,14,15,16,16,13,14,14,16,16,11,12,12,
+       14,15,12,12,13,15,15,12,13,13,15,15,14,15,15,16,
+       17,14,15,15,16,16,10,12,12,14,14,12,13,13,15,15,
+       11,13,12,15,15,14,15,15,16,17,13,15,14,16,16,14,
+       14,14,15,16,14,15,15,16,17,14,15,15,16,17,16,16,
+       17,16,18,16,17,17,17,17,12,14,13,16,15,13,15,14,
+       16,16,13,14,14,16,15,16,16,16,17,17,15,16,15,17,
+       16,10,11,11,14,14,12,12,13,14,15,11,13,12,15,14,
+       14,15,15,16,17,14,15,15,16,16,12,13,13,15,15,12,
+       13,14,15,16,13,14,14,15,15,15,15,16,16,17,15,15,
+       16,17,17,11,12,12,15,15,13,13,14,15,16,12,13,13,
+       15,15,15,15,16,16,17,14,15,15,16,16,14,15,15,16,
+       16,15,15,15,16,17,15,16,16,17,17,16,16,17,16,18,
+       17,17,17,17,18,13,14,15,16,16,15,15,16,16,17,14,
+       14,14,16,16,16,16,17,17,18,16,16,16,17,16,10,12,
+       12,14,14,12,13,13,15,15,11,13,12,15,15,14,15,15,
+       16,17,13,15,14,17,16,12,13,13,15,15,13,13,14,15,
+       16,13,14,14,16,16,15,15,16,16,17,15,15,16,17,17,
+       11,13,12,15,14,13,14,13,16,15,12,14,12,16,15,15,
+       16,15,17,17,14,15,14,17,16,14,15,15,16,17,15,15,
+       16,16,17,15,16,16,17,17,16,16,17,17,18,17,17,17,
+       18,18,13,15,13,17,14,14,16,14,17,16,14,15,13,17,
+       15,16,17,16,18,17,15,17,15,18,16,11,12,12,15,15,
+       13,13,14,15,16,13,14,13,16,15,15,16,16,16,17,15,
+       16,16,17,16,12,14,13,16,15,13,13,14,15,16,14,15,
+       15,16,16,16,15,16,16,17,16,16,16,17,17,12,13,14,
+       15,16,14,14,15,15,17,13,14,13,16,15,16,16,17,17,
+       18,15,16,15,17,15,15,16,15,17,17,15,15,16,16,17,
+       16,17,16,17,17,16,15,17,15,18,17,18,17,18,18,15,
+       15,16,16,17,16,16,17,16,18,15,15,15,16,16,17,17,
+       18,17,18,16,16,15,17,15,12,13,13,15,15,13,14,14,
+       16,16,13,14,14,16,16,15,16,16,17,18,15,16,15,18,
+       16,13,14,14,16,16,14,14,15,16,17,14,15,15,17,17,
+       16,16,17,17,18,16,16,17,18,17,13,14,13,16,14,14,
+       15,15,17,16,14,15,14,17,15,16,17,17,18,17,15,17,
+       15,18,16,15,16,16,17,17,16,16,17,17,18,16,17,17,
+       18,18,17,16,18,17,19,18,18,18,18,18,15,16,15,17,
+       14,16,16,16,18,15,16,17,15,18,14,18,18,18,18,17,
+       17,18,16,19,15,
+};
+
+static const static_codebook _44p5_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p5_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p5_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p3_0[] = {
+        1, 5, 6, 5, 7, 8, 5, 8, 7, 5, 7, 8, 7, 8,10, 8,
+       10,10, 5, 8, 7, 8,10,10, 7,10, 8, 6, 8, 9, 8,10,
+       11, 9,10,10, 9,10,11,10,11,12,11,12,12, 9,11,10,
+       11,12,12,10,12,11, 6, 9, 8, 9,10,10, 8,11,10, 9,
+       10,11,10,11,12,11,12,12, 9,11,10,11,12,12,10,12,
+       11, 6, 9, 9, 8,10,11, 9,11,10, 8,10,10,10,10,12,
+       11,12,12, 9,11,10,11,12,12,10,12,11, 8,10,10,10,
+       11,12,10,12,11,10,10,12,11,11,13,12,13,13,10,12,
+       11,12,13,13,11,13,11, 7,10,10,10,11,12,10,12,11,
+       10,12,11,11,11,12,12,14,13,10,12,12,12,14,14,11,
+       13,11, 6, 9, 9, 9,10,11, 8,11,10, 9,10,11,10,11,
+       12,11,12,12, 8,11,10,11,12,12,10,12,10, 7,10,10,
+       10,11,12,10,12,11,10,12,12,11,11,13,12,13,13,10,
+       11,12,12,13,14,11,12,11, 8,10,10,10,11,12,10,12,
+       11,10,11,12,11,11,13,12,13,13,10,12,10,12,13,13,
+       11,13,11,
+};
+
+static const static_codebook _44p5_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p5_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p3_1[] = {
+        5, 6, 6, 6, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 8, 7,
+        8, 8, 6, 7, 7, 7, 8, 8, 7, 8, 7, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8,
+        8, 9, 9, 8, 9, 9, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9,
+        8, 6, 8, 8, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 9,
+        8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8, 8,
+        9, 9, 8, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 8, 9, 8,
+        8, 8, 8, 8, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 8,
+        9, 9, 6, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8,
+        8, 8, 9, 8, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 8,
+        8, 8, 9, 9, 9, 8, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9,
+        9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p5_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p5_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p4_0[] = {
+        1, 5, 5, 5, 7, 9, 5, 9, 7, 5, 7, 8, 7, 7,10, 9,
+       10,10, 5, 8, 7, 9,10,10, 7,10, 7, 6, 8, 9, 9,10,
+       12, 9,11,11, 9,10,11,11,11,13,12,13,13, 9,11,11,
+       11,12,13,11,13,11, 6, 9, 8, 9,11,11, 9,12,10, 9,
+       11,11,11,11,13,11,13,12, 9,11,10,12,13,13,11,13,
+       11, 6, 9, 9, 8,10,11, 9,12,11, 9,10,11,10,10,12,
+       11,13,13, 9,11,11,11,13,12,11,13,11, 8,10,10, 9,
+       10,12,10,12,11,10,10,12,10,10,13,12,13,13,10,12,
+       11,12,13,13,10,13,10, 7,10,10,11,11,13,11,14,11,
+       10,12,11,11,11,13,13,14,13,10,12,12,14,14,14,11,
+       14,11, 6, 9, 9, 9,11,12, 8,11,10, 9,11,11,11,11,
+       13,11,12,13, 8,11,10,11,13,13,10,12,10, 7,10,10,
+       11,11,14,11,13,11,10,12,12,11,11,14,14,14,14,10,
+       11,12,13,13,14,11,13,11, 8,10,10,10,11,12, 9,12,
+       10,10,11,12,11,10,13,12,13,13,10,12,10,12,13,13,
+       11,13,10,
+};
+
+static const static_codebook _44p5_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p5_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p5_p4_1[] = {
+        5, 7, 7,10,10, 7, 8, 9,10,11, 7, 9, 8,11,10, 9,
+       10,10,11,11, 9,10,10,11,11, 7, 9, 9,10,10, 8, 9,
+       10,10,11, 9,10,10,11,11,10,10,11,11,11,10,11,11,
+       12,12, 7, 9, 9,10,10, 9,10,10,11,11, 8,10, 9,11,
+       10,10,11,11,11,11,10,11,10,11,11,10,10,10,11,11,
+       10,10,11,11,11,11,11,11,11,11,11,11,12,11,12,11,
+       12,11,12,12,10,10,10,11,11,10,11,11,11,11,10,11,
+       10,11,11,11,12,11,12,12,11,12,11,12,11, 8, 9, 9,
+       11,11, 9,10,10,11,12, 9,10,10,11,11,10,11,11,12,
+       12,10,11,11,12,12, 9,10,10,11,11,10,10,11,11,12,
+       10,11,11,12,12,11,11,12,12,12,11,12,12,12,12, 9,
+       10,10,11,11,10,11,11,12,12,10,11,10,12,12,11,12,
+       12,12,12,11,12,12,12,12,11,11,11,12,12,11,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12, 8, 9, 9,11,11, 9,
+       10,10,11,11, 9,10,10,11,11,10,11,11,12,12,10,11,
+       11,12,12, 9,10,10,11,11,10,10,11,12,12,10,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12, 9,10,10,11,
+       11,10,11,11,12,12,10,11,10,12,11,11,12,12,12,12,
+       11,12,11,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,
+       11,12,12,11,12,12,12,12,11,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,10,11,11,12,12,11,12,12,12,
+       12,11,12,12,12,12,12,12,13,13,13,12,12,12,13,13,
+       11,12,12,12,12,12,12,12,12,13,12,12,12,13,13,12,
+       12,13,13,13,12,13,13,13,13,11,12,12,12,12,12,12,
+       12,13,13,12,12,12,13,13,12,13,13,13,13,12,13,13,
+       13,13,12,12,12,12,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,12,12,12,13,12,
+       13,13,13,13,13,12,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,10,11,11,12,12,11,12,12,12,12,11,12,
+       11,12,12,12,12,12,13,12,12,12,12,13,13,11,12,12,
+       12,12,12,12,12,13,13,12,12,12,13,13,12,13,13,13,
+       13,12,13,13,13,13,11,12,12,12,12,12,12,12,13,13,
+       12,12,12,13,12,12,13,13,13,13,12,13,12,13,13,12,
+       12,12,12,13,12,13,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,12,12,12,13,12,13,13,13,
+       13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,10,12,11,
+       10,11,11,12,12,10,11,11,12,12, 9,10,10,11,11,10,
+       10,11,11,12,10,11,11,12,12,11,11,12,12,12,11,12,
+       12,12,12, 9,10,10,11,11,10,11,11,12,12,10,11,10,
+       12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,12,
+       12,11,11,12,12,12,11,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12, 9,10,
+       10,11,11,10,10,11,12,12,10,11,11,12,12,11,11,12,
+       12,12,11,12,12,12,12,10,10,11,11,12,11,11,12,12,
+       12,11,11,12,12,12,11,11,12,12,13,12,12,12,12,12,
+       10,11,11,12,12,11,12,11,12,12,11,12,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,12,12,13,12,13,12,12,13,
+       13,13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,13,12, 8,10,10,11,11,
+       10,11,11,12,12,10,11,10,12,12,11,12,12,12,12,11,
+       12,12,12,12,10,11,10,12,12,10,10,11,12,12,11,12,
+       12,12,12,12,12,12,12,13,12,12,12,13,13,10,11,11,
+       12,12,11,12,12,12,12,10,12,11,12,12,12,12,12,13,
+       13,12,13,12,13,12,11,12,12,12,12,11,12,12,12,13,
+       12,12,12,13,13,12,12,13,12,13,12,13,13,13,13,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,13,
+       13,13,13,12,13,12,13,12,11,11,11,12,12,11,12,12,
+       12,13,11,12,12,12,12,12,12,12,13,13,12,12,13,13,
+       13,11,12,12,12,12,12,12,12,12,13,12,12,13,13,13,
+       12,12,13,13,13,13,13,13,13,13,11,12,12,12,12,12,
+       13,12,13,13,12,12,12,13,13,12,13,13,13,13,12,13,
+       13,13,13,12,12,12,12,13,12,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,10,11,11,12,12,11,12,12,12,13,11,
+       12,12,13,12,12,13,13,13,13,12,13,13,13,13,11,12,
+       12,12,12,12,12,12,13,13,12,13,12,13,13,13,13,13,
+       13,13,13,13,13,13,13,11,12,12,13,12,12,13,12,13,
+       13,12,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       12,13,13,13,13,12,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,10,11,
+       11,10,11,11,12,12,10,11,11,12,12, 9,10,10,11,11,
+       10,10,11,12,12,10,11,11,12,12,11,11,12,12,12,11,
+       12,12,12,12, 9,10,10,11,11,10,11,11,12,12,10,11,
+       10,12,12,11,12,12,12,12,11,12,11,12,12,11,11,11,
+       12,12,11,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12, 8,
+       10,10,11,11,10,10,11,12,12,10,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,10,11,11,12,12,10,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       13,10,10,11,12,12,11,12,12,12,12,10,11,10,12,12,
+       12,12,12,13,13,12,12,12,13,12,11,12,12,12,12,11,
+       12,12,12,13,12,12,12,13,13,12,12,13,12,13,12,13,
+       13,13,13,11,12,12,12,12,12,12,12,13,13,11,12,12,
+       13,12,12,13,13,13,13,12,13,12,13,12, 9,10,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,10,11,11,12,12,11,11,12,12,12,11,
+       11,12,12,12,12,12,12,12,13,12,12,12,13,12,10,11,
+       10,12,11,11,12,11,12,12,11,12,11,12,12,12,12,12,
+       12,12,12,12,11,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,13,12,13,12,13,13,13,13,
+       11,12,11,12,12,12,12,12,13,12,12,12,12,12,12,12,
+       13,12,13,13,12,12,12,13,12,10,11,11,12,12,11,12,
+       12,12,13,11,12,12,13,12,12,12,13,13,13,12,13,13,
+       13,13,11,12,12,12,13,12,12,13,13,13,12,12,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,11,12,12,12,12,
+       12,12,13,13,13,12,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13,12,13,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,13,
+       13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,11,11,11,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,13,13,13,12,13,12,13,13,11,
+       12,12,12,12,12,12,13,13,13,12,12,13,13,13,12,13,
+       13,13,13,12,13,13,13,13,11,12,12,12,12,12,13,12,
+       13,13,12,12,12,13,12,13,13,13,13,13,12,13,12,13,
+       13,12,12,12,13,13,12,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,12,12,12,13,12,13,
+       13,13,13,13,12,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,10,11,11,12,12,11,12,12,12,12,11,12,12,
+       12,12,12,12,12,13,13,12,12,12,13,13,11,12,12,12,
+       12,11,12,12,13,13,12,12,12,13,13,12,12,13,13,13,
+       12,13,13,13,13,11,12,12,12,12,12,12,12,13,13,12,
+       12,12,13,12,12,13,13,13,13,12,13,12,13,13,12,12,
+       12,12,12,12,12,13,13,13,12,13,13,13,13,12,13,13,
+       13,13,13,13,13,13,13,12,12,12,13,12,12,13,13,13,
+       13,12,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       10,11,11,12,12,11,12,12,12,13,11,12,12,13,12,12,
+       12,12,13,13,12,12,12,13,13,11,12,12,12,12,12,12,
+       13,13,13,12,12,12,13,13,12,12,13,13,13,12,13,13,
+       13,13,11,12,12,12,12,12,12,12,13,13,12,12,12,13,
+       13,12,13,13,13,13,12,13,13,13,13,12,12,12,12,13,
+       12,12,13,13,13,12,13,13,13,13,12,13,13,13,13,13,
+       13,13,13,13,12,12,12,13,13,13,13,13,13,13,12,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,10,11,11,
+       12,12,11,12,12,12,13,11,12,12,13,12,12,13,13,13,
+       13,12,13,12,13,13,11,12,12,13,13,12,12,12,13,13,
+       12,12,13,13,13,12,13,13,13,13,13,13,13,13,13,11,
+       12,12,13,12,12,13,12,13,13,12,13,12,13,13,13,13,
+       13,13,13,12,13,13,13,13,12,12,12,13,13,12,13,13,
+       13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,12,12,12,13,13,12,13,13,13,13,12,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,11,11,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,12,12,12,13,13,12,12,
+       12,13,13,11,12,12,12,12,12,12,12,12,13,12,12,12,
+       13,13,12,12,13,13,13,12,13,13,13,13,11,12,12,12,
+       12,12,12,12,13,13,12,12,12,13,12,12,13,13,13,13,
+       12,13,12,13,13,12,12,12,12,12,12,12,13,12,13,12,
+       13,13,13,13,12,13,13,12,13,13,13,13,13,13,12,12,
+       12,12,12,12,13,13,13,13,12,13,12,13,13,13,13,13,
+       13,13,12,13,13,13,12,10,11,11,12,12,11,12,12,12,
+       12,11,12,12,12,12,12,12,12,13,13,12,13,12,13,13,
+       11,12,12,12,12,12,12,12,13,13,12,12,12,13,13,12,
+       12,13,13,13,13,13,13,13,13,11,12,12,12,12,12,13,
+       12,13,13,12,13,12,13,13,12,13,13,13,13,12,13,12,
+       13,13,12,12,12,12,12,12,13,13,13,13,12,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,12,12,12,13,12,
+       12,13,13,13,13,12,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13,10,11,11,12,12,11,12,12,12,12,11,12,
+       12,12,12,12,12,12,13,13,12,12,12,13,13,11,12,12,
+       12,12,12,12,12,13,13,12,12,12,13,13,12,12,13,13,
+       13,12,12,13,13,13,11,12,11,12,12,12,12,12,13,13,
+       11,12,12,13,13,12,13,13,13,13,12,13,12,13,13,12,
+       12,12,12,12,12,13,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,12,12,12,13,12,12,13,13,
+       13,13,12,13,12,13,13,13,13,13,13,13,12,13,13,13,
+       13,10,11,11,12,12,11,12,12,12,13,11,12,12,13,12,
+       12,12,13,13,13,12,13,13,13,13,11,12,12,13,13,12,
+       12,13,13,13,12,12,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,11,12,12,13,12,12,13,12,13,13,12,12,12,
+       13,13,12,13,13,13,13,13,13,13,13,13,12,12,13,13,
+       13,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,12,12,12,13,13,13,13,13,13,13,12,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,10,12,
+       11,12,12,11,12,12,12,13,11,12,12,12,12,12,12,12,
+       13,13,12,12,12,13,13,11,12,12,12,13,12,12,12,13,
+       13,12,12,12,13,13,12,13,13,13,13,12,13,13,13,13,
+       11,12,12,13,12,12,12,12,13,13,12,12,12,13,13,12,
+       13,13,13,13,12,13,12,13,13,12,13,12,13,13,12,13,
+       13,13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,12,12,12,13,12,13,13,13,13,13,12,13,12,13,
+       13,13,13,13,13,13,12,13,13,13,13,10,11,11,12,12,
+       11,12,12,12,13,11,12,12,12,12,12,12,12,13,13,12,
+       12,12,13,13,11,12,12,12,12,12,12,13,13,13,12,13,
+       13,13,13,12,12,13,13,13,13,13,13,13,13,11,12,12,
+       12,12,12,13,12,13,13,12,12,12,13,13,12,13,13,13,
+       13,12,13,12,13,13,12,12,12,12,13,12,13,13,13,13,
+       12,13,13,13,13,12,13,13,13,13,13,13,13,13,13,12,
+       12,12,12,12,12,13,13,13,13,12,13,13,13,13,13,13,
+       13,13,13,12,13,13,13,13,11,12,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       12,11,12,12,12,12,12,12,12,12,13,12,12,12,13,13,
+       12,12,13,13,13,12,13,13,13,13,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,12,12,13,13,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,12,13,13,13,12,13,13,
+       13,13,13,13,13,12,13,13,13,13,13,13,12,12,12,12,
+       12,12,13,13,13,13,12,13,12,13,12,13,13,13,13,13,
+       13,13,13,13,12,
+};
+
+static const static_codebook _44p5_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p5_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p5_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p5_p5_0[] = {
+        1, 6, 6,10,10, 6, 7, 9,11,13, 5, 9, 7,13,11, 8,
+       11,12,13,15, 8,12,11,15,13, 6, 7, 8,11,11, 7, 8,
+       10,11,13, 9,10,10,13,13,11,11,13,12,16,12,13,13,
+       16,15, 6, 8, 7,11,11, 9,10,10,13,13, 7,10, 7,13,
+       11,12,13,13,15,16,11,13,11,16,12,10,11,11,11,13,
+       11,11,13,12,15,13,13,13,14,15,13,12,15,12,17,15,
+       16,16,16,16,10,11,11,14,11,13,13,13,15,14,11,13,
+       11,15,12,15,15,16,16,16,13,15,12,17,12, 6, 8, 9,
+       12,12, 9,10,12,13,15, 9,11,11,15,14,12,13,15,16,
+       18,13,14,14,17,16, 9,10,11,13,14,11,10,13,14,16,
+       11,12,12,15,15,14,13,16,15,18,14,15,15,17,17, 9,
+       11,11,14,14,11,12,13,15,16,11,13,11,15,14,15,15,
+       15,17,18,14,15,14,17,15,13,14,14,15,16,14,14,15,
+       15,17,15,16,15,17,17,16,16,17,15,19,17,18,18,19,
+       18,13,14,14,16,15,15,15,16,17,17,14,15,14,18,15,
+       17,17,17,19,19,16,17,15,19,16, 6, 9, 8,13,12, 9,
+       11,11,14,15, 9,12,10,15,13,13,14,14,16,17,12,15,
+       13,18,16, 9,11,11,14,14,11,11,13,14,15,11,13,12,
+       16,15,14,14,15,15,18,14,15,15,18,17, 9,11,10,14,
+       13,11,12,12,15,15,11,13,10,16,14,14,15,15,16,18,
+       14,16,13,18,15,13,14,14,16,16,14,14,15,15,17,15,
+       16,15,17,17,16,16,17,16,19,17,18,17,18,19,13,14,
+       14,16,15,15,15,15,17,17,14,15,14,17,15,17,17,17,
+       18,19,16,17,15,19,15,11,13,13,15,16,13,14,15,16,
+       18,14,15,15,17,17,16,16,18,18,20,17,18,17,19,20,
+       13,14,14,16,17,15,15,16,17,18,15,16,16,17,17,18,
+       17,19,18,19,18,18,18,19,21,14,14,15,16,17,15,15,
+       16,18,18,15,16,16,17,18,18,18,19,19,21,18,19,19,
+       22,20,16,16,17,17,19,17,17,17,18,20,17,18,18,20,
+       19,19,19,20,19, 0,19,19,20,20,21,17,17,17,19,18,
+       18,18,20,19,19,18,18,18,20,20,19,19,20,20,20,20,
+       21,20,21,19,11,13,13,16,15,14,15,15,17,17,14,15,
+       14,18,16,16,18,18,20,19,16,19,17,21,18,13,14,15,
+       16,17,15,15,16,18,18,15,16,15,19,18,18,18,18,19,
+       19,18,18,18,22,20,13,14,14,16,16,15,16,16,18,17,
+       15,16,15,18,17,18,18,18,19,19,17,18,17,21,18,16,
+       17,17,18,18,17,18,19,19,19,18,20,18,19,19,19,20,
+       21,19,21,20,20,20, 0,21,16,17,17,19,19,18,18,18,
+       19,21,17,18,18,19,18,20,19,21,20,21,19,20,20,22,
+       19, 7, 9, 9,13,13, 8,10,11,14,15, 9,12,11,15,14,
+       11,13,14,16,17,13,15,14,17,16, 8,10,11,14,14,10,
+       10,12,14,16,11,12,12,16,15,13,12,15,15,18,14,15,
+       15,19,17, 9,11,11,14,14,11,12,12,15,15,11,13,11,
+       16,14,14,15,14,17,17,14,16,14,18,15,12,13,14,15,
+       16,13,13,15,14,17,15,15,15,17,17,15,14,17,14,19,
+       17,18,18,19,18,13,14,14,16,16,15,15,15,17,17,14,
+       15,14,18,15,17,18,17,18,17,16,18,16,19,15, 7,10,
+       10,13,13, 9,10,12,14,15,10,12,11,15,14,12,13,14,
+       16,17,13,15,14,18,16,10,10,12,13,14,10,10,13,13,
+       16,12,12,13,15,15,13,12,15,15,18,15,15,16,18,17,
+       10,11,11,14,14,12,13,13,15,16,10,13,10,16,14,14,
+       15,15,17,17,14,15,13,17,15,13,13,14,15,16,14,13,
+       15,14,18,15,15,16,16,17,16,15,18,15,18,17,18,18,
+       18,18,13,15,14,17,16,15,16,16,17,17,14,15,13,17,
+       15,17,17,18,18,18,16,17,14,20,14, 8,10,10,14,14,
+       11,11,13,14,16,11,13,11,16,14,14,15,16,16,18,14,
+       16,15,18,16,10,12,11,15,14,11,11,13,14,16,13,14,
+       13,16,15,15,14,16,15,19,16,17,16,20,18,10,11,12,
+       14,15,13,13,14,16,16,11,14,11,16,14,16,16,17,18,
+       19,15,17,14,20,15,14,15,14,17,16,13,14,15,15,18,
+       16,17,16,19,18,16,15,18,15,19,18,19,18,21,21,14,
+       14,15,16,17,16,16,17,18,18,13,15,14,17,15,18,18,
+       19,18,22,16,18,15,21,15,12,13,14,16,16,14,14,16,
+       16,18,14,15,15,17,18,16,16,18,18,20,18,18,17,20,
+       20,13,14,15,15,17,15,14,16,16,18,16,16,16,17,19,
+       17,15,18,17,21,18,18,18,19,19,14,15,15,18,17,15,
+       16,16,18,19,15,16,15,18,18,17,18,18,20,21,17,19,
+       17,20,19,16,16,17,16,19,17,17,18,17,20,18,18,18,
+       18,19,19,18,20,17,22,20,20,19,20,20,17,17,18,18,
+       19,18,18,20,21,20,17,18,17,20,20,21,21,21,21,21,
+       19,21,18,22,20,11,13,13,17,16,14,14,16,16,18,14,
+       16,14,18,16,17,18,19,19,20,18,19,18,21,19,14,15,
+       14,17,16,14,14,16,18,18,16,17,16,18,17,18,17,19,
+       18,20,19,19,18,20,20,13,14,15,16,17,16,16,17,18,
+       19,14,16,14,19,17,18,19,18,20,20,18,20,17,21,18,
+       17,17,17,19,18,16,17,18,18,19,18,19,18,21,21,18,
+       18,20,17,21,19,20,20,22,21,16,17,18,18,19,18,18,
+       19,21,20,16,17,17,20,18,21,21,22,21,22,18,21,18,
+        0,18, 7, 9, 9,13,13, 9,11,12,14,15, 8,11,10,15,
+       14,13,14,15,16,18,11,14,13,17,15, 9,11,11,14,14,
+       11,11,13,14,16,11,12,12,15,15,14,14,16,15,18,14,
+       14,15,17,17, 8,11,10,14,14,11,12,12,15,15,10,12,
+       10,16,14,14,15,15,17,18,13,15,12,18,15,13,14,14,
+       16,16,14,14,15,15,17,15,15,15,16,17,16,15,17,15,
+       19,17,17,17,18,18,12,14,13,16,15,15,15,15,17,17,
+       13,15,13,17,14,17,18,18,18,19,15,17,14,19,14, 8,
+       10,10,14,14,11,11,13,14,16,11,13,11,16,14,14,15,
+       16,17,19,14,16,15,18,17,10,12,11,15,14,11,11,14,
+       14,17,13,14,13,17,15,15,14,17,15,19,16,17,16,19,
+       17,10,11,12,14,15,13,13,14,15,17,11,13,11,17,14,
+       16,16,17,18,19,15,16,14,18,15,14,15,14,16,16,13,
+       14,15,15,18,16,16,16,18,18,16,15,18,15,20,18,19,
+       18,21,18,14,14,15,16,17,16,16,17,17,18,13,15,14,
+       17,16,19,19,19,19,19,15,18,15,20,15, 7,10,10,13,
+       13,10,11,12,14,15, 9,12,10,15,14,13,14,15,16,17,
+       12,15,13,17,16,10,11,11,14,14,10,10,13,14,16,12,
+       13,13,16,15,14,13,16,15,18,15,15,16,17,17,10,12,
+       10,14,13,12,13,12,15,15,10,13,10,16,13,15,16,15,
+       17,18,13,16,12,18,15,13,14,14,16,17,14,13,15,15,
+       18,15,16,15,17,17,16,14,17,15,19,17,18,18,19,19,
+       13,15,13,17,14,15,15,15,18,17,14,15,13,17,14,18,
+       17,18,18,19,15,17,15,19,15,11,13,13,16,17,14,14,
+       16,16,18,14,16,15,18,17,17,18,19,18,21,18,18,17,
+       20,18,13,15,14,17,16,14,14,16,17,18,16,17,16,19,
+       17,18,17,19,18,22,18,19,19,21,21,13,14,15,16,18,
+       16,16,17,17,20,14,16,14,18,17,18,18,19,19,21,17,
+       18,17,21,18,17,18,17,19,18,16,17,17,18,19,18,18,
+       18,22,22,18,17,19,17, 0,20,21,19,21,20,17,17,18,
+       18,21,18,18,18,19,21,17,17,17,19,19,20,20,22,21,
+       21,19,20,18,20,17,12,14,13,17,16,14,15,15,17,18,
+       14,16,14,18,16,17,18,18,21,20,16,18,16,21,18,14,
+       15,15,17,17,15,15,16,18,18,15,17,16,18,18,17,17,
+       19,19,20,18,19,18,20,19,14,15,14,17,15,15,16,16,
+       18,17,15,16,14,19,15,18,18,18,19,20,17,20,15,21,
+       17,16,17,18,18,19,17,17,18,18,20,18,19,18,19,21,
+       19,18,19,19,21,20, 0,19,21,20,16,17,16,19,16,18,
+       18,18,19,19,17,18,17,20,17,19,20,20,22, 0,19,20,
+       17,21,17,11,13,14,16,17,14,15,15,17,18,14,15,15,
+       18,18,16,17,17,19,20,16,18,17,19,21,13,14,15,17,
+       17,14,15,16,17,19,15,16,16,18,19,16,17,18,19,21,
+       17,18,20,21,21,13,15,15,17,17,15,16,16,18,19,15,
+       16,16,18,19,17,17,18,19,22,17,19,18,22,19,15,16,
+       17,19,19,16,17,18,18,20,17,18,18,19,20,19,18,20,
+       18,22,20,19,19,22,21,16,17,17,18,19,18,18,18,19,
+       20,17,18,18,20,19,20,19,20,22,20,19,20,21,21,20,
+       12,14,14,16,16,13,14,16,17,18,14,16,15,18,18,15,
+       17,17,19,19,17,18,18,19,19,13,14,15,16,17,14,14,
+       16,16,20,15,16,16,17,19,16,15,18,17,20,18,17,19,
+       19,19,14,15,15,17,17,16,16,16,18,18,15,16,15,19,
+       18,17,18,18,20,21,17,18,17,21,18,16,15,17,17,19,
+       17,15,18,17,20,19,17,18,19,20,18,16,19,17,22,20,
+       19,20,19,20,17,17,18,19,19,18,18,19,20,20,17,18,
+       17,18,18,21,21,20,20,21,18,20,17,21,19,11,14,14,
+       16,17,15,14,16,17,19,14,16,14,18,17,18,18,19,19,
+       21,17,19,18,20,20,13,15,14,17,17,14,14,16,17,18,
+       16,17,16,19,18,18,17,19,18,20,18,21,18,20,20,13,
+       15,15,16,17,16,16,17,18,19,14,16,15,19,18,19,19,
+       19,21,20,18,19,17,20,18,16,17,16,19,18,16,17,17,
+       19,20,17,19,18,20,19,18,17,21,18, 0,21,20,20, 0,
+       20,17,17,18,18,19,18,19,19,20,22,16,17,17,20,18,
+       21,22,20,20,22,18,22,18,22,18,12,14,14,17,17,14,
+       15,16,17,19,14,16,15,17,17,17,17,18,18,21,17,19,
+       17,20,19,14,15,15,16,18,15,14,16,16,19,16,17,16,
+       19,18,17,16,20,17,20,18,20,19,19,20,14,15,15,18,
+       17,16,16,17,18,19,14,16,15,19,17,18,21,18,19,21,
+       17,18,17,19,18,17,17,18,17,20,17,16,18,17,21,18,
+       19,19,19,19,18,17,19,17,20,20,21,20,21,20,17,17,
+       17,19,19,19,18,18,20,21,16,18,16,19,18,20,20,21,
+       21,20,18,19,16, 0,17,12,14,14,17,17,15,15,18,17,
+       19,15,18,15,20,16,20,19,21,18,22,20,20,20,22,19,
+       14,16,14,20,17,14,15,17,17,20,18,18,17,20,18,18,
+       17,19,17,21,20,21,20, 0,21,14,15,16,17,19,18,17,
+       19,18,21,14,18,15,21,17,21,20,21,20, 0,18,21,17,
+       21,17,18,19,17,20,18,16,17,17,19,19,19,21,20, 0,
+       20,18,17,21,17, 0,22, 0,21, 0,22,17,17,19,18,20,
+       20,20,21,19,22,16,17,18,20,18,22,22, 0,22, 0,17,
+       21,17,22,17,11,14,13,16,16,14,15,15,17,18,14,15,
+       14,18,17,17,18,18,19,20,16,17,17,21,19,13,14,15,
+       17,17,15,16,16,18,18,15,16,16,19,18,18,18,18,19,
+       20,17,18,18,20,19,13,15,14,17,17,15,16,16,17,18,
+       14,16,15,19,17,17,18,19,21,21,17,18,17,20,18,16,
+       17,17,19,19,17,18,19,19,20,18,19,18,21,21,21,20,
+       19,21,22,20,20,19,21,20,15,17,16,19,19,17,18,18,
+       20,21,16,18,17,20,18,19,19,21,21,21,19,19,19,20,
+       18,11,14,13,17,16,14,14,16,16,19,14,16,15,19,16,
+       18,18,18,19,22,17,18,17,20,19,13,15,14,17,17,15,
+       15,16,17,19,16,17,16,20,18,18,17,19,18,21,19,19,
+       18,22, 0,13,14,15,17,18,16,16,17,17,19,14,16,15,
+       19,18,18,19,19,20,21,18,18,17,20,18,17,18,17,20,
+       18,16,17,17,18,20,18,19,18,20,20,18,18,21,17,21,
+       20,21,21, 0,19,16,16,18,18,19,19,18,20,19,20,16,
+       17,17,20,18,21,20,21,22,22,18,20,17,21,17,12,14,
+       14,17,16,14,15,16,18,18,13,15,14,18,17,17,18,18,
+       19,19,15,17,16,19,19,14,15,15,17,17,15,15,16,18,
+       19,15,16,16,19,18,17,17,18,18,20,18,18,18,21,20,
+       13,15,14,17,16,15,16,15,18,18,14,16,14,18,17,18,
+       18,18,19,21,16,18,16,20,17,17,18,17,18,19,17,17,
+       18,18,19,18,19,19,21,19,19,18,20,18,21,21,20,20,
+       21,20,16,17,15,20,17,17,19,17,19,19,17,18,15,20,
+       17,19,20,19,21,22,17,20,16, 0,17,12,14,14,17,18,
+       16,15,18,16,20,16,18,15,21,17,20,18,21,19,22,19,
+       21,19, 0,19,14,16,15,19,17,14,15,17,16,21,18,19,
+       18,21,17,19,17,21,17,22,20,21,21, 0,21,14,15,16,
+       17,19,18,17,19,18,21,14,17,15,20,17,21,22,21,20,
+       22,18,21,17,21,17,17,19,17,21,18,16,17,17,19,20,
+       19,21,20,21,20,17,18,20,17,21, 0,22,20,21,22,17,
+       17,20,18,21,21,20,22,20,21,16,17,17,21,19, 0,22,
+        0,21,21,18,22,17,21,17,12,14,14,17,16,14,15,16,
+       17,18,14,16,15,18,17,17,17,20,19,20,16,18,17,21,
+       18,14,15,15,17,17,14,15,16,17,19,16,17,16,18,18,
+       17,16,19,18,19,18,19,18,21,20,14,15,15,18,17,16,
+       16,16,19,18,15,16,14,20,16,18,18,19,19,20,16,19,
+       16,21,17,17,17,18,19,19,16,16,18,18,19,19,19,18,
+       20,20,18,16,19,18,20,22,21,20,19,20,16,18,17,20,
+       16,18,19,18,19,18,16,18,16,20,17,21,20,21,20,20,
+       18,19,17,21,16,
+};
+
+static const static_codebook _44p5_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p5_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p5_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p5_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p5_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p5_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p5_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p6_0[] = {
+        1, 5, 5, 5, 7, 9, 5, 9, 7, 5, 7, 8, 7, 7,10, 9,
+        9,10, 5, 8, 7, 9,10, 9, 7,10, 7, 6, 9, 9, 9,10,
+       12,10,12,11, 9,10,11,11,10,13,12,12,13,10,11,11,
+       12,13,13,11,13,11, 6, 9, 9,10,11,12, 9,12,11,10,
+       11,11,11,11,13,12,13,13, 9,11,10,12,13,13,11,13,
+       10, 6, 9,10, 9,11,12,10,12,11, 9,10,11,10,10,13,
+       11,13,13,10,11,11,12,13,12,11,13,11, 7, 9,10, 9,
+       10,12,10,11,11,10,10,11,10,10,12,12,11,12,10,11,
+       10,12,12,12,10,12,10, 7,10,10,11,11,13,11,13,11,
+       10,12,11,11,10,13,13,14,13,10,11,12,13,13,14,11,
+       13,10, 6,10, 9,10,11,12, 9,12,11, 9,11,11,11,11,
+       13,12,12,13, 9,11,10,12,13,13,10,13,10, 7,10,10,
+       11,11,14,11,13,11,10,12,11,11,10,14,13,14,13,10,
+       11,12,13,13,14,11,13,10, 7,10, 9,10,10,12, 9,12,
+       10,10,11,11,10,10,12,12,12,12, 9,11,10,11,12,12,
+       10,12, 9,
+};
+
+static const static_codebook _44p5_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p5_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p6_1[] = {
+        2, 6, 6, 5, 7, 8, 5, 8, 7, 6, 7, 7, 7, 7, 8, 8,
+        8, 8, 6, 7, 7, 7, 8, 8, 7, 8, 7, 6, 8, 8, 8, 9,
+       10, 8, 9, 9, 8, 9, 9, 9, 9,10,10,10,10, 8, 9, 9,
+       10,10,10, 9,10,10, 6, 8, 8, 8, 9, 9, 8,10, 9, 9,
+        9, 9, 9, 9,10,10,10,10, 8, 9, 9,10,10,10, 9,10,
+        9, 6, 8, 9, 8, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9,10,
+        9,10,10, 8, 9, 9, 9,10,10, 9,10, 9, 7, 8, 9, 8,
+        9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 7, 9, 9, 9,10,10, 9,10,10,
+        9,10, 9, 9, 9,10,10,10,10, 9,10, 9,10,10,10, 9,
+       10, 9, 6, 8, 8, 8, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9,
+       10, 9,10,10, 8, 9, 9, 9,10,10, 9,10, 9, 7, 9, 9,
+        9,10,10, 9,10, 9, 9, 9,10,10, 9,10,10,10,10, 9,
+        9, 9,10,10,10, 9,10, 9, 7, 9, 8, 8, 9, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p5_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p5_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p5_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p5_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p5_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p5_p7_1[] = {
+        1, 7, 7, 6, 9, 9, 7, 9, 9, 6, 9, 9, 9, 9, 9, 9,
+        9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,
+};
+
+static const static_codebook _44p5_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p5_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p5_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p5_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p5_p7_2[] = {
+        1, 2, 3, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+       11,12,12,13,13,14,14,14,14,
+};
+
+static const static_codebook _44p5_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p5_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p5_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p5_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p5_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p5_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p5_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p5_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p5_short[] = {
+        4, 7,12,14,15,18,20,20, 5, 3, 4, 6, 9,11,15,19,
+        9, 4, 3, 4, 7, 9,13,18,11, 6, 3, 3, 5, 8,13,19,
+       14, 9, 6, 5, 7,10,16,20,16,11, 9, 8,10,10,14,16,
+       21,14,13,11, 8, 7,11,14,21,14,13, 9, 6, 5,10,12,
+};
+
+static const static_codebook _huff_book__44p5_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p5_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p6_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p6_l0_0[] = {
+        1, 4, 4, 7, 7,10,10,12,12,12,12,13,12, 5, 5, 5,
+        8, 6,11, 9,12,12,13,12,12,12, 4, 5, 5, 6, 8, 9,
+       11,12,12,13,12,12,12, 7, 7, 8, 9, 9,11, 8,12, 9,
+       12,12,12,12, 7, 8, 8, 9, 9, 8,11, 9,12,12,12,11,
+       12,10,10,10,11,11,11,11,11,10,11,11,12,11,10,10,
+       10,11,11,11,11,10,11,11,11,11,12,11,11,11,12,11,
+       12,11,12,11,13,11,13,11,11,11,11,11,12,11,12,10,
+       13,11,12,11,13,12,12,12,13,12,13,13,13,12,14,12,
+       14,13,12,12,12,12,13,13,13,12,14,12,14,13,14,13,
+       14,14,14,14,14,14,14,14,15,14,15,14,13,14,13,14,
+       14,14,14,14,15,14,14,14,15,
+};
+
+static const static_codebook _44p6_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p6_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p6_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p6_l0_1[] = {
+        4, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
+        5, 5, 4, 5, 5, 5, 5, 5, 4,
+};
+
+static const static_codebook _44p6_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p6_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p6_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_l1_0[] = {
+        1, 3, 2, 5, 5, 6, 6, 6, 6,
+};
+
+static const static_codebook _44p6_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44p6_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p6_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p6_lfe[] = {
+        2, 3, 1, 3,
+};
+
+static const static_codebook _huff_book__44p6_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p6_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p6_long[] = {
+        2, 7,13,15,16,17,19,20, 6, 3, 4, 7, 9,10,12,15,
+       13, 4, 3, 4, 7, 8,11,13,14, 7, 4, 4, 6, 7,10,11,
+       16, 9, 7, 6, 7, 8, 9,10,16, 9, 8, 7, 7, 6, 8, 8,
+       18,12,10,10, 9, 8, 8, 9,20,14,13,12,11, 8, 9, 9,
+};
+
+static const static_codebook _huff_book__44p6_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p6_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p6_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p1_0[] = {
+        2, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 5, 7, 8, 8, 9,
+       10, 8, 9, 9, 8, 9,10, 9,10,12,10,11,11, 8, 9,10,
+       10,11,11, 9,11,11, 5, 8, 7, 8, 9, 9, 8,10, 9, 8,
+       10, 9, 9,11,11,10,11,11, 8,10, 9,10,11,11, 9,12,
+       10, 5, 8, 8, 7, 9,10, 8,10, 9, 7, 9, 9, 9,10,11,
+        9,11,11, 8,10,10,10,11,11,10,12,11, 7, 9, 9, 9,
+       10,11, 9,11,11, 9, 9,11,10,10,13,11,11,12, 9,11,
+       11,11,12,13,11,13,12, 7, 9, 9, 9,11,11, 9,12,10,
+        9,11,10,10,11,12,11,13,12, 9,11,11,11,13,13,11,
+       13,11, 5, 8, 8, 8, 9,10, 7,10, 9, 8,10,10,10,11,
+       11,10,11,11, 7, 9, 9, 9,11,11, 9,11,10, 7, 9, 9,
+        9,10,12, 9,11,11, 9,11,11,11,11,13,11,13,13, 9,
+       10,11,11,12,13,10,12,11, 7, 9, 9, 9,11,11, 9,11,
+       10, 9,11,11,11,12,13,11,13,12, 9,11, 9,11,12,11,
+       10,13,10,
+};
+
+static const static_codebook _44p6_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p6_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p6_p2_0[] = {
+        4, 6, 6, 9, 9, 6, 7, 8,10,10, 6, 8, 7,10,10, 8,
+       10,10,12,13, 8,10,10,13,12, 6, 8, 8,10,10, 7, 8,
+        9,10,11, 8, 9, 9,11,11,10,10,11,12,13,10,11,11,
+       14,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 9, 8,11,
+       10,10,11,11,13,14,10,11,10,13,12, 9,10,10,12,12,
+       10,10,11,12,13,10,11,11,13,13,12,12,13,12,15,13,
+       14,13,15,14, 9,10,10,13,12,10,11,11,13,13,10,11,
+       10,13,12,13,13,14,14,15,12,13,12,15,12, 6, 8, 8,
+       10,11, 8, 9,10,11,12, 8, 9, 9,11,11,10,11,12,13,
+       14,10,11,11,14,13, 8, 9, 9,11,12, 9,10,11,12,13,
+        9,10,11,12,13,11,11,13,13,15,11,12,12,14,14, 8,
+        9, 9,12,12, 9,10,11,12,13, 9,10,10,13,12,11,12,
+       13,14,15,11,12,12,14,14,11,11,12,13,14,11,12,13,
+       13,15,12,13,13,14,15,13,13,14,14,16,14,15,15,16,
+       16,11,12,11,14,13,12,13,13,14,14,11,13,12,14,13,
+       14,15,15,16,16,13,14,14,16,14, 6, 8, 8,11,10, 8,
+        9, 9,12,11, 8,10, 9,12,11,10,11,11,13,13,10,12,
+       11,14,13, 8, 9, 9,12,12, 9,10,10,12,13, 9,11,10,
+       13,12,11,12,12,14,14,11,13,12,15,14, 8, 9, 9,12,
+       11, 9,10,10,13,12, 9,11,10,13,12,12,12,12,14,14,
+       11,13,12,15,13,11,11,12,13,14,11,12,13,13,14,12,
+       13,13,14,15,13,13,14,14,16,14,15,15,16,16,11,12,
+       11,14,13,12,13,13,15,14,11,13,12,15,13,14,15,15,
+       16,16,13,15,13,16,14, 9,10,11,12,13,11,11,12,13,
+       14,11,12,12,13,14,13,13,14,14,16,13,14,14,15,16,
+       11,11,12,13,14,12,12,13,14,15,12,13,13,14,15,14,
+       14,15,15,17,14,15,15,16,17,11,12,12,14,14,12,13,
+       13,14,15,12,13,12,15,15,14,15,15,16,17,14,15,15,
+       16,16,13,14,14,15,16,14,14,15,15,17,15,15,15,16,
+       17,16,16,17,16,18,16,17,17,18,18,13,14,14,16,15,
+       14,15,15,17,16,14,15,15,16,16,16,17,17,18,18,16,
+       16,16,17,16, 9,11,10,13,12,11,12,12,14,13,11,12,
+       11,15,13,13,14,14,16,15,13,14,13,17,14,11,12,12,
+       14,14,12,12,13,15,15,12,13,13,15,14,14,14,15,16,
+       16,14,15,15,17,16,11,12,11,14,13,12,13,13,15,14,
+       12,13,12,15,13,14,15,15,16,16,14,15,14,17,15,13,
+       14,14,15,16,14,15,15,16,17,14,15,15,16,17,16,16,
+       16,17,17,16,17,17,18,18,13,15,14,16,15,15,15,15,
+       17,16,14,15,14,17,15,16,17,17,18,18,16,17,16,18,
+       16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,11,
+       10,11,11,13,14,10,12,11,14,13, 7, 9, 9,11,12, 9,
+       10,10,12,13, 9,10,10,13,12,11,11,12,13,15,11,12,
+       12,15,14, 8, 9, 9,12,11, 9,10,10,13,13, 9,11,10,
+       13,12,12,12,12,14,15,11,13,12,15,13,10,11,11,13,
+       14,11,12,12,13,15,11,12,12,14,14,13,13,14,14,16,
+       14,15,14,16,16,11,12,11,14,13,12,13,13,15,14,11,
+       13,12,15,13,14,15,15,16,16,13,14,14,16,14, 8, 9,
+        9,11,12, 9,10,11,12,13, 9,10,10,13,12,11,12,13,
+       14,15,11,12,12,15,14, 9, 9,11,11,13,10,10,12,12,
+       14,10,10,11,13,14,12,12,13,14,16,12,13,13,15,15,
+        9,11,10,13,12,10,11,11,13,14,10,12,11,14,13,12,
+       13,13,15,16,12,13,13,15,15,11,11,13,13,15,12,12,
+       14,13,15,13,13,14,14,15,14,14,15,14,17,15,15,15,
+       16,16,12,13,12,15,14,13,14,14,15,15,12,14,13,15,
+       14,15,15,15,17,17,14,15,14,17,15, 7, 9, 9,12,11,
+        9,10,10,12,12, 9,11,10,13,12,11,12,12,14,14,11,
+       13,12,15,14, 9,10,10,12,12,10,10,11,12,13,10,11,
+       11,14,13,12,12,13,14,15,12,13,13,16,15, 9,10,10,
+       13,12,10,11,11,13,13,10,11,10,14,12,13,13,13,15,
+       15,12,13,12,15,14,11,12,12,14,14,12,12,13,14,15,
+       13,14,13,15,15,14,13,15,14,16,15,16,15,17,16,12,
+       12,12,14,14,13,13,14,15,15,12,13,12,15,14,15,15,
+       16,16,17,14,15,14,17,14,10,11,12,13,14,11,12,13,
+       14,15,11,12,13,14,15,13,14,15,15,17,14,15,15,16,
+       16,11,12,13,12,15,12,12,14,13,16,13,13,14,13,16,
+       14,14,16,14,18,15,15,16,16,17,12,13,12,15,15,13,
+       14,14,15,16,13,14,13,16,15,15,15,16,17,18,15,15,
+       15,17,16,14,14,15,14,17,15,14,16,14,17,15,15,16,
+       15,18,16,16,17,16,19,17,17,17,17,18,14,15,15,17,
+       16,15,16,16,17,17,15,16,15,18,16,17,17,18,18,18,
+       16,17,16,18,17,10,11,11,14,13,11,12,12,15,14,11,
+       13,12,15,14,14,15,15,16,16,14,15,15,17,16,11,12,
+       12,15,14,12,13,13,15,14,13,14,13,16,14,14,15,15,
+       16,16,15,16,15,18,16,11,13,12,15,15,13,14,14,15,
+       15,12,14,13,16,15,15,16,16,17,17,15,16,15,17,16,
+       14,15,14,16,16,14,15,15,16,16,15,16,15,17,16,16,
+       16,17,16,17,17,18,17,19,18,14,15,15,17,16,15,16,
+       16,17,17,15,15,15,18,16,17,18,18,18,18,16,17,16,
+       19,16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,
+       11,10,11,12,13,14,10,11,11,14,13, 8, 9, 9,11,12,
+        9,10,11,12,13, 9,10,10,13,13,11,12,13,13,15,11,
+       12,12,15,14, 7, 9, 9,12,11, 9,10,10,12,13, 9,10,
+       10,13,12,11,12,12,14,15,11,12,11,14,13,11,11,12,
+       13,14,11,12,13,13,15,12,13,13,14,15,13,14,14,14,
+       16,14,15,15,16,16,10,11,11,14,13,11,12,12,14,14,
+       11,12,12,15,13,14,14,14,16,16,13,14,13,16,14, 7,
+        9, 9,11,12, 9,10,10,12,13, 9,10,10,12,12,11,12,
+       13,14,15,11,12,12,14,14, 9,10,10,12,13,10,10,11,
+       12,14,10,11,11,13,13,12,12,13,14,15,13,13,13,15,
+       15, 9,10,10,12,12,10,11,11,13,14,10,11,10,13,12,
+       12,13,13,15,16,12,13,12,15,14,11,12,13,14,14,12,
+       12,13,14,15,13,14,13,15,15,14,14,15,14,17,15,16,
+       15,17,16,11,12,12,14,14,13,13,13,15,15,12,13,12,
+       15,14,15,15,15,16,17,14,15,14,16,14, 8, 9, 9,12,
+       11, 9,10,10,12,13, 9,11,10,13,12,11,12,12,14,15,
+       11,12,12,15,14, 9,10,11,13,13,10,11,12,13,14,10,
+       11,11,14,13,12,13,13,15,15,12,13,13,16,15, 9,11,
+        9,13,11,10,11,10,14,13,10,12,10,14,12,12,13,13,
+       15,15,12,13,12,16,14,12,12,13,14,15,12,13,14,14,
+       16,13,14,14,15,15,14,14,15,15,17,15,16,15,17,16,
+       11,13,11,15,13,13,14,13,15,14,12,14,12,16,13,15,
+       15,15,16,16,14,15,14,17,14,10,11,11,13,14,11,12,
+       13,14,15,11,12,12,14,15,14,14,15,16,17,14,15,15,
+       16,16,11,12,13,14,15,12,13,14,15,16,13,14,14,15,
+       16,15,15,16,16,18,15,16,16,17,17,11,12,12,14,15,
+       13,13,14,14,16,12,13,13,15,15,15,15,16,16,18,14,
+       15,15,16,16,14,15,15,16,17,15,15,16,16,17,15,16,
+       16,17,17,16,16,17,16,19,17,18,17,18,18,14,14,15,
+       16,16,15,15,16,16,17,14,15,15,16,16,17,17,18,18,
+       19,16,17,16,17,16,10,12,11,14,13,11,13,12,15,14,
+       11,13,12,15,14,14,15,15,16,16,13,15,14,17,15,12,
+       13,13,15,15,13,13,14,15,16,13,14,14,16,16,14,15,
+       15,17,17,15,16,16,17,17,11,13,12,15,12,13,14,13,
+       16,13,12,14,12,16,13,15,16,15,17,16,14,16,14,18,
+       14,14,15,15,16,17,15,15,16,16,17,15,16,16,17,17,
+       16,16,17,17,18,17,18,17,18,18,14,15,14,17,14,15,
+       16,15,18,15,15,16,15,18,14,17,17,17,18,17,16,17,
+       16,19,16, 9,11,11,13,13,10,12,12,14,14,11,12,12,
+       15,14,13,14,14,16,16,13,14,14,16,16,10,11,12,14,
+       14,11,12,13,14,15,12,13,13,15,15,13,14,15,16,16,
+       14,15,15,17,16,11,12,12,15,14,12,13,13,15,15,12,
+       13,12,15,15,14,15,15,16,17,14,15,14,17,16,12,13,
+       14,15,16,13,13,14,15,16,13,14,15,16,16,14,15,16,
+       16,18,15,16,16,18,18,13,14,14,16,15,14,15,15,17,
+       16,14,15,15,17,16,16,17,17,18,18,16,17,16,18,17,
+       10,12,12,14,14,11,12,13,15,15,12,13,13,15,15,13,
+       14,15,16,17,14,15,15,17,16,11,11,13,14,15,12,12,
+       14,15,16,13,13,14,15,16,14,14,15,16,17,15,15,16,
+       17,17,12,13,12,15,15,13,14,14,16,16,13,14,13,16,
+       15,15,16,15,17,17,15,16,15,18,16,13,12,15,14,17,
+       14,13,16,14,17,14,14,16,15,18,15,14,17,16,18,16,
+       16,17,17,18,14,15,15,17,16,15,16,16,17,17,15,16,
+       15,18,16,17,17,17,18,18,16,17,16,19,17,10,11,11,
+       14,14,11,12,12,15,15,11,13,12,15,15,14,15,14,16,
+       16,14,15,15,17,16,11,12,12,15,14,12,12,13,15,15,
+       13,14,13,16,15,14,15,15,16,16,15,16,15,18,17,11,
+       13,12,15,15,13,14,13,15,15,12,14,13,16,15,15,16,
+       15,17,17,15,16,15,18,16,13,14,13,16,16,14,15,14,
+       16,16,14,15,15,17,16,16,16,16,16,18,16,18,17,19,
+       18,14,15,15,17,16,15,16,16,17,17,15,15,15,17,16,
+       17,17,18,18,19,16,17,16,18,16,12,13,13,15,16,13,
+       14,14,16,17,13,14,14,16,16,15,15,16,17,18,15,16,
+       16,18,17,13,13,14,14,17,14,14,15,15,17,14,14,15,
+       16,17,15,15,17,16,18,16,17,17,18,18,13,14,14,17,
+       16,14,15,15,17,17,14,15,14,17,16,16,17,17,18,18,
+       16,17,16,18,17,15,14,16,13,18,16,15,17,14,19,16,
+       16,17,15,18,17,16,18,15,19,18,18,18,17,19,15,16,
+       16,18,17,16,17,17,18,18,16,17,16,19,17,18,19,18,
+       19,19,17,18,17,20,18,11,12,12,15,15,13,13,14,15,
+       16,13,14,13,16,15,15,16,16,17,17,15,16,16,18,17,
+       12,14,13,16,15,13,13,14,15,16,14,15,14,17,16,16,
+       16,16,16,17,16,17,17,19,17,12,13,14,16,16,14,15,
+       15,16,17,13,15,13,17,15,16,17,17,18,18,16,17,16,
+       18,16,15,16,15,17,16,15,15,15,17,17,16,17,16,18,
+       17,17,16,17,16,18,18,19,18,20,18,15,16,16,17,17,
+       16,17,17,18,18,15,16,15,18,17,18,18,19,19,19,17,
+       18,16,19,16, 9,11,11,13,13,11,12,12,14,15,10,12,
+       12,14,14,13,14,14,16,16,13,14,14,16,16,11,12,12,
+       14,14,12,12,13,15,15,12,13,13,15,15,14,15,15,16,
+       17,14,15,15,16,16,10,12,11,14,14,12,13,13,15,15,
+       11,13,12,15,14,14,15,15,16,17,13,15,14,17,16,13,
+       14,14,15,16,14,15,15,16,17,14,15,15,16,17,16,16,
+       17,17,18,16,17,17,18,18,12,14,13,16,15,13,15,14,
+       17,16,13,14,13,17,15,15,16,16,18,18,15,16,15,18,
+       16,10,11,11,14,14,11,12,13,14,15,11,12,12,15,15,
+       14,15,15,16,17,14,15,15,16,16,11,12,13,15,15,12,
+       13,14,15,16,13,14,14,15,16,15,15,16,16,18,15,15,
+       16,17,17,11,12,12,14,15,13,13,14,15,16,12,13,13,
+       15,15,15,15,16,17,18,14,15,15,17,16,14,15,15,16,
+       17,15,15,16,16,17,15,16,16,17,17,16,16,17,16,19,
+       17,17,18,19,18,13,13,14,16,16,14,15,16,17,17,14,
+       14,15,16,16,16,16,17,18,18,16,16,16,18,16,10,12,
+       12,14,14,12,13,13,15,15,11,13,12,15,15,14,15,15,
+       16,17,13,15,14,17,16,12,13,13,15,15,13,13,14,15,
+       16,13,14,14,16,16,15,15,16,17,18,15,15,16,17,17,
+       11,13,12,15,14,13,14,13,16,15,12,14,12,16,14,15,
+       16,15,17,17,14,16,14,17,16,14,15,15,16,17,15,15,
+       16,16,18,15,16,16,17,17,16,17,17,17,19,17,17,17,
+       18,18,13,15,12,17,14,14,16,14,17,15,14,15,13,17,
+       14,16,17,16,18,17,15,17,14,19,15,11,12,12,15,15,
+       13,13,14,15,16,13,14,13,16,15,15,16,16,17,18,15,
+       16,16,17,17,12,14,13,16,16,13,13,15,15,17,14,15,
+       15,17,16,16,16,17,16,19,16,17,17,18,18,12,13,14,
+       15,16,14,14,15,16,17,13,14,13,16,15,16,17,17,18,
+       19,15,16,16,17,16,15,16,16,18,17,15,15,16,17,18,
+       16,17,17,18,18,16,16,18,16,19,18,19,19,20,19,15,
+       15,16,16,17,16,16,17,17,18,15,15,15,17,16,18,18,
+       19,18,20,17,17,16,18,16,12,13,13,16,15,13,14,14,
+       16,16,13,14,14,16,16,15,16,16,17,18,15,16,15,18,
+       17,13,14,14,16,16,14,15,15,16,17,14,15,15,17,17,
+       16,17,17,18,18,16,17,17,18,18,13,14,13,17,14,14,
+       15,14,17,16,14,15,14,17,15,16,17,17,18,18,15,17,
+       15,19,15,16,16,16,17,18,16,16,17,17,19,16,17,17,
+       18,19,17,17,18,18,20,18,18,18,19,19,15,16,14,18,
+       13,16,17,16,19,15,16,17,15,19,14,18,18,18,19,17,
+       17,18,16,20,15,
+};
+
+static const static_codebook _44p6_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p6_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p6_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p3_0[] = {
+        1, 5, 5, 5, 7, 8, 5, 8, 7, 5, 7, 8, 8, 8,10, 8,
+       10,10, 5, 8, 7, 8,10,10, 8,10, 8, 6, 8, 9, 8,10,
+       12, 9,11,11, 9,10,11,11,11,13,12,13,13, 9,11,11,
+       11,13,13,11,13,12, 6, 9, 8, 9,11,11, 8,12,10, 9,
+       11,11,11,12,13,11,13,13, 9,11,10,11,13,13,11,13,
+       11, 5, 9, 9, 8,11,11, 9,12,11, 8,10,11,10,11,13,
+       11,13,13, 9,11,11,11,13,13,11,13,12, 8,10,11,10,
+       12,13,10,13,12,10,10,13,11,11,14,12,13,14,11,13,
+       12,13,14,14,12,14,12, 8,11,10,11,12,13,11,14,12,
+       10,13,12,12,12,13,13,15,14,11,12,13,13,14,15,12,
+       14,12, 5, 9, 9, 9,11,12, 8,11,11, 9,11,11,11,12,
+       13,11,13,13, 8,11,10,11,13,13,10,13,11, 8,10,11,
+       11,12,14,11,13,12,11,13,12,12,12,14,13,15,14,10,
+       12,13,13,14,15,12,13,12, 8,11,10,10,12,13,10,13,
+       12,11,12,13,12,12,14,13,14,14,10,13,10,12,14,13,
+       11,14,11,
+};
+
+static const static_codebook _44p6_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p6_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p3_1[] = {
+        5, 7, 7, 6, 7, 7, 6, 7, 7, 6, 7, 7, 7, 8, 8, 7,
+        8, 8, 6, 7, 7, 7, 8, 8, 7, 8, 8, 7, 7, 8, 7, 8,
+        8, 7, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8,
+        8, 9, 9, 8, 9, 8, 7, 8, 7, 7, 8, 8, 7, 8, 8, 8,
+        8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9,
+        8, 6, 8, 8, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 9,
+        8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8, 8,
+        8, 9, 8, 9, 9, 8, 8, 9, 8, 9, 9, 9, 9, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9, 8,
+        8, 8, 8, 8, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9,
+        9, 9, 6, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8,
+        8, 8, 9, 8, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8,
+        8, 8, 9, 9, 9, 8, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9,
+        8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p6_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p6_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p4_0[] = {
+        2, 5, 5, 5, 7, 8, 5, 8, 7, 5, 7, 7, 7, 7, 9, 7,
+        9, 9, 5, 7, 7, 8, 9, 9, 7, 9, 7, 6, 8, 8, 8, 9,
+       10, 8, 9, 9, 8, 9,10, 9, 9,11,10,11,11, 8, 9, 9,
+       10,11,11, 9,11,10, 6, 8, 8, 8, 9, 9, 8,10, 9, 8,
+        9, 9, 9,10,11,10,11,10, 8,10, 9,10,11,11, 9,11,
+        9, 6, 8, 8, 7, 9, 9, 8,10, 9, 7, 9, 9, 9, 9,10,
+        9,10,10, 8, 9, 9, 9,10,10, 9,11,10, 7, 9, 9, 8,
+       10,10, 9,10,10, 9, 9,10,10,10,11,10,11,11, 9,10,
+       10,10,11,11,10,11,10, 7, 9, 9, 9, 9,10, 9,10, 9,
+        8,10, 9, 9, 9,11,10,11,11, 9,10,10,10,11,11, 9,
+       11, 9, 6, 8, 8, 8, 9,10, 7, 9, 9, 8, 9, 9, 9,10,
+       10, 9,10,10, 7, 9, 9, 9,10,10, 9,10, 9, 7, 9, 9,
+        9, 9,10, 9,10, 9, 9,10,10, 9, 9,11,10,11,11, 8,
+        9,10,10,11,11, 9,11, 9, 7, 9, 9, 9,10,10, 8,10,
+       10, 9,10,10,10,10,11,10,11,11, 9,10, 9,10,11,11,
+       10,11,10,
+};
+
+static const static_codebook _44p6_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p6_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p6_p4_1[] = {
+        6, 8, 8,10,10, 8, 9, 9,10,11, 8,10, 9,11,10, 9,
+       10,10,11,11, 9,10,10,11,11, 8, 9, 9,10,10, 9, 9,
+       10,11,11,10,10,10,11,11,10,11,11,11,11,10,11,11,
+       11,11, 8, 9, 9,11,10,10,10,10,11,11, 9,10, 9,11,
+       11,10,11,11,11,11,10,11,10,11,11,10,10,11,11,11,
+       10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+       11,11,11,11,10,11,10,11,11,11,11,11,11,11,10,11,
+       11,11,11,11,11,11,11,11,11,11,11,11,11, 8, 9,10,
+       11,11,10,10,11,11,11,10,10,10,11,11,10,11,11,12,
+       12,10,11,11,12,12,10,10,11,11,11,10,10,11,11,12,
+       11,11,11,12,12,11,11,12,12,12,11,11,12,12,12,10,
+       10,10,11,11,11,11,11,12,12,10,11,11,12,12,11,12,
+       12,12,12,11,12,11,12,12,11,11,11,11,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,11,12,11,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12, 8,10, 9,11,11,10,
+       10,10,11,11,10,11,10,11,11,10,11,11,12,12,10,11,
+       11,12,12,10,10,10,11,11,10,11,11,12,12,11,11,11,
+       12,12,11,11,12,12,12,11,12,12,12,12,10,11,10,11,
+       11,11,11,11,12,12,10,11,10,12,11,11,12,11,12,12,
+       11,12,11,12,12,11,11,11,12,12,11,11,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,
+       11,12,11,11,12,12,12,12,11,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,10,11,11,11,12,11,11,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       11,11,12,12,12,11,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,13,11,12,11,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,13,12,12,12,12,13,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,12,
+       12,12,13,12,10,11,11,12,11,11,11,12,12,12,11,12,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,12,11,12,12,12,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,12,12,12,13,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,13,12,13,12,13,
+       12, 8,10,10,11,11,10,10,11,11,11,10,11,10,11,11,
+       10,11,11,12,12,10,11,11,12,12, 9,10,11,11,11,10,
+       10,11,12,12,10,11,11,12,12,11,11,12,12,12,11,12,
+       12,12,12,10,11,10,11,11,11,11,11,12,12,10,11,11,
+       12,12,11,12,12,12,12,11,12,11,12,12,11,11,11,12,
+       12,11,11,12,12,12,11,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12, 9,10,
+       10,11,11,10,11,11,12,12,10,11,11,12,12,11,11,12,
+       12,12,11,12,12,12,12,10,11,11,12,12,11,11,12,12,
+       12,11,11,12,12,12,11,11,12,12,12,12,12,12,12,12,
+       10,11,11,12,12,11,12,12,12,12,11,12,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12, 9,10,10,11,11,
+       10,11,11,12,12,10,11,11,12,11,11,12,12,12,12,11,
+       12,12,12,12,10,11,11,12,12,11,11,11,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,10,11,11,
+       12,12,11,12,12,12,12,11,12,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,11,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,13,12,12,13,13,13,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,12,12,12,12,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,12,12,12,13,12,13,13,
+       13,13,12,13,13,13,13,13,13,13,13,13,12,12,12,12,
+       12,12,12,13,13,13,12,13,12,13,13,12,13,13,13,13,
+       12,13,13,13,13,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       12,13,12,12,12,13,13,11,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,12,12,13,12,13,13,12,13,12,13,13,
+       12,12,12,12,12,12,12,13,13,13,12,12,13,13,13,12,
+       13,13,12,13,13,13,13,13,13,12,12,12,12,12,12,13,
+       12,13,13,12,13,12,13,12,12,13,13,13,13,12,13,13,
+       13,13, 8,10,10,11,11,10,10,11,11,11, 9,11,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,10,10,11,11,11,
+       10,11,11,12,12,11,11,11,12,12,11,11,12,12,12,11,
+       12,12,12,12, 9,11,10,11,11,10,11,11,12,12,10,11,
+       10,12,12,11,12,12,12,12,11,12,11,12,12,11,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12, 9,
+       10,10,11,11,10,11,11,12,12,10,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,10,11,11,12,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,10,11,11,12,12,11,11,12,12,12,11,11,11,12,12,
+       12,12,12,12,12,11,12,12,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12, 9,10,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,10,11,11,12,12,11,11,12,12,12,11,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,10,11,
+       11,12,12,11,12,11,12,12,11,12,11,12,12,12,12,12,
+       12,12,11,12,11,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,13,12,12,13,13,13,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,12,13,13,12,
+       12,12,13,12,12,12,12,12,12,12,12,13,13,13,12,12,
+       13,13,13,12,13,13,12,13,12,13,13,13,13,12,12,12,
+       12,12,12,12,13,13,13,12,12,12,13,12,12,13,13,13,
+       13,12,13,13,13,13,11,11,11,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,12,
+       13,13,13,12,12,12,13,13,11,12,12,12,12,12,12,12,
+       13,12,12,12,12,13,12,12,13,12,13,13,12,13,12,13,
+       12,12,12,12,12,12,12,12,13,13,13,12,13,13,13,13,
+       12,13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,
+       13,12,13,12,12,13,12,13,12,13,13,13,13,13,12,13,
+       13,13,13,10,11,11,12,12,11,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,11,11,12,12,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,13,13,
+       12,12,12,13,13,11,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,12,
+       12,12,12,12,12,12,12,13,12,12,12,12,13,12,12,13,
+       12,13,12,13,13,13,13,12,12,12,12,12,12,12,12,13,
+       12,12,12,12,13,12,12,13,13,13,13,12,13,12,13,13,
+       11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,13,12,12,12,13,12,11,12,12,12,12,12,12,
+       12,12,13,12,12,12,12,13,12,12,13,13,13,12,12,13,
+       13,13,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       12,12,13,12,13,13,12,13,12,13,13,12,12,12,12,12,
+       12,12,13,12,13,12,12,13,13,13,12,12,13,13,13,13,
+       13,13,13,13,12,12,12,12,12,12,13,13,13,13,12,13,
+       12,13,12,12,13,13,13,13,12,13,13,13,13,11,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,13,11,12,12,12,12,12,12,12,12,13,
+       12,12,12,13,13,12,12,13,13,13,12,12,13,13,13,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,13,
+       12,13,13,12,13,12,13,13,12,12,12,12,12,12,12,12,
+       12,13,12,13,12,13,13,12,13,13,13,13,12,13,13,13,
+       13,12,12,12,12,12,12,13,12,13,13,12,12,12,13,13,
+       12,13,13,13,13,12,13,12,13,13,11,12,12,12,12,11,
+       12,12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,12,13,12,12,12,13,13,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,
+       12,13,12,13,13,12,12,12,12,12,12,12,13,12,13,12,
+       12,13,12,13,12,12,13,12,13,12,13,13,13,13,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,12,12,13,13,
+       13,13,12,13,12,13,12,11,11,11,12,12,11,12,12,12,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,13,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,12,12,13,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,12,12,12,13,12,12,13,12,13,12,12,
+       13,12,13,12,10,11,11,12,12,11,12,12,12,12,11,12,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,13,11,12,11,12,12,12,12,12,12,12,
+       11,12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,
+       12,12,12,12,12,12,12,12,13,12,12,12,12,13,12,13,
+       13,12,13,12,13,13,13,13,12,12,12,12,12,12,12,12,
+       13,13,12,12,12,13,12,12,13,13,13,13,12,13,12,13,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,13,13,12,12,12,13,12,11,12,12,12,12,12,
+       12,12,12,13,12,12,12,13,13,12,12,13,13,13,12,12,
+       13,13,13,11,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,12,12,13,12,13,13,12,12,12,13,13,12,12,12,12,
+       12,12,12,13,13,13,12,12,13,13,13,12,12,13,13,13,
+       12,13,13,13,13,12,12,12,12,12,12,12,13,13,13,12,
+       12,12,13,12,12,13,13,13,13,12,13,13,13,13,11,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,
+       12,13,12,12,12,13,13,11,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,13,12,12,13,13,13,12,12,13,13,13,
+       11,12,12,12,12,12,12,12,13,12,12,12,12,13,12,12,
+       13,12,13,13,12,13,12,13,13,12,12,12,12,12,12,12,
+       12,13,13,12,13,12,13,13,12,13,13,13,13,13,13,13,
+       13,13,12,12,12,12,12,12,13,12,13,13,12,13,12,13,
+       12,12,13,13,13,13,12,13,12,13,13,11,11,11,12,12,
+       11,12,12,12,12,11,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,12,12,12,13,13,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       13,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       12,12,12,12,13,12,12,12,12,13,12,12,13,12,13,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,12,12,12,11,12,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,12,12,12,12,12,12,12,12,13,12,12,12,12,12,
+       12,12,12,13,13,12,12,12,13,13,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,13,13,12,12,
+       12,13,12,12,12,12,12,12,12,12,12,12,13,12,12,12,
+       13,13,12,12,13,12,13,12,13,13,13,13,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,13,12,12,13,12,13,13,
+       12,13,12,13,12,
+};
+
+static const static_codebook _44p6_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p6_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p6_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p6_p5_0[] = {
+        2, 6, 6,10,10, 5, 7, 8,11,12, 5, 8, 7,12,11, 9,
+       11,11,13,15, 9,11,11,15,13, 6, 7, 8,11,11, 7, 7,
+        9,11,13, 8, 9, 9,13,12,11,11,12,12,15,11,12,12,
+       15,14, 6, 8, 7,11,11, 8, 9, 9,12,13, 7, 9, 7,13,
+       11,11,12,12,14,15,11,12,11,15,12,10,11,11,12,14,
+       10,11,12,12,15,12,13,13,14,15,13,12,14,12,16,15,
+       15,15,16,16,10,11,11,14,12,12,13,13,15,14,10,12,
+       11,15,12,15,15,15,16,17,13,14,12,17,12, 6, 8, 8,
+       12,12, 8, 9,10,13,13, 8, 9, 9,13,13,12,12,13,15,
+       16,12,13,13,16,15, 8, 9,10,12,13, 9, 9,11,13,14,
+       10,11,11,14,14,13,13,14,15,16,13,14,14,16,16, 8,
+       10, 9,13,13,10,11,11,14,14, 9,10,10,14,13,13,14,
+       14,16,17,13,13,13,16,15,12,13,13,14,16,13,13,14,
+       14,16,14,14,14,16,16,15,15,16,15,18,16,17,17,18,
+       18,12,13,13,15,15,14,14,14,16,16,13,14,13,16,15,
+       16,16,17,18,18,15,16,15,18,15, 6, 8, 8,12,12, 8,
+        9, 9,13,13, 8,10, 9,13,13,12,13,13,15,16,12,13,
+       12,16,15, 8, 9,10,13,13, 9,10,10,13,14,10,11,11,
+       14,14,13,13,13,15,16,13,14,14,17,16, 8,10, 9,13,
+       13,10,11,11,14,14, 9,11, 9,14,13,13,14,14,16,16,
+       13,14,13,16,14,12,13,13,15,16,13,13,14,15,16,14,
+       14,14,16,16,15,15,16,15,18,17,17,17,18,18,12,13,
+       13,16,14,14,14,14,16,16,13,14,13,16,14,16,17,17,
+       18,18,15,16,15,18,15,11,12,13,14,16,13,13,14,15,
+       17,13,14,14,16,17,16,16,17,17,19,16,17,17,18,19,
+       13,13,14,16,16,14,14,15,16,17,14,15,15,17,17,17,
+       16,17,17,19,17,17,18,19,19,13,14,14,16,16,14,14,
+       15,17,18,14,15,14,17,17,17,17,18,18,19,17,17,17,
+       18,19,16,16,16,17,18,17,17,17,18,19,17,17,17,18,
+       19,18,18,19,18,20,19,20,19,21,20,16,17,17,18,18,
+       17,17,18,19,19,17,17,17,19,18,19,19,19,19,20,19,
+       19,19,20,19,11,13,12,16,14,13,14,14,17,16,13,14,
+       13,17,15,16,17,17,18,18,16,17,16,19,17,13,14,14,
+       16,16,14,14,14,17,17,14,15,15,17,16,17,17,17,19,
+       19,17,18,17,19,18,13,14,13,17,16,14,15,15,17,17,
+       14,15,14,18,16,17,17,17,19,19,17,17,16,19,17,16,
+       17,17,18,19,17,17,17,18,18,17,18,17,19,18,18,19,
+       18,19,19,19,20,19,20,20,16,17,16,18,17,17,17,17,
+       18,18,17,18,17,19,17,19,19,19,19,20,18,19,19,20,
+       18, 6, 8, 8,12,12, 8, 9, 9,13,13, 8,10, 9,13,13,
+       11,13,13,15,16,12,13,13,16,15, 8, 9, 9,13,13, 9,
+        9,10,13,14,10,11,11,14,14,12,12,13,14,16,13,14,
+       14,17,16, 8,10, 9,13,13,10,11,11,14,14, 9,11,10,
+       14,13,13,14,14,16,16,13,14,13,16,15,12,13,13,14,
+       16,12,13,14,14,16,13,14,14,16,16,15,14,16,15,18,
+       16,17,17,18,17,12,13,13,16,15,14,14,14,16,16,13,
+       14,13,16,15,16,16,17,17,17,15,16,15,18,15, 7, 9,
+        9,13,13, 9, 9,11,13,14, 9,10,10,14,13,12,13,14,
+       15,16,12,14,13,17,15, 9, 9,10,13,14,10, 9,11,13,
+       15,11,11,11,14,14,13,12,14,14,17,14,14,14,17,16,
+        9,10,10,14,13,11,11,11,14,14,10,11,10,15,13,14,
+       14,14,16,17,13,14,13,17,14,13,13,14,14,16,13,13,
+       14,14,17,14,14,14,16,16,15,14,16,15,18,17,17,17,
+       18,18,13,14,13,16,15,14,14,15,17,16,13,14,13,17,
+       15,17,16,17,17,17,15,16,14,18,14, 7, 9, 9,13,13,
+        9,10,10,13,14, 9,11,10,14,13,13,14,14,16,16,13,
+       14,14,17,15, 9,10,10,14,13, 9,10,11,13,14,11,12,
+       11,15,14,13,13,14,14,16,14,15,15,17,17, 9,10,10,
+       14,14,11,12,12,14,15,10,11,10,15,13,14,15,15,17,
+       17,14,15,13,17,14,13,14,13,16,16,13,13,14,15,16,
+       14,15,15,17,17,15,14,16,15,18,17,18,17,20,18,13,
+       14,14,16,16,15,15,15,17,17,13,14,13,17,15,17,17,
+       18,18,18,15,16,14,19,14,12,13,13,15,16,13,13,15,
+       16,17,13,14,14,16,16,15,15,17,17,19,16,17,17,19,
+       18,13,13,14,15,17,14,13,15,15,17,14,15,15,16,17,
+       16,15,18,16,19,17,17,17,18,19,13,14,14,17,16,14,
+       15,15,17,17,14,15,14,17,16,17,17,17,18,19,16,17,
+       16,19,17,16,16,17,16,18,16,16,17,16,19,17,17,18,
+       18,19,18,17,18,17,21,19,19,19,20,19,16,17,17,18,
+       18,17,17,18,18,19,16,17,16,18,18,19,19,19,19,20,
+       18,18,17,20,18,11,13,13,16,15,13,14,14,16,17,13,
+       15,14,17,16,16,17,17,18,18,17,17,17,19,18,13,14,
+       13,17,16,14,13,14,16,17,15,16,15,18,16,17,16,17,
+       17,19,18,18,18,20,18,13,14,14,16,17,15,15,15,17,
+       18,14,15,14,18,16,18,18,18,19,20,17,18,16,20,17,
+       16,17,16,18,18,16,16,17,18,18,17,18,18,19,18,18,
+       17,19,17,20,19,20,19,22,20,16,16,17,18,18,18,17,
+       17,19,19,16,17,16,18,17,19,20,19,22,21,18,19,18,
+       21,17, 6, 8, 8,12,12, 8, 9,10,13,13, 8, 9, 9,13,
+       13,12,13,13,15,16,11,13,13,16,15, 8, 9,10,13,13,
+        9,10,11,13,14,10,11,11,14,14,13,13,14,15,16,13,
+       14,14,16,16, 8, 9, 9,13,13,10,11,11,14,14, 9,10,
+        9,14,13,13,14,14,16,17,12,14,12,16,14,12,13,13,
+       15,16,13,13,14,15,16,13,14,14,15,17,15,15,16,15,
+       18,16,16,17,17,17,12,13,13,16,14,13,14,14,16,16,
+       12,14,13,16,14,16,17,17,18,18,15,15,14,18,14, 7,
+        9, 9,13,13, 9,10,11,13,14, 9,10,10,14,13,13,14,
+       14,15,17,13,14,14,16,15, 9,10,10,14,14,10,10,11,
+       13,15,11,12,12,15,14,14,13,15,14,17,14,15,15,17,
+       17, 9,10,10,13,14,11,11,12,14,15, 9,11,10,14,13,
+       14,15,15,16,18,13,14,13,16,14,13,14,14,16,16,13,
+       13,14,15,17,15,15,15,16,17,15,14,16,15,18,17,17,
+       18,19,18,13,14,14,16,16,14,15,15,17,17,13,14,13,
+       16,15,17,17,18,18,18,15,16,14,18,15, 7, 9, 9,13,
+       13, 9,10,10,13,14, 9,11,10,14,13,12,13,14,15,16,
+       12,14,13,16,15, 9,10,10,13,14,10,10,11,13,14,11,
+       11,11,15,14,13,13,14,14,16,14,14,14,17,16, 9,10,
+        9,14,13,11,11,11,14,14,10,11, 9,15,13,14,14,14,
+       16,16,13,14,12,17,14,13,13,14,15,16,13,13,14,15,
+       16,14,15,14,16,17,15,14,16,14,18,16,17,17,18,18,
+       13,14,13,16,14,14,14,14,16,16,13,14,13,17,14,17,
+       17,17,18,18,15,16,14,18,15,11,13,13,16,16,13,14,
+       15,16,17,13,14,14,17,16,16,17,17,18,19,17,17,17,
+       19,18,13,14,14,17,17,13,13,15,16,18,15,15,15,17,
+       17,17,16,18,17,20,18,17,18,19,19,13,14,14,16,17,
+       15,15,16,16,18,14,15,14,16,16,17,17,18,18,20,17,
+       18,16,18,17,16,17,16,19,18,16,16,17,18,19,18,18,
+       18,19,19,18,17,18,17,21,20,19,19,21,21,16,16,17,
+       18,18,17,17,18,19,19,16,17,16,19,18,20,20,20,19,
+       21,18,18,17,20,18,12,13,13,16,15,13,14,14,16,16,
+       13,14,13,17,16,16,17,17,18,18,15,17,15,19,17,13,
+       14,14,16,17,14,14,15,16,17,14,15,15,17,17,16,16,
+       17,17,18,17,17,17,19,19,13,14,13,17,15,14,15,15,
+       17,16,14,15,13,17,15,17,18,17,19,18,16,17,15,20,
+       16,16,17,17,18,18,16,16,17,18,18,17,18,17,19,18,
+       17,17,18,18,20,19,20,19,20,19,16,16,16,19,16,17,
+       17,17,19,18,16,17,16,19,16,19,19,19,19,19,18,19,
+       17,19,17,11,13,13,16,16,13,14,14,17,17,13,14,14,
+       17,17,15,17,17,19,19,16,18,17,20,19,12,14,14,17,
+       17,13,14,15,17,18,14,15,15,17,18,16,16,17,18,20,
+       17,18,18,20,18,13,14,14,17,17,14,15,15,17,18,14,
+       15,15,17,17,17,18,17,19,19,17,18,17,19,19,15,16,
+       16,18,18,15,16,17,18,19,16,17,17,19,19,17,17,18,
+       18,21,18,19,19,21,19,16,17,17,18,18,17,17,18,19,
+       19,17,18,17,19,19,19,19,19,20,20,18,19,18,21,19,
+       12,13,13,16,16,13,14,14,16,17,13,15,14,17,16,15,
+       16,17,17,19,16,17,17,19,18,13,13,14,16,17,14,13,
+       15,16,17,14,15,15,17,17,15,15,17,17,20,17,17,18,
+       19,18,13,14,14,17,16,15,15,15,17,18,14,15,14,17,
+       16,17,17,17,18,18,16,17,16,19,17,16,15,17,17,19,
+       16,15,17,16,19,17,16,17,18,19,17,16,19,16,20,19,
+       18,19,19,19,16,17,17,18,18,17,17,17,18,19,16,17,
+       16,19,18,20,19,19,20,19,18,18,17,20,17,11,13,13,
+       16,16,13,14,15,16,17,14,15,14,18,16,17,17,17,18,
+       21,17,18,17,20,19,13,14,14,17,16,13,14,15,16,18,
+       15,16,15,18,17,17,16,17,17,19,17,18,18,20,19,13,
+       14,14,16,17,15,15,16,17,18,14,15,14,18,17,17,18,
+       18,19,20,17,18,16,19,17,16,17,15,19,18,16,16,16,
+       18,18,17,18,17,20,19,18,17,18,17,20,20,20,19,22,
+       20,16,17,17,18,19,18,18,18,19,20,16,17,16,19,18,
+       20,19,19,20,20,18,19,17,20,17,13,14,14,16,17,14,
+       14,16,16,18,14,16,15,17,16,16,16,17,17,18,17,17,
+       16,19,18,14,14,15,16,17,14,14,16,16,18,16,16,16,
+       17,17,16,15,17,16,19,18,18,18,19,19,14,15,15,17,
+       17,15,16,16,17,18,14,16,14,18,16,17,17,18,18,19,
+       16,17,16,19,17,16,16,17,16,18,16,16,17,16,19,18,
+       18,18,17,18,17,16,18,16,20,19,19,19,19,19,16,17,
+       17,18,18,17,17,18,19,19,16,17,16,19,17,18,19,19,
+       19,20,17,18,16,20,16,11,14,13,17,17,14,14,16,16,
+       18,14,16,14,19,16,18,18,19,18,19,18,19,18,21,18,
+       13,15,14,18,16,14,14,16,16,18,16,17,16,19,17,18,
+       16,19,17,20,19,19,19,21,19,13,14,15,17,18,17,16,
+       17,17,19,14,16,14,18,16,20,19,19,20,21,18,19,16,
+       21,17,17,18,16,19,17,16,16,17,18,18,19,19,18,21,
+       18,17,17,18,17,20,20,20,20,22,20,17,17,18,18,20,
+       19,19,19,18,20,16,17,17,19,19,21,21,21,20,21,17,
+       19,17,23,17,11,13,13,16,16,13,14,14,17,17,13,14,
+       14,17,17,16,17,17,19,20,15,16,16,19,19,13,14,14,
+       16,17,14,15,15,17,18,14,15,15,17,17,17,17,18,19,
+       19,17,17,18,19,19,13,14,14,17,16,14,15,15,17,17,
+       13,15,14,18,17,17,18,18,19,20,16,17,16,19,18,16,
+       16,17,18,18,17,17,17,18,19,17,18,17,19,19,19,19,
+       19,19,20,19,20,19,20,20,15,16,16,18,17,16,17,17,
+       20,18,15,16,16,19,17,19,19,19,20,20,17,18,17,21,
+       17,11,13,13,16,16,13,14,15,16,17,13,15,14,17,16,
+       17,17,18,18,20,17,17,17,19,19,13,14,14,17,17,14,
+       14,15,17,18,15,15,15,18,17,17,17,18,17,20,18,18,
+       17,20,18,13,14,14,16,17,15,15,16,17,18,14,15,13,
+       17,17,17,18,18,19,20,17,17,16,19,17,16,17,17,18,
+       18,16,16,17,18,18,18,18,18,19,19,18,17,19,18,21,
+       19,20,20,20,20,16,15,17,18,18,17,17,18,18,20,16,
+       16,16,18,17,20,19,20,21,22,17,18,17,20,17,12,13,
+       13,16,16,13,14,15,16,17,13,14,14,17,16,16,17,18,
+       18,19,15,16,16,19,18,13,14,14,16,17,14,14,15,16,
+       17,14,15,15,17,17,16,16,17,17,19,17,17,17,19,18,
+       13,14,13,17,16,14,15,15,17,17,13,15,13,17,16,17,
+       17,17,19,19,15,17,15,19,17,16,17,17,18,18,16,16,
+       17,17,19,17,18,17,19,19,18,17,19,17,19,19,19,19,
+       20,19,15,17,15,19,16,17,17,16,19,18,16,17,15,18,
+       16,19,19,19,20,19,17,19,16,19,16,11,14,14,17,17,
+       15,14,16,16,18,15,16,14,18,16,18,18,19,18,21,18,
+       19,18,20,18,13,15,14,18,17,14,14,16,16,18,16,17,
+       16,19,17,17,17,19,17,22,19,19,19,21,19,13,14,15,
+       17,18,17,16,17,17,19,14,16,14,18,16,19,19,19,20,
+       21,18,18,16,20,17,17,18,16,19,18,15,17,17,19,19,
+       19,19,18,21,19,18,17,20,17,21,22,21,20,21,21,17,
+       16,19,18,20,19,18,19,18,20,16,17,16,19,18,21,20,
+       21,19,23,18,19,16,20,17,13,14,14,17,16,14,14,15,
+       16,18,14,16,14,17,16,16,16,17,17,19,16,17,16,19,
+       17,14,15,15,17,17,14,14,16,16,17,15,16,16,18,17,
+       16,16,17,17,19,17,18,17,19,18,14,15,14,17,16,16,
+       16,16,17,17,14,16,14,17,16,18,18,18,18,19,16,17,
+       15,19,16,17,17,17,18,18,16,15,17,17,18,18,18,18,
+       19,19,17,16,18,16,19,19,19,19,19,19,16,17,16,19,
+       16,18,18,17,19,18,16,17,16,19,16,19,19,20,19,19,
+       17,18,16,20,16,
+};
+
+static const static_codebook _44p6_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p6_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p6_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p6_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p6_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p6_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p6_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p6_0[] = {
+        1, 5, 5, 5, 7, 9, 5, 9, 7, 5, 7, 8, 7, 7,10, 9,
+       10,10, 5, 8, 7, 9,10,10, 7,10, 7, 6, 9, 9, 9,10,
+       12, 9,11,11, 9,10,11,11,11,13,12,13,13, 9,11,11,
+       12,13,13,11,13,11, 6, 9, 9, 9,11,11, 9,12,10, 9,
+       11,11,11,11,13,12,13,13, 9,11,10,12,13,13,11,13,
+       11, 6, 9, 9, 9,11,12, 9,12,11, 9,10,11,10,10,13,
+       12,13,13, 9,11,11,12,13,12,11,13,11, 7, 9,10, 9,
+       10,12,10,12,11,10,10,12,10,10,12,12,12,13,10,11,
+       11,12,12,13,10,12,10, 7,10,10,11,11,14,11,14,11,
+       10,12,11,11,11,14,14,14,14,10,11,12,14,14,14,11,
+       14,11, 6, 9, 9, 9,11,12, 9,12,11, 9,11,11,11,11,
+       13,12,12,13, 9,11,10,12,13,13,10,13,10, 7,10,10,
+       11,11,14,11,14,11,10,12,11,11,11,14,14,15,14,10,
+       11,12,13,14,15,11,14,11, 7,10, 9,10,11,12, 9,12,
+       10,10,11,11,10,10,12,12,13,12, 9,12,10,12,13,12,
+       10,12,10,
+};
+
+static const static_codebook _44p6_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p6_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p6_1[] = {
+        2, 6, 6, 6, 7, 8, 6, 8, 7, 6, 7, 7, 7, 7, 8, 7,
+        8, 8, 6, 7, 7, 7, 8, 8, 7, 8, 7, 6, 8, 8, 8, 9,
+        9, 8, 9, 9, 8, 9, 9, 9, 9,10, 9,10,10, 8, 9, 9,
+        9,10,10, 9,10, 9, 6, 8, 8, 8, 9, 9, 8, 9, 9, 8,
+        9, 9, 9, 9,10, 9,10,10, 8, 9, 9, 9,10, 9, 9,10,
+        9, 6, 8, 8, 8, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9,10,
+        9, 9,10, 8, 9, 9, 9,10, 9, 9,10, 9, 7, 8, 8, 8,
+        9, 9, 8, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8, 9,
+        9, 9,10, 9, 9, 9, 9, 7, 9, 9, 9, 9,10, 9,10, 9,
+        9, 9, 9, 9, 9,10,10,10,10, 9, 9, 9,10,10,10, 9,
+       10, 9, 6, 8, 8, 8, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9,
+       10, 9,10,10, 8, 9, 9, 9,10, 9, 9,10, 9, 7, 9, 9,
+        9, 9,10, 9,10, 9, 9, 9, 9, 9, 9,10,10,10,10, 9,
+        9, 9,10,10,10, 9,10, 9, 7, 8, 8, 8, 9, 9, 8, 9,
+        9, 8, 9, 9, 9, 9,10, 9, 9,10, 8, 9, 8, 9, 9, 9,
+        9,10, 9,
+};
+
+static const static_codebook _44p6_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p6_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p6_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p6_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p6_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p6_p7_1[] = {
+        1, 4, 5, 5,10,10, 5,10,10, 5,10,10,10,10,10,10,
+       10,10, 5,10,10,10,10,10,10,10,10, 7,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10, 6,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10, 6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10, 6,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
+       11,11,11,
+};
+
+static const static_codebook _44p6_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p6_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p6_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p6_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p6_p7_2[] = {
+        1, 2, 3, 4, 5, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p6_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p6_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p6_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p6_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p6_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p6_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p6_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p6_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p6_short[] = {
+        2, 8,13,15,16,18,21,22, 5, 4, 6, 8,10,12,17,21,
+        9, 5, 5, 6, 8,11,15,19,11, 6, 5, 5, 6, 7,12,14,
+       14, 8, 7, 5, 4, 4, 9,11,16,11, 9, 7, 4, 3, 7,10,
+       22,15,14,12, 8, 7, 9,11,21,16,15,12, 9, 5, 6, 8,
+};
+
+static const static_codebook _huff_book__44p6_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p6_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p7_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p7_l0_0[] = {
+        2, 4, 4, 7, 7, 8, 8,10,10,11,11,12,12, 4, 5, 5,
+        7, 7, 9, 9,11, 9,12,11,12,12, 4, 5, 5, 7, 7, 9,
+        9, 9,10,10,11,12,12, 7, 7, 7, 7, 8, 9, 8,11, 5,
+       12, 6,12,10, 7, 7, 7, 8, 7, 8, 9, 5,11, 6,12,10,
+       12, 8, 9, 9, 9, 9,10,10,11, 7,11, 7,12, 9, 8, 9,
+        8, 9, 9,10,10, 7,11, 7,11, 9,11,10,10,10,10,10,
+       10,10,11,10,11, 8,11, 9,10,10,10,10,10,10,10,10,
+       11, 8,10, 9,11,10,11,11,11,11,11,10,11,10,12,10,
+       12,11,10,11,11,11,11,10,11,10,11,10,12,11,12,11,
+       12,12,12,12,12,12,12,12,12,12,13,12,11,12,11,12,
+       12,12,12,12,11,12,11,12,13,
+};
+
+static const static_codebook _44p7_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p7_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p7_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p7_l0_1[] = {
+        4, 4, 4, 5, 5, 4, 4, 5, 5, 5, 4, 5, 4, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p7_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p7_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p7_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_l1_0[] = {
+       54,
+       29,
+       79,
+       0,
+       108,
+};
+
+static const char _vq_lengthlist__44p7_l1_0[] = {
+        1, 2, 3, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44p7_l1_0 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p7_l1_0,
+       1, -514516992, 1620639744, 7, 0,
+       (long *)_vq_quantlist__44p7_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p7_lfe[] = {
+        2, 3, 1, 3,
+};
+
+static const static_codebook _huff_book__44p7_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p7_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p7_long[] = {
+        2, 7,14,16,17,17,18,20, 6, 3, 5, 8,10,11,13,15,
+       13, 5, 3, 5, 8, 9,11,12,15, 7, 4, 3, 5, 7, 9,11,
+       16,10, 7, 5, 6, 7, 9,10,17,11, 8, 7, 7, 6, 8, 8,
+       19,13,11, 9, 9, 8, 8, 9,20,14,13,11,10, 8, 9, 9,
+};
+
+static const static_codebook _huff_book__44p7_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p7_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p7_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p1_0[] = {
+        2, 5, 5, 4, 7, 7, 4, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 6, 7, 8, 8, 9,
+       10, 8, 9,10, 8, 9,10,10,10,12,10,11,11, 8,10,10,
+       10,11,12,10,11,11, 6, 8, 7, 8,10, 9, 8,10, 9, 8,
+       10,10,10,11,11,10,12,11, 8,10, 9,10,11,11,10,12,
+       10, 5, 8, 8, 8,10,10, 8,10,10, 7, 9,10, 9,10,11,
+        9,11,11, 8,10,10,10,11,12,10,12,11, 7, 9, 9, 9,
+       10,11, 9,11,11, 9, 9,11,10,11,12,11,11,12, 9,11,
+       11,11,12,12,11,12,12, 7, 9, 9,10,11,11,10,12,11,
+        9,11,10,11,11,12,11,13,12,10,11,11,12,13,13,11,
+       13,11, 5, 8, 8, 8,10,10, 8,10,10, 8,10,10,10,11,
+       12,10,12,11, 7,10, 9, 9,11,11, 9,11,10, 7, 9, 9,
+       10,11,12,10,11,11,10,11,11,11,11,13,12,13,13, 9,
+       10,11,11,12,13,11,12,11, 7, 9, 9, 9,11,11, 9,11,
+       10, 9,11,11,11,12,12,11,12,12, 9,11, 9,11,12,11,
+       10,12,11,
+};
+
+static const static_codebook _44p7_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p7_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p7_p2_0[] = {
+        4, 6, 6, 9, 9, 6, 8, 8,10,10, 6, 8, 8,10,10, 8,
+       10,10,12,13, 8,10,10,13,12, 6, 8, 8,10,10, 8, 8,
+        9,10,11, 8, 9, 9,11,11,10,10,11,12,13,10,11,11,
+       13,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 8, 9, 8,11,
+       10,10,11,11,13,13,10,11,10,13,12, 9,10,10,12,12,
+       10,10,11,12,13,10,11,11,13,13,12,12,13,12,15,13,
+       13,13,15,14, 9,10,10,12,12,10,11,11,13,13,10,11,
+       10,13,12,12,13,13,14,15,12,13,12,15,12, 6, 8, 8,
+       10,11, 8, 9,10,11,12, 8, 9, 9,11,11,10,11,12,13,
+       14,10,11,11,13,13, 8, 9, 9,11,12, 9,10,11,12,13,
+        9,10,10,12,13,11,12,13,13,15,11,12,12,14,14, 8,
+        9, 9,11,12, 9,10,11,12,13, 9,10,10,13,12,11,12,
+       13,14,15,11,12,12,14,13,10,11,12,13,14,11,12,13,
+       13,15,12,13,13,14,14,13,13,14,14,16,14,15,14,16,
+       15,10,12,11,14,13,12,12,13,14,14,11,12,12,14,14,
+       14,14,15,15,16,13,14,14,16,14, 6, 8, 8,11,10, 8,
+        9, 9,11,11, 8,10, 9,12,11,10,11,11,13,13,10,12,
+       11,14,13, 8, 9, 9,12,11, 9,10,10,12,13, 9,11,10,
+       13,12,11,12,12,14,14,11,13,12,15,14, 8, 9, 9,12,
+       11, 9,10,10,13,12, 9,11,10,13,12,11,12,12,14,14,
+       11,13,12,15,13,10,11,12,13,14,11,12,13,13,14,12,
+       13,12,14,14,13,13,14,14,16,14,15,14,16,16,10,12,
+       11,14,13,12,13,13,14,14,11,13,12,15,13,14,14,15,
+       16,16,13,14,13,16,14, 9,10,11,12,13,11,11,12,13,
+       14,11,11,12,13,14,13,13,14,14,16,13,14,14,15,15,
+       11,11,12,13,14,12,12,13,13,15,12,13,13,14,15,14,
+       14,15,15,17,14,14,15,16,16,11,12,12,13,14,12,12,
+       13,14,15,12,13,12,14,15,14,14,15,15,17,14,15,14,
+       16,16,13,14,14,15,16,14,14,15,15,17,14,15,15,16,
+       16,15,16,17,16,18,16,17,16,17,17,13,14,14,16,15,
+       14,15,15,16,16,14,15,14,16,15,16,16,17,17,18,16,
+       16,16,17,16, 9,11,10,13,12,11,12,11,14,13,11,12,
+       11,14,13,13,14,14,16,15,13,14,13,16,14,11,12,12,
+       14,13,12,12,13,14,14,12,13,13,15,14,14,14,15,16,
+       16,14,15,14,17,15,11,12,11,14,13,12,13,13,15,14,
+       12,13,12,15,13,14,15,14,16,16,14,15,14,17,15,13,
+       14,14,15,16,14,14,15,16,16,14,15,15,16,16,15,16,
+       16,16,17,16,16,16,17,17,13,14,14,16,15,14,15,15,
+       17,16,14,15,14,17,15,16,17,17,17,17,16,16,16,18,
+       16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,11,
+       10,11,11,13,14,10,11,11,14,13, 8, 9, 9,11,12, 9,
+       10,10,12,13, 9,10,10,13,12,11,11,12,13,15,11,12,
+       12,15,14, 8, 9, 9,12,11, 9,10,11,12,13, 9,11,10,
+       13,12,11,12,12,14,15,11,13,12,15,14,10,11,11,13,
+       14,11,12,12,13,14,11,12,12,14,14,13,13,14,14,16,
+       13,14,14,16,15,11,12,11,14,13,12,13,13,14,14,11,
+       13,12,14,13,14,14,15,16,16,13,14,14,16,14, 8, 9,
+        9,11,12, 9,10,10,12,13, 9,10,10,13,12,11,12,12,
+       14,15,11,12,12,14,14, 9, 9,10,11,13,10,10,12,12,
+       14,10,10,11,13,13,12,12,13,14,16,12,12,13,15,15,
+        9,10,10,13,12,10,11,11,13,14,10,12,11,14,13,12,
+       13,13,15,15,12,13,13,15,15,11,11,12,13,15,12,12,
+       13,13,15,12,13,13,14,15,14,14,15,15,17,14,15,15,
+       16,16,11,13,12,15,14,13,13,13,15,15,12,14,13,15,
+       14,15,15,15,16,16,14,15,15,17,15, 7, 9, 9,12,11,
+        9,10,10,12,12, 9,11,10,13,12,11,12,12,14,14,11,
+       13,12,15,14, 9,10,10,12,12,10,10,11,12,13,10,11,
+       11,14,13,12,12,13,14,15,12,13,13,15,14, 9,10,10,
+       12,12,10,11,11,13,13,10,11,10,14,12,12,13,13,15,
+       15,12,13,12,15,13,11,12,12,14,14,12,12,13,14,15,
+       12,13,13,15,15,14,13,14,13,16,14,15,15,16,16,11,
+       12,12,14,14,13,13,14,15,15,12,13,12,15,14,15,15,
+       15,16,16,14,15,14,17,14,10,11,12,13,14,11,12,13,
+       14,15,11,12,12,14,15,13,14,15,15,17,14,14,14,16,
+       16,11,12,13,12,15,12,12,14,13,16,13,13,14,13,16,
+       14,14,15,14,17,15,15,15,15,17,11,13,12,15,15,13,
+       13,14,15,16,12,14,13,16,15,15,15,15,17,17,15,15,
+       15,17,16,14,14,15,14,16,14,14,16,14,17,15,15,15,
+       14,17,16,16,17,15,18,17,17,17,16,18,14,15,15,17,
+       16,15,16,16,17,17,15,16,15,17,16,17,17,17,18,18,
+       16,17,16,18,17,10,11,11,14,13,11,12,12,14,14,11,
+       13,12,15,14,14,14,14,16,16,14,15,14,16,15,11,12,
+       12,15,13,12,13,13,15,14,13,14,13,16,14,14,15,15,
+       16,16,15,16,15,17,16,11,13,12,15,14,13,13,14,15,
+       15,12,14,13,16,14,15,15,15,17,17,14,16,15,17,16,
+       14,14,14,16,15,14,15,15,16,16,15,16,15,17,16,16,
+       16,16,16,17,16,17,17,18,17,14,15,15,16,16,15,15,
+       16,17,16,14,15,15,17,16,17,17,17,18,18,16,17,16,
+       18,16, 6, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,
+       11,10,11,12,13,14,10,11,11,14,13, 8, 9, 9,11,12,
+        9,10,11,12,13, 9,11,10,13,12,11,12,13,14,15,11,
+       12,12,15,14, 8, 9, 9,12,11, 9,10,10,12,13, 9,10,
+       10,13,12,11,12,12,14,15,11,12,12,14,13,11,11,12,
+       13,14,11,12,13,13,15,12,13,13,14,14,13,14,14,14,
+       16,14,15,14,16,16,10,11,11,14,13,11,12,12,14,14,
+       11,12,12,14,13,13,14,14,15,16,13,14,13,16,14, 7,
+        9, 9,11,11, 9,10,11,12,13, 9,10,10,12,12,11,12,
+       13,14,15,11,12,12,14,14, 9,10,10,12,12,10,10,11,
+       12,13,10,11,11,13,13,12,12,13,13,15,12,13,13,15,
+       15, 9,10,10,12,12,10,11,11,13,13,10,11,10,13,12,
+       12,13,13,14,15,12,13,12,15,13,11,12,12,14,14,12,
+       12,13,14,15,13,14,13,15,15,14,13,15,13,16,15,15,
+       15,16,16,11,12,12,14,14,12,13,13,14,15,12,13,12,
+       15,14,14,15,15,16,17,13,14,13,16,13, 8, 9, 9,12,
+       11, 9,10,10,12,13, 9,10,10,13,12,11,12,12,14,15,
+       11,12,12,15,14, 9,10,10,12,13,10,11,12,13,14,10,
+       11,11,14,13,12,13,13,15,15,12,13,13,15,15, 9,10,
+        9,13,11,10,11,10,13,13,10,12,10,14,12,12,13,12,
+       15,15,12,13,12,15,14,11,12,13,14,15,12,13,14,14,
+       15,13,13,13,15,15,14,15,15,15,17,15,15,15,16,16,
+       11,12,11,15,13,12,13,13,15,14,12,13,12,16,13,14,
+       15,15,16,16,14,15,14,17,14,10,11,11,13,14,11,12,
+       13,14,15,11,12,12,14,14,14,14,15,15,17,14,14,14,
+       15,16,11,12,13,14,15,12,13,14,14,16,13,14,13,15,
+       15,14,15,16,15,17,15,15,15,17,17,11,12,12,13,15,
+       13,13,14,14,16,12,13,13,14,15,15,15,15,16,17,14,
+       15,15,16,16,14,15,15,16,16,14,15,15,16,17,15,15,
+       16,16,17,16,16,17,16,18,17,17,17,18,18,14,14,15,
+       15,16,15,15,15,16,17,14,15,15,16,16,16,17,17,17,
+       18,16,16,16,17,16,10,11,11,14,13,11,13,12,15,14,
+       11,13,12,15,14,14,15,14,16,16,13,15,14,17,15,11,
+       12,13,15,15,12,13,14,15,16,13,14,13,16,15,15,15,
+       15,16,17,15,15,15,17,16,11,13,11,15,12,13,14,13,
+       16,13,12,14,12,16,13,15,15,15,17,15,14,16,14,17,
+       14,14,15,15,16,17,15,15,16,16,17,15,16,15,17,17,
+       16,16,17,17,18,16,17,17,18,18,14,15,14,17,13,15,
+       16,15,17,15,15,16,15,17,14,16,17,16,18,16,16,17,
+       16,18,15, 9,11,11,13,13,10,12,12,14,14,11,12,12,
+       14,14,13,14,14,15,16,13,14,14,16,16,10,11,12,14,
+       14,11,12,13,14,15,11,13,13,15,15,13,14,14,15,16,
+       14,15,15,16,16,11,12,12,14,14,12,13,13,15,15,12,
+       13,12,15,14,14,15,15,16,16,14,15,14,17,16,12,13,
+       13,15,16,13,13,14,15,16,13,14,14,16,16,14,15,16,
+       16,17,15,16,16,17,17,13,14,14,16,15,14,15,15,17,
+       16,14,15,14,17,15,16,16,17,17,17,16,16,16,18,16,
+       10,11,12,14,14,11,12,13,14,15,11,13,12,15,15,13,
+       14,15,16,16,14,15,15,17,16,11,11,13,14,15,12,12,
+       14,14,16,12,13,14,15,15,14,14,15,16,17,15,15,15,
+       17,17,12,13,12,15,15,13,14,14,16,15,13,14,13,16,
+       15,15,16,15,17,17,15,16,15,17,16,13,12,15,14,16,
+       14,13,15,14,17,14,13,15,15,17,15,14,17,15,18,16,
+       15,17,17,18,14,15,15,17,16,15,16,16,17,17,15,16,
+       15,17,16,16,17,17,18,18,16,17,16,18,17,10,11,11,
+       14,14,11,12,12,14,15,11,13,12,15,14,13,14,14,16,
+       16,14,15,14,16,16,11,12,12,14,14,12,12,13,15,15,
+       12,13,13,15,15,14,14,15,16,16,14,15,15,17,16,11,
+       12,12,15,15,13,13,13,15,15,12,13,13,15,15,15,15,
+       15,17,17,14,15,15,17,16,13,14,13,16,15,14,14,14,
+       16,16,14,15,14,17,16,15,15,16,16,17,16,17,16,18,
+       17,14,15,15,16,16,15,15,15,17,17,14,15,15,17,16,
+       16,17,17,18,18,16,17,16,18,16,12,13,13,15,15,13,
+       14,14,16,16,13,14,14,16,16,14,15,16,16,18,15,16,
+       16,17,17,13,13,14,14,16,14,14,15,15,17,14,14,15,
+       15,17,15,15,17,15,18,16,16,17,17,18,13,14,14,16,
+       16,14,15,15,16,17,14,15,15,17,16,16,17,16,17,18,
+       16,17,16,18,17,15,14,16,13,18,16,15,17,14,18,16,
+       15,17,14,18,17,16,18,15,19,17,17,18,16,19,15,16,
+       16,17,17,16,17,17,18,18,16,17,16,18,17,18,18,18,
+       19,18,17,18,17,19,17,11,12,12,15,15,13,13,14,15,
+       16,13,14,13,16,15,15,15,15,16,17,15,16,15,17,16,
+       12,13,13,15,15,13,13,14,15,16,14,15,14,16,15,15,
+       15,16,16,17,16,16,16,18,17,12,13,13,15,15,14,14,
+       15,16,16,13,14,13,16,15,16,16,16,17,17,15,16,15,
+       18,16,15,15,15,17,15,14,15,15,16,16,16,17,16,17,
+       16,16,16,17,16,17,17,18,17,19,18,15,15,16,17,17,
+       16,16,16,17,17,15,16,15,17,16,17,18,18,18,18,16,
+       17,16,18,16, 9,11,11,13,13,11,12,12,14,14,10,12,
+       12,14,14,13,14,14,15,16,13,14,14,16,15,11,12,12,
+       14,14,12,12,13,14,15,12,13,13,15,15,14,14,15,16,
+       17,14,15,15,16,16,10,12,11,14,14,11,13,13,15,15,
+       11,13,12,15,14,14,14,15,16,16,13,14,14,16,15,13,
+       14,14,15,16,14,14,15,15,17,14,15,15,16,17,16,16,
+       16,16,18,16,16,17,17,17,12,13,13,16,15,13,14,14,
+       16,16,12,14,13,16,15,15,16,16,17,17,14,16,15,17,
+       16,10,11,11,14,14,11,12,13,14,15,11,12,12,15,14,
+       14,14,15,16,16,13,14,14,16,16,11,12,12,14,15,12,
+       13,14,15,15,13,13,13,15,15,14,15,15,16,17,15,15,
+       15,16,17,11,12,12,14,14,12,13,13,15,15,12,13,12,
+       15,15,14,15,15,16,17,14,15,14,16,16,14,14,15,16,
+       16,14,15,15,16,17,15,16,15,17,17,16,16,17,16,18,
+       16,17,17,18,18,13,13,14,15,16,14,14,15,16,17,14,
+       14,14,16,15,16,16,17,17,18,15,16,15,17,16,10,12,
+       11,14,14,11,13,13,15,15,11,13,12,15,15,14,15,15,
+       16,16,13,15,14,16,16,12,12,13,15,15,13,13,14,15,
+       16,13,14,14,16,15,15,15,16,16,17,15,15,15,17,17,
+       11,13,11,15,14,12,14,13,16,15,12,14,12,16,14,15,
+       15,15,17,17,14,15,14,17,15,14,15,15,16,17,15,15,
+       16,16,17,15,16,16,17,17,16,16,17,17,18,16,17,17,
+       18,18,13,14,12,16,14,14,15,13,17,15,14,15,13,17,
+       14,16,17,15,18,17,15,17,14,18,15,11,12,12,14,15,
+       13,13,14,15,16,13,14,13,16,15,15,15,16,16,17,15,
+       15,15,16,16,12,13,13,15,15,13,13,14,15,16,14,15,
+       14,16,16,15,15,16,16,18,16,16,16,18,17,12,13,13,
+       15,15,14,14,15,15,16,13,14,13,15,15,16,16,16,17,
+       18,15,16,15,17,16,15,16,15,17,16,15,15,16,16,17,
+       16,17,16,17,17,16,16,17,16,18,17,18,18,18,18,14,
+       15,15,15,17,16,15,17,16,17,14,15,15,16,16,17,17,
+       18,18,19,16,16,16,17,16,12,13,13,15,15,13,14,14,
+       16,16,13,14,14,16,16,15,16,16,17,17,15,16,15,18,
+       16,13,14,14,16,16,14,15,15,16,17,14,15,15,17,16,
+       16,16,17,17,18,16,17,16,18,18,13,14,13,16,14,14,
+       15,14,17,15,14,15,14,17,14,16,17,16,18,17,15,17,
+       15,18,15,15,16,16,17,18,16,16,17,17,18,16,17,17,
+       17,18,17,17,18,18,19,17,18,18,19,18,15,16,14,17,
+       13,16,17,15,18,14,16,17,15,18,14,18,18,17,19,16,
+       17,18,16,19,15,
+};
+
+static const static_codebook _44p7_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p7_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p7_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p3_0[] = {
+        2, 5, 5, 4, 7, 7, 4, 7, 7, 5, 7, 8, 7, 8,10, 8,
+        9, 9, 5, 7, 7, 8, 9, 9, 7,10, 8, 5, 7, 8, 8, 9,
+       10, 8,10,10, 8, 9,10,10,10,12,10,12,12, 8,10,10,
+       10,12,12,10,12,11, 5, 8, 7, 8,10,10, 8,10, 9, 8,
+       10,10,10,11,12,10,12,12, 8,10, 9,10,12,12,10,12,
+       10, 5, 8, 8, 7,10,10, 8,10,10, 7, 9,10, 9,10,12,
+       10,12,12, 8,10,10,10,12,12,10,12,11, 7, 9,10, 9,
+       11,12,10,12,11, 9, 9,12,11,10,14,12,12,13,10,12,
+       11,12,13,13,11,14,12, 7,10, 9,10,11,11,10,12,11,
+        9,11,11,11,11,13,12,14,13,10,12,12,12,14,14,11,
+       14,12, 5, 8, 8, 8,10,10, 7,10,10, 8,10,10,10,11,
+       12,10,12,12, 7,10, 9,10,12,12, 9,12,10, 7, 9,10,
+       10,11,12,10,11,11,10,12,12,11,12,14,12,14,14, 9,
+       11,11,12,13,14,11,13,11, 7,10, 9,10,11,12, 9,12,
+       11,10,11,12,11,12,14,12,13,13, 9,12, 9,12,13,12,
+       11,14,10,
+};
+
+static const static_codebook _44p7_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p7_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p3_1[] = {
+        6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7,
+        8, 8, 7, 8, 7, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8,
+        8, 8, 8, 8, 9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9,
+        8, 7, 8, 8, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 7, 8, 8, 8,
+        8, 9, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8,
+        8, 9, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8,
+        9, 8, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 8, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8,
+        8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8, 8, 8, 8, 8, 9,
+        8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9,
+        8, 9, 8,
+};
+
+static const static_codebook _44p7_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p7_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p4_0[] = {
+        1, 5, 5, 5, 7, 8, 5, 8, 7, 5, 7, 8, 7, 8,10, 8,
+       10,10, 5, 8, 7, 8,10,10, 7,10, 8, 6, 8, 9, 9,10,
+       12, 9,11,11, 9,10,11,11,11,13,11,13,13, 9,11,11,
+       11,12,13,11,13,11, 6, 9, 8, 9,11,11, 9,12,10, 9,
+       11,11,11,11,13,11,13,13, 9,11,10,11,13,13,11,13,
+       11, 6, 9, 9, 8,10,11, 9,12,11, 8,10,11,10,11,13,
+       11,13,13, 9,11,11,11,13,12,11,13,11, 8,10,10, 9,
+       11,12,10,12,12,10,10,12,11,11,14,12,13,14,10,12,
+       12,12,13,13,11,14,11, 8,11,10,11,12,13,11,14,12,
+       10,12,11,11,12,14,13,15,14,10,12,12,13,14,15,12,
+       14,12, 5, 9, 9, 9,11,12, 8,11,10, 9,11,11,11,11,
+       13,11,12,13, 8,11,10,11,13,13,10,13,11, 8,10,11,
+       11,12,14,11,13,12,10,12,12,12,12,14,14,15,14,10,
+       11,12,13,14,15,11,14,12, 8,10,10,10,12,12, 9,12,
+       11,10,12,12,11,11,14,12,13,13,10,12,10,12,14,13,
+       11,13,11,
+};
+
+static const static_codebook _44p7_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p7_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p7_p4_1[] = {
+        7, 8, 8,10,10, 8, 9, 9,10,11, 8, 9, 9,10,10, 9,
+       10,10,11,11, 9,10,10,11,11, 8, 9, 9,10,10, 9, 9,
+       10,11,11, 9,10,10,11,11,10,10,11,11,11,10,11,11,
+       11,11, 8, 9, 9,10,10, 9,10,10,11,11, 9,10, 9,11,
+       11,10,11,11,11,11,10,11,10,11,11,10,10,10,11,11,
+       10,11,11,11,11,10,11,11,11,11,11,11,11,11,12,11,
+       11,11,11,12,10,10,10,11,11,10,11,11,11,11,10,11,
+       11,11,11,11,11,11,12,11,11,11,11,12,11, 8, 9,10,
+       11,11, 9,10,11,11,11, 9,10,10,11,11,10,11,11,12,
+       12,10,11,11,12,12,10,10,10,11,11,10,10,11,11,12,
+       10,11,11,12,12,11,11,12,12,12,11,11,12,12,12,10,
+       10,10,11,11,10,11,11,12,12,10,11,11,12,11,11,12,
+       12,12,12,11,12,11,12,12,11,11,11,11,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12, 8,10, 9,11,11, 9,
+       10,10,11,11, 9,10,10,11,11,10,11,11,12,12,10,11,
+       11,12,12,10,10,10,11,11,10,11,11,12,12,10,11,11,
+       12,12,11,11,12,12,12,11,12,12,12,12,10,10,10,11,
+       11,10,11,11,12,12,10,11,10,12,11,11,12,11,12,12,
+       11,12,11,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,
+       11,12,11,11,12,12,12,12,11,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,10,11,11,11,12,11,11,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       11,11,12,12,12,11,12,12,12,12,12,12,12,12,12,12,
+       12,13,12,13,12,12,12,13,13,11,12,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,13,12,12,12,12,12,12,12,12,12,13,12,12,13,13,
+       13,12,13,13,13,13,12,13,13,13,13,12,12,12,12,12,
+       12,12,13,13,13,12,12,12,13,12,12,13,13,13,13,12,
+       13,13,13,13,10,11,11,12,11,11,11,11,12,12,11,12,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,13,11,12,11,12,12,12,12,12,12,12,
+       11,12,11,12,12,12,12,12,13,13,12,12,12,13,12,12,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,12,13,
+       13,13,13,12,13,13,13,13,12,12,12,12,12,12,12,12,
+       13,13,12,13,12,13,12,12,13,13,13,13,13,13,13,13,
+       13, 8,10,10,11,11, 9,10,10,11,11, 9,10,10,11,11,
+       10,11,11,12,12,10,11,11,12,12, 9,10,10,11,11,10,
+       10,11,11,12,10,11,11,12,12,11,11,12,12,12,11,11,
+       12,12,12,10,10,10,11,11,10,11,11,12,12,10,11,10,
+       12,11,11,12,11,12,12,11,12,11,12,12,11,11,11,12,
+       12,11,11,12,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,11,11,11,12,11,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12, 9,10,
+       10,11,11,10,11,11,11,12,10,11,11,12,12,11,11,11,
+       12,12,11,11,11,12,12,10,10,11,11,12,11,11,12,12,
+       12,11,11,11,12,12,11,11,12,12,12,11,12,12,12,12,
+       10,11,11,12,12,11,11,11,12,12,11,12,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,11,11,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,12,
+       12,13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12, 9,10,10,11,11,
+       10,11,11,12,12,10,11,11,12,11,11,12,11,12,12,11,
+       12,11,12,12,10,11,11,12,12,11,11,11,12,12,11,12,
+       11,12,12,11,12,12,12,12,12,12,12,12,12,10,11,11,
+       12,12,11,12,11,12,12,11,12,11,12,12,12,12,12,13,
+       12,12,12,12,12,12,11,12,11,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12,12,12,12,13,11,
+       12,12,12,12,12,12,12,13,12,11,12,12,12,12,12,12,
+       12,13,12,12,12,12,13,12,10,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       13,11,11,12,12,12,12,12,12,12,13,12,12,12,12,12,
+       12,12,13,12,13,12,12,13,13,13,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,12,12,13,12,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,12,13,12,13,12,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,13,
+       13,12,13,13,13,13,12,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,10,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,11,12,
+       12,12,12,12,12,12,12,13,12,12,12,13,12,12,12,13,
+       13,13,12,13,13,13,13,11,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,12,12,13,13,13,13,12,13,12,13,13,
+       12,12,12,12,12,12,13,13,13,13,12,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,12,12,12,13,12,12,13,
+       13,13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13, 8,10,10,11,11, 9,10,10,11,11, 9,10,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,10,10,10,11,11,
+       10,11,11,11,12,10,11,11,12,12,11,11,12,12,12,11,
+       11,12,12,12, 9,10,10,11,11,10,11,11,12,12,10,11,
+       10,12,11,11,12,11,12,12,11,12,11,12,12,11,11,11,
+       12,12,11,11,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,11,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12, 9,
+       10,10,11,11,10,11,11,12,12,10,11,11,12,12,11,11,
+       12,12,12,11,12,12,12,12,10,11,11,12,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,10,11,11,12,12,11,11,12,12,12,11,11,11,12,12,
+       12,12,12,12,12,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,12,13,12,12,
+       12,13,12,11,12,12,12,12,12,12,12,12,12,11,12,12,
+       12,12,12,12,12,13,12,12,12,12,13,12, 9,10,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,11,11,11,12,12,
+       11,12,11,12,12,10,11,11,12,12,11,11,12,12,12,11,
+       11,11,12,12,11,12,12,12,12,11,12,12,12,12,10,11,
+       10,12,11,11,11,11,12,12,11,12,11,12,12,11,12,12,
+       12,12,11,12,11,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,12,12,12,13,
+       11,12,11,12,12,12,12,12,12,12,11,12,12,12,12,12,
+       12,12,13,12,12,12,12,13,12,10,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,13,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       13,12,12,13,13,13,12,13,13,13,13,11,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,12,12,13,13,13,13,12,
+       13,12,13,13,12,12,12,12,13,12,13,13,13,13,12,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
+       12,12,12,13,13,13,13,12,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,11,11,11,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,12,13,13,12,12,12,13,12,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,12,12,
+       13,13,13,12,13,13,13,13,11,12,11,12,12,12,12,12,
+       13,12,12,12,12,13,12,12,13,12,13,13,12,13,12,13,
+       12,12,12,12,12,13,12,12,13,13,13,12,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,
+       13,13,13,13,12,13,12,13,12,13,13,13,13,13,13,13,
+       13,13,13,10,11,11,12,12,10,11,11,12,12,10,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,12,
+       12,11,11,12,12,12,11,12,12,12,12,12,12,12,13,13,
+       12,12,12,13,13,11,11,11,12,12,11,12,12,12,12,11,
+       12,11,13,12,12,12,12,13,13,12,12,12,13,13,11,12,
+       12,12,12,12,12,12,12,13,12,12,12,13,13,12,12,13,
+       13,13,12,13,12,13,13,11,12,12,12,12,12,12,12,13,
+       12,12,12,12,13,12,12,13,13,13,13,12,13,13,13,13,
+       10,11,11,12,12,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,13,11,11,12,12,12,11,12,
+       12,12,13,12,12,12,13,13,12,12,13,13,13,12,12,13,
+       13,13,11,12,12,12,12,12,12,12,13,13,12,12,12,13,
+       13,12,13,13,13,13,12,13,12,13,13,12,12,12,12,13,
+       12,12,13,12,13,12,12,13,13,13,12,12,13,13,13,12,
+       13,13,13,13,12,12,12,12,13,12,12,13,13,13,12,12,
+       12,13,13,13,13,13,13,13,12,13,13,13,13,10,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,13,11,12,12,12,12,11,12,12,12,13,
+       12,12,12,13,13,12,12,13,13,13,12,13,13,13,13,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,13,
+       12,13,13,12,13,12,13,13,12,12,12,12,12,12,12,12,
+       13,13,12,13,12,13,13,12,13,13,13,13,13,13,13,13,
+       13,12,12,12,13,12,12,13,13,13,13,12,13,12,13,13,
+       13,13,13,13,13,13,13,13,13,13,11,11,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,12,12,12,13,13,12,12,
+       12,13,13,11,12,12,12,12,12,12,12,12,13,12,12,12,
+       13,13,12,12,13,13,13,12,12,13,13,13,11,12,12,12,
+       12,12,12,12,13,13,12,12,12,13,13,12,13,13,13,13,
+       12,13,12,13,13,12,12,12,12,12,12,12,13,12,13,12,
+       13,13,13,13,12,13,13,12,13,13,13,13,13,13,12,12,
+       12,12,12,12,13,13,13,13,12,13,12,13,13,13,13,13,
+       13,13,13,13,13,13,13,10,11,11,12,12,11,12,12,12,
+       13,11,12,12,13,12,12,12,12,13,13,12,12,12,13,13,
+       11,12,12,12,12,12,12,12,13,13,12,13,12,13,13,12,
+       12,13,13,13,12,13,13,13,13,11,12,12,12,13,12,12,
+       12,13,13,12,12,12,13,12,12,13,13,13,13,12,13,12,
+       13,13,12,12,12,12,12,12,12,13,13,13,12,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,12,12,12,13,12,
+       12,13,13,13,13,12,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13,10,11,11,12,12,10,11,11,12,12,10,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,
+       12,12,11,11,12,12,13,11,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,13,10,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,13,13,12,12,12,13,12,11,
+       12,12,12,12,12,12,12,12,13,12,12,12,13,13,12,12,
+       13,13,13,12,13,13,13,13,11,12,12,12,12,12,12,12,
+       13,13,12,12,12,13,12,12,13,13,13,13,12,13,12,13,
+       13,10,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,13,13,12,12,12,13,13,11,12,12,12,12,12,
+       12,12,12,13,12,12,12,13,13,12,12,13,13,13,12,12,
+       13,13,13,11,12,12,12,12,12,12,12,13,13,11,12,12,
+       13,12,12,13,13,13,13,12,13,12,13,13,12,12,12,12,
+       13,12,12,13,13,13,12,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,12,12,12,13,12,12,12,13,13,13,12,
+       12,12,13,13,13,13,13,13,13,12,13,13,13,13,10,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,
+       13,13,12,12,12,13,13,11,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,13,12,12,13,13,13,12,12,13,13,13,
+       11,12,11,12,12,12,12,12,13,13,11,12,12,13,12,12,
+       13,12,13,13,12,13,12,13,13,12,12,12,12,12,12,12,
+       13,13,13,12,13,12,13,13,12,13,13,13,13,13,13,13,
+       13,13,12,12,12,13,12,12,13,12,13,13,12,13,12,13,
+       13,13,13,13,13,13,12,13,12,13,13,10,11,11,12,12,
+       11,12,12,12,12,11,12,12,13,12,12,12,12,13,13,12,
+       12,12,13,13,11,12,12,12,12,12,12,12,12,13,12,12,
+       12,13,13,12,12,13,13,13,12,13,13,13,13,11,12,12,
+       12,12,12,12,12,13,13,12,12,12,13,12,12,13,13,13,
+       13,12,13,12,13,13,12,12,12,12,13,12,12,13,13,13,
+       12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,
+       12,12,12,12,12,13,13,13,13,12,13,12,13,13,13,13,
+       13,13,13,13,13,13,13,13,11,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,13,13,12,12,12,13,
+       13,11,12,12,12,12,12,12,12,13,13,12,12,12,13,13,
+       12,12,13,13,13,12,13,13,13,13,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,12,12,13,12,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,13,13,13,13,12,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,
+       12,12,13,13,13,13,12,13,12,13,12,13,13,13,13,13,
+       13,13,13,13,12,
+};
+
+static const static_codebook _44p7_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p7_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p7_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p7_p5_0[] = {
+        2, 6, 6, 9, 9, 5, 7, 8,10,11, 5, 8, 7,11,10, 8,
+       10,11,12,13, 8,11,10,13,12, 6, 7, 8,10,11, 7, 8,
+       10,10,12, 8, 9, 9,12,11,10,10,12,11,14,10,11,12,
+       14,13, 6, 8, 7,11,10, 8, 9, 9,11,12, 7,10, 8,12,
+       10,10,12,12,13,14,10,12,10,14,11, 9,10,11,11,12,
+       10,10,11,11,13,11,12,12,13,13,12,11,13,11,15,13,
+       14,13,14,14, 9,11,10,12,11,11,12,12,13,13,10,11,
+       10,13,11,13,13,14,14,14,12,13,11,14,11, 7, 8, 9,
+       11,12, 9, 9,11,12,13, 9,10,10,13,12,11,12,13,13,
+       15,11,12,12,14,14, 9,10,10,12,13,10,10,12,12,14,
+       11,11,11,13,13,12,12,13,13,15,12,13,13,15,14, 9,
+       10,10,12,13,10,11,11,13,14,10,12,11,14,13,12,13,
+       13,14,15,12,13,13,15,14,12,12,13,13,14,12,13,13,
+       13,15,13,14,14,14,15,14,14,15,14,16,14,15,15,16,
+       16,12,13,13,14,14,13,13,14,15,14,12,13,13,15,14,
+       14,15,15,15,16,14,15,14,16,14, 7, 9, 8,12,11, 9,
+       10,10,12,13, 9,11, 9,13,12,11,12,12,14,14,11,13,
+       12,15,13, 9,10,10,13,12,10,11,12,13,14,10,12,11,
+       14,13,12,13,13,14,15,13,13,13,15,14, 9,10,10,13,
+       12,11,11,11,13,13,10,12,10,14,12,13,13,13,14,15,
+       12,13,12,15,13,12,13,13,14,14,12,13,13,14,15,13,
+       14,13,15,15,14,14,15,14,16,14,15,15,16,15,12,13,
+       12,14,13,13,13,13,15,14,12,13,13,15,13,14,15,15,
+       16,15,14,15,14,16,14,11,12,12,13,14,12,13,14,14,
+       15,12,13,13,14,15,14,14,15,15,16,14,15,15,16,16,
+       12,13,13,14,15,13,13,14,14,16,13,14,14,15,15,15,
+       15,16,15,17,15,15,15,16,16,12,13,13,14,15,13,14,
+       14,15,16,13,14,14,15,15,15,15,16,16,17,15,15,15,
+       17,16,14,15,15,16,16,15,15,16,15,16,15,16,16,16,
+       17,16,16,17,16,18,16,16,17,18,17,14,15,15,16,16,
+       15,16,16,16,17,15,16,15,17,16,16,17,17,17,18,16,
+       16,16,17,16,11,12,12,14,13,12,13,13,15,14,12,14,
+       13,15,14,14,15,15,16,16,14,15,14,16,15,12,13,13,
+       15,14,13,14,14,15,15,13,14,14,16,15,15,15,15,16,
+       16,15,16,15,17,16,12,13,13,15,14,13,14,14,15,15,
+       13,14,13,16,14,15,15,15,16,16,15,15,15,17,15,14,
+       15,15,16,16,15,15,15,16,16,15,16,16,17,17,16,16,
+       17,17,17,16,17,17,18,17,14,15,15,16,15,15,15,16,
+       16,16,15,15,15,17,15,17,17,17,18,17,16,17,16,18,
+       16, 6, 9, 9,12,12, 8,10,10,12,13, 9,11,10,13,12,
+       10,12,12,14,14,11,13,12,14,14, 8,10,10,12,12, 9,
+       10,11,12,14,10,11,11,13,13,12,12,13,13,15,12,13,
+       13,15,14, 9,10,10,13,13,10,11,11,13,13,10,12,10,
+       14,13,12,13,13,14,15,12,13,13,15,14,11,12,12,13,
+       14,12,12,13,13,15,12,13,13,14,14,13,13,14,13,16,
+       14,15,15,16,15,11,12,12,14,14,13,13,13,15,14,12,
+       13,13,15,14,14,15,15,16,15,14,14,14,16,14, 7, 9,
+       10,12,12, 9,10,11,13,13, 9,11,10,13,13,11,12,13,
+       14,15,12,13,13,15,14, 9,10,11,12,13,10,10,12,13,
+       14,11,11,12,14,14,12,12,14,14,15,13,13,13,15,15,
+        9,11,11,13,13,11,12,12,14,14,10,12,10,14,13,13,
+       14,13,15,15,12,14,13,15,14,12,12,13,13,15,12,12,
+       14,13,15,13,14,14,15,15,14,14,15,14,17,14,15,15,
+       16,16,12,13,13,15,14,13,14,14,15,15,12,14,13,15,
+       14,14,15,15,16,16,14,15,14,16,14, 7,10,10,12,12,
+       10,11,11,12,13,10,12,10,14,12,12,13,13,14,15,12,
+       13,13,15,14, 9,11,10,13,12,10,10,12,12,14,11,13,
+       12,14,13,13,13,14,13,15,13,14,14,15,14,10,11,11,
+       13,13,12,12,12,13,14,10,12,10,14,12,13,14,14,15,
+       15,13,14,13,15,13,12,13,13,14,14,12,12,13,14,15,
+       13,14,14,15,15,13,13,14,13,15,14,15,15,16,16,12,
+       13,13,14,14,13,14,14,15,15,12,13,13,15,13,15,15,
+       15,16,16,13,14,13,16,13,11,12,13,14,14,12,13,14,
+       14,15,12,13,13,15,15,14,14,15,15,17,14,15,15,16,
+       16,12,13,14,14,15,13,13,14,14,16,13,14,14,15,16,
+       14,14,16,15,17,15,15,16,16,16,12,13,13,15,15,13,
+       14,14,15,16,13,14,14,15,16,15,15,16,17,17,15,16,
+       15,17,16,14,15,15,15,16,15,15,16,15,17,15,15,16,
+       16,17,16,16,16,16,18,16,16,17,17,17,14,15,15,16,
+       16,15,16,16,16,17,15,16,15,17,16,16,17,17,17,17,
+       16,17,16,18,17,11,12,12,14,14,13,13,14,14,15,13,
+       14,13,15,14,14,15,15,15,16,14,15,15,17,15,12,13,
+       13,15,14,13,13,14,15,15,14,15,14,16,15,15,15,15,
+       15,16,15,16,15,17,16,12,13,13,15,15,14,14,14,15,
+       16,13,14,13,16,15,15,15,16,16,17,15,16,15,17,15,
+       14,15,15,16,16,14,15,15,16,16,15,16,16,17,16,15,
+       15,16,15,17,16,17,17,18,17,14,15,15,16,16,15,16,
+       16,16,17,14,15,15,17,16,17,17,17,17,18,15,16,16,
+       18,15, 6, 9, 9,12,12, 9,10,11,12,13, 8,10,10,13,
+       12,11,12,13,14,14,10,12,12,14,13, 9,10,10,12,13,
+       10,10,12,13,14,10,11,11,13,13,12,13,13,14,15,12,
+       13,13,15,14, 8,10,10,12,12,10,11,11,13,13, 9,11,
+       10,13,13,12,13,13,14,15,12,13,12,15,13,11,12,12,
+       14,14,12,13,13,13,15,13,13,13,14,15,14,14,15,14,
+       16,14,15,15,15,15,11,12,12,14,13,12,13,13,15,14,
+       12,13,12,15,13,14,14,15,16,16,13,14,13,16,13, 7,
+       10,10,12,12,10,10,12,12,14,10,11,11,13,12,12,13,
+       13,13,15,12,13,13,15,14,10,11,11,13,13,10,10,12,
+       12,14,12,12,12,14,13,13,13,14,13,15,13,14,14,15,
+       14, 9,10,11,13,13,11,12,12,13,14,10,12,10,14,12,
+       13,13,14,14,15,13,13,12,15,13,12,13,13,14,14,12,
+       13,13,14,15,13,14,14,15,15,13,13,15,13,16,15,15,
+       15,16,16,12,13,13,14,14,13,14,14,15,15,12,13,12,
+       15,14,15,15,15,16,16,13,14,13,15,13, 7,10, 9,12,
+       12, 9,10,11,13,13, 9,11,10,13,13,11,13,13,14,15,
+       11,13,12,15,14, 9,11,11,13,13,10,10,12,13,14,11,
+       12,12,14,14,12,13,14,14,15,13,13,13,15,15, 9,11,
+       10,13,12,11,12,11,14,14,10,12,10,14,13,13,14,13,
+       15,15,12,14,12,15,14,12,13,13,14,15,13,13,14,14,
+       15,13,14,14,15,15,14,14,15,14,17,14,15,15,16,16,
+       12,13,12,15,13,13,14,14,15,15,12,14,13,15,13,14,
+       15,15,16,16,14,15,14,16,14,11,12,12,14,14,13,13,
+       14,14,15,13,14,13,15,15,14,15,15,16,17,14,15,15,
+       16,15,12,13,13,15,15,13,13,14,15,16,14,14,14,16,
+       15,15,15,16,15,17,15,16,15,17,16,12,13,13,14,15,
+       14,14,15,15,16,13,14,13,15,15,15,15,16,16,17,15,
+       15,15,16,15,14,15,15,16,16,14,15,15,16,17,15,16,
+       16,17,17,16,15,16,15,17,16,17,17,17,17,14,15,15,
+       15,16,15,15,16,16,17,14,15,15,16,16,16,16,17,17,
+       18,15,16,15,17,15,11,13,12,14,14,12,13,13,15,15,
+       12,14,13,15,14,14,15,15,16,16,14,15,14,16,15,12,
+       13,13,15,15,13,14,14,15,16,13,14,14,16,16,15,15,
+       16,16,17,15,16,15,17,16,12,13,13,15,14,13,14,14,
+       16,15,13,14,13,16,14,15,16,15,17,16,15,15,14,18,
+       15,14,15,15,16,16,15,15,16,16,17,15,16,15,17,16,
+       16,16,17,17,18,16,17,17,18,17,14,15,15,16,15,15,
+       16,15,17,16,15,15,15,17,15,16,17,17,18,17,16,17,
+       16,18,15,10,12,12,14,14,12,13,13,14,14,12,13,13,
+       14,14,13,14,14,15,15,13,14,14,16,15,11,12,13,14,
+       14,12,13,13,15,15,12,13,13,15,15,13,14,15,15,16,
+       14,15,15,16,16,12,13,13,14,14,13,13,14,15,15,13,
+       14,13,15,15,14,15,15,16,16,14,15,14,16,15,13,14,
+       14,15,15,13,14,14,15,16,14,14,15,16,16,14,15,15,
+       15,17,15,16,16,17,17,13,14,14,15,15,14,15,15,16,
+       16,14,15,15,16,16,15,16,16,16,17,15,16,15,17,16,
+       11,12,12,14,14,12,13,13,14,15,12,13,13,15,14,13,
+       14,14,15,16,13,14,14,16,15,12,13,13,14,15,13,13,
+       14,15,15,13,14,14,15,15,14,14,15,15,17,14,15,15,
+       16,16,12,13,13,15,15,13,14,14,15,15,13,14,13,15,
+       15,14,15,15,16,17,14,15,15,16,16,13,13,14,15,16,
+       14,14,15,15,16,14,15,15,16,16,15,15,16,15,18,15,
+       16,16,17,17,14,15,15,16,16,15,15,15,16,16,14,15,
+       15,17,16,16,16,16,17,17,15,16,16,17,16,10,12,12,
+       14,14,12,13,13,14,15,12,13,13,15,14,14,14,15,15,
+       16,14,15,14,16,15,12,13,13,15,14,13,13,14,15,15,
+       13,14,14,15,15,14,14,15,15,16,14,15,15,16,16,12,
+       13,13,15,15,13,14,14,15,16,13,14,13,15,14,15,15,
+       15,16,16,14,15,15,16,15,13,14,14,16,15,14,14,14,
+       15,16,14,15,15,16,16,15,15,16,15,17,16,17,16,17,
+       17,14,14,15,15,16,15,15,16,16,16,14,15,14,16,15,
+       16,16,16,17,17,15,16,15,17,15,11,13,13,14,15,13,
+       13,14,15,15,13,14,13,15,15,14,15,15,15,16,14,15,
+       15,17,15,13,13,14,15,15,13,14,15,15,16,14,14,14,
+       16,16,15,14,16,15,17,15,16,16,17,16,13,14,14,15,
+       15,14,14,14,16,16,13,15,14,16,15,15,15,16,17,17,
+       15,16,15,17,16,14,15,15,15,16,15,15,16,15,17,15,
+       16,16,16,17,16,16,17,15,18,16,17,17,17,17,14,15,
+       15,16,16,15,16,16,17,17,15,16,15,17,16,16,17,17,
+       18,18,16,17,15,18,16,10,12,12,14,14,13,13,14,14,
+       15,13,14,13,15,14,14,15,15,15,16,15,15,15,16,15,
+       12,13,13,15,14,12,12,14,14,15,14,15,14,16,15,15,
+       14,15,14,17,15,16,16,17,16,12,13,13,14,15,14,14,
+       15,15,16,13,14,12,16,14,15,16,16,16,17,15,16,14,
+       17,15,14,15,14,16,15,14,14,15,15,15,15,16,15,17,
+       16,15,14,16,14,16,16,17,17,18,17,14,14,15,15,16,
+       15,16,16,16,17,14,15,14,16,15,16,16,17,17,17,15,
+       16,14,17,14,10,12,12,14,13,12,13,13,14,14,11,13,
+       12,14,14,13,14,14,15,16,13,14,14,16,15,12,13,13,
+       14,14,13,13,14,15,15,13,14,13,15,15,14,14,15,15,
+       16,14,15,15,16,16,11,13,12,14,14,12,13,13,15,15,
+       12,13,13,15,15,14,15,15,16,16,13,14,14,16,15,13,
+       14,14,15,15,14,15,15,15,16,14,15,15,16,16,15,16,
+       16,16,17,16,16,16,17,17,13,14,14,15,15,14,15,15,
+       16,16,13,14,14,16,15,15,16,16,17,17,15,15,15,17,
+       15,11,12,12,14,14,12,13,13,14,15,12,13,13,15,14,
+       14,14,15,15,16,14,14,14,16,15,12,13,13,15,14,13,
+       13,14,15,15,13,14,14,16,15,14,15,15,15,16,15,15,
+       15,16,16,12,13,13,14,15,13,13,14,15,15,13,14,13,
+       15,15,15,15,15,16,16,14,15,14,16,15,14,14,15,16,
+       16,14,15,15,15,16,15,16,15,16,16,15,15,16,15,17,
+       16,16,16,17,17,13,14,14,15,16,14,15,15,16,16,14,
+       14,14,16,16,16,16,16,17,17,15,15,15,17,15,11,12,
+       12,14,14,12,13,13,14,15,12,13,13,15,14,14,14,14,
+       15,16,13,14,14,16,15,12,13,13,15,15,13,13,14,15,
+       16,13,14,14,15,15,14,15,15,16,17,14,15,15,17,16,
+       12,13,13,15,14,13,14,14,15,15,13,14,13,15,15,14,
+       15,15,16,16,14,15,14,17,15,14,15,15,16,16,14,15,
+       15,16,17,15,15,15,17,17,15,16,16,16,17,16,17,16,
+       17,17,13,15,14,16,15,14,15,15,16,16,14,15,14,16,
+       15,16,16,16,17,17,15,16,15,17,15,10,12,12,14,14,
+       13,13,14,14,15,13,14,13,15,14,14,15,15,15,17,14,
+       15,15,16,15,12,13,13,15,14,12,12,14,14,15,14,15,
+       14,16,15,15,14,16,15,17,15,16,16,17,16,12,13,13,
+       14,15,14,14,15,15,16,12,14,12,15,14,15,16,16,16,
+       17,15,16,14,17,14,14,15,14,16,16,14,14,15,15,16,
+       15,16,16,17,16,15,14,16,14,17,16,17,17,18,17,14,
+       14,15,15,16,15,15,16,16,17,14,15,14,16,15,16,17,
+       17,17,18,15,16,14,17,14,11,13,13,15,14,13,13,14,
+       15,15,12,14,13,15,15,14,15,15,15,17,14,15,14,16,
+       15,13,14,14,15,15,13,14,15,15,16,14,15,14,16,16,
+       15,15,16,16,17,15,16,16,17,17,13,14,13,15,15,14,
+       14,14,16,16,13,15,14,16,15,15,16,16,17,17,15,16,
+       14,17,15,15,15,15,16,17,15,15,16,16,17,15,16,16,
+       17,17,16,15,17,16,17,17,17,17,18,18,14,15,15,17,
+       15,15,16,16,17,16,15,16,15,17,15,16,17,17,17,17,
+       16,17,15,18,15,
+};
+
+static const static_codebook _44p7_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p7_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p7_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p7_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p7_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p7_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p7_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p6_0[] = {
+        2, 5, 6, 5, 7, 8, 5, 8, 7, 5, 7, 7, 7, 7, 9, 8,
+        9, 9, 5, 7, 7, 8, 9, 9, 7, 9, 7, 6, 8, 8, 8, 9,
+       10, 8, 9, 9, 8, 9,10, 9, 9,11,10,10,11, 8,10, 9,
+       10,10,11, 9,10,10, 6, 8, 8, 8, 9, 9, 8,10, 9, 8,
+        9,10, 9,10,10,10,11,10, 8,10, 9,10,11,10, 9,11,
+        9, 6, 8, 8, 7, 9, 9, 8, 9, 9, 7, 9, 9, 9, 9,10,
+        9,10,10, 8, 9, 9, 9,10,10, 9,10, 9, 7, 9, 9, 9,
+       10,10, 9,10,10, 9, 9,10,10, 9,11,10,11,11, 9,10,
+       10,10,11,11,10,11,10, 6, 9, 8, 9,10,10, 9,10, 9,
+        8,10,10, 9, 9,10,10,11,11, 9,10,10,10,11,11, 9,
+       11, 9, 6, 8, 8, 8, 9, 9, 7, 9, 9, 8, 9, 9, 9, 9,
+       10, 9,10,10, 7, 9, 9, 9,10,10, 9,10, 9, 6, 8, 9,
+        9, 9,10, 9,10,10, 9,10,10, 9, 9,11,10,11,11, 8,
+       10,10,10,11,11, 9,10, 9, 7, 9, 9, 9,10,10, 9,10,
+       10, 9,10,10,10,10,11,10,11,11, 9,10, 9,10,11,11,
+       10,11, 9,
+};
+
+static const static_codebook _44p7_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p7_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p6_1[] = {
+        4, 7, 7, 6, 7, 8, 6, 8, 7, 7, 7, 8, 7, 7, 8, 8,
+        8, 8, 7, 7, 7, 8, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8,
+        8, 9, 9, 8, 9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9,
+        8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8, 8,
+        8, 9, 8, 9, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8,
+        8, 9, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8,
+        9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8,
+        8, 8, 8, 9, 9, 8, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 9, 9, 9,
+        8, 9, 8,
+};
+
+static const static_codebook _44p7_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p7_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p7_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p7_0,
+       1, -513979392, 1633504256, 2, 0,
+       (long *)_vq_quantlist__44p7_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p7_p7_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p7_p7_1[] = {
+        1, 5, 5, 4,10,10, 5,10,10, 5,10,10,10,10,10,10,
+       10,10, 5,10,10,10,10,10, 9,10,10, 6,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10, 7,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10, 6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10, 6,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,11,11,
+};
+
+static const static_codebook _44p7_p7_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p7_p7_1,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44p7_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p7_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p7_p7_2[] = {
+        1, 3, 2, 4, 5, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p7_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p7_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p7_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p7_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p7_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p7_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p7_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p7_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p7_short[] = {
+        3, 9,14,16,17,19,22,22, 5, 4, 6, 9,11,13,17,20,
+        9, 5, 5, 6, 9,11,15,19,11, 7, 5, 5, 7, 9,13,17,
+       14, 9, 7, 6, 6, 7,11,14,16,11, 9, 7, 6, 4, 4, 8,
+       19,15,13,11, 9, 4, 3, 4,21,16,16,15,12, 6, 4, 4,
+};
+
+static const static_codebook _huff_book__44p7_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p7_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p8_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p8_l0_0[] = {
+        2, 4, 4, 7, 7, 8, 8,10,10,11,11,12,12, 4, 5, 5,
+        7, 7, 9, 9,10, 9,12,10,12,12, 4, 5, 5, 7, 7, 9,
+        9, 9,10,10,12,12,12, 7, 7, 7, 7, 8, 9, 8,11, 5,
+       12, 6,12,10, 7, 7, 7, 8, 7, 8, 9, 5,11, 6,12,10,
+       12, 8, 9, 9, 9, 9, 9, 9,11, 7,11, 7,11, 9, 8, 9,
+        9, 9, 9, 9, 9, 7,10, 7,11, 9,11,10,10,10,10,10,
+       10,10,11,10,11, 8,12, 9,10,10,10,10,10,10,10,10,
+       11, 8,11, 9,12,10,11,11,11,11,11,11,11,11,12,10,
+       12,11,10,11,11,11,11,11,11,11,11,10,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,
+       12,12,12,12,12,12,11,12,12,
+};
+
+static const static_codebook _44p8_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p8_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p8_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p8_l0_1[] = {
+        4, 4, 4, 5, 5, 4, 4, 5, 5, 5, 4, 5, 4, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p8_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p8_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p8_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_l1_0[] = {
+       54,
+       29,
+       79,
+       0,
+       108,
+};
+
+static const char _vq_lengthlist__44p8_l1_0[] = {
+        1, 2, 3, 6, 7, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44p8_l1_0 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p8_l1_0,
+       1, -514516992, 1620639744, 7, 0,
+       (long *)_vq_quantlist__44p8_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p8_lfe[] = {
+        2, 3, 1, 3,
+};
+
+static const static_codebook _huff_book__44p8_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44p8_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p8_long[] = {
+        2, 7,14,16,17,18,20,21, 7, 4, 6, 8,11,12,14,16,
+       13, 5, 4, 4, 8, 9,11,13,15, 8, 4, 3, 5, 7, 9,10,
+       17,11, 8, 4, 4, 6, 9, 9,17,11, 9, 7, 6, 5, 7, 8,
+       19,13,11, 9, 9, 7, 8, 8,21,15,13,11,10, 8, 8, 7,
+};
+
+static const static_codebook _huff_book__44p8_long = {
+       2, 64,
+       (char *)_huff_lengthlist__44p8_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p8_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p1_0[] = {
+        2, 5, 5, 4, 7, 7, 4, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 6, 7, 8, 8, 9,
+       10, 8, 9,10, 8, 9,10,10,10,12,10,11,12, 8,10,10,
+       10,11,12,10,11,11, 6, 8, 7, 8,10, 9, 8,10, 9, 8,
+       10,10,10,11,11,10,12,11, 8,10, 9,10,12,11,10,12,
+       10, 5, 8, 8, 8,10,10, 8,10,10, 7, 9,10, 9,10,11,
+        9,11,11, 8,10,10,10,12,12,10,12,11, 7, 9, 9, 9,
+       10,11, 9,11,11, 9, 9,11,10,11,12,10,11,12, 9,11,
+       11,11,12,12,11,12,12, 7, 9, 9,10,11,11,10,12,11,
+        9,11,10,11,11,12,11,13,12,10,11,11,12,13,13,11,
+       13,11, 5, 8, 8, 8,10,10, 8,10,10, 8,10,10,10,11,
+       12,10,12,11, 7,10, 9, 9,11,11, 9,11,10, 7, 9, 9,
+       10,11,12,10,11,11,10,11,11,11,11,13,12,13,13, 9,
+       10,11,12,12,13,11,12,11, 7, 9, 9, 9,11,11, 9,11,
+       10, 9,11,11,11,12,12,11,12,12, 9,11, 9,10,12,11,
+       10,12,11,
+};
+
+static const static_codebook _44p8_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p8_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p8_p2_0[] = {
+        4, 6, 6, 9, 9, 6, 8, 8,10,10, 6, 8, 8,10,10, 8,
+        9,10,12,12, 8,10, 9,12,12, 6, 8, 8,10,10, 8, 8,
+        9,10,11, 8, 9, 9,11,11, 9,10,11,12,13,10,11,11,
+       13,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 8, 9, 8,11,
+       10,10,11,11,13,13, 9,11,10,13,12, 9,10,10,12,12,
+       10,10,11,12,13,10,11,11,13,13,12,12,13,12,15,12,
+       13,13,15,14, 9,10,10,12,12,10,11,11,13,13,10,11,
+       10,13,12,12,13,13,14,15,12,13,12,15,12, 7, 8, 8,
+       10,11, 8, 9,10,11,12, 8, 9, 9,11,11,10,11,11,13,
+       14,10,11,11,13,13, 8, 9, 9,11,12, 9,10,11,11,13,
+        9,10,10,12,12,11,11,12,13,15,11,12,12,14,14, 8,
+        9, 9,11,11, 9,10,11,12,13, 9,10,10,12,12,11,12,
+       12,14,15,11,12,12,14,14,10,11,12,13,13,11,12,12,
+       13,14,12,12,12,14,14,13,13,14,14,16,14,14,14,16,
+       15,10,11,11,13,13,12,12,12,14,14,11,12,12,14,13,
+       14,14,14,15,16,13,14,13,16,14, 7, 8, 8,11,10, 8,
+        9, 9,11,11, 8,10, 9,12,11,10,11,11,13,13,10,11,
+       11,14,13, 8, 9, 9,12,11, 9,10,10,12,12, 9,11,10,
+       13,12,11,12,12,13,14,11,12,12,15,14, 8, 9, 9,12,
+       11, 9,10,10,12,12, 9,11,10,13,11,11,12,12,14,14,
+       11,12,12,14,13,10,11,11,13,13,11,12,12,13,14,12,
+       13,12,14,14,13,13,14,14,16,13,14,14,16,15,10,11,
+       11,13,13,12,12,12,14,14,11,12,12,14,13,13,14,14,
+       15,15,13,14,13,16,14, 9,10,11,12,13,11,11,12,12,
+       14,11,11,12,13,14,13,13,14,14,16,13,13,14,15,15,
+       11,11,12,12,14,12,12,13,13,15,12,12,13,13,15,14,
+       14,15,15,16,14,14,14,15,16,11,12,12,13,14,12,12,
+       13,14,15,12,13,12,14,14,14,14,15,15,16,14,14,14,
+       16,16,13,13,14,15,16,14,14,15,15,16,14,15,15,16,
+       16,15,15,16,16,18,16,16,16,17,17,13,14,14,15,15,
+       14,14,15,16,16,14,15,14,16,16,16,16,16,17,18,15,
+       16,16,17,16, 9,11,10,13,12,11,12,11,14,13,11,12,
+       11,14,12,13,14,13,15,14,13,14,13,16,14,11,12,12,
+       14,13,12,12,13,14,14,12,13,12,15,14,14,14,14,16,
+       16,14,15,14,17,15,11,12,11,14,12,12,13,12,15,13,
+       12,13,12,15,13,14,14,14,16,15,14,15,14,16,15,13,
+       14,14,15,15,14,14,15,16,16,14,15,14,16,16,15,15,
+       16,16,17,16,16,16,17,17,13,14,14,16,15,14,15,15,
+       16,16,14,15,14,17,15,16,16,16,17,17,15,16,15,18,
+       16, 7, 8, 8,10,11, 8, 9, 9,11,12, 8, 9, 9,12,11,
+       10,11,11,13,14,10,11,11,14,13, 8, 9, 9,11,11, 9,
+       10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,12,
+       12,14,14, 8, 9, 9,12,11, 9,10,11,12,13, 9,11,10,
+       13,12,11,12,12,14,14,11,12,12,14,13,10,11,11,13,
+       13,11,12,12,13,14,11,12,12,14,14,13,13,14,14,16,
+       13,14,14,16,15,10,12,11,13,13,12,12,12,14,14,11,
+       12,12,14,13,14,14,14,15,16,13,14,14,16,14, 8, 9,
+        9,11,11, 9,10,10,12,12, 9,10,10,12,12,11,11,12,
+       13,14,11,12,12,14,14, 9, 9,10,11,12,10,10,11,12,
+       13,10,10,11,12,13,12,12,13,14,15,12,12,13,14,15,
+        9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
+       13,13,15,15,12,13,13,15,14,11,11,12,13,14,12,12,
+       13,13,15,12,12,13,14,15,14,14,15,14,16,14,14,15,
+       15,16,11,12,12,14,14,12,13,13,15,15,12,13,13,15,
+       14,14,15,15,16,16,14,15,14,17,15, 8, 9, 9,11,11,
+        9,10,10,12,12, 9,11,10,13,12,11,12,12,14,14,11,
+       13,12,15,13, 9,10,10,12,12,10,10,11,12,13,10,12,
+       11,13,13,12,12,13,13,15,12,13,13,15,14, 9,10,10,
+       12,12,11,11,12,13,13,10,12,10,13,12,12,13,13,15,
+       15,12,13,13,15,13,11,12,12,14,14,12,12,13,14,14,
+       12,13,13,15,14,13,13,14,13,16,14,15,14,16,16,11,
+       12,12,14,14,13,13,13,15,15,12,13,12,15,14,14,15,
+       15,16,17,14,15,13,16,13,10,11,11,13,14,11,12,12,
+       13,15,11,12,12,14,14,13,14,14,15,16,13,14,14,16,
+       16,11,11,12,12,14,12,12,13,13,15,12,13,13,13,15,
+       14,14,15,14,17,14,14,15,15,16,11,12,12,14,14,12,
+       13,13,15,15,12,13,13,15,15,14,15,15,16,17,14,15,
+       15,16,16,13,14,14,14,16,14,14,15,14,17,14,15,15,
+       14,17,16,16,17,15,18,16,16,17,16,18,13,14,14,16,
+       16,14,15,15,17,16,14,15,15,17,16,16,17,17,18,18,
+       16,17,16,18,17,10,11,11,14,13,11,12,12,14,14,11,
+       13,12,15,14,14,14,14,16,15,14,15,14,16,15,11,12,
+       12,14,13,12,13,13,15,14,13,14,13,15,14,14,15,15,
+       16,16,14,15,15,17,15,11,12,12,14,14,13,13,13,15,
+       15,12,13,13,15,14,15,15,15,17,17,14,15,15,17,15,
+       13,14,14,16,15,14,15,15,16,16,15,15,15,17,16,16,
+       16,16,16,17,16,17,16,18,17,14,14,14,16,16,15,15,
+       15,16,16,14,15,14,17,16,16,17,17,17,18,16,17,16,
+       18,16, 7, 8, 8,11,11, 8, 9, 9,11,12, 8, 9, 9,12,
+       11,10,11,11,13,14,10,11,11,14,13, 8, 9, 9,11,12,
+        9,10,11,12,13, 9,11,10,13,12,11,12,12,13,14,11,
+       12,12,14,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+       10,13,12,11,12,12,14,14,11,12,11,14,13,10,11,12,
+       13,13,11,12,12,13,14,12,13,12,14,14,13,13,14,14,
+       16,13,14,14,16,15,10,11,11,13,13,11,12,12,14,14,
+       11,12,12,14,13,13,14,14,15,16,13,14,13,16,14, 8,
+        9, 9,11,11, 9,10,11,12,13, 9,10,10,12,12,11,12,
+       13,13,14,11,12,12,14,14, 9,10,10,12,12,10,10,11,
+       12,13,11,12,11,13,13,12,12,13,13,15,12,13,13,15,
+       15, 9,10,10,12,12,10,11,12,13,14,10,11,10,13,12,
+       12,13,13,14,15,12,13,12,15,13,12,12,12,14,14,12,
+       12,13,14,15,13,13,13,15,15,14,14,15,13,16,14,15,
+       15,16,16,11,12,12,14,14,12,13,13,14,15,12,13,12,
+       14,14,14,14,15,16,16,13,14,13,16,14, 8, 9, 9,11,
+       11, 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,
+       11,12,11,14,14, 9,10,10,12,12,10,11,11,13,13,10,
+       11,11,13,13,12,13,13,14,15,12,13,13,15,14, 9,10,
+        9,12,11,10,11,10,13,12,10,11,10,13,12,12,13,12,
+       15,14,12,13,12,15,14,11,12,12,14,14,12,13,13,14,
+       15,12,13,13,15,15,14,14,15,15,17,14,15,15,16,16,
+       11,12,11,14,13,12,13,12,15,14,12,13,12,15,13,14,
+       15,14,16,15,13,15,14,17,14,10,11,11,13,14,11,12,
+       13,13,15,11,12,12,14,14,14,14,15,15,17,13,14,14,
+       15,16,11,12,12,14,14,12,12,13,14,15,13,13,13,15,
+       15,14,15,15,15,17,15,15,15,16,16,11,12,12,13,14,
+       13,13,14,14,15,12,13,13,14,15,14,15,15,16,17,14,
+       15,15,16,16,14,14,14,16,16,14,14,15,15,17,15,15,
+       15,17,16,16,16,17,16,18,16,17,17,18,17,13,14,14,
+       15,16,14,15,15,16,17,14,15,15,16,16,16,17,17,17,
+       18,16,16,16,17,16,10,11,11,14,13,11,12,12,14,14,
+       11,12,12,15,13,13,14,14,16,15,13,14,14,16,15,11,
+       12,12,14,14,12,13,13,15,15,12,13,13,15,15,14,15,
+       15,16,17,14,15,15,17,16,11,12,11,14,12,12,13,13,
+       15,13,12,13,12,15,13,14,15,15,16,15,14,15,14,17,
+       14,13,14,14,16,16,14,15,15,16,17,14,15,15,16,17,
+       16,16,17,17,18,16,17,17,18,18,13,14,14,16,13,14,
+       15,15,17,14,14,15,14,17,14,16,17,16,17,16,16,17,
+       16,18,15, 8,11,11,13,13,10,12,12,14,14,11,12,12,
+       14,14,13,13,14,15,16,13,14,14,16,15,10,11,11,14,
+       14,11,12,12,14,15,11,12,12,15,14,13,14,14,15,16,
+       13,14,14,16,16,11,12,12,14,14,12,13,13,15,15,12,
+       13,12,15,14,14,14,15,16,16,14,15,14,16,16,12,13,
+       13,15,15,12,13,14,15,16,13,14,14,16,16,14,15,15,
+       16,17,15,15,16,17,17,13,14,14,16,15,14,15,15,16,
+       16,14,15,14,16,16,16,16,16,17,17,15,16,16,18,16,
+       10,11,11,13,14,11,12,12,14,15,11,12,12,15,14,13,
+       14,14,16,16,13,14,14,16,16,11,11,12,14,14,12,12,
+       13,14,15,12,13,13,15,15,14,14,15,15,17,14,14,15,
+       16,16,11,12,12,15,14,12,13,13,15,15,12,13,13,15,
+       15,14,15,15,17,17,14,15,15,17,16,13,12,14,14,16,
+       13,13,15,14,17,14,13,15,15,17,15,14,16,15,18,16,
+       15,16,16,18,13,14,14,16,16,14,15,15,17,17,14,15,
+       15,17,16,16,17,17,18,18,16,17,16,18,17,10,11,11,
+       14,13,11,12,12,14,14,11,13,12,15,14,13,14,14,15,
+       16,13,14,14,16,16,11,12,12,14,14,12,13,13,14,15,
+       12,13,13,15,15,14,14,15,15,16,14,15,15,17,16,11,
+       12,12,14,14,13,13,13,15,15,12,13,13,15,14,14,15,
+       15,16,17,14,15,14,17,15,13,14,13,16,15,14,14,14,
+       15,16,14,15,14,16,16,15,15,16,16,17,16,16,16,18,
+       17,14,14,14,16,16,15,15,15,17,16,14,15,14,17,16,
+       16,16,17,17,18,16,17,16,18,16,11,13,13,15,15,12,
+       13,14,15,16,12,14,14,15,15,14,15,15,16,17,14,15,
+       15,17,17,12,13,14,14,16,13,14,14,14,16,14,14,14,
+       15,16,15,15,16,15,18,15,16,16,17,17,13,14,14,16,
+       16,14,14,15,16,16,14,15,14,16,16,15,16,16,17,18,
+       15,16,16,18,17,14,14,16,13,17,15,15,16,14,18,15,
+       15,16,14,18,16,16,18,15,19,17,17,18,16,18,15,16,
+       15,17,17,15,16,17,18,18,16,16,16,18,17,17,18,18,
+       19,19,17,18,17,19,18,11,12,12,15,14,13,13,14,15,
+       16,13,14,13,16,14,15,15,15,16,17,15,16,15,17,16,
+       12,13,13,15,14,13,13,14,15,15,14,15,14,16,15,15,
+       15,16,16,17,16,16,16,18,17,12,13,13,15,15,14,14,
+       15,16,16,13,14,13,16,15,16,16,16,17,18,15,16,15,
+       17,16,14,15,14,17,15,14,15,15,16,16,15,16,15,17,
+       16,16,15,16,15,17,17,18,17,18,17,15,15,15,16,17,
+       16,16,16,17,17,15,16,15,17,16,17,18,18,18,18,16,
+       17,16,18,15, 8,11,11,13,13,11,12,12,14,14,10,12,
+       12,14,14,13,14,14,15,16,13,14,13,16,15,11,12,12,
+       14,14,12,12,13,14,15,12,13,13,15,15,14,14,15,15,
+       16,14,14,14,16,16,10,11,11,14,14,11,12,12,14,15,
+       11,12,12,15,14,13,14,14,16,16,13,14,14,16,15,13,
+       14,14,15,16,14,14,15,16,16,14,15,15,16,16,15,16,
+       16,16,18,16,16,16,17,17,12,13,13,15,15,13,14,14,
+       16,16,12,14,13,16,15,15,16,15,17,17,14,16,15,17,
+       16,10,11,11,13,14,11,12,13,14,15,11,13,12,14,14,
+       14,14,15,16,16,13,14,14,16,16,11,12,12,14,14,12,
+       13,13,14,15,13,14,13,15,15,14,15,15,16,17,14,15,
+       15,17,16,11,12,12,14,14,12,13,13,15,15,12,13,12,
+       15,14,14,15,15,16,17,14,15,15,16,16,14,14,14,16,
+       16,14,14,15,16,16,15,15,15,16,16,16,16,17,16,18,
+       16,17,17,18,18,13,13,14,15,16,14,14,15,16,17,13,
+       14,14,16,16,16,16,17,17,18,15,16,15,17,16,10,11,
+       11,14,13,11,12,12,14,14,11,12,12,15,14,13,14,14,
+       16,16,13,14,14,16,16,11,12,12,14,14,12,13,13,15,
+       15,12,13,13,15,15,14,15,15,16,17,14,15,15,17,16,
+       11,12,11,14,14,12,13,13,15,15,12,13,12,15,14,14,
+       15,14,16,16,14,15,14,17,16,14,14,14,16,16,14,15,
+       15,16,17,14,15,15,17,17,16,16,17,17,18,16,17,17,
+       18,18,13,14,12,16,14,14,15,13,17,15,13,15,13,17,
+       14,16,16,15,18,16,15,17,14,18,15,11,12,12,14,15,
+       13,13,14,14,16,13,14,13,15,14,15,15,16,16,17,15,
+       16,15,17,16,12,13,13,15,15,13,13,14,15,16,14,15,
+       14,16,16,15,15,16,15,18,16,16,16,18,17,12,13,13,
+       15,15,14,14,15,15,16,13,14,13,15,15,16,16,16,16,
+       18,15,16,15,17,16,15,15,15,17,16,15,15,16,16,17,
+       16,16,16,18,17,16,16,17,15,18,17,18,17,19,18,14,
+       14,15,15,17,15,15,16,16,17,14,15,15,16,16,17,17,
+       18,17,19,16,17,15,17,15,11,13,12,15,15,12,14,14,
+       15,15,12,14,13,16,15,15,15,15,17,17,14,15,15,17,
+       16,12,14,14,16,16,14,14,15,16,16,14,14,14,16,16,
+       15,16,17,17,18,15,16,16,18,17,12,14,13,16,14,13,
+       14,14,16,15,13,15,14,16,14,15,16,16,17,17,15,16,
+       15,18,15,15,15,16,17,17,15,16,16,17,18,16,16,16,
+       18,18,17,17,18,18,19,17,17,18,19,19,14,15,14,17,
+       13,15,16,15,18,14,15,16,15,18,14,17,18,17,18,16,
+       16,18,16,19,15,
+};
+
+static const static_codebook _44p8_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p8_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p8_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p3_0[] = {
+        2, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 5, 7, 8, 7, 9,
+       10, 8, 9, 9, 8, 9,10, 9,10,12,10,11,11, 8,10, 9,
+       10,11,12, 9,11,10, 5, 8, 7, 8,10, 9, 7,10, 9, 8,
+        9,10, 9,10,11,10,12,11, 8,10, 9,10,11,11, 9,12,
+       10, 5, 8, 8, 7, 9,10, 8,10, 9, 7, 9,10, 9,10,11,
+        9,11,11, 8,10, 9,10,11,11,10,12,10, 7, 9,10, 9,
+       10,12, 9,11,11, 9, 9,12,11,10,13,11,11,13,10,12,
+       11,11,13,13,11,13,12, 7, 9, 9, 9,11,11, 9,12,11,
+        9,11,10,10,11,12,11,13,12, 9,11,11,12,13,13,11,
+       13,11, 5, 8, 8, 8, 9,10, 7,10, 9, 8, 9,10,10,10,
+       12,10,11,11, 7,10, 9, 9,11,11, 9,11,10, 7, 9, 9,
+        9,11,12, 9,11,11, 9,11,11,11,11,13,12,13,13, 9,
+       10,11,11,12,13,10,12,11, 7,10, 9, 9,11,11, 9,12,
+       10,10,11,12,11,12,13,12,13,13, 9,12, 9,11,13,11,
+       10,13,10,
+};
+
+static const static_codebook _44p8_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p8_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p3_1[] = {
+        6, 7, 7, 7, 7, 8, 7, 8, 7, 7, 7, 8, 7, 8, 8, 8,
+        8, 8, 7, 8, 7, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 8,
+        8, 8, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 8, 8, 8, 9, 9, 8,
+        9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8,
+        8, 8, 8, 8, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8, 9, 8,
+        8, 9, 8,
+};
+
+static const static_codebook _44p8_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p8_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p4_0[] = {
+        2, 5, 5, 4, 7, 8, 4, 8, 7, 5, 7, 8, 7, 7,10, 8,
+        9, 9, 5, 7, 7, 8, 9, 9, 7,10, 7, 5, 7, 8, 8, 9,
+       11, 8,10,10, 8, 9,10,10,10,12,11,12,12, 8,10,10,
+       10,12,12,10,12,11, 5, 8, 7, 8,10,10, 8,11, 9, 8,
+       10,10,10,11,12,10,12,12, 8,10, 9,11,12,12,10,12,
+       10, 5, 8, 8, 7,10,10, 8,11,10, 7, 9,10, 9,10,12,
+       10,12,12, 8,10,10,10,12,12,10,12,11, 7, 9,10, 9,
+       11,12,10,12,11, 9, 9,12,10,10,13,12,12,13,10,12,
+       11,12,13,13,11,13,11, 7,10, 9,10,11,12,10,13,11,
+        9,11,11,11,11,13,12,14,13,10,11,11,12,14,14,11,
+       14,11, 5, 8, 8, 8,10,11, 7,10,10, 8,10,10,10,11,
+       12,10,12,12, 7,10, 9,10,12,12, 9,12,10, 7, 9,10,
+       10,11,13,10,12,11,10,11,11,11,11,14,12,14,14, 9,
+       11,11,12,13,14,11,13,11, 7,10, 9,10,11,12, 9,12,
+       10,10,11,12,11,11,13,12,13,13, 9,12, 9,12,13,12,
+       10,13,10,
+};
+
+static const static_codebook _44p8_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p8_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p8_p4_1[] = {
+        7, 9, 9,10,10, 9,10,10,10,11, 9,10,10,11,10, 9,
+       10,10,11,11, 9,10,10,11,11, 9,10,10,11,11,10,10,
+       10,11,11,10,10,10,11,11,10,11,11,11,11,10,11,11,
+       11,11, 9,10,10,11,11,10,10,10,11,11, 9,10,10,11,
+       11,10,11,11,11,11,10,11,11,11,11,10,11,11,11,11,
+       10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+       11,11,11,12,10,11,11,11,11,11,11,11,11,11,10,11,
+       11,11,11,11,11,11,11,11,11,11,11,11,11, 9,10,10,
+       11,11,10,10,11,11,11,10,10,11,11,11,10,11,11,11,
+       12,10,11,11,12,12,10,10,11,11,11,10,11,11,11,12,
+       11,11,11,12,12,11,11,12,12,12,11,11,12,12,12,10,
+       11,11,11,11,11,11,11,12,12,10,11,11,12,12,11,12,
+       11,12,12,11,12,11,12,12,11,11,11,11,12,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12, 9,10,10,11,11,10,
+       11,10,11,11,10,11,10,11,11,10,11,11,12,12,10,11,
+       11,12,11,10,11,11,11,11,10,11,11,11,12,11,11,11,
+       12,12,11,11,12,12,12,11,11,11,12,12,10,11,10,11,
+       11,11,11,11,12,12,10,11,11,12,11,11,12,11,12,12,
+       11,12,11,12,12,11,11,11,12,12,11,11,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,
+       11,12,11,11,12,12,12,12,11,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,10,11,11,11,11,11,11,11,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       11,11,11,12,12,11,11,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,13,12,12,12,12,13,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,10,11,11,11,11,11,11,11,12,12,11,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,12,13,12,13,
+       12, 9,10,10,11,11,10,10,11,11,11,10,11,10,11,11,
+       10,11,11,12,12,10,11,11,12,12,10,10,11,11,11,10,
+       11,11,11,12,10,11,11,12,12,11,11,12,12,12,11,11,
+       11,12,12,10,11,10,11,11,11,11,11,12,12,10,11,11,
+       12,11,11,12,11,12,12,11,12,11,12,12,11,11,11,11,
+       12,11,11,12,12,12,11,12,12,12,12,11,12,12,12,12,
+       11,12,12,12,12,11,11,11,12,11,11,12,12,12,12,11,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,10,10,
+       11,11,11,10,11,11,12,12,10,11,11,12,12,11,11,11,
+       12,12,11,11,12,12,12,10,11,11,11,12,11,11,12,12,
+       12,11,11,12,12,12,11,11,12,12,12,11,12,12,12,12,
+       11,11,11,12,12,11,12,12,12,12,11,12,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,11,11,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12, 9,10,10,11,11,
+       10,11,11,11,12,10,11,11,12,11,11,12,11,12,12,11,
+       12,11,12,12,10,11,11,12,11,11,11,11,12,12,11,12,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,10,11,11,
+       12,12,11,12,11,12,12,11,12,11,12,12,12,12,12,12,
+       12,11,12,12,12,12,11,12,11,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,11,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,13,12,12,
+       12,13,13,12,12,12,12,12,12,12,12,12,13,12,12,12,
+       12,13,12,12,13,12,13,12,13,13,13,13,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,13,12,12,13,13,13,13,
+       12,13,13,13,13,10,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,13,13,12,12,12,13,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,12,
+       13,13,12,13,12,13,13,13,13,12,12,12,12,12,12,12,
+       12,13,12,12,12,12,13,12,12,13,13,13,13,12,13,13,
+       13,13, 9,10,10,11,11,10,10,11,11,11,10,11,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,10,11,11,11,11,
+       10,11,11,12,12,11,11,11,12,12,11,11,12,12,12,11,
+       11,12,12,12,10,11,10,11,11,10,11,11,12,12,10,11,
+       11,12,11,11,12,11,12,12,11,11,11,12,12,11,11,11,
+       11,12,11,11,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,11,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,11,12,12,12,12, 9,
+       10,10,11,11,10,11,11,11,12,10,11,11,12,11,11,11,
+       12,12,12,11,11,12,12,12,10,11,11,12,12,11,11,12,
+       12,12,11,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,10,11,11,12,12,11,11,11,12,12,11,11,11,12,12,
+       11,12,12,12,12,11,12,12,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,11,11,12,12,12,12,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,10,11,10,11,
+       11,10,11,11,12,12,10,11,11,12,12,11,11,11,12,12,
+       11,12,11,12,12,11,11,11,12,12,11,11,12,12,12,11,
+       11,12,12,12,11,12,12,12,12,11,12,12,12,12,10,11,
+       11,12,11,11,12,11,12,12,11,12,11,12,12,11,12,12,
+       12,12,11,12,11,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,11,12,12,11,11,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,13,12,12,12,12,
+       12,12,12,12,13,13,12,12,12,13,13,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,12,13,12,12,
+       12,13,13,12,13,13,12,13,12,13,13,13,13,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,
+       13,12,13,12,13,12,11,11,11,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,13,13,12,12,12,13,13,11,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,12,12,12,13,
+       12,12,12,12,12,12,12,12,12,13,13,12,12,12,12,13,
+       12,13,13,13,13,12,13,13,13,13,12,12,12,12,12,12,
+       12,12,13,12,12,12,12,13,12,12,13,13,13,13,12,13,
+       13,13,12,10,11,11,12,12,11,11,11,12,12,11,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,12,
+       12,11,11,12,12,12,11,12,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,13,12,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12,12,12,12,12,12,
+       11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,11,12,12,12,12,11,11,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,12,
+       13,13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,13,12,12,12,13,13,12,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,13,12,12,13,12,13,12,
+       12,13,13,13,12,12,12,12,12,12,12,12,12,13,12,12,
+       12,13,12,12,13,13,13,13,12,13,13,13,13,10,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,11,12,12,12,
+       12,12,12,12,12,12,11,11,12,12,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12,12,12,13,13,11,
+       12,11,12,12,12,12,12,12,12,11,12,12,12,12,12,12,
+       12,13,13,12,12,12,13,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,13,12,12,12,12,12,13,12,13,12,13,
+       13,12,12,12,12,12,12,12,12,13,12,12,12,12,13,12,
+       12,13,12,13,13,12,13,12,13,12,11,11,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,12,13,12,12,13,13,13,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12,12,12,12,13,13,
+       12,12,12,13,12,12,12,12,12,12,12,12,13,12,13,12,
+       12,12,12,13,12,12,13,12,13,12,13,13,12,13,12,12,
+       12,12,12,12,13,13,13,12,12,12,12,13,12,12,13,13,
+       13,13,12,13,13,13,12,11,11,11,12,12,11,12,12,12,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,12,13,13,13,11,12,12,12,12,12,12,
+       12,12,13,12,12,12,13,12,12,13,12,13,13,12,13,12,
+       13,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,13,12,13,12,13,13,13,12,12,12,12,12,12,
+       12,13,12,13,12,12,12,12,13,12,12,13,13,13,12,12,
+       13,12,13,12,10,11,11,12,12,11,11,11,12,12,11,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,11,
+       12,12,11,11,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,11,11,12,12,11,12,12,12,12,
+       11,12,11,12,12,12,12,12,12,12,11,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,12,12,12,12,11,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,10,11,11,12,12,11,11,12,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,11,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,
+       12,13,13,11,11,11,12,12,12,12,12,12,12,11,12,12,
+       12,12,12,12,12,13,13,12,12,12,13,13,12,12,12,12,
+       12,12,12,12,12,13,12,12,12,12,13,12,12,13,12,13,
+       12,12,13,13,13,12,12,12,12,12,12,12,12,12,13,12,
+       12,12,12,12,12,12,13,13,13,12,12,12,13,12,11,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,13,12,12,12,13,13,
+       11,12,11,12,12,12,12,12,12,12,11,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,12,12,12,12,12,12,12,12,
+       12,12,13,12,12,12,13,13,12,13,13,13,13,12,13,13,
+       13,13,12,12,12,12,12,12,12,12,13,12,12,12,12,13,
+       12,12,13,12,13,13,12,13,12,13,12,11,11,11,12,12,
+       11,12,12,12,12,11,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,11,12,12,12,12,12,12,12,12,13,12,12,
+       12,13,13,12,12,13,12,13,12,12,13,13,13,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,12,12,12,12,12,12,12,12,12,12,13,
+       12,12,12,13,13,12,12,13,12,13,12,13,13,13,13,12,
+       12,12,12,12,12,12,13,12,13,12,12,12,12,12,12,13,
+       13,12,12,12,13,12,12,12,11,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,12,12,12,12,12,12,12,12,13,12,12,12,12,13,
+       12,12,13,13,13,12,12,12,13,13,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,13,13,12,13,
+       12,13,12,12,12,12,12,12,12,12,12,12,13,12,13,12,
+       13,13,12,13,13,12,13,12,13,13,13,13,12,12,12,12,
+       12,12,12,12,13,12,12,13,12,13,12,12,13,12,13,12,
+       12,13,12,13,12,
+};
+
+static const static_codebook _44p8_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p8_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p8_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p8_p5_0[] = {
+        2, 6, 6, 9, 9, 5, 7, 8,10,11, 5, 8, 7,11,10, 8,
+       10,11,12,13, 8,11,10,13,12, 6, 7, 8,10,11, 7, 8,
+       10,10,12, 8, 9, 9,12,12,10,10,12,12,14,10,12,12,
+       14,13, 6, 8, 7,11,10, 8, 9, 9,12,12, 7,10, 8,12,
+       11,10,12,12,13,14,10,12,10,14,12, 9,10,11,11,13,
+       10,10,11,11,13,11,12,12,13,14,12,12,13,11,15,13,
+       14,14,15,14, 9,11,10,13,11,11,12,12,13,13,10,11,
+       10,13,11,13,14,14,15,15,12,13,12,15,11, 6, 8, 9,
+       11,12, 8, 9,11,12,13, 8,10,10,13,13,11,12,13,14,
+       15,11,12,13,14,14, 9, 9,10,12,13,10,10,12,12,14,
+       10,11,11,13,14,12,12,14,14,15,13,13,14,15,15, 9,
+       10,10,13,13,10,11,11,13,14,10,11,10,14,13,13,13,
+       14,15,15,12,14,13,15,14,12,12,13,13,14,12,13,14,
+       13,15,13,14,14,15,15,14,14,15,14,16,15,15,15,16,
+       16,12,13,13,14,14,13,14,14,15,15,12,14,13,15,14,
+       14,15,15,16,16,14,15,14,16,14, 6, 9, 8,12,11, 8,
+       10,10,13,13, 8,11, 9,13,12,11,12,12,14,14,11,13,
+       12,15,14, 9,10,10,13,13,10,10,11,13,14,10,12,11,
+       14,13,12,13,14,14,15,13,13,13,15,14, 9,10, 9,13,
+       12,10,11,11,14,13,10,12,10,14,12,13,14,13,15,15,
+       12,14,12,15,14,12,13,13,14,14,13,13,13,14,15,13,
+       14,14,15,15,14,14,15,14,16,14,15,15,16,16,12,13,
+       12,14,13,13,14,14,15,15,12,14,13,15,13,15,15,15,
+       16,16,14,15,14,16,14,11,12,12,13,14,12,13,14,14,
+       16,12,13,13,15,15,14,14,16,15,17,14,15,15,16,16,
+       12,13,14,14,15,13,13,15,15,16,14,14,14,15,16,15,
+       15,16,16,17,15,15,16,16,17,13,13,13,15,15,14,14,
+       15,15,16,13,14,14,15,16,15,15,16,16,17,15,16,15,
+       17,16,14,15,15,16,16,15,15,16,16,17,15,16,16,17,
+       17,16,16,17,16,18,16,17,17,17,17,15,15,15,16,16,
+       15,16,16,17,17,15,16,16,17,16,16,17,17,18,18,16,
+       17,16,17,16,11,12,12,15,13,13,13,13,15,15,12,14,
+       13,16,14,14,15,15,16,16,14,15,14,17,15,13,13,13,
+       15,14,13,14,14,16,15,14,14,14,16,15,15,15,16,16,
+       17,15,16,15,17,16,12,14,13,15,14,14,14,14,16,15,
+       13,14,13,16,15,15,16,16,17,16,15,16,15,17,16,15,
+       15,15,16,16,15,15,16,16,17,15,16,16,17,17,16,16,
+       17,17,17,17,17,17,18,17,14,15,15,16,16,15,16,16,
+       17,16,15,16,15,17,16,17,17,17,18,17,16,17,16,18,
+       16, 6, 9, 9,12,12, 8,10,10,12,13, 8,10,10,13,12,
+       10,12,12,14,15,11,13,12,15,14, 8, 9,10,12,13, 9,
+       10,11,13,14,10,11,11,14,13,12,12,13,14,15,12,13,
+       13,15,15, 8,10,10,13,13,10,11,11,13,14,10,12,10,
+       14,13,12,13,13,15,15,12,14,13,15,14,11,12,12,13,
+       14,12,12,13,13,15,12,13,13,15,15,14,13,15,14,16,
+       14,15,15,16,16,12,13,13,14,14,13,13,14,15,14,12,
+       14,13,15,14,14,15,15,16,15,14,15,14,16,14, 7, 9,
+       10,12,12, 9,10,11,13,14, 9,11,10,13,13,11,12,13,
+       14,15,12,13,13,15,14, 9,10,11,12,13,10,10,12,13,
+       14,11,11,12,14,14,12,12,14,14,15,13,13,14,15,15,
+        9,11,11,13,13,11,12,12,14,14,10,12,10,14,13,13,
+       14,14,15,15,13,14,13,16,14,12,12,13,14,15,13,13,
+       14,14,16,13,14,14,15,15,14,14,15,14,17,14,15,15,
+       16,16,12,13,13,15,14,13,14,14,15,15,13,14,13,16,
+       14,15,15,15,16,16,14,15,14,16,14, 7,10, 9,13,12,
+       10,11,12,12,14,10,12,11,14,12,12,13,13,14,15,12,
+       14,13,15,14, 9,11,10,13,13,10,11,12,13,14,12,13,
+       12,15,13,13,13,14,13,15,13,14,14,16,15,10,11,11,
+       13,13,12,12,13,14,14,11,12,11,14,13,14,14,14,15,
+       16,13,14,13,16,13,12,13,13,14,14,12,13,13,14,15,
+       14,14,14,15,15,14,13,15,13,16,15,15,15,17,16,13,
+       13,13,14,14,14,14,14,15,15,12,13,13,15,14,15,16,
+       16,16,16,14,15,14,16,13,11,12,13,14,15,12,13,14,
+       15,16,13,14,14,15,15,14,14,15,15,17,14,15,15,16,
+       16,13,13,14,14,15,13,13,15,14,16,14,14,15,15,16,
+       15,14,16,15,17,15,16,16,16,17,13,14,14,15,15,14,
+       14,15,16,16,13,15,14,16,16,15,16,16,17,17,15,16,
+       15,17,16,14,15,15,15,17,15,15,16,15,17,15,16,16,
+       16,17,16,16,17,16,18,17,17,17,17,18,15,15,15,17,
+       16,15,16,16,17,17,15,16,16,17,16,16,17,17,18,18,
+       16,17,16,18,17,11,13,12,15,14,13,13,14,15,15,13,
+       14,13,16,14,15,15,15,16,16,15,16,15,17,16,13,14,
+       13,15,14,13,13,14,15,15,14,15,14,16,15,15,15,16,
+       16,16,15,16,15,18,16,13,14,14,15,15,14,15,15,15,
+       16,13,15,13,16,15,15,16,16,17,17,15,16,15,17,16,
+       15,15,15,16,16,15,15,15,16,17,16,16,16,17,16,16,
+       16,17,16,17,17,17,17,18,17,15,15,15,16,16,16,16,
+       16,17,17,15,16,15,17,16,17,17,17,18,18,16,17,16,
+       17,15, 6, 9, 9,12,12, 8,10,10,12,13, 8,10,10,13,
+       12,11,12,13,14,15,10,12,12,14,14, 9,10,10,13,13,
+       10,10,12,13,14,10,11,11,14,13,12,13,14,14,15,12,
+       13,13,15,15, 8,10, 9,13,12,10,11,11,13,14, 9,11,
+       10,14,13,12,13,13,15,15,12,13,12,15,14,12,13,13,
+       14,14,12,13,13,14,15,13,14,14,14,15,14,14,15,14,
+       16,14,15,15,16,16,11,12,12,14,13,13,13,13,15,15,
+       12,13,12,15,13,14,15,15,16,16,14,15,14,16,14, 7,
+        9,10,12,13,10,10,12,12,14,10,12,11,14,13,12,13,
+       14,14,15,12,13,13,15,14,10,11,11,13,13,11,11,12,
+       13,14,12,13,12,14,14,13,13,14,13,16,14,14,14,15,
+       15, 9,10,11,13,14,12,12,13,13,15,10,12,10,14,13,
+       13,14,14,15,16,13,14,13,15,13,13,14,13,14,15,12,
+       13,13,14,15,14,14,14,15,15,14,13,15,13,16,15,16,
+       16,16,16,12,13,13,14,14,14,14,14,15,15,12,13,13,
+       15,14,15,15,16,16,16,14,15,13,16,13, 7,10, 9,12,
+       12, 9,10,11,13,13, 9,11,10,14,13,12,13,13,14,15,
+       11,13,12,15,14, 9,11,11,13,13,10,10,12,13,14,11,
+       12,12,14,14,13,13,14,14,16,13,14,14,16,15, 9,11,
+       10,13,12,11,12,11,14,14,10,12,10,14,13,13,14,13,
+       15,15,12,14,12,16,14,12,13,13,14,15,13,13,14,14,
+       16,13,14,14,15,15,14,14,15,14,16,15,15,15,16,16,
+       12,13,12,15,14,13,14,14,15,15,12,14,13,16,14,14,
+       15,15,16,16,14,15,14,17,14,11,12,13,14,15,13,13,
+       14,14,16,13,14,13,15,15,15,15,16,16,17,15,15,15,
+       16,16,13,14,13,15,15,13,13,15,15,16,14,15,15,16,
+       16,15,15,16,15,17,16,16,16,17,17,13,13,14,14,15,
+       14,14,15,15,16,13,14,13,15,15,15,16,16,16,17,15,
+       16,15,16,16,15,15,15,16,16,15,15,16,16,17,16,16,
+       16,17,17,16,16,17,16,18,17,17,17,18,18,15,15,15,
+       16,16,16,16,16,17,17,15,15,15,16,16,17,17,17,17,
+       18,16,16,16,17,15,11,13,12,15,14,13,13,14,15,15,
+       12,14,13,16,14,14,15,15,16,16,14,15,14,16,15,13,
+       14,14,15,15,13,14,14,16,16,14,15,14,16,16,15,15,
+       16,17,17,15,16,16,17,17,13,14,13,15,14,14,14,14,
+       16,15,13,15,13,16,14,15,16,15,17,16,15,16,14,17,
+       15,14,16,15,16,17,15,16,16,16,17,15,16,16,17,17,
+       16,16,17,17,18,16,17,17,18,17,14,15,15,17,15,15,
+       16,16,17,16,15,16,15,17,15,16,17,17,18,17,16,17,
+       16,18,15,10,12,12,14,14,12,13,13,15,15,12,13,13,
+       15,15,13,14,14,15,16,14,15,14,16,16,12,13,13,15,
+       15,12,13,14,15,15,13,14,14,15,15,14,14,15,16,17,
+       14,15,15,17,16,12,13,13,15,15,13,14,14,15,16,13,
+       14,14,16,15,14,15,15,16,17,14,15,15,17,16,13,14,
+       14,15,16,14,14,15,15,16,14,15,15,16,16,15,15,16,
+       16,17,15,16,16,17,17,14,15,15,16,16,15,15,15,16,
+       16,15,15,15,16,16,16,17,16,17,17,16,16,16,18,16,
+       11,12,12,14,14,12,13,14,15,15,12,13,13,15,15,13,
+       14,15,16,16,14,15,15,16,16,12,13,13,15,15,13,13,
+       14,15,16,13,14,14,15,16,14,14,15,16,17,15,15,15,
+       16,17,12,13,13,15,15,13,14,14,15,16,13,14,14,16,
+       15,15,15,15,16,17,15,16,15,17,16,14,14,15,15,16,
+       14,14,15,15,17,15,15,16,16,17,15,15,16,15,18,16,
+       16,16,17,17,14,15,15,16,16,15,16,16,17,17,15,15,
+       15,17,16,16,17,16,17,17,16,16,16,18,16,11,12,12,
+       14,14,13,13,14,15,15,13,14,13,15,15,14,15,15,16,
+       16,14,15,15,16,16,12,13,13,15,15,13,13,14,15,15,
+       14,14,14,16,15,15,15,15,15,16,15,16,15,17,16,12,
+       13,13,15,15,14,14,15,15,16,13,14,13,16,15,15,15,
+       16,16,17,15,16,15,17,15,14,15,14,16,16,14,15,15,
+       16,16,15,16,15,17,16,15,15,16,15,17,16,17,16,17,
+       17,14,15,15,16,16,15,16,16,16,17,14,15,15,16,16,
+       16,17,17,17,18,16,16,16,17,16,12,13,13,15,15,13,
+       13,14,15,16,13,14,14,16,15,14,15,15,16,17,14,15,
+       15,17,16,13,14,14,15,16,14,14,15,15,17,14,15,15,
+       16,16,15,14,16,15,17,15,16,16,17,17,13,14,14,16,
+       16,14,15,15,16,16,14,15,14,16,16,15,16,16,17,17,
+       15,16,15,17,16,15,15,16,15,17,15,15,16,15,17,15,
+       16,16,16,17,16,15,17,15,18,17,17,17,17,17,15,15,
+       15,17,17,16,16,16,17,17,15,16,15,17,17,16,17,17,
+       18,18,16,17,15,18,15,11,12,12,15,15,13,13,15,14,
+       16,13,14,13,16,14,15,15,16,16,17,15,16,15,17,15,
+       12,14,13,16,14,13,13,14,14,16,14,15,14,16,15,15,
+       15,16,15,17,16,16,16,17,16,12,13,14,15,16,15,15,
+       15,15,16,13,15,13,16,14,16,16,16,17,17,15,16,15,
+       17,15,15,16,15,16,15,14,14,15,16,16,16,16,16,17,
+       16,15,15,16,15,17,17,17,17,18,17,15,15,15,16,16,
+       16,16,16,16,17,14,15,15,17,16,17,17,17,17,18,15,
+       16,15,18,14,10,12,12,14,14,12,13,13,15,15,12,13,
+       13,15,15,14,14,15,15,16,13,15,14,16,16,12,13,13,
+       15,15,13,14,14,15,16,13,14,14,15,15,14,15,15,16,
+       17,14,15,15,17,16,12,13,13,15,15,13,14,14,15,15,
+       12,14,13,15,15,14,15,15,16,17,14,15,14,17,15,14,
+       15,15,16,16,14,15,15,16,17,15,15,15,17,16,16,16,
+       16,16,17,16,16,16,17,17,13,14,14,16,15,14,15,15,
+       16,16,14,15,14,16,16,15,16,16,17,17,15,16,15,17,
+       16,11,12,12,14,15,13,13,14,14,15,13,14,13,15,15,
+       14,15,15,16,16,14,15,15,16,16,12,14,13,15,15,13,
+       13,14,15,16,14,15,14,16,15,15,15,16,15,17,15,16,
+       16,17,16,12,13,13,15,15,14,14,15,15,16,13,14,13,
+       16,15,15,15,16,16,17,15,15,15,16,16,14,15,15,16,
+       16,14,15,15,16,16,15,16,16,17,17,16,16,16,16,17,
+       16,17,17,18,17,14,14,15,15,16,15,15,16,16,17,14,
+       15,15,16,16,16,16,16,17,17,15,16,15,17,15,11,12,
+       12,14,14,12,13,14,15,15,12,13,13,15,15,14,15,15,
+       16,16,13,15,14,16,16,12,13,13,15,15,13,14,14,15,
+       16,13,14,14,16,16,15,15,15,16,17,15,15,15,17,16,
+       12,13,13,15,15,13,14,14,16,15,13,14,13,16,15,15,
+       16,15,17,17,14,15,14,17,16,14,15,15,16,16,15,15,
+       16,16,17,15,16,16,17,17,16,16,16,16,18,16,17,16,
+       18,17,14,15,14,16,15,15,15,15,17,16,14,15,14,17,
+       15,16,17,16,17,17,15,16,15,17,15,11,12,12,15,15,
+       13,13,15,14,16,13,15,13,16,14,15,15,16,15,17,15,
+       16,15,17,16,12,14,13,15,15,13,13,15,15,16,15,15,
+       15,16,15,15,15,16,15,17,16,16,16,17,16,12,13,14,
+       15,16,14,14,15,15,16,13,14,13,16,14,16,16,16,16,
+       17,15,16,15,17,15,15,16,15,16,16,14,15,15,16,16,
+       16,16,16,17,16,15,15,16,15,17,17,17,17,18,17,15,
+       15,15,15,16,16,16,16,16,17,14,15,14,16,15,17,17,
+       17,17,18,15,16,15,17,15,12,13,13,15,15,13,14,14,
+       15,16,13,14,14,16,15,14,15,15,16,17,14,15,15,17,
+       16,13,14,14,16,15,13,14,15,16,16,14,15,15,16,16,
+       15,15,16,16,17,15,16,16,17,17,13,14,13,16,15,14,
+       15,15,16,16,13,15,14,16,15,15,16,16,17,17,15,16,
+       14,17,15,15,15,16,17,17,15,15,16,16,17,16,16,16,
+       17,17,16,15,17,16,18,17,17,17,18,18,15,15,15,17,
+       14,16,16,16,17,16,15,16,15,17,15,16,17,17,18,17,
+       16,17,15,18,15,
+};
+
+static const static_codebook _44p8_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p8_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p8_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p8_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p8_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p8_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p8_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p6_0[] = {
+        2, 6, 6, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 7, 9, 7,
+        9, 9, 6, 7, 7, 8, 9, 9, 7, 9, 7, 6, 8, 8, 8, 9,
+       10, 8, 9, 9, 8, 9,10, 9, 9,10,10,10,10, 8, 9, 9,
+       10,10,11, 9,10,10, 6, 8, 8, 8, 9, 9, 8,10, 9, 8,
+        9, 9, 9,10,10,10,11,10, 8,10, 9,10,11,10, 9,11,
+        9, 6, 8, 8, 7, 9, 9, 7, 9, 9, 7, 9, 9, 8, 9,10,
+        9,10,10, 8, 9, 9, 9,10,10, 9,10, 9, 7, 9, 9, 9,
+        9,10, 9,10,10, 9, 9,10,10, 9,11,10,11,11, 9,10,
+       10,10,11,11,10,11,10, 6, 9, 8, 9, 9,10, 9,10, 9,
+        8,10,10, 9, 9,10,10,11,11, 9,10,10,10,11,11, 9,
+       11, 9, 6, 8, 8, 7, 9, 9, 7, 9, 9, 8, 9, 9, 9, 9,
+       10, 9,10,10, 7, 9, 9, 9,10,10, 8,10, 9, 6, 8, 9,
+        9, 9,10, 9,10, 9, 9,10,10, 9, 9,11,10,11,11, 8,
+        9,10,10,11,11, 9,10, 9, 7, 9, 9, 9,10,10, 9,10,
+        9, 9,10,10,10,10,11,10,11,11, 9,10, 9,10,11,11,
+       10,11, 9,
+};
+
+static const static_codebook _44p8_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p8_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p6_1[] = {
+        4, 7, 7, 7, 7, 8, 7, 8, 7, 7, 7, 8, 7, 8, 8, 8,
+        8, 8, 7, 8, 7, 8, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8,
+        8, 9, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9,
+        8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        8, 8, 9, 8, 8, 8, 8, 9, 9, 8, 9, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8, 8,
+        8, 8, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 8, 9, 8, 8, 8, 8, 8, 9, 9, 8,
+        9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 9, 9, 8, 8, 8, 8, 9, 8, 8, 9, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8,
+        8, 8, 8, 9, 9, 8, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9,
+        8, 9, 8,
+};
+
+static const static_codebook _44p8_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p8_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_p7_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p8_p7_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p8_p7_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p8_p7_0,
+       1, -512202240, 1635281408, 2, 0,
+       (long *)_vq_quantlist__44p8_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p8_p7_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p8_p7_1[] = {
+        1, 7, 7,12,12, 5,11,12,12,12, 5,12,11,12,12,12,
+       12,12,12,12,12,13,13,13,13, 7,11,11,13,13,13,12,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13, 7,13,10,13,13,13,13,13,13,13,12,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13, 7,13,12,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13, 8,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13, 8,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,12,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,10,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13, 8,13,12,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,11,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,11,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,
+};
+
+static const static_codebook _44p8_p7_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p8_p7_1,
+       1, -514619392, 1630767104, 3, 0,
+       (long *)_vq_quantlist__44p8_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p8_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p8_p7_2[] = {
+        1, 3, 2, 4, 5, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44p8_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p8_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p8_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p8_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p8_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p8_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p8_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p8_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p8_short[] = {
+        3, 9,15,17,20,21,22,23, 5, 5, 7, 9,11,13,17,20,
+        9, 5, 5, 6, 8,10,15,18,11, 7, 5, 4, 6, 9,13,17,
+       14, 9, 7, 5, 6, 7,10,14,17,10, 8, 6, 6, 4, 5, 8,
+       20,14,13,10, 8, 4, 3, 4,23,17,16,14,12, 6, 4, 4,
+};
+
+static const static_codebook _huff_book__44p8_short = {
+       2, 64,
+       (char *)_huff_lengthlist__44p8_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p9_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44p9_l0_0[] = {
+        2, 5, 5, 7, 6, 8, 8, 9, 9,10,10,11,11, 4, 5, 5,
+        6, 7, 8, 8, 9, 9,10,10,11,10, 4, 5, 5, 7, 6, 8,
+        8, 9, 9,10,10,10,10, 6, 6, 7, 6, 7, 8, 8, 9, 9,
+       10, 9,11, 9, 6, 6, 6, 7, 6, 8, 8, 9, 9, 9,10, 9,
+       11, 7, 7, 8, 8, 8, 8, 9, 9, 9,10, 9,11, 9, 7, 8,
+        8, 8, 8, 9, 8, 9, 9, 9,10, 9,11, 8, 9, 9, 9, 9,
+        9, 9,10,10,11,10,12,10, 8, 9, 9, 9, 9, 9, 9,10,
+        9,10,11,11,12, 9,10,10,10,10,10,10,10,11,11,11,
+       11,12, 9,10,10,10,10,11,10,11,10,11,11,12,11,11,
+       11,11,11,11,11,11,11,12,11,12,11,12,11,11,11,11,
+       11,11,11,12,11,12,11,12,11,
+};
+
+static const static_codebook _44p9_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44p9_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44p9_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_l0_1[] = {
+        4, 4, 4, 5, 5, 4, 4, 5, 5, 5, 4, 5, 4, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p9_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p9_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p9_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_l1_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_l1_0[] = {
+        1, 2, 3, 5, 9, 9, 4, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44p9_l1_0 = {
+       2, 25,
+       (char *)_vq_lengthlist__44p9_l1_0,
+       1, -514619392, 1630767104, 3, 0,
+       (long *)_vq_quantlist__44p9_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44p9_lfe[] = {
+        1, 1,
+};
+
+static const static_codebook _huff_book__44p9_lfe = {
+       1, 2,
+       (char *)_huff_lengthlist__44p9_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44p9_long[] = {
+        3, 3, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _huff_book__44p9_long = {
+       1, 8,
+       (char *)_huff_lengthlist__44p9_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44p9_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p1_0[] = {
+        1, 5, 5, 4, 8, 8, 4, 8, 8, 5, 7, 8, 8, 9,10, 8,
+       10,10, 5, 8, 7, 8,10,10, 8,10, 9, 7, 9, 9, 9,11,
+       11, 9,11,11, 9,11,11,11,12,13,11,13,13, 9,11,11,
+       11,13,13,11,13,13, 7, 9, 9, 9,11,11, 9,11,11, 9,
+       11,11,11,13,13,11,13,13, 9,11,11,11,13,13,11,13,
+       12, 5, 9, 9, 9,11,11, 9,11,11, 9,11,11,11,12,13,
+       11,13,13, 9,11,11,11,13,13,11,13,13, 9,11,12,11,
+       13,13,12,13,13,11,12,13,13,14,15,13,14,14,12,13,
+       13,13,15,15,13,15,14, 8,10,10,11,13,13,12,14,13,
+       11,12,12,13,14,15,13,15,15,11,12,12,13,15,15,13,
+       15,14, 5, 9, 9, 9,11,11, 9,11,11, 9,11,11,11,13,
+       13,11,13,13, 9,11,10,11,13,13,11,13,12, 8,10,10,
+       11,13,13,12,13,13,11,12,12,13,14,15,14,15,15,10,
+       12,12,13,14,15,13,15,14, 9,12,11,12,13,13,11,13,
+       13,12,13,13,13,15,15,13,14,15,11,13,12,13,15,14,
+       13,15,14,
+};
+
+static const static_codebook _44p9_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p9_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_p2_0[] = {
+        4, 6, 6, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 6,
+        8, 8,11,11, 6, 8, 8,11,11, 6, 7, 7, 9, 9, 7, 8,
+        9,10,11, 7, 9, 9,11,10, 8, 9,10,12,12, 8,10,10,
+       12,12, 6, 7, 7, 9, 9, 7, 9, 9,10,10, 7, 9, 8,11,
+       10, 8,10,10,12,12, 8,10, 9,12,12, 8, 9, 9,11,11,
+        9,10,10,12,12, 9,11,11,12,13,11,12,12,13,14,11,
+       12,12,14,14, 8, 9, 9,11,11, 9,11,10,13,12, 9,10,
+       10,13,12,11,12,12,14,14,11,12,12,14,13, 7, 8, 9,
+       10,10, 8,10,10,11,11, 8,10,10,11,11,10,11,11,13,
+       13,10,11,11,13,13, 8, 9,10,10,11,10,11,11,12,13,
+       10,11,11,12,12,11,11,12,13,14,11,12,12,14,14, 8,
+       10,10,11,11,10,11,11,12,13,10,11,11,12,12,11,12,
+       12,14,14,11,12,12,14,14,10,11,11,12,13,11,12,12,
+       13,14,12,13,13,14,14,13,13,14,14,16,13,14,14,15,
+       16,10,11,11,13,13,12,12,12,14,14,11,12,12,14,14,
+       13,14,14,15,16,13,14,14,16,15, 7, 8, 8,10,10, 8,
+       10,10,11,11, 8,10,10,12,11,10,11,11,13,13,10,11,
+       11,13,13, 8,10,10,11,11,10,11,11,12,12,10,11,11,
+       12,12,11,12,12,14,14,11,12,12,14,14, 8,10, 9,11,
+       10,10,11,11,13,12,10,11,10,13,12,11,12,12,14,14,
+       11,12,11,14,13,10,11,11,13,13,11,12,12,14,14,12,
+       12,12,14,14,13,14,14,15,16,13,14,14,15,15,10,11,
+       11,13,12,12,12,12,14,14,11,12,12,14,13,13,14,14,
+       16,15,13,14,13,16,14,10,11,11,13,13,12,12,13,14,
+       15,12,13,13,14,15,13,14,15,15,16,13,14,14,16,16,
+       11,12,13,14,14,13,13,14,15,16,13,14,14,15,16,14,
+       15,15,16,17,14,15,16,17,17,11,12,12,14,14,13,14,
+       14,15,16,13,14,14,15,15,14,15,15,16,18,14,15,15,
+       17,16,13,14,15,15,16,15,15,16,16,18,15,15,15,17,
+       17,16,16,17,17,18,16,16,16,18,18,14,14,14,16,16,
+       15,15,15,16,17,15,15,15,16,17,16,17,17,18,18,16,
+       16,17,18,17,10,11,11,14,13,12,13,13,15,14,11,13,
+       13,15,14,13,15,15,16,16,13,14,14,16,16,11,12,12,
+       14,14,13,13,13,15,15,13,14,13,15,15,15,15,15,17,
+       16,14,15,15,17,16,11,13,12,14,14,13,14,13,15,15,
+       13,14,13,15,15,14,15,15,17,17,14,15,15,17,16,14,
+       14,14,16,16,14,15,15,17,17,15,15,16,17,16,17,16,
+       17,18,18,16,17,17,18,18,13,14,14,16,15,15,15,15,
+       17,17,14,16,15,16,16,17,17,17,18,18,16,17,16,20,
+       19, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,12,11,
+       10,11,11,13,13,10,11,11,13,13, 8, 9,10,11,11,10,
+       11,11,12,12,10,11,11,13,12,11,12,12,14,14,11,12,
+       12,14,14, 9,10,10,11,11,10,11,11,12,12,10,11,11,
+       13,12,11,12,12,14,14,11,12,12,14,14,10,10,11,12,
+       13,11,12,12,14,14,11,12,12,14,14,13,14,14,15,16,
+       13,14,14,15,16,10,11,11,13,13,12,12,12,14,14,12,
+       13,12,14,14,13,14,14,16,16,13,14,14,15,15, 9,10,
+       10,11,12,10,11,11,12,13,10,11,11,13,12,11,12,12,
+       14,14,11,12,12,14,14,10,10,11,12,13,11,12,12,13,
+       14,11,12,12,13,14,12,13,14,14,15,12,13,13,15,15,
+       10,11,11,13,13,11,12,12,13,14,11,12,12,14,13,12,
+       13,13,15,15,12,13,13,15,15,12,11,13,12,14,13,13,
+       14,14,15,13,13,14,14,15,14,15,15,16,17,14,15,15,
+       16,17,12,13,12,14,14,13,14,14,15,15,13,14,14,15,
+       15,14,15,15,16,17,14,15,15,16,17, 8, 9, 9,11,11,
+       10,11,11,12,13,10,11,11,13,12,12,13,13,14,15,11,
+       13,12,15,14, 9,11,10,12,12,11,12,12,13,14,11,12,
+       12,14,13,13,13,14,15,15,13,14,13,15,15, 9,11,11,
+       12,12,11,12,12,14,14,11,12,12,14,13,13,14,14,15,
+       16,13,14,13,15,14,11,12,12,14,13,12,13,13,14,15,
+       13,14,14,16,15,15,15,15,15,16,15,16,15,17,17,11,
+       12,12,14,14,13,14,14,15,15,12,13,13,15,14,15,15,
+       15,17,17,14,15,15,17,15,11,12,12,14,14,12,13,13,
+       15,15,12,13,13,15,15,14,15,15,17,17,14,15,15,16,
+       16,12,13,13,14,15,13,14,14,16,16,14,14,14,15,16,
+       15,16,16,17,17,15,16,16,17,17,12,13,13,15,15,14,
+       14,14,16,16,14,14,15,16,16,15,16,16,17,17,15,16,
+       16,17,17,14,15,15,15,16,15,15,16,16,18,15,16,16,
+       17,17,17,17,17,18,18,16,17,17,19,18,14,15,15,16,
+       17,15,16,16,17,17,15,16,16,18,17,16,17,17,19,18,
+       17,17,17,19,18,10,12,12,14,14,13,13,14,15,15,12,
+       14,13,16,15,15,15,15,17,17,14,15,15,17,16,12,13,
+       13,15,14,13,14,14,16,16,14,14,15,17,16,15,16,16,
+       17,17,15,16,16,18,17,12,13,13,15,14,14,15,15,16,
+       16,13,15,14,16,15,16,17,16,19,17,15,16,16,17,17,
+       14,15,15,17,15,15,16,15,17,17,16,17,16,18,17,17,
+       17,18,18,18,17,17,18,19,18,14,15,15,16,16,15,16,
+       16,17,18,15,16,16,18,16,17,18,18,19,19,17,18,17,
+       18,19, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,12,
+       11,10,11,11,13,13, 9,11,11,13,13, 9,10,10,11,11,
+       10,11,11,12,12,10,11,11,12,12,11,12,12,14,14,11,
+       12,12,14,14, 8,10, 9,11,11,10,11,11,12,12,10,11,
+       11,12,12,11,12,12,14,14,11,12,12,14,14,10,11,11,
+       13,13,11,12,13,14,14,12,12,12,14,14,13,14,14,15,
+       16,13,14,14,16,16,10,11,10,13,12,11,12,12,14,14,
+       11,12,12,14,14,13,14,14,15,16,13,14,14,16,15, 8,
+        9, 9,11,11,10,11,11,12,13,10,11,11,13,12,12,13,
+       13,14,15,12,13,13,15,14,10,11,11,12,12,11,11,12,
+       13,14,11,12,12,14,14,13,13,14,15,16,13,14,14,15,
+       15, 9,10,11,12,12,11,12,12,13,14,11,12,12,14,13,
+       13,14,14,15,16,12,14,13,15,15,11,12,12,14,14,12,
+       13,13,14,15,13,14,14,16,15,14,15,15,15,17,15,15,
+       16,16,17,11,12,12,13,14,13,14,14,15,15,12,13,13,
+       15,14,15,16,15,16,17,14,16,15,17,15, 9,10,10,12,
+       11,10,11,11,13,13,10,11,11,13,12,11,12,12,14,14,
+       11,12,12,14,14,10,11,11,12,13,11,12,12,13,14,11,
+       12,12,14,14,12,13,13,15,15,12,13,13,15,15,10,11,
+       10,13,12,11,12,12,13,13,11,12,12,14,13,12,13,13,
+       15,15,12,13,13,15,14,12,13,12,14,14,13,14,14,15,
+       15,13,14,14,15,15,14,15,15,16,16,14,15,15,16,16,
+       11,13,11,14,12,13,13,13,15,14,12,14,13,15,14,15,
+       15,15,17,16,14,15,14,17,15,10,12,12,14,14,13,13,
+       14,15,16,12,14,13,15,15,14,15,16,17,17,14,15,16,
+       17,17,12,13,13,14,15,13,14,14,16,16,14,14,15,16,
+       16,16,16,16,17,17,16,16,16,18,18,12,13,13,14,15,
+       14,14,15,16,16,13,14,14,16,15,16,16,16,17,18,15,
+       16,16,17,17,14,15,15,16,16,15,15,16,17,17,15,16,
+       16,17,18,17,18,18,18,19,17,18,18,19,19,14,15,15,
+       16,16,15,16,16,17,17,15,16,16,17,17,17,17,18,20,
+       18,17,18,17,18,18,11,12,12,14,14,12,13,14,15,15,
+       12,13,13,15,15,14,15,15,16,17,14,15,15,16,17,12,
+       13,13,15,15,14,14,14,16,16,14,14,14,16,16,15,16,
+       16,17,17,15,16,16,17,17,12,13,13,15,14,13,14,14,
+       16,15,14,15,14,16,15,15,16,16,17,17,15,16,16,17,
+       16,14,15,15,16,16,15,16,16,17,17,16,16,16,17,17,
+       17,17,17,19,18,17,17,17,18,19,14,15,14,17,15,15,
+       16,16,17,17,15,16,15,17,17,16,17,17,18,18,16,17,
+       17,18,17, 6,11,11,13,13,11,12,12,14,14,11,12,12,
+       14,14,13,14,14,16,16,13,14,14,16,16,11,12,12,14,
+       14,12,13,13,15,15,12,13,13,15,15,14,15,15,16,17,
+       14,15,15,17,18,11,12,12,14,14,12,13,13,15,15,12,
+       13,13,15,15,14,15,15,17,17,14,15,15,16,16,13,14,
+       14,15,16,14,15,15,16,17,14,15,15,17,16,15,16,17,
+       18,17,16,16,16,18,17,14,14,15,16,16,14,15,15,18,
+       16,14,15,15,17,16,16,17,17,18,18,16,17,16,18,17,
+       11,12,12,14,14,12,13,13,15,15,12,13,13,15,15,14,
+       15,15,17,17,14,15,15,16,16,12,13,13,15,15,13,14,
+       14,15,16,13,14,14,16,16,15,16,16,17,17,15,15,16,
+       17,17,12,13,13,15,15,14,14,14,16,16,13,14,14,16,
+       16,15,16,16,17,17,15,16,16,17,17,14,14,15,15,16,
+       15,15,16,16,17,15,15,16,16,17,16,17,17,17,18,16,
+       17,17,18,18,14,15,15,16,16,15,16,16,17,17,15,16,
+       16,17,17,17,17,17,18,19,17,17,17,18,18,10,12,12,
+       14,14,12,13,14,15,16,13,14,13,15,15,14,15,15,17,
+       17,14,15,16,17,17,12,13,13,15,15,13,14,14,15,15,
+       14,15,14,16,16,15,16,16,17,18,15,17,16,18,17,12,
+       13,13,15,15,14,14,14,16,16,13,14,14,16,15,15,16,
+       16,17,18,15,16,16,17,17,14,14,14,16,16,15,15,16,
+       17,17,15,16,16,17,17,17,17,17,18,20,17,17,17,19,
+       19,14,15,15,16,16,15,17,16,18,18,15,16,15,17,16,
+       17,18,19,19,19,17,17,17,18,17,13,14,14,16,16,14,
+       15,15,17,17,14,15,15,16,17,15,17,17,18,18,16,16,
+       17,18,17,14,15,15,16,17,15,16,16,17,17,15,16,16,
+       17,17,16,17,17,18,18,17,17,17,18,19,14,15,15,16,
+       17,15,16,16,17,17,15,16,16,17,17,16,17,17,18,18,
+       17,17,17,19,19,16,16,16,16,18,16,17,17,17,18,17,
+       17,17,17,19,18,18,18,19,19,18,18,18,19,20,16,16,
+       17,18,18,16,18,17,18,18,17,17,17,20,19,18,18,19,
+       21,20,18,20,18,18,19,10,12,12,14,14,14,14,15,15,
+       17,14,15,14,17,15,16,16,17,18,18,16,18,17,19,18,
+       12,14,13,16,15,14,14,15,15,17,15,16,16,18,17,16,
+       17,18,17,19,17,19,18,20,19,12,13,13,15,15,15,16,
+       17,17,18,14,16,14,17,16,17,18,18,19,19,17,17,17,
+       18,18,15,15,15,17,16,15,16,16,17,17,17,19,17,18,
+       18,18,18,18,18,21,19,20,19,20,19,15,15,16,16,17,
+       17,17,18,20,20,15,16,16,18,17,18,19,19,19,20,18,
+       19,18,19,17, 6,11,11,13,13,11,12,12,14,14,11,12,
+       12,14,14,13,14,14,16,16,13,14,14,16,16,11,12,12,
+       14,14,12,13,13,15,15,12,13,13,15,15,14,15,15,17,
+       17,14,15,15,17,16,11,12,12,14,14,12,13,13,15,15,
+       12,13,13,15,15,14,15,15,16,16,14,15,15,16,16,13,
+       14,14,16,16,15,15,15,16,16,14,15,15,17,16,16,17,
+       17,19,18,16,17,17,18,18,13,14,14,15,15,14,15,15,
+       17,16,14,15,15,17,16,16,17,16,17,18,15,16,16,18,
+       18,10,12,12,14,14,12,13,14,15,15,12,13,13,15,15,
+       14,15,15,17,17,14,15,15,17,16,12,13,13,15,15,14,
+       14,14,15,16,14,15,15,16,16,15,16,16,17,18,16,16,
+       16,18,18,12,13,13,14,14,14,14,15,16,16,13,14,14,
+       16,16,15,16,16,18,18,15,16,16,19,17,14,15,15,16,
+       17,15,15,16,17,17,16,17,16,17,18,17,17,18,17,19,
+       17,17,18,18,19,14,14,14,16,16,15,16,16,17,17,15,
+       16,15,17,17,17,17,17,19,20,16,17,17,18,18,11,12,
+       12,14,14,12,13,13,15,15,12,13,13,15,15,14,15,15,
+       16,16,14,15,14,16,16,12,13,13,15,15,14,14,14,16,
+       16,13,14,14,16,16,15,16,16,18,17,15,16,16,17,17,
+       12,13,13,15,15,13,14,14,16,16,13,14,14,16,16,15,
+       16,15,18,18,15,16,15,17,16,14,15,15,16,16,15,16,
+       16,17,17,15,16,16,18,17,16,17,17,18,18,16,17,17,
+       18,18,14,15,14,16,15,15,16,15,17,17,15,16,15,17,
+       16,16,17,17,18,18,17,17,16,19,17,10,12,12,14,15,
+       14,14,15,15,17,14,15,14,17,15,16,17,17,17,18,16,
+       17,17,18,18,12,14,13,16,15,14,14,16,15,17,15,17,
+       16,18,17,17,17,18,17,19,18,18,18,19,18,12,13,14,
+       15,15,15,16,16,16,17,14,15,14,18,16,18,17,18,19,
+       19,17,18,17,20,18,15,15,15,17,17,15,16,16,17,18,
+       18,18,18,19,18,18,18,19,18,20,18,19,19,21,21,15,
+       15,16,16,17,17,18,18,18,18,15,16,16,17,17,17,19,
+       20,19,20,17,18,18,19,17,13,14,14,16,16,14,15,15,
+       16,17,14,15,15,17,17,16,16,17,17,18,15,17,16,17,
+       17,14,15,15,16,16,15,16,16,17,17,16,16,16,17,17,
+       17,17,18,17,18,17,17,17,18,20,14,15,15,17,16,15,
+       16,16,17,17,15,16,16,17,17,17,17,17,18,18,16,17,
+       17,19,18,16,16,17,17,17,17,18,17,19,18,17,17,17,
+       18,19,17,20,18,19,21,17,19,18,19,20,15,17,15,17,
+       16,16,17,17,18,18,17,17,17,18,17,18,19,18,19,21,
+       18,18,17,19,19,
+};
+
+static const static_codebook _44p9_p2_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p9_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p9_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p3_0[] = {
+        2, 5, 4, 4, 7, 7, 4, 7, 6, 5, 6, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 6, 7, 9, 9, 7, 9, 8, 6, 8, 8, 8,10,
+       10, 8,10,10, 8, 9,10,10,11,12,10,12,12, 8,10,10,
+       10,12,12,10,12,11, 6, 8, 8, 8,10,10, 8,10,10, 8,
+       10,10,10,11,12,10,12,12, 8,10, 9,10,12,11,10,12,
+       11, 5, 8, 8, 8,10,10, 8,10,10, 8, 9,10,10,11,11,
+       10,11,11, 8,10,10,10,11,12,10,12,11, 8,10,10,10,
+       11,11,10,11,11,10,11,11,11,12,13,11,12,13,10,11,
+       11,11,13,13,11,13,13, 7, 9, 9,10,11,12,10,12,11,
+        9,11,11,11,12,13,12,14,13, 9,11,11,12,13,14,11,
+       13,12, 5, 8, 8, 8,10,10, 8,10,10, 8,10,10,10,11,
+       12,10,12,12, 8,10, 9,10,12,11, 9,11,11, 7, 9, 9,
+       10,11,12,10,12,11, 9,11,11,11,12,13,12,14,13, 9,
+       11,11,12,13,14,11,13,12, 8,10,10,10,11,11,10,11,
+       11,10,11,11,11,13,13,11,13,13,10,11,10,11,13,12,
+       11,13,12,
+};
+
+static const static_codebook _44p9_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p3_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44p9_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p3_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p3_1[] = {
+        4, 6, 6, 6, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 8, 7,
+        7, 8, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8,
+        8, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9,
+        9, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9,
+        8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8,
+        9, 9, 8, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8, 9,
+        9, 9, 9, 9, 9, 9, 9, 7, 8, 8, 8, 9, 9, 8, 9, 9,
+        8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9,
+        9, 9, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        9, 8, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9, 9, 7, 8, 8,
+        8, 9, 9, 8, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 8,
+        8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 9,
+        9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44p9_p3_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p3_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44p9_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_p4_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p4_0[] = {
+        2, 5, 5, 4, 7, 7, 4, 7, 6, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 6, 7, 8, 8, 9,
+       10, 8,10,10, 8, 9,10,10,11,12,10,11,12, 8,10,10,
+       10,11,12,10,12,11, 6, 8, 7, 8,10,10, 8,10, 9, 8,
+       10,10,10,11,12,10,12,12, 8,10, 9,10,12,11,10,12,
+       11, 5, 8, 8, 8,10,10, 8,10,10, 7, 9,10, 9,10,11,
+       10,11,11, 8,10,10,10,12,12,10,12,11, 7, 9, 9, 9,
+       11,11, 9,11,11, 9,10,11,11,11,12,11,12,12, 9,11,
+       11,11,12,12,11,12,12, 7, 9, 9,10,11,12,10,12,11,
+        9,11,10,11,11,12,12,13,13, 9,11,11,12,13,13,11,
+       13,11, 5, 8, 8, 8,10,10, 8,10,10, 8,10,10,10,11,
+       12,10,12,12, 7, 9, 9, 9,11,11, 9,11,10, 7, 9, 9,
+       10,11,12,10,12,11, 9,11,11,11,11,13,12,13,13, 9,
+       10,11,12,13,13,11,12,11, 7, 9, 9, 9,11,11, 9,11,
+       11, 9,11,11,11,12,12,11,12,12, 9,11,10,11,12,12,
+       10,12,11,
+};
+
+static const static_codebook _44p9_p4_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p4_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44p9_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p4_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_p4_1[] = {
+        6, 8, 8,10, 9, 8, 9, 9,10,10, 8, 9, 9,10,10, 8,
+       10,10,10,10, 8,10,10,10,10, 9, 9, 9,10,10, 9,10,
+       10,10,11, 9,10,10,11,11,10,10,10,11,11,10,10,10,
+       11,11, 9, 9, 9,10,10, 9,10,10,11,11, 9,10,10,11,
+       10,10,10,10,11,11,10,10,10,11,11,10,10,10,10,11,
+       10,10,11,11,11,10,11,11,11,11,11,11,11,11,11,11,
+       11,11,11,11,10,10,10,11,10,10,11,11,11,11,10,11,
+       10,11,11,11,11,11,11,11,10,11,11,11,11, 9,10,10,
+       10,11,10,10,11,11,11,10,11,11,11,11,10,11,11,11,
+       11,10,11,11,11,11,10,10,11,11,11,11,11,11,11,11,
+       11,11,11,11,12,11,11,12,12,12,11,11,11,12,12,10,
+       11,11,11,11,11,11,11,12,12,11,11,11,11,11,11,11,
+       11,12,12,11,11,11,12,12,11,11,11,11,11,11,12,12,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,11,11,11,11,11,11,12,12,12,12,11,12,11,12,12,
+       11,12,12,12,12,12,12,12,12,12, 9,10,10,11,10,10,
+       11,11,11,11,10,11,11,11,11,10,11,11,11,11,10,11,
+       11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
+       12,12,11,11,12,12,12,11,11,11,12,12,10,11,10,11,
+       11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,
+       11,11,11,12,12,11,11,11,11,11,11,12,12,12,12,11,
+       12,12,12,12,11,12,12,12,12,12,12,12,12,12,11,11,
+       11,11,11,11,12,12,12,12,11,12,11,12,12,12,12,12,
+       12,12,11,12,12,12,12,11,11,11,11,11,11,12,12,12,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,13,12,12,12,13,13,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,13,12,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       13,12,13,13,13,13,12,13,13,13,13,12,12,12,12,12,
+       12,12,12,13,13,12,12,12,13,13,12,13,13,13,13,12,
+       13,13,13,13,11,11,11,11,11,11,12,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,13,11,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,13,13,12,12,12,13,13,12,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,12,13,
+       13,13,13,12,13,13,13,13,12,12,12,12,12,12,12,12,
+       13,13,12,12,12,13,12,12,13,13,13,13,12,13,13,13,
+       13, 7,10,10,11,11,10,10,11,11,11,10,11,11,11,11,
+       10,11,11,11,11,10,11,11,11,11,10,10,10,11,11,10,
+       11,11,11,11,11,11,11,11,12,11,11,11,12,12,11,11,
+       11,12,12,10,11,11,11,11,11,11,11,12,11,11,11,11,
+       12,11,11,11,11,12,12,11,11,11,12,12,11,11,11,11,
+       11,11,11,11,12,12,11,11,12,12,12,11,12,12,12,12,
+       11,12,12,12,12,11,11,11,11,11,11,12,12,12,12,11,
+       11,12,12,12,11,12,12,12,12,11,12,12,12,12,10,11,
+       11,11,11,11,11,11,11,12,11,11,11,11,11,11,11,11,
+       12,12,11,11,11,12,12,11,11,11,11,11,11,11,12,12,
+       12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,
+       11,11,11,11,11,11,12,11,12,12,11,11,11,12,12,11,
+       12,12,12,12,11,12,12,12,12,11,11,11,11,12,11,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,11,11,11,12,12,11,12,12,12,12,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,10,11,10,11,11,
+       11,11,11,12,12,11,11,11,12,12,11,12,12,12,12,11,
+       12,12,12,12,10,11,11,12,11,11,11,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,
+       12,11,11,12,12,12,12,11,12,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,11,12,11,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,13,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,12,12,13,12,11,11,11,12,12,12,12,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,13,13,12,12,12,13,13,11,12,12,12,12,12,
+       12,12,12,13,12,12,12,12,12,12,12,13,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,13,12,13,13,13,13,12,13,13,13,13,12,12,12,12,
+       12,12,12,12,13,13,12,13,12,13,13,12,13,13,13,13,
+       12,13,13,13,13,11,11,11,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,12,13,12,
+       13,13,12,13,13,13,13,11,12,12,12,12,12,12,12,13,
+       13,12,12,12,13,12,12,13,13,13,13,12,13,13,13,13,
+       12,12,12,12,12,12,12,13,13,13,12,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,13,
+       13,13,13,12,12,12,13,13,13,13,13,13,13,13,13,13,
+       13,13, 7,10,10,11,11,10,11,11,11,11,10,11,11,11,
+       11,10,11,11,11,11,10,11,11,11,11,10,11,11,11,11,
+       11,11,11,11,11,11,11,11,12,11,11,11,12,12,12,11,
+       11,11,12,12,10,10,10,11,11,11,11,11,12,11,10,11,
+       11,11,11,11,11,11,12,12,11,11,11,12,12,11,11,11,
+       11,11,11,11,12,12,12,11,12,11,12,12,11,12,12,12,
+       12,11,12,12,12,12,11,11,11,11,11,11,11,11,12,12,
+       11,12,11,12,12,11,12,12,12,12,11,12,12,12,12,10,
+       10,10,11,11,11,11,11,12,12,11,11,11,12,12,11,12,
+       12,12,12,11,12,12,12,12,11,11,11,11,11,11,11,12,
+       12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,11,11,11,11,11,11,12,12,12,12,11,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,13,12,12,
+       12,13,12,11,11,11,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,10,11,11,11,
+       11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,
+       11,11,11,12,12,11,11,11,11,11,11,11,12,12,12,11,
+       12,11,12,12,11,12,12,12,12,11,12,12,12,12,11,11,
+       11,11,11,11,11,11,12,12,11,11,11,12,12,11,12,12,
+       12,12,11,12,12,12,12,11,11,11,12,11,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       11,11,11,12,11,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,11,11,12,12,11,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,12,11,12,12,12,12,12,12,12,12,13,12,12,12,13,
+       13,12,13,13,13,13,12,13,13,13,13,11,12,12,12,12,
+       12,12,12,12,13,12,12,12,12,12,12,13,13,13,13,12,
+       13,13,13,13,12,12,12,12,12,12,12,13,13,13,12,13,
+       12,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
+       12,12,12,13,13,13,13,12,13,12,13,13,13,13,13,13,
+       13,13,13,13,13,13,11,11,11,12,12,11,12,12,12,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
+       12,13,13,12,12,12,13,13,11,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,13,12,13,12,13,
+       13,12,12,12,12,12,12,12,12,13,13,12,12,12,13,13,
+       13,13,13,13,13,12,13,13,13,13,12,12,12,12,12,12,
+       13,12,13,13,12,13,12,13,12,12,13,13,13,13,12,13,
+       13,13,13, 8,11,11,12,12,11,12,12,12,12,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,12,
+       12,11,12,12,12,12,12,12,12,12,12,12,12,12,13,13,
+       12,12,12,13,13,11,11,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,13,12,12,12,13,13,11,12,
+       12,12,12,12,12,12,12,13,12,12,12,12,12,12,12,13,
+       13,13,12,12,13,13,13,11,12,12,12,12,12,12,12,13,
+       12,12,12,12,13,13,12,13,13,13,13,12,13,13,13,13,
+       11,11,11,12,12,11,12,12,12,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,13,13,12,12,12,
+       13,13,11,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,12,13,13,12,13,12,13,13,12,12,12,12,12,
+       12,12,12,12,13,12,12,12,13,13,12,13,13,13,13,12,
+       13,13,13,13,12,12,12,12,12,12,12,12,13,13,12,12,
+       12,13,13,12,13,13,13,13,12,13,13,13,13,11,11,11,
+       12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,13,
+       12,12,12,12,12,13,11,12,12,12,12,12,12,12,12,13,
+       12,12,12,12,13,12,13,13,13,13,12,13,13,13,13,11,
+       12,12,12,12,12,12,12,12,13,12,12,12,13,12,12,13,
+       13,13,13,12,13,13,13,13,12,12,12,12,12,12,12,12,
+       13,13,12,12,13,13,13,12,13,13,13,13,12,13,13,13,
+       13,12,12,12,12,12,12,13,13,13,13,12,13,12,13,13,
+       12,13,13,13,13,13,13,13,13,13,11,11,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,11,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,13,13,13,12,13,13,13,13,11,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,
+       12,13,12,13,13,12,12,12,12,12,12,12,12,13,13,12,
+       12,12,13,13,12,13,13,13,13,12,13,13,13,13,12,12,
+       12,12,12,12,13,12,13,13,12,12,12,13,13,13,13,13,
+       13,13,12,13,13,13,13,11,11,11,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,12,12,12,13,12,
+       11,12,12,12,12,12,12,12,12,12,12,12,12,13,13,12,
+       12,13,13,13,12,13,13,13,13,11,12,12,12,12,12,12,
+       12,12,13,12,12,12,13,12,12,13,13,13,13,12,13,13,
+       13,13,12,12,12,12,12,12,12,12,13,13,12,12,12,13,
+       13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
+       12,13,13,13,13,12,13,12,13,13,13,13,13,13,13,13,
+       13,13,13,13, 8,11,11,11,11,11,12,12,12,12,11,12,
+       12,12,12,12,12,12,12,12,11,12,12,12,12,11,11,11,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,12,12,12,13,13,11,11,11,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,13,13,12,12,12,13,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,13,13,12,13,
+       13,13,13,12,13,13,13,13,11,12,12,12,12,12,12,12,
+       12,13,12,12,12,13,12,12,13,13,13,13,12,13,12,13,
+       13,11,11,11,12,12,12,12,12,12,12,11,12,12,12,12,
+       12,12,12,13,13,12,12,12,13,12,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,13,12,12,13,13,13,12,13,
+       13,13,13,11,12,12,12,12,12,12,12,13,13,12,12,12,
+       12,12,12,13,13,13,13,12,13,13,13,13,12,12,12,12,
+       12,12,12,13,13,13,12,12,13,13,13,13,13,13,13,13,
+       12,13,13,13,13,12,12,12,12,12,12,13,12,13,13,12,
+       12,12,13,13,13,13,13,13,13,12,13,13,13,13,11,11,
+       11,12,12,11,12,12,12,12,11,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,13,12,13,13,12,12,12,13,13,
+       11,12,12,12,12,12,12,12,12,13,12,12,12,12,12,12,
+       12,12,13,13,12,13,12,13,13,12,12,12,12,12,12,12,
+       12,13,12,12,12,12,13,13,12,13,13,13,13,12,13,13,
+       13,13,12,12,12,12,12,12,12,12,13,13,12,12,12,13,
+       12,12,13,13,13,13,12,13,13,13,13,11,11,11,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,13,13,11,12,12,12,12,12,12,12,12,13,12,12,
+       12,12,12,12,13,13,13,13,12,13,13,13,13,11,12,12,
+       12,12,12,12,12,12,13,12,12,12,12,12,12,13,13,13,
+       13,12,13,13,13,13,12,12,12,12,12,12,12,12,13,13,
+       12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,12,
+       12,12,12,12,12,13,13,13,13,12,12,12,13,12,13,13,
+       13,13,13,12,13,13,13,13,11,11,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       13,11,12,12,12,12,12,12,12,12,12,12,12,12,13,12,
+       12,12,12,13,13,12,13,13,13,13,11,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,13,13,13,13,12,13,
+       12,13,13,12,12,12,12,12,12,12,13,13,13,12,13,12,
+       13,13,12,13,13,13,13,13,13,13,13,13,12,12,12,12,
+       12,12,12,12,12,13,12,12,12,13,13,13,13,13,13,13,
+       12,13,13,13,13,
+};
+
+static const static_codebook _44p9_p4_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p9_p4_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p9_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_p5_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_p5_0[] = {
+        4, 6, 6, 9, 9, 6, 7, 8,10,11, 6, 8, 7,10,10, 8,
+       10,10,12,12, 8,10,10,12,12, 6, 7, 8,10,10, 7, 8,
+        9,10,11, 8, 9, 9,11,11,10,10,11,12,13,10,11,11,
+       13,13, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 9, 8,11,
+       10,10,11,11,13,13,10,11,10,13,12, 9,10,10,11,12,
+       10,10,11,12,13,10,11,11,12,13,12,12,13,12,14,12,
+       13,13,14,14, 9,10,10,12,11,10,11,11,13,12,10,11,
+       10,13,12,12,13,13,14,14,12,13,12,14,12, 7, 8, 8,
+       10,11, 8, 9,10,11,12, 8, 9, 9,11,12,10,11,12,13,
+       14,10,11,11,13,13, 8, 9,10,11,12, 9,10,11,12,13,
+       10,10,11,12,12,11,12,12,13,14,11,12,12,14,14, 8,
+        9, 9,11,12,10,10,11,12,13, 9,10,10,12,12,11,12,
+       12,14,14,11,12,12,14,13,11,11,12,12,13,11,12,12,
+       13,14,12,12,13,14,14,13,13,14,14,16,13,14,14,15,
+       15,11,12,11,13,13,12,12,12,14,14,11,12,12,14,13,
+       13,14,14,15,15,13,14,13,15,14, 7, 8, 8,11,10, 8,
+       10, 9,12,11, 8,10, 9,12,11,10,11,11,13,13,10,12,
+       11,14,13, 8, 9, 9,12,11, 9,10,10,12,12,10,11,10,
+       13,12,11,12,12,13,14,11,12,12,14,14, 8,10, 9,12,
+       11,10,11,10,12,12, 9,11,10,13,11,11,12,12,14,14,
+       11,12,12,14,13,11,11,12,13,13,11,12,12,13,14,12,
+       12,12,14,14,13,13,14,14,15,13,14,14,15,15,11,12,
+       11,13,12,12,12,12,14,14,11,12,12,14,13,13,14,14,
+       15,15,13,14,13,15,14,10,11,11,12,13,11,12,12,13,
+       14,11,12,12,13,14,13,13,14,14,16,13,14,14,15,15,
+       11,12,12,12,14,12,12,13,13,15,12,13,13,13,15,14,
+       14,15,15,16,14,14,15,15,16,11,12,12,13,14,12,13,
+       13,14,15,12,13,13,14,14,14,14,15,15,16,14,14,14,
+       15,15,13,14,14,14,15,14,14,15,15,16,14,15,15,15,
+       16,15,15,16,16,18,16,16,16,17,17,13,14,14,15,15,
+       14,14,15,16,16,14,14,14,16,15,16,16,16,17,17,15,
+       16,16,17,16,10,11,11,13,12,11,12,12,14,13,11,12,
+       12,14,13,13,14,14,15,15,13,14,13,16,14,11,12,12,
+       14,13,12,13,13,14,14,12,13,13,15,14,14,14,14,15,
+       15,14,15,14,16,15,11,12,12,14,12,12,13,13,15,14,
+       12,13,12,15,13,14,15,14,16,15,14,15,14,16,15,13,
+       14,14,15,15,14,14,14,15,16,14,15,14,16,16,15,16,
+       16,16,17,16,16,16,17,17,13,14,14,15,14,14,15,15,
+       16,15,14,15,14,16,15,16,16,16,17,17,15,16,15,18,
+       16, 6, 8, 8,11,11, 8, 9,10,11,12, 8,10, 9,12,12,
+       10,11,11,13,13,10,12,11,14,13, 8, 9, 9,11,12, 9,
+       10,10,12,12, 9,10,10,12,12,11,11,12,13,14,11,12,
+       12,14,14, 8,10, 9,12,11,10,11,11,12,12, 9,11,10,
+       13,12,11,12,12,14,14,11,12,12,14,13,10,11,11,13,
+       13,11,12,12,13,14,11,12,12,14,14,13,13,14,13,15,
+       13,14,14,15,15,11,12,11,13,13,12,12,12,14,14,11,
+       12,12,14,13,13,14,14,15,15,13,14,13,15,14, 8, 9,
+        9,11,11, 9,10,10,12,12, 9,10,10,12,12,11,12,12,
+       13,14,11,12,12,14,14, 9, 9,10,11,12,10,10,11,12,
+       13,10,10,11,12,13,12,12,13,13,15,12,12,13,14,14,
+        9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
+       13,13,14,15,12,13,12,14,14,11,11,12,12,14,12,12,
+       13,13,14,12,12,13,13,14,13,13,14,14,16,14,14,14,
+       15,15,11,12,12,14,13,12,13,13,14,14,12,13,13,15,
+       14,14,14,14,16,16,13,14,14,16,14, 7, 9, 9,12,11,
+        9,10,10,12,12, 9,11,10,13,12,11,12,12,13,14,11,
+       13,12,14,13, 9,10,10,12,12,10,10,11,12,13,10,12,
+       11,13,13,12,12,13,13,14,12,13,13,15,14, 9,10,10,
+       12,12,11,11,11,13,13,10,12,10,13,12,12,13,13,14,
+       15,12,13,12,15,13,11,12,12,14,13,12,12,13,13,14,
+       12,13,13,15,14,13,13,14,13,16,14,15,14,16,15,12,
+       12,12,14,14,13,13,13,14,14,12,13,12,14,13,14,15,
+       15,16,16,13,14,13,16,13,10,11,12,13,14,11,12,13,
+       13,15,12,12,13,14,14,13,14,14,15,16,13,14,14,16,
+       15,12,12,13,12,14,12,12,13,13,15,13,13,13,13,15,
+       14,14,15,14,16,14,15,15,15,16,12,13,12,14,14,13,
+       13,13,15,15,12,13,13,15,15,14,15,15,16,16,14,15,
+       15,16,16,13,14,14,13,16,14,14,15,14,16,14,14,15,
+       14,16,15,15,16,15,18,16,16,16,16,17,14,14,14,16,
+       15,14,15,15,16,16,14,15,15,16,16,16,16,16,17,17,
+       15,16,16,17,16,10,12,11,14,13,12,13,13,14,14,12,
+       13,12,15,14,14,14,14,15,15,14,15,14,16,15,12,13,
+       12,14,13,12,13,13,15,14,13,14,13,15,14,14,15,15,
+       16,16,14,15,15,17,15,12,13,12,14,14,13,14,14,15,
+       15,13,14,13,15,14,15,15,15,16,16,14,15,15,17,15,
+       14,14,14,16,15,14,15,15,16,16,14,15,15,16,15,16,
+       16,16,16,17,16,17,16,18,17,14,14,14,16,15,15,15,
+       15,16,16,14,15,14,16,15,16,16,17,17,17,15,16,15,
+       17,16, 6, 8, 8,11,11, 8, 9,10,12,12, 8,10, 9,12,
+       11,10,11,12,13,13,10,11,11,13,13, 8, 9,10,11,12,
+        9,10,11,12,13,10,11,11,12,12,11,12,12,13,14,11,
+       12,12,14,14, 8, 9, 9,12,11, 9,10,10,12,12, 9,10,
+       10,12,12,11,12,12,14,14,11,12,11,14,13,11,11,12,
+       13,13,11,12,12,13,14,12,12,12,14,14,13,13,14,14,
+       15,13,14,14,15,15,10,11,11,13,13,11,12,12,14,14,
+       11,12,12,14,13,13,14,14,15,15,13,14,13,15,13, 7,
+        9, 9,11,12, 9,10,11,12,13, 9,10,10,12,12,11,12,
+       13,13,14,11,12,12,14,14, 9,10,10,12,12,10,10,11,
+       12,13,11,12,11,13,13,12,12,13,13,15,12,13,13,15,
+       14, 9,10,10,12,12,10,11,12,13,13,10,11,10,13,12,
+       12,13,13,14,15,12,13,12,14,13,12,12,12,14,14,12,
+       12,13,13,14,13,13,13,15,14,14,13,14,13,16,14,15,
+       15,16,16,11,12,12,13,14,12,13,13,14,15,12,13,12,
+       14,13,14,14,15,15,16,13,14,13,15,13, 8, 9, 9,11,
+       11, 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,
+       11,12,11,14,13, 9,10,10,12,12,10,11,11,13,13,10,
+       11,11,13,13,12,12,13,14,15,12,13,13,15,14, 9,10,
+        9,12,11,10,11,10,13,12,10,11,10,13,12,12,13,12,
+       14,14,12,13,12,15,13,11,12,12,13,14,12,13,13,14,
+       14,12,13,13,14,14,14,14,14,14,16,14,14,14,16,15,
+       11,12,11,14,12,12,13,12,15,13,12,13,12,15,13,14,
+       14,14,16,15,13,14,13,16,14,10,11,12,13,14,12,12,
+       13,13,15,12,13,13,14,14,14,14,15,15,16,14,14,14,
+       15,16,12,12,13,14,14,12,13,14,14,15,13,14,14,15,
+       15,14,15,15,15,17,15,15,15,16,16,12,12,13,13,14,
+       13,13,14,14,15,12,13,13,14,15,15,15,15,15,17,14,
+       15,15,15,15,14,14,14,16,16,14,15,15,15,16,15,15,
+       15,16,16,16,15,16,16,18,16,16,17,17,17,14,14,14,
+       15,16,15,15,15,16,17,14,15,14,16,16,16,16,17,17,
+       18,16,16,15,17,16,10,12,11,14,13,12,12,12,14,14,
+       11,13,12,14,13,13,14,14,15,15,13,14,13,16,15,12,
+       12,13,14,14,12,13,13,15,15,13,13,13,15,15,14,15,
+       15,16,16,14,15,15,17,16,12,13,12,14,12,13,13,13,
+       15,13,12,13,12,15,13,14,15,15,16,15,14,15,14,16,
+       14,14,14,14,16,16,14,15,15,16,16,14,15,15,16,16,
+       15,16,16,16,17,16,17,16,18,17,13,14,14,16,13,14,
+       15,15,16,14,14,15,14,16,14,16,16,16,17,16,15,16,
+       15,18,15, 9,11,11,13,13,11,12,12,14,14,11,12,12,
+       14,14,13,14,14,15,15,13,14,14,15,15,11,12,12,14,
+       14,11,12,13,14,15,12,13,13,15,14,13,14,14,15,16,
+       13,14,14,16,16,11,12,12,14,14,12,13,13,15,15,12,
+       13,13,15,14,14,14,14,16,16,14,15,14,16,15,12,13,
+       13,14,15,12,13,14,15,16,13,14,14,16,16,14,14,15,
+       16,17,15,15,15,17,17,13,14,14,15,15,14,15,14,16,
+       16,14,15,14,16,15,15,16,16,17,17,15,16,15,17,16,
+       10,12,12,13,14,11,12,13,14,14,12,13,12,14,14,13,
+       14,14,15,16,13,14,14,16,15,11,12,12,14,14,12,12,
+       13,14,15,12,13,13,15,15,13,13,15,15,17,14,14,15,
+       16,16,12,13,12,14,14,12,13,13,15,15,12,13,13,15,
+       14,14,15,15,16,16,14,15,14,16,16,13,12,14,13,16,
+       13,13,15,14,16,14,13,15,15,16,14,14,16,15,17,15,
+       15,16,16,17,13,14,14,16,15,14,15,15,16,16,14,15,
+       14,16,15,16,16,16,17,17,15,16,16,18,16,10,12,12,
+       14,14,12,12,13,14,14,12,13,12,15,14,13,14,14,15,
+       16,14,15,14,16,15,11,12,12,14,14,12,13,13,14,15,
+       13,14,13,15,15,14,14,15,15,16,14,15,15,17,16,12,
+       13,13,14,14,13,13,14,15,15,12,14,13,15,15,14,15,
+       15,16,16,14,15,15,17,15,13,14,13,15,15,13,14,14,
+       15,16,14,15,14,17,16,15,15,15,15,17,16,16,16,18,
+       17,14,14,14,16,16,15,15,15,16,16,14,15,14,16,16,
+       16,16,17,17,17,16,16,16,17,16,11,12,13,14,14,12,
+       13,13,15,15,12,13,13,15,15,14,15,15,16,16,14,15,
+       15,17,16,12,13,13,14,15,13,13,14,14,16,13,14,14,
+       15,16,15,14,16,15,17,15,15,16,16,17,12,13,13,15,
+       15,13,14,14,16,16,13,14,14,16,15,15,15,16,17,17,
+       15,16,15,17,16,14,14,15,13,16,15,14,16,14,17,15,
+       15,16,14,17,16,15,17,15,18,16,16,17,16,18,14,15,
+       15,17,16,15,16,16,17,17,15,16,15,17,16,16,17,17,
+       18,18,16,17,15,18,16,11,12,12,14,14,13,13,14,14,
+       15,13,14,13,16,14,15,15,15,16,16,15,16,15,17,16,
+       12,13,13,15,14,13,13,14,15,15,14,15,14,16,15,15,
+       15,16,15,16,16,16,16,18,16,12,13,13,15,15,14,14,
+       15,15,16,13,14,13,16,15,16,16,16,17,17,15,16,15,
+       17,15,14,15,14,16,15,14,15,15,16,16,15,16,15,17,
+       16,16,15,16,15,17,17,18,17,18,17,15,15,15,16,16,
+       16,16,16,17,17,14,15,15,17,16,17,17,18,18,18,16,
+       17,15,18,15, 9,11,11,13,13,11,12,12,14,14,11,12,
+       12,14,14,13,14,14,15,16,13,14,14,15,15,11,12,12,
+       14,14,12,13,13,14,15,12,13,13,14,14,14,14,15,15,
+       16,14,14,14,16,16,11,12,12,14,14,12,13,13,14,15,
+       11,13,12,14,14,13,14,14,16,16,13,14,14,16,15,13,
+       14,14,15,15,14,14,15,15,16,14,15,14,16,16,15,15,
+       16,16,17,15,16,16,17,17,12,13,13,15,15,13,14,14,
+       16,15,12,14,13,16,15,15,16,15,17,17,14,15,15,17,
+       15,10,12,12,14,14,12,12,13,14,15,12,13,12,14,14,
+       14,14,15,15,16,13,14,14,16,16,12,13,13,14,14,13,
+       13,14,14,15,13,14,13,15,15,14,15,15,15,17,14,15,
+       15,16,16,11,12,12,14,14,13,13,14,15,15,12,13,13,
+       15,14,14,15,15,16,17,14,15,14,16,15,14,14,14,16,
+       16,14,15,15,16,16,15,15,15,16,16,15,16,16,16,18,
+       16,17,16,18,17,13,13,14,15,15,14,14,15,16,16,13,
+       14,14,16,15,16,16,17,17,17,15,15,15,17,15,10,12,
+       12,14,13,12,12,13,14,14,11,13,12,14,14,13,14,14,
+       16,16,13,14,14,16,15,12,12,13,14,14,12,13,13,14,
+       15,13,13,13,15,15,14,14,15,16,16,14,15,15,16,16,
+       11,12,12,14,14,12,13,13,15,15,12,13,12,15,14,14,
+       15,14,16,16,13,15,13,16,15,13,14,14,15,16,14,15,
+       15,15,17,14,15,15,16,16,16,15,16,16,17,16,16,16,
+       17,17,13,14,12,16,13,14,15,13,16,15,13,15,13,16,
+       14,15,16,15,17,16,15,16,14,17,15,11,12,12,14,15,
+       13,13,14,14,16,13,14,13,15,14,15,15,16,16,17,15,
+       15,15,16,16,12,13,13,15,15,13,13,14,15,16,14,15,
+       14,16,15,15,15,16,15,17,16,16,16,17,17,12,13,13,
+       14,15,14,14,15,15,16,13,14,13,15,15,16,16,16,17,
+       17,15,16,15,16,15,15,15,15,16,16,14,15,15,16,17,
+       16,16,16,17,17,16,15,17,15,18,17,18,17,18,18,14,
+       14,15,15,17,15,15,16,16,17,14,15,15,16,16,17,17,
+       17,17,18,16,16,15,17,15,11,12,12,14,14,12,13,13,
+       15,15,12,13,13,15,15,14,15,15,16,16,14,15,14,17,
+       16,13,13,13,15,15,13,14,14,15,16,13,14,14,16,16,
+       15,15,16,16,17,15,16,16,17,17,12,13,13,15,14,13,
+       14,14,16,15,13,14,13,16,14,15,16,16,17,16,15,16,
+       14,17,15,14,15,15,16,17,15,15,16,16,17,15,16,16,
+       17,17,16,15,17,16,18,16,17,17,18,18,14,15,14,16,
+       13,15,16,15,17,14,15,16,14,17,14,16,17,16,18,16,
+       16,17,15,18,15,
+};
+
+static const static_codebook _44p9_p5_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p9_p5_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44p9_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p5_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44p9_p5_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44p9_p5_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44p9_p5_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44p9_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p6_0[] = {
+        2, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 8, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 8, 5, 7, 8, 8, 9,
+       10, 8, 9,10, 8, 9,10,10,10,12,10,11,11, 8,10,10,
+       10,11,12,10,11,10, 5, 8, 7, 8,10,10, 8,10, 9, 8,
+       10,10,10,10,11,10,12,11, 8,10, 9,10,11,11,10,12,
+       10, 5, 8, 8, 7, 9,10, 8,10, 9, 7, 9,10, 9,10,11,
+        9,11,11, 8,10, 9,10,11,11, 9,11,10, 7, 9, 9, 9,
+       10,11, 9,11,11, 9, 9,11,10,10,13,11,12,12, 9,11,
+       11,11,12,13,11,13,11, 7, 9, 9, 9,10,11, 9,11,10,
+        9,11,10,10,10,12,11,13,12, 9,11,11,11,12,12,10,
+       12,10, 5, 8, 8, 8, 9,10, 7,10, 9, 8, 9,10, 9,10,
+       11,10,11,11, 7,10, 9, 9,11,11, 9,11,10, 7, 9, 9,
+        9,10,11, 9,11,10, 9,11,11,10,10,12,11,12,12, 9,
+       10,11,11,12,13,10,12,10, 7, 9, 9, 9,11,11, 9,11,
+       10, 9,11,11,11,11,13,11,13,12, 9,11, 9,11,12,12,
+       10,13,10,
+};
+
+static const static_codebook _44p9_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p6_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44p9_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p6_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44p9_p6_1[] = {
+        6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7,
+        8, 8, 7, 8, 7, 7, 8, 8, 7, 8, 8, 7, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+        8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 8, 8,
+        8, 8, 9, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 9, 8, 8, 8, 8, 8, 9, 9, 8,
+        9, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 8, 9, 9, 8,
+        8, 8, 8, 8, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 9, 9, 8, 9, 9, 8, 8, 8, 8, 9, 8,
+        8, 9, 8,
+};
+
+static const static_codebook _44p9_p6_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44p9_p6_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44p9_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_p7_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_p7_0[] = {
+        1,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+       12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+       13,13,13,13,13,
+};
+
+static const static_codebook _44p9_p7_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p9_p7_0,
+       1, -510105088, 1635281408, 3, 0,
+       (long *)_vq_quantlist__44p9_p7_0,
+       0
+};
+
+static const long _vq_quantlist__44p9_p7_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44p9_p7_1[] = {
+        1, 4, 4,16,16, 4, 9,11,15,16, 4,12, 8,16,16,12,
+       16,16,16,16,13,16,16,16,16, 5, 8,10,16,16, 9, 9,
+       14,15,16,12,14,14,16,16,16,16,16,16,16,16,16,16,
+       16,16, 5,11, 8,16,15,12,14,16,16,16, 9,15, 9,16,
+       16,16,16,16,16,16,16,16,16,16,16,15,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16, 6,11,11,
+       16,16,12,13,16,16,16,12,16,14,16,16,16,16,16,16,
+       16,16,16,16,16,16,11,15,15,16,16,14,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,12,
+       15,16,16,16,16,16,16,16,16,14,16,15,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16, 5,11,11,16,16,12,
+       15,16,16,16,12,16,14,16,16,16,16,16,16,16,16,16,
+       16,16,16,12,15,15,16,16,14,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,11,15,15,16,
+       16,16,16,16,16,16,15,16,14,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16, 6,11,12,16,16,11,15,16,16,16,13,16,14,16,16,
+       16,16,16,16,16,16,16,16,16,16,11,16,14,16,16,14,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,12,14,14,16,16,16,16,16,16,16,15,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16, 8,13,
+       15,16,16,15,15,16,16,16,14,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,14,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16, 7,12,12,16,16,
+       13,12,16,16,16,14,16,14,16,16,16,16,16,16,16,16,
+       16,16,16,16,13,16,16,16,16,14,14,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,12,14,16,
+       16,16,16,16,16,16,16,14,16,14,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16, 6,11,11,16,16,13,15,16,16,16,11,15,14,16,
+       16,16,16,16,16,16,14,16,16,16,16,11,16,16,16,16,
+       16,16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,11,16,14,16,16,14,16,16,16,16,13,15,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 7,
+       11,11,16,16,13,13,16,16,16,13,16,13,16,16,16,16,
+       16,16,16,16,16,16,16,16,12,16,15,16,16,14,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,12,14,16,16,16,16,16,16,16,16,14,16,13,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16, 8,13,14,16,
+       16,15,16,16,16,16,14,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,16,
+       15,16,16,16,16,16,16,16,16,16,15,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+       16,16,16,16,16,
+};
+
+static const static_codebook _44p9_p7_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44p9_p7_1,
+       1, -514619392, 1630767104, 3, 0,
+       (long *)_vq_quantlist__44p9_p7_1,
+       0
+};
+
+static const long _vq_quantlist__44p9_p7_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p9_p7_2[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9,10,10,10,11,11,11,
+       12,12,12,13,13,13,13,13,13,
+};
+
+static const static_codebook _44p9_p7_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p9_p7_2,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44p9_p7_2,
+       0
+};
+
+static const long _vq_quantlist__44p9_p7_3[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44p9_p7_3[] = {
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44p9_p7_3 = {
+       1, 25,
+       (char *)_vq_lengthlist__44p9_p7_3,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44p9_p7_3,
+       0
+};
+
+static const char _huff_lengthlist__44p9_short[] = {
+        3, 3, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _huff_book__44p9_short = {
+       1, 8,
+       (char *)_huff_lengthlist__44p9_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44pn1_l0_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__44pn1_l0_0[] = {
+        1, 3, 3, 8, 8,10,10,10,10,10,10,10,10, 5, 7, 5,
+        9, 8,10,10,10,10,11,10,11,10, 5, 5, 7, 8, 9,10,
+       10,11,10,10,11,10,11,10,10,10,11,11,11,11,11,11,
+       11,10,11,11,10,10,10,10,11,11,11,11,11,10,11,11,
+       11,11,11,11,11,11,12,11,10,11,11,11,11,11,11,11,
+       11,11,11,11,11,10,10,11,11,12,11,11,11,11,11,11,
+       12,11,11,11,10,11,11,11,11,11,11,11,11,10,11,11,
+       10,11,10,11,11,11,11,11,11,11,11,11,11,12,11,11,
+       12,12,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
+       10,11,11,11,11,11,11,11,12,11,13,11,11,11,11,11,
+       11,11,11,11,11,11,12,11,13,
+};
+
+static const static_codebook _44pn1_l0_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__44pn1_l0_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__44pn1_l0_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_l0_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44pn1_l0_1[] = {
+        1, 4, 4, 7, 7, 4, 5, 6, 7, 7, 4, 6, 5, 7, 7, 7,
+        6, 7, 6, 7, 7, 7, 6, 7, 6,
+};
+
+static const static_codebook _44pn1_l0_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__44pn1_l0_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44pn1_l0_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_l1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_l1_0[] = {
+        1, 4, 4, 4, 4, 4, 4, 4, 4,
+};
+
+static const static_codebook _44pn1_l1_0 = {
+       2, 9,
+       (char *)_vq_lengthlist__44pn1_l1_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44pn1_l1_0,
+       0
+};
+
+static const char _huff_lengthlist__44pn1_lfe[] = {
+        1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book__44pn1_lfe = {
+       2, 4,
+       (char *)_huff_lengthlist__44pn1_lfe,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const char _huff_lengthlist__44pn1_long[] = {
+        2, 3, 6, 7, 9,13,17, 3, 2, 5, 7, 9,13,17, 6, 5,
+        5, 6, 9,12,16, 7, 7, 6, 6, 7,10,13,10,10, 9, 7,
+        6,10,13,13,13,12,10,10,11,15,17,17,17,14,14,15,
+       17,
+};
+
+static const static_codebook _huff_book__44pn1_long = {
+       2, 49,
+       (char *)_huff_lengthlist__44pn1_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p1_0[] = {
+        1, 2, 2, 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, 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, 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, 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, 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,
+        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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44pn1_p1_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44pn1_p1_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p2_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p2_0[] = {
+        1, 5, 5, 0, 7, 7, 0, 8, 8, 0, 9, 9, 0,12,12, 0,
+        8, 8, 0, 9, 9, 0,13,13, 0, 8, 8, 0, 6, 6, 0,11,
+       11, 0,12,12, 0,12,12, 0,14,14, 0,11,12, 0,12,12,
+        0,15,15, 0,12,12, 0, 5, 5, 0, 5, 5, 0, 6, 6, 0,
+        7, 7, 0,10,10, 0, 6, 6, 0, 7, 7, 0,11,11, 0, 6,
+        6, 0, 7, 7, 0,11,11, 0,12,11, 0,11,11, 0,14,14,
+        0,10,10, 0,12,12, 0,15,15, 0,12,12, 0, 6, 6, 0,
+       12,12, 0,12,12, 0,12,12, 0,14,14, 0,11,11, 0,12,
+       12, 0,16,16, 0,12,12, 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,
+        0, 0, 0, 8, 8, 0,12,12, 0,12,12, 0,12,12, 0,15,
+       15, 0,12,12, 0,11,11, 0,16,16, 0,11,11, 0, 6, 6,
+        0,12,12, 0,12,12, 0,13,13, 0,15,15, 0,12,12, 0,
+       13,13, 0,15,15, 0,12,12, 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, 0, 0,
+};
+
+static const static_codebook _44pn1_p2_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p2_0,
+       1, -533200896, 1614282752, 2, 0,
+       (long *)_vq_quantlist__44pn1_p2_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p2_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p2_1[] = {
+        1, 3, 3, 0, 9, 9, 0, 9, 9, 0,10,10, 0, 9, 9, 0,
+       10,10, 0,10,10, 0,10,10, 0,10,10, 0, 7, 7, 0, 7,
+        7, 0, 6, 6, 0, 8, 8, 0, 7, 7, 0, 8, 8, 0, 8, 8,
+        0, 7, 7, 0, 8, 8, 0, 7, 7, 0, 9, 9, 0, 8, 9, 0,
+       10,10, 0, 9, 9, 0,10,10, 0,10,11, 0, 9, 9, 0,10,
+       10, 0, 9, 9, 0,11,11, 0,12,12, 0,12,12, 0,11,11,
+        0,12,12, 0,13,13, 0,12,12, 0,13,13, 0, 8, 8, 0,
+       12,12, 0,12,12, 0,13,13, 0,13,13, 0,13,13, 0,13,
+       13, 0,13,13, 0,13,13, 0, 7, 7, 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, 9, 9, 0,11,11, 0,12,12, 0,13,13, 0,12,
+       12, 0,13,13, 0,13,13, 0,12,12, 0,12,12, 0, 9, 9,
+        0,12,12, 0,13,13, 0,14,14, 0,13,13, 0,14,14, 0,
+       14,14, 0,13,13, 0,14,14, 0, 7, 7, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,
+};
+
+static const static_codebook _44pn1_p2_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p2_1,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__44pn1_p2_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p3_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p3_0[] = {
+        1, 6, 6, 6, 8, 8, 6, 8, 8, 7, 9, 9,10,11,11, 8,
+        8, 8, 7, 9, 9,11,12,12, 9, 9, 9, 6, 7, 7,10,11,
+       11,10,11,11,10,11,11,13,13,13,12,12,12,10,12,11,
+       14,14,14,12,12,12, 6, 5, 5, 9, 6, 6, 9, 6, 6, 9,
+        7, 7,12,10,10,11, 7, 6, 9, 7, 7,13,11,11,12, 7,
+        7, 7, 8, 8,12,10,10,12,10,10,11,10,10,15,13,13,
+       13, 9, 9,12,11,11,15,14,14,15,11,11, 8, 7, 7,12,
+       11,11,12,11,11,11,11,11,14,13,14,14,12,12,12,11,
+       11,16,15,15,14,12,12, 0,10,10, 0,12,12, 0,12,12,
+        0,11,11, 0,14,14, 0,11,11, 0,11,11, 0,15,15, 0,
+       11,11, 7, 8, 8,13,11,11,12,10,10,12,11,11,15,13,
+       13,14,11,11,12,10,10,16,14,14,15,10,10, 9, 7, 7,
+       13,11,12,13,12,11,12,11,11,15,14,14,14,12,12,13,
+       12,12,16,15,15,15,12,12, 0,11,11, 0,12,12, 0,12,
+       13, 0,12,12, 0,15,15, 0,12,12, 0,12,12, 0,16,15,
+        0,12,12,
+};
+
+static const static_codebook _44pn1_p3_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p3_0,
+       1, -531365888, 1616117760, 2, 0,
+       (long *)_vq_quantlist__44pn1_p3_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p3_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44pn1_p3_1[] = {
+        2, 3, 4, 9, 9,10,12,12,12,11,10,12,12,13,12,11,
+       13,12,11,11,11,12,12,12,11,11,13,13,13,13,11,12,
+       12,14,14,12,13,13,13,13,11,13,13,13,13,11,13,13,
+       13,13,11,13,13,13,13,11,12,12,14,14,12,13,13,12,
+       12,11,13,13,13,13,11,13,13,12,12,11,13,13,13,13,
+       12,12,13,14,14,12,13,13,12,12,11,13,13,13,13,11,
+       13,13,12,12,11,13,13,13,13,12,13,13,14,14,12,13,
+       13,12,12,11,13,13,13,13,11,13,13,12,12,11,10,10,
+       10,10,12,10,10,11,11,12, 9, 9,11,11,13,11,11,10,
+       10,13,10,10,10,10,13,11,11,12,12,13,10,10,12,12,
+       14,12,11,12,12,13,11,11,11,12,13,12,12,12,12,13,
+       11,11,12,12,13,10,10,12,12,14,11,11,12,12,13,11,
+       11,12,12,13,11,11,12,12,14,12,12,12,12,14,10,10,
+       11,11,14,12,11,11,11,13,11,11,11,11,13,12,12,11,
+       11,14,12,12,12,11,14,10,10,11,11,14,12,11,11,11,
+       13,11,11,11,11,13,12,12,11,11,11,11,11,10,10,12,
+       10,11, 9, 9,12,12,12,11,11,13,12,12, 9, 9,13,13,
+       13,10,10,13,13,13,12,12,13,13,13,14,14,13,12,12,
+       11,11,14,13,13,12,12,14,13,13,11,11,13,13,13,12,
+       11,13,13,13,14,14,13,12,12,10,10,14,13,13,11,11,
+       13,13,13,10,10,13,13,13,11,11,14,13,13,14,14,14,
+       12,12,10,10,13,13,13,11,11,13,13,13,10,10,13,13,
+       13,11,11,14,13,13,14,14,14,13,13,10,10,13,13,13,
+       11,11,13,13,13,10,10,14,12,12, 8, 8,14,12,12, 9,
+        9,14,11,11, 9, 9,14,12,12, 8, 8,14,12,12, 7, 7,
+       15,13,13,10,10,15,12,12,10,10,15,13,13,10,10,15,
+       12,13, 9, 9,15,13,13,10,10,15,13,13,10,10,15,12,
+       12,10,10,15,13,13,10,10,15,13,13, 9, 9,15,13,13,
+       10,10,15,13,13,10,10,15,12,12,10,10,15,13,13, 9,
+        9,14,13,12, 9, 9,14,13,13, 9, 9,15,13,13,10,10,
+       15,12,12,10,10,15,13,13, 9, 9,15,13,13, 9, 9,14,
+       13,13, 9, 9,14,12,12, 8, 8,13,13,13, 8, 8,14,14,
+       13, 9, 9,14,14,13, 7, 7,14,14,14, 8, 8,14,14,14,
+       10,10,15,14,14,12,12,14,14,14, 9, 9,15,14,14,10,
+       10,14,14,14, 9, 9,14,14,14,10, 9,15,14,14,12,12,
+       14,14,14, 9, 9,15,14,14,10,10,14,14,14, 9, 9,15,
+       14,15, 9, 9,15,14,14,11,11,14,14,14, 8, 8,14,14,
+       14, 9, 9,14,14,14, 8, 8,14,15,14,10,10,15,14,14,
+       11,11,14,14,14, 8, 8,15,14,14, 9, 9,14,14,14, 8,
+        8,12,12,12,13,13,16,16,15,12,12,17,16,16,13,13,
+       17,16,16,11,11,17,16,16,12,12,17,16,17,13,13,17,
+       16,16,14,14,17,17,16,12,12,18,16,16,13,13,17,16,
+       17,12,12,17,17,17,13,13,18,16,16,14,14,18,17,17,
+       12,12,17,17,17,13,13,18,17,17,13,13,17,17,17,13,
+       13,17,16,16,14,14,17,17,17,12,12,16,16,17,13,13,
+       17,17,16,12,12,18,17,17,13,13,18,16,16,14,14,18,
+       17,17,12,12,19,16,17,13,13,17,16,17,12,12,13,14,
+       14,10,10,16,14,14,13,13,17,15,15,14,14,17,14,14,
+       13,13,16,14,14,13,13,17,16,15,14,14,16,16,16,15,
+       15,17,15,15,14,14,17,15,15,14,14,17,15,15,14,14,
+       17,16,15,14,14,16,16,16,15,15,18,15,15,13,13,16,
+       16,15,14,14,17,15,15,14,13,17,15,15,14,14,16,16,
+       16,15,15,18,15,14,13,13,17,15,15,14,14,18,14,15,
+       13,13,18,15,15,14,14,16,16,16,15,15,17,15,15,13,
+       13,17,15,15,14,14,17,15,15,13,13,13,11,11,10,10,
+       16,14,14,13,13,17,14,15,14,14,17,15,15,12,12,17,
+       14,14,12,12,16,15,15,14,14,16,14,14,14,14,16,15,
+       15,14,14,16,15,15,14,14,16,15,15,14,14,16,15,15,
+       14,14,16,15,14,15,15,17,15,15,14,14,17,15,15,14,
+       14,17,15,15,14,14,17,15,16,14,14,16,14,14,14,14,
+       17,15,15,13,13,17,15,15,13,13,16,15,15,13,13,17,
+       16,16,14,14,17,15,14,15,14,17,15,15,13,13,17,15,
+       15,13,13,17,15,15,13,13,14,14,14, 9, 9,14,14,14,
+       18,19,14,15,15,19,18,14,14,14,19,19,15,14,14,19,
+       19,15,16,16,19,19,15,16,16,19,19,15,15,15,19,19,
+       15,16,16,19,20,15,15,15,19,19,15,15,15,19,19,15,
+       16,16,20,20,15,15,15,18,19,15,15,16,19,20,15,15,
+       15,19,18,15,15,15,18,18,15,16,16,21,20,15,15,15,
+       19,19,15,15,15,19,19,15,15,14,19,20,15,15,15,20,
+       19,15,16,16,19,20,15,15,15,19,19,15,15,15,20,21,
+       15,14,15,19,19,14,12,12, 9, 9,14,14,15,21,19,14,
+       14,14,18,19,14,15,15,19,20,14,14,14,19,19,15,15,
+       15,19,20,15,15,14,21,19,15,15,15,20,19,15,14,15,
+       20,21,15,15,15,18,18,15,15,15,20,21,16,14,14,18,
+       19,15,15,15,20,19,15,15,15,18,21,15,15,15,19,19,
+       15,15,15,19,20,16,15,14,20,19,15,16,15,19,19,15,
+       15,15,19, 0,14,15,15,19,19,15,15,15,19,19,15,15,
+       14,20,19,15,15,15,20,19,15,15,15,19,19,15,15,15,
+       20,19,12,12,12,13,13,16,15,16,11,11,16,16,16,12,
+       12,17,16,16,11,11,17,16,16,12,11,17,17,17,13,13,
+       18,16,16,14,14,18,18,17,13,13,17,16,16,13,13,17,
+       17,17,13,13,17,16,17,12,12,17,15,16,13,13,17,16,
+       17,12,12,17,16,16,13,12,17,16,16,12,12,18,17,17,
+       13,13,18,16,16,13,14,18,17,17,12,12,17,16,16,12,
+       12,17,17,17,12,12,18,17,17,13,13,17,16,16,14,14,
+       17,17,17,12,12,17,16,16,12,12,18,17,17,12,12,13,
+       14,14, 9, 9,16,14,14,13,13,16,15,15,14,14,16,14,
+       14,13,13,16,14,14,13,13,17,16,15,15,15,16,15,16,
+       16,15,17,15,15,14,14,17,15,15,15,15,17,15,15,14,
+       14,17,15,15,14,14,16,15,16,16,16,17,15,15,14,14,
+       16,15,15,14,15,16,15,15,14,14,17,15,15,15,15,16,
+       16,16,15,16,18,15,14,13,14,17,15,15,14,14,17,14,
+       14,13,13,17,15,15,14,14,16,15,15,15,15,17,15,14,
+       14,14,17,15,15,14,14,17,14,14,13,13,13,11,11,11,
+       11,16,14,14,12,12,16,14,14,13,13,16,14,14,12,12,
+       16,14,14,12,12,16,15,15,13,13,17,14,14,14,14,17,
+       15,15,13,13,16,15,15,14,13,16,15,15,13,13,16,15,
+       15,13,13,16,14,14,14,14,16,15,15,13,13,16,14,15,
+       13,13,17,15,15,13,13,17,15,15,13,13,16,14,14,14,
+       14,17,15,15,12,12,17,14,15,13,13,17,15,15,12,12,
+       16,15,15,13,13,17,14,14,14,14,17,15,15,12,12,17,
+       15,15,13,13,16,15,15,12,12,14,15,15, 8, 8,14,14,
+       14,19,18,14,15,15,19,20,14,14,14,19,19,14,14,15,
+       19,20,15,16,15,19,21,15,16,16,21,19,15,15,15,20,
+       19,15,16,16,19,20,15,15,15,19,18,15,16,15,20,19,
+       15,16,16,19,20,15,15,15,19,19,15,16,15,20,20,14,
+       15,15,19,19,15,15,15,21,19,15,17,16,19,20,15,14,
+       15, 0,21,15,15,15,19,20,14,14,14,19,19,15,15,15,
+       20,19,15,16,16,19,19,15,15,15,19,18,15,15,15,20,
+       19,14,14,15,18,18,14,12,12, 9, 9,14,14,14,18,18,
+       14,14,14,18,18,14,15,14,19,18,14,14,14,19,18,15,
+       15,15,19,20,15,14,14,18,18,15,15,15,20,19,15,15,
+       15,18,20,15,15,15,19,18,15,15,15,19,19,15,14,14,
+       19,21,15,15,15,20,20,15,15,15,18,19,14,15,15,19,
+       20,15,15,15,20,19,15,14,14,19,21,15,15,15,18,19,
+       15,14,15,20,19,14,15,15,21,21,14,15,15,19,20,15,
+       14,14,19,20,15,15,15,19,20,15,15,14,20,20,14,15,
+       15,20,19,13,12,12,13,13,17,16,16,11,11,17,16,16,
+       12,12,18,17,16,11,11,18,16,16,11,11,17,17,17,13,
+       13,18,16,16,13,13,18,17,17,12,12,18,16,16,13,13,
+       18,17,17,12,12,18,17,17,13,13,18,16,16,14,14,18,
+       16,17,12,12,18,17,17,13,13,17,17,17,12,12,17,17,
+       17,12,12,17,16,15,13,13,18,16,16,11,11,17,16,16,
+       12,12,17,16,17,11,11,18,17,17,13,12,17,16,16,13,
+       13,17,17,17,12,12,17,16,17,12,12,18,17,17,11,11,
+       14,14,14, 9, 9,16,14,14,13,13,17,15,15,14,14,17,
+       14,14,13,13,16,14,14,13,13,17,15,15,14,14,16,16,
+       16,16,15,18,15,15,14,14,17,16,15,15,15,17,15,15,
+       14,14,17,15,15,14,15,16,16,16,15,16,18,15,15,14,
+       14,17,15,15,14,15,17,15,15,14,14,17,15,15,14,14,
+       16,16,16,15,16,17,14,14,13,13,17,15,15,14,14,18,
+       15,15,13,13,17,15,15,14,14,16,16,16,15,15,17,14,
+       14,13,13,17,15,15,14,14,17,14,14,13,13,13,11,11,
+       11,11,16,14,14,12,12,16,14,14,12,13,17,15,14,11,
+       11,17,14,14,11,11,17,15,15,13,14,17,14,14,14,14,
+       17,15,15,13,13,17,14,14,13,13,17,15,15,13,13,17,
+       15,15,13,13,17,14,14,14,14,17,15,15,13,13,18,14,
+       15,13,13,17,15,15,13,13,16,15,15,13,13,17,14,14,
+       13,13,17,15,15,12,12,16,14,14,12,12,16,15,15,12,
+       12,17,16,15,13,13,17,14,14,13,13,17,15,15,12,12,
+       16,15,15,12,12,16,15,15,12,12,13,15,15, 8, 8,14,
+       14,14,18,19,14,15,15,19,20,14,14,14,18,18,14,15,
+       15,18,18,15,16,16,19,19,15,16,17,20,20,15,15,15,
+       19,19,15,16,16,18,20,15,15,15,19,19,15,15,16,18,
+       18,15,17,16,19,19,15,15,15,18,21,15,16,16,21,20,
+       15,15,15,19,21,15,16,15,20,19,15,16,17,20,20,15,
+       15,15,19,19,15,16,16,21,20,15,15,15,19,20,15,15,
+       15,19,19,15,16,16,20,19,15,15,15,19,19,15,16,15,
+       20,21,15,15,15,21,19,14,12,12, 8, 8,14,14,14,20,
+       18,14,13,13,19,19,14,14,14,19,18,15,14,14,19,20,
+       14,15,15,20,20,15,14,14,21,20,15,15,15,20,20,15,
+       15,14,21,19,15,15,15,19,19,15,15,15,19,20,15,14,
+       14,20,20,15,15,15,19,20,15,14,14,19,20,15,15,15,
+       20,20,15,15,15,20,19,15,14,14,20,21,15,15,15,20,
+       21,15,14,14,20, 0,15,16,15,20,21,15,15,15,19,20,
+       15,14,14,19,19,15,15,15,19,20,15,15,15,19,19,15,
+       15,15,18,20,13,12,12,13,13,18,16,17,12,12,17,16,
+       16,12,12,17,17,16,11,11,18,16,16,11,11,17,17,18,
+       13,13,18,16,16,14,14,18,17,17,13,13,18,16,16,13,
+       13,18,17,17,12,12,17,17,16,13,13,17,16,16,13,14,
+       18,17,17,12,12,18,16,16,12,13,17,16,17,12,12,17,
+       18,17,13,13,18,16,16,13,13,18,17,17,12,12,17,16,
+       16,12,12,17,17,17,11,11,17,16,17,12,12,17,16,16,
+       13,13,17,16,16,11,11,17,16,16,12,12,18,16,17,11,
+       11,14,14,14, 9, 9,16,14,15,13,13,17,15,15,14,14,
+       17,14,14,12,12,16,14,14,13,13,18,15,15,15,15,17,
+       15,16,15,16,18,15,15,14,14,17,15,16,15,15,17,15,
+       15,14,14,18,15,15,14,14,16,16,16,16,15,17,15,15,
+       14,14,16,15,15,14,14,17,15,15,14,14,17,15,15,14,
+       14,17,16,16,15,15,17,15,14,13,13,17,15,15,14,14,
+       17,15,15,13,13,17,15,15,14,14,16,16,16,15,15,18,
+       15,14,14,14,17,15,15,14,14,18,15,15,13,13,13,12,
+       12,11,11,16,14,14,12,12,16,14,14,13,13,17,15,15,
+       12,12,17,14,14,12,12,17,15,15,14,14,17,14,14,14,
+       14,17,15,15,13,13,17,15,14,13,13,17,15,15,13,13,
+       17,15,15,13,13,16,14,14,14,14,17,15,15,13,13,16,
+       14,14,13,13,16,15,15,13,13,17,15,16,13,13,17,14,
+       14,14,13,17,15,15,12,12,16,15,14,12,12,17,15,15,
+       12,12,16,15,16,13,13,16,14,14,14,13,17,15,15,12,
+       12,16,14,14,12,12,17,15,15,12,12,14,15,15, 8, 8,
+       14,14,14,18,18,14,15,15,19,18,14,14,14,18,18,14,
+       15,15,19,20,15,16,15,21,18,15,16,16,18, 0,15,15,
+       15,19,20,15,16,16,20, 0,15,16,15,19,18,15,15,15,
+       19,19,15,16,16,21,19,15,15,15,19,19,15,16,16,20,
+       20,15,15,15,19,19,15,15,15,19,18,15,16,16,20,20,
+       15,14,15,20,19,15,15,15,19,20,15,15,15,19,19,15,
+       16,15,19,20,15,16,16,19,20,15,15,15,19,19,15,16,
+       15,20,20,15,15,15,20,18,13,12,12, 8, 8,14,14,14,
+       19,20,14,14,14,19,19,14,15,15,20,20,14,14,14,18,
+       19,15,15,15,20, 0,15,14,14,18,20,15,15,15,19,19,
+       15,15,15,21,19,15,15,15,19,20,15,15,15,20,21,15,
+       14,14,20,19,15,15,15,20,19,15,15,14,21,19,15,15,
+       15,19,18,15,15,15,20,19,15,14,14,19,19,15,15,16,
+       20,19,15,15,15,20, 0,15,15,15,19,21,15,15,15,22,
+       20,15,14,14,22,19,15,15,15,19,20,15,14,14,20,19,
+       14,15,15,19,21,
+};
+
+static const static_codebook _44pn1_p3_1 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44pn1_p3_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44pn1_p3_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p4_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__44pn1_p4_0[] = {
+        1, 7, 7,14,14, 6, 8, 8,15,16, 7, 8, 8,16,15, 0,
+       14,14,17,17, 0,14,14,16,16, 7, 9, 9,16,16,10,11,
+       11,17,18, 9, 8, 8,16,16, 0,14,14,19,19, 0,14,14,
+       17,16, 8, 9, 9,16,16,12,12,12,17,17,10, 9, 9,16,
+       16, 0,15,14,18,20, 0,14,14,17,17, 0,15,15,18,17,
+        0,21, 0, 0,21, 0,13,13,17,17, 0,17,17, 0, 0, 0,
+       15,15,17,17, 0,15,15,17,18, 0, 0, 0, 0,21, 0,13,
+       13,17,17, 0,18,18, 0,21, 0,16,15,17,18, 6, 7, 7,
+       14,14, 9,10,10,16,16,11,10,10,15,15, 0,21, 0,20,
+       21, 0, 0, 0,18,20,10,10,10,15,16,12,13,13,18,18,
+       12,11,11,15,15, 0, 0, 0,20,20, 0, 0,21,19,19,12,
+       11,11,15,15,15,14,14,18,18,13,11,11,15,16, 0, 0,
+        0,20,19, 0, 0, 0,20,21, 0, 0,20,19,19, 0, 0, 0,
+        0, 0, 0,20, 0,17,18, 0, 0,21, 0, 0, 0, 0, 0,21,
+        0, 0,21, 0,20,19, 0, 0, 0, 0, 0, 0,21, 0,18,18,
+        0, 0, 0,21, 0, 0, 0, 0, 0,20, 7, 6, 6,13,13, 9,
+        6, 6,12,12, 9, 7, 7,14,14, 0,10,10,12,12, 0,11,
+       11,15,15, 9, 7, 7,14,14,12, 9, 9,14,14,10, 7, 7,
+       14,13, 0,11,11,16,15, 0,11,11,14,14, 9, 7, 7,14,
+       14,13,10,10,14,14,11, 7, 7,14,13, 0,11,11,16,16,
+        0,11,11,14,14, 0,12,12,16,16, 0,19, 0,17,18, 0,
+       10,10,14,14, 0,15,14, 0, 0, 0,12,12,14,14, 0,12,
+       12,15,15, 0,20, 0,18,19, 0,10,10,14,14, 0,16,15,
+        0,20, 0,13,13,14,14, 0,11,11,13,13, 0,12,13,16,
+       16, 0,12,12,16,16, 0,16,16, 0,21, 0,17,18, 0, 0,
+        0,12,12,16,16, 0,15,15,18, 0, 0,12,12,16,16, 0,
+       17,16,21,21, 0,16,17, 0, 0, 0,13,13,17,16, 0,16,
+       16,20,21, 0,12,12,17,16, 0,17,17, 0,21, 0,17,17,
+       21,21, 0,17,18, 0, 0, 0, 0, 0, 0, 0, 0,15,15, 0,
+        0, 0,18,21, 0, 0, 0,18,19, 0, 0, 0,18,17,21,21,
+        0, 0, 0, 0, 0, 0,16,16, 0, 0, 0, 0, 0, 0, 0, 0,
+       19,19, 0, 0, 0,11,11,12,12, 0,11,11,10,10, 0,12,
+       12,13,13, 0,12,12, 9, 9, 0,14,14,13,13, 0,12,12,
+       13,13, 0,14,14,12,13, 0,11,11,12,12, 0,13,13,13,
+       13, 0,13,13,13,13, 0,12,12,13,13, 0,14,14,12,12,
+        0,11,11,12,12, 0,14,13,14,14, 0,13,13,13,13, 0,
+       15,15,14,15, 0, 0, 0,16,16, 0,12,12,13,13, 0,16,
+       17,20,21, 0,14,13,12,12, 0,14,14,14,14, 0,21, 0,
+       16,16, 0,12,12,13,13, 0,18,17,21, 0, 0,14,14,13,
+       13, 7, 8, 8,17,17,11,10,10,18,18,12,10,10,17,17,
+        0,15,15,20,18, 0,15,15,17,17,11, 9, 9,17,17,14,
+       12,12,19,19,13, 9, 9,16,16, 0,15,14, 0,19, 0,14,
+       14,16,16,12,10,10,20,18,16,13,13,21,20,14,10,10,
+       17,17, 0,15,15,21,20, 0,15,14,17,17, 0,15,15,21,
+       21, 0, 0,21, 0, 0, 0,13,13,18,18, 0,19,16, 0, 0,
+        0,15,15,17,16, 0,16,16, 0,21, 0, 0, 0, 0,21, 0,
+       13,14,18,17, 0,20,19, 0, 0, 0,15,15,18,18, 8, 7,
+        7,15,15,12,11,11,17,16,13,11,11,16,16, 0, 0, 0,
+       21,20, 0, 0, 0, 0,20,11,10,10,17,17,14,13,13,19,
+       18,14,11,11,16,16, 0,20, 0,21,19, 0, 0,21, 0,20,
+       12,11,11,17,17,16,15,15, 0,19,14,11,11,17,16, 0,
+       21, 0, 0,19, 0, 0, 0,21,20, 0, 0,21,20, 0, 0, 0,
+        0, 0, 0, 0, 0, 0,19,21, 0, 0, 0, 0, 0, 0, 0, 0,
+       19,20, 0, 0, 0,20,21, 0, 0, 0, 0, 0, 0,20, 0,19,
+       21, 0, 0, 0, 0, 0, 0, 0, 0,21,20,11,10, 9,15,15,
+       14,11,11,15,15,14,11,11,16,16, 0,14,14,14,14, 0,
+       16,15,17,16,13,11,11,16,16,16,13,13,16,16,15,10,
+       10,15,15, 0,14,15,17,17, 0,14,14,16,15,13,11,11,
+       16,16,17,15,14,16,16,15,10,10,15,15, 0,15,15,17,
+       18, 0,15,15,16,16, 0,16,16,17,17, 0,21, 0,21,20,
+        0,13,13,15,15, 0,18,18, 0,21, 0,15,15,15,15, 0,
+       16,16,17,17, 0, 0, 0, 0,18, 0,13,13,15,15, 0,19,
+       18, 0, 0, 0,15,15,16,16, 0,12,12,15,15, 0,13,13,
+       17,17, 0,13,13,17,18, 0,16,17,21, 0, 0,20,18, 0,
+        0, 0,13,13,17,17, 0,15,15, 0,18, 0,12,12,17,18,
+        0,16,16, 0, 0, 0,17,17,21, 0, 0,13,13,18,18, 0,
+       16,16,21,21, 0,12,12,17,18, 0,16,17,21, 0, 0,17,
+       17, 0,21, 0,17,18, 0, 0, 0, 0, 0, 0, 0, 0,16,15,
+        0,21, 0,21,19, 0, 0, 0,18,18, 0, 0, 0,18,19, 0,
+        0, 0, 0, 0, 0, 0, 0,16,16,21,21, 0,20,19, 0, 0,
+        0,19,21, 0,21, 0,12,12,15,15, 0,12,12,15,16, 0,
+       13,13,16,16, 0,14,14,15,15, 0,16,15,17,17, 0,13,
+       13,17,17, 0,15,15,16,18, 0,12,12,16,16, 0,14,14,
+       17,17, 0,15,14,16,16, 0,13,13,16,16, 0,16,15,17,
+       17, 0,12,12,16,16, 0,15,15,18,18, 0,14,14,17,16,
+        0,16,16,17,18, 0, 0, 0,20,21, 0,13,13,16,17, 0,
+       17,17, 0, 0, 0,15,15,16,16, 0,15,16,17,17, 0, 0,
+        0,19, 0, 0,13,13,15,16, 0,19,18, 0, 0, 0,16,15,
+       16,17, 8, 8, 8,17,17,13,11,10,17,18,13,10,10,17,
+       17, 0,15,15,20,19, 0,15,15,17,17,12,10,10,19,18,
+       15,12,12,20,18,14,10,10,17,16, 0,15,15,20,20, 0,
+       14,15,16,16,13,10,10,17,17,17,14,14, 0,18,15,10,
+       10,17,17, 0,16,15,20,20, 0,14,14,17,17, 0,15,16,
+       20,20, 0, 0,21, 0, 0, 0,13,13,17,17, 0,18,17, 0,
+        0, 0,15,16,17,18, 0,15,15,18,21, 0, 0, 0,21, 0,
+        0,13,13,18,18, 0,19,19, 0, 0, 0,16,16,18,17, 9,
+        8, 8,15,15,12,11,11,16,16,13,11,11,16,15, 0, 0,
+        0, 0,21, 0,21, 0,19,19,12,11,11,17,18,15,13,13,
+       18,19,14,11,11,16,16, 0, 0,21,21,19, 0, 0, 0,21,
+       20,13,11,11,18,17,17,14,15,20,21,15,11,12,16,16,
+        0, 0, 0,20, 0, 0, 0,21, 0,19, 0, 0, 0, 0,19, 0,
+        0, 0, 0, 0, 0,21,21,19,19, 0, 0, 0,21, 0, 0, 0,
+        0,19,21, 0, 0, 0,19,20, 0, 0, 0,21, 0, 0, 0,21,
+       19,19, 0, 0, 0, 0, 0, 0, 0, 0,21,20, 0,11,11,15,
+       15, 0,12,12,15,16, 0,12,12,16,16, 0,15,15,16,15,
+        0,16,16,17,17, 0,12,12,17,17, 0,14,14,17,17, 0,
+       11,11,16,16, 0,15,15,19,18, 0,15,15,16,16, 0,12,
+       12,17,16, 0,14,15,16,16, 0,11,11,15,15, 0,16,16,
+       18,19, 0,15,15,15,16, 0,17,17,18,20, 0,21, 0,21,
+       19, 0,14,14,16,16, 0,18,18, 0, 0, 0,16,16,15,15,
+        0,16,16,18,17, 0, 0, 0,19,20, 0,14,14,16,16, 0,
+       19,19, 0, 0, 0,16,17,15,15, 0,12,12,14,15, 0,13,
+       13,16,17, 0,12,12,17,17, 0,17,16, 0, 0, 0,18,17,
+       21, 0, 0,13,13,19,17, 0,15,15,20,21, 0,12,12,17,
+       17, 0,17,17, 0, 0, 0,17,17, 0, 0, 0,13,13,17,18,
+        0,16,16,21, 0, 0,12,12,17,17, 0,17,17, 0, 0, 0,
+       17,17, 0, 0, 0,18,21, 0, 0, 0, 0, 0, 0, 0, 0,15,
+       15,21, 0, 0,20,21, 0, 0, 0,18,19, 0, 0, 0,18,17,
+        0, 0, 0, 0, 0, 0, 0, 0,16,16,21, 0, 0,21,21, 0,
+        0, 0,18,19, 0, 0, 0,12,12,16,16, 0,13,13,16,17,
+        0,13,13,17,16, 0,14,14,16,16, 0,16,15,19,18, 0,
+       13,13,17,17, 0,15,15,18,18, 0,12,12,16,16, 0,15,
+       15,18,19, 0,15,15,17,16, 0,13,13,17,17, 0,16,16,
+       18,17, 0,12,12,17,16, 0,15,15,18,18, 0,15,15,17,
+       17, 0,16,16, 0,19, 0, 0, 0, 0, 0, 0,14,14,16,17,
+        0,18,18, 0, 0, 0,15,15,17,17, 0,16,16,21,19, 0,
+       21, 0,21,21, 0,13,14,16,16, 0,19,19, 0, 0, 0,15,
+       16,16,16, 0,11,11,17,16, 0,15,14,19,18, 0,14,14,
+       19,19, 0,18,17,18,20, 0,17,17,18,19, 0,13,13,17,
+       17, 0,16,17,21,18, 0,13,13,17,16, 0,18,17,19, 0,
+        0,16,17,18,18, 0,12,12,19,18, 0,18,18,20,20, 0,
+       13,13,17,17, 0,17,17,21, 0, 0,16,17,17,18, 0,18,
+       17,19,18, 0, 0, 0, 0, 0, 0,14,14,17,17, 0,19,19,
+       21, 0, 0,16,16,16,17, 0,17,17,19,20, 0, 0, 0, 0,
+       21, 0,15,15,17,18, 0,21,21, 0, 0, 0,17,17,17,18,
+        0,10,10,15,15, 0,15,14,17,18, 0,14,14,16,16, 0,
+        0, 0,18, 0, 0,21, 0,19, 0, 0,13,13,17,16, 0,17,
+       17,18, 0, 0,14,14,16,15, 0, 0, 0,21, 0, 0,21, 0,
+       19,18, 0,13,13,17,17, 0,18,18,20,20, 0,15,15,16,
+       16, 0, 0, 0,21,21, 0, 0, 0,20,20, 0, 0, 0,19, 0,
+        0, 0, 0, 0, 0, 0,21,20,18,18, 0, 0, 0, 0, 0, 0,
+        0, 0, 0,20, 0, 0, 0, 0,20, 0, 0, 0, 0, 0, 0, 0,
+        0,19,18, 0, 0, 0, 0,21, 0, 0, 0,18,20, 0,18,19,
+       16,17, 0,21,19,17,17, 0, 0,21,18,18, 0, 0,21,20,
+       19, 0, 0, 0,20,20, 0, 0,21,17,17, 0, 0, 0,19,19,
+        0,20,20,17,17, 0, 0, 0, 0,20, 0, 0,20,18,18, 0,
+       21,20,17,17, 0, 0, 0,20,21, 0,19, 0,17,17, 0, 0,
+       21, 0, 0, 0,20, 0,18,19, 0, 0, 0,21,21, 0, 0, 0,
+        0,21, 0,20,20,17,17, 0, 0, 0, 0, 0, 0,21, 0,18,
+       17, 0, 0, 0,20,19, 0, 0, 0, 0,21, 0,20,20,17,17,
+        0, 0, 0, 0, 0, 0,21,21,18,18, 0,12,12,15,14, 0,
+       14,14,17,17, 0,14,14,17,16, 0,18,18,21, 0, 0,19,
+       20, 0, 0, 0,13,13,18,17, 0,16,16,19,18, 0,13,13,
+       17,17, 0,17,17, 0, 0, 0,17,17,21, 0, 0,13,13,17,
+       17, 0,17,17,21,20, 0,13,13,18,17, 0,18,19,21,21,
+        0,19,18, 0, 0, 0,18,17, 0, 0, 0, 0, 0, 0, 0, 0,
+       15,16, 0, 0, 0,21,21, 0, 0, 0,20,18,21, 0, 0,17,
+       18, 0, 0, 0, 0, 0, 0, 0, 0,15,16, 0, 0, 0, 0,20,
+        0, 0, 0, 0,19, 0, 0, 0,15,15,18,19, 0,18,17,21,
+        0, 0,16,18, 0,20, 0,17,18,21, 0, 0,18,20, 0, 0,
+        0,16,16,21,21, 0,19,20,21, 0, 0,16,15, 0,21, 0,
+       18,20, 0, 0, 0,18,19, 0, 0, 0,16,15,21,21, 0,21,
+        0, 0, 0, 0,16,15,21, 0, 0,20,19, 0, 0, 0,18,21,
+       21, 0, 0,20,18, 0, 0, 0, 0, 0, 0, 0, 0,16,16, 0,
+       20, 0,21, 0, 0, 0, 0,17,18,20,21, 0,18,18,21,21,
+        0, 0, 0, 0, 0, 0,16,16,20, 0, 0, 0,21, 0, 0, 0,
+       21,18, 0, 0, 0,12,12,20,17, 0,15,15,19,18, 0,14,
+       14,19,18, 0,18,17,21,19, 0,17,17,21,17, 0,13,13,
+       21,19, 0,16,17,20,19, 0,13,13,16,16, 0,17,17,20,
+       21, 0,16,16,19,17, 0,13,13,18,18, 0,17,19,19,19,
+        0,13,13,17,17, 0,18,18, 0,19, 0,16,17,18,18, 0,
+       16,17,19,21, 0, 0, 0, 0, 0, 0,15,15,16,17, 0,20,
+       19,21, 0, 0,17,17,17,17, 0,17,17,21,19, 0, 0, 0,
+        0, 0, 0,15,15,17,17, 0,21, 0, 0, 0, 0,18,18,17,
+       17, 0,10,10,15,15, 0,15,15,17,17, 0,15,14,16,16,
+        0, 0, 0,21,19, 0,21,21,19,21, 0,13,13,17,16, 0,
+       17,17,18,19, 0,14,15,16,15, 0, 0, 0,21,19, 0,21,
+       21,18,19, 0,14,14,16,17, 0,18,18,18,19, 0,15,15,
+       15,16, 0, 0,21, 0,21, 0, 0, 0,19,20, 0, 0, 0,21,
+       19, 0, 0, 0, 0, 0, 0,21,21,19,17, 0, 0, 0, 0, 0,
+        0, 0, 0,21,21, 0,21, 0, 0,21, 0, 0, 0, 0, 0, 0,
+       21,21,19,18, 0, 0, 0, 0, 0, 0, 0, 0, 0,19, 0,21,
+       18,18,17, 0,21, 0,20,20, 0, 0, 0,18,20, 0, 0,21,
+       18,21, 0, 0, 0,21,18, 0, 0, 0, 0,19, 0, 0, 0,21,
+       21, 0,20,21,17,19, 0,21, 0,21, 0, 0,21, 0,18,18,
+        0,20,21,17,18, 0, 0, 0,21,19, 0,20,21,17,18, 0,
+        0, 0,21,21, 0, 0, 0,20,19, 0, 0, 0,21,21, 0, 0,
+        0, 0, 0, 0,21,21,19,18, 0, 0, 0, 0, 0, 0, 0,21,
+       19,18, 0,21,21,19, 0, 0, 0, 0,21, 0, 0,21,21,18,
+       17, 0, 0, 0, 0, 0, 0,21, 0,21,18, 0,12,12,14,14,
+        0,15,14,17,17, 0,14,14,17,16, 0,19,17, 0, 0, 0,
+       19,19, 0, 0, 0,13,13,17,17, 0,17,17,20,20, 0,13,
+       13,18,18, 0,18,17, 0, 0, 0,18,21, 0, 0, 0,13,13,
+       17,17, 0,18,18,21,20, 0,14,14,18,19, 0,19,18,21,
+        0, 0,19,19, 0, 0, 0,20,18,20, 0, 0, 0, 0, 0, 0,
+        0,15,16, 0, 0, 0,21,21, 0, 0, 0,19,19, 0, 0, 0,
+       18,18, 0, 0, 0, 0, 0, 0, 0, 0,16,16, 0,21, 0, 0,
+        0, 0, 0, 0,19,20, 0, 0, 0,15,15,20,21, 0,17,17,
+       21,21, 0,17,17, 0, 0, 0,19,18, 0, 0, 0,18,19, 0,
+        0, 0,17,16, 0,21, 0, 0,20, 0, 0, 0,16,16, 0,20,
+        0,19,19, 0,21, 0,19,18, 0,21, 0,16,16, 0, 0, 0,
+       21,21, 0, 0, 0,16,16, 0, 0, 0,21,21, 0, 0, 0,19,
+       19, 0, 0, 0,20, 0, 0, 0, 0, 0, 0, 0, 0, 0,17,17,
+        0,21, 0, 0,20, 0, 0, 0,20,18,21,21, 0,19,18, 0,
+       20, 0, 0, 0, 0, 0, 0,16,17,21, 0, 0, 0,21, 0, 0,
+        0,19,20,21,20,
+};
+
+static const static_codebook _44pn1_p4_0 = {
+       5, 3125,
+       (char *)_vq_lengthlist__44pn1_p4_0,
+       1, -528744448, 1616642048, 3, 0,
+       (long *)_vq_quantlist__44pn1_p4_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p4_1[] = {
+       3,
+       2,
+       4,
+       1,
+       5,
+       0,
+       6,
+};
+
+static const char _vq_lengthlist__44pn1_p4_1[] = {
+        2, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _44pn1_p4_1 = {
+       1, 7,
+       (char *)_vq_lengthlist__44pn1_p4_1,
+       1, -533200896, 1611661312, 3, 0,
+       (long *)_vq_quantlist__44pn1_p4_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p5_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p5_0[] = {
+        1, 7, 7, 6, 8, 8, 7, 8, 8, 7, 9, 9,11,11,11, 9,
+        8, 8, 7, 9, 9,11,12,11, 9, 9, 9, 6, 7, 7,10,11,
+       11,10,10,10,10,11,11,15,14,14,12,12,12,11,11,11,
+       14,14,14,12,12,12, 5, 6, 6, 8, 5, 5, 8, 7, 7, 8,
+        8, 8,12,10,10,10, 7, 7, 8, 7, 7,12,10,10,10, 7,
+        7, 6, 7, 7,12,11,11,12,10,10,11,10,10,14,14,13,
+       13,10,10,11,10,10,16,14,14,14,11,10, 7, 7, 7,13,
+       12,12,12,12,11,11,11,11,15,14,17,13,12,12,12,11,
+       11,15,15,15,14,13,13,10, 9, 9,14,12,11,13,11,11,
+       12,11,11,16,15,14,14,11,11,12,11,11,17,14,14,15,
+       11,11, 7, 8, 8,12,11,11,13,10,10,11,10,10,17,14,
+       13,14,10,10,12,10,10,18,15,15,14,10,10, 8, 7, 7,
+       13,12,12,13,11,11,12,11,11,16,14,15,14,12,12,12,
+       11,11,18,16,16,14,12,12,11,10,10,13,12,11,13,11,
+       11,13,12,12, 0,15,14,14,11,11,13,11,11,16,15,15,
+       15,11,11,
+};
+
+static const static_codebook _44pn1_p5_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p5_0,
+       1, -527106048, 1620377600, 2, 0,
+       (long *)_vq_quantlist__44pn1_p5_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p5_1[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p5_1[] = {
+        2, 6, 7, 6, 8, 8, 7, 7, 8, 7, 8, 8, 9, 9, 9, 8,
+        7, 7, 8, 8, 8, 9, 9, 9, 9, 8, 8, 6, 6, 6, 9, 7,
+        7, 9, 7, 7, 9, 8, 8,10, 8, 8,10, 8, 8,10, 8, 8,
+       10, 9, 8,10, 8, 8, 7, 6, 6, 9, 6, 6, 9, 6, 6, 9,
+        7, 7,10, 8, 8,10, 6, 6, 9, 7, 7,10, 8, 8,10, 6,
+        6, 7, 7, 7,11, 9, 9,11, 9, 9,10, 9, 9,12,10,10,
+       12, 8, 8,11, 9, 9,13, 9,10,12, 8, 8, 8, 7, 7,11,
+        9,10,11,10,10,10, 9, 9,11,11,11,11, 9, 9,11,10,
+        9,12,11,11,11, 9,10,10, 8, 8,11, 9,10,11, 9, 9,
+       11, 9, 9,12,10,10,11, 9, 9,11, 9, 9,12,10,11,11,
+        9, 9, 8, 8, 8,12, 9, 9,12, 9, 9,11, 9, 9,13, 9,
+        9,13, 8, 8,12, 9, 9,13,10,10,12, 8, 8, 9, 7, 7,
+       11,10,10,11,10,10,11,10,10,12,11,11,11,10, 9,11,
+       10,10,11,11,11,11, 9, 9,11, 9, 9,12,10,10,11,10,
+       10,12,10,10,11,11,11,11, 9, 9,11,10,10,12,11,11,
+       11, 9, 9,
+};
+
+static const static_codebook _44pn1_p5_1 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p5_1,
+       1, -530841600, 1616642048, 2, 0,
+       (long *)_vq_quantlist__44pn1_p5_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p6_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__44pn1_p6_0[] = {
+        1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9,
+};
+
+static const static_codebook _44pn1_p6_0 = {
+       5, 243,
+       (char *)_vq_lengthlist__44pn1_p6_0,
+       1, -516716544, 1630767104, 2, 0,
+       (long *)_vq_quantlist__44pn1_p6_0,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p6_1[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44pn1_p6_1[] = {
+        1, 3, 2, 5, 4, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+       12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _44pn1_p6_1 = {
+       1, 25,
+       (char *)_vq_lengthlist__44pn1_p6_1,
+       1, -518864896, 1620639744, 5, 0,
+       (long *)_vq_quantlist__44pn1_p6_1,
+       0
+};
+
+static const long _vq_quantlist__44pn1_p6_2[] = {
+       12,
+       11,
+       13,
+       10,
+       14,
+       9,
+       15,
+       8,
+       16,
+       7,
+       17,
+       6,
+       18,
+       5,
+       19,
+       4,
+       20,
+       3,
+       21,
+       2,
+       22,
+       1,
+       23,
+       0,
+       24,
+};
+
+static const char _vq_lengthlist__44pn1_p6_2[] = {
+        3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 4, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44pn1_p6_2 = {
+       1, 25,
+       (char *)_vq_lengthlist__44pn1_p6_2,
+       1, -529006592, 1611661312, 5, 0,
+       (long *)_vq_quantlist__44pn1_p6_2,
+       0
+};
+
+static const char _huff_lengthlist__44pn1_short[] = {
+        4, 3, 7, 9,12,16,16, 3, 2, 5, 7,11,14,15, 7, 4,
+        5, 6, 9,12,15, 8, 5, 5, 5, 8,10,14, 9, 7, 6, 6,
+        8,10,12,12,10,10, 7, 6, 8,10,15,12,10, 6, 4, 7,
+        9,
+};
+
+static const static_codebook _huff_book__44pn1_short = {
+       2, 49,
+       (char *)_huff_lengthlist__44pn1_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
diff --git a/vorbis/lib/books/coupled/res_books_stereo.h b/vorbis/lib/books/coupled/res_books_stereo.h
new file mode 100644 (file)
index 0000000..61d9340
--- /dev/null
@@ -0,0 +1,15782 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: static codebooks autogenerated by huff/huffbuld
+
+ ********************************************************************/
+
+#include "codebook.h"
+
+static const long _vq_quantlist__16c0_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16c0_s_p1_0[] = {
+         1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
+         0, 0, 0, 7, 9,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
+         0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
+         0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
+         0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
+         0, 0, 0, 0, 8,10,10, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
+         0, 0, 0, 0, 0, 9,10,12, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
+         0, 0, 0, 0, 0, 0, 9,12, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c0_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__16c0_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16c0_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16c0_s_p3_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c0_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16c0_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16c0_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16c0_s_p4_0[] = {
+         1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c0_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16c0_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c0_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16c0_s_p5_0[] = {
+         1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
+         8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
+         8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
+         8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _16c0_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16c0_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c0_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__16c0_s_p6_0[] = {
+         1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
+        11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
+        11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
+        10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
+        10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
+        14,
+};
+
+static const static_codebook _16c0_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__16c0_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16c0_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16c0_s_p7_0[] = {
+         1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
+        11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
+        11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
+        11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
+         9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
+        13,
+};
+
+static const static_codebook _16c0_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16c0_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__16c0_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__16c0_s_p7_1[] = {
+         1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
+         8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
+         8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
+         7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
+         9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
+         9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
+         9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
+        11,11,11, 9, 9, 9, 9,10,10,
+};
+
+static const static_codebook _16c0_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__16c0_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c0_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__16c0_s_p8_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
+         8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
+         8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
+         9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
+        10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
+        13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
+         8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
+        10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
+        14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
+         0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
+         0,12,13,13,12,13,14,14,14,
+};
+
+static const static_codebook _16c0_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__16c0_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__16c0_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16c0_s_p8_1[] = {
+         1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
+         7, 7, 6, 6, 7, 7, 7, 6, 6,
+};
+
+static const static_codebook _16c0_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__16c0_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16c0_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p9_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16c0_s_p9_0[] = {
+         1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _16c0_s_p9_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16c0_s_p9_0,
+        1, -518803456, 1628680192, 2, 0,
+        (long *)_vq_quantlist__16c0_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__16c0_s_p9_1[] = {
+         1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
+         6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
+         6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
+         8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
+        10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _16c0_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__16c0_s_p9_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__16c0_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__16c0_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__16c0_s_p9_2[] = {
+         1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
+        10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
+        11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
+         9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
+        12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
+        12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
+         9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
+        11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
+        10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
+        11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
+        11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
+        10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
+        10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
+        10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
+        11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
+        10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
+        10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
+        11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
+        11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
+        11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
+        11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
+        11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
+         9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
+         9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
+        11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
+        10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
+        11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
+        10,11,10,10,11, 9,10,10,10,
+};
+
+static const static_codebook _16c0_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__16c0_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16c0_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__16c0_s_single[] = {
+         3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
+         8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
+        18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
+        12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
+         7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
+        13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
+        16,16,18,18,
+};
+
+static const static_codebook _huff_book__16c0_s_single = {
+        2, 100,
+        (char *)_huff_lengthlist__16c0_s_single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__16c1_s_long[] = {
+         2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
+         7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
+        19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
+        11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
+         7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
+        12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
+        12,11,11,13,
+};
+
+static const static_codebook _huff_book__16c1_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__16c1_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16c1_s_p1_0[] = {
+         1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
+         0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
+         0, 0, 0, 0, 0, 8, 9,11, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
+         0, 0, 0, 0, 0, 0, 9,11, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c1_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__16c1_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16c1_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16c1_s_p3_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c1_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16c1_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16c1_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16c1_s_p4_0[] = {
+         1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
+         0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _16c1_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16c1_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16c1_s_p5_0[] = {
+         1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
+         9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
+         8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
+         9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _16c1_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16c1_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__16c1_s_p6_0[] = {
+         1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
+        12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
+        11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
+        11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
+        11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
+        10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
+        14,
+};
+
+static const static_codebook _16c1_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__16c1_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16c1_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16c1_s_p7_0[] = {
+         1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
+        10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
+        11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
+        11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
+        10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
+        11,
+};
+
+static const static_codebook _16c1_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16c1_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__16c1_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__16c1_s_p7_1[] = {
+         2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
+         7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
+         8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
+        10,10,10, 8, 8, 8, 8, 9, 9,
+};
+
+static const static_codebook _16c1_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__16c1_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__16c1_s_p8_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
+         7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
+         9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
+        10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
+        13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
+         9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
+        10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
+        13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
+         0,12,12,12,12,13,13,14,15,
+};
+
+static const static_codebook _16c1_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__16c1_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16c1_s_p8_1[] = {
+         2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _16c1_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__16c1_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16c1_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__16c1_s_p9_0[] = {
+         1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _16c1_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__16c1_s_p9_0,
+        1, -513964032, 1628680192, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__16c1_s_p9_1[] = {
+         1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
+         6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
+         5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
+         9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
+         8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
+        13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
+        13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,
+};
+
+static const static_codebook _16c1_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__16c1_s_p9_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__16c1_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__16c1_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__16c1_s_p9_2[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
+        10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
+         8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
+        11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
+        11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
+        10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
+        10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
+        11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
+        11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
+        11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
+        10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
+        12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
+        11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
+        12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
+        11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
+        12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
+        12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
+        11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
+        11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
+        12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
+        12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
+        11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
+        12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
+        12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
+        12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
+        11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
+        11,11,11,11,12,11,11,12,11,
+};
+
+static const static_codebook _16c1_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__16c1_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16c1_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__16c1_s_short[] = {
+         5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
+         7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
+        16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
+        13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
+         8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
+        11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
+         9, 9,10,13,
+};
+
+static const static_codebook _huff_book__16c1_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__16c1_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__16c2_s_long[] = {
+        4, 7, 9, 9, 9, 8, 9,10,13,16, 5, 4, 5, 6, 7, 7,
+        8, 9,12,16, 6, 5, 5, 5, 7, 7, 9,10,12,15, 7, 6,
+        5, 4, 5, 6, 8, 9,10,13, 8, 7, 7, 5, 5, 5, 7, 9,
+       10,12, 7, 7, 7, 6, 5, 5, 6, 7,10,12, 8, 8, 8, 7,
+        7, 5, 5, 6, 9,11, 8, 9, 9, 8, 8, 6, 6, 5, 8,11,
+       10,11,12,12,11, 9, 9, 8, 9,12,13,14,15,15,14,12,
+       12,11,11,13,
+};
+
+static const static_codebook _huff_book__16c2_s_long = {
+       2, 100,
+       (char *)_huff_lengthlist__16c2_s_long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__16c2_s_p1_0[] = {
+        1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
+        0, 0, 4, 5, 5, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0,
+};
+
+static const static_codebook _16c2_s_p1_0 = {
+       4, 81,
+       (char *)_vq_lengthlist__16c2_s_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__16c2_s_p1_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__16c2_s_p2_0[] = {
+        2, 4, 4, 7, 7, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
+        0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 4, 4, 8, 7, 0, 0,
+        0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
+        9, 9, 4, 4, 4, 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
+        8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10, 9,
+        0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0,14,13, 0,
+        0, 0,14,14, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
+        0,11,11, 0, 0, 0,14,14, 0, 0, 0,14,14, 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, 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, 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, 8, 8, 8,11,11, 0, 0, 0,
+       12,11, 0, 0, 0,12,12, 0, 0, 0,13,12, 0, 0, 0,13,
+       13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,12,12,
+        0, 0, 0,13,13, 0, 0, 0,13,13, 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, 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, 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, 8, 9, 8,12,11, 0, 0, 0,12,12, 0,
+        0, 0,12,11, 0, 0, 0,13,13, 0, 0, 0,13,13, 8, 8,
+        8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
+       13,14, 0, 0, 0,13,13, 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,
+        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, 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, 8, 9, 9,14,14, 0, 0, 0,13,13, 0, 0, 0,13,
+       13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,14,14,
+        0, 0, 0,13,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
+        0, 0,13,13, 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, 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, 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, 8,
+        9, 9,14,14, 0, 0, 0,13,13, 0, 0, 0,13,13, 0, 0,
+        0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
+       13,13, 0, 0, 0,13,13, 0, 0, 0,13,13, 0, 0, 0,12,
+       12,
+};
+
+static const static_codebook _16c2_s_p2_0 = {
+       4, 625,
+       (char *)_vq_lengthlist__16c2_s_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__16c2_s_p2_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p3_0[] = {
+       4,
+       3,
+       5,
+       2,
+       6,
+       1,
+       7,
+       0,
+       8,
+};
+
+static const char _vq_lengthlist__16c2_s_p3_0[] = {
+        1, 3, 3, 5, 5, 7, 7, 8, 8, 0, 0, 0, 6, 6, 8, 8,
+        9, 9, 0, 0, 0, 6, 6, 8, 8, 9, 9, 0, 0, 0, 7, 7,
+        8, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0, 0, 0,
+        8, 8, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0,
+};
+
+static const static_codebook _16c2_s_p3_0 = {
+       2, 81,
+       (char *)_vq_lengthlist__16c2_s_p3_0,
+       1, -531628032, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p3_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p4_0[] = {
+       8,
+       7,
+       9,
+       6,
+       10,
+       5,
+       11,
+       4,
+       12,
+       3,
+       13,
+       2,
+       14,
+       1,
+       15,
+       0,
+       16,
+};
+
+static const char _vq_lengthlist__16c2_s_p4_0[] = {
+        2, 3, 3, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9,
+        9, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
+       11,10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
+       10,10,10, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
+       11,11,11,11, 0, 0, 0, 7, 6, 8, 8, 9, 9, 9, 9,10,
+       10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
+       11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
+       10,11,11,11,11,12,12, 0, 0, 0, 7, 8, 8, 8, 9, 9,
+       10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
+        9,10,10,11,11,12,12,13,13, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0,
+};
+
+static const static_codebook _16c2_s_p4_0 = {
+       2, 289,
+       (char *)_vq_lengthlist__16c2_s_p4_0,
+       1, -529530880, 1611661312, 5, 0,
+       (long *)_vq_quantlist__16c2_s_p4_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p5_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__16c2_s_p5_0[] = {
+        1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,11,10,10,
+       10,11, 4, 6, 6,10,10,11,10,11,10, 5,10,10, 9,12,
+       11,10,12,12, 7,10,10,12,12,12,12,13,13, 7,11,10,
+       11,12,12,12,13,13, 6,11,10,10,12,12,11,12,12, 7,
+       11,10,12,13,13,12,12,12, 7,10,11,12,13,13,12,12,
+       12,
+};
+
+static const static_codebook _16c2_s_p5_0 = {
+       4, 81,
+       (char *)_vq_lengthlist__16c2_s_p5_0,
+       1, -529137664, 1618345984, 2, 0,
+       (long *)_vq_quantlist__16c2_s_p5_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p5_1[] = {
+       5,
+       4,
+       6,
+       3,
+       7,
+       2,
+       8,
+       1,
+       9,
+       0,
+       10,
+};
+
+static const char _vq_lengthlist__16c2_s_p5_1[] = {
+        2, 3, 3, 6, 6, 6, 6, 7, 7, 7, 7,11,10,10, 6, 6,
+        7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
+        8,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9,11,11,11, 6,
+        7, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
+        8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,
+        8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
+        8, 8, 8,12,11,11,11,11, 8, 8, 8, 8, 8, 8,12,11,
+       11,11,11, 7, 7, 8, 8, 8, 8,
+};
+
+static const static_codebook _16c2_s_p5_1 = {
+       2, 121,
+       (char *)_vq_lengthlist__16c2_s_p5_1,
+       1, -531365888, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p5_1,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p6_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__16c2_s_p6_0[] = {
+        1, 4, 4, 6, 6, 8, 7, 8, 8, 9, 9,10,10, 5, 5, 5,
+        7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
+        9,10, 9,11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,
+       11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
+       12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,12,
+       12, 9, 9,10,10,11,11,12,12,13,13, 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, 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, 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, 0, 0, 0,
+};
+
+static const static_codebook _16c2_s_p6_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__16c2_s_p6_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p6_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p6_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__16c2_s_p6_1[] = {
+        2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+        6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _16c2_s_p6_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__16c2_s_p6_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__16c2_s_p6_1,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p7_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__16c2_s_p7_0[] = {
+        1, 4, 4, 7, 7, 8, 8, 8, 8,10, 9,10,10, 5, 5, 5,
+        7, 7, 9, 9,10,10,11,10,12,11, 6, 5, 5, 7, 7, 9,
+        9,10,10,11,11,12,12,20, 7, 7, 7, 7, 9, 9,10,10,
+       11,11,12,12,20, 7, 7, 7, 7, 9, 9,11,10,12,11,12,
+       12,20,11,11, 8, 8,10,10,11,11,12,12,13,13,20,12,
+       12, 8, 8, 9, 9,11,11,12,12,13,13,20,20,21,10,10,
+       10,10,11,11,12,12,13,13,21,21,21,10,10,10,10,11,
+       11,12,12,13,13,21,21,21,14,14,11,11,12,12,13,13,
+       13,14,21,21,21,16,15,11,11,12,11,13,13,14,14,21,
+       21,21,21,21,13,13,12,12,13,13,14,14,21,21,21,21,
+       21,13,13,12,12,13,13,14,14,
+};
+
+static const static_codebook _16c2_s_p7_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__16c2_s_p7_0,
+       1, -523206656, 1618345984, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p7_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p7_1[] = {
+       5,
+       4,
+       6,
+       3,
+       7,
+       2,
+       8,
+       1,
+       9,
+       0,
+       10,
+};
+
+static const char _vq_lengthlist__16c2_s_p7_1[] = {
+        2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 7,
+        7, 7, 7, 7, 8, 8, 9, 9, 9, 6, 6, 7, 7, 7, 7, 8,
+        8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
+        7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
+        8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
+        7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7,
+        7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
+        9, 9, 9, 7, 7, 7, 7, 8, 8,
+};
+
+static const static_codebook _16c2_s_p7_1 = {
+       2, 121,
+       (char *)_vq_lengthlist__16c2_s_p7_1,
+       1, -531365888, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p7_1,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p8_0[] = {
+       7,
+       6,
+       8,
+       5,
+       9,
+       4,
+       10,
+       3,
+       11,
+       2,
+       12,
+       1,
+       13,
+       0,
+       14,
+};
+
+static const char _vq_lengthlist__16c2_s_p8_0[] = {
+        1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 6,
+        6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11, 6, 5,
+        5, 8, 7, 9, 9, 8, 8, 9, 9,10,10,11,11,20, 8, 8,
+        8, 8, 9, 9, 9, 9,10,10,11,10,12,11,20, 8, 8, 8,
+        8, 9, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
+       10,10,10,10,11,11,12,12,13,12,20,13,13, 9, 9,10,
+       10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
+       10,10,11,11,12,12,13,12,20,20,20, 9, 9, 9, 8,10,
+       10,12,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
+       12,12,13,13,13,13,20,20,20,13,13,10,10,11,10,12,
+       11,13,13,14,14,20,20,20,20,20,11,11,11,11,12,12,
+       13,13,14,14,20,20,20,20,20,11,10,11,11,13,11,13,
+       13,14,14,20,20,21,21,21,14,14,11,12,13,13,13,13,
+       14,14,21,21,21,21,21,15,15,12,11,13,12,14,13,15,
+       14,
+};
+
+static const static_codebook _16c2_s_p8_0 = {
+       2, 225,
+       (char *)_vq_lengthlist__16c2_s_p8_0,
+       1, -520986624, 1620377600, 4, 0,
+       (long *)_vq_quantlist__16c2_s_p8_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p8_1[] = {
+       10,
+       9,
+       11,
+       8,
+       12,
+       7,
+       13,
+       6,
+       14,
+       5,
+       15,
+       4,
+       16,
+       3,
+       17,
+       2,
+       18,
+       1,
+       19,
+       0,
+       20,
+};
+
+static const char _vq_lengthlist__16c2_s_p8_1[] = {
+        2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9,
+        9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10, 7, 7, 8,
+        8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
+       11,11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+        9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
+        9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
+       11, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
+       10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
+       10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
+        9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,11,11,
+       11,11, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
+       10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
+       10,10,10,10,10,10,10,11,11,11,11,11,10, 9,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
+       11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
+       11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
+       10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
+       10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
+       11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
+       11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
+       10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
+       10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _16c2_s_p8_1 = {
+       2, 441,
+       (char *)_vq_lengthlist__16c2_s_p8_1,
+       1, -529268736, 1611661312, 5, 0,
+       (long *)_vq_quantlist__16c2_s_p8_1,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p9_0[] = {
+       8,
+       7,
+       9,
+       6,
+       10,
+       5,
+       11,
+       4,
+       12,
+       3,
+       13,
+       2,
+       14,
+       1,
+       15,
+       0,
+       16,
+};
+
+static const char _vq_lengthlist__16c2_s_p9_0[] = {
+        1, 4, 3,10, 8,10,10,10,10,10,10,10,10,10,10,10,
+       10, 6,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10, 6,10, 9,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,
+};
+
+static const static_codebook _16c2_s_p9_0 = {
+       2, 289,
+       (char *)_vq_lengthlist__16c2_s_p9_0,
+       1, -509798400, 1631393792, 5, 0,
+       (long *)_vq_quantlist__16c2_s_p9_0,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p9_1[] = {
+       9,
+       8,
+       10,
+       7,
+       11,
+       6,
+       12,
+       5,
+       13,
+       4,
+       14,
+       3,
+       15,
+       2,
+       16,
+       1,
+       17,
+       0,
+       18,
+};
+
+static const char _vq_lengthlist__16c2_s_p9_1[] = {
+        1, 4, 4, 7, 7, 7, 7, 7, 7, 8, 8,10, 9,11,10,13,
+       11,14,13, 6, 6, 6, 8, 8, 8, 8, 8, 7, 9, 8,11, 9,
+       13,11,14,12,14,13, 5, 6, 6, 8, 8, 8, 8, 8, 8, 9,
+        9,11,11,13,11,14,13,15,15,17, 8, 8, 8, 8, 9, 9,
+        9, 8,11, 9,12,10,13,11,14,12,14,13,17, 8, 8, 8,
+        8, 9, 9, 9, 9,10,10,11,11,13,13,13,14,16,15,17,
+       12,12, 8, 8, 9, 9,10,10,11,11,12,11,13,12,13,12,
+       14,13,16,12,12, 8, 8, 9, 9,10,10,11,11,12,12,13,
+       13,14,14,15,15,17,17,17, 9, 9, 9, 9,11,11,12,12,
+       12,13,13,13,16,14,14,14,17,17,17, 9, 8, 9, 8,11,
+       10,12,12,13,13,14,14,15,15,16,16,17,17,17,12,12,
+       10,10,11,12,12,13,13,14,13,15,15,14,16,15,17,17,
+       17,12,12,10, 8,12, 9,13,12,14,14,15,14,15,16,16,
+       16,17,17,17,17,17,11,11,12,12,14,14,14,16,15,16,
+       15,16,15,17,17,17,17,17,17,11, 9,12,10,13,11,15,
+       14,16,16,17,16,16,15,17,17,17,17,17,15,15,12,12,
+       14,14,15,16,16,15,16,16,17,17,17,17,17,17,17,14,
+       14,12,10,14,11,15,12,17,16,15,16,17,16,17,17,17,
+       17,17,17,17,13,13,14,14,14,16,17,17,16,17,17,17,
+       17,17,17,17,17,17,17,13, 9,13,12,15,13,16,16,17,
+       17,17,17,17,17,17,17,17,17,17,15,17,14,14,15,16,
+       16,17,16,17,16,17,17,17,17,17,17,17,17,17,17,14,
+       13,15,16,16,17,16,17,17,17,
+};
+
+static const static_codebook _16c2_s_p9_1 = {
+       2, 361,
+       (char *)_vq_lengthlist__16c2_s_p9_1,
+       1, -518287360, 1622704128, 5, 0,
+       (long *)_vq_quantlist__16c2_s_p9_1,
+       0
+};
+
+static const long _vq_quantlist__16c2_s_p9_2[] = {
+       24,
+       23,
+       25,
+       22,
+       26,
+       21,
+       27,
+       20,
+       28,
+       19,
+       29,
+       18,
+       30,
+       17,
+       31,
+       16,
+       32,
+       15,
+       33,
+       14,
+       34,
+       13,
+       35,
+       12,
+       36,
+       11,
+       37,
+       10,
+       38,
+       9,
+       39,
+       8,
+       40,
+       7,
+       41,
+       6,
+       42,
+       5,
+       43,
+       4,
+       44,
+       3,
+       45,
+       2,
+       46,
+       1,
+       47,
+       0,
+       48,
+};
+
+static const char _vq_lengthlist__16c2_s_p9_2[] = {
+        2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
+        6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+        7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+        7,
+};
+
+static const static_codebook _16c2_s_p9_2 = {
+       1, 49,
+       (char *)_vq_lengthlist__16c2_s_p9_2,
+       1, -526909440, 1611661312, 6, 0,
+       (long *)_vq_quantlist__16c2_s_p9_2,
+       0
+};
+
+static const char _huff_lengthlist__16c2_s_short[] = {
+        7,10,12,11,12,13,15,16,18,15,10, 8, 8, 8, 9,10,
+       12,13,14,17,10, 7, 7, 7, 7, 8,10,12,15,18,10, 7,
+        7, 5, 5, 6, 8,10,13,15,10, 7, 6, 5, 4, 4, 6, 9,
+       12,15,11, 7, 7, 5, 4, 3, 4, 7,11,13,12, 9, 8, 7,
+        5, 4, 4, 5,10,13,11,11,11, 9, 7, 5, 5, 5, 9,12,
+       13,12,13,12,10, 8, 8, 7, 9,13,14,14,14,14,13,11,
+       11,10,10,13,
+};
+
+static const static_codebook _huff_book__16c2_s_short = {
+       2, 100,
+       (char *)_huff_lengthlist__16c2_s_short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__8c0_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8c0_s_p1_0[] = {
+         1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 7, 9, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
+         0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
+         0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
+         0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9,10, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
+         0, 0, 0, 0, 0, 9,10,11, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
+         0, 0, 0, 0, 0, 0, 8,11, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c0_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__8c0_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8c0_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8c0_s_p3_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c0_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8c0_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8c0_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8c0_s_p4_0[] = {
+         1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
+         0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c0_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8c0_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c0_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8c0_s_p5_0[] = {
+         1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
+         8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
+         8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
+         9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _8c0_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8c0_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c0_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__8c0_s_p6_0[] = {
+         1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
+        11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
+        10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
+        11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
+        10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
+        11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
+         9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
+         0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
+         0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _8c0_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__8c0_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8c0_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8c0_s_p7_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
+         9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
+        12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
+        11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
+         9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
+        10,
+};
+
+static const static_codebook _8c0_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8c0_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__8c0_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__8c0_s_p7_1[] = {
+         1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
+         8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
+         9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
+         8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
+        10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
+         9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
+        10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
+        10,10,10, 9, 9, 9,10,10,10,
+};
+
+static const static_codebook _8c0_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__8c0_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c0_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__8c0_s_p8_0[] = {
+         1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
+         7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
+         7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
+         9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
+        10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
+         0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
+        10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
+        10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
+        12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
+         0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
+         0, 0,13,13,11,13,13,11,12,
+};
+
+static const static_codebook _8c0_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__8c0_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__8c0_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8c0_s_p8_1[] = {
+         1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
+         7, 7, 6, 6, 7, 7, 7, 6, 6,
+};
+
+static const static_codebook _8c0_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__8c0_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8c0_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p9_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8c0_s_p9_0[] = {
+         1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _8c0_s_p9_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8c0_s_p9_0,
+        1, -518803456, 1628680192, 2, 0,
+        (long *)_vq_quantlist__8c0_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__8c0_s_p9_1[] = {
+         1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
+         6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
+         6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
+         8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
+         8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,
+};
+
+static const static_codebook _8c0_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__8c0_s_p9_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__8c0_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__8c0_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__8c0_s_p9_2[] = {
+         1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
+        11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
+        10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
+         7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
+        11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
+        10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
+        10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
+         9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
+        12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
+        10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
+        11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
+        10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
+        12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
+        10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
+         9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
+        10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
+        11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
+        10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
+        11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
+        10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
+        12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
+        12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
+        10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
+        11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
+        12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
+        10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
+        10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
+        10,11, 9,11,10, 9,10, 9,10,
+};
+
+static const static_codebook _8c0_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__8c0_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8c0_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__8c0_s_single[] = {
+         4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
+         6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
+        17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
+        11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
+         6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
+         9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
+        17,16,17,17,
+};
+
+static const static_codebook _huff_book__8c0_s_single = {
+        2, 100,
+        (char *)_huff_lengthlist__8c0_s_single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8c1_s_p1_0[] = {
+         1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
+         0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
+         0, 0, 0, 0, 0, 8, 9,10, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         0, 0, 0, 0, 0, 0, 8,10, 8, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c1_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__8c1_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8c1_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8c1_s_p3_0[] = {
+         2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c1_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8c1_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8c1_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8c1_s_p4_0[] = {
+         1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
+         0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _8c1_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8c1_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8c1_s_p5_0[] = {
+         1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
+         9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
+         8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
+        11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
+         0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _8c1_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8c1_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__8c1_s_p6_0[] = {
+         1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
+        11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
+        12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
+        11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
+        11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
+        10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
+        14,
+};
+
+static const static_codebook _8c1_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__8c1_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8c1_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8c1_s_p7_0[] = {
+         1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
+         9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
+        10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
+        10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
+         9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
+         9,
+};
+
+static const static_codebook _8c1_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8c1_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__8c1_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__8c1_s_p7_1[] = {
+         2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
+         8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _8c1_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__8c1_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__8c1_s_p8_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
+         7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+         9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
+        12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
+         9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
+        13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
+         0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
+         0,12,12,11,10,12,11,13,12,
+};
+
+static const static_codebook _8c1_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__8c1_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8c1_s_p8_1[] = {
+         2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _8c1_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__8c1_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8c1_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__8c1_s_p9_0[] = {
+         1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
+        10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10, 9, 9, 9, 9,
+};
+
+static const static_codebook _8c1_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__8c1_s_p9_0,
+        1, -513964032, 1628680192, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__8c1_s_p9_1[] = {
+         1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
+         5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
+         5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
+         8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
+         8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
+        11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
+        11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
+        13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
+        13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
+        15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
+        15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
+        14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
+        15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
+        17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
+        15,
+};
+
+static const static_codebook _8c1_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__8c1_s_p9_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__8c1_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__8c1_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__8c1_s_p9_2[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
+         9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
+         7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
+        11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
+         9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
+        11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
+        10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
+        10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
+         9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
+        12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
+        10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
+        10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
+        11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
+        10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
+        11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
+        10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
+        11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
+        11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
+        12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
+        10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _8c1_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__8c1_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8c1_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__8c1_s_single[] = {
+         4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
+         6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
+        17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
+        10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
+         8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
+         8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
+         9, 7, 7, 8,
+};
+
+static const static_codebook _huff_book__8c1_s_single = {
+        2, 100,
+        (char *)_huff_lengthlist__8c1_s_single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c2_s_long[] = {
+         6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
+         7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
+        12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
+        12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
+         7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
+        12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
+        10, 8, 8, 9,
+};
+
+static const static_codebook _huff_book__44c2_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c2_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c2_s_p1_0[] = {
+         2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
+         0, 0, 5, 6, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
+         0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
+         0, 0, 0, 0, 0, 8, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c2_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c2_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c2_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c2_s_p2_0[] = {
+         1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
+         8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
+         0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
+         0, 0, 9, 9, 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, 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, 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, 0,
+         0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
+         0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
+         8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
+        12, 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, 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, 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, 0, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
+         0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
+         0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
+        12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
+        11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c2_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c2_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c2_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c2_s_p3_0[] = {
+         2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c2_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c2_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c2_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c2_s_p4_0[] = {
+         1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
+         0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
+         0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
+         7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c2_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c2_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c2_s_p5_0[] = {
+         1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
+         9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
+         8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
+         9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
+        11,
+};
+
+static const static_codebook _44c2_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c2_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c2_s_p6_0[] = {
+         1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
+        11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
+        10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
+        11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
+        10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
+        14,
+};
+
+static const static_codebook _44c2_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c2_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c2_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c2_s_p7_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
+        11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
+         9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
+        11,
+};
+
+static const static_codebook _44c2_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c2_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c2_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c2_s_p7_1[] = {
+         2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
+         7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c2_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c2_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c2_s_p8_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
+        13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
+        10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
+        11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
+        13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
+         0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
+         0,12,12,12,12,13,12,14,14,
+};
+
+static const static_codebook _44c2_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c2_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c2_s_p8_1[] = {
+         2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c2_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c2_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c2_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c2_s_p9_0[] = {
+         1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
+        11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _44c2_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c2_s_p9_0,
+        1, -514541568, 1627103232, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p9_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c2_s_p9_1[] = {
+         1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
+         7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
+         8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
+        12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
+        13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
+        11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
+        11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
+        12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
+        13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
+        17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
+        17,13,12,12,10,13,11,14,14,
+};
+
+static const static_codebook _44c2_s_p9_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c2_s_p9_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c2_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c2_s_p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c2_s_p9_2[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
+         8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
+         9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
+         9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
+        11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
+        11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
+        11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
+        10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
+        10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
+        10,
+};
+
+static const static_codebook _44c2_s_p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c2_s_p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c2_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c2_s_short[] = {
+        11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
+         7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
+        12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
+        13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
+         7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
+        14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
+         6, 8, 9,12,
+};
+
+static const static_codebook _huff_book__44c2_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c2_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c3_s_long[] = {
+         5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
+         7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
+        11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
+        10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
+         6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
+        12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
+         9, 8, 8, 8,
+};
+
+static const static_codebook _huff_book__44c3_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c3_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c3_s_p1_0[] = {
+         2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
+         0, 0, 5, 6, 6, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 6, 7, 8, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
+         0, 0, 0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c3_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c3_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c3_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c3_s_p2_0[] = {
+         2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
+         7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
+         7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+         0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
+         0, 0,10,10, 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, 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, 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, 0,
+         0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
+         0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
+         7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
+         9, 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, 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, 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, 0, 0, 0, 0,
+         0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
+         0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
+         0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
+        10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
+         9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c3_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c3_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c3_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c3_s_p3_0[] = {
+         2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c3_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c3_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c3_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c3_s_p4_0[] = {
+         2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
+         0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
+         7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c3_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c3_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c3_s_p5_0[] = {
+         1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
+         9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
+         8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
+         9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
+         0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
+        11,
+};
+
+static const static_codebook _44c3_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c3_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c3_s_p6_0[] = {
+         2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
+         9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
+         9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
+         8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
+         9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
+         0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
+        13,
+};
+
+static const static_codebook _44c3_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c3_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c3_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c3_s_p7_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
+        10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
+         9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44c3_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c3_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c3_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c3_s_p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c3_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c3_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c3_s_p8_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
+         8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
+        13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
+        10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
+        11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
+        13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
+         0,13,13,12,12,13,12,14,13,
+};
+
+static const static_codebook _44c3_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c3_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c3_s_p8_1[] = {
+         2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c3_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c3_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c3_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c3_s_p9_0[] = {
+         1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
+        12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _44c3_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c3_s_p9_0,
+        1, -514332672, 1627381760, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c3_s_p9_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
+         5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
+         5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
+         8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
+         8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
+        10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
+        10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
+        12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
+        11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
+        13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
+        13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
+        14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
+        14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
+        14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
+        15,
+};
+
+static const static_codebook _44c3_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c3_s_p9_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c3_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c3_s_p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c3_s_p9_2[] = {
+         2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
+         9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
+         9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
+         9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
+        11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
+        11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
+        10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
+        11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
+        10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
+        10,
+};
+
+static const static_codebook _44c3_s_p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c3_s_p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c3_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c3_s_short[] = {
+        10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
+         7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
+        12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
+        12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
+         7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
+        14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
+         6, 8, 9,11,
+};
+
+static const static_codebook _huff_book__44c3_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c3_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c4_s_long[] = {
+         4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
+         7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
+        11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
+        10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
+         6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
+        12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
+         9, 8, 7, 7,
+};
+
+static const static_codebook _huff_book__44c4_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c4_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c4_s_p1_0[] = {
+         2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
+         0, 0, 5, 6, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
+         0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
+         0, 0, 0, 0, 0, 8, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c4_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c4_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c4_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c4_s_p2_0[] = {
+         2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
+         7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
+         7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+         0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
+         0, 0,10,10, 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, 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, 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, 0,
+         0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
+         0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
+         7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
+         9, 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, 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, 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, 0, 0, 0, 0,
+         0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
+         0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
+         0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
+        10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
+         9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c4_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c4_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c4_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c4_s_p3_0[] = {
+         2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c4_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c4_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c4_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c4_s_p4_0[] = {
+         2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
+         0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
+         7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c4_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c4_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c4_s_p5_0[] = {
+         2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
+         9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
+         8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
+         9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _44c4_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c4_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c4_s_p6_0[] = {
+         2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
+        11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
+         9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
+         9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
+         9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
+         0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
+        13,
+};
+
+static const static_codebook _44c4_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c4_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c4_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c4_s_p7_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
+        10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
+         9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44c4_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c4_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c4_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c4_s_p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 9, 9,
+};
+
+static const static_codebook _44c4_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c4_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c4_s_p8_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
+         7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
+        13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
+        10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
+        10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
+        12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
+         0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
+         0,13,12,12,12,12,12,13,13,
+};
+
+static const static_codebook _44c4_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c4_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c4_s_p8_1[] = {
+         2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c4_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c4_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c4_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c4_s_p9_0[] = {
+         1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
+        12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,
+};
+
+static const static_codebook _44c4_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c4_s_p9_0,
+        1, -513964032, 1628680192, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c4_s_p9_1[] = {
+         1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
+         5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
+         5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
+         8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
+         8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
+        11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
+        10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
+        12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
+        11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
+        13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
+        13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
+        14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
+        14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
+        15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
+        15,
+};
+
+static const static_codebook _44c4_s_p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c4_s_p9_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44c4_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c4_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c4_s_p9_2[] = {
+         2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
+         7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
+         9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
+         9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
+        11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
+        10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
+        10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
+         9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
+        11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
+        10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
+        11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
+        11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
+        10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
+        11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
+        12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
+        11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
+        10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c4_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c4_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c4_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c4_s_short[] = {
+         4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
+         8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
+        11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
+        12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
+         7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
+        13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
+         7, 9,12,17,
+};
+
+static const static_codebook _huff_book__44c4_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c4_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c5_s_long[] = {
+         3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
+        10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
+        10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
+        10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
+         6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
+        13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
+         9, 8, 7, 7,
+};
+
+static const static_codebook _huff_book__44c5_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c5_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c5_s_p1_0[] = {
+         2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
+         0, 0, 4, 6, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
+         0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
+         0, 0, 0, 0, 0, 8, 9,10, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         0, 0, 0, 0, 0, 0, 9,11,10, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c5_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c5_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c5_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c5_s_p2_0[] = {
+         2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
+         8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
+         8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
+         0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
+         0, 0,10,10, 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, 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, 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, 0,
+         0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
+         0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
+         7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
+        10, 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, 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, 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, 0, 0, 0, 0,
+         0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
+         0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
+         0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
+        11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
+        10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c5_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c5_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c5_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c5_s_p3_0[] = {
+         2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 5, 6, 6, 8, 8, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c5_s_p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c5_s_p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c5_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c5_s_p4_0[] = {
+         2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
+         0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
+         7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c5_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c5_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c5_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c5_s_p5_0[] = {
+         2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
+         9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
+         7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
+         8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
+         0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _44c5_s_p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c5_s_p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c5_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p6_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c5_s_p6_0[] = {
+         2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
+        11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
+        11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
+        10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
+        10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
+        10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
+         9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
+        13,
+};
+
+static const static_codebook _44c5_s_p6_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c5_s_p6_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c5_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c5_s_p7_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
+        10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
+         9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44c5_s_p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c5_s_p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c5_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c5_s_p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c5_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c5_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c5_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c5_s_p8_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
+         7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
+        10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
+        10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
+        12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
+         0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
+         0,12,12,12,12,12,12,13,13,
+};
+
+static const static_codebook _44c5_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c5_s_p8_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c5_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p8_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c5_s_p8_1[] = {
+         2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c5_s_p8_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c5_s_p8_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c5_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p9_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c5_s_p9_0[] = {
+         1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
+         7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
+         6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c5_s_p9_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c5_s_p9_0,
+        1, -512522752, 1628852224, 4, 0,
+        (long *)_vq_quantlist__44c5_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p9_1[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c5_s_p9_1[] = {
+         1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
+        11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
+        13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
+        12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
+        13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
+        13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
+        13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
+        12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
+        13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
+        12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
+        12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
+        11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
+        13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
+        19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
+        18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
+        17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
+        19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
+        19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
+        15,
+};
+
+static const static_codebook _44c5_s_p9_1 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c5_s_p9_1,
+        1, -520814592, 1620377600, 5, 0,
+        (long *)_vq_quantlist__44c5_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c5_s_p9_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c5_s_p9_2[] = {
+         3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
+         7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
+         7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
+        11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
+        10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
+         9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
+        11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
+        10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
+        11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
+        11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
+        10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
+        10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
+        11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
+        11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
+        10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c5_s_p9_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c5_s_p9_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c5_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c5_s_short[] = {
+         5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
+        10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
+        10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
+        14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
+         6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
+        14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
+         6, 8,11,16,
+};
+
+static const static_codebook _huff_book__44c5_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c5_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c6_s_long[] = {
+         3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
+        10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
+         4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
+        13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
+         7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
+        13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
+        11,10,10,12,
+};
+
+static const static_codebook _huff_book__44c6_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c6_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c6_s_p1_0[] = {
+         1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
+         9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
+         0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+         9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
+         8,
+};
+static const static_codebook _44c6_s_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c6_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c6_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c6_s_p2_0[] = {
+         3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
+         7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
+         8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
+        11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
+        10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
+         0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
+         0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
+        11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
+         0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
+         7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
+         9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
+        12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
+        13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
+         0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
+        10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
+        11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
+         0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
+        10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
+        10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
+        13,13, 0, 0, 0,13,13, 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,
+         7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
+        10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
+         9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
+        12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
+        13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
+         0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
+         0, 0,13,13, 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, 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, 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, 9,
+        11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
+        12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
+        13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
+        13,
+};
+
+static const static_codebook _44c6_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c6_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c6_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c6_s_p3_0[] = {
+         2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
+         9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
+         8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
+         7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c6_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c6_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c6_s_p4_0[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
+        10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
+        11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
+        10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
+        10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
+         9,10,10,11,11,12,12,12,12, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c6_s_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c6_s_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c6_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c6_s_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
+        10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
+        11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
+        11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
+         9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c6_s_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c6_s_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c6_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c6_s_p5_1[] = {
+         3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
+         7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
+         8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
+         6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
+         8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
+         8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
+         8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
+        11,10,10, 7, 7, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c6_s_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c6_s_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c6_s_p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
+         7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
+         9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
+        11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
+        12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
+        12, 9, 8,10,10,11,11,12,12,13,13, 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, 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, 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, 0, 0, 0,
+};
+
+static const static_codebook _44c6_s_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c6_s_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c6_s_p6_1[] = {
+         3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c6_s_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c6_s_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c6_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c6_s_p7_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
+         7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
+        11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
+        12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
+        12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
+        10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
+        12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
+        13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
+        21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
+        20,13,13,13,13,13,13,14,14,
+};
+
+static const static_codebook _44c6_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c6_s_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c6_s_p7_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
+         7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
+         7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
+         7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
+         8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
+         8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
+         7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
+         9, 8, 8, 7, 7, 7, 7, 8, 8,
+};
+
+static const static_codebook _44c6_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c6_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c6_s_p8_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
+         5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
+         5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
+         9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
+         9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
+        10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
+        10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
+        11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
+        10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
+        12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
+        12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
+        13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
+        13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
+        14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
+        14,
+};
+
+static const static_codebook _44c6_s_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c6_s_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c6_s_p8_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
+         8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
+         7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
+        11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
+        11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
+        10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
+        10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
+        10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
+        11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
+        10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
+        10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
+         9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
+        11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
+        11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
+        10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
+        10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
+        11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
+        11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
+        10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c6_s_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c6_s_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c6_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c6_s_p9_0[] = {
+         1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
+        11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c6_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c6_s_p9_0,
+        1, -511845376, 1630791680, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p9_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c6_s_p9_1[] = {
+         1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
+         8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
+         9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
+        10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
+        11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
+        14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
+         9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
+        11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
+        13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
+        16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
+        15,12,10,11,11,13,11,12,13,
+};
+
+static const static_codebook _44c6_s_p9_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c6_s_p9_1,
+        1, -518889472, 1622704128, 4, 0,
+        (long *)_vq_quantlist__44c6_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c6_s_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44c6_s_p9_2[] = {
+         2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44c6_s_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44c6_s_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44c6_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c6_s_short[] = {
+         3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
+        13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
+         5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
+        17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
+         7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
+        18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
+         9,10,17,18,
+};
+
+static const static_codebook _huff_book__44c6_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c6_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c7_s_long[] = {
+         3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
+        11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
+         4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
+        12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
+         7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
+        13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
+        11,10,10,12,
+};
+
+static const static_codebook _huff_book__44c7_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c7_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c7_s_p1_0[] = {
+         1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
+         9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
+         0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+         9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
+         8,
+};
+
+static const static_codebook _44c7_s_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c7_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c7_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c7_s_p2_0[] = {
+         3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
+         7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
+         8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
+        11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
+        10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
+         0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
+         0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
+        11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
+         0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
+         7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
+         9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
+        12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
+        13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
+         0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
+        10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
+        11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
+         0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
+        10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
+        10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
+        13,13, 0, 0, 0,12,13, 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,
+         7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
+        10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
+         9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
+        12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
+        13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
+         0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
+         0, 0,13,13, 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, 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, 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, 9,
+        11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
+        12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
+        13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
+        13,
+};
+
+static const static_codebook _44c7_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c7_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c7_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c7_s_p3_0[] = {
+         2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
+         9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
+         8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
+         7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c7_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c7_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c7_s_p4_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
+        12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+        11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
+        11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
+        10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
+         9,10,10,11,11,12,12,13,13, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c7_s_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c7_s_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c7_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c7_s_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
+        10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
+        12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
+        11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
+        10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c7_s_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c7_s_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c7_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c7_s_p5_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
+         7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
+         9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
+         6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
+         9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
+         7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
+         8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
+        11,11,11, 7, 7, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c7_s_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c7_s_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c7_s_p6_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
+         7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
+        10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
+        11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
+        12, 9, 9,10,10,11,11,11,11,12,12, 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, 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, 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, 0, 0, 0,
+};
+
+static const static_codebook _44c7_s_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c7_s_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c7_s_p6_1[] = {
+         3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c7_s_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c7_s_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c7_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c7_s_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
+         7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
+         8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
+        11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
+        13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
+        11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
+        10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
+        12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
+        14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
+        20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
+        19,13,13,13,13,14,14,15,15,
+};
+
+static const static_codebook _44c7_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c7_s_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c7_s_p7_1[] = {
+         4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
+         7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
+         7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
+         7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
+         7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
+         7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
+         7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
+         8, 8, 8, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _44c7_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c7_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c7_s_p8_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
+         5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
+         5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
+         8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
+         8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
+        10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
+        10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
+        11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
+        10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
+        12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
+        12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
+        14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
+        14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
+        15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
+        14,
+};
+
+static const static_codebook _44c7_s_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c7_s_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c7_s_p8_1[] = {
+         3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
+        10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
+        11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
+         9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
+        10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
+         9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
+        11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
+        10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
+         9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
+        11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
+        10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
+        10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
+        11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
+        10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
+         9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c7_s_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c7_s_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c7_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c7_s_p9_0[] = {
+         1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
+        11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _44c7_s_p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c7_s_p9_0,
+        1, -511845376, 1630791680, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p9_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c7_s_p9_1[] = {
+         1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
+         8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
+         8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
+        10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
+        11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
+        13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
+         9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
+        10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
+        12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
+        16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
+        15,11,11,10,10,12,12,12,12,
+};
+
+static const static_codebook _44c7_s_p9_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c7_s_p9_1,
+        1, -518889472, 1622704128, 4, 0,
+        (long *)_vq_quantlist__44c7_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c7_s_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44c7_s_p9_2[] = {
+         2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44c7_s_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44c7_s_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44c7_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c7_s_short[] = {
+         4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
+        13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
+         5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
+        15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
+         7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
+        16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
+        10, 9,11,14,
+};
+
+static const static_codebook _huff_book__44c7_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c7_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c8_s_long[] = {
+         3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
+        11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
+         5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
+        11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
+         7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
+        14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
+        11, 9, 9,10,
+};
+
+static const static_codebook _huff_book__44c8_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c8_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c8_s_p1_0[] = {
+         1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
+         9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
+         0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+         9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
+         8,
+};
+
+static const static_codebook _44c8_s_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c8_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c8_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c8_s_p2_0[] = {
+         3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
+         7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
+         7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
+        11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
+        10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
+         0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
+         0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
+        11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
+         0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
+         7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
+         9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
+        12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
+        12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
+         0,12,12,13,13, 0, 0, 0,12,13, 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, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
+        10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
+        11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
+         0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
+        10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
+        10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
+        13,13, 0, 0, 0,12,13, 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,
+         7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
+        10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
+         9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
+        12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
+        12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
+         0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
+         0, 0,13,13, 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, 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, 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, 9,
+        11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
+        12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
+        13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
+        13,
+};
+
+static const static_codebook _44c8_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c8_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c8_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c8_s_p3_0[] = {
+         2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
+         9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
+         8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
+         7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c8_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c8_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c8_s_p4_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
+        11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+        11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
+        10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
+         9,10,10,11,11,12,12,13,13, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c8_s_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c8_s_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c8_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c8_s_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
+        10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
+        11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
+        11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
+        10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c8_s_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c8_s_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c8_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c8_s_p5_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
+         6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
+         8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
+         7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
+         8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
+        11,11,11, 7, 7, 7, 7, 8, 8,
+};
+
+static const static_codebook _44c8_s_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c8_s_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c8_s_p6_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
+         7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
+         8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
+        10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
+        11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
+        12, 9, 9,10,10,11,11,12,12,12,12, 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, 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, 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, 0, 0, 0,
+};
+
+static const static_codebook _44c8_s_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c8_s_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c8_s_p6_1[] = {
+         3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c8_s_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c8_s_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c8_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c8_s_p7_0[] = {
+         1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
+         7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
+         8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
+        11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
+        13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
+        11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
+        10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
+        11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
+        14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
+        21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
+        20,13,13,13,13,14,13,15,15,
+};
+
+static const static_codebook _44c8_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c8_s_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c8_s_p7_1[] = {
+         4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
+         7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
+         7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
+         7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
+         7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
+         7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
+         7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
+         8, 8, 8, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _44c8_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c8_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c8_s_p8_0[] = {
+         1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
+         5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
+         5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
+         8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
+         8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
+        10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
+        10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
+        11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
+        11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
+        12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
+        12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
+        13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
+        14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
+        14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
+        15,
+};
+
+static const static_codebook _44c8_s_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c8_s_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44c8_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c8_s_p8_1[] = {
+         4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
+         8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
+        10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
+         9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
+        10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
+         9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
+         9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
+        10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
+        10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
+        10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
+         9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+        10, 9, 9,10,10, 9,10, 9, 9,
+};
+
+static const static_codebook _44c8_s_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c8_s_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c8_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p9_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c8_s_p9_0[] = {
+         1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _44c8_s_p9_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c8_s_p9_0,
+        1, -509798400, 1631393792, 5, 0,
+        (long *)_vq_quantlist__44c8_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p9_1[] = {
+        9,
+        8,
+        10,
+        7,
+        11,
+        6,
+        12,
+        5,
+        13,
+        4,
+        14,
+        3,
+        15,
+        2,
+        16,
+        1,
+        17,
+        0,
+        18,
+};
+
+static const char _vq_lengthlist__44c8_s_p9_1[] = {
+         1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
+        10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
+        12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
+         9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
+         9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
+        13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
+        14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
+        13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
+        12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
+        11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
+         9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
+        17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
+        14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
+        13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
+        13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
+        12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
+        17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
+        17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
+        17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
+        15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
+        14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
+        14,13,13,14,14,15,14,15,14,
+};
+
+static const static_codebook _44c8_s_p9_1 = {
+        2, 361,
+        (char *)_vq_lengthlist__44c8_s_p9_1,
+        1, -518287360, 1622704128, 5, 0,
+        (long *)_vq_quantlist__44c8_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c8_s_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44c8_s_p9_2[] = {
+         2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44c8_s_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44c8_s_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44c8_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c8_s_short[] = {
+         4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
+        12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
+         5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
+        15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
+         7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
+        17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
+        10, 9,11,14,
+};
+
+static const static_codebook _huff_book__44c8_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c8_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c9_s_long[] = {
+         3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
+        13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
+         5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
+        11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
+         7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
+        15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
+        10, 9, 8, 9,
+};
+
+static const static_codebook _huff_book__44c9_s_long = {
+        2, 100,
+        (char *)_huff_lengthlist__44c9_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c9_s_p1_0[] = {
+         1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
+         9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
+         0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+         9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
+         7,
+};
+
+static const static_codebook _44c9_s_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c9_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c9_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c9_s_p2_0[] = {
+         3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
+         7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
+         8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
+        11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
+         9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
+         0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
+         0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
+        10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 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, 6, 8, 7,10,10, 0, 7, 7,10, 9,
+         0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
+         7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
+         9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
+        11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
+        12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
+         0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
+        10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
+        10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
+         0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
+        10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
+        10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
+        12,12, 0, 0, 0,12,12, 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,
+         7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
+        10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
+         9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
+        11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
+        12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
+         0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
+         0, 0,12,13, 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, 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, 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, 9,
+        11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
+        12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
+        12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
+        12,
+};
+
+static const static_codebook _44c9_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c9_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c9_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c9_s_p3_0[] = {
+         3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
+         8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
+         7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
+         7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c9_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c9_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c9_s_p4_0[] = {
+         3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
+        10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
+        11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
+        10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
+        10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
+         9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
+         9,10,10,11,11,12,12,12,12, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c9_s_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c9_s_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c9_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c9_s_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
+        10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
+        11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
+        11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
+        10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c9_s_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c9_s_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c9_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c9_s_p5_1[] = {
+         4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
+         7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
+         8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
+         6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
+         8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
+         7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
+         7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
+        11,11,11, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _44c9_s_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c9_s_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c9_s_p6_0[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
+         6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
+         8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
+        10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+        11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
+        11, 8, 8, 9, 9,10,10,11,11,12,12, 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, 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, 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, 0, 0, 0,
+};
+
+static const static_codebook _44c9_s_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c9_s_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c9_s_p6_1[] = {
+         4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
+         5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44c9_s_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c9_s_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c9_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c9_s_p7_0[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
+         6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
+         8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
+        11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
+        12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
+        11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
+         9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
+        11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
+        13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
+        20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
+        19,12,12,12,12,13,13,14,14,
+};
+
+static const static_codebook _44c9_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c9_s_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c9_s_p7_1[] = {
+         5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
+         7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
+         7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
+         6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
+         7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
+         7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
+         7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
+         8, 8, 8, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _44c9_s_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c9_s_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44c9_s_p8_0[] = {
+         1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
+         5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
+         5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
+         8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
+         8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
+        10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
+        10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
+        11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
+        11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
+        12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
+        12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
+        13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
+        13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
+        14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
+        14,
+};
+
+static const static_codebook _44c9_s_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44c9_s_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44c9_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44c9_s_p8_1[] = {
+         4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
+         7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
+        10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
+        10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
+         9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
+         9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
+         9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
+        10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
+        10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
+         9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
+         9, 9, 9,10, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _44c9_s_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44c9_s_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c9_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p9_0[] = {
+        9,
+        8,
+        10,
+        7,
+        11,
+        6,
+        12,
+        5,
+        13,
+        4,
+        14,
+        3,
+        15,
+        2,
+        16,
+        1,
+        17,
+        0,
+        18,
+};
+
+static const char _vq_lengthlist__44c9_s_p9_0[] = {
+         1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _44c9_s_p9_0 = {
+        2, 361,
+        (char *)_vq_lengthlist__44c9_s_p9_0,
+        1, -508535424, 1631393792, 5, 0,
+        (long *)_vq_quantlist__44c9_s_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p9_1[] = {
+        9,
+        8,
+        10,
+        7,
+        11,
+        6,
+        12,
+        5,
+        13,
+        4,
+        14,
+        3,
+        15,
+        2,
+        16,
+        1,
+        17,
+        0,
+        18,
+};
+
+static const char _vq_lengthlist__44c9_s_p9_1[] = {
+         1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
+        11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
+        12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
+         9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
+         9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
+        13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
+        14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
+        13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
+        12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
+        11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
+        10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
+        18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
+        14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
+        13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
+        14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
+        13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
+        15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
+        18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
+        18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
+        14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
+        14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
+        13,13,13,14,13,14,15,15,15,
+};
+
+static const static_codebook _44c9_s_p9_1 = {
+        2, 361,
+        (char *)_vq_lengthlist__44c9_s_p9_1,
+        1, -518287360, 1622704128, 5, 0,
+        (long *)_vq_quantlist__44c9_s_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44c9_s_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44c9_s_p9_2[] = {
+         2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44c9_s_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44c9_s_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44c9_s_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44c9_s_short[] = {
+         5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
+        13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
+         6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
+        15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
+         7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
+        18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
+         9, 8,10,13,
+};
+
+static const static_codebook _huff_book__44c9_s_short = {
+        2, 100,
+        (char *)_huff_lengthlist__44c9_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c0_s_long[] = {
+         5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
+        12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
+         9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
+         7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
+        12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
+        12,
+};
+
+static const static_codebook _huff_book__44c0_s_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44c0_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c0_s_p1_0[] = {
+         1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
+         0, 0, 0, 0, 0, 9, 9,11, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
+         0, 0, 0, 0, 0, 0, 9,11,10, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c0_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c0_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c0_s_p2_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c0_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c0_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c0_s_p3_0[] = {
+         1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c0_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c0_s_p4_0[] = {
+         1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
+         9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
+         7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
+         9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
+        10,
+};
+
+static const static_codebook _44c0_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c0_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c0_s_p5_0[] = {
+         1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
+        11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
+        10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
+        10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44c0_s_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c0_s_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c0_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c0_s_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
+         9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
+        11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
+         9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44c0_s_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c0_s_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c0_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c0_s_p6_1[] = {
+         2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
+         7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c0_s_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c0_s_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c0_s_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
+        10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
+        11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
+        13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
+         0,12,12,11,11,12,12,13,13,
+};
+
+static const static_codebook _44c0_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c0_s_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c0_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c0_s_p7_1[] = {
+         2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c0_s_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c0_s_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c0_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p8_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c0_s_p8_0[] = {
+         1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,
+};
+
+static const static_codebook _44c0_s_p8_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c0_s_p8_0,
+        1, -518283264, 1627103232, 3, 0,
+        (long *)_vq_quantlist__44c0_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c0_s_p8_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
+         7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
+         8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
+        12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
+        13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
+        10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
+        10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
+        13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
+        14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
+        16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
+        16,13,13,12,12,14,14,15,13,
+};
+
+static const static_codebook _44c0_s_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c0_s_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c0_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_s_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c0_s_p8_2[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
+         9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
+         9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
+         9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
+         9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
+         9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
+        11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
+        10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
+        11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
+        10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
+        10,
+};
+
+static const static_codebook _44c0_s_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c0_s_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c0_s_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44c0_s_short[] = {
+         9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
+        14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
+        10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
+         9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
+         6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
+        12,
+};
+
+static const static_codebook _huff_book__44c0_s_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44c0_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c0_sm_long[] = {
+         5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
+        12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
+         7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
+         7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
+        13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
+        13,
+};
+
+static const static_codebook _huff_book__44c0_sm_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44c0_sm_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c0_sm_p1_0[] = {
+         1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
+         0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
+         0, 0, 0, 0, 0, 9, 9,10, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_sm_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c0_sm_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c0_sm_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c0_sm_p2_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_sm_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c0_sm_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c0_sm_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c0_sm_p3_0[] = {
+         1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
+         0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
+         0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
+         9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
+         0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c0_sm_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c0_sm_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c0_sm_p4_0[] = {
+         1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
+         9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
+         8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
+         9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
+         0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
+        11,
+};
+
+static const static_codebook _44c0_sm_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c0_sm_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c0_sm_p5_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
+        11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
+        11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
+        11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
+        10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44c0_sm_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c0_sm_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c0_sm_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c0_sm_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
+        11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
+         9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
+        11,
+};
+
+static const static_codebook _44c0_sm_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c0_sm_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c0_sm_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c0_sm_p6_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
+         8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c0_sm_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c0_sm_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c0_sm_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
+        10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
+        11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
+        13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
+         0,12,12,11,11,13,12,14,14,
+};
+
+static const static_codebook _44c0_sm_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c0_sm_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c0_sm_p7_1[] = {
+         2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c0_sm_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c0_sm_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c0_sm_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p8_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c0_sm_p8_0[] = {
+         1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
+        11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44c0_sm_p8_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c0_sm_p8_0,
+        1, -516186112, 1627103232, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c0_sm_p8_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
+         7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
+         8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
+        12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
+        13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
+        10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
+        10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
+        12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
+        14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
+        20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
+        20,13,13,12,12,16,13,15,13,
+};
+
+static const static_codebook _44c0_sm_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c0_sm_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c0_sm_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c0_sm_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c0_sm_p8_2[] = {
+         2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
+         9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
+        11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
+        11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
+        11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
+        11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
+        10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44c0_sm_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c0_sm_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c0_sm_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44c0_sm_short[] = {
+         6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
+        15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
+         8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
+         7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
+         6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
+        12,
+};
+
+static const static_codebook _huff_book__44c0_sm_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44c0_sm_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c1_s_long[] = {
+         5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
+        12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
+         8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
+         7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
+        11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
+        11,
+};
+
+static const static_codebook _huff_book__44c1_s_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44c1_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c1_s_p1_0[] = {
+         2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
+         0, 0, 5, 6, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 7, 8, 8, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
+         0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
+         0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
+         0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
+         0, 0, 0, 0, 7, 8, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
+         0, 0, 0, 0, 0, 8, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
+         0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c1_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c1_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c1_s_p2_0[] = {
+         2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 6, 8, 8, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c1_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c1_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c1_s_p3_0[] = {
+         1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
+         0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c1_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c1_s_p4_0[] = {
+         1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
+         9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
+         8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
+         9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
+         0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
+        11,
+};
+
+static const static_codebook _44c1_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c1_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c1_s_p5_0[] = {
+         1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
+        10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
+        10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
+        10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44c1_s_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c1_s_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c1_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c1_s_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
+        11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
+         9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
+        11,
+};
+
+static const static_codebook _44c1_s_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c1_s_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c1_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c1_s_p6_1[] = {
+         2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
+         7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c1_s_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c1_s_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_s_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
+        10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
+        11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
+        13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
+         0,12,11,11,11,13,10,14,13,
+};
+
+static const static_codebook _44c1_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_s_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c1_s_p7_1[] = {
+         2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c1_s_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c1_s_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c1_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_s_p8_0[] = {
+         1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
+        10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44c1_s_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_s_p8_0,
+        1, -514541568, 1627103232, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_s_p8_1[] = {
+         1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
+         7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
+         8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
+        12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
+        13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
+        11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
+        10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
+        12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
+        14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
+        16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
+        16,13,12,12,11,14,12,15,13,
+};
+
+static const static_codebook _44c1_s_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_s_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c1_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_s_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c1_s_p8_2[] = {
+         2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
+         9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
+         9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
+         9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
+        11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
+        11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
+        11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
+        11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
+        11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44c1_s_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c1_s_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c1_s_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44c1_s_short[] = {
+         6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
+        13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
+         8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
+         8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
+         7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
+        11,
+};
+
+static const static_codebook _huff_book__44c1_s_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44c1_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44c1_sm_long[] = {
+         5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
+        11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
+         6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
+         6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
+        12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
+        11,
+};
+
+static const static_codebook _huff_book__44c1_sm_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44c1_sm_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c1_sm_p1_0[] = {
+         1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
+         0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
+         0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
+         0, 0, 0, 0, 0, 8, 9,10, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         0, 0, 0, 0, 0, 0, 9,10, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_sm_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44c1_sm_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44c1_sm_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c1_sm_p2_0[] = {
+         2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_sm_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44c1_sm_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c1_sm_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c1_sm_p3_0[] = {
+         1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
+         0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44c1_sm_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c1_sm_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44c1_sm_p4_0[] = {
+         1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
+         9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
+         8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
+         8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
+         0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
+        11,
+};
+
+static const static_codebook _44c1_sm_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44c1_sm_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c1_sm_p5_0[] = {
+         2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
+        10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
+        10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+         9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+         9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
+         0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
+         0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44c1_sm_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c1_sm_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c1_sm_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44c1_sm_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
+         9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
+        11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
+         9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
+        11,
+};
+
+static const static_codebook _44c1_sm_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44c1_sm_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44c1_sm_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44c1_sm_p6_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
+         8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
+         8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
+        10,10,10, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44c1_sm_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44c1_sm_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_sm_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
+         8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
+         9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
+        11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
+        13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
+         0,12,12,11,11,13,12,14,13,
+};
+
+static const static_codebook _44c1_sm_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_sm_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44c1_sm_p7_1[] = {
+         2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44c1_sm_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44c1_sm_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44c1_sm_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p8_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_sm_p8_0[] = {
+         1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
+        13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,
+};
+
+static const static_codebook _44c1_sm_p8_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_sm_p8_0,
+        1, -514541568, 1627103232, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44c1_sm_p8_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
+         7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
+         8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
+        12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
+        13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
+        11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
+        10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
+        12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
+        14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
+        20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
+        20,13,12,12,12,14,12,14,13,
+};
+
+static const static_codebook _44c1_sm_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44c1_sm_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44c1_sm_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44c1_sm_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44c1_sm_p8_2[] = {
+         2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
+         8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
+         8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
+        11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
+        11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
+        11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
+        11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
+        10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44c1_sm_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44c1_sm_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44c1_sm_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44c1_sm_short[] = {
+         4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
+        15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
+         8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
+         6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
+         8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
+        11,
+};
+
+static const static_codebook _huff_book__44c1_sm_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44c1_sm_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44cn1_s_long[] = {
+         4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
+        12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
+         9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
+         8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
+        13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
+        20,
+};
+
+static const static_codebook _huff_book__44cn1_s_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44cn1_s_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44cn1_s_p1_0[] = {
+         1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 9,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
+         0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
+         0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
+         0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
+         0, 0, 0, 0, 8,10,10, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
+         0, 0, 0, 0, 0, 9, 9,11, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
+         0, 0, 0, 0, 0, 0, 9,11, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_s_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44cn1_s_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44cn1_s_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44cn1_s_p2_0[] = {
+         1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_s_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44cn1_s_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44cn1_s_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44cn1_s_p3_0[] = {
+         1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
+         0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
+         0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
+         9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
+         0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_s_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44cn1_s_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_s_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44cn1_s_p4_0[] = {
+         1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
+         9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
+         8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
+         9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
+         0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
+        11,
+};
+
+static const static_codebook _44cn1_s_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44cn1_s_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_s_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44cn1_s_p5_0[] = {
+         1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
+        10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
+        11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
+        10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
+        10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
+        10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
+        10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
+        10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
+         0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44cn1_s_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44cn1_s_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44cn1_s_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44cn1_s_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
+         9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
+        11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
+        11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
+         9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44cn1_s_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44cn1_s_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44cn1_s_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44cn1_s_p6_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
+         8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
+         8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
+         9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
+        10,10,10, 9, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _44cn1_s_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44cn1_s_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_s_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44cn1_s_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
+         8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
+        10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
+        11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
+        13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
+         0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
+         0,13,13,12,12,13,13,13,14,
+};
+
+static const static_codebook _44cn1_s_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44cn1_s_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44cn1_s_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44cn1_s_p7_1[] = {
+         2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
+         6, 6, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44cn1_s_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44cn1_s_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44cn1_s_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p8_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44cn1_s_p8_0[] = {
+         1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,
+};
+
+static const static_codebook _44cn1_s_p8_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44cn1_s_p8_0,
+        1, -518283264, 1627103232, 3, 0,
+        (long *)_vq_quantlist__44cn1_s_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44cn1_s_p8_1[] = {
+         1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
+         7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
+         9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
+        10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
+        13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
+        11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
+        10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
+        11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
+        14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
+        15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
+        15,12,12,11,11,14,12,13,14,
+};
+
+static const static_codebook _44cn1_s_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44cn1_s_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44cn1_s_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_s_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44cn1_s_p8_2[] = {
+         3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+         9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
+         9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
+         9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
+         9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
+         9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
+        11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
+        10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
+        11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
+        11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
+        11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44cn1_s_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44cn1_s_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44cn1_s_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44cn1_s_short[] = {
+        10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
+        16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
+        12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
+        14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
+         8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
+        10,
+};
+
+static const static_codebook _huff_book__44cn1_s_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44cn1_s_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44cn1_sm_long[] = {
+         3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
+        12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
+         7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
+         7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
+        13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
+        17,
+};
+
+static const static_codebook _huff_book__44cn1_sm_long = {
+        2, 81,
+        (char *)_huff_lengthlist__44cn1_sm_long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p1_0[] = {
+         1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
+         0, 0, 5, 7, 7, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
+         0, 0, 0, 7, 8, 9, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
+         0, 0, 0, 0, 8, 9, 9, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
+         0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 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,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
+         0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
+         0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
+         0, 0, 0, 0, 8, 9,10, 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,
+         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, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
+         0, 0, 0, 0, 0, 8, 9,10, 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, 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, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
+         0, 0, 0, 0, 0, 0, 9,10, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_sm_p1_0 = {
+        8, 6561,
+        (char *)_vq_lengthlist__44cn1_sm_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44cn1_sm_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p2_0[] = {
+         1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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,
+         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, 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, 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, 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, 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, 0, 0, 0,
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_sm_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44cn1_sm_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44cn1_sm_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p3_0[] = {
+         1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
+         0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
+         0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
+         9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
+         0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0,
+};
+
+static const static_codebook _44cn1_sm_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44cn1_sm_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p4_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p4_0[] = {
+         1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
+         9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
+         8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
+         9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
+         0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
+        11,
+};
+
+static const static_codebook _44cn1_sm_p4_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44cn1_sm_p4_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p5_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p5_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
+        11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
+        12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
+        11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
+        11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
+        11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
+        10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
+        10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
+        10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
+        10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
+         9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
+        10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
+         0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
+         0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
+         0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
+         0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
+         0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
+        14,
+};
+
+static const static_codebook _44cn1_sm_p5_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44cn1_sm_p5_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44cn1_sm_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p6_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p6_0[] = {
+         1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
+         9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
+        11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
+        11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
+         9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
+        10,
+};
+
+static const static_codebook _44cn1_sm_p6_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44cn1_sm_p6_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44cn1_sm_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p6_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p6_1[] = {
+         2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
+         7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
+         8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
+         8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
+         8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
+        10,10,10, 8, 9, 8, 8, 9, 8,
+};
+
+static const static_codebook _44cn1_sm_p6_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44cn1_sm_p6_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p7_0[] = {
+         1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
+         7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
+         8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
+        11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
+        13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
+        10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
+        11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
+        13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
+         0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
+         0,13,12,12,12,13,13,13,14,
+};
+
+static const static_codebook _44cn1_sm_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44cn1_sm_p7_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p7_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p7_1[] = {
+         2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
+         5, 5, 5, 5, 6, 6, 6, 5, 5,
+};
+
+static const static_codebook _44cn1_sm_p7_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44cn1_sm_p7_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44cn1_sm_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p8_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p8_0[] = {
+         1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
+        14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
+        14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
+        13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,
+};
+
+static const static_codebook _44cn1_sm_p8_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44cn1_sm_p8_0,
+        1, -516186112, 1627103232, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p8_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p8_1[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
+         7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
+         8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
+        11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
+        12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
+        11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
+        10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
+        11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
+        13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
+        13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
+        17,12,12,11,10,13,11,13,13,
+};
+
+static const static_codebook _44cn1_sm_p8_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44cn1_sm_p8_1,
+        1, -522616832, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44cn1_sm_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44cn1_sm_p8_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44cn1_sm_p8_2[] = {
+         3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
+         8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
+        11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
+        11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
+        11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
+        11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
+        10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44cn1_sm_p8_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44cn1_sm_p8_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44cn1_sm_p8_2,
+        0
+};
+
+static const char _huff_lengthlist__44cn1_sm_short[] = {
+         5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
+        14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
+         8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
+         6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
+         8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
+         9,
+};
+
+static const static_codebook _huff_book__44cn1_sm_short = {
+        2, 81,
+        (char *)_huff_lengthlist__44cn1_sm_short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
diff --git a/vorbis/lib/books/floor/floor_books.h b/vorbis/lib/books/floor/floor_books.h
new file mode 100644 (file)
index 0000000..67d5f31
--- /dev/null
@@ -0,0 +1,1546 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: static codebooks autogenerated by huff/huffbuld
+
+ ********************************************************************/
+
+#include "codebook.h"
+
+static const char _huff_lengthlist_line_256x7_0sub1[] = {
+         0, 2, 3, 3, 3, 3, 4, 3, 4,
+};
+
+static const static_codebook _huff_book_line_256x7_0sub1 = {
+        1, 9,
+        (char *)_huff_lengthlist_line_256x7_0sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_0sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
+         6, 3, 6, 4, 6, 4, 7, 5, 7,
+};
+
+static const static_codebook _huff_book_line_256x7_0sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_256x7_0sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_0sub3[] = {
+         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, 3, 5, 2, 5, 3, 5, 3,
+         6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
+        11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
+};
+
+static const static_codebook _huff_book_line_256x7_0sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_256x7_0sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_1sub1[] = {
+         0, 3, 3, 3, 3, 2, 4, 3, 4,
+};
+
+static const static_codebook _huff_book_line_256x7_1sub1 = {
+        1, 9,
+        (char *)_huff_lengthlist_line_256x7_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_1sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
+         5, 4, 6, 5, 6, 7, 6, 8, 8,
+};
+
+static const static_codebook _huff_book_line_256x7_1sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_256x7_1sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_1sub3[] = {
+         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, 3, 2, 4, 3, 6, 3, 7,
+         3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
+};
+
+static const static_codebook _huff_book_line_256x7_1sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_256x7_1sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_class0[] = {
+         7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
+         6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
+         8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
+        14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
+};
+
+static const static_codebook _huff_book_line_256x7_class0 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_256x7_class0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x7_class1[] = {
+         5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
+         4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
+         6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
+        15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
+         4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
+         2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
+         5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
+        14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
+         7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
+         5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
+         7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
+        13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
+        15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+        13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
+        15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
+        15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
+};
+
+static const static_codebook _huff_book_line_256x7_class1 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_256x7_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_0sub0[] = {
+         4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+         5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
+         7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
+         9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
+        10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
+        13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
+        15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
+        18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
+};
+
+static const static_codebook _huff_book_line_512x17_0sub0 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_512x17_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_1sub0[] = {
+         2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
+         6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
+};
+
+static const static_codebook _huff_book_line_512x17_1sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_512x17_1sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_1sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
+         6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
+         9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
+        14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
+        13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
+        15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
+};
+
+static const static_codebook _huff_book_line_512x17_1sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_512x17_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_2sub1[] = {
+         0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
+         5, 3,
+};
+
+static const static_codebook _huff_book_line_512x17_2sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_512x17_2sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_2sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
+         6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
+         9, 8,
+};
+
+static const static_codebook _huff_book_line_512x17_2sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_512x17_2sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_2sub3[] = {
+         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, 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, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
+         7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
+        11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _huff_book_line_512x17_2sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_512x17_2sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_3sub1[] = {
+         0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
+         5, 5,
+};
+
+static const static_codebook _huff_book_line_512x17_3sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_512x17_3sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_3sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
+         6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
+        11,14,
+};
+
+static const static_codebook _huff_book_line_512x17_3sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_512x17_3sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_3sub3[] = {
+         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, 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, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
+         4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _huff_book_line_512x17_3sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_512x17_3sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_class1[] = {
+         1, 2, 3, 6, 5, 4, 7, 7,
+};
+
+static const static_codebook _huff_book_line_512x17_class1 = {
+        1, 8,
+        (char *)_huff_lengthlist_line_512x17_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_class2[] = {
+         3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
+         6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
+        10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
+        17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_512x17_class2 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_512x17_class2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_512x17_class3[] = {
+         2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
+         3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
+         6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
+        17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_512x17_class3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_512x17_class3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x4_class0[] = {
+         7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
+         7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
+        10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
+        15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
+         7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
+         7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
+        10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
+        17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
+         7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
+         7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
+        10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
+        17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
+        11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
+        11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
+        14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
+        17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
+};
+
+static const static_codebook _huff_book_line_128x4_class0 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_128x4_class0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x4_0sub0[] = {
+         2, 2, 2, 2,
+};
+
+static const static_codebook _huff_book_line_128x4_0sub0 = {
+        1, 4,
+        (char *)_huff_lengthlist_line_128x4_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x4_0sub1[] = {
+         0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
+};
+
+static const static_codebook _huff_book_line_128x4_0sub1 = {
+        1, 10,
+        (char *)_huff_lengthlist_line_128x4_0sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x4_0sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
+         4, 4, 5, 4, 5, 4, 6, 5, 6,
+};
+
+static const static_codebook _huff_book_line_128x4_0sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_128x4_0sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x4_0sub3[] = {
+         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, 4, 3, 5, 3, 5, 3,
+         5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
+        11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
+};
+
+static const static_codebook _huff_book_line_128x4_0sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x4_0sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4_class0[] = {
+         6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
+         7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
+        10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
+        11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
+         6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
+         7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
+         9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
+        12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
+         6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
+         7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
+         8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
+        14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
+        11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
+        13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
+        15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
+        15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
+};
+
+static const static_codebook _huff_book_line_256x4_class0 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_256x4_class0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4_0sub0[] = {
+         2, 2, 2, 2,
+};
+
+static const static_codebook _huff_book_line_256x4_0sub0 = {
+        1, 4,
+        (char *)_huff_lengthlist_line_256x4_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4_0sub1[] = {
+         0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
+};
+
+static const static_codebook _huff_book_line_256x4_0sub1 = {
+        1, 10,
+        (char *)_huff_lengthlist_line_256x4_0sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4_0sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
+         5, 3, 5, 4, 5, 4, 6, 4, 6,
+};
+
+static const static_codebook _huff_book_line_256x4_0sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_256x4_0sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4_0sub3[] = {
+         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, 4, 3, 5, 3, 5, 3,
+         6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
+};
+
+static const static_codebook _huff_book_line_256x4_0sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_256x4_0sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_class0[] = {
+        10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
+         7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
+         7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
+        10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
+};
+
+static const static_codebook _huff_book_line_128x7_class0 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x7_class0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_class1[] = {
+         8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
+         6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
+         9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
+        17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
+         6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
+         4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
+         6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
+        16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
+         5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
+         3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
+         5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
+        12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
+         8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
+         5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
+         7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
+        12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
+};
+
+static const static_codebook _huff_book_line_128x7_class1 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_128x7_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_0sub1[] = {
+         0, 3, 3, 3, 3, 3, 3, 3, 3,
+};
+
+static const static_codebook _huff_book_line_128x7_0sub1 = {
+        1, 9,
+        (char *)_huff_lengthlist_line_128x7_0sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_0sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
+         5, 4, 5, 4, 5, 4, 6, 4, 6,
+};
+
+static const static_codebook _huff_book_line_128x7_0sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_128x7_0sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_0sub3[] = {
+         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, 3, 5, 3, 5, 3, 5, 4,
+         5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
+};
+
+static const static_codebook _huff_book_line_128x7_0sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x7_0sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_1sub1[] = {
+         0, 3, 3, 2, 3, 3, 4, 3, 4,
+};
+
+static const static_codebook _huff_book_line_128x7_1sub1 = {
+        1, 9,
+        (char *)_huff_lengthlist_line_128x7_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_1sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
+         6, 3, 7, 3, 8, 4, 9, 4, 9,
+};
+
+static const static_codebook _huff_book_line_128x7_1sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_128x7_1sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x7_1sub3[] = {
+         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, 1, 7, 2, 7, 3, 8, 4,
+         9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
+};
+
+static const static_codebook _huff_book_line_128x7_1sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x7_1sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_class1[] = {
+         1, 6, 3, 7, 2, 4, 5, 7,
+};
+
+static const static_codebook _huff_book_line_128x11_class1 = {
+        1, 8,
+        (char *)_huff_lengthlist_line_128x11_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_class2[] = {
+         1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
+         2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
+         4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
+        15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
+};
+
+static const static_codebook _huff_book_line_128x11_class2 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x11_class2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_class3[] = {
+         7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
+         5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
+         5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
+        12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
+};
+
+static const static_codebook _huff_book_line_128x11_class3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x11_class3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_0sub0[] = {
+         5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
+         7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
+         8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
+        10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
+        11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
+        17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
+        17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
+};
+
+static const static_codebook _huff_book_line_128x11_0sub0 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x11_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_1sub0[] = {
+         2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
+         6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
+};
+
+static const static_codebook _huff_book_line_128x11_1sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_128x11_1sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_1sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
+         8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
+        10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
+        15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
+        11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+};
+
+static const static_codebook _huff_book_line_128x11_1sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x11_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_2sub1[] = {
+         0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
+         5, 5,
+};
+
+static const static_codebook _huff_book_line_128x11_2sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_128x11_2sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_2sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
+         5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
+         8,11,
+};
+
+static const static_codebook _huff_book_line_128x11_2sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_128x11_2sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_2sub3[] = {
+         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, 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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
+         4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _huff_book_line_128x11_2sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x11_2sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_3sub1[] = {
+         0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
+         5, 4,
+};
+
+static const static_codebook _huff_book_line_128x11_3sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_128x11_3sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_3sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
+         8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
+        12, 6,
+};
+
+static const static_codebook _huff_book_line_128x11_3sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_128x11_3sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x11_3sub3[] = {
+         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, 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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
+         7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
+};
+
+static const static_codebook _huff_book_line_128x11_3sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x11_3sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_class1[] = {
+         1, 3, 4, 7, 2, 5, 6, 7,
+};
+
+static const static_codebook _huff_book_line_128x17_class1 = {
+        1, 8,
+        (char *)_huff_lengthlist_line_128x17_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_class2[] = {
+         1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
+         2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
+         6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
+        18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
+};
+
+static const static_codebook _huff_book_line_128x17_class2 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x17_class2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_class3[] = {
+         3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
+         2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
+         3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
+        13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
+};
+
+static const static_codebook _huff_book_line_128x17_class3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_128x17_class3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_0sub0[] = {
+         5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
+         8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
+         9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
+        10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
+        12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
+        14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
+        20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
+};
+
+static const static_codebook _huff_book_line_128x17_0sub0 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x17_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_1sub0[] = {
+         2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
+         6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
+};
+
+static const static_codebook _huff_book_line_128x17_1sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_128x17_1sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_1sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
+         8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
+        11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
+        12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
+        14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
+        17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_128x17_1sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x17_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_2sub1[] = {
+         0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
+         9, 4,
+};
+
+static const static_codebook _huff_book_line_128x17_2sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_128x17_2sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_2sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
+        12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
+        13,13,
+};
+
+static const static_codebook _huff_book_line_128x17_2sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_128x17_2sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_2sub3[] = {
+         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, 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, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
+         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+};
+
+static const static_codebook _huff_book_line_128x17_2sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x17_2sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_3sub1[] = {
+         0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
+         6, 4,
+};
+
+static const static_codebook _huff_book_line_128x17_3sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_128x17_3sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_3sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
+         8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
+        10, 8,
+};
+
+static const static_codebook _huff_book_line_128x17_3sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_128x17_3sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_128x17_3sub3[] = {
+         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, 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, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
+         6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
+        12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _huff_book_line_128x17_3sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_128x17_3sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_class1[] = {
+         2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
+};
+
+static const static_codebook _huff_book_line_1024x27_class1 = {
+        1, 16,
+        (char *)_huff_lengthlist_line_1024x27_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_class2[] = {
+         1, 4, 2, 6, 3, 7, 5, 7,
+};
+
+static const static_codebook _huff_book_line_1024x27_class2 = {
+        1, 8,
+        (char *)_huff_lengthlist_line_1024x27_class2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_class3[] = {
+         1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
+         4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
+         9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
+        20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
+         3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
+         5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
+         8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
+        18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
+         7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
+         6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
+         9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
+        20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
+        11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
+         9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
+        16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
+        20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
+};
+
+static const static_codebook _huff_book_line_1024x27_class3 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_1024x27_class3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_class4[] = {
+         2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
+         2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
+         4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
+        18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
+};
+
+static const static_codebook _huff_book_line_1024x27_class4 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_1024x27_class4,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_0sub0[] = {
+         5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
+         8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
+        11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
+        12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
+        13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
+        14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
+        22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
+};
+
+static const static_codebook _huff_book_line_1024x27_0sub0 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_1024x27_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_1sub0[] = {
+         2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
+         6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
+};
+
+static const static_codebook _huff_book_line_1024x27_1sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_1024x27_1sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_1sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
+         9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
+         9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
+        12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
+        15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
+        19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
+};
+
+static const static_codebook _huff_book_line_1024x27_1sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_1024x27_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_2sub0[] = {
+         1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
+};
+
+static const static_codebook _huff_book_line_1024x27_2sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_1024x27_2sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_2sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
+         7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
+         9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
+        10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
+        13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
+        16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
+};
+
+static const static_codebook _huff_book_line_1024x27_2sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_1024x27_2sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_3sub1[] = {
+         0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
+         5, 5,
+};
+
+static const static_codebook _huff_book_line_1024x27_3sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_1024x27_3sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_3sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
+         5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
+         9,11,
+};
+
+static const static_codebook _huff_book_line_1024x27_3sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_1024x27_3sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_3sub3[] = {
+         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, 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, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
+         4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+};
+
+static const static_codebook _huff_book_line_1024x27_3sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_1024x27_3sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_4sub1[] = {
+         0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
+         5, 4,
+};
+
+static const static_codebook _huff_book_line_1024x27_4sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_1024x27_4sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_4sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
+         7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
+         9,12,
+};
+
+static const static_codebook _huff_book_line_1024x27_4sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_1024x27_4sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_1024x27_4sub3[] = {
+         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, 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, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
+         6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
+};
+
+static const static_codebook _huff_book_line_1024x27_4sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_1024x27_4sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_class1[] = {
+         2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
+};
+
+static const static_codebook _huff_book_line_2048x27_class1 = {
+        1, 16,
+        (char *)_huff_lengthlist_line_2048x27_class1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_class2[] = {
+         1, 2, 3, 6, 4, 7, 5, 7,
+};
+
+static const static_codebook _huff_book_line_2048x27_class2 = {
+        1, 8,
+        (char *)_huff_lengthlist_line_2048x27_class2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_class3[] = {
+         3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
+         5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
+         9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
+        16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
+         5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
+         5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
+         9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
+        16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
+         8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
+         6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
+        10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
+        16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+        16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
+        12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
+        16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+        16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_2048x27_class3 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_2048x27_class3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_class4[] = {
+         2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
+         2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
+         6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
+        16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_2048x27_class4 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_2048x27_class4,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_0sub0[] = {
+         5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
+         6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
+         9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
+        11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
+        11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
+        12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
+        14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
+        17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
+};
+
+static const static_codebook _huff_book_line_2048x27_0sub0 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_2048x27_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_1sub0[] = {
+         4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
+         5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
+};
+
+static const static_codebook _huff_book_line_2048x27_1sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_2048x27_1sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_1sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
+         8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
+         9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
+        10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
+        13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
+        15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
+};
+
+static const static_codebook _huff_book_line_2048x27_1sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_2048x27_1sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_2sub0[] = {
+         2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
+         6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
+};
+
+static const static_codebook _huff_book_line_2048x27_2sub0 = {
+        1, 32,
+        (char *)_huff_lengthlist_line_2048x27_2sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_2sub1[] = {
+         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, 0, 0, 0, 0, 0, 0, 0,
+         3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
+         6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
+         7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
+        10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
+        12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+};
+
+static const static_codebook _huff_book_line_2048x27_2sub1 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_2048x27_2sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_3sub1[] = {
+         0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+         5, 5,
+};
+
+static const static_codebook _huff_book_line_2048x27_3sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_2048x27_3sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_3sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
+         6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
+        10,12,
+};
+
+static const static_codebook _huff_book_line_2048x27_3sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_2048x27_3sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_3sub3[] = {
+         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, 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, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+};
+
+static const static_codebook _huff_book_line_2048x27_3sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_2048x27_3sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_4sub1[] = {
+         0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
+         4, 5,
+};
+
+static const static_codebook _huff_book_line_2048x27_4sub1 = {
+        1, 18,
+        (char *)_huff_lengthlist_line_2048x27_4sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_4sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+         0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
+         6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
+        10,10,
+};
+
+static const static_codebook _huff_book_line_2048x27_4sub2 = {
+        1, 50,
+        (char *)_huff_lengthlist_line_2048x27_4sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_2048x27_4sub3[] = {
+         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, 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, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
+         5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
+};
+
+static const static_codebook _huff_book_line_2048x27_4sub3 = {
+        1, 128,
+        (char *)_huff_lengthlist_line_2048x27_4sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4low_class0[] = {
+         4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
+         6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
+         8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
+        19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
+         5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
+         6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
+         9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
+        19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
+         7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
+         8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
+         9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
+        18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
+        16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
+        16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
+        17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
+        18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
+};
+
+static const static_codebook _huff_book_line_256x4low_class0 = {
+        1, 256,
+        (char *)_huff_lengthlist_line_256x4low_class0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4low_0sub0[] = {
+         1, 3, 2, 3,
+};
+
+static const static_codebook _huff_book_line_256x4low_0sub0 = {
+        1, 4,
+        (char *)_huff_lengthlist_line_256x4low_0sub0,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4low_0sub1[] = {
+         0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
+};
+
+static const static_codebook _huff_book_line_256x4low_0sub1 = {
+        1, 10,
+        (char *)_huff_lengthlist_line_256x4low_0sub1,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4low_0sub2[] = {
+         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
+         4, 4, 4, 4, 5, 5, 5, 6, 6,
+};
+
+static const static_codebook _huff_book_line_256x4low_0sub2 = {
+        1, 25,
+        (char *)_huff_lengthlist_line_256x4low_0sub2,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist_line_256x4low_0sub3[] = {
+         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, 3, 4, 2, 4, 3, 5, 4,
+         5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
+         7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
+};
+
+static const static_codebook _huff_book_line_256x4low_0sub3 = {
+        1, 64,
+        (char *)_huff_lengthlist_line_256x4low_0sub3,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
diff --git a/vorbis/lib/books/uncoupled/res_books_uncoupled.h b/vorbis/lib/books/uncoupled/res_books_uncoupled.h
new file mode 100644 (file)
index 0000000..3d658ec
--- /dev/null
@@ -0,0 +1,7757 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: static codebooks autogenerated by huff/huffbuld
+
+ ********************************************************************/
+
+#include "codebook.h"
+
+static const long _vq_quantlist__16u0__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u0__p1_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
+        10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
+        11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
+        10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
+        11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
+        12,
+};
+
+static const static_codebook _16u0__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u0__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16u0__p1_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u0__p2_0[] = {
+         2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
+         8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
+         9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
+         8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
+         9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
+         8,
+};
+
+static const static_codebook _16u0__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u0__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16u0__p2_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16u0__p3_0[] = {
+         1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
+         9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
+        10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
+        13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
+        11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
+        10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
+        13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
+        12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
+        11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
+        14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
+        10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
+        11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
+        12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
+        17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
+        17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
+        13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
+        11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
+        12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
+        13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
+        13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
+        12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
+        12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
+        12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
+        17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
+        17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
+         8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
+        17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
+        13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
+        18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
+        17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
+        12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
+        18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
+        13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
+        16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
+        18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
+        11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
+        14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
+        17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
+        17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
+        18,
+};
+
+static const static_codebook _16u0__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16u0__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16u0__p3_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16u0__p4_0[] = {
+         3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
+        10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
+         8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
+        11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
+        10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
+        10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
+        12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
+        11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
+        10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
+        13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
+         8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
+         8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
+        10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
+        13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
+        14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
+        12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
+         8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
+        11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
+        11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
+        11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
+        10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
+        11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
+        14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
+        13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
+         9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
+        12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
+        11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
+        17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
+        15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
+        11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
+        14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
+        11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
+        12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
+        15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
+        10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
+        12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
+        14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
+        14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
+        11,
+};
+
+static const static_codebook _16u0__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16u0__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16u0__p4_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16u0__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
+         9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
+         9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
+         9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+         9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
+        12,
+};
+
+static const static_codebook _16u0__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16u0__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16u0__p5_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__16u0__p6_0[] = {
+         1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
+         9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
+        11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
+        15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
+        18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
+        11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
+        15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
+        18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
+         0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
+        17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
+        18, 0,19, 0, 0, 0, 0, 0, 0,
+};
+
+static const static_codebook _16u0__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__16u0__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__16u0__p6_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16u0__p6_1[] = {
+         1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
+         6, 6, 7, 7, 6, 6, 6, 7, 7,
+};
+
+static const static_codebook _16u0__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__16u0__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16u0__p6_1,
+        0
+};
+
+static const long _vq_quantlist__16u0__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u0__p7_0[] = {
+         1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _16u0__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u0__p7_0,
+        1, -518803456, 1628680192, 2, 0,
+        (long *)_vq_quantlist__16u0__p7_0,
+        0
+};
+
+static const long _vq_quantlist__16u0__p7_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__16u0__p7_1[] = {
+         1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
+         8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
+         9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
+        10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _16u0__p7_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__16u0__p7_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__16u0__p7_1,
+        0
+};
+
+static const long _vq_quantlist__16u0__p7_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__16u0__p7_2[] = {
+         1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
+         9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
+        11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
+         8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
+        10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
+        11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
+        11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
+         9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
+         9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
+        11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
+        12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
+        12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
+        10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
+        12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
+        12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
+        12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
+        10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
+        11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
+        12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
+        12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
+        12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
+         9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
+        11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
+        12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
+        11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
+        10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
+        12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
+        10,10,12,11,10,11,11,11,10,
+};
+
+static const static_codebook _16u0__p7_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__16u0__p7_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16u0__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__16u0__single[] = {
+         3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
+         8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
+        12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
+         8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
+};
+
+static const static_codebook _huff_book__16u0__single = {
+        2, 64,
+        (char *)_huff_lengthlist__16u0__single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__16u1__long[] = {
+         3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
+        11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
+         7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
+        18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
+         9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
+        11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
+        16,13,16,18,
+};
+
+static const static_codebook _huff_book__16u1__long = {
+        2, 100,
+        (char *)_huff_lengthlist__16u1__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__16u1__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u1__p1_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
+         9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
+        10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
+         9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
+        10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
+        11,
+};
+
+static const static_codebook _16u1__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u1__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16u1__p1_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u1__p2_0[] = {
+         3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
+         7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
+         8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
+         7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
+         8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
+         8,
+};
+
+static const static_codebook _16u1__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u1__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__16u1__p2_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16u1__p3_0[] = {
+         1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
+        10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
+        10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
+        13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
+        11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
+        10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
+        13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
+        12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
+        11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
+        14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
+        10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
+        10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
+        12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
+        16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
+        17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
+        13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
+        10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
+        12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
+        12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
+        13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
+        12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
+        12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
+        12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
+        17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
+        15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
+         9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
+        15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
+        13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
+        17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
+        17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
+        13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
+        17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
+        12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
+        15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
+        17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
+        11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
+        14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
+        16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
+        17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
+        16,
+};
+
+static const static_codebook _16u1__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16u1__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16u1__p3_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__16u1__p4_0[] = {
+         4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
+        10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
+         8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
+        11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
+        10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
+        10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
+        11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
+        10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
+        10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
+        12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
+         8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
+        10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
+        12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
+        14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
+        11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
+         7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
+        10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
+        10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
+        10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
+        11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
+        10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
+        11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
+        15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
+        13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
+         9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
+        12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
+        10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
+        14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
+        14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
+        11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
+        14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
+        11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
+        13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
+        14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
+        10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
+        12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
+        14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
+        14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
+        11,
+};
+
+static const static_codebook _16u1__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__16u1__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__16u1__p4_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16u1__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
+        10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
+         9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
+        10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
+        10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
+        13,
+};
+
+static const static_codebook _16u1__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16u1__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16u1__p5_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p6_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__16u1__p6_0[] = {
+         3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
+         9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
+         8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
+         8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
+         9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
+        11,
+};
+
+static const static_codebook _16u1__p6_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__16u1__p6_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16u1__p6_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__16u1__p7_0[] = {
+         1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
+        12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
+        13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
+        13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
+        15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
+        13,
+};
+
+static const static_codebook _16u1__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__16u1__p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__16u1__p7_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__16u1__p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
+         8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
+         8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
+         9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
+         9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
+        10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
+         8, 9, 9,10,10,10,10,10,10,
+};
+
+static const static_codebook _16u1__p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__16u1__p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16u1__p7_1,
+        0
+};
+
+static const long _vq_quantlist__16u1__p8_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__16u1__p8_0[] = {
+         1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
+         9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
+        12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
+         9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
+        17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
+        12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
+        15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
+        13,14,14,15,15,16,16,15,16,
+};
+
+static const static_codebook _16u1__p8_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__16u1__p8_0,
+        1, -524582912, 1618345984, 4, 0,
+        (long *)_vq_quantlist__16u1__p8_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p8_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__16u1__p8_1[] = {
+         2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
+         8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
+         8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
+         7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
+         8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
+         8, 9, 9, 9, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _16u1__p8_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__16u1__p8_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__16u1__p8_1,
+        0
+};
+
+static const long _vq_quantlist__16u1__p9_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__16u1__p9_0[] = {
+         1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8,
+};
+
+static const static_codebook _16u1__p9_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__16u1__p9_0,
+        1, -514071552, 1627381760, 4, 0,
+        (long *)_vq_quantlist__16u1__p9_0,
+        0
+};
+
+static const long _vq_quantlist__16u1__p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__16u1__p9_1[] = {
+         1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
+        10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
+         9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
+        10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
+        10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
+        10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
+        10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
+        10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _16u1__p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__16u1__p9_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__16u1__p9_1,
+        0
+};
+
+static const long _vq_quantlist__16u1__p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__16u1__p9_2[] = {
+         1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
+         9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
+        11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
+         9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
+        11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
+        10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
+        11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
+        11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
+         9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
+         9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
+        11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
+         8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
+        11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
+        11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
+         9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
+         9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
+        11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
+         9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
+        10,
+};
+
+static const static_codebook _16u1__p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__16u1__p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__16u1__p9_2,
+        0
+};
+
+static const char _huff_lengthlist__16u1__short[] = {
+         5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
+        10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
+         7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
+        15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
+         5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
+         9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
+        16,16,16,16,
+};
+
+static const static_codebook _huff_book__16u1__short = {
+        2, 100,
+        (char *)_huff_lengthlist__16u1__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__16u2__long[] = {
+        5, 8,10,10,10,11,11,12,14,18, 7, 5, 5, 6, 8, 9,
+       10,12,14,17, 9, 5, 4, 5, 6, 8,10,11,13,19, 9, 5,
+        4, 4, 5, 6, 9,10,12,17, 8, 6, 5, 4, 4, 5, 7,10,
+       11,15, 8, 7, 7, 6, 5, 5, 6, 9,11,14, 8, 9, 8, 7,
+        6, 5, 6, 7,11,14, 9,11,11, 9, 7, 6, 6, 6, 9,14,
+       11,14,15,13, 9, 8, 7, 7, 9,14,13,15,19,17,12,11,
+       10, 9,10,14,
+};
+
+static const static_codebook _huff_book__16u2__long = {
+       2, 100,
+       (char *)_huff_lengthlist__16u2__long,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__16u2_p1_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__16u2_p1_0[] = {
+        1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
+        9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 8, 9,
+        9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,10,10, 7, 9, 9,
+        9,10, 9, 9,10,11, 5, 8, 7, 7, 9, 9, 8, 9, 9, 7,
+        9, 9, 9,11,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
+       10,
+};
+
+static const static_codebook _16u2_p1_0 = {
+       4, 81,
+       (char *)_vq_lengthlist__16u2_p1_0,
+       1, -535822336, 1611661312, 2, 0,
+       (long *)_vq_quantlist__16u2_p1_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p2_0[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__16u2_p2_0[] = {
+        3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
+       10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
+        8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
+       11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
+       10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
+       10,10,10,12,12, 9,10,10,12,12,12,12,12,14,14,11,
+       12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
+       10,12,12,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
+        9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
+       12,10,10,10,12,12, 7, 8, 8,11,10, 8, 9, 9,11,11,
+        8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 7,
+        8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+       10,13,12,10,11,11,13,13,10,11,10,13,12,10,11,11,
+       13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
+       14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
+       12,13,12,14,13,12,13,13,14,15, 5, 7, 7, 9,10, 7,
+        8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
+       11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
+       10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
+       10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
+       10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
+       10,11,12,13,12,13,13,15,14,12,12,13,12,14, 9,10,
+       11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
+       14,14,12,13,12,14,13, 8,10,10,12,12, 9,11,10,13,
+       12, 9,10,10,12,13,12,13,13,14,14,12,12,12,14,14,
+        9,10,10,13,13,10,11,11,13,13,10,11,11,13,13,13,
+       13,13,14,15,12,13,13,14,15, 9,10,10,12,13,10,11,
+       10,13,13,10,11,11,12,13,12,13,12,15,14,12,13,13,
+       14,15,11,12,12,15,14,12,12,13,14,15,12,13,13,15,
+       14,13,13,15,14,16,14,14,14,16,15,11,12,12,14,14,
+       11,12,12,14,14,12,13,13,14,15,13,14,13,15,13,14,
+       14,14,15,16, 8, 9,10,12,12, 9,10,10,13,12, 9,10,
+       11,12,13,12,12,12,14,14,12,13,13,14,14, 9,10,10,
+       13,12,10,11,11,13,13,10,10,11,13,13,12,13,13,15,
+       14,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
+       10,11,11,13,13,12,13,13,14,14,13,13,13,15,15,11,
+       12,12,14,13,12,13,13,15,14,11,12,12,14,14,14,14,
+       14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
+       14,15,12,13,12,14,14,14,14,14,16,16,14,15,13,16,
+       14,
+};
+
+static const static_codebook _16u2_p2_0 = {
+       4, 625,
+       (char *)_vq_lengthlist__16u2_p2_0,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__16u2_p2_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p3_0[] = {
+       4,
+       3,
+       5,
+       2,
+       6,
+       1,
+       7,
+       0,
+       8,
+};
+
+static const char _vq_lengthlist__16u2_p3_0[] = {
+        2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
+        9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
+        8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
+        8, 8, 9, 9,11,10, 7, 7, 8, 8, 8, 9, 9,10,11, 9,
+        9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,10,11,11,
+       11,
+};
+
+static const static_codebook _16u2_p3_0 = {
+       2, 81,
+       (char *)_vq_lengthlist__16u2_p3_0,
+       1, -531628032, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16u2_p3_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p4_0[] = {
+       8,
+       7,
+       9,
+       6,
+       10,
+       5,
+       11,
+       4,
+       12,
+       3,
+       13,
+       2,
+       14,
+       1,
+       15,
+       0,
+       16,
+};
+
+static const char _vq_lengthlist__16u2_p4_0[] = {
+        2, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
+       11, 5, 5, 5, 7, 6, 8, 7, 9, 9, 9, 9,10,10,11,11,
+       12,12, 5, 5, 5, 6, 6, 7, 8, 8, 9, 9, 9,10,10,11,
+       11,12,12, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+       11,11,12,12, 6, 6, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
+       10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
+       11,11,11,11,12,12, 7, 7, 8, 8, 8, 9, 9, 9, 9,10,
+       10,11,11,11,11,12,12, 8, 9, 9, 9, 9, 9, 9,10,10,
+       10,10,11,11,12,12,12,12, 8, 9, 9, 9, 9, 9, 9,10,
+       10,10,10,11,11,12,12,12,12, 9, 9, 9, 9, 9,10,10,
+       10,10,10,11,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,
+       10,10,10,11,10,11,11,12,12,13,13,10,10,10,10,10,
+       11,11,11,11,11,11,11,12,12,12,13,13,10,10,10,10,
+       10,11,11,11,11,11,11,12,11,12,12,13,13,11,11,11,
+       11,11,11,11,12,12,12,12,12,12,13,13,13,13,11,11,
+       11,11,11,11,11,12,12,12,12,13,12,13,13,13,13,11,
+       12,12,12,12,12,12,12,12,13,13,13,13,13,13,14,14,
+       11,12,12,12,12,12,12,12,13,13,13,13,13,13,13,14,
+       14,
+};
+
+static const static_codebook _16u2_p4_0 = {
+       2, 289,
+       (char *)_vq_lengthlist__16u2_p4_0,
+       1, -529530880, 1611661312, 5, 0,
+       (long *)_vq_quantlist__16u2_p4_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p5_0[] = {
+       1,
+       0,
+       2,
+};
+
+static const char _vq_lengthlist__16u2_p5_0[] = {
+        1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9, 9, 7,
+        9,10, 5, 8, 8, 7,10, 9, 7,10, 9, 5, 8, 8, 8,11,
+       10, 8,10,10, 7,10,10, 9, 9,12,10,12,12, 7,10,10,
+        9,12,10,10,11,12, 5, 8, 8, 8,10,10, 8,11,11, 7,
+       11,10,10,12,11, 9,10,12, 7,10,11,10,12,12, 9,12,
+        9,
+};
+
+static const static_codebook _16u2_p5_0 = {
+       4, 81,
+       (char *)_vq_lengthlist__16u2_p5_0,
+       1, -529137664, 1618345984, 2, 0,
+       (long *)_vq_quantlist__16u2_p5_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p5_1[] = {
+       5,
+       4,
+       6,
+       3,
+       7,
+       2,
+       8,
+       1,
+       9,
+       0,
+       10,
+};
+
+static const char _vq_lengthlist__16u2_p5_1[] = {
+        2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7,
+        7, 7, 8, 8, 8, 8, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8,
+        8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
+        7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
+        8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
+        8, 8, 8, 8, 8, 9, 9, 9, 9,
+};
+
+static const static_codebook _16u2_p5_1 = {
+       2, 121,
+       (char *)_vq_lengthlist__16u2_p5_1,
+       1, -531365888, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16u2_p5_1,
+       0
+};
+
+static const long _vq_quantlist__16u2_p6_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__16u2_p6_0[] = {
+        1, 5, 4, 7, 7, 8, 8, 8, 8,10,10,11,11, 4, 6, 6,
+        7, 7, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9,
+        9, 9, 9,10,10,11,11, 7, 8, 8, 9, 9, 9, 9,10,10,
+       11,11,12,12, 7, 7, 7, 9, 8,10, 9,10,10,11,11,12,
+       12, 8, 9, 9, 9,10,10,10,11,11,12,12,13,13, 8, 9,
+        9,10, 9,10,10,11,11,12,12,13,13, 8, 9, 9,10,10,
+       11,11,11,11,12,12,13,13, 8, 9, 9,10,10,11,11,12,
+       11,12,12,13,13,10,10,10,11,11,12,12,12,12,13,13,
+       14,14,10,10,10,11,11,12,12,12,12,13,13,14,14,11,
+       11,11,12,12,13,13,13,13,14,14,14,14,11,11,11,12,
+       12,13,13,13,13,14,14,14,14,
+};
+
+static const static_codebook _16u2_p6_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__16u2_p6_0,
+       1, -526516224, 1616117760, 4, 0,
+       (long *)_vq_quantlist__16u2_p6_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p6_1[] = {
+       2,
+       1,
+       3,
+       0,
+       4,
+};
+
+static const char _vq_lengthlist__16u2_p6_1[] = {
+        2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _16u2_p6_1 = {
+       2, 25,
+       (char *)_vq_lengthlist__16u2_p6_1,
+       1, -533725184, 1611661312, 3, 0,
+       (long *)_vq_quantlist__16u2_p6_1,
+       0
+};
+
+static const long _vq_quantlist__16u2_p7_0[] = {
+       6,
+       5,
+       7,
+       4,
+       8,
+       3,
+       9,
+       2,
+       10,
+       1,
+       11,
+       0,
+       12,
+};
+
+static const char _vq_lengthlist__16u2_p7_0[] = {
+        1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
+        8, 8, 9, 9, 9, 9,10,10,11,10, 4, 6, 6, 8, 8, 9,
+        9, 9, 9,10,10,11,11, 7, 8, 8,10, 9,10,10,10,10,
+       11,11,12,12, 7, 8, 8,10,10,10,10,10,10,11,11,12,
+       12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
+        9,10,10,11,11,11,11,12,12,13,13, 8, 9, 9,11,10,
+       11,11,12,12,13,13,14,13, 8, 9, 9,10,10,11,11,12,
+       12,13,13,13,13, 9,10,10,11,11,12,12,13,13,13,13,
+       14,14, 9,10,10,11,11,12,12,13,13,13,13,14,14,10,
+       11,11,12,12,13,13,14,13,14,14,15,14,10,11,11,12,
+       12,13,13,14,13,14,14,15,14,
+};
+
+static const static_codebook _16u2_p7_0 = {
+       2, 169,
+       (char *)_vq_lengthlist__16u2_p7_0,
+       1, -523206656, 1618345984, 4, 0,
+       (long *)_vq_quantlist__16u2_p7_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p7_1[] = {
+       5,
+       4,
+       6,
+       3,
+       7,
+       2,
+       8,
+       1,
+       9,
+       0,
+       10,
+};
+
+static const char _vq_lengthlist__16u2_p7_1[] = {
+        2, 5, 5, 7, 7, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
+        7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
+        8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7,
+        7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
+        8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+        8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _16u2_p7_1 = {
+       2, 121,
+       (char *)_vq_lengthlist__16u2_p7_1,
+       1, -531365888, 1611661312, 4, 0,
+       (long *)_vq_quantlist__16u2_p7_1,
+       0
+};
+
+static const long _vq_quantlist__16u2_p8_0[] = {
+       7,
+       6,
+       8,
+       5,
+       9,
+       4,
+       10,
+       3,
+       11,
+       2,
+       12,
+       1,
+       13,
+       0,
+       14,
+};
+
+static const char _vq_lengthlist__16u2_p8_0[] = {
+        1, 4, 4, 7, 7, 8, 8, 7, 7, 9, 8,10, 9,11,11, 4,
+        7, 6, 9, 8, 9, 9, 9, 9,10, 9,11, 9,12, 9, 4, 6,
+        7, 8, 8, 9, 9, 9, 9,10,10,10,11,11,12, 7, 9, 8,
+       10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
+       10,10,11,10,10,11,11,11,12,12,13, 8, 9, 9,11,11,
+       11,11,11,11,12,12,13,13,13,13, 8, 9, 9,11,11,11,
+       11,11,11,12,12,13,13,13,14, 8, 9, 9,10,10,11,11,
+       12,11,13,13,14,13,14,14, 8, 9, 9,10,10,11,11,12,
+       12,12,12,13,13,14,14, 9,10,10,11,11,12,12,13,12,
+       13,13,14,14,15,15, 9,10,10,11,11,12,12,12,13,13,
+       13,14,14,14,15,10,11,11,12,12,13,13,14,13,14,14,
+       15,14,15,15,10,11,11,12,12,13,12,13,14,14,14,14,
+       14,15,15,11,12,12,13,13,13,13,14,14,15,14,15,15,
+       16,16,11,12,12,13,13,13,13,14,14,14,15,15,15,16,
+       16,
+};
+
+static const static_codebook _16u2_p8_0 = {
+       2, 225,
+       (char *)_vq_lengthlist__16u2_p8_0,
+       1, -520986624, 1620377600, 4, 0,
+       (long *)_vq_quantlist__16u2_p8_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p8_1[] = {
+       10,
+       9,
+       11,
+       8,
+       12,
+       7,
+       13,
+       6,
+       14,
+       5,
+       15,
+       4,
+       16,
+       3,
+       17,
+       2,
+       18,
+       1,
+       19,
+       0,
+       20,
+};
+
+static const char _vq_lengthlist__16u2_p8_1[] = {
+        3, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9,10,10,10,10, 5, 6, 6, 7, 7, 8,
+        8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
+        7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,
+       10,10,10,10, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+        9,10, 9,10,10,10, 9,10, 9, 8, 8, 8, 9, 8, 9, 9,
+        9, 9,10, 9,10,10,10,10,10,10,10,10,10,10, 8, 8,
+        8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,
+       10,10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,
+       10,10,10,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9, 9,
+       10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+        9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+        9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10, 9, 9,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10, 9,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _16u2_p8_1 = {
+       2, 441,
+       (char *)_vq_lengthlist__16u2_p8_1,
+       1, -529268736, 1611661312, 5, 0,
+       (long *)_vq_quantlist__16u2_p8_1,
+       0
+};
+
+static const long _vq_quantlist__16u2_p9_0[] = {
+       7,
+       6,
+       8,
+       5,
+       9,
+       4,
+       10,
+       3,
+       11,
+       2,
+       12,
+       1,
+       13,
+       0,
+       14,
+};
+
+static const char _vq_lengthlist__16u2_p9_0[] = {
+        1, 5, 3, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5,
+        7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 7,
+        8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+       10,
+};
+
+static const static_codebook _16u2_p9_0 = {
+       2, 225,
+       (char *)_vq_lengthlist__16u2_p9_0,
+       1, -510036736, 1631393792, 4, 0,
+       (long *)_vq_quantlist__16u2_p9_0,
+       0
+};
+
+static const long _vq_quantlist__16u2_p9_1[] = {
+       9,
+       8,
+       10,
+       7,
+       11,
+       6,
+       12,
+       5,
+       13,
+       4,
+       14,
+       3,
+       15,
+       2,
+       16,
+       1,
+       17,
+       0,
+       18,
+};
+
+static const char _vq_lengthlist__16u2_p9_1[] = {
+        1, 4, 4, 7, 7, 7, 7, 7, 6, 9, 7,10, 8,12,12,13,
+       13,14,14, 4, 7, 7, 9, 9, 9, 8, 9, 8,10, 9,11, 9,
+       14, 9,14,10,13,11, 4, 7, 7, 9, 9, 9, 9, 8, 9,10,
+       10,11,11,12,13,12,13,14,15, 7, 9, 9,10,11,10,10,
+       10,10,11,12,13,13,13,14,17,14,15,16, 7, 9, 9,10,
+       10,10,10,10,10,11,12,13,13,14,14,15,15,18,18, 8,
+        9, 9,11,10,11,11,11,12,13,12,14,14,16,15,15,17,
+       18,15, 8, 9, 9,10,10,11,11,11,11,13,13,14,14,15,
+       15,15,16,16,18, 7, 9, 8,10,10,11,11,12,12,14,14,
+       15,15,16,16,15,17,16,18, 8, 9, 9,10,10,11,12,12,
+       12,13,13,16,15,17,16,17,18,17,18, 9,10,10,12,11,
+       13,13,14,13,14,14,15,17,16,18,17,18,17,18, 9,10,
+       10,12,11,12,13,13,14,15,16,14,15,16,18,18,18,18,
+       17,11,11,11,13,13,14,14,16,15,15,15,16,15,15,18,
+       18,18,17,16,11,11,12,13,13,15,14,15,16,16,16,17,
+       16,15,18,17,18,16,18,12,13,13,15,15,15,16,18,16,
+       17,16,17,16,17,17,17,18,18,17,13,13,13,15,13,16,
+       15,17,16,16,16,18,18,18,18,16,17,17,18,13,15,14,
+       15,15,18,17,18,18,18,16,18,17,18,17,18,16,17,17,
+       14,14,14,15,16,17,16,18,18,18,17,18,17,18,18,18,
+       16,16,16,14,17,16,17,15,16,18,18,17,18,17,18,17,
+       18,18,18,17,18,17,15,16,15,18,15,18,17,16,18,18,
+       18,18,18,18,17,18,16,18,17,
+};
+
+static const static_codebook _16u2_p9_1 = {
+       2, 361,
+       (char *)_vq_lengthlist__16u2_p9_1,
+       1, -518287360, 1622704128, 5, 0,
+       (long *)_vq_quantlist__16u2_p9_1,
+       0
+};
+
+static const long _vq_quantlist__16u2_p9_2[] = {
+       24,
+       23,
+       25,
+       22,
+       26,
+       21,
+       27,
+       20,
+       28,
+       19,
+       29,
+       18,
+       30,
+       17,
+       31,
+       16,
+       32,
+       15,
+       33,
+       14,
+       34,
+       13,
+       35,
+       12,
+       36,
+       11,
+       37,
+       10,
+       38,
+       9,
+       39,
+       8,
+       40,
+       7,
+       41,
+       6,
+       42,
+       5,
+       43,
+       4,
+       44,
+       3,
+       45,
+       2,
+       46,
+       1,
+       47,
+       0,
+       48,
+};
+
+static const char _vq_lengthlist__16u2_p9_2[] = {
+        2, 3, 4, 4, 4, 5, 5, 6, 5, 6, 6, 6, 6, 6, 6, 7,
+        7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+        7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 7, 8, 8, 8, 8, 8,
+        8,
+};
+
+static const static_codebook _16u2_p9_2 = {
+       1, 49,
+       (char *)_vq_lengthlist__16u2_p9_2,
+       1, -526909440, 1611661312, 6, 0,
+       (long *)_vq_quantlist__16u2_p9_2,
+       0
+};
+
+static const char _huff_lengthlist__16u2__short[] = {
+        8,11,13,13,15,16,19,19,19,19,11, 8, 8, 9, 9,11,
+       13,15,19,20,14, 8, 7, 7, 8, 9,12,13,15,20,15, 9,
+        6, 5, 5, 7,10,12,14,18,14, 9, 7, 5, 3, 4, 7,10,
+       12,16,13,10, 8, 6, 3, 3, 5, 8,11,14,11,10, 9, 7,
+        5, 4, 4, 6,11,14,10,10,10, 8, 6, 5, 5, 6,10,14,
+       10,10,10, 9, 8, 7, 7, 7,10,14,11,12,12,12,11,10,
+       10,10,12,16,
+};
+
+static const static_codebook _huff_book__16u2__short = {
+       2, 100,
+       (char *)_huff_lengthlist__16u2__short,
+       0, 0, 0, 0, 0,
+       NULL,
+       0
+};
+
+static const long _vq_quantlist__8u0__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u0__p1_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
+        10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
+        11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
+        10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
+        11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
+        11,
+};
+
+static const static_codebook _8u0__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u0__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8u0__p1_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u0__p2_0[] = {
+         2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
+         7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
+         9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
+         8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
+         8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
+         8,
+};
+
+static const static_codebook _8u0__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u0__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8u0__p2_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8u0__p3_0[] = {
+         1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
+        10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
+        10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
+        12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
+        11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
+        10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
+        14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
+        12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
+        11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
+        14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
+        10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
+        10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
+        12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
+        15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
+        16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
+        13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
+        11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
+        12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
+        13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
+        13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
+        12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
+        13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
+        12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
+        16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
+        15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
+         9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
+        15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
+        13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
+        17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
+        17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
+        13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
+        17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
+        13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
+        16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
+         0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
+        12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
+        14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
+        17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
+        19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
+        16,
+};
+
+static const static_codebook _8u0__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8u0__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8u0__p3_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8u0__p4_0[] = {
+         3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
+         9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
+         8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
+        11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
+        10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
+        10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
+        11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
+        11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
+        10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
+        12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
+         8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
+         8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
+        10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
+        12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
+        13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
+        12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
+         8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
+        10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
+        10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
+        11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
+        10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
+        10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
+        11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
+        13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
+        13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
+         9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
+        12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
+        10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
+        15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
+        13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
+        11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
+        15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
+        11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
+        12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
+        14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
+        10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
+        12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
+        14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
+        14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
+        12,
+};
+
+static const static_codebook _8u0__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8u0__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8u0__p4_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8u0__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
+        10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
+         9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
+         9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+        10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
+        12,
+};
+
+static const static_codebook _8u0__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8u0__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8u0__p5_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__8u0__p6_0[] = {
+         1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
+         9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
+        11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
+        14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
+         0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
+        11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
+        15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
+        14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
+         0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
+        17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
+        16, 0,15, 0,17, 0, 0, 0, 0,
+};
+
+static const static_codebook _8u0__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__8u0__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__8u0__p6_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8u0__p6_1[] = {
+         1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
+         7, 7, 7, 7, 6, 7, 7, 7, 7,
+};
+
+static const static_codebook _8u0__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__8u0__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8u0__p6_1,
+        0
+};
+
+static const long _vq_quantlist__8u0__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u0__p7_0[] = {
+         1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _8u0__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u0__p7_0,
+        1, -518803456, 1628680192, 2, 0,
+        (long *)_vq_quantlist__8u0__p7_0,
+        0
+};
+
+static const long _vq_quantlist__8u0__p7_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__8u0__p7_1[] = {
+         1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
+         7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
+         7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
+        11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
+        10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
+        11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _8u0__p7_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__8u0__p7_1,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__8u0__p7_1,
+        0
+};
+
+static const long _vq_quantlist__8u0__p7_2[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__8u0__p7_2[] = {
+         1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
+        11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
+        10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
+        10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
+         9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
+        10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
+         9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
+         9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
+         9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
+         9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
+        10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
+        11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
+        11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
+        11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
+        12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
+        11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
+        11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
+        11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
+        11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
+        11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
+        10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
+         9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
+        10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
+        10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
+        10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
+        11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
+        10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
+        11,12,11,11,11,10,10,11,11,
+};
+
+static const static_codebook _8u0__p7_2 = {
+        2, 441,
+        (char *)_vq_lengthlist__8u0__p7_2,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8u0__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__8u0__single[] = {
+         4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
+         9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
+        10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
+         7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
+};
+
+static const static_codebook _huff_book__8u0__single = {
+        2, 64,
+        (char *)_huff_lengthlist__8u0__single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__8u1__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u1__p1_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
+         9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
+        10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
+         9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
+        10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
+        10,
+};
+
+static const static_codebook _8u1__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u1__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8u1__p1_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u1__p2_0[] = {
+         3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
+         7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
+         8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
+         7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
+         8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
+         7,
+};
+
+static const static_codebook _8u1__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u1__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__8u1__p2_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8u1__p3_0[] = {
+         1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
+        10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
+        10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
+        12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
+        11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
+        10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
+        13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
+        12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
+        11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
+        13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
+        10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
+        10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
+        12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
+        15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
+        15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
+        13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
+        10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
+        12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
+        12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
+        12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
+        12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
+        12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
+        12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
+        16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
+        15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
+         9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
+        15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
+        13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
+        17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
+        18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
+        12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
+        16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
+        13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
+        15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
+        16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
+        11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
+        14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
+        16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
+        18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
+        16,
+};
+
+static const static_codebook _8u1__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8u1__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8u1__p3_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__8u1__p4_0[] = {
+         4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
+         9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
+         8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
+        10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
+         9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
+         9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
+        11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
+        10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
+        12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
+         8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
+        10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
+        12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
+        14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
+        11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
+         7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
+        10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
+        10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
+        10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
+        10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
+        10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
+        10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
+        14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
+        12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
+         9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
+        12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
+        10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
+        13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
+        13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
+        10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
+        13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
+        10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
+        12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
+        13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
+         9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
+        12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
+        13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
+        13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
+        10,
+};
+
+static const static_codebook _8u1__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__8u1__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__8u1__p4_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8u1__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
+        10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
+         9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
+         9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
+        10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
+        13,
+};
+
+static const static_codebook _8u1__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8u1__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8u1__p5_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p6_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__8u1__p6_0[] = {
+         3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
+         9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
+         8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
+         8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
+         9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
+        10,
+};
+
+static const static_codebook _8u1__p6_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__8u1__p6_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8u1__p6_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__8u1__p7_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
+        10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
+        12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
+        10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
+        12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
+        11,
+};
+
+static const static_codebook _8u1__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__8u1__p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__8u1__p7_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__8u1__p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
+         8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
+         9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
+         9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
+        10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
+         9, 9, 9, 9, 9,10,10,10,10,
+};
+
+static const static_codebook _8u1__p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__8u1__p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8u1__p7_1,
+        0
+};
+
+static const long _vq_quantlist__8u1__p8_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__8u1__p8_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
+         9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
+        12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
+         9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
+        14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
+        12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
+        14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
+        12,13,13,14,14,15,15,15,15,
+};
+
+static const static_codebook _8u1__p8_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__8u1__p8_0,
+        1, -524582912, 1618345984, 4, 0,
+        (long *)_vq_quantlist__8u1__p8_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p8_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__8u1__p8_1[] = {
+         2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
+         7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
+         8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
+         7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
+         8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
+         8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
+         8, 8, 8, 8, 8, 9, 9, 9, 9,
+};
+
+static const static_codebook _8u1__p8_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__8u1__p8_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__8u1__p8_1,
+        0
+};
+
+static const long _vq_quantlist__8u1__p9_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__8u1__p9_0[] = {
+         1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
+        11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
+         9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _8u1__p9_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__8u1__p9_0,
+        1, -514071552, 1627381760, 4, 0,
+        (long *)_vq_quantlist__8u1__p9_0,
+        0
+};
+
+static const long _vq_quantlist__8u1__p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__8u1__p9_1[] = {
+         1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
+         7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
+         7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
+        12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
+        11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
+        14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
+        13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
+        11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
+        12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
+        12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
+        12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
+        12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
+        12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
+        12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
+        13,
+};
+
+static const static_codebook _8u1__p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__8u1__p9_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__8u1__p9_1,
+        0
+};
+
+static const long _vq_quantlist__8u1__p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__8u1__p9_2[] = {
+         2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
+        10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
+        10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+         9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
+         9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+        10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+         9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _8u1__p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__8u1__p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__8u1__p9_2,
+        0
+};
+
+static const char _huff_lengthlist__8u1__single[] = {
+         4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
+        10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
+         8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
+        11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
+         6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
+         9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
+        13, 8, 8,15,
+};
+
+static const static_codebook _huff_book__8u1__single = {
+        2, 100,
+        (char *)_huff_lengthlist__8u1__single,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u0__long[] = {
+         5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
+        13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
+        15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
+         9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
+};
+
+static const static_codebook _huff_book__44u0__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44u0__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u0__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u0__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
+        10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
+        11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
+        10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
+        11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
+        13,
+};
+
+static const static_codebook _44u0__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u0__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u0__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u0__p2_0[] = {
+         2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
+         8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
+         8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
+         8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
+         8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
+         9,
+};
+
+static const static_codebook _44u0__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u0__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u0__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u0__p3_0[] = {
+         1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
+        10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
+        10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
+        13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
+        11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
+        10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
+        14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
+        12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
+        11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
+        14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
+        10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
+        10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
+        12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
+        16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
+        19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
+        14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
+        10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
+        12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
+        13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
+        13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
+        12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
+        12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
+        12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
+        17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
+        17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
+         9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
+        17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
+        13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
+        18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
+        17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
+        13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
+        17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
+        13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
+        16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
+        20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
+        11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
+        14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
+        17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
+         0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
+        19,
+};
+
+static const static_codebook _44u0__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u0__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u0__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u0__p4_0[] = {
+         4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
+        10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
+         8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
+        12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
+        10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
+        10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
+        12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
+        10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
+        10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
+        13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
+         8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
+        14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
+        15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
+        12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
+         8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
+        11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
+        11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
+        10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
+        10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
+        11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
+        16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
+        13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
+         9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
+        13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
+        10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
+        15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
+        15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
+        11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
+        16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
+        11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
+        14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
+        16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
+        10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
+        13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
+        16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
+        15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
+        12,
+};
+
+static const static_codebook _44u0__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u0__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u0__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u0__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
+         9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
+         9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
+         9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+         9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
+        12,
+};
+
+static const static_codebook _44u0__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u0__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u0__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u0__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
+         8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
+         9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
+        12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
+        15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
+         9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
+        12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
+        12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
+        17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
+        15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
+        15,17,16,17,18,17,17,18, 0,
+};
+
+static const static_codebook _44u0__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u0__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u0__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u0__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
+         6, 6, 6, 6, 5, 6, 6, 6, 6,
+};
+
+static const static_codebook _44u0__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u0__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u0__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u0__p7_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u0__p7_0[] = {
+         1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _44u0__p7_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u0__p7_0,
+        1, -518709248, 1626677248, 3, 0,
+        (long *)_vq_quantlist__44u0__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u0__p7_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u0__p7_1[] = {
+         1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
+         8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
+         7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
+        12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
+        12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
+         8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
+        13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
+        14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
+        15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
+        15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
+        15,15,15,15,15,15,15,15,15,
+};
+
+static const static_codebook _44u0__p7_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u0__p7_1,
+        1, -523010048, 1618608128, 4, 0,
+        (long *)_vq_quantlist__44u0__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u0__p7_2[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u0__p7_2[] = {
+         2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
+         9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
+         8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
+         9, 9, 9,10, 9, 9,10,10, 9,
+};
+
+static const static_codebook _44u0__p7_2 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u0__p7_2,
+        1, -531103744, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u0__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44u0__short[] = {
+        12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
+         4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
+         6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
+        11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
+};
+
+static const static_codebook _huff_book__44u0__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44u0__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u1__long[] = {
+         5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
+        13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
+        15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
+         9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
+};
+
+static const static_codebook _huff_book__44u1__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44u1__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u1__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u1__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
+        10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
+        11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
+        10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
+        11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
+        13,
+};
+
+static const static_codebook _44u1__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u1__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u1__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u1__p2_0[] = {
+         2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
+         8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
+         8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
+         8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
+         8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
+         9,
+};
+
+static const static_codebook _44u1__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u1__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u1__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u1__p3_0[] = {
+         1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
+        10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
+        10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
+        13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
+        11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
+        10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
+        14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
+        12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
+        11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
+        14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
+        10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
+        10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
+        12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
+        16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
+        19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
+        14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
+        10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
+        12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
+        13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
+        13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
+        12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
+        12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
+        12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
+        17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
+        17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
+         9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
+        17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
+        13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
+        18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
+        17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
+        13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
+        17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
+        13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
+        16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
+        20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
+        11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
+        14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
+        17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
+         0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
+        19,
+};
+
+static const static_codebook _44u1__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u1__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u1__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u1__p4_0[] = {
+         4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
+        10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
+         8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
+        12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
+        10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
+        10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
+        12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
+        10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
+        10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
+        13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
+         8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
+        14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
+        15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
+        12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
+         8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
+        11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
+        11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
+        10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
+        10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
+        11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
+        16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
+        13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
+         9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
+        13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
+        10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
+        15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
+        15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
+        11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
+        16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
+        11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
+        14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
+        16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
+        10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
+        13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
+        16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
+        15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
+        12,
+};
+
+static const static_codebook _44u1__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u1__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u1__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u1__p5_0[] = {
+         1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
+         9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
+         9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
+         9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+         9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
+        12,
+};
+
+static const static_codebook _44u1__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u1__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u1__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u1__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
+         8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
+         9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
+        12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
+        15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
+         9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
+        12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
+        12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
+        17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
+        15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
+        15,17,16,17,18,17,17,18, 0,
+};
+
+static const static_codebook _44u1__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u1__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u1__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u1__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
+         6, 6, 6, 6, 5, 6, 6, 6, 6,
+};
+
+static const static_codebook _44u1__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u1__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u1__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u1__p7_0[] = {
+        3,
+        2,
+        4,
+        1,
+        5,
+        0,
+        6,
+};
+
+static const char _vq_lengthlist__44u1__p7_0[] = {
+         1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8,
+};
+
+static const static_codebook _44u1__p7_0 = {
+        2, 49,
+        (char *)_vq_lengthlist__44u1__p7_0,
+        1, -518017024, 1626677248, 3, 0,
+        (long *)_vq_quantlist__44u1__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u1__p7_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u1__p7_1[] = {
+         1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
+         8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
+         7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
+        12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
+        12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
+         8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
+        13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
+        14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
+        15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
+        15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
+        15,15,15,15,15,15,15,15,15,
+};
+
+static const static_codebook _44u1__p7_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u1__p7_1,
+        1, -523010048, 1618608128, 4, 0,
+        (long *)_vq_quantlist__44u1__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u1__p7_2[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u1__p7_2[] = {
+         2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
+         9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
+         8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
+         9, 9, 9,10, 9, 9,10,10, 9,
+};
+
+static const static_codebook _44u1__p7_2 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u1__p7_2,
+        1, -531103744, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u1__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44u1__short[] = {
+        12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
+         4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
+         6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
+        11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
+};
+
+static const static_codebook _huff_book__44u1__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44u1__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u2__long[] = {
+         5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
+        13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
+        14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
+         9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
+};
+
+static const static_codebook _huff_book__44u2__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44u2__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u2__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u2__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
+        10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
+        11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
+        10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
+        11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
+        13,
+};
+
+static const static_codebook _44u2__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u2__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u2__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u2__p2_0[] = {
+         2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
+         8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
+         8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
+         7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
+         8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
+         9,
+};
+
+static const static_codebook _44u2__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u2__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u2__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u2__p3_0[] = {
+         2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
+         9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
+         9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
+        12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
+        11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
+        10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
+        13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
+        11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
+        10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
+        13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
+         9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
+         9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
+        12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
+        16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
+        17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
+        13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
+         9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
+        11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
+        12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
+        12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
+        12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
+        11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
+        11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
+        18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
+        15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
+         9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
+        16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
+        12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
+         0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
+        17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
+        12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
+        17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
+        12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
+        16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
+        18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
+        11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
+        14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
+        19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
+         0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
+         0,
+};
+
+static const static_codebook _44u2__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u2__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u2__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u2__p4_0[] = {
+         4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
+         9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
+        11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
+        10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
+        10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
+        12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
+        10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
+        10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
+        12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
+         8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
+        13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
+        15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
+        12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
+         8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
+        11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
+        11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
+        10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
+        10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
+        10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
+        15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
+        13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
+         9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
+        13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
+        10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
+        14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
+        15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
+        11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
+        15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
+        10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
+        13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
+        14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
+        10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
+        12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
+        15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
+        15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
+        13,
+};
+
+static const static_codebook _44u2__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u2__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u2__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u2__p5_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
+        10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
+         9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
+         9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
+        10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
+        13,
+};
+
+static const static_codebook _44u2__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u2__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u2__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u2__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
+         8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
+         9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
+        12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
+        15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
+        10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
+        12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
+        13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
+        18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
+        15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
+        15,17,17,16,18,17,18, 0, 0,
+};
+
+static const static_codebook _44u2__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u2__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u2__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u2__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
+         6, 5, 6, 6, 5, 5, 6, 6, 6,
+};
+
+static const static_codebook _44u2__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u2__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u2__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u2__p7_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u2__p7_0[] = {
+         1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
+        12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,
+};
+
+static const static_codebook _44u2__p7_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u2__p7_0,
+        1, -516612096, 1626677248, 4, 0,
+        (long *)_vq_quantlist__44u2__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u2__p7_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u2__p7_1[] = {
+         1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
+         8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
+         8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
+        12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
+        13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
+         9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
+        13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
+        14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
+        17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
+        12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
+        14,14,14,17,15,17,17,17,17,
+};
+
+static const static_codebook _44u2__p7_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u2__p7_1,
+        1, -523010048, 1618608128, 4, 0,
+        (long *)_vq_quantlist__44u2__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u2__p7_2[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u2__p7_2[] = {
+         2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
+         7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
+         7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
+         9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
+         8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _44u2__p7_2 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u2__p7_2,
+        1, -531103744, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u2__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44u2__short[] = {
+        13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
+        10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
+        15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
+        13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
+};
+
+static const static_codebook _huff_book__44u2__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44u2__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u3__long[] = {
+         6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
+        11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
+        13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
+         9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
+};
+
+static const static_codebook _huff_book__44u3__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44u3__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u3__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u3__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
+        10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
+        11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
+        10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
+        11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
+        13,
+};
+
+static const static_codebook _44u3__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u3__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u3__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u3__p2_0[] = {
+         2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
+         8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
+         8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
+         8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
+         8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
+         9,
+};
+
+static const static_codebook _44u3__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u3__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u3__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u3__p3_0[] = {
+         2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
+         9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
+         9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
+        13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
+        11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
+        10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
+        13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
+        11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
+        10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
+        14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
+         9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
+         9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
+        12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
+        16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
+        17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
+        13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
+         9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
+        12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
+        12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
+        12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
+        12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
+        12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
+        12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
+         0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
+        15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
+         9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
+        17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
+        12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
+        18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
+         0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
+        12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
+        18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
+        12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
+        15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
+        17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
+        11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
+        13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
+        18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
+        18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
+         0,
+};
+
+static const static_codebook _44u3__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u3__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u3__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u3__p4_0[] = {
+         4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
+         9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
+        11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
+        10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
+         9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
+        12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
+        10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
+        12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
+         8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
+        13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
+        15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
+        12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
+         8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
+        11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
+        10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
+        11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
+        10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
+        11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
+        15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
+        13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
+         9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
+        13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
+        10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
+        15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
+        14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
+        11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
+        15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
+        10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
+        13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
+        15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
+        10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
+        12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
+        15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
+        14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
+        13,
+};
+
+static const static_codebook _44u3__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u3__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u3__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u3__p5_0[] = {
+         2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
+        10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
+         9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
+         9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+        10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
+        12,
+};
+
+static const static_codebook _44u3__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u3__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u3__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u3__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
+         8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
+         9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
+        12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
+        15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
+         9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
+        12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
+        13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
+        17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
+        15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
+        15,16,16,16,17,18,16,20,18,
+};
+
+static const static_codebook _44u3__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u3__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u3__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u3__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
+         6, 5, 6, 6, 5, 5, 6, 6, 6,
+};
+
+static const static_codebook _44u3__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u3__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u3__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u3__p7_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u3__p7_0[] = {
+         1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
+        10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,
+};
+
+static const static_codebook _44u3__p7_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u3__p7_0,
+        1, -515907584, 1627381760, 4, 0,
+        (long *)_vq_quantlist__44u3__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u3__p7_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u3__p7_1[] = {
+         1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
+         7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
+         7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
+         9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
+         9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
+        12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
+        12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
+        13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
+        14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
+        15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
+        17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
+        17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
+        17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
+        17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
+        17,
+};
+
+static const static_codebook _44u3__p7_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u3__p7_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44u3__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u3__p7_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u3__p7_2[] = {
+         2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+        10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
+         9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+        10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
+         9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
+         9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
+         9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
+         9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
+         9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+         9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
+        11,
+};
+
+static const static_codebook _44u3__p7_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u3__p7_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u3__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44u3__short[] = {
+        14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
+        10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
+        14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
+        13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
+};
+
+static const static_codebook _huff_book__44u3__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44u3__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u4__long[] = {
+         3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
+         9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
+        12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
+        10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
+};
+
+static const static_codebook _huff_book__44u4__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44u4__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u4__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u4__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
+        10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
+        11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
+        10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
+        11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
+        13,
+};
+
+static const static_codebook _44u4__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u4__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u4__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u4__p2_0[] = {
+         2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
+         8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
+         8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
+         8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
+         8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
+         9,
+};
+
+static const static_codebook _44u4__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u4__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u4__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u4__p3_0[] = {
+         2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
+        10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
+         9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
+        13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
+        11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
+        10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
+        14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
+        12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
+        10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
+        14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
+         9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
+         9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
+        12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
+        17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
+        20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
+        14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
+         9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
+        12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
+        12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
+        12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
+        12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
+        12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
+        12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
+        19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
+        15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
+         9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
+        17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
+        12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
+        17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
+         0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
+        13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
+        19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
+        12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
+        16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
+        18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
+        11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
+        14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
+         0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
+        18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
+         0,
+};
+
+static const static_codebook _44u4__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u4__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u4__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u4__p4_0[] = {
+         4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
+         9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
+        11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
+        10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
+         9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
+        12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
+        10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
+        12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
+         8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
+         8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
+        13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
+        15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
+        12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
+         8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
+        11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
+        11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
+        11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
+        10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
+        11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
+        15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
+        13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
+         9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
+        13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
+        10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
+        14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
+        15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
+        11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
+        15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
+        10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
+        13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
+        15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
+        10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
+        12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
+        15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
+        15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
+        13,
+};
+
+static const static_codebook _44u4__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u4__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u4__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u4__p5_0[] = {
+         2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
+        10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
+         9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
+         9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
+        10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
+        12,
+};
+
+static const static_codebook _44u4__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u4__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u4__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u4__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
+         8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
+         9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
+        12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
+        15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
+         9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
+        12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
+        13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
+        18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
+        15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
+        16,16,16,17,17,18,17,20,21,
+};
+
+static const static_codebook _44u4__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u4__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u4__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u4__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
+         6, 5, 6, 6, 5, 5, 6, 6, 6,
+};
+
+static const static_codebook _44u4__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u4__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u4__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u4__p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u4__p7_0[] = {
+         1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
+        12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,
+};
+
+static const static_codebook _44u4__p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u4__p7_0,
+        1, -514332672, 1627381760, 4, 0,
+        (long *)_vq_quantlist__44u4__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u4__p7_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u4__p7_1[] = {
+         1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
+         7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
+         7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
+        10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
+        10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
+        12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
+        12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
+        13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
+        13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
+        14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
+        14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
+        15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
+        15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
+        16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
+        16,
+};
+
+static const static_codebook _44u4__p7_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u4__p7_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44u4__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u4__p7_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u4__p7_2[] = {
+         2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+        10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
+         9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
+        10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
+         9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+        10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+         9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
+        10,
+};
+
+static const static_codebook _44u4__p7_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u4__p7_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u4__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44u4__short[] = {
+        14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
+         9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
+        14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
+        12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
+};
+
+static const static_codebook _huff_book__44u4__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44u4__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u5__long[] = {
+         3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
+        10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
+         5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
+        11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
+         6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
+        10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
+        14, 8, 7, 8,
+};
+
+static const static_codebook _huff_book__44u5__long = {
+        2, 100,
+        (char *)_huff_lengthlist__44u5__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u5__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u5__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
+         9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
+        10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
+        10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
+        10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
+        12,
+};
+
+static const static_codebook _44u5__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u5__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u5__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u5__p2_0[] = {
+         3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
+         7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
+         8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
+         7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
+         8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
+         9,
+};
+
+static const static_codebook _44u5__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u5__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u5__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u5__p3_0[] = {
+         2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
+        10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
+         9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
+        13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
+        11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
+        10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
+        13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
+        11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
+        10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
+        14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
+         9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
+         9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
+        12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
+        16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
+        18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
+        13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
+         9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
+        12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
+        12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
+        12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
+        11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
+        12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
+        12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
+        18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
+        15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
+         9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
+        15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
+        12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
+        17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
+         0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
+        13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
+        18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
+        12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
+        16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
+        18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
+        11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
+        14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
+        17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
+         0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
+         0,
+};
+
+static const static_codebook _44u5__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u5__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u5__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u5__p4_0[] = {
+         4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
+         9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
+         8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
+        11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
+        10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
+         9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
+        11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
+        12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
+         8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
+         7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
+        12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
+        15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
+        11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
+         8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
+        10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
+        10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
+        10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
+        10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
+        10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
+        10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
+        14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
+        12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
+         9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
+        12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
+        10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
+        14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
+        14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
+        11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
+        14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
+        10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
+        12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
+        14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
+        10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
+        12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
+        14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
+        14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
+        12,
+};
+
+static const static_codebook _44u5__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u5__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u5__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u5__p5_0[] = {
+         2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
+        11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
+        10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
+        10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
+        11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
+        14,
+};
+
+static const static_codebook _44u5__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u5__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u5__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p6_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u5__p6_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
+         9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
+         8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
+         8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
+         9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
+        11,
+};
+
+static const static_codebook _44u5__p6_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u5__p6_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u5__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u5__p7_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
+        11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
+        12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
+        11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
+        12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
+        12,
+};
+
+static const static_codebook _44u5__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u5__p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44u5__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u5__p7_1[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
+         8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
+         9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
+         8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
+         9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
+        10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
+         9, 9, 9, 9, 9,10,10,10,10,
+};
+
+static const static_codebook _44u5__p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u5__p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u5__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u5__p8_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u5__p8_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
+         9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
+        11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
+         9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
+        14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
+        12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
+        14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
+        12,13,13,14,14,14,14,15,15,
+};
+
+static const static_codebook _44u5__p8_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u5__p8_0,
+        1, -524582912, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44u5__p8_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p8_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u5__p8_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
+         7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
+         8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
+         7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
+         8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u5__p8_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u5__p8_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u5__p8_1,
+        0
+};
+
+static const long _vq_quantlist__44u5__p9_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u5__p9_0[] = {
+         1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
+        13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
+        13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
+        13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
+        13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
+        12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+        12,12,12,12,12,12,12,12,12,
+};
+
+static const static_codebook _44u5__p9_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u5__p9_0,
+        1, -514332672, 1627381760, 4, 0,
+        (long *)_vq_quantlist__44u5__p9_0,
+        0
+};
+
+static const long _vq_quantlist__44u5__p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u5__p9_1[] = {
+         1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
+         7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
+         6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
+        10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
+        10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
+        12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
+        12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
+        12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
+        12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
+        12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
+        12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
+        13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
+        13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
+        14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
+        14,
+};
+
+static const static_codebook _44u5__p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u5__p9_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44u5__p9_1,
+        0
+};
+
+static const long _vq_quantlist__44u5__p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u5__p9_2[] = {
+         2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+         9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
+         9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
+         9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
+        10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
+         9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+         9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+         9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
+         9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+         9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+         9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _44u5__p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u5__p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u5__p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44u5__short[] = {
+         4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
+        15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
+         7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
+        14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
+         4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
+        14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
+         6, 8,15,17,
+};
+
+static const static_codebook _huff_book__44u5__short = {
+        2, 100,
+        (char *)_huff_lengthlist__44u5__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u6__long[] = {
+         3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
+        11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
+         6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
+        11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
+         5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
+        11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
+        13, 8, 7, 7,
+};
+
+static const static_codebook _huff_book__44u6__long = {
+        2, 100,
+        (char *)_huff_lengthlist__44u6__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u6__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u6__p1_0[] = {
+         1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
+         9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
+        10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
+        10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
+        10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
+        12,
+};
+
+static const static_codebook _44u6__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u6__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u6__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u6__p2_0[] = {
+         3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
+         7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
+         8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
+         7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
+         8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
+         9,
+};
+
+static const static_codebook _44u6__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u6__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u6__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u6__p3_0[] = {
+         2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
+         9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
+         9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
+        13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
+        11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
+        10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
+        13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
+        12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
+        10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
+        14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
+         9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
+         9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
+        12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
+        15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
+         0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
+        13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
+         9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
+        12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
+        12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
+        12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
+        11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
+        12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
+        12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
+        19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
+        15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
+         9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
+        16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
+        12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
+        19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
+        19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
+        13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
+        20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
+        12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
+        16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
+        19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
+        11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
+        14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
+        20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
+        19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
+        19,
+};
+
+static const static_codebook _44u6__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u6__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u6__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u6__p4_0[] = {
+         4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
+         9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
+        11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
+        10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
+         9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
+        11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
+         9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
+        11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
+         8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
+         7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
+        10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
+        13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
+        14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
+        11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
+         8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
+        10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
+        10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
+        10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
+        10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
+        10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
+        10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
+        14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
+        12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
+         9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
+        12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
+        10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
+        14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
+        14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
+        11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
+        14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
+        12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
+        14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
+        10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
+        11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
+        14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
+        14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
+        13,
+};
+
+static const static_codebook _44u6__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u6__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u6__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u6__p5_0[] = {
+         2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
+        11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
+        10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
+        10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
+        11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44u6__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u6__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u6__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p6_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u6__p6_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
+         9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
+         8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
+         8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
+         9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
+        12,
+};
+
+static const static_codebook _44u6__p6_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u6__p6_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u6__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u6__p7_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
+        10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
+        11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
+        10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
+        11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
+        10,
+};
+
+static const static_codebook _44u6__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u6__p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44u6__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u6__p7_1[] = {
+         3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
+         8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
+         8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
+         7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
+         9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
+         8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _44u6__p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u6__p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u6__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u6__p8_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u6__p8_0[] = {
+         1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
+         9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
+        11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
+         9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
+        13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
+        11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
+        13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
+        12,13,13,14,14,14,15,15,15,
+};
+
+static const static_codebook _44u6__p8_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u6__p8_0,
+        1, -524582912, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44u6__p8_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p8_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u6__p8_1[] = {
+         3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
+         7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
+         8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
+         7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
+         8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
+         8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u6__p8_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u6__p8_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u6__p8_1,
+        0
+};
+
+static const long _vq_quantlist__44u6__p9_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u6__p9_0[] = {
+         1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
+         8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
+         9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
+        14,
+};
+
+static const static_codebook _44u6__p9_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u6__p9_0,
+        1, -514071552, 1627381760, 4, 0,
+        (long *)_vq_quantlist__44u6__p9_0,
+        0
+};
+
+static const long _vq_quantlist__44u6__p9_1[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u6__p9_1[] = {
+         1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
+         7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
+         6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
+        10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
+        10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
+        12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
+        11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
+        12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
+        12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
+        13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
+        13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
+        13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
+        13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
+        13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
+        13,
+};
+
+static const static_codebook _44u6__p9_1 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u6__p9_1,
+        1, -522338304, 1620115456, 4, 0,
+        (long *)_vq_quantlist__44u6__p9_1,
+        0
+};
+
+static const long _vq_quantlist__44u6__p9_2[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u6__p9_2[] = {
+         3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
+         9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
+         9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
+         9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
+        10,
+};
+
+static const static_codebook _44u6__p9_2 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u6__p9_2,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u6__p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44u6__short[] = {
+         4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
+        16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
+         7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
+        16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
+         5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
+        14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
+         7, 6, 9,16,
+};
+
+static const static_codebook _huff_book__44u6__short = {
+        2, 100,
+        (char *)_huff_lengthlist__44u6__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u7__long[] = {
+         3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
+        11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
+         6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
+        12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
+         5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
+        12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
+        12, 8, 6, 7,
+};
+
+static const static_codebook _huff_book__44u7__long = {
+        2, 100,
+        (char *)_huff_lengthlist__44u7__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u7__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u7__p1_0[] = {
+         1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
+        10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
+        10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
+        10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
+        10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
+        12,
+};
+
+static const static_codebook _44u7__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u7__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u7__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u7__p2_0[] = {
+         3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
+         7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
+         7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
+         7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
+         8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
+         9,
+};
+
+static const static_codebook _44u7__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u7__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u7__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u7__p3_0[] = {
+         2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
+         9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
+         9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
+        13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
+        11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
+        10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
+        13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
+        12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
+        10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
+        14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
+         9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
+         9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
+        12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
+        16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
+         0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
+        14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
+         9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
+        12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
+        12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
+        12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
+        11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
+        12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
+        11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
+        19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
+        15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
+         9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
+        16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
+        12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
+        18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
+        19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
+        13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
+        19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
+        12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
+        16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
+        17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
+        11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
+        14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
+        18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
+         0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
+         0,
+};
+
+static const static_codebook _44u7__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u7__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u7__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u7__p4_0[] = {
+         4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
+         9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
+         8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
+        11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
+        10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
+         9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
+        11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
+        10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
+         9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
+        11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
+         8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
+         7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
+        10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
+        13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
+        14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
+        11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
+         8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
+        10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
+        10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
+        10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
+        10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
+        10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
+        10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
+        14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
+        12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
+         9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
+        13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
+        10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
+        14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
+        14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
+        11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
+        14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
+        12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
+        14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
+        10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
+        12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
+        14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
+        14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
+        14,
+};
+
+static const static_codebook _44u7__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u7__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u7__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u7__p5_0[] = {
+         2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
+        11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
+        10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
+        10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
+        11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
+        14,
+};
+
+static const static_codebook _44u7__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u7__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u7__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p6_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u7__p6_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
+         9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
+         8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
+         8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
+         9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
+        12,
+};
+
+static const static_codebook _44u7__p6_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u7__p6_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u7__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p7_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u7__p7_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
+        10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
+        10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
+        10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
+        11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
+        10,
+};
+
+static const static_codebook _44u7__p7_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u7__p7_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44u7__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u7__p7_1[] = {
+         3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
+         8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
+         8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
+         7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
+         9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
+         9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
+         8, 9, 9, 9, 9, 9,10,10,10,
+};
+
+static const static_codebook _44u7__p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u7__p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u7__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u7__p8_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u7__p8_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
+         9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
+        12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
+         8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
+        14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
+        11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
+        14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
+        12,13,13,14,14,15,15,15,16,
+};
+
+static const static_codebook _44u7__p8_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u7__p8_0,
+        1, -524582912, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44u7__p8_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p8_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u7__p8_1[] = {
+         4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
+         7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
+         7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
+         7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
+         8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
+         7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
+         8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
+         7, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u7__p8_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u7__p8_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u7__p8_1,
+        0
+};
+
+static const long _vq_quantlist__44u7__p9_0[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u7__p9_0[] = {
+         1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
+        10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,
+};
+
+static const static_codebook _44u7__p9_0 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u7__p9_0,
+        1, -512171520, 1630791680, 4, 0,
+        (long *)_vq_quantlist__44u7__p9_0,
+        0
+};
+
+static const long _vq_quantlist__44u7__p9_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u7__p9_1[] = {
+         1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
+         8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
+         9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
+        13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
+        13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
+        10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
+        14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
+        14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
+        16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
+        13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
+        15,15,15,15,17,17,16,17,16,
+};
+
+static const static_codebook _44u7__p9_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u7__p9_1,
+        1, -518889472, 1622704128, 4, 0,
+        (long *)_vq_quantlist__44u7__p9_1,
+        0
+};
+
+static const long _vq_quantlist__44u7__p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44u7__p9_2[] = {
+         2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
+         8,
+};
+
+static const static_codebook _44u7__p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44u7__p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44u7__p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44u7__short[] = {
+         5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
+        17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
+        10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
+        16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
+         5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
+        12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
+         6, 8, 5, 9,
+};
+
+static const static_codebook _huff_book__44u7__short = {
+        2, 100,
+        (char *)_huff_lengthlist__44u7__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u8__long[] = {
+         3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
+        12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
+         4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
+        12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
+         7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
+        12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
+        10, 8, 8, 9,
+};
+
+static const static_codebook _huff_book__44u8__long = {
+        2, 100,
+        (char *)_huff_lengthlist__44u8__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u8__short[] = {
+         6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
+        15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
+         5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
+        17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
+         6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
+        17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
+        10,10,15,17,
+};
+
+static const static_codebook _huff_book__44u8__short = {
+        2, 100,
+        (char *)_huff_lengthlist__44u8__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u8_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u8_p1_0[] = {
+         1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
+         9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
+         9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
+         9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
+         9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
+        10,
+};
+
+static const static_codebook _44u8_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u8_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u8_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u8_p2_0[] = {
+         4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
+         9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
+        11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
+        10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
+         9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
+        11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
+        12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
+         8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
+         8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
+        10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
+        13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
+        14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
+        11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
+         8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
+        10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
+        10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
+        10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
+        10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
+        10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
+        10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
+        15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
+        12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
+         9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
+        13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
+        10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
+        14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
+        14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
+        11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
+        14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
+        10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
+        12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
+        14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
+        10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
+        12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
+        14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
+        14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
+        14,
+};
+
+static const static_codebook _44u8_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u8_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u8_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u8_p3_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
+         9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
+         8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
+         8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
+         9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
+        12,
+};
+
+static const static_codebook _44u8_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u8_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u8_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u8_p4_0[] = {
+         4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
+        11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
+        12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
+        11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
+        11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
+        10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
+        11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
+        10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
+        11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
+        10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
+        11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
+        10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
+        11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
+        10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
+        11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
+        11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
+        12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
+        11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
+        14,
+};
+
+static const static_codebook _44u8_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u8_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u8_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u8_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
+         9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
+        10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
+         9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
+        10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
+        10,
+};
+
+static const static_codebook _44u8_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u8_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44u8_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u8_p5_1[] = {
+         4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
+         7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
+         8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
+         7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
+         8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
+         8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
+         8, 8, 8, 8, 8, 8, 8, 9, 9,
+};
+
+static const static_codebook _44u8_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u8_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u8_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44u8_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u8_p6_0[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
+         9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
+        10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
+         8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
+         9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
+         9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
+        11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
+        10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
+        11,11,11,11,11,12,11,12,12,
+};
+
+static const static_codebook _44u8_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u8_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u8_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u8_p6_1[] = {
+         3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
+         5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44u8_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u8_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u8_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u8_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u8_p7_0[] = {
+         1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
+         7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
+         8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
+        12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
+         8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
+        11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
+        12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
+        15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
+        12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
+        13,13,14,14,14,15,15,15,16,
+};
+
+static const static_codebook _44u8_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u8_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44u8_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u8_p7_1[] = {
+         4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
+         7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
+         7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
+         8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
+         8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
+         8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
+         7, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u8_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u8_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u8_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u8_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u8_p8_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
+         6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
+         6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
+        10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
+        10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
+        12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
+        12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
+        13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
+        12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
+        14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
+        14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
+        14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
+        14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
+        15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
+        17,
+};
+
+static const static_codebook _44u8_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u8_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44u8_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44u8_p8_1[] = {
+         4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
+         8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
+         7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
+        10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
+        10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
+        10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
+        10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
+        10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
+         9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+         9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
+         9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+         9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44u8_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44u8_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u8_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44u8_p9_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u8_p9_0[] = {
+         1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
+         9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
+         8,
+};
+
+static const static_codebook _44u8_p9_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u8_p9_0,
+        1, -511895552, 1631393792, 4, 0,
+        (long *)_vq_quantlist__44u8_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44u8_p9_1[] = {
+        9,
+        8,
+        10,
+        7,
+        11,
+        6,
+        12,
+        5,
+        13,
+        4,
+        14,
+        3,
+        15,
+        2,
+        16,
+        1,
+        17,
+        0,
+        18,
+};
+
+static const char _vq_lengthlist__44u8_p9_1[] = {
+         1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
+        11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
+        11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
+        10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
+        10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
+        11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
+         9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
+        15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
+        13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
+        13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
+        12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
+        12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
+        10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
+        15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
+        15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
+        16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
+        16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
+        14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
+        14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
+        12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
+        16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
+        16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
+        16,15,16,16,16,16,16,16,16,
+};
+
+static const static_codebook _44u8_p9_1 = {
+        2, 361,
+        (char *)_vq_lengthlist__44u8_p9_1,
+        1, -518287360, 1622704128, 5, 0,
+        (long *)_vq_quantlist__44u8_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44u8_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44u8_p9_2[] = {
+         2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44u8_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44u8_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44u8_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44u9__long[] = {
+         3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
+        13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
+         5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
+        12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
+         7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
+        13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
+        10, 8, 8, 9,
+};
+
+static const static_codebook _huff_book__44u9__long = {
+        2, 100,
+        (char *)_huff_lengthlist__44u9__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const char _huff_lengthlist__44u9__short[] = {
+         9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
+        17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
+         7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
+        17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
+         6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
+        15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
+         9, 9,12,15,
+};
+
+static const static_codebook _huff_book__44u9__short = {
+        2, 100,
+        (char *)_huff_lengthlist__44u9__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44u9_p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u9_p1_0[] = {
+         1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
+         9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
+         9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
+         9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
+         9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
+        10,
+};
+
+static const static_codebook _44u9_p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u9_p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44u9_p1_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p2_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u9_p2_0[] = {
+         3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
+         9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
+         8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
+        11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
+        10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
+         9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
+        11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
+        10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
+         9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
+        11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
+         8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
+         8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
+        10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
+        12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
+        13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
+        11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
+         8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
+        10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
+        10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
+        10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
+        10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
+        10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
+        10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
+        14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
+        11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
+         9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
+        12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
+        10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
+        13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
+        14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
+        11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
+        13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
+        10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
+        11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
+        13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
+        10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
+        11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
+        13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
+        13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
+        14,
+};
+
+static const static_codebook _44u9_p2_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44u9_p2_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u9_p2_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p3_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44u9_p3_0[] = {
+         3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
+         9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
+         8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
+         8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
+         9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
+        11,
+};
+
+static const static_codebook _44u9_p3_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44u9_p3_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u9_p3_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p4_0[] = {
+        8,
+        7,
+        9,
+        6,
+        10,
+        5,
+        11,
+        4,
+        12,
+        3,
+        13,
+        2,
+        14,
+        1,
+        15,
+        0,
+        16,
+};
+
+static const char _vq_lengthlist__44u9_p4_0[] = {
+         4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
+        11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
+        11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
+        10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
+        10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
+        10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
+         9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
+        10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
+        10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
+        10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
+         9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
+        10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
+        10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
+        11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
+        10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
+        11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
+        11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
+        14,
+};
+
+static const static_codebook _44u9_p4_0 = {
+        2, 289,
+        (char *)_vq_lengthlist__44u9_p4_0,
+        1, -529530880, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u9_p4_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p5_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44u9_p5_0[] = {
+         1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
+         9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
+        10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
+         9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
+        10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
+        10,
+};
+
+static const static_codebook _44u9_p5_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44u9_p5_0,
+        1, -529137664, 1618345984, 2, 0,
+        (long *)_vq_quantlist__44u9_p5_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p5_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u9_p5_1[] = {
+         5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
+         7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
+         7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
+         7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
+         8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
+         8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
+         8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
+         8, 8, 8, 8, 8, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u9_p5_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u9_p5_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u9_p5_1,
+        0
+};
+
+static const long _vq_quantlist__44u9_p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u9_p6_0[] = {
+         2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
+         7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
+         8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+        10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
+        10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
+         8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
+         9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
+         9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
+        11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
+        10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
+        10,11,11,11,11,12,11,12,12,
+};
+
+static const static_codebook _44u9_p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u9_p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44u9_p6_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44u9_p6_1[] = {
+         4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
+         5, 5, 5, 5, 5, 5, 5, 5, 5,
+};
+
+static const static_codebook _44u9_p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44u9_p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44u9_p6_1,
+        0
+};
+
+static const long _vq_quantlist__44u9_p7_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44u9_p7_0[] = {
+         1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
+         7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
+         8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
+        11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
+        12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
+         8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
+        11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
+        12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
+        15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
+        11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
+        12,13,13,14,14,14,15,15,15,
+};
+
+static const static_codebook _44u9_p7_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44u9_p7_0,
+        1, -523206656, 1618345984, 4, 0,
+        (long *)_vq_quantlist__44u9_p7_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p7_1[] = {
+        5,
+        4,
+        6,
+        3,
+        7,
+        2,
+        8,
+        1,
+        9,
+        0,
+        10,
+};
+
+static const char _vq_lengthlist__44u9_p7_1[] = {
+         5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
+         7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
+         7, 7, 7, 7, 7, 8, 8, 8, 8,
+};
+
+static const static_codebook _44u9_p7_1 = {
+        2, 121,
+        (char *)_vq_lengthlist__44u9_p7_1,
+        1, -531365888, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44u9_p7_1,
+        0
+};
+
+static const long _vq_quantlist__44u9_p8_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u9_p8_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
+         6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
+         6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
+        10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
+        10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
+        12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
+        12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
+        13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
+        12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
+        14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
+        14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
+        15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
+        14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
+        16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
+        15,
+};
+
+static const static_codebook _44u9_p8_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u9_p8_0,
+        1, -520986624, 1620377600, 4, 0,
+        (long *)_vq_quantlist__44u9_p8_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p8_1[] = {
+        10,
+        9,
+        11,
+        8,
+        12,
+        7,
+        13,
+        6,
+        14,
+        5,
+        15,
+        4,
+        16,
+        3,
+        17,
+        2,
+        18,
+        1,
+        19,
+        0,
+        20,
+};
+
+static const char _vq_lengthlist__44u9_p8_1[] = {
+         4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
+         7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
+         8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+        10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
+         9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
+        10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
+        10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+         9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
+         9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
+        10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
+        10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
+        10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+         9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
+         9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,
+};
+
+static const static_codebook _44u9_p8_1 = {
+        2, 441,
+        (char *)_vq_lengthlist__44u9_p8_1,
+        1, -529268736, 1611661312, 5, 0,
+        (long *)_vq_quantlist__44u9_p8_1,
+        0
+};
+
+static const long _vq_quantlist__44u9_p9_0[] = {
+        7,
+        6,
+        8,
+        5,
+        9,
+        4,
+        10,
+        3,
+        11,
+        2,
+        12,
+        1,
+        13,
+        0,
+        14,
+};
+
+static const char _vq_lengthlist__44u9_p9_0[] = {
+         1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
+        10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
+        10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _44u9_p9_0 = {
+        2, 225,
+        (char *)_vq_lengthlist__44u9_p9_0,
+        1, -510036736, 1631393792, 4, 0,
+        (long *)_vq_quantlist__44u9_p9_0,
+        0
+};
+
+static const long _vq_quantlist__44u9_p9_1[] = {
+        9,
+        8,
+        10,
+        7,
+        11,
+        6,
+        12,
+        5,
+        13,
+        4,
+        14,
+        3,
+        15,
+        2,
+        16,
+        1,
+        17,
+        0,
+        18,
+};
+
+static const char _vq_lengthlist__44u9_p9_1[] = {
+         1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
+        11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
+        12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
+        10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
+        11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
+        10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
+         9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
+        14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
+        14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
+        13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
+        12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
+        13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
+        10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
+        16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
+        15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
+        15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
+        17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
+        14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
+        14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
+        12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
+        15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
+        17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
+        17,17,15,17,15,17,16,16,17,
+};
+
+static const static_codebook _44u9_p9_1 = {
+        2, 361,
+        (char *)_vq_lengthlist__44u9_p9_1,
+        1, -518287360, 1622704128, 5, 0,
+        (long *)_vq_quantlist__44u9_p9_1,
+        0
+};
+
+static const long _vq_quantlist__44u9_p9_2[] = {
+        24,
+        23,
+        25,
+        22,
+        26,
+        21,
+        27,
+        20,
+        28,
+        19,
+        29,
+        18,
+        30,
+        17,
+        31,
+        16,
+        32,
+        15,
+        33,
+        14,
+        34,
+        13,
+        35,
+        12,
+        36,
+        11,
+        37,
+        10,
+        38,
+        9,
+        39,
+        8,
+        40,
+        7,
+        41,
+        6,
+        42,
+        5,
+        43,
+        4,
+        44,
+        3,
+        45,
+        2,
+        46,
+        1,
+        47,
+        0,
+        48,
+};
+
+static const char _vq_lengthlist__44u9_p9_2[] = {
+         2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
+         6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+         7,
+};
+
+static const static_codebook _44u9_p9_2 = {
+        1, 49,
+        (char *)_vq_lengthlist__44u9_p9_2,
+        1, -526909440, 1611661312, 6, 0,
+        (long *)_vq_quantlist__44u9_p9_2,
+        0
+};
+
+static const char _huff_lengthlist__44un1__long[] = {
+         5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
+        12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
+        14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
+         9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
+};
+
+static const static_codebook _huff_book__44un1__long = {
+        2, 64,
+        (char *)_huff_lengthlist__44un1__long,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
+static const long _vq_quantlist__44un1__p1_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44un1__p1_0[] = {
+         1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
+        10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
+        11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
+        10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
+        11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
+        12,
+};
+
+static const static_codebook _44un1__p1_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44un1__p1_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44un1__p1_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p2_0[] = {
+        1,
+        0,
+        2,
+};
+
+static const char _vq_lengthlist__44un1__p2_0[] = {
+         2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
+         7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
+         8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
+         7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
+         8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
+         8,
+};
+
+static const static_codebook _44un1__p2_0 = {
+        4, 81,
+        (char *)_vq_lengthlist__44un1__p2_0,
+        1, -535822336, 1611661312, 2, 0,
+        (long *)_vq_quantlist__44un1__p2_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p3_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44un1__p3_0[] = {
+         1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
+        10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
+        10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
+        12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
+        11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
+        10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
+        13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
+        12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
+        11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
+        14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
+        10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
+        10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
+        12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
+        16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
+        17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
+        13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
+        10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
+        12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
+        12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
+        13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
+        12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
+        12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
+        12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
+        18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
+        16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
+         9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
+        15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
+        12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
+        19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
+        16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
+        13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
+        17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
+        13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
+        16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
+        17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
+        11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
+        14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
+        16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
+        17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
+        17,
+};
+
+static const static_codebook _44un1__p3_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44un1__p3_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44un1__p3_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p4_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44un1__p4_0[] = {
+         3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
+        10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
+         8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
+        11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
+        10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
+        10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
+        12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
+        11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
+        10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
+        13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
+         8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
+         8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
+        10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
+        13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
+        16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
+        12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
+         8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
+        11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
+        10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
+        11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
+        11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
+        10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
+        11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
+        16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
+        14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
+         9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
+        14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
+        10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
+        14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
+        14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
+        11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
+        15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
+        11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
+        13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
+        14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
+        10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
+        13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
+        15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
+        14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
+        12,
+};
+
+static const static_codebook _44un1__p4_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44un1__p4_0,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44un1__p4_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p5_0[] = {
+        4,
+        3,
+        5,
+        2,
+        6,
+        1,
+        7,
+        0,
+        8,
+};
+
+static const char _vq_lengthlist__44un1__p5_0[] = {
+         1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
+        10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
+         9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
+         9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
+        10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
+        12,
+};
+
+static const static_codebook _44un1__p5_0 = {
+        2, 81,
+        (char *)_vq_lengthlist__44un1__p5_0,
+        1, -531628032, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44un1__p5_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p6_0[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44un1__p6_0[] = {
+         1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
+         8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
+         9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
+        13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
+        15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
+         9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
+        12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
+        13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
+        17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
+        15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
+        16, 0,15,18,18, 0,16, 0, 0,
+};
+
+static const static_codebook _44un1__p6_0 = {
+        2, 169,
+        (char *)_vq_lengthlist__44un1__p6_0,
+        1, -526516224, 1616117760, 4, 0,
+        (long *)_vq_quantlist__44un1__p6_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p6_1[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44un1__p6_1[] = {
+         2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
+         6, 5, 6, 6, 5, 6, 6, 6, 6,
+};
+
+static const static_codebook _44un1__p6_1 = {
+        2, 25,
+        (char *)_vq_lengthlist__44un1__p6_1,
+        1, -533725184, 1611661312, 3, 0,
+        (long *)_vq_quantlist__44un1__p6_1,
+        0
+};
+
+static const long _vq_quantlist__44un1__p7_0[] = {
+        2,
+        1,
+        3,
+        0,
+        4,
+};
+
+static const char _vq_lengthlist__44un1__p7_0[] = {
+         1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+        10,
+};
+
+static const static_codebook _44un1__p7_0 = {
+        4, 625,
+        (char *)_vq_lengthlist__44un1__p7_0,
+        1, -518709248, 1626677248, 3, 0,
+        (long *)_vq_quantlist__44un1__p7_0,
+        0
+};
+
+static const long _vq_quantlist__44un1__p7_1[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44un1__p7_1[] = {
+         1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
+         7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
+         8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
+        11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
+        12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
+         8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
+        11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
+        11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
+        13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
+        11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
+        12,13,13,12,13,13,14,14,14,
+};
+
+static const static_codebook _44un1__p7_1 = {
+        2, 169,
+        (char *)_vq_lengthlist__44un1__p7_1,
+        1, -523010048, 1618608128, 4, 0,
+        (long *)_vq_quantlist__44un1__p7_1,
+        0
+};
+
+static const long _vq_quantlist__44un1__p7_2[] = {
+        6,
+        5,
+        7,
+        4,
+        8,
+        3,
+        9,
+        2,
+        10,
+        1,
+        11,
+        0,
+        12,
+};
+
+static const char _vq_lengthlist__44un1__p7_2[] = {
+         3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
+         6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
+         8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
+         9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
+         9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
+         8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
+         9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
+         9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
+        10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
+         9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
+         9, 9, 9,10,10,10,10,10,10,
+};
+
+static const static_codebook _44un1__p7_2 = {
+        2, 169,
+        (char *)_vq_lengthlist__44un1__p7_2,
+        1, -531103744, 1611661312, 4, 0,
+        (long *)_vq_quantlist__44un1__p7_2,
+        0
+};
+
+static const char _huff_lengthlist__44un1__short[] = {
+        12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
+        12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
+        13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
+        12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
+};
+
+static const static_codebook _huff_book__44un1__short = {
+        2, 64,
+        (char *)_huff_lengthlist__44un1__short,
+        0, 0, 0, 0, 0,
+        NULL,
+        0
+};
+
diff --git a/vorbis/lib/codebook.c b/vorbis/lib/codebook.c
new file mode 100644 (file)
index 0000000..78672e2
--- /dev/null
@@ -0,0 +1,461 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: basic codebook pack/unpack/code/decode operations
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codebook.h"
+#include "scales.h"
+#include "misc.h"
+#include "os.h"
+
+/* packs the given codebook into the bitstream **************************/
+
+int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
+  long i,j;
+  int ordered=0;
+
+  /* first the basic parameters */
+  oggpack_write(opb,0x564342,24);
+  oggpack_write(opb,c->dim,16);
+  oggpack_write(opb,c->entries,24);
+
+  /* pack the codewords.  There are two packings; length ordered and
+     length random.  Decide between the two now. */
+
+  for(i=1;i<c->entries;i++)
+    if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
+  if(i==c->entries)ordered=1;
+
+  if(ordered){
+    /* length ordered.  We only need to say how many codewords of
+       each length.  The actual codewords are generated
+       deterministically */
+
+    long count=0;
+    oggpack_write(opb,1,1);  /* ordered */
+    oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
+
+    for(i=1;i<c->entries;i++){
+      char this=c->lengthlist[i];
+      char last=c->lengthlist[i-1];
+      if(this>last){
+        for(j=last;j<this;j++){
+          oggpack_write(opb,i-count,ov_ilog(c->entries-count));
+          count=i;
+        }
+      }
+    }
+    oggpack_write(opb,i-count,ov_ilog(c->entries-count));
+
+  }else{
+    /* length random.  Again, we don't code the codeword itself, just
+       the length.  This time, though, we have to encode each length */
+    oggpack_write(opb,0,1);   /* unordered */
+
+    /* algortihmic mapping has use for 'unused entries', which we tag
+       here.  The algorithmic mapping happens as usual, but the unused
+       entry has no codeword. */
+    for(i=0;i<c->entries;i++)
+      if(c->lengthlist[i]==0)break;
+
+    if(i==c->entries){
+      oggpack_write(opb,0,1); /* no unused entries */
+      for(i=0;i<c->entries;i++)
+        oggpack_write(opb,c->lengthlist[i]-1,5);
+    }else{
+      oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
+      for(i=0;i<c->entries;i++){
+        if(c->lengthlist[i]==0){
+          oggpack_write(opb,0,1);
+        }else{
+          oggpack_write(opb,1,1);
+          oggpack_write(opb,c->lengthlist[i]-1,5);
+        }
+      }
+    }
+  }
+
+  /* is the entry number the desired return value, or do we have a
+     mapping? If we have a mapping, what type? */
+  oggpack_write(opb,c->maptype,4);
+  switch(c->maptype){
+  case 0:
+    /* no mapping */
+    break;
+  case 1:case 2:
+    /* implicitly populated value mapping */
+    /* explicitly populated value mapping */
+
+    if(!c->quantlist){
+      /* no quantlist?  error */
+      return(-1);
+    }
+
+    /* values that define the dequantization */
+    oggpack_write(opb,c->q_min,32);
+    oggpack_write(opb,c->q_delta,32);
+    oggpack_write(opb,c->q_quant-1,4);
+    oggpack_write(opb,c->q_sequencep,1);
+
+    {
+      int quantvals;
+      switch(c->maptype){
+      case 1:
+        /* a single column of (c->entries/c->dim) quantized values for
+           building a full value list algorithmically (square lattice) */
+        quantvals=_book_maptype1_quantvals(c);
+        break;
+      case 2:
+        /* every value (c->entries*c->dim total) specified explicitly */
+        quantvals=c->entries*c->dim;
+        break;
+      default: /* NOT_REACHABLE */
+        quantvals=-1;
+      }
+
+      /* quantized values */
+      for(i=0;i<quantvals;i++)
+        oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
+
+    }
+    break;
+  default:
+    /* error case; we don't have any other map types now */
+    return(-1);
+  }
+
+  return(0);
+}
+
+/* unpacks a codebook from the packet buffer into the codebook struct,
+   readies the codebook auxiliary structures for decode *************/
+static_codebook *vorbis_staticbook_unpack(oggpack_buffer *opb){
+  long i,j;
+  static_codebook *s=_ogg_calloc(1,sizeof(*s));
+  s->allocedp=1;
+
+  /* make sure alignment is correct */
+  if(oggpack_read(opb,24)!=0x564342)goto _eofout;
+
+  /* first the basic parameters */
+  s->dim=oggpack_read(opb,16);
+  s->entries=oggpack_read(opb,24);
+  if(s->entries==-1)goto _eofout;
+
+  if(ov_ilog(s->dim)+ov_ilog(s->entries)>24)goto _eofout;
+
+  /* codeword ordering.... length ordered or unordered? */
+  switch((int)oggpack_read(opb,1)){
+  case 0:{
+    long unused;
+    /* allocated but unused entries? */
+    unused=oggpack_read(opb,1);
+    if((s->entries*(unused?1:5)+7)>>3>opb->storage-oggpack_bytes(opb))
+      goto _eofout;
+    /* unordered */
+    s->lengthlist=_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
+
+    /* allocated but unused entries? */
+    if(unused){
+      /* yes, unused entries */
+
+      for(i=0;i<s->entries;i++){
+        if(oggpack_read(opb,1)){
+          long num=oggpack_read(opb,5);
+          if(num==-1)goto _eofout;
+          s->lengthlist[i]=num+1;
+        }else
+          s->lengthlist[i]=0;
+      }
+    }else{
+      /* all entries used; no tagging */
+      for(i=0;i<s->entries;i++){
+        long num=oggpack_read(opb,5);
+        if(num==-1)goto _eofout;
+        s->lengthlist[i]=num+1;
+      }
+    }
+
+    break;
+  }
+  case 1:
+    /* ordered */
+    {
+      long length=oggpack_read(opb,5)+1;
+      if(length==0)goto _eofout;
+      s->lengthlist=_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
+
+      for(i=0;i<s->entries;){
+        long num=oggpack_read(opb,ov_ilog(s->entries-i));
+        if(num==-1)goto _eofout;
+        if(length>32 || num>s->entries-i ||
+           (num>0 && (num-1)>>(length-1)>1)){
+          goto _errout;
+        }
+        if(length>32)goto _errout;
+        for(j=0;j<num;j++,i++)
+          s->lengthlist[i]=length;
+        length++;
+      }
+    }
+    break;
+  default:
+    /* EOF */
+    goto _eofout;
+  }
+
+  /* Do we have a mapping to unpack? */
+  switch((s->maptype=oggpack_read(opb,4))){
+  case 0:
+    /* no mapping */
+    break;
+  case 1: case 2:
+    /* implicitly populated value mapping */
+    /* explicitly populated value mapping */
+
+    s->q_min=oggpack_read(opb,32);
+    s->q_delta=oggpack_read(opb,32);
+    s->q_quant=oggpack_read(opb,4)+1;
+    s->q_sequencep=oggpack_read(opb,1);
+    if(s->q_sequencep==-1)goto _eofout;
+
+    {
+      int quantvals=0;
+      switch(s->maptype){
+      case 1:
+        quantvals=(s->dim==0?0:_book_maptype1_quantvals(s));
+        break;
+      case 2:
+        quantvals=s->entries*s->dim;
+        break;
+      }
+
+      /* quantized values */
+      if(((quantvals*s->q_quant+7)>>3)>opb->storage-oggpack_bytes(opb))
+        goto _eofout;
+      s->quantlist=_ogg_malloc(sizeof(*s->quantlist)*quantvals);
+      for(i=0;i<quantvals;i++)
+        s->quantlist[i]=oggpack_read(opb,s->q_quant);
+
+      if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
+    }
+    break;
+  default:
+    goto _errout;
+  }
+
+  /* all set */
+  return(s);
+
+ _errout:
+ _eofout:
+  vorbis_staticbook_destroy(s);
+  return(NULL);
+}
+
+/* returns the number of bits ************************************************/
+int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
+  if(a<0 || a>=book->c->entries)return(0);
+  oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
+  return(book->c->lengthlist[a]);
+}
+
+/* the 'eliminate the decode tree' optimization actually requires the
+   codewords to be MSb first, not LSb.  This is an annoying inelegancy
+   (and one of the first places where carefully thought out design
+   turned out to be wrong; Vorbis II and future Ogg codecs should go
+   to an MSb bitpacker), but not actually the huge hit it appears to
+   be.  The first-stage decode table catches most words so that
+   bitreverse is not in the main execution path. */
+
+static ogg_uint32_t bitreverse(ogg_uint32_t x){
+  x=    ((x>>16)&0x0000ffff) | ((x<<16)&0xffff0000);
+  x=    ((x>> 8)&0x00ff00ff) | ((x<< 8)&0xff00ff00);
+  x=    ((x>> 4)&0x0f0f0f0f) | ((x<< 4)&0xf0f0f0f0);
+  x=    ((x>> 2)&0x33333333) | ((x<< 2)&0xcccccccc);
+  return((x>> 1)&0x55555555) | ((x<< 1)&0xaaaaaaaa);
+}
+
+STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
+  int  read=book->dec_maxlength;
+  long lo,hi;
+  long lok = oggpack_look(b,book->dec_firsttablen);
+
+  if (lok >= 0) {
+    long entry = book->dec_firsttable[lok];
+    if(entry&0x80000000UL){
+      lo=(entry>>15)&0x7fff;
+      hi=book->used_entries-(entry&0x7fff);
+    }else{
+      oggpack_adv(b, book->dec_codelengths[entry-1]);
+      return(entry-1);
+    }
+  }else{
+    lo=0;
+    hi=book->used_entries;
+  }
+
+  /* Single entry codebooks use a firsttablen of 1 and a
+     dec_maxlength of 1.  If a single-entry codebook gets here (due to
+     failure to read one bit above), the next look attempt will also
+     fail and we'll correctly kick out instead of trying to walk the
+     underformed tree */
+
+  lok = oggpack_look(b, read);
+
+  while(lok<0 && read>1)
+    lok = oggpack_look(b, --read);
+  if(lok<0)return -1;
+
+  /* bisect search for the codeword in the ordered list */
+  {
+    ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
+
+    while(hi-lo>1){
+      long p=(hi-lo)>>1;
+      long test=book->codelist[lo+p]>testword;
+      lo+=p&(test-1);
+      hi-=p&(-test);
+      }
+
+    if(book->dec_codelengths[lo]<=read){
+      oggpack_adv(b, book->dec_codelengths[lo]);
+      return(lo);
+    }
+  }
+
+  oggpack_adv(b, read);
+
+  return(-1);
+}
+
+/* Decode side is specced and easier, because we don't need to find
+   matches using different criteria; we simply read and map.  There are
+   two things we need to do 'depending':
+
+   We may need to support interleave.  We don't really, but it's
+   convenient to do it here rather than rebuild the vector later.
+
+   Cascades may be additive or multiplicitive; this is not inherent in
+   the codebook, but set in the code using the codebook.  Like
+   interleaving, it's easiest to do it here.
+   addmul==0 -> declarative (set the value)
+   addmul==1 -> additive
+   addmul==2 -> multiplicitive */
+
+/* returns the [original, not compacted] entry number or -1 on eof *********/
+long vorbis_book_decode(codebook *book, oggpack_buffer *b){
+  if(book->used_entries>0){
+    long packed_entry=decode_packed_entry_number(book,b);
+    if(packed_entry>=0)
+      return(book->dec_index[packed_entry]);
+  }
+
+  /* if there's no dec_index, the codebook unpacking isn't collapsed */
+  return(-1);
+}
+
+/* returns 0 on OK or -1 on eof *************************************/
+/* decode vector / dim granularity gaurding is done in the upper layer */
+long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
+  if(book->used_entries>0){
+    int step=n/book->dim;
+    long *entry = alloca(sizeof(*entry)*step);
+    float **t = alloca(sizeof(*t)*step);
+    int i,j,o;
+
+    for (i = 0; i < step; i++) {
+      entry[i]=decode_packed_entry_number(book,b);
+      if(entry[i]==-1)return(-1);
+      t[i] = book->valuelist+entry[i]*book->dim;
+    }
+    for(i=0,o=0;i<book->dim;i++,o+=step)
+      for (j=0;o+j<n && j<step;j++)
+        a[o+j]+=t[j][i];
+  }
+  return(0);
+}
+
+/* decode vector / dim granularity gaurding is done in the upper layer */
+long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
+  if(book->used_entries>0){
+    int i,j,entry;
+    float *t;
+
+    for(i=0;i<n;){
+      entry = decode_packed_entry_number(book,b);
+      if(entry==-1)return(-1);
+      t     = book->valuelist+entry*book->dim;
+      for(j=0;i<n && j<book->dim;)
+        a[i++]+=t[j++];
+    }
+  }
+  return(0);
+}
+
+/* unlike the others, we guard against n not being an integer number
+   of <dim> internally rather than in the upper layer (called only by
+   floor0) */
+long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
+  if(book->used_entries>0){
+    int i,j,entry;
+    float *t;
+
+    for(i=0;i<n;){
+      entry = decode_packed_entry_number(book,b);
+      if(entry==-1)return(-1);
+      t     = book->valuelist+entry*book->dim;
+      for (j=0;i<n && j<book->dim;){
+        a[i++]=t[j++];
+      }
+    }
+  }else{
+    int i;
+
+    for(i=0;i<n;){
+      a[i++]=0.f;
+    }
+  }
+  return(0);
+}
+
+long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
+                              oggpack_buffer *b,int n){
+
+  long i,j,entry;
+  int chptr=0;
+  if(book->used_entries>0){
+    int m=(offset+n)/ch;
+    for(i=offset/ch;i<m;){
+      entry = decode_packed_entry_number(book,b);
+      if(entry==-1)return(-1);
+      {
+        const float *t = book->valuelist+entry*book->dim;
+        for (j=0;i<m && j<book->dim;j++){
+          a[chptr++][i]+=t[j];
+          if(chptr==ch){
+            chptr=0;
+            i++;
+          }
+        }
+      }
+    }
+  }
+  return(0);
+}
diff --git a/vorbis/lib/codebook.h b/vorbis/lib/codebook.h
new file mode 100644 (file)
index 0000000..08440c6
--- /dev/null
@@ -0,0 +1,117 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: basic shared codebook operations
+
+ ********************************************************************/
+
+#ifndef _V_CODEBOOK_H_
+#define _V_CODEBOOK_H_
+
+#include <ogg/ogg.h>
+
+/* This structure encapsulates huffman and VQ style encoding books; it
+   doesn't do anything specific to either.
+
+   valuelist/quantlist are nonNULL (and q_* significant) only if
+   there's entry->value mapping to be done.
+
+   If encode-side mapping must be done (and thus the entry needs to be
+   hunted), the auxiliary encode pointer will point to a decision
+   tree.  This is true of both VQ and huffman, but is mostly useful
+   with VQ.
+
+*/
+
+typedef struct static_codebook{
+  long   dim;           /* codebook dimensions (elements per vector) */
+  long   entries;       /* codebook entries */
+  char  *lengthlist;    /* codeword lengths in bits */
+
+  /* mapping ***************************************************************/
+  int    maptype;       /* 0=none
+                           1=implicitly populated values from map column
+                           2=listed arbitrary values */
+
+  /* The below does a linear, single monotonic sequence mapping. */
+  long     q_min;       /* packed 32 bit float; quant value 0 maps to minval */
+  long     q_delta;     /* packed 32 bit float; val 1 - val 0 == delta */
+  int      q_quant;     /* bits: 0 < quant <= 16 */
+  int      q_sequencep; /* bitflag */
+
+  long     *quantlist;  /* map == 1: (int)(entries^(1/dim)) element column map
+                           map == 2: list of dim*entries quantized entry vals
+                        */
+  int allocedp;
+} static_codebook;
+
+typedef struct codebook{
+  long dim;           /* codebook dimensions (elements per vector) */
+  long entries;       /* codebook entries */
+  long used_entries;  /* populated codebook entries */
+  const static_codebook *c;
+
+  /* for encode, the below are entry-ordered, fully populated */
+  /* for decode, the below are ordered by bitreversed codeword and only
+     used entries are populated */
+  float        *valuelist;  /* list of dim*entries actual entry values */
+  ogg_uint32_t *codelist;   /* list of bitstream codewords for each entry */
+
+  int          *dec_index;  /* only used if sparseness collapsed */
+  char         *dec_codelengths;
+  ogg_uint32_t *dec_firsttable;
+  int           dec_firsttablen;
+  int           dec_maxlength;
+
+  /* The current encoder uses only centered, integer-only lattice books. */
+  int           quantvals;
+  int           minval;
+  int           delta;
+} codebook;
+
+extern void vorbis_staticbook_destroy(static_codebook *b);
+extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
+extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
+extern void vorbis_book_clear(codebook *b);
+
+extern float *_book_unquantize(const static_codebook *b,int n,int *map);
+extern float *_book_logdist(const static_codebook *b,float *vals);
+extern float _float32_unpack(long val);
+extern long   _float32_pack(float val);
+extern int  _best(codebook *book, float *a, int step);
+extern long _book_maptype1_quantvals(const static_codebook *b);
+
+extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
+extern long vorbis_book_codeword(codebook *book,int entry);
+extern long vorbis_book_codelen(codebook *book,int entry);
+
+
+
+extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
+extern static_codebook *vorbis_staticbook_unpack(oggpack_buffer *b);
+
+extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
+
+extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
+extern long vorbis_book_decodevs_add(codebook *book, float *a,
+                                     oggpack_buffer *b,int n);
+extern long vorbis_book_decodev_set(codebook *book, float *a,
+                                    oggpack_buffer *b,int n);
+extern long vorbis_book_decodev_add(codebook *book, float *a,
+                                    oggpack_buffer *b,int n);
+extern long vorbis_book_decodevv_add(codebook *book, float **a,
+                                     long off,int ch,
+                                    oggpack_buffer *b,int n);
+
+
+
+#endif
diff --git a/vorbis/lib/codec_internal.h b/vorbis/lib/codec_internal.h
new file mode 100644 (file)
index 0000000..e522be1
--- /dev/null
@@ -0,0 +1,166 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: libvorbis codec headers
+
+ ********************************************************************/
+
+#ifndef _V_CODECI_H_
+#define _V_CODECI_H_
+
+#include "envelope.h"
+#include "codebook.h"
+
+#define BLOCKTYPE_IMPULSE    0
+#define BLOCKTYPE_PADDING    1
+#define BLOCKTYPE_TRANSITION 0
+#define BLOCKTYPE_LONG       1
+
+#define PACKETBLOBS 15
+
+typedef struct vorbis_block_internal{
+  float  **pcmdelay;  /* this is a pointer into local storage */
+  float  ampmax;
+  int    blocktype;
+
+  oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
+                                              blob [PACKETBLOBS/2] points to
+                                              the oggpack_buffer in the
+                                              main vorbis_block */
+} vorbis_block_internal;
+
+typedef void vorbis_look_floor;
+typedef void vorbis_look_residue;
+typedef void vorbis_look_transform;
+
+/* mode ************************************************************/
+typedef struct {
+  int blockflag;
+  int windowtype;
+  int transformtype;
+  int mapping;
+} vorbis_info_mode;
+
+typedef void vorbis_info_floor;
+typedef void vorbis_info_residue;
+typedef void vorbis_info_mapping;
+
+#include "psy.h"
+#include "bitrate.h"
+
+typedef struct private_state {
+  /* local lookup storage */
+  envelope_lookup        *ve; /* envelope lookup */
+  int                     window[2];
+  vorbis_look_transform **transform[2];    /* block, type */
+  drft_lookup             fft_look[2];
+
+  int                     modebits;
+  vorbis_look_floor     **flr;
+  vorbis_look_residue   **residue;
+  vorbis_look_psy        *psy;
+  vorbis_look_psy_global *psy_g_look;
+
+  /* local storage, only used on the encoding side.  This way the
+     application does not need to worry about freeing some packets'
+     memory and not others'; packet storage is always tracked.
+     Cleared next call to a _dsp_ function */
+  unsigned char *header;
+  unsigned char *header1;
+  unsigned char *header2;
+
+  bitrate_manager_state bms;
+
+  ogg_int64_t sample_count;
+} private_state;
+
+/* codec_setup_info contains all the setup information specific to the
+   specific compression/decompression mode in progress (eg,
+   psychoacoustic settings, channel setup, options, codebook
+   etc).
+*********************************************************************/
+
+#include "highlevel.h"
+typedef struct codec_setup_info {
+
+  /* Vorbis supports only short and long blocks, but allows the
+     encoder to choose the sizes */
+
+  long blocksizes[2];
+
+  /* modes are the primary means of supporting on-the-fly different
+     blocksizes, different channel mappings (LR or M/A),
+     different residue backends, etc.  Each mode consists of a
+     blocksize flag and a mapping (along with the mapping setup */
+
+  int        modes;
+  int        maps;
+  int        floors;
+  int        residues;
+  int        books;
+  int        psys;     /* encode only */
+
+  vorbis_info_mode       *mode_param[64];
+  int                     map_type[64];
+  vorbis_info_mapping    *map_param[64];
+  int                     floor_type[64];
+  vorbis_info_floor      *floor_param[64];
+  int                     residue_type[64];
+  vorbis_info_residue    *residue_param[64];
+  static_codebook        *book_param[256];
+  codebook               *fullbooks;
+
+  vorbis_info_psy        *psy_param[4]; /* encode only */
+  vorbis_info_psy_global psy_g_param;
+
+  bitrate_manager_info   bi;
+  highlevel_encode_setup hi; /* used only by vorbisenc.c.  It's a
+                                highly redundant structure, but
+                                improves clarity of program flow. */
+  int         halfrate_flag; /* painless downsample for decode */
+} codec_setup_info;
+
+extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
+extern void _vp_global_free(vorbis_look_psy_global *look);
+
+
+
+typedef struct {
+  int sorted_index[VIF_POSIT+2];
+  int forward_index[VIF_POSIT+2];
+  int reverse_index[VIF_POSIT+2];
+
+  int hineighbor[VIF_POSIT];
+  int loneighbor[VIF_POSIT];
+  int posts;
+
+  int n;
+  int quant_q;
+  vorbis_info_floor1 *vi;
+
+  long phrasebits;
+  long postbits;
+  long frames;
+} vorbis_look_floor1;
+
+
+
+extern int *floor1_fit(vorbis_block *vb,vorbis_look_floor1 *look,
+                          const float *logmdct,   /* in */
+                          const float *logmask);
+extern int *floor1_interpolate_fit(vorbis_block *vb,vorbis_look_floor1 *look,
+                          int *A,int *B,
+                          int del);
+extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
+                  vorbis_look_floor1 *look,
+                  int *post,int *ilogmask);
+#endif
diff --git a/vorbis/lib/envelope.c b/vorbis/lib/envelope.c
new file mode 100644 (file)
index 0000000..da75237
--- /dev/null
@@ -0,0 +1,374 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: PCM data envelope analysis
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+
+#include "os.h"
+#include "scales.h"
+#include "envelope.h"
+#include "mdct.h"
+#include "misc.h"
+
+void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *gi=&ci->psy_g_param;
+  int ch=vi->channels;
+  int i,j;
+  int n=e->winlength=128;
+  e->searchstep=64; /* not random */
+
+  e->minenergy=gi->preecho_minenergy;
+  e->ch=ch;
+  e->storage=128;
+  e->cursor=ci->blocksizes[1]/2;
+  e->mdct_win=_ogg_calloc(n,sizeof(*e->mdct_win));
+  mdct_init(&e->mdct,n);
+
+  for(i=0;i<n;i++){
+    e->mdct_win[i]=sin(i/(n-1.)*M_PI);
+    e->mdct_win[i]*=e->mdct_win[i];
+  }
+
+  /* magic follows */
+  e->band[0].begin=2;  e->band[0].end=4;
+  e->band[1].begin=4;  e->band[1].end=5;
+  e->band[2].begin=6;  e->band[2].end=6;
+  e->band[3].begin=9;  e->band[3].end=8;
+  e->band[4].begin=13;  e->band[4].end=8;
+  e->band[5].begin=17;  e->band[5].end=8;
+  e->band[6].begin=22;  e->band[6].end=8;
+
+  for(j=0;j<VE_BANDS;j++){
+    n=e->band[j].end;
+    e->band[j].window=_ogg_malloc(n*sizeof(*e->band[0].window));
+    for(i=0;i<n;i++){
+      e->band[j].window[i]=sin((i+.5)/n*M_PI);
+      e->band[j].total+=e->band[j].window[i];
+    }
+    e->band[j].total=1./e->band[j].total;
+  }
+
+  e->filter=_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
+  e->mark=_ogg_calloc(e->storage,sizeof(*e->mark));
+
+}
+
+void _ve_envelope_clear(envelope_lookup *e){
+  int i;
+  mdct_clear(&e->mdct);
+  for(i=0;i<VE_BANDS;i++)
+    _ogg_free(e->band[i].window);
+  _ogg_free(e->mdct_win);
+  _ogg_free(e->filter);
+  _ogg_free(e->mark);
+  memset(e,0,sizeof(*e));
+}
+
+/* fairly straight threshhold-by-band based until we find something
+   that works better and isn't patented. */
+
+static int _ve_amp(envelope_lookup *ve,
+                   vorbis_info_psy_global *gi,
+                   float *data,
+                   envelope_band *bands,
+                   envelope_filter_state *filters){
+  long n=ve->winlength;
+  int ret=0;
+  long i,j;
+  float decay;
+
+  /* we want to have a 'minimum bar' for energy, else we're just
+     basing blocks on quantization noise that outweighs the signal
+     itself (for low power signals) */
+
+  float minV=ve->minenergy;
+  float *vec=alloca(n*sizeof(*vec));
+
+  /* stretch is used to gradually lengthen the number of windows
+     considered prevoius-to-potential-trigger */
+  int stretch=max(VE_MINSTRETCH,ve->stretch/2);
+  float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
+  if(penalty<0.f)penalty=0.f;
+  if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
+
+  /*_analysis_output_always("lpcm",seq2,data,n,0,0,
+    totalshift+pos*ve->searchstep);*/
+
+ /* window and transform */
+  for(i=0;i<n;i++)
+    vec[i]=data[i]*ve->mdct_win[i];
+  mdct_forward(&ve->mdct,vec,vec);
+
+  /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
+
+  /* near-DC spreading function; this has nothing to do with
+     psychoacoustics, just sidelobe leakage and window size */
+  {
+    float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
+    int ptr=filters->nearptr;
+
+    /* the accumulation is regularly refreshed from scratch to avoid
+       floating point creep */
+    if(ptr==0){
+      decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
+      filters->nearDC_partialacc=temp;
+    }else{
+      decay=filters->nearDC_acc+=temp;
+      filters->nearDC_partialacc+=temp;
+    }
+    filters->nearDC_acc-=filters->nearDC[ptr];
+    filters->nearDC[ptr]=temp;
+
+    decay*=(1./(VE_NEARDC+1));
+    filters->nearptr++;
+    if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
+    decay=todB(&decay)*.5-15.f;
+  }
+
+  /* perform spreading and limiting, also smooth the spectrum.  yes,
+     the MDCT results in all real coefficients, but it still *behaves*
+     like real/imaginary pairs */
+  for(i=0;i<n/2;i+=2){
+    float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
+    val=todB(&val)*.5f;
+    if(val<decay)val=decay;
+    if(val<minV)val=minV;
+    vec[i>>1]=val;
+    decay-=8.;
+  }
+
+  /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
+
+  /* perform preecho/postecho triggering by band */
+  for(j=0;j<VE_BANDS;j++){
+    float acc=0.;
+    float valmax,valmin;
+
+    /* accumulate amplitude */
+    for(i=0;i<bands[j].end;i++)
+      acc+=vec[i+bands[j].begin]*bands[j].window[i];
+
+    acc*=bands[j].total;
+
+    /* convert amplitude to delta */
+    {
+      int p,this=filters[j].ampptr;
+      float postmax,postmin,premax=-99999.f,premin=99999.f;
+
+      p=this;
+      p--;
+      if(p<0)p+=VE_AMP;
+      postmax=max(acc,filters[j].ampbuf[p]);
+      postmin=min(acc,filters[j].ampbuf[p]);
+
+      for(i=0;i<stretch;i++){
+        p--;
+        if(p<0)p+=VE_AMP;
+        premax=max(premax,filters[j].ampbuf[p]);
+        premin=min(premin,filters[j].ampbuf[p]);
+      }
+
+      valmin=postmin-premin;
+      valmax=postmax-premax;
+
+      /*filters[j].markers[pos]=valmax;*/
+      filters[j].ampbuf[this]=acc;
+      filters[j].ampptr++;
+      if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
+    }
+
+    /* look at min/max, decide trigger */
+    if(valmax>gi->preecho_thresh[j]+penalty){
+      ret|=1;
+      ret|=4;
+    }
+    if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
+  }
+
+  return(ret);
+}
+
+#if 0
+static int seq=0;
+static ogg_int64_t totalshift=-1024;
+#endif
+
+long _ve_envelope_search(vorbis_dsp_state *v){
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *gi=&ci->psy_g_param;
+  envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
+  long i,j;
+
+  int first=ve->current/ve->searchstep;
+  int last=v->pcm_current/ve->searchstep-VE_WIN;
+  if(first<0)first=0;
+
+  /* make sure we have enough storage to match the PCM */
+  if(last+VE_WIN+VE_POST>ve->storage){
+    ve->storage=last+VE_WIN+VE_POST; /* be sure */
+    ve->mark=_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
+  }
+
+  for(j=first;j<last;j++){
+    int ret=0;
+
+    ve->stretch++;
+    if(ve->stretch>VE_MAXSTRETCH*2)
+      ve->stretch=VE_MAXSTRETCH*2;
+
+    for(i=0;i<ve->ch;i++){
+      float *pcm=v->pcm[i]+ve->searchstep*(j);
+      ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS);
+    }
+
+    ve->mark[j+VE_POST]=0;
+    if(ret&1){
+      ve->mark[j]=1;
+      ve->mark[j+1]=1;
+    }
+
+    if(ret&2){
+      ve->mark[j]=1;
+      if(j>0)ve->mark[j-1]=1;
+    }
+
+    if(ret&4)ve->stretch=-1;
+  }
+
+  ve->current=last*ve->searchstep;
+
+  {
+    long centerW=v->centerW;
+    long testW=
+      centerW+
+      ci->blocksizes[v->W]/4+
+      ci->blocksizes[1]/2+
+      ci->blocksizes[0]/4;
+
+    j=ve->cursor;
+
+    while(j<ve->current-(ve->searchstep)){/* account for postecho
+                                             working back one window */
+      if(j>=testW)return(1);
+
+      ve->cursor=j;
+
+      if(ve->mark[j/ve->searchstep]){
+        if(j>centerW){
+
+#if 0
+          if(j>ve->curmark){
+            float *marker=alloca(v->pcm_current*sizeof(*marker));
+            int l,m;
+            memset(marker,0,sizeof(*marker)*v->pcm_current);
+            fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
+                    seq,
+                    (totalshift+ve->cursor)/44100.,
+                    (totalshift+j)/44100.);
+            _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
+            _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
+
+            _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
+            _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
+
+            for(m=0;m<VE_BANDS;m++){
+              char buf[80];
+              sprintf(buf,"delL%d",m);
+              for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
+              _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
+            }
+
+            for(m=0;m<VE_BANDS;m++){
+              char buf[80];
+              sprintf(buf,"delR%d",m);
+              for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
+              _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
+            }
+
+            for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
+            _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
+
+
+            seq++;
+
+          }
+#endif
+
+          ve->curmark=j;
+          if(j>=testW)return(1);
+          return(0);
+        }
+      }
+      j+=ve->searchstep;
+    }
+  }
+
+  return(-1);
+}
+
+int _ve_envelope_mark(vorbis_dsp_state *v){
+  envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
+  vorbis_info *vi=v->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  long centerW=v->centerW;
+  long beginW=centerW-ci->blocksizes[v->W]/4;
+  long endW=centerW+ci->blocksizes[v->W]/4;
+  if(v->W){
+    beginW-=ci->blocksizes[v->lW]/4;
+    endW+=ci->blocksizes[v->nW]/4;
+  }else{
+    beginW-=ci->blocksizes[0]/4;
+    endW+=ci->blocksizes[0]/4;
+  }
+
+  if(ve->curmark>=beginW && ve->curmark<endW)return(1);
+  {
+    long first=beginW/ve->searchstep;
+    long last=endW/ve->searchstep;
+    long i;
+    for(i=first;i<last;i++)
+      if(ve->mark[i])return(1);
+  }
+  return(0);
+}
+
+void _ve_envelope_shift(envelope_lookup *e,long shift){
+  int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
+                                                     ahead of ve->current */
+  int smallshift=shift/e->searchstep;
+
+  memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
+
+#if 0
+  for(i=0;i<VE_BANDS*e->ch;i++)
+    memmove(e->filter[i].markers,
+            e->filter[i].markers+smallshift,
+            (1024-smallshift)*sizeof(*(*e->filter).markers));
+  totalshift+=shift;
+#endif
+
+  e->current-=shift;
+  if(e->curmark>=0)
+    e->curmark-=shift;
+  e->cursor-=shift;
+}
diff --git a/vorbis/lib/envelope.h b/vorbis/lib/envelope.h
new file mode 100644 (file)
index 0000000..f466efd
--- /dev/null
@@ -0,0 +1,79 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: PCM data envelope analysis and manipulation
+
+ ********************************************************************/
+
+#ifndef _V_ENVELOPE_
+#define _V_ENVELOPE_
+
+#include "mdct.h"
+
+#define VE_PRE    16
+#define VE_WIN    4
+#define VE_POST   2
+#define VE_AMP    (VE_PRE+VE_POST-1)
+
+#define VE_BANDS  7
+#define VE_NEARDC 15
+
+#define VE_MINSTRETCH 2   /* a bit less than short block */
+#define VE_MAXSTRETCH 12  /* one-third full block */
+
+typedef struct {
+  float ampbuf[VE_AMP];
+  int   ampptr;
+
+  float nearDC[VE_NEARDC];
+  float nearDC_acc;
+  float nearDC_partialacc;
+  int   nearptr;
+
+} envelope_filter_state;
+
+typedef struct {
+  int begin;
+  int end;
+  float *window;
+  float total;
+} envelope_band;
+
+typedef struct {
+  int ch;
+  int winlength;
+  int searchstep;
+  float minenergy;
+
+  mdct_lookup  mdct;
+  float       *mdct_win;
+
+  envelope_band          band[VE_BANDS];
+  envelope_filter_state *filter;
+  int   stretch;
+
+  int                   *mark;
+
+  long storage;
+  long current;
+  long curmark;
+  long cursor;
+} envelope_lookup;
+
+extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
+extern void _ve_envelope_clear(envelope_lookup *e);
+extern long _ve_envelope_search(vorbis_dsp_state *v);
+extern void _ve_envelope_shift(envelope_lookup *e,long shift);
+extern int  _ve_envelope_mark(vorbis_dsp_state *v);
+
+
+#endif
diff --git a/vorbis/lib/floor0.c b/vorbis/lib/floor0.c
new file mode 100644 (file)
index 0000000..443c0e5
--- /dev/null
@@ -0,0 +1,223 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: floor backend 0 implementation
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "lpc.h"
+#include "lsp.h"
+#include "codebook.h"
+#include "scales.h"
+#include "misc.h"
+#include "os.h"
+
+#include "misc.h"
+#include <stdio.h>
+
+typedef struct {
+  int ln;
+  int  m;
+  int **linearmap;
+  int  n[2];
+
+  vorbis_info_floor0 *vi;
+
+  long bits;
+  long frames;
+} vorbis_look_floor0;
+
+
+/***********************************************/
+
+static void floor0_free_info(vorbis_info_floor *i){
+  vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
+  if(info){
+    memset(info,0,sizeof(*info));
+    _ogg_free(info);
+  }
+}
+
+static void floor0_free_look(vorbis_look_floor *i){
+  vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
+  if(look){
+
+    if(look->linearmap){
+
+      if(look->linearmap[0])_ogg_free(look->linearmap[0]);
+      if(look->linearmap[1])_ogg_free(look->linearmap[1]);
+
+      _ogg_free(look->linearmap);
+    }
+    memset(look,0,sizeof(*look));
+    _ogg_free(look);
+  }
+}
+
+static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
+  codec_setup_info     *ci=vi->codec_setup;
+  int j;
+
+  vorbis_info_floor0 *info=_ogg_malloc(sizeof(*info));
+  info->order=oggpack_read(opb,8);
+  info->rate=oggpack_read(opb,16);
+  info->barkmap=oggpack_read(opb,16);
+  info->ampbits=oggpack_read(opb,6);
+  info->ampdB=oggpack_read(opb,8);
+  info->numbooks=oggpack_read(opb,4)+1;
+
+  if(info->order<1)goto err_out;
+  if(info->rate<1)goto err_out;
+  if(info->barkmap<1)goto err_out;
+  if(info->numbooks<1)goto err_out;
+
+  for(j=0;j<info->numbooks;j++){
+    info->books[j]=oggpack_read(opb,8);
+    if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
+    if(ci->book_param[info->books[j]]->maptype==0)goto err_out;
+    if(ci->book_param[info->books[j]]->dim<1)goto err_out;
+  }
+  return(info);
+
+ err_out:
+  floor0_free_info(info);
+  return(NULL);
+}
+
+/* initialize Bark scale and normalization lookups.  We could do this
+   with static tables, but Vorbis allows a number of possible
+   combinations, so it's best to do it computationally.
+
+   The below is authoritative in terms of defining scale mapping.
+   Note that the scale depends on the sampling rate as well as the
+   linear block and mapping sizes */
+
+static void floor0_map_lazy_init(vorbis_block      *vb,
+                                 vorbis_info_floor *infoX,
+                                 vorbis_look_floor0 *look){
+  if(!look->linearmap[vb->W]){
+    vorbis_dsp_state   *vd=vb->vd;
+    vorbis_info        *vi=vd->vi;
+    codec_setup_info   *ci=vi->codec_setup;
+    vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
+    int W=vb->W;
+    int n=ci->blocksizes[W]/2,j;
+
+    /* we choose a scaling constant so that:
+       floor(bark(rate/2-1)*C)=mapped-1
+     floor(bark(rate/2)*C)=mapped */
+    float scale=look->ln/toBARK(info->rate/2.f);
+
+    /* the mapping from a linear scale to a smaller bark scale is
+       straightforward.  We do *not* make sure that the linear mapping
+       does not skip bark-scale bins; the decoder simply skips them and
+       the encoder may do what it wishes in filling them.  They're
+       necessary in some mapping combinations to keep the scale spacing
+       accurate */
+    look->linearmap[W]=_ogg_malloc((n+1)*sizeof(**look->linearmap));
+    for(j=0;j<n;j++){
+      int val=floor( toBARK((info->rate/2.f)/n*j)
+                     *scale); /* bark numbers represent band edges */
+      if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
+      look->linearmap[W][j]=val;
+    }
+    look->linearmap[W][j]=-1;
+    look->n[W]=n;
+  }
+}
+
+static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
+                                      vorbis_info_floor *i){
+  vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
+  vorbis_look_floor0 *look=_ogg_calloc(1,sizeof(*look));
+
+  (void)vd;
+
+  look->m=info->order;
+  look->ln=info->barkmap;
+  look->vi=info;
+
+  look->linearmap=_ogg_calloc(2,sizeof(*look->linearmap));
+
+  return look;
+}
+
+static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
+  vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
+  vorbis_info_floor0 *info=look->vi;
+  int j,k;
+
+  int ampraw=oggpack_read(&vb->opb,info->ampbits);
+  if(ampraw>0){ /* also handles the -1 out of data case */
+    long maxval=(1<<info->ampbits)-1;
+    float amp=(float)ampraw/maxval*info->ampdB;
+    int booknum=oggpack_read(&vb->opb,ov_ilog(info->numbooks));
+
+    if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
+      codec_setup_info  *ci=vb->vd->vi->codec_setup;
+      codebook *b=ci->fullbooks+info->books[booknum];
+      float last=0.f;
+
+      /* the additional b->dim is a guard against any possible stack
+         smash; b->dim is provably more than we can overflow the
+         vector */
+      float *lsp=_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
+
+      if(vorbis_book_decodev_set(b,lsp,&vb->opb,look->m)==-1)goto eop;
+      for(j=0;j<look->m;){
+        for(k=0;j<look->m && k<b->dim;k++,j++)lsp[j]+=last;
+        last=lsp[j-1];
+      }
+
+      lsp[look->m]=amp;
+      return(lsp);
+    }
+  }
+ eop:
+  return(NULL);
+}
+
+static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
+                           void *memo,float *out){
+  vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
+  vorbis_info_floor0 *info=look->vi;
+
+  floor0_map_lazy_init(vb,info,look);
+
+  if(memo){
+    float *lsp=(float *)memo;
+    float amp=lsp[look->m];
+
+    /* take the coefficients back to a spectral envelope curve */
+    vorbis_lsp_to_curve(out,
+                        look->linearmap[vb->W],
+                        look->n[vb->W],
+                        look->ln,
+                        lsp,look->m,amp,(float)info->ampdB);
+    return(1);
+  }
+  memset(out,0,sizeof(*out)*look->n[vb->W]);
+  return(0);
+}
+
+/* export hooks */
+const vorbis_func_floor floor0_exportbundle={
+  NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
+  &floor0_free_look,&floor0_inverse1,&floor0_inverse2
+};
diff --git a/vorbis/lib/floor1.c b/vorbis/lib/floor1.c
new file mode 100644 (file)
index 0000000..673e954
--- /dev/null
@@ -0,0 +1,1086 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: floor backend 1 implementation
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "codebook.h"
+#include "misc.h"
+#include "scales.h"
+
+#include <stdio.h>
+
+#define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
+
+typedef struct lsfit_acc{
+  int x0;
+  int x1;
+
+  int xa;
+  int ya;
+  int x2a;
+  int y2a;
+  int xya;
+  int an;
+
+  int xb;
+  int yb;
+  int x2b;
+  int y2b;
+  int xyb;
+  int bn;
+} lsfit_acc;
+
+/***********************************************/
+
+static void floor1_free_info(vorbis_info_floor *i){
+  vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
+  if(info){
+    memset(info,0,sizeof(*info));
+    _ogg_free(info);
+  }
+}
+
+static void floor1_free_look(vorbis_look_floor *i){
+  vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
+  if(look){
+    /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
+            (float)look->phrasebits/look->frames,
+            (float)look->postbits/look->frames,
+            (float)(look->postbits+look->phrasebits)/look->frames);*/
+
+    memset(look,0,sizeof(*look));
+    _ogg_free(look);
+  }
+}
+
+static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
+  vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
+  int j,k;
+  int count=0;
+  int rangebits;
+  int maxposit=info->postlist[1];
+  int maxclass=-1;
+
+  /* save out partitions */
+  oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
+  for(j=0;j<info->partitions;j++){
+    oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
+    if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
+  }
+
+  /* save out partition classes */
+  for(j=0;j<maxclass+1;j++){
+    oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
+    oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
+    if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
+    for(k=0;k<(1<<info->class_subs[j]);k++)
+      oggpack_write(opb,info->class_subbook[j][k]+1,8);
+  }
+
+  /* save out the post list */
+  oggpack_write(opb,info->mult-1,2);     /* only 1,2,3,4 legal now */
+  /* maxposit cannot legally be less than 1; this is encode-side, we
+     can assume our setup is OK */
+  oggpack_write(opb,ov_ilog(maxposit-1),4);
+  rangebits=ov_ilog(maxposit-1);
+
+  for(j=0,k=0;j<info->partitions;j++){
+    count+=info->class_dim[info->partitionclass[j]];
+    for(;k<count;k++)
+      oggpack_write(opb,info->postlist[k+2],rangebits);
+  }
+}
+
+static int icomp(const void *a,const void *b){
+  return(**(int **)a-**(int **)b);
+}
+
+static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
+  codec_setup_info     *ci=vi->codec_setup;
+  int j,k,count=0,maxclass=-1,rangebits;
+
+  vorbis_info_floor1 *info=_ogg_calloc(1,sizeof(*info));
+  /* read partitions */
+  info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
+  for(j=0;j<info->partitions;j++){
+    info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
+    if(info->partitionclass[j]<0)goto err_out;
+    if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
+  }
+
+  /* read partition classes */
+  for(j=0;j<maxclass+1;j++){
+    info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
+    info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
+    if(info->class_subs[j]<0)
+      goto err_out;
+    if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
+    if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
+      goto err_out;
+    for(k=0;k<(1<<info->class_subs[j]);k++){
+      info->class_subbook[j][k]=oggpack_read(opb,8)-1;
+      if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
+        goto err_out;
+    }
+  }
+
+  /* read the post list */
+  info->mult=oggpack_read(opb,2)+1;     /* only 1,2,3,4 legal now */
+  rangebits=oggpack_read(opb,4);
+  if(rangebits<0)goto err_out;
+
+  for(j=0,k=0;j<info->partitions;j++){
+    count+=info->class_dim[info->partitionclass[j]];
+    if(count>VIF_POSIT) goto err_out;
+    for(;k<count;k++){
+      int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
+      if(t<0 || t>=(1<<rangebits))
+        goto err_out;
+    }
+  }
+  info->postlist[0]=0;
+  info->postlist[1]=1<<rangebits;
+
+  /* don't allow repeated values in post list as they'd result in
+     zero-length segments */
+  {
+    int *sortpointer[VIF_POSIT+2];
+    for(j=0;j<count+2;j++)sortpointer[j]=info->postlist+j;
+    qsort(sortpointer,count+2,sizeof(*sortpointer),icomp);
+
+    for(j=1;j<count+2;j++)
+      if(*sortpointer[j-1]==*sortpointer[j])goto err_out;
+  }
+
+  return(info);
+
+ err_out:
+  floor1_free_info(info);
+  return(NULL);
+}
+
+static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
+                                      vorbis_info_floor *in){
+
+  int *sortpointer[VIF_POSIT+2];
+  vorbis_info_floor1 *info=(vorbis_info_floor1 *)in;
+  vorbis_look_floor1 *look=_ogg_calloc(1,sizeof(*look));
+  int i,j,n=0;
+
+  (void)vd;
+
+  look->vi=info;
+  look->n=info->postlist[1];
+
+  /* we drop each position value in-between already decoded values,
+     and use linear interpolation to predict each new value past the
+     edges.  The positions are read in the order of the position
+     list... we precompute the bounding positions in the lookup.  Of
+     course, the neighbors can change (if a position is declined), but
+     this is an initial mapping */
+
+  for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
+  n+=2;
+  look->posts=n;
+
+  /* also store a sorted position index */
+  for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
+  qsort(sortpointer,n,sizeof(*sortpointer),icomp);
+
+  /* points from sort order back to range number */
+  for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
+  /* points from range order to sorted position */
+  for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
+  /* we actually need the post values too */
+  for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
+
+  /* quantize values to multiplier spec */
+  switch(info->mult){
+  case 1: /* 1024 -> 256 */
+    look->quant_q=256;
+    break;
+  case 2: /* 1024 -> 128 */
+    look->quant_q=128;
+    break;
+  case 3: /* 1024 -> 86 */
+    look->quant_q=86;
+    break;
+  case 4: /* 1024 -> 64 */
+    look->quant_q=64;
+    break;
+  }
+
+  /* discover our neighbors for decode where we don't use fit flags
+     (that would push the neighbors outward) */
+  for(i=0;i<n-2;i++){
+    int lo=0;
+    int hi=1;
+    int lx=0;
+    int hx=look->n;
+    int currentx=info->postlist[i+2];
+    for(j=0;j<i+2;j++){
+      int x=info->postlist[j];
+      if(x>lx && x<currentx){
+        lo=j;
+        lx=x;
+      }
+      if(x<hx && x>currentx){
+        hi=j;
+        hx=x;
+      }
+    }
+    look->loneighbor[i]=lo;
+    look->hineighbor[i]=hi;
+  }
+
+  return(look);
+}
+
+static int render_point(int x0,int x1,int y0,int y1,int x){
+  y0&=0x7fff; /* mask off flag */
+  y1&=0x7fff;
+
+  {
+    int dy=y1-y0;
+    int adx=x1-x0;
+    int ady=abs(dy);
+    int err=ady*(x-x0);
+
+    int off=err/adx;
+    if(dy<0)return(y0-off);
+    return(y0+off);
+  }
+}
+
+static int vorbis_dBquant(const float *x){
+  int i= *x*7.3142857f+1023.5f;
+  if(i>1023)return(1023);
+  if(i<0)return(0);
+  return i;
+}
+
+static const float FLOOR1_fromdB_LOOKUP[256]={
+  1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
+  1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
+  1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
+  2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
+  2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
+  3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
+  4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
+  6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
+  7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
+  1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
+  1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
+  1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
+  2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
+  2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
+  3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
+  4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
+  5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
+  7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
+  9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
+  1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
+  1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
+  2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
+  2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
+  3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
+  4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
+  5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
+  7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
+  9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
+  0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
+  0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
+  0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
+  0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
+  0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
+  0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
+  0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
+  0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
+  0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
+  0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
+  0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
+  0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
+  0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
+  0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
+  0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
+  0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
+  0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
+  0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
+  0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
+  0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
+  0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
+  0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
+  0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
+  0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
+  0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
+  0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
+  0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
+  0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
+  0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
+  0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
+  0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
+  0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
+  0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
+  0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
+  0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
+  0.82788260F, 0.88168307F, 0.9389798F, 1.F,
+};
+
+static void render_line(int n, int x0,int x1,int y0,int y1,float *d){
+  int dy=y1-y0;
+  int adx=x1-x0;
+  int ady=abs(dy);
+  int base=dy/adx;
+  int sy=(dy<0?base-1:base+1);
+  int x=x0;
+  int y=y0;
+  int err=0;
+
+  ady-=abs(base*adx);
+
+  if(n>x1)n=x1;
+
+  if(x<n)
+    d[x]*=FLOOR1_fromdB_LOOKUP[y];
+
+  while(++x<n){
+    err=err+ady;
+    if(err>=adx){
+      err-=adx;
+      y+=sy;
+    }else{
+      y+=base;
+    }
+    d[x]*=FLOOR1_fromdB_LOOKUP[y];
+  }
+}
+
+static void render_line0(int n, int x0,int x1,int y0,int y1,int *d){
+  int dy=y1-y0;
+  int adx=x1-x0;
+  int ady=abs(dy);
+  int base=dy/adx;
+  int sy=(dy<0?base-1:base+1);
+  int x=x0;
+  int y=y0;
+  int err=0;
+
+  ady-=abs(base*adx);
+
+  if(n>x1)n=x1;
+
+  if(x<n)
+    d[x]=y;
+
+  while(++x<n){
+    err=err+ady;
+    if(err>=adx){
+      err-=adx;
+      y+=sy;
+    }else{
+      y+=base;
+    }
+    d[x]=y;
+  }
+}
+
+/* the floor has already been filtered to only include relevant sections */
+static int accumulate_fit(const float *flr,const float *mdct,
+                          int x0, int x1,lsfit_acc *a,
+                          int n,vorbis_info_floor1 *info){
+  long i;
+
+  int xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
+
+  memset(a,0,sizeof(*a));
+  a->x0=x0;
+  a->x1=x1;
+  if(x1>=n)x1=n-1;
+
+  for(i=x0;i<=x1;i++){
+    int quantized=vorbis_dBquant(flr+i);
+    if(quantized){
+      if(mdct[i]+info->twofitatten>=flr[i]){
+        xa  += i;
+        ya  += quantized;
+        x2a += i*i;
+        y2a += quantized*quantized;
+        xya += i*quantized;
+        na++;
+      }else{
+        xb  += i;
+        yb  += quantized;
+        x2b += i*i;
+        y2b += quantized*quantized;
+        xyb += i*quantized;
+        nb++;
+      }
+    }
+  }
+
+  a->xa=xa;
+  a->ya=ya;
+  a->x2a=x2a;
+  a->y2a=y2a;
+  a->xya=xya;
+  a->an=na;
+
+  a->xb=xb;
+  a->yb=yb;
+  a->x2b=x2b;
+  a->y2b=y2b;
+  a->xyb=xyb;
+  a->bn=nb;
+
+  return(na);
+}
+
+static int fit_line(lsfit_acc *a,int fits,int *y0,int *y1,
+                    vorbis_info_floor1 *info){
+  double xb=0,yb=0,x2b=0,y2b=0,xyb=0,bn=0;
+  int i;
+  int x0=a[0].x0;
+  int x1=a[fits-1].x1;
+
+  for(i=0;i<fits;i++){
+    double weight = (a[i].bn+a[i].an)*info->twofitweight/(a[i].an+1)+1.;
+
+    xb+=a[i].xb + a[i].xa * weight;
+    yb+=a[i].yb + a[i].ya * weight;
+    x2b+=a[i].x2b + a[i].x2a * weight;
+    y2b+=a[i].y2b + a[i].y2a * weight;
+    xyb+=a[i].xyb + a[i].xya * weight;
+    bn+=a[i].bn + a[i].an * weight;
+  }
+
+  if(*y0>=0){
+    xb+=   x0;
+    yb+=  *y0;
+    x2b+=  x0 *  x0;
+    y2b+= *y0 * *y0;
+    xyb+= *y0 *  x0;
+    bn++;
+  }
+
+  if(*y1>=0){
+    xb+=   x1;
+    yb+=  *y1;
+    x2b+=  x1 *  x1;
+    y2b+= *y1 * *y1;
+    xyb+= *y1 *  x1;
+    bn++;
+  }
+
+  {
+    double denom=(bn*x2b-xb*xb);
+
+    if(denom>0.){
+      double a=(yb*x2b-xyb*xb)/denom;
+      double b=(bn*xyb-xb*yb)/denom;
+      *y0=rint(a+b*x0);
+      *y1=rint(a+b*x1);
+
+      /* limit to our range! */
+      if(*y0>1023)*y0=1023;
+      if(*y1>1023)*y1=1023;
+      if(*y0<0)*y0=0;
+      if(*y1<0)*y1=0;
+
+      return 0;
+    }else{
+      *y0=0;
+      *y1=0;
+      return 1;
+    }
+  }
+}
+
+static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
+                         const float *mdct,
+                         vorbis_info_floor1 *info){
+  int dy=y1-y0;
+  int adx=x1-x0;
+  int ady=abs(dy);
+  int base=dy/adx;
+  int sy=(dy<0?base-1:base+1);
+  int x=x0;
+  int y=y0;
+  int err=0;
+  int val=vorbis_dBquant(mask+x);
+  int mse=0;
+  int n=0;
+
+  ady-=abs(base*adx);
+
+  mse=(y-val);
+  mse*=mse;
+  n++;
+  if(mdct[x]+info->twofitatten>=mask[x]){
+    if(y+info->maxover<val)return(1);
+    if(y-info->maxunder>val)return(1);
+  }
+
+  while(++x<x1){
+    err=err+ady;
+    if(err>=adx){
+      err-=adx;
+      y+=sy;
+    }else{
+      y+=base;
+    }
+
+    val=vorbis_dBquant(mask+x);
+    mse+=((y-val)*(y-val));
+    n++;
+    if(mdct[x]+info->twofitatten>=mask[x]){
+      if(val){
+        if(y+info->maxover<val)return(1);
+        if(y-info->maxunder>val)return(1);
+      }
+    }
+  }
+
+  if(info->maxover*info->maxover/n>info->maxerr)return(0);
+  if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
+  if(mse/n>info->maxerr)return(1);
+  return(0);
+}
+
+static int post_Y(int *A,int *B,int pos){
+  if(A[pos]<0)
+    return B[pos];
+  if(B[pos]<0)
+    return A[pos];
+
+  return (A[pos]+B[pos])>>1;
+}
+
+int *floor1_fit(vorbis_block *vb,vorbis_look_floor1 *look,
+                          const float *logmdct,   /* in */
+                          const float *logmask){
+  long i,j;
+  vorbis_info_floor1 *info=look->vi;
+  long n=look->n;
+  long posts=look->posts;
+  long nonzero=0;
+  lsfit_acc fits[VIF_POSIT+1];
+  int fit_valueA[VIF_POSIT+2]; /* index by range list position */
+  int fit_valueB[VIF_POSIT+2]; /* index by range list position */
+
+  int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
+  int hineighbor[VIF_POSIT+2];
+  int *output=NULL;
+  int memo[VIF_POSIT+2];
+
+  for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
+  for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
+  for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
+  for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
+  for(i=0;i<posts;i++)memo[i]=-1;      /* no neighbor yet */
+
+  /* quantize the relevant floor points and collect them into line fit
+     structures (one per minimal division) at the same time */
+  if(posts==0){
+    nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
+  }else{
+    for(i=0;i<posts-1;i++)
+      nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
+                              look->sorted_index[i+1],fits+i,
+                              n,info);
+  }
+
+  if(nonzero){
+    /* start by fitting the implicit base case.... */
+    int y0=-200;
+    int y1=-200;
+    fit_line(fits,posts-1,&y0,&y1,info);
+
+    fit_valueA[0]=y0;
+    fit_valueB[0]=y0;
+    fit_valueB[1]=y1;
+    fit_valueA[1]=y1;
+
+    /* Non degenerate case */
+    /* start progressive splitting.  This is a greedy, non-optimal
+       algorithm, but simple and close enough to the best
+       answer. */
+    for(i=2;i<posts;i++){
+      int sortpos=look->reverse_index[i];
+      int ln=loneighbor[sortpos];
+      int hn=hineighbor[sortpos];
+
+      /* eliminate repeat searches of a particular range with a memo */
+      if(memo[ln]!=hn){
+        /* haven't performed this error search yet */
+        int lsortpos=look->reverse_index[ln];
+        int hsortpos=look->reverse_index[hn];
+        memo[ln]=hn;
+
+        {
+          /* A note: we want to bound/minimize *local*, not global, error */
+          int lx=info->postlist[ln];
+          int hx=info->postlist[hn];
+          int ly=post_Y(fit_valueA,fit_valueB,ln);
+          int hy=post_Y(fit_valueA,fit_valueB,hn);
+
+          if(ly==-1 || hy==-1){
+            exit(1);
+          }
+
+          if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
+            /* outside error bounds/begin search area.  Split it. */
+            int ly0=-200;
+            int ly1=-200;
+            int hy0=-200;
+            int hy1=-200;
+            int ret0=fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1,info);
+            int ret1=fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1,info);
+
+            if(ret0){
+              ly0=ly;
+              ly1=hy0;
+            }
+            if(ret1){
+              hy0=ly1;
+              hy1=hy;
+            }
+
+            if(ret0 && ret1){
+              fit_valueA[i]=-200;
+              fit_valueB[i]=-200;
+            }else{
+              /* store new edge values */
+              fit_valueB[ln]=ly0;
+              if(ln==0)fit_valueA[ln]=ly0;
+              fit_valueA[i]=ly1;
+              fit_valueB[i]=hy0;
+              fit_valueA[hn]=hy1;
+              if(hn==1)fit_valueB[hn]=hy1;
+
+              if(ly1>=0 || hy0>=0){
+                /* store new neighbor values */
+                for(j=sortpos-1;j>=0;j--)
+                  if(hineighbor[j]==hn)
+                    hineighbor[j]=i;
+                  else
+                    break;
+                for(j=sortpos+1;j<posts;j++)
+                  if(loneighbor[j]==ln)
+                    loneighbor[j]=i;
+                  else
+                    break;
+              }
+            }
+          }else{
+            fit_valueA[i]=-200;
+            fit_valueB[i]=-200;
+          }
+        }
+      }
+    }
+
+    output=_vorbis_block_alloc(vb,sizeof(*output)*posts);
+
+    output[0]=post_Y(fit_valueA,fit_valueB,0);
+    output[1]=post_Y(fit_valueA,fit_valueB,1);
+
+    /* fill in posts marked as not using a fit; we will zero
+       back out to 'unused' when encoding them so long as curve
+       interpolation doesn't force them into use */
+    for(i=2;i<posts;i++){
+      int ln=look->loneighbor[i-2];
+      int hn=look->hineighbor[i-2];
+      int x0=info->postlist[ln];
+      int x1=info->postlist[hn];
+      int y0=output[ln];
+      int y1=output[hn];
+
+      int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
+      int vx=post_Y(fit_valueA,fit_valueB,i);
+
+      if(vx>=0 && predicted!=vx){
+        output[i]=vx;
+      }else{
+        output[i]= predicted|0x8000;
+      }
+    }
+  }
+
+  return(output);
+
+}
+
+int *floor1_interpolate_fit(vorbis_block *vb,vorbis_look_floor1 *look,
+                          int *A,int *B,
+                          int del){
+
+  long i;
+  long posts=look->posts;
+  int *output=NULL;
+
+  if(A && B){
+    output=_vorbis_block_alloc(vb,sizeof(*output)*posts);
+
+    /* overly simpleminded--- look again post 1.2 */
+    for(i=0;i<posts;i++){
+      output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
+      if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
+    }
+  }
+
+  return(output);
+}
+
+
+int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
+                  vorbis_look_floor1 *look,
+                  int *post,int *ilogmask){
+
+  long i,j;
+  vorbis_info_floor1 *info=look->vi;
+  long posts=look->posts;
+  codec_setup_info *ci=vb->vd->vi->codec_setup;
+  int out[VIF_POSIT+2];
+  static_codebook **sbooks=ci->book_param;
+  codebook *books=ci->fullbooks;
+
+  /* quantize values to multiplier spec */
+  if(post){
+    for(i=0;i<posts;i++){
+      int val=post[i]&0x7fff;
+      switch(info->mult){
+      case 1: /* 1024 -> 256 */
+        val>>=2;
+        break;
+      case 2: /* 1024 -> 128 */
+        val>>=3;
+        break;
+      case 3: /* 1024 -> 86 */
+        val/=12;
+        break;
+      case 4: /* 1024 -> 64 */
+        val>>=4;
+        break;
+      }
+      post[i]=val | (post[i]&0x8000);
+    }
+
+    out[0]=post[0];
+    out[1]=post[1];
+
+    /* find prediction values for each post and subtract them */
+    for(i=2;i<posts;i++){
+      int ln=look->loneighbor[i-2];
+      int hn=look->hineighbor[i-2];
+      int x0=info->postlist[ln];
+      int x1=info->postlist[hn];
+      int y0=post[ln];
+      int y1=post[hn];
+
+      int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
+
+      if((post[i]&0x8000) || (predicted==post[i])){
+        post[i]=predicted|0x8000; /* in case there was roundoff jitter
+                                     in interpolation */
+        out[i]=0;
+      }else{
+        int headroom=(look->quant_q-predicted<predicted?
+                      look->quant_q-predicted:predicted);
+
+        int val=post[i]-predicted;
+
+        /* at this point the 'deviation' value is in the range +/- max
+           range, but the real, unique range can always be mapped to
+           only [0-maxrange).  So we want to wrap the deviation into
+           this limited range, but do it in the way that least screws
+           an essentially gaussian probability distribution. */
+
+        if(val<0)
+          if(val<-headroom)
+            val=headroom-val-1;
+          else
+            val=-1-(val<<1);
+        else
+          if(val>=headroom)
+            val= val+headroom;
+          else
+            val<<=1;
+
+        out[i]=val;
+        post[ln]&=0x7fff;
+        post[hn]&=0x7fff;
+      }
+    }
+
+    /* we have everything we need. pack it out */
+    /* mark nontrivial floor */
+    oggpack_write(opb,1,1);
+
+    /* beginning/end post */
+    look->frames++;
+    look->postbits+=ov_ilog(look->quant_q-1)*2;
+    oggpack_write(opb,out[0],ov_ilog(look->quant_q-1));
+    oggpack_write(opb,out[1],ov_ilog(look->quant_q-1));
+
+
+    /* partition by partition */
+    for(i=0,j=2;i<info->partitions;i++){
+      int class=info->partitionclass[i];
+      int cdim=info->class_dim[class];
+      int csubbits=info->class_subs[class];
+      int csub=1<<csubbits;
+      int bookas[8]={0,0,0,0,0,0,0,0};
+      int cval=0;
+      int cshift=0;
+      int k,l;
+
+      /* generate the partition's first stage cascade value */
+      if(csubbits){
+        int maxval[8]={0,0,0,0,0,0,0,0}; /* gcc's static analysis
+                                            issues a warning without
+                                            initialization */
+        for(k=0;k<csub;k++){
+          int booknum=info->class_subbook[class][k];
+          if(booknum<0){
+            maxval[k]=1;
+          }else{
+            maxval[k]=sbooks[info->class_subbook[class][k]]->entries;
+          }
+        }
+        for(k=0;k<cdim;k++){
+          for(l=0;l<csub;l++){
+            int val=out[j+k];
+            if(val<maxval[l]){
+              bookas[k]=l;
+              break;
+            }
+          }
+          cval|= bookas[k]<<cshift;
+          cshift+=csubbits;
+        }
+        /* write it */
+        look->phrasebits+=
+          vorbis_book_encode(books+info->class_book[class],cval,opb);
+
+#ifdef TRAIN_FLOOR1
+        {
+          FILE *of;
+          char buffer[80];
+          sprintf(buffer,"line_%dx%ld_class%d.vqd",
+                  vb->pcmend/2,posts-2,class);
+          of=fopen(buffer,"a");
+          fprintf(of,"%d\n",cval);
+          fclose(of);
+        }
+#endif
+      }
+
+      /* write post values */
+      for(k=0;k<cdim;k++){
+        int book=info->class_subbook[class][bookas[k]];
+        if(book>=0){
+          /* hack to allow training with 'bad' books */
+          if(out[j+k]<(books+book)->entries)
+            look->postbits+=vorbis_book_encode(books+book,
+                                               out[j+k],opb);
+          /*else
+            fprintf(stderr,"+!");*/
+
+#ifdef TRAIN_FLOOR1
+          {
+            FILE *of;
+            char buffer[80];
+            sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
+                    vb->pcmend/2,posts-2,class,bookas[k]);
+            of=fopen(buffer,"a");
+            fprintf(of,"%d\n",out[j+k]);
+            fclose(of);
+          }
+#endif
+        }
+      }
+      j+=cdim;
+    }
+
+    {
+      /* generate quantized floor equivalent to what we'd unpack in decode */
+      /* render the lines */
+      int hx=0;
+      int lx=0;
+      int ly=post[0]*info->mult;
+      int n=ci->blocksizes[vb->W]/2;
+
+      for(j=1;j<look->posts;j++){
+        int current=look->forward_index[j];
+        int hy=post[current]&0x7fff;
+        if(hy==post[current]){
+
+          hy*=info->mult;
+          hx=info->postlist[current];
+
+          render_line0(n,lx,hx,ly,hy,ilogmask);
+
+          lx=hx;
+          ly=hy;
+        }
+      }
+      for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
+      return(1);
+    }
+  }else{
+    oggpack_write(opb,0,1);
+    memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
+    return(0);
+  }
+}
+
+static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
+  vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
+  vorbis_info_floor1 *info=look->vi;
+  codec_setup_info   *ci=vb->vd->vi->codec_setup;
+
+  int i,j,k;
+  codebook *books=ci->fullbooks;
+
+  /* unpack wrapped/predicted values from stream */
+  if(oggpack_read(&vb->opb,1)==1){
+    int *fit_value=_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
+
+    fit_value[0]=oggpack_read(&vb->opb,ov_ilog(look->quant_q-1));
+    fit_value[1]=oggpack_read(&vb->opb,ov_ilog(look->quant_q-1));
+
+    /* partition by partition */
+    for(i=0,j=2;i<info->partitions;i++){
+      int class=info->partitionclass[i];
+      int cdim=info->class_dim[class];
+      int csubbits=info->class_subs[class];
+      int csub=1<<csubbits;
+      int cval=0;
+
+      /* decode the partition's first stage cascade value */
+      if(csubbits){
+        cval=vorbis_book_decode(books+info->class_book[class],&vb->opb);
+
+        if(cval==-1)goto eop;
+      }
+
+      for(k=0;k<cdim;k++){
+        int book=info->class_subbook[class][cval&(csub-1)];
+        cval>>=csubbits;
+        if(book>=0){
+          if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
+            goto eop;
+        }else{
+          fit_value[j+k]=0;
+        }
+      }
+      j+=cdim;
+    }
+
+    /* unwrap positive values and reconsitute via linear interpolation */
+    for(i=2;i<look->posts;i++){
+      int predicted=render_point(info->postlist[look->loneighbor[i-2]],
+                                 info->postlist[look->hineighbor[i-2]],
+                                 fit_value[look->loneighbor[i-2]],
+                                 fit_value[look->hineighbor[i-2]],
+                                 info->postlist[i]);
+      int hiroom=look->quant_q-predicted;
+      int loroom=predicted;
+      int room=(hiroom<loroom?hiroom:loroom)<<1;
+      int val=fit_value[i];
+
+      if(val){
+        if(val>=room){
+          if(hiroom>loroom){
+            val = val-loroom;
+          }else{
+            val = -1-(val-hiroom);
+          }
+        }else{
+          if(val&1){
+            val= -((val+1)>>1);
+          }else{
+            val>>=1;
+          }
+        }
+
+        fit_value[i]=(val+predicted)&0x7fff;
+        fit_value[look->loneighbor[i-2]]&=0x7fff;
+        fit_value[look->hineighbor[i-2]]&=0x7fff;
+
+      }else{
+        fit_value[i]=predicted|0x8000;
+      }
+
+    }
+
+    return(fit_value);
+  }
+ eop:
+  return(NULL);
+}
+
+static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
+                          float *out){
+  vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
+  vorbis_info_floor1 *info=look->vi;
+
+  codec_setup_info   *ci=vb->vd->vi->codec_setup;
+  int                  n=ci->blocksizes[vb->W]/2;
+  int j;
+
+  if(memo){
+    /* render the lines */
+    int *fit_value=(int *)memo;
+    int hx=0;
+    int lx=0;
+    int ly=fit_value[0]*info->mult;
+    /* guard lookup against out-of-range values */
+    ly=(ly<0?0:ly>255?255:ly);
+
+    for(j=1;j<look->posts;j++){
+      int current=look->forward_index[j];
+      int hy=fit_value[current]&0x7fff;
+      if(hy==fit_value[current]){
+
+        hx=info->postlist[current];
+        hy*=info->mult;
+        /* guard lookup against out-of-range values */
+        hy=(hy<0?0:hy>255?255:hy);
+
+        render_line(n,lx,hx,ly,hy,out);
+
+        lx=hx;
+        ly=hy;
+      }
+    }
+    for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
+    return(1);
+  }
+  memset(out,0,sizeof(*out)*n);
+  return(0);
+}
+
+/* export hooks */
+const vorbis_func_floor floor1_exportbundle={
+  &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
+  &floor1_free_look,&floor1_inverse1,&floor1_inverse2
+};
diff --git a/vorbis/lib/highlevel.h b/vorbis/lib/highlevel.h
new file mode 100644 (file)
index 0000000..337b75b
--- /dev/null
@@ -0,0 +1,57 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: highlevel encoder setup struct separated out for vorbisenc clarity
+
+ ********************************************************************/
+
+typedef struct highlevel_byblocktype {
+  double tone_mask_setting;
+  double tone_peaklimit_setting;
+  double noise_bias_setting;
+  double noise_compand_setting;
+} highlevel_byblocktype;
+
+typedef struct highlevel_encode_setup {
+  int   set_in_stone;
+  const void *setup;
+  double base_setting;
+
+  double impulse_noisetune;
+
+  /* bitrate management below all settable */
+  float  req;
+  int    managed;
+  long   bitrate_min;
+  long   bitrate_av;
+  double bitrate_av_damp;
+  long   bitrate_max;
+  long   bitrate_reservoir;
+  double bitrate_reservoir_bias;
+
+  int impulse_block_p;
+  int noise_normalize_p;
+  int coupling_p;
+
+  double stereo_point_setting;
+  double lowpass_kHz;
+  int    lowpass_altered;
+
+  double ath_floating_dB;
+  double ath_absolute_dB;
+
+  double amplitude_track_dBpersec;
+  double trigger_setting;
+
+  highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
+
+} highlevel_encode_setup;
diff --git a/vorbis/lib/info.c b/vorbis/lib/info.c
new file mode 100644 (file)
index 0000000..3fbb7c7
--- /dev/null
@@ -0,0 +1,679 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: maintain the info structure, info <-> header packets
+
+ ********************************************************************/
+
+/* general handling of the header and the vorbis_info structure (and
+   substructures) */
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "codebook.h"
+#include "registry.h"
+#include "window.h"
+#include "psy.h"
+#include "misc.h"
+#include "os.h"
+
+#define GENERAL_VENDOR_STRING "Xiph.Org libVorbis 1.3.6"
+#define ENCODE_VENDOR_STRING "Xiph.Org libVorbis I 20180316 (Now 100% fewer shells)"
+
+/* helpers */
+static void _v_writestring(oggpack_buffer *o,const char *s, int bytes){
+
+  while(bytes--){
+    oggpack_write(o,*s++,8);
+  }
+}
+
+static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
+  while(bytes--){
+    *buf++=oggpack_read(o,8);
+  }
+}
+
+void vorbis_comment_init(vorbis_comment *vc){
+  memset(vc,0,sizeof(*vc));
+}
+
+void vorbis_comment_add(vorbis_comment *vc,const char *comment){
+  vc->user_comments=_ogg_realloc(vc->user_comments,
+                            (vc->comments+2)*sizeof(*vc->user_comments));
+  vc->comment_lengths=_ogg_realloc(vc->comment_lengths,
+                                  (vc->comments+2)*sizeof(*vc->comment_lengths));
+  vc->comment_lengths[vc->comments]=strlen(comment);
+  vc->user_comments[vc->comments]=_ogg_malloc(vc->comment_lengths[vc->comments]+1);
+  strcpy(vc->user_comments[vc->comments], comment);
+  vc->comments++;
+  vc->user_comments[vc->comments]=NULL;
+}
+
+void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, const char *contents){
+  /* Length for key and value +2 for = and \0 */
+  char *comment=_ogg_malloc(strlen(tag)+strlen(contents)+2);
+  strcpy(comment, tag);
+  strcat(comment, "=");
+  strcat(comment, contents);
+  vorbis_comment_add(vc, comment);
+  _ogg_free(comment);
+}
+
+/* This is more or less the same as strncasecmp - but that doesn't exist
+ * everywhere, and this is a fairly trivial function, so we include it */
+static int tagcompare(const char *s1, const char *s2, int n){
+  int c=0;
+  while(c < n){
+    if(toupper(s1[c]) != toupper(s2[c]))
+      return !0;
+    c++;
+  }
+  return 0;
+}
+
+char *vorbis_comment_query(vorbis_comment *vc, const char *tag, int count){
+  long i;
+  int found = 0;
+  int taglen = strlen(tag)+1; /* +1 for the = we append */
+  char *fulltag = _ogg_malloc(taglen+1);
+
+  strcpy(fulltag, tag);
+  strcat(fulltag, "=");
+
+  for(i=0;i<vc->comments;i++){
+    if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
+      if(count == found) {
+        /* We return a pointer to the data, not a copy */
+        _ogg_free(fulltag);
+        return vc->user_comments[i] + taglen;
+      } else {
+        found++;
+      }
+    }
+  }
+  _ogg_free(fulltag);
+  return NULL; /* didn't find anything */
+}
+
+int vorbis_comment_query_count(vorbis_comment *vc, const char *tag){
+  int i,count=0;
+  int taglen = strlen(tag)+1; /* +1 for the = we append */
+  char *fulltag = _ogg_malloc(taglen+1);
+  strcpy(fulltag,tag);
+  strcat(fulltag, "=");
+
+  for(i=0;i<vc->comments;i++){
+    if(!tagcompare(vc->user_comments[i], fulltag, taglen))
+      count++;
+  }
+
+  _ogg_free(fulltag);
+  return count;
+}
+
+void vorbis_comment_clear(vorbis_comment *vc){
+  if(vc){
+    long i;
+    if(vc->user_comments){
+      for(i=0;i<vc->comments;i++)
+        if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
+      _ogg_free(vc->user_comments);
+    }
+    if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
+    if(vc->vendor)_ogg_free(vc->vendor);
+    memset(vc,0,sizeof(*vc));
+  }
+}
+
+/* blocksize 0 is guaranteed to be short, 1 is guaranteed to be long.
+   They may be equal, but short will never ge greater than long */
+int vorbis_info_blocksize(vorbis_info *vi,int zo){
+  codec_setup_info *ci = vi->codec_setup;
+  return ci ? ci->blocksizes[zo] : -1;
+}
+
+/* used by synthesis, which has a full, alloced vi */
+void vorbis_info_init(vorbis_info *vi){
+  memset(vi,0,sizeof(*vi));
+  vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
+}
+
+void vorbis_info_clear(vorbis_info *vi){
+  codec_setup_info     *ci=vi->codec_setup;
+  int i;
+
+  if(ci){
+
+    for(i=0;i<ci->modes;i++)
+      if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
+
+    for(i=0;i<ci->maps;i++) /* unpack does the range checking */
+      if(ci->map_param[i]) /* this may be cleaning up an aborted
+                              unpack, in which case the below type
+                              cannot be trusted */
+        _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
+
+    for(i=0;i<ci->floors;i++) /* unpack does the range checking */
+      if(ci->floor_param[i]) /* this may be cleaning up an aborted
+                                unpack, in which case the below type
+                                cannot be trusted */
+        _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
+
+    for(i=0;i<ci->residues;i++) /* unpack does the range checking */
+      if(ci->residue_param[i]) /* this may be cleaning up an aborted
+                                  unpack, in which case the below type
+                                  cannot be trusted */
+        _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
+
+    for(i=0;i<ci->books;i++){
+      if(ci->book_param[i]){
+        /* knows if the book was not alloced */
+        vorbis_staticbook_destroy(ci->book_param[i]);
+      }
+      if(ci->fullbooks)
+        vorbis_book_clear(ci->fullbooks+i);
+    }
+    if(ci->fullbooks)
+        _ogg_free(ci->fullbooks);
+
+    for(i=0;i<ci->psys;i++)
+      _vi_psy_free(ci->psy_param[i]);
+
+    _ogg_free(ci);
+  }
+
+  memset(vi,0,sizeof(*vi));
+}
+
+/* Header packing/unpacking ********************************************/
+
+static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
+  codec_setup_info     *ci=vi->codec_setup;
+  if(!ci)return(OV_EFAULT);
+
+  vi->version=oggpack_read(opb,32);
+  if(vi->version!=0)return(OV_EVERSION);
+
+  vi->channels=oggpack_read(opb,8);
+  vi->rate=oggpack_read(opb,32);
+
+  vi->bitrate_upper=(ogg_int32_t)oggpack_read(opb,32);
+  vi->bitrate_nominal=(ogg_int32_t)oggpack_read(opb,32);
+  vi->bitrate_lower=(ogg_int32_t)oggpack_read(opb,32);
+
+  ci->blocksizes[0]=1<<oggpack_read(opb,4);
+  ci->blocksizes[1]=1<<oggpack_read(opb,4);
+
+  if(vi->rate<1)goto err_out;
+  if(vi->channels<1)goto err_out;
+  if(ci->blocksizes[0]<64)goto err_out;
+  if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
+  if(ci->blocksizes[1]>8192)goto err_out;
+
+  if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
+
+  return(0);
+ err_out:
+  vorbis_info_clear(vi);
+  return(OV_EBADHEADER);
+}
+
+static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
+  int i;
+  int vendorlen=oggpack_read(opb,32);
+  if(vendorlen<0)goto err_out;
+  if(vendorlen>opb->storage-8)goto err_out;
+  vc->vendor=_ogg_calloc(vendorlen+1,1);
+  _v_readstring(opb,vc->vendor,vendorlen);
+  i=oggpack_read(opb,32);
+  if(i<0)goto err_out;
+  if(i>((opb->storage-oggpack_bytes(opb))>>2))goto err_out;
+  vc->comments=i;
+  vc->user_comments=_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
+  vc->comment_lengths=_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
+
+  for(i=0;i<vc->comments;i++){
+    int len=oggpack_read(opb,32);
+    if(len<0)goto err_out;
+    if(len>opb->storage-oggpack_bytes(opb))goto err_out;
+    vc->comment_lengths[i]=len;
+    vc->user_comments[i]=_ogg_calloc(len+1,1);
+    _v_readstring(opb,vc->user_comments[i],len);
+  }
+  if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
+
+  return(0);
+ err_out:
+  vorbis_comment_clear(vc);
+  return(OV_EBADHEADER);
+}
+
+/* all of the real encoding details are here.  The modes, books,
+   everything */
+static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
+  codec_setup_info     *ci=vi->codec_setup;
+  int i;
+
+  /* codebooks */
+  ci->books=oggpack_read(opb,8)+1;
+  if(ci->books<=0)goto err_out;
+  for(i=0;i<ci->books;i++){
+    ci->book_param[i]=vorbis_staticbook_unpack(opb);
+    if(!ci->book_param[i])goto err_out;
+  }
+
+  /* time backend settings; hooks are unused */
+  {
+    int times=oggpack_read(opb,6)+1;
+    if(times<=0)goto err_out;
+    for(i=0;i<times;i++){
+      int test=oggpack_read(opb,16);
+      if(test<0 || test>=VI_TIMEB)goto err_out;
+    }
+  }
+
+  /* floor backend settings */
+  ci->floors=oggpack_read(opb,6)+1;
+  if(ci->floors<=0)goto err_out;
+  for(i=0;i<ci->floors;i++){
+    ci->floor_type[i]=oggpack_read(opb,16);
+    if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
+    ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
+    if(!ci->floor_param[i])goto err_out;
+  }
+
+  /* residue backend settings */
+  ci->residues=oggpack_read(opb,6)+1;
+  if(ci->residues<=0)goto err_out;
+  for(i=0;i<ci->residues;i++){
+    ci->residue_type[i]=oggpack_read(opb,16);
+    if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
+    ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
+    if(!ci->residue_param[i])goto err_out;
+  }
+
+  /* map backend settings */
+  ci->maps=oggpack_read(opb,6)+1;
+  if(ci->maps<=0)goto err_out;
+  for(i=0;i<ci->maps;i++){
+    ci->map_type[i]=oggpack_read(opb,16);
+    if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
+    ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
+    if(!ci->map_param[i])goto err_out;
+  }
+
+  /* mode settings */
+  ci->modes=oggpack_read(opb,6)+1;
+  if(ci->modes<=0)goto err_out;
+  for(i=0;i<ci->modes;i++){
+    ci->mode_param[i]=_ogg_calloc(1,sizeof(*ci->mode_param[i]));
+    ci->mode_param[i]->blockflag=oggpack_read(opb,1);
+    ci->mode_param[i]->windowtype=oggpack_read(opb,16);
+    ci->mode_param[i]->transformtype=oggpack_read(opb,16);
+    ci->mode_param[i]->mapping=oggpack_read(opb,8);
+
+    if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
+    if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
+    if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
+    if(ci->mode_param[i]->mapping<0)goto err_out;
+  }
+
+  if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
+
+  return(0);
+ err_out:
+  vorbis_info_clear(vi);
+  return(OV_EBADHEADER);
+}
+
+/* Is this packet a vorbis ID header? */
+int vorbis_synthesis_idheader(ogg_packet *op){
+  oggpack_buffer opb;
+  char buffer[6];
+
+  if(op){
+    oggpack_readinit(&opb,op->packet,op->bytes);
+
+    if(!op->b_o_s)
+      return(0); /* Not the initial packet */
+
+    if(oggpack_read(&opb,8) != 1)
+      return 0; /* not an ID header */
+
+    memset(buffer,0,6);
+    _v_readstring(&opb,buffer,6);
+    if(memcmp(buffer,"vorbis",6))
+      return 0; /* not vorbis */
+
+    return 1;
+  }
+
+  return 0;
+}
+
+/* The Vorbis header is in three packets; the initial small packet in
+   the first page that identifies basic parameters, a second packet
+   with bitstream comments and a third packet that holds the
+   codebook. */
+
+int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
+  oggpack_buffer opb;
+
+  if(op){
+    oggpack_readinit(&opb,op->packet,op->bytes);
+
+    /* Which of the three types of header is this? */
+    /* Also verify header-ness, vorbis */
+    {
+      char buffer[6];
+      int packtype=oggpack_read(&opb,8);
+      memset(buffer,0,6);
+      _v_readstring(&opb,buffer,6);
+      if(memcmp(buffer,"vorbis",6)){
+        /* not a vorbis header */
+        return(OV_ENOTVORBIS);
+      }
+      switch(packtype){
+      case 0x01: /* least significant *bit* is read first */
+        if(!op->b_o_s){
+          /* Not the initial packet */
+          return(OV_EBADHEADER);
+        }
+        if(vi->rate!=0){
+          /* previously initialized info header */
+          return(OV_EBADHEADER);
+        }
+
+        return(_vorbis_unpack_info(vi,&opb));
+
+      case 0x03: /* least significant *bit* is read first */
+        if(vi->rate==0){
+          /* um... we didn't get the initial header */
+          return(OV_EBADHEADER);
+        }
+        if(vc->vendor!=NULL){
+          /* previously initialized comment header */
+          return(OV_EBADHEADER);
+        }
+
+        return(_vorbis_unpack_comment(vc,&opb));
+
+      case 0x05: /* least significant *bit* is read first */
+        if(vi->rate==0 || vc->vendor==NULL){
+          /* um... we didn;t get the initial header or comments yet */
+          return(OV_EBADHEADER);
+        }
+        if(vi->codec_setup==NULL){
+          /* improperly initialized vorbis_info */
+          return(OV_EFAULT);
+        }
+        if(((codec_setup_info *)vi->codec_setup)->books>0){
+          /* previously initialized setup header */
+          return(OV_EBADHEADER);
+        }
+
+        return(_vorbis_unpack_books(vi,&opb));
+
+      default:
+        /* Not a valid vorbis header type */
+        return(OV_EBADHEADER);
+        break;
+      }
+    }
+  }
+  return(OV_EBADHEADER);
+}
+
+/* pack side **********************************************************/
+
+static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
+  codec_setup_info     *ci=vi->codec_setup;
+  if(!ci||
+     ci->blocksizes[0]<64||
+     ci->blocksizes[1]<ci->blocksizes[0]){
+    return(OV_EFAULT);
+  }
+
+  /* preamble */
+  oggpack_write(opb,0x01,8);
+  _v_writestring(opb,"vorbis", 6);
+
+  /* basic information about the stream */
+  oggpack_write(opb,0x00,32);
+  oggpack_write(opb,vi->channels,8);
+  oggpack_write(opb,vi->rate,32);
+
+  oggpack_write(opb,vi->bitrate_upper,32);
+  oggpack_write(opb,vi->bitrate_nominal,32);
+  oggpack_write(opb,vi->bitrate_lower,32);
+
+  oggpack_write(opb,ov_ilog(ci->blocksizes[0]-1),4);
+  oggpack_write(opb,ov_ilog(ci->blocksizes[1]-1),4);
+  oggpack_write(opb,1,1);
+
+  return(0);
+}
+
+static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
+  int bytes = strlen(ENCODE_VENDOR_STRING);
+
+  /* preamble */
+  oggpack_write(opb,0x03,8);
+  _v_writestring(opb,"vorbis", 6);
+
+  /* vendor */
+  oggpack_write(opb,bytes,32);
+  _v_writestring(opb,ENCODE_VENDOR_STRING, bytes);
+
+  /* comments */
+
+  oggpack_write(opb,vc->comments,32);
+  if(vc->comments){
+    int i;
+    for(i=0;i<vc->comments;i++){
+      if(vc->user_comments[i]){
+        oggpack_write(opb,vc->comment_lengths[i],32);
+        _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
+      }else{
+        oggpack_write(opb,0,32);
+      }
+    }
+  }
+  oggpack_write(opb,1,1);
+
+  return(0);
+}
+
+static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
+  codec_setup_info     *ci=vi->codec_setup;
+  int i;
+  if(!ci)return(OV_EFAULT);
+
+  oggpack_write(opb,0x05,8);
+  _v_writestring(opb,"vorbis", 6);
+
+  /* books */
+  oggpack_write(opb,ci->books-1,8);
+  for(i=0;i<ci->books;i++)
+    if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
+
+  /* times; hook placeholders */
+  oggpack_write(opb,0,6);
+  oggpack_write(opb,0,16);
+
+  /* floors */
+  oggpack_write(opb,ci->floors-1,6);
+  for(i=0;i<ci->floors;i++){
+    oggpack_write(opb,ci->floor_type[i],16);
+    if(_floor_P[ci->floor_type[i]]->pack)
+      _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
+    else
+      goto err_out;
+  }
+
+  /* residues */
+  oggpack_write(opb,ci->residues-1,6);
+  for(i=0;i<ci->residues;i++){
+    oggpack_write(opb,ci->residue_type[i],16);
+    _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
+  }
+
+  /* maps */
+  oggpack_write(opb,ci->maps-1,6);
+  for(i=0;i<ci->maps;i++){
+    oggpack_write(opb,ci->map_type[i],16);
+    _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
+  }
+
+  /* modes */
+  oggpack_write(opb,ci->modes-1,6);
+  for(i=0;i<ci->modes;i++){
+    oggpack_write(opb,ci->mode_param[i]->blockflag,1);
+    oggpack_write(opb,ci->mode_param[i]->windowtype,16);
+    oggpack_write(opb,ci->mode_param[i]->transformtype,16);
+    oggpack_write(opb,ci->mode_param[i]->mapping,8);
+  }
+  oggpack_write(opb,1,1);
+
+  return(0);
+err_out:
+  return(-1);
+}
+
+int vorbis_commentheader_out(vorbis_comment *vc,
+                                          ogg_packet *op){
+
+  oggpack_buffer opb;
+
+  oggpack_writeinit(&opb);
+  if(_vorbis_pack_comment(&opb,vc)){
+    oggpack_writeclear(&opb);
+    return OV_EIMPL;
+  }
+
+  op->packet = _ogg_malloc(oggpack_bytes(&opb));
+  memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
+
+  op->bytes=oggpack_bytes(&opb);
+  op->b_o_s=0;
+  op->e_o_s=0;
+  op->granulepos=0;
+  op->packetno=1;
+
+  oggpack_writeclear(&opb);
+  return 0;
+}
+
+int vorbis_analysis_headerout(vorbis_dsp_state *v,
+                              vorbis_comment *vc,
+                              ogg_packet *op,
+                              ogg_packet *op_comm,
+                              ogg_packet *op_code){
+  int ret=OV_EIMPL;
+  vorbis_info *vi=v->vi;
+  oggpack_buffer opb;
+  private_state *b=v->backend_state;
+
+  if(!b||vi->channels<=0||vi->channels>256){
+    b = NULL;
+    ret=OV_EFAULT;
+    goto err_out;
+  }
+
+  /* first header packet **********************************************/
+
+  oggpack_writeinit(&opb);
+  if(_vorbis_pack_info(&opb,vi))goto err_out;
+
+  /* build the packet */
+  if(b->header)_ogg_free(b->header);
+  b->header=_ogg_malloc(oggpack_bytes(&opb));
+  memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
+  op->packet=b->header;
+  op->bytes=oggpack_bytes(&opb);
+  op->b_o_s=1;
+  op->e_o_s=0;
+  op->granulepos=0;
+  op->packetno=0;
+
+  /* second header packet (comments) **********************************/
+
+  oggpack_reset(&opb);
+  if(_vorbis_pack_comment(&opb,vc))goto err_out;
+
+  if(b->header1)_ogg_free(b->header1);
+  b->header1=_ogg_malloc(oggpack_bytes(&opb));
+  memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
+  op_comm->packet=b->header1;
+  op_comm->bytes=oggpack_bytes(&opb);
+  op_comm->b_o_s=0;
+  op_comm->e_o_s=0;
+  op_comm->granulepos=0;
+  op_comm->packetno=1;
+
+  /* third header packet (modes/codebooks) ****************************/
+
+  oggpack_reset(&opb);
+  if(_vorbis_pack_books(&opb,vi))goto err_out;
+
+  if(b->header2)_ogg_free(b->header2);
+  b->header2=_ogg_malloc(oggpack_bytes(&opb));
+  memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
+  op_code->packet=b->header2;
+  op_code->bytes=oggpack_bytes(&opb);
+  op_code->b_o_s=0;
+  op_code->e_o_s=0;
+  op_code->granulepos=0;
+  op_code->packetno=2;
+
+  oggpack_writeclear(&opb);
+  return(0);
+ err_out:
+  memset(op,0,sizeof(*op));
+  memset(op_comm,0,sizeof(*op_comm));
+  memset(op_code,0,sizeof(*op_code));
+
+  if(b){
+    if(vi->channels>0)oggpack_writeclear(&opb);
+    if(b->header)_ogg_free(b->header);
+    if(b->header1)_ogg_free(b->header1);
+    if(b->header2)_ogg_free(b->header2);
+    b->header=NULL;
+    b->header1=NULL;
+    b->header2=NULL;
+  }
+  return(ret);
+}
+
+double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
+  if(granulepos == -1) return -1;
+
+  /* We're not guaranteed a 64 bit unsigned type everywhere, so we
+     have to put the unsigned granpo in a signed type. */
+  if(granulepos>=0){
+    return((double)granulepos/v->vi->rate);
+  }else{
+    ogg_int64_t granuleoff=0xffffffff;
+    granuleoff<<=31;
+    granuleoff|=0x7ffffffff;
+    return(((double)granulepos+2+granuleoff+granuleoff)/v->vi->rate);
+  }
+}
+
+const char *vorbis_version_string(void){
+  return GENERAL_VENDOR_STRING;
+}
diff --git a/vorbis/lib/lookup.c b/vorbis/lib/lookup.c
new file mode 100644 (file)
index 0000000..1cc1f88
--- /dev/null
@@ -0,0 +1,93 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: lookup based functions
+
+ ********************************************************************/
+
+#include <math.h>
+#include "lookup.h"
+#include "lookup_data.h"
+#include "os.h"
+#include "misc.h"
+
+#ifdef FLOAT_LOOKUP
+
+/* interpolated lookup based cos function, domain 0 to PI only */
+float vorbis_coslook(float a){
+  double d=a*(.31830989*(float)COS_LOOKUP_SZ);
+  int i=vorbis_ftoi(d-.5);
+
+  return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
+}
+
+/* interpolated 1./sqrt(p) where .5 <= p < 1. */
+float vorbis_invsqlook(float a){
+  double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
+  int i=vorbis_ftoi(d-.5f);
+  return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
+}
+
+/* interpolated 1./sqrt(p) where .5 <= p < 1. */
+float vorbis_invsq2explook(int a){
+  return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
+}
+
+#include <stdio.h>
+/* interpolated lookup based fromdB function, domain -140dB to 0dB only */
+float vorbis_fromdBlook(float a){
+  int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
+  return (i<0)?1.f:
+    ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
+     FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
+}
+
+#endif
+
+#ifdef INT_LOOKUP
+/* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
+   16.16 format
+
+   returns in m.8 format */
+long vorbis_invsqlook_i(long a,long e){
+  long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
+  long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /*  0.16 */
+  long val=INVSQ_LOOKUP_I[i]-                                /*  1.16 */
+    (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])*               /*  0.16 */
+      d)>>16);                                               /* result 1.16 */
+
+  e+=32;
+  if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
+  e=(e>>1)-8;
+
+  return(val>>e);
+}
+
+/* interpolated lookup based fromdB function, domain -140dB to 0dB only */
+/* a is in n.12 format */
+float vorbis_fromdBlook_i(long a){
+  int i=(-a)>>(12-FROMdB2_SHIFT);
+  return (i<0)?1.f:
+    ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
+     FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
+}
+
+/* interpolated lookup based cos function, domain 0 to PI only */
+/* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
+long vorbis_coslook_i(long a){
+  int i=a>>COS_LOOKUP_I_SHIFT;
+  int d=a&COS_LOOKUP_I_MASK;
+  return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
+                           COS_LOOKUP_I_SHIFT);
+}
+
+#endif
diff --git a/vorbis/lib/lookup.h b/vorbis/lib/lookup.h
new file mode 100644 (file)
index 0000000..4bc0f3a
--- /dev/null
@@ -0,0 +1,31 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: lookup based functions
+
+ ********************************************************************/
+
+#ifndef _V_LOOKUP_H_
+
+#ifdef FLOAT_LOOKUP
+extern float vorbis_coslook(float a);
+extern float vorbis_invsqlook(float a);
+extern float vorbis_invsq2explook(int a);
+extern float vorbis_fromdBlook(float a);
+#endif
+#ifdef INT_LOOKUP
+extern long vorbis_invsqlook_i(long a,long e);
+extern long vorbis_coslook_i(long a);
+extern float vorbis_fromdBlook_i(long a);
+#endif
+
+#endif
diff --git a/vorbis/lib/lookup_data.h b/vorbis/lib/lookup_data.h
new file mode 100644 (file)
index 0000000..5de3cfd
--- /dev/null
@@ -0,0 +1,191 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: lookup data; generated by lookups.pl; edit there
+
+ ********************************************************************/
+
+#ifndef _V_LOOKUP_DATA_H_
+
+#ifdef FLOAT_LOOKUP
+#define COS_LOOKUP_SZ 128
+static const float COS_LOOKUP[COS_LOOKUP_SZ+1]={
+        +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
+        +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
+        +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
+        +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
+        +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
+        +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
+        +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
+        +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
+        +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
+        +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
+        +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
+        +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
+        +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
+        +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
+        +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
+        +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
+        +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
+        -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
+        -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
+        -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
+        -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
+        -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
+        -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
+        -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
+        -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
+        -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
+        -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
+        -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
+        -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
+        -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
+        -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
+        -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
+        -1.0000000000000f,
+};
+
+#define INVSQ_LOOKUP_SZ 32
+static const float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
+        1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
+        1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
+        1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
+        1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
+        1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
+        1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
+        1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
+        1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
+        1.000000000000f,
+};
+
+#define INVSQ2EXP_LOOKUP_MIN (-32)
+#define INVSQ2EXP_LOOKUP_MAX 32
+static const float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
+                              INVSQ2EXP_LOOKUP_MIN+1]={
+                 65536.f,    46340.95001f,         32768.f,    23170.47501f,
+                 16384.f,     11585.2375f,          8192.f,    5792.618751f,
+                  4096.f,    2896.309376f,          2048.f,    1448.154688f,
+                  1024.f,    724.0773439f,           512.f,     362.038672f,
+                   256.f,     181.019336f,           128.f,    90.50966799f,
+                    64.f,      45.254834f,            32.f,      22.627417f,
+                    16.f,     11.3137085f,             8.f,    5.656854249f,
+                     4.f,    2.828427125f,             2.f,    1.414213562f,
+                     1.f,   0.7071067812f,            0.5f,   0.3535533906f,
+                   0.25f,   0.1767766953f,          0.125f,  0.08838834765f,
+                 0.0625f,  0.04419417382f,        0.03125f,  0.02209708691f,
+               0.015625f,  0.01104854346f,      0.0078125f, 0.005524271728f,
+             0.00390625f, 0.002762135864f,    0.001953125f, 0.001381067932f,
+           0.0009765625f, 0.000690533966f,  0.00048828125f, 0.000345266983f,
+         0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
+        6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
+        1.525878906e-05f,
+};
+
+#endif
+
+#define FROMdB_LOOKUP_SZ 35
+#define FROMdB2_LOOKUP_SZ 32
+#define FROMdB_SHIFT 5
+#define FROMdB2_SHIFT 3
+#define FROMdB2_MASK 31
+
+#ifdef FLOAT_LOOKUP
+static const float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
+                     1.f,   0.6309573445f,   0.3981071706f,   0.2511886432f,
+           0.1584893192f,            0.1f,  0.06309573445f,  0.03981071706f,
+          0.02511886432f,  0.01584893192f,           0.01f, 0.006309573445f,
+         0.003981071706f, 0.002511886432f, 0.001584893192f,          0.001f,
+        0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
+                 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
+        1.584893192e-05f,          1e-05f,6.309573445e-06f,3.981071706e-06f,
+        2.511886432e-06f,1.584893192e-06f,          1e-06f,6.309573445e-07f,
+        3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
+};
+
+static const float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
+           0.9928302478f,   0.9786445908f,   0.9646616199f,   0.9508784391f,
+           0.9372921937f,     0.92390007f,   0.9106992942f,   0.8976871324f,
+           0.8848608897f,   0.8722179097f,   0.8597555737f,   0.8474713009f,
+            0.835362547f,   0.8234268041f,   0.8116616003f,   0.8000644989f,
+           0.7886330981f,   0.7773650302f,   0.7662579617f,    0.755309592f,
+           0.7445176537f,   0.7338799116f,   0.7233941627f,   0.7130582353f,
+           0.7028699885f,   0.6928273125f,   0.6829281272f,   0.6731703824f,
+           0.6635520573f,   0.6540711597f,   0.6447257262f,   0.6355138211f,
+};
+#endif
+
+#ifdef INT_LOOKUP
+
+#define INVSQ_LOOKUP_I_SHIFT 10
+#define INVSQ_LOOKUP_I_MASK 1023
+static const long INVSQ_LOOKUP_I[64+1]={
+           92682l,   91966l,   91267l,   90583l,
+           89915l,   89261l,   88621l,   87995l,
+           87381l,   86781l,   86192l,   85616l,
+           85051l,   84497l,   83953l,   83420l,
+           82897l,   82384l,   81880l,   81385l,
+           80899l,   80422l,   79953l,   79492l,
+           79039l,   78594l,   78156l,   77726l,
+           77302l,   76885l,   76475l,   76072l,
+           75674l,   75283l,   74898l,   74519l,
+           74146l,   73778l,   73415l,   73058l,
+           72706l,   72359l,   72016l,   71679l,
+           71347l,   71019l,   70695l,   70376l,
+           70061l,   69750l,   69444l,   69141l,
+           68842l,   68548l,   68256l,   67969l,
+           67685l,   67405l,   67128l,   66855l,
+           66585l,   66318l,   66054l,   65794l,
+           65536l,
+};
+
+#define COS_LOOKUP_I_SHIFT 9
+#define COS_LOOKUP_I_MASK 511
+#define COS_LOOKUP_I_SZ 128
+static const long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
+           16384l,   16379l,   16364l,   16340l,
+           16305l,   16261l,   16207l,   16143l,
+           16069l,   15986l,   15893l,   15791l,
+           15679l,   15557l,   15426l,   15286l,
+           15137l,   14978l,   14811l,   14635l,
+           14449l,   14256l,   14053l,   13842l,
+           13623l,   13395l,   13160l,   12916l,
+           12665l,   12406l,   12140l,   11866l,
+           11585l,   11297l,   11003l,   10702l,
+           10394l,   10080l,    9760l,    9434l,
+            9102l,    8765l,    8423l,    8076l,
+            7723l,    7366l,    7005l,    6639l,
+            6270l,    5897l,    5520l,    5139l,
+            4756l,    4370l,    3981l,    3590l,
+            3196l,    2801l,    2404l,    2006l,
+            1606l,    1205l,     804l,     402l,
+               0l,    -401l,    -803l,   -1204l,
+           -1605l,   -2005l,   -2403l,   -2800l,
+           -3195l,   -3589l,   -3980l,   -4369l,
+           -4755l,   -5138l,   -5519l,   -5896l,
+           -6269l,   -6638l,   -7004l,   -7365l,
+           -7722l,   -8075l,   -8422l,   -8764l,
+           -9101l,   -9433l,   -9759l,  -10079l,
+          -10393l,  -10701l,  -11002l,  -11296l,
+          -11584l,  -11865l,  -12139l,  -12405l,
+          -12664l,  -12915l,  -13159l,  -13394l,
+          -13622l,  -13841l,  -14052l,  -14255l,
+          -14448l,  -14634l,  -14810l,  -14977l,
+          -15136l,  -15285l,  -15425l,  -15556l,
+          -15678l,  -15790l,  -15892l,  -15985l,
+          -16068l,  -16142l,  -16206l,  -16260l,
+          -16304l,  -16339l,  -16363l,  -16378l,
+          -16383l,
+};
+
+#endif
+
+#endif
diff --git a/vorbis/lib/lookups.pl b/vorbis/lib/lookups.pl
new file mode 100644 (file)
index 0000000..9bc0b03
--- /dev/null
@@ -0,0 +1,141 @@
+#!/usr/bin/perl
+print <<'EOD';
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: lookup data; generated by lookups.pl; edit there
+
+ ********************************************************************/
+
+#ifndef _V_LOOKUP_DATA_H_
+
+#ifdef FLOAT_LOOKUP
+EOD
+
+$cos_sz=128;
+$invsq_sz=32;
+$invsq2exp_min=-32;
+$invsq2exp_max=32;
+
+$fromdB_sz=35;
+$fromdB_shift=5;
+$fromdB2_shift=3;
+
+$invsq_i_shift=10;
+$cos_i_shift=9;
+$delta_shift=6;
+
+print "#define COS_LOOKUP_SZ $cos_sz\n";
+print "static float COS_LOOKUP[COS_LOOKUP_SZ+1]={\n";
+
+for($i=0;$i<=$cos_sz;){
+    print "\t";
+    for($j=0;$j<4 && $i<=$cos_sz;$j++){
+       printf "%+.13f,", cos(3.14159265358979323846*($i++)/$cos_sz) ;
+    }
+    print "\n";
+}
+print "};\n\n";
+
+print "#define INVSQ_LOOKUP_SZ $invsq_sz\n";
+print "static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={\n";
+
+for($i=0;$i<=$invsq_sz;){
+    print "\t";
+    for($j=0;$j<4 && $i<=$invsq_sz;$j++){
+       my$indexmap=$i++/$invsq_sz*.5+.5;
+       printf "%.12f,", 1./sqrt($indexmap);
+    }
+    print "\n";
+}
+print "};\n\n";
+
+print "#define INVSQ2EXP_LOOKUP_MIN $invsq2exp_min\n";
+print "#define INVSQ2EXP_LOOKUP_MAX $invsq2exp_max\n";
+print "static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\\\n".
+      "                              INVSQ2EXP_LOOKUP_MIN+1]={\n";
+
+for($i=$invsq2exp_min;$i<=$invsq2exp_max;){
+    print "\t";
+    for($j=0;$j<4 && $i<=$invsq2exp_max;$j++){
+       printf "%15.10g,", 2**($i++*-.5);
+    }
+    print "\n";
+}
+print "};\n\n#endif\n\n";
+
+
+# 0 to -140 dB
+$fromdB2_sz=1<<$fromdB_shift;
+$fromdB_gran=1<<($fromdB_shift-$fromdB2_shift);
+print "#define FROMdB_LOOKUP_SZ $fromdB_sz\n";
+print "#define FROMdB2_LOOKUP_SZ $fromdB2_sz\n";
+print "#define FROMdB_SHIFT $fromdB_shift\n";
+print "#define FROMdB2_SHIFT $fromdB2_shift\n";
+print "#define FROMdB2_MASK ".((1<<$fromdB_shift)-1)."\n";
+
+print "static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={\n";
+
+for($i=0;$i<$fromdB_sz;){
+    print "\t";
+    for($j=0;$j<4 && $i<$fromdB_sz;$j++){
+       printf "%15.10g,", 10**(.05*(-$fromdB_gran*$i++));
+    }
+    print "\n";
+}
+print "};\n\n";
+
+print "static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={\n";
+
+for($i=0;$i<$fromdB2_sz;){
+    print "\t";
+    for($j=0;$j<4 && $i<$fromdB_sz;$j++){
+       printf "%15.10g,", 10**(.05*(-$fromdB_gran/$fromdB2_sz*(.5+$i++)));
+    }
+    print "\n";
+}
+print "};\n\n#ifdef INT_LOOKUP\n\n";
+
+
+$iisz=0x10000>>$invsq_i_shift;
+print "#define INVSQ_LOOKUP_I_SHIFT $invsq_i_shift\n";
+print "#define INVSQ_LOOKUP_I_MASK ".(0x0ffff>>(16-$invsq_i_shift))."\n";
+print "static long INVSQ_LOOKUP_I[$iisz+1]={\n";
+for($i=0;$i<=$iisz;){
+    print "\t";
+    for($j=0;$j<4 && $i<=$iisz;$j++){
+       my$indexmap=$i++/$iisz*.5+.5;
+       printf "%8d,", int(1./sqrt($indexmap)*65536.+.5);
+    }
+    print "\n";
+}
+print "};\n\n";
+
+$cisz=0x10000>>$cos_i_shift;
+print "#define COS_LOOKUP_I_SHIFT $cos_i_shift\n";
+print "#define COS_LOOKUP_I_MASK ".(0x0ffff>>(16-$cos_i_shift))."\n";
+print "#define COS_LOOKUP_I_SZ $cisz\n";
+print "static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={\n";
+
+for($i=0;$i<=$cisz;){
+    print "\t";
+    for($j=0;$j<4 && $i<=$cisz;$j++){
+       printf "%8d,", int(cos(3.14159265358979323846*($i++)/$cos_sz)*16384.+.5) ;
+    }
+    print "\n";
+}
+print "};\n\n";
+
+
+print "#endif\n\n#endif\n";
+
+
diff --git a/vorbis/lib/lpc.c b/vorbis/lib/lpc.c
new file mode 100644 (file)
index 0000000..798f4cf
--- /dev/null
@@ -0,0 +1,159 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: LPC low level routines
+
+ ********************************************************************/
+
+/* Some of these routines (autocorrelator, LPC coefficient estimator)
+   are derived from code written by Jutta Degener and Carsten Bormann;
+   thus we include their copyright below.  The entirety of this file
+   is freely redistributable on the condition that both of these
+   copyright notices are preserved without modification.  */
+
+/* Preserved Copyright: *********************************************/
+
+/* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universita"t Berlin
+
+Any use of this software is permitted provided that this notice is not
+removed and that neither the authors nor the Technische Universita"t
+Berlin are deemed to have made any representations as to the
+suitability of this software for any purpose nor are held responsible
+for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
+THIS SOFTWARE.
+
+As a matter of courtesy, the authors request to be informed about uses
+this software has found, about bugs in this software, and about any
+improvements that may be of general interest.
+
+Berlin, 28.11.1994
+Jutta Degener
+Carsten Bormann
+
+*********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include "os.h"
+#include "smallft.h"
+#include "lpc.h"
+#include "scales.h"
+#include "misc.h"
+
+/* Autocorrelation LPC coeff generation algorithm invented by
+   N. Levinson in 1947, modified by J. Durbin in 1959. */
+
+/* Input : n elements of time doamin data
+   Output: m lpc coefficients, excitation energy */
+
+float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
+  double *aut=alloca(sizeof(*aut)*(m+1));
+  double *lpc=alloca(sizeof(*lpc)*(m));
+  double error;
+  double epsilon;
+  int i,j;
+
+  /* autocorrelation, p+1 lag coefficients */
+  j=m+1;
+  while(j--){
+    double d=0; /* double needed for accumulator depth */
+    for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
+    aut[j]=d;
+  }
+
+  /* Generate lpc coefficients from autocorr values */
+
+  /* set our noise floor to about -100dB */
+  error=aut[0] * (1. + 1e-10);
+  epsilon=1e-9*aut[0]+1e-10;
+
+  for(i=0;i<m;i++){
+    double r= -aut[i+1];
+
+    if(error<epsilon){
+      memset(lpc+i,0,(m-i)*sizeof(*lpc));
+      goto done;
+    }
+
+    /* Sum up this iteration's reflection coefficient; note that in
+       Vorbis we don't save it.  If anyone wants to recycle this code
+       and needs reflection coefficients, save the results of 'r' from
+       each iteration. */
+
+    for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
+    r/=error;
+
+    /* Update LPC coefficients and total error */
+
+    lpc[i]=r;
+    for(j=0;j<i/2;j++){
+      double tmp=lpc[j];
+
+      lpc[j]+=r*lpc[i-1-j];
+      lpc[i-1-j]+=r*tmp;
+    }
+    if(i&1)lpc[j]+=lpc[j]*r;
+
+    error*=1.-r*r;
+
+  }
+
+ done:
+
+  /* slightly damp the filter */
+  {
+    double g = .99;
+    double damp = g;
+    for(j=0;j<m;j++){
+      lpc[j]*=damp;
+      damp*=g;
+    }
+  }
+
+  for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
+
+  /* we need the error value to know how big an impulse to hit the
+     filter with later */
+
+  return error;
+}
+
+void vorbis_lpc_predict(float *coeff,float *prime,int m,
+                     float *data,long n){
+
+  /* in: coeff[0...m-1] LPC coefficients
+         prime[0...m-1] initial values (allocated size of n+m-1)
+    out: data[0...n-1] data samples */
+
+  long i,j,o,p;
+  float y;
+  float *work=alloca(sizeof(*work)*(m+n));
+
+  if(!prime)
+    for(i=0;i<m;i++)
+      work[i]=0.f;
+  else
+    for(i=0;i<m;i++)
+      work[i]=prime[i];
+
+  for(i=0;i<n;i++){
+    y=0;
+    o=i;
+    p=m;
+    for(j=0;j<m;j++)
+      y-=work[o++]*coeff[--p];
+
+    data[i]=work[o]=y;
+  }
+}
diff --git a/vorbis/lib/lpc.h b/vorbis/lib/lpc.h
new file mode 100644 (file)
index 0000000..9cc7945
--- /dev/null
@@ -0,0 +1,28 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: LPC low level routines
+
+ ********************************************************************/
+
+#ifndef _V_LPC_H_
+#define _V_LPC_H_
+
+#include "vorbis/codec.h"
+
+/* simple linear scale LPC code */
+extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
+
+extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
+                               float *data,long n);
+
+#endif
diff --git a/vorbis/lib/lsp.c b/vorbis/lib/lsp.c
new file mode 100644 (file)
index 0000000..8588054
--- /dev/null
@@ -0,0 +1,453 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: LSP (also called LSF) conversion routines
+
+  The LSP generation code is taken (with minimal modification and a
+  few bugfixes) from "On the Computation of the LSP Frequencies" by
+  Joseph Rothweiler (see http://www.rothweiler.us for contact info).
+  The paper is available at:
+
+  http://www.myown1.com/joe/lsf
+
+ ********************************************************************/
+
+/* Note that the lpc-lsp conversion finds the roots of polynomial with
+   an iterative root polisher (CACM algorithm 283).  It *is* possible
+   to confuse this algorithm into not converging; that should only
+   happen with absurdly closely spaced roots (very sharp peaks in the
+   LPC f response) which in turn should be impossible in our use of
+   the code.  If this *does* happen anyway, it's a bug in the floor
+   finder; find the cause of the confusion (probably a single bin
+   spike or accidental near-float-limit resolution problems) and
+   correct it. */
+
+#include <math.h>
+#include <string.h>
+#include <stdlib.h>
+#include "lsp.h"
+#include "os.h"
+#include "misc.h"
+#include "lookup.h"
+#include "scales.h"
+
+/* three possible LSP to f curve functions; the exact computation
+   (float), a lookup based float implementation, and an integer
+   implementation.  The float lookup is likely the optimal choice on
+   any machine with an FPU.  The integer implementation is *not* fixed
+   point (due to the need for a large dynamic range and thus a
+   separately tracked exponent) and thus much more complex than the
+   relatively simple float implementations. It's mostly for future
+   work on a fully fixed point implementation for processors like the
+   ARM family. */
+
+/* define either of these (preferably FLOAT_LOOKUP) to have faster
+   but less precise implementation. */
+#undef FLOAT_LOOKUP
+#undef INT_LOOKUP
+
+#ifdef FLOAT_LOOKUP
+#include "lookup.c" /* catch this in the build system; we #include for
+                       compilers (like gcc) that can't inline across
+                       modules */
+
+/* side effect: changes *lsp to cosines of lsp */
+void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
+                            float amp,float ampoffset){
+  int i;
+  float wdel=M_PI/ln;
+  vorbis_fpu_control fpu;
+
+  vorbis_fpu_setround(&fpu);
+  for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
+
+  i=0;
+  while(i<n){
+    int k=map[i];
+    int qexp;
+    float p=.7071067812f;
+    float q=.7071067812f;
+    float w=vorbis_coslook(wdel*k);
+    float *ftmp=lsp;
+    int c=m>>1;
+
+    while(c--){
+      q*=ftmp[0]-w;
+      p*=ftmp[1]-w;
+      ftmp+=2;
+    }
+
+    if(m&1){
+      /* odd order filter; slightly assymetric */
+      /* the last coefficient */
+      q*=ftmp[0]-w;
+      q*=q;
+      p*=p*(1.f-w*w);
+    }else{
+      /* even order filter; still symmetric */
+      q*=q*(1.f+w);
+      p*=p*(1.f-w);
+    }
+
+    q=frexp(p+q,&qexp);
+    q=vorbis_fromdBlook(amp*
+                        vorbis_invsqlook(q)*
+                        vorbis_invsq2explook(qexp+m)-
+                        ampoffset);
+
+    do{
+      curve[i++]*=q;
+    }while(map[i]==k);
+  }
+  vorbis_fpu_restore(fpu);
+}
+
+#else
+
+#ifdef INT_LOOKUP
+#include "lookup.c" /* catch this in the build system; we #include for
+                       compilers (like gcc) that can't inline across
+                       modules */
+
+static const int MLOOP_1[64]={
+   0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
+  14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
+  15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+  15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
+};
+
+static const int MLOOP_2[64]={
+  0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
+  8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
+  9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
+  9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
+};
+
+static const int MLOOP_3[8]={0,1,2,2,3,3,3,3};
+
+
+/* side effect: changes *lsp to cosines of lsp */
+void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
+                            float amp,float ampoffset){
+
+  /* 0 <= m < 256 */
+
+  /* set up for using all int later */
+  int i;
+  int ampoffseti=rint(ampoffset*4096.f);
+  int ampi=rint(amp*16.f);
+  long *ilsp=alloca(m*sizeof(*ilsp));
+  for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
+
+  i=0;
+  while(i<n){
+    int j,k=map[i];
+    unsigned long pi=46341; /* 2**-.5 in 0.16 */
+    unsigned long qi=46341;
+    int qexp=0,shift;
+    long wi=vorbis_coslook_i(k*65536/ln);
+
+    qi*=labs(ilsp[0]-wi);
+    pi*=labs(ilsp[1]-wi);
+
+    for(j=3;j<m;j+=2){
+      if(!(shift=MLOOP_1[(pi|qi)>>25]))
+        if(!(shift=MLOOP_2[(pi|qi)>>19]))
+          shift=MLOOP_3[(pi|qi)>>16];
+      qi=(qi>>shift)*labs(ilsp[j-1]-wi);
+      pi=(pi>>shift)*labs(ilsp[j]-wi);
+      qexp+=shift;
+    }
+    if(!(shift=MLOOP_1[(pi|qi)>>25]))
+      if(!(shift=MLOOP_2[(pi|qi)>>19]))
+        shift=MLOOP_3[(pi|qi)>>16];
+
+    /* pi,qi normalized collectively, both tracked using qexp */
+
+    if(m&1){
+      /* odd order filter; slightly assymetric */
+      /* the last coefficient */
+      qi=(qi>>shift)*labs(ilsp[j-1]-wi);
+      pi=(pi>>shift)<<14;
+      qexp+=shift;
+
+      if(!(shift=MLOOP_1[(pi|qi)>>25]))
+        if(!(shift=MLOOP_2[(pi|qi)>>19]))
+          shift=MLOOP_3[(pi|qi)>>16];
+
+      pi>>=shift;
+      qi>>=shift;
+      qexp+=shift-14*((m+1)>>1);
+
+      pi=((pi*pi)>>16);
+      qi=((qi*qi)>>16);
+      qexp=qexp*2+m;
+
+      pi*=(1<<14)-((wi*wi)>>14);
+      qi+=pi>>14;
+
+    }else{
+      /* even order filter; still symmetric */
+
+      /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
+         worth tracking step by step */
+
+      pi>>=shift;
+      qi>>=shift;
+      qexp+=shift-7*m;
+
+      pi=((pi*pi)>>16);
+      qi=((qi*qi)>>16);
+      qexp=qexp*2+m;
+
+      pi*=(1<<14)-wi;
+      qi*=(1<<14)+wi;
+      qi=(qi+pi)>>14;
+
+    }
+
+
+    /* we've let the normalization drift because it wasn't important;
+       however, for the lookup, things must be normalized again.  We
+       need at most one right shift or a number of left shifts */
+
+    if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
+      qi>>=1; qexp++;
+    }else
+      while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
+        qi<<=1; qexp--;
+      }
+
+    amp=vorbis_fromdBlook_i(ampi*                     /*  n.4         */
+                            vorbis_invsqlook_i(qi,qexp)-
+                                                      /*  m.8, m+n<=8 */
+                            ampoffseti);              /*  8.12[0]     */
+
+    curve[i]*=amp;
+    while(map[++i]==k)curve[i]*=amp;
+  }
+}
+
+#else
+
+/* old, nonoptimized but simple version for any poor sap who needs to
+   figure out what the hell this code does, or wants the other
+   fraction of a dB precision */
+
+/* side effect: changes *lsp to cosines of lsp */
+void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
+                            float amp,float ampoffset){
+  int i;
+  float wdel=M_PI/ln;
+  for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
+
+  i=0;
+  while(i<n){
+    int j,k=map[i];
+    float p=.5f;
+    float q=.5f;
+    float w=2.f*cos(wdel*k);
+    for(j=1;j<m;j+=2){
+      q *= w-lsp[j-1];
+      p *= w-lsp[j];
+    }
+    if(j==m){
+      /* odd order filter; slightly assymetric */
+      /* the last coefficient */
+      q*=w-lsp[j-1];
+      p*=p*(4.f-w*w);
+      q*=q;
+    }else{
+      /* even order filter; still symmetric */
+      p*=p*(2.f-w);
+      q*=q*(2.f+w);
+    }
+
+    q=fromdB(amp/sqrt(p+q)-ampoffset);
+
+    curve[i]*=q;
+    while(map[++i]==k)curve[i]*=q;
+  }
+}
+
+#endif
+#endif
+
+static void cheby(float *g, int ord) {
+  int i, j;
+
+  g[0] *= .5f;
+  for(i=2; i<= ord; i++) {
+    for(j=ord; j >= i; j--) {
+      g[j-2] -= g[j];
+      g[j] += g[j];
+    }
+  }
+}
+
+static int comp(const void *a,const void *b){
+  return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
+}
+
+/* Newton-Raphson-Maehly actually functioned as a decent root finder,
+   but there are root sets for which it gets into limit cycles
+   (exacerbated by zero suppression) and fails.  We can't afford to
+   fail, even if the failure is 1 in 100,000,000, so we now use
+   Laguerre and later polish with Newton-Raphson (which can then
+   afford to fail) */
+
+#define EPSILON 10e-7
+static int Laguerre_With_Deflation(float *a,int ord,float *r){
+  int i,m;
+  double *defl=alloca(sizeof(*defl)*(ord+1));
+  for(i=0;i<=ord;i++)defl[i]=a[i];
+
+  for(m=ord;m>0;m--){
+    double new=0.f,delta;
+
+    /* iterate a root */
+    while(1){
+      double p=defl[m],pp=0.f,ppp=0.f,denom;
+
+      /* eval the polynomial and its first two derivatives */
+      for(i=m;i>0;i--){
+        ppp = new*ppp + pp;
+        pp  = new*pp  + p;
+        p   = new*p   + defl[i-1];
+      }
+
+      /* Laguerre's method */
+      denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
+      if(denom<0)
+        return(-1);  /* complex root!  The LPC generator handed us a bad filter */
+
+      if(pp>0){
+        denom = pp + sqrt(denom);
+        if(denom<EPSILON)denom=EPSILON;
+      }else{
+        denom = pp - sqrt(denom);
+        if(denom>-(EPSILON))denom=-(EPSILON);
+      }
+
+      delta  = m*p/denom;
+      new   -= delta;
+
+      if(delta<0.f)delta*=-1;
+
+      if(fabs(delta/new)<10e-12)break;
+    }
+
+    r[m-1]=new;
+
+    /* forward deflation */
+
+    for(i=m;i>0;i--)
+      defl[i-1]+=new*defl[i];
+    defl++;
+
+  }
+  return(0);
+}
+
+
+/* for spit-and-polish only */
+static int Newton_Raphson(float *a,int ord,float *r){
+  int i, k, count=0;
+  double error=1.f;
+  double *root=alloca(ord*sizeof(*root));
+
+  for(i=0; i<ord;i++) root[i] = r[i];
+
+  while(error>1e-20){
+    error=0;
+
+    for(i=0; i<ord; i++) { /* Update each point. */
+      double pp=0.,delta;
+      double rooti=root[i];
+      double p=a[ord];
+      for(k=ord-1; k>= 0; k--) {
+
+        pp= pp* rooti + p;
+        p = p * rooti + a[k];
+      }
+
+      delta = p/pp;
+      root[i] -= delta;
+      error+= delta*delta;
+    }
+
+    if(count>40)return(-1);
+
+    count++;
+  }
+
+  /* Replaced the original bubble sort with a real sort.  With your
+     help, we can eliminate the bubble sort in our lifetime. --Monty */
+
+  for(i=0; i<ord;i++) r[i] = root[i];
+  return(0);
+}
+
+
+/* Convert lpc coefficients to lsp coefficients */
+int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
+  int order2=(m+1)>>1;
+  int g1_order,g2_order;
+  float *g1=alloca(sizeof(*g1)*(order2+1));
+  float *g2=alloca(sizeof(*g2)*(order2+1));
+  float *g1r=alloca(sizeof(*g1r)*(order2+1));
+  float *g2r=alloca(sizeof(*g2r)*(order2+1));
+  int i;
+
+  /* even and odd are slightly different base cases */
+  g1_order=(m+1)>>1;
+  g2_order=(m)  >>1;
+
+  /* Compute the lengths of the x polynomials. */
+  /* Compute the first half of K & R F1 & F2 polynomials. */
+  /* Compute half of the symmetric and antisymmetric polynomials. */
+  /* Remove the roots at +1 and -1. */
+
+  g1[g1_order] = 1.f;
+  for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
+  g2[g2_order] = 1.f;
+  for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
+
+  if(g1_order>g2_order){
+    for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
+  }else{
+    for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
+    for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
+  }
+
+  /* Convert into polynomials in cos(alpha) */
+  cheby(g1,g1_order);
+  cheby(g2,g2_order);
+
+  /* Find the roots of the 2 even polynomials.*/
+  if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
+     Laguerre_With_Deflation(g2,g2_order,g2r))
+    return(-1);
+
+  Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
+  Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
+
+  qsort(g1r,g1_order,sizeof(*g1r),comp);
+  qsort(g2r,g2_order,sizeof(*g2r),comp);
+
+  for(i=0;i<g1_order;i++)
+    lsp[i*2] = acos(g1r[i]);
+
+  for(i=0;i<g2_order;i++)
+    lsp[i*2+1] = acos(g2r[i]);
+  return(0);
+}
diff --git a/vorbis/lib/lsp.h b/vorbis/lib/lsp.h
new file mode 100644 (file)
index 0000000..8a8d10e
--- /dev/null
@@ -0,0 +1,27 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+  function: LSP (also called LSF) conversion routines
+
+ ********************************************************************/
+
+
+#ifndef _V_LSP_H_
+#define _V_LSP_H_
+
+extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
+
+extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
+                                float *lsp,int m,
+                                float amp,float ampoffset);
+
+#endif
diff --git a/vorbis/lib/mapping0.c b/vorbis/lib/mapping0.c
new file mode 100644 (file)
index 0000000..ccb4493
--- /dev/null
@@ -0,0 +1,808 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: channel mapping 0 implementation
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "codebook.h"
+#include "window.h"
+#include "registry.h"
+#include "psy.h"
+#include "misc.h"
+
+/* simplistic, wasteful way of doing this (unique lookup for each
+   mode/submapping); there should be a central repository for
+   identical lookups.  That will require minor work, so I'm putting it
+   off as low priority.
+
+   Why a lookup for each backend in a given mode?  Because the
+   blocksize is set by the mode, and low backend lookups may require
+   parameters from other areas of the mode/mapping */
+
+static void mapping0_free_info(vorbis_info_mapping *i){
+  vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
+  if(info){
+    memset(info,0,sizeof(*info));
+    _ogg_free(info);
+  }
+}
+
+static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
+                          oggpack_buffer *opb){
+  int i;
+  vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
+
+  /* another 'we meant to do it this way' hack...  up to beta 4, we
+     packed 4 binary zeros here to signify one submapping in use.  We
+     now redefine that to mean four bitflags that indicate use of
+     deeper features; bit0:submappings, bit1:coupling,
+     bit2,3:reserved. This is backward compatable with all actual uses
+     of the beta code. */
+
+  if(info->submaps>1){
+    oggpack_write(opb,1,1);
+    oggpack_write(opb,info->submaps-1,4);
+  }else
+    oggpack_write(opb,0,1);
+
+  if(info->coupling_steps>0){
+    oggpack_write(opb,1,1);
+    oggpack_write(opb,info->coupling_steps-1,8);
+
+    for(i=0;i<info->coupling_steps;i++){
+      oggpack_write(opb,info->coupling_mag[i],ov_ilog(vi->channels-1));
+      oggpack_write(opb,info->coupling_ang[i],ov_ilog(vi->channels-1));
+    }
+  }else
+    oggpack_write(opb,0,1);
+
+  oggpack_write(opb,0,2); /* 2,3:reserved */
+
+  /* we don't write the channel submappings if we only have one... */
+  if(info->submaps>1){
+    for(i=0;i<vi->channels;i++)
+      oggpack_write(opb,info->chmuxlist[i],4);
+  }
+  for(i=0;i<info->submaps;i++){
+    oggpack_write(opb,0,8); /* time submap unused */
+    oggpack_write(opb,info->floorsubmap[i],8);
+    oggpack_write(opb,info->residuesubmap[i],8);
+  }
+}
+
+/* also responsible for range checking */
+static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
+  int i,b;
+  vorbis_info_mapping0 *info=_ogg_calloc(1,sizeof(*info));
+  codec_setup_info     *ci=vi->codec_setup;
+  if(vi->channels<=0)goto err_out;
+
+  b=oggpack_read(opb,1);
+  if(b<0)goto err_out;
+  if(b){
+    info->submaps=oggpack_read(opb,4)+1;
+    if(info->submaps<=0)goto err_out;
+  }else
+    info->submaps=1;
+
+  b=oggpack_read(opb,1);
+  if(b<0)goto err_out;
+  if(b){
+    info->coupling_steps=oggpack_read(opb,8)+1;
+    if(info->coupling_steps<=0)goto err_out;
+    for(i=0;i<info->coupling_steps;i++){
+      /* vi->channels > 0 is enforced in the caller */
+      int testM=info->coupling_mag[i]=
+        oggpack_read(opb,ov_ilog(vi->channels-1));
+      int testA=info->coupling_ang[i]=
+        oggpack_read(opb,ov_ilog(vi->channels-1));
+
+      if(testM<0 ||
+         testA<0 ||
+         testM==testA ||
+         testM>=vi->channels ||
+         testA>=vi->channels) goto err_out;
+    }
+
+  }
+
+  if(oggpack_read(opb,2)!=0)goto err_out; /* 2,3:reserved */
+
+  if(info->submaps>1){
+    for(i=0;i<vi->channels;i++){
+      info->chmuxlist[i]=oggpack_read(opb,4);
+      if(info->chmuxlist[i]>=info->submaps || info->chmuxlist[i]<0)goto err_out;
+    }
+  }
+  for(i=0;i<info->submaps;i++){
+    oggpack_read(opb,8); /* time submap unused */
+    info->floorsubmap[i]=oggpack_read(opb,8);
+    if(info->floorsubmap[i]>=ci->floors || info->floorsubmap[i]<0)goto err_out;
+    info->residuesubmap[i]=oggpack_read(opb,8);
+    if(info->residuesubmap[i]>=ci->residues || info->residuesubmap[i]<0)goto err_out;
+  }
+
+  return info;
+
+ err_out:
+  mapping0_free_info(info);
+  return(NULL);
+}
+
+#include "os.h"
+#include "lpc.h"
+#include "lsp.h"
+#include "envelope.h"
+#include "mdct.h"
+#include "psy.h"
+#include "scales.h"
+
+#if 0
+static long seq=0;
+static ogg_int64_t total=0;
+static float FLOOR1_fromdB_LOOKUP[256]={
+  1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
+  1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
+  1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
+  2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
+  2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
+  3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
+  4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
+  6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
+  7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
+  1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
+  1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
+  1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
+  2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
+  2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
+  3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
+  4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
+  5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
+  7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
+  9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
+  1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
+  1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
+  2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
+  2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
+  3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
+  4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
+  5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
+  7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
+  9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
+  0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
+  0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
+  0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
+  0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
+  0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
+  0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
+  0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
+  0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
+  0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
+  0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
+  0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
+  0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
+  0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
+  0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
+  0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
+  0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
+  0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
+  0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
+  0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
+  0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
+  0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
+  0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
+  0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
+  0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
+  0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
+  0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
+  0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
+  0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
+  0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
+  0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
+  0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
+  0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
+  0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
+  0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
+  0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
+  0.82788260F, 0.88168307F, 0.9389798F, 1.F,
+};
+
+#endif
+
+
+static int mapping0_forward(vorbis_block *vb){
+  vorbis_dsp_state      *vd=vb->vd;
+  vorbis_info           *vi=vd->vi;
+  codec_setup_info      *ci=vi->codec_setup;
+  private_state         *b=vb->vd->backend_state;
+  vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
+  int                    n=vb->pcmend;
+  int i,j,k;
+
+  int    *nonzero    = alloca(sizeof(*nonzero)*vi->channels);
+  float  **gmdct     = _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
+  int    **iwork      = _vorbis_block_alloc(vb,vi->channels*sizeof(*iwork));
+  int ***floor_posts = _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
+
+  float global_ampmax=vbi->ampmax;
+  float *local_ampmax=alloca(sizeof(*local_ampmax)*vi->channels);
+  int blocktype=vbi->blocktype;
+
+  int modenumber=vb->W;
+  vorbis_info_mapping0 *info=ci->map_param[modenumber];
+  vorbis_look_psy *psy_look=b->psy+blocktype+(vb->W?2:0);
+
+  vb->mode=modenumber;
+
+  for(i=0;i<vi->channels;i++){
+    float scale=4.f/n;
+    float scale_dB;
+
+    float *pcm     =vb->pcm[i];
+    float *logfft  =pcm;
+
+    iwork[i]=_vorbis_block_alloc(vb,n/2*sizeof(**iwork));
+    gmdct[i]=_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
+
+    scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
+                                     todB estimation used on IEEE 754
+                                     compliant machines had a bug that
+                                     returned dB values about a third
+                                     of a decibel too high.  The bug
+                                     was harmless because tunings
+                                     implicitly took that into
+                                     account.  However, fixing the bug
+                                     in the estimator requires
+                                     changing all the tunings as well.
+                                     For now, it's easier to sync
+                                     things back up here, and
+                                     recalibrate the tunings in the
+                                     next major model upgrade. */
+
+#if 0
+    if(vi->channels==2){
+      if(i==0)
+        _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
+      else
+        _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
+    }else{
+      _analysis_output("pcm",seq,pcm,n,0,0,total-n/2);
+    }
+#endif
+
+    /* window the PCM data */
+    _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
+
+#if 0
+    if(vi->channels==2){
+      if(i==0)
+        _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
+      else
+        _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
+    }else{
+      _analysis_output("windowed",seq,pcm,n,0,0,total-n/2);
+    }
+#endif
+
+    /* transform the PCM data */
+    /* only MDCT right now.... */
+    mdct_forward(b->transform[vb->W][0],pcm,gmdct[i]);
+
+    /* FFT yields more accurate tonal estimation (not phase sensitive) */
+    drft_forward(&b->fft_look[vb->W],pcm);
+    logfft[0]=scale_dB+todB(pcm)  + .345; /* + .345 is a hack; the
+                                     original todB estimation used on
+                                     IEEE 754 compliant machines had a
+                                     bug that returned dB values about
+                                     a third of a decibel too high.
+                                     The bug was harmless because
+                                     tunings implicitly took that into
+                                     account.  However, fixing the bug
+                                     in the estimator requires
+                                     changing all the tunings as well.
+                                     For now, it's easier to sync
+                                     things back up here, and
+                                     recalibrate the tunings in the
+                                     next major model upgrade. */
+    local_ampmax[i]=logfft[0];
+    for(j=1;j<n-1;j+=2){
+      float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
+      temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp)  + .345; /* +
+                                     .345 is a hack; the original todB
+                                     estimation used on IEEE 754
+                                     compliant machines had a bug that
+                                     returned dB values about a third
+                                     of a decibel too high.  The bug
+                                     was harmless because tunings
+                                     implicitly took that into
+                                     account.  However, fixing the bug
+                                     in the estimator requires
+                                     changing all the tunings as well.
+                                     For now, it's easier to sync
+                                     things back up here, and
+                                     recalibrate the tunings in the
+                                     next major model upgrade. */
+      if(temp>local_ampmax[i])local_ampmax[i]=temp;
+    }
+
+    if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
+    if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
+
+#if 0
+    if(vi->channels==2){
+      if(i==0){
+        _analysis_output("fftL",seq,logfft,n/2,1,0,0);
+      }else{
+        _analysis_output("fftR",seq,logfft,n/2,1,0,0);
+      }
+    }else{
+      _analysis_output("fft",seq,logfft,n/2,1,0,0);
+    }
+#endif
+
+  }
+
+  {
+    float   *noise        = _vorbis_block_alloc(vb,n/2*sizeof(*noise));
+    float   *tone         = _vorbis_block_alloc(vb,n/2*sizeof(*tone));
+
+    for(i=0;i<vi->channels;i++){
+      /* the encoder setup assumes that all the modes used by any
+         specific bitrate tweaking use the same floor */
+
+      int submap=info->chmuxlist[i];
+
+      /* the following makes things clearer to *me* anyway */
+      float *mdct    =gmdct[i];
+      float *logfft  =vb->pcm[i];
+
+      float *logmdct =logfft+n/2;
+      float *logmask =logfft;
+
+      vb->mode=modenumber;
+
+      floor_posts[i]=_vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
+      memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
+
+      for(j=0;j<n/2;j++)
+        logmdct[j]=todB(mdct+j)  + .345; /* + .345 is a hack; the original
+                                     todB estimation used on IEEE 754
+                                     compliant machines had a bug that
+                                     returned dB values about a third
+                                     of a decibel too high.  The bug
+                                     was harmless because tunings
+                                     implicitly took that into
+                                     account.  However, fixing the bug
+                                     in the estimator requires
+                                     changing all the tunings as well.
+                                     For now, it's easier to sync
+                                     things back up here, and
+                                     recalibrate the tunings in the
+                                     next major model upgrade. */
+
+#if 0
+      if(vi->channels==2){
+        if(i==0)
+          _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
+        else
+          _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
+      }else{
+        _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
+      }
+#endif
+
+      /* first step; noise masking.  Not only does 'noise masking'
+         give us curves from which we can decide how much resolution
+         to give noise parts of the spectrum, it also implicitly hands
+         us a tonality estimate (the larger the value in the
+         'noise_depth' vector, the more tonal that area is) */
+
+      _vp_noisemask(psy_look,
+                    logmdct,
+                    noise); /* noise does not have by-frequency offset
+                               bias applied yet */
+#if 0
+      if(vi->channels==2){
+        if(i==0)
+          _analysis_output("noiseL",seq,noise,n/2,1,0,0);
+        else
+          _analysis_output("noiseR",seq,noise,n/2,1,0,0);
+      }else{
+        _analysis_output("noise",seq,noise,n/2,1,0,0);
+      }
+#endif
+
+      /* second step: 'all the other crap'; all the stuff that isn't
+         computed/fit for bitrate management goes in the second psy
+         vector.  This includes tone masking, peak limiting and ATH */
+
+      _vp_tonemask(psy_look,
+                   logfft,
+                   tone,
+                   global_ampmax,
+                   local_ampmax[i]);
+
+#if 0
+      if(vi->channels==2){
+        if(i==0)
+          _analysis_output("toneL",seq,tone,n/2,1,0,0);
+        else
+          _analysis_output("toneR",seq,tone,n/2,1,0,0);
+      }else{
+        _analysis_output("tone",seq,tone,n/2,1,0,0);
+      }
+#endif
+
+      /* third step; we offset the noise vectors, overlay tone
+         masking.  We then do a floor1-specific line fit.  If we're
+         performing bitrate management, the line fit is performed
+         multiple times for up/down tweakage on demand. */
+
+#if 0
+      {
+      float aotuv[psy_look->n];
+#endif
+
+        _vp_offset_and_mix(psy_look,
+                           noise,
+                           tone,
+                           1,
+                           logmask,
+                           mdct,
+                           logmdct);
+
+#if 0
+        if(vi->channels==2){
+          if(i==0)
+            _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
+          else
+            _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
+        }else{
+          _analysis_output("aotuvM1",seq,aotuv,psy_look->n,1,1,0);
+        }
+      }
+#endif
+
+
+#if 0
+      if(vi->channels==2){
+        if(i==0)
+          _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
+        else
+          _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
+      }else{
+        _analysis_output("mask1",seq,logmask,n/2,1,0,0);
+      }
+#endif
+
+      /* this algorithm is hardwired to floor 1 for now; abort out if
+         we're *not* floor1.  This won't happen unless someone has
+         broken the encode setup lib.  Guard it anyway. */
+      if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
+
+      floor_posts[i][PACKETBLOBS/2]=
+        floor1_fit(vb,b->flr[info->floorsubmap[submap]],
+                   logmdct,
+                   logmask);
+
+      /* are we managing bitrate?  If so, perform two more fits for
+         later rate tweaking (fits represent hi/lo) */
+      if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
+        /* higher rate by way of lower noise curve */
+
+        _vp_offset_and_mix(psy_look,
+                           noise,
+                           tone,
+                           2,
+                           logmask,
+                           mdct,
+                           logmdct);
+
+#if 0
+        if(vi->channels==2){
+          if(i==0)
+            _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
+          else
+            _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
+        }else{
+          _analysis_output("mask2",seq,logmask,n/2,1,0,0);
+        }
+#endif
+
+        floor_posts[i][PACKETBLOBS-1]=
+          floor1_fit(vb,b->flr[info->floorsubmap[submap]],
+                     logmdct,
+                     logmask);
+
+        /* lower rate by way of higher noise curve */
+        _vp_offset_and_mix(psy_look,
+                           noise,
+                           tone,
+                           0,
+                           logmask,
+                           mdct,
+                           logmdct);
+
+#if 0
+        if(vi->channels==2){
+          if(i==0)
+            _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
+          else
+            _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
+        }else{
+          _analysis_output("mask0",seq,logmask,n/2,1,0,0);
+        }
+#endif
+
+        floor_posts[i][0]=
+          floor1_fit(vb,b->flr[info->floorsubmap[submap]],
+                     logmdct,
+                     logmask);
+
+        /* we also interpolate a range of intermediate curves for
+           intermediate rates */
+        for(k=1;k<PACKETBLOBS/2;k++)
+          floor_posts[i][k]=
+            floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
+                                   floor_posts[i][0],
+                                   floor_posts[i][PACKETBLOBS/2],
+                                   k*65536/(PACKETBLOBS/2));
+        for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
+          floor_posts[i][k]=
+            floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
+                                   floor_posts[i][PACKETBLOBS/2],
+                                   floor_posts[i][PACKETBLOBS-1],
+                                   (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
+      }
+    }
+  }
+  vbi->ampmax=global_ampmax;
+
+  /*
+    the next phases are performed once for vbr-only and PACKETBLOB
+    times for bitrate managed modes.
+
+    1) encode actual mode being used
+    2) encode the floor for each channel, compute coded mask curve/res
+    3) normalize and couple.
+    4) encode residue
+    5) save packet bytes to the packetblob vector
+
+  */
+
+  /* iterate over the many masking curve fits we've created */
+
+  {
+    int **couple_bundle=alloca(sizeof(*couple_bundle)*vi->channels);
+    int *zerobundle=alloca(sizeof(*zerobundle)*vi->channels);
+
+    for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
+        k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
+        k++){
+      oggpack_buffer *opb=vbi->packetblob[k];
+
+      /* start out our new packet blob with packet type and mode */
+      /* Encode the packet type */
+      oggpack_write(opb,0,1);
+      /* Encode the modenumber */
+      /* Encode frame mode, pre,post windowsize, then dispatch */
+      oggpack_write(opb,modenumber,b->modebits);
+      if(vb->W){
+        oggpack_write(opb,vb->lW,1);
+        oggpack_write(opb,vb->nW,1);
+      }
+
+      /* encode floor, compute masking curve, sep out residue */
+      for(i=0;i<vi->channels;i++){
+        int submap=info->chmuxlist[i];
+        int *ilogmask=iwork[i];
+
+        nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
+                                 floor_posts[i][k],
+                                 ilogmask);
+#if 0
+        {
+          char buf[80];
+          sprintf(buf,"maskI%c%d",i?'R':'L',k);
+          float work[n/2];
+          for(j=0;j<n/2;j++)
+            work[j]=FLOOR1_fromdB_LOOKUP[iwork[i][j]];
+          _analysis_output(buf,seq,work,n/2,1,1,0);
+        }
+#endif
+      }
+
+      /* our iteration is now based on masking curve, not prequant and
+         coupling.  Only one prequant/coupling step */
+
+      /* quantize/couple */
+      /* incomplete implementation that assumes the tree is all depth
+         one, or no tree at all */
+      _vp_couple_quantize_normalize(k,
+                                    &ci->psy_g_param,
+                                    psy_look,
+                                    info,
+                                    gmdct,
+                                    iwork,
+                                    nonzero,
+                                    ci->psy_g_param.sliding_lowpass[vb->W][k],
+                                    vi->channels);
+
+#if 0
+      for(i=0;i<vi->channels;i++){
+        char buf[80];
+        sprintf(buf,"res%c%d",i?'R':'L',k);
+        float work[n/2];
+        for(j=0;j<n/2;j++)
+          work[j]=iwork[i][j];
+        _analysis_output(buf,seq,work,n/2,1,0,0);
+      }
+#endif
+
+      /* classify and encode by submap */
+      for(i=0;i<info->submaps;i++){
+        int ch_in_bundle=0;
+        long **classifications;
+        int resnum=info->residuesubmap[i];
+
+        for(j=0;j<vi->channels;j++){
+          if(info->chmuxlist[j]==i){
+            zerobundle[ch_in_bundle]=0;
+            if(nonzero[j])zerobundle[ch_in_bundle]=1;
+            couple_bundle[ch_in_bundle++]=iwork[j];
+          }
+        }
+
+        classifications=_residue_P[ci->residue_type[resnum]]->
+          class(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
+
+        ch_in_bundle=0;
+        for(j=0;j<vi->channels;j++)
+          if(info->chmuxlist[j]==i)
+            couple_bundle[ch_in_bundle++]=iwork[j];
+
+        _residue_P[ci->residue_type[resnum]]->
+          forward(opb,vb,b->residue[resnum],
+                  couple_bundle,zerobundle,ch_in_bundle,classifications,i);
+      }
+
+      /* ok, done encoding.  Next protopacket. */
+    }
+
+  }
+
+#if 0
+  seq++;
+  total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
+#endif
+  return(0);
+}
+
+static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
+  vorbis_dsp_state     *vd=vb->vd;
+  vorbis_info          *vi=vd->vi;
+  codec_setup_info     *ci=vi->codec_setup;
+  private_state        *b=vd->backend_state;
+  vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
+
+  int                   i,j;
+  long                  n=vb->pcmend=ci->blocksizes[vb->W];
+
+  float **pcmbundle=alloca(sizeof(*pcmbundle)*vi->channels);
+  int    *zerobundle=alloca(sizeof(*zerobundle)*vi->channels);
+
+  int   *nonzero  =alloca(sizeof(*nonzero)*vi->channels);
+  void **floormemo=alloca(sizeof(*floormemo)*vi->channels);
+
+  /* recover the spectral envelope; store it in the PCM vector for now */
+  for(i=0;i<vi->channels;i++){
+    int submap=info->chmuxlist[i];
+    floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
+      inverse1(vb,b->flr[info->floorsubmap[submap]]);
+    if(floormemo[i])
+      nonzero[i]=1;
+    else
+      nonzero[i]=0;
+    memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
+  }
+
+  /* channel coupling can 'dirty' the nonzero listing */
+  for(i=0;i<info->coupling_steps;i++){
+    if(nonzero[info->coupling_mag[i]] ||
+       nonzero[info->coupling_ang[i]]){
+      nonzero[info->coupling_mag[i]]=1;
+      nonzero[info->coupling_ang[i]]=1;
+    }
+  }
+
+  /* recover the residue into our working vectors */
+  for(i=0;i<info->submaps;i++){
+    int ch_in_bundle=0;
+    for(j=0;j<vi->channels;j++){
+      if(info->chmuxlist[j]==i){
+        if(nonzero[j])
+          zerobundle[ch_in_bundle]=1;
+        else
+          zerobundle[ch_in_bundle]=0;
+        pcmbundle[ch_in_bundle++]=vb->pcm[j];
+      }
+    }
+
+    _residue_P[ci->residue_type[info->residuesubmap[i]]]->
+      inverse(vb,b->residue[info->residuesubmap[i]],
+              pcmbundle,zerobundle,ch_in_bundle);
+  }
+
+  /* channel coupling */
+  for(i=info->coupling_steps-1;i>=0;i--){
+    float *pcmM=vb->pcm[info->coupling_mag[i]];
+    float *pcmA=vb->pcm[info->coupling_ang[i]];
+
+    for(j=0;j<n/2;j++){
+      float mag=pcmM[j];
+      float ang=pcmA[j];
+
+      if(mag>0)
+        if(ang>0){
+          pcmM[j]=mag;
+          pcmA[j]=mag-ang;
+        }else{
+          pcmA[j]=mag;
+          pcmM[j]=mag+ang;
+        }
+      else
+        if(ang>0){
+          pcmM[j]=mag;
+          pcmA[j]=mag+ang;
+        }else{
+          pcmA[j]=mag;
+          pcmM[j]=mag-ang;
+        }
+    }
+  }
+
+  /* compute and apply spectral envelope */
+  for(i=0;i<vi->channels;i++){
+    float *pcm=vb->pcm[i];
+    int submap=info->chmuxlist[i];
+    _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
+      inverse2(vb,b->flr[info->floorsubmap[submap]],
+               floormemo[i],pcm);
+  }
+
+  /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
+  /* only MDCT right now.... */
+  for(i=0;i<vi->channels;i++){
+    float *pcm=vb->pcm[i];
+    mdct_backward(b->transform[vb->W][0],pcm,pcm);
+  }
+
+  /* all done! */
+  return(0);
+}
+
+/* export hooks */
+const vorbis_func_mapping mapping0_exportbundle={
+  &mapping0_pack,
+  &mapping0_unpack,
+  &mapping0_free_info,
+  &mapping0_forward,
+  &mapping0_inverse
+};
diff --git a/vorbis/lib/masking.h b/vorbis/lib/masking.h
new file mode 100644 (file)
index 0000000..955e18c
--- /dev/null
@@ -0,0 +1,784 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: masking curve data for psychoacoustics
+
+ ********************************************************************/
+
+#ifndef _V_MASKING_H_
+#define _V_MASKING_H_
+
+/* more detailed ATH; the bass if flat to save stressing the floor
+   overly for only a bin or two of savings. */
+
+#define MAX_ATH 88
+static const float ATH[]={
+  /*15*/  -51, -52, -53, -54, -55, -56, -57, -58,
+  /*31*/  -59, -60, -61, -62, -63, -64, -65, -66,
+  /*63*/  -67, -68, -69, -70, -71, -72, -73, -74,
+  /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
+  /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
+  /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
+  /*1k*/  -96, -97, -98, -98, -99, -99,-100,-100,
+  /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
+  /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
+  /*8k*/  -95, -95, -96, -97, -96, -95, -93, -90,
+  /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
+};
+
+/* The tone masking curves from Ehmer's and Fielder's papers have been
+   replaced by an empirically collected data set.  The previously
+   published values were, far too often, simply on crack. */
+
+#define EHMER_OFFSET 16
+#define EHMER_MAX 56
+
+/* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
+   test tones from -2 octaves to +5 octaves sampled at eighth octaves */
+/* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
+   for collection of these curves) */
+
+static const float tonemasks[P_BANDS][6][EHMER_MAX]={
+  /* 62.5 Hz */
+  {{ -60,  -60,  -60,  -60,  -60,  -60,  -60,  -60,
+     -60,  -60,  -60,  -60,  -62,  -62,  -65,  -73,
+     -69,  -68,  -68,  -67,  -70,  -70,  -72,  -74,
+     -75,  -79,  -79,  -80,  -83,  -88,  -93, -100,
+     -110, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -48,  -48,  -48,  -48,  -48,  -48,  -48,  -48,
+     -48,  -48,  -48,  -48,  -48,  -53,  -61,  -66,
+     -66,  -68,  -67,  -70,  -76,  -76,  -72,  -73,
+     -75,  -76,  -78,  -79,  -83,  -88,  -93, -100,
+     -110, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -37,  -37,  -37,  -37,  -37,  -37,  -37,  -37,
+     -38,  -40,  -42,  -46,  -48,  -53,  -55,  -62,
+     -65,  -58,  -56,  -56,  -61,  -60,  -65,  -67,
+     -69,  -71,  -77,  -77,  -78,  -80,  -82,  -84,
+     -88,  -93,  -98, -106, -112, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -25,  -25,  -25,  -25,  -25,  -25,  -25,  -25,
+     -25,  -26,  -27,  -29,  -32,  -38,  -48,  -52,
+     -52,  -50,  -48,  -48,  -51,  -52,  -54,  -60,
+     -67,  -67,  -66,  -68,  -69,  -73,  -73,  -76,
+     -80,  -81,  -81,  -85,  -85,  -86,  -88,  -93,
+     -100, -110, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -16,  -16,  -16,  -16,  -16,  -16,  -16,  -16,
+     -17,  -19,  -20,  -22,  -26,  -28,  -31,  -40,
+     -47,  -39,  -39,  -40,  -42,  -43,  -47,  -51,
+     -57,  -52,  -55,  -55,  -60,  -58,  -62,  -63,
+     -70,  -67,  -69,  -72,  -73,  -77,  -80,  -82,
+     -83,  -87,  -90,  -94,  -98, -104, -115, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   {  -8,   -8,   -8,   -8,   -8,   -8,   -8,   -8,
+      -8,   -8,  -10,  -11,  -15,  -19,  -25,  -30,
+      -34,  -31,  -30,  -31,  -29,  -32,  -35,  -42,
+      -48,  -42,  -44,  -46,  -50,  -50,  -51,  -52,
+      -59,  -54,  -55,  -55,  -58,  -62,  -63,  -66,
+      -72,  -73,  -76,  -75,  -78,  -80,  -80,  -81,
+      -84,  -88,  -90,  -94,  -98, -101, -106, -110}},
+  /* 88Hz */
+  {{ -66,  -66,  -66,  -66,  -66,  -66,  -66,  -66,
+     -66,  -66,  -66,  -66,  -66,  -67,  -67,  -67,
+     -76,  -72,  -71,  -74,  -76,  -76,  -75,  -78,
+     -79,  -79,  -81,  -83,  -86,  -89,  -93,  -97,
+     -100, -105, -110, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -47,  -47,  -47,  -47,  -47,  -47,  -47,  -47,
+     -47,  -47,  -47,  -48,  -51,  -55,  -59,  -66,
+     -66,  -66,  -67,  -66,  -68,  -69,  -70,  -74,
+     -79,  -77,  -77,  -78,  -80,  -81,  -82,  -84,
+     -86,  -88,  -91,  -95, -100, -108, -116, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -36,  -36,  -36,  -36,  -36,  -36,  -36,  -36,
+     -36,  -37,  -37,  -41,  -44,  -48,  -51,  -58,
+     -62,  -60,  -57,  -59,  -59,  -60,  -63,  -65,
+     -72,  -71,  -70,  -72,  -74,  -77,  -76,  -78,
+     -81,  -81,  -80,  -83,  -86,  -91,  -96, -100,
+     -105, -110, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -28,  -28,  -28,  -28,  -28,  -28,  -28,  -28,
+     -28,  -30,  -32,  -32,  -33,  -35,  -41,  -49,
+     -50,  -49,  -47,  -48,  -48,  -52,  -51,  -57,
+     -65,  -61,  -59,  -61,  -64,  -69,  -70,  -74,
+     -77,  -77,  -78,  -81,  -84,  -85,  -87,  -90,
+     -92,  -96, -100, -107, -112, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -19,  -19,  -19,  -19,  -19,  -19,  -19,  -19,
+     -20,  -21,  -23,  -27,  -30,  -35,  -36,  -41,
+     -46,  -44,  -42,  -40,  -41,  -41,  -43,  -48,
+     -55,  -53,  -52,  -53,  -56,  -59,  -58,  -60,
+     -67,  -66,  -69,  -71,  -72,  -75,  -79,  -81,
+     -84,  -87,  -90,  -93,  -97, -101, -107, -114,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   {  -9,   -9,   -9,   -9,   -9,   -9,   -9,   -9,
+      -11,  -12,  -12,  -15,  -16,  -20,  -23,  -30,
+      -37,  -34,  -33,  -34,  -31,  -32,  -32,  -38,
+      -47,  -44,  -41,  -40,  -47,  -49,  -46,  -46,
+      -58,  -50,  -50,  -54,  -58,  -62,  -64,  -67,
+      -67,  -70,  -72,  -76,  -79,  -83,  -87,  -91,
+      -96, -100, -104, -110, -999, -999, -999, -999}},
+  /* 125 Hz */
+  {{ -62,  -62,  -62,  -62,  -62,  -62,  -62,  -62,
+     -62,  -62,  -63,  -64,  -66,  -67,  -66,  -68,
+     -75,  -72,  -76,  -75,  -76,  -78,  -79,  -82,
+     -84,  -85,  -90,  -94, -101, -110, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -59,  -59,  -59,  -59,  -59,  -59,  -59,  -59,
+     -59,  -59,  -59,  -60,  -60,  -61,  -63,  -66,
+     -71,  -68,  -70,  -70,  -71,  -72,  -72,  -75,
+     -81,  -78,  -79,  -82,  -83,  -86,  -90,  -97,
+     -103, -113, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -53,  -53,  -53,  -53,  -53,  -53,  -53,  -53,
+     -53,  -54,  -55,  -57,  -56,  -57,  -55,  -61,
+     -65,  -60,  -60,  -62,  -63,  -63,  -66,  -68,
+     -74,  -73,  -75,  -75,  -78,  -80,  -80,  -82,
+     -85,  -90,  -96, -101, -108, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -46,  -46,  -46,  -46,  -46,  -46,  -46,  -46,
+     -46,  -46,  -47,  -47,  -47,  -47,  -48,  -51,
+     -57,  -51,  -49,  -50,  -51,  -53,  -54,  -59,
+     -66,  -60,  -62,  -67,  -67,  -70,  -72,  -75,
+     -76,  -78,  -81,  -85,  -88,  -94,  -97, -104,
+     -112, -999, -999, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -36,  -36,  -36,  -36,  -36,  -36,  -36,  -36,
+     -39,  -41,  -42,  -42,  -39,  -38,  -41,  -43,
+     -52,  -44,  -40,  -39,  -37,  -37,  -40,  -47,
+     -54,  -50,  -48,  -50,  -55,  -61,  -59,  -62,
+     -66,  -66,  -66,  -69,  -69,  -73,  -74,  -74,
+     -75,  -77,  -79,  -82,  -87,  -91,  -95, -100,
+     -108, -115, -999, -999, -999, -999, -999, -999},
+   { -28,  -26,  -24,  -22,  -20,  -20,  -23,  -29,
+     -30,  -31,  -28,  -27,  -28,  -28,  -28,  -35,
+     -40,  -33,  -32,  -29,  -30,  -30,  -30,  -37,
+     -45,  -41,  -37,  -38,  -45,  -47,  -47,  -48,
+     -53,  -49,  -48,  -50,  -49,  -49,  -51,  -52,
+     -58,  -56,  -57,  -56,  -60,  -61,  -62,  -70,
+     -72,  -74,  -78,  -83,  -88,  -93, -100, -106}},
+  /* 177 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -110, -105, -100,  -95,  -91,  -87,  -83,
+    -80,  -78,  -76,  -78,  -78,  -81,  -83,  -85,
+    -86,  -85,  -86,  -87,  -90,  -97, -107, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -110, -105, -100,  -95,  -90,
+    -85,  -81,  -77,  -73,  -70,  -67,  -67,  -68,
+    -75,  -73,  -70,  -69,  -70,  -72,  -75,  -79,
+    -84,  -83,  -84,  -86,  -88,  -89,  -89,  -93,
+    -98, -105, -112, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-105, -100,  -95,  -90,  -85,  -80,  -76,  -71,
+    -68,  -68,  -65,  -63,  -63,  -62,  -62,  -64,
+    -65,  -64,  -61,  -62,  -63,  -64,  -66,  -68,
+    -73,  -73,  -74,  -75,  -76,  -81,  -83,  -85,
+    -88,  -89,  -92,  -95, -100, -108, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   { -80,  -75,  -71,  -68,  -65,  -63,  -62,  -61,
+     -61,  -61,  -61,  -59,  -56,  -57,  -53,  -50,
+     -58,  -52,  -50,  -50,  -52,  -53,  -54,  -58,
+     -67,  -63,  -67,  -68,  -72,  -75,  -78,  -80,
+     -81,  -81,  -82,  -85,  -89,  -90,  -93,  -97,
+     -101, -107, -114, -999, -999, -999, -999, -999,
+     -999, -999, -999, -999, -999, -999, -999, -999},
+   { -65,  -61,  -59,  -57,  -56,  -55,  -55,  -56,
+     -56,  -57,  -55,  -53,  -52,  -47,  -44,  -44,
+     -50,  -44,  -41,  -39,  -39,  -42,  -40,  -46,
+     -51,  -49,  -50,  -53,  -54,  -63,  -60,  -61,
+     -62,  -66,  -66,  -66,  -70,  -73,  -74,  -75,
+     -76,  -75,  -79,  -85,  -89,  -91,  -96, -102,
+     -110, -999, -999, -999, -999, -999, -999, -999},
+   { -52,  -50,  -49,  -49,  -48,  -48,  -48,  -49,
+     -50,  -50,  -49,  -46,  -43,  -39,  -35,  -33,
+     -38,  -36,  -32,  -29,  -32,  -32,  -32,  -35,
+     -44,  -39,  -38,  -38,  -46,  -50,  -45,  -46,
+     -53,  -50,  -50,  -50,  -54,  -54,  -53,  -53,
+     -56,  -57,  -59,  -66,  -70,  -72,  -74,  -79,
+     -83,  -85,  -90, -97, -114, -999, -999, -999}},
+  /* 250 Hz */
+  {{-999, -999, -999, -999, -999, -999, -110, -105,
+    -100,  -95,  -90,  -86,  -80,  -75,  -75,  -79,
+    -80,  -79,  -80,  -81,  -82,  -88,  -95, -103,
+    -110, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -108, -103,  -98,  -93,
+    -88,  -83,  -79,  -78,  -75,  -71,  -67,  -68,
+    -73,  -73,  -72,  -73,  -75,  -77,  -80,  -82,
+    -88,  -93, -100, -107, -114, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -110, -105, -101,  -96,  -90,
+    -86,  -81,  -77,  -73,  -69,  -66,  -61,  -62,
+    -66,  -64,  -62,  -65,  -66,  -70,  -72,  -76,
+    -81,  -80,  -84,  -90,  -95, -102, -110, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -107, -103,  -97,  -92,  -88,
+    -83,  -79,  -74,  -70,  -66,  -59,  -53,  -58,
+    -62,  -55,  -54,  -54,  -54,  -58,  -61,  -62,
+    -72,  -70,  -72,  -75,  -78,  -80,  -81,  -80,
+    -83,  -83,  -88,  -93, -100, -107, -115, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -105, -100,  -95,  -90,  -85,
+    -80,  -75,  -70,  -66,  -62,  -56,  -48,  -44,
+    -48,  -46,  -46,  -43,  -46,  -48,  -48,  -51,
+    -58,  -58,  -59,  -60,  -62,  -62,  -61,  -61,
+    -65,  -64,  -65,  -68,  -70,  -74,  -75,  -78,
+    -81,  -86,  -95, -110, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999,  -999, -105, -100,  -95,  -90,  -85,  -80,
+    -75,  -70,  -65,  -61,  -55,  -49,  -39,  -33,
+    -40,  -35,  -32,  -38,  -40,  -33,  -35,  -37,
+    -46,  -41,  -45,  -44,  -46,  -42,  -45,  -46,
+    -52,  -50,  -50,  -50,  -54,  -54,  -55,  -57,
+    -62,  -64,  -66,  -68,  -70,  -76,  -81,  -90,
+    -100, -110, -999, -999, -999, -999, -999, -999}},
+  /* 354 hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -105,  -98,  -90,  -85,  -82,  -83,  -80,  -78,
+    -84,  -79,  -80,  -83,  -87,  -89,  -91,  -93,
+    -99, -106, -117, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -105,  -98,  -90,  -85,  -80,  -75,  -70,  -68,
+    -74,  -72,  -74,  -77,  -80,  -82,  -85,  -87,
+    -92,  -89,  -91,  -95, -100, -106, -112, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -105,  -98,  -90,  -83,  -75,  -71,  -63,  -64,
+    -67,  -62,  -64,  -67,  -70,  -73,  -77,  -81,
+    -84,  -83,  -85,  -89,  -90,  -93,  -98, -104,
+    -109, -114, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -103,  -96,  -88,  -81,  -75,  -68,  -58,  -54,
+    -56,  -54,  -56,  -56,  -58,  -60,  -63,  -66,
+    -74,  -69,  -72,  -72,  -75,  -74,  -77,  -81,
+    -81,  -82,  -84,  -87,  -93,  -96,  -99, -104,
+    -110, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -108, -102,  -96,
+    -91,  -85,  -80,  -74,  -68,  -60,  -51,  -46,
+    -48,  -46,  -43,  -45,  -47,  -47,  -49,  -48,
+    -56,  -53,  -55,  -58,  -57,  -63,  -58,  -60,
+    -66,  -64,  -67,  -70,  -70,  -74,  -77,  -84,
+    -86,  -89,  -91,  -93,  -94, -101, -109, -118,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -108, -103,  -98,  -93,  -88,
+    -83,  -78,  -73,  -68,  -60,  -53,  -44,  -35,
+    -38,  -38,  -34,  -34,  -36,  -40,  -41,  -44,
+    -51,  -45,  -46,  -47,  -46,  -54,  -50,  -49,
+    -50,  -50,  -50,  -51,  -54,  -57,  -58,  -60,
+    -66,  -66,  -66,  -64,  -65,  -68,  -77,  -82,
+    -87,  -95, -110, -999, -999, -999, -999, -999}},
+  /* 500 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -107, -102,  -97,  -92,  -87,  -83,  -78,  -75,
+    -82,  -79,  -83,  -85,  -89,  -92,  -95,  -98,
+    -101, -105, -109, -113, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -106,
+    -100,  -95,  -90,  -86,  -81,  -78,  -74,  -69,
+    -74,  -74,  -76,  -79,  -83,  -84,  -86,  -89,
+    -92,  -97,  -93, -100, -103, -107, -110, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -106, -100,
+    -95, -90, -87, -83, -80, -75, -69, -60,
+    -66, -66, -68, -70, -74, -78, -79, -81,
+    -81, -83, -84, -87, -93, -96, -99, -103,
+    -107, -110, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -108, -103, -98,
+    -93, -89, -85, -82, -78, -71, -62, -55,
+    -58, -58, -54, -54, -55, -59, -61, -62,
+    -70, -66, -66, -67, -70, -72, -75, -78,
+    -84, -84, -84, -88, -91, -90, -95, -98,
+    -102, -103, -106, -110, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -108, -103,  -98,  -94,
+    -90,  -87,  -82,  -79,  -73,  -67,  -58,  -47,
+    -50,  -45,  -41,  -45,  -48,  -44,  -44,  -49,
+    -54,  -51,  -48,  -47,  -49,  -50,  -51,  -57,
+    -58,  -60,  -63,  -69,  -70,  -69,  -71,  -74,
+    -78,  -82,  -90,  -95, -101, -105, -110, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -105, -101, -97, -93, -90,
+    -85, -80, -77, -72, -65, -56, -48, -37,
+    -40, -36, -34, -40, -50, -47, -38, -41,
+    -47, -38, -35, -39, -38, -43, -40, -45,
+    -50, -45, -44, -47, -50, -55, -48, -48,
+    -52, -66, -70, -76, -82, -90, -97, -105,
+    -110, -999, -999, -999, -999, -999, -999, -999}},
+  /* 707 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -108, -103,  -98,  -93,  -86,  -79,  -76,
+    -83,  -81,  -85,  -87,  -89,  -93,  -98, -102,
+    -107, -112, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -108, -103,  -98,  -93,  -86,  -79,  -71,
+    -77,  -74,  -77,  -79,  -81,  -84,  -85,  -90,
+    -92,  -93,  -92,  -98, -101, -108, -112, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -108, -103,  -98,  -93,  -87,  -78,  -68,  -65,
+    -66,  -62,  -65,  -67,  -70,  -73,  -75,  -78,
+    -82,  -82,  -83,  -84,  -91,  -93,  -98, -102,
+    -106, -110, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -105, -100, -95, -90, -82, -74, -62, -57,
+    -58, -56, -51, -52, -52, -54, -54, -58,
+    -66, -59, -60, -63, -66, -69, -73, -79,
+    -83, -84, -80, -81, -81, -82, -88, -92,
+    -98, -105, -113, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -107,
+    -102,  -97,  -92,  -84,  -79,  -69,  -57,  -47,
+    -52,  -47,  -44,  -45,  -50,  -52,  -42,  -42,
+    -53,  -43,  -43,  -48,  -51,  -56,  -55,  -52,
+    -57,  -59,  -61,  -62,  -67,  -71,  -78,  -83,
+    -86,  -94,  -98, -103, -110, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -105, -100,
+    -95,  -90,  -84,  -78,  -70,  -61,  -51,  -41,
+    -40,  -38,  -40,  -46,  -52,  -51,  -41,  -40,
+    -46,  -40,  -38,  -38,  -41,  -46,  -41,  -46,
+    -47,  -43,  -43,  -45,  -41,  -45,  -56,  -67,
+    -68,  -83,  -87,  -90,  -95, -102, -107, -113,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 1000 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -109, -105, -101,  -96,  -91,  -84,  -77,
+    -82,  -82,  -85,  -89,  -94, -100, -106, -110,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -106, -103,  -98,  -92,  -85,  -80,  -71,
+    -75,  -72,  -76,  -80,  -84,  -86,  -89,  -93,
+    -100, -107, -113, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -107,
+    -104, -101,  -97,  -92,  -88,  -84,  -80,  -64,
+    -66,  -63,  -64,  -66,  -69,  -73,  -77,  -83,
+    -83,  -86,  -91,  -98, -104, -111, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -107,
+    -104, -101,  -97,  -92,  -90,  -84,  -74,  -57,
+    -58,  -52,  -55,  -54,  -50,  -52,  -50,  -52,
+    -63,  -62,  -69,  -76,  -77,  -78,  -78,  -79,
+    -82,  -88,  -94, -100, -106, -111, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -106, -102,
+    -98,  -95,  -90,  -85,  -83,  -78,  -70,  -50,
+    -50,  -41,  -44,  -49,  -47,  -50,  -50,  -44,
+    -55,  -46,  -47,  -48,  -48,  -54,  -49,  -49,
+    -58,  -62,  -71,  -81,  -87,  -92,  -97, -102,
+    -108, -114, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -106, -102,
+    -98,  -95,  -90,  -85,  -83,  -78,  -70,  -45,
+    -43,  -41,  -47,  -50,  -51,  -50,  -49,  -45,
+    -47,  -41,  -44,  -41,  -39,  -43,  -38,  -37,
+    -40,  -41,  -44,  -50,  -58,  -65,  -73,  -79,
+    -85,  -92,  -97, -101, -105, -109, -113, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 1414 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -107, -100,  -95,  -87,  -81,
+    -85,  -83,  -88,  -93, -100, -107, -114, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -107, -101,  -95,  -88,  -83,  -76,
+    -73,  -72,  -79,  -84,  -90,  -95, -100, -105,
+    -110, -115, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -104,  -98,  -92,  -87,  -81,  -70,
+    -65,  -62,  -67,  -71,  -74,  -80,  -85,  -91,
+    -95,  -99, -103, -108, -111, -114, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -103,  -97,  -90,  -85,  -76,  -60,
+    -56,  -54,  -60,  -62,  -61,  -56,  -63,  -65,
+    -73,  -74,  -77,  -75,  -78,  -81,  -86,  -87,
+    -88,  -91,  -94,  -98, -103, -110, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -105,
+    -100,  -97,  -92,  -86,  -81,  -79,  -70,  -57,
+    -51,  -47,  -51,  -58,  -60,  -56,  -53,  -50,
+    -58,  -52,  -50,  -50,  -53,  -55,  -64,  -69,
+    -71,  -85,  -82,  -78,  -81,  -85,  -95, -102,
+    -112, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -105,
+    -100,  -97,  -92,  -85,  -83,  -79,  -72,  -49,
+    -40,  -43,  -43,  -54,  -56,  -51,  -50,  -40,
+    -43,  -38,  -36,  -35,  -37,  -38,  -37,  -44,
+    -54,  -60,  -57,  -60,  -70,  -75,  -84,  -92,
+    -103, -112, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 2000 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -102,  -95,  -89,  -82,
+    -83,  -84,  -90,  -92,  -99, -107, -113, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -107, -101,  -95,  -89,  -83,  -72,
+    -74,  -78,  -85,  -88,  -88,  -90,  -92,  -98,
+    -105, -111, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -109, -103, -97, -93, -87, -81, -70,
+    -70, -67, -75, -73, -76, -79, -81, -83,
+    -88, -89, -97, -103, -110, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -107, -100,  -94,  -88,  -83,  -75,  -63,
+    -59,  -59,  -63,  -66,  -60,  -62,  -67,  -67,
+    -77,  -76,  -81,  -88,  -86,  -92,  -96, -102,
+    -109, -116, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -105,  -98,  -92,  -86,  -81,  -73,  -56,
+    -52,  -47,  -55,  -60,  -58,  -52,  -51,  -45,
+    -49,  -50,  -53,  -54,  -61,  -71,  -70,  -69,
+    -78,  -79,  -87,  -90,  -96, -104, -112, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -103,  -96,  -90,  -86,  -78,  -70,  -51,
+    -42,  -47,  -48,  -55,  -54,  -54,  -53,  -42,
+    -35,  -28,  -33,  -38,  -37,  -44,  -47,  -49,
+    -54,  -63,  -68,  -78,  -82,  -89,  -94,  -99,
+    -104, -109, -114, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 2828 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -110, -100,  -90,  -79,
+    -85,  -81,  -82,  -82,  -89,  -94,  -99, -103,
+    -109, -115, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -105,  -97,  -85,  -72,
+    -74,  -70,  -70,  -70,  -76,  -85,  -91,  -93,
+    -97, -103, -109, -115, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -112,  -93,  -81,  -68,
+    -62,  -60,  -60,  -57,  -63,  -70,  -77,  -82,
+    -90,  -93,  -98, -104, -109, -113, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -113, -100,  -93,  -84,  -63,
+    -58,  -48,  -53,  -54,  -52,  -52,  -57,  -64,
+    -66,  -76,  -83,  -81,  -85,  -85,  -90,  -95,
+    -98, -101, -103, -106, -108, -111, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -105,  -95,  -86,  -74,  -53,
+    -50,  -38,  -43,  -49,  -43,  -42,  -39,  -39,
+    -46,  -52,  -57,  -56,  -72,  -69,  -74,  -81,
+    -87,  -92,  -94,  -97,  -99, -102, -105, -108,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -108,  -99,  -90,  -76,  -66,  -45,
+    -43,  -41,  -44,  -47,  -43,  -47,  -40,  -30,
+    -31,  -31,  -39,  -33,  -40,  -41,  -43,  -53,
+    -59,  -70,  -73,  -77,  -79,  -82,  -84,  -87,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 4000 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110,  -91,  -76,
+    -75,  -85,  -93,  -98, -104, -110, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110,  -91,  -70,
+    -70,  -75,  -86,  -89,  -94,  -98, -101, -106,
+    -110, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -110,  -95,  -80,  -60,
+    -65,  -64,  -74,  -83,  -88,  -91,  -95,  -99,
+    -103, -107, -110, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -110,  -95,  -80,  -58,
+    -55,  -49,  -66,  -68,  -71,  -78,  -78,  -80,
+    -88,  -85,  -89,  -97, -100, -105, -110, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -110,  -95,  -80,  -53,
+    -52,  -41,  -59,  -59,  -49,  -58,  -56,  -63,
+    -86,  -79,  -90,  -93,  -98, -103, -107, -112,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110,  -97,  -91,  -73,  -45,
+    -40,  -33,  -53,  -61,  -49,  -54,  -50,  -50,
+    -60,  -52,  -67,  -74,  -81,  -92,  -96, -100,
+    -105, -110, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 5657 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -113, -106,  -99,  -92,  -77,
+    -80,  -88,  -97, -106, -115, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -116, -109, -102,  -95,  -89,  -74,
+    -72,  -88,  -87,  -95, -102, -109, -116, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -116, -109, -102,  -95,  -89,  -75,
+    -66,  -74,  -77,  -78,  -86,  -87,  -90,  -96,
+    -105, -115, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -115, -108, -101,  -94,  -88,  -66,
+    -56,  -61,  -70,  -65,  -78,  -72,  -83,  -84,
+    -93,  -98, -105, -110, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -110, -105,  -95,  -89,  -82,  -57,
+    -52,  -52,  -59,  -56,  -59,  -58,  -69,  -67,
+    -88,  -82,  -82,  -89,  -94, -100, -108, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -110, -101,  -96,  -90,  -83,  -77,  -54,
+    -43,  -38,  -50,  -48,  -52,  -48,  -42,  -42,
+    -51,  -52,  -53,  -59,  -65,  -71,  -78,  -85,
+    -95, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 8000 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -120, -105,  -86,  -68,
+    -78,  -79,  -90, -100, -110, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -120, -105,  -86,  -66,
+    -73,  -77,  -88,  -96, -105, -115, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -120, -105,  -92,  -80,  -61,
+    -64,  -68,  -80,  -87,  -92, -100, -110, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -120, -104,  -91,  -79,  -52,
+    -60,  -54,  -64,  -69,  -77,  -80,  -82,  -84,
+    -85,  -87,  -88,  -90, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -118, -100,  -87,  -77,  -49,
+    -50,  -44,  -58,  -61,  -61,  -67,  -65,  -62,
+    -62,  -62,  -65,  -68, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -115,  -98,  -84,  -62,  -49,
+    -44,  -38,  -46,  -49,  -49,  -46,  -39,  -37,
+    -39,  -40,  -42,  -43, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 11314 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110,  -88,  -74,
+    -77,  -82,  -82,  -85,  -90,  -94,  -99, -104,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110,  -88,  -66,
+    -70,  -81,  -80,  -81,  -84,  -88,  -91,  -93,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110,  -88,  -61,
+    -63,  -70,  -71,  -74,  -77,  -80,  -83,  -85,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -110, -86, -62,
+    -63,  -62,  -62,  -58,  -52,  -50,  -50,  -52,
+    -54, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -118, -108,  -84,  -53,
+    -50,  -50,  -50,  -55,  -47,  -45,  -40,  -40,
+    -40, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -118, -100,  -73,  -43,
+    -37,  -42,  -43,  -53,  -38,  -37,  -35,  -35,
+    -38, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}},
+  /* 16000 Hz */
+  {{-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -91,  -84,  -74,
+    -80,  -80,  -80,  -80,  -80, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -91,  -84,  -74,
+    -68,  -68,  -68,  -68,  -68, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -86,  -78,  -70,
+    -60,  -45,  -30,  -21, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -87,  -78,  -67,
+    -48,  -38,  -29,  -21, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -86,  -69,  -56,
+    -45,  -35,  -33,  -29, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999},
+   {-999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -110, -100,  -83,  -71,  -48,
+    -27,  -38,  -37,  -34, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999,
+    -999, -999, -999, -999, -999, -999, -999, -999}}
+};
+
+#endif
diff --git a/vorbis/lib/mdct.c b/vorbis/lib/mdct.c
new file mode 100644 (file)
index 0000000..f3f1ed8
--- /dev/null
@@ -0,0 +1,562 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: normalized modified discrete cosine transform
+           power of two length transform only [64 <= n ]
+
+ Original algorithm adapted long ago from _The use of multirate filter
+ banks for coding of high quality digital audio_, by T. Sporer,
+ K. Brandenburg and B. Edler, collection of the European Signal
+ Processing Conference (EUSIPCO), Amsterdam, June 1992, Vol.1, pp
+ 211-214
+
+ The below code implements an algorithm that no longer looks much like
+ that presented in the paper, but the basic structure remains if you
+ dig deep enough to see it.
+
+ This module DOES NOT INCLUDE code to generate/apply the window
+ function.  Everybody has their own weird favorite including me... I
+ happen to like the properties of y=sin(.5PI*sin^2(x)), but others may
+ vehemently disagree.
+
+ ********************************************************************/
+
+/* this can also be run as an integer transform by uncommenting a
+   define in mdct.h; the integerization is a first pass and although
+   it's likely stable for Vorbis, the dynamic range is constrained and
+   roundoff isn't done (so it's noisy).  Consider it functional, but
+   only a starting point.  There's no point on a machine with an FPU */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include "vorbis/codec.h"
+#include "mdct.h"
+#include "os.h"
+#include "misc.h"
+
+/* build lookups for trig functions; also pre-figure scaling and
+   some window function algebra. */
+
+void mdct_init(mdct_lookup *lookup,int n){
+  int   *bitrev=_ogg_malloc(sizeof(*bitrev)*(n/4));
+  DATA_TYPE *T=_ogg_malloc(sizeof(*T)*(n+n/4));
+
+  int i;
+  int n2=n>>1;
+  int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
+  lookup->n=n;
+  lookup->trig=T;
+  lookup->bitrev=bitrev;
+
+/* trig lookups... */
+
+  for(i=0;i<n/4;i++){
+    T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
+    T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
+    T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
+    T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
+  }
+  for(i=0;i<n/8;i++){
+    T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
+    T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
+  }
+
+  /* bitreverse lookup... */
+
+  {
+    int mask=(1<<(log2n-1))-1,i,j;
+    int msb=1<<(log2n-2);
+    for(i=0;i<n/8;i++){
+      int acc=0;
+      for(j=0;msb>>j;j++)
+        if((msb>>j)&i)acc|=1<<j;
+      bitrev[i*2]=((~acc)&mask)-1;
+      bitrev[i*2+1]=acc;
+
+    }
+  }
+  lookup->scale=FLOAT_CONV(4.f/n);
+}
+
+/* 8 point butterfly (in place, 4 register) */
+STIN void mdct_butterfly_8(DATA_TYPE *x){
+  REG_TYPE r0   = x[6] + x[2];
+  REG_TYPE r1   = x[6] - x[2];
+  REG_TYPE r2   = x[4] + x[0];
+  REG_TYPE r3   = x[4] - x[0];
+
+           x[6] = r0   + r2;
+           x[4] = r0   - r2;
+
+           r0   = x[5] - x[1];
+           r2   = x[7] - x[3];
+           x[0] = r1   + r0;
+           x[2] = r1   - r0;
+
+           r0   = x[5] + x[1];
+           r1   = x[7] + x[3];
+           x[3] = r2   + r3;
+           x[1] = r2   - r3;
+           x[7] = r1   + r0;
+           x[5] = r1   - r0;
+
+}
+
+/* 16 point butterfly (in place, 4 register) */
+STIN void mdct_butterfly_16(DATA_TYPE *x){
+  REG_TYPE r0     = x[1]  - x[9];
+  REG_TYPE r1     = x[0]  - x[8];
+
+           x[8]  += x[0];
+           x[9]  += x[1];
+           x[0]   = MULT_NORM((r0   + r1) * cPI2_8);
+           x[1]   = MULT_NORM((r0   - r1) * cPI2_8);
+
+           r0     = x[3]  - x[11];
+           r1     = x[10] - x[2];
+           x[10] += x[2];
+           x[11] += x[3];
+           x[2]   = r0;
+           x[3]   = r1;
+
+           r0     = x[12] - x[4];
+           r1     = x[13] - x[5];
+           x[12] += x[4];
+           x[13] += x[5];
+           x[4]   = MULT_NORM((r0   - r1) * cPI2_8);
+           x[5]   = MULT_NORM((r0   + r1) * cPI2_8);
+
+           r0     = x[14] - x[6];
+           r1     = x[15] - x[7];
+           x[14] += x[6];
+           x[15] += x[7];
+           x[6]  = r0;
+           x[7]  = r1;
+
+           mdct_butterfly_8(x);
+           mdct_butterfly_8(x+8);
+}
+
+/* 32 point butterfly (in place, 4 register) */
+STIN void mdct_butterfly_32(DATA_TYPE *x){
+  REG_TYPE r0     = x[30] - x[14];
+  REG_TYPE r1     = x[31] - x[15];
+
+           x[30] +=         x[14];
+           x[31] +=         x[15];
+           x[14]  =         r0;
+           x[15]  =         r1;
+
+           r0     = x[28] - x[12];
+           r1     = x[29] - x[13];
+           x[28] +=         x[12];
+           x[29] +=         x[13];
+           x[12]  = MULT_NORM( r0 * cPI1_8  -  r1 * cPI3_8 );
+           x[13]  = MULT_NORM( r0 * cPI3_8  +  r1 * cPI1_8 );
+
+           r0     = x[26] - x[10];
+           r1     = x[27] - x[11];
+           x[26] +=         x[10];
+           x[27] +=         x[11];
+           x[10]  = MULT_NORM(( r0  - r1 ) * cPI2_8);
+           x[11]  = MULT_NORM(( r0  + r1 ) * cPI2_8);
+
+           r0     = x[24] - x[8];
+           r1     = x[25] - x[9];
+           x[24] += x[8];
+           x[25] += x[9];
+           x[8]   = MULT_NORM( r0 * cPI3_8  -  r1 * cPI1_8 );
+           x[9]   = MULT_NORM( r1 * cPI3_8  +  r0 * cPI1_8 );
+
+           r0     = x[22] - x[6];
+           r1     = x[7]  - x[23];
+           x[22] += x[6];
+           x[23] += x[7];
+           x[6]   = r1;
+           x[7]   = r0;
+
+           r0     = x[4]  - x[20];
+           r1     = x[5]  - x[21];
+           x[20] += x[4];
+           x[21] += x[5];
+           x[4]   = MULT_NORM( r1 * cPI1_8  +  r0 * cPI3_8 );
+           x[5]   = MULT_NORM( r1 * cPI3_8  -  r0 * cPI1_8 );
+
+           r0     = x[2]  - x[18];
+           r1     = x[3]  - x[19];
+           x[18] += x[2];
+           x[19] += x[3];
+           x[2]   = MULT_NORM(( r1  + r0 ) * cPI2_8);
+           x[3]   = MULT_NORM(( r1  - r0 ) * cPI2_8);
+
+           r0     = x[0]  - x[16];
+           r1     = x[1]  - x[17];
+           x[16] += x[0];
+           x[17] += x[1];
+           x[0]   = MULT_NORM( r1 * cPI3_8  +  r0 * cPI1_8 );
+           x[1]   = MULT_NORM( r1 * cPI1_8  -  r0 * cPI3_8 );
+
+           mdct_butterfly_16(x);
+           mdct_butterfly_16(x+16);
+
+}
+
+/* N point first stage butterfly (in place, 2 register) */
+STIN void mdct_butterfly_first(DATA_TYPE *T,
+                                        DATA_TYPE *x,
+                                        int points){
+
+  DATA_TYPE *x1        = x          + points      - 8;
+  DATA_TYPE *x2        = x          + (points>>1) - 8;
+  REG_TYPE   r0;
+  REG_TYPE   r1;
+
+  do{
+
+               r0      = x1[6]      -  x2[6];
+               r1      = x1[7]      -  x2[7];
+               x1[6]  += x2[6];
+               x1[7]  += x2[7];
+               x2[6]   = MULT_NORM(r1 * T[1]  +  r0 * T[0]);
+               x2[7]   = MULT_NORM(r1 * T[0]  -  r0 * T[1]);
+
+               r0      = x1[4]      -  x2[4];
+               r1      = x1[5]      -  x2[5];
+               x1[4]  += x2[4];
+               x1[5]  += x2[5];
+               x2[4]   = MULT_NORM(r1 * T[5]  +  r0 * T[4]);
+               x2[5]   = MULT_NORM(r1 * T[4]  -  r0 * T[5]);
+
+               r0      = x1[2]      -  x2[2];
+               r1      = x1[3]      -  x2[3];
+               x1[2]  += x2[2];
+               x1[3]  += x2[3];
+               x2[2]   = MULT_NORM(r1 * T[9]  +  r0 * T[8]);
+               x2[3]   = MULT_NORM(r1 * T[8]  -  r0 * T[9]);
+
+               r0      = x1[0]      -  x2[0];
+               r1      = x1[1]      -  x2[1];
+               x1[0]  += x2[0];
+               x1[1]  += x2[1];
+               x2[0]   = MULT_NORM(r1 * T[13] +  r0 * T[12]);
+               x2[1]   = MULT_NORM(r1 * T[12] -  r0 * T[13]);
+
+    x1-=8;
+    x2-=8;
+    T+=16;
+
+  }while(x2>=x);
+}
+
+/* N/stage point generic N stage butterfly (in place, 2 register) */
+STIN void mdct_butterfly_generic(DATA_TYPE *T,
+                                          DATA_TYPE *x,
+                                          int points,
+                                          int trigint){
+
+  DATA_TYPE *x1        = x          + points      - 8;
+  DATA_TYPE *x2        = x          + (points>>1) - 8;
+  REG_TYPE   r0;
+  REG_TYPE   r1;
+
+  do{
+
+               r0      = x1[6]      -  x2[6];
+               r1      = x1[7]      -  x2[7];
+               x1[6]  += x2[6];
+               x1[7]  += x2[7];
+               x2[6]   = MULT_NORM(r1 * T[1]  +  r0 * T[0]);
+               x2[7]   = MULT_NORM(r1 * T[0]  -  r0 * T[1]);
+
+               T+=trigint;
+
+               r0      = x1[4]      -  x2[4];
+               r1      = x1[5]      -  x2[5];
+               x1[4]  += x2[4];
+               x1[5]  += x2[5];
+               x2[4]   = MULT_NORM(r1 * T[1]  +  r0 * T[0]);
+               x2[5]   = MULT_NORM(r1 * T[0]  -  r0 * T[1]);
+
+               T+=trigint;
+
+               r0      = x1[2]      -  x2[2];
+               r1      = x1[3]      -  x2[3];
+               x1[2]  += x2[2];
+               x1[3]  += x2[3];
+               x2[2]   = MULT_NORM(r1 * T[1]  +  r0 * T[0]);
+               x2[3]   = MULT_NORM(r1 * T[0]  -  r0 * T[1]);
+
+               T+=trigint;
+
+               r0      = x1[0]      -  x2[0];
+               r1      = x1[1]      -  x2[1];
+               x1[0]  += x2[0];
+               x1[1]  += x2[1];
+               x2[0]   = MULT_NORM(r1 * T[1]  +  r0 * T[0]);
+               x2[1]   = MULT_NORM(r1 * T[0]  -  r0 * T[1]);
+
+               T+=trigint;
+    x1-=8;
+    x2-=8;
+
+  }while(x2>=x);
+}
+
+STIN void mdct_butterflies(mdct_lookup *init,
+                             DATA_TYPE *x,
+                             int points){
+
+  DATA_TYPE *T=init->trig;
+  int stages=init->log2n-5;
+  int i,j;
+
+  if(--stages>0){
+    mdct_butterfly_first(T,x,points);
+  }
+
+  for(i=1;--stages>0;i++){
+    for(j=0;j<(1<<i);j++)
+      mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
+  }
+
+  for(j=0;j<points;j+=32)
+    mdct_butterfly_32(x+j);
+
+}
+
+void mdct_clear(mdct_lookup *l){
+  if(l){
+    if(l->trig)_ogg_free(l->trig);
+    if(l->bitrev)_ogg_free(l->bitrev);
+    memset(l,0,sizeof(*l));
+  }
+}
+
+STIN void mdct_bitreverse(mdct_lookup *init,
+                            DATA_TYPE *x){
+  int        n       = init->n;
+  int       *bit     = init->bitrev;
+  DATA_TYPE *w0      = x;
+  DATA_TYPE *w1      = x = w0+(n>>1);
+  DATA_TYPE *T       = init->trig+n;
+
+  do{
+    DATA_TYPE *x0    = x+bit[0];
+    DATA_TYPE *x1    = x+bit[1];
+
+    REG_TYPE  r0     = x0[1]  - x1[1];
+    REG_TYPE  r1     = x0[0]  + x1[0];
+    REG_TYPE  r2     = MULT_NORM(r1     * T[0]   + r0 * T[1]);
+    REG_TYPE  r3     = MULT_NORM(r1     * T[1]   - r0 * T[0]);
+
+              w1    -= 4;
+
+              r0     = HALVE(x0[1] + x1[1]);
+              r1     = HALVE(x0[0] - x1[0]);
+
+              w0[0]  = r0     + r2;
+              w1[2]  = r0     - r2;
+              w0[1]  = r1     + r3;
+              w1[3]  = r3     - r1;
+
+              x0     = x+bit[2];
+              x1     = x+bit[3];
+
+              r0     = x0[1]  - x1[1];
+              r1     = x0[0]  + x1[0];
+              r2     = MULT_NORM(r1     * T[2]   + r0 * T[3]);
+              r3     = MULT_NORM(r1     * T[3]   - r0 * T[2]);
+
+              r0     = HALVE(x0[1] + x1[1]);
+              r1     = HALVE(x0[0] - x1[0]);
+
+              w0[2]  = r0     + r2;
+              w1[0]  = r0     - r2;
+              w0[3]  = r1     + r3;
+              w1[1]  = r3     - r1;
+
+              T     += 4;
+              bit   += 4;
+              w0    += 4;
+
+  }while(w0<w1);
+}
+
+void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
+  int n=init->n;
+  int n2=n>>1;
+  int n4=n>>2;
+
+  /* rotate */
+
+  DATA_TYPE *iX = in+n2-7;
+  DATA_TYPE *oX = out+n2+n4;
+  DATA_TYPE *T  = init->trig+n4;
+
+  do{
+    oX         -= 4;
+    oX[0]       = MULT_NORM(-iX[2] * T[3] - iX[0]  * T[2]);
+    oX[1]       = MULT_NORM (iX[0] * T[3] - iX[2]  * T[2]);
+    oX[2]       = MULT_NORM(-iX[6] * T[1] - iX[4]  * T[0]);
+    oX[3]       = MULT_NORM (iX[4] * T[1] - iX[6]  * T[0]);
+    iX         -= 8;
+    T          += 4;
+  }while(iX>=in);
+
+  iX            = in+n2-8;
+  oX            = out+n2+n4;
+  T             = init->trig+n4;
+
+  do{
+    T          -= 4;
+    oX[0]       =  MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
+    oX[1]       =  MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
+    oX[2]       =  MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
+    oX[3]       =  MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
+    iX         -= 8;
+    oX         += 4;
+  }while(iX>=in);
+
+  mdct_butterflies(init,out+n2,n2);
+  mdct_bitreverse(init,out);
+
+  /* roatate + window */
+
+  {
+    DATA_TYPE *oX1=out+n2+n4;
+    DATA_TYPE *oX2=out+n2+n4;
+    DATA_TYPE *iX =out;
+    T             =init->trig+n2;
+
+    do{
+      oX1-=4;
+
+      oX1[3]  =  MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
+      oX2[0]  = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
+
+      oX1[2]  =  MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
+      oX2[1]  = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
+
+      oX1[1]  =  MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
+      oX2[2]  = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
+
+      oX1[0]  =  MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
+      oX2[3]  = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
+
+      oX2+=4;
+      iX    +=   8;
+      T     +=   8;
+    }while(iX<oX1);
+
+    iX=out+n2+n4;
+    oX1=out+n4;
+    oX2=oX1;
+
+    do{
+      oX1-=4;
+      iX-=4;
+
+      oX2[0] = -(oX1[3] = iX[3]);
+      oX2[1] = -(oX1[2] = iX[2]);
+      oX2[2] = -(oX1[1] = iX[1]);
+      oX2[3] = -(oX1[0] = iX[0]);
+
+      oX2+=4;
+    }while(oX2<iX);
+
+    iX=out+n2+n4;
+    oX1=out+n2+n4;
+    oX2=out+n2;
+    do{
+      oX1-=4;
+      oX1[0]= iX[3];
+      oX1[1]= iX[2];
+      oX1[2]= iX[1];
+      oX1[3]= iX[0];
+      iX+=4;
+    }while(oX1>oX2);
+  }
+}
+
+void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
+  int n=init->n;
+  int n2=n>>1;
+  int n4=n>>2;
+  int n8=n>>3;
+  DATA_TYPE *w=alloca(n*sizeof(*w)); /* forward needs working space */
+  DATA_TYPE *w2=w+n2;
+
+  /* rotate */
+
+  /* window + rotate + step 1 */
+
+  REG_TYPE r0;
+  REG_TYPE r1;
+  DATA_TYPE *x0=in+n2+n4;
+  DATA_TYPE *x1=x0+1;
+  DATA_TYPE *T=init->trig+n2;
+
+  int i=0;
+
+  for(i=0;i<n8;i+=2){
+    x0 -=4;
+    T-=2;
+    r0= x0[2] + x1[0];
+    r1= x0[0] + x1[2];
+    w2[i]=   MULT_NORM(r1*T[1] + r0*T[0]);
+    w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
+    x1 +=4;
+  }
+
+  x1=in+1;
+
+  for(;i<n2-n8;i+=2){
+    T-=2;
+    x0 -=4;
+    r0= x0[2] - x1[0];
+    r1= x0[0] - x1[2];
+    w2[i]=   MULT_NORM(r1*T[1] + r0*T[0]);
+    w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
+    x1 +=4;
+  }
+
+  x0=in+n;
+
+  for(;i<n2;i+=2){
+    T-=2;
+    x0 -=4;
+    r0= -x0[2] - x1[0];
+    r1= -x0[0] - x1[2];
+    w2[i]=   MULT_NORM(r1*T[1] + r0*T[0]);
+    w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
+    x1 +=4;
+  }
+
+
+  mdct_butterflies(init,w+n2,n2);
+  mdct_bitreverse(init,w);
+
+  /* roatate + window */
+
+  T=init->trig+n2;
+  x0=out+n2;
+
+  for(i=0;i<n4;i++){
+    x0--;
+    out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
+    x0[0]  =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
+    w+=2;
+    T+=2;
+  }
+}
diff --git a/vorbis/lib/mdct.h b/vorbis/lib/mdct.h
new file mode 100644 (file)
index 0000000..3b8c9ba
--- /dev/null
@@ -0,0 +1,70 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: modified discrete cosine transform prototypes
+
+ ********************************************************************/
+
+#ifndef _OGG_mdct_H_
+#define _OGG_mdct_H_
+
+#include "vorbis/codec.h"
+
+
+
+
+
+/*#define MDCT_INTEGERIZED  <- be warned there could be some hurt left here*/
+#ifdef MDCT_INTEGERIZED
+
+#define DATA_TYPE int
+#define REG_TYPE  register int
+#define TRIGBITS 14
+#define cPI3_8 6270
+#define cPI2_8 11585
+#define cPI1_8 15137
+
+#define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
+#define MULT_NORM(x) ((x)>>TRIGBITS)
+#define HALVE(x) ((x)>>1)
+
+#else
+
+#define DATA_TYPE float
+#define REG_TYPE  float
+#define cPI3_8 .38268343236508977175F
+#define cPI2_8 .70710678118654752441F
+#define cPI1_8 .92387953251128675613F
+
+#define FLOAT_CONV(x) (x)
+#define MULT_NORM(x) (x)
+#define HALVE(x) ((x)*.5f)
+
+#endif
+
+
+typedef struct {
+  int n;
+  int log2n;
+
+  DATA_TYPE *trig;
+  int       *bitrev;
+
+  DATA_TYPE scale;
+} mdct_lookup;
+
+extern void mdct_init(mdct_lookup *lookup,int n);
+extern void mdct_clear(mdct_lookup *l);
+extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
+extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
+
+#endif
diff --git a/vorbis/lib/misc.h b/vorbis/lib/misc.h
new file mode 100644 (file)
index 0000000..1378844
--- /dev/null
@@ -0,0 +1,57 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: miscellaneous prototypes
+
+ ********************************************************************/
+
+#ifndef _V_RANDOM_H_
+#define _V_RANDOM_H_
+#include "vorbis/codec.h"
+
+extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
+extern void _vorbis_block_ripcord(vorbis_block *vb);
+extern int ov_ilog(ogg_uint32_t v);
+
+#ifdef ANALYSIS
+extern int analysis_noisy;
+extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
+                             ogg_int64_t off);
+extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
+                             ogg_int64_t off);
+#endif
+
+#ifdef DEBUG_MALLOC
+
+#define _VDBG_GRAPHFILE "malloc.m"
+#undef _VDBG_GRAPHFILE
+extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
+extern void _VDBG_free(void *ptr,char *file,long line);
+
+#ifndef MISC_C
+#undef _ogg_malloc
+#undef _ogg_calloc
+#undef _ogg_realloc
+#undef _ogg_free
+
+#define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
+#define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
+#define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
+#define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
+#endif
+#endif
+
+#endif
+
+
+
+
diff --git a/vorbis/lib/modes/floor_all.h b/vorbis/lib/modes/floor_all.h
new file mode 100644 (file)
index 0000000..20928aa
--- /dev/null
@@ -0,0 +1,259 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: key floor settings
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "backends.h"
+#include "books/floor/floor_books.h"
+
+static const static_codebook*const _floor_128x4_books[]={
+  &_huff_book_line_128x4_class0,
+  &_huff_book_line_128x4_0sub0,
+  &_huff_book_line_128x4_0sub1,
+  &_huff_book_line_128x4_0sub2,
+  &_huff_book_line_128x4_0sub3,
+};
+static const static_codebook*const _floor_256x4_books[]={
+  &_huff_book_line_256x4_class0,
+  &_huff_book_line_256x4_0sub0,
+  &_huff_book_line_256x4_0sub1,
+  &_huff_book_line_256x4_0sub2,
+  &_huff_book_line_256x4_0sub3,
+};
+static const static_codebook*const _floor_128x7_books[]={
+  &_huff_book_line_128x7_class0,
+  &_huff_book_line_128x7_class1,
+
+  &_huff_book_line_128x7_0sub1,
+  &_huff_book_line_128x7_0sub2,
+  &_huff_book_line_128x7_0sub3,
+  &_huff_book_line_128x7_1sub1,
+  &_huff_book_line_128x7_1sub2,
+  &_huff_book_line_128x7_1sub3,
+};
+static const static_codebook*const _floor_256x7_books[]={
+  &_huff_book_line_256x7_class0,
+  &_huff_book_line_256x7_class1,
+
+  &_huff_book_line_256x7_0sub1,
+  &_huff_book_line_256x7_0sub2,
+  &_huff_book_line_256x7_0sub3,
+  &_huff_book_line_256x7_1sub1,
+  &_huff_book_line_256x7_1sub2,
+  &_huff_book_line_256x7_1sub3,
+};
+static const static_codebook*const _floor_128x11_books[]={
+  &_huff_book_line_128x11_class1,
+  &_huff_book_line_128x11_class2,
+  &_huff_book_line_128x11_class3,
+
+  &_huff_book_line_128x11_0sub0,
+  &_huff_book_line_128x11_1sub0,
+  &_huff_book_line_128x11_1sub1,
+  &_huff_book_line_128x11_2sub1,
+  &_huff_book_line_128x11_2sub2,
+  &_huff_book_line_128x11_2sub3,
+  &_huff_book_line_128x11_3sub1,
+  &_huff_book_line_128x11_3sub2,
+  &_huff_book_line_128x11_3sub3,
+};
+static const static_codebook*const _floor_128x17_books[]={
+  &_huff_book_line_128x17_class1,
+  &_huff_book_line_128x17_class2,
+  &_huff_book_line_128x17_class3,
+
+  &_huff_book_line_128x17_0sub0,
+  &_huff_book_line_128x17_1sub0,
+  &_huff_book_line_128x17_1sub1,
+  &_huff_book_line_128x17_2sub1,
+  &_huff_book_line_128x17_2sub2,
+  &_huff_book_line_128x17_2sub3,
+  &_huff_book_line_128x17_3sub1,
+  &_huff_book_line_128x17_3sub2,
+  &_huff_book_line_128x17_3sub3,
+};
+static const static_codebook*const _floor_256x4low_books[]={
+  &_huff_book_line_256x4low_class0,
+  &_huff_book_line_256x4low_0sub0,
+  &_huff_book_line_256x4low_0sub1,
+  &_huff_book_line_256x4low_0sub2,
+  &_huff_book_line_256x4low_0sub3,
+};
+static const static_codebook*const _floor_1024x27_books[]={
+  &_huff_book_line_1024x27_class1,
+  &_huff_book_line_1024x27_class2,
+  &_huff_book_line_1024x27_class3,
+  &_huff_book_line_1024x27_class4,
+
+  &_huff_book_line_1024x27_0sub0,
+  &_huff_book_line_1024x27_1sub0,
+  &_huff_book_line_1024x27_1sub1,
+  &_huff_book_line_1024x27_2sub0,
+  &_huff_book_line_1024x27_2sub1,
+  &_huff_book_line_1024x27_3sub1,
+  &_huff_book_line_1024x27_3sub2,
+  &_huff_book_line_1024x27_3sub3,
+  &_huff_book_line_1024x27_4sub1,
+  &_huff_book_line_1024x27_4sub2,
+  &_huff_book_line_1024x27_4sub3,
+};
+static const static_codebook*const _floor_2048x27_books[]={
+  &_huff_book_line_2048x27_class1,
+  &_huff_book_line_2048x27_class2,
+  &_huff_book_line_2048x27_class3,
+  &_huff_book_line_2048x27_class4,
+
+  &_huff_book_line_2048x27_0sub0,
+  &_huff_book_line_2048x27_1sub0,
+  &_huff_book_line_2048x27_1sub1,
+  &_huff_book_line_2048x27_2sub0,
+  &_huff_book_line_2048x27_2sub1,
+  &_huff_book_line_2048x27_3sub1,
+  &_huff_book_line_2048x27_3sub2,
+  &_huff_book_line_2048x27_3sub3,
+  &_huff_book_line_2048x27_4sub1,
+  &_huff_book_line_2048x27_4sub2,
+  &_huff_book_line_2048x27_4sub3,
+};
+
+static const static_codebook*const _floor_512x17_books[]={
+  &_huff_book_line_512x17_class1,
+  &_huff_book_line_512x17_class2,
+  &_huff_book_line_512x17_class3,
+
+  &_huff_book_line_512x17_0sub0,
+  &_huff_book_line_512x17_1sub0,
+  &_huff_book_line_512x17_1sub1,
+  &_huff_book_line_512x17_2sub1,
+  &_huff_book_line_512x17_2sub2,
+  &_huff_book_line_512x17_2sub3,
+  &_huff_book_line_512x17_3sub1,
+  &_huff_book_line_512x17_3sub2,
+  &_huff_book_line_512x17_3sub3,
+};
+
+static const static_codebook*const _floor_Xx0_books[]={
+  0
+};
+
+static const static_codebook*const *const _floor_books[11]={
+  _floor_128x4_books,
+  _floor_256x4_books,
+  _floor_128x7_books,
+  _floor_256x7_books,
+  _floor_128x11_books,
+  _floor_128x17_books,
+  _floor_256x4low_books,
+  _floor_1024x27_books,
+  _floor_2048x27_books,
+  _floor_512x17_books,
+  _floor_Xx0_books,
+};
+
+static const vorbis_info_floor1 _floor[11]={
+  /* 0: 128 x 4 */
+  {
+    1,{0},{4},{2},{0},
+    {{1,2,3,4}},
+    4,{0,128, 33,8,16,70},
+
+    60,30,500,   1.,18.,  128
+  },
+  /* 1: 256 x 4 */
+  {
+    1,{0},{4},{2},{0},
+    {{1,2,3,4}},
+    4,{0,256, 66,16,32,140},
+
+    60,30,500,   1.,18.,  256
+  },
+  /* 2: 128 x 7 */
+  {
+    2,{0,1},{3,4},{2,2},{0,1},
+    {{-1,2,3,4},{-1,5,6,7}},
+    4,{0,128, 14,4,58, 2,8,28,90},
+
+    60,30,500,   1.,18.,  128
+  },
+  /* 3: 256 x 7 */
+  {
+    2,{0,1},{3,4},{2,2},{0,1},
+    {{-1,2,3,4},{-1,5,6,7}},
+    4,{0,256, 28,8,116, 4,16,56,180},
+
+    60,30,500,   1.,18.,  256
+  },
+  /* 4: 128 x 11 */
+  {
+    4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
+    {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
+
+    2,{0,128,  8,33,  4,16,70,  2,6,12,  23,46,90},
+
+     60,30,500,   1,18.,  128
+  },
+  /* 5: 128 x 17 */
+  {
+    6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
+    {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
+    2,{0,128,  12,46,  4,8,16,  23,33,70,  2,6,10,  14,19,28,  39,58,90},
+
+    60,30,500,    1,18.,  128
+  },
+  /* 6: 256 x 4 (low bitrate version) */
+  {
+    1,{0},{4},{2},{0},
+    {{1,2,3,4}},
+    4,{0,256, 66,16,32,140},
+
+    60,30,500,   1.,18.,  256
+  },
+  /* 7: 1024 x 27 */
+  {
+    8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
+    {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
+    2,{0,1024,   93,23,372, 6,46,186,750,  14,33,65, 130,260,556,
+       3,10,18,28,  39,55,79,111,  158,220,312,  464,650,850},
+
+    60,30,500,    3,18.,  1024
+  },
+  /* 8: 2048 x 27 */
+  {
+    8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
+    {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
+    2,{0,2048,   186,46,744, 12,92,372,1500,  28,66,130, 260,520,1112,
+       6,20,36,56,  78,110,158,222,  316,440,624,  928,1300,1700},
+
+    60,30,500,    3,18.,  2048
+  },
+  /* 9: 512 x 17 */
+  {
+    6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
+    {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
+    2,{0,512,  46,186,  16,33,65,  93,130,278,
+       7,23,39,  55,79,110,  156,232,360},
+
+    60,30,500,    1,18.,  512
+  },
+
+  /* 10: X x 0 (LFE floor; edge posts only) */
+  {
+    0,{0}, {0},{0},{-1},
+    {{-1}},
+    2,{0,12},
+    60,30,500,   1.,18.,  10
+  },
+
+};
diff --git a/vorbis/lib/modes/psych_11.h b/vorbis/lib/modes/psych_11.h
new file mode 100644 (file)
index 0000000..cc5eea2
--- /dev/null
@@ -0,0 +1,50 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 11kHz settings
+
+ ********************************************************************/
+
+static const double _psy_lowpass_11[3]={4.5,5.5,30.,};
+
+static const att3 _psy_tone_masteratt_11[3]={
+  {{ 30,  25,  12},  0,   0},  /* 0 */
+  {{ 30,  25,  12},  0,   0},  /* 0 */
+  {{ 20,   0, -14},  0,   0}, /* 0 */
+};
+
+static const vp_adjblock _vp_tonemask_adj_11[3]={
+  /* adjust for mode zero */
+  /* 63     125     250     500     1     2     4     8    16 */
+  {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
+  {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
+  {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
+};
+
+
+static const noise3 _psy_noisebias_11[3]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4, 10, 10, 12, 12, 12, 99, 99, 99},
+    {-15,-15,-15,-15,-10,-10, -5,  0,  0,  4,  4,  5,  5, 10, 99, 99, 99},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
+
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4, 10, 10, 12, 12, 12, 99, 99, 99},
+    {-15,-15,-15,-15,-10,-10, -5, -5, -5,  0,  0,  0,  0,  0, 99, 99, 99},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5, 99, 99, 99},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
+};
+
+static const double _noise_thresh_11[3]={ .3,.5,.5 };
+
diff --git a/vorbis/lib/modes/psych_16.h b/vorbis/lib/modes/psych_16.h
new file mode 100644 (file)
index 0000000..477cb4d
--- /dev/null
@@ -0,0 +1,132 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 16kHz settings
+
+ ********************************************************************/
+
+/* stereo mode by base quality level */
+static const adj_stereo _psy_stereo_modes_16[4]={
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  */
+  {{  4,  4,  4,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  6,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   {  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  4,  4},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  {{  4,  4,  4,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  6,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   {  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  4,  4,  4,  4,  4},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  {{  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  5,  4,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  {{  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,  0,  0,  0,  0,  0},
+   {  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+};
+
+static const double _psy_lowpass_16[4]={6.5,8,30.,99.};
+
+static const att3 _psy_tone_masteratt_16[4]={
+  {{ 30,  25,  12},  0,   0},  /* 0 */
+  {{ 25,  22,  12},  0,   0},  /* 0 */
+  {{ 20,  12,   0},  0,   0},  /* 0 */
+  {{ 15,   0, -14},  0,   0}, /* 0 */
+};
+
+static const vp_adjblock _vp_tonemask_adj_16[4]={
+  /* adjust for mode zero */
+  /* 63     125     250     500       1     2     4     8    16 */
+  {{-20,-20,-20,-20,-20,-16,-10,  0,  0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
+  {{-20,-20,-20,-20,-20,-16,-10,  0,  0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
+  {{-20,-20,-20,-20,-20,-16,-10,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
+  {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
+};
+
+
+static const noise3 _psy_noisebias_16_short[4]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  {{{-15,-15,-15,-15,-15,-10,-10,-5,   4, 10, 10, 10, 10, 12, 12, 14, 20},
+    {-15,-15,-15,-15,-15,-10,-10, -5,  0,  0,  4,  5,  5,  6,  8,  8, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
+
+  {{{-15,-15,-15,-15,-15,-10,-10,-5,   4,  6,  6,  6,  6,  8, 10, 12, 20},
+    {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5,  4,  5,  6,  8,  8, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5,  5,  8, 12},
+    {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8,  0,  0,  0,  0,  2,  5},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5,  0,  0,  0,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+};
+
+static const noise3 _psy_noisebias_16_impulse[4]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  {{{-15,-15,-15,-15,-15,-10,-10,-5,   4, 10, 10, 10, 10, 12, 12, 14, 20},
+    {-15,-15,-15,-15,-15,-10,-10, -5,  0,  0,  4,  5,  5,  6,  8,  8, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
+
+  {{{-15,-15,-15,-15,-15,-10,-10,-5,   4,  4,  4,  4,  5,  5,  6,  8, 15},
+    {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5,  0,  0,  0,  0,  4, 10},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  4, 10},
+    {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5,  0,  0,  0,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+};
+
+static const noise3 _psy_noisebias_16[4]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4,  6,  8,  8, 10, 10, 10, 14, 20},
+    {-10,-10,-10,-10,-10, -5, -2, -2,  0,  0,  0,  4,  5,  6,  8,  8, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
+
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4,  6,  6,  6,  6,  8, 10, 12, 20},
+    {-15,-15,-15,-15,-15,-10, -5, -5,  0,  0,  0,  4,  5,  6,  8,  8, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5,  5,  8, 12},
+    {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5,  0,  0,  0,  0,  0,  2,  5},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5,  0,  0,  0,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
+};
+
+static const noiseguard _psy_noiseguards_16[4]={
+  {10,10,-1},
+  {10,10,-1},
+  {20,20,-1},
+  {20,20,-1},
+};
+
+static const double _noise_thresh_16[4]={ .3,.5,.5,.5 };
+
+static const int _noise_start_16[3]={ 256,256,9999 };
+static const int _noise_part_16[4]={ 8,8,8,8 };
+
+static const int _psy_ath_floater_16[4]={
+  -100,-100,-100,-105,
+};
+
+static const int _psy_ath_abs_16[4]={
+  -130,-130,-130,-140,
+};
diff --git a/vorbis/lib/modes/psych_44.h b/vorbis/lib/modes/psych_44.h
new file mode 100644 (file)
index 0000000..6c9eaa4
--- /dev/null
@@ -0,0 +1,641 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: key psychoacoustic settings for 44.1/48kHz
+
+ ********************************************************************/
+
+
+/* preecho trigger settings *****************************************/
+
+static const vorbis_info_psy_global _psy_global_44[5]={
+
+  {8,   /* lines per eighth octave */
+   {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
+   {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
+   -6.f,
+   {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
+  },
+  {8,   /* lines per eighth octave */
+   {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
+   {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
+   -6.f,
+   {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
+  },
+  {8,   /* lines per eighth octave */
+   {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
+   {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
+   -6.f,
+   {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
+  },
+  {8,   /* lines per eighth octave */
+   {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
+   {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
+   -6.f,
+   {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
+  },
+  {8,   /* lines per eighth octave */
+   {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
+   {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
+   -6.f,
+   {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
+  },
+};
+
+/* noise compander lookups * low, mid, high quality ****************/
+static const compandblock _psy_compand_44[6]={
+  /* sub-mode Z short */
+  {{
+    0, 1, 2, 3, 4, 5, 6,  7,     /* 7dB */
+    8, 9,10,11,12,13,14, 15,     /* 15dB */
+    16,17,18,19,20,21,22, 23,     /* 23dB */
+    24,25,26,27,28,29,30, 31,     /* 31dB */
+    32,33,34,35,36,37,38, 39,     /* 39dB */
+  }},
+  /* mode_Z nominal short */
+  {{
+     0, 1, 2, 3, 4, 5, 6,  6,     /* 7dB */
+     7, 7, 7, 7, 6, 6, 6,  7,     /* 15dB */
+     7, 8, 9,10,11,12,13, 14,     /* 23dB */
+    15,16,17,17,17,18,18, 19,     /* 31dB */
+    19,19,20,21,22,23,24, 25,     /* 39dB */
+  }},
+  /* mode A short */
+  {{
+    0, 1, 2, 3, 4, 5, 5,  5,     /* 7dB */
+    6, 6, 6, 5, 4, 4, 4,  4,     /* 15dB */
+    4, 4, 5, 5, 5, 6, 6,  6,     /* 23dB */
+    7, 7, 7, 8, 8, 8, 9, 10,     /* 31dB */
+    11,12,13,14,15,16,17, 18,     /* 39dB */
+  }},
+  /* sub-mode Z long */
+  {{
+     0, 1, 2, 3, 4, 5, 6,  7,     /* 7dB */
+     8, 9,10,11,12,13,14, 15,     /* 15dB */
+    16,17,18,19,20,21,22, 23,     /* 23dB */
+    24,25,26,27,28,29,30, 31,     /* 31dB */
+    32,33,34,35,36,37,38, 39,     /* 39dB */
+  }},
+  /* mode_Z nominal long */
+  {{
+    0, 1, 2, 3, 4, 5, 6,  7,     /* 7dB */
+    8, 9,10,11,12,12,13, 13,     /* 15dB */
+    13,14,14,14,15,15,15, 15,     /* 23dB */
+    16,16,17,17,17,18,18, 19,     /* 31dB */
+    19,19,20,21,22,23,24, 25,     /* 39dB */
+  }},
+  /* mode A long */
+  {{
+    0, 1, 2, 3, 4, 5, 6,  7,     /* 7dB */
+    8, 8, 7, 6, 5, 4, 4,  4,     /* 15dB */
+    4, 4, 5, 5, 5, 6, 6,  6,     /* 23dB */
+    7, 7, 7, 8, 8, 8, 9, 10,     /* 31dB */
+    11,12,13,14,15,16,17, 18,     /* 39dB */
+  }}
+};
+
+/* tonal masking curve level adjustments *************************/
+
+static const vp_adjblock _vp_tonemask_adj_longblock[12]={
+
+   /* 63     125     250     500       1       2       4       8      16 */
+
+   {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10,  0,  0,  0,  0,  0,  0}}, /* -1 */
+
+/* {{-15,-15,-15,-15,-10, -8, -4, -2,  0,  0,  0, 10,  0,  0,  0,  0,  0}},    0 */
+   {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1,  0}}, /* 0 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  5,  0,  0,  0,  0,  0}},    1 */
+   {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1,  0}}, /* 1 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    2 */
+   {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1,  0}}, /* 2 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    3 */
+   {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1,  0}}, /* 3 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}}, *//* 4 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7  -3, -1, -1 , 0}}, /* 4 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    5 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7  -3, -1, -1 , 0}}, /* 5 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    6 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2,  0}}, /* 6 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    7 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 7 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    8 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 8 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    9 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 9 */
+
+/* {{-15,-15,-15,-15,-15,-12,-10, -8,  0,  0,  0,  0,  0,  0,  0,  0,  0}},    10 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 10 */
+};
+
+static const vp_adjblock _vp_tonemask_adj_otherblock[12]={
+   /* 63     125     250     500       1       2       4       8      16 */
+
+   {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9,  1,  1,  1,  1,  1,  1}}, /* -1 */
+
+/* {{-20,-20,-20,-20,-14,-12,-10, -8, -4,  0,  0, 10,  0,  0,  0,  0,  0}},    0 */
+   {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10,  0,  0,  0,  0,  0,  0}}, /* 0 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  5,  0,  0,  0,  0,  0}},    1 */
+   {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1,  0,  0,  0}}, /* 1 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    2 */
+   {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1,  0,  0,  0}}, /* 2 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    3 */
+   {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2,  0,  0,  0}}, /* 3 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    4 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7  -3, -1, -1 , 0}}, /* 4 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    5 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7  -3, -1, -1 , 0}}, /* 5 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    6 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2,  0}}, /* 6 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    7 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 7 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    8 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 8 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    9 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 9 */
+
+/* {{-20,-20,-20,-20,-20,-18,-16,-14,-10,  0,  0,  0,  0,  0,  0,  0,  0}},    10 */
+   {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2,  0}}, /* 10 */
+};
+
+/* noise bias (transition block) */
+static const noise3 _psy_noisebias_trans[12]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  /* -1 */
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  8,  8,  8,  8, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2,  2,  2,  3,  6,  6, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
+  /* 0
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4,  0,  0,  0,  0,  2,  4,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4,  -2}}},*/
+  {{{-15,-15,-15,-15,-15,-12, -6, -4,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4,  0,  0,  0,  0,  2,  3,   6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4,  -2}}},
+  /* 1
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2,  0,  2,  8},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2,  0,  1,   4},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6,  -4}}},
+  /* 2
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  2,  2,  4,  4,  5,  6,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2,  0,  2,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  2,  2,  4,  4,  5,  6,  10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1,  0,  3},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
+  /* 3
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  2,  2,  4,  4,  4,  5,  8},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1,  1,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  2,  2,  4,  4,  4,  5,  8},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2,  0,  2},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
+  /* 4
+  {{{-20,-20,-20,-20,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1,  1,  5},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
+  {{{-20,-20,-20,-20,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1,  1},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
+  /* 5
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1,  2},
+    {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1,  0},
+    {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
+  /* 6
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2,  1},
+    {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2,  0},
+    {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
+  /* 7
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4,  0},
+    {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
+  {{{-24,-24,-24,-24,-20,-18,-14, -8, -1,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
+    {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
+  /* 8
+  {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2,  0,  0,  0,  1,  2,  3,  7},
+    {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
+    {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
+  {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2,  0,  0,  0,  1,  2,  3,  7},
+    {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
+    {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
+  /* 9
+  {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2,  2},
+    {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
+    {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
+  {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2,  2},
+    {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
+    {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
+  /* 10 */
+  {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
+};
+
+/*  noise bias (long block) */
+static const noise3 _psy_noisebias_long[12]={
+  /*63     125     250     500      1k       2k      4k      8k     16k*/
+  /* -1 */
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  0,  6,  6,  6,  6, 10, 10, 12,  20},
+    {-20,-20,-20,-20,-20,-20,-10, -2,  0,  0,  0,  0,  0,  2,  4,  6,  15},
+    {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
+
+  /* 0 */
+  /*  {{{-10,-10,-10,-10,-10,-10, -8,  2,  2,  2,  4,  4,  5,  5,  5,  8,  10},
+      {-20,-20,-20,-20,-20,-20,-20,-14, -6,  0,  0,  0,  0,  0,  2,  4,  10},
+      {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
+  {{{-10,-10,-10,-10,-10,-10, -8,  2,  2,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-20,-20,-20,-20,-20,-20,-20,-14, -6,  0,  0,  0,  0,  0,  2,  3,  6},
+    {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
+  /* 1 */
+  /*  {{{-10,-10,-10,-10,-10,-10, -8, -4,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2,  0,  2,  8},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
+  {{{-10,-10,-10,-10,-10,-10, -8, -4,  0,  2,  4,  4,  5,  5,  5,  8,  10},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2,  0,  1,  4},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
+  /* 2 */
+  /*  {{{-10,-10,-10,-10,-10,-10,-10, -8,  0,  2,  2,  2,  4,  4,  5,  6,  10},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2,  0,  2,  6},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
+  {{{-10,-10,-10,-10,-10,-10,-10, -8,  0,  2,  2,  2,  4,  4,  5,  6,  10},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1,  0,  3},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
+  /* 3 */
+  /*  {{{-10,-10,-10,-10,-10,-10,-10, -8,  0,  2,  2,  2,  4,  4,  4,  5,  8},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1,  1,  6},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
+  {{{-10,-10,-10,-10,-10,-10,-10, -8,  0,  2,  2,  2,  4,  4,  4,  5,  8},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2,  0,  2},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
+  /* 4 */
+  /*  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1,  1,  5},
+      {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
+  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1,  1},
+    {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
+  /* 5 */
+  /*  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+      {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1,  2},
+      {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
+  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1,  0},
+    {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
+  /* 6 */
+  /*  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+      {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2,  1},
+      {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
+  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2,  0},
+    {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
+  /* 7 */
+  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  1,  1,  1,  2,  3,  3,  4,  7},
+    {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4,  0},
+    {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
+  /* 8 */
+  {{{-15,-15,-15,-15,-15,-15,-15,-10, -4,  0,  0,  0,  0,  1,  2,  3,  7},
+    {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
+    {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
+  /* 9 */
+  {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2,  2},
+    {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
+    {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
+  /* 10 */
+  {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
+    {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
+};
+
+/* noise bias (impulse block) */
+static const noise3 _psy_noisebias_impulse[12]={
+  /*  63     125     250     500      1k      2k      4k      8k     16k*/
+  /* -1 */
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  8,  8,  8,  8, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2,  2,  2,  3,  6,  6, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
+
+  /* 0 */
+  /*  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  4,  8,  8,  8, 10, 12, 14, 20},
+      {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2,  0,  0,  0,  0,  2,  4,  10},
+      {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  4,  8,  8,  8, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2,  0,  0,  0,  0,  2,  3,  6},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
+  /* 1 */
+  {{{-12,-12,-12,-12,-12, -8, -6, -4,  0,  4,  4,  4,  4, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2,  2},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
+  /* 2 */
+  {{{-14,-14,-14,-14,-14,-10, -8, -6, -2,  2,  2,  2,  2,  8, 10, 10, 16},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2,  0},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
+  /* 3 */
+  {{{-14,-14,-14,-14,-14,-10, -8, -6, -2,  2,  2,  2,  2,  6,  8,  8, 14},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2,  0},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
+  /* 4 */
+  {{{-16,-16,-16,-16,-16,-12,-10, -6, -2,  0,  0,  0,  0,  4,  6,  6, 12},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2,  0},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
+  /* 5 */
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  4,  6, 11},
+    {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
+    {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
+  /* 6
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  4,  6, 11},
+      {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
+      {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  4,  6, 11},
+    {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
+    {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
+  /* 7 */
+  /*  {{{-22,-22,-22,-22,-22,-20,-14,-10, -6,  0,  0,  0,  0,  4,  4,  6, 11},
+      {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
+      {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
+  {{{-22,-22,-22,-22,-22,-20,-14,-10, -6,  0,  0,  0,  0,  4,  4,  6, 11},
+    {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
+    {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
+  /* 8 */
+  /*  {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1,  3,  3,  5, 10},
+      {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
+      {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
+  {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1,  3,  3,  5, 10},
+    {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
+    {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
+  /* 9 */
+  /*  {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2,  2},
+      {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
+      {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
+  {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2,  2},
+    {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
+    {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
+  /* 10 */
+  {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
+};
+
+/* noise bias (padding block) */
+static const noise3 _psy_noisebias_padding[12]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+
+  /* -1 */
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  8,  8,  8,  8, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2,  2,  2,  3,  6,  6, 15},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
+
+  /* 0 */
+  {{{-10,-10,-10,-10,-10, -4,  0,  0,  4,  8,  8,  8,  8, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2,  2,  3,  6,  6,  8, 10},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2,  0,  2}}},
+  /* 1 */
+  {{{-12,-12,-12,-12,-12, -8, -6, -4,  0,  4,  4,  4,  4, 10, 12, 14, 20},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4,  0,  0,  0,  2,  2,  4,  8},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2,  0}}},
+  /* 2 */
+  /*  {{{-14,-14,-14,-14,-14,-10, -8, -6, -2,  2,  2,  2,  2,  8, 10, 10, 16},
+      {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4,  0,  0,  0,  2,  2,  4,  8},
+      {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
+  {{{-14,-14,-14,-14,-14,-10, -8, -6, -2,  2,  2,  2,  2,  8, 10, 10, 16},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1,  0,  0,  2,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
+  /* 3 */
+  {{{-14,-14,-14,-14,-14,-10, -8, -6, -2,  2,  2,  2,  2,  6,  8,  8, 14},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1,  0,  0,  2,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
+  /* 4 */
+  {{{-16,-16,-16,-16,-16,-12,-10, -6, -2,  0,  0,  0,  0,  4,  6,  6, 12},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1,  0,  2,  6},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
+  /* 5 */
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  6,  6, 12},
+    {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2,  0,  4},
+    {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
+  /* 6 */
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  6,  6, 12},
+    {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1,  4},
+    {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
+  /* 7 */
+  {{{-20,-20,-20,-20,-20,-18,-14,-10, -4,  0,  0,  0,  0,  4,  6,  6, 12},
+    {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3,  1},
+    {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
+  /* 8 */
+  {{{-22,-22,-22,-22,-22,-20,-14,-10, -4,  0,  0,  0,  0,  3,  5,  5, 11},
+    {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
+    {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
+  /* 9 */
+  {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2,  0,  2,  6},
+    {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
+    {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
+  /* 10 */
+  {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
+    {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
+};
+
+
+static const noiseguard _psy_noiseguards_44[4]={
+  {3,3,15},
+  {3,3,15},
+  {10,10,100},
+  {10,10,100},
+};
+
+static const int _psy_tone_suppress[12]={
+  -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
+};
+static const int _psy_tone_0dB[12]={
+  90,90,95,95,95,95,105,105,105,105,105,105,
+};
+static const int _psy_noise_suppress[12]={
+  -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
+};
+
+static const vorbis_info_psy _psy_info_template={
+  /* blockflag */
+  -1,
+  /* ath_adjatt, ath_maxatt */
+  -140.,-140.,
+  /* tonemask att boost/decay,suppr,curves */
+  {0.f,0.f,0.f},     0.,0.,    -40.f, {0.},
+
+  /*noisemaskp,supp, low/high window, low/hi guard, minimum */
+  1,          -0.f,           .5f, .5f,         0,0,0,
+  /* noiseoffset*3, noisecompand, max_curve_dB */
+  {{-1},{-1},{-1}},{-1},105.f,
+  /* noise normalization - noise_p, start, partition, thresh. */
+  0,-1,-1,0.,
+};
+
+/* ath ****************/
+
+static const int _psy_ath_floater[12]={
+  -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
+};
+static const int _psy_ath_abs[12]={
+  -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
+};
+
+/* stereo setup.  These don't map directly to quality level, there's
+   an additional indirection as several of the below may be used in a
+   single bitmanaged stream
+
+****************/
+
+/* various stereo possibilities */
+
+/* stereo mode by base quality level */
+static const adj_stereo _psy_stereo_modes_44[12]={
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         -1  */
+  {{  4,  4,  4,  4,  4,  4,  4,  3,  2,  2,  1,  0,  0,  0,  0},
+   {  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  5,  4,  3},
+   {  1,  2,  3,  4,  4,  4,  4,  4,  4,  5,  6,  7,  8,  8,  8},
+   { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
+
+/*    0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         0  */
+  {{  4,  4,  4,  4,  4,  4,  4,  3,  2,  1,  0,  0,  0,  0,  0},
+   {  8,  8,  8,  8,  6,  6,  5,  5,  5,  5,  5,  5,  5,  4,  3},
+   {  1,  2,  3,  4,  4,  5,  6,  6,  6,  6,  6,  8,  8,  8,  8},
+   { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
+
+
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         1  */
+  {{  3,  3,  3,  3,  3,  3,  3,  3,  2,  1,  0,  0,  0,  0,  0},
+   {  8,  8,  8,  8,  6,  6,  5,  5,  5,  5,  5,  5,  5,  4,  3},
+   {  1,  2,  3,  4,  4,  5,  6,  6,  6,  6,  6,  8,  8,  8,  8},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+
+
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         2  */
+  {{  3,  3,  3,  3,  3,  3,  3,  2,  1,  1,  0,  0,  0,  0,  0},
+   {  8,  8,  6,  6,  5,  5,  4,  4,  4,  4,  4,  4,  3,  2,  1},
+   {  3,  4,  4,  5,  5,  6,  6,  6,  6,  6,  6,  8,  8,  8,  8},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         3  */
+  {{  2,  2,  2,  2,  2,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0},
+   {  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  3,  2,  1},
+   {  4,  4,  5,  6,  6,  6,  6,  6,  8,  8, 10, 10, 10, 10, 10},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         4  */
+  {{  2,  2,  2,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  3,  3,  2,  1,  0},
+   {  6,  6,  6,  8,  8,  8,  8,  8,  8,  8, 10, 10, 10, 10, 10},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         5  */
+  {{  2,  2,  2,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  3,  3,  3,  3,  3,  2,  2,  2,  2,  2,  2,  0,  0,  0,  0},
+   {  6,  7,  8,  8,  8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         6  */
+  {{  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  3,  3,  3,  2,  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  8,  8,  8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         7  */
+  {{  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  3,  3,  3,  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  8,  8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         8  */
+  {{  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  2,  2,  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
+   {  8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14         9  */
+  {{  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,  0,  0,  0,  0,  0},
+   {  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14        10  */
+  {{  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,  0,  0,  0,  0,  0},
+   {  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+};
+
+/* tone master attenuation by base quality mode and bitrate tweak */
+static const att3 _psy_tone_masteratt_44[12]={
+  {{ 35,  21,   9},  0,    0}, /* -1 */
+  {{ 30,  20,   8}, -2, 1.25}, /* 0 */
+  /*  {{ 25,  14,   4},  0,    0}, *//* 1 */
+  {{ 25,  12,   2},  0,    0}, /* 1 */
+  /*  {{ 20,  10,  -2},  0,    0}, *//* 2 */
+  {{ 20,   9,  -3},  0,    0}, /* 2 */
+  {{ 20,   9,  -4},  0,    0}, /* 3 */
+  {{ 20,   9,  -4},  0,    0}, /* 4 */
+  {{ 20,   6,  -6},  0,    0}, /* 5 */
+  {{ 20,   3, -10},  0,    0}, /* 6 */
+  {{ 18,   1, -14},  0,    0}, /* 7 */
+  {{ 18,   0, -16},  0,    0}, /* 8 */
+  {{ 18,  -2, -16},  0,    0}, /* 9 */
+  {{ 12,  -2, -20},  0,    0}, /* 10 */
+};
+
+/* lowpass by mode **************/
+static const double _psy_lowpass_44[12]={
+  /*  15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
+  13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
+};
+
+/* noise normalization **********/
+
+static const int _noise_start_short_44[11]={
+  /*  16,16,16,16,32,32,9999,9999,9999,9999 */
+  32,16,16,16,32,9999,9999,9999,9999,9999,9999
+};
+static const int _noise_start_long_44[11]={
+  /*  128,128,128,256,512,512,9999,9999,9999,9999 */
+  256,128,128,256,512,9999,9999,9999,9999,9999,9999
+};
+
+static const int _noise_part_short_44[11]={
+    8,8,8,8,8,8,8,8,8,8,8
+};
+static const int _noise_part_long_44[11]={
+    32,32,32,32,32,32,32,32,32,32,32
+};
+
+static const double _noise_thresh_44[11]={
+  /*  .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
+   .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
+};
+
+static const double _noise_thresh_5only[2]={
+ .5,.5,
+};
diff --git a/vorbis/lib/modes/psych_8.h b/vorbis/lib/modes/psych_8.h
new file mode 100644 (file)
index 0000000..277db84
--- /dev/null
@@ -0,0 +1,100 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 8kHz psychoacoustic settings
+
+ ********************************************************************/
+
+static const att3 _psy_tone_masteratt_8[3]={
+  {{ 32,  25,  12},  0,   0},  /* 0 */
+  {{ 30,  25,  12},  0,   0},  /* 0 */
+  {{ 20,   0, -14},  0,   0}, /* 0 */
+};
+
+static const vp_adjblock _vp_tonemask_adj_8[3]={
+  /* adjust for mode zero */
+  /* 63     125     250     500     1     2     4     8    16 */
+  {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
+  {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
+  {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
+};
+
+
+static const noise3 _psy_noisebias_8[3]={
+  /*  63     125     250     500      1k       2k      4k      8k     16k*/
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4,  8,  8,  8, 10, 10, 99, 99, 99},
+    {-10,-10,-10,-10, -5, -5, -5,  0,  0,  4,  4,  4,  4,  4, 99, 99, 99},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
+
+  {{{-10,-10,-10,-10, -5, -5, -5,  0,  4,  8,  8,  8, 10, 10, 99, 99, 99},
+    {-10,-10,-10,-10,-10,-10, -5, -5, -5,  0,  0,  0,  0,  0, 99, 99, 99},
+    {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
+
+  {{{-15,-15,-15,-15,-15,-12,-10, -8,  0,  2,  4,  4,  5,  5, 99, 99, 99},
+    {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
+    {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
+};
+
+/* stereo mode by base quality level */
+static const adj_stereo _psy_stereo_modes_8[3]={
+  /*  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  */
+  {{  4,  4,  4,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  6,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   {  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  {{  4,  4,  4,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  6,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   {  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+  {{  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3},
+   {  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4},
+   {  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1},
+   { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
+};
+
+static const noiseguard _psy_noiseguards_8[2]={
+  {10,10,-1},
+  {10,10,-1},
+};
+
+static const compandblock _psy_compand_8[2]={
+  {{
+     0, 1, 2, 3, 4, 5, 6,  7,     /* 7dB */
+     8, 8, 9, 9,10,10,11, 11,     /* 15dB */
+    12,12,13,13,14,14,15, 15,     /* 23dB */
+    16,16,17,17,17,18,18, 19,     /* 31dB */
+    19,19,20,21,22,23,24, 25,     /* 39dB */
+  }},
+  {{
+     0, 1, 2, 3, 4, 5, 6,  6,     /* 7dB */
+     7, 7, 6, 6, 5, 5, 4,  4,     /* 15dB */
+     3, 3, 3, 4, 5, 6, 7,  8,     /* 23dB */
+     9,10,11,12,13,14,15, 16,     /* 31dB */
+    17,18,19,20,21,22,23, 24,     /* 39dB */
+  }},
+};
+
+static const double _psy_lowpass_8[3]={3.,4.,4.};
+static const int _noise_start_8[2]={
+  64,64,
+};
+static const int _noise_part_8[2]={
+  8,8,
+};
+
+static const int _psy_ath_floater_8[3]={
+  -100,-100,-105,
+};
+
+static const int _psy_ath_abs_8[3]={
+  -130,-130,-140,
+};
diff --git a/vorbis/lib/modes/residue_16.h b/vorbis/lib/modes/residue_16.h
new file mode 100644 (file)
index 0000000..3e05471
--- /dev/null
@@ -0,0 +1,162 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel residue templates 16/22kHz
+
+ ********************************************************************/
+
+/***** residue backends *********************************************/
+
+static const static_bookblock _resbook_16s_0={
+  {
+    {0},
+    {0,0,&_16c0_s_p1_0},
+    {0},
+    {0,0,&_16c0_s_p3_0},
+    {0,0,&_16c0_s_p4_0},
+    {0,0,&_16c0_s_p5_0},
+    {0,0,&_16c0_s_p6_0},
+    {&_16c0_s_p7_0,&_16c0_s_p7_1},
+    {&_16c0_s_p8_0,&_16c0_s_p8_1},
+    {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_16s_1={
+  {
+    {0},
+    {0,0,&_16c1_s_p1_0},
+    {0},
+    {0,0,&_16c1_s_p3_0},
+    {0,0,&_16c1_s_p4_0},
+    {0,0,&_16c1_s_p5_0},
+    {0,0,&_16c1_s_p6_0},
+    {&_16c1_s_p7_0,&_16c1_s_p7_1},
+    {&_16c1_s_p8_0,&_16c1_s_p8_1},
+    {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_16s_2={
+  {
+    {0},
+    {0,0,&_16c2_s_p1_0},
+    {0,0,&_16c2_s_p2_0},
+    {0,0,&_16c2_s_p3_0},
+    {0,0,&_16c2_s_p4_0},
+    {&_16c2_s_p5_0,&_16c2_s_p5_1},
+    {&_16c2_s_p6_0,&_16c2_s_p6_1},
+    {&_16c2_s_p7_0,&_16c2_s_p7_1},
+    {&_16c2_s_p8_0,&_16c2_s_p8_1},
+    {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_16s_0[]={
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
+   &_resbook_16s_0,&_resbook_16s_0},
+};
+static const vorbis_residue_template _res_16s_1[]={
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
+   &_resbook_16s_1,&_resbook_16s_1},
+
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
+   &_resbook_16s_1,&_resbook_16s_1}
+};
+static const vorbis_residue_template _res_16s_2[]={
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
+   &_resbook_16s_2,&_resbook_16s_2},
+
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
+   &_resbook_16s_2,&_resbook_16s_2}
+};
+
+static const vorbis_mapping_template _mapres_template_16_stereo[3]={
+  { _map_nominal, _res_16s_0 }, /* 0 */
+  { _map_nominal, _res_16s_1 }, /* 1 */
+  { _map_nominal, _res_16s_2 }, /* 2 */
+};
+
+static const static_bookblock _resbook_16u_0={
+  {
+    {0},
+    {0,0,&_16u0__p1_0},
+    {0,0,&_16u0__p2_0},
+    {0,0,&_16u0__p3_0},
+    {0,0,&_16u0__p4_0},
+    {0,0,&_16u0__p5_0},
+    {&_16u0__p6_0,&_16u0__p6_1},
+    {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
+   }
+};
+static const static_bookblock _resbook_16u_1={
+  {
+    {0},
+    {0,0,&_16u1__p1_0},
+    {0,0,&_16u1__p2_0},
+    {0,0,&_16u1__p3_0},
+    {0,0,&_16u1__p4_0},
+    {0,0,&_16u1__p5_0},
+    {0,0,&_16u1__p6_0},
+    {&_16u1__p7_0,&_16u1__p7_1},
+    {&_16u1__p8_0,&_16u1__p8_1},
+    {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
+   }
+};
+static const static_bookblock _resbook_16u_2={
+  {
+    {0},
+    {0,0,&_16u2_p1_0},
+    {0,0,&_16u2_p2_0},
+    {0,0,&_16u2_p3_0},
+    {0,0,&_16u2_p4_0},
+    {&_16u2_p5_0,&_16u2_p5_1},
+    {&_16u2_p6_0,&_16u2_p6_1},
+    {&_16u2_p7_0,&_16u2_p7_1},
+    {&_16u2_p8_0,&_16u2_p8_1},
+    {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_16u_0[]={
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__16u0__single,&_huff_book__16u0__single,
+   &_resbook_16u_0,&_resbook_16u_0},
+};
+static const vorbis_residue_template _res_16u_1[]={
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__16u1__short,&_huff_book__16u1__short,
+   &_resbook_16u_1,&_resbook_16u_1},
+
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__16u1__long,&_huff_book__16u1__long,
+   &_resbook_16u_1,&_resbook_16u_1}
+};
+static const vorbis_residue_template _res_16u_2[]={
+  {1,0,32,  &_residue_44_hi_un,
+   &_huff_book__16u2__short,&_huff_book__16u2__short,
+   &_resbook_16u_2,&_resbook_16u_2},
+
+  {1,0,32,  &_residue_44_hi_un,
+   &_huff_book__16u2__long,&_huff_book__16u2__long,
+   &_resbook_16u_2,&_resbook_16u_2}
+};
+
+
+static const vorbis_mapping_template _mapres_template_16_uncoupled[3]={
+  { _map_nominal_u, _res_16u_0 }, /* 0 */
+  { _map_nominal_u, _res_16u_1 }, /* 1 */
+  { _map_nominal_u, _res_16u_2 }, /* 2 */
+};
diff --git a/vorbis/lib/modes/residue_44.h b/vorbis/lib/modes/residue_44.h
new file mode 100644 (file)
index 0000000..e89bc0e
--- /dev/null
@@ -0,0 +1,291 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel residue templates for 32/44.1/48kHz
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "backends.h"
+#include "books/coupled/res_books_stereo.h"
+
+/***** residue backends *********************************************/
+
+static const vorbis_info_residue0 _residue_44_low={
+  0,-1, -1, 9,-1,-1,
+  /* 0   1   2   3   4   5   6   7  */
+  {0},
+  {-1},
+  {  0,  1,  2,  2,  4,  8, 16, 32},
+  {  0,  0,  0,999,  4,  8, 16, 32},
+};
+
+static const vorbis_info_residue0 _residue_44_mid={
+  0,-1, -1, 10,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  {  0,  1,  1,  2,  2,  4,  8, 16, 32},
+  {  0,  0,999,  0,999,  4,  8, 16, 32},
+};
+
+static const vorbis_info_residue0 _residue_44_high={
+  0,-1, -1, 10,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  {  0,  1,  2,  4,  8, 16, 32, 71,157},
+  {  0,  1,  2,  3,  4,  8, 16, 71,157},
+};
+
+static const static_bookblock _resbook_44s_n1={
+  {
+    {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
+    {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
+    {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
+    {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
+   }
+};
+static const static_bookblock _resbook_44sm_n1={
+  {
+    {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
+    {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
+    {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
+    {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
+   }
+};
+
+static const static_bookblock _resbook_44s_0={
+  {
+    {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
+    {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
+    {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
+    {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
+   }
+};
+static const static_bookblock _resbook_44sm_0={
+  {
+    {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
+    {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
+    {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
+    {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
+   }
+};
+
+static const static_bookblock _resbook_44s_1={
+  {
+    {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
+    {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
+    {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
+    {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
+   }
+};
+static const static_bookblock _resbook_44sm_1={
+  {
+    {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
+    {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
+    {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
+    {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
+   }
+};
+
+static const static_bookblock _resbook_44s_2={
+  {
+    {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
+    {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
+    {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
+    {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_3={
+  {
+    {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
+    {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
+    {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
+    {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_4={
+  {
+    {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
+    {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
+    {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
+    {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_5={
+  {
+    {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
+    {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
+    {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
+    {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_6={
+  {
+    {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
+    {0,0,&_44c6_s_p4_0},
+    {&_44c6_s_p5_0,&_44c6_s_p5_1},
+    {&_44c6_s_p6_0,&_44c6_s_p6_1},
+    {&_44c6_s_p7_0,&_44c6_s_p7_1},
+    {&_44c6_s_p8_0,&_44c6_s_p8_1},
+    {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_7={
+  {
+    {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
+    {0,0,&_44c7_s_p4_0},
+    {&_44c7_s_p5_0,&_44c7_s_p5_1},
+    {&_44c7_s_p6_0,&_44c7_s_p6_1},
+    {&_44c7_s_p7_0,&_44c7_s_p7_1},
+    {&_44c7_s_p8_0,&_44c7_s_p8_1},
+    {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_8={
+  {
+    {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
+    {0,0,&_44c8_s_p4_0},
+    {&_44c8_s_p5_0,&_44c8_s_p5_1},
+    {&_44c8_s_p6_0,&_44c8_s_p6_1},
+    {&_44c8_s_p7_0,&_44c8_s_p7_1},
+    {&_44c8_s_p8_0,&_44c8_s_p8_1},
+    {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_44s_9={
+  {
+    {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
+    {0,0,&_44c9_s_p4_0},
+    {&_44c9_s_p5_0,&_44c9_s_p5_1},
+    {&_44c9_s_p6_0,&_44c9_s_p6_1},
+    {&_44c9_s_p7_0,&_44c9_s_p7_1},
+    {&_44c9_s_p8_0,&_44c9_s_p8_1},
+    {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_44s_n1[]={
+  {2,0,32,  &_residue_44_low,
+   &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
+   &_resbook_44s_n1,&_resbook_44sm_n1},
+
+  {2,0,32,  &_residue_44_low,
+   &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
+   &_resbook_44s_n1,&_resbook_44sm_n1}
+};
+static const vorbis_residue_template _res_44s_0[]={
+  {2,0,16,  &_residue_44_low,
+   &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
+   &_resbook_44s_0,&_resbook_44sm_0},
+
+  {2,0,32,  &_residue_44_low,
+   &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
+   &_resbook_44s_0,&_resbook_44sm_0}
+};
+static const vorbis_residue_template _res_44s_1[]={
+  {2,0,16,  &_residue_44_low,
+   &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
+   &_resbook_44s_1,&_resbook_44sm_1},
+
+  {2,0,32,  &_residue_44_low,
+   &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
+   &_resbook_44s_1,&_resbook_44sm_1}
+};
+
+static const vorbis_residue_template _res_44s_2[]={
+  {2,0,16,  &_residue_44_mid,
+   &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
+   &_resbook_44s_2,&_resbook_44s_2},
+
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
+   &_resbook_44s_2,&_resbook_44s_2}
+};
+static const vorbis_residue_template _res_44s_3[]={
+  {2,0,16,  &_residue_44_mid,
+   &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
+   &_resbook_44s_3,&_resbook_44s_3},
+
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
+   &_resbook_44s_3,&_resbook_44s_3}
+};
+static const vorbis_residue_template _res_44s_4[]={
+  {2,0,16,  &_residue_44_mid,
+   &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
+   &_resbook_44s_4,&_resbook_44s_4},
+
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
+   &_resbook_44s_4,&_resbook_44s_4}
+};
+static const vorbis_residue_template _res_44s_5[]={
+  {2,0,16,  &_residue_44_mid,
+   &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
+   &_resbook_44s_5,&_resbook_44s_5},
+
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
+   &_resbook_44s_5,&_resbook_44s_5}
+};
+static const vorbis_residue_template _res_44s_6[]={
+  {2,0,16,  &_residue_44_high,
+   &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
+   &_resbook_44s_6,&_resbook_44s_6},
+
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
+   &_resbook_44s_6,&_resbook_44s_6}
+};
+static const vorbis_residue_template _res_44s_7[]={
+  {2,0,16,  &_residue_44_high,
+   &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
+   &_resbook_44s_7,&_resbook_44s_7},
+
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
+   &_resbook_44s_7,&_resbook_44s_7}
+};
+static const vorbis_residue_template _res_44s_8[]={
+  {2,0,16,  &_residue_44_high,
+   &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
+   &_resbook_44s_8,&_resbook_44s_8},
+
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
+   &_resbook_44s_8,&_resbook_44s_8}
+};
+static const vorbis_residue_template _res_44s_9[]={
+  {2,0,16,  &_residue_44_high,
+   &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
+   &_resbook_44s_9,&_resbook_44s_9},
+
+  {2,0,32,  &_residue_44_high,
+   &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
+   &_resbook_44s_9,&_resbook_44s_9}
+};
+
+static const vorbis_mapping_template _mapres_template_44_stereo[]={
+  { _map_nominal, _res_44s_n1 }, /* -1 */
+  { _map_nominal, _res_44s_0 }, /* 0 */
+  { _map_nominal, _res_44s_1 }, /* 1 */
+  { _map_nominal, _res_44s_2 }, /* 2 */
+  { _map_nominal, _res_44s_3 }, /* 3 */
+  { _map_nominal, _res_44s_4 }, /* 4 */
+  { _map_nominal, _res_44s_5 }, /* 5 */
+  { _map_nominal, _res_44s_6 }, /* 6 */
+  { _map_nominal, _res_44s_7 }, /* 7 */
+  { _map_nominal, _res_44s_8 }, /* 8 */
+  { _map_nominal, _res_44s_9 }, /* 9 */
+};
diff --git a/vorbis/lib/modes/residue_44p51.h b/vorbis/lib/modes/residue_44p51.h
new file mode 100644 (file)
index 0000000..7f33e25
--- /dev/null
@@ -0,0 +1,450 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel residue templates for 32/44.1/48kHz uncoupled
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "backends.h"
+
+#include "books/coupled/res_books_51.h"
+
+/***** residue backends *********************************************/
+
+static const vorbis_info_residue0 _residue_44p_lo={
+  0,-1, -1, 7,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  {  0,  1,  2,  7, 17, 31},
+  {  0,  0, 99,  7, 17, 31},
+};
+
+static const vorbis_info_residue0 _residue_44p={
+  0,-1, -1, 8,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  {  0,  1,  1,   2,  7, 17, 31},
+  {  0,  0, 99,  99,  7, 17, 31},
+};
+
+static const vorbis_info_residue0 _residue_44p_hi={
+  0,-1, -1, 8,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  {  0,  1,  2,  4,  7, 17, 31},
+  {  0,  1,  2,  4,  7, 17, 31},
+};
+
+static const vorbis_info_residue0 _residue_44p_lfe={
+  0,-1, -1, 2,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8  */
+  {0},
+  {-1},
+  { 32},
+  { -1}
+};
+
+static const static_bookblock _resbook_44p_n1={
+  {
+    {0},
+    {0,&_44pn1_p1_0},
+
+    {&_44pn1_p2_0,&_44pn1_p2_1,0},
+    {&_44pn1_p3_0,&_44pn1_p3_1,0},
+    {&_44pn1_p4_0,&_44pn1_p4_1,0},
+
+    {&_44pn1_p5_0,&_44pn1_p5_1,&_44pn1_p4_1},
+    {&_44pn1_p6_0,&_44pn1_p6_1,&_44pn1_p6_2},
+   }
+};
+
+static const static_bookblock _resbook_44p_0={
+  {
+    {0},
+    {0,&_44p0_p1_0},
+
+    {&_44p0_p2_0,&_44p0_p2_1,0},
+    {&_44p0_p3_0,&_44p0_p3_1,0},
+    {&_44p0_p4_0,&_44p0_p4_1,0},
+
+    {&_44p0_p5_0,&_44p0_p5_1,&_44p0_p4_1},
+    {&_44p0_p6_0,&_44p0_p6_1,&_44p0_p6_2},
+   }
+};
+
+static const static_bookblock _resbook_44p_1={
+  {
+    {0},
+    {0,&_44p1_p1_0},
+
+    {&_44p1_p2_0,&_44p1_p2_1,0},
+    {&_44p1_p3_0,&_44p1_p3_1,0},
+    {&_44p1_p4_0,&_44p1_p4_1,0},
+
+    {&_44p1_p5_0,&_44p1_p5_1,&_44p1_p4_1},
+    {&_44p1_p6_0,&_44p1_p6_1,&_44p1_p6_2},
+   }
+};
+
+static const static_bookblock _resbook_44p_2={
+  {
+    {0},
+    {0,0,&_44p2_p1_0},
+    {0,&_44p2_p2_0,0},
+
+    {&_44p2_p3_0,&_44p2_p3_1,0},
+    {&_44p2_p4_0,&_44p2_p4_1,0},
+    {&_44p2_p5_0,&_44p2_p5_1,0},
+
+    {&_44p2_p6_0,&_44p2_p6_1,&_44p2_p5_1},
+    {&_44p2_p7_0,&_44p2_p7_1,&_44p2_p7_2,&_44p2_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_3={
+  {
+    {0},
+    {0,0,&_44p3_p1_0},
+    {0,&_44p3_p2_0,0},
+
+    {&_44p3_p3_0,&_44p3_p3_1,0},
+    {&_44p3_p4_0,&_44p3_p4_1,0},
+    {&_44p3_p5_0,&_44p3_p5_1,0},
+
+    {&_44p3_p6_0,&_44p3_p6_1,&_44p3_p5_1},
+    {&_44p3_p7_0,&_44p3_p7_1,&_44p3_p7_2,&_44p3_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_4={
+  {
+    {0},
+    {0,0,&_44p4_p1_0},
+    {0,&_44p4_p2_0,0},
+
+    {&_44p4_p3_0,&_44p4_p3_1,0},
+    {&_44p4_p4_0,&_44p4_p4_1,0},
+    {&_44p4_p5_0,&_44p4_p5_1,0},
+
+    {&_44p4_p6_0,&_44p4_p6_1,&_44p4_p5_1},
+    {&_44p4_p7_0,&_44p4_p7_1,&_44p4_p7_2,&_44p4_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_5={
+  {
+    {0},
+    {0,0,&_44p5_p1_0},
+    {0,&_44p5_p2_0,0},
+
+    {&_44p5_p3_0,&_44p5_p3_1,0},
+    {&_44p5_p4_0,&_44p5_p4_1,0},
+    {&_44p5_p5_0,&_44p5_p5_1,0},
+
+    {&_44p5_p6_0,&_44p5_p6_1,&_44p5_p5_1},
+    {&_44p5_p7_0,&_44p5_p7_1,&_44p5_p7_2,&_44p5_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_6={
+  {
+    {0},
+    {0,0,&_44p6_p1_0},
+    {0,&_44p6_p2_0,0},
+
+    {&_44p6_p3_0,&_44p6_p3_1,0},
+    {&_44p6_p4_0,&_44p6_p4_1,0},
+    {&_44p6_p5_0,&_44p6_p5_1,0},
+
+    {&_44p6_p6_0,&_44p6_p6_1,&_44p6_p5_1},
+    {&_44p6_p7_0,&_44p6_p7_1,&_44p6_p7_2,&_44p6_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_7={
+  {
+    {0},
+    {0,0,&_44p7_p1_0},
+    {0,&_44p7_p2_0,0},
+
+    {&_44p7_p3_0,&_44p7_p3_1,0},
+    {&_44p7_p4_0,&_44p7_p4_1,0},
+    {&_44p7_p5_0,&_44p7_p5_1,0},
+
+    {&_44p7_p6_0,&_44p7_p6_1,&_44p7_p5_1},
+    {&_44p7_p7_0,&_44p7_p7_1,&_44p7_p7_2,&_44p7_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_8={
+  {
+    {0},
+    {0,0,&_44p8_p1_0},
+    {0,&_44p8_p2_0,0},
+
+    {&_44p8_p3_0,&_44p8_p3_1,0},
+    {&_44p8_p4_0,&_44p8_p4_1,0},
+    {&_44p8_p5_0,&_44p8_p5_1,0},
+
+    {&_44p8_p6_0,&_44p8_p6_1,&_44p8_p5_1},
+    {&_44p8_p7_0,&_44p8_p7_1,&_44p8_p7_2,&_44p8_p7_3}
+   }
+};
+static const static_bookblock _resbook_44p_9={
+  {
+    {0},
+    {0,0,&_44p9_p1_0},
+    {0,&_44p9_p2_0,0},
+
+    {&_44p9_p3_0,&_44p9_p3_1,0},
+    {&_44p9_p4_0,&_44p9_p4_1,0},
+    {&_44p9_p5_0,&_44p9_p5_1,0},
+
+    {&_44p9_p6_0,&_44p9_p6_1,&_44p9_p5_1},
+    {&_44p9_p7_0,&_44p9_p7_1,&_44p9_p7_2,&_44p9_p7_3}
+   }
+};
+
+static const static_bookblock _resbook_44p_ln1={
+  {
+    {&_44pn1_l0_0,&_44pn1_l0_1,0},
+    {&_44pn1_l1_0,&_44pn1_p6_1,&_44pn1_p6_2},
+   }
+};
+static const static_bookblock _resbook_44p_l0={
+  {
+    {&_44p0_l0_0,&_44p0_l0_1,0},
+    {&_44p0_l1_0,&_44p0_p6_1,&_44p0_p6_2},
+   }
+};
+static const static_bookblock _resbook_44p_l1={
+  {
+    {&_44p1_l0_0,&_44p1_l0_1,0},
+    {&_44p1_l1_0,&_44p1_p6_1,&_44p1_p6_2},
+   }
+};
+static const static_bookblock _resbook_44p_l2={
+  {
+    {&_44p2_l0_0,&_44p2_l0_1,0},
+    {&_44p2_l1_0,&_44p2_p7_2,&_44p2_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l3={
+  {
+    {&_44p3_l0_0,&_44p3_l0_1,0},
+    {&_44p3_l1_0,&_44p3_p7_2,&_44p3_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l4={
+  {
+    {&_44p4_l0_0,&_44p4_l0_1,0},
+    {&_44p4_l1_0,&_44p4_p7_2,&_44p4_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l5={
+  {
+    {&_44p5_l0_0,&_44p5_l0_1,0},
+    {&_44p5_l1_0,&_44p5_p7_2,&_44p5_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l6={
+  {
+    {&_44p6_l0_0,&_44p6_l0_1,0},
+    {&_44p6_l1_0,&_44p6_p7_2,&_44p6_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l7={
+  {
+    {&_44p7_l0_0,&_44p7_l0_1,0},
+    {&_44p7_l1_0,&_44p7_p7_2,&_44p7_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l8={
+  {
+    {&_44p8_l0_0,&_44p8_l0_1,0},
+    {&_44p8_l1_0,&_44p8_p7_2,&_44p8_p7_3},
+   }
+};
+static const static_bookblock _resbook_44p_l9={
+  {
+    {&_44p9_l0_0,&_44p9_l0_1,0},
+    {&_44p9_l1_0,&_44p9_p7_2,&_44p9_p7_3},
+   }
+};
+
+
+static const vorbis_info_mapping0 _map_nominal_51[2]={
+  {2, {0,0,0,0,0,1}, {0,2}, {0,2}, 4,{0,3,0,0},{2,4,1,3}},
+  {2, {0,0,0,0,0,1}, {1,2}, {1,2}, 4,{0,3,0,0},{2,4,1,3}}
+};
+static const vorbis_info_mapping0 _map_nominal_51u[2]={
+  {2, {0,0,0,0,0,1}, {0,2}, {0,2}, 0,{0},{0}},
+  {2, {0,0,0,0,0,1}, {1,2}, {1,2}, 0,{0},{0}}
+};
+
+static const vorbis_residue_template _res_44p51_n1[]={
+  {2,0,30,  &_residue_44p_lo,
+   &_huff_book__44pn1_short,&_huff_book__44pn1_short,
+   &_resbook_44p_n1,&_resbook_44p_n1},
+
+  {2,0,30,  &_residue_44p_lo,
+   &_huff_book__44pn1_long,&_huff_book__44pn1_long,
+   &_resbook_44p_n1,&_resbook_44p_n1},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44pn1_lfe,&_huff_book__44pn1_lfe,
+   &_resbook_44p_ln1,&_resbook_44p_ln1}
+};
+static const vorbis_residue_template _res_44p51_0[]={
+  {2,0,15,  &_residue_44p_lo,
+   &_huff_book__44p0_short,&_huff_book__44p0_short,
+   &_resbook_44p_0,&_resbook_44p_0},
+
+  {2,0,30,  &_residue_44p_lo,
+   &_huff_book__44p0_long,&_huff_book__44p0_long,
+   &_resbook_44p_0,&_resbook_44p_0},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p0_lfe,&_huff_book__44p0_lfe,
+   &_resbook_44p_l0,&_resbook_44p_l0}
+};
+static const vorbis_residue_template _res_44p51_1[]={
+  {2,0,15,  &_residue_44p_lo,
+   &_huff_book__44p1_short,&_huff_book__44p1_short,
+   &_resbook_44p_1,&_resbook_44p_1},
+
+  {2,0,30,  &_residue_44p_lo,
+   &_huff_book__44p1_long,&_huff_book__44p1_long,
+   &_resbook_44p_1,&_resbook_44p_1},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p1_lfe,&_huff_book__44p1_lfe,
+   &_resbook_44p_l1,&_resbook_44p_l1}
+};
+static const vorbis_residue_template _res_44p51_2[]={
+  {2,0,15,  &_residue_44p,
+   &_huff_book__44p2_short,&_huff_book__44p2_short,
+   &_resbook_44p_2,&_resbook_44p_2},
+
+  {2,0,30,  &_residue_44p,
+   &_huff_book__44p2_long,&_huff_book__44p2_long,
+   &_resbook_44p_2,&_resbook_44p_2},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p2_lfe,&_huff_book__44p2_lfe,
+   &_resbook_44p_l2,&_resbook_44p_l2}
+};
+static const vorbis_residue_template _res_44p51_3[]={
+  {2,0,15,  &_residue_44p,
+   &_huff_book__44p3_short,&_huff_book__44p3_short,
+   &_resbook_44p_3,&_resbook_44p_3},
+
+  {2,0,30,  &_residue_44p,
+   &_huff_book__44p3_long,&_huff_book__44p3_long,
+   &_resbook_44p_3,&_resbook_44p_3},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p3_lfe,&_huff_book__44p3_lfe,
+   &_resbook_44p_l3,&_resbook_44p_l3}
+};
+static const vorbis_residue_template _res_44p51_4[]={
+  {2,0,15,  &_residue_44p,
+   &_huff_book__44p4_short,&_huff_book__44p4_short,
+   &_resbook_44p_4,&_resbook_44p_4},
+
+  {2,0,30,  &_residue_44p,
+   &_huff_book__44p4_long,&_huff_book__44p4_long,
+   &_resbook_44p_4,&_resbook_44p_4},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p4_lfe,&_huff_book__44p4_lfe,
+   &_resbook_44p_l4,&_resbook_44p_l4}
+};
+static const vorbis_residue_template _res_44p51_5[]={
+  {2,0,15,  &_residue_44p_hi,
+   &_huff_book__44p5_short,&_huff_book__44p5_short,
+   &_resbook_44p_5,&_resbook_44p_5},
+
+  {2,0,30,  &_residue_44p_hi,
+   &_huff_book__44p5_long,&_huff_book__44p5_long,
+   &_resbook_44p_5,&_resbook_44p_5},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p5_lfe,&_huff_book__44p5_lfe,
+   &_resbook_44p_l5,&_resbook_44p_l5}
+};
+static const vorbis_residue_template _res_44p51_6[]={
+  {2,0,15,  &_residue_44p_hi,
+   &_huff_book__44p6_short,&_huff_book__44p6_short,
+   &_resbook_44p_6,&_resbook_44p_6},
+
+  {2,0,30,  &_residue_44p_hi,
+   &_huff_book__44p6_long,&_huff_book__44p6_long,
+   &_resbook_44p_6,&_resbook_44p_6},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p6_lfe,&_huff_book__44p6_lfe,
+   &_resbook_44p_l6,&_resbook_44p_l6}
+};
+
+
+static const vorbis_residue_template _res_44p51_7[]={
+  {2,0,15,  &_residue_44p_hi,
+   &_huff_book__44p7_short,&_huff_book__44p7_short,
+   &_resbook_44p_7,&_resbook_44p_7},
+
+  {2,0,30,  &_residue_44p_hi,
+   &_huff_book__44p7_long,&_huff_book__44p7_long,
+   &_resbook_44p_7,&_resbook_44p_7},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p6_lfe,&_huff_book__44p6_lfe,
+   &_resbook_44p_l6,&_resbook_44p_l6}
+};
+static const vorbis_residue_template _res_44p51_8[]={
+  {2,0,15,  &_residue_44p_hi,
+   &_huff_book__44p8_short,&_huff_book__44p8_short,
+   &_resbook_44p_8,&_resbook_44p_8},
+
+  {2,0,30,  &_residue_44p_hi,
+   &_huff_book__44p8_long,&_huff_book__44p8_long,
+   &_resbook_44p_8,&_resbook_44p_8},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p6_lfe,&_huff_book__44p6_lfe,
+   &_resbook_44p_l6,&_resbook_44p_l6}
+};
+static const vorbis_residue_template _res_44p51_9[]={
+  {2,0,15,  &_residue_44p_hi,
+   &_huff_book__44p9_short,&_huff_book__44p9_short,
+   &_resbook_44p_9,&_resbook_44p_9},
+
+  {2,0,30,  &_residue_44p_hi,
+   &_huff_book__44p9_long,&_huff_book__44p9_long,
+   &_resbook_44p_9,&_resbook_44p_9},
+
+  {1,2,6,  &_residue_44p_lfe,
+   &_huff_book__44p6_lfe,&_huff_book__44p6_lfe,
+   &_resbook_44p_l6,&_resbook_44p_l6}
+};
+
+static const vorbis_mapping_template _mapres_template_44_51[]={
+  { _map_nominal_51, _res_44p51_n1 }, /* -1 */
+  { _map_nominal_51, _res_44p51_0 }, /* 0 */
+  { _map_nominal_51, _res_44p51_1 }, /* 1 */
+  { _map_nominal_51, _res_44p51_2 }, /* 2 */
+  { _map_nominal_51, _res_44p51_3 }, /* 3 */
+  { _map_nominal_51, _res_44p51_4 }, /* 4 */
+  { _map_nominal_51u, _res_44p51_5 }, /* 5 */
+  { _map_nominal_51u, _res_44p51_6 }, /* 6 */
+  { _map_nominal_51u, _res_44p51_7 }, /* 7 */
+  { _map_nominal_51u, _res_44p51_8 }, /* 8 */
+  { _map_nominal_51u, _res_44p51_9 }, /* 9 */
+};
diff --git a/vorbis/lib/modes/residue_44u.h b/vorbis/lib/modes/residue_44u.h
new file mode 100644 (file)
index 0000000..e55ac12
--- /dev/null
@@ -0,0 +1,317 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel residue templates for 32/44.1/48kHz uncoupled
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "backends.h"
+#include "books/uncoupled/res_books_uncoupled.h"
+
+/***** residue backends *********************************************/
+
+
+static const vorbis_info_residue0 _residue_44_low_un={
+  0,-1, -1, 8,-1,-1,
+  {0},
+  {-1},
+  {  0,  1,  1,  2,  2,  4, 28},
+  { -1, 25, -1, 45, -1, -1, -1}
+};
+
+static const vorbis_info_residue0 _residue_44_mid_un={
+  0,-1, -1, 10,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8   9 */
+  {0},
+  {-1},
+  {  0,  1,  1,  2,  2,  4,  4, 16, 60},
+  { -1, 30, -1, 50, -1, 80, -1, -1, -1}
+};
+
+static const vorbis_info_residue0 _residue_44_hi_un={
+  0,-1, -1, 10,-1,-1,
+  /* 0   1   2   3   4   5   6   7   8   9 */
+  {0},
+  {-1},
+  {  0,  1,  2,  4,  8, 16, 32, 71,157},
+  { -1, -1, -1, -1, -1, -1, -1, -1, -1}
+};
+
+/* mapping conventions:
+   only one submap (this would change for efficient 5.1 support for example)*/
+/* Four psychoacoustic profiles are used, one for each blocktype */
+static const vorbis_info_mapping0 _map_nominal_u[2]={
+  {1, {0,0,0,0,0,0}, {0}, {0}, 0,{0},{0}},
+  {1, {0,0,0,0,0,0}, {1}, {1}, 0,{0},{0}}
+};
+
+static const static_bookblock _resbook_44u_n1={
+  {
+    {0},
+    {0,0,&_44un1__p1_0},
+    {0,0,&_44un1__p2_0},
+    {0,0,&_44un1__p3_0},
+    {0,0,&_44un1__p4_0},
+    {0,0,&_44un1__p5_0},
+    {&_44un1__p6_0,&_44un1__p6_1},
+    {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_0={
+  {
+    {0},
+    {0,0,&_44u0__p1_0},
+    {0,0,&_44u0__p2_0},
+    {0,0,&_44u0__p3_0},
+    {0,0,&_44u0__p4_0},
+    {0,0,&_44u0__p5_0},
+    {&_44u0__p6_0,&_44u0__p6_1},
+    {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_1={
+  {
+    {0},
+    {0,0,&_44u1__p1_0},
+    {0,0,&_44u1__p2_0},
+    {0,0,&_44u1__p3_0},
+    {0,0,&_44u1__p4_0},
+    {0,0,&_44u1__p5_0},
+    {&_44u1__p6_0,&_44u1__p6_1},
+    {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_2={
+  {
+    {0},
+    {0,0,&_44u2__p1_0},
+    {0,0,&_44u2__p2_0},
+    {0,0,&_44u2__p3_0},
+    {0,0,&_44u2__p4_0},
+    {0,0,&_44u2__p5_0},
+    {&_44u2__p6_0,&_44u2__p6_1},
+    {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_3={
+  {
+    {0},
+    {0,0,&_44u3__p1_0},
+    {0,0,&_44u3__p2_0},
+    {0,0,&_44u3__p3_0},
+    {0,0,&_44u3__p4_0},
+    {0,0,&_44u3__p5_0},
+    {&_44u3__p6_0,&_44u3__p6_1},
+    {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_4={
+  {
+    {0},
+    {0,0,&_44u4__p1_0},
+    {0,0,&_44u4__p2_0},
+    {0,0,&_44u4__p3_0},
+    {0,0,&_44u4__p4_0},
+    {0,0,&_44u4__p5_0},
+    {&_44u4__p6_0,&_44u4__p6_1},
+    {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
+   }
+};
+static const static_bookblock _resbook_44u_5={
+  {
+    {0},
+    {0,0,&_44u5__p1_0},
+    {0,0,&_44u5__p2_0},
+    {0,0,&_44u5__p3_0},
+    {0,0,&_44u5__p4_0},
+    {0,0,&_44u5__p5_0},
+    {0,0,&_44u5__p6_0},
+    {&_44u5__p7_0,&_44u5__p7_1},
+    {&_44u5__p8_0,&_44u5__p8_1},
+    {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
+   }
+};
+static const static_bookblock _resbook_44u_6={
+  {
+    {0},
+    {0,0,&_44u6__p1_0},
+    {0,0,&_44u6__p2_0},
+    {0,0,&_44u6__p3_0},
+    {0,0,&_44u6__p4_0},
+    {0,0,&_44u6__p5_0},
+    {0,0,&_44u6__p6_0},
+    {&_44u6__p7_0,&_44u6__p7_1},
+    {&_44u6__p8_0,&_44u6__p8_1},
+    {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
+   }
+};
+static const static_bookblock _resbook_44u_7={
+  {
+    {0},
+    {0,0,&_44u7__p1_0},
+    {0,0,&_44u7__p2_0},
+    {0,0,&_44u7__p3_0},
+    {0,0,&_44u7__p4_0},
+    {0,0,&_44u7__p5_0},
+    {0,0,&_44u7__p6_0},
+    {&_44u7__p7_0,&_44u7__p7_1},
+    {&_44u7__p8_0,&_44u7__p8_1},
+    {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
+   }
+};
+static const static_bookblock _resbook_44u_8={
+  {
+    {0},
+    {0,0,&_44u8_p1_0},
+    {0,0,&_44u8_p2_0},
+    {0,0,&_44u8_p3_0},
+    {0,0,&_44u8_p4_0},
+    {&_44u8_p5_0,&_44u8_p5_1},
+    {&_44u8_p6_0,&_44u8_p6_1},
+    {&_44u8_p7_0,&_44u8_p7_1},
+    {&_44u8_p8_0,&_44u8_p8_1},
+    {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
+   }
+};
+static const static_bookblock _resbook_44u_9={
+  {
+    {0},
+    {0,0,&_44u9_p1_0},
+    {0,0,&_44u9_p2_0},
+    {0,0,&_44u9_p3_0},
+    {0,0,&_44u9_p4_0},
+    {&_44u9_p5_0,&_44u9_p5_1},
+    {&_44u9_p6_0,&_44u9_p6_1},
+    {&_44u9_p7_0,&_44u9_p7_1},
+    {&_44u9_p8_0,&_44u9_p8_1},
+    {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_44u_n1[]={
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44un1__short,&_huff_book__44un1__short,
+   &_resbook_44u_n1,&_resbook_44u_n1},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44un1__long,&_huff_book__44un1__long,
+   &_resbook_44u_n1,&_resbook_44u_n1}
+};
+static const vorbis_residue_template _res_44u_0[]={
+  {1,0,16,  &_residue_44_low_un,
+   &_huff_book__44u0__short,&_huff_book__44u0__short,
+   &_resbook_44u_0,&_resbook_44u_0},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44u0__long,&_huff_book__44u0__long,
+   &_resbook_44u_0,&_resbook_44u_0}
+};
+static const vorbis_residue_template _res_44u_1[]={
+  {1,0,16,  &_residue_44_low_un,
+   &_huff_book__44u1__short,&_huff_book__44u1__short,
+   &_resbook_44u_1,&_resbook_44u_1},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44u1__long,&_huff_book__44u1__long,
+   &_resbook_44u_1,&_resbook_44u_1}
+};
+static const vorbis_residue_template _res_44u_2[]={
+  {1,0,16,  &_residue_44_low_un,
+   &_huff_book__44u2__short,&_huff_book__44u2__short,
+   &_resbook_44u_2,&_resbook_44u_2},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44u2__long,&_huff_book__44u2__long,
+   &_resbook_44u_2,&_resbook_44u_2}
+};
+static const vorbis_residue_template _res_44u_3[]={
+  {1,0,16,  &_residue_44_low_un,
+   &_huff_book__44u3__short,&_huff_book__44u3__short,
+   &_resbook_44u_3,&_resbook_44u_3},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44u3__long,&_huff_book__44u3__long,
+   &_resbook_44u_3,&_resbook_44u_3}
+};
+static const vorbis_residue_template _res_44u_4[]={
+  {1,0,16,  &_residue_44_low_un,
+   &_huff_book__44u4__short,&_huff_book__44u4__short,
+   &_resbook_44u_4,&_resbook_44u_4},
+
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__44u4__long,&_huff_book__44u4__long,
+   &_resbook_44u_4,&_resbook_44u_4}
+};
+
+static const vorbis_residue_template _res_44u_5[]={
+  {1,0,16,  &_residue_44_mid_un,
+   &_huff_book__44u5__short,&_huff_book__44u5__short,
+   &_resbook_44u_5,&_resbook_44u_5},
+
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__44u5__long,&_huff_book__44u5__long,
+   &_resbook_44u_5,&_resbook_44u_5}
+};
+
+static const vorbis_residue_template _res_44u_6[]={
+  {1,0,16,  &_residue_44_mid_un,
+   &_huff_book__44u6__short,&_huff_book__44u6__short,
+   &_resbook_44u_6,&_resbook_44u_6},
+
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__44u6__long,&_huff_book__44u6__long,
+   &_resbook_44u_6,&_resbook_44u_6}
+};
+
+static const vorbis_residue_template _res_44u_7[]={
+  {1,0,16,  &_residue_44_mid_un,
+   &_huff_book__44u7__short,&_huff_book__44u7__short,
+   &_resbook_44u_7,&_resbook_44u_7},
+
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__44u7__long,&_huff_book__44u7__long,
+   &_resbook_44u_7,&_resbook_44u_7}
+};
+
+static const vorbis_residue_template _res_44u_8[]={
+  {1,0,16,  &_residue_44_hi_un,
+   &_huff_book__44u8__short,&_huff_book__44u8__short,
+   &_resbook_44u_8,&_resbook_44u_8},
+
+  {1,0,32,  &_residue_44_hi_un,
+   &_huff_book__44u8__long,&_huff_book__44u8__long,
+   &_resbook_44u_8,&_resbook_44u_8}
+};
+static const vorbis_residue_template _res_44u_9[]={
+  {1,0,16,  &_residue_44_hi_un,
+   &_huff_book__44u9__short,&_huff_book__44u9__short,
+   &_resbook_44u_9,&_resbook_44u_9},
+
+  {1,0,32,  &_residue_44_hi_un,
+   &_huff_book__44u9__long,&_huff_book__44u9__long,
+   &_resbook_44u_9,&_resbook_44u_9}
+};
+
+static const vorbis_mapping_template _mapres_template_44_uncoupled[]={
+  { _map_nominal_u, _res_44u_n1 }, /* -1 */
+  { _map_nominal_u, _res_44u_0 }, /* 0 */
+  { _map_nominal_u, _res_44u_1 }, /* 1 */
+  { _map_nominal_u, _res_44u_2 }, /* 2 */
+  { _map_nominal_u, _res_44u_3 }, /* 3 */
+  { _map_nominal_u, _res_44u_4 }, /* 4 */
+  { _map_nominal_u, _res_44u_5 }, /* 5 */
+  { _map_nominal_u, _res_44u_6 }, /* 6 */
+  { _map_nominal_u, _res_44u_7 }, /* 7 */
+  { _map_nominal_u, _res_44u_8 }, /* 8 */
+  { _map_nominal_u, _res_44u_9 }, /* 9 */
+};
diff --git a/vorbis/lib/modes/residue_8.h b/vorbis/lib/modes/residue_8.h
new file mode 100644 (file)
index 0000000..ae123a2
--- /dev/null
@@ -0,0 +1,108 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel residue templates 8/11kHz
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "backends.h"
+
+/***** residue backends *********************************************/
+
+static const static_bookblock _resbook_8s_0={
+  {
+    {0},
+    {0,0,&_8c0_s_p1_0},
+    {0},
+    {0,0,&_8c0_s_p3_0},
+    {0,0,&_8c0_s_p4_0},
+    {0,0,&_8c0_s_p5_0},
+    {0,0,&_8c0_s_p6_0},
+    {&_8c0_s_p7_0,&_8c0_s_p7_1},
+    {&_8c0_s_p8_0,&_8c0_s_p8_1},
+    {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
+   }
+};
+static const static_bookblock _resbook_8s_1={
+  {
+    {0},
+    {0,0,&_8c1_s_p1_0},
+    {0},
+    {0,0,&_8c1_s_p3_0},
+    {0,0,&_8c1_s_p4_0},
+    {0,0,&_8c1_s_p5_0},
+    {0,0,&_8c1_s_p6_0},
+    {&_8c1_s_p7_0,&_8c1_s_p7_1},
+    {&_8c1_s_p8_0,&_8c1_s_p8_1},
+    {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_8s_0[]={
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
+   &_resbook_8s_0,&_resbook_8s_0},
+};
+static const vorbis_residue_template _res_8s_1[]={
+  {2,0,32,  &_residue_44_mid,
+   &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
+   &_resbook_8s_1,&_resbook_8s_1},
+};
+
+static const vorbis_mapping_template _mapres_template_8_stereo[2]={
+  { _map_nominal, _res_8s_0 }, /* 0 */
+  { _map_nominal, _res_8s_1 }, /* 1 */
+};
+
+static const static_bookblock _resbook_8u_0={
+  {
+    {0},
+    {0,0,&_8u0__p1_0},
+    {0,0,&_8u0__p2_0},
+    {0,0,&_8u0__p3_0},
+    {0,0,&_8u0__p4_0},
+    {0,0,&_8u0__p5_0},
+    {&_8u0__p6_0,&_8u0__p6_1},
+    {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
+   }
+};
+static const static_bookblock _resbook_8u_1={
+  {
+    {0},
+    {0,0,&_8u1__p1_0},
+    {0,0,&_8u1__p2_0},
+    {0,0,&_8u1__p3_0},
+    {0,0,&_8u1__p4_0},
+    {0,0,&_8u1__p5_0},
+    {0,0,&_8u1__p6_0},
+    {&_8u1__p7_0,&_8u1__p7_1},
+    {&_8u1__p8_0,&_8u1__p8_1},
+    {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
+   }
+};
+
+static const vorbis_residue_template _res_8u_0[]={
+  {1,0,32,  &_residue_44_low_un,
+   &_huff_book__8u0__single,&_huff_book__8u0__single,
+   &_resbook_8u_0,&_resbook_8u_0},
+};
+static const vorbis_residue_template _res_8u_1[]={
+  {1,0,32,  &_residue_44_mid_un,
+   &_huff_book__8u1__single,&_huff_book__8u1__single,
+   &_resbook_8u_1,&_resbook_8u_1},
+};
+
+static const vorbis_mapping_template _mapres_template_8_uncoupled[2]={
+  { _map_nominal_u, _res_8u_0 }, /* 0 */
+  { _map_nominal_u, _res_8u_1 }, /* 1 */
+};
diff --git a/vorbis/lib/modes/setup_11.h b/vorbis/lib/modes/setup_11.h
new file mode 100644 (file)
index 0000000..0cbcaaf
--- /dev/null
@@ -0,0 +1,142 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 11kHz settings
+
+ ********************************************************************/
+
+#include "psych_11.h"
+
+static const int blocksize_11[2]={
+  512,512
+};
+
+static const int _floor_mapping_11a[]={
+  6,6
+};
+static const int *_floor_mapping_11[]={
+  _floor_mapping_11a
+};
+
+static const double rate_mapping_11[3]={
+  8000.,13000.,44000.,
+};
+
+static const double rate_mapping_11_uncoupled[3]={
+  12000.,20000.,50000.,
+};
+
+static const double quality_mapping_11[3]={
+  -.1,.0,1.
+};
+
+static const ve_setup_data_template ve_setup_11_stereo={
+  2,
+  rate_mapping_11,
+  quality_mapping_11,
+  2,
+  9000,
+  15000,
+
+  blocksize_11,
+  blocksize_11,
+
+  _psy_tone_masteratt_11,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_11,
+  NULL,
+  _vp_tonemask_adj_11,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_11,
+  _psy_noisebias_11,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_11,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_11,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_11,
+
+  _mapres_template_8_stereo
+};
+
+static const ve_setup_data_template ve_setup_11_uncoupled={
+  2,
+  rate_mapping_11_uncoupled,
+  quality_mapping_11,
+  -1,
+  9000,
+  15000,
+
+  blocksize_11,
+  blocksize_11,
+
+  _psy_tone_masteratt_11,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_11,
+  NULL,
+  _vp_tonemask_adj_11,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_11,
+  _psy_noisebias_11,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_11,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_11,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_11,
+
+  _mapres_template_8_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_16.h b/vorbis/lib/modes/setup_16.h
new file mode 100644 (file)
index 0000000..d59ad70
--- /dev/null
@@ -0,0 +1,152 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 16kHz settings
+
+ ********************************************************************/
+
+#include "psych_16.h"
+#include "residue_16.h"
+
+static const int blocksize_16_short[3]={
+  1024,512,512
+};
+static const int blocksize_16_long[3]={
+  1024,1024,1024
+};
+
+static const int _floor_mapping_16a[]={
+  9,3,3
+};
+static const int _floor_mapping_16b[]={
+  9,9,9
+};
+static const int *_floor_mapping_16[]={
+  _floor_mapping_16a,
+  _floor_mapping_16b
+};
+
+static const double rate_mapping_16[4]={
+  12000.,20000.,44000.,86000.
+};
+
+static const double rate_mapping_16_uncoupled[4]={
+  16000.,28000.,64000.,100000.
+};
+
+static const double _global_mapping_16[4]={ 1., 2., 3., 4. };
+
+static const double quality_mapping_16[4]={ -.1,.05,.5,1. };
+
+static const double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
+
+static const ve_setup_data_template ve_setup_16_stereo={
+  3,
+  rate_mapping_16,
+  quality_mapping_16,
+  2,
+  15000,
+  19000,
+
+  blocksize_16_short,
+  blocksize_16_long,
+
+  _psy_tone_masteratt_16,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+
+  _psy_noiseguards_16,
+  _psy_noisebias_16_impulse,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_16_mapping,
+  _psy_compand_16_mapping,
+
+  {_noise_start_16,_noise_start_16},
+  { _noise_part_16, _noise_part_16},
+  _noise_thresh_16,
+
+  _psy_ath_floater_16,
+  _psy_ath_abs_16,
+
+  _psy_lowpass_16,
+
+  _psy_global_44,
+  _global_mapping_16,
+  _psy_stereo_modes_16,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_16,
+
+  _mapres_template_16_stereo
+};
+
+static const ve_setup_data_template ve_setup_16_uncoupled={
+  3,
+  rate_mapping_16_uncoupled,
+  quality_mapping_16,
+  -1,
+  15000,
+  19000,
+
+  blocksize_16_short,
+  blocksize_16_long,
+
+  _psy_tone_masteratt_16,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+
+  _psy_noiseguards_16,
+  _psy_noisebias_16_impulse,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_16_mapping,
+  _psy_compand_16_mapping,
+
+  {_noise_start_16,_noise_start_16},
+  { _noise_part_16, _noise_part_16},
+  _noise_thresh_16,
+
+  _psy_ath_floater_16,
+  _psy_ath_abs_16,
+
+  _psy_lowpass_16,
+
+  _psy_global_44,
+  _global_mapping_16,
+  _psy_stereo_modes_16,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_16,
+
+  _mapres_template_16_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_22.h b/vorbis/lib/modes/setup_22.h
new file mode 100644 (file)
index 0000000..bc38af9
--- /dev/null
@@ -0,0 +1,127 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 22kHz settings
+
+ ********************************************************************/
+
+static const double rate_mapping_22[4]={
+  15000.,20000.,44000.,86000.
+};
+
+static const double rate_mapping_22_uncoupled[4]={
+  16000.,28000.,50000.,90000.
+};
+
+static const double _psy_lowpass_22[4]={9.5,11.,30.,99.};
+
+static const ve_setup_data_template ve_setup_22_stereo={
+  3,
+  rate_mapping_22,
+  quality_mapping_16,
+  2,
+  19000,
+  26000,
+
+  blocksize_16_short,
+  blocksize_16_long,
+
+  _psy_tone_masteratt_16,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+
+  _psy_noiseguards_16,
+  _psy_noisebias_16_impulse,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_16_mapping,
+  _psy_compand_16_mapping,
+
+  {_noise_start_16,_noise_start_16},
+  { _noise_part_16, _noise_part_16},
+  _noise_thresh_16,
+
+  _psy_ath_floater_16,
+  _psy_ath_abs_16,
+
+  _psy_lowpass_22,
+
+  _psy_global_44,
+  _global_mapping_16,
+  _psy_stereo_modes_16,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_16,
+
+  _mapres_template_16_stereo
+};
+
+static const ve_setup_data_template ve_setup_22_uncoupled={
+  3,
+  rate_mapping_22_uncoupled,
+  quality_mapping_16,
+  -1,
+  19000,
+  26000,
+
+  blocksize_16_short,
+  blocksize_16_long,
+
+  _psy_tone_masteratt_16,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+  _vp_tonemask_adj_16,
+
+  _psy_noiseguards_16,
+  _psy_noisebias_16_impulse,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16_short,
+  _psy_noisebias_16,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_16_mapping,
+  _psy_compand_16_mapping,
+
+  {_noise_start_16,_noise_start_16},
+  { _noise_part_16, _noise_part_16},
+  _noise_thresh_16,
+
+  _psy_ath_floater_16,
+  _psy_ath_abs_16,
+
+  _psy_lowpass_22,
+
+  _psy_global_44,
+  _global_mapping_16,
+  _psy_stereo_modes_16,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_16,
+
+  _mapres_template_16_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_32.h b/vorbis/lib/modes/setup_32.h
new file mode 100644 (file)
index 0000000..f66a0bc
--- /dev/null
@@ -0,0 +1,131 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel settings for 32kHz
+
+ ********************************************************************/
+
+static const double rate_mapping_32[12]={
+  18000.,28000.,35000.,45000.,56000.,60000.,
+  75000.,90000.,100000.,115000.,150000.,190000.,
+};
+
+static const double rate_mapping_32_un[12]={
+  30000.,42000.,52000.,64000.,72000.,78000.,
+  86000.,92000.,110000.,120000.,140000.,190000.,
+};
+
+static const double _psy_lowpass_32[12]={
+  12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
+};
+
+static const ve_setup_data_template ve_setup_32_stereo={
+  11,
+  rate_mapping_32,
+  quality_mapping_44,
+  2,
+  26000,
+  40000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_32,
+
+  _psy_global_44,
+  _global_mapping_44,
+  _psy_stereo_modes_44,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_stereo
+};
+
+static const ve_setup_data_template ve_setup_32_uncoupled={
+  11,
+  rate_mapping_32_un,
+  quality_mapping_44,
+  -1,
+  26000,
+  40000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_32,
+
+  _psy_global_44,
+  _global_mapping_44,
+  NULL,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_44.h b/vorbis/lib/modes/setup_44.h
new file mode 100644 (file)
index 0000000..a189b5f
--- /dev/null
@@ -0,0 +1,116 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel settings for 44.1/48kHz
+
+ ********************************************************************/
+
+#include "modes/floor_all.h"
+#include "modes/residue_44.h"
+#include "modes/psych_44.h"
+
+static const double rate_mapping_44_stereo[12]={
+  22500.,32000.,40000.,48000.,56000.,64000.,
+  80000.,96000.,112000.,128000.,160000.,250001.
+};
+
+static const double quality_mapping_44[12]={
+  -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
+};
+
+static const int blocksize_short_44[11]={
+  512,256,256,256,256,256,256,256,256,256,256
+};
+static const int blocksize_long_44[11]={
+  4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
+};
+
+static const double _psy_compand_short_mapping[12]={
+  0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
+};
+static const double _psy_compand_long_mapping[12]={
+  3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
+};
+
+static const double _global_mapping_44[12]={
+  /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
+ 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
+};
+
+static const int _floor_mapping_44a[11]={
+  1,0,0,2,2,4,5,5,5,5,5
+};
+
+static const int _floor_mapping_44b[11]={
+  8,7,7,7,7,7,7,7,7,7,7
+};
+
+static const int _floor_mapping_44c[11]={
+  10,10,10,10,10,10,10,10,10,10,10
+};
+
+static const int *_floor_mapping_44[]={
+  _floor_mapping_44a,
+  _floor_mapping_44b,
+  _floor_mapping_44c,
+};
+
+static const ve_setup_data_template ve_setup_44_stereo={
+  11,
+  rate_mapping_44_stereo,
+  quality_mapping_44,
+  2,
+  40000,
+  50000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_44,
+
+  _psy_global_44,
+  _global_mapping_44,
+  _psy_stereo_modes_44,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_stereo
+};
diff --git a/vorbis/lib/modes/setup_44p51.h b/vorbis/lib/modes/setup_44p51.h
new file mode 100644 (file)
index 0000000..3bde7b3
--- /dev/null
@@ -0,0 +1,73 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel settings for 44.1/48kHz 5.1 surround modes
+
+ ********************************************************************/
+
+#include "modes/residue_44p51.h"
+
+static const double rate_mapping_44p51[12]={
+  14000.,20000.,28000.,38000.,46000.,54000.,
+  75000.,96000.,120000.,140000.,180000.,240001.
+};
+
+static const ve_setup_data_template ve_setup_44_51={
+  11,
+  rate_mapping_44p51,
+  quality_mapping_44,
+  6,
+  40000,
+  70000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_44,
+
+  _psy_global_44,
+  _global_mapping_44,
+  _psy_stereo_modes_44,
+
+  _floor_books,
+  _floor,
+  3,
+  _floor_mapping_44,
+
+  _mapres_template_44_51
+};
diff --git a/vorbis/lib/modes/setup_44u.h b/vorbis/lib/modes/setup_44u.h
new file mode 100644 (file)
index 0000000..7ae3af6
--- /dev/null
@@ -0,0 +1,73 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: toplevel settings for 44.1/48kHz uncoupled modes
+
+ ********************************************************************/
+
+#include "modes/residue_44u.h"
+
+static const double rate_mapping_44_un[12]={
+  32000.,48000.,60000.,70000.,80000.,86000.,
+  96000.,110000.,120000.,140000.,160000.,240001.
+};
+
+static const ve_setup_data_template ve_setup_44_uncoupled={
+  11,
+  rate_mapping_44_un,
+  quality_mapping_44,
+  -1,
+  40000,
+  50000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_44,
+
+  _psy_global_44,
+  _global_mapping_44,
+  _psy_stereo_modes_44,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_8.h b/vorbis/lib/modes/setup_8.h
new file mode 100644 (file)
index 0000000..7502556
--- /dev/null
@@ -0,0 +1,148 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: 8kHz settings
+
+ ********************************************************************/
+
+#include "psych_8.h"
+#include "residue_8.h"
+
+static const int blocksize_8[2]={
+  512,512
+};
+
+static const int _floor_mapping_8a[]={
+  6,6
+};
+
+static const int *_floor_mapping_8[]={
+  _floor_mapping_8a
+};
+
+static const double rate_mapping_8[3]={
+  6000.,9000.,32000.,
+};
+
+static const double rate_mapping_8_uncoupled[3]={
+  8000.,14000.,42000.,
+};
+
+static const double quality_mapping_8[3]={
+  -.1,.0,1.
+};
+
+static const double _psy_compand_8_mapping[3]={ 0., 1., 1.};
+
+static const double _global_mapping_8[3]={ 1., 2., 3. };
+
+static const ve_setup_data_template ve_setup_8_stereo={
+  2,
+  rate_mapping_8,
+  quality_mapping_8,
+  2,
+  8000,
+  9000,
+
+  blocksize_8,
+  blocksize_8,
+
+  _psy_tone_masteratt_8,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_8,
+  NULL,
+  _vp_tonemask_adj_8,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_8,
+  _psy_noisebias_8,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_5only,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_8,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_8,
+
+  _mapres_template_8_stereo
+};
+
+static const ve_setup_data_template ve_setup_8_uncoupled={
+  2,
+  rate_mapping_8_uncoupled,
+  quality_mapping_8,
+  -1,
+  8000,
+  9000,
+
+  blocksize_8,
+  blocksize_8,
+
+  _psy_tone_masteratt_8,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_8,
+  NULL,
+  _vp_tonemask_adj_8,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_8,
+  _psy_noisebias_8,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_5only,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_8,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_8,
+
+  _mapres_template_8_uncoupled
+};
diff --git a/vorbis/lib/modes/setup_X.h b/vorbis/lib/modes/setup_X.h
new file mode 100644 (file)
index 0000000..2229a5e
--- /dev/null
@@ -0,0 +1,224 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: catch-all toplevel settings for q modes only
+
+ ********************************************************************/
+
+static const double rate_mapping_X[12]={
+  -1.,-1.,-1.,-1.,-1.,-1.,
+  -1.,-1.,-1.,-1.,-1.,-1.
+};
+
+static const ve_setup_data_template ve_setup_X_stereo={
+  11,
+  rate_mapping_X,
+  quality_mapping_44,
+  2,
+  50000,
+  200000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_44,
+
+  _psy_global_44,
+  _global_mapping_44,
+  _psy_stereo_modes_44,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_stereo
+};
+
+static const ve_setup_data_template ve_setup_X_uncoupled={
+  11,
+  rate_mapping_X,
+  quality_mapping_44,
+  -1,
+  50000,
+  200000,
+
+  blocksize_short_44,
+  blocksize_long_44,
+
+  _psy_tone_masteratt_44,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_otherblock,
+  _vp_tonemask_adj_longblock,
+  _vp_tonemask_adj_otherblock,
+
+  _psy_noiseguards_44,
+  _psy_noisebias_impulse,
+  _psy_noisebias_padding,
+  _psy_noisebias_trans,
+  _psy_noisebias_long,
+  _psy_noise_suppress,
+
+  _psy_compand_44,
+  _psy_compand_short_mapping,
+  _psy_compand_long_mapping,
+
+  {_noise_start_short_44,_noise_start_long_44},
+  {_noise_part_short_44,_noise_part_long_44},
+  _noise_thresh_44,
+
+  _psy_ath_floater,
+  _psy_ath_abs,
+
+  _psy_lowpass_44,
+
+  _psy_global_44,
+  _global_mapping_44,
+  NULL,
+
+  _floor_books,
+  _floor,
+  2,
+  _floor_mapping_44,
+
+  _mapres_template_44_uncoupled
+};
+
+static const ve_setup_data_template ve_setup_XX_stereo={
+  2,
+  rate_mapping_X,
+  quality_mapping_8,
+  2,
+  0,
+  8000,
+
+  blocksize_8,
+  blocksize_8,
+
+  _psy_tone_masteratt_8,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_8,
+  NULL,
+  _vp_tonemask_adj_8,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_8,
+  _psy_noisebias_8,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_5only,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_8,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_8,
+
+  _mapres_template_8_stereo
+};
+
+static const ve_setup_data_template ve_setup_XX_uncoupled={
+  2,
+  rate_mapping_X,
+  quality_mapping_8,
+  -1,
+  0,
+  8000,
+
+  blocksize_8,
+  blocksize_8,
+
+  _psy_tone_masteratt_8,
+  _psy_tone_0dB,
+  _psy_tone_suppress,
+
+  _vp_tonemask_adj_8,
+  NULL,
+  _vp_tonemask_adj_8,
+
+  _psy_noiseguards_8,
+  _psy_noisebias_8,
+  _psy_noisebias_8,
+  NULL,
+  NULL,
+  _psy_noise_suppress,
+
+  _psy_compand_8,
+  _psy_compand_8_mapping,
+  NULL,
+
+  {_noise_start_8,_noise_start_8},
+  {_noise_part_8,_noise_part_8},
+  _noise_thresh_5only,
+
+  _psy_ath_floater_8,
+  _psy_ath_abs_8,
+
+  _psy_lowpass_8,
+
+  _psy_global_44,
+  _global_mapping_8,
+  _psy_stereo_modes_8,
+
+  _floor_books,
+  _floor,
+  1,
+  _floor_mapping_8,
+
+  _mapres_template_8_uncoupled
+};
diff --git a/vorbis/lib/os.h b/vorbis/lib/os.h
new file mode 100644 (file)
index 0000000..416a401
--- /dev/null
@@ -0,0 +1,190 @@
+#ifndef _OS_H
+#define _OS_H
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: #ifdef jail to whip a few platforms into the UNIX ideal.
+
+ ********************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <math.h>
+#include <ogg/os_types.h>
+
+#include "misc.h"
+
+#ifndef _V_IFDEFJAIL_H_
+#  define _V_IFDEFJAIL_H_
+
+#  ifdef __GNUC__
+#    define STIN static __inline__
+#  elif defined(_WIN32)
+#    define STIN static __inline
+#  else
+#    define STIN static
+#  endif
+
+#ifdef DJGPP
+#  define rint(x)   (floor((x)+0.5f))
+#endif
+
+#ifndef M_PI
+#  define M_PI (3.1415926536f)
+#endif
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+#  include <malloc.h>
+#  define rint(x)   (floor((x)+0.5f))
+#  define NO_FLOAT_MATH_LIB
+#  define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
+#endif
+
+#if defined(__SYMBIAN32__) && defined(__WINS__)
+void *_alloca(size_t size);
+#  define alloca _alloca
+#endif
+
+#ifndef FAST_HYPOT
+#  define FAST_HYPOT hypot
+#endif
+
+#endif
+
+#ifdef HAVE_ALLOCA_H
+#  include <alloca.h>
+#endif
+
+#ifdef USE_MEMORY_H
+#  include <memory.h>
+#endif
+
+#ifndef min
+#  define min(x,y)  ((x)>(y)?(y):(x))
+#endif
+
+#ifndef max
+#  define max(x,y)  ((x)<(y)?(y):(x))
+#endif
+
+
+/* Special i386 GCC implementation */
+#if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
+#  define VORBIS_FPU_CONTROL
+/* both GCC and MSVC are kinda stupid about rounding/casting to int.
+   Because of encapsulation constraints (GCC can't see inside the asm
+   block and so we end up doing stupid things like a store/load that
+   is collectively a noop), we do it this way */
+
+/* we must set up the fpu before this works!! */
+
+typedef ogg_int16_t vorbis_fpu_control;
+
+static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
+  ogg_int16_t ret;
+  ogg_int16_t temp;
+  __asm__ __volatile__("fnstcw %0\n\t"
+          "movw %0,%%dx\n\t"
+          "andw $62463,%%dx\n\t"
+          "movw %%dx,%1\n\t"
+          "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
+  *fpu=ret;
+}
+
+static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
+  __asm__ __volatile__("fldcw %0":: "m"(fpu));
+}
+
+/* assumes the FPU is in round mode! */
+static inline int vorbis_ftoi(double f){  /* yes, double!  Otherwise,
+                                             we get extra fst/fld to
+                                             truncate precision */
+  int i;
+  __asm__("fistl %0": "=m"(i) : "t"(f));
+  return(i);
+}
+#endif /* Special i386 GCC implementation */
+
+
+/* MSVC inline assembly. 32 bit only; inline ASM isn't implemented in the
+ * 64 bit compiler and doesn't work on arm. */
+#if defined(_MSC_VER) && !defined(_WIN64) && \
+      !defined(_WIN32_WCE) && !defined(_M_ARM)
+#  define VORBIS_FPU_CONTROL
+
+typedef ogg_int16_t vorbis_fpu_control;
+
+static __inline int vorbis_ftoi(double f){
+        int i;
+        __asm{
+                fld f
+                fistp i
+        }
+        return i;
+}
+
+static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
+  (void)fpu;
+}
+
+static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
+  (void)fpu;
+}
+
+#endif /* Special MSVC 32 bit implementation */
+
+
+/* Optimized code path for x86_64 builds. Uses SSE2 intrinsics. This can be
+   done safely because all x86_64 CPUs supports SSE2. */
+#if (defined(_MSC_VER) && defined(_WIN64)) || (defined(__GNUC__) && defined (__x86_64__))
+#  define VORBIS_FPU_CONTROL
+
+typedef ogg_int16_t vorbis_fpu_control;
+
+#include <emmintrin.h>
+static __inline int vorbis_ftoi(double f){
+        return _mm_cvtsd_si32(_mm_load_sd(&f));
+}
+
+static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
+  (void)fpu;
+}
+
+static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
+  (void)fpu;
+}
+
+#endif /* Special MSVC x64 implementation */
+
+
+/* If no special implementation was found for the current compiler / platform,
+   use the default implementation here: */
+#ifndef VORBIS_FPU_CONTROL
+
+typedef int vorbis_fpu_control;
+
+static int vorbis_ftoi(double f){
+        /* Note: MSVC and GCC (at least on some systems) round towards zero, thus,
+           the floor() call is required to ensure correct roudning of
+           negative numbers */
+        return (int)floor(f+.5);
+}
+
+/* We don't have special code for this compiler/arch, so do it the slow way */
+#  define vorbis_fpu_setround(vorbis_fpu_control) {}
+#  define vorbis_fpu_restore(vorbis_fpu_control) {}
+
+#endif /* default implementation */
+
+#endif /* _OS_H */
diff --git a/vorbis/lib/psy.c b/vorbis/lib/psy.c
new file mode 100644 (file)
index 0000000..422c6f1
--- /dev/null
@@ -0,0 +1,1205 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: psychoacoustics not including preecho
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+
+#include "masking.h"
+#include "psy.h"
+#include "os.h"
+#include "lpc.h"
+#include "smallft.h"
+#include "scales.h"
+#include "misc.h"
+
+#define NEGINF -9999.f
+static const double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
+static const double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
+
+vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *gi=&ci->psy_g_param;
+  vorbis_look_psy_global *look=_ogg_calloc(1,sizeof(*look));
+
+  look->channels=vi->channels;
+
+  look->ampmax=-9999.;
+  look->gi=gi;
+  return(look);
+}
+
+void _vp_global_free(vorbis_look_psy_global *look){
+  if(look){
+    memset(look,0,sizeof(*look));
+    _ogg_free(look);
+  }
+}
+
+void _vi_gpsy_free(vorbis_info_psy_global *i){
+  if(i){
+    memset(i,0,sizeof(*i));
+    _ogg_free(i);
+  }
+}
+
+void _vi_psy_free(vorbis_info_psy *i){
+  if(i){
+    memset(i,0,sizeof(*i));
+    _ogg_free(i);
+  }
+}
+
+static void min_curve(float *c,
+                       float *c2){
+  int i;
+  for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
+}
+static void max_curve(float *c,
+                       float *c2){
+  int i;
+  for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
+}
+
+static void attenuate_curve(float *c,float att){
+  int i;
+  for(i=0;i<EHMER_MAX;i++)
+    c[i]+=att;
+}
+
+static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
+                                  float center_boost, float center_decay_rate){
+  int i,j,k,m;
+  float ath[EHMER_MAX];
+  float workc[P_BANDS][P_LEVELS][EHMER_MAX];
+  float athc[P_LEVELS][EHMER_MAX];
+  float *brute_buffer=alloca(n*sizeof(*brute_buffer));
+
+  float ***ret=_ogg_malloc(sizeof(*ret)*P_BANDS);
+
+  memset(workc,0,sizeof(workc));
+
+  for(i=0;i<P_BANDS;i++){
+    /* we add back in the ATH to avoid low level curves falling off to
+       -infinity and unnecessarily cutting off high level curves in the
+       curve limiting (last step). */
+
+    /* A half-band's settings must be valid over the whole band, and
+       it's better to mask too little than too much */
+    int ath_offset=i*4;
+    for(j=0;j<EHMER_MAX;j++){
+      float min=999.;
+      for(k=0;k<4;k++)
+        if(j+k+ath_offset<MAX_ATH){
+          if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
+        }else{
+          if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
+        }
+      ath[j]=min;
+    }
+
+    /* copy curves into working space, replicate the 50dB curve to 30
+       and 40, replicate the 100dB curve to 110 */
+    for(j=0;j<6;j++)
+      memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
+    memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
+    memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
+
+    /* apply centered curve boost/decay */
+    for(j=0;j<P_LEVELS;j++){
+      for(k=0;k<EHMER_MAX;k++){
+        float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
+        if(adj<0. && center_boost>0)adj=0.;
+        if(adj>0. && center_boost<0)adj=0.;
+        workc[i][j][k]+=adj;
+      }
+    }
+
+    /* normalize curves so the driving amplitude is 0dB */
+    /* make temp curves with the ATH overlayed */
+    for(j=0;j<P_LEVELS;j++){
+      attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
+      memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
+      attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
+      max_curve(athc[j],workc[i][j]);
+    }
+
+    /* Now limit the louder curves.
+
+       the idea is this: We don't know what the playback attenuation
+       will be; 0dB SL moves every time the user twiddles the volume
+       knob. So that means we have to use a single 'most pessimal' curve
+       for all masking amplitudes, right?  Wrong.  The *loudest* sound
+       can be in (we assume) a range of ...+100dB] SL.  However, sounds
+       20dB down will be in a range ...+80], 40dB down is from ...+60],
+       etc... */
+
+    for(j=1;j<P_LEVELS;j++){
+      min_curve(athc[j],athc[j-1]);
+      min_curve(workc[i][j],athc[j]);
+    }
+  }
+
+  for(i=0;i<P_BANDS;i++){
+    int hi_curve,lo_curve,bin;
+    ret[i]=_ogg_malloc(sizeof(**ret)*P_LEVELS);
+
+    /* low frequency curves are measured with greater resolution than
+       the MDCT/FFT will actually give us; we want the curve applied
+       to the tone data to be pessimistic and thus apply the minimum
+       masking possible for a given bin.  That means that a single bin
+       could span more than one octave and that the curve will be a
+       composite of multiple octaves.  It also may mean that a single
+       bin may span > an eighth of an octave and that the eighth
+       octave values may also be composited. */
+
+    /* which octave curves will we be compositing? */
+    bin=floor(fromOC(i*.5)/binHz);
+    lo_curve=  ceil(toOC(bin*binHz+1)*2);
+    hi_curve=  floor(toOC((bin+1)*binHz)*2);
+    if(lo_curve>i)lo_curve=i;
+    if(lo_curve<0)lo_curve=0;
+    if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
+
+    for(m=0;m<P_LEVELS;m++){
+      ret[i][m]=_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
+
+      for(j=0;j<n;j++)brute_buffer[j]=999.;
+
+      /* render the curve into bins, then pull values back into curve.
+         The point is that any inherent subsampling aliasing results in
+         a safe minimum */
+      for(k=lo_curve;k<=hi_curve;k++){
+        int l=0;
+
+        for(j=0;j<EHMER_MAX;j++){
+          int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
+          int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
+
+          if(lo_bin<0)lo_bin=0;
+          if(lo_bin>n)lo_bin=n;
+          if(lo_bin<l)l=lo_bin;
+          if(hi_bin<0)hi_bin=0;
+          if(hi_bin>n)hi_bin=n;
+
+          for(;l<hi_bin && l<n;l++)
+            if(brute_buffer[l]>workc[k][m][j])
+              brute_buffer[l]=workc[k][m][j];
+        }
+
+        for(;l<n;l++)
+          if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
+            brute_buffer[l]=workc[k][m][EHMER_MAX-1];
+
+      }
+
+      /* be equally paranoid about being valid up to next half ocatve */
+      if(i+1<P_BANDS){
+        int l=0;
+        k=i+1;
+        for(j=0;j<EHMER_MAX;j++){
+          int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
+          int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
+
+          if(lo_bin<0)lo_bin=0;
+          if(lo_bin>n)lo_bin=n;
+          if(lo_bin<l)l=lo_bin;
+          if(hi_bin<0)hi_bin=0;
+          if(hi_bin>n)hi_bin=n;
+
+          for(;l<hi_bin && l<n;l++)
+            if(brute_buffer[l]>workc[k][m][j])
+              brute_buffer[l]=workc[k][m][j];
+        }
+
+        for(;l<n;l++)
+          if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
+            brute_buffer[l]=workc[k][m][EHMER_MAX-1];
+
+      }
+
+
+      for(j=0;j<EHMER_MAX;j++){
+        int bin=fromOC(j*.125+i*.5-2.)/binHz;
+        if(bin<0){
+          ret[i][m][j+2]=-999.;
+        }else{
+          if(bin>=n){
+            ret[i][m][j+2]=-999.;
+          }else{
+            ret[i][m][j+2]=brute_buffer[bin];
+          }
+        }
+      }
+
+      /* add fenceposts */
+      for(j=0;j<EHMER_OFFSET;j++)
+        if(ret[i][m][j+2]>-200.f)break;
+      ret[i][m][0]=j;
+
+      for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
+        if(ret[i][m][j+2]>-200.f)
+          break;
+      ret[i][m][1]=j;
+
+    }
+  }
+
+  return(ret);
+}
+
+void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
+                  vorbis_info_psy_global *gi,int n,long rate){
+  long i,j,lo=-99,hi=1;
+  long maxoc;
+  memset(p,0,sizeof(*p));
+
+  p->eighth_octave_lines=gi->eighth_octave_lines;
+  p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
+
+  p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
+  maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
+  p->total_octave_lines=maxoc-p->firstoc+1;
+  p->ath=_ogg_malloc(n*sizeof(*p->ath));
+
+  p->octave=_ogg_malloc(n*sizeof(*p->octave));
+  p->bark=_ogg_malloc(n*sizeof(*p->bark));
+  p->vi=vi;
+  p->n=n;
+  p->rate=rate;
+
+  /* AoTuV HF weighting */
+  p->m_val = 1.;
+  if(rate < 26000) p->m_val = 0;
+  else if(rate < 38000) p->m_val = .94;   /* 32kHz */
+  else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
+
+  /* set up the lookups for a given blocksize and sample rate */
+
+  for(i=0,j=0;i<MAX_ATH-1;i++){
+    int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
+    float base=ATH[i];
+    if(j<endpos){
+      float delta=(ATH[i+1]-base)/(endpos-j);
+      for(;j<endpos && j<n;j++){
+        p->ath[j]=base+100.;
+        base+=delta;
+      }
+    }
+  }
+
+  for(;j<n;j++){
+    p->ath[j]=p->ath[j-1];
+  }
+
+  for(i=0;i<n;i++){
+    float bark=toBARK(rate/(2*n)*i);
+
+    for(;lo+vi->noisewindowlomin<i &&
+          toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
+
+    for(;hi<=n && (hi<i+vi->noisewindowhimin ||
+          toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
+
+    p->bark[i]=((lo-1)<<16)+(hi-1);
+
+  }
+
+  for(i=0;i<n;i++)
+    p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
+
+  p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
+                                  vi->tone_centerboost,vi->tone_decay);
+
+  /* set up rolling noise median */
+  p->noiseoffset=_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
+  for(i=0;i<P_NOISECURVES;i++)
+    p->noiseoffset[i]=_ogg_malloc(n*sizeof(**p->noiseoffset));
+
+  for(i=0;i<n;i++){
+    float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
+    int inthalfoc;
+    float del;
+
+    if(halfoc<0)halfoc=0;
+    if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
+    inthalfoc=(int)halfoc;
+    del=halfoc-inthalfoc;
+
+    for(j=0;j<P_NOISECURVES;j++)
+      p->noiseoffset[j][i]=
+        p->vi->noiseoff[j][inthalfoc]*(1.-del) +
+        p->vi->noiseoff[j][inthalfoc+1]*del;
+
+  }
+#if 0
+  {
+    static int ls=0;
+    _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
+    _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
+    _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
+  }
+#endif
+}
+
+void _vp_psy_clear(vorbis_look_psy *p){
+  int i,j;
+  if(p){
+    if(p->ath)_ogg_free(p->ath);
+    if(p->octave)_ogg_free(p->octave);
+    if(p->bark)_ogg_free(p->bark);
+    if(p->tonecurves){
+      for(i=0;i<P_BANDS;i++){
+        for(j=0;j<P_LEVELS;j++){
+          _ogg_free(p->tonecurves[i][j]);
+        }
+        _ogg_free(p->tonecurves[i]);
+      }
+      _ogg_free(p->tonecurves);
+    }
+    if(p->noiseoffset){
+      for(i=0;i<P_NOISECURVES;i++){
+        _ogg_free(p->noiseoffset[i]);
+      }
+      _ogg_free(p->noiseoffset);
+    }
+    memset(p,0,sizeof(*p));
+  }
+}
+
+/* octave/(8*eighth_octave_lines) x scale and dB y scale */
+static void seed_curve(float *seed,
+                       const float **curves,
+                       float amp,
+                       int oc, int n,
+                       int linesper,float dBoffset){
+  int i,post1;
+  int seedptr;
+  const float *posts,*curve;
+
+  int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
+  choice=max(choice,0);
+  choice=min(choice,P_LEVELS-1);
+  posts=curves[choice];
+  curve=posts+2;
+  post1=(int)posts[1];
+  seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
+
+  for(i=posts[0];i<post1;i++){
+    if(seedptr>0){
+      float lin=amp+curve[i];
+      if(seed[seedptr]<lin)seed[seedptr]=lin;
+    }
+    seedptr+=linesper;
+    if(seedptr>=n)break;
+  }
+}
+
+static void seed_loop(vorbis_look_psy *p,
+                      const float ***curves,
+                      const float *f,
+                      const float *flr,
+                      float *seed,
+                      float specmax){
+  vorbis_info_psy *vi=p->vi;
+  long n=p->n,i;
+  float dBoffset=vi->max_curve_dB-specmax;
+
+  /* prime the working vector with peak values */
+
+  for(i=0;i<n;i++){
+    float max=f[i];
+    long oc=p->octave[i];
+    while(i+1<n && p->octave[i+1]==oc){
+      i++;
+      if(f[i]>max)max=f[i];
+    }
+
+    if(max+6.f>flr[i]){
+      oc=oc>>p->shiftoc;
+
+      if(oc>=P_BANDS)oc=P_BANDS-1;
+      if(oc<0)oc=0;
+
+      seed_curve(seed,
+                 curves[oc],
+                 max,
+                 p->octave[i]-p->firstoc,
+                 p->total_octave_lines,
+                 p->eighth_octave_lines,
+                 dBoffset);
+    }
+  }
+}
+
+static void seed_chase(float *seeds, int linesper, long n){
+  long  *posstack=alloca(n*sizeof(*posstack));
+  float *ampstack=alloca(n*sizeof(*ampstack));
+  long   stack=0;
+  long   pos=0;
+  long   i;
+
+  for(i=0;i<n;i++){
+    if(stack<2){
+      posstack[stack]=i;
+      ampstack[stack++]=seeds[i];
+    }else{
+      while(1){
+        if(seeds[i]<ampstack[stack-1]){
+          posstack[stack]=i;
+          ampstack[stack++]=seeds[i];
+          break;
+        }else{
+          if(i<posstack[stack-1]+linesper){
+            if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
+               i<posstack[stack-2]+linesper){
+              /* we completely overlap, making stack-1 irrelevant.  pop it */
+              stack--;
+              continue;
+            }
+          }
+          posstack[stack]=i;
+          ampstack[stack++]=seeds[i];
+          break;
+
+        }
+      }
+    }
+  }
+
+  /* the stack now contains only the positions that are relevant. Scan
+     'em straight through */
+
+  for(i=0;i<stack;i++){
+    long endpos;
+    if(i<stack-1 && ampstack[i+1]>ampstack[i]){
+      endpos=posstack[i+1];
+    }else{
+      endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
+                                        discarded in short frames */
+    }
+    if(endpos>n)endpos=n;
+    for(;pos<endpos;pos++)
+      seeds[pos]=ampstack[i];
+  }
+
+  /* there.  Linear time.  I now remember this was on a problem set I
+     had in Grad Skool... I didn't solve it at the time ;-) */
+
+}
+
+/* bleaugh, this is more complicated than it needs to be */
+#include<stdio.h>
+static void max_seeds(vorbis_look_psy *p,
+                      float *seed,
+                      float *flr){
+  long   n=p->total_octave_lines;
+  int    linesper=p->eighth_octave_lines;
+  long   linpos=0;
+  long   pos;
+
+  seed_chase(seed,linesper,n); /* for masking */
+
+  pos=p->octave[0]-p->firstoc-(linesper>>1);
+
+  while(linpos+1<p->n){
+    float minV=seed[pos];
+    long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
+    if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
+    while(pos+1<=end){
+      pos++;
+      if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
+        minV=seed[pos];
+    }
+
+    end=pos+p->firstoc;
+    for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
+      if(flr[linpos]<minV)flr[linpos]=minV;
+  }
+
+  {
+    float minV=seed[p->total_octave_lines-1];
+    for(;linpos<p->n;linpos++)
+      if(flr[linpos]<minV)flr[linpos]=minV;
+  }
+
+}
+
+static void bark_noise_hybridmp(int n,const long *b,
+                                const float *f,
+                                float *noise,
+                                const float offset,
+                                const int fixed){
+
+  float *N=alloca(n*sizeof(*N));
+  float *X=alloca(n*sizeof(*N));
+  float *XX=alloca(n*sizeof(*N));
+  float *Y=alloca(n*sizeof(*N));
+  float *XY=alloca(n*sizeof(*N));
+
+  float tN, tX, tXX, tY, tXY;
+  int i;
+
+  int lo, hi;
+  float R=0.f;
+  float A=0.f;
+  float B=0.f;
+  float D=1.f;
+  float w, x, y;
+
+  tN = tX = tXX = tY = tXY = 0.f;
+
+  y = f[0] + offset;
+  if (y < 1.f) y = 1.f;
+
+  w = y * y * .5;
+
+  tN += w;
+  tX += w;
+  tY += w * y;
+
+  N[0] = tN;
+  X[0] = tX;
+  XX[0] = tXX;
+  Y[0] = tY;
+  XY[0] = tXY;
+
+  for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
+
+    y = f[i] + offset;
+    if (y < 1.f) y = 1.f;
+
+    w = y * y;
+
+    tN += w;
+    tX += w * x;
+    tXX += w * x * x;
+    tY += w * y;
+    tXY += w * x * y;
+
+    N[i] = tN;
+    X[i] = tX;
+    XX[i] = tXX;
+    Y[i] = tY;
+    XY[i] = tXY;
+  }
+
+  for (i = 0, x = 0.f;; i++, x += 1.f) {
+
+    lo = b[i] >> 16;
+    if( lo>=0 ) break;
+    hi = b[i] & 0xffff;
+
+    tN = N[hi] + N[-lo];
+    tX = X[hi] - X[-lo];
+    tXX = XX[hi] + XX[-lo];
+    tY = Y[hi] + Y[-lo];
+    tXY = XY[hi] - XY[-lo];
+
+    A = tY * tXX - tX * tXY;
+    B = tN * tXY - tX * tY;
+    D = tN * tXX - tX * tX;
+    R = (A + x * B) / D;
+    if (R < 0.f)
+      R = 0.f;
+
+    noise[i] = R - offset;
+  }
+
+  for ( ;; i++, x += 1.f) {
+
+    lo = b[i] >> 16;
+    hi = b[i] & 0xffff;
+    if(hi>=n)break;
+
+    tN = N[hi] - N[lo];
+    tX = X[hi] - X[lo];
+    tXX = XX[hi] - XX[lo];
+    tY = Y[hi] - Y[lo];
+    tXY = XY[hi] - XY[lo];
+
+    A = tY * tXX - tX * tXY;
+    B = tN * tXY - tX * tY;
+    D = tN * tXX - tX * tX;
+    R = (A + x * B) / D;
+    if (R < 0.f) R = 0.f;
+
+    noise[i] = R - offset;
+  }
+  for ( ; i < n; i++, x += 1.f) {
+
+    R = (A + x * B) / D;
+    if (R < 0.f) R = 0.f;
+
+    noise[i] = R - offset;
+  }
+
+  if (fixed <= 0) return;
+
+  for (i = 0, x = 0.f;; i++, x += 1.f) {
+    hi = i + fixed / 2;
+    lo = hi - fixed;
+    if(lo>=0)break;
+
+    tN = N[hi] + N[-lo];
+    tX = X[hi] - X[-lo];
+    tXX = XX[hi] + XX[-lo];
+    tY = Y[hi] + Y[-lo];
+    tXY = XY[hi] - XY[-lo];
+
+
+    A = tY * tXX - tX * tXY;
+    B = tN * tXY - tX * tY;
+    D = tN * tXX - tX * tX;
+    R = (A + x * B) / D;
+
+    if (R - offset < noise[i]) noise[i] = R - offset;
+  }
+  for ( ;; i++, x += 1.f) {
+
+    hi = i + fixed / 2;
+    lo = hi - fixed;
+    if(hi>=n)break;
+
+    tN = N[hi] - N[lo];
+    tX = X[hi] - X[lo];
+    tXX = XX[hi] - XX[lo];
+    tY = Y[hi] - Y[lo];
+    tXY = XY[hi] - XY[lo];
+
+    A = tY * tXX - tX * tXY;
+    B = tN * tXY - tX * tY;
+    D = tN * tXX - tX * tX;
+    R = (A + x * B) / D;
+
+    if (R - offset < noise[i]) noise[i] = R - offset;
+  }
+  for ( ; i < n; i++, x += 1.f) {
+    R = (A + x * B) / D;
+    if (R - offset < noise[i]) noise[i] = R - offset;
+  }
+}
+
+void _vp_noisemask(vorbis_look_psy *p,
+                   float *logmdct,
+                   float *logmask){
+
+  int i,n=p->n;
+  float *work=alloca(n*sizeof(*work));
+
+  bark_noise_hybridmp(n,p->bark,logmdct,logmask,
+                      140.,-1);
+
+  for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
+
+  bark_noise_hybridmp(n,p->bark,work,logmask,0.,
+                      p->vi->noisewindowfixed);
+
+  for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
+
+#if 0
+  {
+    static int seq=0;
+
+    float work2[n];
+    for(i=0;i<n;i++){
+      work2[i]=logmask[i]+work[i];
+    }
+
+    if(seq&1)
+      _analysis_output("median2R",seq/2,work,n,1,0,0);
+    else
+      _analysis_output("median2L",seq/2,work,n,1,0,0);
+
+    if(seq&1)
+      _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
+    else
+      _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
+    seq++;
+  }
+#endif
+
+  for(i=0;i<n;i++){
+    int dB=logmask[i]+.5;
+    if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
+    if(dB<0)dB=0;
+    logmask[i]= work[i]+p->vi->noisecompand[dB];
+  }
+
+}
+
+void _vp_tonemask(vorbis_look_psy *p,
+                  float *logfft,
+                  float *logmask,
+                  float global_specmax,
+                  float local_specmax){
+
+  int i,n=p->n;
+
+  float *seed=alloca(sizeof(*seed)*p->total_octave_lines);
+  float att=local_specmax+p->vi->ath_adjatt;
+  for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
+
+  /* set the ATH (floating below localmax, not global max by a
+     specified att) */
+  if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
+
+  for(i=0;i<n;i++)
+    logmask[i]=p->ath[i]+att;
+
+  /* tone masking */
+  seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
+  max_seeds(p,seed,logmask);
+
+}
+
+void _vp_offset_and_mix(vorbis_look_psy *p,
+                        float *noise,
+                        float *tone,
+                        int offset_select,
+                        float *logmask,
+                        float *mdct,
+                        float *logmdct){
+  int i,n=p->n;
+  float de, coeffi, cx;/* AoTuV */
+  float toneatt=p->vi->tone_masteratt[offset_select];
+
+  cx = p->m_val;
+
+  for(i=0;i<n;i++){
+    float val= noise[i]+p->noiseoffset[offset_select][i];
+    if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
+    logmask[i]=max(val,tone[i]+toneatt);
+
+
+    /* AoTuV */
+    /** @ M1 **
+        The following codes improve a noise problem.
+        A fundamental idea uses the value of masking and carries out
+        the relative compensation of the MDCT.
+        However, this code is not perfect and all noise problems cannot be solved.
+        by Aoyumi @ 2004/04/18
+    */
+
+    if(offset_select == 1) {
+      coeffi = -17.2;       /* coeffi is a -17.2dB threshold */
+      val = val - logmdct[i];  /* val == mdct line value relative to floor in dB */
+
+      if(val > coeffi){
+        /* mdct value is > -17.2 dB below floor */
+
+        de = 1.0-((val-coeffi)*0.005*cx);
+        /* pro-rated attenuation:
+           -0.00 dB boost if mdct value is -17.2dB (relative to floor)
+           -0.77 dB boost if mdct value is 0dB (relative to floor)
+           -1.64 dB boost if mdct value is +17.2dB (relative to floor)
+           etc... */
+
+        if(de < 0) de = 0.0001;
+      }else
+        /* mdct value is <= -17.2 dB below floor */
+
+        de = 1.0-((val-coeffi)*0.0003*cx);
+      /* pro-rated attenuation:
+         +0.00 dB atten if mdct value is -17.2dB (relative to floor)
+         +0.45 dB atten if mdct value is -34.4dB (relative to floor)
+         etc... */
+
+      mdct[i] *= de;
+
+    }
+  }
+}
+
+float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
+  vorbis_info *vi=vd->vi;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *gi=&ci->psy_g_param;
+
+  int n=ci->blocksizes[vd->W]/2;
+  float secs=(float)n/vi->rate;
+
+  amp+=secs*gi->ampmax_att_per_sec;
+  if(amp<-9999)amp=-9999;
+  return(amp);
+}
+
+static float FLOOR1_fromdB_LOOKUP[256]={
+  1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
+  1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
+  1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
+  2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
+  2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
+  3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
+  4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
+  6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
+  7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
+  1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
+  1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
+  1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
+  2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
+  2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
+  3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
+  4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
+  5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
+  7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
+  9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
+  1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
+  1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
+  2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
+  2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
+  3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
+  4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
+  5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
+  7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
+  9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
+  0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
+  0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
+  0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
+  0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
+  0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
+  0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
+  0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
+  0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
+  0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
+  0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
+  0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
+  0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
+  0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
+  0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
+  0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
+  0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
+  0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
+  0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
+  0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
+  0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
+  0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
+  0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
+  0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
+  0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
+  0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
+  0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
+  0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
+  0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
+  0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
+  0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
+  0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
+  0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
+  0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
+  0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
+  0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
+  0.82788260F, 0.88168307F, 0.9389798F, 1.F,
+};
+
+/* this is for per-channel noise normalization */
+static int apsort(const void *a, const void *b){
+  float f1=**(float**)a;
+  float f2=**(float**)b;
+  return (f1<f2)-(f1>f2);
+}
+
+static void flag_lossless(int limit, float prepoint, float postpoint, float *mdct,
+                         float *floor, int *flag, int i, int jn){
+  int j;
+  for(j=0;j<jn;j++){
+    float point = j>=limit-i ? postpoint : prepoint;
+    float r = fabs(mdct[j])/floor[j];
+    if(r<point)
+      flag[j]=0;
+    else
+      flag[j]=1;
+  }
+}
+
+/* Overload/Side effect: On input, the *q vector holds either the
+   quantized energy (for elements with the flag set) or the absolute
+   values of the *r vector (for elements with flag unset).  On output,
+   *q holds the quantized energy for all elements */
+static float noise_normalize(vorbis_look_psy *p, int limit, float *r, float *q, float *f, int *flags, float acc, int i, int n, int *out){
+
+  vorbis_info_psy *vi=p->vi;
+  float **sort = alloca(n*sizeof(*sort));
+  int j,count=0;
+  int start = (vi->normal_p ? vi->normal_start-i : n);
+  if(start>n)start=n;
+
+  /* force classic behavior where only energy in the current band is considered */
+  acc=0.f;
+
+  /* still responsible for populating *out where noise norm not in
+     effect.  There's no need to [re]populate *q in these areas */
+  for(j=0;j<start;j++){
+    if(!flags || !flags[j]){ /* lossless coupling already quantized.
+                                Don't touch; requantizing based on
+                                energy would be incorrect. */
+      float ve = q[j]/f[j];
+      if(r[j]<0)
+        out[j] = -rint(sqrt(ve));
+      else
+        out[j] = rint(sqrt(ve));
+    }
+  }
+
+  /* sort magnitudes for noise norm portion of partition */
+  for(;j<n;j++){
+    if(!flags || !flags[j]){ /* can't noise norm elements that have
+                                already been loslessly coupled; we can
+                                only account for their energy error */
+      float ve = q[j]/f[j];
+      /* Despite all the new, more capable coupling code, for now we
+         implement noise norm as it has been up to this point. Only
+         consider promotions to unit magnitude from 0.  In addition
+         the only energy error counted is quantizations to zero. */
+      /* also-- the original point code only applied noise norm at > pointlimit */
+      if(ve<.25f && (!flags || j>=limit-i)){
+        acc += ve;
+        sort[count++]=q+j; /* q is fabs(r) for unflagged element */
+      }else{
+        /* For now: no acc adjustment for nonzero quantization.  populate *out and q as this value is final. */
+        if(r[j]<0)
+          out[j] = -rint(sqrt(ve));
+        else
+          out[j] = rint(sqrt(ve));
+        q[j] = out[j]*out[j]*f[j];
+      }
+    }/* else{
+        again, no energy adjustment for error in nonzero quant-- for now
+        }*/
+  }
+
+  if(count){
+    /* noise norm to do */
+    qsort(sort,count,sizeof(*sort),apsort);
+    for(j=0;j<count;j++){
+      int k=sort[j]-q;
+      if(acc>=vi->normal_thresh){
+        out[k]=unitnorm(r[k]);
+        acc-=1.f;
+        q[k]=f[k];
+      }else{
+        out[k]=0;
+        q[k]=0.f;
+      }
+    }
+  }
+
+  return acc;
+}
+
+/* Noise normalization, quantization and coupling are not wholly
+   seperable processes in depth>1 coupling. */
+void _vp_couple_quantize_normalize(int blobno,
+                                   vorbis_info_psy_global *g,
+                                   vorbis_look_psy *p,
+                                   vorbis_info_mapping0 *vi,
+                                   float **mdct,
+                                   int   **iwork,
+                                   int    *nonzero,
+                                   int     sliding_lowpass,
+                                   int     ch){
+
+  int i;
+  int n = p->n;
+  int partition=(p->vi->normal_p ? p->vi->normal_partition : 16);
+  int limit = g->coupling_pointlimit[p->vi->blockflag][blobno];
+  float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
+  float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
+#if 0
+  float de=0.1*p->m_val; /* a blend of the AoTuV M2 and M3 code here and below */
+#endif
+
+  /* mdct is our raw mdct output, floor not removed. */
+  /* inout passes in the ifloor, passes back quantized result */
+
+  /* unquantized energy (negative indicates amplitude has negative sign) */
+  float **raw = alloca(ch*sizeof(*raw));
+
+  /* dual pupose; quantized energy (if flag set), othersize fabs(raw) */
+  float **quant = alloca(ch*sizeof(*quant));
+
+  /* floor energy */
+  float **floor = alloca(ch*sizeof(*floor));
+
+  /* flags indicating raw/quantized status of elements in raw vector */
+  int   **flag  = alloca(ch*sizeof(*flag));
+
+  /* non-zero flag working vector */
+  int    *nz    = alloca(ch*sizeof(*nz));
+
+  /* energy surplus/defecit tracking */
+  float  *acc   = alloca((ch+vi->coupling_steps)*sizeof(*acc));
+
+  /* The threshold of a stereo is changed with the size of n */
+  if(n > 1000)
+    postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
+
+  raw[0]   = alloca(ch*partition*sizeof(**raw));
+  quant[0] = alloca(ch*partition*sizeof(**quant));
+  floor[0] = alloca(ch*partition*sizeof(**floor));
+  flag[0]  = alloca(ch*partition*sizeof(**flag));
+
+  for(i=1;i<ch;i++){
+    raw[i]   = &raw[0][partition*i];
+    quant[i] = &quant[0][partition*i];
+    floor[i] = &floor[0][partition*i];
+    flag[i]  = &flag[0][partition*i];
+  }
+  for(i=0;i<ch+vi->coupling_steps;i++)
+    acc[i]=0.f;
+
+  for(i=0;i<n;i+=partition){
+    int k,j,jn = partition > n-i ? n-i : partition;
+    int step,track = 0;
+
+    memcpy(nz,nonzero,sizeof(*nz)*ch);
+
+    /* prefill */
+    memset(flag[0],0,ch*partition*sizeof(**flag));
+    for(k=0;k<ch;k++){
+      int *iout = &iwork[k][i];
+      if(nz[k]){
+
+        for(j=0;j<jn;j++)
+          floor[k][j] = FLOOR1_fromdB_LOOKUP[iout[j]];
+
+        flag_lossless(limit,prepoint,postpoint,&mdct[k][i],floor[k],flag[k],i,jn);
+
+        for(j=0;j<jn;j++){
+          quant[k][j] = raw[k][j] = mdct[k][i+j]*mdct[k][i+j];
+          if(mdct[k][i+j]<0.f) raw[k][j]*=-1.f;
+          floor[k][j]*=floor[k][j];
+        }
+
+        acc[track]=noise_normalize(p,limit,raw[k],quant[k],floor[k],NULL,acc[track],i,jn,iout);
+
+      }else{
+        for(j=0;j<jn;j++){
+          floor[k][j] = 1e-10f;
+          raw[k][j] = 0.f;
+          quant[k][j] = 0.f;
+          flag[k][j] = 0;
+          iout[j]=0;
+        }
+        acc[track]=0.f;
+      }
+      track++;
+    }
+
+    /* coupling */
+    for(step=0;step<vi->coupling_steps;step++){
+      int Mi = vi->coupling_mag[step];
+      int Ai = vi->coupling_ang[step];
+      int *iM = &iwork[Mi][i];
+      int *iA = &iwork[Ai][i];
+      float *reM = raw[Mi];
+      float *reA = raw[Ai];
+      float *qeM = quant[Mi];
+      float *qeA = quant[Ai];
+      float *floorM = floor[Mi];
+      float *floorA = floor[Ai];
+      int *fM = flag[Mi];
+      int *fA = flag[Ai];
+
+      if(nz[Mi] || nz[Ai]){
+        nz[Mi] = nz[Ai] = 1;
+
+        for(j=0;j<jn;j++){
+
+          if(j<sliding_lowpass-i){
+            if(fM[j] || fA[j]){
+              /* lossless coupling */
+
+              reM[j] = fabs(reM[j])+fabs(reA[j]);
+              qeM[j] = qeM[j]+qeA[j];
+              fM[j]=fA[j]=1;
+
+              /* couple iM/iA */
+              {
+                int A = iM[j];
+                int B = iA[j];
+
+                if(abs(A)>abs(B)){
+                  iA[j]=(A>0?A-B:B-A);
+                }else{
+                  iA[j]=(B>0?A-B:B-A);
+                  iM[j]=B;
+                }
+
+                /* collapse two equivalent tuples to one */
+                if(iA[j]>=abs(iM[j])*2){
+                  iA[j]= -iA[j];
+                  iM[j]= -iM[j];
+                }
+
+              }
+
+            }else{
+              /* lossy (point) coupling */
+              if(j<limit-i){
+                /* dipole */
+                reM[j] += reA[j];
+                qeM[j] = fabs(reM[j]);
+              }else{
+#if 0
+                /* AoTuV */
+                /** @ M2 **
+                    The boost problem by the combination of noise normalization and point stereo is eased.
+                    However, this is a temporary patch.
+                    by Aoyumi @ 2004/04/18
+                */
+                float derate = (1.0 - de*((float)(j-limit+i) / (float)(n-limit)));
+                /* elliptical */
+                if(reM[j]+reA[j]<0){
+                  reM[j] = - (qeM[j] = (fabs(reM[j])+fabs(reA[j]))*derate*derate);
+                }else{
+                  reM[j] =   (qeM[j] = (fabs(reM[j])+fabs(reA[j]))*derate*derate);
+                }
+#else
+                /* elliptical */
+                if(reM[j]+reA[j]<0){
+                  reM[j] = - (qeM[j] = fabs(reM[j])+fabs(reA[j]));
+                }else{
+                  reM[j] =   (qeM[j] = fabs(reM[j])+fabs(reA[j]));
+                }
+#endif
+
+              }
+              reA[j]=qeA[j]=0.f;
+              fA[j]=1;
+              iA[j]=0;
+            }
+          }
+          floorM[j]=floorA[j]=floorM[j]+floorA[j];
+        }
+        /* normalize the resulting mag vector */
+        acc[track]=noise_normalize(p,limit,raw[Mi],quant[Mi],floor[Mi],flag[Mi],acc[track],i,jn,iM);
+        track++;
+      }
+    }
+  }
+
+  for(i=0;i<vi->coupling_steps;i++){
+    /* make sure coupling a zero and a nonzero channel results in two
+       nonzero channels. */
+    if(nonzero[vi->coupling_mag[i]] ||
+       nonzero[vi->coupling_ang[i]]){
+      nonzero[vi->coupling_mag[i]]=1;
+      nonzero[vi->coupling_ang[i]]=1;
+    }
+  }
+}
diff --git a/vorbis/lib/psy.h b/vorbis/lib/psy.h
new file mode 100644 (file)
index 0000000..ab2534d
--- /dev/null
@@ -0,0 +1,153 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: random psychoacoustics (not including preecho)
+
+ ********************************************************************/
+
+#ifndef _V_PSY_H_
+#define _V_PSY_H_
+#include "smallft.h"
+
+#include "backends.h"
+#include "envelope.h"
+
+#ifndef EHMER_MAX
+#define EHMER_MAX 56
+#endif
+
+/* psychoacoustic setup ********************************************/
+#define P_BANDS 17      /* 62Hz to 16kHz */
+#define P_LEVELS 8      /* 30dB to 100dB */
+#define P_LEVEL_0 30.    /* 30 dB */
+#define P_NOISECURVES 3
+
+#define NOISE_COMPAND_LEVELS 40
+typedef struct vorbis_info_psy{
+  int   blockflag;
+
+  float ath_adjatt;
+  float ath_maxatt;
+
+  float tone_masteratt[P_NOISECURVES];
+  float tone_centerboost;
+  float tone_decay;
+  float tone_abs_limit;
+  float toneatt[P_BANDS];
+
+  int noisemaskp;
+  float noisemaxsupp;
+  float noisewindowlo;
+  float noisewindowhi;
+  int   noisewindowlomin;
+  int   noisewindowhimin;
+  int   noisewindowfixed;
+  float noiseoff[P_NOISECURVES][P_BANDS];
+  float noisecompand[NOISE_COMPAND_LEVELS];
+
+  float max_curve_dB;
+
+  int normal_p;
+  int normal_start;
+  int normal_partition;
+  double normal_thresh;
+} vorbis_info_psy;
+
+typedef struct{
+  int   eighth_octave_lines;
+
+  /* for block long/short tuning; encode only */
+  float preecho_thresh[VE_BANDS];
+  float postecho_thresh[VE_BANDS];
+  float stretch_penalty;
+  float preecho_minenergy;
+
+  float ampmax_att_per_sec;
+
+  /* channel coupling config */
+  int   coupling_pkHz[PACKETBLOBS];
+  int   coupling_pointlimit[2][PACKETBLOBS];
+  int   coupling_prepointamp[PACKETBLOBS];
+  int   coupling_postpointamp[PACKETBLOBS];
+  int   sliding_lowpass[2][PACKETBLOBS];
+
+} vorbis_info_psy_global;
+
+typedef struct {
+  float ampmax;
+  int   channels;
+
+  vorbis_info_psy_global *gi;
+  int   coupling_pointlimit[2][P_NOISECURVES];
+} vorbis_look_psy_global;
+
+
+typedef struct {
+  int n;
+  struct vorbis_info_psy *vi;
+
+  float ***tonecurves;
+  float **noiseoffset;
+
+  float *ath;
+  long  *octave;             /* in n.ocshift format */
+  long  *bark;
+
+  long  firstoc;
+  long  shiftoc;
+  int   eighth_octave_lines; /* power of two, please */
+  int   total_octave_lines;
+  long  rate; /* cache it */
+
+  float m_val; /* Masking compensation value */
+
+} vorbis_look_psy;
+
+extern void   _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
+                           vorbis_info_psy_global *gi,int n,long rate);
+extern void   _vp_psy_clear(vorbis_look_psy *p);
+extern void  *_vi_psy_dup(void *source);
+
+extern void   _vi_psy_free(vorbis_info_psy *i);
+extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
+
+extern void _vp_noisemask(vorbis_look_psy *p,
+                          float *logmdct,
+                          float *logmask);
+
+extern void _vp_tonemask(vorbis_look_psy *p,
+                         float *logfft,
+                         float *logmask,
+                         float global_specmax,
+                         float local_specmax);
+
+extern void _vp_offset_and_mix(vorbis_look_psy *p,
+                               float *noise,
+                               float *tone,
+                               int offset_select,
+                               float *logmask,
+                               float *mdct,
+                               float *logmdct);
+
+extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
+
+extern void _vp_couple_quantize_normalize(int blobno,
+                                          vorbis_info_psy_global *g,
+                                          vorbis_look_psy *p,
+                                          vorbis_info_mapping0 *vi,
+                                          float **mdct,
+                                          int   **iwork,
+                                          int    *nonzero,
+                                          int     sliding_lowpass,
+                                          int     ch);
+
+#endif
diff --git a/vorbis/lib/registry.c b/vorbis/lib/registry.c
new file mode 100644 (file)
index 0000000..74f7ef0
--- /dev/null
@@ -0,0 +1,44 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: registry for time, floor, res backends and channel mappings
+
+ ********************************************************************/
+
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "misc.h"
+/* seems like major overkill now; the backend numbers will grow into
+   the infrastructure soon enough */
+
+extern const vorbis_func_floor     floor0_exportbundle;
+extern const vorbis_func_floor     floor1_exportbundle;
+extern const vorbis_func_residue   residue0_exportbundle;
+extern const vorbis_func_residue   residue1_exportbundle;
+extern const vorbis_func_residue   residue2_exportbundle;
+extern const vorbis_func_mapping   mapping0_exportbundle;
+
+const vorbis_func_floor     *const _floor_P[]={
+  &floor0_exportbundle,
+  &floor1_exportbundle,
+};
+
+const vorbis_func_residue   *const _residue_P[]={
+  &residue0_exportbundle,
+  &residue1_exportbundle,
+  &residue2_exportbundle,
+};
+
+const vorbis_func_mapping   *const _mapping_P[]={
+  &mapping0_exportbundle,
+};
diff --git a/vorbis/lib/registry.h b/vorbis/lib/registry.h
new file mode 100644 (file)
index 0000000..599d959
--- /dev/null
@@ -0,0 +1,31 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: registry for time, floor, res backends and channel mappings
+
+ ********************************************************************/
+
+#ifndef _V_REG_H_
+#define _V_REG_H_
+
+#define VI_TRANSFORMB 1
+#define VI_WINDOWB 1
+#define VI_TIMEB 1
+#define VI_FLOORB 2
+#define VI_RESB 3
+#define VI_MAPB 1
+
+extern const vorbis_func_floor     *const _floor_P[];
+extern const vorbis_func_residue   *const _residue_P[];
+extern const vorbis_func_mapping   *const _mapping_P[];
+
+#endif
diff --git a/vorbis/lib/res0.c b/vorbis/lib/res0.c
new file mode 100644 (file)
index 0000000..6d623d7
--- /dev/null
@@ -0,0 +1,889 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2010             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: residue backend 0, 1 and 2 implementation
+
+ ********************************************************************/
+
+/* Slow, slow, slow, simpleminded and did I mention it was slow?  The
+   encode/decode loops are coded for clarity and performance is not
+   yet even a nagging little idea lurking in the shadows.  Oh and BTW,
+   it's slow. */
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "codebook.h"
+#include "misc.h"
+#include "os.h"
+
+//#define TRAIN_RES 1
+//#define TRAIN_RESAUX 1
+
+#if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
+#include <stdio.h>
+#endif
+
+typedef struct {
+  vorbis_info_residue0 *info;
+
+  int         parts;
+  int         stages;
+  codebook   *fullbooks;
+  codebook   *phrasebook;
+  codebook ***partbooks;
+
+  int         partvals;
+  int       **decodemap;
+
+  long      postbits;
+  long      phrasebits;
+  long      frames;
+
+#if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
+  int        train_seq;
+  long      *training_data[8][64];
+  float      training_max[8][64];
+  float      training_min[8][64];
+  float     tmin;
+  float     tmax;
+  int       submap;
+#endif
+
+} vorbis_look_residue0;
+
+void res0_free_info(vorbis_info_residue *i){
+  vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
+  if(info){
+    memset(info,0,sizeof(*info));
+    _ogg_free(info);
+  }
+}
+
+void res0_free_look(vorbis_look_residue *i){
+  int j;
+  if(i){
+
+    vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
+
+#ifdef TRAIN_RES
+    {
+      int j,k,l;
+      for(j=0;j<look->parts;j++){
+        /*fprintf(stderr,"partition %d: ",j);*/
+        for(k=0;k<8;k++)
+          if(look->training_data[k][j]){
+            char buffer[80];
+            FILE *of;
+            codebook *statebook=look->partbooks[j][k];
+
+            /* long and short into the same bucket by current convention */
+            sprintf(buffer,"res_sub%d_part%d_pass%d.vqd",look->submap,j,k);
+            of=fopen(buffer,"a");
+
+            for(l=0;l<statebook->entries;l++)
+              fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
+
+            fclose(of);
+
+            /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
+              look->training_min[k][j],look->training_max[k][j]);*/
+
+            _ogg_free(look->training_data[k][j]);
+            look->training_data[k][j]=NULL;
+          }
+        /*fprintf(stderr,"\n");*/
+      }
+    }
+    fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
+
+    /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
+            (float)look->phrasebits/look->frames,
+            (float)look->postbits/look->frames,
+            (float)(look->postbits+look->phrasebits)/look->frames);*/
+#endif
+
+
+    /*vorbis_info_residue0 *info=look->info;
+
+    fprintf(stderr,
+            "%ld frames encoded in %ld phrasebits and %ld residue bits "
+            "(%g/frame) \n",look->frames,look->phrasebits,
+            look->resbitsflat,
+            (look->phrasebits+look->resbitsflat)/(float)look->frames);
+
+    for(j=0;j<look->parts;j++){
+      long acc=0;
+      fprintf(stderr,"\t[%d] == ",j);
+      for(k=0;k<look->stages;k++)
+        if((info->secondstages[j]>>k)&1){
+          fprintf(stderr,"%ld,",look->resbits[j][k]);
+          acc+=look->resbits[j][k];
+        }
+
+      fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
+              acc?(float)acc/(look->resvals[j]*info->grouping):0);
+    }
+    fprintf(stderr,"\n");*/
+
+    for(j=0;j<look->parts;j++)
+      if(look->partbooks[j])_ogg_free(look->partbooks[j]);
+    _ogg_free(look->partbooks);
+    for(j=0;j<look->partvals;j++)
+      _ogg_free(look->decodemap[j]);
+    _ogg_free(look->decodemap);
+
+    memset(look,0,sizeof(*look));
+    _ogg_free(look);
+  }
+}
+
+static int icount(unsigned int v){
+  int ret=0;
+  while(v){
+    ret+=v&1;
+    v>>=1;
+  }
+  return(ret);
+}
+
+
+void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
+  vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
+  int j,acc=0;
+  oggpack_write(opb,info->begin,24);
+  oggpack_write(opb,info->end,24);
+
+  oggpack_write(opb,info->grouping-1,24);  /* residue vectors to group and
+                                             code with a partitioned book */
+  oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
+  oggpack_write(opb,info->groupbook,8);  /* group huffman book */
+
+  /* secondstages is a bitmask; as encoding progresses pass by pass, a
+     bitmask of one indicates this partition class has bits to write
+     this pass */
+  for(j=0;j<info->partitions;j++){
+    if(ov_ilog(info->secondstages[j])>3){
+      /* yes, this is a minor hack due to not thinking ahead */
+      oggpack_write(opb,info->secondstages[j],3);
+      oggpack_write(opb,1,1);
+      oggpack_write(opb,info->secondstages[j]>>3,5);
+    }else
+      oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
+    acc+=icount(info->secondstages[j]);
+  }
+  for(j=0;j<acc;j++)
+    oggpack_write(opb,info->booklist[j],8);
+
+}
+
+/* vorbis_info is for range checking */
+vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
+  int j,acc=0;
+  vorbis_info_residue0 *info=_ogg_calloc(1,sizeof(*info));
+  codec_setup_info     *ci=vi->codec_setup;
+
+  info->begin=oggpack_read(opb,24);
+  info->end=oggpack_read(opb,24);
+  info->grouping=oggpack_read(opb,24)+1;
+  info->partitions=oggpack_read(opb,6)+1;
+  info->groupbook=oggpack_read(opb,8);
+
+  /* check for premature EOP */
+  if(info->groupbook<0)goto errout;
+
+  for(j=0;j<info->partitions;j++){
+    int cascade=oggpack_read(opb,3);
+    int cflag=oggpack_read(opb,1);
+    if(cflag<0) goto errout;
+    if(cflag){
+      int c=oggpack_read(opb,5);
+      if(c<0) goto errout;
+      cascade|=(c<<3);
+    }
+    info->secondstages[j]=cascade;
+
+    acc+=icount(cascade);
+  }
+  for(j=0;j<acc;j++){
+    int book=oggpack_read(opb,8);
+    if(book<0) goto errout;
+    info->booklist[j]=book;
+  }
+
+  if(info->groupbook>=ci->books)goto errout;
+  for(j=0;j<acc;j++){
+    if(info->booklist[j]>=ci->books)goto errout;
+    if(ci->book_param[info->booklist[j]]->maptype==0)goto errout;
+  }
+
+  /* verify the phrasebook is not specifying an impossible or
+     inconsistent partitioning scheme. */
+  /* modify the phrasebook ranging check from r16327; an early beta
+     encoder had a bug where it used an oversized phrasebook by
+     accident.  These files should continue to be playable, but don't
+     allow an exploit */
+  {
+    int entries = ci->book_param[info->groupbook]->entries;
+    int dim = ci->book_param[info->groupbook]->dim;
+    int partvals = 1;
+    if (dim<1) goto errout;
+    while(dim>0){
+      partvals *= info->partitions;
+      if(partvals > entries) goto errout;
+      dim--;
+    }
+    info->partvals = partvals;
+  }
+
+  return(info);
+ errout:
+  res0_free_info(info);
+  return(NULL);
+}
+
+vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
+                               vorbis_info_residue *vr){
+  vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
+  vorbis_look_residue0 *look=_ogg_calloc(1,sizeof(*look));
+  codec_setup_info     *ci=vd->vi->codec_setup;
+
+  int j,k,acc=0;
+  int dim;
+  int maxstage=0;
+  look->info=info;
+
+  look->parts=info->partitions;
+  look->fullbooks=ci->fullbooks;
+  look->phrasebook=ci->fullbooks+info->groupbook;
+  dim=look->phrasebook->dim;
+
+  look->partbooks=_ogg_calloc(look->parts,sizeof(*look->partbooks));
+
+  for(j=0;j<look->parts;j++){
+    int stages=ov_ilog(info->secondstages[j]);
+    if(stages){
+      if(stages>maxstage)maxstage=stages;
+      look->partbooks[j]=_ogg_calloc(stages,sizeof(*look->partbooks[j]));
+      for(k=0;k<stages;k++)
+        if(info->secondstages[j]&(1<<k)){
+          look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
+#ifdef TRAIN_RES
+          look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
+                                           sizeof(***look->training_data));
+#endif
+        }
+    }
+  }
+
+  look->partvals=1;
+  for(j=0;j<dim;j++)
+      look->partvals*=look->parts;
+
+  look->stages=maxstage;
+  look->decodemap=_ogg_malloc(look->partvals*sizeof(*look->decodemap));
+  for(j=0;j<look->partvals;j++){
+    long val=j;
+    long mult=look->partvals/look->parts;
+    look->decodemap[j]=_ogg_malloc(dim*sizeof(*look->decodemap[j]));
+    for(k=0;k<dim;k++){
+      long deco=val/mult;
+      val-=deco*mult;
+      mult/=look->parts;
+      look->decodemap[j][k]=deco;
+    }
+  }
+#if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
+  {
+    static int train_seq=0;
+    look->train_seq=train_seq++;
+  }
+#endif
+  return(look);
+}
+
+/* break an abstraction and copy some code for performance purposes */
+static int local_book_besterror(codebook *book,int *a){
+  int dim=book->dim;
+  int i,j,o;
+  int minval=book->minval;
+  int del=book->delta;
+  int qv=book->quantvals;
+  int ze=(qv>>1);
+  int index=0;
+  /* assumes integer/centered encoder codebook maptype 1 no more than dim 8 */
+  int p[8]={0,0,0,0,0,0,0,0};
+
+  if(del!=1){
+    for(i=0,o=dim;i<dim;i++){
+      int v = (a[--o]-minval+(del>>1))/del;
+      int m = (v<ze ? ((ze-v)<<1)-1 : ((v-ze)<<1));
+      index = index*qv+ (m<0?0:(m>=qv?qv-1:m));
+      p[o]=v*del+minval;
+    }
+  }else{
+    for(i=0,o=dim;i<dim;i++){
+      int v = a[--o]-minval;
+      int m = (v<ze ? ((ze-v)<<1)-1 : ((v-ze)<<1));
+      index = index*qv+ (m<0?0:(m>=qv?qv-1:m));
+      p[o]=v*del+minval;
+    }
+  }
+
+  if(book->c->lengthlist[index]<=0){
+    const static_codebook *c=book->c;
+    int best=-1;
+    /* assumes integer/centered encoder codebook maptype 1 no more than dim 8 */
+    int e[8]={0,0,0,0,0,0,0,0};
+    int maxval = book->minval + book->delta*(book->quantvals-1);
+    for(i=0;i<book->entries;i++){
+      if(c->lengthlist[i]>0){
+        int this=0;
+        for(j=0;j<dim;j++){
+          int val=(e[j]-a[j]);
+          this+=val*val;
+        }
+        if(best==-1 || this<best){
+          memcpy(p,e,sizeof(p));
+          best=this;
+          index=i;
+        }
+      }
+      /* assumes the value patterning created by the tools in vq/ */
+      j=0;
+      while(e[j]>=maxval)
+        e[j++]=0;
+      if(e[j]>=0)
+        e[j]+=book->delta;
+      e[j]= -e[j];
+    }
+  }
+
+  if(index>-1){
+    for(i=0;i<dim;i++)
+      *a++ -= p[i];
+  }
+
+  return(index);
+}
+
+#ifdef TRAIN_RES
+static int _encodepart(oggpack_buffer *opb,int *vec, int n,
+                       codebook *book,long *acc){
+#else
+static int _encodepart(oggpack_buffer *opb,int *vec, int n,
+                       codebook *book){
+#endif
+  int i,bits=0;
+  int dim=book->dim;
+  int step=n/dim;
+
+  for(i=0;i<step;i++){
+    int entry=local_book_besterror(book,vec+i*dim);
+
+#ifdef TRAIN_RES
+    if(entry>=0)
+      acc[entry]++;
+#endif
+
+    bits+=vorbis_book_encode(book,entry,opb);
+
+  }
+
+  return(bits);
+}
+
+static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
+                       int **in,int ch){
+  long i,j,k;
+  vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
+  vorbis_info_residue0 *info=look->info;
+
+  /* move all this setup out later */
+  int samples_per_partition=info->grouping;
+  int possible_partitions=info->partitions;
+  int n=info->end-info->begin;
+
+  int partvals=n/samples_per_partition;
+  long **partword=_vorbis_block_alloc(vb,ch*sizeof(*partword));
+  float scale=100./samples_per_partition;
+
+  /* we find the partition type for each partition of each
+     channel.  We'll go back and do the interleaved encoding in a
+     bit.  For now, clarity */
+
+  for(i=0;i<ch;i++){
+    partword[i]=_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
+    memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
+  }
+
+  for(i=0;i<partvals;i++){
+    int offset=i*samples_per_partition+info->begin;
+    for(j=0;j<ch;j++){
+      int max=0;
+      int ent=0;
+      for(k=0;k<samples_per_partition;k++){
+        if(abs(in[j][offset+k])>max)max=abs(in[j][offset+k]);
+        ent+=abs(in[j][offset+k]);
+      }
+      ent*=scale;
+
+      for(k=0;k<possible_partitions-1;k++)
+        if(max<=info->classmetric1[k] &&
+           (info->classmetric2[k]<0 || ent<info->classmetric2[k]))
+          break;
+
+      partword[j][i]=k;
+    }
+  }
+
+#ifdef TRAIN_RESAUX
+  {
+    FILE *of;
+    char buffer[80];
+
+    for(i=0;i<ch;i++){
+      sprintf(buffer,"resaux_%d.vqd",look->train_seq);
+      of=fopen(buffer,"a");
+      for(j=0;j<partvals;j++)
+        fprintf(of,"%ld, ",partword[i][j]);
+      fprintf(of,"\n");
+      fclose(of);
+    }
+  }
+#endif
+  look->frames++;
+
+  return(partword);
+}
+
+/* designed for stereo or other modes where the partition size is an
+   integer multiple of the number of channels encoded in the current
+   submap */
+static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,int **in,
+                      int ch){
+  long i,j,k,l;
+  vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
+  vorbis_info_residue0 *info=look->info;
+
+  /* move all this setup out later */
+  int samples_per_partition=info->grouping;
+  int possible_partitions=info->partitions;
+  int n=info->end-info->begin;
+
+  int partvals=n/samples_per_partition;
+  long **partword=_vorbis_block_alloc(vb,sizeof(*partword));
+
+#if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
+  FILE *of;
+  char buffer[80];
+#endif
+
+  partword[0]=_vorbis_block_alloc(vb,partvals*sizeof(*partword[0]));
+  memset(partword[0],0,partvals*sizeof(*partword[0]));
+
+  for(i=0,l=info->begin/ch;i<partvals;i++){
+    int magmax=0;
+    int angmax=0;
+    for(j=0;j<samples_per_partition;j+=ch){
+      if(abs(in[0][l])>magmax)magmax=abs(in[0][l]);
+      for(k=1;k<ch;k++)
+        if(abs(in[k][l])>angmax)angmax=abs(in[k][l]);
+      l++;
+    }
+
+    for(j=0;j<possible_partitions-1;j++)
+      if(magmax<=info->classmetric1[j] &&
+         angmax<=info->classmetric2[j])
+        break;
+
+    partword[0][i]=j;
+
+  }
+
+#ifdef TRAIN_RESAUX
+  sprintf(buffer,"resaux_%d.vqd",look->train_seq);
+  of=fopen(buffer,"a");
+  for(i=0;i<partvals;i++)
+    fprintf(of,"%ld, ",partword[0][i]);
+  fprintf(of,"\n");
+  fclose(of);
+#endif
+
+  look->frames++;
+
+  return(partword);
+}
+
+static int _01forward(oggpack_buffer *opb,
+                      vorbis_look_residue *vl,
+                      int **in,int ch,
+                      long **partword,
+#ifdef TRAIN_RES
+                      int (*encode)(oggpack_buffer *,int *,int,
+                                    codebook *,long *),
+                      int submap
+#else
+                      int (*encode)(oggpack_buffer *,int *,int,
+                                    codebook *)
+#endif
+){
+  long i,j,k,s;
+  vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
+  vorbis_info_residue0 *info=look->info;
+
+#ifdef TRAIN_RES
+  look->submap=submap;
+#endif
+
+  /* move all this setup out later */
+  int samples_per_partition=info->grouping;
+  int possible_partitions=info->partitions;
+  int partitions_per_word=look->phrasebook->dim;
+  int n=info->end-info->begin;
+
+  int partvals=n/samples_per_partition;
+  long resbits[128];
+  long resvals[128];
+
+#ifdef TRAIN_RES
+  for(i=0;i<ch;i++)
+    for(j=info->begin;j<info->end;j++){
+      if(in[i][j]>look->tmax)look->tmax=in[i][j];
+      if(in[i][j]<look->tmin)look->tmin=in[i][j];
+    }
+#endif
+
+  memset(resbits,0,sizeof(resbits));
+  memset(resvals,0,sizeof(resvals));
+
+  /* we code the partition words for each channel, then the residual
+     words for a partition per channel until we've written all the
+     residual words for that partition word.  Then write the next
+     partition channel words... */
+
+  for(s=0;s<look->stages;s++){
+
+    for(i=0;i<partvals;){
+
+      /* first we encode a partition codeword for each channel */
+      if(s==0){
+        for(j=0;j<ch;j++){
+          long val=partword[j][i];
+          for(k=1;k<partitions_per_word;k++){
+            val*=possible_partitions;
+            if(i+k<partvals)
+              val+=partword[j][i+k];
+          }
+
+          /* training hack */
+          if(val<look->phrasebook->entries)
+            look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
+#if 0 /*def TRAIN_RES*/
+          else
+            fprintf(stderr,"!");
+#endif
+
+        }
+      }
+
+      /* now we encode interleaved residual values for the partitions */
+      for(k=0;k<partitions_per_word && i<partvals;k++,i++){
+        long offset=i*samples_per_partition+info->begin;
+
+        for(j=0;j<ch;j++){
+          if(s==0)resvals[partword[j][i]]+=samples_per_partition;
+          if(info->secondstages[partword[j][i]]&(1<<s)){
+            codebook *statebook=look->partbooks[partword[j][i]][s];
+            if(statebook){
+              int ret;
+#ifdef TRAIN_RES
+              long *accumulator=NULL;
+              accumulator=look->training_data[s][partword[j][i]];
+              {
+                int l;
+                int *samples=in[j]+offset;
+                for(l=0;l<samples_per_partition;l++){
+                  if(samples[l]<look->training_min[s][partword[j][i]])
+                    look->training_min[s][partword[j][i]]=samples[l];
+                  if(samples[l]>look->training_max[s][partword[j][i]])
+                    look->training_max[s][partword[j][i]]=samples[l];
+                }
+              }
+              ret=encode(opb,in[j]+offset,samples_per_partition,
+                         statebook,accumulator);
+#else
+              ret=encode(opb,in[j]+offset,samples_per_partition,
+                         statebook);
+#endif
+
+              look->postbits+=ret;
+              resbits[partword[j][i]]+=ret;
+            }
+          }
+        }
+      }
+    }
+  }
+
+  return(0);
+}
+
+/* a truncated packet here just means 'stop working'; it's not an error */
+static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
+                      float **in,int ch,
+                      long (*decodepart)(codebook *, float *,
+                                         oggpack_buffer *,int)){
+
+  long i,j,k,l,s;
+  vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
+  vorbis_info_residue0 *info=look->info;
+
+  /* move all this setup out later */
+  int samples_per_partition=info->grouping;
+  int partitions_per_word=look->phrasebook->dim;
+  int max=vb->pcmend>>1;
+  int end=(info->end<max?info->end:max);
+  int n=end-info->begin;
+
+  if(n>0){
+    int partvals=n/samples_per_partition;
+    int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
+    int ***partword=alloca(ch*sizeof(*partword));
+
+    for(j=0;j<ch;j++)
+      partword[j]=_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
+
+    for(s=0;s<look->stages;s++){
+
+      /* each loop decodes on partition codeword containing
+         partitions_per_word partitions */
+      for(i=0,l=0;i<partvals;l++){
+        if(s==0){
+          /* fetch the partition word for each channel */
+          for(j=0;j<ch;j++){
+            int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
+
+            if(temp==-1 || temp>=info->partvals)goto eopbreak;
+            partword[j][l]=look->decodemap[temp];
+            if(partword[j][l]==NULL)goto errout;
+          }
+        }
+
+        /* now we decode residual values for the partitions */
+        for(k=0;k<partitions_per_word && i<partvals;k++,i++)
+          for(j=0;j<ch;j++){
+            long offset=info->begin+i*samples_per_partition;
+            if(info->secondstages[partword[j][l][k]]&(1<<s)){
+              codebook *stagebook=look->partbooks[partword[j][l][k]][s];
+              if(stagebook){
+                if(decodepart(stagebook,in[j]+offset,&vb->opb,
+                              samples_per_partition)==-1)goto eopbreak;
+              }
+            }
+          }
+      }
+    }
+  }
+ errout:
+ eopbreak:
+  return(0);
+}
+
+int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
+                 float **in,int *nonzero,int ch){
+  int i,used=0;
+  for(i=0;i<ch;i++)
+    if(nonzero[i])
+      in[used++]=in[i];
+  if(used)
+    return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
+  else
+    return(0);
+}
+
+int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
+                 int **in,int *nonzero,int ch, long **partword, int submap){
+  int i,used=0;
+  (void)vb;
+  for(i=0;i<ch;i++)
+    if(nonzero[i])
+      in[used++]=in[i];
+
+  if(used){
+#ifdef TRAIN_RES
+    return _01forward(opb,vl,in,used,partword,_encodepart,submap);
+#else
+    (void)submap;
+    return _01forward(opb,vl,in,used,partword,_encodepart);
+#endif
+  }else{
+    return(0);
+  }
+}
+
+long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
+                  int **in,int *nonzero,int ch){
+  int i,used=0;
+  for(i=0;i<ch;i++)
+    if(nonzero[i])
+      in[used++]=in[i];
+  if(used)
+    return(_01class(vb,vl,in,used));
+  else
+    return(0);
+}
+
+int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
+                 float **in,int *nonzero,int ch){
+  int i,used=0;
+  for(i=0;i<ch;i++)
+    if(nonzero[i])
+      in[used++]=in[i];
+  if(used)
+    return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
+  else
+    return(0);
+}
+
+long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
+                  int **in,int *nonzero,int ch){
+  int i,used=0;
+  for(i=0;i<ch;i++)
+    if(nonzero[i])used++;
+  if(used)
+    return(_2class(vb,vl,in,ch));
+  else
+    return(0);
+}
+
+/* res2 is slightly more different; all the channels are interleaved
+   into a single vector and encoded. */
+
+int res2_forward(oggpack_buffer *opb,
+                 vorbis_block *vb,vorbis_look_residue *vl,
+                 int **in,int *nonzero,int ch, long **partword,int submap){
+  long i,j,k,n=vb->pcmend/2,used=0;
+
+  /* don't duplicate the code; use a working vector hack for now and
+     reshape ourselves into a single channel res1 */
+  /* ugly; reallocs for each coupling pass :-( */
+  int *work=_vorbis_block_alloc(vb,ch*n*sizeof(*work));
+  for(i=0;i<ch;i++){
+    int *pcm=in[i];
+    if(nonzero[i])used++;
+    for(j=0,k=i;j<n;j++,k+=ch)
+      work[k]=pcm[j];
+  }
+
+  if(used){
+#ifdef TRAIN_RES
+    return _01forward(opb,vl,&work,1,partword,_encodepart,submap);
+#else
+    (void)submap;
+    return _01forward(opb,vl,&work,1,partword,_encodepart);
+#endif
+  }else{
+    return(0);
+  }
+}
+
+/* duplicate code here as speed is somewhat more important */
+int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
+                 float **in,int *nonzero,int ch){
+  long i,k,l,s;
+  vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
+  vorbis_info_residue0 *info=look->info;
+
+  /* move all this setup out later */
+  int samples_per_partition=info->grouping;
+  int partitions_per_word=look->phrasebook->dim;
+  int max=(vb->pcmend*ch)>>1;
+  int end=(info->end<max?info->end:max);
+  int n=end-info->begin;
+
+  if(n>0){
+    int partvals=n/samples_per_partition;
+    int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
+    int **partword=_vorbis_block_alloc(vb,partwords*sizeof(*partword));
+
+    for(i=0;i<ch;i++)if(nonzero[i])break;
+    if(i==ch)return(0); /* no nonzero vectors */
+
+    for(s=0;s<look->stages;s++){
+      for(i=0,l=0;i<partvals;l++){
+
+        if(s==0){
+          /* fetch the partition word */
+          int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
+          if(temp==-1 || temp>=info->partvals)goto eopbreak;
+          partword[l]=look->decodemap[temp];
+          if(partword[l]==NULL)goto errout;
+        }
+
+        /* now we decode residual values for the partitions */
+        for(k=0;k<partitions_per_word && i<partvals;k++,i++)
+          if(info->secondstages[partword[l][k]]&(1<<s)){
+            codebook *stagebook=look->partbooks[partword[l][k]][s];
+
+            if(stagebook){
+              if(vorbis_book_decodevv_add(stagebook,in,
+                                          i*samples_per_partition+info->begin,ch,
+                                          &vb->opb,samples_per_partition)==-1)
+                goto eopbreak;
+            }
+          }
+      }
+    }
+  }
+ errout:
+ eopbreak:
+  return(0);
+}
+
+
+const vorbis_func_residue residue0_exportbundle={
+  NULL,
+  &res0_unpack,
+  &res0_look,
+  &res0_free_info,
+  &res0_free_look,
+  NULL,
+  NULL,
+  &res0_inverse
+};
+
+const vorbis_func_residue residue1_exportbundle={
+  &res0_pack,
+  &res0_unpack,
+  &res0_look,
+  &res0_free_info,
+  &res0_free_look,
+  &res1_class,
+  &res1_forward,
+  &res1_inverse
+};
+
+const vorbis_func_residue residue2_exportbundle={
+  &res0_pack,
+  &res0_unpack,
+  &res0_look,
+  &res0_free_info,
+  &res0_free_look,
+  &res2_class,
+  &res2_forward,
+  &res2_inverse
+};
diff --git a/vorbis/lib/scales.h b/vorbis/lib/scales.h
new file mode 100644 (file)
index 0000000..18bc4e7
--- /dev/null
@@ -0,0 +1,89 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: linear scale -> dB, Bark and Mel scales
+
+ ********************************************************************/
+
+#ifndef _V_SCALES_H_
+#define _V_SCALES_H_
+
+#include <math.h>
+#include "os.h"
+
+#ifdef _MSC_VER
+/* MS Visual Studio doesn't have C99 inline keyword. */
+#define inline __inline
+#endif
+
+/* 20log10(x) */
+#define VORBIS_IEEE_FLOAT32 1
+#ifdef VORBIS_IEEE_FLOAT32
+
+static inline float unitnorm(float x){
+  union {
+    ogg_uint32_t i;
+    float f;
+  } ix;
+  ix.f = x;
+  ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
+  return ix.f;
+}
+
+/* Segher was off (too high) by ~ .3 decibel.  Center the conversion correctly. */
+static inline float todB(const float *x){
+  union {
+    ogg_uint32_t i;
+    float f;
+  } ix;
+  ix.f = *x;
+  ix.i = ix.i&0x7fffffff;
+  return (float)(ix.i * 7.17711438e-7f -764.6161886f);
+}
+
+#define todB_nn(x) todB(x)
+
+#else
+
+static float unitnorm(float x){
+  if(x<0)return(-1.f);
+  return(1.f);
+}
+
+#define todB(x)   (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
+#define todB_nn(x)   (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
+
+#endif
+
+#define fromdB(x) (exp((x)*.11512925f))
+
+/* The bark scale equations are approximations, since the original
+   table was somewhat hand rolled.  The below are chosen to have the
+   best possible fit to the rolled tables, thus their somewhat odd
+   appearance (these are more accurate and over a longer range than
+   the oft-quoted bark equations found in the texts I have).  The
+   approximations are valid from 0 - 30kHz (nyquist) or so.
+
+   all f in Hz, z in Bark */
+
+#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)
+#define toMEL(n)    (log(1.f+(n)*.001f)*1442.695f)
+#define fromMEL(m)  (1000.f*exp((m)/1442.695f)-1000.f)
+
+/* Frequency to octave.  We arbitrarily declare 63.5 Hz to be octave
+   0.0 */
+
+#define toOC(n)     (log(n)*1.442695f-5.965784f)
+#define fromOC(o)   (exp(((o)+5.965784f)*.693147f))
+
+#endif
diff --git a/vorbis/lib/sharedbook.c b/vorbis/lib/sharedbook.c
new file mode 100644 (file)
index 0000000..4545d4f
--- /dev/null
@@ -0,0 +1,595 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: basic shared codebook operations
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <limits.h>
+#include <math.h>
+#include <string.h>
+#include <ogg/ogg.h>
+#include "os.h"
+#include "misc.h"
+#include "vorbis/codec.h"
+#include "codebook.h"
+#include "scales.h"
+
+/**** pack/unpack helpers ******************************************/
+
+int ov_ilog(ogg_uint32_t v){
+  int ret;
+  for(ret=0;v;ret++)v>>=1;
+  return ret;
+}
+
+/* 32 bit float (not IEEE; nonnormalized mantissa +
+   biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
+   Why not IEEE?  It's just not that important here. */
+
+#define VQ_FEXP 10
+#define VQ_FMAN 21
+#define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
+
+/* doesn't currently guard under/overflow */
+long _float32_pack(float val){
+  int sign=0;
+  long exp;
+  long mant;
+  if(val<0){
+    sign=0x80000000;
+    val= -val;
+  }
+  exp= floor(log(val)/log(2.f)+.001); //+epsilon
+  mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
+  exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
+
+  return(sign|exp|mant);
+}
+
+float _float32_unpack(long val){
+  double mant=val&0x1fffff;
+  int    sign=val&0x80000000;
+  long   exp =(val&0x7fe00000L)>>VQ_FMAN;
+  if(sign)mant= -mant;
+  return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
+}
+
+/* given a list of word lengths, generate a list of codewords.  Works
+   for length ordered or unordered, always assigns the lowest valued
+   codewords first.  Extended to handle unused entries (length 0) */
+ogg_uint32_t *_make_words(char *l,long n,long sparsecount){
+  long i,j,count=0;
+  ogg_uint32_t marker[33];
+  ogg_uint32_t *r=_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
+  memset(marker,0,sizeof(marker));
+
+  for(i=0;i<n;i++){
+    long length=l[i];
+    if(length>0){
+      ogg_uint32_t entry=marker[length];
+
+      /* when we claim a node for an entry, we also claim the nodes
+         below it (pruning off the imagined tree that may have dangled
+         from it) as well as blocking the use of any nodes directly
+         above for leaves */
+
+      /* update ourself */
+      if(length<32 && (entry>>length)){
+        /* error condition; the lengths must specify an overpopulated tree */
+        _ogg_free(r);
+        return(NULL);
+      }
+      r[count++]=entry;
+
+      /* Look to see if the next shorter marker points to the node
+         above. if so, update it and repeat.  */
+      {
+        for(j=length;j>0;j--){
+
+          if(marker[j]&1){
+            /* have to jump branches */
+            if(j==1)
+              marker[1]++;
+            else
+              marker[j]=marker[j-1]<<1;
+            break; /* invariant says next upper marker would already
+                      have been moved if it was on the same path */
+          }
+          marker[j]++;
+        }
+      }
+
+      /* prune the tree; the implicit invariant says all the longer
+         markers were dangling from our just-taken node.  Dangle them
+         from our *new* node. */
+      for(j=length+1;j<33;j++)
+        if((marker[j]>>1) == entry){
+          entry=marker[j];
+          marker[j]=marker[j-1]<<1;
+        }else
+          break;
+    }else
+      if(sparsecount==0)count++;
+  }
+
+  /* any underpopulated tree must be rejected. */
+  /* Single-entry codebooks are a retconned extension to the spec.
+     They have a single codeword '0' of length 1 that results in an
+     underpopulated tree.  Shield that case from the underformed tree check. */
+  if(!(count==1 && marker[2]==2)){
+    for(i=1;i<33;i++)
+      if(marker[i] & (0xffffffffUL>>(32-i))){
+        _ogg_free(r);
+        return(NULL);
+      }
+  }
+
+  /* bitreverse the words because our bitwise packer/unpacker is LSb
+     endian */
+  for(i=0,count=0;i<n;i++){
+    ogg_uint32_t temp=0;
+    for(j=0;j<l[i];j++){
+      temp<<=1;
+      temp|=(r[count]>>j)&1;
+    }
+
+    if(sparsecount){
+      if(l[i])
+        r[count++]=temp;
+    }else
+      r[count++]=temp;
+  }
+
+  return(r);
+}
+
+/* there might be a straightforward one-line way to do the below
+   that's portable and totally safe against roundoff, but I haven't
+   thought of it.  Therefore, we opt on the side of caution */
+long _book_maptype1_quantvals(const static_codebook *b){
+  long vals;
+  if(b->entries<1){
+    return(0);
+  }
+  vals=floor(pow((float)b->entries,1.f/b->dim));
+
+  /* the above *should* be reliable, but we'll not assume that FP is
+     ever reliable when bitstream sync is at stake; verify via integer
+     means that vals really is the greatest value of dim for which
+     vals^b->bim <= b->entries */
+  /* treat the above as an initial guess */
+  if(vals<1){
+    vals=1;
+  }
+  while(1){
+    long acc=1;
+    long acc1=1;
+    int i;
+    for(i=0;i<b->dim;i++){
+      if(b->entries/vals<acc)break;
+      acc*=vals;
+      if(LONG_MAX/(vals+1)<acc1)acc1=LONG_MAX;
+      else acc1*=vals+1;
+    }
+    if(i>=b->dim && acc<=b->entries && acc1>b->entries){
+      return(vals);
+    }else{
+      if(i<b->dim || acc>b->entries){
+        vals--;
+      }else{
+        vals++;
+      }
+    }
+  }
+}
+
+/* unpack the quantized list of values for encode/decode ***********/
+/* we need to deal with two map types: in map type 1, the values are
+   generated algorithmically (each column of the vector counts through
+   the values in the quant vector). in map type 2, all the values came
+   in in an explicit list.  Both value lists must be unpacked */
+float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
+  long j,k,count=0;
+  if(b->maptype==1 || b->maptype==2){
+    int quantvals;
+    float mindel=_float32_unpack(b->q_min);
+    float delta=_float32_unpack(b->q_delta);
+    float *r=_ogg_calloc(n*b->dim,sizeof(*r));
+
+    /* maptype 1 and 2 both use a quantized value vector, but
+       different sizes */
+    switch(b->maptype){
+    case 1:
+      /* most of the time, entries%dimensions == 0, but we need to be
+         well defined.  We define that the possible vales at each
+         scalar is values == entries/dim.  If entries%dim != 0, we'll
+         have 'too few' values (values*dim<entries), which means that
+         we'll have 'left over' entries; left over entries use zeroed
+         values (and are wasted).  So don't generate codebooks like
+         that */
+      quantvals=_book_maptype1_quantvals(b);
+      for(j=0;j<b->entries;j++){
+        if((sparsemap && b->lengthlist[j]) || !sparsemap){
+          float last=0.f;
+          int indexdiv=1;
+          for(k=0;k<b->dim;k++){
+            int index= (j/indexdiv)%quantvals;
+            float val=b->quantlist[index];
+            val=fabs(val)*delta+mindel+last;
+            if(b->q_sequencep)last=val;
+            if(sparsemap)
+              r[sparsemap[count]*b->dim+k]=val;
+            else
+              r[count*b->dim+k]=val;
+            indexdiv*=quantvals;
+          }
+          count++;
+        }
+
+      }
+      break;
+    case 2:
+      for(j=0;j<b->entries;j++){
+        if((sparsemap && b->lengthlist[j]) || !sparsemap){
+          float last=0.f;
+
+          for(k=0;k<b->dim;k++){
+            float val=b->quantlist[j*b->dim+k];
+            val=fabs(val)*delta+mindel+last;
+            if(b->q_sequencep)last=val;
+            if(sparsemap)
+              r[sparsemap[count]*b->dim+k]=val;
+            else
+              r[count*b->dim+k]=val;
+          }
+          count++;
+        }
+      }
+      break;
+    }
+
+    return(r);
+  }
+  return(NULL);
+}
+
+void vorbis_staticbook_destroy(static_codebook *b){
+  if(b->allocedp){
+    if(b->quantlist)_ogg_free(b->quantlist);
+    if(b->lengthlist)_ogg_free(b->lengthlist);
+    memset(b,0,sizeof(*b));
+    _ogg_free(b);
+  } /* otherwise, it is in static memory */
+}
+
+void vorbis_book_clear(codebook *b){
+  /* static book is not cleared; we're likely called on the lookup and
+     the static codebook belongs to the info struct */
+  if(b->valuelist)_ogg_free(b->valuelist);
+  if(b->codelist)_ogg_free(b->codelist);
+
+  if(b->dec_index)_ogg_free(b->dec_index);
+  if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
+  if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
+
+  memset(b,0,sizeof(*b));
+}
+
+int vorbis_book_init_encode(codebook *c,const static_codebook *s){
+
+  memset(c,0,sizeof(*c));
+  c->c=s;
+  c->entries=s->entries;
+  c->used_entries=s->entries;
+  c->dim=s->dim;
+  c->codelist=_make_words(s->lengthlist,s->entries,0);
+  //c->valuelist=_book_unquantize(s,s->entries,NULL);
+  c->quantvals=_book_maptype1_quantvals(s);
+  c->minval=(int)rint(_float32_unpack(s->q_min));
+  c->delta=(int)rint(_float32_unpack(s->q_delta));
+
+  return(0);
+}
+
+static ogg_uint32_t bitreverse(ogg_uint32_t x){
+  x=    ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
+  x=    ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
+  x=    ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
+  x=    ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
+  return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
+}
+
+static int sort32a(const void *a,const void *b){
+  return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
+    ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
+}
+
+/* decode codebook arrangement is more heavily optimized than encode */
+int vorbis_book_init_decode(codebook *c,const static_codebook *s){
+  int i,j,n=0,tabn;
+  int *sortindex;
+
+  memset(c,0,sizeof(*c));
+
+  /* count actually used entries and find max length */
+  for(i=0;i<s->entries;i++)
+    if(s->lengthlist[i]>0)
+      n++;
+
+  c->entries=s->entries;
+  c->used_entries=n;
+  c->dim=s->dim;
+
+  if(n>0){
+    /* two different remappings go on here.
+
+    First, we collapse the likely sparse codebook down only to
+    actually represented values/words.  This collapsing needs to be
+    indexed as map-valueless books are used to encode original entry
+    positions as integers.
+
+    Second, we reorder all vectors, including the entry index above,
+    by sorted bitreversed codeword to allow treeless decode. */
+
+    /* perform sort */
+    ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
+    ogg_uint32_t **codep=alloca(sizeof(*codep)*n);
+
+    if(codes==NULL)goto err_out;
+
+    for(i=0;i<n;i++){
+      codes[i]=bitreverse(codes[i]);
+      codep[i]=codes+i;
+    }
+
+    qsort(codep,n,sizeof(*codep),sort32a);
+
+    sortindex=alloca(n*sizeof(*sortindex));
+    c->codelist=_ogg_malloc(n*sizeof(*c->codelist));
+    /* the index is a reverse index */
+    for(i=0;i<n;i++){
+      int position=codep[i]-codes;
+      sortindex[position]=i;
+    }
+
+    for(i=0;i<n;i++)
+      c->codelist[sortindex[i]]=codes[i];
+    _ogg_free(codes);
+
+    c->valuelist=_book_unquantize(s,n,sortindex);
+    c->dec_index=_ogg_malloc(n*sizeof(*c->dec_index));
+
+    for(n=0,i=0;i<s->entries;i++)
+      if(s->lengthlist[i]>0)
+        c->dec_index[sortindex[n++]]=i;
+
+    c->dec_codelengths=_ogg_malloc(n*sizeof(*c->dec_codelengths));
+    c->dec_maxlength=0;
+    for(n=0,i=0;i<s->entries;i++)
+      if(s->lengthlist[i]>0){
+        c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
+        if(s->lengthlist[i]>c->dec_maxlength)
+          c->dec_maxlength=s->lengthlist[i];
+      }
+
+    if(n==1 && c->dec_maxlength==1){
+      /* special case the 'single entry codebook' with a single bit
+       fastpath table (that always returns entry 0 )in order to use
+       unmodified decode paths. */
+      c->dec_firsttablen=1;
+      c->dec_firsttable=_ogg_calloc(2,sizeof(*c->dec_firsttable));
+      c->dec_firsttable[0]=c->dec_firsttable[1]=1;
+
+    }else{
+      c->dec_firsttablen=ov_ilog(c->used_entries)-4; /* this is magic */
+      if(c->dec_firsttablen<5)c->dec_firsttablen=5;
+      if(c->dec_firsttablen>8)c->dec_firsttablen=8;
+
+      tabn=1<<c->dec_firsttablen;
+      c->dec_firsttable=_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
+
+      for(i=0;i<n;i++){
+        if(c->dec_codelengths[i]<=c->dec_firsttablen){
+          ogg_uint32_t orig=bitreverse(c->codelist[i]);
+          for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
+            c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
+        }
+      }
+
+      /* now fill in 'unused' entries in the firsttable with hi/lo search
+         hints for the non-direct-hits */
+      {
+        ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
+        long lo=0,hi=0;
+
+        for(i=0;i<tabn;i++){
+          ogg_uint32_t word=i<<(32-c->dec_firsttablen);
+          if(c->dec_firsttable[bitreverse(word)]==0){
+            while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
+            while(    hi<n && word>=(c->codelist[hi]&mask))hi++;
+
+            /* we only actually have 15 bits per hint to play with here.
+               In order to overflow gracefully (nothing breaks, efficiency
+               just drops), encode as the difference from the extremes. */
+            {
+              unsigned long loval=lo;
+              unsigned long hival=n-hi;
+
+              if(loval>0x7fff)loval=0x7fff;
+              if(hival>0x7fff)hival=0x7fff;
+              c->dec_firsttable[bitreverse(word)]=
+                0x80000000UL | (loval<<15) | hival;
+            }
+          }
+        }
+      }
+    }
+  }
+
+  return(0);
+ err_out:
+  vorbis_book_clear(c);
+  return(-1);
+}
+
+long vorbis_book_codeword(codebook *book,int entry){
+  if(book->c) /* only use with encode; decode optimizations are
+                 allowed to break this */
+    return book->codelist[entry];
+  return -1;
+}
+
+long vorbis_book_codelen(codebook *book,int entry){
+  if(book->c) /* only use with encode; decode optimizations are
+                 allowed to break this */
+    return book->c->lengthlist[entry];
+  return -1;
+}
+
+#ifdef _V_SELFTEST
+
+/* Unit tests of the dequantizer; this stuff will be OK
+   cross-platform, I simply want to be sure that special mapping cases
+   actually work properly; a bug could go unnoticed for a while */
+
+#include <stdio.h>
+
+/* cases:
+
+   no mapping
+   full, explicit mapping
+   algorithmic mapping
+
+   nonsequential
+   sequential
+*/
+
+static long full_quantlist1[]={0,1,2,3,    4,5,6,7, 8,3,6,1};
+static long partial_quantlist1[]={0,7,2};
+
+/* no mapping */
+static_codebook test1={
+  4,16,
+  NULL,
+  0,
+  0,0,0,0,
+  NULL,
+  0
+};
+static float *test1_result=NULL;
+
+/* linear, full mapping, nonsequential */
+static_codebook test2={
+  4,3,
+  NULL,
+  2,
+  -533200896,1611661312,4,0,
+  full_quantlist1,
+  0
+};
+static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
+
+/* linear, full mapping, sequential */
+static_codebook test3={
+  4,3,
+  NULL,
+  2,
+  -533200896,1611661312,4,1,
+  full_quantlist1,
+  0
+};
+static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
+
+/* linear, algorithmic mapping, nonsequential */
+static_codebook test4={
+  3,27,
+  NULL,
+  1,
+  -533200896,1611661312,4,0,
+  partial_quantlist1,
+  0
+};
+static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
+                              -3, 4,-3, 4, 4,-3, -1, 4,-3,
+                              -3,-1,-3, 4,-1,-3, -1,-1,-3,
+                              -3,-3, 4, 4,-3, 4, -1,-3, 4,
+                              -3, 4, 4, 4, 4, 4, -1, 4, 4,
+                              -3,-1, 4, 4,-1, 4, -1,-1, 4,
+                              -3,-3,-1, 4,-3,-1, -1,-3,-1,
+                              -3, 4,-1, 4, 4,-1, -1, 4,-1,
+                              -3,-1,-1, 4,-1,-1, -1,-1,-1};
+
+/* linear, algorithmic mapping, sequential */
+static_codebook test5={
+  3,27,
+  NULL,
+  1,
+  -533200896,1611661312,4,1,
+  partial_quantlist1,
+  0
+};
+static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
+                              -3, 1,-2, 4, 8, 5, -1, 3, 0,
+                              -3,-4,-7, 4, 3, 0, -1,-2,-5,
+                              -3,-6,-2, 4, 1, 5, -1,-4, 0,
+                              -3, 1, 5, 4, 8,12, -1, 3, 7,
+                              -3,-4, 0, 4, 3, 7, -1,-2, 2,
+                              -3,-6,-7, 4, 1, 0, -1,-4,-5,
+                              -3, 1, 0, 4, 8, 7, -1, 3, 2,
+                              -3,-4,-5, 4, 3, 2, -1,-2,-3};
+
+void run_test(static_codebook *b,float *comp){
+  float *out=_book_unquantize(b,b->entries,NULL);
+  int i;
+
+  if(comp){
+    if(!out){
+      fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
+      exit(1);
+    }
+
+    for(i=0;i<b->entries*b->dim;i++)
+      if(fabs(out[i]-comp[i])>.0001){
+        fprintf(stderr,"disagreement in unquantized and reference data:\n"
+                "position %d, %g != %g\n",i,out[i],comp[i]);
+        exit(1);
+      }
+
+  }else{
+    if(out){
+      fprintf(stderr,"_book_unquantize returned a value array: \n"
+              " correct result should have been NULL\n");
+      exit(1);
+    }
+  }
+}
+
+int main(){
+  /* run the nine dequant tests, and compare to the hand-rolled results */
+  fprintf(stderr,"Dequant test 1... ");
+  run_test(&test1,test1_result);
+  fprintf(stderr,"OK\nDequant test 2... ");
+  run_test(&test2,test2_result);
+  fprintf(stderr,"OK\nDequant test 3... ");
+  run_test(&test3,test3_result);
+  fprintf(stderr,"OK\nDequant test 4... ");
+  run_test(&test4,test4_result);
+  fprintf(stderr,"OK\nDequant test 5... ");
+  run_test(&test5,test5_result);
+  fprintf(stderr,"OK\n\n");
+
+  return(0);
+}
+
+#endif
diff --git a/vorbis/lib/smallft.c b/vorbis/lib/smallft.c
new file mode 100644 (file)
index 0000000..6d528af
--- /dev/null
@@ -0,0 +1,1254 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: *unnormalized* fft transform
+
+ ********************************************************************/
+
+/* FFT implementation from OggSquish, minus cosine transforms,
+ * minus all but radix 2/4 case.  In Vorbis we only need this
+ * cut-down version.
+ *
+ * To do more than just power-of-two sized vectors, see the full
+ * version I wrote for NetLib.
+ *
+ * Note that the packing is a little strange; rather than the FFT r/i
+ * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
+ * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
+ * FORTRAN version
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include "smallft.h"
+#include "os.h"
+#include "misc.h"
+
+static void drfti1(int n, float *wa, int *ifac){
+  static int ntryh[4] = { 4,2,3,5 };
+  static float tpi = 6.28318530717958648f;
+  float arg,argh,argld,fi;
+  int ntry=0,i,j=-1;
+  int k1, l1, l2, ib;
+  int ld, ii, ip, is, nq, nr;
+  int ido, ipm, nfm1;
+  int nl=n;
+  int nf=0;
+
+ L101:
+  j++;
+  if (j < 4)
+    ntry=ntryh[j];
+  else
+    ntry+=2;
+
+ L104:
+  nq=nl/ntry;
+  nr=nl-ntry*nq;
+  if (nr!=0) goto L101;
+
+  nf++;
+  ifac[nf+1]=ntry;
+  nl=nq;
+  if(ntry!=2)goto L107;
+  if(nf==1)goto L107;
+
+  for (i=1;i<nf;i++){
+    ib=nf-i+1;
+    ifac[ib+1]=ifac[ib];
+  }
+  ifac[2] = 2;
+
+ L107:
+  if(nl!=1)goto L104;
+  ifac[0]=n;
+  ifac[1]=nf;
+  argh=tpi/n;
+  is=0;
+  nfm1=nf-1;
+  l1=1;
+
+  if(nfm1==0)return;
+
+  for (k1=0;k1<nfm1;k1++){
+    ip=ifac[k1+2];
+    ld=0;
+    l2=l1*ip;
+    ido=n/l2;
+    ipm=ip-1;
+
+    for (j=0;j<ipm;j++){
+      ld+=l1;
+      i=is;
+      argld=(float)ld*argh;
+      fi=0.f;
+      for (ii=2;ii<ido;ii+=2){
+        fi+=1.f;
+        arg=fi*argld;
+        wa[i++]=cos(arg);
+        wa[i++]=sin(arg);
+      }
+      is+=ido;
+    }
+    l1=l2;
+  }
+}
+
+static void fdrffti(int n, float *wsave, int *ifac){
+
+  if (n == 1) return;
+  drfti1(n, wsave+n, ifac);
+}
+
+static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
+  int i,k;
+  float ti2,tr2;
+  int t0,t1,t2,t3,t4,t5,t6;
+
+  t1=0;
+  t0=(t2=l1*ido);
+  t3=ido<<1;
+  for(k=0;k<l1;k++){
+    ch[t1<<1]=cc[t1]+cc[t2];
+    ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
+    t1+=ido;
+    t2+=ido;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  t2=t0;
+  for(k=0;k<l1;k++){
+    t3=t2;
+    t4=(t1<<1)+(ido<<1);
+    t5=t1;
+    t6=t1+t1;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4-=2;
+      t5+=2;
+      t6+=2;
+      tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
+      ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
+      ch[t6]=cc[t5]+ti2;
+      ch[t4]=ti2-cc[t5];
+      ch[t6-1]=cc[t5-1]+tr2;
+      ch[t4-1]=cc[t5-1]-tr2;
+    }
+    t1+=ido;
+    t2+=ido;
+  }
+
+  if(ido%2==1)return;
+
+ L105:
+  t3=(t2=(t1=ido)-1);
+  t2+=t0;
+  for(k=0;k<l1;k++){
+    ch[t1]=-cc[t2];
+    ch[t1-1]=cc[t3];
+    t1+=ido<<1;
+    t2+=ido;
+    t3+=ido;
+  }
+}
+
+static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
+            float *wa2,float *wa3){
+  static float hsqt2 = .70710678118654752f;
+  int i,k,t0,t1,t2,t3,t4,t5,t6;
+  float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
+  t0=l1*ido;
+
+  t1=t0;
+  t4=t1<<1;
+  t2=t1+(t1<<1);
+  t3=0;
+
+  for(k=0;k<l1;k++){
+    tr1=cc[t1]+cc[t2];
+    tr2=cc[t3]+cc[t4];
+
+    ch[t5=t3<<2]=tr1+tr2;
+    ch[(ido<<2)+t5-1]=tr2-tr1;
+    ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
+    ch[t5]=cc[t2]-cc[t1];
+
+    t1+=ido;
+    t2+=ido;
+    t3+=ido;
+    t4+=ido;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+
+  t1=0;
+  for(k=0;k<l1;k++){
+    t2=t1;
+    t4=t1<<2;
+    t5=(t6=ido<<1)+t4;
+    for(i=2;i<ido;i+=2){
+      t3=(t2+=2);
+      t4+=2;
+      t5-=2;
+
+      t3+=t0;
+      cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
+      ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
+      t3+=t0;
+      cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
+      ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
+      t3+=t0;
+      cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
+      ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
+
+      tr1=cr2+cr4;
+      tr4=cr4-cr2;
+      ti1=ci2+ci4;
+      ti4=ci2-ci4;
+
+      ti2=cc[t2]+ci3;
+      ti3=cc[t2]-ci3;
+      tr2=cc[t2-1]+cr3;
+      tr3=cc[t2-1]-cr3;
+
+      ch[t4-1]=tr1+tr2;
+      ch[t4]=ti1+ti2;
+
+      ch[t5-1]=tr3-ti4;
+      ch[t5]=tr4-ti3;
+
+      ch[t4+t6-1]=ti4+tr3;
+      ch[t4+t6]=tr4+ti3;
+
+      ch[t5+t6-1]=tr2-tr1;
+      ch[t5+t6]=ti1-ti2;
+    }
+    t1+=ido;
+  }
+  if(ido&1)return;
+
+ L105:
+
+  t2=(t1=t0+ido-1)+(t0<<1);
+  t3=ido<<2;
+  t4=ido;
+  t5=ido<<1;
+  t6=ido;
+
+  for(k=0;k<l1;k++){
+    ti1=-hsqt2*(cc[t1]+cc[t2]);
+    tr1=hsqt2*(cc[t1]-cc[t2]);
+
+    ch[t4-1]=tr1+cc[t6-1];
+    ch[t4+t5-1]=cc[t6-1]-tr1;
+
+    ch[t4]=ti1-cc[t1+t0];
+    ch[t4+t5]=ti1+cc[t1+t0];
+
+    t1+=ido;
+    t2+=ido;
+    t4+=t3;
+    t6+=ido;
+  }
+}
+
+static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
+                          float *c2,float *ch,float *ch2,float *wa){
+
+  static float tpi=6.283185307179586f;
+  int idij,ipph,i,j,k,l,ic,ik,is;
+  int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
+  float dc2,ai1,ai2,ar1,ar2,ds2;
+  int nbd;
+  float dcp,arg,dsp,ar1h,ar2h;
+  int idp2,ipp2;
+
+  arg=tpi/(float)ip;
+  dcp=cos(arg);
+  dsp=sin(arg);
+  ipph=(ip+1)>>1;
+  ipp2=ip;
+  idp2=ido;
+  nbd=(ido-1)>>1;
+  t0=l1*ido;
+  t10=ip*ido;
+
+  if(ido==1)goto L119;
+  for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
+
+  t1=0;
+  for(j=1;j<ip;j++){
+    t1+=t0;
+    t2=t1;
+    for(k=0;k<l1;k++){
+      ch[t2]=c1[t2];
+      t2+=ido;
+    }
+  }
+
+  is=-ido;
+  t1=0;
+  if(nbd>l1){
+    for(j=1;j<ip;j++){
+      t1+=t0;
+      is+=ido;
+      t2= -ido+t1;
+      for(k=0;k<l1;k++){
+        idij=is-1;
+        t2+=ido;
+        t3=t2;
+        for(i=2;i<ido;i+=2){
+          idij+=2;
+          t3+=2;
+          ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
+          ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
+        }
+      }
+    }
+  }else{
+
+    for(j=1;j<ip;j++){
+      is+=ido;
+      idij=is-1;
+      t1+=t0;
+      t2=t1;
+      for(i=2;i<ido;i+=2){
+        idij+=2;
+        t2+=2;
+        t3=t2;
+        for(k=0;k<l1;k++){
+          ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
+          ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
+          t3+=ido;
+        }
+      }
+    }
+  }
+
+  t1=0;
+  t2=ipp2*t0;
+  if(nbd<l1){
+    for(j=1;j<ipph;j++){
+      t1+=t0;
+      t2-=t0;
+      t3=t1;
+      t4=t2;
+      for(i=2;i<ido;i+=2){
+        t3+=2;
+        t4+=2;
+        t5=t3-ido;
+        t6=t4-ido;
+        for(k=0;k<l1;k++){
+          t5+=ido;
+          t6+=ido;
+          c1[t5-1]=ch[t5-1]+ch[t6-1];
+          c1[t6-1]=ch[t5]-ch[t6];
+          c1[t5]=ch[t5]+ch[t6];
+          c1[t6]=ch[t6-1]-ch[t5-1];
+        }
+      }
+    }
+  }else{
+    for(j=1;j<ipph;j++){
+      t1+=t0;
+      t2-=t0;
+      t3=t1;
+      t4=t2;
+      for(k=0;k<l1;k++){
+        t5=t3;
+        t6=t4;
+        for(i=2;i<ido;i+=2){
+          t5+=2;
+          t6+=2;
+          c1[t5-1]=ch[t5-1]+ch[t6-1];
+          c1[t6-1]=ch[t5]-ch[t6];
+          c1[t5]=ch[t5]+ch[t6];
+          c1[t6]=ch[t6-1]-ch[t5-1];
+        }
+        t3+=ido;
+        t4+=ido;
+      }
+    }
+  }
+
+L119:
+  for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
+
+  t1=0;
+  t2=ipp2*idl1;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1-ido;
+    t4=t2-ido;
+    for(k=0;k<l1;k++){
+      t3+=ido;
+      t4+=ido;
+      c1[t3]=ch[t3]+ch[t4];
+      c1[t4]=ch[t4]-ch[t3];
+    }
+  }
+
+  ar1=1.f;
+  ai1=0.f;
+  t1=0;
+  t2=ipp2*idl1;
+  t3=(ip-1)*idl1;
+  for(l=1;l<ipph;l++){
+    t1+=idl1;
+    t2-=idl1;
+    ar1h=dcp*ar1-dsp*ai1;
+    ai1=dcp*ai1+dsp*ar1;
+    ar1=ar1h;
+    t4=t1;
+    t5=t2;
+    t6=t3;
+    t7=idl1;
+
+    for(ik=0;ik<idl1;ik++){
+      ch2[t4++]=c2[ik]+ar1*c2[t7++];
+      ch2[t5++]=ai1*c2[t6++];
+    }
+
+    dc2=ar1;
+    ds2=ai1;
+    ar2=ar1;
+    ai2=ai1;
+
+    t4=idl1;
+    t5=(ipp2-1)*idl1;
+    for(j=2;j<ipph;j++){
+      t4+=idl1;
+      t5-=idl1;
+
+      ar2h=dc2*ar2-ds2*ai2;
+      ai2=dc2*ai2+ds2*ar2;
+      ar2=ar2h;
+
+      t6=t1;
+      t7=t2;
+      t8=t4;
+      t9=t5;
+      for(ik=0;ik<idl1;ik++){
+        ch2[t6++]+=ar2*c2[t8++];
+        ch2[t7++]+=ai2*c2[t9++];
+      }
+    }
+  }
+
+  t1=0;
+  for(j=1;j<ipph;j++){
+    t1+=idl1;
+    t2=t1;
+    for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
+  }
+
+  if(ido<l1)goto L132;
+
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t4=t2;
+    for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
+    t1+=ido;
+    t2+=t10;
+  }
+
+  goto L135;
+
+ L132:
+  for(i=0;i<ido;i++){
+    t1=i;
+    t2=i;
+    for(k=0;k<l1;k++){
+      cc[t2]=ch[t1];
+      t1+=ido;
+      t2+=t10;
+    }
+  }
+
+ L135:
+  t1=0;
+  t2=ido<<1;
+  t3=0;
+  t4=ipp2*t0;
+  for(j=1;j<ipph;j++){
+
+    t1+=t2;
+    t3+=t0;
+    t4-=t0;
+
+    t5=t1;
+    t6=t3;
+    t7=t4;
+
+    for(k=0;k<l1;k++){
+      cc[t5-1]=ch[t6];
+      cc[t5]=ch[t7];
+      t5+=t10;
+      t6+=ido;
+      t7+=ido;
+    }
+  }
+
+  if(ido==1)return;
+  if(nbd<l1)goto L141;
+
+  t1=-ido;
+  t3=0;
+  t4=0;
+  t5=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t2;
+    t3+=t2;
+    t4+=t0;
+    t5-=t0;
+    t6=t1;
+    t7=t3;
+    t8=t4;
+    t9=t5;
+    for(k=0;k<l1;k++){
+      for(i=2;i<ido;i+=2){
+        ic=idp2-i;
+        cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
+        cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
+        cc[i+t7]=ch[i+t8]+ch[i+t9];
+        cc[ic+t6]=ch[i+t9]-ch[i+t8];
+      }
+      t6+=t10;
+      t7+=t10;
+      t8+=ido;
+      t9+=ido;
+    }
+  }
+  return;
+
+ L141:
+
+  t1=-ido;
+  t3=0;
+  t4=0;
+  t5=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t2;
+    t3+=t2;
+    t4+=t0;
+    t5-=t0;
+    for(i=2;i<ido;i+=2){
+      t6=idp2+t1-i;
+      t7=i+t3;
+      t8=i+t4;
+      t9=i+t5;
+      for(k=0;k<l1;k++){
+        cc[t7-1]=ch[t8-1]+ch[t9-1];
+        cc[t6-1]=ch[t8-1]-ch[t9-1];
+        cc[t7]=ch[t8]+ch[t9];
+        cc[t6]=ch[t9]-ch[t8];
+        t6+=t10;
+        t7+=t10;
+        t8+=ido;
+        t9+=ido;
+      }
+    }
+  }
+}
+
+static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
+  int i,k1,l1,l2;
+  int na,kh,nf;
+  int ip,iw,ido,idl1,ix2,ix3;
+
+  nf=ifac[1];
+  na=1;
+  l2=n;
+  iw=n;
+
+  for(k1=0;k1<nf;k1++){
+    kh=nf-k1;
+    ip=ifac[kh+1];
+    l1=l2/ip;
+    ido=n/l2;
+    idl1=ido*l1;
+    iw-=(ip-1)*ido;
+    na=1-na;
+
+    if(ip!=4)goto L102;
+
+    ix2=iw+ido;
+    ix3=ix2+ido;
+    if(na!=0)
+      dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    else
+      dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    goto L110;
+
+ L102:
+    if(ip!=2)goto L104;
+    if(na!=0)goto L103;
+
+    dradf2(ido,l1,c,ch,wa+iw-1);
+    goto L110;
+
+  L103:
+    dradf2(ido,l1,ch,c,wa+iw-1);
+    goto L110;
+
+  L104:
+    if(ido==1)na=1-na;
+    if(na!=0)goto L109;
+
+    dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
+    na=1;
+    goto L110;
+
+  L109:
+    dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
+    na=0;
+
+  L110:
+    l2=l1;
+  }
+
+  if(na==1)return;
+
+  for(i=0;i<n;i++)c[i]=ch[i];
+}
+
+static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
+  int i,k,t0,t1,t2,t3,t4,t5,t6;
+  float ti2,tr2;
+
+  t0=l1*ido;
+
+  t1=0;
+  t2=0;
+  t3=(ido<<1)-1;
+  for(k=0;k<l1;k++){
+    ch[t1]=cc[t2]+cc[t3+t2];
+    ch[t1+t0]=cc[t2]-cc[t3+t2];
+    t2=(t1+=ido)<<1;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t5=(t4=t2)+(ido<<1);
+    t6=t0+t1;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t5-=2;
+      t6+=2;
+      ch[t3-1]=cc[t4-1]+cc[t5-1];
+      tr2=cc[t4-1]-cc[t5-1];
+      ch[t3]=cc[t4]-cc[t5];
+      ti2=cc[t4]+cc[t5];
+      ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
+      ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
+    }
+    t2=(t1+=ido)<<1;
+  }
+
+  if(ido%2==1)return;
+
+L105:
+  t1=ido-1;
+  t2=ido-1;
+  for(k=0;k<l1;k++){
+    ch[t1]=cc[t2]+cc[t2];
+    ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
+    t1+=ido;
+    t2+=ido<<1;
+  }
+}
+
+static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
+                          float *wa2){
+  static float taur = -.5f;
+  static float taui = .8660254037844386f;
+  int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
+  float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
+  t0=l1*ido;
+
+  t1=0;
+  t2=t0<<1;
+  t3=ido<<1;
+  t4=ido+(ido<<1);
+  t5=0;
+  for(k=0;k<l1;k++){
+    tr2=cc[t3-1]+cc[t3-1];
+    cr2=cc[t5]+(taur*tr2);
+    ch[t1]=cc[t5]+tr2;
+    ci3=taui*(cc[t3]+cc[t3]);
+    ch[t1+t0]=cr2-ci3;
+    ch[t1+t2]=cr2+ci3;
+    t1+=ido;
+    t3+=t4;
+    t5+=t4;
+  }
+
+  if(ido==1)return;
+
+  t1=0;
+  t3=ido<<1;
+  for(k=0;k<l1;k++){
+    t7=t1+(t1<<1);
+    t6=(t5=t7+t3);
+    t8=t1;
+    t10=(t9=t1+t0)+t0;
+
+    for(i=2;i<ido;i+=2){
+      t5+=2;
+      t6-=2;
+      t7+=2;
+      t8+=2;
+      t9+=2;
+      t10+=2;
+      tr2=cc[t5-1]+cc[t6-1];
+      cr2=cc[t7-1]+(taur*tr2);
+      ch[t8-1]=cc[t7-1]+tr2;
+      ti2=cc[t5]-cc[t6];
+      ci2=cc[t7]+(taur*ti2);
+      ch[t8]=cc[t7]+ti2;
+      cr3=taui*(cc[t5-1]-cc[t6-1]);
+      ci3=taui*(cc[t5]+cc[t6]);
+      dr2=cr2-ci3;
+      dr3=cr2+ci3;
+      di2=ci2+cr3;
+      di3=ci2-cr3;
+      ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
+      ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
+      ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
+      ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
+    }
+    t1+=ido;
+  }
+}
+
+static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
+                          float *wa2,float *wa3){
+  static float sqrt2=1.414213562373095f;
+  int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
+  float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
+  t0=l1*ido;
+
+  t1=0;
+  t2=ido<<2;
+  t3=0;
+  t6=ido<<1;
+  for(k=0;k<l1;k++){
+    t4=t3+t6;
+    t5=t1;
+    tr3=cc[t4-1]+cc[t4-1];
+    tr4=cc[t4]+cc[t4];
+    tr1=cc[t3]-cc[(t4+=t6)-1];
+    tr2=cc[t3]+cc[t4-1];
+    ch[t5]=tr2+tr3;
+    ch[t5+=t0]=tr1-tr4;
+    ch[t5+=t0]=tr2-tr3;
+    ch[t5+=t0]=tr1+tr4;
+    t1+=ido;
+    t3+=t2;
+  }
+
+  if(ido<2)return;
+  if(ido==2)goto L105;
+
+  t1=0;
+  for(k=0;k<l1;k++){
+    t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
+    t7=t1;
+    for(i=2;i<ido;i+=2){
+      t2+=2;
+      t3+=2;
+      t4-=2;
+      t5-=2;
+      t7+=2;
+      ti1=cc[t2]+cc[t5];
+      ti2=cc[t2]-cc[t5];
+      ti3=cc[t3]-cc[t4];
+      tr4=cc[t3]+cc[t4];
+      tr1=cc[t2-1]-cc[t5-1];
+      tr2=cc[t2-1]+cc[t5-1];
+      ti4=cc[t3-1]-cc[t4-1];
+      tr3=cc[t3-1]+cc[t4-1];
+      ch[t7-1]=tr2+tr3;
+      cr3=tr2-tr3;
+      ch[t7]=ti2+ti3;
+      ci3=ti2-ti3;
+      cr2=tr1-tr4;
+      cr4=tr1+tr4;
+      ci2=ti1+ti4;
+      ci4=ti1-ti4;
+
+      ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
+      ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
+      ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
+      ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
+      ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
+      ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
+    }
+    t1+=ido;
+  }
+
+  if(ido%2 == 1)return;
+
+ L105:
+
+  t1=ido;
+  t2=ido<<2;
+  t3=ido-1;
+  t4=ido+(ido<<1);
+  for(k=0;k<l1;k++){
+    t5=t3;
+    ti1=cc[t1]+cc[t4];
+    ti2=cc[t4]-cc[t1];
+    tr1=cc[t1-1]-cc[t4-1];
+    tr2=cc[t1-1]+cc[t4-1];
+    ch[t5]=tr2+tr2;
+    ch[t5+=t0]=sqrt2*(tr1-ti1);
+    ch[t5+=t0]=ti2+ti2;
+    ch[t5+=t0]=-sqrt2*(tr1+ti1);
+
+    t3+=ido;
+    t1+=t2;
+    t4+=t2;
+  }
+}
+
+static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
+            float *c2,float *ch,float *ch2,float *wa){
+  static float tpi=6.283185307179586f;
+  int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
+      t11,t12;
+  float dc2,ai1,ai2,ar1,ar2,ds2;
+  int nbd;
+  float dcp,arg,dsp,ar1h,ar2h;
+  int ipp2;
+
+  t10=ip*ido;
+  t0=l1*ido;
+  arg=tpi/(float)ip;
+  dcp=cos(arg);
+  dsp=sin(arg);
+  nbd=(ido-1)>>1;
+  ipp2=ip;
+  ipph=(ip+1)>>1;
+  if(ido<l1)goto L103;
+
+  t1=0;
+  t2=0;
+  for(k=0;k<l1;k++){
+    t3=t1;
+    t4=t2;
+    for(i=0;i<ido;i++){
+      ch[t3]=cc[t4];
+      t3++;
+      t4++;
+    }
+    t1+=ido;
+    t2+=t10;
+  }
+  goto L106;
+
+ L103:
+  t1=0;
+  for(i=0;i<ido;i++){
+    t2=t1;
+    t3=t1;
+    for(k=0;k<l1;k++){
+      ch[t2]=cc[t3];
+      t2+=ido;
+      t3+=t10;
+    }
+    t1++;
+  }
+
+ L106:
+  t1=0;
+  t2=ipp2*t0;
+  t7=(t5=ido<<1);
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    t6=t5;
+    for(k=0;k<l1;k++){
+      ch[t3]=cc[t6-1]+cc[t6-1];
+      ch[t4]=cc[t6]+cc[t6];
+      t3+=ido;
+      t4+=ido;
+      t6+=t10;
+    }
+    t5+=t7;
+  }
+
+  if (ido == 1)goto L116;
+  if(nbd<l1)goto L112;
+
+  t1=0;
+  t2=ipp2*t0;
+  t7=0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+
+    t7+=(ido<<1);
+    t8=t7;
+    for(k=0;k<l1;k++){
+      t5=t3;
+      t6=t4;
+      t9=t8;
+      t11=t8;
+      for(i=2;i<ido;i+=2){
+        t5+=2;
+        t6+=2;
+        t9+=2;
+        t11-=2;
+        ch[t5-1]=cc[t9-1]+cc[t11-1];
+        ch[t6-1]=cc[t9-1]-cc[t11-1];
+        ch[t5]=cc[t9]-cc[t11];
+        ch[t6]=cc[t9]+cc[t11];
+      }
+      t3+=ido;
+      t4+=ido;
+      t8+=t10;
+    }
+  }
+  goto L116;
+
+ L112:
+  t1=0;
+  t2=ipp2*t0;
+  t7=0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    t7+=(ido<<1);
+    t8=t7;
+    t9=t7;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t8+=2;
+      t9-=2;
+      t5=t3;
+      t6=t4;
+      t11=t8;
+      t12=t9;
+      for(k=0;k<l1;k++){
+        ch[t5-1]=cc[t11-1]+cc[t12-1];
+        ch[t6-1]=cc[t11-1]-cc[t12-1];
+        ch[t5]=cc[t11]-cc[t12];
+        ch[t6]=cc[t11]+cc[t12];
+        t5+=ido;
+        t6+=ido;
+        t11+=t10;
+        t12+=t10;
+      }
+    }
+  }
+
+L116:
+  ar1=1.f;
+  ai1=0.f;
+  t1=0;
+  t9=(t2=ipp2*idl1);
+  t3=(ip-1)*idl1;
+  for(l=1;l<ipph;l++){
+    t1+=idl1;
+    t2-=idl1;
+
+    ar1h=dcp*ar1-dsp*ai1;
+    ai1=dcp*ai1+dsp*ar1;
+    ar1=ar1h;
+    t4=t1;
+    t5=t2;
+    t6=0;
+    t7=idl1;
+    t8=t3;
+    for(ik=0;ik<idl1;ik++){
+      c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
+      c2[t5++]=ai1*ch2[t8++];
+    }
+    dc2=ar1;
+    ds2=ai1;
+    ar2=ar1;
+    ai2=ai1;
+
+    t6=idl1;
+    t7=t9-idl1;
+    for(j=2;j<ipph;j++){
+      t6+=idl1;
+      t7-=idl1;
+      ar2h=dc2*ar2-ds2*ai2;
+      ai2=dc2*ai2+ds2*ar2;
+      ar2=ar2h;
+      t4=t1;
+      t5=t2;
+      t11=t6;
+      t12=t7;
+      for(ik=0;ik<idl1;ik++){
+        c2[t4++]+=ar2*ch2[t11++];
+        c2[t5++]+=ai2*ch2[t12++];
+      }
+    }
+  }
+
+  t1=0;
+  for(j=1;j<ipph;j++){
+    t1+=idl1;
+    t2=t1;
+    for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
+  }
+
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(k=0;k<l1;k++){
+      ch[t3]=c1[t3]-c1[t4];
+      ch[t4]=c1[t3]+c1[t4];
+      t3+=ido;
+      t4+=ido;
+    }
+  }
+
+  if(ido==1)goto L132;
+  if(nbd<l1)goto L128;
+
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(k=0;k<l1;k++){
+      t5=t3;
+      t6=t4;
+      for(i=2;i<ido;i+=2){
+        t5+=2;
+        t6+=2;
+        ch[t5-1]=c1[t5-1]-c1[t6];
+        ch[t6-1]=c1[t5-1]+c1[t6];
+        ch[t5]=c1[t5]+c1[t6-1];
+        ch[t6]=c1[t5]-c1[t6-1];
+      }
+      t3+=ido;
+      t4+=ido;
+    }
+  }
+  goto L132;
+
+ L128:
+  t1=0;
+  t2=ipp2*t0;
+  for(j=1;j<ipph;j++){
+    t1+=t0;
+    t2-=t0;
+    t3=t1;
+    t4=t2;
+    for(i=2;i<ido;i+=2){
+      t3+=2;
+      t4+=2;
+      t5=t3;
+      t6=t4;
+      for(k=0;k<l1;k++){
+        ch[t5-1]=c1[t5-1]-c1[t6];
+        ch[t6-1]=c1[t5-1]+c1[t6];
+        ch[t5]=c1[t5]+c1[t6-1];
+        ch[t6]=c1[t5]-c1[t6-1];
+        t5+=ido;
+        t6+=ido;
+      }
+    }
+  }
+
+L132:
+  if(ido==1)return;
+
+  for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
+
+  t1=0;
+  for(j=1;j<ip;j++){
+    t2=(t1+=t0);
+    for(k=0;k<l1;k++){
+      c1[t2]=ch[t2];
+      t2+=ido;
+    }
+  }
+
+  if(nbd>l1)goto L139;
+
+  is= -ido-1;
+  t1=0;
+  for(j=1;j<ip;j++){
+    is+=ido;
+    t1+=t0;
+    idij=is;
+    t2=t1;
+    for(i=2;i<ido;i+=2){
+      t2+=2;
+      idij+=2;
+      t3=t2;
+      for(k=0;k<l1;k++){
+        c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
+        c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
+        t3+=ido;
+      }
+    }
+  }
+  return;
+
+ L139:
+  is= -ido-1;
+  t1=0;
+  for(j=1;j<ip;j++){
+    is+=ido;
+    t1+=t0;
+    t2=t1;
+    for(k=0;k<l1;k++){
+      idij=is;
+      t3=t2;
+      for(i=2;i<ido;i+=2){
+        idij+=2;
+        t3+=2;
+        c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
+        c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
+      }
+      t2+=ido;
+    }
+  }
+}
+
+static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
+  int i,k1,l1,l2;
+  int na;
+  int nf,ip,iw,ix2,ix3,ido,idl1;
+
+  nf=ifac[1];
+  na=0;
+  l1=1;
+  iw=1;
+
+  for(k1=0;k1<nf;k1++){
+    ip=ifac[k1 + 2];
+    l2=ip*l1;
+    ido=n/l2;
+    idl1=ido*l1;
+    if(ip!=4)goto L103;
+    ix2=iw+ido;
+    ix3=ix2+ido;
+
+    if(na!=0)
+      dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    else
+      dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
+    na=1-na;
+    goto L115;
+
+  L103:
+    if(ip!=2)goto L106;
+
+    if(na!=0)
+      dradb2(ido,l1,ch,c,wa+iw-1);
+    else
+      dradb2(ido,l1,c,ch,wa+iw-1);
+    na=1-na;
+    goto L115;
+
+  L106:
+    if(ip!=3)goto L109;
+
+    ix2=iw+ido;
+    if(na!=0)
+      dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
+    else
+      dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
+    na=1-na;
+    goto L115;
+
+  L109:
+/*    The radix five case can be translated later..... */
+/*    if(ip!=5)goto L112;
+
+    ix2=iw+ido;
+    ix3=ix2+ido;
+    ix4=ix3+ido;
+    if(na!=0)
+      dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
+    else
+      dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
+    na=1-na;
+    goto L115;
+
+  L112:*/
+    if(na!=0)
+      dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
+    else
+      dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
+    if(ido==1)na=1-na;
+
+  L115:
+    l1=l2;
+    iw+=(ip-1)*ido;
+  }
+
+  if(na==0)return;
+
+  for(i=0;i<n;i++)c[i]=ch[i];
+}
+
+void drft_forward(drft_lookup *l,float *data){
+  if(l->n==1)return;
+  drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
+}
+
+void drft_backward(drft_lookup *l,float *data){
+  if (l->n==1)return;
+  drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
+}
+
+void drft_init(drft_lookup *l,int n){
+  l->n=n;
+  l->trigcache=_ogg_calloc(3*n,sizeof(*l->trigcache));
+  l->splitcache=_ogg_calloc(32,sizeof(*l->splitcache));
+  fdrffti(n, l->trigcache, l->splitcache);
+}
+
+void drft_clear(drft_lookup *l){
+  if(l){
+    if(l->trigcache)_ogg_free(l->trigcache);
+    if(l->splitcache)_ogg_free(l->splitcache);
+    memset(l,0,sizeof(*l));
+  }
+}
diff --git a/vorbis/lib/smallft.h b/vorbis/lib/smallft.h
new file mode 100644 (file)
index 0000000..9e867c6
--- /dev/null
@@ -0,0 +1,33 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: fft transform
+
+ ********************************************************************/
+
+#ifndef _V_SMFT_H_
+#define _V_SMFT_H_
+
+#include "vorbis/codec.h"
+
+typedef struct {
+  int n;
+  float *trigcache;
+  int *splitcache;
+} drft_lookup;
+
+extern void drft_forward(drft_lookup *l,float *data);
+extern void drft_backward(drft_lookup *l,float *data);
+extern void drft_init(drft_lookup *l,int n);
+extern void drft_clear(drft_lookup *l);
+
+#endif
diff --git a/vorbis/lib/synthesis.c b/vorbis/lib/synthesis.c
new file mode 100644 (file)
index 0000000..5f6092c
--- /dev/null
@@ -0,0 +1,179 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: single-block PCM synthesis
+
+ ********************************************************************/
+
+#include <stdio.h>
+#include <ogg/ogg.h>
+#include "vorbis/codec.h"
+#include "codec_internal.h"
+#include "registry.h"
+#include "misc.h"
+#include "os.h"
+
+int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
+  vorbis_dsp_state     *vd= vb ? vb->vd : 0;
+  private_state        *b= vd ? vd->backend_state : 0;
+  vorbis_info          *vi= vd ? vd->vi : 0;
+  codec_setup_info     *ci= vi ? vi->codec_setup : 0;
+  oggpack_buffer       *opb=vb ? &vb->opb : 0;
+  int                   type,mode,i;
+
+  if (!vd || !b || !vi || !ci || !opb) {
+    return OV_EBADPACKET;
+  }
+
+  /* first things first.  Make sure decode is ready */
+  _vorbis_block_ripcord(vb);
+  oggpack_readinit(opb,op->packet,op->bytes);
+
+  /* Check the packet type */
+  if(oggpack_read(opb,1)!=0){
+    /* Oops.  This is not an audio data packet */
+    return(OV_ENOTAUDIO);
+  }
+
+  /* read our mode and pre/post windowsize */
+  mode=oggpack_read(opb,b->modebits);
+  if(mode==-1){
+    return(OV_EBADPACKET);
+  }
+
+  vb->mode=mode;
+  if(!ci->mode_param[mode]){
+    return(OV_EBADPACKET);
+  }
+
+  vb->W=ci->mode_param[mode]->blockflag;
+  if(vb->W){
+
+    /* this doesn;t get mapped through mode selection as it's used
+       only for window selection */
+    vb->lW=oggpack_read(opb,1);
+    vb->nW=oggpack_read(opb,1);
+    if(vb->nW==-1){
+      return(OV_EBADPACKET);
+    }
+  }else{
+    vb->lW=0;
+    vb->nW=0;
+  }
+
+  /* more setup */
+  vb->granulepos=op->granulepos;
+  vb->sequence=op->packetno;
+  vb->eofflag=op->e_o_s;
+
+  /* alloc pcm passback storage */
+  vb->pcmend=ci->blocksizes[vb->W];
+  vb->pcm=_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
+  for(i=0;i<vi->channels;i++)
+    vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
+
+  /* unpack_header enforces range checking */
+  type=ci->map_type[ci->mode_param[mode]->mapping];
+
+  return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
+                                                   mapping]));
+}
+
+/* used to track pcm position without actually performing decode.
+   Useful for sequential 'fast forward' */
+int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
+  vorbis_dsp_state     *vd=vb->vd;
+  private_state        *b=vd->backend_state;
+  vorbis_info          *vi=vd->vi;
+  codec_setup_info     *ci=vi->codec_setup;
+  oggpack_buffer       *opb=&vb->opb;
+  int                   mode;
+
+  /* first things first.  Make sure decode is ready */
+  _vorbis_block_ripcord(vb);
+  oggpack_readinit(opb,op->packet,op->bytes);
+
+  /* Check the packet type */
+  if(oggpack_read(opb,1)!=0){
+    /* Oops.  This is not an audio data packet */
+    return(OV_ENOTAUDIO);
+  }
+
+  /* read our mode and pre/post windowsize */
+  mode=oggpack_read(opb,b->modebits);
+  if(mode==-1)return(OV_EBADPACKET);
+
+  vb->mode=mode;
+  if(!ci->mode_param[mode]){
+    return(OV_EBADPACKET);
+  }
+
+  vb->W=ci->mode_param[mode]->blockflag;
+  if(vb->W){
+    vb->lW=oggpack_read(opb,1);
+    vb->nW=oggpack_read(opb,1);
+    if(vb->nW==-1)   return(OV_EBADPACKET);
+  }else{
+    vb->lW=0;
+    vb->nW=0;
+  }
+
+  /* more setup */
+  vb->granulepos=op->granulepos;
+  vb->sequence=op->packetno;
+  vb->eofflag=op->e_o_s;
+
+  /* no pcm */
+  vb->pcmend=0;
+  vb->pcm=NULL;
+
+  return(0);
+}
+
+long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
+  codec_setup_info     *ci=vi->codec_setup;
+  oggpack_buffer       opb;
+  int                  mode;
+
+  if(ci==NULL || ci->modes<=0){
+    /* codec setup not properly intialized */
+    return(OV_EFAULT);
+  }
+
+  oggpack_readinit(&opb,op->packet,op->bytes);
+
+  /* Check the packet type */
+  if(oggpack_read(&opb,1)!=0){
+    /* Oops.  This is not an audio data packet */
+    return(OV_ENOTAUDIO);
+  }
+
+  /* read our mode and pre/post windowsize */
+  mode=oggpack_read(&opb,ov_ilog(ci->modes-1));
+  if(mode==-1 || !ci->mode_param[mode])return(OV_EBADPACKET);
+  return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
+}
+
+int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
+  /* set / clear half-sample-rate mode */
+  codec_setup_info     *ci=vi->codec_setup;
+
+  /* right now, our MDCT can't handle < 64 sample windows. */
+  if(ci->blocksizes[0]<=64 && flag)return -1;
+  ci->halfrate_flag=(flag?1:0);
+  return 0;
+}
+
+int vorbis_synthesis_halfrate_p(vorbis_info *vi){
+  codec_setup_info     *ci=vi->codec_setup;
+  return ci->halfrate_flag;
+}
diff --git a/vorbis/lib/vorbisenc.c b/vorbis/lib/vorbisenc.c
new file mode 100644 (file)
index 0000000..4a4607c
--- /dev/null
@@ -0,0 +1,1223 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: simple programmatic interface for encoder mode setup
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#include "vorbis/codec.h"
+#include "vorbis/vorbisenc.h"
+
+#include "codec_internal.h"
+
+#include "os.h"
+#include "misc.h"
+
+/* careful with this; it's using static array sizing to make managing
+   all the modes a little less annoying.  If we use a residue backend
+   with > 12 partition types, or a different division of iteration,
+   this needs to be updated. */
+typedef struct {
+  const static_codebook *books[12][4];
+} static_bookblock;
+
+typedef struct {
+  int res_type;
+  int limit_type; /* 0 lowpass limited, 1 point stereo limited */
+  int grouping;
+  const vorbis_info_residue0 *res;
+  const static_codebook  *book_aux;
+  const static_codebook  *book_aux_managed;
+  const static_bookblock *books_base;
+  const static_bookblock *books_base_managed;
+} vorbis_residue_template;
+
+typedef struct {
+  const vorbis_info_mapping0    *map;
+  const vorbis_residue_template *res;
+} vorbis_mapping_template;
+
+typedef struct vp_adjblock{
+  int block[P_BANDS];
+} vp_adjblock;
+
+typedef struct {
+  int data[NOISE_COMPAND_LEVELS];
+} compandblock;
+
+/* high level configuration information for setting things up
+   step-by-step with the detailed vorbis_encode_ctl interface.
+   There's a fair amount of redundancy such that interactive setup
+   does not directly deal with any vorbis_info or codec_setup_info
+   initialization; it's all stored (until full init) in this highlevel
+   setup, then flushed out to the real codec setup structs later. */
+
+typedef struct {
+  int att[P_NOISECURVES];
+  float boost;
+  float decay;
+} att3;
+typedef struct { int data[P_NOISECURVES]; } adj3;
+
+typedef struct {
+  int   pre[PACKETBLOBS];
+  int   post[PACKETBLOBS];
+  float kHz[PACKETBLOBS];
+  float lowpasskHz[PACKETBLOBS];
+} adj_stereo;
+
+typedef struct {
+  int lo;
+  int hi;
+  int fixed;
+} noiseguard;
+typedef struct {
+  int data[P_NOISECURVES][17];
+} noise3;
+
+typedef struct {
+  int      mappings;
+  const double  *rate_mapping;
+  const double  *quality_mapping;
+  int      coupling_restriction;
+  long     samplerate_min_restriction;
+  long     samplerate_max_restriction;
+
+
+  const int     *blocksize_short;
+  const int     *blocksize_long;
+
+  const att3    *psy_tone_masteratt;
+  const int     *psy_tone_0dB;
+  const int     *psy_tone_dBsuppress;
+
+  const vp_adjblock *psy_tone_adj_impulse;
+  const vp_adjblock *psy_tone_adj_long;
+  const vp_adjblock *psy_tone_adj_other;
+
+  const noiseguard  *psy_noiseguards;
+  const noise3      *psy_noise_bias_impulse;
+  const noise3      *psy_noise_bias_padding;
+  const noise3      *psy_noise_bias_trans;
+  const noise3      *psy_noise_bias_long;
+  const int         *psy_noise_dBsuppress;
+
+  const compandblock  *psy_noise_compand;
+  const double        *psy_noise_compand_short_mapping;
+  const double        *psy_noise_compand_long_mapping;
+
+  const int      *psy_noise_normal_start[2];
+  const int      *psy_noise_normal_partition[2];
+  const double   *psy_noise_normal_thresh;
+
+  const int      *psy_ath_float;
+  const int      *psy_ath_abs;
+
+  const double   *psy_lowpass;
+
+  const vorbis_info_psy_global *global_params;
+  const double     *global_mapping;
+  const adj_stereo *stereo_modes;
+
+  const static_codebook *const *const *const floor_books;
+  const vorbis_info_floor1 *floor_params;
+  const int floor_mappings;
+  const int **floor_mapping_list;
+
+  const vorbis_mapping_template *maps;
+} ve_setup_data_template;
+
+/* a few static coder conventions */
+static const vorbis_info_mode _mode_template[2]={
+  {0,0,0,0},
+  {1,0,0,1}
+};
+
+static const vorbis_info_mapping0 _map_nominal[2]={
+  {1, {0,0}, {0}, {0}, 1,{0},{1}},
+  {1, {0,0}, {1}, {1}, 1,{0},{1}}
+};
+
+#include "modes/setup_44.h"
+#include "modes/setup_44u.h"
+#include "modes/setup_44p51.h"
+#include "modes/setup_32.h"
+#include "modes/setup_8.h"
+#include "modes/setup_11.h"
+#include "modes/setup_16.h"
+#include "modes/setup_22.h"
+#include "modes/setup_X.h"
+
+static const ve_setup_data_template *const setup_list[]={
+  &ve_setup_44_stereo,
+  &ve_setup_44_51,
+  &ve_setup_44_uncoupled,
+
+  &ve_setup_32_stereo,
+  &ve_setup_32_uncoupled,
+
+  &ve_setup_22_stereo,
+  &ve_setup_22_uncoupled,
+  &ve_setup_16_stereo,
+  &ve_setup_16_uncoupled,
+
+  &ve_setup_11_stereo,
+  &ve_setup_11_uncoupled,
+  &ve_setup_8_stereo,
+  &ve_setup_8_uncoupled,
+
+  &ve_setup_X_stereo,
+  &ve_setup_X_uncoupled,
+  &ve_setup_XX_stereo,
+  &ve_setup_XX_uncoupled,
+  0
+};
+
+static void vorbis_encode_floor_setup(vorbis_info *vi,int s,
+                                     const static_codebook *const *const *const books,
+                                     const vorbis_info_floor1 *in,
+                                     const int *x){
+  int i,k,is=s;
+  vorbis_info_floor1 *f=_ogg_calloc(1,sizeof(*f));
+  codec_setup_info *ci=vi->codec_setup;
+
+  memcpy(f,in+x[is],sizeof(*f));
+
+  /* books */
+  {
+    int partitions=f->partitions;
+    int maxclass=-1;
+    int maxbook=-1;
+    for(i=0;i<partitions;i++)
+      if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
+    for(i=0;i<=maxclass;i++){
+      if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
+      f->class_book[i]+=ci->books;
+      for(k=0;k<(1<<f->class_subs[i]);k++){
+        if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
+        if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
+      }
+    }
+
+    for(i=0;i<=maxbook;i++)
+      ci->book_param[ci->books++]=(static_codebook *)books[x[is]][i];
+  }
+
+  /* for now, we're only using floor 1 */
+  ci->floor_type[ci->floors]=1;
+  ci->floor_param[ci->floors]=f;
+  ci->floors++;
+
+  return;
+}
+
+static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
+                                            const vorbis_info_psy_global *in,
+                                            const double *x){
+  int i,is=s;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *g=&ci->psy_g_param;
+
+  memcpy(g,in+(int)x[is],sizeof(*g));
+
+  ds=x[is]*(1.-ds)+x[is+1]*ds;
+  is=(int)ds;
+  ds-=is;
+  if(ds==0 && is>0){
+    is--;
+    ds=1.;
+  }
+
+  /* interpolate the trigger threshholds */
+  for(i=0;i<4;i++){
+    g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
+    g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
+  }
+  g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
+  return;
+}
+
+static void vorbis_encode_global_stereo(vorbis_info *vi,
+                                        const highlevel_encode_setup *const hi,
+                                        const adj_stereo *p){
+  float s=hi->stereo_point_setting;
+  int i,is=s;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy_global *g=&ci->psy_g_param;
+
+  if(p){
+    memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
+    memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
+
+    if(hi->managed){
+      /* interpolate the kHz threshholds */
+      for(i=0;i<PACKETBLOBS;i++){
+        float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
+        g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
+        g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
+        g->coupling_pkHz[i]=kHz;
+
+        kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
+        g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
+        g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
+
+      }
+    }else{
+      float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
+      for(i=0;i<PACKETBLOBS;i++){
+        g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
+        g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
+        g->coupling_pkHz[i]=kHz;
+      }
+
+      kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
+      for(i=0;i<PACKETBLOBS;i++){
+        g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
+        g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
+      }
+    }
+  }else{
+    for(i=0;i<PACKETBLOBS;i++){
+      g->sliding_lowpass[0][i]=ci->blocksizes[0];
+      g->sliding_lowpass[1][i]=ci->blocksizes[1];
+    }
+  }
+  return;
+}
+
+static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
+                                       const int *nn_start,
+                                       const int *nn_partition,
+                                       const double *nn_thresh,
+                                       int block){
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+  highlevel_encode_setup *hi=&ci->hi;
+  int is=s;
+
+  if(block>=ci->psys)
+    ci->psys=block+1;
+  if(!p){
+    p=_ogg_calloc(1,sizeof(*p));
+    ci->psy_param[block]=p;
+  }
+
+  memcpy(p,&_psy_info_template,sizeof(*p));
+  p->blockflag=block>>1;
+
+  if(hi->noise_normalize_p){
+    p->normal_p=1;
+    p->normal_start=nn_start[is];
+    p->normal_partition=nn_partition[is];
+    p->normal_thresh=nn_thresh[is];
+  }
+
+  return;
+}
+
+static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
+                                         const att3 *att,
+                                         const int  *max,
+                                         const vp_adjblock *in){
+  int i,is=s;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+
+  /* 0 and 2 are only used by bitmanagement, but there's no harm to always
+     filling the values in here */
+  p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
+  p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
+  p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
+  p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
+  p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
+
+  p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
+
+  for(i=0;i<P_BANDS;i++)
+    p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
+  return;
+}
+
+
+static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
+                                        const compandblock *in,
+                                        const double *x){
+  int i,is=s;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+
+  ds=x[is]*(1.-ds)+x[is+1]*ds;
+  is=(int)ds;
+  ds-=is;
+  if(ds==0 && is>0){
+    is--;
+    ds=1.;
+  }
+
+  /* interpolate the compander settings */
+  for(i=0;i<NOISE_COMPAND_LEVELS;i++)
+    p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
+  return;
+}
+
+static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
+                                    const int *suppress){
+  int is=s;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+
+  p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
+
+  return;
+}
+
+static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
+                                         const int *suppress,
+                                         const noise3 *in,
+                                         const noiseguard *guard,
+                                         double userbias){
+  int i,is=s,j;
+  double ds=s-is;
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+
+  p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
+  p->noisewindowlomin=guard[block].lo;
+  p->noisewindowhimin=guard[block].hi;
+  p->noisewindowfixed=guard[block].fixed;
+
+  for(j=0;j<P_NOISECURVES;j++)
+    for(i=0;i<P_BANDS;i++)
+      p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
+
+  /* impulse blocks may take a user specified bias to boost the
+     nominal/high noise encoding depth */
+  for(j=0;j<P_NOISECURVES;j++){
+    float min=p->noiseoff[j][0]+6; /* the lowest it can go */
+    for(i=0;i<P_BANDS;i++){
+      p->noiseoff[j][i]+=userbias;
+      if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
+    }
+  }
+
+  return;
+}
+
+static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
+  codec_setup_info *ci=vi->codec_setup;
+  vorbis_info_psy *p=ci->psy_param[block];
+
+  p->ath_adjatt=ci->hi.ath_floating_dB;
+  p->ath_maxatt=ci->hi.ath_absolute_dB;
+  return;
+}
+
+
+static int book_dup_or_new(codec_setup_info *ci,const static_codebook *book){
+  int i;
+  for(i=0;i<ci->books;i++)
+    if(ci->book_param[i]==book)return(i);
+
+  return(ci->books++);
+}
+
+static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
+                                         const int *shortb,const int *longb){
+
+  codec_setup_info *ci=vi->codec_setup;
+  int is=s;
+
+  int blockshort=shortb[is];
+  int blocklong=longb[is];
+  ci->blocksizes[0]=blockshort;
+  ci->blocksizes[1]=blocklong;
+
+}
+
+static void vorbis_encode_residue_setup(vorbis_info *vi,
+                                        int number, int block,
+                                        const vorbis_residue_template *res){
+
+  codec_setup_info *ci=vi->codec_setup;
+  int i;
+
+  vorbis_info_residue0 *r=ci->residue_param[number]=
+    _ogg_malloc(sizeof(*r));
+
+  memcpy(r,res->res,sizeof(*r));
+  if(ci->residues<=number)ci->residues=number+1;
+
+  r->grouping=res->grouping;
+  ci->residue_type[number]=res->res_type;
+
+  /* fill in all the books */
+  {
+    int booklist=0,k;
+
+    if(ci->hi.managed){
+      for(i=0;i<r->partitions;i++)
+        for(k=0;k<4;k++)
+          if(res->books_base_managed->books[i][k])
+            r->secondstages[i]|=(1<<k);
+
+      r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
+      ci->book_param[r->groupbook]=(static_codebook *)res->book_aux_managed;
+
+      for(i=0;i<r->partitions;i++){
+        for(k=0;k<4;k++){
+          if(res->books_base_managed->books[i][k]){
+            int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
+            r->booklist[booklist++]=bookid;
+            ci->book_param[bookid]=(static_codebook *)res->books_base_managed->books[i][k];
+          }
+        }
+      }
+
+    }else{
+
+      for(i=0;i<r->partitions;i++)
+        for(k=0;k<4;k++)
+          if(res->books_base->books[i][k])
+            r->secondstages[i]|=(1<<k);
+
+      r->groupbook=book_dup_or_new(ci,res->book_aux);
+      ci->book_param[r->groupbook]=(static_codebook *)res->book_aux;
+
+      for(i=0;i<r->partitions;i++){
+        for(k=0;k<4;k++){
+          if(res->books_base->books[i][k]){
+            int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
+            r->booklist[booklist++]=bookid;
+            ci->book_param[bookid]=(static_codebook *)res->books_base->books[i][k];
+          }
+        }
+      }
+    }
+  }
+
+  /* lowpass setup/pointlimit */
+  {
+    double freq=ci->hi.lowpass_kHz*1000.;
+    vorbis_info_floor1 *f=ci->floor_param[block]; /* by convention */
+    double nyq=vi->rate/2.;
+    long blocksize=ci->blocksizes[block]>>1;
+
+    /* lowpass needs to be set in the floor and the residue. */
+    if(freq>nyq)freq=nyq;
+    /* in the floor, the granularity can be very fine; it doesn't alter
+       the encoding structure, only the samples used to fit the floor
+       approximation */
+    f->n=freq/nyq*blocksize;
+
+    /* this res may by limited by the maximum pointlimit of the mode,
+       not the lowpass. the floor is always lowpass limited. */
+    switch(res->limit_type){
+    case 1: /* point stereo limited */
+      if(ci->hi.managed)
+        freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
+      else
+        freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
+      if(freq>nyq)freq=nyq;
+      break;
+    case 2: /* LFE channel; lowpass at ~ 250Hz */
+      freq=250;
+      break;
+    default:
+      /* already set */
+      break;
+    }
+
+    /* in the residue, we're constrained, physically, by partition
+       boundaries.  We still lowpass 'wherever', but we have to round up
+       here to next boundary, or the vorbis spec will round it *down* to
+       previous boundary in encode/decode */
+    if(ci->residue_type[number]==2){
+      /* residue 2 bundles together multiple channels; used by stereo
+         and surround.  Count the channels in use */
+      /* Multiple maps/submaps can point to the same residue.  In the case
+         of residue 2, they all better have the same number of
+         channels/samples. */
+      int j,k,ch=0;
+      for(i=0;i<ci->maps&&ch==0;i++){
+        vorbis_info_mapping0 *mi=(vorbis_info_mapping0 *)ci->map_param[i];
+        for(j=0;j<mi->submaps && ch==0;j++)
+          if(mi->residuesubmap[j]==number) /* we found a submap referencing theis residue backend */
+            for(k=0;k<vi->channels;k++)
+              if(mi->chmuxlist[k]==j) /* this channel belongs to the submap */
+                ch++;
+      }
+
+      r->end=(int)((freq/nyq*blocksize*ch)/r->grouping+.9)* /* round up only if we're well past */
+        r->grouping;
+      /* the blocksize and grouping may disagree at the end */
+      if(r->end>blocksize*ch)r->end=blocksize*ch/r->grouping*r->grouping;
+
+    }else{
+
+      r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
+        r->grouping;
+      /* the blocksize and grouping may disagree at the end */
+      if(r->end>blocksize)r->end=blocksize/r->grouping*r->grouping;
+
+    }
+
+    if(r->end==0)r->end=r->grouping; /* LFE channel */
+
+  }
+}
+
+/* we assume two maps in this encoder */
+static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
+                                          const vorbis_mapping_template *maps){
+
+  codec_setup_info *ci=vi->codec_setup;
+  int i,j,is=s,modes=2;
+  const vorbis_info_mapping0 *map=maps[is].map;
+  const vorbis_info_mode *mode=_mode_template;
+  const vorbis_residue_template *res=maps[is].res;
+
+  if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
+
+  for(i=0;i<modes;i++){
+
+    ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
+    ci->mode_param[i]=_ogg_calloc(1,sizeof(*mode));
+
+    memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
+    if(i>=ci->modes)ci->modes=i+1;
+
+    ci->map_type[i]=0;
+    memcpy(ci->map_param[i],map+i,sizeof(*map));
+    if(i>=ci->maps)ci->maps=i+1;
+
+    for(j=0;j<map[i].submaps;j++)
+      vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
+                                  ,res+map[i].residuesubmap[j]);
+  }
+}
+
+static double setting_to_approx_bitrate(vorbis_info *vi){
+  codec_setup_info *ci=vi->codec_setup;
+  highlevel_encode_setup *hi=&ci->hi;
+  ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
+  int is=hi->base_setting;
+  double ds=hi->base_setting-is;
+  int ch=vi->channels;
+  const double *r=setup->rate_mapping;
+
+  if(r==NULL)
+    return(-1);
+
+  return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
+}
+
+static const void *get_setup_template(long ch,long srate,
+                                      double req,int q_or_bitrate,
+                                      double *base_setting){
+  int i=0,j;
+  if(q_or_bitrate)req/=ch;
+
+  while(setup_list[i]){
+    if(setup_list[i]->coupling_restriction==-1 ||
+       setup_list[i]->coupling_restriction==ch){
+      if(srate>=setup_list[i]->samplerate_min_restriction &&
+         srate<=setup_list[i]->samplerate_max_restriction){
+        int mappings=setup_list[i]->mappings;
+        const double *map=(q_or_bitrate?
+                     setup_list[i]->rate_mapping:
+                     setup_list[i]->quality_mapping);
+
+        /* the template matches.  Does the requested quality mode
+           fall within this template's modes? */
+        if(req<map[0]){++i;continue;}
+        if(req>map[setup_list[i]->mappings]){++i;continue;}
+        for(j=0;j<mappings;j++)
+          if(req>=map[j] && req<map[j+1])break;
+        /* an all-points match */
+        if(j==mappings)
+          *base_setting=j-.001;
+        else{
+          float low=map[j];
+          float high=map[j+1];
+          float del=(req-low)/(high-low);
+          *base_setting=j+del;
+        }
+
+        return(setup_list[i]);
+      }
+    }
+    i++;
+  }
+
+  return NULL;
+}
+
+/* encoders will need to use vorbis_info_init beforehand and call
+   vorbis_info clear when all done */
+
+/* two interfaces; this, more detailed one, and later a convenience
+   layer on top */
+
+/* the final setup call */
+int vorbis_encode_setup_init(vorbis_info *vi){
+  int i,i0=0,singleblock=0;
+  codec_setup_info *ci=vi->codec_setup;
+  ve_setup_data_template *setup=NULL;
+  highlevel_encode_setup *hi=&ci->hi;
+
+  if(ci==NULL)return(OV_EINVAL);
+  if(!hi->impulse_block_p)i0=1;
+
+  /* too low/high an ATH floater is nonsensical, but doesn't break anything */
+  if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
+  if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
+
+  /* again, bound this to avoid the app shooting itself int he foot
+     too badly */
+  if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
+  if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
+
+  /* get the appropriate setup template; matches the fetch in previous
+     stages */
+  setup=(ve_setup_data_template *)hi->setup;
+  if(setup==NULL)return(OV_EINVAL);
+
+  hi->set_in_stone=1;
+  /* choose block sizes from configured sizes as well as paying
+     attention to long_block_p and short_block_p.  If the configured
+     short and long blocks are the same length, we set long_block_p
+     and unset short_block_p */
+  vorbis_encode_blocksize_setup(vi,hi->base_setting,
+                                setup->blocksize_short,
+                                setup->blocksize_long);
+  if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
+
+  /* floor setup; choose proper floor params.  Allocated on the floor
+     stack in order; if we alloc only a single long floor, it's 0 */
+  for(i=0;i<setup->floor_mappings;i++)
+    vorbis_encode_floor_setup(vi,hi->base_setting,
+                              setup->floor_books,
+                              setup->floor_params,
+                              setup->floor_mapping_list[i]);
+
+  /* setup of [mostly] short block detection and stereo*/
+  vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
+                                   setup->global_params,
+                                   setup->global_mapping);
+  vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
+
+  /* basic psych setup and noise normalization */
+  vorbis_encode_psyset_setup(vi,hi->base_setting,
+                             setup->psy_noise_normal_start[0],
+                             setup->psy_noise_normal_partition[0],
+                             setup->psy_noise_normal_thresh,
+                             0);
+  vorbis_encode_psyset_setup(vi,hi->base_setting,
+                             setup->psy_noise_normal_start[0],
+                             setup->psy_noise_normal_partition[0],
+                             setup->psy_noise_normal_thresh,
+                             1);
+  if(!singleblock){
+    vorbis_encode_psyset_setup(vi,hi->base_setting,
+                               setup->psy_noise_normal_start[1],
+                               setup->psy_noise_normal_partition[1],
+                                    setup->psy_noise_normal_thresh,
+                               2);
+    vorbis_encode_psyset_setup(vi,hi->base_setting,
+                               setup->psy_noise_normal_start[1],
+                               setup->psy_noise_normal_partition[1],
+                               setup->psy_noise_normal_thresh,
+                               3);
+  }
+
+  /* tone masking setup */
+  vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
+                               setup->psy_tone_masteratt,
+                               setup->psy_tone_0dB,
+                               setup->psy_tone_adj_impulse);
+  vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
+                               setup->psy_tone_masteratt,
+                               setup->psy_tone_0dB,
+                               setup->psy_tone_adj_other);
+  if(!singleblock){
+    vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
+                                 setup->psy_tone_masteratt,
+                                 setup->psy_tone_0dB,
+                                 setup->psy_tone_adj_other);
+    vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
+                                 setup->psy_tone_masteratt,
+                                 setup->psy_tone_0dB,
+                                 setup->psy_tone_adj_long);
+  }
+
+  /* noise companding setup */
+  vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
+                              setup->psy_noise_compand,
+                              setup->psy_noise_compand_short_mapping);
+  vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
+                              setup->psy_noise_compand,
+                              setup->psy_noise_compand_short_mapping);
+  if(!singleblock){
+    vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
+                                setup->psy_noise_compand,
+                                setup->psy_noise_compand_long_mapping);
+    vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
+                                setup->psy_noise_compand,
+                                setup->psy_noise_compand_long_mapping);
+  }
+
+  /* peak guarding setup  */
+  vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
+                           setup->psy_tone_dBsuppress);
+  vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
+                           setup->psy_tone_dBsuppress);
+  if(!singleblock){
+    vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
+                             setup->psy_tone_dBsuppress);
+    vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
+                             setup->psy_tone_dBsuppress);
+  }
+
+  /* noise bias setup */
+  vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
+                                setup->psy_noise_dBsuppress,
+                                setup->psy_noise_bias_impulse,
+                                setup->psy_noiseguards,
+                                (i0==0?hi->impulse_noisetune:0.));
+  vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
+                                setup->psy_noise_dBsuppress,
+                                setup->psy_noise_bias_padding,
+                                setup->psy_noiseguards,0.);
+  if(!singleblock){
+    vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
+                                  setup->psy_noise_dBsuppress,
+                                  setup->psy_noise_bias_trans,
+                                  setup->psy_noiseguards,0.);
+    vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
+                                  setup->psy_noise_dBsuppress,
+                                  setup->psy_noise_bias_long,
+                                  setup->psy_noiseguards,0.);
+  }
+
+  vorbis_encode_ath_setup(vi,0);
+  vorbis_encode_ath_setup(vi,1);
+  if(!singleblock){
+    vorbis_encode_ath_setup(vi,2);
+    vorbis_encode_ath_setup(vi,3);
+  }
+
+  vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
+
+  /* set bitrate readonlies and management */
+  if(hi->bitrate_av>0)
+    vi->bitrate_nominal=hi->bitrate_av;
+  else{
+    vi->bitrate_nominal=setting_to_approx_bitrate(vi);
+  }
+
+  vi->bitrate_lower=hi->bitrate_min;
+  vi->bitrate_upper=hi->bitrate_max;
+  if(hi->bitrate_av)
+    vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
+  else
+    vi->bitrate_window=0.;
+
+  if(hi->managed){
+    ci->bi.avg_rate=hi->bitrate_av;
+    ci->bi.min_rate=hi->bitrate_min;
+    ci->bi.max_rate=hi->bitrate_max;
+
+    ci->bi.reservoir_bits=hi->bitrate_reservoir;
+    ci->bi.reservoir_bias=
+      hi->bitrate_reservoir_bias;
+
+    ci->bi.slew_damp=hi->bitrate_av_damp;
+
+  }
+
+  return(0);
+
+}
+
+static void vorbis_encode_setup_setting(vorbis_info *vi,
+                                       long  channels,
+                                       long  rate){
+  int i,is;
+  codec_setup_info *ci=vi->codec_setup;
+  highlevel_encode_setup *hi=&ci->hi;
+  const ve_setup_data_template *setup=hi->setup;
+  double ds;
+
+  vi->version=0;
+  vi->channels=channels;
+  vi->rate=rate;
+
+  hi->impulse_block_p=1;
+  hi->noise_normalize_p=1;
+
+  is=hi->base_setting;
+  ds=hi->base_setting-is;
+
+  hi->stereo_point_setting=hi->base_setting;
+
+  if(!hi->lowpass_altered)
+    hi->lowpass_kHz=
+      setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
+
+  hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
+    setup->psy_ath_float[is+1]*ds;
+  hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
+    setup->psy_ath_abs[is+1]*ds;
+
+  hi->amplitude_track_dBpersec=-6.;
+  hi->trigger_setting=hi->base_setting;
+
+  for(i=0;i<4;i++){
+    hi->block[i].tone_mask_setting=hi->base_setting;
+    hi->block[i].tone_peaklimit_setting=hi->base_setting;
+    hi->block[i].noise_bias_setting=hi->base_setting;
+    hi->block[i].noise_compand_setting=hi->base_setting;
+  }
+}
+
+int vorbis_encode_setup_vbr(vorbis_info *vi,
+                            long  channels,
+                            long  rate,
+                            float quality){
+  codec_setup_info *ci;
+  highlevel_encode_setup *hi;
+  if(rate<=0) return OV_EINVAL;
+
+  ci=vi->codec_setup;
+  hi=&ci->hi;
+
+  quality+=.0000001;
+  if(quality>=1.)quality=.9999;
+
+  hi->req=quality;
+  hi->setup=get_setup_template(channels,rate,quality,0,&hi->base_setting);
+  if(!hi->setup)return OV_EIMPL;
+
+  vorbis_encode_setup_setting(vi,channels,rate);
+  hi->managed=0;
+  hi->coupling_p=1;
+
+  return 0;
+}
+
+int vorbis_encode_init_vbr(vorbis_info *vi,
+                           long channels,
+                           long rate,
+
+                           float base_quality /* 0. to 1. */
+                           ){
+  int ret=0;
+
+  ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
+
+  if(ret){
+    vorbis_info_clear(vi);
+    return ret;
+  }
+  ret=vorbis_encode_setup_init(vi);
+  if(ret)
+    vorbis_info_clear(vi);
+  return(ret);
+}
+
+int vorbis_encode_setup_managed(vorbis_info *vi,
+                                long channels,
+                                long rate,
+
+                                long max_bitrate,
+                                long nominal_bitrate,
+                                long min_bitrate){
+
+  codec_setup_info *ci;
+  highlevel_encode_setup *hi;
+  double tnominal;
+  if(rate<=0) return OV_EINVAL;
+
+  ci=vi->codec_setup;
+  hi=&ci->hi;
+  tnominal=nominal_bitrate;
+
+  if(nominal_bitrate<=0.){
+    if(max_bitrate>0.){
+      if(min_bitrate>0.)
+        nominal_bitrate=(max_bitrate+min_bitrate)*.5;
+      else
+        nominal_bitrate=max_bitrate*.875;
+    }else{
+      if(min_bitrate>0.){
+        nominal_bitrate=min_bitrate;
+      }else{
+        return(OV_EINVAL);
+      }
+    }
+  }
+
+  hi->req=nominal_bitrate;
+  hi->setup=get_setup_template(channels,rate,nominal_bitrate,1,&hi->base_setting);
+  if(!hi->setup)return OV_EIMPL;
+
+  vorbis_encode_setup_setting(vi,channels,rate);
+
+  /* initialize management with sane defaults */
+  hi->coupling_p=1;
+  hi->managed=1;
+  hi->bitrate_min=min_bitrate;
+  hi->bitrate_max=max_bitrate;
+  hi->bitrate_av=tnominal;
+  hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
+  hi->bitrate_reservoir=nominal_bitrate*2;
+  hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
+
+  return(0);
+
+}
+
+int vorbis_encode_init(vorbis_info *vi,
+                       long channels,
+                       long rate,
+
+                       long max_bitrate,
+                       long nominal_bitrate,
+                       long min_bitrate){
+
+  int ret=vorbis_encode_setup_managed(vi,channels,rate,
+                                      max_bitrate,
+                                      nominal_bitrate,
+                                      min_bitrate);
+  if(ret){
+    vorbis_info_clear(vi);
+    return(ret);
+  }
+
+  ret=vorbis_encode_setup_init(vi);
+  if(ret)
+    vorbis_info_clear(vi);
+  return(ret);
+}
+
+int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
+  if(vi){
+    codec_setup_info *ci=vi->codec_setup;
+    highlevel_encode_setup *hi=&ci->hi;
+    int setp=(number&0xf); /* a read request has a low nibble of 0 */
+
+    if(setp && hi->set_in_stone)return(OV_EINVAL);
+
+    switch(number){
+
+    /* now deprecated *****************/
+    case OV_ECTL_RATEMANAGE_GET:
+      {
+
+        struct ovectl_ratemanage_arg *ai=
+          (struct ovectl_ratemanage_arg *)arg;
+
+        ai->management_active=hi->managed;
+        ai->bitrate_hard_window=ai->bitrate_av_window=
+          (double)hi->bitrate_reservoir/vi->rate;
+        ai->bitrate_av_window_center=1.;
+        ai->bitrate_hard_min=hi->bitrate_min;
+        ai->bitrate_hard_max=hi->bitrate_max;
+        ai->bitrate_av_lo=hi->bitrate_av;
+        ai->bitrate_av_hi=hi->bitrate_av;
+
+      }
+      return(0);
+
+    /* now deprecated *****************/
+    case OV_ECTL_RATEMANAGE_SET:
+      {
+        struct ovectl_ratemanage_arg *ai=
+          (struct ovectl_ratemanage_arg *)arg;
+        if(ai==NULL){
+          hi->managed=0;
+        }else{
+          hi->managed=ai->management_active;
+          vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
+          vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
+        }
+      }
+      return 0;
+
+    /* now deprecated *****************/
+    case OV_ECTL_RATEMANAGE_AVG:
+      {
+        struct ovectl_ratemanage_arg *ai=
+          (struct ovectl_ratemanage_arg *)arg;
+        if(ai==NULL){
+          hi->bitrate_av=0;
+        }else{
+          hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
+        }
+      }
+      return(0);
+    /* now deprecated *****************/
+    case OV_ECTL_RATEMANAGE_HARD:
+      {
+        struct ovectl_ratemanage_arg *ai=
+          (struct ovectl_ratemanage_arg *)arg;
+        if(ai==NULL){
+          hi->bitrate_min=0;
+          hi->bitrate_max=0;
+        }else{
+          hi->bitrate_min=ai->bitrate_hard_min;
+          hi->bitrate_max=ai->bitrate_hard_max;
+          hi->bitrate_reservoir=ai->bitrate_hard_window*
+            (hi->bitrate_max+hi->bitrate_min)*.5;
+        }
+        if(hi->bitrate_reservoir<128.)
+          hi->bitrate_reservoir=128.;
+      }
+      return(0);
+
+      /* replacement ratemanage interface */
+    case OV_ECTL_RATEMANAGE2_GET:
+      {
+        struct ovectl_ratemanage2_arg *ai=
+          (struct ovectl_ratemanage2_arg *)arg;
+        if(ai==NULL)return OV_EINVAL;
+
+        ai->management_active=hi->managed;
+        ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
+        ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
+        ai->bitrate_average_kbps=hi->bitrate_av/1000;
+        ai->bitrate_average_damping=hi->bitrate_av_damp;
+        ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
+        ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
+      }
+      return (0);
+    case OV_ECTL_RATEMANAGE2_SET:
+      {
+        struct ovectl_ratemanage2_arg *ai=
+          (struct ovectl_ratemanage2_arg *)arg;
+        if(ai==NULL){
+          hi->managed=0;
+        }else{
+          /* sanity check; only catch invariant violations */
+          if(ai->bitrate_limit_min_kbps>0 &&
+             ai->bitrate_average_kbps>0 &&
+             ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
+            return OV_EINVAL;
+
+          if(ai->bitrate_limit_max_kbps>0 &&
+             ai->bitrate_average_kbps>0 &&
+             ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
+            return OV_EINVAL;
+
+          if(ai->bitrate_limit_min_kbps>0 &&
+             ai->bitrate_limit_max_kbps>0 &&
+             ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
+            return OV_EINVAL;
+
+          if(ai->bitrate_average_damping <= 0.)
+            return OV_EINVAL;
+
+          if(ai->bitrate_limit_reservoir_bits < 0)
+            return OV_EINVAL;
+
+          if(ai->bitrate_limit_reservoir_bias < 0.)
+            return OV_EINVAL;
+
+          if(ai->bitrate_limit_reservoir_bias > 1.)
+            return OV_EINVAL;
+
+          hi->managed=ai->management_active;
+          hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
+          hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
+          hi->bitrate_av=ai->bitrate_average_kbps * 1000;
+          hi->bitrate_av_damp=ai->bitrate_average_damping;
+          hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
+          hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
+        }
+      }
+      return 0;
+
+    case OV_ECTL_LOWPASS_GET:
+      {
+        double *farg=(double *)arg;
+        *farg=hi->lowpass_kHz;
+      }
+      return(0);
+    case OV_ECTL_LOWPASS_SET:
+      {
+        double *farg=(double *)arg;
+        hi->lowpass_kHz=*farg;
+
+        if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
+        if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
+        hi->lowpass_altered=1;
+      }
+      return(0);
+    case OV_ECTL_IBLOCK_GET:
+      {
+        double *farg=(double *)arg;
+        *farg=hi->impulse_noisetune;
+      }
+      return(0);
+    case OV_ECTL_IBLOCK_SET:
+      {
+        double *farg=(double *)arg;
+        hi->impulse_noisetune=*farg;
+
+        if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
+        if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
+      }
+      return(0);
+    case OV_ECTL_COUPLING_GET:
+      {
+        int *iarg=(int *)arg;
+        *iarg=hi->coupling_p;
+      }
+      return(0);
+    case OV_ECTL_COUPLING_SET:
+      {
+        const void *new_template;
+        double new_base=0.;
+        int *iarg=(int *)arg;
+        hi->coupling_p=((*iarg)!=0);
+
+        /* Fetching a new template can alter the base_setting, which
+           many other parameters are based on.  Right now, the only
+           parameter drawn from the base_setting that can be altered
+           by an encctl is the lowpass, so that is explictly flagged
+           to not be overwritten when we fetch a new template and
+           recompute the dependant settings */
+        new_template = get_setup_template(hi->coupling_p?vi->channels:-1,
+                                          vi->rate,
+                                          hi->req,
+                                          hi->managed,
+                                          &new_base);
+        if(!hi->setup)return OV_EIMPL;
+        hi->setup=new_template;
+        hi->base_setting=new_base;
+        vorbis_encode_setup_setting(vi,vi->channels,vi->rate);
+      }
+      return(0);
+    }
+    return(OV_EIMPL);
+  }
+  return(OV_EINVAL);
+}
diff --git a/vorbis/lib/vorbisfile.c b/vorbis/lib/vorbisfile.c
new file mode 100644 (file)
index 0000000..b570c3c
--- /dev/null
@@ -0,0 +1,2424 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2015             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: stdio-based convenience library for opening/seeking/decoding
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <math.h>
+
+#include "vorbis/codec.h"
+
+/* we don't need or want the static callback symbols here */
+#define OV_EXCLUDE_STATIC_CALLBACKS
+#include "vorbis/vorbisfile.h"
+
+#include "os.h"
+#include "misc.h"
+
+/* A 'chained bitstream' is a Vorbis bitstream that contains more than
+   one logical bitstream arranged end to end (the only form of Ogg
+   multiplexing allowed in a Vorbis bitstream; grouping [parallel
+   multiplexing] is not allowed in Vorbis) */
+
+/* A Vorbis file can be played beginning to end (streamed) without
+   worrying ahead of time about chaining (see decoder_example.c).  If
+   we have the whole file, however, and want random access
+   (seeking/scrubbing) or desire to know the total length/time of a
+   file, we need to account for the possibility of chaining. */
+
+/* We can handle things a number of ways; we can determine the entire
+   bitstream structure right off the bat, or find pieces on demand.
+   This example determines and caches structure for the entire
+   bitstream, but builds a virtual decoder on the fly when moving
+   between links in the chain. */
+
+/* There are also different ways to implement seeking.  Enough
+   information exists in an Ogg bitstream to seek to
+   sample-granularity positions in the output.  Or, one can seek by
+   picking some portion of the stream roughly in the desired area if
+   we only want coarse navigation through the stream. */
+
+/*************************************************************************
+ * Many, many internal helpers.  The intention is not to be confusing;
+ * rampant duplication and monolithic function implementation would be
+ * harder to understand anyway.  The high level functions are last.  Begin
+ * grokking near the end of the file */
+
+/* read a little more data from the file/pipe into the ogg_sync framer
+*/
+#define CHUNKSIZE 65536 /* greater-than-page-size granularity seeking */
+#define READSIZE 2048 /* a smaller read size is needed for low-rate streaming. */
+
+static long _get_data(OggVorbis_File *vf){
+  errno=0;
+  if(!(vf->callbacks.read_func))return(-1);
+  if(vf->datasource){
+    char *buffer=ogg_sync_buffer(&vf->oy,READSIZE);
+    long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource);
+    if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
+    if(bytes==0 && errno)return(-1);
+    return(bytes);
+  }else
+    return(0);
+}
+
+/* save a tiny smidge of verbosity to make the code more readable */
+static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
+  if(vf->datasource){
+    /* only seek if the file position isn't already there */
+    if(vf->offset != offset){
+      if(!(vf->callbacks.seek_func)||
+         (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1)
+        return OV_EREAD;
+      vf->offset=offset;
+      ogg_sync_reset(&vf->oy);
+    }
+  }else{
+    /* shouldn't happen unless someone writes a broken callback */
+    return OV_EFAULT;
+  }
+  return 0;
+}
+
+/* The read/seek functions track absolute position within the stream */
+
+/* from the head of the stream, get the next page.  boundary specifies
+   if the function is allowed to fetch more data from the stream (and
+   how much) or only use internally buffered data.
+
+   boundary: -1) unbounded search
+              0) read no additional data; use cached only
+              n) search for a new page beginning for n bytes
+
+   return:   <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
+              n) found a page at absolute offset n */
+
+static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
+                                  ogg_int64_t boundary){
+  if(boundary>0)boundary+=vf->offset;
+  while(1){
+    long more;
+
+    if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
+    more=ogg_sync_pageseek(&vf->oy,og);
+
+    if(more<0){
+      /* skipped n bytes */
+      vf->offset-=more;
+    }else{
+      if(more==0){
+        /* send more paramedics */
+        if(!boundary)return(OV_FALSE);
+        {
+          long ret=_get_data(vf);
+          if(ret==0)return(OV_EOF);
+          if(ret<0)return(OV_EREAD);
+        }
+      }else{
+        /* got a page.  Return the offset at the page beginning,
+           advance the internal offset past the page end */
+        ogg_int64_t ret=vf->offset;
+        vf->offset+=more;
+        return(ret);
+
+      }
+    }
+  }
+}
+
+/* find the latest page beginning before the passed in position. Much
+   dirtier than the above as Ogg doesn't have any backward search
+   linkage.  no 'readp' as it will certainly have to read. */
+/* returns offset or OV_EREAD, OV_FAULT */
+static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_int64_t begin,ogg_page *og){
+  ogg_int64_t end = begin;
+  ogg_int64_t ret;
+  ogg_int64_t offset=-1;
+
+  while(offset==-1){
+    begin-=CHUNKSIZE;
+    if(begin<0)
+      begin=0;
+
+    ret=_seek_helper(vf,begin);
+    if(ret)return(ret);
+
+    while(vf->offset<end){
+      memset(og,0,sizeof(*og));
+      ret=_get_next_page(vf,og,end-vf->offset);
+      if(ret==OV_EREAD)return(OV_EREAD);
+      if(ret<0){
+        break;
+      }else{
+        offset=ret;
+      }
+    }
+  }
+
+  /* In a fully compliant, non-multiplexed stream, we'll still be
+     holding the last page.  In multiplexed (or noncompliant streams),
+     we will probably have to re-read the last page we saw */
+  if(og->header_len==0){
+    ret=_seek_helper(vf,offset);
+    if(ret)return(ret);
+
+    ret=_get_next_page(vf,og,CHUNKSIZE);
+    if(ret<0)
+      /* this shouldn't be possible */
+      return(OV_EFAULT);
+  }
+
+  return(offset);
+}
+
+static void _add_serialno(ogg_page *og,long **serialno_list, int *n){
+  long s = ogg_page_serialno(og);
+  (*n)++;
+
+  if(*serialno_list){
+    *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n));
+  }else{
+    *serialno_list = _ogg_malloc(sizeof(**serialno_list));
+  }
+
+  (*serialno_list)[(*n)-1] = s;
+}
+
+/* returns nonzero if found */
+static int _lookup_serialno(long s, long *serialno_list, int n){
+  if(serialno_list){
+    while(n--){
+      if(*serialno_list == s) return 1;
+      serialno_list++;
+    }
+  }
+  return 0;
+}
+
+static int _lookup_page_serialno(ogg_page *og, long *serialno_list, int n){
+  long s = ogg_page_serialno(og);
+  return _lookup_serialno(s,serialno_list,n);
+}
+
+/* performs the same search as _get_prev_page, but prefers pages of
+   the specified serial number. If a page of the specified serialno is
+   spotted during the seek-back-and-read-forward, it will return the
+   info of last page of the matching serial number instead of the very
+   last page.  If no page of the specified serialno is seen, it will
+   return the info of last page and alter *serialno.  */
+static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, ogg_int64_t begin,
+                                         long *serial_list, int serial_n,
+                                         int *serialno, ogg_int64_t *granpos){
+  ogg_page og;
+  ogg_int64_t end=begin;
+  ogg_int64_t ret;
+
+  ogg_int64_t prefoffset=-1;
+  ogg_int64_t offset=-1;
+  ogg_int64_t ret_serialno=-1;
+  ogg_int64_t ret_gran=-1;
+
+  while(offset==-1){
+    begin-=CHUNKSIZE;
+    if(begin<0)
+      begin=0;
+
+    ret=_seek_helper(vf,begin);
+    if(ret)return(ret);
+
+    while(vf->offset<end){
+      ret=_get_next_page(vf,&og,end-vf->offset);
+      if(ret==OV_EREAD)return(OV_EREAD);
+      if(ret<0){
+        break;
+      }else{
+        ret_serialno=ogg_page_serialno(&og);
+        ret_gran=ogg_page_granulepos(&og);
+        offset=ret;
+
+        if(ret_serialno == *serialno){
+          prefoffset=ret;
+          *granpos=ret_gran;
+        }
+
+        if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){
+          /* we fell off the end of the link, which means we seeked
+             back too far and shouldn't have been looking in that link
+             to begin with.  If we found the preferred serial number,
+             forget that we saw it. */
+          prefoffset=-1;
+        }
+      }
+    }
+  }
+
+  /* we're not interested in the page... just the serialno and granpos. */
+  if(prefoffset>=0)return(prefoffset);
+
+  *serialno = ret_serialno;
+  *granpos = ret_gran;
+  return(offset);
+
+}
+
+/* uses the local ogg_stream storage in vf; this is important for
+   non-streaming input sources */
+static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
+                          long **serialno_list, int *serialno_n,
+                          ogg_page *og_ptr){
+  ogg_page og;
+  ogg_packet op;
+  int i,ret;
+  int allbos=0;
+
+  if(!og_ptr){
+    ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
+    if(llret==OV_EREAD)return(OV_EREAD);
+    if(llret<0)return(OV_ENOTVORBIS);
+    og_ptr=&og;
+  }
+
+  vorbis_info_init(vi);
+  vorbis_comment_init(vc);
+  vf->ready_state=OPENED;
+
+  /* extract the serialnos of all BOS pages + the first set of vorbis
+     headers we see in the link */
+
+  while(ogg_page_bos(og_ptr)){
+    if(serialno_list){
+      if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){
+        /* a dupe serialnumber in an initial header packet set == invalid stream */
+        if(*serialno_list)_ogg_free(*serialno_list);
+        *serialno_list=0;
+        *serialno_n=0;
+        ret=OV_EBADHEADER;
+        goto bail_header;
+      }
+
+      _add_serialno(og_ptr,serialno_list,serialno_n);
+    }
+
+    if(vf->ready_state<STREAMSET){
+      /* we don't have a vorbis stream in this link yet, so begin
+         prospective stream setup. We need a stream to get packets */
+      ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
+      ogg_stream_pagein(&vf->os,og_ptr);
+
+      if(ogg_stream_packetout(&vf->os,&op) > 0 &&
+         vorbis_synthesis_idheader(&op)){
+        /* vorbis header; continue setup */
+        vf->ready_state=STREAMSET;
+        if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
+          ret=OV_EBADHEADER;
+          goto bail_header;
+        }
+      }
+    }
+
+    /* get next page */
+    {
+      ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE);
+      if(llret==OV_EREAD){
+        ret=OV_EREAD;
+        goto bail_header;
+      }
+      if(llret<0){
+        ret=OV_ENOTVORBIS;
+        goto bail_header;
+      }
+
+      /* if this page also belongs to our vorbis stream, submit it and break */
+      if(vf->ready_state==STREAMSET &&
+         vf->os.serialno == ogg_page_serialno(og_ptr)){
+        ogg_stream_pagein(&vf->os,og_ptr);
+        break;
+      }
+    }
+  }
+
+  if(vf->ready_state!=STREAMSET){
+    ret = OV_ENOTVORBIS;
+    goto bail_header;
+  }
+
+  while(1){
+
+    i=0;
+    while(i<2){ /* get a page loop */
+
+      while(i<2){ /* get a packet loop */
+
+        int result=ogg_stream_packetout(&vf->os,&op);
+        if(result==0)break;
+        if(result==-1){
+          ret=OV_EBADHEADER;
+          goto bail_header;
+        }
+
+        if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
+          goto bail_header;
+
+        i++;
+      }
+
+      while(i<2){
+        if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
+          ret=OV_EBADHEADER;
+          goto bail_header;
+        }
+
+        /* if this page belongs to the correct stream, go parse it */
+        if(vf->os.serialno == ogg_page_serialno(og_ptr)){
+          ogg_stream_pagein(&vf->os,og_ptr);
+          break;
+        }
+
+        /* if we never see the final vorbis headers before the link
+           ends, abort */
+        if(ogg_page_bos(og_ptr)){
+          if(allbos){
+            ret = OV_EBADHEADER;
+            goto bail_header;
+          }else
+            allbos=1;
+        }
+
+        /* otherwise, keep looking */
+      }
+    }
+
+    return 0;
+  }
+
+ bail_header:
+  vorbis_info_clear(vi);
+  vorbis_comment_clear(vc);
+  vf->ready_state=OPENED;
+
+  return ret;
+}
+
+/* Starting from current cursor position, get initial PCM offset of
+   next page.  Consumes the page in the process without decoding
+   audio, however this is only called during stream parsing upon
+   seekable open. */
+static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){
+  ogg_page    og;
+  ogg_int64_t accumulated=0;
+  long        lastblock=-1;
+  int         result;
+  int         serialno = vf->os.serialno;
+
+  while(1){
+    ogg_packet op;
+    if(_get_next_page(vf,&og,-1)<0)
+      break; /* should not be possible unless the file is truncated/mangled */
+
+    if(ogg_page_bos(&og)) break;
+    if(ogg_page_serialno(&og)!=serialno) continue;
+
+    /* count blocksizes of all frames in the page */
+    ogg_stream_pagein(&vf->os,&og);
+    while((result=ogg_stream_packetout(&vf->os,&op))){
+      if(result>0){ /* ignore holes */
+        long thisblock=vorbis_packet_blocksize(vi,&op);
+        if(thisblock>=0){
+          if(lastblock!=-1)
+            accumulated+=(lastblock+thisblock)>>2;
+          lastblock=thisblock;
+        }
+      }
+    }
+
+    if(ogg_page_granulepos(&og)!=-1){
+      /* pcm offset of last packet on the first audio page */
+      accumulated= ogg_page_granulepos(&og)-accumulated;
+      break;
+    }
+  }
+
+  /* less than zero?  Either a corrupt file or a stream with samples
+     trimmed off the beginning, a normal occurrence; in both cases set
+     the offset to zero */
+  if(accumulated<0)accumulated=0;
+
+  return accumulated;
+}
+
+/* finds each bitstream link one at a time using a bisection search
+   (has to begin by knowing the offset of the lb's initial page).
+   Recurses for each link so it can alloc the link storage after
+   finding them all, then unroll and fill the cache at the same time */
+static int _bisect_forward_serialno(OggVorbis_File *vf,
+                                    ogg_int64_t begin,
+                                    ogg_int64_t searched,
+                                    ogg_int64_t end,
+                                    ogg_int64_t endgran,
+                                    int endserial,
+                                    long *currentno_list,
+                                    int  currentnos,
+                                    long m){
+  ogg_int64_t pcmoffset;
+  ogg_int64_t dataoffset=searched;
+  ogg_int64_t endsearched=end;
+  ogg_int64_t next=end;
+  ogg_int64_t searchgran=-1;
+  ogg_page og;
+  ogg_int64_t ret,last;
+  int serialno = vf->os.serialno;
+
+  /* invariants:
+     we have the headers and serialnos for the link beginning at 'begin'
+     we have the offset and granpos of the last page in the file (potentially
+       not a page we care about)
+  */
+
+  /* Is the last page in our list of current serialnumbers? */
+  if(_lookup_serialno(endserial,currentno_list,currentnos)){
+
+    /* last page is in the starting serialno list, so we've bisected
+       down to (or just started with) a single link.  Now we need to
+       find the last vorbis page belonging to the first vorbis stream
+       for this link. */
+    searched = end;
+    while(endserial != serialno){
+      endserial = serialno;
+      searched=_get_prev_page_serial(vf,searched,currentno_list,currentnos,&endserial,&endgran);
+    }
+
+    vf->links=m+1;
+    if(vf->offsets)_ogg_free(vf->offsets);
+    if(vf->serialnos)_ogg_free(vf->serialnos);
+    if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
+
+    vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
+    vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
+    vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
+    vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos));
+    vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
+    vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
+
+    vf->offsets[m+1]=end;
+    vf->offsets[m]=begin;
+    vf->pcmlengths[m*2+1]=(endgran<0?0:endgran);
+
+  }else{
+
+    /* last page is not in the starting stream's serial number list,
+       so we have multiple links.  Find where the stream that begins
+       our bisection ends. */
+
+    long *next_serialno_list=NULL;
+    int next_serialnos=0;
+    vorbis_info vi;
+    vorbis_comment vc;
+    int testserial = serialno+1;
+
+    /* the below guards against garbage seperating the last and
+       first pages of two links. */
+    while(searched<endsearched){
+      ogg_int64_t bisect;
+
+      if(endsearched-searched<CHUNKSIZE){
+        bisect=searched;
+      }else{
+        bisect=(searched+endsearched)/2;
+      }
+
+      ret=_seek_helper(vf,bisect);
+      if(ret)return(ret);
+
+      last=_get_next_page(vf,&og,-1);
+      if(last==OV_EREAD)return(OV_EREAD);
+      if(last<0 || !_lookup_page_serialno(&og,currentno_list,currentnos)){
+        endsearched=bisect;
+        if(last>=0)next=last;
+      }else{
+        searched=vf->offset;
+      }
+    }
+
+    /* Bisection point found */
+    /* for the time being, fetch end PCM offset the simple way */
+    searched = next;
+    while(testserial != serialno){
+      testserial = serialno;
+      searched = _get_prev_page_serial(vf,searched,currentno_list,currentnos,&testserial,&searchgran);
+    }
+
+    ret=_seek_helper(vf,next);
+    if(ret)return(ret);
+
+    ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL);
+    if(ret)return(ret);
+    serialno = vf->os.serialno;
+    dataoffset = vf->offset;
+
+    /* this will consume a page, however the next bisection always
+       starts with a raw seek */
+    pcmoffset = _initial_pcmoffset(vf,&vi);
+
+    ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial,
+                                 next_serialno_list,next_serialnos,m+1);
+    if(ret)return(ret);
+
+    if(next_serialno_list)_ogg_free(next_serialno_list);
+
+    vf->offsets[m+1]=next;
+    vf->serialnos[m+1]=serialno;
+    vf->dataoffsets[m+1]=dataoffset;
+
+    vf->vi[m+1]=vi;
+    vf->vc[m+1]=vc;
+
+    vf->pcmlengths[m*2+1]=searchgran;
+    vf->pcmlengths[m*2+2]=pcmoffset;
+    vf->pcmlengths[m*2+3]-=pcmoffset;
+    if(vf->pcmlengths[m*2+3]<0)vf->pcmlengths[m*2+3]=0;
+  }
+  return(0);
+}
+
+static int _make_decode_ready(OggVorbis_File *vf){
+  if(vf->ready_state>STREAMSET)return 0;
+  if(vf->ready_state<STREAMSET)return OV_EFAULT;
+  if(vf->seekable){
+    if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
+      return OV_EBADLINK;
+  }else{
+    if(vorbis_synthesis_init(&vf->vd,vf->vi))
+      return OV_EBADLINK;
+  }
+  vorbis_block_init(&vf->vd,&vf->vb);
+  vf->ready_state=INITSET;
+  vf->bittrack=0.f;
+  vf->samptrack=0.f;
+  return 0;
+}
+
+static int _open_seekable2(OggVorbis_File *vf){
+  ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1;
+  int endserial=vf->os.serialno;
+  int serialno=vf->os.serialno;
+
+  /* we're partially open and have a first link header state in
+     storage in vf */
+
+  /* fetch initial PCM offset */
+  ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi);
+
+  /* we can seek, so set out learning all about this file */
+  if(vf->callbacks.seek_func && vf->callbacks.tell_func){
+    (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
+    vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
+  }else{
+    vf->offset=vf->end=-1;
+  }
+
+  /* If seek_func is implemented, tell_func must also be implemented */
+  if(vf->end==-1) return(OV_EINVAL);
+
+  /* Get the offset of the last page of the physical bitstream, or, if
+     we're lucky the last vorbis page of this link as most OggVorbis
+     files will contain a single logical bitstream */
+  end=_get_prev_page_serial(vf,vf->end,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran);
+  if(end<0)return(end);
+
+  /* now determine bitstream structure recursively */
+  if(_bisect_forward_serialno(vf,0,dataoffset,end,endgran,endserial,
+                              vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD);
+
+  vf->offsets[0]=0;
+  vf->serialnos[0]=serialno;
+  vf->dataoffsets[0]=dataoffset;
+  vf->pcmlengths[0]=pcmoffset;
+  vf->pcmlengths[1]-=pcmoffset;
+  if(vf->pcmlengths[1]<0)vf->pcmlengths[1]=0;
+
+  return(ov_raw_seek(vf,dataoffset));
+}
+
+/* clear out the current logical bitstream decoder */
+static void _decode_clear(OggVorbis_File *vf){
+  vorbis_dsp_clear(&vf->vd);
+  vorbis_block_clear(&vf->vb);
+  vf->ready_state=OPENED;
+}
+
+/* fetch and process a packet.  Handles the case where we're at a
+   bitstream boundary and dumps the decoding machine.  If the decoding
+   machine is unloaded, it loads it.  It also keeps pcm_offset up to
+   date (seek and read both use this.  seek uses a special hack with
+   readp).
+
+   return: <0) error, OV_HOLE (lost packet) or OV_EOF
+            0) need more data (only if readp==0)
+            1) got a packet
+*/
+
+static int _fetch_and_process_packet(OggVorbis_File *vf,
+                                     ogg_packet *op_in,
+                                     int readp,
+                                     int spanp){
+  ogg_page og;
+
+  /* handle one packet.  Try to fetch it from current stream state */
+  /* extract packets from page */
+  while(1){
+
+    if(vf->ready_state==STREAMSET){
+      int ret=_make_decode_ready(vf);
+      if(ret<0)return ret;
+    }
+
+    /* process a packet if we can. */
+
+    if(vf->ready_state==INITSET){
+      int hs=vorbis_synthesis_halfrate_p(vf->vi);
+
+      while(1) {
+              ogg_packet op;
+              ogg_packet *op_ptr=(op_in?op_in:&op);
+        int result=ogg_stream_packetout(&vf->os,op_ptr);
+        ogg_int64_t granulepos;
+
+        op_in=NULL;
+        if(result==-1)return(OV_HOLE); /* hole in the data. */
+        if(result>0){
+          /* got a packet.  process it */
+          granulepos=op_ptr->granulepos;
+          if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
+                                                    header handling.  The
+                                                    header packets aren't
+                                                    audio, so if/when we
+                                                    submit them,
+                                                    vorbis_synthesis will
+                                                    reject them */
+
+            /* suck in the synthesis data and track bitrate */
+            {
+              int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
+              /* for proper use of libvorbis within libvorbisfile,
+                 oldsamples will always be zero. */
+              if(oldsamples)return(OV_EFAULT);
+
+              vorbis_synthesis_blockin(&vf->vd,&vf->vb);
+              vf->samptrack+=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
+              vf->bittrack+=op_ptr->bytes*8;
+            }
+
+            /* update the pcm offset. */
+            if(granulepos!=-1 && !op_ptr->e_o_s){
+              int link=(vf->seekable?vf->current_link:0);
+              int i,samples;
+
+              /* this packet has a pcm_offset on it (the last packet
+                 completed on a page carries the offset) After processing
+                 (above), we know the pcm position of the *last* sample
+                 ready to be returned. Find the offset of the *first*
+
+                 As an aside, this trick is inaccurate if we begin
+                 reading anew right at the last page; the end-of-stream
+                 granulepos declares the last frame in the stream, and the
+                 last packet of the last page may be a partial frame.
+                 So, we need a previous granulepos from an in-sequence page
+                 to have a reference point.  Thus the !op_ptr->e_o_s clause
+                 above */
+
+              if(vf->seekable && link>0)
+                granulepos-=vf->pcmlengths[link*2];
+              if(granulepos<0)granulepos=0; /* actually, this
+                                               shouldn't be possible
+                                               here unless the stream
+                                               is very broken */
+
+              samples=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
+
+              granulepos-=samples;
+              for(i=0;i<link;i++)
+                granulepos+=vf->pcmlengths[i*2+1];
+              vf->pcm_offset=granulepos;
+            }
+            return(1);
+          }
+        }
+        else
+          break;
+      }
+    }
+
+    if(vf->ready_state>=OPENED){
+      ogg_int64_t ret;
+
+      while(1){
+        /* the loop is not strictly necessary, but there's no sense in
+           doing the extra checks of the larger loop for the common
+           case in a multiplexed bistream where the page is simply
+           part of a different logical bitstream; keep reading until
+           we get one with the correct serialno */
+
+        if(!readp)return(0);
+        if((ret=_get_next_page(vf,&og,-1))<0){
+          return(OV_EOF); /* eof. leave unitialized */
+        }
+
+        /* bitrate tracking; add the header's bytes here, the body bytes
+           are done by packet above */
+        vf->bittrack+=og.header_len*8;
+
+        if(vf->ready_state==INITSET){
+          if(vf->current_serialno!=ogg_page_serialno(&og)){
+
+            /* two possibilities:
+               1) our decoding just traversed a bitstream boundary
+               2) another stream is multiplexed into this logical section */
+
+            if(ogg_page_bos(&og)){
+              /* boundary case */
+              if(!spanp)
+                return(OV_EOF);
+
+              _decode_clear(vf);
+
+              if(!vf->seekable){
+                vorbis_info_clear(vf->vi);
+                vorbis_comment_clear(vf->vc);
+              }
+              break;
+
+            }else
+              continue; /* possibility #2 */
+          }
+        }
+
+        break;
+      }
+    }
+
+    /* Do we need to load a new machine before submitting the page? */
+    /* This is different in the seekable and non-seekable cases.
+
+       In the seekable case, we already have all the header
+       information loaded and cached; we just initialize the machine
+       with it and continue on our merry way.
+
+       In the non-seekable (streaming) case, we'll only be at a
+       boundary if we just left the previous logical bitstream and
+       we're now nominally at the header of the next bitstream
+    */
+
+    if(vf->ready_state!=INITSET){
+      int link;
+
+      if(vf->ready_state<STREAMSET){
+        if(vf->seekable){
+          long serialno = ogg_page_serialno(&og);
+
+          /* match the serialno to bitstream section.  We use this rather than
+             offset positions to avoid problems near logical bitstream
+             boundaries */
+
+          for(link=0;link<vf->links;link++)
+            if(vf->serialnos[link]==serialno)break;
+
+          if(link==vf->links) continue; /* not the desired Vorbis
+                                           bitstream section; keep
+                                           trying */
+
+          vf->current_serialno=serialno;
+          vf->current_link=link;
+
+          ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
+          vf->ready_state=STREAMSET;
+
+        }else{
+          /* we're streaming */
+          /* fetch the three header packets, build the info struct */
+
+          int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og);
+          if(ret)return(ret);
+          vf->current_serialno=vf->os.serialno;
+          vf->current_link++;
+          link=0;
+        }
+      }
+    }
+
+    /* the buffered page is the data we want, and we're ready for it;
+       add it to the stream state */
+    ogg_stream_pagein(&vf->os,&og);
+
+  }
+}
+
+/* if, eg, 64 bit stdio is configured by default, this will build with
+   fseek64 */
+static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
+  if(f==NULL)return(-1);
+  return fseek(f,off,whence);
+}
+
+static int _ov_open1(void *f,OggVorbis_File *vf,const char *initial,
+                     long ibytes, ov_callbacks callbacks){
+  int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1);
+  long *serialno_list=NULL;
+  int serialno_list_size=0;
+  int ret;
+
+  memset(vf,0,sizeof(*vf));
+  vf->datasource=f;
+  vf->callbacks = callbacks;
+
+  /* init the framing state */
+  ogg_sync_init(&vf->oy);
+
+  /* perhaps some data was previously read into a buffer for testing
+     against other stream types.  Allow initialization from this
+     previously read data (especially as we may be reading from a
+     non-seekable stream) */
+  if(initial){
+    char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
+    memcpy(buffer,initial,ibytes);
+    ogg_sync_wrote(&vf->oy,ibytes);
+  }
+
+  /* can we seek? Stevens suggests the seek test was portable */
+  if(offsettest!=-1)vf->seekable=1;
+
+  /* No seeking yet; Set up a 'single' (current) logical bitstream
+     entry for partial open */
+  vf->links=1;
+  vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi));
+  vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc));
+  ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
+
+  /* Fetch all BOS pages, store the vorbis header and all seen serial
+     numbers, load subsequent vorbis setup headers */
+  if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){
+    vf->datasource=NULL;
+    ov_clear(vf);
+  }else{
+    /* serial number list for first link needs to be held somewhere
+       for second stage of seekable stream open; this saves having to
+       seek/reread first link's serialnumber data then. */
+    vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos));
+    vf->serialnos[0]=vf->current_serialno=vf->os.serialno;
+    vf->serialnos[1]=serialno_list_size;
+    memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos));
+
+    vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets));
+    vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets));
+    vf->offsets[0]=0;
+    vf->dataoffsets[0]=vf->offset;
+
+    vf->ready_state=PARTOPEN;
+  }
+  if(serialno_list)_ogg_free(serialno_list);
+  return(ret);
+}
+
+static int _ov_open2(OggVorbis_File *vf){
+  if(vf->ready_state != PARTOPEN) return OV_EINVAL;
+  vf->ready_state=OPENED;
+  if(vf->seekable){
+    int ret=_open_seekable2(vf);
+    if(ret){
+      vf->datasource=NULL;
+      ov_clear(vf);
+    }
+    return(ret);
+  }else
+    vf->ready_state=STREAMSET;
+
+  return 0;
+}
+
+
+/* clear out the OggVorbis_File struct */
+int ov_clear(OggVorbis_File *vf){
+  if(vf){
+    vorbis_block_clear(&vf->vb);
+    vorbis_dsp_clear(&vf->vd);
+    ogg_stream_clear(&vf->os);
+
+    if(vf->vi && vf->links){
+      int i;
+      for(i=0;i<vf->links;i++){
+        vorbis_info_clear(vf->vi+i);
+        vorbis_comment_clear(vf->vc+i);
+      }
+      _ogg_free(vf->vi);
+      _ogg_free(vf->vc);
+    }
+    if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
+    if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
+    if(vf->serialnos)_ogg_free(vf->serialnos);
+    if(vf->offsets)_ogg_free(vf->offsets);
+    ogg_sync_clear(&vf->oy);
+    if(vf->datasource && vf->callbacks.close_func)
+      (vf->callbacks.close_func)(vf->datasource);
+    memset(vf,0,sizeof(*vf));
+  }
+#ifdef DEBUG_LEAKS
+  _VDBG_dump();
+#endif
+  return(0);
+}
+
+/* inspects the OggVorbis file and finds/documents all the logical
+   bitstreams contained in it.  Tries to be tolerant of logical
+   bitstream sections that are truncated/woogie.
+
+   return: -1) error
+            0) OK
+*/
+
+int ov_open_callbacks(void *f,OggVorbis_File *vf,
+    const char *initial,long ibytes,ov_callbacks callbacks){
+  int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
+  if(ret)return ret;
+  return _ov_open2(vf);
+}
+
+int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
+  ov_callbacks callbacks = {
+    (size_t (*)(void *, size_t, size_t, void *))  fread,
+    (int (*)(void *, ogg_int64_t, int))              _fseek64_wrap,
+    (int (*)(void *))                             fclose,
+    (long (*)(void *))                            ftell
+  };
+
+  return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
+}
+
+int ov_fopen(const char *path,OggVorbis_File *vf){
+  int ret;
+  FILE *f = fopen(path,"rb");
+  if(!f) return -1;
+
+  ret = ov_open(f,vf,NULL,0);
+  if(ret) fclose(f);
+  return ret;
+}
+
+
+/* cheap hack for game usage where downsampling is desirable; there's
+   no need for SRC as we can just do it cheaply in libvorbis. */
+
+int ov_halfrate(OggVorbis_File *vf,int flag){
+  int i;
+  if(vf->vi==NULL)return OV_EINVAL;
+  if(vf->ready_state>STREAMSET){
+    /* clear out stream state; dumping the decode machine is needed to
+       reinit the MDCT lookups. */
+    vorbis_dsp_clear(&vf->vd);
+    vorbis_block_clear(&vf->vb);
+    vf->ready_state=STREAMSET;
+    if(vf->pcm_offset>=0){
+      ogg_int64_t pos=vf->pcm_offset;
+      vf->pcm_offset=-1; /* make sure the pos is dumped if unseekable */
+      ov_pcm_seek(vf,pos);
+    }
+  }
+
+  for(i=0;i<vf->links;i++){
+    if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
+      if(flag) ov_halfrate(vf,0);
+      return OV_EINVAL;
+    }
+  }
+  return 0;
+}
+
+int ov_halfrate_p(OggVorbis_File *vf){
+  if(vf->vi==NULL)return OV_EINVAL;
+  return vorbis_synthesis_halfrate_p(vf->vi);
+}
+
+/* Only partially open the vorbis file; test for Vorbisness, and load
+   the headers for the first chain.  Do not seek (although test for
+   seekability).  Use ov_test_open to finish opening the file, else
+   ov_clear to close/free it. Same return codes as open.
+
+   Note that vorbisfile does _not_ take ownership of the file if the
+   call fails; the calling applicaiton is responsible for closing the file
+   if this call returns an error. */
+
+int ov_test_callbacks(void *f,OggVorbis_File *vf,
+    const char *initial,long ibytes,ov_callbacks callbacks)
+{
+  return _ov_open1(f,vf,initial,ibytes,callbacks);
+}
+
+int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
+  ov_callbacks callbacks = {
+    (size_t (*)(void *, size_t, size_t, void *))  fread,
+    (int (*)(void *, ogg_int64_t, int))              _fseek64_wrap,
+    (int (*)(void *))                             fclose,
+    (long (*)(void *))                            ftell
+  };
+
+  return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
+}
+
+int ov_test_open(OggVorbis_File *vf){
+  if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
+  return _ov_open2(vf);
+}
+
+/* How many logical bitstreams in this physical bitstream? */
+long ov_streams(OggVorbis_File *vf){
+  return vf->links;
+}
+
+/* Is the FILE * associated with vf seekable? */
+long ov_seekable(OggVorbis_File *vf){
+  return vf->seekable;
+}
+
+/* returns the bitrate for a given logical bitstream or the entire
+   physical bitstream.  If the file is open for random access, it will
+   find the *actual* average bitrate.  If the file is streaming, it
+   returns the nominal bitrate (if set) else the average of the
+   upper/lower bounds (if set) else -1 (unset).
+
+   If you want the actual bitrate field settings, get them from the
+   vorbis_info structs */
+
+long ov_bitrate(OggVorbis_File *vf,int i){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(i>=vf->links)return(OV_EINVAL);
+  if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
+  if(i<0){
+    ogg_int64_t bits=0;
+    int i;
+    float br;
+    for(i=0;i<vf->links;i++)
+      bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
+    /* This once read: return(rint(bits/ov_time_total(vf,-1)));
+     * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
+     * so this is slightly transformed to make it work.
+     */
+    br = bits/ov_time_total(vf,-1);
+    return(rint(br));
+  }else{
+    if(vf->seekable){
+      /* return the actual bitrate */
+      return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
+    }else{
+      /* return nominal if set */
+      if(vf->vi[i].bitrate_nominal>0){
+        return vf->vi[i].bitrate_nominal;
+      }else{
+        if(vf->vi[i].bitrate_upper>0){
+          if(vf->vi[i].bitrate_lower>0){
+            return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
+          }else{
+            return vf->vi[i].bitrate_upper;
+          }
+        }
+        return(OV_FALSE);
+      }
+    }
+  }
+}
+
+/* returns the actual bitrate since last call.  returns -1 if no
+   additional data to offer since last call (or at beginning of stream),
+   EINVAL if stream is only partially open
+*/
+long ov_bitrate_instant(OggVorbis_File *vf){
+  int link=(vf->seekable?vf->current_link:0);
+  long ret;
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(vf->samptrack==0)return(OV_FALSE);
+  ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
+  vf->bittrack=0.f;
+  vf->samptrack=0.f;
+  return(ret);
+}
+
+/* Guess */
+long ov_serialnumber(OggVorbis_File *vf,int i){
+  if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
+  if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
+  if(i<0){
+    return(vf->current_serialno);
+  }else{
+    return(vf->serialnos[i]);
+  }
+}
+
+/* returns: total raw (compressed) length of content if i==-1
+            raw (compressed) length of that logical bitstream for i==0 to n
+            OV_EINVAL if the stream is not seekable (we can't know the length)
+            or if stream is only partially open
+*/
+ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
+  if(i<0){
+    ogg_int64_t acc=0;
+    int i;
+    for(i=0;i<vf->links;i++)
+      acc+=ov_raw_total(vf,i);
+    return(acc);
+  }else{
+    return(vf->offsets[i+1]-vf->offsets[i]);
+  }
+}
+
+/* returns: total PCM length (samples) of content if i==-1 PCM length
+            (samples) of that logical bitstream for i==0 to n
+            OV_EINVAL if the stream is not seekable (we can't know the
+            length) or only partially open
+*/
+ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
+  if(i<0){
+    ogg_int64_t acc=0;
+    int i;
+    for(i=0;i<vf->links;i++)
+      acc+=ov_pcm_total(vf,i);
+    return(acc);
+  }else{
+    return(vf->pcmlengths[i*2+1]);
+  }
+}
+
+/* returns: total seconds of content if i==-1
+            seconds in that logical bitstream for i==0 to n
+            OV_EINVAL if the stream is not seekable (we can't know the
+            length) or only partially open
+*/
+double ov_time_total(OggVorbis_File *vf,int i){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
+  if(i<0){
+    double acc=0;
+    int i;
+    for(i=0;i<vf->links;i++)
+      acc+=ov_time_total(vf,i);
+    return(acc);
+  }else{
+    return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
+  }
+}
+
+/* seek to an offset relative to the *compressed* data. This also
+   scans packets to update the PCM cursor. It will cross a logical
+   bitstream boundary, but only if it can't get any packets out of the
+   tail of the bitstream we seek to (so no surprises).
+
+   returns zero on success, nonzero on failure */
+
+int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
+  ogg_stream_state work_os;
+  int ret;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable)
+    return(OV_ENOSEEK); /* don't dump machine if we can't seek */
+
+  if(pos<0 || pos>vf->end)return(OV_EINVAL);
+
+  /* is the seek position outside our current link [if any]? */
+  if(vf->ready_state>=STREAMSET){
+    if(pos<vf->offsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1])
+      _decode_clear(vf); /* clear out stream state */
+  }
+
+  /* don't yet clear out decoding machine (if it's initialized), in
+     the case we're in the same link.  Restart the decode lapping, and
+     let _fetch_and_process_packet deal with a potential bitstream
+     boundary */
+  vf->pcm_offset=-1;
+  ogg_stream_reset_serialno(&vf->os,
+                            vf->current_serialno); /* must set serialno */
+  vorbis_synthesis_restart(&vf->vd);
+
+  ret=_seek_helper(vf,pos);
+  if(ret)goto seek_error;
+
+  /* we need to make sure the pcm_offset is set, but we don't want to
+     advance the raw cursor past good packets just to get to the first
+     with a granulepos.  That's not equivalent behavior to beginning
+     decoding as immediately after the seek position as possible.
+
+     So, a hack.  We use two stream states; a local scratch state and
+     the shared vf->os stream state.  We use the local state to
+     scan, and the shared state as a buffer for later decode.
+
+     Unfortuantely, on the last page we still advance to last packet
+     because the granulepos on the last page is not necessarily on a
+     packet boundary, and we need to make sure the granpos is
+     correct.
+  */
+
+  {
+    ogg_page og;
+    ogg_packet op;
+    int lastblock=0;
+    int accblock=0;
+    int thisblock=0;
+    int lastflag=0;
+    int firstflag=0;
+    ogg_int64_t pagepos=-1;
+
+    ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
+    ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
+                                   return from not necessarily
+                                   starting from the beginning */
+
+    while(1){
+      if(vf->ready_state>=STREAMSET){
+        /* snarf/scan a packet if we can */
+        int result=ogg_stream_packetout(&work_os,&op);
+
+        if(result>0){
+
+          if(vf->vi[vf->current_link].codec_setup){
+            thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
+            if(thisblock<0){
+              ogg_stream_packetout(&vf->os,NULL);
+              thisblock=0;
+            }else{
+
+              /* We can't get a guaranteed correct pcm position out of the
+                 last page in a stream because it might have a 'short'
+                 granpos, which can only be detected in the presence of a
+                 preceding page.  However, if the last page is also the first
+                 page, the granpos rules of a first page take precedence.  Not
+                 only that, but for first==last, the EOS page must be treated
+                 as if its a normal first page for the stream to open/play. */
+              if(lastflag && !firstflag)
+                ogg_stream_packetout(&vf->os,NULL);
+              else
+                if(lastblock)accblock+=(lastblock+thisblock)>>2;
+            }
+
+            if(op.granulepos!=-1){
+              int i,link=vf->current_link;
+              ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
+              if(granulepos<0)granulepos=0;
+
+              for(i=0;i<link;i++)
+                granulepos+=vf->pcmlengths[i*2+1];
+              vf->pcm_offset=granulepos-accblock;
+              if(vf->pcm_offset<0)vf->pcm_offset=0;
+              break;
+            }
+            lastblock=thisblock;
+            continue;
+          }else
+            ogg_stream_packetout(&vf->os,NULL);
+        }
+      }
+
+      if(!lastblock){
+        pagepos=_get_next_page(vf,&og,-1);
+        if(pagepos<0){
+          vf->pcm_offset=ov_pcm_total(vf,-1);
+          break;
+        }
+      }else{
+        /* huh?  Bogus stream with packets but no granulepos */
+        vf->pcm_offset=-1;
+        break;
+      }
+
+      /* has our decoding just traversed a bitstream boundary? */
+      if(vf->ready_state>=STREAMSET){
+        if(vf->current_serialno!=ogg_page_serialno(&og)){
+
+          /* two possibilities:
+             1) our decoding just traversed a bitstream boundary
+             2) another stream is multiplexed into this logical section? */
+
+          if(ogg_page_bos(&og)){
+            /* we traversed */
+            _decode_clear(vf); /* clear out stream state */
+            ogg_stream_clear(&work_os);
+          } /* else, do nothing; next loop will scoop another page */
+        }
+      }
+
+      if(vf->ready_state<STREAMSET){
+        int link;
+        long serialno = ogg_page_serialno(&og);
+
+        for(link=0;link<vf->links;link++)
+          if(vf->serialnos[link]==serialno)break;
+
+        if(link==vf->links) continue; /* not the desired Vorbis
+                                         bitstream section; keep
+                                         trying */
+        vf->current_link=link;
+        vf->current_serialno=serialno;
+        ogg_stream_reset_serialno(&vf->os,serialno);
+        ogg_stream_reset_serialno(&work_os,serialno);
+        vf->ready_state=STREAMSET;
+        firstflag=(pagepos<=vf->dataoffsets[link]);
+      }
+
+      ogg_stream_pagein(&vf->os,&og);
+      ogg_stream_pagein(&work_os,&og);
+      lastflag=ogg_page_eos(&og);
+
+    }
+  }
+
+  ogg_stream_clear(&work_os);
+  vf->bittrack=0.f;
+  vf->samptrack=0.f;
+  return(0);
+
+ seek_error:
+  /* dump the machine so we're in a known state */
+  vf->pcm_offset=-1;
+  ogg_stream_clear(&work_os);
+  _decode_clear(vf);
+  return OV_EBADLINK;
+}
+
+/* Page granularity seek (faster than sample granularity because we
+   don't do the last bit of decode to find a specific sample).
+
+   Seek to the last [granule marked] page preceding the specified pos
+   location, such that decoding past the returned point will quickly
+   arrive at the requested position. */
+int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
+  int link=-1;
+  ogg_int64_t result=0;
+  ogg_int64_t total=ov_pcm_total(vf,-1);
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable)return(OV_ENOSEEK);
+
+  if(pos<0 || pos>total)return(OV_EINVAL);
+
+  /* which bitstream section does this pcm offset occur in? */
+  for(link=vf->links-1;link>=0;link--){
+    total-=vf->pcmlengths[link*2+1];
+    if(pos>=total)break;
+  }
+
+  /* Search within the logical bitstream for the page with the highest
+     pcm_pos preceding pos.  If we're looking for a position on the
+     first page, bisection will halt without finding our position as
+     it's before the first explicit granulepos fencepost. That case is
+     handled separately below.
+
+     There is a danger here; missing pages or incorrect frame number
+     information in the bitstream could make our task impossible.
+     Account for that (it would be an error condition) */
+
+  /* new search algorithm originally by HB (Nicholas Vinen) */
+
+  {
+    ogg_int64_t end=vf->offsets[link+1];
+    ogg_int64_t begin=vf->dataoffsets[link];
+    ogg_int64_t begintime = vf->pcmlengths[link*2];
+    ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
+    ogg_int64_t target=pos-total+begintime;
+    ogg_int64_t best=-1;
+    int         got_page=0;
+
+    ogg_page og;
+
+    /* if we have only one page, there will be no bisection.  Grab the page here */
+    if(begin==end){
+      result=_seek_helper(vf,begin);
+      if(result) goto seek_error;
+
+      result=_get_next_page(vf,&og,1);
+      if(result<0) goto seek_error;
+
+      got_page=1;
+    }
+
+    /* bisection loop */
+    while(begin<end){
+      ogg_int64_t bisect;
+
+      if(end-begin<CHUNKSIZE){
+        bisect=begin;
+      }else{
+        /* take a (pretty decent) guess. */
+        bisect=begin +
+          (ogg_int64_t)((double)(target-begintime)*(end-begin)/(endtime-begintime))
+          - CHUNKSIZE;
+        if(bisect<begin+CHUNKSIZE)
+          bisect=begin;
+      }
+
+      result=_seek_helper(vf,bisect);
+      if(result) goto seek_error;
+
+      /* read loop within the bisection loop */
+      while(begin<end){
+        result=_get_next_page(vf,&og,end-vf->offset);
+        if(result==OV_EREAD) goto seek_error;
+        if(result<0){
+          /* there is no next page! */
+          if(bisect<=begin+1)
+              /* No bisection left to perform.  We've either found the
+                 best candidate already or failed. Exit loop. */
+            end=begin;
+          else{
+            /* We tried to load a fraction of the last page; back up a
+               bit and try to get the whole last page */
+            if(bisect==0) goto seek_error;
+            bisect-=CHUNKSIZE;
+
+            /* don't repeat/loop on a read we've already performed */
+            if(bisect<=begin)bisect=begin+1;
+
+            /* seek and cntinue bisection */
+            result=_seek_helper(vf,bisect);
+            if(result) goto seek_error;
+          }
+        }else{
+          ogg_int64_t granulepos;
+          got_page=1;
+
+          /* got a page. analyze it */
+          /* only consider pages from primary vorbis stream */
+          if(ogg_page_serialno(&og)!=vf->serialnos[link])
+            continue;
+
+          /* only consider pages with the granulepos set */
+          granulepos=ogg_page_granulepos(&og);
+          if(granulepos==-1)continue;
+
+          if(granulepos<target){
+            /* this page is a successful candidate! Set state */
+
+            best=result;  /* raw offset of packet with granulepos */
+            begin=vf->offset; /* raw offset of next page */
+            begintime=granulepos;
+
+            /* if we're before our target but within a short distance,
+               don't bisect; read forward */
+            if(target-begintime>44100)break;
+
+            bisect=begin; /* *not* begin + 1 as above */
+          }else{
+
+            /* This is one of our pages, but the granpos is
+               post-target; it is not a bisection return
+               candidate. (The only way we'd use it is if it's the
+               first page in the stream; we handle that case later
+               outside the bisection) */
+            if(bisect<=begin+1){
+              /* No bisection left to perform.  We've either found the
+                 best candidate already or failed. Exit loop. */
+              end=begin;
+            }else{
+              if(end==vf->offset){
+                /* bisection read to the end; use the known page
+                   boundary (result) to update bisection, back up a
+                   little bit, and try again */
+                end=result;
+                bisect-=CHUNKSIZE;
+                if(bisect<=begin)bisect=begin+1;
+                result=_seek_helper(vf,bisect);
+                if(result) goto seek_error;
+              }else{
+                /* Normal bisection */
+                end=bisect;
+                endtime=granulepos;
+                break;
+              }
+            }
+          }
+        }
+      }
+    }
+
+    /* Out of bisection: did it 'fail?' */
+    if(best == -1){
+
+      /* Check the 'looking for data in first page' special case;
+         bisection would 'fail' because our search target was before the
+         first PCM granule position fencepost. */
+
+      if(got_page &&
+         begin == vf->dataoffsets[link] &&
+         ogg_page_serialno(&og)==vf->serialnos[link]){
+
+        /* Yes, this is the beginning-of-stream case. We already have
+           our page, right at the beginning of PCM data.  Set state
+           and return. */
+
+        vf->pcm_offset=total;
+
+        if(link!=vf->current_link){
+          /* Different link; dump entire decode machine */
+          _decode_clear(vf);
+
+          vf->current_link=link;
+          vf->current_serialno=vf->serialnos[link];
+          vf->ready_state=STREAMSET;
+
+        }else{
+          vorbis_synthesis_restart(&vf->vd);
+        }
+
+        ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
+        ogg_stream_pagein(&vf->os,&og);
+
+      }else
+        goto seek_error;
+
+    }else{
+
+      /* Bisection found our page. seek to it, update pcm offset. Easier case than
+         raw_seek, don't keep packets preceding granulepos. */
+
+      ogg_page og;
+      ogg_packet op;
+
+      /* seek */
+      result=_seek_helper(vf,best);
+      vf->pcm_offset=-1;
+      if(result) goto seek_error;
+      result=_get_next_page(vf,&og,-1);
+      if(result<0) goto seek_error;
+
+      if(link!=vf->current_link){
+        /* Different link; dump entire decode machine */
+        _decode_clear(vf);
+
+        vf->current_link=link;
+        vf->current_serialno=vf->serialnos[link];
+        vf->ready_state=STREAMSET;
+
+      }else{
+        vorbis_synthesis_restart(&vf->vd);
+      }
+
+      ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
+      ogg_stream_pagein(&vf->os,&og);
+
+      /* pull out all but last packet; the one with granulepos */
+      while(1){
+        result=ogg_stream_packetpeek(&vf->os,&op);
+        if(result==0){
+          /* No packet returned; we exited the bisection with 'best'
+             pointing to a page with a granule position, so the packet
+             finishing this page ('best') originated on a preceding
+             page. Keep fetching previous pages until we get one with
+             a granulepos or without the 'continued' flag set.  Then
+             just use raw_seek for simplicity. */
+          /* Do not rewind past the beginning of link data; if we do,
+             it's either a bug or a broken stream */
+          result=best;
+          while(result>vf->dataoffsets[link]){
+            result=_get_prev_page(vf,result,&og);
+            if(result<0) goto seek_error;
+            if(ogg_page_serialno(&og)==vf->current_serialno &&
+               (ogg_page_granulepos(&og)>-1 ||
+                !ogg_page_continued(&og))){
+              return ov_raw_seek(vf,result);
+            }
+          }
+        }
+        if(result<0){
+          result = OV_EBADPACKET;
+          goto seek_error;
+        }
+        if(op.granulepos!=-1){
+          vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
+          if(vf->pcm_offset<0)vf->pcm_offset=0;
+          vf->pcm_offset+=total;
+          break;
+        }else
+          result=ogg_stream_packetout(&vf->os,NULL);
+      }
+    }
+  }
+
+  /* verify result */
+  if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
+    result=OV_EFAULT;
+    goto seek_error;
+  }
+  vf->bittrack=0.f;
+  vf->samptrack=0.f;
+  return(0);
+
+ seek_error:
+  /* dump machine so we're in a known state */
+  vf->pcm_offset=-1;
+  _decode_clear(vf);
+  return (int)result;
+}
+
+/* seek to a sample offset relative to the decompressed pcm stream
+   returns zero on success, nonzero on failure */
+
+int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
+  int thisblock,lastblock=0;
+  int ret=ov_pcm_seek_page(vf,pos);
+  if(ret<0)return(ret);
+  if((ret=_make_decode_ready(vf)))return ret;
+
+  /* discard leading packets we don't need for the lapping of the
+     position we want; don't decode them */
+
+  while(1){
+    ogg_packet op;
+    ogg_page og;
+
+    int ret=ogg_stream_packetpeek(&vf->os,&op);
+    if(ret>0){
+      thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
+      if(thisblock<0){
+        ogg_stream_packetout(&vf->os,NULL);
+        continue; /* non audio packet */
+      }
+      if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
+
+      if(vf->pcm_offset+((thisblock+
+                          vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
+
+      /* remove the packet from packet queue and track its granulepos */
+      ogg_stream_packetout(&vf->os,NULL);
+      vorbis_synthesis_trackonly(&vf->vb,&op);  /* set up a vb with
+                                                   only tracking, no
+                                                   pcm_decode */
+      vorbis_synthesis_blockin(&vf->vd,&vf->vb);
+
+      /* end of logical stream case is hard, especially with exact
+         length positioning. */
+
+      if(op.granulepos>-1){
+        int i;
+        /* always believe the stream markers */
+        vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
+        if(vf->pcm_offset<0)vf->pcm_offset=0;
+        for(i=0;i<vf->current_link;i++)
+          vf->pcm_offset+=vf->pcmlengths[i*2+1];
+      }
+
+      lastblock=thisblock;
+
+    }else{
+      if(ret<0 && ret!=OV_HOLE)break;
+
+      /* suck in a new page */
+      if(_get_next_page(vf,&og,-1)<0)break;
+      if(ogg_page_bos(&og))_decode_clear(vf);
+
+      if(vf->ready_state<STREAMSET){
+        long serialno=ogg_page_serialno(&og);
+        int link;
+
+        for(link=0;link<vf->links;link++)
+          if(vf->serialnos[link]==serialno)break;
+        if(link==vf->links) continue;
+        vf->current_link=link;
+
+        vf->ready_state=STREAMSET;
+        vf->current_serialno=ogg_page_serialno(&og);
+        ogg_stream_reset_serialno(&vf->os,serialno);
+        ret=_make_decode_ready(vf);
+        if(ret)return ret;
+        lastblock=0;
+      }
+
+      ogg_stream_pagein(&vf->os,&og);
+    }
+  }
+
+  vf->bittrack=0.f;
+  vf->samptrack=0.f;
+  /* discard samples until we reach the desired position. Crossing a
+     logical bitstream boundary with abandon is OK. */
+  {
+    /* note that halfrate could be set differently in each link, but
+       vorbisfile encoforces all links are set or unset */
+    int hs=vorbis_synthesis_halfrate_p(vf->vi);
+    while(vf->pcm_offset<((pos>>hs)<<hs)){
+      ogg_int64_t target=(pos-vf->pcm_offset)>>hs;
+      long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
+
+      if(samples>target)samples=target;
+      vorbis_synthesis_read(&vf->vd,samples);
+      vf->pcm_offset+=samples<<hs;
+
+      if(samples<target)
+        if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
+          vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
+    }
+  }
+  return 0;
+}
+
+/* seek to a playback time relative to the decompressed pcm stream
+   returns zero on success, nonzero on failure */
+int ov_time_seek(OggVorbis_File *vf,double seconds){
+  /* translate time to PCM position and call ov_pcm_seek */
+
+  int link=-1;
+  ogg_int64_t pcm_total=0;
+  double time_total=0.;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable)return(OV_ENOSEEK);
+  if(seconds<0)return(OV_EINVAL);
+
+  /* which bitstream section does this time offset occur in? */
+  for(link=0;link<vf->links;link++){
+    double addsec = ov_time_total(vf,link);
+    if(seconds<time_total+addsec)break;
+    time_total+=addsec;
+    pcm_total+=vf->pcmlengths[link*2+1];
+  }
+
+  if(link==vf->links)return(OV_EINVAL);
+
+  /* enough information to convert time offset to pcm offset */
+  {
+    ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
+    return(ov_pcm_seek(vf,target));
+  }
+}
+
+/* page-granularity version of ov_time_seek
+   returns zero on success, nonzero on failure */
+int ov_time_seek_page(OggVorbis_File *vf,double seconds){
+  /* translate time to PCM position and call ov_pcm_seek */
+
+  int link=-1;
+  ogg_int64_t pcm_total=0;
+  double time_total=0.;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(!vf->seekable)return(OV_ENOSEEK);
+  if(seconds<0)return(OV_EINVAL);
+
+  /* which bitstream section does this time offset occur in? */
+  for(link=0;link<vf->links;link++){
+    double addsec = ov_time_total(vf,link);
+    if(seconds<time_total+addsec)break;
+    time_total+=addsec;
+    pcm_total+=vf->pcmlengths[link*2+1];
+  }
+
+  if(link==vf->links)return(OV_EINVAL);
+
+  /* enough information to convert time offset to pcm offset */
+  {
+    ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
+    return(ov_pcm_seek_page(vf,target));
+  }
+}
+
+/* tell the current stream offset cursor.  Note that seek followed by
+   tell will likely not give the set offset due to caching */
+ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  return(vf->offset);
+}
+
+/* return PCM offset (sample) of next PCM sample to be read */
+ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  return(vf->pcm_offset);
+}
+
+/* return time offset (seconds) of next PCM sample to be read */
+double ov_time_tell(OggVorbis_File *vf){
+  int link=0;
+  ogg_int64_t pcm_total=0;
+  double time_total=0.f;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  if(vf->seekable){
+    pcm_total=ov_pcm_total(vf,-1);
+    time_total=ov_time_total(vf,-1);
+
+    /* which bitstream section does this time offset occur in? */
+    for(link=vf->links-1;link>=0;link--){
+      pcm_total-=vf->pcmlengths[link*2+1];
+      time_total-=ov_time_total(vf,link);
+      if(vf->pcm_offset>=pcm_total)break;
+    }
+  }
+
+  return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
+}
+
+/*  link:   -1) return the vorbis_info struct for the bitstream section
+                currently being decoded
+           0-n) to request information for a specific bitstream section
+
+    In the case of a non-seekable bitstream, any call returns the
+    current bitstream.  NULL in the case that the machine is not
+    initialized */
+
+vorbis_info *ov_info(OggVorbis_File *vf,int link){
+  if(vf->seekable){
+    if(link<0)
+      if(vf->ready_state>=STREAMSET)
+        return vf->vi+vf->current_link;
+      else
+      return vf->vi;
+    else
+      if(link>=vf->links)
+        return NULL;
+      else
+        return vf->vi+link;
+  }else{
+    return vf->vi;
+  }
+}
+
+/* grr, strong typing, grr, no templates/inheritence, grr */
+vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
+  if(vf->seekable){
+    if(link<0)
+      if(vf->ready_state>=STREAMSET)
+        return vf->vc+vf->current_link;
+      else
+        return vf->vc;
+    else
+      if(link>=vf->links)
+        return NULL;
+      else
+        return vf->vc+link;
+  }else{
+    return vf->vc;
+  }
+}
+
+static int host_is_big_endian() {
+  ogg_int32_t pattern = 0xfeedface; /* deadbeef */
+  unsigned char *bytewise = (unsigned char *)&pattern;
+  if (bytewise[0] == 0xfe) return 1;
+  return 0;
+}
+
+/* up to this point, everything could more or less hide the multiple
+   logical bitstream nature of chaining from the toplevel application
+   if the toplevel application didn't particularly care.  However, at
+   the point that we actually read audio back, the multiple-section
+   nature must surface: Multiple bitstream sections do not necessarily
+   have to have the same number of channels or sampling rate.
+
+   ov_read returns the sequential logical bitstream number currently
+   being decoded along with the PCM data in order that the toplevel
+   application can take action on channel/sample rate changes.  This
+   number will be incremented even for streamed (non-seekable) streams
+   (for seekable streams, it represents the actual logical bitstream
+   index within the physical bitstream.  Note that the accessor
+   functions above are aware of this dichotomy).
+
+   ov_read_filter is exactly the same as ov_read except that it processes
+   the decoded audio data through a filter before packing it into the
+   requested format. This gives greater accuracy than applying a filter
+   after the audio has been converted into integral PCM.
+
+   input values: buffer) a buffer to hold packed PCM data for return
+                 length) the byte length requested to be placed into buffer
+                 bigendianp) should the data be packed LSB first (0) or
+                             MSB first (1)
+                 word) word size for output.  currently 1 (byte) or
+                       2 (16 bit short)
+
+   return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
+                   0) EOF
+                   n) number of bytes of PCM actually returned.  The
+                   below works on a packet-by-packet basis, so the
+                   return length is not related to the 'length' passed
+                   in, just guaranteed to fit.
+
+            *section) set to the logical bitstream number */
+
+long ov_read_filter(OggVorbis_File *vf,char *buffer,int length,
+                    int bigendianp,int word,int sgned,int *bitstream,
+                    void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param){
+  int i,j;
+  int host_endian = host_is_big_endian();
+  int hs;
+
+  float **pcm;
+  long samples;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+
+  while(1){
+    if(vf->ready_state==INITSET){
+      samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
+      if(samples)break;
+    }
+
+    /* suck in another packet */
+    {
+      int ret=_fetch_and_process_packet(vf,NULL,1,1);
+      if(ret==OV_EOF)
+        return(0);
+      if(ret<=0)
+        return(ret);
+    }
+
+  }
+
+  if(samples>0){
+
+    /* yay! proceed to pack data into the byte buffer */
+
+    long channels=ov_info(vf,-1)->channels;
+    long bytespersample=word * channels;
+    vorbis_fpu_control fpu;
+    if(samples>length/bytespersample)samples=length/bytespersample;
+
+    if(samples <= 0)
+      return OV_EINVAL;
+
+    /* Here. */
+    if(filter)
+      filter(pcm,channels,samples,filter_param);
+
+    /* a tight loop to pack each size */
+    {
+      int val;
+      if(word==1){
+        int off=(sgned?0:128);
+        vorbis_fpu_setround(&fpu);
+        for(j=0;j<samples;j++)
+          for(i=0;i<channels;i++){
+            val=vorbis_ftoi(pcm[i][j]*128.f);
+            if(val>127)val=127;
+            else if(val<-128)val=-128;
+            *buffer++=val+off;
+          }
+        vorbis_fpu_restore(fpu);
+      }else{
+        int off=(sgned?0:32768);
+
+        if(host_endian==bigendianp){
+          if(sgned){
+
+            vorbis_fpu_setround(&fpu);
+            for(i=0;i<channels;i++) { /* It's faster in this order */
+              float *src=pcm[i];
+              short *dest=((short *)buffer)+i;
+              for(j=0;j<samples;j++) {
+                val=vorbis_ftoi(src[j]*32768.f);
+                if(val>32767)val=32767;
+                else if(val<-32768)val=-32768;
+                *dest=val;
+                dest+=channels;
+              }
+            }
+            vorbis_fpu_restore(fpu);
+
+          }else{
+
+            vorbis_fpu_setround(&fpu);
+            for(i=0;i<channels;i++) {
+              float *src=pcm[i];
+              short *dest=((short *)buffer)+i;
+              for(j=0;j<samples;j++) {
+                val=vorbis_ftoi(src[j]*32768.f);
+                if(val>32767)val=32767;
+                else if(val<-32768)val=-32768;
+                *dest=val+off;
+                dest+=channels;
+              }
+            }
+            vorbis_fpu_restore(fpu);
+
+          }
+        }else if(bigendianp){
+
+          vorbis_fpu_setround(&fpu);
+          for(j=0;j<samples;j++)
+            for(i=0;i<channels;i++){
+              val=vorbis_ftoi(pcm[i][j]*32768.f);
+              if(val>32767)val=32767;
+              else if(val<-32768)val=-32768;
+              val+=off;
+              *buffer++=(val>>8);
+              *buffer++=(val&0xff);
+            }
+          vorbis_fpu_restore(fpu);
+
+        }else{
+          int val;
+          vorbis_fpu_setround(&fpu);
+          for(j=0;j<samples;j++)
+            for(i=0;i<channels;i++){
+              val=vorbis_ftoi(pcm[i][j]*32768.f);
+              if(val>32767)val=32767;
+              else if(val<-32768)val=-32768;
+              val+=off;
+              *buffer++=(val&0xff);
+              *buffer++=(val>>8);
+                  }
+          vorbis_fpu_restore(fpu);
+
+        }
+      }
+    }
+
+    vorbis_synthesis_read(&vf->vd,samples);
+    hs=vorbis_synthesis_halfrate_p(vf->vi);
+    vf->pcm_offset+=(samples<<hs);
+    if(bitstream)*bitstream=vf->current_link;
+    return(samples*bytespersample);
+  }else{
+    return(samples);
+  }
+}
+
+long ov_read(OggVorbis_File *vf,char *buffer,int length,
+             int bigendianp,int word,int sgned,int *bitstream){
+  return ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, NULL, NULL);
+}
+
+/* input values: pcm_channels) a float vector per channel of output
+                 length) the sample length being read by the app
+
+   return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
+                   0) EOF
+                   n) number of samples of PCM actually returned.  The
+                   below works on a packet-by-packet basis, so the
+                   return length is not related to the 'length' passed
+                   in, just guaranteed to fit.
+
+            *section) set to the logical bitstream number */
+
+
+
+long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
+                   int *bitstream){
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+
+  while(1){
+    if(vf->ready_state==INITSET){
+      float **pcm;
+      long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
+      if(samples){
+        int hs=vorbis_synthesis_halfrate_p(vf->vi);
+        if(pcm_channels)*pcm_channels=pcm;
+        if(samples>length)samples=length;
+        vorbis_synthesis_read(&vf->vd,samples);
+        vf->pcm_offset+=samples<<hs;
+        if(bitstream)*bitstream=vf->current_link;
+        return samples;
+
+      }
+    }
+
+    /* suck in another packet */
+    {
+      int ret=_fetch_and_process_packet(vf,NULL,1,1);
+      if(ret==OV_EOF)return(0);
+      if(ret<=0)return(ret);
+    }
+
+  }
+}
+
+extern const float *vorbis_window(vorbis_dsp_state *v,int W);
+
+static void _ov_splice(float **pcm,float **lappcm,
+                       int n1, int n2,
+                       int ch1, int ch2,
+                       const float *w1, const float *w2){
+  int i,j;
+  const float *w=w1;
+  int n=n1;
+
+  if(n1>n2){
+    n=n2;
+    w=w2;
+  }
+
+  /* splice */
+  for(j=0;j<ch1 && j<ch2;j++){
+    float *s=lappcm[j];
+    float *d=pcm[j];
+
+    for(i=0;i<n;i++){
+      float wd=w[i]*w[i];
+      float ws=1.-wd;
+      d[i]=d[i]*wd + s[i]*ws;
+    }
+  }
+  /* window from zero */
+  for(;j<ch2;j++){
+    float *d=pcm[j];
+    for(i=0;i<n;i++){
+      float wd=w[i]*w[i];
+      d[i]=d[i]*wd;
+    }
+  }
+
+}
+
+/* make sure vf is INITSET */
+static int _ov_initset(OggVorbis_File *vf){
+  while(1){
+    if(vf->ready_state==INITSET)break;
+    /* suck in another packet */
+    {
+      int ret=_fetch_and_process_packet(vf,NULL,1,0);
+      if(ret<0 && ret!=OV_HOLE)return(ret);
+    }
+  }
+  return 0;
+}
+
+/* make sure vf is INITSET and that we have a primed buffer; if
+   we're crosslapping at a stream section boundary, this also makes
+   sure we're sanity checking against the right stream information */
+static int _ov_initprime(OggVorbis_File *vf){
+  vorbis_dsp_state *vd=&vf->vd;
+  while(1){
+    if(vf->ready_state==INITSET)
+      if(vorbis_synthesis_pcmout(vd,NULL))break;
+
+    /* suck in another packet */
+    {
+      int ret=_fetch_and_process_packet(vf,NULL,1,0);
+      if(ret<0 && ret!=OV_HOLE)return(ret);
+    }
+  }
+  return 0;
+}
+
+/* grab enough data for lapping from vf; this may be in the form of
+   unreturned, already-decoded pcm, remaining PCM we will need to
+   decode, or synthetic postextrapolation from last packets. */
+static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
+                       float **lappcm,int lapsize){
+  int lapcount=0,i;
+  float **pcm;
+
+  /* try first to decode the lapping data */
+  while(lapcount<lapsize){
+    int samples=vorbis_synthesis_pcmout(vd,&pcm);
+    if(samples){
+      if(samples>lapsize-lapcount)samples=lapsize-lapcount;
+      for(i=0;i<vi->channels;i++)
+        memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
+      lapcount+=samples;
+      vorbis_synthesis_read(vd,samples);
+    }else{
+    /* suck in another packet */
+      int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
+      if(ret==OV_EOF)break;
+    }
+  }
+  if(lapcount<lapsize){
+    /* failed to get lapping data from normal decode; pry it from the
+       postextrapolation buffering, or the second half of the MDCT
+       from the last packet */
+    int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
+    if(samples==0){
+      for(i=0;i<vi->channels;i++)
+        memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
+      lapcount=lapsize;
+    }else{
+      if(samples>lapsize-lapcount)samples=lapsize-lapcount;
+      for(i=0;i<vi->channels;i++)
+        memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
+      lapcount+=samples;
+    }
+  }
+}
+
+/* this sets up crosslapping of a sample by using trailing data from
+   sample 1 and lapping it into the windowing buffer of sample 2 */
+int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
+  vorbis_info *vi1,*vi2;
+  float **lappcm;
+  float **pcm;
+  const float *w1,*w2;
+  int n1,n2,i,ret,hs1,hs2;
+
+  if(vf1==vf2)return(0); /* degenerate case */
+  if(vf1->ready_state<OPENED)return(OV_EINVAL);
+  if(vf2->ready_state<OPENED)return(OV_EINVAL);
+
+  /* the relevant overlap buffers must be pre-checked and pre-primed
+     before looking at settings in the event that priming would cross
+     a bitstream boundary.  So, do it now */
+
+  ret=_ov_initset(vf1);
+  if(ret)return(ret);
+  ret=_ov_initprime(vf2);
+  if(ret)return(ret);
+
+  vi1=ov_info(vf1,-1);
+  vi2=ov_info(vf2,-1);
+  hs1=ov_halfrate_p(vf1);
+  hs2=ov_halfrate_p(vf2);
+
+  lappcm=alloca(sizeof(*lappcm)*vi1->channels);
+  n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
+  n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
+  w1=vorbis_window(&vf1->vd,0);
+  w2=vorbis_window(&vf2->vd,0);
+
+  for(i=0;i<vi1->channels;i++)
+    lappcm[i]=alloca(sizeof(**lappcm)*n1);
+
+  _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
+
+  /* have a lapping buffer from vf1; now to splice it into the lapping
+     buffer of vf2 */
+  /* consolidate and expose the buffer. */
+  vorbis_synthesis_lapout(&vf2->vd,&pcm);
+
+#if 0
+  _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
+  _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
+#endif
+
+  /* splice */
+  _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
+
+  /* done */
+  return(0);
+}
+
+static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
+                           int (*localseek)(OggVorbis_File *,ogg_int64_t)){
+  vorbis_info *vi;
+  float **lappcm;
+  float **pcm;
+  const float *w1,*w2;
+  int n1,n2,ch1,ch2,hs;
+  int i,ret;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  ret=_ov_initset(vf);
+  if(ret)return(ret);
+  vi=ov_info(vf,-1);
+  hs=ov_halfrate_p(vf);
+
+  ch1=vi->channels;
+  n1=vorbis_info_blocksize(vi,0)>>(1+hs);
+  w1=vorbis_window(&vf->vd,0);  /* window arrays from libvorbis are
+                                   persistent; even if the decode state
+                                   from this link gets dumped, this
+                                   window array continues to exist */
+
+  lappcm=alloca(sizeof(*lappcm)*ch1);
+  for(i=0;i<ch1;i++)
+    lappcm[i]=alloca(sizeof(**lappcm)*n1);
+  _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
+
+  /* have lapping data; seek and prime the buffer */
+  ret=localseek(vf,pos);
+  if(ret)return ret;
+  ret=_ov_initprime(vf);
+  if(ret)return(ret);
+
+ /* Guard against cross-link changes; they're perfectly legal */
+  vi=ov_info(vf,-1);
+  ch2=vi->channels;
+  n2=vorbis_info_blocksize(vi,0)>>(1+hs);
+  w2=vorbis_window(&vf->vd,0);
+
+  /* consolidate and expose the buffer. */
+  vorbis_synthesis_lapout(&vf->vd,&pcm);
+
+  /* splice */
+  _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
+
+  /* done */
+  return(0);
+}
+
+int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
+  return _ov_64_seek_lap(vf,pos,ov_raw_seek);
+}
+
+int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
+  return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
+}
+
+int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
+  return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
+}
+
+static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
+                           int (*localseek)(OggVorbis_File *,double)){
+  vorbis_info *vi;
+  float **lappcm;
+  float **pcm;
+  const float *w1,*w2;
+  int n1,n2,ch1,ch2,hs;
+  int i,ret;
+
+  if(vf->ready_state<OPENED)return(OV_EINVAL);
+  ret=_ov_initset(vf);
+  if(ret)return(ret);
+  vi=ov_info(vf,-1);
+  hs=ov_halfrate_p(vf);
+
+  ch1=vi->channels;
+  n1=vorbis_info_blocksize(vi,0)>>(1+hs);
+  w1=vorbis_window(&vf->vd,0);  /* window arrays from libvorbis are
+                                   persistent; even if the decode state
+                                   from this link gets dumped, this
+                                   window array continues to exist */
+
+  lappcm=alloca(sizeof(*lappcm)*ch1);
+  for(i=0;i<ch1;i++)
+    lappcm[i]=alloca(sizeof(**lappcm)*n1);
+  _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
+
+  /* have lapping data; seek and prime the buffer */
+  ret=localseek(vf,pos);
+  if(ret)return ret;
+  ret=_ov_initprime(vf);
+  if(ret)return(ret);
+
+ /* Guard against cross-link changes; they're perfectly legal */
+  vi=ov_info(vf,-1);
+  ch2=vi->channels;
+  n2=vorbis_info_blocksize(vi,0)>>(1+hs);
+  w2=vorbis_window(&vf->vd,0);
+
+  /* consolidate and expose the buffer. */
+  vorbis_synthesis_lapout(&vf->vd,&pcm);
+
+  /* splice */
+  _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
+
+  /* done */
+  return(0);
+}
+
+int ov_time_seek_lap(OggVorbis_File *vf,double pos){
+  return _ov_d_seek_lap(vf,pos,ov_time_seek);
+}
+
+int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
+  return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
+}
diff --git a/vorbis/lib/window.c b/vorbis/lib/window.c
new file mode 100644 (file)
index 0000000..b3b7ce0
--- /dev/null
@@ -0,0 +1,2135 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2009             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: window functions
+
+ ********************************************************************/
+
+#include <stdlib.h>
+#include <math.h>
+#include "os.h"
+#include "misc.h"
+#include "window.h"
+
+static const float vwin64[32] = {
+  0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
+  0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
+  0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
+  0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
+  0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
+  0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
+  0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
+  0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
+};
+
+static const float vwin128[64] = {
+  0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
+  0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
+  0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
+  0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
+  0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
+  0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
+  0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
+  0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
+  0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
+  0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
+  0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
+  0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
+  0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
+  0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
+  0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
+  0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
+};
+
+static const float vwin256[128] = {
+  0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
+  0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
+  0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
+  0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
+  0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
+  0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
+  0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
+  0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
+  0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
+  0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
+  0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
+  0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
+  0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
+  0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
+  0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
+  0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
+  0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
+  0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
+  0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
+  0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
+  0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
+  0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
+  0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
+  0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
+  0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
+  0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
+  0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
+  0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
+  0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
+  0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
+  0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
+  0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
+};
+
+static const float vwin512[256] = {
+  0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
+  0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
+  0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
+  0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
+  0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
+  0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
+  0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
+  0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
+  0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
+  0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
+  0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
+  0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
+  0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
+  0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
+  0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
+  0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
+  0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
+  0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
+  0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
+  0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
+  0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
+  0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
+  0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
+  0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
+  0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
+  0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
+  0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
+  0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
+  0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
+  0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
+  0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
+  0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
+  0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
+  0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
+  0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
+  0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
+  0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
+  0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
+  0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
+  0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
+  0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
+  0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
+  0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
+  0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
+  0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
+  0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
+  0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
+  0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
+  0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
+  0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
+  0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
+  0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
+  0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
+  0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
+  0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
+  0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
+  0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
+  0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
+  0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
+  0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
+  0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
+  0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
+  0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
+  0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
+};
+
+static const float vwin1024[512] = {
+  0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
+  0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
+  0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
+  0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
+  0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
+  0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
+  0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
+  0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
+  0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
+  0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
+  0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
+  0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
+  0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
+  0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
+  0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
+  0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
+  0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
+  0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
+  0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
+  0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
+  0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
+  0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
+  0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
+  0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
+  0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
+  0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
+  0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
+  0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
+  0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
+  0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
+  0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
+  0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
+  0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
+  0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
+  0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
+  0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
+  0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
+  0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
+  0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
+  0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
+  0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
+  0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
+  0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
+  0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
+  0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
+  0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
+  0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
+  0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
+  0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
+  0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
+  0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
+  0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
+  0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
+  0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
+  0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
+  0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
+  0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
+  0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
+  0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
+  0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
+  0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
+  0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
+  0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
+  0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
+  0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
+  0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
+  0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
+  0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
+  0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
+  0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
+  0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
+  0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
+  0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
+  0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
+  0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
+  0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
+  0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
+  0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
+  0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
+  0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
+  0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
+  0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
+  0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
+  0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
+  0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
+  0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
+  0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
+  0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
+  0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
+  0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
+  0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
+  0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
+  0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
+  0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
+  0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
+  0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
+  0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
+  0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
+  0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
+  0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
+  0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
+  0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
+  0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
+  0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
+  0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
+  0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
+  0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
+  0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
+  0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
+  0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
+  0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
+  0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
+  0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
+  0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
+  0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
+  0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
+  0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
+  0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
+  0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
+  0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
+  0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
+  0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
+  0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
+  0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
+  0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
+  0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
+  0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
+  0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
+};
+
+static const float vwin2048[1024] = {
+  0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
+  0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
+  0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
+  0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
+  0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
+  0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
+  0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
+  0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
+  0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
+  0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
+  0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
+  0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
+  0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
+  0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
+  0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
+  0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
+  0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
+  0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
+  0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
+  0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
+  0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
+  0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
+  0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
+  0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
+  0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
+  0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
+  0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
+  0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
+  0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
+  0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
+  0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
+  0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
+  0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
+  0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
+  0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
+  0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
+  0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
+  0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
+  0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
+  0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
+  0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
+  0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
+  0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
+  0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
+  0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
+  0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
+  0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
+  0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
+  0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
+  0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
+  0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
+  0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
+  0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
+  0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
+  0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
+  0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
+  0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
+  0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
+  0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
+  0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
+  0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
+  0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
+  0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
+  0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
+  0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
+  0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
+  0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
+  0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
+  0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
+  0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
+  0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
+  0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
+  0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
+  0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
+  0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
+  0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
+  0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
+  0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
+  0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
+  0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
+  0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
+  0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
+  0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
+  0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
+  0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
+  0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
+  0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
+  0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
+  0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
+  0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
+  0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
+  0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
+  0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
+  0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
+  0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
+  0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
+  0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
+  0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
+  0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
+  0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
+  0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
+  0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
+  0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
+  0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
+  0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
+  0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
+  0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
+  0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
+  0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
+  0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
+  0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
+  0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
+  0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
+  0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
+  0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
+  0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
+  0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
+  0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
+  0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
+  0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
+  0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
+  0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
+  0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
+  0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
+  0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
+  0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
+  0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
+  0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
+  0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
+  0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
+  0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
+  0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
+  0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
+  0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
+  0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
+  0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
+  0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
+  0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
+  0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
+  0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
+  0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
+  0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
+  0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
+  0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
+  0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
+  0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
+  0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
+  0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
+  0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
+  0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
+  0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
+  0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
+  0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
+  0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
+  0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
+  0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
+  0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
+  0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
+  0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
+  0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
+  0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
+  0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
+  0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
+  0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
+  0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
+  0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
+  0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
+  0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
+  0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
+  0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
+  0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
+  0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
+  0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
+  0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
+  0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
+  0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
+  0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
+  0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
+  0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
+  0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
+  0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
+  0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
+  0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
+  0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
+  0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
+  0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
+  0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
+  0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
+  0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
+  0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
+  0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
+  0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
+  0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
+  0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
+  0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
+  0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
+  0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
+  0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
+  0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
+  0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
+  0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
+  0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
+  0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
+  0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
+  0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
+  0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
+  0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
+  0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
+  0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
+  0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
+  0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
+  0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
+  0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
+  0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
+  0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
+  0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
+  0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
+  0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
+  0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
+  0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
+  0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
+  0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
+  0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
+  0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
+  0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
+  0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
+  0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
+  0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
+  0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
+  0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
+  0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
+  0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
+  0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
+  0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
+  0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
+  0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
+  0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
+  0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
+  0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
+  0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
+  0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
+  0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
+  0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
+  0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
+  0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
+  0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
+  0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
+  0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
+  0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
+  0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
+  0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
+  0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
+  0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
+  0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
+  0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
+  0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
+};
+
+static const float vwin4096[2048] = {
+  0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
+  0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
+  0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
+  0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
+  0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
+  0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
+  0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
+  0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
+  0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
+  0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
+  0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
+  0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
+  0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
+  0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
+  0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
+  0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
+  0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
+  0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
+  0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
+  0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
+  0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
+  0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
+  0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
+  0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
+  0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
+  0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
+  0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
+  0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
+  0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
+  0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
+  0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
+  0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
+  0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
+  0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
+  0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
+  0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
+  0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
+  0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
+  0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
+  0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
+  0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
+  0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
+  0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
+  0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
+  0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
+  0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
+  0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
+  0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
+  0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
+  0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
+  0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
+  0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
+  0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
+  0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
+  0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
+  0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
+  0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
+  0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
+  0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
+  0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
+  0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
+  0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
+  0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
+  0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
+  0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
+  0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
+  0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
+  0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
+  0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
+  0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
+  0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
+  0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
+  0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
+  0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
+  0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
+  0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
+  0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
+  0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
+  0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
+  0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
+  0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
+  0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
+  0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
+  0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
+  0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
+  0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
+  0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
+  0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
+  0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
+  0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
+  0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
+  0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
+  0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
+  0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
+  0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
+  0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
+  0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
+  0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
+  0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
+  0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
+  0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
+  0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
+  0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
+  0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
+  0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
+  0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
+  0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
+  0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
+  0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
+  0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
+  0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
+  0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
+  0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
+  0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
+  0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
+  0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
+  0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
+  0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
+  0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
+  0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
+  0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
+  0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
+  0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
+  0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
+  0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
+  0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
+  0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
+  0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
+  0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
+  0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
+  0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
+  0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
+  0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
+  0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
+  0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
+  0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
+  0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
+  0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
+  0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
+  0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
+  0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
+  0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
+  0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
+  0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
+  0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
+  0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
+  0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
+  0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
+  0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
+  0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
+  0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
+  0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
+  0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
+  0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
+  0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
+  0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
+  0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
+  0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
+  0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
+  0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
+  0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
+  0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
+  0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
+  0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
+  0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
+  0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
+  0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
+  0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
+  0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
+  0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
+  0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
+  0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
+  0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
+  0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
+  0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
+  0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
+  0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
+  0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
+  0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
+  0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
+  0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
+  0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
+  0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
+  0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
+  0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
+  0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
+  0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
+  0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
+  0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
+  0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
+  0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
+  0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
+  0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
+  0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
+  0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
+  0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
+  0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
+  0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
+  0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
+  0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
+  0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
+  0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
+  0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
+  0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
+  0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
+  0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
+  0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
+  0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
+  0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
+  0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
+  0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
+  0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
+  0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
+  0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
+  0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
+  0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
+  0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
+  0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
+  0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
+  0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
+  0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
+  0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
+  0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
+  0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
+  0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
+  0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
+  0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
+  0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
+  0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
+  0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
+  0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
+  0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
+  0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
+  0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
+  0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
+  0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
+  0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
+  0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
+  0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
+  0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
+  0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
+  0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
+  0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
+  0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
+  0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
+  0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
+  0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
+  0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
+  0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
+  0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
+  0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
+  0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
+  0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
+  0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
+  0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
+  0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
+  0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
+  0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
+  0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
+  0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
+  0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
+  0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
+  0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
+  0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
+  0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
+  0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
+  0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
+  0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
+  0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
+  0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
+  0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
+  0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
+  0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
+  0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
+  0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
+  0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
+  0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
+  0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
+  0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
+  0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
+  0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
+  0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
+  0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
+  0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
+  0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
+  0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
+  0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
+  0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
+  0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
+  0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
+  0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
+  0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
+  0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
+  0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
+  0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
+  0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
+  0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
+  0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
+  0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
+  0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
+  0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
+  0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
+  0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
+  0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
+  0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
+  0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
+  0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
+  0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
+  0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
+  0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
+  0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
+  0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
+  0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
+  0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
+  0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
+  0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
+  0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
+  0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
+  0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
+  0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
+  0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
+  0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
+  0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
+  0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
+  0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
+  0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
+  0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
+  0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
+  0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
+  0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
+  0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
+  0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
+  0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
+  0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
+  0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
+  0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
+  0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
+  0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
+  0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
+  0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
+  0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
+  0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
+  0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
+  0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
+  0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
+  0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
+  0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
+  0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
+  0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
+  0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
+  0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
+  0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
+  0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
+  0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
+  0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
+  0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
+  0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
+  0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
+  0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
+  0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
+  0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
+  0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
+  0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
+  0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
+  0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
+  0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
+  0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
+  0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
+  0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
+  0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
+  0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
+  0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
+  0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
+  0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
+  0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
+  0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
+  0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
+  0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
+  0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
+  0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
+  0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
+  0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
+  0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
+  0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
+  0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
+  0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
+  0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
+  0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
+  0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
+  0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
+  0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
+  0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
+  0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
+  0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
+  0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
+  0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
+  0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
+  0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
+  0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
+  0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
+  0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
+  0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
+  0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
+  0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
+  0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
+  0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
+  0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
+  0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
+  0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
+  0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
+  0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
+  0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
+  0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
+  0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
+  0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
+  0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
+  0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
+  0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
+  0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
+  0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
+  0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
+  0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
+  0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
+  0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
+  0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
+  0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
+  0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
+  0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
+  0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
+  0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
+  0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
+  0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
+  0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
+  0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
+  0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
+  0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
+  0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
+  0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
+  0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
+  0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
+  0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
+  0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
+  0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
+  0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
+  0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
+  0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
+  0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
+  0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
+  0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
+  0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
+  0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
+  0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
+  0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
+  0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
+  0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
+  0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
+  0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
+  0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
+  0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
+  0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
+  0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
+  0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
+  0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
+  0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
+  0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
+  0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
+  0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
+  0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
+  0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
+  0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
+  0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
+  0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
+  0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
+  0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
+  0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
+  0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
+  0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
+  0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
+  0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
+  0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
+  0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
+  0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
+  0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
+  0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
+  0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
+  0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
+  0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
+  0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
+  0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
+  0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
+  0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
+  0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
+  0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
+  0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
+  0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
+  0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
+  0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
+  0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
+  0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
+  0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
+  0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
+  0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
+  0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
+  0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
+  0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
+  0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
+  0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
+  0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
+  0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
+  0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
+  0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
+  0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
+};
+
+static const float vwin8192[4096] = {
+  0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
+  0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
+  0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
+  0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
+  0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
+  0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
+  0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
+  0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
+  0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
+  0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
+  0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
+  0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
+  0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
+  0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
+  0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
+  0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
+  0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
+  0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
+  0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
+  0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
+  0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
+  0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
+  0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
+  0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
+  0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
+  0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
+  0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
+  0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
+  0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
+  0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
+  0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
+  0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
+  0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
+  0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
+  0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
+  0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
+  0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
+  0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
+  0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
+  0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
+  0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
+  0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
+  0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
+  0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
+  0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
+  0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
+  0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
+  0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
+  0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
+  0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
+  0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
+  0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
+  0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
+  0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
+  0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
+  0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
+  0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
+  0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
+  0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
+  0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
+  0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
+  0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
+  0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
+  0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
+  0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
+  0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
+  0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
+  0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
+  0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
+  0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
+  0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
+  0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
+  0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
+  0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
+  0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
+  0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
+  0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
+  0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
+  0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
+  0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
+  0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
+  0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
+  0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
+  0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
+  0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
+  0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
+  0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
+  0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
+  0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
+  0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
+  0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
+  0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
+  0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
+  0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
+  0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
+  0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
+  0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
+  0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
+  0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
+  0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
+  0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
+  0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
+  0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
+  0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
+  0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
+  0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
+  0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
+  0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
+  0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
+  0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
+  0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
+  0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
+  0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
+  0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
+  0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
+  0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
+  0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
+  0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
+  0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
+  0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
+  0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
+  0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
+  0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
+  0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
+  0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
+  0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
+  0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
+  0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
+  0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
+  0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
+  0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
+  0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
+  0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
+  0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
+  0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
+  0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
+  0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
+  0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
+  0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
+  0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
+  0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
+  0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
+  0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
+  0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
+  0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
+  0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
+  0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
+  0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
+  0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
+  0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
+  0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
+  0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
+  0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
+  0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
+  0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
+  0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
+  0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
+  0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
+  0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
+  0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
+  0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
+  0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
+  0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
+  0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
+  0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
+  0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
+  0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
+  0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
+  0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
+  0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
+  0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
+  0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
+  0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
+  0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
+  0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
+  0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
+  0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
+  0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
+  0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
+  0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
+  0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
+  0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
+  0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
+  0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
+  0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
+  0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
+  0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
+  0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
+  0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
+  0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
+  0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
+  0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
+  0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
+  0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
+  0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
+  0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
+  0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
+  0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
+  0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
+  0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
+  0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
+  0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
+  0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
+  0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
+  0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
+  0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
+  0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
+  0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
+  0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
+  0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
+  0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
+  0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
+  0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
+  0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
+  0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
+  0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
+  0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
+  0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
+  0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
+  0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
+  0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
+  0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
+  0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
+  0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
+  0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
+  0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
+  0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
+  0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
+  0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
+  0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
+  0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
+  0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
+  0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
+  0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
+  0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
+  0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
+  0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
+  0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
+  0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
+  0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
+  0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
+  0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
+  0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
+  0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
+  0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
+  0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
+  0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
+  0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
+  0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
+  0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
+  0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
+  0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
+  0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
+  0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
+  0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
+  0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
+  0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
+  0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
+  0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
+  0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
+  0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
+  0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
+  0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
+  0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
+  0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
+  0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
+  0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
+  0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
+  0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
+  0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
+  0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
+  0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
+  0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
+  0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
+  0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
+  0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
+  0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
+  0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
+  0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
+  0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
+  0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
+  0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
+  0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
+  0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
+  0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
+  0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
+  0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
+  0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
+  0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
+  0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
+  0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
+  0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
+  0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
+  0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
+  0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
+  0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
+  0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
+  0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
+  0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
+  0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
+  0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
+  0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
+  0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
+  0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
+  0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
+  0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
+  0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
+  0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
+  0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
+  0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
+  0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
+  0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
+  0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
+  0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
+  0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
+  0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
+  0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
+  0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
+  0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
+  0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
+  0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
+  0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
+  0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
+  0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
+  0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
+  0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
+  0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
+  0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
+  0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
+  0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
+  0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
+  0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
+  0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
+  0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
+  0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
+  0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
+  0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
+  0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
+  0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
+  0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
+  0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
+  0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
+  0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
+  0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
+  0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
+  0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
+  0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
+  0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
+  0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
+  0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
+  0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
+  0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
+  0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
+  0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
+  0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
+  0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
+  0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
+  0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
+  0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
+  0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
+  0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
+  0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
+  0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
+  0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
+  0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
+  0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
+  0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
+  0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
+  0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
+  0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
+  0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
+  0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
+  0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
+  0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
+  0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
+  0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
+  0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
+  0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
+  0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
+  0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
+  0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
+  0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
+  0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
+  0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
+  0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
+  0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
+  0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
+  0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
+  0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
+  0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
+  0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
+  0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
+  0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
+  0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
+  0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
+  0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
+  0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
+  0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
+  0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
+  0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
+  0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
+  0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
+  0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
+  0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
+  0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
+  0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
+  0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
+  0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
+  0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
+  0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
+  0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
+  0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
+  0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
+  0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
+  0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
+  0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
+  0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
+  0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
+  0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
+  0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
+  0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
+  0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
+  0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
+  0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
+  0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
+  0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
+  0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
+  0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
+  0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
+  0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
+  0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
+  0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
+  0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
+  0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
+  0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
+  0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
+  0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
+  0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
+  0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
+  0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
+  0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
+  0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
+  0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
+  0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
+  0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
+  0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
+  0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
+  0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
+  0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
+  0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
+  0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
+  0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
+  0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
+  0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
+  0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
+  0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
+  0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
+  0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
+  0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
+  0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
+  0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
+  0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
+  0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
+  0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
+  0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
+  0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
+  0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
+  0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
+  0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
+  0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
+  0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
+  0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
+  0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
+  0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
+  0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
+  0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
+  0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
+  0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
+  0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
+  0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
+  0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
+  0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
+  0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
+  0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
+  0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
+  0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
+  0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
+  0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
+  0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
+  0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
+  0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
+  0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
+  0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
+  0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
+  0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
+  0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
+  0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
+  0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
+  0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
+  0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
+  0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
+  0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
+  0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
+  0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
+  0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
+  0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
+  0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
+  0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
+  0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
+  0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
+  0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
+  0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
+  0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
+  0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
+  0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
+  0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
+  0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
+  0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
+  0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
+  0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
+  0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
+  0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
+  0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
+  0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
+  0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
+  0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
+  0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
+  0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
+  0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
+  0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
+  0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
+  0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
+  0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
+  0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
+  0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
+  0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
+  0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
+  0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
+  0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
+  0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
+  0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
+  0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
+  0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
+  0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
+  0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
+  0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
+  0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
+  0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
+  0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
+  0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
+  0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
+  0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
+  0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
+  0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
+  0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
+  0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
+  0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
+  0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
+  0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
+  0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
+  0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
+  0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
+  0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
+  0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
+  0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
+  0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
+  0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
+  0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
+  0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
+  0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
+  0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
+  0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
+  0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
+  0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
+  0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
+  0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
+  0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
+  0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
+  0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
+  0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
+  0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
+  0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
+  0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
+  0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
+  0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
+  0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
+  0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
+  0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
+  0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
+  0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
+  0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
+  0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
+  0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
+  0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
+  0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
+  0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
+  0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
+  0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
+  0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
+  0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
+  0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
+  0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
+  0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
+  0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
+  0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
+  0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
+  0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
+  0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
+  0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
+  0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
+  0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
+  0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
+  0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
+  0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
+  0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
+  0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
+  0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
+  0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
+  0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
+  0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
+  0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
+  0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
+  0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
+  0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
+  0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
+  0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
+  0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
+  0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
+  0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
+  0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
+  0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
+  0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
+  0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
+  0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
+  0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
+  0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
+  0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
+  0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
+  0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
+  0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
+  0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
+  0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
+  0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
+  0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
+  0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
+  0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
+  0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
+  0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
+  0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
+  0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
+  0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
+  0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
+  0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
+  0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
+  0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
+  0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
+  0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
+  0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
+  0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
+  0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
+  0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
+  0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
+  0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
+  0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
+  0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
+  0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
+  0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
+  0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
+  0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
+  0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
+  0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
+  0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
+  0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
+  0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
+  0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
+  0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
+  0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
+  0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
+  0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
+  0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
+  0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
+  0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
+  0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
+  0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
+  0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
+  0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
+  0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
+  0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
+  0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
+  0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
+  0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
+  0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
+  0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
+  0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
+  0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
+  0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
+  0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
+  0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
+  0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
+  0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
+  0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
+  0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
+  0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
+  0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
+  0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
+  0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
+  0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
+  0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
+  0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
+  0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
+  0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
+  0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
+  0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
+  0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
+  0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
+  0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
+  0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
+  0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
+  0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
+  0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
+  0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
+  0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
+  0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
+  0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
+  0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
+  0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
+  0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
+  0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
+  0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
+  0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
+  0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
+  0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
+  0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
+  0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
+  0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
+  0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
+  0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
+  0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
+  0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
+  0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
+  0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
+  0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
+  0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
+  0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
+  0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
+  0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
+  0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
+  0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
+  0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
+  0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
+  0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
+  0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
+  0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
+  0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
+  0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
+  0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
+  0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
+  0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
+  0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
+  0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
+  0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
+  0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
+  0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
+  0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
+  0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
+  0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
+  0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
+  0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
+  0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
+  0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
+  0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
+  0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
+  0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
+  0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
+  0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
+  0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
+  0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
+  0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
+  0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
+  0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
+  0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
+  0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
+  0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
+  0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
+  0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
+  0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
+  0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
+  0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
+  0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
+  0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
+  0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
+  0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
+  0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
+  0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
+  0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
+  0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
+  0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
+  0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
+  0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
+  0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
+  0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
+  0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
+  0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
+  0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
+  0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
+  0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
+  0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
+  0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
+  0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
+  0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
+  0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
+  0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
+  0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
+  0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
+  0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
+  0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
+  0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
+  0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
+  0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
+  0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
+  0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
+  0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
+  0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
+  0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
+  0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
+  0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
+  0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
+  0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
+  0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
+  0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
+  0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
+  0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
+  0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
+  0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
+  0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
+  0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
+  0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
+  0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
+  0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
+  0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
+  0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
+  0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
+  0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
+  0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
+  0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
+  0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
+  0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
+  0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
+  0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
+  0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
+  0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
+  0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
+  0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
+  0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
+  0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
+  0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
+  0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
+  0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
+  0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
+  0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
+  0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
+  0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
+  0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
+  0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
+  0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
+  0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
+  0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
+  0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
+  0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
+  0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
+  0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
+  0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
+  0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
+  0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
+  0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
+  0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
+  0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
+  0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
+  0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
+  0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
+  0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
+  0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
+  0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
+  0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
+  0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
+  0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
+  0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
+  0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
+  0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
+  0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
+  0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
+  0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
+  0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
+  0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
+  0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
+  0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
+  0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
+  0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
+  0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
+  0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
+  0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
+  0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
+  0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
+  0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
+  0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
+  0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
+  0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
+  0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
+  0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
+  0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
+  0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
+  0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
+  0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
+  0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
+  0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
+  0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
+  0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
+  0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
+  0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
+  0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
+  0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
+  0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
+  0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
+  0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
+  0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
+  0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
+  0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
+  0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
+  0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
+  0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
+  0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
+  0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
+  0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
+  0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
+  0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
+  0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
+  0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
+  0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
+  0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
+  0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
+  0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
+  0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
+  0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
+  0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
+  0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
+  0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
+  0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
+  0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
+  0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
+  0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
+  0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
+  0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
+  0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
+  0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
+  0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
+  0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
+  0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
+  0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
+  0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
+  0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
+  0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
+  0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
+  0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
+  0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
+  0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
+  0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
+  0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
+  0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
+  0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
+  0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
+  0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
+  0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
+  0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
+  0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
+  0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
+  0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
+  0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
+  0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
+  0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
+  0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
+  0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
+  0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
+  0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
+  0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
+  0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
+  0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
+  0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
+  0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
+  0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
+  0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
+  0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
+  0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
+  0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
+  0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
+  0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
+  0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
+  0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
+  0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
+  0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
+  0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
+  0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
+  0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
+  0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
+  0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
+  0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
+  0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
+  0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
+  0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
+  0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
+  0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
+  0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
+  0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
+  0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
+  0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
+  0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
+  0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
+  0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
+  0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
+  0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
+  0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
+  0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
+  0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
+  0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
+  1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
+};
+
+static const float *const vwin[8] = {
+  vwin64,
+  vwin128,
+  vwin256,
+  vwin512,
+  vwin1024,
+  vwin2048,
+  vwin4096,
+  vwin8192,
+};
+
+const float *_vorbis_window_get(int n){
+  return vwin[n];
+}
+
+void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
+                          int lW,int W,int nW){
+  lW=(W?lW:0);
+  nW=(W?nW:0);
+
+  {
+    const float *windowLW=vwin[winno[lW]];
+    const float *windowNW=vwin[winno[nW]];
+
+    long n=blocksizes[W];
+    long ln=blocksizes[lW];
+    long rn=blocksizes[nW];
+
+    long leftbegin=n/4-ln/4;
+    long leftend=leftbegin+ln/2;
+
+    long rightbegin=n/2+n/4-rn/4;
+    long rightend=rightbegin+rn/2;
+
+    int i,p;
+
+    for(i=0;i<leftbegin;i++)
+      d[i]=0.f;
+
+    for(p=0;i<leftend;i++,p++)
+      d[i]*=windowLW[p];
+
+    for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
+      d[i]*=windowNW[p];
+
+    for(;i<n;i++)
+      d[i]=0.f;
+  }
+}
diff --git a/vorbis/lib/window.h b/vorbis/lib/window.h
new file mode 100644 (file)
index 0000000..6ac2607
--- /dev/null
@@ -0,0 +1,25 @@
+/********************************************************************
+ *                                                                  *
+ * 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-2007             *
+ * by the Xiph.Org Foundation http://www.xiph.org/                  *
+ *                                                                  *
+ ********************************************************************
+
+ function: window functions
+
+ ********************************************************************/
+
+#ifndef _V_WINDOW_
+#define _V_WINDOW_
+
+extern const float *_vorbis_window_get(int n);
+extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
+                          int lW,int W,int nW);
+
+
+#endif
diff --git a/vorbis/vorbisenc.h b/vorbis/vorbisenc.h
deleted file mode 100644 (file)
index ed2210a..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/********************************************************************
- *                                                                  *
- * 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-2001             *
- * by the XIPHOPHORUS Company http://www.xiph.org/                  *
- *                                                                  *
- ********************************************************************
-
- function: vorbis encode-engine setup
- last mod: $Id: vorbisenc.h,v 1.10 2002/07/01 11:20:10 xiphmont Exp $
-
- ********************************************************************/
-
-#ifndef _OV_ENC_H_
-#define _OV_ENC_H_
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-#include "codec.h"
-
-extern int vorbis_encode_init(vorbis_info *vi,
-                             long channels,
-                             long rate,
-                             
-                             long max_bitrate,
-                             long nominal_bitrate,
-                             long min_bitrate);
-
-extern int vorbis_encode_setup_managed(vorbis_info *vi,
-                                      long channels,
-                                      long rate,
-                                      
-                                      long max_bitrate,
-                                      long nominal_bitrate,
-                                      long min_bitrate);
-  
-extern int vorbis_encode_setup_vbr(vorbis_info *vi,
-                                 long channels,
-                                 long rate,
-                                 
-                                 float /* quality level from 0. (lo) to 1. (hi) */
-                                 );
-
-extern int vorbis_encode_init_vbr(vorbis_info *vi,
-                                 long channels,
-                                 long rate,
-                                 
-                                 float base_quality /* quality level from 0. (lo) to 1. (hi) */
-                                 );
-
-extern int vorbis_encode_setup_init(vorbis_info *vi);
-
-extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
-
-#define OV_ECTL_RATEMANAGE_GET       0x10
-
-#define OV_ECTL_RATEMANAGE_SET       0x11
-#define OV_ECTL_RATEMANAGE_AVG       0x12
-#define OV_ECTL_RATEMANAGE_HARD      0x13
-
-#define OV_ECTL_LOWPASS_GET          0x20
-#define OV_ECTL_LOWPASS_SET          0x21
-
-#define OV_ECTL_IBLOCK_GET           0x30
-#define OV_ECTL_IBLOCK_SET           0x31
-
-struct ovectl_ratemanage_arg {
-  int    management_active;
-
-  long   bitrate_hard_min;
-  long   bitrate_hard_max;
-  double bitrate_hard_window;
-
-  long   bitrate_av_lo;
-  long   bitrate_av_hi;
-  double bitrate_av_window;
-  double bitrate_av_window_center;
-};
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif
-
-
diff --git a/vorbis/win32/vorbis.def b/vorbis/win32/vorbis.def
new file mode 100644 (file)
index 0000000..884f8f0
--- /dev/null
@@ -0,0 +1,58 @@
+; vorbis.def
+; 
+LIBRARY
+EXPORTS
+_floor_P
+_mapping_P
+_residue_P
+;
+vorbis_info_init
+vorbis_info_clear
+vorbis_info_blocksize
+;
+vorbis_comment_init
+vorbis_comment_add
+vorbis_comment_add_tag
+vorbis_comment_query
+vorbis_comment_query_count
+vorbis_comment_clear
+;
+vorbis_block_init
+vorbis_block_clear
+vorbis_dsp_clear
+vorbis_granule_time
+;
+vorbis_analysis_init
+vorbis_commentheader_out
+vorbis_analysis_headerout
+vorbis_analysis_buffer
+vorbis_analysis_wrote
+vorbis_analysis_blockout
+vorbis_analysis
+vorbis_bitrate_addblock
+vorbis_bitrate_flushpacket
+;
+vorbis_synthesis_headerin
+vorbis_synthesis_init
+vorbis_synthesis_restart
+vorbis_synthesis
+vorbis_synthesis_trackonly
+vorbis_synthesis_blockin
+vorbis_synthesis_pcmout
+vorbis_synthesis_lapout
+vorbis_synthesis_read
+vorbis_packet_blocksize
+vorbis_synthesis_halfrate
+vorbis_synthesis_halfrate_p
+vorbis_synthesis_idheader
+;
+vorbis_window
+;_analysis_output_always
+vorbis_encode_init
+vorbis_encode_setup_managed
+vorbis_encode_setup_vbr
+vorbis_encode_init_vbr
+vorbis_encode_setup_init
+vorbis_encode_ctl
+;
+vorbis_version_string
diff --git a/vorbis/win32/vorbisenc.def b/vorbis/win32/vorbisenc.def
new file mode 100644 (file)
index 0000000..79af064
--- /dev/null
@@ -0,0 +1,12 @@
+; vorbisenc.def
+;
+LIBRARY
+
+EXPORTS
+vorbis_encode_init
+vorbis_encode_setup_managed
+vorbis_encode_setup_vbr
+vorbis_encode_init_vbr
+vorbis_encode_setup_init
+vorbis_encode_ctl
+
diff --git a/vorbis/win32/vorbisfile.def b/vorbis/win32/vorbisfile.def
new file mode 100644 (file)
index 0000000..4dc5549
--- /dev/null
@@ -0,0 +1,39 @@
+; vorbisfile.def
+;
+LIBRARY
+EXPORTS
+ov_clear
+ov_open
+ov_open_callbacks
+ov_bitrate
+ov_bitrate_instant
+ov_streams
+ov_seekable
+ov_serialnumber
+ov_raw_total
+ov_pcm_total
+ov_time_total
+ov_raw_seek
+ov_pcm_seek
+ov_pcm_seek_page
+ov_time_seek
+ov_time_seek_page
+ov_raw_seek_lap
+ov_pcm_seek_lap
+ov_pcm_seek_page_lap
+ov_time_seek_lap
+ov_time_seek_page_lap
+ov_raw_tell
+ov_pcm_tell
+ov_time_tell
+ov_info
+ov_comment
+ov_read
+ov_read_float
+ov_test
+ov_test_callbacks
+ov_test_open
+ov_crosslap
+ov_halfrate
+ov_halfrate_p
+ov_fopen